Pick the rank that keeps a target energy in a low-rank factorization
Why it matters Low-rank factorization is used to compress embedding and projection layers and is the idea behind LoRA and SVD-based model compression.
A dense m x n layer can be replaced by two thin factors of rank r, costing r * (m + n) parameters. The rank is often chosen to keep a fraction of the matrix's energy (sum of squared singular values).
Write choose_rank(W, keep). Compute the singular values s of W. Return a dict with "rank": the smallest r with sum(s[:r]^2) / sum(s^2) >= keep (r is at least 1), "params": r * (m + n), "saves": True if params < m * n, and "rel_error": the relative Frobenius error sqrt(sum(s[r:]^2) / sum(s^2)) of the best rank-r approximation. Compare energies with a 1e-12 tolerance.
def choose_rank(W, keep)Example
W = diag(3, 2, 1) (3 x 3), keep 0.9 gives {"rank": 2, "params": 12, "saves": False, "rel_error": 0.2673}.
Understand the idea
Energy is a way to ask how much of a matrix's content survives if we keep only its strongest directions. The singular values s1 >= s2 >= ... rank those directions, and the squared values add up to the total squared size of the matrix. Worked example: diag(3, 2, 1) has energies 9, 4, 1, total 14. Rank 1 keeps 9 / 14 = 0.64, rank 2 keeps 13 / 14 = 0.93, so for a 90 percent target the rank is 2. The leftover error is sqrt(1 / 14) = 0.27. Rank 2 for a 3 x 3 matrix costs 2 x 6 = 12 numbers, more than 9, so it does not save memory there. Rule: r = min r with cumsum(s^2)[r] / sum(s^2) >= keep, params = r (m + n). Large LLM matrices are often far from full rank, which is why low-rank compression works on them.