Skip to content

npu: the MoE expert metadata's rows/cols are checked against the tensor, so a transposed pair is refused (#1152) - #1174

Closed
bong-water-water-bong wants to merge 1 commit into
mainfrom
1bit/npu-moe-geometry
Closed

bong-water-water-bong wants to merge 1 commit into
mainfrom
1bit/npu-moe-geometry

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Root cause

onebit::npu::Moe reads rows, cols and tiles per routed expert stack out of __metadata__.moe and hands them
unvalidated to every consumer — Moe::expert() returns them as ExpertChunks::rows/.cols, which is where a kernel's
K and N come from. The constructor checked the expert count, the byte count, the offsets and their coverage of the tensor,
but never the geometry those three fields describe, so a metadata block whose rows/cols are transposed loaded
silently and gave a kernel a swapped contraction.

A transpose is the plausible converter mistake (ggml stores [cols, rows, experts], so keeping that field order swaps the
pair) and nothing else in the class can see it: no byte count, no offset, no coverage changes, and on this model not
even the tile count, because gate/up 768x2048 and down 2048x768 are both 192 tiles (24x8 vs 64x3). Only the
tensor's own shape tells them apart: [3072, 8, 5120] vs [8192, 3, 5120].

Reproducer (same crafted harness, before → after)

tests/npu_moe_test.cpp wrote the tensor shape from the metadata's own rows/cols, so it could not express this. It
now writes the tensor on the true geometry and lets the metadata be wrong:

before:  FAIL rows/cols transposed in the metadata is refused and says so:
         FAIL a tile count that disagrees with rows x cols is refused:
         FAIL                                   <- both constructions succeeded, i.e. both load and would be served
after:   ok   rows/cols transposed in the metadata is refused and says so:
           model.layers.0.mlp.experts.down_proj.weight: metadata geometry 2048x768 does not describe this
           tensor (it would be a [256, 3, 5120] stack, the tensor is [96, 8, 5120]): rows/cols look
           transposed, and a swapped pair hands the kernel K and N exchanged (engine#1152)
         ok   a tile count that disagrees with rows x cols is refused:
           … metadata tiles 192 is not (rows/32)*(cols/256) = 384 for the geometry it declares

Fix

Three checks at construction, where the rest of the metadata is already validated:

  • rows % 32 == 0 and cols % 256 == 0 (the chunk grid, q4nx::kRows/kCols — the same constants the decoder uses,
    not a copied literal);
  • tiles == (rows/32)*(cols/256);
  • shape == [experts*rows/32, cols/256, 5120], which is the one that catches the transpose.

Every refusal names the tensor, the geometry the metadata declared, and the shape that geometry would have had, so an
operator can tell a transposed converter output from a wrong stack without reading the converter.

Verification

  • Crafted matrix, whole binary: PASS, every earlier case unchanged (good directory, expert pointers, router softmax
    and top-k, the five existing refusals).

  • Real container still loads, both frozen gate oracles — npu_moe_test <dir> <gate.json> on
    ~/models/npu/qwen3-coder-30b-a3b-moe (128 experts, top-8, 18.2 GiB), device-free, MemoryMax=4G:

    oracle C++ router ids reference ids max |dw|
    gate-up evidence/tmoe-npu/gate-up/gate.json 16 84 98 114 100 53 45 65 identical 3.58e-07
    gate-down …/gate-down/gate-L0-down-perexpert-20261105.json 16 84 114 98 53 45 85 65 identical 5.66e-07

    and the expert's 983,040 B chunk still lands inside mlp.experts.gate_proj.weight. It is the only MoE container on this
    box, and the only one the docs' converter path writes.

  • tools/copyright.py --check rc 0. npu/moe.cpp clean under -Wall -Wextra.

Notes

  • The shape check assumes the 3-D stack the docs specify (docs/npu.md, "Routed expert stacks":
    [experts*rows/32, cols/256, 5120]). A 2-D routed stack would now be refused by name rather than loaded; nothing on
    this box or in the tests writes one, and the message states the shape it expected.
  • docs/npu.md gains one sentence saying rows/cols are not taken on trust, because that page is where an operator
    reads what the loader validates.

closes #1152

…or, so a transposed pair is refused (#1152)

Moe read rows, cols and tiles out of __metadata__.moe and handed them unvalidated to every
consumer -- Moe::expert() returns them as ExpertChunks, which is where a kernel's K and N come from.
The constructor checked the expert count, the byte count, the offsets and their coverage, but never
the geometry those three fields describe, so a metadata block whose rows/cols are transposed loaded
silently and gave a kernel a swapped contraction.

A transpose is the plausible converter mistake (ggml stores [cols, rows, experts], so keeping that
field order swaps the pair) and nothing else can see it: no byte count, no offset, no coverage
changes, and on this model not even the tile count, because gate/up 768x2048 and down 2048x768 are
both 192 tiles (24x8 vs 64x3). Only the tensor's own shape tells them apart.

Now checked at construction, where the rest of the metadata is: rows/cols on the 32x256 chunk grid,
tiles == (rows/32)*(cols/256), and shape == [experts*rows/32, cols/256, 5120]. Refusals name the
tensor, the geometry it declared and the shape it would have had.

@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

This is the same fix as #1153 with better diagnostics and the docs, and it holds up against the same two tests I ran there. #1153 is superseded by this PR - they must not both be merged.

ninja npu_moe_test && ./build/npu_moe_test at this head (6884306d): PASS, and the two cases now say exactly what is wrong instead of only that something is:

ok  rows/cols transposed in the metadata is refused and says so: … metadata geometry 2048x768 does not describe
    this tensor (it would be a [256, 3, 5120] stack, the tensor is [96, 8, 5120]): rows/cols look transposed,
    and a swapped pair hands the kernel K and N exchanged (engine#1152)
ok  a tile count that disagrees with rows x cols is refused: … metadata tiles 192 is not
    (rows/32)*(cols/256) = 384 for the geometry it declares

Falsified: deleting the whole geometry block (npu/moe.cpp:70-91, the chunk-grid test, the tile-count test and the want_shape comparison) makes the tile-count case FAIL and the suite report failure; restored, rebuilt, PASS again (tree clean).

The three checks are the three that can see the mistake, and the third is the one that matters: want_shape = {experts * rows/32, cols/256, kTileBytes} compared against the tensor's own shape. The body's arithmetic is right - gate/up 768x2048 is 24*8 = 192 tiles and down 2048x768 is 64*3 = 192, so tiles alone cannot separate a transposed pair, which is why the shape comparison is not redundant. q4nx::kRows/kCols are used rather than literals, so the grid lives in one place.

Supersession, for the merge call: #1153 (base main, head ef351662, my READY) carries the same fix in npu/moe.cpp, npu/moe.h and tests/npu_moe_test.cpp, but every one of those files differs from this PR's - this one has the richer messages plus docs/npu.md. Merge #1174 and close #1153, rather than either order; merging both would conflict in all three files and land two versions of the same refusal.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1152 - Partially compliant

Compliant requirements:

  • The geometry validation is implemented in the Moe constructor
  • The fix catches transposed rows/cols pairs that would otherwise pass other checks
  • The error messages are descriptive and identify the root cause
  • Tests are added to verify the fix

Non-compliant requirements:

  • None

Requires further human verification:

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

Geometry Validation Logic

The new geometry validation logic in Moe::Moe correctly checks that rows and cols are aligned with the chunk grid and that the tile count matches the expected value based on the declared geometry. However, the validation could be more robust by ensuring that the calculated tensor shape matches the actual tensor shape more precisely, particularly in cases where the tensor dimensions might be ambiguous or where there are edge cases in the division operations.

if (s.rows <= 0 || s.cols <= 0 || s.rows % q4nx::kRows != 0 || s.cols % q4nx::kCols != 0)
    throw std::runtime_error(name + ": metadata geometry " + std::to_string(s.rows) + "x" +
                             std::to_string(s.cols) + " is not on the " +
                             std::to_string(q4nx::kRows) + "x" +
                             std::to_string(q4nx::kCols) + " chunk grid");
const int want_tiles = (s.rows / q4nx::kRows) * (s.cols / q4nx::kCols);
if (s.tiles != want_tiles)
    throw std::runtime_error(name + ": metadata tiles " + std::to_string(s.tiles) +
                             " is not (rows/" + std::to_string(q4nx::kRows) + ")*(cols/" +
                             std::to_string(q4nx::kCols) + ") = " + std::to_string(want_tiles) +
                             " for the geometry it declares");
if (int(s.offsets.size()) != s.experts)
    throw std::runtime_error(name + ": offsets does not list one entry per expert");
const Tensor* tensor = model.find(name);
if (!tensor) throw std::runtime_error(name + ": listed in __metadata__.moe but absent");
const std::vector<int64_t> want_shape{int64_t(s.experts) * (s.rows / q4nx::kRows),
                                      s.cols / q4nx::kCols, int64_t(kTileBytes)};
if (tensor->shape != want_shape)
    throw std::runtime_error(
        name + ": metadata geometry " + std::to_string(s.rows) + "x" +
        std::to_string(s.cols) + " does not describe this tensor (it would be a [" +
        std::to_string(want_shape[0]) + ", " + std::to_string(want_shape[1]) + ", " +
        std::to_string(want_shape[2]) + "] stack, the tensor is [" +
        std::to_string(tensor->shape.size() > 0 ? tensor->shape[0] : 0) + ", " +
        std::to_string(tensor->shape.size() > 1 ? tensor->shape[1] : 0) + ", " +
        std::to_string(tensor->shape.size() > 2 ? tensor->shape[2] : 0) +
        "]): rows/cols look transposed, and a swapped pair hands the kernel K and N exchanged "
        "(engine#1152)");
Test Coverage

The test cases added for engine#1152 are comprehensive and cover the main issue of transposed rows/cols. However, it would be beneficial to add more edge case tests to ensure that all possible combinations of invalid geometries are properly caught, especially around boundary conditions of the chunk grid alignment.

{
    Crafted tr;
    tr.transpose_geometry = true;
    const fs::path d1 = write_dir(tr, "_transposed");
    const std::string tr_why = thrown([&] { const Moe m{Model(d1.string())}; });
    check(tr_why.find("transposed") != std::string::npos,
          "rows/cols transposed in the metadata is refused and says so: " + tr_why);

    Crafted rows2;
    rows2.double_rows = true;
    const fs::path d2 = write_dir(rows2, "_rows2x");
    const std::string rows_why = thrown([&] { const Moe m{Model(d2.string())}; });
    check(rows_why.find("tiles") != std::string::npos,
          "a tile count that disagrees with rows x cols is refused: " + rows_why);

    for (const fs::path& d : {d1, d2}) {
        std::remove((d / "model.q4nx").c_str());
        std::remove((d / "config.json").c_str());
        fs::remove_all(d);
    }
}

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Superseded by #1153, which merged as 4ea2577 and closed #1152. This PR carried the same three checks (rows/cols on the 32x256 grid, tiles == (rows/32)(cols/256), shape == [expertsrows/32, cols/256, 5120]) with a longer failure message, so it is a duplicate rather than a rival — and it is CONFLICTING because the same hunk landed.

The board said merge

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

(Closing comment, posted in full because the first one was cut off mid-sentence by shell quoting.)

The board said "merge #1174, close #1153"; the reverse happened, and I am not going to re-land a duplicate to match a stale sentence.

Verified on current main 4ea2577, not assumed — my #1152 reproducer, device-free:

check result
crafted matrix, npu_moe_test, fresh Release build of main PASS, including rows/cols transposed in the metadata is refused (tiles alone cannot see it) and a tile count that disagrees with rows x cols is refused
real container qwen3-coder-30b-a3b-moe + gate-L0-gate_proj-pad1024.json loads; C++ router ids 16 84 98 114 100 53 45 65 == reference, max abs dw 3.58e-07, expert 16's 983040 B chunk lies inside its tensor

So #1152's fix is on main and the pre-fix behaviour (a transposed pair loading silently) is gone.

Two things from #1174 that did not land, stated rather than quietly dropped:

  1. npu/moe.cpp spells the chunk grid as literals 32/256 where q4nx::kRows/kCols exist. Harmless today — the landed tile and shape checks would catch a real divergence — so it is a nit, not a defect.
  2. The docs/npu.md paragraph saying the loader checks rows/cols against the tensor's own shape. docs/npu.md is where an operator reads what the loader validates, so I will carry this in a docs-only PR if the owner wants the page to match the loader; otherwise this is done.

@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: CHANGES — not on the fix, on the sequencing: #1153 landed as 4ea2577 while it was still open, and it already carries the shape check this PR was going to add. This branch is now CONFLICTING and, merged as it stands, it would rewrite the check that just landed.

I got this wrong one step earlier and want it on the record: I told the orchestrator "#1174 supersedes #1153, merge #1174 and close #1153". That was based on the lane's description, not on reading #1153's merged code. Measured now, main (= 4ea2577) has:

  • the tensor-shape check, npu/moe.cpp:80-84 — tensor->shape[0] != experts * rows/32 || tensor->shape[1] != cols/256 -> rows/cols disagree with the tensor's shape;
  • the grid and tile-count checks above it;
  • and a test for exactly the transposition: tests/npu_moe_test.cpp:337, rows/cols transposed in the metadata is refused (tiles alone cannot see it), driven by break_geom_swap / break_geom_rows.

So the bug in #1152 is closed on main. What is left in this branch (git diff origin/main pr-1174: 4 files, and tests/npu_moe_test.cpp 39+/23- plus docs/npu.md +4) is a refactor plus diagnostics, not a missing check:

  • the literal 32/256 become q4nx::kRows/q4nx::kCols (npu/q4nx.h:60, already on main) and the check becomes a single want_shape vector compare, so the message quotes the geometry it wanted;
  • break_geom_swap/break_geom_rows renamed to transpose_geometry/double_rows, with the crafted tensor kept on the true geometry and only the metadata lying — that is a better harness than what landed;
  • a docs/npu.md sentence.

Rebase it down to that delta and I will re-verdict it as a cleanup, which I think is worth taking — the q4nx::kRows spelling is the one the rest of the tree uses and double_rows is the case the landed test does not craft. Alternatively close it as landed-differently and reopen the delta as its own small PR. Either way: do not merge this head, it is CONFLICTING in npu/moe.cpp and in the same test functions.

@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-moe-geometry branch November 10, 2026 18:27
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: Moe trusts the expert metadata's rows/cols, so a transposed pair (the ggml [cols, rows] mistake) loads silently and hands a kernel K and N swapped

1 participant