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:
  1. relu(x): Return elementwise max(x, 0) for an array x of any rank (including 0-D scalars), keeping NaN entries as NaN.
  2. softmax(x, dim=-1): Convert slices along axis dim into probability distributions exp(x_i) / sum_j exp(x_j), stabilized per slice so very large positive or negative scores neither overflow nor divide by zero.
  3. layer_norm(x, gamma, beta, eps=1e-5): Normalize each slice over the trailing k = gamma.ndim axes using its mean and biased variance (mean((x - mean)^2)), then apply per-feature scale gamma and shift beta: gamma * (x - mean) / sqrt(var + eps) + beta. Raise ValueError if gamma.ndim == 0, x.ndim < gamma.ndim, the last k dimensions of x.shape differ from gamma.shape, or beta.shape != gamma.shape.
  4. batch_norm(x, gamma, beta, running_mean, running_var, training, momentum=0.1, eps=1e-5): Normalize channel axis 1 across batch axis 0 and any spatial dimensions 2.. for x of shape (N, C) or (N, C, H, W, ...). Arrays gamma, beta, running_mean, and running_var must each have shape (C,) (x.ndim < 2 or any shape mismatch raises ValueError). Return (y, new_running_mean, new_running_var):
    • training=True: Require at least 2 elements per channel (M = x.size // C >= 2, otherwise raise ValueError). Standardize x using each channel's batch mean and biased variance (/ M), and compute updated moving averages via (1 - momentum) * old + momentum * stat, using the batch mean for new_running_mean and the Bessel-corrected unbiased variance (biased_var * M / (M - 1)) for new_running_var.
    • training=False: Standardize x using running_mean and running_var, and return copies of both running arrays unchanged.
  5. rms_norm(x, gamma, eps=1e-6): Scale x across its trailing gamma.ndim axes by its root-mean-square magnitude with no mean subtraction or bias term: (x / sqrt(mean(x^2) + eps)) * gamma. Raise ValueError if gamma.ndim == 0, x.ndim < gamma.ndim, or the trailing dimensions of x.shape differ from gamma.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

  • x is a floating-point np.ndarray (float16, float32, or float64) containing up to 10^6 elements.
  • 0.0 <= momentum <= 1.0, and eps > 0 in general (eps >= 0 when variance is strictly positive).
  • Use only standard library modules and basic NumPy array operations; never mutate input arrays in place.

Step-by-step walkthrough

  1. 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 1
    

    Because this sandbox runs NumPy rather than PyTorch, solution.py implements 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. float16 uses 5 exponent bits (max finite value 65504) and 10 mantissa bits (integers above 2048 lose unit precision, so 2048.0 + 1.0 rounds right back to 2048.0!). If we compute exp, sums, or squared deviations directly in float16, 1000^2 overflows to Inf and long sums stall. Just like PyTorch's mixed-precision kernels, we upcast float16 inputs to float32 for intermediate reductions and cast the final answer back to x.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.float32
    
  2. ReLU and numerically stable Softmax (the max-shift trick)

    ReLU (Rectified Linear Unit) replaces negative numbers with 0 and leaves non-negative numbers unchanged: y = max(x, 0). Using np.maximum(x, 0) instead of x * (x > 0) preserves NaN values (NaN in -> NaN out, matching torch.relu so upstream bugs are not silently masked as 0.0), and wrapping with np.asarray(..., dtype=x.dtype) keeps even 0-D scalar tensors as ndarrays of the original dtype.

    Softmax converts a vector of raw scores (logits) along dim into positive probabilities that sum to 1: 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) overflows float32 (> 3.4e38 -> Inf, giving Inf / Inf = NaN), and exp(12) already overflows float16 (> 65504)! - If every entry is -1000, every exp(-1000) underflows to 0.0, giving 0.0 / 0.0 = NaN!

    To make softmax safe for both extremes, subtract a constant c from every element of the slice before exponentiating. Because exp(x_i - c) = exp(x_i) * exp(-c), the factor exp(-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)_i
    

    Picking c = max_j x_j per slice (using keepdims=True so each slice along dim subtracts its own maximum) makes the largest shifted value 0.0: 1. Every shifted entry is <= 0.0, so exp(shifted) <= 1.0 — overflow is impossible. 2. At least one entry equals 0.0, so exp(0.0) = 1.0 and 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)
    
  3. 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.ndim feature axes so that slice has mean 0 and variance 1, then applies learnable per-feature scale gamma and shift beta:

    y = gamma * (x - mean) / sqrt(var + eps) + beta

    Let's trace x = [2.0, 4.0, 6.0, 8.0] with gamma = [1, 2, 0.5, 1], beta = [0, 1, -0.5, 2], and eps = 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 by count (whereas torch.var defaults to count - 1!). 2. Two-pass variance (mean((x - mean)^2)): Never use the textbook shortcut E[x^2] - E[x]^2! When values sit around a large offset like [20002, 20004, 20006, 20008], E[x^2] and E[x]^2 are both ~ 4.0020e8; subtracting them in float32 loses all low bits (catastrophic cancellation) and collapses the variance instead of preserving 5.0. Subtracting mean first gives [-3.0, -1.0, 1.0, 3.0] cleanly. 3. eps inside sqrt(var + eps): On a constant input like [9, 9, 9, 9], centered = 0 and var = 0, so 0 / sqrt(0 + eps) = 0 and the output is cleanly beta instead of 0 / 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)
    
  4. 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 divides x by the square root of its average squared value (root mean square):

    rms = sqrt(mean(x^2) + eps) y = (x / rms) * gamma

    Computing one reduction (mean(x^2)) instead of two (mean(x) then mean((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)
    
  5. BatchNorm: per-channel batch stats in training, running stats in eval

    While LayerNorm normalizes across channels/features within one sample, BatchNorm normalizes each channel c across 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 pools M = N * H * W values (M = N for 2-D (N, C) inputs). If M < 2, raise ValueError because variance across a single number is 0 and the unbiased variance divides by M - 1 = 0. 2. Normalize the batch using batch_mean and the biased variance biased_var = mean((x - batch_mean)^2) (dividing by M). 3. Update the exponential moving averages (running_mean, running_var) using PyTorch's momentum rule new = (1 - momentum) * old + momentum * stat, where the variance tracked in running_var is the Bessel-corrected unbiased variance unbiased_var = biased_var * M / (M - 1). - training=False (inference): - Normalize using the frozen running_mean and running_var (upcast to compute_dtype so tiny eps values like 1e-8 never underflow to 0.0 in float16), 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.9333
    
    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
    
  6. Direct 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. relu gradient at exact 0.0: torch.maximum(x, torch.zeros_like(x)) splits tie gradients evenly between its two arguments (0.5 at x = 0), whereas torch.relu defines the subgradient at 0 to be 0.0. Using torch.where(x <= 0, torch.zeros_like(x), x) gives gradient 0.0 at x = 0 and lets NaN (where NaN <= 0 is False) pass through as NaN! 2. amax and var(..., correction=0): x.max(dim=...) returns (values, indices), whereas x.amax(dim=..., keepdim=True) returns just the tensor of maxima; x.var(dim=..., correction=0) requests the biased variance (1 / N). 3. nn.Parameter vs register_buffer: gamma and beta are learnable nn.Parameters (optimized by gradient descent), while running_mean and running_var are registered buffers (saved in state_dict and moved by .to(device), but ignored by the optimizer). 4. Update running stats under with torch.no_grad():: updating buffers in-place without no_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)
    
  7. 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, and F.rms_norm (or independent scalar-loop references) using torch.testing.assert_close. For float16, compare your float16 output against a float64 ground truth evaluated on the exact same float16-quantized input (atol=2e-3), so shared float16 bugs cannot mask each other! 3. Mathematical invariants & stress cases: - relu: non-negative outputs, NaN preserved, exact 0.0 subgradient == 0.0. - softmax: non-negative, sums to 1.0 along every positive/negative dim, shift-invariant (softmax(x + 900) == softmax(x)), survives +-900 and float16 [15, 13, 12]. - layer_norm: with gamma=1, beta=0, non-constant rows have mean ~ 0 and variance ~ 1; constant rows [9, 9, 9, 9] return beta; large-offset float32 [20002..20008] catches E[x^2] - E[x]^2 cancellation. - batch_norm: training running stats match EMA formulas without mutating pure-function inputs; eval output for sample 0 is identical whether passed alone x[:1] or inside a batch x; < 2 values per channel in training raises ValueError. - rms_norm: all-zero rows return 0.0 (not NaN); non-zero constant rows stay non-zero (~ gamma). 4. Finite-difference gradient checks (gradcheck): perturb each input entry by +-h (h ~ 1e-6) in float64 (requires_grad=True) and verify (f(x + h) - f(x - h)) / (2h) matches autograd gradients (float32 rounding 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,))
    
  8. 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 of x a small constant number of times (one elementwise pass for relu; one max pass, one exp pass, one sum pass, and one division pass for softmax; one or two reduction passes plus an elementwise affine pass for layer_norm, batch_norm, and rms_norm).
  • Space: O(n) auxiliary memory to hold intermediate arrays of the same shape as x (shifted, exp_vals, centered, x_hat), plus smaller summary tensors (O(n / D) for LayerNorm/RMSNorm slice statistics or O(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.compile or fused library kernels (F.layer_norm, F.rms_norm) fuse those passes in fast on-chip SRAM so x is read from DRAM once and y is written once.

Edge cases

  • Half-precision (float16 / bfloat16) inputs: Upcasting reductions to float32 prevents exp(12) and 1000^2 from overflowing float16's 65504 ceiling, and upcasting running_var in eval BatchNorm prevents tiny eps (such as 1e-8) from rounding down to 0.0 in float16.
  • Extreme positive or negative logits (+1000 or -1000): Subtracting the per-slice maximum turns [1000, 1001, 1002] and [-1002, -1001, -1000] into [-2, -1, 0], avoiding both Inf / Inf and 0 / 0.
  • All--inf softmax slice (e.g., a completely masked attention query): -inf - (-inf) produces NaN, matching torch.softmax; attention masks must always keep at least one unmasked token per row.
  • Zero variance (constant slice [7, 7, 7, 7] or all zeros): Putting eps inside sqrt(var + eps) makes 0 / sqrt(eps) = 0, so LayerNorm cleanly returns beta and RMSNorm on zeros returns 0.0 with no NaN.
  • ReLU behavior at NaN and at x = 0: np.maximum and torch.where(x <= 0, 0, x) propagate NaN instead of hiding it as 0.0, and torch.where gives subgradient 0.0 at x = 0.0 (matching torch.relu, unlike torch.maximum which gives 0.5).
  • BatchNorm training with < 2 values per channel ((1, C) or (1, C, 1, 1)): Explicitly raises ValueError because a 1-element sample has zero variance and Bessel's correction M / (M - 1) divides by zero.
  • 0-D scalar inputs and mismatched parameter shapes: relu preserves 0-D ndarrays, while mismatched gamma, beta, running_mean, or running_var shapes raise ValueError instead 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 max 1001 shifts row 0 to [-1001, -1000], underflowing both exponentials to 0.0 and turning row 0 into 0 / 0 = NaN!
  • Mixing up biased vs unbiased variance: Calling torch.var(x, dim=...) without correction=0 divides by N - 1 instead of N during forward normalization, whereas forgetting * M / (M - 1) when updating running_var disagrees with PyTorch's nn.BatchNorm.
  • Using mean(x^2) - mean(x)^2 for variance: Fails via catastrophic cancellation on shifted float32 inputs like [10000, 10001, 10002, 10003].
  • Putting eps outside the square root (sqrt(var) + eps): Avoids division by zero, but changes the function and its gradient whenever var is close to eps.
  • Reducing BatchNorm over the wrong axes (e.g., reducing only batch axis 0 on (N, C, H, W) instead of (0, 2, 3)), or flipping PyTorch's momentum = 0.1 weight (new = 0.9 * old + 0.1 * batch) with TensorFlow/Keras's 0.99 convention.
  • Updating running_mean / running_var outside torch.no_grad(), which attaches persistent state buffers to the autograd graph across training steps, or forgetting model.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_softmax via log-sum-exp: When feeding cross-entropy loss, compute x_shifted - log(sum(exp(x_shifted))) directly instead of log(softmax(x)), because softmax can round a rare class's probability to 0.0 and turn log(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, and g = 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 size D: dx = (g - mean(g) - x_hat * mean(g * x_hat)) / sigma, while dgamma and dbeta sum dy * x_hat and dy across all non-normalized batch/token axes. You verify dx, dgamma, dbeta in float64 against central finite differences (f(z + h) - f(z - h)) / (2h) with h = 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 1 or heterogeneous cached prefix lengths where batch statistics make no sense. LayerNorm and RMSNorm normalize 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) and running_var (v) are constants, so y = gamma * (W * x + b - mu) / sqrt(v + eps) + beta is purely linear in x! Defining scale = gamma / sqrt(v + eps), you multiply each output channel c of the convolution weight by scale[c] (W_fused[c] = scale[c] * W[c]) and set b_fused[c] = scale[c] * (b[c] - mu[c]) + beta[c], eliminating the BatchNorm memory read/write pass completely at serving time.

Follow-up questions

Similar questions

More Startups.Com interview questions

All 3 Startups.Com questions →