Repository navigation
refactor: move Gemma 4 and AFMoE onto scheduler-owned layer state - #3643
Merged
Merged
Conversation
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
marked this pull request as ready for review
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.
This was referenced Dec 1, 2026
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`.
2 of 8 tasks
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.
This was referenced Dec 2, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #3259
Closes #3324
Summary
Migrates Gemma 4 (text, VL, and Unified) and AFMoE off
ModelOwnedSequenceStateonto scheduler-ownedLayerStatefollowing ADR 0010 (docs/adr/0010-scheduler-owned-sequence-state.md) and the Gemma 3 / Qwen 3.5 reference migrations.Gemma 4
LayerStateKind::Nonefor E-series KV-shared layers,LayerStateKind::Fullfor full-attention layers, andLayerStateKind::Slidingfor sliding layers, withGEMMA4_LAYER_STATE_SNAPSHOTfor generic snapshot encoding.Gemma4LayerCache(implemented by bothgemma4::CacheandLayerState) and a stack-localSharedKvCachePlaceholdersoGemma4TextModel,Gemma4Model, andgemma4_batched.rsrun directly over scheduler-ownedLayerStatewhile keepingGemma4StageModelandGemma4MtpBatchedTargetAdapteronCache.Gemma4Wrapper'sModelOwnedSequenceState<Cache>with a single id-lessfallback: RefCell<Vec<LayerState>>slot, removes all per-family snapshot and ring-checkpoint hooks, implementsforward_layer_state, and refuses sequence IDs on theKVCache-slice entries.Gemma4VLModelandGemma4UnifiedModelto forwardlayer_state_kinds,make_layer_state,layer_state_snapshot_spec, andforward_layer_statewhile preservingGemma4PerLayerInputsStateand Unified visionbidirectional_block_ids, and adds both toSCHEDULER_OWNED_WRAPPERSinsrc/vision/snapshot_forwarding_tests.rs.Gemma4MtpTargetAdapter,Gemma4VLMtpTargetAdapter, andGemma4UnifiedMtpTargetAdapterto borrow scheduler-owned layer state viafor_sequenceor use the fallback slot viafallback/fallback_with_block_size, wired throughscheduler.rs,speculative_burst.rs,generate.rs, andspeculative_bench.rs.StatePolicy::snapshotinsrc/server/prompt_cache/state_snapshot.rsto refuse snapshot donation while anyLayerState::Rotatinghas an active speculative rollback buffer (buffer_size > 0).AFMoE
Attention::forward_batched_decode,AfmoeModel::forward_batched_decode_with_caches,AfmoeModel::forward_rows, andhybrid_prefill_masksgeneric overgemma3::SlidingLayerCache.AfmoeModel'sModelOwnedSequenceState<Cache>withfallback: RefCell<Vec<LayerState>>, removesimpl SlidingHybridModel for AfmoeModeland all per-family snapshot/ring-checkpoint hooks, implementslayer_state_kinds,make_layer_state,layer_state_snapshot_spec(AFMOE_LAYER_STATE_SNAPSHOT), andforward_layer_state, and refuses sequence IDs on theKVCache-slice entries.src/models/sliding_hybrid_lm.rsandsrc/models/gemma3.rs, leavingstate_snapshot.rsas the single caller ofkv_ring_checkpoint.Test Harness & Coverage
last_row_logitsforwarding onPooled<M>insrc/models/pooled_model_language_model.rs.gemma4_ring_checkpoint_tests) ontoPooled<...>.gemma4_layer_state_tests,afmoe_layer_state_tests, buffered rotating cache snapshot refusal test instate_snapshot_tests.rs, and paged-decode-override scheduler tests (DecodeStorageBackend::Paged) for both families inscheduler_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 newgemma4andafmoepaged-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-existingclippy::manual_containsonmainin unrelatedsrc/models/lfm3_omni_config.rs:184).Unmeasured
docs/benchmark_results/) were not measured in this worktree because release benchmark runs were out of budget for the test-fast worktree.tests/speculative_parity.rswere compile-checked only.