Count LoRA's trainable parameters

LoRA freezes a weight W of shape (d_out, d_in) and trains two small matrices: B (d_out, r) and A (r, d_in). That is why a 7B model can be fine-tuned on one GPU.

Write lora_params(shapes, r) where shapes is a list of (d_out, d_in) for every adapted matrix. Return (lora_trainable, full_trainable, percent) where percent = 100 * lora / full.

Signaturedef lora_params(shapes, r)

Understand the idea

LoRA freezes a big weight matrix W of shape (d_out, d_in) and trains a small update B A instead, where B is (d_out, r) and A is (r, d_in). The product has the same shape as W, but you only store r x (d_out + d_in) numbers. Like editing a huge photo with a small adjustment layer instead of repainting every pixel. Worked example: one 4096 by 4096 matrix with r = 8. Full training needs 4096 x 4096 = 16,777,216 parameters. LoRA needs 8 x (4096 + 4096) = 65,536. Percent = 100 x 65,536 / 16,777,216 = 0.390625. For several matrices, add up each one's LoRA count and each one's full count, then take the ratio of the totals. Rule: lora = sum of r (d_out + d_in); full = sum of d_out x d_in; percent = 100 x lora / full. This tiny fraction is why a 7B model can be fine-tuned on a single GPU.

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

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

  • Sample 1: one 4096 square, r = 8lora_params([(4096, 4096)], 8)
  • Sample 2: q and v of 32 layerslora_params([(4096, 4096)] * 64, 16)
  • Test 3: rectangularlora_params([(11008, 4096), (4096, 11008)], 4)