Parameters, State, and Memory

Dive into Deep Learning · §5.2

Parameters, State, and Memory
the state tree · trainable parameters vs. buffers · 16 B/param Adam floor · weight tying · freezing

Why an 8B Model Needs 128 GB Before Batch Size 1

The Systems Memory Budget

  • Four full-precision copies (16\text{ B/param}): fp32 Adam stores weights \mathbf{w} (4\text{ B}), gradients \mathbf{g} (4\text{ B}), first moment \mathbf{m} (4\text{ B}), and second moment \mathbf{v} (4\text{ B}).
  • 8B parameter static floor: 8 \times 10^9 \times 16\text{ B} = 128\text{ GB}, exceeding an 80 GB GPU before loading a single input batch.
  • Why state tree literacy matters: Budgeting memory, saving checkpoints, and freezing layers require tracking every tensor in the state tree.

Running Example: A Two-Block Residual MLP

Constructing the State Tree

  • We inspect state traversal on a compact residual MLP (20 \to 64 \to \text{ two } 64\text{-wide residual blocks } \to 10) containing 6 linear layers and 12 parameter tensors:
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).shape

Accessing Parameters by Their Path in the State Tree

Tree Traversal

  • A full-tree iterator yields every leaf alongside its path in the tree:
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]))])
list(net.state_dict()) == [name for name, _ in net.named_parameters()]
True

The Three-Way Classification of Tensors in a Layer

Parameters vs. Buffers

  • Parameters: Updated by optimizer, saved in checkpoints, and moved to GPUs (\mathbf{W}, \mathbf{b}, \mathbf{g}).
  • Registered buffers: Skipped by optimizer, but saved in checkpoints and moved/cast with the model (feature \boldsymbol{\mu}, \boldsymbol{\sigma}, BatchNorm running stats).
  • Plain attributes: Invisible to checkpoints and device moves; never store persistent tensors as plain Python attributes.

Registering Non-Trainable Buffers in a Standardizer

Buffers in Code

  • A Standardizer layer registers training-set statistics \boldsymbol{\mu} and \boldsymbol{\sigma} as non-trainable buffers.

A Standardizer Layer with Two Buffers

Buffers in Code

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']

Checkpoints Include Buffers; Optimizers Skip Them

Filtering the State Tree

  • Comparing the full state tree against trainable parameters confirms that mean and std travel to disk and GPU while the optimizer updates only weight and bias:
[name for name, _ in standardizer.named_parameters()]
['out.weight', 'out.bias']

Accounting for Parameters and Bytes in the Residual MLP

Memory Arithmetic

We can verify the parameter count of our residual MLP analytically and convert it to bytes under the 16-byte-per-parameter fp32 Adam rule:

Layer Group Parameter Formula (W + b) Parameter Count fp32 Adam State (16\text{ B/param})
Input layer (0) 20 \times 64 + 64 1{,}344 21{,}504\text{ B}
Residual blocks (1, 2) 2 \times [2 \times (64 \times 64 + 64)] 16{,}640 266{,}240\text{ B}
Output head (3) 64 \times 10 + 10 650 10{,}400\text{ B}
Total network 12 parameter tensors 18{,}634 298{,}144\text{ B} (0.28\text{ MiB})
18634 parameters: 0.28 MiB for weights + gradients + Adam state

Verifying That Adam Allocates Two Full Model Copies

Optimizer State Allocation

  • Adam keeps running first and second moments (\mathbf{m} and \mathbf{v}) for every parameter, adding 2 \times 18{,}634 = 37{,}268 floats (8\text{ B/param}):
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 * n
True

Counting Parameters Abstractly Without Allocating RAM

Meta Devices & Shape Tracing

  • Frameworks trace constructors abstractly using shapes and dtypes alone—auditing Llama 3 8B’s 525.3\text{M}-parameter (2.1 GB) output head with zero bytes allocated:
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

Materializing a Meta-Device Model on Target Hardware

Zero-Waste Checkpoint Loading

  • Constructing on torch.device('meta') and calling to_empty(device=...) before load_state_dict skips wasted CPU random initialization:
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

Weight Tying: One Parameter Tensor in Multiple Roles

Shared Parameters

Language models map input token IDs to d-vectors via a |V| \times d embedding table and project final d-vectors back to |V| token logits via a |V| \times d output head:

  • Shared semantic geometry: Tying both layers to the exact same |V| \times d tensor enforces a unified token representation and eliminates |V| \times d parameters.
  • Massive memory savings: In GPT-2 small (|V|=50{,}257, d=768), the tied table is 38.6\text{M} of 124\text{M} parameters (31\% of the entire network).

Implementing Weight Tying in a Miniature Language Model

Tying in Code

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.weight
  • In ToyLM (|V| = 100, d = 16), the output projection is an alias of the input embedding table, so the table is stored once:
True

Tied Tensors Are Deduplicated and Counted Once

Parameter Deduplication

  • Tree walkers deduplicate shared storage so the 100 \times 16 = 1{,}600 embedding table is counted only once (1{,}872 tied vs. 3{,}472 untied):
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)

Gradients from All Call Sites Sum Into a Tied Tensor

Multivariable Chain Rule

\frac{\partial L}{\partial \mathbf{W}} = \frac{\partial L}{\partial \mathbf{W}_{\text{emb}}} + \frac{\partial L}{\partial \mathbf{W}_{\text{head}}}

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

Freezing Parameters for Transfer Learning

Selective Optimization

When fine-tuning a pretrained backbone on a small dataset, we freeze the backbone weights and train only the output head (650 of 18{,}634 parameters in our residual MLP):

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)

After Freezing, Only the Head Trains

Selective Optimization

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]

Two Silent Pitfalls of Freezing Parameters

Systems Hazards of Freezing

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
  • Pitfall 1: Adam moments (8\text{ B/param}) stay in memory unless the optimizer covers only unfrozen parameters.
  • Pitfall 2: In training mode, BatchNorm layers can still update running mean/variance buffers during the forward pass unless switched to evaluation mode.

Concept Check: Memory Budgets & Parameter Sharing

Concept Check

Test your understanding on the 8-billion-parameter language model (fp32, Adam, output head 4096 \times 128{,}256 \approx 525\text{M} parameters):

  1. Suppose you freeze the entire 8B backbone except the 525\text{M}-parameter output head and construct Adam over the head alone. How much persistent state memory is required in fp32, and does it fit on a single 80 GB GPU?
  2. What if you instead constructed Adam over all 8B parameters, ran 1 warmup step, and then froze the backbone without recreating the optimizer?
  3. If two layers share a weight matrix \mathbf{W} and you freeze \mathbf{W} through the embedding layer, can self.head still adapt?

Answers:

  1. \approx 38.3\text{ GB} (fits on one 80 GB GPU): All 8B weights require 32\text{ GB}, while gradients and Adam moments for the 525\text{M} head require only 12 \times 0.525\text{B} = 6.3\text{ GB}.
  2. \approx 98.1\text{ GB} (OOM on 80 GB): Adam keeps the 64\text{ GB} of moments allocated on step 1 (32\text{ GB weights} + 64\text{ GB moments} + 2.1\text{ GB head grad}).
  3. No: Because self.emb.weight and self.head.weight alias the exact same parameter tensor, freezing one freezes both roles.

Summary: Parameters, State, and Memory

Key Takeaways

  • Parameters vs. buffers: Both travel to checkpoints and GPUs, while optimizers update only trainable parameters.
  • Static memory & meta counting: fp32 Adam costs 16\text{ B/param} (128 GB for 8B); meta devices audit exact byte budgets with zero physical allocation.
  • Weight tying & freezing: Shared tensors are counted once and sum gradients across call sites; freezing requires filtering the optimizer and switching BatchNorm to evaluation mode.