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()
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 = epsdef forward(self, X): rms = X.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()returnself.gain * X / rms
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
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:
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):@staticmethoddef forward(ctx, X):return X.round()@staticmethoddef backward(ctx, grad_output):# Treat the forward pass as the identity: pass the gradient onreturn grad_output
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:
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:
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?
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?
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:
65 \times 4096 = 266{,}240 parameters (\approx 0.0033\% of 8B): Tiny in memory footprint, yet critical for stabilizing every residual branch.
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.
\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.