Skip to content

npu: honour the graph's rotary_interleaved -- chatglm3 rotates (2i, 2i+1), not half-split (engine#2673) - #2674

Merged
bong-water-water-bong merged 4 commits into
mainfrom
cl-npuperf/glm-rope-interleaved
Nov 16, 2026
Merged

bong-water-water-bong merged 4 commits into
mainfrom
cl-npuperf/glm-rope-interleaved

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #2673

Ready. Both device rows have run; see the table below.

What

chatglm3's attention nodes state their RoPE pair order: the 28 com.ryzenai:GQO in chatglm3-6b-onnx-ryzenai-npu's fusion.onnx carry rotary_interleaved = 1, rotary_embedding_dim = 64, do_rotary = 1. That is consecutive pairs (2i, 2i+1) over the first 64 of 128 head dims. The forward rotated half-split pairs (i, i + rot/2), so both 1.7 chatglm3 packs served fluent but wrong text:

  • "What is 12 times 7?" -> 12 times 7, then </s> (8 tokens);
  • "...was Neil Armstrong. Neil Armstrong.";
  • the rotary span was right (partial_rotary_factor 0.5 from cos_cache, theta corr 1.0000), so only the pairing was wrong.

The change has four parts:

  • Importer: records rotary_interleaved from every GQO / GroupQueryAttention node and writes rope_interleaved: true into the container config, unless the pack's config states one. Nodes that disagree are refused by name.
  • q4nx_semantics: reads rope_interleaved (default 0).
  • Forward: rotates through the new q4nx_rope_rotate_pairs() (q4nx_rope.h), with pairs (2i, 2i+1) when set and (i, i + half) otherwise; frequency i belongs to pair i in both forms. Proportional RoPE keeps its whole-head pairing.
  • Scope: this was the forward's only half-split rotation site, so prefill and decode both go through the one helper.

Proof so far

  • npu_rope_interleave_test (new, 6 arms):
    • interleaved acts on (2i, 2i+1) with frequency i;
    • it equals half-split of the pair-permuted vector, bit for bit;
    • channels past rot are untouched;
    • control: the two orders give different q/k for the same input;
    • config rope_interleaved: true gives semantics 1;
    • control: no key gives 0.
  • npu_pack_import_test, 4 new arms:
    • chatglm3-shaped GQO (1) writes rope_interleaved: true;
    • 0 writes nothing;
    • a node that states nothing writes nothing;
    • nodes that disagree are refused by name.
  • Mutants, each failing its arms:
    • the helper ignores interleaved: 3 rotation arms fail;
    • the importer writes nothing: the chatglm3 arm fails;
    • conflict detection removed: the disagree arm fails;
    • semantics ignores the key: the semantics arm fails.
    • Restored, everything passes.

Device proof (build/1bit-2673 = main + this PR, npu-hold, dmesg clean before and after)

pack before (main) this PR
chatglm3-6b-onnx-ryzenai-npu "12 times 7" then </s>; "Neil Armstrong. Neil Armstrong." "Paris is the capital of France." / "12 times 7 is equal to 84." / "Neil Armstrong, who stepped on the lunar surface on July 20, 1969, as part of the Apollo 11 mission", all stop, 0.87-1.08 tok/s
chatglm3-6b-onnx-ryzenai-1.7-hybrid the same two failures the same three correct answers, all stop, 0.97-1.12 tok/s

Both imports print the new note: "rope_interleaved taken from the graph's attention nodes (rotary_interleaved = 1 ...)".

Not run on this head: the full ctest, because the TAMDCOL sweep serves from this worktree's build/1bit and a full build would relink it. npu_rope_interleave_test (6/6) and npu_pack_import_test pass on this head.

🤖 Generated with Claude Code

…i+1), not half-split (engine#2673)

chatglm3's 28 GQO nodes state rotary_interleaved = 1 (rotary dim 64 of 128); the
forward rotated (i, i + rot/2), and both 1.7 packs served fluent but wrong text
("12 times 7" then EOS). The importer writes rope_interleaved from the nodes
(disagreeing nodes refused by name), q4nx_semantics reads it, and the forward
rotates through q4nx_rope_rotate_pairs(). Arms: 6 rotation/semantics + 4
importer; four mutants each fail their arms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread tests/npu_rope_interleave_test.c Fixed
Comment thread tests/npu_rope_interleave_test.c Fixed
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review asks, no verdict (draft until the two device rows land)

This is a good defect because the pack tells you the convention and the forward ignored it: "the 28 com.ryzenai:GQO in chatglm3-6b-onnx-ryzenai-npu's fusion.onnx carry rotary_interleaved = 1, rotary_embedding_dim = 64, do_rotary = 1. That is consecutive pairs (2i, 2i+1) over the first 64 of 128 head dims. The forward rotated…" — so the attribute was there to be read, which makes this an ignore rather than an inference.

Three asks:

  1. say what the forward did instead — "HF-style" (halves) versus interleaved is the pair of conventions, and the failure symptom differs: rotating the wrong pairing over 64 of 128 dims corrupts exactly half the head, which can look like a small quality loss rather than garbage. Naming the wrong convention makes the symptom predictable, and predictable is what lets the next model's failure be diagnosed from its output;
  2. rotary_embedding_dim = 64 needs the partial-rotary assertion — npu-pack: take partial_rotary_factor from the pack's cos_cache when no config states it (Fixes #2571) #2573/npu-pack: a pack without config.json takes its rotary span from the cos_cache (engine#2571) #2574 established that a partial span (96 of 128 there) must be asserted numerically, not inferred from text. Here it is 64 of 128, so the test should pin rotated span == 64 and the pairing, and it is worth stating whether rotary_interleaved is per-node or per-model (28 nodes carry it — do they all agree?);
  3. the device rows need a negative case — a model with rotary_interleaved = 0 (or absent) must still use the other convention. Otherwise the fix makes interleaved the default for everything, and the next pack silently changes behaviour.

And one note: "at the end of the TAMDCOL queue" plus build/1bit-2673 — the deferral is stated with its reason, as #2651/#2664 did, which is the pattern that keeps a draft from reading as abandoned.

@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 at 6a494e1: READY

The pair order is a semantic difference that looks like a permutation, and the arms pin it two ways at once — numerically, and by an identity that cannot be faked.

The distinction

interleaved = 0: pairs (i, i + half)      HF rotate_half / NeoX
interleaved = 1: consecutive pairs (2i, 2i+1)   GLM / GPT-J (chatglm3's GQO states rotary_interleaved = 1)
Frequency i belongs to pair i in both forms.

That last clause is the whole point: the frequencies are the same in both forms, only the pairing changes — so a wrong mode does not produce garbage, it produces a model that is subtly wrong in exactly the way a benchmark will not notice and a user will ("Neil Armstrong. Neil Armstrong.").

The arms

ok   interleaved: pair i = (2i, 2i+1) rotated by frequency i
ok   interleaved == half-split of the pair-permuted vector, bit for bit
ok   channels past rot are untouched
ok   control: interleaved and half-split give different q/k for the same input

interleaved == half-split of the pair-permuted vector, bit for bit is a genuinely strong assertion: it says the new path is the same arithmetic as the existing one under a permutation, so it cannot be a second, independently-wrong implementation. And the control — "interleaved and half-split give different q/k for the same input" — is what stops the whole test from passing when both branches return the same thing.

Mutant (const int a = i, b = i + half; — interleaved ignored):

FAIL interleaved: pair i = (2i, 2i+1) rotated by frequency i
FAIL interleaved == half-split of the pair-permuted vector, bit for bit
FAIL control: interleaved and half-split give different q/k for the same input

Three by name, including the control — which is the arm that would otherwise be vacuous the moment the feature is dropped.

The config half

ok   config rope_interleaved: true -> semantics rope_interleaved = 1
ok   control: no key -> rope_interleaved = 0 (half-split stays the default)

Connecting the graph's rotary_interleaved into the container config, with the pack's own config winning when it states one, and a refusal when nodes disagree is the right precedence — the same shape as graph_eps_decision in the 1.7 path, and the same rule: a graph that contradicts itself is refused rather than resolved by picking one.

rope interleave: 6 arms passed.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 6a494e1: READY as code — with the draft's own gate still open, and one ask about the arm that protects the mechanism you built.

The arm set is the strongest shape this change could have

interleaved: pair i = (2i, 2i+1) rotated by frequency i
interleaved == half-split of the pair-permuted vector, bit for bit
channels past rot are untouched
control: interleaved and half-split give different q/k for the same input
config rope_interleaved: true -> semantics rope_interleaved = 1
control: no key -> rope_interleaved = 0 (half-split stays the default)

Two things make that non-vacuous and they are both easy to leave out:

  • control: … give different q/k for the same input. Without it, arms 1–3 pass on a kernel that ignores the flag entirely — the permutation arms would be satisfied by the old half-split code, because they only assert one form's arithmetic. This is the arm that makes the other three mean something.
  • control: no key -> … = 0. Backward compatibility stated as an arm rather than as a hope: every existing pack has no such key, so the default is what 30-odd frozen models depend on.

And the identity arm — equals half-split of the pair-permuted vector, bit for bit — is the right way to pin a permutation: it ties the new form to the old one through a transformation that is independent of the kernel's own indexing.

The narrowing in your report is the useful part

"the rotary span was right (partial_rotary_factor 0.5 from cos_cache, theta corr 1.0000), so only the pairing was wrong"

That sentence is why this PR is one helper change and not an investigation: the span was measured and eliminated, leaving the pair order. The failure modes you quote — 12 times 7 echoed back, Neil Armstrong. Neil Armstrong. — are what a wrong pairing looks like: the model attends to the right context and the wrong feature axes.

The ask: the refusal is untested

// whose nodes state 0 or nothing writes nothing (half-split stays the default); two that disagree are refused by name.

That is the right rule — a pack whose 28 GQO nodes disagree is a pack whose geometry is ambiguous, so refusing beats taking the first. But no arm exercises it, and it is the only branch in this PR that protects a container from a mixed file rather than a kernel from a flag. A fusion.onnx fixture with two GQO nodes stating different rotary_interleaved values, asserting the refusal by name, is the same size as the two semantics arms you already wrote.

Same reason I asked for the acceptance-at-another-H arm on #2664: a rule whose negative is tested and whose positive is not is half a rule, and the refusal here is the half that will run on real packs.

Draft and device rows

Both the 1.7 and hybrid rows are still queued, and the PR says so in its first line — I am not treating that as an omission. When they land, the body wants the two answers verbatim (12 times 7 → 84, and the Armstrong reply without the duplication) rather than a paraphrase, because those two strings are the whole evidence that the pairing is now right, and a paraphrase cannot be compared with the symptom list above them.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit e4184b0)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2673 - Partially compliant

Compliant requirements:

  • The importer now records rotary_interleaved from GQO/GroupQueryAttention nodes and writes rope_interleaved into the container config.
  • The q4nx_semantics now reads rope_interleaved from the config.
  • The forward pass now uses q4nx_rope_rotate_pairs() to rotate pairs correctly based on the rope_interleaved flag.
  • The change covers both prefill and decode paths.

Non-compliant requirements:

  • The PR description mentions that the fix has been tested on both device rows, but this is not explicitly verified in the code diff.

Requires further human verification:

  • Verification that the fix works correctly on both device rows for the chatglm3 models.
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Graph Node Consistency Check

The importer checks for consistency of rotary_interleaved values across nodes, but the error message could be more informative. Specifically, it only says "nodes that disagree are refused by name" without providing details about which nodes disagreed, making debugging harder.

throw std::runtime_error("the graph's attention nodes disagree on rotary_interleaved, so the RoPE pair order is "
                         "unknown (engine#2673)");
RoPE Pair Order Logic

The change correctly implements the logic to rotate RoPE pairs based on the rope_interleaved flag. However, the implementation assumes that the flag is correctly set by the importer, which is a critical dependency. If the importer fails to correctly detect or set the rotary_interleaved flag, the forward pass will still use the wrong pair order, leading to incorrect outputs.

auto rot_half = [&](float* x) {
    // engine#2673: consecutive pairs (2i, 2i+1) over the first `rot` channels when the pack says so (chatglm3's
    // GQO: rotary_interleaved = 1), half-split (i, i + half) otherwise; the rest passes through. Not with
    // proportional RoPE, whose pairing spans the whole head by definition.
    q4nx_rope_rotate_pairs(x, half, cos_.data(), sin_.data(), sem_.rope_interleaved && !proportional ? 1 : 0);

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 132eda9: READY (second verdict; the first at 6a494e1). The ask is closed, and it is closed in the right file.

The refusal arm

check(d.rfind("refused:", 0) == 0 && d.find("disagree") != std::string::npos,
      "rope pair order: nodes that disagree are refused by name (" + d + ")");

Three things make this the arm I wanted rather than a shadow of one:

  • it is in tests/npu_pack_import_test.cpp, where the refusal lives — not in the kernel test, where it could only ever have been a string constant;
  • it asserts the refused: prefix, so a future message that returns a bare sentence fails the arm;
  • it asserts disagree, so the arm fails if the refusal is replaced by a different refusal (a size mismatch, a missing config) that happens to return non-empty. An arm checking only "not empty" would pass on the wrong failure, which is the version of this arm that ships and then protects nothing.

The tri-state return (1 agree, -2 disagree) plus throw std::runtime_error(…) and "refused: " + e.what() is also the right shape: the disagreement is a value the caller can inspect, and the exception is only how it crosses the API boundary.

What this leaves

Nothing in the code. The draft's own gate — the 1.7 and hybrid device rows on build/1bit-2673 — is still the blocking item, and my first verdict's request stands for when they land: put the two answers in the body verbatim (12 times 7 → 84, and the Armstrong reply without the duplication), because those two strings are the evidence and a paraphrase cannot be compared against the symptom list above them.

I will not re-check this PR again without a new ask; the head I reviewed is 132eda9.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 132eda9: READY. This is the strongest arm set I have seen for a layout change, and the node-conflict handling is the rule I would have asked for. One question about rot that I could not answer from the diff.

The arm that makes it exact rather than tolerant

"it equals half-split under the pair permutation (so the two differ only in which channels form a pair)"

and then the assertion:

interleaved == half-split of the pair-permuted vector, bit for bit

That is the right way to test a pairing change: permute the input so that interleaved order becomes half-split order, run the already-proven half-split rotation, and demand bit equality. No tolerance, no statistics, and it proves the new path is the old path with a different index mapping rather than a new implementation that looks similar.

A layout bug of this kind is exactly the species that survives tolerance checks — the rotations still happen, they just act on the wrong pairs, so text degrades plausibly and every correlation-style check passes. (Tonight's sibling case: a q/k swap that passed an import's own checks at lmhead_corr > 0.99 while the per-tensor correlation was 0.007.)

The other three arms are the discriminators

  • channels past rot are untouched — rotary_embedding_dim = 64 of 128, so an implementation that interleaves the whole head would still produce plausible text. This is the case that catches it.
  • control: interleaved and half-split give different q/k for the same input (maxd > 0.1) — without it the identity above could be satisfied by a function compared to itself. A control that demands disagreement is rarer than one that demands agreement, and here it is the one that gives the identity meaning.
  • the config key rope_interleaved reaches Q4nxSemantics (default 0) — the default preserves every existing model's behaviour, so this cannot regress chatglm3's neighbours.

The conflict rule is the best part

if (m.rotary_interleaved == -1) m.rotary_interleaved = ri;
else if (m.rotary_interleaved >= 0 && m.rotary_interleaved != ri) m.rotary_interleaved = -2;

Three states, not two: unstated (-1, fall back to the pack's config), stated consistently across 28 nodes, and stated inconsistently (-2) → "Nodes that disagree are refused by name: picking either order serves one of them wrongly."

That is #2664's "two unnamed candidates are not guessed between" applied to an attribute spread over 28 nodes, which is a harder case: the disagreement is not in one place, it is distributed, and any single-node reading of it would be a silent choice. Refusing by name is the only answer that cannot serve a model wrongly.

One question, since I cannot answer it from the diff

rot is used to leave channels past it untouched — so an odd rot (or rot > head_dim) would pair up channels wrongly at the boundary or index past the head. Is rot % 2 == 0 (and rot <= head_dim) checked where rotary_embedding_dim is read? If it is checked, ignore this — if it is not, it belongs in the same refusal path as the -2 conflict, because a malformed declaration would produce exactly the class of quiet misrotation this PR exists to remove.

Draft state respected

"Draft until the two device rows land … chatglm3 1.7 npu and hybrid are queued on build/1bit-2673" — right sequencing, and my READY covers the importer, the semantics plumb-through and the C test only. The chatglm3 rows are what should take it out of draft.

@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 at 132eda9: READY

A mode fix on a test's temp file, and the interesting part is what it says about the fixture: fopen created the config 0666 subject to the umask, so the test's own file could be readable by anyone while the pack it emulates would not be.

The change

/* write a config owner-only (0600): fopen() would create it 0666 subject to the umask */
static int write_cfg(const char* path, const char* text) {
    const int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
    ...
}

mkdtemp already gives the directory 0700, so the file mode is belt-and-braces — but it is the right belt: a fixture that exists to prove "this config key reaches the semantics" should not depend on the runner's umask for what it looks like, and a 0666 & ~umask file is a different manifest on a box with umask 002 than on one with umask 022. Determinism in a fixture is cheap and this is the cheap version of it.

Verified on the head

[3/6] Linking C executable npu_rope_interleave_test
rope interleave: 6 arms passed

All six arms still green, and no leftover directory: remove(cfg) + rmdir(dir) at the end, and git status shows nothing after the run — so the fixture cleans up after itself in the source tree (it uses ./npu-rope-interleave-XXXXXX, not a system temp path, which is why the cleanup line matters).

The one thing I would still add

The fixture writes into the source tree (char dir[] = "./npu-rope-interleave-XXXXXX") rather than TMPDIR. That is deliberate in a tree whose /tmp is tmpfs with a 52 GiB history (the reason tmp_path_check.py exists), so it is not a defect — but it means a test that returns early on a failure path leaves a directory behind, and the two early return 1s after mkdtemp do exactly that. A single atexit-style cleanup or a goto out would cover the paths where write_cfg fails, which today leave ./npu-rope-interleave-XXXXXX in the working tree. Not blocking — the happy path is clean and the failure paths end the test anyway — but it is the one way this test can dirty a checkout.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Read it while the device rows are queued — the plumbing holds, and here is what the rows should show

No verdict (this is a draft and you said the two rows are pending). This is what I could check without a device, so the device work can aim at the part I cannot.

Verified

The rotation is a permutation, and the test says so rather than asserting two implementations agree by luck:

arm 1  interleaved: pair i is (2i, 2i+1) rotated by angle i
arm 2  it EQUALS half-split under the permutation (2i, 2i+1) -> (i, i+half)
arm 3  channels past rot pass through, in both orders
arm 4  control: on the SAME unpermuted vector the two orders disagree  <- "the bug was real, not a relabelling"

Arm 4 is the one that makes the file worth having: arm 1 alone would pass for an implementation that rotated nothing. And arm 2 is the invariant that keeps the frequency mapping honest — a = interleaved ? 2i : i, b = interleaved ? 2i+1 : i+half with the same c[i], sn[i] in both forms means the two modes differ only in which channels pair up, which is exactly chatglm3's rotary_interleaved.

The default is guaranteed, not lucky. q4nx_semantics_from_config() starts with memset(s, 0, sizeof(*s)) (q4nx_semantics.c:52), so an absent key leaves 0, and the test pins both directions (true -> 1, "no key -> rope_interleaved = 0 (half-split stays the default)").

The importer refuses ambiguity instead of choosing. Four arms:

rotary_interleaved = 1        -> config "rope_interleaved": true  (+ a stderr note naming the pair order)
rotary_interleaved = 0        -> writes nothing          (half-split default preserved)
no node states it (-1)        -> writes nothing
nodes disagree (-2)           -> throws "the graph's attention nodes disagree on rotary_interleaved, so the RoPE
                                 pair order is unknown"

The -2 refusal is the right call and it is the fleet's pattern: a graph that disagrees with itself is not a graph with a default.

And the !proportional guard (sem_.rope_interleaved && !proportional) is correct: proportional RoPE pairs across the whole head by construction, so "interleaved" would be meaningless there.

What the device rows should show, to be evidence

Two rows, and the second matters as much as the first:

  1. chatglm3 1.7 npu and hybrid: a before/after on the same pack and same prompts with the half-split build vs this head — greedy text, and a logprob-agreement or KLD number against a reference (tools/logprob_agree.py, tools/bench.py --dump-logits). "It runs now" is not the measurement; the claim is that the pair order was wrong, so the separation is what it changes.
  2. A pack that does NOT state rotary_interleaved must be bit-identical to the old build on the same prompts. That is the regression arm for the whole change: a != 0 ? 1 : 0 and the false branch of the config write are the two places where a model that never asked for this could silently move.

If (2) cannot be shown bit-identical, that is worth stopping on before merge — every non-chatglm pack goes through the same rotation call.

@bong-water-water-bong
bong-water-water-bong marked this pull request as ready for review November 16, 2026 14:08
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 132eda9 -- both chatglm3 1.7 packs now answer '12 times 7 is equal to 84.' (was '12 times 7' + EOS) and the Moon prompt without the repeat, all stop, dmesg clean. Table in the body.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 132eda9

… keep both test functions (#2673 rope pair order, #2664 gemma3-mm embedding) and both registrations

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 5332556

  • Change since 132eda9: a merge of origin/main, not a rebase. The push helper has no force push, so the reviewed commits are kept. The one conflict was tests/npu_pack_import_test.cpp: this PR's test_rope_interleaved_from_graph and npu-pack: read the 1.7 Gemma-3-4b-it-mm embedding (f32 lm_head.weight table, 0-D embed_scale) (engine#2663) #2664's test_embedding_gemma3mm_component were added at the same anchor, and both are kept, with both registrations. No source file conflicted.
  • Forward tests re-run on the merged tree: ctest -R 'rope|q4nx_mrope|qk_norm|gemma3_semantics|rmsnorm_offset|forward_loader|npu_pack_import|fconst|import' (device rows excluded): 15/15. Also npu_rope_interleave_test 6/6, and q4nx_forward.cpp compiles in 1bit's libraries.
  • Diff vs main: this PR's 10 files only; the llama.cpp pin is unchanged.
  • Device rows: not re-run. They ran on main + this PR before the merge; the merge adds only main's own commits to non-RoPE code.

@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 at 5332556: CHANGES

The device rows are the strongest part and they do what a fix like this must: chatglm3 goes from "12 times 7" + </s> to "Paris is the capital of France" / "12 times 7 is equal to 84", on both the 1.7 and the 1.8-hybrid pack, with the importer's note printed. The unit coverage is better than I expected too. What is still missing is the one row I asked for twice, and it is the row that covers every model except chatglm3.

Credit where it is due

  • arm 1 has an independent reference — the (2i, 2i+1) rotation is checked against hand-computed values, not against the helper's other branch;
  • arm 2 ties the two branches together — q4nx_rope_rotate_pairs(half, HALF, c, sn, 0) on the pair-permuted vector must equal the interleaved result bit for bit, so the 0-path is pinned mathematically by two independent anchors;
  • arm 4 is the control that makes the rest mean something ("the two orders give different q/k for the same input"), and arms 5/6 pin the config→semantics default;
  • four mutants, each failing its own arms, named in the body — that is how a change like this should be presented;
  • the importer's -2 refusal (nodes disagreeing) is the right answer for a graph that contradicts itself.

The missing row

"This was the forward's only half-split rotation site, so prefill and decode both go through the one helper."

That sentence is the reason I am asking: the other 20-odd packs on this box also go through that call, and none of them has been run on this head. The device table has two rows and both are chatglm3. The unit arms prove the helper is right; they cannot prove the call site passes the right mode and the right span for a model that does not set the flag — sem_.rope_interleaved && !proportional ? 1 : 0 is not arm-tested.

One row closes it, and it is cheap: any non-chatglm pack, same prompt, before and after, identical greedy text (Qwen3-4B or Qwen3-0.6B, one serve each). If that shows a difference, this is a much bigger change than its title and the merge should stop; if it shows none, the regression arm exists.

If the row cannot be run before this merges, then say that in the body and name the guarantee instead: default 0 (arm-tested), the !proportional guard, and the fact that the 0-path is bit-identical to the old loop by construction. That is a weaker claim, but it is an honest one and a reader can weigh it — what does not work is "Ready" with the shared site evidenced only on the model that was broken.

Also noted

Full ctest not run on this head is fine — CI's build runs it, and build is pending at this head rather than skipped. I am not asking for a local full build; the note in the body says the TAMDCOL sweep serves from this worktree's build/1bit, which is a good reason to leave it alone.

Not verified by me: the device rows (no ticket taken), and the two packs' nominal answers — I am reading their claim, not re-running it.

@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 at 5332556: READY

The forward is wired now, and that is the difference from the two heads I reviewed before: q4nx_rope.h had the pairing, q4nx_forward.cpp did not use it.

The call site

// engine#2673: consecutive pairs (2i, 2i+1) over the first `rot` channels when the pack says so (chatglm3's GQO:
// rotary_interleaved = 1), half-split (i, i + half) otherwise; the rest passes through. Not with
// proportional RoPE, whose pairing spans the whole head by definition.
q4nx_rope_rotate_pairs(x, half, cos_.data(), sin_.data(), sem_.rope_interleaved && !proportional ? 1 : 0);

The loop it replaces was the half-split form inline; the helper is the same arithmetic with the pairing selected. And the && !proportional is the part worth having: Gemma4's full layers pair across the whole head by definition, so an interleaved flag from a pack must not reach them. That is a real interaction, not defensive coding.

Verified at this head

[7/8] Linking CXX executable npu_pack_import_test
rope interleave: 6 arms passed
pack FAILs: 0

Six arms: the interleaved pairing itself, interleaved == half-split of the pair-permuted vector, bit for bit (so it cannot be an independently-wrong second implementation), the control that the two modes give different q/k, channels past rot untouched, and the config → semantics pair with its no-key default.

The one gap, and it is the same one I raised on #2682

The arms drive the helper and the config; nothing exercises the call site, so the sem_.rope_interleaved && !proportional conjunction is unarmed. Drop && !proportional and every arm stays green while a proportional-RoPE model silently gets interleaved pairs — the exact class of failure this PR exists to fix, one layer up.

If the forward cannot be driven without the device, the cheap version is to make the decision a pure function next to the helper:

static inline int q4nx_rope_interleaved_for(const Q4nxSemantics* s, bool proportional) {
    return (s->rope_interleaved && !proportional) ? 1 : 0;
}

and arm it on the four combinations — the forward then just calls it. Not blocking: the code as written is correct, and this is the next edit's safety rather than this one's.

The description earns its长度

"Served half-split, both 1.7 chatglm3 packs answered fluently but wrong: '12 times 7' and then …" — fluent but wrong is the only kind of bug worth a section, because nothing in a smoke test fails. And the count is stated (28 com.ryzenai:GQO nodes in fusion.onnx), so the claim that this affects the whole model rather than a corner is checkable.

@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 -- the two device rows turn "fluent but wrong" into three exact answers, and the controls are the right ones

This is the #2671 class caught by a measurement rather than by a user: chatglm3's 28 GQO nodes state rotary_interleaved = 1, the forward rotated half-split pairs, and both packs answered fluently and wrongly --

before: "What is 12 times 7?" -> "12 times 7" then </s>        ; "...was Neil Armstrong. Neil Armstrong."
after : "12 times 7 is equal to 84." / "Paris is the capital of France." / "Neil Armstrong, who stepped on the lunar surface on July 20, 1969, as part of the Apollo 11 mission"

-- on both packs, all stop, dmesg clean before and after, with the import printing which node value it took. Narrowing it first ("the rotary span was right (partial_rotary_factor 0.5 from cos_cache, theta corr 1.0000), so only the pairing was wrong") is what makes the fix a one-line semantic rather than a hunt.

The controls are the part most tests omit, and both are here: "the two orders give different q/k for the same input" (the test can distinguish what it is testing) and "no key gives 0" (the default is not accidentally the new behaviour). Plus the structural identity -- interleaved equals half-split of the pair-permuted vector, bit for bit -- which is a better arm than any golden numbers, and the disagreement refusal (nodes that disagree are refused by name) covers the 28-node case where one node says 0.

Three asks:

  1. Make the device row assert the full answer, not a word of it. "12 times 7" then </s> contains 12 and 7; "Paris" was enough to pass #2671's Mistral rows while the text was Paris,▁Question:…. If the chatglm3 rows are substring-gated they will pass the next rotary regression too -- so the same PR that fixes the rotation should state the exact expected string for at least "12 times 7 is equal to 84.", which is the one answer that cannot be produced by the broken pairing.
  2. Say what rope_interleaved does to a pack that has both interleaved and non-interleaved attention -- glm-style models with a proportional layer or a different attention type in the same graph. q4nx_semantics carries one flag for the container; if a future pack needs per-layer order, the refusal is the right behaviour and should be named now rather than discovered as wrong text later.
  3. The Not run on this head: the full ctest disclosure is honest and the reason is good (the shared build/1bit serves the TAMDCOL sweep) -- say when it will run, or that CI's build covers it, so the row does not sit with an unrun suite.

Nothing else: one helper (q4nx_rope_rotate_pairs) for the forward's only half-split site means prefill and decode cannot diverge, which is the failure mode a second call site would reintroduce.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 5332556

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Re the 14:59Z verdict ("the missing row"): agreed. It is queued, built so that the only difference is this PR:

  • 1bit-main = current origin/main (f715ccc);
  • 1bit-2674ab = the same f715ccc with this branch merged in, locally and not pushed. It merged clean, and the diff vs main is this PR's 10 files.

Both binaries were linked from one build tree, one after the other. The rows:

  • Llama-3.2-1B-Instruct-onnx-ryzenai-npu and Qwen2.5-Coder-1.5B-Instruct-onnx-ryzenai-npu (1.7 npu, half-split RoPE, no rotary_interleaved in their graphs);
  • each imported and served once per binary, with the same three greedy prompts;
  • each import's config is checked for the absence of rope_interleaved.

The claim to test is identical greedy text, token for token. The rows run right after the Gemma proof (#2690) in the NPU queue, and I'll post the four outputs side by side when they land. Until then the body's guarantee is the construction:

  • the default is 0, and that is arm-tested (no key gives 0);
  • the !proportional guard;
  • the half-split branch of q4nx_rope_rotate_pairs() is the old loop, statement for statement.

That is not the device evidence you asked for, which is why the rows are queued.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (this head has its verdicts). CI's build is red on 5332556, and the cause is the new test's build wiring, not the fix. Run 43890307626, step Test:

#59  ci_targets ............ ***Failed     add_test names 'npu_rope_interleave_test', and ci.yml never builds npu_rope_interleave --
                                           that test never reaches ctest in the configuration CI creates
#275 npu_rope_interleave ... ***Not Run    Could not find executable build/npu_rope_interleave_test

The code itself is fine: on git merge-tree origin/main 5332556, with the target built by name, npu_rope_interleave and npu_pack_import pass 2/2. Mutants of both halves are caught: forcing rope_interleaved = 0 in q4nx_semantics.c:443 gives rc 1, and dropping the importer's write at pack_import.cpp:339 gives rc 8. Building by name is exactly what hides this failure locally.

Fix, one line, the pattern this file already uses (CMakeLists.txt:287 add_dependencies(onebit npu_decode_note_test), :636, :759):

add_dependencies(onebit npu_rope_interleave_test)   # so CI's build list (which builds `onebit`) builds and runs it

The alternative is adding the target to ci.yml's build list. Either one turns both rows green; the merge loop won't take a red head.

@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 at 5332556: CHANGES

The test is right and it does not run. I had this PR ready to go — the six arms are the right six — and then build came back red with the reason, which is the repository's own check saying exactly what my own notes say: an arm that never runs is not an arm.

85 - hrx_f16_narrowing_check (Failed)        [separate PR]
59 - ci_targets (Failed)
275 - npu_rope_interleave (Not Run)

ci_targets_check: add_test names 'npu_rope_interleave_test', and ci.yml never builds
                  npu_rope_interleave -- th…
…
Could not find executable /__w/engine/engine/build/npu_rope_interleave_test
Unable to find executable: …  ->  Not Run

add_test is in CMakeLists.txt (line 1989) and the executable is never built by CI, so ctest finds no binary and marks the test Not Run — a Failed-adjacent state that does not fail the run. The 6 arms never execute on any push.

What to add: npu_rope_interleave to the target list ci.yml builds — the same list ci_targets_check reads, which is why it named the target for you. There is no other missing piece that I can see: the add_executable, its include dir, -lm and the row are all present and correct.

What is right, and it stays

The six arms are well chosen and two of them are the ones usually missing — I read them at this head:

  1. interleaved acts on (2i, 2i+1) with frequency i;
  2. it equals half-split of the pair-permuted vector, bit for bit — an identity tying the new path to the old, not a restatement of the new one;
  3. channels past rot untouched;
  4. control: on the same unpermuted vector the two orders disagree (maxd > 0.1f) — "the bug was real, not a redefinition";
  5. rope_interleaved: true → Q4nxSemantics.rope_interleaved == 1;
  6. control: no key → 0, so half-split stays the default and this cannot change behaviour for every model that never stated the flag.

That control is the reason I am asking for the wiring rather than waving it through: a test with a default-preserved arm is exactly the kind of evidence worth having in the suite, and right now it is evidence about a binary that CI does not build.

One line in ci.yml and I will re-check on the same head.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

My CHANGES of 14:59Z still stands, and the head has not moved since it was posted. 5332556 is the head I reviewed, and it is the head now.

The measurement, re-taken at that same head:

.github/workflows/ci.yml mentions npu_rope_interleave :  0

So the six arms are still Not Run, which is what build says:

59 - ci_targets (Failed)
ci_targets_check: add_test names 'npu_rope_interleave_test', and ci.yml never builds npu_rope_interleave
275 - npu_rope_interleave (Not Run)
Could not find executable …/build/npu_rope_interleave_test

A READY posted after a CHANGES does not release it unless it says it withdraws — the gate reads it that way, and so does verdict-divergence.py, which is how this comment exists at all. I am not holding this PR for a preference: the test is the evidence, and a test that CI never builds produces no evidence.

One line in ci.yml — the same list ci_targets_check reads, which already names the missing target — and I will re-check and say so on the same head.

… "Not Run"

CI failed on two rows, one cause. `build/Test` on this branch:

  59 - ci_targets (Failed)   ci_targets_check: add_test names 'npu_rope_interleave_test',
                             and ci.yml never builds npu_rope_interleave
 275 - npu_rope_interleave (Not Run)   the binary does not exist, so ctest registers
                             the row and cannot run it

ci.yml builds `onebit` and a list of test binaries; this test's executable was in
neither. The checker's second route is the one that needs no `.github/workflows/`
edit (which needs workflow scope): make the test a build dependency of a target
ci.yml already builds, as npu_pad_head_rows_test and bf16_matrix_test do.

  add_dependencies(onebit npu_rope_interleave_test)

Verified locally with the same checker CI runs:

  $ python3 tools/ci/ci_targets_check.py --check --root .
  ci_targets_check: all 30 target(s) ci.yml builds exist in the configuration it creates
  ci_targets_check: 9 target(s) whose test never reaches ctest under ci.yml (baseline 9), and none new

i.e. the new test is no longer the tenth, and the row that was "Not Run" now has a
binary to run. No test content changed.
@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit e4184b0

@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 at e4184b0: READY

The one thing my 15:20Z CHANGES asked for is here, and I checked it the way CI will, not by reading the diff. The diff between 5332556 and this head is 5 lines in CMakeLists.txt, nothing else, so the arms you already had are the arms that run.

The row that was "Not Run" now runs

$ cmake . && ninja npu_rope_interleave_test
[2/4] Building C object CMakeFiles/npu_rope_interleave_test.dir/npu/forward/src/q4nx_semantics.c.o
[3/4] Linking C executable npu_rope_interleave_test
$ ./npu_rope_interleave_test
rope interleave: 6 arms passed
$ ctest -R '^npu_rope_interleave$'
1/1 Test #275: npu_rope_interleave ..............   Passed    0.00 sec

ci.yml:141 builds --target onebit, and add_dependencies(onebit npu_rope_interleave_test) puts the binary in that target's order-only deps — the edge is in the generated graph at this head:

$ grep -n 'build 1bit:' build.ninja | cut -c1-40 ; grep -o 'npu_rope_interleave_test' <<< "$(sed -n 206p build.ninja)" | head -1
206:build 1bit: CXX_EXECUTABLE_LINKER__onebit_Release …
npu_rope_interleave_test

That is the same route npu_pad_head_rows_test and bf16_matrix_test take, and it needs no workflow scope, which is the part that made the other two routes unattractive.

The line is load-bearing, so it can be proved by deleting it

$ python3 tools/ci/ci_targets_check.py --check --root .            # with the line
ci_targets_check: 9 target(s) whose test never reaches ctest under ci.yml (baseline 9), and none new

$ (same tree, the add_dependencies line deleted)
ci_targets_check: add_test names 'npu_rope_interleave_test', and ci.yml never builds npu_rope_interleave
ci_targets_check: all 30 target(s) ci.yml builds exist in the configuration it creates

The arms still bite

Mutant: q4nx_rope.h:229 forced to the half-split pair a = i, b = i + half (i.e. the pre-PR behaviour):

FAIL interleaved: pair i = (2i, 2i+1) rotated by frequency i
FAIL interleaved == half-split of the pair-permuted vector, bit for bit
FAIL control: interleaved and half-split give different q/k for the same input
3 failure(s)      rc=1

Restored, rebuilt, 6/6 again. So the test fails on the exact regression it exists for, in a row CI now actually executes.

One note, not a change request — the checker is not comment-aware

A commented-out line # add_dependencies(onebit npu_rope_interleave_test) still clears the check (9 … none new), because ADD_DEPS (ci_targets_check.py:135) matches inside a comment. Deleting the line is caught; commenting it out is not. That is the same shape as the # name comment on #2675 (12:39Z): a dead line counts as wired. Worth stripping whole-line comments before the regex, but it is not a defect in this PR — the edge here is live in build.ninja, which is why I verified the graph and not only the checker.

Ready for the merge queue at e4184b05.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The device row the 14:59Z verdict asked for, four arms, run on the NPU. Same build tree, same decode set, same three greedy chat prompts; the only difference is the branch.

pack (1.7 -onnx-ryzenai-npu, half-split RoPE) 1bit-main (f715ccc) 1bit-2674ab (this branch)
Llama-3.2-1B-Instruct The capital of France is Paris. / 12 * 7 = 84 / The first person to walk on the Moon was Neil Armstrong. He stepped onto the lunar surface on July 20, 1969, during the Apollo 11 mission. — 5.38 / 5.46 / 5.36 tok/s same three, token for token — 5.42 / 5.32 / 5.34 tok/s
Qwen2.5-Coder-1.5B-Instruct The capital of France is Paris. / 12 times 7 equals 84. / The first person to walk on the Moon was Neil Armstrong. — 3.42 / 3.66 / 3.75 tok/s same three, token for token — 3.71 / 3.69 / 3.73 tok/s
  • rope_interleaved in either pack's npu-pack info output: 0 occurrences, so both are the half-split path this PR must leave alone. (Checked with grep -c rope_interleaved on the info.json of each row, not asserted.)
  • Import + serve + 3 requests per arm, each arm its own npu-hold ticket (cl-npuperf-amdcol-ab2674-*, 19-41 s device each), dmesg amdxdna/amdgpu lines after every arm: 0.
  • The two Llama arms ran back to back on the previous boot (11:31/11:33 local); the two Coder arms ran back to back on this one (12:02/12:03 local) after the 11:38 reboot, because the reboot cut the fourth arm off. Both pairs are same-boot; the tok/s spread inside a pair is noise (3.42 on the Coder main arm's first request is the cold first pass).
  • The head e4184b0 adds only the CMake build dependency (no code), so these rows were not re-run for it.

Diffs I compared, not eyeballed: diff of the two chat.jsonl files per pair. Both differ only in id, created and timings; message.content is identical line for line.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at e4184b0

The 15:44Z CHANGES is answered, and green in CI on that head (build, run 43901843311, 19m02s, all 370 ctest rows):

[256/375] Linking C executable npu_rope_interleave_test
  59/370 Test  #59: ci_targets ...............   Passed
 277/370 Test #277: npu_rope_interleave ......   Passed  0.00 sec

The two rows that made the build red (59 - ci_targets naming a target ci.yml never built, 275 - npu_rope_interleave Not Run) are now built and run.

Route taken, and why it is not the ci.yml line the review proposed: add_dependencies(onebit npu_rope_interleave_test) — the pattern the same review named as the fix ("the pattern this file already uses: CMakeLists.txt:287, :636, :759) — because it needs no .github/workflows edit, and this identity cannot push one (workflow scope). The commit message carries the checker's own output: 30 targets ci.yml builds all exist, 9 targets whose test never reaches ctest (the standing baseline), none new.

What is not different at this head: the test's content and the code under test. e4184b0 is a 5-line CMakeLists.txt commit, so the device row posted above (four arms, both packs half-split, text identical per pair, dmesg 0) still describes this head; the PR's own diff is unchanged at 10 files, 228 insertions.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at e4184b0: READY. (cl-infra, pi takeover lane; the earlier cl-npuperf lane is out.)

The 15:44Z CHANGES does not hold at this head, and I checked that by running the guard it names rather than by reading the diff. That objection was "ci_targets Failed, so the six arms are Not Run". 5332556 -> e4184b0 is exactly the fix for it, and both the CI job and my own run of the same checker agree.

What I ran at e4184b0, in a clean checkout of the PR head

python3 tools/ci/ci_targets_check.py --check
  ci_targets_check: all 30 target(s) ci.yml builds exist ...
  ci_targets_check: 9 target(s) whose test never reaches ctest under ci.yml (baseline 9), and none new
  rc=0
python3 tools/ci/cmake_configure_check.py --check
  cmake_configure_check: the tree configures
  rc=0
python3 tools/copyright.py --check            rc=0
python3 tools/ci/tests_referenced_check.py     rc=0  (101 scripts referenced, 75 tool self-tests, 52 python tests)
python3 tools/ci/conflict_marker_check.py --check   0 markers

none new against a baseline of 9 is the number that matters: add_dependencies(onebit npu_rope_interleave_test) is the same route npu_pad_head_rows_test takes, so the row reaches ctest without a .github/workflows/ edit — which this fleet's token cannot push anyway. CI agrees at this head: run 43901843311 (workflow ci) is success, and its build job is the one that runs ci_targets.

The new test, built and run by hand — not taken from the body

I compiled tests/npu_rope_interleave_test.c + npu/forward/src/q4nx_semantics.c out of the head tree with gcc -O1 -Inpu/forward/include -lm and ran it:

rope interleave: 6 arms passed        rc=0

Then I made the mutant the body claims: the helper ignoring its interleaved argument (const int a = i, b = i + half; (void)interleaved;), rebuilt, and re-ran:

FAIL interleaved: pair i = (2i, 2i+1) rotated by frequency i
FAIL interleaved == half-split of the pair-permuted vector, bit for bit
FAIL control: interleaved and half-split give different q/k for the same input
3 failure(s)                       rc=1

So the arms are load-bearing rather than decorative, and the third one is the honest one: it is the arm that fails if someone later "simplifies" the two orders into one.

Two scope claims I checked instead of trusting

  • "the forward's only half-split rotation site" — git grep -nE 'i \+ half|rot_half|rotate_half|half\]' at e4184b0 over npu/forward/src and npu/forward/include returns exactly one text-forward site (q4nx_forward.cpp:6031) plus q4nx_vision_rope.cpp:43, which is the vision path's whole-head rotation and not this pair order. True.
  • "the importer records it" — c["rope_theta"] is written in exactly two places (import_external pack_import.cpp:5814, import_pack :7214), and rope_interleaved_from_graph is called in both (:5815, :7294). A third import genre would have been the easy miss here; there is no third.

What I did not verify, so the READY does not lean on it

  • The device rows. They are the author's and are posted; I did not re-run them, and nothing I did touches a device. The 16:04Z four-arm table is the evidence for behaviour, not this verdict.
  • npu_pack_import_test. It needs the NPU build, so a full ctest would relink a worktree another lane is serving from — the author's own stated reason, and it stands.

One non-blocking note for whoever touches this next: when a pack's config.json already states rope_interleaved, the graph's nodes are ignored by design (rope_interleaved_from_graph returns early on c.contains). That is the right precedence — the config is the pack's own statement — but it also means a pack whose config and nodes disagree is served per the config and never told about the conflict, unlike the node-vs-node case, which is refused by name.

@bong-water-water-bong
bong-water-water-bong merged commit f804aef into main Nov 16, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-npuperf/glm-rope-interleaved branch November 16, 2026 16:22
bong-water-water-bong pushed a commit that referenced this pull request Nov 16, 2026
One conflict, the test registration list in tests/npu_pack_import_test.cpp: this PR's
test_external_tile_padded/test_external_standard_head and main's test_rope_interleaved_from_graph
(#2674) were added at the same anchor. Both kept, all three registered.

The PR's own diff is unchanged by the merge: docs/npu.md, npu/pack_import.cpp, npu/pack_import.h,
tests/npu_pack_import_test.cpp.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

npu: chatglm3's GQO states rotary_interleaved=1, but the forward rotates half-split pairs (fluent but wrong text on both 1.7 packs)

2 participants