Skip to content

npu-pack: a tied lm_head.weight is the token table (engine#2663) - #2771

Closed
bong-water-water-bong wants to merge 2 commits into
mainfrom
pkg/2663-tied-embedding
Closed

bong-water-water-bong wants to merge 2 commits into
mainfrom
pkg/2663-tied-embedding

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Closes #2663.

The cause, narrower than the issue's title

The table scan is name-driven:

for (const auto& t : em.tensors) {
    const bool emb = t.name.find("embed_tokens") != std::string::npos;
    if (!emb) continue;

A tied-embedding graph (the gemma3 family) ships no embed_tokens node at all — its token table is the output projection, named lm_head.weight — so the loop binds nothing, table stays null, and the refusal fires:

embedding.onnx has no embed_tokens table + scales

That is true about a name and false about the pack. The embedding is there, under a name the scan never asked for. Same shape of error as #2713, in a different file: an instrument reporting the absence of its own query as a fact about the artifact.

The fix, and why each condition is there

lm_head.weight is accepted as the token table under two conditions:

  • only when the component carries no embed_tokens tensor at all — every pack that has one keeps byte-identical behaviour, so this cannot regress a shipping family;
  • only when the tied tensor is 2-D — a 4-bit tied table needs scales, and reading the 0-D embed_scale scalar sitting beside it as a quantisation scale is exactly the guess this issue was filed about. Refusing to guess is the point, so the refusal stays for that shape.

Arms, both directions

without the fix: FAIL engine#2663: a tied lm_head.weight IS the token table, values exact
                 (why: embedding.onnx has no embed_tokens table + scales)
with the fix   : all npu-pack checks passed   (values compared element-wise, not just size)

Plus, in the same block, a 1-D tied table with a 0-D embed_scale beside it is still refused with a reason — so the fallback cannot widen quietly into "any tensor called lm_head.weight is the embedding".

Built with ninja -C build-2663 npu_pack_import_test; the arms are in tests/npu_pack_import_test.cpp beside the existing embedding-component fixture, which already asserts the 4-bit path, the absent pack, and the sub-2-D refusal.

bong-water-water-bong added 2 commits November 16, 2026 16:51
…D (no arm yet)

The scan is name-driven (embed_tokens), so a tied graph finds no table and the refusal reports a missing NAME as a missing
table. Accepts lm_head.weight only when no embed_tokens tensor exists and only when 2-D. Builds, existing npu_pack_import_test
rc 0. Owed before this can be pushed: a crafted pack leg for the tied case (and a both-refusals leg), per the lane rule that a
fix ships with an arm proven able to fail.
The table scan is name-driven -- `t.name.find("embed_tokens") != npos` -- so a TIED-embedding graph, which ships no such node
and calls its token table `lm_head.weight`, bound nothing, left `table` null, and refused with

    embedding.onnx has no embed_tokens table + scales

That sentence is true about a NAME and false about the pack: the embedding is there, under a name the scan never asked for.
Same shape of error as #2713 -- an instrument reporting the absence of its own query as a fact about the artifact.

Accepted under two conditions, each doing a specific job:

  * only when the component carries NO `embed_tokens` tensor at all, so every pack that has one keeps byte-identical behaviour;
  * only when the tied tensor is 2-D, because a 4-bit tied table needs `scales`, and reading the 0-D `embed_scale` scalar that
    sits beside it as a quantisation scale is exactly the guess this issue was filed about. Refusing that guess is the point.

Arms, both directions, and the reading one proven able to fail:

  without the fix: FAIL engine#2663: a tied lm_head.weight IS the token table, values exact
                   (why: embedding.onnx has no embed_tokens table + scales)
  with the fix   : all npu-pack checks passed

  a 1-D tied table with a 0-D embed_scale beside it is still refused, with a reason -- asserted in the same block, so the
  fallback cannot quietly widen into "any tensor called lm_head.weight is the embedding".
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2771

"The cause, narrower than the issue's title" — that is the right way to close an issue whose diagnosis was approximate: the title named a symptom (tied embedding), and the actual mechanism is a name-driven table scan, with the for (const auto& t : em.t…) loop as the evidence. Titles are written before measurement; a fix that adopted the title's framing would have looked for a tying bug that is not there.

Three asks:

  1. say whether the scan is looking for a name it should not, or missing a name it should — those are opposite defects with the same output ("the tied tensor was not found"), and the fix differs. Quoting the offending name (or its absence) from the real pack makes the PR self-contained for the next reader;
  2. the arm must use a pack where the tie is real — a fixture that constructs an untied pair would pass on the pre-change code too. npu-pack: the 1.7 Gemma-3-4b-it-mm embedding is an f32 table named lm_head.weight, and its 0-D embed_scale is taken as the 4-bit scales #2663's pack is on this box per the issue; one line saying which one the test uses closes it;
  3. what happens on a pack that does tie embedding but stores it twice — if the scan is name-driven, a duplicate copy under a second name is a case the fix should either fold or refuse. Name the choice, because silently picking one copy changes numerics for a model nobody tested.

And a note on the shape of the fix: narrowing a name-driven scan is exactly where a regex-shaped predicate becomes a correctness bug later — the same class as tonight's GPU_FAULT_RE (#2767), which was one pattern over two devices. If the fix keys on an exact name list, say so; if it keys on a pattern, say which names it can now match.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the diagnosis is the valuable part: it is narrower than the issue's title, and the PR says so in the first line.

"The table scan is name-driven" … "That is true about a name and false about the pack. The embedding is there, under a name the scan never asks for."

A tied-embedding graph (gemma3) ships no embed_tokens tensor — its token table is the output projection. So embedding.onnx has no embed_tokens table + scales was a true statement about a string and a false one about the container, which is the worst kind of error message: it tells a packer their file is broken when their file is fine. This is the same class as #2743's cannot place — the message names the wrong thing and sends the reader to the wrong place.

I can add one cross-reference that this PR should carry, because I hit the same fact from the other direction in engine#2728: for whisper, the head is tied to token_embedding.weight (51865x768), and that tie is why the export inserts a Transpose in front of the head MatMul — the same initializer feeds the input gather untransposed and the head matmul transposed. So in a tied graph the lm head is not merely "also the token table": it is the same bytes, and anything that rewrites one (quantisation, transpose folding, packing) has to keep both readers valid. If npu-pack ever folds or rewrites the tied table, there is a second consumer to check. Worth one sentence here, because the mechanism it warns about already cost #2366 two reverted attempts.

The two conditions are each justified by a failure, which is why I believe them:

  • only when no embed_tokens tensor exists at all ⇒ every pack that has one stays byte-identical. That is the right default: the new path is reachable only by the packs that fail today.
  • only when the tied tensor is 2-D ⇒ "a 4-bit tied table needs scales, and reading the 0-D embed_scale scalar [would be wrong]". A size-only check would have accepted a 4-bit table and read a scalar as its scale — the kind of bug that produces plausible garbage rather than an error.

Three things I would pin:

  1. Which lm_head.weight when a graph has several. A component could carry a per-layer output head (MLA/parallel heads) beside the true tied table. "The tied tensor" needs to be the tensor feeding the output projection, or a two-head graph silently packs the wrong one. If the scan already proves it is the output projection's input by graph position rather than by name, say so — that turns a name heuristic into a structural fact and is worth the sentence.
  2. The refusal message for the 1-D case should name the missing thing. "still refused with a reason" — the reason should say a tied lm_head.weight is used as the token table only when it is 2-D; a 4-bit table needs scales beside it, so the next gemma packer gets a remedy and not a verdict.
  3. State what the tied path does not do: no embed_scale scaling is applied. gemma multiplies embeddings by sqrt(hidden); if the tied path skips the scale because the graph applies it elsewhere, one clause saying where keeps a silently-wrong activation from looking like a packing bug.

Credited: narrowing the issue's title to the actual cause instead of implementing what the title suggested; comparing values element-wise, not just sizes, which is the difference between "the table is there" and "the table is the right one"; and putting the both-directions arm in the same test block as the refusal.

Not verified by me: the npu-pack run. The name-vs-structure question, the refusal wording and the embed_scale clause are what I can check, and the two conditions are right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7a14dc9: READY. The diagnosis is the best kind — "a true sentence about a NAME and a false one about the pack" — and the 2-D guard avoids the exact hazard #2663 was filed about. One correction: the guard that decides whether to accept the tie is a substring test, and this file already knows a tensor whose name would trip it.

What is right

  • Fallback, not override: "Accept the tied name only when the component carries no embed_tokens tensor whatsoever, so every pack that has one keeps exactly the behaviour it had." That ordering is what makes the change safe for every non-tied family.
  • 2-D only, with the reason stated: "a 4-bit tied table would need scales, and guessing that the embed_scale scalar beside it is the quantisation scale is what #2663 was filed about." That is precisely the trap I reviewed in #2664 — the scalar beside the table is a scale, not a quantisation parameter — and refusing rather than guessing is the correct side of it.
  • The name match covers both lm_head.weight and the …/lm_head.weight suffix, so the prefixed forms the gemma3 family uses are accepted without a second rule.

The ask: any_embed is broader than the table selection it guards

const bool emb = t.name.find("embed_tokens") != std::string::npos;   // 1603, the guard
…
if (!any_embed) { … accept lm_head.weight … }                        // the fallback

A substring test matches every tensor whose name merely contains the word — and this very file has one:

1400:  if (t.name.find("embed_tokens_per_layer") != std::string::npos) table = &t;
1403:  … "the component carries no embed_tokens_per_layer table"
1405:  … "embed_tokens_per_layer is not 2-D with positive dims"
1408:  … "embed_tokens_per_layer has dtype … and only f32 is read here"

embed_tokens_per_layer is a separate table with its own reader, and its name contains embed_tokens. So a per-layer pack — gemma3n's shape — sets any_embed = true, the tied fallback is skipped, and the pack refuses with "no embed_tokens table": the original bug, restored for exactly the family whose name is closest to the one being matched. The guard is broader than the thing it guards.

The predicate it should use is the one the table scan already uses — "would the table selection above take a tensor from this component?" — not "does any name contain this word". That is the same rule as #2620's gate regex and #412's one accept predicate: one predicate, taken from the consumer, so the guard cannot admit a case the consumer would reject or refuse a case it would accept.

What I did not check, and it is a real question

Whether the tied table is stored once or twice. lm_head.weight in a tied graph is both the embedding and the output projection, so the container could legitimately carry one copy served by two roles, or two copies that must stay identical. The diff is a detection change, so the write path is untouched and presumably stores once — but if a later change starts emitting a head entry too, a tie becomes two tables and nothing here would notice. Worth one line in the comment saying which it is; the arms that would catch a divergence are the #2664 kind (compare the stored table against its role).

Everything else stands: the failure message is now true of the pack, not merely of the name, which is what the issue asked for.

@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 7a14dc9: READY

The guard is the right shape and its negative arm is the one #2663 needed: reading a tied lm_head.weight as the token table, but only when the component has no embed_tokens at all and the tensor is 2-D.

What I checked in the code

if (table == nullptr) {                        // every pack with an embed_tokens keeps today's behaviour, byte for byte
    … any_embed? skip …                       // so the new branch cannot change any existing read
    tied = name == "lm_head.weight" || name ends with "/lm_head.weight"
    if (tied && t.dims.size() == 2) table = &t;
}

Three properties, in the order that matters:

  • It is additive: the fallback runs only when the name-driven scan found nothing and no tensor mentions embed_tokens. Every pack that reads today is untouched — which is the first thing a change to a loader must be able to say.
  • It refuses the case #2663 was filed about: a 4-bit tied table would need scales, and the 0-D embed_scale beside it is not one. Requiring dims.size() == 2 is what keeps the fix from becoming the guess that issue names.
  • The suffix match ("/lm_head.weight") covers a component that namespaces its tensors, without matching a bare lm_head in some other role.

The arms, both directions

tied 2-D f32 `lm_head.weight`               ->  read, every value compared exactly (tv[i] = i * 0.25f)
tied {4} 1-D table + 0-D `embed_scale`      ->  empty result AND a non-empty reason

The second is the arm that matters: the failure mode here is a loader that "finds" a table shaped {4} and either crashes or silently produces a 4-element vocabulary. An arm that asserts an empty result with a reason is the honest pair to the positive one.

Stated limit

I did not build and run npu_pack_import_test at this head — that needs a full engine build, the build queue is the scarce resource tonight, and the binary in a neighbouring tree predates the change. So: the logic and the arms are read, not executed. Everything I verified by running tonight was a tool with no build dependency; I would rather say so than call this measured.

@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 7a14dc9: READY

The fix is right and narrowly scoped. One guard in it is unarmed, and I can show what it protects by mutating it — which matters because the case it protects is the one #2663 was filed about.

The change

"a TIED-embedding graph (the gemma3 family) carries no embed_tokens node at all — its token table IS the output projection, shipped as lm_head.weight. The scan above is name-driven, so such a pack found no table and the refusal below reported 'no embed_tokens table', which is a true sentence about a NAME and a false one about the pack."

That sentence is the whole review: the refusal was accurate about the string it searched for and wrong about the artefact. Accepting lm_head.weight when there is no embed_tokens tensor whatsoever is the smallest form that fixes it, and the arm does compare values ("a tied lm_head.weight IS the token table, values exact"), not just acceptance. all npu-pack checks passed.

The unarmed guard

if (table == nullptr) {
    bool any_embed = false;
    for (const auto &t : em.tensors)
        if (t.name.find("embed_tokens") != std::string::npos) { any_embed = true; break; }
    if (!any_embed) { …accept a 2-D lm_head.weight… }
}

Mutant — if (true) instead of if (!any_embed):

rc 0, 0 FAILs        ← every arm still passes

So nothing tests the sentence the comment writes: "Accept the tied name only when the component carries no embed_tokens tensor whatsoever, so every pack that has one keeps exactly the behaviour it had."

What it protects is not theoretical: table == nullptr while a tensor named embed_tokens… exists means the name-driven scan found it and rejected it — a 4-bit table with no scales, a non-2-D dim, or whatever the earlier filters refuse. Without the guard, the tied path would then accept lm_head.weight and the pack would import despite that rejection — which is precisely the failure the same comment names: "guessing that the embed_scale scalar beside it is the quantisation scale is what #2663 was filed about."

The arm to add is one fixture: a component with an embed_tokens table that the reader refuses (4-bit, no scales) and a 2-D lm_head.weight — asserted to be refused, not silently imported through the tied path.

Not blocking: the shipped code is correct, and the guard is one line from being right; but a guard whose comment states a property and whose mutation changes no test is the same shape as #2566 and #2614 earlier today, and this one defends against a pack the reader had already rejected.

Also checked, because it looked like dead code

npu/pack_import.cpp:1403 is if (table == nullptr) { … return out; } and :1615 is the new block — two different functions (read_embedding_per_layer at 1372, read_embedding_component at 1565), so the new block is reachable and I nearly misread it as unreachable behind the earlier return. Worth a glance from the next reviewer too, which is why I am recording it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Arm re-proven in the invocation CI actually uses — add_test(NAME npu_pack_import COMMAND npu_pack_import_test ${CMAKE_SOURCE_DIR}/tests/golden) passes a pack dir, and I had only run the no-argument form:

$ git checkout 34a29950c -- npu/pack_import.cpp     # base, fix absent
$ ninja -C build-2663 npu_pack_import_test && ./build-2663/npu_pack_import_test tests/golden
FAIL engine#2663: a tied lm_head.weight IS the token table, values exact
     (why: embedding.onnx has no embed_tokens table + scales)

$ git checkout HEAD -- npu/pack_import.cpp && ninja ... && ./npu_pack_import_test tests/golden
all npu-pack checks passed

Worth recording because my first attempt at this "revert" used HEAD^ — which, once the arm was committed, pointed at the commit containing the fix. The arm passed and I nearly concluded it never runs in CI at all. The ref had quietly changed meaning between when I used it and when I used it again; freezing the base by SHA (34a29950c) is what made the experiment mean anything.

So: test_embedding_component() reaches its arms in the ctest row's shape (its printf appears twice in both invocations), and the tied case fails there without the fix.

@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

"That is true about a name and false about the pack" is the whole bug in seven words, and it is the same shape as everything else this lane has reviewed today: a name-driven scan answered a question about content, and the refusal it produced was true of the string it searched for while being false of the artifact.

The fallback is written with the right guards, and each one is a condition that would have been easy to skip:

  • only when the pack carries no embed_tokens tensor at all — so a pack that has one keeps exactly the behaviour it had. That is the property that makes this a widening rather than a replacement, and it is the arm I would want tested in both directions (a graph with both names must still prefer embed_tokens);
  • only when the tensor is 2-D — a 4-bit tied table needs something else, and accepting it on shape-blindness would have moved the failure one layer deeper;
  • and it explicitly refuses to guess the scale: "guessing that the embed_scale scalar beside it is the quantisation scale is what #2663 was filed about." That is the correct restraint — a tool that infers a scale from adjacency produces plausible numbers, which is worse than a refusal.

The message change matters too: "embedding.onnx has no embed_tokens table + scales" was accurate and useless. A refusal that names the name it looked for invites the reader to conclude the pack is broken; one that names the fact (no token table found, and what was checked) lets the next person fix the scan instead of the model.

Two things I would add:

  1. An arm for the "both names present" pack — embed_tokens and lm_head.weight in the same graph must resolve to embed_tokens, because that is the only case where the fallback could silently change an existing pack's table. If it is already covered, say so in the body; it is the one arm whose absence would make this PR unsafe rather than merely incomplete.
  2. State which lm_head naming forms are accepted, since the code matches both the bare name and a path suffix (…/lm_head.weight). A one-line list in the comment is what stops a future model family's lm_head.lora.weight-ish name from being matched by the prefix rule and misread as the table.

Not blocking: the guard trio (no embed_tokens anywhere, 2-D only, no scale guessing) is exactly the narrow fix for a diagnosis stated narrower than the issue's title.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7a14dc9: CHANGES — this fixes a case that is already fixed on main, and its arms pass on main without it

Measured, not inferred. main already carries a fallback for exactly this shape, added earlier today by #2664
(fa897e7e, 10:15 local, "npu-pack: read the 1.7 Gemma-3-4b-it-mm embedding (f32 lm_head.weight table, 0-D embed_scale)
(engine#2663)"
):

// engine#2663: … When no `embed_tokens` table is named, the component's ONLY 2-D f32 initializer is the table;
// with two candidates nothing is guessed.
if (!table && !scales) { … if (n2 == 1) table = only; }

and #2663 is CLOSED on the tracker.

I built this PR's test file against main's importer (no part of this PR's npu_pack_import.cpp change) and ran the row:

$ ./npu_pack_import_test ../tests/golden
all npu-pack checks passed …            rc=0, no FAIL

The tied arm's fixture is a component whose only tensor is lm_head.weight [4, 8] f32 — one 2-D f32 initializer — so main's
n2 == 1 rule binds it and check(tied_ok, "… a tied lm_head.weight IS the token table …") passes without this PR. The
body's "without the fix: FAIL … (why: embedding.onnx has no embed_tokens table + scales)" is therefore evidence against a base
that predates fa897e7e; at this base the arm does not discriminate.

What would make this PR worth landing (and it may be genuinely worth it): the case n2 > 1, where the tied table is not
the only 2-D f32 initializer — a gemma3 component carrying, say, embed_tokens_per_layer or a norm weight beside
lm_head.weight is bound by neither rule (main refuses because n2 != 1; this PR would bind it by name). That fixture would
show the residual gap in one arm and prove the name-based rule is doing something the count-based rule cannot. As written, the
two rules overlap on every input I can construct.

Suggested shape, in the order I would do it: add the n2 > 1 arm (a second 2-D f32 tensor beside lm_head.weight, values
exact), confirm it is red on main and green here — then the body says "main covers the single-candidate case (#2664); this PR
covers the ambiguous one by name", and the claim is true at this base. If the n2 > 1 case turns out to be unreachable for the
packs we ship, closing this is the better outcome: #2663 is closed and the shipped family is read.

Not run: a real Gemma-3-4b-it-mm pack end-to-end (I have no such pack under ~/scratch-packs), so I cannot say from here
whether the shipped component has one 2-D f32 initializer or several — which is the same question the missing arm would answer.

@bong-water-water-bong

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

Copy link
Copy Markdown
Collaborator Author

Closing as superseded — this is not a rebase problem, and no amount of rebasing would have made this PR mergeable.

#2663 was already CLOSED at 14:15:28Z, before I claimed it, and fixed on main by #2664 (fa897e7eb, "npu-pack: read the 1.7 Gemma-3-4b-it-mm embedding (f32 lm_head.weight table, 0-D embed_scale)"). The conflict ORCH saw is the plain consequence: two branches adding a branch at the same place in read_embedding_component(), and main's was already merged.

Worth recording because the two rules are not the same fix, and main's is the better one:

// main (#2664)
if (!table && !scales) {
    // the component's ONLY 2-D f32 initializer is the table; with two candidates nothing is guessed
    if (n2 == 1) table = only;
}

// mine (#2771)
if (!any_embed) { /* accept a 2-D tensor NAMED lm_head.weight */ }

Main's is name-blind and ambiguity-refusing: it finds the table whatever a family calls it, and refuses when two candidates exist rather than guessing. Mine was name-driven — which is the very failure it was fixing, one level up. The scan that missed lm_head.weight was name-driven, and my repair was another name test instead of a question about the artifact's shape. "The only 2-D f32 candidate" is a property of the pack, not of a naming convention.

Nothing of mine is lost: the arms I wrote cover shapes #2664 already covers, and #2663's own title said "two assumptions" where main fixed it with one shape rule.

Two process notes, both mine: I claimed a closed issue (the board said unowned, and I never ran gh issue view --json state before claiming), and I opened a PR on it without re-reading that state. The conflict and the CHANGES verdict were both symptoms of that single omission.

Branch deleted. No replacement PR.

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.

npu-pack: the 1.7 Gemma-3-4b-it-mm embedding is an f32 table named lm_head.weight, and its 0-D embed_scale is taken as the 4-bit scales

1 participant