5.4 Custom Layers and Functions
A deep learning framework's built-in library covers the standard layers everyone needed yesterday: linear projections, activation functions, dropout. Research moves faster than release cycles, however, and a newly proposed layer can take years to appear in official libraries. RMSNorm, a normalization layer that rescales each activation vector to unit root-mean-square magnitude, is a case in point: published in 2019 (Zhang and Sennrich, 2019), it took years to reach the standard layer libraries. Until then, every codebase that wanted RMSNorm either implemented it by hand or imported a third-party version. To behave like a first-class built-in layer, any custom layer we write must plug seamlessly into the framework: its parameters must reach the optimizer, its state must serialize into checkpoints and migrate onto GPUs, and it must slot into sequential and custom containers alongside built-in layers.
Sometimes the obstacle is not the forward operation at all, but its derivative. To squeeze an 8-billion-parameter model (Section 5.1) into tight memory, practitioners often quantize weights down to 4-bit integers, cutting storage to just 4 GB (a quarter of 16-bit floating point). Quantizing a finished model needs no gradients. Training with quantized weights in the forward pass does, and there the rounding is in the way: it has derivative zero almost everywhere, so any weight quantized inside the forward pass receives zero gradient and stops learning.
In this section, we build both kinds of extensions. Because every framework
operation (optimization, checkpointing, and device movement) walks registered
state in the module tree (Section 5.1), subclassing the
base module and registering our tensors is all it takes for a custom layer to
participate automatically. We progress through four concrete examples: a
stateless layer, RMSNorm with a learned parameter, a random-features layer
holding fixed non-trainable buffers, and a custom backward pass (the
straight-through estimator) that lets gradients flow through rounding.
5.4.1 Layers without Parameters#
We start with the simplest possible custom layer: one that holds no state at
all. CenteredLayer subtracts the global mean from its input tensor. To build it,
we subclass the framework's base module and implement only the forward pass.
class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, X):
return X - X.mean()The vector [1, 2, 3, 4, 5] has mean 3, so CenteredLayer shifts it to run
from to :
layer = CenteredLayer()
layer(torch.tensor([1.0, 2, 3, 4, 5]))tensor([-2., -1., 0., 1., 2.])
Because CenteredLayer shares the exact same module interface as built-in
layers, we can drop it directly into a sequential container after a linear layer
to center its outputs. The resulting mean should vanish; in floating-point
arithmetic, seeing a tiny residual around or smaller is ordinary
rounding error rather than a bug.
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
Y = net(torch.rand(4, 8))
Y.mean()tensor(2.5611e-09, grad_fn=<MeanBackward0>)
5.4.2 Layers with Parameters#
In Section 4.4, we saw how activation scales can drift across depth depending on layer weights. A normalization layer removes that sensitivity by rescaling each activation vector to a controlled magnitude and giving the network a learned scale parameter to adjust it instead. We explore this family in depth starting in Section 7.3; here, we implement its cleanest member, RMSNorm.
5.4.2.1 RMSNorm#
Given an input vector with root mean square , RMSNorm divides by its RMS and scales the result elementwise by a learned gain vector :
A small constant (such as ) guards against division by zero. With initialized to , the output always has root mean square close to 1 regardless of the input's scale. For example, for , the mean square is and the RMS is , yielding , and rescaling the input to produces the exact same output. Geometrically (Figure 5.4.1), RMSNorm preserves the direction of while projecting it onto the sphere of radius , after which stretches each coordinate axis.
RMSNorm in two dimensions. Left: with gain 1, every input (blue) moves along its ray from the origin onto the circle of radius (orange); two inputs on the same ray, at lengths 0.6 and 2.9, land on the same point. Right: the gain stretches the circle into an ellipse with semi-axes and .
RMSNorm streamlines layer normalization (Ba et al., 2016), which
additionally subtracts each example's mean (like a per-row CenteredLayer) and
adds a learned bias after rescaling. Zhang and Sennrich showed that dropping
mean-centering rarely hurts performance while cutting computation, which is why
many modern language models, including Llama 3 8B
(Grattafiori et al., 2024) (Section 5.1), adopt
RMSNorm throughout.
Because must be trained, the layer registers it as a parameter (Section 5.2); the rest of the implementation mirrors the formula directly.
In PyTorch, assigning a tensor wrapped in nn.Parameter to an attribute
registers it.
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-6):
super().__init__()
self.gain = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, X):
rms = X.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
return self.gain * X / rmsWe test RMSNorm on and on the 100-fold rescaled vector
; both rows should map to :
norm = RMSNorm(2)
norm(torch.tensor([[3.0, 4.0], [300.0, 400.0]]))tensor([[0.8485, 1.1314],
[0.8485, 1.1314]], grad_fn=<DivBackward0>)
5.4.2.2 Registration#
Why wrap RMSNorm inside a module subclass rather than calling a plain function
with a standalone gain tensor? Because module registration automatically grants
our custom layer all four capabilities of built-in layers: parameter discovery
by optimizers, composability inside containers, checkpoint serialization, and
device migration (Section 5.1, Section 5.2).
We verify this end to end by sandwiching RMSNorm between two linear layers,
taking one gradient step so the gain moves off ones, and copying the full state
into a freshly initialized clone, after which both models should produce
identical outputs (Section 5.6 extends this to disk checkpoints).
net = nn.Sequential(nn.Linear(20, 8), RMSNorm(8), nn.Linear(8, 2))
X = torch.randn(4, 20)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
net(X).pow(2).sum().backward()
optimizer.step()
clone = nn.Sequential(nn.Linear(20, 8), RMSNorm(8), nn.Linear(8, 2))
clone.load_state_dict(net.state_dict())
net[1].gain.data, torch.equal(net(X), clone(X))(tensor([0.9681, 0.9702, 0.9415, 0.7670, 1.0491, 0.9845, 0.9079, 0.9954]),
True)
Sure enough, the gain updates away from ones and the clone matches the trained
model bit for bit, with zero boilerplate inside RMSNorm beyond registering
self.gain.
5.4.2.3 Comparison with Framework Implementations#
Passing the integration checks proves our layer plugs into the framework properly, not that its math is bug-free. Whenever a library offers a native equivalent, testing our custom implementation against it with non-trivial weights provides an immediate numerical sanity check.
We set a non-trivial gain (linspace(0.5, 1.5, 8)) on both our custom RMSNorm and the native nn.RMSNorm and verify that their outputs match:
ours, native = RMSNorm(8), nn.RMSNorm(8, eps=1e-6)
with torch.no_grad():
ours.gain.copy_(torch.linspace(0.5, 1.5, 8))
native.weight.copy_(ours.gain)
X = torch.randn(16, 8)
torch.allclose(ours(X), native(X))True
Whenever a built-in library layer matches your specification, prefer it in production for maintenance and fused-kernel speed; write custom layers for novel operations or modifications the library lacks.
5.4.3 Layers with Fixed State#
Some layers depend on arrays that are neither learned by gradient descent nor recomputed from scratch on every call: they are generated once at construction and must remain fixed for the lifetime of the model. A classic example is a random features layer (Rahimi and Recht, 2007), which projects a minibatch through a fixed standard-normal matrix , shifts by random phases drawn uniformly from , and applies cosine elementwise:
Each row of provides fixed nonlinear features—remarkably, even without ever updating or , a single trainable linear layer placed on top can approximate rich nonlinear functions.
Just like the running statistics in Standardizer (Section 5.2.1.2),
and must stay fixed during optimization yet travel
with the model in checkpoints and across devices. We therefore register them as
buffers:
class RandomFeatures(nn.Module):
def __init__(self, d, num_features):
super().__init__()
self.register_buffer('W', torch.randn(d, num_features))
self.register_buffer('b', 2 * torch.pi * torch.rand(num_features))
def forward(self, X):
return (2 / self.b.numel()) ** 0.5 * torch.cos(X @ self.W + self.b)We now put RandomFeatures to work by fitting across 100 evenly
spaced points in using 500 random features feeding a single linear
layer trained with Adam. Because and are registered as
buffers rather than parameters, handing the whole model to the optimizer updates
only the linear head:
x = torch.linspace(-2, 2, 100)
X, y = x.reshape(-1, 1), torch.sin(3 * x)
def mse(net, X, y):
return ((net(X)[:, 0] - y) ** 2).mean()
net = nn.Sequential(RandomFeatures(1, 500), nn.Linear(500, 1))
optimizer = torch.optim.Adam(net.parameters(), lr=0.05)
for _ in range(500):
optimizer.zero_grad()
mse(net, X, y).backward()
optimizer.step()
print(f'mean squared error {mse(net, X, y):.2g}')
d2l.plot(x, [y, net(X)[:, 0].detach()], 'x', 'y',
legend=['sin(3x)', 'fit'], figsize=(4.5, 2.5))mean squared error 0.00054
The learned combination tracks closely, driving the mean squared error below 0.01 (compared with 0.5 for a constant zero baseline).
Now watch what happens if a checkpoint saves only the trained linear head: a freshly instantiated model draws a completely different and , feeding the linear layer features it has never seen. Below we compare restoring just the linear head against restoring the full state, buffers included:
fresh = nn.Sequential(RandomFeatures(1, 500), nn.Linear(500, 1))
fresh[1].load_state_dict(net[1].state_dict())
print(f'linear layer only: mean squared error {mse(fresh, X, y):.2g}')
fresh.load_state_dict(net.state_dict())
print(f'full state: mean squared error {mse(fresh, X, y):.2g}')linear layer only: mean squared error 0.96
full state: mean squared error 0.00054
Loading only the linear weights causes the MSE to explode by more than two orders of magnitude (no better than predicting zero), whereas restoring the full state including the buffers recovers the trained fit exactly.
This exact same buffer mechanism stores non-trainable tables and running statistics across later chapters, such as the running mean and variance of batch normalization (Section 7.3).
5.4.4 Functions with Custom Gradients#
Up to now we have written forward passes and trusted automatic differentiation to supply the backward pass. Autograd differentiates every operation faithfully, which is occasionally the very thing that gets in our way. Return to the 4-bit quantization example from the opening: rounding weights to integers in the forward pass is piecewise constant, so its true derivative is zero almost everywhere—leaving every weight behind a rounding step with zero gradient:
w = torch.tensor([0.9, 1.4, 2.6], requires_grad=True)
w.round().sum().backward()
w.gradtensor([0., 0., 0.])
Mathematically, a zero gradient is exact; practically, it halts learning dead in its tracks. The straight-through estimator (STE) (Bengio et al., 2013) sidesteps this by decoupling the two directions: the forward pass still rounds to integers, while the backward pass pretends rounding were the identity function and passes the upstream gradient through unchanged (derivative 1). Although deliberately not the true derivative, it works well in practice because the staircase never deviates by more than from the identity (Figure 5.4.2). Since autograd cannot invent a surrogate derivative that differs from the forward function, we supply the backward rule explicitly.
The straight-through estimator. Forward: the staircase round(x) stays close to the identity (dashed). Backward: the true derivative of rounding is zero almost everywhere; the estimator uses the derivative of the identity, 1, instead.
In PyTorch the tool is a subclass of torch.autograd.Function with the two
directions as static methods:
class RoundSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, X):
return X.round()
@staticmethod
def backward(ctx, grad_output):
# Treat the forward pass as the identity: pass the gradient on
return grad_outputAlways invoke RoundSTE.apply(X) (calling forward directly bypasses autograd registration); if backward needs forward tensors, save them via ctx.save_for_backward.
We verify our custom backward rule by multiplying the rounded weights by and summing: the straight-through estimator should deliver directly as the gradient with respect to :
w.grad = None
y = (RoundSTE.apply(w) * torch.tensor([1.0, 2.0, 3.0])).sum()
y.backward()
w.gradtensor([1., 2., 3.])
The gradient passes straight back to as if rounding were the identity, while the forward pass still operates on integer-rounded weights. Can gradient descent actually learn through this surrogate? Below we fit an eight-weight linear model whose weights are rounded to integers during the forward pass on synthetic data generated by weights drawn uniformly from (the symmetric part of the 4-bit signed range ). Starting from , we compare plain rounding against the straight-through estimator, alongside the initial loss and the loss of the rounded true weights, a reference point (rounding each weight separately is not the best integer fit):
X = torch.randn(256, 8)
w_true = torch.empty(8).uniform_(-7, 7)
y = X @ w_true
def fit(rnd, X, y, num_steps=100, lr=0.05):
w = torch.zeros(8, requires_grad=True)
optimizer = torch.optim.SGD([w], lr=lr)
for _ in range(num_steps):
loss = ((X @ rnd(w) - y) ** 2).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.item()
print(f'start {(y ** 2).mean():.3g}, '
f'rounding {fit(torch.round, X, y):.3g}, '
f'straight-through {fit(RoundSTE.apply, X, y):.3g}, '
f'rounded target {((X @ w_true.round() - y) ** 2).mean():.3g}')start 82.9, rounding 82.9, straight-through 1.04, rounded target 0.557
With plain rounding, every gradient is zero and the loss never budges from its starting value. With the straight-through estimator, the loss plunges from tens or hundreds down to 1 or 2, within a small factor of the loss of the rounded ground-truth weights. A deliberately approximate surrogate gradient successfully trains a quantized model.
The identity is just one possible surrogate. A full 4-bit quantizer also clamps its inputs to , so practical implementations often pass gradients only inside the representable range and zero them out in the saturated exterior (see the exercises). Choosing the right surrogate is a modeling decision tailored to the operation it approximates.
When the surrogate is the identity, there is an elegant one-line trick that avoids writing a custom autograd function altogether, and it is what you will most often encounter in production code. Using a stop-gradient operator (which acts as the identity in the forward pass and has zero derivative in the backward pass), writing evaluates to forward while differentiating solely through the leading backward. We still need the full custom-backward mechanism for non-identity surrogates like clipped quantizers, but for plain straight-through rounding, both definitions match identically in values and gradients:
In PyTorch the stop-gradient operation is the method detach(), which
returns a tensor with the same values that autograd treats as a constant.
def round_ste2(X):
return X + (X.round() - X).detach()
def grad_of(f):
w.grad = None
(f(w) * torch.tensor([1.0, 2.0, 3.0])).sum().backward()
return w.grad
(torch.allclose(RoundSTE.apply(w), round_ste2(w)),
torch.allclose(grad_of(RoundSTE.apply), grad_of(round_ste2)))(True, True)
A backward rule written by hand can be wrong, and nothing in the forward pass will show it. The standard test is a gradient check: perturb each input by a small amount, measure how much the output changes, and compare this finite-difference slope with the gradient that the rule returns. Below we check a smooth built-in function and our straight-through rule:
def check(f):
x = torch.tensor([0.9, 1.4, 2.6], dtype=torch.float64, requires_grad=True)
return torch.autograd.gradcheck(f, (x,), raise_exception=False)
check(torch.tanh), check(RoundSTE.apply)(True, False)
The built-in function passes and the straight-through estimator fails. This failure is by design. The forward pass is a staircase, whose slope is zero wherever a finite difference can measure it, while our backward rule reports a slope of one. A gradient check therefore tells us whether a rule is the derivative of its forward pass, not whether the rule is useful. Run it on every rule that is meant to be exact, such as the clamp in the exercises.
Keep in mind that a custom gradient overrides the derivative of an expression built from existing tensor primitives; writing custom GPU kernels from scratch is a separate systems discipline outside our scope, though Chapter 13 covers how to maximize speed using the primitives frameworks already supply.
One vital question remains about layers like RMSNorm: is their floating-point
arithmetic actually safe? Squaring activations and summing them can easily
overflow in 16-bit formats. In Section 5.5, we examine numerical
formats and mixed-precision training directly.
5.4.5 Summary#
A custom layer is simply a subclass of the framework's base module implementing
a forward pass; registering its tensors handles optimization, containers,
checkpointing, and device placement automatically. Learned weights are
registered as parameters (as with the gain of RMSNorm), while fixed
non-trainable tensors (such as the random projections in RandomFeatures) are
registered as buffers so checkpoints preserve them without exposing them to the
optimizer. When an operation's true derivative is uninformative—such as
rounding—a custom backward rule like the straight-through estimator (or its
stop-gradient shortcut) lets training proceed. Whenever a built-in library layer
matches your specification, prefer it for maintenance and fused-kernel speed.
5.4.6 Exercises#
- [code] Scale invariance of RMSNorm. ● Set .
- Show that for every .
- Differentiate both sides with respect to at and conclude that the Jacobian of RMSNorm at satisfies .
- Conclude that the gradient of any loss with respect to the input of RMSNorm is orthogonal to , and check this with automatic differentiation for a random and a random linear loss. What does a small gradient step do to the length of ?
- [code] RMSNorm bias. Add an optional learned bias to
RMSNorm(a shift applied after the gain, restoring part of what layer normalization had), and verify that the state dict of a model containing it grows by the expected entry. Then place the layer directly before a linear layer with weight and bias , and show that can be folded into without changing the outputs. What is the folded bias?
-
[code] Random features approximate a kernel. Let have independent standard normal entries and be uniform on .
- Using
and ,
show that the features of
RandomFeaturessatisfy for every number of features. - Check this numerically for two inputs at distance 1, with , 100, 1,000, and 10,000, averaging the error over several layers for each . How does the error shrink as grows?
- Repeat the fit of from this section with and features, and with a linear model on alone in place of the random features. What error does each reach, and why?
Adapted from (Rahimi and Recht, 2007).
- Using
and ,
show that the features of
-
[code] A clamp with a custom gradient. Implement an
autograd.Functionwhose forward isX.clamp(lo, hi)and whose backward passes the gradient only where the input lay strictly inside the clamp range. Compare its gradients with those of the nativetorch.clampfor inputs inside, outside, and exactly on the boundary. Which convention does the native operation use at the boundary?Adapted from the PyTorch tutorial Learning PyTorch with Examples and the JAX notebook Custom derivative rules.