TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Parameters, Buffers, Custom Layers and Hooks

Parameters, Buffers, Custom Layers and Hooks

Sooner or later you need a layer PyTorch does not ship, or you need to look inside a model while it trains: which layer's activations saturate, where the gradients vanish, what a pretrained network's middle layer computes for an image. This lesson covers the four tools for that. nn.Parameter marks a tensor as trainable; buffers hold state that is saved and moved with the model but not trained; a custom layer is a small nn.Module combining both; and hooks let you read (or change) activations and gradients without editing the model's code. Freezing parameters and the choice between torch.nn.functional and modules close the lesson.

Three kinds of tensor in a module

Assigned as In parameters() In state_dict() Moved by .to() Trained by the optimizer
self.w = nn.Parameter(t) yes yes yes yes
self.register_buffer("b", t) no yes yes no
self.register_buffer("b", t, persistent=False) no no yes no
self.t = t (plain tensor) no no no no

Use a parameter for anything learned (weights, a learnable scale or temperature), a persistent buffer for state that must survive a checkpoint (batch-norm running mean and variance, a counter of steps), and a non-persistent buffer for constants you can recompute (a causal mask, a table of positional encodings). A plain tensor attribute is almost always a bug: it stays on the CPU when the model moves to the GPU.

A custom layer: layer normalisation

Layer normalisation is a good first custom layer: a few lines, two parameters, and a built-in reference to compare against. For an input row x∈Rdx \in \mathbb{R}^d it computes

μ=1d∑j=1dxj,σ2=1d∑j=1d(xj−μ)2,x^j=xj−μσ2+ε,yj=γjx^j+βj\mu = \frac{1}{d} \sum_{j=1}^{d} x_j, \qquad \sigma^2 = \frac{1}{d} \sum_{j=1}^{d} (x_j - \mu)^2, \qquad \hat{x}_j = \frac{x_j - \mu}{\sqrt{\sigma^2 + \varepsilon}}, \qquad y_j = \gamma_j \hat{x}_j + \beta_j

with learnable γ,β∈Rd\gamma, \beta \in \mathbb{R}^d initialised to ones and zeros. The derivation of its full backward pass and why it helps are in layer norm (this course returns to it in layer normalisation and RMSNorm). For the parameters the gradient is short: with g=∂L/∂yg = \partial L / \partial y for a batch of NN rows,

∂L∂γj=∑n=1Ngnj x^nj,∂L∂βj=∑n=1Ngnj\frac{\partial L}{\partial \gamma_j} = \sum_{n=1}^{N} g_{nj} \, \hat{x}_{nj}, \qquad \frac{\partial L}{\partial \beta_j} = \sum_{n=1}^{N} g_{nj}

The sum over nn is the general rule for a parameter that is shared by every row of the batch: its gradient adds up the contributions of all rows.

In NumPy first

The layer, the parameter gradient checked against central differences, and a forward "hook" as a list of callbacks that see each layer's output:

python · try it yourself
import numpy as np
rng = np.random.default_rng(0)

def layer_norm(x, gamma, beta, eps=1e-5):
    mu = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)           # divisor d, not d - 1
    x_hat = (x - mu) / np.sqrt(var + eps)
    return gamma * x_hat + beta, x_hat

x = rng.normal(2.0, 3.0, size=(8, 6))
gamma, beta = rng.uniform(0.5, 1.5, 6), rng.normal(0, 0.1, 6)
y, x_hat = layer_norm(x, gamma, beta)
print("x_hat row means", [round(float(v), 6) + 0.0 for v in x_hat.mean(axis=1)[:3]],
      "row std", [round(float(v), 4) for v in x_hat.std(axis=1)[:3]])

# gradients of L = sum(c * y) for a fixed random c: analytic vs numerical
c = rng.normal(size=y.shape)
g_gamma = (c * x_hat).sum(axis=0)                  # dL/dgamma
h = 1e-6
num = np.zeros(6)
for j in range(6):
    e = np.zeros(6); e[j] = h
    num[j] = ((c * layer_norm(x, gamma + e, beta)[0]).sum() - (c * layer_norm(x, gamma - e, beta)[0]).sum()) / (2 * h)
print("dL/dgamma analytic ", np.round(g_gamma, 4).tolist())
print("dL/dgamma numerical", np.round(num, 4).tolist())
print("agree to 1e-8:", bool(np.abs(num - g_gamma).max() < 1e-8))

# a forward "hook": a callback that sees every layer's output
hooks = []
def forward(x, layers):
    for name, f in layers:
        x = f(x)
        for hook in hooks:
            hook(name, x)
    return x

W1, W2 = rng.normal(0, 1, (6, 16)), rng.normal(0, 1, (16, 3))
layers = [("fc1", lambda a: a @ W1), ("tanh", np.tanh),
          ("norm", lambda a: layer_norm(a, np.ones(16), np.zeros(16))[0]), ("fc2", lambda a: a @ W2)]
stats = {}
hooks.append(lambda name, a: stats.__setitem__(name, (round(float(a.mean()), 3) + 0.0, round(float(a.std()), 3))))
out = forward(x, layers)
for name, (m, s) in stats.items():
    print(f"{name:5s} mean {m:7.3f}  std {s:6.3f}")
x_hat row means [0.0, 0.0, 0.0] row std [1.0, 1.0, 1.0]
dL/dgamma analytic  [-1.5374, 3.6311, -0.729, -0.297, -1.0733, 4.5176]
dL/dgamma numerical [-1.5374, 3.6311, -0.729, -0.297, -1.0733, 4.5176]
agree to 1e-8: True
fc1   mean  -1.254  std  8.018
tanh  mean  -0.090  std  0.931
norm  mean   0.000  std  1.000
fc2   mean  -0.695  std  3.727

Every normalised row has mean 0 and standard deviation 1, the formula for ∂L/∂γ\partial L / \partial \gamma matches the numerical gradient, and the hook reports each layer's statistics without the layers knowing about it. Note what the hook revealed: the first layer's outputs have a standard deviation of 8.018, far into the flat part of tanh⁡\tanh (most of its outputs sit near ±1\pm 1, hence a standard deviation of 0.931). PyTorch's hooks are this same callback idea, attached to modules and tensors.

In PyTorch

The same layer as a module, checked against nn.LayerNorm, next to a module with buffers:

python · try it yourself
import torch
from torch import nn

class SimpleLayerNorm(nn.Module):
    def __init__(self, d, eps=1e-5):
        super().__init__()
        self.gamma = nn.Parameter(torch.ones(d))        # learnable, in parameters() and state_dict
        self.beta = nn.Parameter(torch.zeros(d))
        self.eps = eps                                  # plain float: just an attribute
    def forward(self, x):
        mu = x.mean(dim=-1, keepdim=True)
        var = x.var(dim=-1, unbiased=False, keepdim=True)
        return self.gamma * (x - mu) / torch.sqrt(var + self.eps) + self.beta

class RunningMean(nn.Module):
    def __init__(self, d, momentum=0.1):
        super().__init__()
        self.momentum = momentum
        self.register_buffer("running_mean", torch.zeros(d))             # saved, moved, not trained
        self.register_buffer("calls", torch.zeros((), dtype=torch.long), persistent=False)
    def forward(self, x):
        if self.training:
            with torch.no_grad():
                self.running_mean.lerp_(x.mean(0), self.momentum)
                self.calls += 1
        return x - self.running_mean

torch.manual_seed(0)
x = torch.randn(8, 6) * 3 + 2
mine, ref = SimpleLayerNorm(6), nn.LayerNorm(6)
with torch.no_grad():
    mine.gamma.uniform_(0.5, 1.5); ref.weight.copy_(mine.gamma)
print("matches nn.LayerNorm to 1e-6:", (mine(x) - ref(x)).abs().max().item() < 1e-6)
print("SimpleLayerNorm parameters:", [n for n, _ in mine.named_parameters()])

rm = RunningMean(6)
for _ in range(3):
    rm(x)
print("RunningMean parameters:", [n for n, _ in rm.named_parameters()])
print("buffers:", [n for n, _ in rm.named_buffers()], "| state_dict:", list(rm.state_dict().keys()))
print("running mean[:3]:", [round(v, 4) for v in rm.running_mean[:3].tolist()], "calls", rm.calls.item())
rm.eval(); before = rm.running_mean.clone(); rm(x)
print("eval leaves the buffer alone:", torch.equal(before, rm.running_mean))

class Plain(nn.Module):
    def __init__(self):
        super().__init__()
        self.scale = torch.ones(3)            # plain tensor: not a parameter, not a buffer
p = Plain().double()
print("plain tensor attribute after .double():", p.scale.dtype, "| state_dict:", list(p.state_dict().keys()))
matches nn.LayerNorm to 1e-6: True
SimpleLayerNorm parameters: ['gamma', 'beta']
RunningMean parameters: []
buffers: ['running_mean', 'calls'] | state_dict: ['running_mean']
running mean[:3]: [0.6529, 0.2879, 0.7619] calls 3
eval leaves the buffer alone: True
plain tensor attribute after .double(): torch.float32 | state_dict: []

The table at the top, confirmed: the two nn.Parameters are parameters; both buffers are listed by named_buffers(), but only the persistent running_mean is in the state_dict; and a plain tensor attribute is ignored by .double() (and would be ignored by .to("cuda")) and by the state_dict. Updating a buffer happens under torch.no_grad() and in place (lerp_ computes m←m+0.1 (xˉ−m)m \leftarrow m + 0.1\,(\bar{x} - m), the exponential moving average batch norm uses), and only in training mode. The custom layer agrees with nn.LayerNorm to better than 10−610^{-6}: unbiased=False matters here, since the default var divides by d−1d - 1.

A custom layer needs no backward: autograd differentiates the forward you wrote. Write a torch.autograd.Function with an explicit backward only when you need a cheaper or more stable gradient than autograd's, as shown in autograd in PyTorch.

Hooks: activations and gradients

Hook Called Receives Typical use
module.register_forward_hook(fn) after forward (module, inputs, output) capture activations, feature extraction, checks for NaN
module.register_forward_pre_hook(fn) before forward (module, inputs) inspect or change inputs
module.register_full_backward_hook(fn) during backward (module, grad_input, grad_output) gradients flowing out of a layer
tensor.register_hook(fn) when the tensor's gradient is computed grad per-parameter gradient norms, gradient clipping or masking

Each call returns a handle; handle.remove() detaches the hook. A hook that returns a value replaces the output (forward hook) or the gradient (tensor hook), so a reading hook must return None. For monitoring, the number to watch per layer is the gradient norm ∥∇WL∥2=∑ij(∂L/∂Wij)2\lVert \nabla_W L \rVert_2 = \sqrt{\sum_{ij} (\partial L / \partial W_{ij})^2}, and for activations their standard deviation and the fraction of saturated or dead units.

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 10))
x, y = torch.randn(128, 64), torch.randint(0, 10, (128,))

acts = {}
def save_activation(name):
    def hook(module, inputs, output):
        acts[name] = output.detach()              # detach: keep the values, not the graph
    return hook
handles = [model[i].register_forward_hook(save_activation(f"tanh{i}")) for i in (1, 3)]

grad_norms = {}
for name, p in model.named_parameters():
    if name.endswith("weight"):
        p.register_hook(lambda g, name=name: grad_norms.__setitem__(name, g.norm().item()))

loss = nn.functional.cross_entropy(model(x), y)
loss.backward()
for name, a in acts.items():
    print(f"{name}: shape {tuple(a.shape)}  std {a.std().item():.3f}  mean |a| {a.abs().mean().item():.3f}")
for name, g in grad_norms.items():
    print(f"grad norm {name:9s} {g:.4f}  (= p.grad.norm(): {model.get_parameter(name).grad.norm().item():.4f})")
for h in handles:
    h.remove()
acts.clear(); model(x)
print("after remove(): captured", len(acts))

# freezing the first layer
model[0].requires_grad_(False)
trainable = [p for p in model.parameters() if p.requires_grad]
print("trainable tensors", len(trainable), "of", len(list(model.parameters())),
      "| trainable numbers", sum(p.numel() for p in trainable))
opt = torch.optim.SGD(trainable, lr=0.1)
w0 = model[0].weight.clone()
model.zero_grad()
nn.functional.cross_entropy(model(x), y).backward(); opt.step()
print("frozen layer grad:", model[0].weight.grad, "| unchanged:", torch.equal(w0, model[0].weight))

# functional vs module
drop_mod = nn.Dropout(0.5); drop_mod.eval()
z = torch.ones(1000)
print("nn.Dropout in eval keeps all:", drop_mod(z).sum().item())
print("F.dropout with default training=True drops:", (nn.functional.dropout(z, 0.5) == 0).sum().item() > 0)
print("F.dropout(training=False):", nn.functional.dropout(z, 0.5, training=False).sum().item())
tanh1: shape (128, 32)  std 0.467  mean |a| 0.397
tanh3: shape (128, 32)  std 0.253  mean |a| 0.206
grad norm 4.weight  0.1238  (= p.grad.norm(): 0.1238)
grad norm 2.weight  0.1239  (= p.grad.norm(): 0.1239)
grad norm 0.weight  0.1673  (= p.grad.norm(): 0.1673)
after remove(): captured 0
trainable tensors 4 of 6 | trainable numbers 1386
frozen layer grad: None | unchanged: True
nn.Dropout in eval keeps all: 1000.0
F.dropout with default training=True drops: True
F.dropout(training=False): 1000.0

Reading the output:

  • Forward hooks captured both hidden activations, shape (128,32)(128, 32). Their spread shrinks from 0.467 to 0.253 from the first to the second hidden layer: PyTorch's default initialisation is on the small side, a theme of weight initialisation in practice. The hook stores output.detach(), so keeping the activations does not keep the graph alive.
  • Tensor hooks fire in backward order, last layer first (4.weight, then 2.weight, then 0.weight), and the norm they see is exactly p.grad.norm(). With hooks you get the values as they are computed, which matters when you want to log, clip or modify a gradient before it is accumulated into .grad. Debugging a network uses the same pattern to find vanishing gradients.
  • handle.remove() detaches a hook; after it, nothing is captured. Forgotten hooks are a classic memory leak in notebooks.

Freezing parameters

module.requires_grad_(False) sets the flag on every parameter of the module. Autograd then computes no gradient for them, their .grad stays None, and an optimizer step leaves them unchanged, as the output shows: 4 of the 6 parameter tensors remain trainable, 1386 numbers in total (32⋅32+3232 \cdot 32 + 32 plus 32⋅10+1032 \cdot 10 + 10). Pass only the trainable parameters to the optimizer, for two reasons: optimizers with weight decay would otherwise still shrink frozen weights if they ever had a gradient, and Adam allocates state for every parameter it is given. Freezing saves the most when the frozen layers come first: autograd then needs no backward pass through them at all, and keeps fewer activations; partial fine-tuning uses this to train a head on a frozen pretrained body. requires_grad_(False) is not eval(): a frozen batch-norm layer in training mode still updates its running statistics.

torch.nn.functional or a module?

torch.nn.functional (imported as F) holds the stateless functions behind the layers: F.relu, F.cross_entropy, F.dropout, F.conv2d(x, weight). A module wraps such a function together with its parameters, buffers and the training flag.

  • Use modules for anything with parameters or buffers (nn.Linear, nn.BatchNorm1d), and for layers whose behaviour depends on train()/eval() (nn.Dropout). They show up in print(model), can carry hooks and are found by apply.
  • Use functions for stateless operations inside forward (F.relu, F.softmax, F.pad) and for losses.
  • F.dropout does not know the module's mode. Its training argument defaults to True, so the recording shows it dropping units even though nothing is in training mode. Inside a module write F.dropout(x, p, training=self.training), or simply use nn.Dropout.

Pitfalls

  • A plain tensor attribute. Not saved, not moved: use a buffer (or a parameter if it is learned).
  • A hook that returns something. It replaces the output or gradient. Return None from monitoring hooks.
  • Storing activations without detach(). The graph of every batch stays in memory.
  • Not removing hooks in notebooks or after a diagnostic run. Keep the handles.
  • Freezing with requires_grad_(False) but passing all parameters to an optimizer with weight decay or state. Filter them: [p for p in model.parameters() if p.requires_grad].
  • F.dropout without training=self.training. Dropout stays on at evaluation time.
  • var() default. PyTorch's var and std divide by n−1n - 1; normalisation layers divide by nn (unbiased=False).

Practice

  1. Write a ScaledTanh module computing y=atanh⁡(x/a)y = a \tanh(x / a) with a learnable scalar aa initialised to 3. Which tensor type is aa, and what will state_dict() contain?
Answer
python
class ScaledTanh(nn.Module):
    def __init__(self, a=3.0):
        super().__init__()
        self.a = nn.Parameter(torch.tensor(a))
    def forward(self, x):
        return self.a * torch.tanh(x / self.a)

aa is an nn.Parameter; state_dict() has one key, a. The layer behaves like the identity for small ∣x∣\lvert x \rvert and saturates at ±a\pm a ("soft capping", used on attention logits in some language models).

  1. A positional-encoding table of shape (512,64)(512, 64) is computed from a formula in __init__. Parameter, persistent buffer or non-persistent buffer?
Answer

A non-persistent buffer: it must move to the model's device, it is not learned, and it can be recomputed from the formula, so there is no need to store it in every checkpoint. (If the table were learned, it would be a parameter.)

  1. With a forward hook, how do you get the 512-dimensional features before the final fc layer of a torchvision ResNet without changing its code?
Answer

Register a forward hook on model.avgpool (its output has shape (N,512,1,1)(N, 512, 1, 1)) and flatten it, or a forward pre-hook on model.fc, whose input is the flattened (N,512)(N, 512) tensor:

python
feats = {}
h = model.fc.register_forward_pre_hook(lambda m, inp: feats.__setitem__("x", inp[0].detach()))
model.eval()
with torch.no_grad():
    model(images)
h.remove()

Test yourself

Where does a tensor registered with register_buffer("m", t) appear?

  1. In parameters() and state_dict()
  2. In state_dict() and it moves with .to(), but the optimizer does not train it
  3. Only in named_buffers(); it is not saved
  4. Nowhere; buffers are temporary

A shared parameter γj\gamma_j scales feature jj of every row in a batch of NN rows. Its gradient is

  1. the gradient of the first row only
  2. the mean of the rows' outputs
  3. the sum over the NN rows of each row's contribution gnjx^njg_{nj} \hat{x}_{nj}
  4. zero, because it is shared

Why should a forward hook used for logging store output.detach()?

  1. detach makes a deep copy for the GPU
  2. Without it the stored tensor keeps the computation graph alive, wasting memory
  3. Hooks cannot see tensors that require grad
  4. It switches the model to eval mode

Inside a custom module, which call disables dropout correctly at evaluation time?

  1. F.dropout(x, 0.1)
  2. F.dropout(x, 0.1, training=self.training)
  3. F.dropout(x, 0.1, inplace=True)
  4. torch.no_grad() around the call