Repository navigation
Description
Part of milestone 8 (SPEC §13.8, decisions 21–22). First rung of the ladder: everything here is CPU-only, gradchecked, and becomes the oracle for 8b/8c/8d.
Goal
A MoeFfn module in crates/nn that is a drop-in type substitution for the dense FFN block (SPEC §6): same Input/Output types as the composition it replaces, so the CPU Llama (and later GpuLlama) swaps it in without touching surrounding wiring.
Const generics: expert count E, top-k K, per-expert capacity C — these size buffers and (later) launch grids. The aux-loss coefficient is runtime config (decision 21), not a const.
Proposed shape
pub struct MoeFfn<const N: usize, const D: usize, const FF: usize,
const E: usize, const K: usize, const C: usize> {
router: Linear<N, D, E>, // fp32, always (decision 22)
experts: [ExpertFfn<C, D, FF>; E], // gate/up/down Linears + SwiGlu each
pub aux_coefficient: f32, // set by the training loop each step
pub last_aux_loss: f32, // read by the training loop after forward
}Input = Output = CpuTensor<f32, Rank2<N, D>>— identical to the dense path, which is what makes the swap a type substitution.- Experts reuse the existing leaves:
Linear(crates/nn/src/linear.rs:16) andSwiGlu(crates/nn/src/swiglu.rs:10). The dense model wires gate/up/down manually incrates/nn/src/llama.rs:140-146; the expert is that same composition behind one struct. Ctxcarries: router logits/probs, selected experts + gate weights per token, the capacity-bin assignment (slot index or dropped), per-expertSwiGluctxs, and whatever the aux-loss backward needs (per-expert mean probs).
Semantics to pin down (proposals, push back in comments)
Routing math — softmax over E logits, take top-K, then renormalize the selected probs over the K winners (Mixtral-style) for the combine weights. The alternative (Switch-style raw probs) under-weights the FFN output early in training; renormalization keeps the block's output scale comparable to the dense FFN it replaces, which matters because we gate on overfit behavior against the dense baseline. Ties in top-k select the lower expert index — determinism is load-bearing for GPU parity later.
Capacity dispatch — each expert takes at most C tokens, priority by token order (first come, first served). A (token, expert) pair that overflows is dropped: that expert contributes zero for that token. A token dropped by all its K experts contributes zero FFN output entirely — with the residual add around the FFN (llama.rs:140-146), that degrades to identity passthrough, which is exactly the SPEC's "dropped-token passthrough". No gradient flows through dropped pairs.
Aux load-balancing loss — Switch-style: L_aux = E · Σ_i f_i · P_i, where f_i = fraction of tokens routed to expert i (discrete, no gradient) and P_i = mean router softmax prob for expert i (differentiable). Minimized at uniform routing where it equals 1.
How the aux loss reaches the training loss without breaking the Module types: forward computes L_aux and stashes it (last_aux_loss + ctx); the training loop adds coefficient · last_aux_loss to the reported loss scalar. backward internally injects coefficient · dL_aux/d(router params) into the router grads alongside the gate-weight path — it does not need an extra input because the loss seed is always [1.0] (crates/nn/src/llama.rs:175-178, same convention as SoftmaxCrossEntropy). This keeps Output = Rank2<N,D> so the type substitution holds. The coefficient is a plain f32 field the loop sets each step from its schedule — the same lifecycle as learning_rate (decision 21).
Gradient paths (for the backward implementation)
- Expert params: standard, through each expert's Linears/SwiGlu over its bin.
- Gate weights:
dg_e = dot(expert_out_e[token], dy[token]), then through the top-k renormalization and softmax into the router weight and the input. - Aux loss: through
P_i(mean softmax probs) into the router only, scaled byaux_coefficient. - Input: sum of expert-path grads (scattered back token-order) + router-path grads. Dropped pairs contribute nothing.
Gradcheck subtlety (the important one)
Top-k selection and capacity cutoffs are discontinuous: a central-difference probe that crosses a routing boundary measures garbage. The existing harness (numeric_grad, crates/nn/src/gradcheck.rs:14) probes every element. Plan:
- Gradcheck at seeded inputs whose router logit margins are verified ≥ some
MARGIN >> EPSfor every token (assert this in the test setup, don't hope). - Separately gradcheck the router weight through the aux-loss path with a nonzero coefficient, and with coefficient 0 to isolate the gate path.
- Also gradcheck a configuration that forces drops (small
C) and one with underfull experts (skewed logits) — the boundaries themselves must sit far from the probe points, but drop handling must be exercised.
Gates (all CPU)
- Gradcheck: input, router weight, every expert param — at a no-drop config, a forced-drop config, and an underfull-expert config.
- Tiny-batch overfit through a 1-block model with
MoeFfnsubstituted for the dense FFN (pattern: existing CPU overfit gate), aux coefficient nonzero. - Sanity: with strong imbalance in router init, training with the aux loss measurably flattens
f_ivs coefficient 0. - Deterministic: same seed → bit-identical routing decisions (shared splitmix64, SPEC §4).
Complexity
~400–600 LOC in crates/nn (module + dispatch + aux loss) plus ~200–300 LOC of tests. No new dependencies, no type-level shape arithmetic needed — E/K/C only ever share const params between types, consistent with the §3 rule.
Activity