5.2 Parameters, State, and Memory
In the previous section, we organized models as trees of modules so frameworks can find every parameter automatically. Until now we could let the framework manage those tensors behind the scenes without asking what else a model holds or how much memory training requires. At small scale, those details rarely bite. At large scale, they dominate every engineering decision. Consider an 8-billion-parameter model such as the Llama 3 model from Section 5.1. Storing its weights in 32-bit floating point takes 32 GB, yet training it requires four times as much (128 GB) before processing a single example: every parameter needs a matching gradient, and the Adam optimizer (Section 9.5) maintains two additional tensors of the same size for running averages of the gradients and squared gradients. That already exceeds the memory of an 80 GB GPU.
Computing such budgets accurately requires knowing every tensor a model owns and the role each one plays. Everyday workflows depend on the exact same inventory: checkpoints must capture every persistent tensor the forward pass depends on, GPU transfers must move them all together, and fine-tuning must specify cleanly which tensors the optimizer may update.
Frameworks unify all of these operations through registration (Section 5.1): each layer registers its tensors into the module tree under structured names, allowing optimizers, checkpoint savers, and device-transfer routines to walk that single tree. This section surveys that state tree in three parts. First, we distinguish trainable parameters from non-trainable buffers. Second, we account for training memory in bytes per parameter and show how to count parameters without allocating their storage. Third, we cover two recurring parameter patterns, weight tying and parameter freezing, used throughout language modeling and transfer learning.
import torch
from torch import nn5.2.1 The State Tree#
5.2.1.1 Access by Path#
Our running example is a compact residual MLP: an input layer projecting 20
features to 64 hidden units, two 64-wide residual blocks, and a 10-unit output
layer. We redefine ResidualBlock from Section 5.1 here so
the notebook stands on its own: each block adds the output of a two-layer body
directly to its input.
class ResidualBlock(nn.Module):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential(
nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
nn.Linear(num_hiddens, num_hiddens))
def forward(self, X):
return X + self.body(X)
net = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
ResidualBlock(64), nn.Linear(64, 10))
X = torch.randn(2, 20)
net(X).shapetorch.Size([2, 10])
Parameters sit at the leaves of the module tree. The dotted path to any leaf (Figure 5.1.1) mirrors how we index into it in Python, which is handy for inspecting a single layer during debugging. Optimizers and checkpoint writers, however, need every leaf at once, so each framework provides a full-tree traversal yielding all parameters alongside their paths.
In PyTorch it is named_parameters(). Each parameter is an nn.Parameter,
a tensor that registers itself with the module system as trainable, and
its gradient .grad stays None until backpropagation fills it.
This residual MLP contains 12 parameter tensors in total. Below we inspect the total count along with the four tensors belonging to the first residual block:
named = list(net.named_parameters())
len(named), [(name, p.shape) for name, p in named[2:6]](12,
[('1.body.0.weight', torch.Size([64, 64])),
('1.body.0.bias', torch.Size([64])),
('1.body.2.weight', torch.Size([64, 64])),
('1.body.2.bias', torch.Size([64]))])
A name like 1.body.0.weight traces the path from child 1 of net (the first residual block) through body and its first layer 0 to weight (net[1].body[0].weight). In Gluon, grad_req == 'write' marks trainable parameters; in PyTorch, state_dict() keys match named_parameters() whenever the model has no buffers:
list(net.state_dict()) == [name for name, _ in net.named_parameters()]True
Every framework utility traverses this same state tree under these paths. The equality above holds only because every tensor in our residual MLP happens to be trainable, which is not true of all layers.
5.2.1.2 Parameters and Buffers#
Suppose a model standardizes its inputs using a feature-wise mean and standard deviation computed once from the training set. Those statistics must be saved inside checkpoints (without them, predictions at inference time would be wrong) and moved onto the GPU alongside the weights, yet the optimizer must never update them via gradient descent, because they are data statistics rather than learned weights. Storing them as plain Python attributes fails, since module traversals ignore plain attributes (Section 5.1). Batch normalization (Section 7.3, (Ioffe and Szegedy, 2015)) relies on the exact same category of state: running means and variances updated during training forward passes and applied during inference.
Such persistent, non-trainable tensors are commonly called buffers, and every framework lets us register them so checkpoints and device moves include them while optimizers skip them. This yields a simple three-way rule for every tensor inside a layer: register it as a parameter if the optimizer should update it, register it as a buffer if checkpoints and device transfers need it without gradients, and keep it as an ordinary local variable if it lives only for one forward/backward pass (such as intermediate activations cached by backpropagation in Section 4.3). Architectural constants like layer widths remain plain Python attributes. Table 5.2.1 collects these rules for later reference.
| Kind | Example | Updated by the optimizer | Saved in checkpoints | Moved with the model |
|---|---|---|---|---|
| parameter | weights, biases | yes | yes | yes |
| buffer | input statistics, BatchNorm running means | no | yes | yes |
| plain attribute | layer widths | no | no | no |
| local variable | intermediate activations | no | no | no |
To illustrate, we build a Standardizer module that normalizes its inputs with
a precomputed per-feature mean and standard deviation before applying a linear
layer.
self.register_buffer(name, tensor) registers a non-trainable buffer.
class Standardizer(nn.Module):
def __init__(self, mean, std):
super().__init__()
self.register_buffer('mean', mean)
self.register_buffer('std', std)
self.out = nn.Linear(4, 2)
def forward(self, X):
return self.out((X - self.mean) / self.std)
sample = torch.randn(100, 4) * torch.arange(1., 5.)
standardizer = Standardizer(sample.mean(0), sample.std(0, correction=0))
list(standardizer.state_dict())['mean', 'std', 'out.weight', 'out.bias']
Inspecting the trainable vs. non-trainable state confirms that checkpoints see all four tensors while optimizers see only the linear layer's weight and bias:
[name for name, _ in standardizer.named_parameters()]['out.weight', 'out.bias']
Registration governs more than checkpointing and optimization: whole-model operations such as dtype casting (Section 5.5) and GPU transfers (Section 5.7) traverse the exact same state tree, moving parameters and buffers alike while leaving unregistered plain attributes behind.
5.2.2 Training Memory#
5.2.2.1 Bytes per Parameter#
How much memory does it take to train our residual MLP? Focusing on model and optimizer state alone, memory scales with three per-parameter components: the parameter itself, its gradient, and any per-parameter optimizer state. Plain minibatch SGD keeps no state, so in 32-bit floating point (fp32, 4 bytes per number) it consumes 8 bytes per parameter. Adam adds two fp32 tensors per parameter: exponential moving averages of the gradient and of the squared gradient. Because nearly all large-scale training runs use Adam or a close variant, that 16-byte figure is the practical baseline:
| Training state | Precision | Bytes per parameter |
|---|---|---|
| Weights | fp32 | 4 |
| Gradients | fp32 | 4 |
| Adam's average of the gradients | fp32 | 4 |
| Adam's average of their squares | fp32 | 4 |
| Total | 16 |
These 16 bytes per parameter represent a strict lower bound. They exclude intermediate activations saved during the forward pass for backpropagation (which grow with batch size and sequence length), temporary kernel workspaces, and allocator fragmentation, all of which we measure directly on a GPU in Section 5.7. For our residual MLP, that baseline comes out to:
n = sum(p.numel() for p in net.parameters())
weights, grads, adam_state = 4 * n, 4 * n, 8 * n # bytes, all fp32
print(f'{n} parameters: {(weights + grads + adam_state) / 2**20:.2f} MiB '
'for weights + gradients + Adam state')18634 parameters: 0.28 MiB for weights + gradients + Adam state
We can double-check that count by hand: the input layer contributes parameters, each residual block contributes , and the output layer adds , totaling 18,634 parameters. Adam's optimizer state is not just a theoretical entry in a table: it is real memory allocated tensor by tensor, adding two full copies of the model:
adam = torch.optim.Adam(net.parameters())
net(X).sum().backward()
adam.step()
moments = sum(t.numel() for state in adam.state.values()
for t in state.values() if t.ndim > 0)
moments == 2 * nTrue
Adam allocates the two moments of each parameter on its first step().
For our tiny MLP, that baseline is a negligible 0.28 MiB, which is why memory barely crossed our minds in earlier chapters. Scale the exact same arithmetic to an 8-billion-parameter model, however, and you immediately hit 128 GB regardless of batch size. You might hope that 16-bit mixed-precision training (Section 5.5) cuts this static floor in half. Surprisingly, it does not: mixed precision keeps fp32 master copies of the weights and fp32 Adam moments so tiny updates do not vanish under rounding (Micikevicius et al., 2018), and the 16-bit values that the forward pass uses are cast from them.
5.2.2.2 Counting Without Allocating#
Every parameter count above inspected tensors that had already been allocated. For an 8B model, that gets the order backwards: checking whether 32 GB of weights fit in RAM should not require allocating 32 GB first. Fortunately, counting parameters requires only shapes and dtypes, both of which are determined purely by constructor arguments. Consider the output projection of Llama 3 8B, mapping a 4,096-dimensional hidden state to logits over 128,256 vocabulary tokens. Its weight matrix has entries (2.1 GB in fp32). Below, we instantiate and count this layer without allocating its storage.
Constructing a module inside with torch.device('meta'): creates meta tensors that carry shapes and dtypes without allocating storage:
with torch.device('meta'):
head = nn.Linear(4096, 128256, bias=False) # shapes, no data
n_head = sum(p.numel() for p in head.parameters())
print(head.weight.device, f'{n_head:,} parameters, '
f'{4 * n_head / 1e9:.1f} GB in fp32')meta 525,336,576 parameters, 2.1 GB in fp32
To materialize a meta-device model without wasting time on random initialization before loading a checkpoint, call to_empty(device=...) and then load_state_dict:
with torch.device('meta'):
clone = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
ResidualBlock(64), nn.Linear(64, 10))
clone = clone.to_empty(device='cpu') # memory, no values yet
clone.load_state_dict(net.state_dict())
torch.equal(clone(X), net(X))True
Running the same abstract inspection across every layer of an 8B model yields its exact 8-billion parameter count, along with the 128 GB training floor, without allocating a single byte of tensor memory.
5.2.3 Shared and Frozen Parameters#
5.2.3.1 Tied Parameters#
A single parameter tensor can play multiple roles inside a network. The classic example comes from language modeling (Section 8.3), where a model reads tokens from a vocabulary and predicts the next token. Its input embedding is a lookup table whose row is the -dimensional representation of token , while its output head projects a -dimensional hidden state back to token logits: another table with the exact same geometry and semantic meaning. Tying both layers to one shared weight matrix eliminates parameters and often improves generalization (Press and Wolf, 2017; Inan et al., 2017): tokens that behave interchangeably as inputs naturally deserve similar scores as outputs, and weight tying enforces a single unified token geometry. The memory savings can be dramatic: in GPT-2 small (Radford et al., 2019), the tied table accounts for roughly 38.6 million of the model's 124 million parameters, nearly a third of the entire network.
One weight matrix W, two call sites: the embedding looks up a row by token id, the output head multiplies by its transpose to produce logits. Tying means both point at the same tensor, so gradients from both uses sum into one place.
Figure 5.2.1 illustrates the two call sites. We verify the
mechanics on a miniature language model, ToyLM, with a 100-token vocabulary
and hidden width .
Assigning self.head.weight = self.emb.weight aliases both layers to the same nn.Parameter tensor:
class ToyLM(nn.Module):
def __init__(self, vocab_size, d, tied=True):
super().__init__()
self.emb = nn.Embedding(vocab_size, d)
self.body = nn.Linear(d, d)
self.head = nn.Linear(d, vocab_size, bias=False)
if tied:
self.head.weight = self.emb.weight # one tensor, two roles
def forward(self, tokens):
return self.head(torch.relu(self.body(self.emb(tokens))))
lm = ToyLM(vocab_size=100, d=16)
lm.head.weight is lm.emb.weightTrue
Does the shared matrix get counted once or twice? We compare the tied model against an untied counterpart.
untied = ToyLM(vocab_size=100, d=16, tied=False)
(sum(p.numel() for p in lm.parameters()),
sum(p.numel() for p in untied.parameters()))(1872, 3472)
The tied model contains parameters (one embedding table plus the body layer), whereas the untied version adds a second table for 3472 parameters in all.
Both collect_params() and state_dict() retain both keys (emb.weight and head.weight) pointing to the shared storage (PyTorch's named_parameters(), printed below, lists the shared tensor only once):
sd = lm.state_dict()
(sd['emb.weight'].data_ptr() == sd['head.weight'].data_ptr(),
[name for name, _ in lm.named_parameters()])(True, ['emb.weight', 'body.weight', 'body.bias'])
What happens during backpropagation when a tensor is used twice? By the multivariable chain rule, each call site contributes its own gradient term, and both contributions sum into the gradient of the shared tensor. Writing and for the two tables of the untied model initialized to the same values as the tied matrix , the two models compute the exact same function and satisfy
We verify this identity numerically by copying the tied weights into the untied model and comparing gradients on the same batch:
untied.load_state_dict(lm.state_dict()) # same values, separate tensors
tokens = torch.randint(0, 100, (2, 8))
lm(tokens).sum().backward()
untied(tokens).sum().backward()
torch.allclose(lm.emb.weight.grad,
untied.emb.weight.grad + untied.head.weight.grad)True
5.2.3.2 Frozen Parameters#
When fine-tuning a pretrained network on a new task (Section 20.2), a common strategy is to keep the pretrained backbone fixed and train only a fresh output head, dramatically cutting both data requirements and optimizer memory. Locking parameters against gradient updates is called freezing. Below we freeze every layer except the output head of a fresh residual MLP, leaving just 650 of its 18,634 parameters trainable.
Setting p.requires_grad = False on backbone parameters excludes them from gradient accumulation:
finetune = nn.Sequential(nn.Linear(20, 64), ResidualBlock(64),
ResidualBlock(64), nn.Linear(64, 10))
for p in finetune[:-1].parameters():
p.requires_grad = False
(sum(p.numel() for p in finetune.parameters() if p.requires_grad),
sum(p.numel() for p in finetune.parameters()))(650, 18634)
Taking one Adam step should now update only the output head while leaving all earlier layers untouched. We check every parameter before and after the step.
head_opt = torch.optim.Adam(
(p for p in finetune.parameters() if p.requires_grad), lr=0.1)
before = [p.clone() for p in finetune.parameters()]
finetune(X).sum().backward()
head_opt.step()
[not torch.equal(b, p) for b, p in zip(before, finetune.parameters())][False,
False,
False,
False,
False,
False,
False,
False,
False,
False,
True,
True]
Only the output head's weight and bias changed, and the optimizer allocated Adam moments for just those 650 trainable parameters. Freezing comes with two subtle pitfalls, neither of which raises an error. First, freezing a parameter does not reclaim optimizer state that has already been allocated. If an Adam optimizer was constructed over all parameters and has already stepped, it continues holding 8 bytes per parameter of running moments even for layers frozen later: harmless for 18,634 parameters, but costly at 8-billion-parameter scale (as explored in the exercises).
The second pitfall is even easier to overlook: freezing blocks gradients, yet some layer state mutates without gradients. In particular, batch normalization (Section 7.3) updates its running mean and variance during the forward pass whenever the layer runs in training mode, completely bypassing the optimizer. Whether freezing a BatchNorm layer's trainable weights also locks its running statistics therefore depends on the framework. Below we pass a shifted batch through a frozen BatchNorm layer in training mode, with no optimizer step at all, and check whether its running mean drifts.
bn = nn.BatchNorm1d(4)
for p in bn.parameters():
p.requires_grad = False
before = bn.running_mean.clone()
bn(torch.randn(8, 4) + 3) # training mode: the statistics update
torch.allclose(bn.running_mean, before)False
The running mean moved. Freezing parameter gradients (requires_grad=False) is separate from switching the layer to evaluation mode (bn.eval()). Locking a BatchNorm layer during fine-tuning requires setting both.
Every parameter we inspected in this section (tied, frozen, or averaged) began from initial values supplied by the framework. In the next section, we examine how those initial values are chosen and how to control initialization across the entire module tree.
5.2.4 Summary#
A model's persistent state forms a tree of named tensors, and registration determines which framework operations see each tensor: optimizers update parameters, whereas checkpoints and device transfers also include buffers (persistent tensors without gradients, such as running statistics), and unregistered attributes are silently skipped. Training in fp32 with Adam requires a baseline of 16 bytes per parameter before accounting for activations (weights, gradients, and two Adam moments, or 128 GB for an 8B model), and abstract shape inspection lets us compute such budgets without allocating memory. Weight tying aliases one tensor across multiple roles so it is counted once and receives the sum of gradients from all call sites; freezing halts gradient updates but does not release existing optimizer state, and need not stop forward-pass updates to BatchNorm running statistics.
5.2.5 Exercises#
- [code] Running statistics. This problem needs only one fact about the batch normalization layer of Section 7.3, the update below. In training mode the layer normalizes with the minibatch mean and variance, and each training step updates the running mean by
-
A fresh layer starts from . Predict after the layer has processed batches in training mode, each with minibatch mean 3 in every feature. Check the prediction for on a fresh layer over 4 features, without any optimizer step, and read off the value of the layer uses by default.
-
Suppose you registered as a trainable parameter and removed the update above. What gradient does the training loss send to ? How do the training loss and the evaluation accuracy then compare with those of an unmodified model?
-
Find a loss in alone whose gradient step with learning rate on each minibatch reproduces the removed update, and state the that matches .
-
[code] Memory footprint. Write a helper that reports, for each top-level block of
net, its number of state entries and its bytes under fp32 Adam training with every parameter trained.- Which block dominates? At what output width would the output layer overtake one residual block?
- Insert a batch normalization layer over the 64 hidden features between the two residual blocks. Extend the helper so that it costs the layer's running statistics correctly, and report each block's bytes per entry. For which blocks is the share of the total bytes larger than the share of the total entries, and for which is it smaller? Explain both directions.
- [code] Tying and freezing. Consider the tied
ToyLMof this section.- Freeze
lm.emb.weightbut leavelm.headalone. How many trainable parameters remain, and what does this show about the interaction between tying and freezing? - Starting from the values of
lm, build a model whose embedding stays fixed while its head adapts, and verify both properties after one optimizer step. How many parameters does it store and how many does it train, compared with a fully trainablelm?
- Freeze
- Fine-tuning memory. A language model has 8 billion parameters. Its
output layer is a matrix, not tied to the
embedding. All state is fp32, and the optimizer is Adam.
- How many bytes do weights, gradients, and Adam's running averages take when every parameter is trained? How many 80 GB GPUs does that state alone fill?
- Freeze everything except the output layer, and build the optimizer over the output layer only. How many bytes does the persistent state take now, and does it fit on one 80 GB GPU?
- Suppose instead that an optimizer built over all parameters took one step before the freeze and is kept afterwards. How many bytes remain allocated, and does the state still fit?