Building Core Activation and Normalization Layers from Scratch
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Implement five core neural-network building blocks from first principles using only primitive elementwise and reduction operations (maximum, max, sum, mean, exp, sqrt, reshape, and array broadcasting), without calling prebuilt activation or normalization helpers.
In this Python environment, np.ndarray stands in for tensors (axis and keepdims map directly to dim and keepdim in PyTorch). Every function must leave its input arrays unmodified and return output array(s) matching x.shape and x.dtype (accumulating intermediate reductions in at least float32, or float64 when x.dtype == np.float64, so half-precision float16 inputs do not overflow prematurely):
def relu(x: np.ndarray) -> np.ndarray:
def softmax(x: np.ndarray, dim: int = -1) -> np.ndarray:
def layer_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, eps: float = 1e-5) -> np.ndarray:
def batch_norm(
x: np.ndarray,
gamma: np.ndarray,
beta: np.ndarray,
running_mean: np.ndarray,
running_var: np.ndarray,
training: bool,
momentum: float = 0.1,
eps: float = 1e-5,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
def rms_norm(x: np.ndarray, gamma: np.ndarray, eps: float = 1e-6) -> np.ndarray:
relu(x): Return elementwisemax(x, 0)for an arrayxof any rank (including 0-D scalars), keepingNaNentries asNaN.softmax(x, dim=-1): Convert slices along axisdiminto probability distributionsexp(x_i) / sum_j exp(x_j), stabilized per slice so very large positive or negative scores neither overflow nor divide by zero.layer_norm(x, gamma, beta, eps=1e-5): Normalize each slice over the trailingk = gamma.ndimaxes using its mean and biased variance (mean((x - mean)^2)), then apply per-feature scalegammaand shiftbeta:gamma * (x - mean) / sqrt(var + eps) + beta. RaiseValueErrorifgamma.ndim == 0,x.ndim < gamma.ndim, the lastkdimensions ofx.shapediffer fromgamma.shape, orbeta.shape != gamma.shape.batch_norm(x, gamma, beta, running_mean, running_var, training, momentum=0.1, eps=1e-5): Normalize channel axis1across batch axis0and any spatial dimensions2..forxof shape(N, C)or(N, C, H, W, ...). Arraysgamma,beta,running_mean, andrunning_varmust each have shape(C,)(x.ndim < 2or any shape mismatch raisesValueError). Return(y, new_running_mean, new_running_var):training=True: Require at least2elements per channel (M = x.size // C >= 2, otherwise raiseValueError). Standardizexusing each channel's batch mean and biased variance (/ M), and compute updated moving averages via(1 - momentum) * old + momentum * stat, using the batch mean fornew_running_meanand the Bessel-corrected unbiased variance (biased_var * M / (M - 1)) fornew_running_var.training=False: Standardizexusingrunning_meanandrunning_var, and return copies of both running arrays unchanged.
rms_norm(x, gamma, eps=1e-6): Scalexacross its trailinggamma.ndimaxes by its root-mean-square magnitude with no mean subtraction or bias term:(x / sqrt(mean(x^2) + eps)) * gamma. RaiseValueErrorifgamma.ndim == 0,x.ndim < gamma.ndim, or the trailing dimensions ofx.shapediffer fromgamma.shape.
Additionally, be prepared to discuss how to verify correctness for each primitive (reference comparisons, analytical or finite-difference gradient checks, and low-precision or zero-variance edge cases).
Examples
Example 1
Input:
relu(np.array([[-3.5, 0.0, 4.25], [np.nan, -0.5, 1.5]]))
softmax(np.array([500.0, 501.0, 503.0]), dim=-1)
Output:
relu -> [[0.0, 0.0, 4.25], [nan, 0.0, 1.5]]
softmax -> [0.04201007, 0.11419520, 0.84379473]
Walk-through: relu clamps -3.5 and -0.5 to 0.0 while leaving 4.25, 1.5, and NaN untouched. For softmax, subtracting the slice maximum 503.0 shifts the scores to [-3.0, -2.0, 0.0], giving exponentials [0.049787, 0.135335, 1.0] whose sum is 1.185122 — avoiding exp(503) overflow while summing to 1.0.
Example 2
Input:
layer_norm(
x=np.array([[2.0, 4.0, 6.0, 8.0]]),
gamma=np.array([1.0, 2.0, 0.5, 1.0]),
beta=np.array([0.0, 1.0, -0.5, 2.0]),
eps=1e-5,
)
rms_norm(
x=np.array([[6.0, 8.0]]),
gamma=np.array([1.5, 0.5]),
eps=1e-6,
)
Output:
layer_norm -> [[-1.34163944, 0.10557370, -0.27639343, 3.34163944]]
rms_norm -> [[1.27279219, 0.56568542]]
Walk-through: [2, 4, 6, 8] has mean 5.0, centered deviations [-3, -1, 1, 3], and biased variance 20 / 4 = 5.0; dividing by sqrt(5.00001) ≈ 2.236070 gives x_hat ≈ [-1.341639, -0.447213, 0.447213, 1.341639], which is then scaled by gamma and shifted by beta. For rms_norm, mean([36, 64]) = 50.0, rms = sqrt(50.000001) ≈ 7.071068, and (x / rms) * gamma yields [1.272792, 0.565685].
Example 3
Input (training):
batch_norm(
x=np.array([[2.0], [4.0], [6.0], [8.0]]),
gamma=np.array([1.5]),
beta=np.array([-0.5]),
running_mean=np.array([1.0]),
running_var=np.array([2.0]),
training=True,
momentum=0.2,
eps=1e-5,
)
Input (evaluation):
batch_norm(
x=np.array([[1.0], [5.0]]),
gamma=np.array([1.5]),
beta=np.array([-0.5]),
running_mean=np.array([1.0]),
running_var=np.array([4.0]),
training=False,
momentum=0.2,
eps=0.0,
)
Output:
training -> y = [[-2.51245917], [-1.17081972], [0.17081972], [1.51245917]],
new_running_mean = [1.8],
new_running_var = [2.93333333]
evaluation -> y = [[-0.5], [2.5]],
new_running_mean = [1.0],
new_running_var = [4.0]
Walk-through: During training, the M = 4 values in channel 0 have batch_mean = 5.0, biased_var = 5.0 (used to normalize y), and unbiased_var = 5.0 * (4 / 3) = 20 / 3; running stats update to 0.8 * 1.0 + 0.2 * 5.0 = 1.8 and 0.8 * 2.0 + 0.2 * (20 / 3) = 44 / 15 ≈ 2.933333. During evaluation, frozen running_mean = 1.0 and sqrt(4.0) = 2.0 map [1.0, 5.0] to [0.0, 2.0] and then 1.5 * x_hat - 0.5 = [-0.5, 2.5], returning unchanged copies of the running arrays.
Constraints
xis a floating-pointnp.ndarray(float16,float32, orfloat64) containing up to10^6elements.0.0 <= momentum <= 1.0, andeps > 0in general (eps >= 0when variance is strictly positive).- Use only standard library modules and basic NumPy array operations; never mutate input arrays in place.
Step-by-step walkthrough
Understand the five layers, their shapes, and half-precision safety
We are building five foundational neural-network layers using only elementary array operations (
maximum,max,sum,mean,exp,sqrt,reshape, and broadcasting — automatically stretching size-1 axes so arrays of compatible shapes combine elementwise), plus a verification strategy for each:Layer Input & parameter shapes What axes get reduced? ------------- ---------------------------------------------------- ----------------------------------------- relu x: any shape (...) None (purely elementwise) softmax x: any shape (...), integer dim Single axis `dim` (each slice sums to 1) layer_norm x: (..., *S), gamma: S, beta: S Last len(S) axes (each sample by itself) rms_norm x: (..., *S), gamma: S Last len(S) axes (no mean, no beta) batch_norm x: (N, C) or (N, C, H, W, ...), params: (C,) Every axis EXCEPT channel axis 1Because this sandbox runs NumPy rather than PyTorch,
solution.pyimplements the exact tensor math in NumPy, where every call translates line-for-line to PyTorch (axis->dim,keepdims->keepdim,astype->.to), and Step 6 shows the matching PyTorch module code directly.Before writing any layer, handle half-precision (
float16) accumulation.float16uses 5 exponent bits (max finite value65504) and 10 mantissa bits (integers above2048lose unit precision, so2048.0 + 1.0rounds right back to2048.0!). If we computeexp, sums, or squared deviations directly infloat16,1000^2overflows toInfand long sums stall. Just like PyTorch's mixed-precision kernels, we upcastfloat16inputs tofloat32for intermediate reductions and cast the final answer back tox.dtype:def _compute_dtype(x: np.ndarray): """Promote float16 (and float32) reductions to float32 while keeping float64 in float64.""" # float16 overflows above 65504 and loses integer precision past 2048, so reductions # (sums, means, variances, exponentials) must accumulate in at least float32. return np.float64 if x.dtype == np.float64 else np.float32ReLU and numerically stable Softmax (the max-shift trick)
ReLU (Rectified Linear Unit) replaces negative numbers with
0and leaves non-negative numbers unchanged:y = max(x, 0). Usingnp.maximum(x, 0)instead ofx * (x > 0)preservesNaNvalues (NaNin ->NaNout, matchingtorch.reluso upstream bugs are not silently masked as0.0), and wrapping withnp.asarray(..., dtype=x.dtype)keeps even 0-D scalar tensors asndarrays of the original dtype.Softmax converts a vector of raw scores (logits) along
diminto positive probabilities that sum to1:softmax(x)_i = exp(x_i) / sum_j exp(x_j).Evaluating
np.exp(x)directly fails on moderate magnitudes because exponential growth hits floating-point limits fast: -exp(89)overflowsfloat32(> 3.4e38 -> Inf, givingInf / Inf = NaN), andexp(12)already overflowsfloat16(> 65504)! - If every entry is-1000, everyexp(-1000)underflows to0.0, giving0.0 / 0.0 = NaN!To make softmax safe for both extremes, subtract a constant
cfrom every element of the slice before exponentiating. Becauseexp(x_i - c) = exp(x_i) * exp(-c), the factorexp(-c)cancels cleanly from numerator and denominator:exp(x_i - c) / sum_j exp(x_j - c) = [exp(-c) * exp(x_i)] / [exp(-c) * sum_j exp(x_j)] = softmax(x)_iPicking
c = max_j x_jper slice (usingkeepdims=Trueso each slice alongdimsubtracts its own maximum) makes the largest shifted value0.0: 1. Every shifted entry is<= 0.0, soexp(shifted) <= 1.0— overflow is impossible. 2. At least one entry equals0.0, soexp(0.0) = 1.0and the denominator is>= 1.0— division by zero is impossible.Trace along dim=-1 for x = [500.0, 501.0, 503.0]: max_vals = [503.0] shifted = [-3.0, -2.0, 0.0] exp_vals = [0.0498, 0.1353, 1.0000] -> sum_exp = [1.1851] probs = [0.0420, 0.1142, 0.8438] (sums to 1.0, zero overflow!)def relu(x: np.ndarray) -> np.ndarray: """Elementwise max(x, 0) preserving x's shape, dtype, and NaN values.""" # np.maximum propagates NaN (unlike x * (x > 0), which silently turns NaN into 0.0); # np.asarray keeps 0-D inputs as 0-D ndarrays with the exact input dtype. return np.asarray(np.maximum(x, 0), dtype=x.dtype) def softmax(x: np.ndarray, dim: int = -1) -> np.ndarray: """Numerically stable softmax along `dim` using the per-slice max-shift trick.""" xf = x.astype(_compute_dtype(x)) # Subtract each slice's max along `dim` (kept as size-1 axis so it broadcasts). # Now the largest shifted entry is 0.0, so exp(shifted) <= 1.0 (never overflows) # and at least one exp term equals exp(0) = 1.0 (sum >= 1.0, never divides by zero). max_vals = xf.max(axis=dim, keepdims=True) shifted = xf - max_vals exp_vals = np.exp(shifted) sum_exp = exp_vals.sum(axis=dim, keepdims=True) probs = exp_vals / sum_exp return np.asarray(probs, dtype=x.dtype)LayerNorm: per-sample normalization over the last k axes
LayerNorm standardizes each individual sample (or each token embedding in a Transformer) across its trailing
k = gamma.ndimfeature axes so that slice has mean0and variance1, then applies learnable per-feature scalegammaand shiftbeta:y = gamma * (x - mean) / sqrt(var + eps) + betaLet's trace
x = [2.0, 4.0, 6.0, 8.0]withgamma = [1, 2, 0.5, 1],beta = [0, 1, -0.5, 2], andeps = 1e-5:1. mean = (2 + 4 + 6 + 8) / 4 = 5.0 2. centered = x - mean = [-3.0, -1.0, 1.0, 3.0] 3. var = (9 + 1 + 1 + 9) / 4 = 20.0 / 4 = 5.0 (biased variance: divide by 4, NOT 3!) 4. inv_std = 1 / sqrt(5.0 + 0.00001) = 1 / 2.236070 = 0.447213 5. x_hat = centered * inv_std = [-1.3416, -0.4472, 0.4472, 1.3416] 6. out = gamma * x_hat + beta = [-1.3416, 0.1056, -0.2764, 3.3416]Three numerical details separate a bug-free LayerNorm from a fragile one: 1. Biased variance (
/ count, not/ (count - 1)): Normalization layers standardize the exact features present in the vector, so PyTorch divides bycount(whereastorch.vardefaults tocount - 1!). 2. Two-pass variance (mean((x - mean)^2)): Never use the textbook shortcutE[x^2] - E[x]^2! When values sit around a large offset like[20002, 20004, 20006, 20008],E[x^2]andE[x]^2are both~ 4.0020e8; subtracting them infloat32loses all low bits (catastrophic cancellation) and collapses the variance instead of preserving5.0. Subtractingmeanfirst gives[-3.0, -1.0, 1.0, 3.0]cleanly. 3.epsinsidesqrt(var + eps): On a constant input like[9, 9, 9, 9],centered = 0andvar = 0, so0 / sqrt(0 + eps) = 0and the output is cleanlybetainstead of0 / 0 = NaN.def _normalized_axes(x: np.ndarray, gamma: np.ndarray) -> Tuple[int, ...]: """Return the last gamma.ndim axis indices of x after verifying trailing shapes match.""" num_norm_dims = gamma.ndim if num_norm_dims == 0 or x.ndim < num_norm_dims: raise ValueError(f"x.shape {x.shape} must end with gamma.shape {gamma.shape}") trailing_shape = x.shape[x.ndim - num_norm_dims:] if trailing_shape != gamma.shape: raise ValueError(f"x.shape {x.shape} must end with gamma.shape {gamma.shape}") # Example: x.ndim=4, gamma.ndim=2 -> normalize over axes (2, 3) return tuple(range(x.ndim - num_norm_dims, x.ndim)) def layer_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, eps: float = 1e-5) -> np.ndarray: """Normalize over the last gamma.ndim axes, then apply per-feature scale gamma and shift beta.""" axes = _normalized_axes(x, gamma) if beta.shape != gamma.shape: raise ValueError(f"beta.shape {beta.shape} must match gamma.shape {gamma.shape}") xf = x.astype(_compute_dtype(x)) # Two-pass variance avoids catastrophic cancellation from E[x^2] - E[x]^2 on shifted inputs. # PyTorch LayerNorm uses the biased variance (dividing by count, not count - 1). mean = xf.mean(axis=axes, keepdims=True) centered = xf - mean var = (centered * centered).mean(axis=axes, keepdims=True) # Place eps INSIDE sqrt so zero-variance (constant) slices yield 0 / sqrt(eps) = 0, not NaN. inv_std = 1.0 / np.sqrt(var + eps) x_hat = centered * inv_std out = x_hat * gamma + beta return np.asarray(out, dtype=x.dtype)RMSNorm: scaling by root-mean-square without centering
RMSNorm (Root Mean Square Layer Normalization) simplifies LayerNorm by skipping both the mean subtraction and the shift parameter
beta. It dividesxby the square root of its average squared value (root mean square):rms = sqrt(mean(x^2) + eps)y = (x / rms) * gammaComputing one reduction (
mean(x^2)) instead of two (mean(x)thenmean((x - mean)^2)) cuts memory traffic in modern large language models (such as LLaMA). Notice how RMSNorm preserves the input's direction rather than centering it at zero:Trace on x = [6.0, 8.0], gamma = [1.5, 0.5], eps = 1e-6: mean_square = (6^2 + 8^2) / 2 = 100 / 2 = 50.0 rms = sqrt(50.0 + 1e-6) ≈ 7.071068 x / rms = [0.8485, 1.1314] (contrast LayerNorm, which centers [6, 8] to [-1.0, +1.0]!) y = [1.5 * 0.8485, 0.5 * 1.1314] = [1.2728, 0.5657]def rms_norm(x: np.ndarray, gamma: np.ndarray, eps: float = 1e-6) -> np.ndarray: """Root-mean-square normalization over the last gamma.ndim axes (no mean centering or beta).""" axes = _normalized_axes(x, gamma) xf = x.astype(_compute_dtype(x)) # Divide by RMS = sqrt(mean(x^2) + eps), then scale elementwise by gamma. mean_square = (xf * xf).mean(axis=axes, keepdims=True) rms = np.sqrt(mean_square + eps) out = (xf / rms) * gamma return np.asarray(out, dtype=x.dtype)BatchNorm: per-channel batch stats in training, running stats in eval
While LayerNorm normalizes across channels/features within one sample, BatchNorm normalizes each channel
cacross all samples and spatial pixels in the batch:Input x of shape (N, C, H, W): LayerNorm (over C, H, W): 1 mean/var per sample n (shape (N, 1, 1, 1)) BatchNorm (over N, H, W): 1 mean/var per channel c (reduce_axes = (0, 2, 3), reshaped to (1, C, 1, 1))BatchNorm behaves differently during training and inference, and PyTorch uses a very specific convention for its two variances: -
training=True: 1. Each channel poolsM = N * H * Wvalues (M = Nfor 2-D(N, C)inputs). IfM < 2, raiseValueErrorbecause variance across a single number is0and the unbiased variance divides byM - 1 = 0. 2. Normalize the batch usingbatch_meanand the biased variancebiased_var = mean((x - batch_mean)^2)(dividing byM). 3. Update the exponential moving averages (running_mean,running_var) using PyTorch's momentum rulenew = (1 - momentum) * old + momentum * stat, where the variance tracked inrunning_varis the Bessel-corrected unbiased varianceunbiased_var = biased_var * M / (M - 1). -training=False(inference): - Normalize using the frozenrunning_meanandrunning_var(upcast tocompute_dtypeso tinyepsvalues like1e-8never underflow to0.0infloat16), and return copies of the running statistics unchanged. Now each test example's prediction is 100% independent of batch size or other examples in the batch!Trace 1 channel x = [[2], [4], [6], [8]] (N=4, C=1 -> M=4), running_mean=[1], running_var=[2], momentum=0.2: batch_mean = 5.0 biased_var = 5.0 -> used inside (x - 5.0) / sqrt(5.0 + eps) unbiased_var = 5.0 * (4 / 3) = 20/3 -> used to update running_var! new_running_mean = 0.8 * 1.0 + 0.2 * 5.0 = 1.8 new_running_var = 0.8 * 2.0 + 0.2 * (20/3) = 2.9333def batch_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, running_mean: np.ndarray, running_var: np.ndarray, training: bool, momentum: float = 0.1, eps: float = 1e-5) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Batch normalization over channel axis 1 for x of shape (N, C) or (N, C, H, W, ...). Returns (y, new_running_mean, new_running_var) without mutating any input array. """ if x.ndim < 2: raise ValueError("x must have shape (N, C, ...)") channels = x.shape[1] for name, param in (("gamma", gamma), ("beta", beta), ("running_mean", running_mean), ("running_var", running_var)): if param.shape != (channels,): raise ValueError(f"{name}.shape {param.shape} must be ({channels},)") # Reduce over batch axis 0 and all spatial axes 2..ndim-1, leaving one value per channel C. reduce_axes = (0,) + tuple(range(2, x.ndim)) # bcast_shape: (1, C, 1, 1, ...) so a 1-D (C,) vector aligns with channel axis 1 of x. bcast_shape = (1, channels) + (1,) * (x.ndim - 2) compute_dtype = _compute_dtype(x) xf = x.astype(compute_dtype) if training: values_per_channel = x.size // channels # N * H * W (or N for 2-D inputs) if values_per_channel < 2: raise ValueError("training needs at least 2 values per channel") batch_mean = xf.mean(axis=reduce_axes) centered = xf - batch_mean.reshape(bcast_shape) # Forward normalization uses biased variance (divide by M), whereas PyTorch's # running_var tracks the Bessel-corrected unbiased variance (multiply by M / (M - 1)). biased_var = (centered * centered).mean(axis=reduce_axes) unbiased_var = biased_var * (values_per_channel / (values_per_channel - 1)) new_running_mean = (1.0 - momentum) * running_mean + momentum * batch_mean new_running_var = (1.0 - momentum) * running_var + momentum * unbiased_var norm_mean = batch_mean norm_var = biased_var else: # Upcast running stats so small eps (e.g. 1e-8) never underflows to 0 in float16. norm_mean = running_mean.astype(compute_dtype) norm_var = running_var.astype(compute_dtype) new_running_mean = running_mean.copy() new_running_var = running_var.copy() x_hat = (xf - norm_mean.reshape(bcast_shape)) / np.sqrt(norm_var.reshape(bcast_shape) + eps) out = gamma.reshape(bcast_shape) * x_hat + beta.reshape(bcast_shape) return np.asarray(out, dtype=x.dtype), new_running_mean, new_running_varDirect PyTorch translation and autograd subtleties
Translating our NumPy layers into PyTorch is one-to-one, with four PyTorch-specific details worth calling out in an interview: 1.
relugradient at exact0.0:torch.maximum(x, torch.zeros_like(x))splits tie gradients evenly between its two arguments (0.5atx = 0), whereastorch.reludefines the subgradient at0to be0.0. Usingtorch.where(x <= 0, torch.zeros_like(x), x)gives gradient0.0atx = 0and letsNaN(whereNaN <= 0isFalse) pass through asNaN! 2.amaxandvar(..., correction=0):x.max(dim=...)returns(values, indices), whereasx.amax(dim=..., keepdim=True)returns just the tensor of maxima;x.var(dim=..., correction=0)requests the biased variance (1 / N). 3.nn.Parametervsregister_buffer:gammaandbetaare learnablenn.Parameters (optimized by gradient descent), whilerunning_meanandrunning_varare registered buffers (saved instate_dictand moved by.to(device), but ignored by the optimizer). 4. Update running stats underwith torch.no_grad():: updating buffers in-place withoutno_grad()records the update into the autograd graph and leaks memory across steps.import torch def _compute_dtype(x: torch.Tensor) -> torch.dtype: return torch.float64 if x.dtype == torch.float64 else torch.float32 def relu_torch(x: torch.Tensor) -> torch.Tensor: return torch.where(x <= 0, torch.zeros_like(x), x) def softmax_torch(x: torch.Tensor, dim: int = -1) -> torch.Tensor: xf = x.to(_compute_dtype(x)) shifted = xf - xf.amax(dim=dim, keepdim=True) exp_vals = torch.exp(shifted) return (exp_vals / exp_vals.sum(dim=dim, keepdim=True)).to(x.dtype) def layer_norm_torch(x: torch.Tensor, gamma: torch.Tensor, beta: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: dims = tuple(range(x.dim() - gamma.dim(), x.dim())) xf = x.to(_compute_dtype(x)) mean = xf.mean(dim=dims, keepdim=True) var = xf.var(dim=dims, correction=0, keepdim=True) x_hat = (xf - mean) / torch.sqrt(var + eps) return (x_hat * gamma + beta).to(x.dtype) def rms_norm_torch(x: torch.Tensor, gamma: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: dims = tuple(range(x.dim() - gamma.dim(), x.dim())) xf = x.to(_compute_dtype(x)) mean_square = (xf * xf).mean(dim=dims, keepdim=True) return ((xf / torch.sqrt(mean_square + eps)) * gamma).to(x.dtype) class BatchNormTorch(torch.nn.Module): def __init__(self, num_features: int, eps: float = 1e-5, momentum: float = 0.1): super().__init__() self.gamma = torch.nn.Parameter(torch.ones(num_features)) self.beta = torch.nn.Parameter(torch.zeros(num_features)) self.register_buffer("running_mean", torch.zeros(num_features)) self.register_buffer("running_var", torch.ones(num_features)) self.eps = eps self.momentum = momentum def forward(self, x: torch.Tensor) -> torch.Tensor: dims = [0] + list(range(2, x.dim())) bcast_shape = [1, x.shape[1]] + [1] * (x.dim() - 2) xf = x.to(_compute_dtype(x)) if self.training: count = x.numel() // x.shape[1] if count < 2: raise ValueError("training needs at least 2 values per channel") mean = xf.mean(dim=dims) var = xf.var(dim=dims, correction=0) with torch.no_grad(): unbiased_var = var * (count / (count - 1)) self.running_mean.mul_(1.0 - self.momentum).add_(self.momentum * mean) self.running_var.mul_(1.0 - self.momentum).add_(self.momentum * unbiased_var) else: mean = self.running_mean.to(_compute_dtype(x)) var = self.running_var.to(_compute_dtype(x)) x_hat = (xf - mean.view(bcast_shape)) / torch.sqrt(var.view(bcast_shape) + self.eps) out = self.gamma.view(bcast_shape) * x_hat + self.beta.view(bcast_shape) return out.to(x.dtype)How to verify correctness, gradients, and edge cases
Verify every custom neural-network primitive with four complementary layers of tests: 1. Hand-computed small inputs: the exact 2- to 4-element vectors we worked out on paper above, catching formula errors (such as biased vs unbiased variance or swapped momentum). 2. Reference comparison across shapes and dtypes: compare against
F.relu,F.softmax,F.layer_norm,F.batch_norm, andF.rms_norm(or independent scalar-loop references) usingtorch.testing.assert_close. Forfloat16, compare yourfloat16output against afloat64ground truth evaluated on the exact samefloat16-quantized input (atol=2e-3), so sharedfloat16bugs cannot mask each other! 3. Mathematical invariants & stress cases: -relu: non-negative outputs,NaNpreserved, exact0.0subgradient== 0.0. -softmax: non-negative, sums to1.0along every positive/negativedim, shift-invariant (softmax(x + 900) == softmax(x)), survives+-900andfloat16[15, 13, 12]. -layer_norm: withgamma=1, beta=0, non-constant rows have mean~ 0and variance~ 1; constant rows[9, 9, 9, 9]returnbeta; large-offsetfloat32[20002..20008]catchesE[x^2] - E[x]^2cancellation. -batch_norm: training running stats match EMA formulas without mutating pure-function inputs; eval output for sample0is identical whether passed alonex[:1]or inside a batchx;< 2values per channel in training raisesValueError. -rms_norm: all-zero rows return0.0(notNaN); non-zero constant rows stay non-zero (~ gamma). 4. Finite-difference gradient checks (gradcheck): perturb each input entry by+-h(h ~ 1e-6) infloat64(requires_grad=True) and verify(f(x + h) - f(x - h)) / (2h)matches autograd gradients (float32rounding noise is too coarse for finite differences):import torch import torch.nn.functional as F x64 = torch.randn(3, 5, dtype=torch.float64, requires_grad=True) g64 = torch.randn(5, dtype=torch.float64, requires_grad=True) b64 = torch.randn(5, dtype=torch.float64, requires_grad=True) torch.testing.assert_close(layer_norm_torch(x64, g64, b64), F.layer_norm(x64, (5,), g64, b64, eps=1e-5)) assert torch.autograd.gradcheck(layer_norm_torch, (x64, g64, b64)) assert torch.autograd.gradcheck(lambda t: softmax_torch(t, dim=0), (x64,))Complete solution
from typing import Tuple import numpy as np # The sandbox provides NumPy rather than PyTorch, so we implement all five primitives # using only basic array operations (maximum, max, sum, mean, exp, sqrt, reshape, and # broadcasting). Every operation maps 1-to-1 onto PyTorch (axis -> dim, keepdims -> keepdim, # astype -> to). def _compute_dtype(x: np.ndarray): """Promote float16 (and float32) reductions to float32 while keeping float64 in float64.""" # float16 overflows above 65504 and loses integer precision past 2048, so reductions # (sums, means, variances, exponentials) must accumulate in at least float32. return np.float64 if x.dtype == np.float64 else np.float32 def _normalized_axes(x: np.ndarray, gamma: np.ndarray) -> Tuple[int, ...]: """Return the last gamma.ndim axis indices of x after verifying trailing shapes match.""" num_norm_dims = gamma.ndim if num_norm_dims == 0 or x.ndim < num_norm_dims: raise ValueError(f"x.shape {x.shape} must end with gamma.shape {gamma.shape}") trailing_shape = x.shape[x.ndim - num_norm_dims:] if trailing_shape != gamma.shape: raise ValueError(f"x.shape {x.shape} must end with gamma.shape {gamma.shape}") # Example: x.ndim=4, gamma.ndim=2 -> normalize over axes (2, 3) return tuple(range(x.ndim - num_norm_dims, x.ndim)) def relu(x: np.ndarray) -> np.ndarray: """Elementwise max(x, 0) preserving x's shape, dtype, and NaN values.""" # np.maximum propagates NaN (unlike x * (x > 0), which silently turns NaN into 0.0); # np.asarray keeps 0-D inputs as 0-D ndarrays with the exact input dtype. return np.asarray(np.maximum(x, 0), dtype=x.dtype) def softmax(x: np.ndarray, dim: int = -1) -> np.ndarray: """Numerically stable softmax along `dim` using the per-slice max-shift trick.""" xf = x.astype(_compute_dtype(x)) # Subtract each slice's max along `dim` (kept as size-1 axis so it broadcasts). # Now the largest shifted entry is 0.0, so exp(shifted) <= 1.0 (never overflows) # and at least one exp term equals exp(0) = 1.0 (sum >= 1.0, never divides by zero). max_vals = xf.max(axis=dim, keepdims=True) shifted = xf - max_vals exp_vals = np.exp(shifted) sum_exp = exp_vals.sum(axis=dim, keepdims=True) probs = exp_vals / sum_exp return np.asarray(probs, dtype=x.dtype) def layer_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, eps: float = 1e-5) -> np.ndarray: """Normalize over the last gamma.ndim axes, then apply per-feature scale gamma and shift beta.""" axes = _normalized_axes(x, gamma) if beta.shape != gamma.shape: raise ValueError(f"beta.shape {beta.shape} must match gamma.shape {gamma.shape}") xf = x.astype(_compute_dtype(x)) # Two-pass variance avoids catastrophic cancellation from E[x^2] - E[x]^2 on shifted inputs. # PyTorch LayerNorm uses the biased variance (dividing by count, not count - 1). mean = xf.mean(axis=axes, keepdims=True) centered = xf - mean var = (centered * centered).mean(axis=axes, keepdims=True) # Place eps INSIDE sqrt so zero-variance (constant) slices yield 0 / sqrt(eps) = 0, not NaN. inv_std = 1.0 / np.sqrt(var + eps) x_hat = centered * inv_std out = x_hat * gamma + beta return np.asarray(out, dtype=x.dtype) def batch_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, running_mean: np.ndarray, running_var: np.ndarray, training: bool, momentum: float = 0.1, eps: float = 1e-5) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Batch normalization over channel axis 1 for x of shape (N, C) or (N, C, H, W, ...). Returns (y, new_running_mean, new_running_var) without mutating any input array. """ if x.ndim < 2: raise ValueError("x must have shape (N, C, ...)") channels = x.shape[1] for name, param in (("gamma", gamma), ("beta", beta), ("running_mean", running_mean), ("running_var", running_var)): if param.shape != (channels,): raise ValueError(f"{name}.shape {param.shape} must be ({channels},)") # Reduce over batch axis 0 and all spatial axes 2..ndim-1, leaving one value per channel C. reduce_axes = (0,) + tuple(range(2, x.ndim)) # bcast_shape: (1, C, 1, 1, ...) so a 1-D (C,) vector aligns with channel axis 1 of x. bcast_shape = (1, channels) + (1,) * (x.ndim - 2) compute_dtype = _compute_dtype(x) xf = x.astype(compute_dtype) if training: values_per_channel = x.size // channels # N * H * W (or N for 2-D inputs) if values_per_channel < 2: raise ValueError("training needs at least 2 values per channel") batch_mean = xf.mean(axis=reduce_axes) centered = xf - batch_mean.reshape(bcast_shape) # Forward normalization uses biased variance (divide by M), whereas PyTorch's # running_var tracks the Bessel-corrected unbiased variance (multiply by M / (M - 1)). biased_var = (centered * centered).mean(axis=reduce_axes) unbiased_var = biased_var * (values_per_channel / (values_per_channel - 1)) new_running_mean = (1.0 - momentum) * running_mean + momentum * batch_mean new_running_var = (1.0 - momentum) * running_var + momentum * unbiased_var norm_mean = batch_mean norm_var = biased_var else: # Upcast running stats so small eps (e.g. 1e-8) never underflows to 0 in float16. norm_mean = running_mean.astype(compute_dtype) norm_var = running_var.astype(compute_dtype) new_running_mean = running_mean.copy() new_running_var = running_var.copy() x_hat = (xf - norm_mean.reshape(bcast_shape)) / np.sqrt(norm_var.reshape(bcast_shape) + eps) out = gamma.reshape(bcast_shape) * x_hat + beta.reshape(bcast_shape) return np.asarray(out, dtype=x.dtype), new_running_mean, new_running_var def rms_norm(x: np.ndarray, gamma: np.ndarray, eps: float = 1e-6) -> np.ndarray: """Root-mean-square normalization over the last gamma.ndim axes (no mean centering or beta).""" axes = _normalized_axes(x, gamma) xf = x.astype(_compute_dtype(x)) # Divide by RMS = sqrt(mean(x^2) + eps), then scale elementwise by gamma. mean_square = (xf * xf).mean(axis=axes, keepdims=True) rms = np.sqrt(mean_square + eps) out = (xf / rms) * gamma return np.asarray(out, dtype=x.dtype)✅ Submit now — all tests should pass.
Intuition & how it works
Think of these five neural-network primitives as the basic plumbing and automatic gain control (audio volume levelers) inside a deep network: ReLU (Rectified Linear Unit, max(x, 0)) acts as a one-way valve that zeros out negative signals so stacked layers can learn non-linear patterns; Softmax converts a vector of logits (raw, unnormalized scores) into positive probabilities summing to 1.0; and LayerNorm, BatchNorm, and RMSNorm rescale internal activations before they grow too huge or shrink toward zero across dozens of layers — differing only in which axes they average over (within each sample for LayerNorm/RMSNorm vs across the batch per channel for BatchNorm) and whether they subtract the mean (LayerNorm/BatchNorm) or only divide by the root mean square (RMSNorm, the square root of the average squared value).
Why do literal translations of textbook formulas break on real computers? Floating-point numbers have strict range and precision limits: evaluating exp(900) directly in Softmax overflows float64 to Inf (Inf / Inf = NaN), evaluating E[x^2] - E[x]^2 for [20002, 20004, 20006, 20008] in float32 suffers catastrophic cancellation (losing low-order bits when subtracting two nearly equal large numbers) and destroys the variance, and running reductions directly in float16 overflows above 65504 (1002^2 = Inf). Upcasting reductions to float32, subtracting the per-slice maximum before exp, computing two-pass (x - mean)^2, and placing eps inside sqrt(var + eps) eliminate every one of those failures.
Walk through our three concrete sample cases side by side:
1. Softmax on [500, 501, 503]:
Subtract max (503) -> [-3, -2, 0] -> exp = [0.0498, 0.1353, 1.0000], sum = 1.1851
Divide by sum -> [0.0420, 0.1142, 0.8438] (no Inf, sums to 1.0!)
2. LayerNorm vs BatchNorm on 4 numbers [2, 4, 6, 8] (eps = 1e-5):
mean = 5.0, centered = [-3.0, -1.0, 1.0, 3.0], biased var = 20.0 / 4 = 5.0
Normalized x_hat = [-3, -1, 1, 3] / sqrt(5.00001) = [-1.3416, -0.4472, 0.4472, 1.3416]
(In training BatchNorm with running_var=2.0 and momentum=0.2, running_var updates toward
unbiased var = 5.0 * 4/3 = 6.6667 -> 0.8 * 2.0 + 0.2 * 6.6667 = 2.9333.)
3. RMSNorm on [6, 8] (eps = 1e-6, gamma = [1.5, 0.5]):
mean_square = (36 + 64) / 2 = 50.0 -> rms = sqrt(50.000001) = 7.0711
(x / rms) * gamma = [6 / 7.0711 * 1.5, 8 / 7.0711 * 0.5] = [1.2728, 0.5657]
Complexity
Let n be the total number of elements in x (for example N * C * H * W) and C be the number of channels in BatchNorm:
- Time:
O(n)for all five layers, because each primitive scans every element ofxa small constant number of times (one elementwise pass forrelu; one max pass, one exp pass, one sum pass, and one division pass forsoftmax; one or two reduction passes plus an elementwise affine pass forlayer_norm,batch_norm, andrms_norm). - Space:
O(n)auxiliary memory to hold intermediate arrays of the same shape asx(shifted,exp_vals,centered,x_hat), plus smaller summary tensors (O(n / D)for LayerNorm/RMSNorm slice statistics orO(C)for BatchNorm per-channel statistics). - Hardware note (memory bandwidth vs FLOPs): On a GPU, these ops are memory-bound (limited by reading/writing GPU DRAM rather than arithmetic speed). Composing separate eager PyTorch ops reads and writes full tensors to DRAM several times per layer, whereas
torch.compileor fused library kernels (F.layer_norm,F.rms_norm) fuse those passes in fast on-chip SRAM soxis read from DRAM once andyis written once.
Edge cases
- Half-precision (
float16/bfloat16) inputs: Upcasting reductions tofloat32preventsexp(12)and1000^2from overflowingfloat16's65504ceiling, and upcastingrunning_varin eval BatchNorm prevents tinyeps(such as1e-8) from rounding down to0.0infloat16. - Extreme positive or negative logits (
+1000or-1000): Subtracting the per-slice maximum turns[1000, 1001, 1002]and[-1002, -1001, -1000]into[-2, -1, 0], avoiding bothInf / Infand0 / 0. - All-
-infsoftmax slice (e.g., a completely masked attention query):-inf - (-inf)producesNaN, matchingtorch.softmax; attention masks must always keep at least one unmasked token per row. - Zero variance (constant slice
[7, 7, 7, 7]or all zeros): Puttingepsinsidesqrt(var + eps)makes0 / sqrt(eps) = 0, so LayerNorm cleanly returnsbetaand RMSNorm on zeros returns0.0with noNaN. - ReLU behavior at
NaNand atx = 0:np.maximumandtorch.where(x <= 0, 0, x)propagateNaNinstead of hiding it as0.0, andtorch.wheregives subgradient0.0atx = 0.0(matchingtorch.relu, unliketorch.maximumwhich gives0.5). - BatchNorm training with
< 2values per channel ((1, C)or(1, C, 1, 1)): Explicitly raisesValueErrorbecause a 1-element sample has zero variance and Bessel's correctionM / (M - 1)divides by zero. - 0-D scalar inputs and mismatched parameter shapes:
relupreserves 0-Dndarrays, while mismatchedgamma,beta,running_mean, orrunning_varshapes raiseValueErrorinstead of silently broadcasting into wrong answers.
Common mistakes
- Shifting Softmax by the global tensor maximum instead of
max(dim=dim, keepdim=True): On[[0, 1], [1000, 1001]], subtracting the global max1001shifts row0to[-1001, -1000], underflowing both exponentials to0.0and turning row0into0 / 0 = NaN! - Mixing up biased vs unbiased variance: Calling
torch.var(x, dim=...)withoutcorrection=0divides byN - 1instead ofNduring forward normalization, whereas forgetting* M / (M - 1)when updatingrunning_vardisagrees with PyTorch'snn.BatchNorm. - Using
mean(x^2) - mean(x)^2for variance: Fails via catastrophic cancellation on shiftedfloat32inputs like[10000, 10001, 10002, 10003]. - Putting
epsoutside the square root (sqrt(var) + eps): Avoids division by zero, but changes the function and its gradient whenevervaris close toeps. - Reducing BatchNorm over the wrong axes (e.g., reducing only batch axis
0on(N, C, H, W)instead of(0, 2, 3)), or flipping PyTorch'smomentum = 0.1weight (new = 0.9 * old + 0.1 * batch) with TensorFlow/Keras's0.99convention. - Updating
running_mean/running_varoutsidetorch.no_grad(), which attaches persistent state buffers to the autograd graph across training steps, or forgettingmodel.eval()at test time.
Alternative approaches
- Welford's online algorithm: Updates running count, mean, and sum of squared deviations in a single streaming pass with the same numerical stability as two-pass
(x - mean)^2; GPU normalization kernels (cuDNN,F.layer_norm) combine Welford's reduction across threads in registers/shared memory. - Direct
log_softmaxvia log-sum-exp: When feeding cross-entropy loss, computex_shifted - log(sum(exp(x_shifted)))directly instead oflog(softmax(x)), becausesoftmaxcan round a rare class's probability to0.0and turnlog(0.0)into-Inf.
Follow-up questions
- How do you derive the analytical backward pass for LayerNorm and check it numerically without autograd? Let
sigma = sqrt(var + eps),x_hat = (x - mean) / sigma, andg = dy * gamma(the upstream gradient w.r.t.x_hat). Differentiating through the mean and variance constraints projects out both components along each normalized slice of sizeD:dx = (g - mean(g) - x_hat * mean(g * x_hat)) / sigma, whiledgammaanddbetasumdy * x_hatanddyacross all non-normalized batch/token axes. You verifydx, dgamma, dbetainfloat64against central finite differences(f(z + h) - f(z - h)) / (2h)withh = 1e-6, expecting agreement within~ 1e-9:
def layer_norm_backward(x, gamma, dy, eps=1e-5):
"""Manual backward pass for 2-D x, dy of shape (B, D) and gamma of shape (D,)."""
mean = x.mean(axis=-1, keepdims=True)
sigma = np.sqrt(((x - mean) ** 2).mean(axis=-1, keepdims=True) + eps)
x_hat = (x - mean) / sigma
g = dy * gamma
dx = (g - g.mean(axis=-1, keepdims=True) - x_hat * (g * x_hat).mean(axis=-1, keepdims=True)) / sigma
dgamma = (dy * x_hat).sum(axis=0)
dbeta = dy.sum(axis=0)
return dx, dgamma, dbeta
- Why do Transformer architectures favor LayerNorm or RMSNorm over BatchNorm? Sequences have variable lengths with padding tokens that would pollute cross-batch statistics, per-GPU sequence batches in large language models are often tiny (noisy batch variance), and autoregressive token-by-token decoding processes batch size
1or heterogeneous cached prefix lengths where batch statistics make no sense.LayerNormandRMSNormnormalize each token vector independently, so training and inference execute the exact same deterministic function at any batch size. - How can an inference-mode BatchNorm layer be folded into an adjacent Conv2d or Linear layer? At inference (
training=False),running_mean(mu) andrunning_var(v) are constants, soy = gamma * (W * x + b - mu) / sqrt(v + eps) + betais purely linear inx! Definingscale = gamma / sqrt(v + eps), you multiply each output channelcof the convolution weight byscale[c](W_fused[c] = scale[c] * W[c]) and setb_fused[c] = scale[c] * (b[c] - mu[c]) + beta[c], eliminating the BatchNorm memory read/write pass completely at serving time.
Follow-up questions
- How do you derive the analytical backward pass for LayerNorm and check it numerically without autograd?
- Why do Transformer architectures favor LayerNorm or RMSNorm over BatchNorm?
- How can an inference-mode BatchNorm layer be folded into an adjacent Conv2d or Linear layer?
Similar questions
- Diagnosing and Scaling PyTorch Model Training
- Autoregressive Transformer Serving with KV Caching
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance