Count Trainable Parameters in a PyTorch nn.Module

Basics
BasicsPyTorchModel InspectionGoogleMetaAmazon

Problem

Implement count_trainable_params(model) returning the total number of trainable scalar parameters (p.requires_grad == True) inside a PyTorch nn.Module as a Python int.

Why It Matters: When fine-tuning LLMs with LoRA or freezing backbone layers in transfer learning, verifying exact trainable parameter counts confirms that only the intended weights will update and consume optimizer memory.

Function Signature

import torch.nn as nn

def count_trainable_params(model: nn.Module) -> int:
    """Return total number of parameters with requires_grad=True."""

Sample Input & Output

Example 1: Single Unfrozen Linear Layer

Input:

model = nn.Linear(10, 4)  # weights (4, 10) + bias (4,)

Expected Output:

44

Explanation: 10 * 4 = 40 weight parameters plus 4 bias parameters = 44 trainable parameters.

Example 2: Partially Frozen Sequential Model

Input:

model = nn.Sequential(nn.Linear(10, 4), nn.Linear(4, 2))
for p in model[0].parameters(): p.requires_grad = False

Expected Output:

10

Explanation: Layer 0's 44 params are frozen (requires_grad=False), so only Layer 1's 4*2 + 2 = 10 params are counted.

Constraints & Edge Cases

  • Exclude frozen parameters (requires_grad == False).
  • Return a Python int.
  • Ignore parameters where p.requires_grad is False.
  • Return a Python int (returns 0 if all parameters are frozen).

Constraints & Evaluation Criteria

  • Exclude frozen parameters (`requires_grad == False`).
  • Return a Python `int`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
nn.Linear(10, 4)
Expected Output / Criteria
44