Skip to content

refactor: move Gemma 4 and AFMoE onto scheduler-owned layer state - #3643

Merged
inureyes merged 1 commit into
mainfrom
refactor/issue-3324-gemma4-afmoe-layer-state
Dec 1, 2026
Merged

inureyes merged 1 commit into
mainfrom
refactor/issue-3324-gemma4-afmoe-layer-state

Conversation

@inureyes

@inureyes inureyes commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Part of #3259

Closes #3324

Summary

Migrates Gemma 4 (text, VL, and Unified) and AFMoE off ModelOwnedSequenceState onto scheduler-owned LayerState following ADR 0010 (docs/adr/0010-scheduler-owned-sequence-state.md) and the Gemma 3 / Qwen 3.5 reference migrations.

Gemma 4

  • Reports LayerStateKind::None for E-series KV-shared layers, LayerStateKind::Full for full-attention layers, and LayerStateKind::Sliding for sliding layers, with GEMMA4_LAYER_STATE_SNAPSHOT for generic snapshot encoding.
  • Introduces Gemma4LayerCache (implemented by both gemma4::Cache and LayerState) and a stack-local SharedKvCachePlaceholder so Gemma4TextModel, Gemma4Model, and gemma4_batched.rs run directly over scheduler-owned LayerState while keeping Gemma4StageModel and Gemma4MtpBatchedTargetAdapter on Cache.
  • Replaces Gemma4Wrapper's ModelOwnedSequenceState<Cache> with a single id-less fallback: RefCell<Vec<LayerState>> slot, removes all per-family snapshot and ring-checkpoint hooks, implements forward_layer_state, and refuses sequence IDs on the KVCache-slice entries.
  • Updates Gemma4VLModel and Gemma4UnifiedModel to forward layer_state_kinds, make_layer_state, layer_state_snapshot_spec, and forward_layer_state while preserving Gemma4PerLayerInputsState and Unified vision bidirectional_block_ids, and adds both to SCHEDULER_OWNED_WRAPPERS in src/vision/snapshot_forwarding_tests.rs.
  • Updates Gemma4MtpTargetAdapter, Gemma4VLMtpTargetAdapter, and Gemma4UnifiedMtpTargetAdapter to borrow scheduler-owned layer state via for_sequence or use the fallback slot via fallback / fallback_with_block_size, wired through scheduler.rs, speculative_burst.rs, generate.rs, and speculative_bench.rs.
  • Updates StatePolicy::snapshot in src/server/prompt_cache/state_snapshot.rs to refuse snapshot donation while any LayerState::Rotating has an active speculative rollback buffer (buffer_size > 0).

AFMoE

  • Makes Attention::forward_batched_decode, AfmoeModel::forward_batched_decode_with_caches, AfmoeModel::forward_rows, and hybrid_prefill_masks generic over gemma3::SlidingLayerCache.
  • Replaces AfmoeModel's ModelOwnedSequenceState<Cache> with fallback: RefCell<Vec<LayerState>>, removes impl SlidingHybridModel for AfmoeModel and all per-family snapshot/ring-checkpoint hooks, implements layer_state_kinds, make_layer_state, layer_state_snapshot_spec (AFMOE_LAYER_STATE_SNAPSHOT), and forward_layer_state, and refuses sequence IDs on the KVCache-slice entries.
  • Deletes the now-unused ring-checkpoint helpers from src/models/sliding_hybrid_lm.rs and src/models/gemma3.rs, leaving state_snapshot.rs as the single caller of kv_ring_checkpoint.

Test Harness & Coverage

  • Adds last_row_logits forwarding on Pooled<M> in src/models/pooled_model_language_model.rs.
  • Moves Gemma 4 and AFMoE model-level tests (including gemma4_ring_checkpoint_tests) onto Pooled<...>.
  • Adds gemma4_layer_state_tests, afmoe_layer_state_tests, buffered rotating cache snapshot refusal test in state_snapshot_tests.rs, and paged-decode-override scheduler tests (DecodeStorageBackend::Paged) for both families in scheduler_model_owned_cache_tests.rs.

Verification

  • cargo fmt --all -- --check: passed.
  • rg 'ModelOwnedSequenceState' src/models/gemma4.rs src/models/gemma4_mtp_target.rs src/models/afmoe.rs: 0 matches.
  • python3 scripts/ci/check_cross_repo_refs.py: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib afmoe -- --test-threads=1: 41 passed, 0 failed.
  • cargo test --profile test-fast --features metal,accelerate --lib gemma4 -- --test-threads=1: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib gemma4_ring_checkpoint_tests -- --ignored --test-threads=1: passed unchanged in assertions.
  • cargo test --profile test-fast --features metal,accelerate --lib gemma4_tests::cache_isolation -- --ignored --test-threads=1: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib gemma4_tests::snapshot -- --ignored --test-threads=1: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib state_snapshot -- --test-threads=1: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib snapshot_forwarding -- --test-threads=1: passed.
  • cargo test --profile test-fast --features metal,accelerate --lib speculative_slice -- --test-threads=1: 27 passed, 0 failed.
  • cargo test --profile test-fast --features metal,accelerate --lib speculative_burst_tests -- --test-threads=1: 62 passed, 0 failed.
  • cargo test --profile test-fast --features metal,accelerate --lib scheduler_model_owned_cache_tests -- --test-threads=1: passed (including new gemma4 and afmoe paged-decode-override tests).
  • cargo check --profile test-fast --features metal,accelerate --bin mlxcel --bin speculative_bench --test speculative_parity: passed.
  • cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings: 0 warnings/errors in touched files (1 pre-existing clippy::manual_contains on main in unrelated src/models/lfm3_omni_config.rs:184).

Unmeasured

  • B=1 and B=4 decode tok/s benchmarks at 256 and 8192 prompt tokens (main vs branch, interleaved with null arm, recorded in docs/benchmark_results/) were not measured in this worktree because release benchmark runs were out of budget for the test-fast worktree.
  • Real-checkpoint ignored integration tests in tests/speculative_parity.rs were compile-checked only.

Migrate Gemma 4 (text, VL, Unified) and AFMoE off ModelOwnedSequenceState onto scheduler-owned LayerState per ADR 0010, removing their per-family snapshot and ring-checkpoint hooks.

- Gemma 4 reports LayerStateKind::None for E-series KV-shared layers, LayerStateKind::Full for full-attention layers, and LayerStateKind::Sliding for sliding layers, with a stack-local SharedKvCachePlaceholder for KV-shared forward passes and GEMMA4_LAYER_STATE_SNAPSHOT for generic snapshot encoding.
- Gemma4VLModel and Gemma4UnifiedModel forward the four layer-state methods while keeping Gemma4PerLayerInputsState and Unified vision block_ids on forward_layer_state.
- Gemma4MtpTargetAdapter, Gemma4VLMtpTargetAdapter, and Gemma4UnifiedMtpTargetAdapter now borrow scheduler-owned layer state via for_sequence or use the id-less fallback slot via fallback/fallback_with_block_size, wired across scheduler.rs, speculative_burst.rs, generate.rs, and speculative_bench.rs.
- StatePolicy::snapshot refuses snapshot donation while any LayerState::Rotating has a speculative rollback buffer active (buffer_size > 0).
- AFMoE implements layer_state_kinds, make_layer_state, layer_state_snapshot_spec, and forward_layer_state over generic SlidingLayerCache forwards, removing its SlidingHybridModel implementation and the now-unused ring-checkpoint hooks in sliding_hybrid_lm.rs and gemma3.rs.
- Pooled<M> forwards last_row_logits for scheduler-owned sequences, and model-level tests plus new bit-exact round-trip, encoder-parity, and paged-decode-override scheduler tests cover both families.

Part of #3259
Closes #3324
@inureyes inureyes added type:refactor Code restructuring without changing functionality status:done Completed priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:architecture Architecture and code structure changes labels Dec 1, 2026
@inureyes
inureyes marked this pull request as ready for review December 1, 2026 14:41
@inureyes
inureyes merged commit 4d0e8b1 into main Dec 1, 2026
36 of 38 checks passed
@inureyes
inureyes deleted the refactor/issue-3324-gemma4-afmoe-layer-state branch December 1, 2026 14:41
inureyes added a commit that referenced this pull request Dec 1, 2026
On B200 the stock fp_qmv_single dequantizes every e2m1 weight on CUDA cores and multiplies in fp32. It is instruction-issue bound and streams Gemma 4 31B's MLP weights at about 1.5 TB/s, 42% of decode time.

The CUDA overlay of qmm/fp_qmv.cu adds fp_qmv_tc_single for one NVFP4 vector on compute capability 10.x: hardware cvt.rn.f16x2.e2m1x2 unpack, exact f16 pre-scaling by the e4m3 block scale, f16 mma.sync m16n8k16 with fp32 accumulation, K split across the warps of a block, and x staged once per block as f16 times a power of two so bf16 inputs stay exact. CMake compiles fp_qmv.cu for the architecture-specific image as it already does for fp_quantize.cu; the plain image keeps a software unpack. MLXCEL_FP_QMV_TC=0 restores the stock kernel.

Microbenchmark: 44 us to 21.4 us (gate/up) and 25.6 us (down), same error against an fp64 reference. Model tg128 decode (test-fast): 51.3 to 57.1 tok/s with CUDA graphs off, 60.4 to 79.4 with graphs on. Greedy output through mlxcel-server: 5 of 8 prompts identical over 200 tokens, the rest first differ at near-ties.

Also fixes the logit_trace example for the #3643 adapter rename, adds the microbenchmark source, and renames the record to Gemma4_sm100_Optimization_Report.md with a per-run CSV.
inureyes added a commit that referenced this pull request Dec 1, 2026
…3659)

Part of #3259

Follow-up fix for PR #3643 (#3324), which replaced `Gemma4MtpTargetAdapter::new_with_block_size(wrapper, None, width)` with `Gemma4MtpTargetAdapter::fallback_with_block_size(wrapper, width)`. Updates `examples/logit_trace/gemma4.rs` so `cargo check --examples` and `--all-targets` compile cleanly.

Validated with `cargo fmt --all -- --check` and `cargo check --profile test-fast --features metal,accelerate --examples`.
inureyes added a commit that referenced this pull request Dec 1, 2026
On B200 the stock fp_qmv_single dequantizes every e2m1 weight on CUDA cores and multiplies in fp32. It is instruction-issue bound and streams Gemma 4 31B's MLP weights at about 1.5 TB/s, 42% of decode time.

The CUDA overlay of qmm/fp_qmv.cu adds fp_qmv_tc_single for one NVFP4 vector on compute capability 10.x: hardware cvt.rn.f16x2.e2m1x2 unpack, exact f16 pre-scaling by the e4m3 block scale, f16 mma.sync m16n8k16 with fp32 accumulation, K split across the warps of a block, and x staged once per block as f16 times a power of two so bf16 inputs stay exact. CMake compiles fp_qmv.cu for the architecture-specific image as it already does for fp_quantize.cu; the plain image keeps a software unpack. MLXCEL_FP_QMV_TC=0 restores the stock kernel.

Microbenchmark: 44 us to 21.4 us (gate/up) and 25.6 us (down), same error against an fp64 reference. Model tg128 decode (test-fast): 51.3 to 57.1 tok/s with CUDA graphs off, 60.4 to 79.4 with graphs on. Greedy output through mlxcel-server: 5 of 8 prompts identical over 200 tokens, the rest first differ at near-ties.

Also fixes the logit_trace example for the #3643 adapter rename, adds the microbenchmark source, and renames the record to Gemma4_sm100_Optimization_Report.md with a per-run CSV.
inureyes added a commit that referenced this pull request Dec 2, 2026
On B200 the stock fp_qmv_single dequantizes every e2m1 weight on CUDA cores and multiplies in fp32. It is instruction-issue bound and streams Gemma 4 31B's MLP weights at about 1.5 TB/s, 42% of decode time.

The CUDA overlay of qmm/fp_qmv.cu adds fp_qmv_tc_single for one NVFP4 vector on compute capability 10.x: hardware cvt.rn.f16x2.e2m1x2 unpack, exact f16 pre-scaling by the e4m3 block scale, f16 mma.sync m16n8k16 with fp32 accumulation, K split across the warps of a block, and x staged once per block as f16 times a power of two so bf16 inputs stay exact. CMake compiles fp_qmv.cu for the architecture-specific image as it already does for fp_quantize.cu; the plain image keeps a software unpack. MLXCEL_FP_QMV_TC=0 restores the stock kernel.

Microbenchmark: 44 us to 21.4 us (gate/up) and 25.6 us (down), same error against an fp64 reference. Model tg128 decode (test-fast): 51.3 to 57.1 tok/s with CUDA graphs off, 60.4 to 79.4 with graphs on. Greedy output through mlxcel-server: 5 of 8 prompts identical over 200 tokens, the rest first differ at near-ties.

Also fixes the logit_trace example for the #3643 adapter rename, adds the microbenchmark source, and renames the record to Gemma4_sm100_Optimization_Report.md with a per-run CSV.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:architecture Architecture and code structure changes area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:refactor Code restructuring without changing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: Move Gemma 4 and AFMoE onto scheduler-owned layer state

1 participant