import torch
from torch import nn5.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 tensorflow as tfimport math
import os
from mxnet import autograd, gluon, np as mnp, npx
from mxnet.gluon import nn
npx.set_np()5.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])
class ResidualBlock(tf.keras.layers.Layer):
def __init__(self, num_hiddens, **kwargs):
super().__init__(**kwargs)
self.body = tf.keras.Sequential([
tf.keras.layers.Dense(num_hiddens, activation='relu'),
tf.keras.layers.Dense(num_hiddens)])
def call(self, X):
return X + self.body(X)
net = tf.keras.Sequential([tf.keras.layers.Dense(64), ResidualBlock(64),
ResidualBlock(64), tf.keras.layers.Dense(10)])
X = tf.random.normal((2, 20))
net(X).shapeTensorShape([2, 10])
class ResidualBlock(nnx.Module):
def __init__(self, num_hiddens, *, rngs):
self.body = nnx.Sequential(
nnx.Linear(num_hiddens, num_hiddens, rngs=rngs), nnx.relu,
nnx.Linear(num_hiddens, num_hiddens, rngs=rngs))
def __call__(self, X):
return X + self.body(X)
rngs = nnx.Rngs(d2l.get_key())
net = nnx.Sequential(nnx.Linear(20, 64, rngs=rngs),
ResidualBlock(64, rngs=rngs),
ResidualBlock(64, rngs=rngs),
nnx.Linear(64, 10, rngs=rngs))
X = jax.random.normal(rngs(), (2, 20))
net(X).shape(2, 10)
class ResidualBlock(nn.Block):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential()
self.body.add(nn.Dense(num_hiddens, activation='relu',
in_units=num_hiddens),
nn.Dense(num_hiddens, in_units=num_hiddens))
def forward(self, X):
return X + self.body(X)
net = nn.Sequential()
net.add(nn.Dense(64), ResidualBlock(64), ResidualBlock(64), nn.Dense(10))
net.initialize()
X = mnp.random.normal(size=(2, 20))
net(X).shape(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.
In Keras it is net.weights, a list of variables that each carry their path. Variables do not store their gradients: a tf.GradientTape returns them as a second list, parallel to the variables.
In NNX it is nnx.state(net, nnx.Param), whose flat view yields each array with its path. Parameters do not store their gradients: nnx.grad returns them as a second state tree with the same paths.
In Gluon it is collect_params(), a dictionary keyed by path. Each value is a Parameter, an object that bundles the array, .data(), with its gradient, .grad(), which holds zeros until backpropagation writes to 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]))])
len(net.weights), [(v.path, v.shape) for v in net.weights[2:6]](12,
[('sequential_2/residual_block/sequential/dense_1/kernel',
TensorShape([64, 64])),
('sequential_2/residual_block/sequential/dense_1/bias', TensorShape([64])),
('sequential_2/residual_block/sequential/dense_2/kernel',
TensorShape([64, 64])),
('sequential_2/residual_block/sequential/dense_2/bias', TensorShape([64]))])
params = nnx.state(net, nnx.Param)
flat = list(params.flat_state())
len(flat), [(path, leaf.shape) for path, leaf in flat[2:6]](12,
[(('layers', 1, 'body', 'layers', 0, 'bias'), (64,)),
(('layers', 1, 'body', 'layers', 0, 'kernel'), (64, 64)),
(('layers', 1, 'body', 'layers', 2, 'bias'), (64,)),
(('layers', 1, 'body', 'layers', 2, 'kernel'), (64, 64))])
named = list(net.collect_params().items())
len(named), [(name, p.shape) for name, p in named[2:6]](12,
[('1.body.0.weight', (64, 64)),
('1.body.0.bias', (64,)),
('1.body.1.weight', (64, 64)),
('1.body.1.bias', (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:
A path like sequential_2/residual_block/sequential/dense_1/kernel traces layer names down to kernel (net.layers[1].body.layers[0].kernel). Because default layer names include a creation counter, pass explicit name= arguments when paths must match across scripts. With no buffers present, net.weights equals net.trainable_weights:
A path tuple like ('layers', 1, 'body', 'layers', 0, 'kernel') mirrors net.layers[1].body.layers[0].kernel. With only trainable parameters present, nnx.state(net) matches nnx.state(net, nnx.Param):
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
[v.path for v in net.weights] == [v.path for v in net.trainable_weights]True
([path for path, _ in nnx.state(net).flat_state()]
== [path for path, _ in params.flat_state()])True
params = net.collect_params()
[name for name, p in params.items() if p.grad_req == 'write'] == list(params)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.
self.add_weight(..., trainable=False) registers a non-trainable variable.
Subclassing nnx.Variable (here class Buffer(nnx.Variable)) distinguishes buffers from nnx.Param.
gluon.Constant registers a Parameter with grad_req='null'.
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']
class Standardizer(tf.keras.layers.Layer):
def __init__(self, mean, std, **kwargs):
super().__init__(**kwargs)
self.mean = self.add_weight(
shape=mean.shape, trainable=False, name='mean',
initializer=tf.keras.initializers.Constant(mean))
self.std = self.add_weight(
shape=std.shape, trainable=False, name='std',
initializer=tf.keras.initializers.Constant(std))
self.out = tf.keras.layers.Dense(2)
def call(self, X):
return self.out((X - self.mean) / self.std)
sample = tf.random.normal((100, 4)) * tf.range(1., 5.)
standardizer = Standardizer(tf.reduce_mean(sample, 0),
tf.math.reduce_std(sample, 0))
_ = standardizer(sample[:2]) # build the Dense layer
[v.path for v in standardizer.weights]['standardizer/mean',
'standardizer/std',
'standardizer/dense_6/kernel',
'standardizer/dense_6/bias']
class Buffer(nnx.Variable):
pass
class Standardizer(nnx.Module):
def __init__(self, mean, std, *, rngs):
self.mean = Buffer(mean)
self.std = Buffer(std)
self.out = nnx.Linear(4, 2, rngs=rngs)
def __call__(self, X):
return self.out((X - self.mean) / self.std)
sample = jax.random.normal(rngs(), (100, 4)) * jnp.arange(1., 5.)
standardizer = Standardizer(sample.mean(0), sample.std(0), rngs=rngs)
[(path, value.shape) for path, value in nnx.state(standardizer).flat_state()][(('mean',), (4,)),
(('out', 'bias'), (2,)),
(('out', 'kernel'), (4, 2)),
(('std',), (4,))]
class Standardizer(nn.Block):
def __init__(self, mean, std):
super().__init__()
self.mean = gluon.Constant(mean)
self.std = gluon.Constant(std)
self.out = nn.Dense(2)
def forward(self, X):
return self.out((X - self.mean.data()) / self.std.data())
sample = mnp.random.normal(0, 1, (100, 4)) * mnp.arange(1., 5.)
standardizer = Standardizer(sample.mean(axis=0), sample.std(axis=0))
standardizer.initialize()
standardizer(sample[:2]) # build the deferred Dense layer
list(standardizer.collect_params())['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']
([v.path for v in standardizer.trainable_weights],
[v.path for v in standardizer.non_trainable_weights])(['standardizer/dense_6/kernel', 'standardizer/dense_6/bias'],
['standardizer/mean', 'standardizer/std'])
{'params': list(nnx.state(standardizer, nnx.Param)),
'buffers': list(nnx.state(standardizer, Buffer))}{'params': ['out'], 'buffers': ['mean', 'std']}
{name: p.grad_req for name, p in standardizer.collect_params().items()}{'mean': 'null', 'std': 'null', 'out.weight': 'write', 'out.bias': 'write'}
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
n = net.count_params()
weights = sum(int(tf.size(v)) * tf.as_dtype(v.dtype).size
for v in net.weights) # fp32: 4 bytes
grads, adam_state = weights, 2 * weights
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
leaves = jax.tree_util.tree_leaves(nnx.state(net, nnx.Param))
n = sum(x.size for x in leaves)
weights = sum(x.size * x.dtype.itemsize for x in leaves) # fp32: 4 bytes
grads, adam_state = weights, 2 * weights
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
params = net.collect_params()
n = sum(p.data().size for p in params.values())
weights = sum(p.data().size * p.data().dtype.itemsize
for p in params.values()) # fp32: 4 bytes
grads, adam_state = weights, 2 * weights
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 \(20 \times 64 + 64 = 1344\) parameters, each residual block contributes \(2 \times (64 \times 64 + 64) = 8320\), and the output layer adds \(64 \times 10 + 10 = 650\), 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 = tf.keras.optimizers.Adam()
with tf.GradientTape() as tape:
loss = tf.reduce_sum(net(X))
grads = tape.gradient(loss, net.trainable_weights)
# the first step allocates the moments
adam.apply_gradients(zip(grads, net.trainable_weights))
moments = sum(int(tf.size(v)) for v in adam.variables
if v.ndim > 0) # skip step count and learning rate
moments == 2 * nTrue
optimizer = nnx.Optimizer(net, optax.adam(1e-3), wrt=nnx.Param)
grads = nnx.grad(lambda model: model(X).sum())(net)
optimizer.update(net, grads)
moments = sum(x.size for x in jax.tree.leaves(optimizer.opt_state)
if hasattr(x, 'ndim') and x.ndim > 0)
moments == 2 * nTrue
trainer = gluon.Trainer(net.collect_params(), 'adam')
with autograd.record():
loss = net(X).sum()
loss.backward()
trainer.step(batch_size=1) # the updater allocates the moments here
trainer.save_states('adam.states')
state_bytes = os.path.getsize('adam.states')
os.remove('adam.states')
state_bytes, 8 * n(151114, 149072)
Adam allocates the two moments of each parameter on its first step().
Keras’s Adam allocates the two moments of each weight on its first apply_gradients call.
nnx.Optimizer allocates both moments when it is constructed, before any update.
Gluon’s Trainer owns this state and offers no public traversal of it: at each parameter’s first update, its updater creates two zero arrays shaped like the weight. It does offer save_states, which serializes that state, so apart from a little packaging the file holds Adam’s two running averages: 8 bytes per parameter, two more copies of the model.
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 \(4096 \times 128{,}256 = 525{,}336{,}576\) 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:
An unbuilt Dense layer allocates no variables; its kernel shape (inputs, units) follows directly from the input width and head.units:
nnx.eval_shape traces the constructor abstractly, returning jax.ShapeDtypeStruct leaves with shapes and dtypes but zero allocated arrays:
A Dense layer constructed with in_units records its parameter shapes immediately but allocates no memory until initialize() runs:
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
head = tf.keras.layers.Dense(128256, use_bias=False) # not built
n_head = 4096 * head.units # kernel shape: (inputs, units)
print(head.weights, f'{n_head:,} parameters, '
f'{4 * n_head / 1e9:.1f} GB in fp32')[] 525,336,576 parameters, 2.1 GB in fp32
key = d2l.get_key() # drawn outside the abstract trace
head = nnx.eval_shape(lambda: nnx.Linear(
4096, 128256, use_bias=False, rngs=nnx.Rngs(key)))
leaves = jax.tree.leaves(nnx.state(head, nnx.Param))
n_head = sum(x.size for x in leaves)
print(leaves, f'{n_head:,} params, {4 * n_head / 1e9:.1f} GB in fp32')[ShapeDtypeStruct(shape=(4096, 128256), dtype=float32)] 525,336,576 params, 2.1 GB in fp32
head = nn.Dense(128256, in_units=4096, use_bias=False) # not initialized
n_head = sum(math.prod(p.shape) for p in head.collect_params().values())
print(head.weight, f'{n_head:,} parameters, '
f'{4 * n_head / 1e9:.1f} GB in fp32')Parameter (shape=(128256, 4096), dtype=float32) 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.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 \(\hat{\boldsymbol{\mu}}_{\mathcal{B}}\) and variance, and each training step updates the running mean \(\bar{\boldsymbol{\mu}}\) by
\[\bar{\boldsymbol{\mu}} \leftarrow \rho\, \bar{\boldsymbol{\mu}} + (1 - \rho)\, \hat{\boldsymbol{\mu}}_{\mathcal{B}}. \tag{5.2.2}\]
- A fresh layer starts from \(\bar{\boldsymbol{\mu}} = \mathbf{0}\). Predict \(\bar{\boldsymbol{\mu}}\) after the layer has processed \(k\) batches in training mode, each with minibatch mean 3 in every feature. Check the prediction for \(k = 1, 5, 20\) on a fresh layer over 4 features, without any optimizer step, and read off the value of \(\rho\) the layer uses by default.
- Suppose you registered \(\bar{\boldsymbol{\mu}}\) as a trainable parameter and removed the update above. What gradient does the training loss send to \(\bar{\boldsymbol{\mu}}\)? How do the training loss and the evaluation accuracy then compare with those of an unmodified model?
- Find a loss in \(\bar{\boldsymbol{\mu}}\) alone whose gradient step with learning rate \(\eta\) on each minibatch reproduces the removed update, and state the \(\eta\) that matches \(\rho\).
[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 \(4096 \times 128{,}256\) 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?
[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 \(\hat{\boldsymbol{\mu}}_{\mathcal{B}}\) and variance, and each training step updates the running mean \(\bar{\boldsymbol{\mu}}\) by
\[\bar{\boldsymbol{\mu}} \leftarrow \rho\, \bar{\boldsymbol{\mu}} + (1 - \rho)\, \hat{\boldsymbol{\mu}}_{\mathcal{B}}.\]
- A fresh layer starts from \(\bar{\boldsymbol{\mu}} = \mathbf{0}\). Predict \(\bar{\boldsymbol{\mu}}\) after the layer has processed \(k\) batches in training mode, each with minibatch mean 3 in every feature. Check the prediction for \(k = 1, 5, 20\) on a fresh layer over 4 features, without any optimizer step, and read off the value of \(\rho\) the layer uses by default.
- Suppose you registered \(\bar{\boldsymbol{\mu}}\) as a trainable parameter and removed the update above. What gradient does the training loss send to \(\bar{\boldsymbol{\mu}}\)? How do the training loss and the evaluation accuracy then compare with those of an unmodified model?
- Find a loss in \(\bar{\boldsymbol{\mu}}\) alone whose gradient step with learning rate \(\eta\) on each minibatch reproduces the removed update, and state the \(\eta\) that matches \(\rho\).
[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.- Set
lm.emb.trainable = Falsebut leavelm.headalone. How many trainable parameters remain, and can the head still adapt? 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?
- Set
Fine-tuning memory. A language model has 8 billion parameters. Its output layer is a \(4096 \times 128{,}256\) 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?
[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 \(\hat{\boldsymbol{\mu}}_{\mathcal{B}}\) and variance, and each training step updates the running mean \(\bar{\boldsymbol{\mu}}\) by
\[\bar{\boldsymbol{\mu}} \leftarrow \rho\, \bar{\boldsymbol{\mu}} + (1 - \rho)\, \hat{\boldsymbol{\mu}}_{\mathcal{B}}.\]
- A fresh layer starts from \(\bar{\boldsymbol{\mu}} = \mathbf{0}\). Predict \(\bar{\boldsymbol{\mu}}\) after the layer has processed \(k\) batches in training mode, each with minibatch mean 3 in every feature. Check the prediction for \(k = 1, 5, 20\) on a fresh layer over 4 features, without any optimizer step, and read off the value of \(\rho\) the layer uses by default.
- Suppose you registered \(\bar{\boldsymbol{\mu}}\) as a trainable parameter and removed the update above. What gradient does the training loss send to \(\bar{\boldsymbol{\mu}}\)? How do the training loss and the evaluation accuracy then compare with those of an unmodified model?
- Find a loss in \(\bar{\boldsymbol{\mu}}\) alone whose gradient step with learning rate \(\eta\) on each minibatch reproduces the removed update, and state the \(\eta\) that matches \(\rho\).
[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.- Leave the embedding table out of the trainable filter, for example with
nnx.All(nnx.Param, nnx.Not(nnx.PathContains('emb'))), and pass the filter tonnx.gradandnnx.Optimizer. How many parameters are trained, and can the head still adapt? 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 update. How many parameters does it store and how many does it train, compared with a fully trainablelm?
- Leave the embedding table out of the trainable filter, for example with
Fine-tuning memory. A language model has 8 billion parameters. Its output layer is a \(4096 \times 128{,}256\) 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?
[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 \(\hat{\boldsymbol{\mu}}_{\mathcal{B}}\) and variance, and each training step updates the running mean \(\bar{\boldsymbol{\mu}}\) by
\[\bar{\boldsymbol{\mu}} \leftarrow \rho\, \bar{\boldsymbol{\mu}} + (1 - \rho)\, \hat{\boldsymbol{\mu}}_{\mathcal{B}}.\]
- A fresh layer starts from \(\bar{\boldsymbol{\mu}} = \mathbf{0}\). Predict \(\bar{\boldsymbol{\mu}}\) after the layer has processed \(k\) batches in training mode, each with minibatch mean 3 in every feature. Check the prediction for \(k = 1, 5, 20\) on a fresh layer over 4 features, without any optimizer step, and read off the value of \(\rho\) the layer uses by default.
- Suppose you registered \(\bar{\boldsymbol{\mu}}\) as a trainable parameter and removed the update above. What gradient does the training loss send to \(\bar{\boldsymbol{\mu}}\)? How do the training loss and the evaluation accuracy then compare with those of an unmodified model?
- Find a loss in \(\bar{\boldsymbol{\mu}}\) alone whose gradient step with learning rate \(\eta\) on each minibatch reproduces the removed update, and state the \(\eta\) that matches \(\rho\).
[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.- Set
lm.emb.weight.grad_req = 'null'. What happened to the head, and how many trainable parameters remain? 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?
- Set
Fine-tuning memory. A language model has 8 billion parameters. Its output layer is a \(4096 \times 128{,}256\) 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?