Custom Layers and Functions

Dive into Deep Learning · §5.4

Custom Layers and Functions
stateless modules · RMSNorm · fixed-buffer RandomFeatures · custom backward & Straight-Through Estimator

Why Every Practitioner Must Extend the Library

Beyond Built-In Primitives

  • Lag between research and libraries: RMSNorm was published in 2019 and used across Llama and Gopher, yet reached some major libraries only years later.
  • First-class composability: Custom layers must expose learnable weights to optimizers, serialize buffers into checkpoints, and move across devices automatically.
  • Non-differentiable forward ops: 4-bit weight quantization \text{round}(w) has zero derivative almost everywhere, requiring a custom surrogate backward pass.

Stateless Custom Layers: Subclassing the Base Module

Layers Without Parameters

  • A layer with no persistent state (CenteredLayer) only needs to subclass the base module and define its forward pass:
class CenteredLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        return X - X.mean()
layer = CenteredLayer()
layer(torch.tensor([1.0, 2, 3, 4, 5]))
tensor([-2., -1.,  0.,  1.,  2.])

Stateless Layers Compose Inside Sequential Containers

Container Integration

  • Because CenteredLayer inherits the module interface, it slots directly into sequential pipelines (|output.mean()| ≲ 10⁻⁸):
net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
Y = net(torch.rand(4, 8))
Y.mean()
tensor(2.5611e-09, grad_fn=<MeanBackward0>)

RMSNorm: Root-Mean-Square Layer Normalization

Parameterized Custom Layers

\text{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}} \odot \mathbf{g}

  • Scale invariance: Maps both (3, 4) and (300, 400) to (0.849, 1.131) when \mathbf{g} = \mathbf{1}.
  • Streamlined LayerNorm: Omits mean-centering and bias shifting across all 65 normalization sites in Llama 3 8B.

Geometric View of RMSNorm in Two Dimensions

Direction Preservation & Axis Scaling

  • Projection onto a sphere: Dividing by \text{RMS}(\mathbf{x}) = \|\mathbf{x}\|_2 / \sqrt{d} projects every ray from the origin onto the sphere of radius \sqrt{d} (left), after which \mathbf{g} stretches the sphere into an axis-aligned ellipsoid (right).

Implementing RMSNorm by Registering the Gain Parameter

RMSNorm in Code

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 / rms
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>)

Registration Guarantees End-to-End Composability

Verifying Optimization & Serialization

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))
  • One SGD step moves gain off ones; a clone loaded from the saved state reproduces the outputs bit for bit:
(tensor([0.9681, 0.9702, 0.9415, 0.7670, 1.0491, 0.9845, 0.9079, 0.9954]),
 True)

Verifying a Custom Layer Against a Native Implementation

Numerical Sanity Check

  • Test custom layers against the framework’s native version using non-trivial weights (linspace(0.5, 1.5, 8)):
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

Layers With Fixed State: Random Fourier Features

Non-Trainable Buffers in Custom Layers

\mathbf{Z} = \sqrt{\frac{2}{D}}\, \cos(\mathbf{X}\mathbf{W} + \mathbf{b})

  • Kernel approximation (Rahimi & Recht, 2007): Fixed \mathbf{W} \sim \mathcal{N}(0, 1) and \mathbf{b} \sim \mathcal{U}(0, 2\pi) approximate the Gaussian RBF kernel so a linear head can fit nonlinear targets.
  • Why \mathbf{W}, \mathbf{b} must be buffers: The optimizer must never alter them, yet checkpoints must save them.

Implementing RandomFeatures With Registered Buffers

Buffers in Code

We register W and b as non-trainable 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)

Fitting sin(3x) With 500 Fixed Random Features

Linear Regression on Nonlinear Features

Stacking a single trainable linear layer (500 -> 1) on top of RandomFeatures(1, 500) fits y = \sin(3x) to an MSE below 0.01 while Adam leaves the random projection buffers untouched:

mean squared error 0.00054

Pitfall: Saving Only the Linear Head Destroys the Fit

Why Buffers Must Be Checkpointed

  • Reloading only the linear head into a fresh RandomFeatures layer (with different random \mathbf{W}', \mathbf{b}') is more than 100\times worse, whereas loading the full state restores the trained fit:
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

When True Derivatives Fail: Quantization and Rounding

The Zero-Gradient Obstacle

  • Because \text{round}(w) is a step function, its true derivative is zero everywhere except at half-integers, freezing weights behind rounding:
w = torch.tensor([0.9, 1.4, 2.6], requires_grad=True)
w.round().sum().backward()
w.grad
tensor([0., 0., 0.])

The Straight-Through Estimator (STE)

Surrogate Backward Passes

The Straight-Through Estimator (Bengio et al., 2013) decouples the forward and backward passes:

  • Forward pass (discrete): Evaluates the exact quantized staircase y = \text{round}(x).
  • Backward pass (identity surrogate): Replaces the zero derivative with the derivative of the identity map (\frac{\partial y}{\partial x} \gets 1), passing upstream gradients through unchanged: \nabla_{\mathbf{x}} L \gets \nabla_{\mathbf{y}} L

Defining a Custom Backward Function

Custom Autograd Primitives

When the backward rule differs from the derivative of the forward pass, we define both directions explicitly:

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_output
w.grad = None
y = (RoundSTE.apply(w) * torch.tensor([1.0, 2.0, 3.0])).sum()
y.backward()
w.grad
tensor([1., 2., 3.])

Training Quantized Weights With the STE

Quantization-Aware Optimization

Fitting an 8-weight linear model whose weights are rounded to integers on every forward pass (w_true uniform on [-7, 7]) shows that STE drives the loss down to within a small factor of the quantization floor while plain rounding stays stuck at step 0:

start 82.9, rounding 82.9, straight-through 1.04, rounded target 0.557
  • The stop-gradient one-liner: For an identity surrogate, writing X + stop_gradient(round(X) - X) evaluates to round(X) forward and differentiates through X backward without a custom class.

The Stop-Gradient Shortcut for Identity Surrogates

One-Line STE Implementation

  • We verify that X + stop_gradient(round(X) - X) matches our custom RoundSTE function in both forward outputs and backward gradients:
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)

Concept Check: Custom Layers & Surrogate Gradients

Concept Check

Answer these three design questions:

  1. In Llama 3 8B (32 blocks, hidden width d = 4096), each block has two RMSNorm layers plus one final RMSNorm before the output head. How many total parameters belong to RMSNorm gains, and what fraction of the 8B model do they represent?
  2. If you store the random matrix W as a plain attribute on RandomFeatures instead of registering it as a buffer, what two failures occur when you save a checkpoint and move the model to a GPU?
  3. Under straight-through rounding round_ste, what is the gradient of L(\mathbf{w}) = \sum_i (\text{round\_ste}(w_i))^2 at \mathbf{w} = (0.9, 1.4, 2.6)?

Answers:

  1. 65 \times 4096 = 266{,}240 parameters (\approx 0.0033\% of 8B): Tiny in memory footprint, yet critical for stabilizing every residual branch.
  2. Checkpoint corruption & GPU crash: W is omitted from the saved state (reloaded models draw a mismatched basis) and stays on the CPU when the model moves to the GPU.
  3. \nabla_{\mathbf{w}} L = 2\,\text{round}(\mathbf{w}) = (2, 2, 6): The outer square uses the forward rounded values (1, 1, 3), while STE replaces \text{round}'(w_i) = 0 with 1.

Summary: Custom Layers and Functions

Key Takeaways

  • Stateless & parameterized layers: Subclass Module (CenteredLayer) and register learnable weights as Parameter (RMSNorm).
  • Fixed-state buffers: Register non-trainable tensors as buffers (RandomFeatures) so they save in checkpoints and move to GPUs.
  • Surrogate gradients: Implement custom VJPs (RoundSTE) or the one-liner X + stop_gradient(f(X) - X) to train through discrete operations.