Count trainable parameters when freezing most of a model

Why it matters Freezing the wrong layers wastes GPU memory or ruins a fine-tune; printing these numbers is the first sanity check.

Parameter-efficient fine-tuning freezes almost everything. Checking what is actually trainable catches configuration mistakes before a long run.

Write trainable_stats(shapes, trainable_prefixes). shapes maps parameter names to shape tuples (an empty tuple is a scalar with 1 value). A parameter is trainable if its name STARTS WITH any of the prefixes. Return a dict {"trainable": int, "total": int, "percent": float}, where percent = 100 * trainable / total rounded to 4 decimals (0.0 if total is 0).

Signaturedef trainable_stats(shapes, trainable_prefixes)

Example

trainable_stats({"emb.weight": (10, 4), "l0.lora_A": (2, 4), "l0.lora_B": (4, 2), "head.weight": (10, 4)}, ["l0.lora"]) is {"trainable": 16, "total": 96, "percent": 16.6667}.

Understand the idea

When you fine-tune with LoRA or freeze most layers, you want to know how much of the model will actually learn. It is a quick audit, like checking which rooms in a house are unlocked before leaving.

Example: an embedding (10 x 4 = 40), a head (40), and two LoRA matrices (2 x 4 = 8 and 4 x 2 = 8). Total = 96. Only names starting with "l0.lora" train: 16 parameters, so 16 / 96 = 16.67%.

Rule: count = prod(shape) per parameter; trainable if name.startswith(any prefix); percent = 100 * trainable / total.

Prefix matching matters: "head" should not also select "lm_head". Real LoRA runs on large models usually train well under 1% of the parameters, and seeing a much larger number is a sign that something like the embedding was left unfrozen.

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

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

  • Sample 1: exampletrainable_stats({'emb.weight': (10, 4), 'l0.lora_A': (2, 4), 'l0.lora_B': (4, 2), 'head.weight': (10, 4)}, ...
  • Sample 2: prefix not substringtrainable_stats({'head.weight': (8, 2), 'lm_head.bias': (8,), 'norm.scale': ()}, ['head'])
  • Test 3: nothing trainabletrainable_stats({'w': (3, 3)}, [])
  • Test 4: emptytrainable_stats({}, ['x'])