Measure how much a rank-k approximation loses with the SVD

Low-rank adapters and compression both rest on one idea: many weight matrices are close to a low-rank matrix. The singular values tell you exactly how close.

Write low_rank_error(X, k) for a 2D array X and an int k >= 0. Return the relative Frobenius error of the best rank-k approximation: ||X - X_k|| / ||X||, as a float. By the Eckart-Young theorem this equals sqrt(sum of s_i squared for i >= k) divided by sqrt(sum of all s_i squared), where s are the singular values in descending order. If X is all zeros, return 0.0. If k is at least the number of singular values, the error is 0.0.

Signaturedef low_rank_error(X, k)

Example

X = diag(3, 4), k = 1 gives 0.6.

Understand the idea

Singular values measure how much each direction contributes to a matrix. The best rank-k approximation keeps the top k singular values and drops the rest, and the error it leaves is exactly the energy of the dropped ones. Energy means squared singular values, not raw ones. Like compressing a song by dropping the quietest frequencies: the loss is the power you removed. Worked example: singular values [5, 3, 1], k = 1. Kept energy 25, dropped energy 9 + 1 = 10, total 35. Relative error = sqrt(10) / sqrt(35) = 3.162 / 5.916 = 0.535. With k = 2, error = sqrt(1) / sqrt(35) = 0.169. With k = 3 or more, error is 0. An all-zero matrix returns 0.0. Rule: s = singular values in descending order; error = sqrt(sum of s_i^2 for i >= k) / sqrt(sum of all s_i^2). This is the Eckart-Young result. LoRA and model compression rely on weight matrices having small tail energy.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: examplelow_rank_error(np.diag([3.0, 4.0]), 1)
  • Sample 2: random k=2low_rank_error(_X, 2)
  • Test 3: exact rank 2 matrixlow_rank_error(_L, 2)
  • Test 4: k=0 is full errorlow_rank_error(_X, 0)
  • Test 5: zero matrixlow_rank_error(np.zeros((3, 3)), 1)