Skip to content

fix(convert): AWQ Group A folds into pre_feedforward_layernorm on sandwich-norm layers - #87

Merged
Brooooooklyn merged 1 commit into
mainfrom
fix/awq-gemma4-sandwich-norm
Jul 7, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
fix/awq-gemma4-sandwich-norm

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Bug

apply_awq_prescaling Group A (imatrix AWQ fold, MLP scales) always divided post_attention_layernorm.weight by the per-channel scales s. That pairing is correct for two-norm families (qwen3_5, lfm2) where that norm feeds gate/up_proj — but wrong for gemma4's 4-norm sandwich layers:

qwen wiring (fold assumed):          gemma4 actual wiring:
  post_attn_norm ──→ MLP(gate/up)      post_attn_norm ──→ attn_out → residual
                                       pre_ffn_norm   ──→ MLP(gate/up)

On gemma4 (decoder_layer.rs::apply_ffn_ple_scalar): h = x + post_attention_layernorm(attn_out), MLP reads pre_feedforward_layernorm(h). The old fold rescaled the attention branch by 1/s (raw GGUF imatrix magnitudes give s spanning ~1e-3..1e3) and left gate/up columns uncompensated — any gemma4 + --q-recipe unsloth + --imatrix-path conversion produced garbage.

Evidence (gemma-4-12b-it unsloth-Q8+imatrix vs plain-Q8 control, layer 0): post_attention_layernorm max|Δ| = 8889 while pre_feedforward_layernorm was 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.weight when the layer has one, else falls back to post_attention_layernorm.weight (two-norm families byte-identical to before). Groups B/C/D verified balanced for gemma4 wiring and unchanged.

Verification

  • New unit test awq_group_a_targets_sandwich_ffn_norm: sandwich layer → inverse on pre_feedforward_layernorm, attention-output norm untouched, gate[j] × norm[j] == 1 balance invariant; two-norm layer → unchanged classic behavior. Fails on the old code.
  • E2E: reconverted gemma-4-12b-it → unsloth-Q8+imatrix, coherent generation restored; DSpark (feat(gemma4): DSpark speculative decoding (DeepSeek DeepSpec external draft) #86) on the fixed model: 53.1 tok/s vs 32.7 AR (1.62×), mean accepted 4.34/cycle (was exactly 0 on the broken conversion).
  • cargo clippy --all-targets clean, cargo fmt --check clean, 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 when pre_feedforward_layernorm is absent.

Overview
AWQ Group A imatrix prescaling no longer always divides post_attention_layernorm.weight by the inverse MLP scales. It now picks the norm whose output actually feeds gate_proj / up_proj: pre_feedforward_layernorm when that tensor exists (e.g. gemma4 sandwich layers), otherwise post_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_norm to assert sandwich layers fold into pre_feedforward_layernorm (attention norm untouched, gate×norm balance), and two-norm layers still use post_attention_layernorm.

Reviewed by Cursor Bugbot for commit 9eb4aa8. Bugbot is set up for automated code reviews on this repo. Configure here.

…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]>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8e2896dd-6339-40f1-9ead-8ffb2f00ac56

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/awq-gemma4-sandwich-norm

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cursor

cursor Bot commented Jul 6, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@Brooooooklyn
Brooooooklyn merged commit b33c182 into main Jul 7, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/awq-gemma4-sandwich-norm branch July 7, 2026 00:08
Brooooooklyn added a commit that referenced this pull request Jul 7, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant