Skip to content

npu-pack: de-interleave a gated q_proj's rows, so the forward attends over q and gates with gate - #904

Merged
bong-water-water-bong merged 5 commits into
mainfrom
1bit/903-qproj-deinterleave
Nov 3, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
1bit/903-qproj-deinterleave

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Root cause

Qwen3.5's gated attention builds its query as

query_states, gate = torch.chunk(self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1)

so a gated q_proj's rows are [q_h | gate_h] per head. The forward assembles the fused QKV as
[q block | gate block | k | v] — the layout the FLM/OGA packs store, where attn_q and attn_gate are separate
tensors that get concatenated. tools/safetensors_to_q4nx.py was a pure rename, so a vllm-sr/d3-lite container kept
the per-head order and the forward attended over half-gate rows and gated with half-query ones.

The two layouts are unrelated (below, cos 0.077), so this survives every statistical check and only shows up as
"the first full-attention layer is 0.45 off" — which is exactly where engine#796's per-layer instrument put it.

Measured (real d3 pack, layer 3 = first full attention, last prompt position, bf16 container)

The engine's own dump of the slices it attends over, against the pack's runtime:

comparison cos rel L2
engine q slice vs HF q (per-head, what the container held) 0.0774 3.6499
engine q slice vs HF q (block reading) 0.999992 0.0045
engine gate vs HF gate (per-head) 0.5989 0.8088
engine gate vs HF gate (block reading) 0.999994 0.0042
engine v vs HF v 0.999964 0.0086

Before/after on the whole forward

Per-layer last-position residual over all 24 layers (one 94-token prompt, causal, host-GEMM,
npu-hold -l npufeat, amdxdna errors 0):

before after
first layer with cos < 0.999 3 (cos 0.452) none
layer 3 0.452 0.999968
layer 7 / 11 / 15 / 19 / 23 (all full attention) 0.47 / 0.48 / 0.39 / 0.72 / 0.975 0.999978 / 0.999986 / 0.999988 / 0.999992 / 0.999998
/v1/systemone vs the pack's d3_runtime.py, 9 cases, worst |Δp| 0.4140 0.0061
choice argmax flips 2/5 0/5

(The other half of the 0.6367 → 0.4140 step was engine#901's norm convention, already merged.)

What lands

  • tools/safetensors_to_q4nx.py — gate_geometry() reads attn_output_gate + num_attention_heads + head_dim
    from the pack's own config.json; qwen35_transform() de-interleaves self_attn.q_proj.weight rows into
    [q block | gate block]; verify() applies the same transform, because it compares container against source and
    would otherwise report the fix as a loss.
  • A gated pack whose config lacks the head geometry is refused by name rather than guessed.
  • tests/safetensors_to_q4nx_test.py — the fixture declares the gated geometry, the packed rows are checked against
    the de-interleaved source (and asserted not to be the source order), the converter says it reordered them, and the
    missing-geometry refusal is a case.
  • docs/npu.md — the transform row in the converter table, with the measured cosines.

Nothing else changes: attn_output_gate false (and every non-qwen3_5 arch) takes the identity path, and the FLM/OGA
27B containers are already block-wise.

closes #903

bong-water-water-bong added 2 commits November 3, 2026 09:13
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.
… over q and gates with gate (closes #903)

HF builds a gated attention layer's query as view(*, -1, 2*head_dim) + chunk(2, -1), i.e.
[q_h | gate_h] PER HEAD, while the forward's fused QKV is [q block | gate block | k | v] --
the layout the FLM/OGA packs already use (their attn_q and attn_gate are separate tensors that
get concatenated).  The converter was a pure rename, so a d3 container kept the per-head order
and the forward attended over half-gate rows and gated with half-query ones.

Measured on the real pack (engine#796, layer 3 = first full attention, last position, bf16
container): engine q slice vs HF q per-head cos 0.0774, vs the block reading cos 0.999992;
gate 0.5989 vs 0.999994; v 0.999964.  After the reorder the whole per-layer chain agrees:
first layer below cos 0.999 goes from 3 (cos 0.452) to none, and /v1/systemone vs the pack's own
d3_runtime.py moves from worst |dp| 0.4140 to 0.0061 with 0/5 choice argmax flips.

The transform needs the pack's own head geometry, so it runs only when config.json declares
attn_output_gate, refuses when num_attention_heads/head_dim are missing, and verify() applies the
same reorder (it compares container against source, so it would otherwise call the fix a loss).
ctest safetensors_to_q4nx covers both, with the row order as a known answer.
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 33eaccc)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

796 - Partially compliant

Compliant requirements:

  • Host-side converter now properly handles non-2-D tensors
  • Name map is correctly handled via the qwen3.5 config
  • Three transforms are now properly implemented and tested
  • Device-side ELF set is referenced and used
  • Host rung is met with proper conversion and loading
  • Device rung is met with proper ELF set usage

Non-compliant requirements:

  • Accuracy rung (labelled evaluation) is not covered in this PR

Requires further human verification:

  • Device rung verification (NPU ELF set usage)
  • Accuracy rung (labelled evaluation)

901 - Partially compliant

Compliant requirements:

  • rmsnorm_offset is now probed for qwen3_5
  • q4nx_rmsnorm_offset_from_norm is exported
  • q4nx_semantics.c now has the probe rule
  • q4nx_forward.cpp resolves the convention and prints evidence
  • tests/npu_rmsnorm_offset_test.c added
  • docs/npu.md updated with convention details

Non-compliant requirements:

  • No device row needed for this fix, but host-GEMM verification is required

Requires further human verification:

  • Host-GEMM verification of the fix

903 - Partially compliant

Compliant requirements:

  • q_proj rows are now de-interleaved in the converter
  • The converter now properly handles gated attention geometry
  • Tests added to verify the de-interleaving
  • Documentation updated with the new transform

Non-compliant requirements:

  • No device row needed for this fix, but host-GEMM verification is required

Requires further human verification:

  • Host-GEMM verification of the fix
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect q_proj de-interleaving logic

The qwen35_transform function in tools/safetensors_to_q4nx.py attempts to de-interleave q_proj rows for gated attention, but the logic assumes that the input tensor w has a shape of [2 * nh * hd, H] where nh is the number of attention heads and hd is the head dimension. However, the actual shape of the q_proj weight tensor in the HF model is [2 * nh * hd, H] where H is the hidden size. The reshape operation v = np.asarray(w).reshape(nh, 2, hd, w.shape[1]) and subsequent concatenation np.concatenate([v[:, 0], v[:, 1]], axis=0).reshape(w.shape) may not correctly handle the tensor layout if the dimensions are not as expected. This could lead to incorrect de-interleaving and thus incorrect attention behavior.

v = np.asarray(w).reshape(nh, 2, hd, w.shape[1])
return np.ascontiguousarray(np.concatenate([v[:, 0], v[:, 1]], axis=0).reshape(w.shape)), None
Missing validation for gate geometry

The gate_geometry function in tools/safetensors_to_q4nx.py extracts num_attention_heads and head_dim from the config, but it does not validate that these values are consistent with the actual tensor shapes. If the config specifies incorrect values, the de-interleaving logic in qwen35_transform could produce incorrect results without any error being raised.

nh, hd, gated = pick("num_attention_heads"), pick("head_dim"), pick("attn_output_gate")
if not gated:
    return None
if not (nh and hd):
    raise SystemExit("config.json says attn_output_gate but gives no num_attention_heads/head_dim; "
                     "the q_proj row order cannot be decided")
return (int(nh), int(hd))

@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 a034d3216. But it is stacked on #902: the first commit here is 7d0ecee27 ("npu: resolve qwen3_5's RMSNorm convention…"), and #902 is still open with my READY. So the order is #902 first, then #904 rebased — merging #904 on today's base carries #902's commit in its squash.

I verified the permutation against the real weights, which is stronger than the body's own evidence. The d3 source is on this box, so I compared the container on disk with the source rows, both directions, rounding the source to bf16 so the comparison is like-for-like:

layer  3  source [4096, 1024]  container [4096, 1024]
  container vs source AS-IS (per-head [q_h | gate_h])   cos=0.138608
  container vs DE-INTERLEAVED (this PR's transform)     cos=1.000000
layer  7   as-is cos=0.186560   de-interleaved cos=1.000000
layer 11   as-is cos=0.158402   de-interleaved cos=1.000000

Bit-exact agreement with the de-interleaving and none with the source order, on three layers of a real 4096x1024 fused q_proj. That also confirms the container built from this branch is the one the reference agrees with.

The consumer's layout is what the converter now produces. Both attention paths read the fused QKV as [q | gate | k | v] by block: host :3289-3296 and device :4283-4290 both set gate_ptr = qkv + nhd and copy k/v from 2 * nhd. So the rows this transform emits are exactly the ones the forward slices.

tests/safetensors_to_q4nx_test.py passes at this head (safetensors_to_q4nx: ok), including the new cases — rows are [q block | gate block], rows are not the source order, the converter prints that it reordered, and a config with attn_output_gate but no head_dim is refused with attn_output_gate in the message.

Checked around the edges too:

  • gate_geometry() reads under text_config first, which matters — I confirmed both the d3 source and the 27B family keep num_attention_heads/head_dim/attn_output_gate nested there, so the hoisted read is not accidental luck.
  • verify() applying the same transform is necessary (it compares container to source, so it would otherwise call the fix a regression) — with the caveat below.
  • Qwen3.5's gated attention has no q_proj.bias (the d3 source has only weights), and a suffix the converter does not know is skipped and counted (skipped N tensor(s)), not silently stored under a reshaped name.

One risk worth naming, one note:

  1. verify() shares the transform, so a systematically wrong permutation would pack and verify green — the guard against that is exactly the measurement above (a real pack against its source), not verify. Fine as long as that is the habit; worth remembering when the next converter fix lands, because verify cannot be the witness for it.
  2. All the 27B packs also declare attn_output_gate=1 (nh 24, hd 256). Nothing on disk changes today — their containers were not produced by this converter and no 27B source is on the box — but the converter decides purely from the config's claim that the source is HF-layout. A source whose q_proj is already [q block | gate block] (e.g. assembled from separate attn_q/attn_gate) would now be de-interleaved a second time, silently, with verify still green. One sentence in the new docs/npu.md row ("only for an HF source with a single fused q_proj; a pack whose q_proj is already block-laid must not be passed through this") would close it cheaply.

I ran no device work: the cos residual table across all 24 layers and the |Δp| 0.4140 → 0.0061 on /v1/systemone are the lane's npu-hold runs, and the owner's serve holds the NPU lock.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit dd0082e

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 2244d03

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 33eaccc

@bong-water-water-bong
bong-water-water-bong merged commit 01e39c8 into main Nov 3, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/903-qproj-deinterleave branch November 3, 2026 14:48
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: a qwen3_5 gated q_proj is per-head [q_h|gate_h] in the pack and block-wise in the forward, so the d3 attention attends over gate rows

1 participant