DeepSeek: TorchFeather

    Notes while following Umar Jamil's Building a distributed training framework from first principles and working through TorchFeather. I use these notes to explain the implementation to myself as I study it.

    Output Initialization: Why 1/√dim?πŸ”—

    In DeepSeekV3Model.init_weights:

    final_out_std = self.model_args.dim**-0.5
    

    This sets the initial standard deviation of the output layer's weights. The output layer maps \( d = \texttt{dim} \) hidden features to vocabulary logits; final_out_std is not the measured standard deviation of those logits.

    Goal: Preserve the Input VarianceπŸ”—

    For one output logit, write \( y = \sum_{j=1}^{d} w_j x_j \), summing over \( d \) input features. We choose the weight scale so \( \operatorname{Var}(y) \approx \operatorname{Var}(x_j) \): one output should have roughly the variance of one input feature. This is the forward variance-preservation argument behind fan-in initialization; see Glorot and Bengio, Section 4.2.

    Which Variables Are Independent?πŸ”—

    For the simple derivation, assume each input feature is centered with variance \( v \), and the initialized weights are independent of the input and of each other, with mean zero and variance \( \sigma_w^2 \).

    x and y are dependent: y is computed from x. Independence here refers to the randomly initialized weights and the input, not to the input and output.

    For one product, independence lets us factor its second moment, while zero means remove the mean term:

    \[ \operatorname{Var}(w_j x_j) = \mathbb{E}[w_j^2]\,\mathbb{E}[x_j^2] = \sigma_w^2 v \]

    For a sum, variance generally includes covariance terms:

    \[ \begin{aligned} \operatorname{Var}(y) &= \sum_{j=1}^{d} \operatorname{Var}(w_j x_j) \\ &\quad + 2\sum_{j<k} \operatorname{Cov}(w_j x_j,\, w_k x_k) \end{aligned} \]

    The independent, zero-mean weights make those cross-covariances zero at initialization. The input features themselves need not be independent for this cancellation.

    Solve for the Weight Standard DeviationπŸ”—

    There are \( d \) products, so:

    \[ \operatorname{Var}(y) = d\,\sigma_w^2 v \]

    To preserve a nonzero input variance \( v \):

    \[ \begin{aligned} d\,\sigma_w^2 v &= v \\ \sigma_w^2 &= \frac{1}{d} \\ \sigma_w &= \frac{1}{\sqrt{d}} \end{aligned} \]

    The variance is \( 1/d \); the standard deviation passed to the initializer is its square root. For \( d = 4096 \), this gives \( \frac{1}{64} = 0.015625 \). Here \( d \) is the hidden width, not the vocabulary size.

    Connect the Derivation to RMSNormπŸ”—

    TorchFeather applies RMSNorm before the output projection. RMSNorm controls the mean square, without forcing the input mean to zero. Holding that hidden vector \( x \) fixed and varying the initial weights gives:

    \[ \operatorname{Var}_{W}(y\mid x) = \sigma_w^2\sum_{j=1}^{d} x_j^2 \approx \sigma_w^2 d \]

    Thus \( \sigma_w^2 = 1/d \) keeps initial logit variance around 1 even without the centered-input simplification above. The code truncates the normal distribution at \( \pm 3\sigma \), so this is approximate scale control at initialization, not an exact variance constraint enforced throughout training.

    Residual Initialization: Why Scale With Depth?πŸ”—

    The goal is stable training: keep activations and backpropagated gradients at useful scales, reducing the risk of exploding or vanishing signals. The variance argument below explains forward activation growth; gradient stability also depends on the architecture, normalization, and optimizer.

    Each residual branch adds to the running stream. Assuming negligible covariance and variance v per branch, L additions give:

    \[ \operatorname{Var}(x_L)\approx\operatorname{Var}(x_0)+Lv \]

    A transformer has two residual additions per block: attention and FFN. Across L blocks, the added variance is roughly 2Lv. Scaling branch outputs by 1/√(2L) scales their variance by 1/(2L), controlling growth with depth. This is a simplifying initialization argument, not a guarantee throughout training.

    TorchFeather scales the residual output weights using:

    self.weight_init_std = 0.02 / (2 * (layer_id + 1)) ** 0.5
    

    It uses the current block's depth, not total model depth L, so its schedule differs from the constant scale in the argument above. Several internal attention projections keep std=0.02.

    Why 0.02? It is an established base scale: OpenAI's GPT-2 implementation uses w_init_stdev=0.02. That documents precedent, not why TorchFeather chose it. A plausible intuition is that it is on the scale of fan-in initialization for widths of a few thousand: 1/√2500 = 0.02. This numerical comparison does not derive a universal constant or prove the author's rationale.

    Remember: 0.02 sets the base weight scale; the depth factor reduces residual accumulation. Variance scaling explains the factor, not the exact base value.

    MLA Attention: Why Split Q and K into nope and rope?πŸ”—

    Multi-Head Latent Attention (MLA) shrinks the KV cache by compressing each token into a small latent \( c_t^{KV} \) and reconstructing keys via \( k_s = W^{UK} c_s^{KV} \).

    Without RoPE, \( W^{UK} \) can be absorbed into the query side at inference timeβ€”\( q_t^{\mathsf{T}}(W^{UK} c_s^{KV}) = ((W^{UK})^{\mathsf{T}} q_t)^{\mathsf{T}} c_s^{KV} \)β€”so attention dots directly against the cached latent \( c_s^{KV} \) without decompressing past keys (and similarly \( W^{UV} \) absorbs into \( W^O \)). With RoPE, the position-dependent rotation \( R_{s-t} \) sits between \( q_t \) and \( W^{UK} \) (\( q_t^{\mathsf{T}} R_{s-t} W^{UK} c_s^{KV} \)) and does not commute with \( W^{UK} \), blocking absorption.

    DeepSeek therefore splits each query and key into two concatenated slices:

    • Content / nope (\( q_t^C, k_t^C \)): no RoPE applied; \( W^{UK} \) can be absorbed, so only \( c_t^{KV} \) is cached.
    • Rotary / rope (\( q_t^R, k_t^R \)): RoPE applied; cannot be absorbed, so \( k_t^R \) is kept small, shared across heads (like MQA), and cached alongside \( c_t^{KV} \) (while \( q_t^R \) stays per-head).
    \[ \bigl[q_t^C;\, q_t^R\bigr]^{\mathsf{T}}\bigl[k_s^C;\, k_s^R\bigr] = \underbrace{(q_t^C)^{\mathsf{T}} k_s^C}_{\text{nope (absorbed)}} + \underbrace{(q_t^R)^{\mathsf{T}} k_s^R}_{\text{rope (cached)}} \]

    Here "content" (\( C \)) simply means the no-RoPE slice. During training, implementations typically compute the unabsorbed form; matrix absorption is an inference-time optimization.

    Autograd Basics: Chain, Copy, and Add RulesπŸ”—

    • Chain rule (composition): multiply the upstream gradient by the local derivative along a path (\( \frac{\partial L}{\partial x} = \frac{\partial L}{\partial y}\frac{\partial y}{\partial x} \)).
    • Copy rule (fan-out in forward): when one tensor is copied into multiple branches, its backward gradient is the sum of the incoming gradients from each branch.
    • Add rule (addition in forward): when branches are added together (\( z = a + b \)), the upstream gradient is copied unchanged to each input branch.