BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Fine-tuning1 of 19 in topic

500. Count LoRA's trainable parameters

EasyFine-tuning

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.

Functiondef lora_params(shapes, r)

Example 1

Input: shapes = [(4096, 4096)], r = 8

Output: (65536, 16777216, 0.390625)

Example 2

Input: shapes = [(4096, 4096)] * 64, r = 16

Output: (8388608, 1073741824, 0.78125)

Example 3

Input: shapes = [(11008, 4096), (4096, 11008)], r = 4

Output: (120832, 90177536, 0.133993)

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
Hint 1

LoRA replaces training a d_out by d_in matrix with training two thin matrices that share the rank r.

Hint 2

For every shape, add r * (d_out + d_in) to the LoRA total and d_out * d_in to the full total, then compute the percentage.

Hint 3

B has d_out * r entries and A has r * d_in, so each matrix adds r * (d_out + d_in). Use 100.0 * lora / full so the percent is a float.

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.

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.

Topics
Fine-tuning
Similar questions
  • Estimate GPU memory for QLoRA-style fine-tuningEasy
  • Mask prompt tokens out of the SFT lossEasy
  • Render chat messages into a model prompt stringEasy
  • Swap one merged LoRA adapter for anotherEasy
All Fine-tuning problems
Report
500 / 903
Python 3solution.pyPython idle
1
2
3
4
def lora_params(shapes, r):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 3 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS