Files
foxhunt/crates/ml-core
jgrusewski 88a6db6eae feat(ml-alpha): Mamba2 backward pass — analytical, GPU-pure (Phase 1d.1, session 3)
End-to-end analytical backward through all six stages of the forward
chain. No atomicAdd, no SPSA, no host roundtrip during gradient flow —
each scratch buffer is per-channel-unique so concurrent writes don't
collide; cross-channel reduction is a separate kernel.

New API:
  - GpuLinear::backward_with_slices(dy, act, weight, cublas, stream)
    → LinearGrads{dw, db, dx}
    Mirror of forward_with_slices added to ml-core; no GpuVarStore lookup.
  - Mamba2BackwardGrads holds dw_in/db_in/dw_a/db_a/dw_b/db_b/dw_c/dw_out/db_out
  - Mamba2Block::backward(&cache, &d_logit) → Mamba2BackwardGrads

Chain (reverse of forward):
  6′. W_out backward       (cuBLAS sgemm)         → d_h_enriched, dw_out, db_out
  5′. mamba2_alpha_scan_bwd kernel                → d_a/d_b/d_w_c per-channel/sample
                                                    + d_h_s2 (identity passthrough)
  ↳ mamba2_alpha_reduce_d_proj × 2                → d_a_proj, d_b_proj [N, K, state]
  ↳ mamba2_alpha_reduce_d_w_c                     → dw_c [hidden, state]
  3′. W_b backward                                 → d_x_from_b, dw_b, db_b
  2′. W_a backward                                 → d_x_from_a, dw_a, db_a
  ↳ d_x = d_x_from_a + d_x_from_b
  1′. W_in backward                                → dw_in, db_in (d_input discarded)

Memory cost per backward call (for Phase 1d.1 sizes N=64, sh2=32,
K=16, state=8): ~1.1 MiB scratch — fits comfortably on RTX 3050.

Tests (9 passing on real GPU):
- Backward produces all 9 grads with correct shapes
- All grads finite through the 6-stage chain
- dw_in non-zero (gradient flows to the input projection, proving the
  full chain is wired — not silently zero-ing somewhere)
- Backward rejects wrong d_logit shape
- + all previously-passing forward / config / shape tests

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 01:51:20 +02:00
..