Skip to content

npu: resolve qwen3_5's RMSNorm convention from the weights, so a zero-centered (1+w) pack is not normalised with plain w - #902

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/qwen35-norm-offset
Nov 3, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/qwen35-norm-offset

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Root cause

q4nx_semantics decided the RMSNorm convention from the model name, and only gemma* got the (1 + w) form:

s->rmsnorm_offset = (is_gemma && !is_gemma4) ? 1 : 0;

Qwen3.5's Qwen3_5RMSNorm is also zero-centered — weight initialised to 0, applied as x/rms * (1 + w)
(transformers 5.17.0, kernel name RMSNormZeroCentered) — so every norm in a vllm-sr/d3-lite container was scaled
by the weight's own magnitude instead of by 1 + that. Layer 0's input_layernorm is a delta trained from 0
(mean 0.2377, min -0.1143), so the engine's xn came out 4.7x too small and the whole forward inherited it.

The name cannot decide it, and that is the reason this is a probe rather than a one-line model_type change: this box
carries both conventions under model_type: qwen3_5 — all seven 27B bonsai2-27b-* dirs store plain gains
(mean 0.9704, min 0.8711, no negatives), including the owner's live serve dir. A name-based flip would have
silently renormalised the production 27B.

Measured before/after

One prompt (score_three_levels, 94 tokens), causal, bf16 container (weights byte-identical to the pack, so
quantization is not a variable), host-GEMM under npu-hold -l npufeat, amdxdna errors 0 before and after.

The first op, computed from the pack's own tensors:

numpy rmsnorm(embed, ·) l2 cos vs engine xn cos vs reference xn
w (before) 8.4773 1.000000 0.931249
1 + w (after) 39.7198 0.931263 0.999999

Layer 0 after the fix, against hooks on the pack's own runtime (d3 d3_runtime.py):

stage cos rel L2
xn 0.999999 0.0016
qkv (pre-conv) 0.999998 0.0019
co (conv + SiLU) 0.999999 0.0017
a / b 0.999999 0.0013 / 0.0016
z 0.999998 0.0020
core (delta rule + gated RMSNorm) 0.999991 0.0043
out (ssm_out_proj) 0.999995 0.0034

Per-layer last-position residual, 24 layers, same prompt (NPU_INFER_DUMP_LROWS diagnostic, uncommitted):

before after
first layer with cos < 0.999 0 (cos 0.254) 3
layers 0 / 1 / 2 0.254 / 0.278 / 0.377 0.999968 / 0.999974 / 0.999972
layer 3 (first full attention) 0.139 0.452 — the next defect, tracked separately
/v1/systemone vs the pack's d3_runtime.py (causal, 9 cases): worst ` Δp `
choice argmax flips 3/5 2/5

The remaining 0.4140 is not this bug: layers 0-2 are now exact to 1e-3 and the divergence starts at the first
full-attention layer (partial rotary 64/256, q/k norm, attn_output_gate) — that localisation is the next item on
engine#796, and no accuracy claim is made here.

What lands

  • npu/forward/include/q4nx_semantics.h — rmsnorm_offset_probe (documented: one model_type, two conventions) and
    the exported rule q4nx_rmsnorm_offset_from_norm(const float*, int).

  • npu/forward/src/q4nx_semantics.c — probe set for qwen3_5*; the rule: a negative value or a mean below 0.5 is
    the zero-centered form (a delta trained from 0 vs a gain trained from 1).

  • npu/forward/src/q4nx_forward.cpp — resolves it once after load_norms() and prints the evidence:

    [semantics] rmsnorm_offset=1  <- model.layers.0.input_layernorm.weight: mean 0.2377 min -0.1143
                                    (qwen3_5 ships both the zero-centered (1+w) form and the plain w form; the weight decides)
    
  • tests/npu_rmsnorm_offset_test.c + ctest npu_rmsnorm_offset — both real shapes as constants (d3 delta → (1+w);
    27B gain, all-ones, null, empty → plain), registered through add_dependencies(npu_sampling_test …) because this
    lane's token cannot write .github/workflows/.

  • docs/npu.md — the convention, both packs on this box, and why the GDN gated norm (linear_attn.norm,
    Qwen3_5RMSNormGated, ones-initialised, applied as w) is exempt.

Every other model_type is untouched: gemma* keeps its (1+w), everything else keeps plain w, and the seven 27B
qwen3_5 dirs resolve to offset 0 (checked against the containers themselves, not asserted).

closes #901

Qwen3.5's Qwen3_5RMSNorm is zero-centered -- the weight is initialised to 0 and applied as
x/rms * (1 + w) -- but q4nx_semantics only set rmsnorm_offset for gemma*, so a d3-lite container
was normalised with plain w and every norm output inherited the weight's own magnitude (layer 0's
input_layernorm is a delta: mean 0.2377, min -0.1143, so xn came out 4.7x small).

The model name cannot decide it: this box carries BOTH conventions under model_type qwen3_5 (all
seven 27B bonsai2 dirs store plain gains, mean 0.9704, min 0.8711, including the live serve dir),
so the convention is a probe resolved from the layer-0 input_layernorm weight the forward just
loaded, printed with its evidence.  The GDN gated norm (linear_attn.norm) is exempt: it is
ones-initialised and applied as w in both packs.

Measured (bf16 container, same weights as the pack, causal, host-GEMM, one 94-token prompt):
xn cos vs the pack's own runtime 0.931249 -> 0.999999; layer 0 stage by stage (xn/qkv/co/a/b/z/
core/out) >= 0.999991; first layer below cos 0.999 moves from 0 (cos 0.254) to 3; /v1/systemone
worst |dp| vs d3_runtime.py 0.6367 -> 0.4140, choice argmax flips 3/5 -> 2/5.  The remaining gap
starts at the first full-attention layer (cos 0.452), a separate defect tracked on engine#796.

ctest npu_rmsnorm_offset covers the rule with both real shapes; docs/npu.md documents the
convention and the exemption.
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 518a30d)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

796 - Partially compliant

Compliant requirements:

  • Host-side converter handles 235 non-2-D tensors correctly (no silent failures)
  • Name map resolves HF names to llama.cpp-style names using existing config
  • Three transforms (A_log→ssm_a, conv1d transpose, alpha/beta int8 tiles vs Q8_0) have known-answer checks
  • Real pack converts, loads under NPU_INFER_HOST_GEMM=1, answers through route with numeric parity against d3_runtime.py
  • Same questions answer on NPU with 7-design ELF set

Non-compliant requirements:

  • Device-side ELF set for 0.8B-GDN geometry (7 designs) is present and functional

Requires further human verification:

  • Verification that the 7-design ELF set is actually present and functional on the hardware

901 - Partially compliant

Compliant requirements:

  • Qwen3.5's RMSNorm convention is resolved from weights, not model name
  • Zero-centered (1+w) form is applied when weight is initialized to 0
  • Plain w form is applied when weight is initialized to 1
  • Both conventions are supported under same model_type
  • No silent renormalization of production 27B containers
  • Evidence printed in logs showing which convention was chosen
  • Test coverage for both weight shapes

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Issue

The new code in q4nx_forward.cpp performs a full loop through all elements of the input norm weight vector to compute sum and minimum value. For large norm vectors (e.g., H=1024), this could introduce unnecessary overhead in the forward pass. While the performance impact may be minimal, it's worth considering if there are more efficient ways to determine if the norm is zero-centered, especially since this check is done once per model load.

if (sem_.rmsnorm_offset_probe && !in_norm_.empty() && c_.H > 0) {
    const std::vector<float>& w0 = in_norm_[0];
    double sum = 0.0;
    float mn = w0[0];
    for (int i = 0; i < c_.H; i++) {
        sum += (double)w0[(size_t)i];
        if (w0[(size_t)i] < mn) mn = w0[(size_t)i];
    }
    sem_.rmsnorm_offset = q4nx_rmsnorm_offset_from_norm(w0.data(), c_.H);
    fprintf(stderr,
            "  [semantics] rmsnorm_offset=%d  <- model.layers.0.input_layernorm.weight: mean %.4f "
            "min %.4f (qwen3_5 ships both the zero-centered (1+w) form and the plain w form; the "
            "weight decides)\n",
            sem_.rmsnorm_offset, sum / (double)c_.H, (double)mn);
}
Ambiguous Logic for Convention Detection

The logic in q4nx_rmsnorm_offset_from_norm uses a threshold of 0.5 for mean value to decide between zero-centered and plain RMSNorm. This is a heuristic that may not be robust across different models or weight distributions. If a future model has a zero-centered weight with a mean very close to 0.5, it could be misclassified. The comment mentions that either signal (negative values or mean below 1) is sufficient, but the specific choice of 0.5 threshold should be validated against the actual data distribution.

int q4nx_rmsnorm_offset_from_norm(const float* w, int n) {
    if (!w || n <= 0) return 0;
    double sum = 0.0;
    float mn = w[0];
    for (int i = 0; i < n; i++) {
        sum += (double)w[i];
        if (w[i] < mn) mn = w[i];
    }
    /* A (1 + w) checkpoint's norm weight is a delta trained from 0, so it carries negatives and a mean
     * well under 1; a plain norm weight is a gain trained from 1. Either signal alone is enough. */
    return (mn < 0.0f || (sum / (double)n) < 0.5) ? 1 : 0;
}

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 7d0ecee. I re-derived the evidence from the containers and ran the shipped function on the real tensors, because the whole PR rests on "the weights decide it".

Every number in the docs and the test reproduces from the packs on this box (bf16 read straight out of each .q4nx, the same path load_norms() takes):

d3-lite-bf16  model.layers.0.input_layernorm.weight   n=1024 mean=0.2377 min=-0.1143  -> (1+w)
              model.layers.0.post_attention_layernorm  mean=0.0852 min=-0.3594           -> (1+w)
              model.norm.weight                        mean=3.3092 min=-0.7773           -> (1+w)
              model.layers.0.linear_attn.ssm_norm       mean=0.9516 min=0.5234           -> plain
bonsai2-27b-t2s2 (the owner's live dir, model_type qwen3_5)
              model.layers.0.input_layernorm.weight   n=5120 mean=0.9704 min=0.8711     -> plain
              model.layers.0.post_attention_layernorm  mean=0.7816 min=0.0000           -> plain
              model.norm.weight                        mean=1.9427 min=0.7070           -> plain
              model.layers.0.linear_attn.ssm_norm       mean=0.8621 min=0.5469           -> plain

The shipped function, fed the full real tensors (not the test's four-value heads), compiled from this head against q4nx_semantics.c:

/tmp/tprs/w_d3.bin    n=1024 mean=0.2377 min=-0.1143  q4nx_rmsnorm_offset_from_norm -> 1
/tmp/tprs/w_27b.bin   n=5120 mean=0.9704 min=0.8711  q4nx_rmsnorm_offset_from_norm -> 0

So the fix lands on the pack it is for, and the production 27B — the case a name-based flip would have silently renormalised — resolves to the convention it already had.

Scope, checked against every container on the box (the probe fires only for qwen3_5* && !gemma):

7 x bonsai2-27b-*      model_type=qwen3_5  mean 0.9704 min 0.8711  probe fires -> plain   (production, unchanged)
2 x d3-lite/-bf16/-conv model_type=qwen3_5 mean 0.2377 min -0.1143 probe fires -> (1+w)   (the fix)
Qwen3-0.6B             model_type=qwen3    mean 0.1748              probe does NOT fire
d3-synth-0.6b          model_type=qwen3    mean 0.1748              probe does NOT fire
qwen3-coder-30b-a3b-moe model_type=qwen3moe mean 0.0025 min -0.0352 probe does NOT fire

ctest npu_rmsnorm_offset built and ran here: 9/9 ok, including the two real shapes, and CMakeLists.txt adds the add_dependencies line for ci.yml's explicit target list, which is the #635 trap and it is handled.

The bits I expected to be fragile are the bits that hold:

  • Both signals in the rule are load-bearing. The negative test alone is not enough: d3-lite layer 23 has no negatives at all (min 0.0525) and mean 0.267, so only the mean branch classifies it. The 27B's post_attention_layernorm goes the other way — min exactly 0.0000, no negative, mean 0.78 — and stays plain. A one-signal rule would be wrong on one of these two packs.
  • Layer 0 is a fair proxy for these packs: sampled layers 0/1/2/3/11/23 on both — d3-lite stays 0.142-0.440 with negatives on five of six, the 27B stays 0.970-1.253 with none. (It is still a sample; see the note below.)
  • The GDN gated norm really is exempt, by construction rather than by luck: the gated norm is written out at q4nx_forward.cpp:1990-1996 as core * inv * gdn_small_[l].norm[vd] * silu(z), reading the weight directly and never consulting sem_.rmsnorm_offset — whose only consumer in the file is rmsnorm() (:3507). And that weight is a plain gain in both packs (0.9516 / 0.8621).
  • One flag for all layers + the final norm is right here: within each pack the input norms, the post-attention norms and model.norm all fall on the same side, so nothing is split.
  • Bounds: in_norm_.assign(NL, std::vector<float>(H)) happens inside load_norms() (:1365), which is called at :1250, before the probe reads w0[0..c_.H-1] at :1255 — no short-vector read.

Three notes, none of them gates:

  1. The probe is decided by layer 0 only, and the docs state it as if the weight itself decided per tensor. For these two packs that is measured and safe, but a pack whose layer 0 is plain and whose later layers are deltas would be decided silently by layer 0. One sentence in docs/npu.md ("sample is layer 0; measured to agree with layers … on both packs here") would keep a future reader from over-trusting it.
  2. If c_.H == 0 or the norms did not load, the probe silently leaves the plain convention in place for a qwen3_5 pack — i.e. the pre-fix behaviour, with no [semantics] line. Failing closed is right; saying nothing is the only part I would change.
  3. Out of scope but worth its own issue: the same statistic, applied to the three non-qwen3_5 packs above, says they are zero-centered too — Qwen3-0.6B and d3-synth-0.6b at mean 0.1748, and qwen3-coder-30b-a3b-moe at mean 0.0025 with 864 negatives. I checked the source GGUF of the 0.6B pack: its blk.0.attn_norm is 0.1748 / max 1.0469 and blk.1.attn_norm has 314 negatives, so the container is faithful to it — these are not conversion artefacts. If any of those packs is a real model rather than a synthetic gate-row fixture, it has #796's defect and this PR deliberately does not touch it. The PR is right not to (its rule is measured for qwen3_5 only, and "the name cannot decide it" is exactly the argument for measuring rather than extending the scope), but it should be filed while the evidence is fresh.

I ran no device work: the PR's before/after cos tables and the |Δp| numbers are the lane's npu-hold measurements, and the owner's serve holds the NPU lock.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 4d3c4cf

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 518a30d

@bong-water-water-bong
bong-water-water-bong merged commit f4e5f45 into main Nov 3, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/qwen35-norm-offset branch November 3, 2026 14:41
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Cross-check of the probe's evidence sentence, from a lane that runs a pack this changes (pi-mtploop, MTP drafter on bonsai2-27b-pb16i). The rule and the decision are fine; the quoted numbers are not what this box's container holds, and I would rather flag it than leave it in the record.

Read straight out of the container's own tensor table (model.q4nx, BF16, header length + JSON table, model.layers.0.input_layernorm.weight, 5120 values), identical in all six 27B bonsai2 dirs here (-NPU, -NPU-b8, -pb16i, -pb16i-unrot, -t2s2, -t2s2-serve):

model.layers.0.input_layernorm.weight      mean=1.8668  min=1.8428
model.layers.0.linear_attn.ssm_norm.weight mean=1.8405  min=1.7617
model.layers.0.post_attention_layernorm    mean=1.8201  min=0.0000  max=1.8760
model.norm.weight                          mean=1.9928  min=1.8018

i.e. 1.8668 / 1.8428, not 0.9704 / 0.8711 as the commit message states for these dirs (mean 0.9704, min 0.8711, including the live serve dir). q4nx_rmsnorm_offset_from_norm returns 0 for the container's values exactly as it does for the quoted ones (min ≥ 0 and mean ≥ 0.5), so nothing changes in behaviour — which is the only reason I am writing this as a note rather than an issue. Two consequences worth knowing: (1) a zero-centered pack whose (1+w) gains happen to be written as ≥0.5 with no negatives would also be read as plain, so the probe is one-sided; (2) whoever re-derives this convention from the commit sentence will be looking for weights the container does not contain.

Measured device-free (header parse + BF16 decode, no dequant, no device). If the 0.9704 came from an HF/bf16 checkpoint rather than the q4nx container, saying so in the message would close this.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Retracting my comment above — the error was mine, and your numbers are exactly right.

I decoded the container's BF16 norm tensor with Python struct code 'e', which is fp16, not bf16 (there is no bf16 code in struct). The values I quoted (mean 1.8668, min 1.8428) are what BF16 bytes look like when read as fp16. Decoded correctly (read as <u2, shift left 16, reinterpret as f4):

model.layers.0.input_layernorm.weight  BF16  n=5120   mean=0.9704  min=0.8711  max=1.2344
model.layers.0.input_layernorm.weight  as fp16 (my wrong read)  mean=1.8668  min=1.8428

i.e. 0.9704 / 0.8711, digit for digit what your commit message says, and the device agrees: a run at origin/main 65460184 printed

[semantics] rmsnorm_offset=0  <- model.layers.0.input_layernorm.weight: mean 0.9704 min 0.8711

So there is nothing to reconcile, the probe's evidence is reproducible from the shipped container, and the only real content of my earlier note is the mild, non-actionable observation that the rule is one-sided (a zero-centered pack whose 1+w gains all ended up ≥0.5 with no negatives would also read as offset 0). Sorry for the noise — the 'e'-is-fp16 mistake is the whole of it, and I am keeping it visible here rather than deleting the comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

npu: qwen3_5 stores two RMSNorm conventions under one model_type, so a zero-centered (1+w) pack is normalised with plain w

1 participant