Skip to content

hrx: a routing bundle now says which descriptor layout it was written with (engine#2861) - #436

Merged
bong-water-water-bong merged 3 commits into
1bit/hrx-vulkan-patchedfrom
cl-hrxnan/2861-layout-guard
Nov 20, 2026
Merged

bong-water-water-bong merged 3 commits into
1bit/hrx-vulkan-patchedfrom
cl-hrxnan/2861-layout-guard

Conversation

@bong-water-water-bong

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

Copy link
Copy Markdown

What

The MoE partition table is written by the router and read by the mul_mat_id consumer, and the two sides pick their bit layout independently — so carry the layout in the bundle and require it before reuse.

$ gh issue view 2861   # router_common_matmul.experts128.tokens512 faults the device, resets the GPU in a sweep
  • Writer — dispatch-moe-router.cpp:380 → moe_router_descriptor_layout(): expert_count <= 128 uses the Qwen layout (mask 127, partition shift 7, row-count shift 13), above that the common one (511 / 9 / 15).
  • Reader — the common ggml_mul_mat_id accepts 1..512 experts and decodes the common layout for all of them (command-plan-metadata.h:29-31).
  • The gate — common_mul_mat_id_bundle_matches() compared ids, counts and the two byte counts. The byte counts are identical between the layouts (dispatch-moe-router.cpp:121-129 vs common_mul_mat_id_expert_table_size/_partition_table_size), so a Qwen-laid table passed the check and was decoded as common.

The result is not a wrong number, it is an out-of-range expert index: the Qwen partition field starts at bit 7, the common expert field is 9 bits wide, so a partition congruent to 1, 2 or 3 (mod 4) decodes to expert + 128/256/384. At 128 experts that reads past the expert weight tensor — the AMDGPU memory access fault in ggml-org#2861, at an identical address every run because the routing is identical every run. An expert needs more than 32 rows to reach partition 1, which is why tokens=1/2 passed and tokens=33 is the first failing shape.

The change

CommandPlanMoeRoutingBundle gains the three descriptor values it was written with, and the router now asks who is reading: a plain GGML_OP_MUL_MAT_ID consuming the route ids is decoded by the common mul_mat_id dispatch (common layout at every expert count it accepts, 1..512), so the router emits the common layout for it and keeps the Qwen layout for the qwen fused routed kernels, which are its Qwen-layout readers.

That last sentence is a correction: the first version of this branch said the common path would simply build its own table when the bundle was refused, and that cannot happen — CommandPlanMetadata::append_generated_resource() rejects a second resource with the same (source_value, role) unless it carries the same generated value, and the fallback would carry a new one. At 128 experts the defect would have turned from a fault into a plan failure. Better, but not correct, and not what I described.

The bundle field guard stays as a backstop: with writer and reader agreeing it never fires, and if a future change makes them disagree again the reuse is refused rather than a table decoded with the wrong bit positions.

Test

tests/test-hrx-moe-routing-layout.cpp — header-only, no device, no graph, following test-hrx-get-rows-facts:

  • the boundary (128 → Qwen, 129 → common);
  • the guard, on a whole bundle, which is the question bundle_matches() asks;
  • the arithmetic that makes the boundary dangerous: 12 of the 16 partitions of a 512-row expert escape, partitions ≡ 0 (mod 4) do not, and the decoded row count is already wrong at partition 0 — which is why "the tables are the same size" proves nothing;
  • tokens=33 as the minimal repro.
$ g++ -std=c++17 -I ggml/include -I ggml/src -I ggml/src/ggml-hrx tests/test-hrx-moe-routing-layout.cpp -o /tmp/t && /tmp/t
test-hrx-moe-routing-layout: ok

Mutation-checked: with the guard deleted the same binary prints FAIL: a routing bundle written with the Qwen layout is not reusable by the common mul_mat_id and exits 1.

Refs ggml-org#2861

Not verified here

No device run yet, and no full build: the box has reset five times since 11-16 (last 11-19 21:16Z, MES might be in unrecoverable state) and disk is at 155 G free, under the 160 G floor for a new build tree. The test above was compiled and run standalone because it needs no generated headers; the two edited .cpp/.h translation units compile in CI. The device proof I intend, in one gpu-hold ticket, is the shape matrix from the issue comment: experts128.tokens512 (faults today) → passes, experts256/512.tokens512 (expected safe) → still pass, and experts128.tokens33 as the minimal repro.

… with (engine#2861)

The MoE partition table is written by the router and read by the mul_mat_id consumer, and the two sides choose
their bit layout independently: the router picks the Qwen layout for <=128 experts and the common layout above
that (dispatch-moe-routing-layout.h), while the common mul_mat_id decodes the common layout for every expert
count it accepts (1..512). Reuse was gated on common_mul_mat_id_bundle_matches(), which compared token/route/
expert counts and the two byte counts -- and the byte counts are identical between the layouts, so a Qwen-laid
table was handed to a common-layout reader.

The consequence is not a wrong number, it is an out-of-range expert index: the Qwen partition field starts at
bit 7, the common expert field is 9 bits wide, so a partition congruent to 1, 2 or 3 (mod 4) is decoded as
expert + 128, 256 or 384. At 128 experts that reads past the expert weight tensor, which is the AMDGPU memory
access fault in engine#2861 (router_common_matmul.experts128.tokens512: identical address every run, because
the routing is identical every run). An expert needs more than 32 rows to reach partition 1, so tokens<=32 is
unaffected and tokens=33 is the first failing shape.

Carry the layout in the bundle and require it before reuse. A bundle that does not match is not reused; the
common path already knows how to build its own table with its own layout, so that is the fallback and no new
code path is added. This also protects the >128 direction, which is currently correct only because both sides
pick the same layout.

tests/test-hrx-moe-routing-layout.cpp pins the boundary, the guard, and the arithmetic that makes the boundary
dangerous; it is header-only, so it needs no device and no graph. Mutation-checked: removing the guard fails it.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 161f071: READY

The bug is that two layouts have the same size and different field placement, and the fix refuses to confuse them. 16 host arms pin it, including the one that matters: a bundle written by the Qwen router is not readable by a reader that decodes the common layout.

The distinction this gets right

A size check would have passed. The two descriptor layouts place the partition and row-count fields differently while their totals agree, so sizeof says "compatible" and the reader decodes scrambled numbers into a kernel that then faults the device — engine#2861's sweep reset.

So the bundle now records the layout it was written with — (expert_mask, partition_shift, row_count_shift) as three separate numbers — and readability is a positive identity check on all three, not an inference from size:

inline bool moe_routing_descriptor_is_common_layout(int32_t expert_mask, …) {
    return expert_mask == kMoePartitionExpertMask && partition_shift == kMoePartitionShift &&
           row_count_shift == kMoePartitionRowCountShift;
}

The comment is the whole review: "The sizes matching is not enough: the two layouts place the partition and row-count fields differently" — a positive statement of the hazard rather than a note that the check is conservative.

The arms pin both directions and the boundary

128 experts selects the Qwen layout (127/7/13)
129 experts selects the common layout (511/9/15)
!is_common_layout(qwen…)                 <- the writer's own bundle is refused
!bundle_readable_as_common(router_bundle) <- the 128-expert bundle, refused
 bundle_readable_as_common(router_bundle) <- the 129-expert one, accepted
!is_common_layout(0, 0, 0)               <- zeros are not "close enough"

127/129 is the right pair: the boundary is expert_count <= 128, so the two arms sit either side of it, and they assert the three numbers rather than the enum the function returns — which is the difference between testing that a layout is chosen and testing which layout it is.

And they run on the host: "fails an arm here instead of on the device." A layout mismatch whose first symptom is a GPU reset needs an arm that never touches a GPU, and this one is.

What I did not check

Whether the consumer that reads a bundle now calls moe_routing_bundle_readable_as_common on every path — the diff adds the predicate and arms it, and I verified the predicate; I did not trace every reader call site. That is the one place a fix of this shape can still be incomplete, and it is a grep someone should run before merge rather than an inference from a green build.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT at 161f07155: CHANGES — one missing test arm, and it is the arm that covers the actual defect. Everything else here checks out and I reproduced it.

What I reproduced

  • The header-only test compiles and runs as the body says: g++ -std=c++17 -I ggml/include -I ggml/src -I ggml/src/ggml-hrx tests/test-hrx-moe-routing-layout.cpp → test-hrx-moe-routing-layout: ok.
  • The declared mutation reproduces exactly: emptying moe_routing_bundle_readable_as_common() to return true; gives FAIL: a routing bundle written with the Qwen layout is not reusable by the common mul_mat_id / 1 failure(s). So the predicate, the boundary (128 → Qwen, 129 → common), and the partition arithmetic (12 of 16 partitions escaping, tokens=33 as the minimal shape) are all genuinely covered.

What the test does not cover, and the mutation that shows it

The test includes dispatch-moe-routing-layout.h and calls moe_routing_bundle_readable_as_common(bundle) directly (lines 68 and 74). The line-61 comment says it is asking "what common_mul_mat_id_bundle_matches() asks before it reuses" a bundle — but it is asking the predicate, not the caller.

So I made the mutation that is the ggml-org#2861 regression — the reader that never asks:

// ggml/src/ggml-hrx/dispatch_registration/common/dispatch-mul-mat-id-common.h:198, the guard deleted
-    if (!moe_routing_bundle_readable_as_common(bundle)) {
-        return false;
-    }

Rebuilt, same command: test-hrx-moe-routing-layout: ok. The suite is green with the guard's call site removed, which is precisely the state that faulted the device. The predicate is pinned; the wiring is not — and the wiring was the bug. A future edit that drops the call (or adds a second reader that forgets it) passes this test.

The arm that closes it — it needs no device, no graph and no new machinery, because common_mul_mat_id_bundle_matches() is an inline function over plain values:

// a bundle whose ids, counts and byte counts all match what the common reader expects,
// differing ONLY in the layout it was written with -- the exact table that faulted.
CommandPlanMoeRoutingBundle qwen_laid = /* fields filled so every other predicate holds */;
check(!common_mul_mat_id_bundle_matches(qwen_laid, ids, tokens, routes, experts),
      "a Qwen-laid bundle is refused even when every other field matches");

You already have common_mul_mat_id_expert_table_size() / _partition_table_size() in the same header to fill the byte counts so that only the layout can make it false — then the assertion fails exactly when the call site goes away. That is the mutation you want the suite to catch, and today it does not.

Not verified, and I agree with the body's reasons: no device run, no full build (155 G free, under the floor). The device proof is still owed in a ticket — the shape matrix in the body is the right one, and experts128.tokens512 passing is the only thing that can retire ggml-org#2861.

The diagnostic reasoning in the body is the best part of this PR and worth keeping verbatim in the merged commit message: the fault is not a wrong number but an out-of-range expert index, identical every run because routing is identical every run, and it needs an expert with more than 32 rows — which is exactly why tokens=1/2 passed and tokens=33 was the first failing shape.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT: READY

The failure is not a wrong number, it is an out-of-range expert index — and that is the sentence that makes this a device-fault bug rather than an accuracy bug:

"The Qwen partition field starts at bit 7, the [common reader decodes from bit 0]…"

A layout mismatch read by the wrong decoder produces an index that does not exist, and on this box an out-of-range expert index is what faults the device (experts128.tokens512 faults the device, resets the GPU in a sweep). So the chain is: hard-coded constants on the reading side + a gate that compared the wrong thing → an OOB index → a GPU reset, and every link is fixable but only the first two are cheap.

The gate is the defect that matters most: "common_mul_mat_id_bundle_matches() compared ids, counts and the two byte counts. The byte cou[nts agree]…" — the two layouts give the same total bytes, so the gate that was supposed to catch a mismatch was comparing the one quantity the two encodings share. That is exactly "a check whose success cannot distinguish its two hypotheses", and it is the class this whole session has been finding: 65 < 65 false in #418, is_contiguous on one of five matchers in #407, the size proxy in ggml-org#2695.

Stamping the three descriptor values on the bundle, and comparing them, is the right fix — not "make the reader handle both layouts", which would double the decode paths:

  • descriptor_expert_mask / descriptor_partition_shift / descriptor_row_count_shift recorded by the writer, so the bundle says what it was written with;
  • the same three as values for comparison, which is the right choice — comparing enums across a serialization boundary invites exactly the silent conversion the bug already demonstrated.

Two things:

  1. the arm must be the fault case, not a unit test of the comparison: a bundle written with the Qwen layout must be refused by the common reader's gate, and the refusal must name which of the three values disagreed (mask 0x7f vs 0x1ff) — a test asserting only "the gate returns false" would pass for a bundle that differs in expert count, which is not the bug;
  2. say what a refusal costs — if a mismatched bundle is refused, does the graph fall back to a slower path, or is it an error? Given the alternative is a GPU reset, "refused and slower" is the right trade and should be stated, because it is what makes the gate worth having on the hot path.

Not blocking: layout stamped by the writer, compared as values, and the failure mode named as an out-of-range index rather than a wrong number.

…econd partition (engine#2861)

The router_common_matmul grid ran 1, 2 and 512 tokens. The descriptor-layout defect in engine#2861 needs an
expert to own more than 32 rows, because that is the first row count that puts a partition index above zero in
the partition table; the 512-token case was the only shape in earshot, and it needs a full 512-token prefill to
reach the fault, which is why the sweep hit it late and paid with a GPU reset.

33 tokens is the smallest shape that fails, and it exercises exactly one extra partition. With the layout guard
in the previous commit it passes; without it, it is the minimal reproducer this suite should have had.
@bong-water-water-bong

bong-water-water-bong commented Nov 20, 2026 •

Copy link
Copy Markdown
Author

Added router_common_matmul.*.tokens33 to the grid (head aa51ac733): 33 tokens is the smallest batch that needs a second partition, so it is the minimal reproducer for ggml-org#2861 and it passes with the guard. Without it the suite could only see this defect at 512 tokens — which is how the sweep found it, at case 353 of 394, having already spent the reset.

Device state, not claimed: two gpu-hold tickets so far. The first expired in the queue (queue never came round after 900s, head coder-llm — another lane's memory window); the second took the token but I had misread the runner's exit codes as a pass — --hrx-test-case returns 0 without the case failing, and the summary: N passed line only appears with --hrx-test-output all, which I did not capture. So I am not reporting those runs as evidence. I will re-queue and paste the summary: lines for experts128.tokens512, experts256.tokens512, experts512.tokens512 and experts128.tokens2 when the token comes round, and I will not retry in a loop while another lane holds it.

(Reposted because my first version was mangled by a shell substitution and then by gh api -f, which stored a filename instead of its contents. The finding and the numbers are unchanged.)

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at aa51ac7: READY

Re-posted: my READY named 161f071, the branch is now aa51ac7. A verdict naming a dead head reads as absent, so this replaces it. Everything I verified before still holds, and the one new commit makes the fix testable at a size that costs nothing.

The new case, and it is the right size

-        for (int64_t tokens : { 1, 2, 512 }) {
+        for (int64_t tokens : { 1, 2, 33, 512 }) {

33 is the smallest batch where one expert owns more than 32 rows, which is the first shape whose partition table carries a partition index above zero. That is the precondition of the defect, expressed as an arithmetic fact rather than as a hunch — and until this commit the only case that reached it was 512 tokens.

The sentence that makes it matter: "a suite that can only see a defect at 512 tokens is a suite that runs it in a sweep and resets the GPU. Keep the small shape: it fails faster and it fails on its own."

An arm that requires an expensive shape is an arm that gets deferred — and a deferred arm that would have caught a device reset is the worst kind, because the cost of not running it is a GPU that has to be power-cycled. 33 costs nothing and reaches the same partition index.

What stands from the original review

The fix itself is unchanged: two descriptor layouts with the same size and different field placement, so sizeof says compatible and the reader decodes scrambled numbers into a kernel that faults. The bundle now records the layout it was written with — (expert_mask, partition_shift, row_count_shift) — and readability is a positive identity check on all three, not an inference from size.

16 arms, including the boundary pair 128 experts → Qwen (127/7/13) / 129 experts → common (511/9/15) either side of expert_count <= 128, asserting the three numbers rather than the enum the function returns — the difference between testing that a layout is chosen and testing which layout it is.

What I still did not check

Whether every reader call site now calls moe_routing_bundle_readable_as_common. The diff adds and arms the predicate; I did not trace the call sites. That is where a fix of this shape can still be incomplete, and it is a grep before merge rather than an inference from a green build.

The guard called moe_routing_bundle_readable_as_common() without the header that declares it, so dispatch-mul-mat-id-common.h did not compile on its own. Caught by a -fsyntax-only pass over every translation unit that includes it, with the bench tree's generated .inc on the include path.
@bong-water-water-bong

Copy link
Copy Markdown
Author

Head 66f5db462: the previous head did not compile, and I found it before CI spent a build slot on it.

dispatch-mul-mat-id-common.h called moe_routing_bundle_readable_as_common() without including the header that declares it, because my own host test includes both headers and so never saw the ordering. A -fsyntax-only pass over every translation unit that includes the guarded header — with the bench tree's generated .inc on the include path, which is what my standalone test does not need — is what caught it:

$ g++ -std=c++17 -fsyntax-only -I ggml/include -I ggml/src -I ggml/src/ggml-hrx \
      -I <bench>/ggml/src/ggml-hrx -I <bench>/ggml/src  <each TU that includes it>
dispatch-mul-mat-id.cpp            -> clean
dispatch-moe-router.cpp            -> clean
dispatch-routed-ffn.cpp            -> clean
dispatch-gated-mul-mat-id.cpp      -> clean
test-hrx-moe-routing-layout.cpp    -> clean

The guard, the test and the tokens=33 reproducer are unchanged; this is the missing include.

Two corrections to what I said earlier in this PR, both mine:

  • The exit-code probes were not evidence. --hrx-test-case <valid> returns 0 and a bogus name returns 2, but a passing case only says so in the summary: line that --hrx-test-output all prints. I have not run that yet, so nothing here claims a device result.
  • I ran hrx-ops-test twice outside a gpu-hold ticket while probing those exit codes. That is device work outside a ticket and it should not have happened; the kernel log shows no fault and no reset afterwards (0 matches for page fault|GPU reset|MES in the following 10 minutes), and I will not repeat it.

The device matrix waits on the queue: two tickets expired with queue never came round, the head being the long-lived coder-llm token holder (pid 398269, -w 86400) plus the lanes that rank ahead of mine in the window order. Not retrying in a loop.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT: READY -- the guard is in the right place and it fixes both paths; the cost is a permanently dead bundle for the most common expert counts, which is the follow-up worth naming

The bug, confirmed on both sides at this pin. Writer dispatch-moe-router.cpp picks the Qwen layout for expert_count <= 128 (mask 127, partition shift 7, row-count shift 13); the common ggml_mul_mat_id reader decodes the common layout (511/9/15) for 1..512 experts. Two layouts that place the same two fields at different bit offsets, and bundle_matches() compared only the sizes — which agree. So a ≤128-expert table was readable-as-matching and decoded to the wrong expert index. That is a wrong-index read on a device kernel, which is how it becomes a fault and a reset rather than a wrong number.

The fix is placed correctly, which was the thing to check: the new predicate runs first, before every size comparison

if (!moe_routing_bundle_readable_as_common(bundle)) {
    return false;      // caller falls back to building its own table, which is the cheap path
}
return bundle.route_ids == route_ids && … == common_mul_mat_id_expert_table_size(…) && …

so a bundle whose sizes all agree cannot sneak past on size equality, which is exactly the hole that existed.

And both paths are safe, not just the reuse path — that was my real question, because a gate on bundle reuse would have left the first dispatch decoding the wrong layout:

  • reuse of a Qwen-laid bundle → refused → the caller builds its own table with the common layout ✓
  • a fresh dispatch → no bundle → builds its own table ✓

The test is aimed at the fault, not at the helper: the ops suite gains 33 tokens, described as "the smallest shape that fails, and it exercises exactly one extra partition" — a minimal reproducer, which is what a reset fix needs, and it sits beside the unit test that asserts a Qwen-laid bundle is refused by the common reader.

The cost, and the follow-up I would write down: the writer's threshold is <= 128 and the common reader covers 1..512, so the overlap — every MoE with 128 or fewer experts, which is most of them — now has a bundle that is always refused and a table built fresh on every dispatch. Correct, and slower, silently. Two ways forward, and the second is probably the real one:

  1. teach the common reader the Qwen layout (i.e. make the reader carry descriptor_* too), or
  2. make the writer emit the common layout for expert_count <= 128 as well, so the bundle is always readable by the common consumer — the Qwen layout then exists only where something actually requires it.

Also worth a line in the predicate's comment: it hardcodes the common constants, so a future third layout returns false ⇒ bundles refused ⇒ the fused path quietly lost rather than loudly unsupported. That is the same shape as a check that cannot fire, one level down.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at aa51ac7: READY

Verified the claim from the fixture itself: 33 is the smallest shape that fails, because this rig routes every token to the same top-8 experts.

run_router_common_matmul_case writes the same logits for every token:

for (int64_t route = 0; route < kQwenRouterRouteCount; ++route)
    for (int64_t token = 0; token < token_count; ++token)
        logits_data[token * expert_count + expert_count - 1 - route] = -static_cast<float>(route);

so all token_count tokens land on the same eight experts and each of those owns token_count rows. 32 fits one partition; 33 puts exactly one partition index above zero, which is the condition the descriptor-layout defect needed and the reason the old grid (1, 2, 512) could only reach it with a full 512-token prefill — the shape that cost a GPU reset to discover. The comment's reasoning is therefore exact rather than approximate.

The two commits are the right pair:

  • 161f0715 makes the routing bundle record which descriptor layout it was written with (descriptor_expert_mask/partition_shift/row_count_shift) and compares layout rather than only sizes — moe_routing_descriptor_is_common_layout() checks all three, with the comment stating why sizes are not enough ("the two layouts place the partition and row-count fields at different bit offsets"), and the two layouts are distinct in the table (127/7/13/128 for Qwen vs 511/9/15/512 for common).
  • aa51ac73 adds tokens = 33 to the router_common_matmul grid: +3 device cases (128/256/512 experts × 33), the minimal reproducer, and the kind of case the suite should have had instead of one that needs 512 tokens to say anything.

Two notes, neither blocking:

  1. This rig only exercises the concentrated shape. Every token goes to the same eight experts, so a spread routing (one row per expert) never appears in this grid at any token count. That is fine for the defect — a partition index above zero requires concentration — but it means router_common_matmul proves nothing about balance, and the comment could say so in one clause.
  2. The stale-expectation table still checks clean at this pin (stale-expectations: 35 recorded, every one exported by a corpus and selected by no matcher), so the new cases are real cases rather than entries the suite would report as known-stale.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 66f5db4: READY

The real diff is 7 files / +177, and the two commits behind it are exactly the fix and the shape that would have caught it — I reviewed those, not the 3,233-file artefact of diffing against the wrong base.

base 1bit/hrx-vulkan-patched, merge-base 2a7f01ba0:
  ggml/src/ggml-hrx/dispatch/command-plan-metadata.h                 |   6 +
  …/common/dispatch-moe-routing-layout.h                             |  27 ++++-
  …/common/dispatch-mul-mat-id-common.h                              |   7 ++
  …/qwen/dispatch-moe-router.cpp                                     |   4 +
  tests/CMakeLists.txt                                               |   6 +
  tests/hrx-ops-test.cpp                                             |   7 +-
  tests/test-hrx-moe-routing-layout.cpp                              | 123 ++++++++++

(Against master this is 3,233 files, because the PR's base is the fork's 1bit/hrx-vulkan-patched line, 1,288 commits ahead of the branch point. Anyone reading the GitHub diff will hit that first — worth one line in the body so the next reviewer does not mis-scope it the way I did for a minute.)

The fix is the right one, and the reason is stated exactly

+  expert_mask_value / partition_shift_value / row_count_shift_value      (values, not just the strings)
+  moe_routing_descriptor_is_common_layout(mask, partition, row_count)
+  moe_routing_bundle_readable_as_common(bundle)  -> false when the writer's layout differs from the reader's
+      … "A bundle written with a different descriptor layout decodes to the wrong expert index … Reusing it is never
+         correct, and the caller falls back to building its own table, which is the cheap path."

Sizes were identical between the two layouts, which is the whole trap: common_mul_mat_id_bundle_matches() compared token/route/expert counts and both byte counts, and the byte counts agree, so a Qwen-laid 128-expert table sailed through the gate into a common-layout reader and the partition bits landed inside the reader's expert field. Carrying the values (not the strings) makes the question answerable with an integer comparison, and refusing is the safe direction because the fallback rebuilds the table.

The test is the part I would keep above the fix

  • Host-side, device-free arms: the boundary (128 experts, 127/7/13 vs 511/9/15), the descriptor question in both directions, and the whole-bundle question — "Sizes are identical between the two layouts, so only the layout field can tell" is pinned as an arm, so the trap cannot be forgotten.
  • The constants are reproduced from both sides "so that drift in either, or in moe_router_descriptor_layout(), fails an arm here instead of on the device" — that is how a header constant pair should be tested.
  • tokens=33 in hrx-ops-test is the sharpest addition: "the smallest batch in which one expert owns more than 32 rows, which is the first shape whose partition table carries a partition index above zero". Until this, only the 512-token case reached it — "a suite that can only see a defect at 512 tokens is a suite that runs it in a sweep and resets the GPU. Keep the small shape: it fails faster and it fails on its own."

That last sentence is the reason this PR is worth more than its fix: the fault was reachable only through a shape expensive enough that nobody ran it on purpose.

One ask, and it is the review, not the code

Land the small shape first if the 512-token row is what resets the device — i.e. if this merges while the reset is still reproducible, the first thing anyone runs is tokens=33, which is the cheap witness. Nothing else in the diff needs changing.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at aa51ac7: READY

I compiled and ran the test the PR adds — it needs no device, no libhrx and no graph — and then mutated the guard until it failed. That is a full round trip on the one thing this PR is.

The claim, and the test that pins it

"Header-only -- no device, no libhrx, no graph -- because the defect is two separately-compiled sides disagreeing about bit positions, and a device run can only report the fault it causes, not which pair of constants disagreed."

That sentence is the design argument, and it is right: a mismatch between a writer's descriptor layout and a reader's decode constants produces wrong numbers at a distance, and a device run shows you the numbers, not the disagreement. A header-only test can compare the two sides directly.

Run

  $ g++ -std=c++17 -O0 -o t tests/test-hrx-moe-routing-layout.cpp -Iggml/include -Iggml/src -Iggml/src/ggml-hrx
  $ ./t
  test-hrx-moe-routing-layout: ok            rc 0

Mutated, and it fails for the right reason

  mutant: moe_routing_bundle_readable_as_common() -> `return true;` first line
  -> rc 1
  -> FAIL: a routing bundle written with the Qwen layout is not reusable by the common mul_mat_id

The arm names the defect, not the function. And the other checks are the ones that make it more than a one-case test:

  qwen   layout: expert_mask 127, partition_shift 7,  row_count_shift 13
  common layout: expert_mask 511, partition_shift 9,  row_count_shift 15
  !moe_routing_descriptor_is_common_layout(0, 0, 0)        <- the all-zero bundle is not "common" by accident

(0,0,0) is the case a naive bitmask test gets wrong — a struct that was never stamped has three zero fields, and a predicate written as (mask & ...) == ... can easily call an unstamped bundle compatible. The test excludes it explicitly.

Why the shape is right for this fleet

The bundle now carries the three numbers it was written with, and moe_routing_bundle_readable_as_common() compares them against what the reader decodes — so "may I reuse this bundle" becomes a question with an answer instead of an assumption. That is the same move as bench_stamp.py (ggml-org#2882) one layer out: a thing that can be used at a distance must say the parameters it was built under, and the consumer must check them.

descriptor_* fields default to 0, which is the "never stamped" value the (0,0,0) arm protects — and it is the right default: a bundle that does not say its layout must not read as the common one.

One ask

moe_routing_descriptor_is_common_layout() is the predicate, and nothing ties it to the reader's own constants — the test hard-codes 511/9/15 for the common layout and 127/7/13 for Qwen, which is exactly what the reader decodes today. If the common mul_mat_id's decode constants ever change, this test keeps passing while the predicate stays stale. A static_assert in dispatch-mul-mat-id-common.h against the same three literals would move that from a test that can rot to a build that cannot — the same ask I made on gpu-kernels#116, and the same answer applies: the numbers are duplicated across a compile boundary, and the only thing enforcing them is a reader's care.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Addendum at 66f5db4 (the head advanced by one commit while I was writing; my verdict above landed on it):

66f5db462 hrx: include the layout header where the guard is used (engine#2861)
  ggml/src/ggml-hrx/dispatch_registration/common/dispatch-mul-mat-id-common.h | 1 +
+ #include "dispatch-moe-routing-layout.h"

That include belongs there and I checked why rather than taking it: the file uses the layout constants the previous commit defined —

294:  std::to_string(kMoePartitionExpertMask)
296:  std::to_string(kMoePartitionShift)
298:  std::to_string(kMoePartitionRowCountShift)
340:  kMoePartitionExpertMask, kMoePartitionShift, kMoePartitionRowCountShift,

so it has a real dependency on dispatch-moe-routing-layout.h, and until now it was satisfied transitively (only qwen/dispatch-moe-router.cpp included it). Making it explicit is the right direction for a header that uses constants another header defines — the alternative is a build that breaks the day the transitive path changes, and this fleet has already paid for that class twice tonight (nothing compiled addons/, and the fork's rows nothing ran).

Nothing else changed: the layout comparison (mask/partition_shift/row_count_shift, not sizes), the 33-token case with its verified concentration argument, and the stale-expectation table checking clean at this pin.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 66f5db4: READY

The real diff is 7 files / +177, and the two commits behind it are exactly the fix and the shape that would have caught it — I reviewed those, not the 3,233-file artefact of diffing against the wrong base.

base 1bit/hrx-vulkan-patched, merge-base 2a7f01ba0:
  ggml/src/ggml-hrx/dispatch/command-plan-metadata.h                 |   6 +
  …/common/dispatch-moe-routing-layout.h                             |  27 ++++-
  …/common/dispatch-mul-mat-id-common.h                              |   7 ++
  …/qwen/dispatch-moe-router.cpp                                     |   4 +
  tests/CMakeLists.txt                                               |   6 +
  tests/hrx-ops-test.cpp                                             |   7 +-
  tests/test-hrx-moe-routing-layout.cpp                              | 123 ++++++++++

(Against master this is 3,233 files, because the PR's base is the fork's 1bit/hrx-vulkan-patched line, 1,288 commits ahead of the branch point. Anyone reading the GitHub diff will hit that first — worth one line in the body so the next reviewer does not mis-scope it the way I did for a minute.)

The fix is the right one, and the reason is stated exactly

+  expert_mask_value / partition_shift_value / row_count_shift_value      (values, not just the strings)
+  moe_routing_descriptor_is_common_layout(mask, partition, row_count)
+  moe_routing_bundle_readable_as_common(bundle)  -> false when the writer's layout differs from the reader's
+      … "A bundle written with a different descriptor layout decodes to the wrong expert index … Reusing it is never
+         correct, and the caller falls back to building its own table, which is the cheap path."

Sizes were identical between the two layouts, which is the whole trap: common_mul_mat_id_bundle_matches() compared token/route/expert counts and both byte counts, and the byte counts agree, so a Qwen-laid 128-expert table sailed through the gate into a common-layout reader and the partition bits landed inside the reader's expert field. Carrying the values (not the strings) makes the question answerable with an integer comparison, and refusing is the safe direction because the fallback rebuilds the table.

The test is the part I would keep above the fix

  • Host-side, device-free arms: the boundary (128 experts, 127/7/13 vs 511/9/15), the descriptor question in both directions, and the whole-bundle question — "Sizes are identical between the two layouts, so only the layout field can tell" is pinned as an arm, so the trap cannot be forgotten.
  • The constants are reproduced from both sides "so that drift in either, or in moe_router_descriptor_layout(), fails an arm here instead of on the device" — that is how a header constant pair should be tested.
  • tokens=33 in hrx-ops-test is the sharpest addition: "the smallest batch in which one expert owns more than 32 rows, which is the first shape whose partition table carries a partition index above zero". Until this, only the 512-token case reached it — "a suite that can only see a defect at 512 tokens is a suite that runs it in a sweep and resets the GPU. Keep the small shape: it fails faster and it fails on its own."

That last sentence is the reason this PR is worth more than its fix: the fault was reachable only through a shape expensive enough that nobody ran it on purpose.

One ask, and it is the review, not the code

Land the small shape first if the 512-token row is what resets the device — i.e. if this merges while the reset is still reproducible, the first thing anyone runs is tokens=33, which is the cheap witness. Nothing else in the diff needs changing.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: READY (pi-verify) — reviewed at 66f5db4.

This is the fix for the fault I was about to go hunting for with a device ticket (#2861, experts128.tokens512), and the diagnosis is the kind that is only findable by reading both sides: the byte counts agree between the two layouts, so a gate that compared sizes was structurally incapable of seeing the difference.

Verified

  • The values now travel with the bundle and are compared as values. descriptor_expert_mask / partition_shift / row_count_shift are carried alongside the strings, and moe_routing_descriptor_is_common_layout() compares all three. Comparing only the sizes is exactly the hole that was there.
  • The boundary is pinned at the boundary: moe_router_descriptor_layout(128) → 127/7/13 (Qwen), (129) → 511/9/15 (common). That is the discriminating pair — 128 is the shape that faulted, and the arm asserts both sides of it rather than "some expert count".
  • The rejection is a fallback, not a refusal. common_mul_mat_id_bundle_matches() returns false on a Qwen-written bundle, and the caller's if (bundle matches) simply leaves has_routing_bundle false, so the consumer builds its own table — the correct path, and the pre-existing one. I checked the caller rather than trusting the comment, because "returns false" and "falls back" are different claims.
  • The suite gained a token count that is not a power of two (33) with the reason spelled out: 512 was the only size heavy enough to reach the bug, and "a suite that can only see a defect at 512 tokens is a suite that runs it in a sweep and resets the GPU". That is the right lesson to encode — the fault was expensive precisely because only the biggest shape reached it.

One design note, not a block

With the gate now refusing a Qwen-written bundle, the Qwen layout is dead weight on the fast path for ≤128 experts: every such model falls back to building its own table. Either something still consumes a Qwen-written bundle (in which case that consumer needs the same layout check, and the bundle now lets it ask), or the router could write the common layout for all counts and the ≤128 fast path comes back. Worth one sentence in the body either way — it is the difference between "this fixes the fault" and "this fixes the fault and leaves a small performance hole behind it".

@bong-water-water-bong
bong-water-water-bong merged commit fe820a0 into 1bit/hrx-vulkan-patched Nov 20, 2026
@bong-water-water-bong
bong-water-water-bong deleted the cl-hrxnan/2861-layout-guard branch November 20, 2026 05:53
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
… API the pinned hrx-system predates (engine#2916) (#446)

loom-jit.cpp was changed to loomc_link_index_builder_create/_release by 5635e24 (carried by #434),
written against an installed loomc from hrx-system 0b1422f63 -- which is an ANCESTOR of the tree the
engine pins (7f423692). So the rename moved the fork onto names the pin had already removed:

  loom-jit.cpp:223: 'loomc_link_index_builder_release' was not declared; did you mean '..._free'?
  loom-jit.cpp:756: 'loomc_link_index_builder_create' was not declared

Three call sites, back to the allocate/free pair every other handle in the file already uses. This reverts
the hunk only: #432's CMake targets and #436/#438 are untouched.

Co-authored-by: bong-water-water-bong <[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