Skip to content

8b — GPU routing: fp32 top-k select + capacity-bin scatter/gather (gpu/llama-ops) #25

Closed

Description

@feitreim

Part of milestone 8 (SPEC §13.8b, decision 22). Depends on #24 (the CPU reference is the parity oracle). Can proceed in parallel with 8c once #24's semantics are frozen.

Goal

GPU kernels in gpu/llama-ops for everything between the FFN-norm output and the expert GEMMs: router forward/backward, top-k select, and the scatter/gather between token order and capacity-padded expert bins. fp32 end-to-end (decision 22): routing is discrete, so bf16 rounding near a top-k boundary doesn't perturb an output — it reassigns a token (the 7e7 two-logit tie in miniature). The [N,D]×[D,E] router GEMM is too skinny for the tcgen05 tile contract anyway, and is a rounding-error share of step FLOPs.

Kernel inventory

All in the kernels module of gpu/llama-ops/src/lib.rs, parity-checked in main.rs following the existing check_* pattern (gpu/llama-ops/src/main.rs:36-44).

Forward:

  1. router_logits — [N,D]×[D,E] fp32 GEMM. E is tiny (single-digit to low tens), so one block per token row with a cooperative dot per expert is plenty; do not route this through gpu/gemm.
  2. router_softmax_topk — per-token softmax over E, top-K select with renormalized combine weights, ties to the lower expert index (must match 8a — CPU reference MoE FFN: router, capacity dispatch, aux loss (crates/nn) #24 bit-for-bit at the decision level). E and K are small enough that one thread per token doing a serial scan is correct and cheap; fancier selection is not worth it at these sizes.
  3. moe_bin_assign — see determinism note below. Produces per-(token, k): expert id, slot-in-bin, drop flag.
  4. moe_scatter — copy each surviving token's [D] row into its [E, C, D] bin slot; zero-fill unused slots (zeros must stay inert through the expert SwiGLU — they do: swiglu(0,0)=0 — and through the down-proj accumulate).
  5. moe_gather_combine — y[token] += Σ_k g_k · expert_out[bin_k, slot_k], skipping dropped pairs.

Backward:
6. moe_scatter_dy — scatter g_k · dy[token] into bin order (input grad for expert backward); per-pair gate grad dg_k = dot(expert_out, dy).
7. moe_gather_dx — gather expert-input grads from bin order back to token order, summing over k.
8. router_backward — renormalized-top-k + softmax backward for the gate path, plus the aux-loss term: mean-prob reduction over tokens, E·f_i scaling, coefficient passed from the host as a plain scalar arg (decision 21 — same plumbing as learning_rate).

Nearest existing precedents: embedding_backward_scatter (gpu/llama-ops/src/lib.rs:554) for one-thread-per-element scatter, and split_group2/join_group2 (lib.rs:413,434) for the layout-shuffle pattern. Nothing top-k-shaped exists yet — that part is genuinely new surface.

The determinism problem (design-load-bearing)

The CPU reference (#24) assigns capacity slots by token order. The obvious GPU implementation — one atomic counter per expert, slot = atomicAdd(count[e], 1) — assigns slots in whatever order threads happen to run, which breaks CPU/GPU parity two ways: which tokens get dropped when a bin overflows becomes nondeterministic, and even without drops, summation order inside the expert GEMMs changes run-to-run.

Plan: make binning a deterministic multi-pass instead of atomics:

  1. Pass A: per-token top-k choices (already computed by kernel 2).
  2. Pass B: per-expert exclusive prefix count over token order — one block per expert scanning the [N,K] choice table serially (N ≤ 32k; E blocks; this is O(E·N·K) trivial integer work, nowhere near the profile). Token's slot = its rank among that expert's claimants; rank ≥ C ⇒ dropped.
  3. Pass C: scatter with the now-fixed slots.

If a profile later shows Pass B mattering (it shouldn't), a block-level scan can replace the serial walk — but deterministic-first, per the correctness-before-speed ladder.

Parity gates

  • Router logits/softmax/top-k/gate-weight parity vs crates/nn at fp32 tolerances (~1e-6), including tie shapes constructed to hit the lower-index rule.
  • Bin assignment parity on shapes that force drops (small C, concentrated logits) and underfull experts (skewed logits): identical drop sets and slot indices, not just identical sums.
  • Scatter→gather round-trip is the identity for surviving tokens; dropped tokens contribute exact zeros.
  • Backward parity for all three grad paths (expert-input, gate, router incl. aux term with a nonzero coefficient).

Complexity

~500–800 LOC of kernels plus ~300 LOC of parity checks in main.rs. No new crate — this lands in llama-ops next to the ops it composes with.

Activity

  1. added this to the 8 — MoE FFN milestone on Jul 18, 2026
  2. added
    enhancement
    on Jul 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions