Repository navigation
fix(convert): AWQ Group A folds into pre_feedforward_layernorm on sandwich-norm layers - #87
Conversation
…dwich-norm layers apply_awq_prescaling Group A always divided post_attention_layernorm by the MLP scales — correct for two-norm families (qwen3_5, lfm2) where that norm feeds gate/up, but wrong for gemma4's 4-norm sandwich layers where post_attention_layernorm normalizes the attention output into the residual stream and the MLP reads pre_feedforward_layernorm. The fold rescaled the attention branch by 1/s (s up to ~10^3 from raw GGUF imatrix magnitudes) and left gate/up columns uncompensated, producing garbage output on any gemma4 + --q-recipe unsloth + --imatrix-path conversion. Group A now targets pre_feedforward_layernorm when the layer has one, falling back to post_attention_layernorm otherwise. Groups B/C/D were verified balanced for gemma4 wiring and are unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_8b8d435f-fb43-4f56-a742-af824ddcbf66) |
…oints (#88) ## What Adds gemma-4 **native MTP** speculative decoding: support for Google's official assistant draft checkpoints (`google/gemma-4-{12B,26B-A4B,31B}-it-assistant`, apache-2.0, ~800 MB) as a **second draft variant** next to DSpark (#86), behind the same `loadSession(path, { draftModelPath })` surface — the loader picks the variant from the draft checkpoint's `config.json`. ``` DSpark (existing): 5-layer draft, masked block-7 proposals, tapped target hiddens Assistant MTP (new): 4-layer draft, Q-only attention reading the TARGET's KV caches (last non-KV-shared sliding/full layers), no draft KV, no prefill; one token per step chained through a hidden feedback loop, constant RoPE position per cycle; mtpDepth drafts/cycle (default 3, clamp [1,8]) ``` Both variants share the engine turn loop (`run_dspark_turn`), verify/rollback machinery, stop-clamp semantics, and telemetry. E2B/E4B assistants (centroid sparse lm_head) are rejected at load with a clear error — follow-up. ## Design - `Gemma4Draft { Dspark, Assistant }` enum dispatch (invalid states unrepresentable); `Gemma4DraftStepper`/`Gemma4DraftTurnState` enums delegate the engine seam; whole-turn core generalized with exactly 3 variant points. - Draft reads target K/V **verbatim** (target caches K post-RoPE) via `get_cached_kv()` re-read after every commit; sliding caches return temporally-ordered windows. - Target-side seams: `lm_head_logits` extraction (pure refactor), `assistant_verify_forward` (logits + post-final-norm hidden), `assistant_kv_source_indices` (exact `layer_types` matching, consistent with `should_store_shared_kv`). - Greedy longest-prefix + Leviathan rejection sampling from the engine — distribution-preserving at T>0 (stronger than mlx-vlm's naive match). - **Zero TS surface changes** — proven by the TS e2e passing with no edits under `packages/` (only doc comments + the server `extra_body.mtp_depth` cap lift landed there). ## Verification - **E2E oracles 6/6 green first run** on real 12B (`tests/gemma4_assistant.rs`): greedy byte-parity vs AR incl. sliding-window wraps, stop-mid-block + warm delta turn, acceptance canary, sampled smoke, stream==sync. DSpark regression suite 6/6 unchanged. TS e2e mirror 1/1. - Unit: 2078 lib tests green; clippy `-D warnings` + fmt clean; typecheck + type-aware lint clean. - Per-phase codex adversarial reviews (5 fix rounds all resolved: exact layer_types KV mapping, draft-dim validation gates ×2, rawText parity asserts, stale MTP docs + server depth cap) + whole-branch review **PASS**. ## Numbers (M5 Max, bf16 12B target, greedy, cooled 3 min between runs) Structured prompt (numbered pancake recipe, 200 tok — same prompt as the PR #86/#87 quantized benches): | Path | tok/s | vs AR | accepted/cycle | |---|---|---|---| | AR | 18.4 | — | — | | **Assistant MTP** | **29.9** | **1.63×** | 3.25 | | DSpark | 27.0 | 1.47× | 3.41 | Open-prose prompt (pour-over brewing guide, run to EOS ~1.7k tok): | Path | tok/s | vs AR | accepted/cycle | |---|---|---|---| | AR | 19.8 | — | — | | **Assistant MTP** | **24.5** | **1.24×** | 2.80 | | DSpark | 27.4 | 1.38× | 3.78 | Speedup is acceptance-driven and prompt-dependent — the PR #86 "2.46×" headline was the `decode_wrap` oracle fixture (highly predictable 600-tok continuation, accept 6.05/cycle, the ceiling); its `multi_cycle` fixture printed 26.7 tok/s accept 3.49, matching these numbers exactly. The assistant beats DSpark on the structured prompt despite lower acceptance because its cycles are much cheaper (0.8 GB Q-only draft + 4-row verify at depth 3 vs 6.9 GB draft + 8-row verify at block 7); it needs no per-cycle context fusion and no draft prefill. Docs: `docs/models.md` speculative-decoding section covers both variants; `ChatConfig.mtpDepth`/TSDoc scoped per family. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Large change to the Gemma4 speculative-decode and KV rollback path; wrong assistant wiring could break greedy parity or session reuse, though fail-closed reset and T=0 e2e oracles target that. > > **Overview** > Adds **Google `gemma-4-*-it-assistant`** as a second Gemma4 external draft alongside DSpark, still loaded through **`loadSession` / `draftModelPath`** with variant chosen from the draft `config.json`. > > The assistant is a Q-only draft that reads the **target’s committed KV** (no draft KV / DSpark-style context fusion), chains single-token proposals with a fixed query position per cycle, and uses family-specific **`mtpDepth`** (default 3, clamp **[1, 8]**). DSpark and assistant share a refactored **`Gemma4Draft`** / **`Gemma4DraftStepper`** / **`draft_chat_turn`** path instead of DSpark-only `dspark_chat_turn` and `dspark_turn_state`. > > **Server/API:** HTTP mappers stop capping `extra_body.mtp_depth` at 5; they forward **6–8** and reject invalid values above **64**, leaving per-family clamps to native code. NAPI/TSDoc now describe both draft kinds and depth rules. > > **Tests:** New env-gated TS e2e for assistant greedy **byte-parity vs no-draft** plus real speculative cycles; DSpark e2e also asserts **`rawText`** parity. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit aff9c98. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Bug
apply_awq_prescalingGroup A (imatrix AWQ fold, MLP scales) always dividedpost_attention_layernorm.weightby the per-channel scaless. That pairing is correct for two-norm families (qwen3_5, lfm2) where that norm feedsgate/up_proj— but wrong for gemma4's 4-norm sandwich layers:On gemma4 (
decoder_layer.rs::apply_ffn_ple_scalar):h = x + post_attention_layernorm(attn_out), MLP readspre_feedforward_layernorm(h). The old fold rescaled the attention branch by1/s(raw GGUF imatrix magnitudes givesspanning ~1e-3..1e3) and leftgate/upcolumns uncompensated — anygemma4 + --q-recipe unsloth + --imatrix-pathconversion produced garbage.Evidence (gemma-4-12b-it unsloth-Q8+imatrix vs plain-Q8 control, layer 0):
post_attention_layernormmax|Δ| = 8889 whilepre_feedforward_layernormwas byte-identical; generation was pure noise ("or & or or…"), DSpark acceptance collapsed to exactly 0 drafts accepted (target-argmax noise).Fix
Group A folds the inverse into
pre_feedforward_layernorm.weightwhen the layer has one, else falls back topost_attention_layernorm.weight(two-norm families byte-identical to before). Groups B/C/D verified balanced for gemma4 wiring and unchanged.Verification
awq_group_a_targets_sandwich_ffn_norm: sandwich layer → inverse onpre_feedforward_layernorm, attention-output norm untouched,gate[j] × norm[j] == 1balance invariant; two-norm layer → unchanged classic behavior. Fails on the old code.cargo clippy --all-targetsclean,cargo fmt --checkclean, codex adversarial review PASS (no findings).🤖 Generated with Claude Code
Note
Medium Risk
Touches quantization reparameterization in
apply_awq_prescaling, which directly affects converted model numerics; scope is narrow (Group A norm key selection) with a regression test and unchanged behavior whenpre_feedforward_layernormis absent.Overview
AWQ Group A imatrix prescaling no longer always divides
post_attention_layernorm.weightby the inverse MLP scales. It now picks the norm whose output actually feedsgate_proj/up_proj:pre_feedforward_layernormwhen that tensor exists (e.g. gemma4 sandwich layers), otherwisepost_attention_layernorm(unchanged for two-norm families like qwen3_5 / lfm2).This fixes broken gemma4 conversions with unsloth + imatrix, where the old fold corrupted the attention residual branch and left MLP weights uncompensated.
Adds
awq_group_a_targets_sandwich_ffn_normto assert sandwich layers fold intopre_feedforward_layernorm(attention norm untouched, gate×norm balance), and two-norm layers still usepost_attention_layernorm.Reviewed by Cursor Bugbot for commit 9eb4aa8. Bugbot is set up for automated code reviews on this repo. Configure here.