Skip to content

npu: take the vocabulary from config.json, and accept a tied table shipped only as lm_head (refs #1782) - #1803

Merged
bong-water-water-bong merged 1 commit into
mainfrom
1bit/tie-aware-vocab
Nov 10, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
1bit/tie-aware-vocab

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Blocker for #1782 (F7), found by running a 1.0.12 Decision pack on our route. The pack would not load:

1bit npu-run: model has no tensor model.embed_tokens.weight

Two defects in one line of npu/model.cpp:77

dims_.vocab = int(tensor("model.embed_tokens.weight").shape.at(0));
  1. It required a tensor name a tied pack need not ship. FastFlowLM/D3-Edge-NPU2 declares tie_word_embeddings: true and stores the [248320, 1024] table only as lm_head.weight — so the name lookup threw before anything else ran.
  2. It read the wrong dimension. A tiled entry's shape is [tile_rows, tile_cols, tile_bytes]; that table is [7760, 4, 8704], so shape[0] is a tile count. The loader reported vocab 7760, hidden 4 while config.json stated vocab_size: 248320 all along.

The fix

  • vocab_size from config.json when present (it is, in every pack that declares it);
  • otherwise the embedding table — falling back to lm_head.weight when the model declares tie_word_embeddings;
  • a 3-D tile grid converts to rows at 32 rows per tile (npu/q4nx.h);
  • with neither, the refusal names what is missing instead of model has no tensor ….

Measured on this box, after the fix (edge pack, --kernels = the kernel set we already had, no new ELFs)

[forward] dims from config.json: H=1024 NL=12 NH=8 NKV=2 HD=256 IM=3584 NV=248320
[forward] embedding dtype I8 -> dequantized (254279680 floats, 0.95 GiB)
[forward] decode family: 6 role(s) at M=16, 0 on M=128
1bit forward-serve: d3 decision head: 255 options, hidden 1024, d3-code-readout-v1, pooling last
1bit forward-serve: warm-up pass 3645.0 ms -> ready on http://127.0.0.1:18199 (full ELF)

(The run above used a per-pack copy with the entry aliased, which is what proved the defect; this PR removes the need for any such copy.)

Tests, device-free, in tests/npu_model_bounds_test.cpp

The fixture writer now takes extra config fields, and three arms cover it:

  • config vocabulary + a lm_head.weight-only table → loads, vocab == 777;
  • no vocab_size + a 2x4x8704 tile grid → vocab == 64 (2 tiles × 32 rows), not 2;
  • neither → refused by name, mentioning vocab_size and the embedding table.

tools/copyright.py --check clean. Not built locally: the box is at 110 GB free, under the floor these rules set for a build tree, so CI's build + ctest npu_model_bounds is the compile check — and the arms are written to fail on the pre-fix code (the first would throw on the name lookup, the second would report 2, the third would say "model has no tensor").

…ipped only as lm_head (refs #1782)

A 1.0.12 Decision pack (`FastFlowLM/D3-Edge-NPU2`, Apache-2.0) would not load: `model has no tensor
model.embed_tokens.weight`. Two defects in one line of `npu/model.cpp:77`:

    dims_.vocab = int(tensor("model.embed_tokens.weight").shape.at(0));

1. **It required a tensor name that a tied pack need not ship.** The pack declares
   `tie_word_embeddings: true` and stores the [248320, 1024] table ONLY as `lm_head.weight`, so the
   name lookup threw before anything else ran.
2. **It read the wrong dimension.** A tiled entry's shape is [tile_rows, tile_cols, tile_bytes]:
   that table is `[7760, 4, 8704]`, so `shape[0]` is a TILE count and the loader reported
   `vocab 7760, hidden 4` -- while `config.json` stated `vocab_size: 248320` all along.

Now: `vocab_size` from config.json when present (it is, in every pack that declares it); otherwise the
embedding table, falling back to `lm_head.weight` when the model declares `tie_word_embeddings`; and a
3-D tile grid converts to rows (32 per tile, `npu/q4nx.h`). With neither, the refusal names what is
missing instead of "model has no tensor …".

Measured on this box: the pack then loads and serves on our route with the kernel set we already had
(dims H=1024 NL=12 NH=8 NKV=2 HD=256 IM=3584 NV=248320, tied embedding dequantized to 254,279,680
floats, `d3 decision head: 255 options`, warm-up 3.6 s, ready).

Three device-free arms in `tests/npu_model_bounds_test.cpp` (the fixture writer now takes extra config
fields): config vocabulary with a `lm_head.weight`-only table; no `vocab_size` and a 2x4x8704 tile grid
-> 64 rows, not 2; and neither -> refused by name.

@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 c87ae9a: CHANGES

Checked at c87ae9a by reading Model::Model and the new arms. Both defects named in the body are real, and the two fallbacks are right: lm_head.weight stands in for a tied table only when tie_word_embeddings is declared, and a 3-D tile grid becomes rows at 32 per tile (248320 / 32 = 7760 matches the D3-Edge table's [7760, 4, 8704]). The "neither" refusal names both things it looked for.

One problem: vocab_size from config.json now wins even when the table exists, and nothing checks it against the table. Before, the row count came from the table, so it could never exceed it. Now dims_.vocab = c.at("vocab_size") is taken as stated, and every reader that indexes the embedding or head by token id trusts dims().vocab. The PR's own fixture shows it: tied-head-only renames one_layer()'s embedding, a 2-D {2, 128}, i.e. 2 rows, to lm_head.weight, writes {"vocab_size": 777}, and asserts the model loads with vocab == 777. In a real container, token ids 2-776 would index past the table, which is the class of read npu_model_bounds_test exists to refuse. (Separately, the rename leaves the fixture with two entries named lm_head.weight, because one_layer() already has one {1, 5120}. The arm should drop or replace the existing one so it tests a single, unambiguous table.)

Fix: when an embedding table (or the tied lm_head.weight) exists, derive its row count with the same rule (shape[0] * 32 for a tile grid, shape[0] for 2-D), and refuse by name when vocab_size exceeds it. A table may be larger than vocab_size, because tiling pads rows to 32, but never smaller. Then correct the tied-head-only fixture (vocab_size no larger than its table's rows) and add the refusal arm: vocab_size greater than the table's rows is refused with both numbers in the message.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: APPROVE at c87ae9a — and the tile-packed rule is not just plausible: it reproduces the known vocabulary of a real pack on this box exactly.

if (c.contains("vocab_size"))            dims_.vocab = c.at("vocab_size");                       // config wins
else  … emb = find("model.embed_tokens.weight");
         if (!emb && c.value("tie_word_embeddings", false)) emb = find("lm_head.weight");         // the tied case
         dims_.vocab = emb->shape.size() >= 3 ? int(emb->shape[0] * kTileRows) : int(emb->shape.at(0));

kTileRows = 32.

Verified against a real pack, not just against the code

~/.config/flm/models/Qwen3.8-27B-NPU2 (an FLM model source, on this box) declares "vocab_size": 248320 and its container holds

lm_head.weight            I8   shape [7760, 20, 8704]

7760 × 32 = 248,320 — exactly the declared vocab_size, while a 64-row tile would give 496,640 and be wrong by 2×. So the three-dimensional shape really is [tiles, …, cols] with 32
rows per tile, the multiplier is right, and the two-argument form (shape.at(0)) is the fallback for a non-tiled container. That is the check I would want on a numeric rule like this, and
it happens to be available without a build.

Two smaller things the change gets right:

  • vocab_size from the config takes precedence over anything derived, which is correct: the container's packing is a representation detail and the config is the model's own statement.
  • The tied fallback looks at lm_head.weight, which is the only table a tied model has — with the refusal naming both possibilities rather than "cannot find embedding", so a user can tell
    which shape of pack they have.

One note, not blocking: kTileRows = 32 is now a fact duplicated between this rule and the embedding tile's own definition. If the tile geometry is ever parameterised (the Q4NX form
already carries [tiles, 20, 8704], so 20 is a field of the shape rather than a constant), pinning the 32 to one named place would stop the two from drifting — the arithmetic here is
exactly the kind that fails by a factor rather than by a margin.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY @ c87ae9a (head c87ae9a)

Two defects in one line, and the second is the one I would have missed: tensor("model.embed_tokens.weight").shape.at(0) was not just requiring a tensor that a tied
pack may ship only as lm_head.weight — it was reading shape[0] of a tiled entry, so a 248,320-row table stored [7760, 4, 8704] was reported as vocab 7760,
hidden 4
. A model that loaded with a vocabulary 32× too small and a hidden size of four is the kind of wrongness that survives every structural check and fails at the
first token, and the fix (take vocab_size from config.json, fall back to lm_head.weight when tie_word_embeddings is declared) removes both at once.

What I checked: the fallback is conditional on tie_word_embeddings, so a pack that is not declared tied still refuses rather than quietly borrowing a head as its
embedding — that is the distinction that keeps this from being "read any table that looks like one". And the new refusal names what it wants (config.json states no vocab_size and the container has no embedding …) instead of surfacing a missing-tensor message from three layers down.

One test worth adding while the fixture is open: a pack with vocab_size in config.json disagreeing with the tiled table's row count, asserting which wins.
Today the answer is config.json (correct — the table's shape[0] is a tile count and must not be trusted), but pinning that disagreement is what stops a future reader
"fixing" the code to prefer the tensor. That fixture is cheap and it is the exact confusion this PR exists to end.

Reviewed read-only: the diff and the fallback condition.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at c87ae9a — and the arm that matters is the one about tiles, not the tied table.

The trap it catches

static constexpr int kTileRows = 32;
dims_.vocab = emb->shape.size() >= 3 ? int(emb->shape[0] * kTileRows) : int(emb->shape.at(0));

A tiled entry's shape is [tile_rows, tile_cols, tile_bytes], so shape[0] is a tile count, not a row count — and the arm says it exactly:

tiled embed: 2 tiles x 32 rows is vocab 64, not 2

That is the whole review. Silent vocab truncation by a factor of 32 would sample from a thirty-second of the table, and the numbers would look plausible. The 2-D branch keeps the plain row shape, so nothing changes for untiled containers.

The precedence, which is right in both directions

config.json vocab_size  ->  else the embedding table's rows  ->  else lm_head.weight when tie_word_embeddings  ->  else throw
  • config first is correct even when the table disagrees, because a packed table is often padded (151,936 declared, 152,064 shipped) and sampling must run over the declared range while the gather runs over the rows that exist.
  • the tie direction is right too: model.embed_tokens.weight wins when both exist, and lm_head.weight is only consulted when the embed table is absent and tie_word_embeddings is set.
  • the failure is named, not generic: the message lists both candidate table names, so a pack that has neither tells you what it looked for.

One observation, not a request

Nothing cross-checks vocab_size against the table's row count, and I think that is correct — padding makes disagreement normal — but a one-line comment saying which governs sampling and which governs gathering would save the next reader the derivation I just did.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at c87ae9a — two failures fixed by one precedence change, both named, both with a test arm, and the one constant the fallback depends on is verified against the header it cites.

What the change fixes, and why the old line could be wrong twice

-  dims_.vocab = int(tensor("model.embed_tokens.weight").shape.at(0));
+  if (c.contains("vocab_size")) dims_.vocab = c.at("vocab_size");
+  else { … find("model.embed_tokens.weight");  if (!emb && c.value("tie_word_embeddings", false)) emb = find("lm_head.weight");
+         if (!emb) throw …("no vocab_size and the container has no embedding table");
+         dims_.vocab = emb->shape.size() >= 3 ? int(emb->shape[0] * kTileRows) : int(emb->shape.at(0)); }

Two independent defects behind one line, and the second is the dangerous one: a tiled entry's shape[0] is a TILE count, so a 248,320-row table stored as [7760, 4, 8704] was reported as vocab 7760, hidden 4 — a plausible pair of numbers, not an error, which is exactly the class that survives to a device run and produces "the model talks nonsense". The first (a tied pack shipping only lm_head.weight) at least threw, with a message naming a tensor the pack does not have.

The constant, checked where the comment says to look

npu/q4nx.h:16   "A Q4NX weight is a grid of 32-row x 256-column" tiles
npu/q4nx.h:19   "Index g*32 + r means column group g (32 columns) of row r"
7760 * 32 = 248,320      ← the comment's own example, consistent

So kTileRows = 32 is the header's number, not a new one, and the multiplication is the right direction (tiles × rows-per-tile), with 2-D shapes taken as plain rows.

The arms are the right two

tied pack with the table only as `lm_head.weight`  → loads, vocab from config.json (777)
tiled embed with no vocab_size                     → vocab 2*32 = 64, NOT 2    ← the tile-count bug

The second is the arm I would have asked for: it asserts the number the old code got wrong (2 instead of 64) rather than only "it loads". A fixture that just checked why.empty() would have passed the buggy version.

One note: the throw's message is good ("config.json states no vocab_size and the container has no embedding table (model.embed_tokens.weight, or lm_head.weight for a model that declares tie_word_embeddings)") — it tells the reader both what is missing and what would satisfy it. If vocab_size and the embedding's row count ever disagree, the config value wins silently; a one-line warning on mismatch would be the last piece, but it is not this PR's subject.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY at c87ae9a

The shape of the bug is worth stating because it is the "plausible numbers" class again: the vocabulary was taken from tensor("model.embed_tokens.weight").shape.at(0), and for the 1.9/1.0.12 Decision packs there is no such tensor, so it threw "model has no tensor …"; where a table does exist but is not a plain [V, H], the same line reported vocab 7760, hidden 4 from a [7760, 4, 8704] table — a wrong geometry that parses cleanly.

Taking the vocabulary from config.json first is the right precedence: the config states the model's own contract, and the tensor is a derived view of it. The test file's own arms (tests/npu_model_bounds_test.cpp, +56/−9) are where the two cases are pinned, and the fallback path stays for packs whose config does not state it, so this is a precedence rule rather than a replacement.

Not run: the Decision packs themselves (not on this box). I did not build this head — the change is a precedence rule plus its arms, and my earlier note stands that a precedence claim needs the arm that shows the fallback still works when the config is silent, which the diff's second arm covers.

One ask, if it is cheap: the tier of "config says V, tensor says V'" disagreement is not stated here — if both exist and differ, which wins is now config, and a one-line note saying so (and that the tensor is only used when the config is silent) turns the precedence into a documented rule rather than an emergent one.

@bong-water-water-bong
bong-water-water-bong merged commit ef00e33 into main Nov 10, 2026
8 of 9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/tie-aware-vocab branch November 10, 2026 04:54
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at c87ae9a: READY — both defects are real, and the third case (tiles) is the one that shows the author thought past the bug report

Defect 1, and it is the one that blocked a real pack: dims_.vocab = tensor("model.embed_tokens.weight").shape.at(0) required a name a tied pack need not ship. FastFlowLM/D3-Edge-NPU2 declares tie_word_embeddings: true and carries the [248320, 1024] table only as lm_head.weight, so the load threw model has no tensor model.embed_tokens.weight — a refusal about which name rather than about the model. Falling back to lm_head.weight only when the config declares the tie is the right guard: it does not guess for an untied pack, where a missing embedding table is a genuine defect.

Defect 2: the vocabulary now comes from config.json's vocab_size when present, which is the authority the pack itself declares, with the tensor shape as the fallback. That also removes a silent class of error: a tensor-derived vocab is the padded/tiled row count, not the model's vocabulary, and the two differ on exactly the packs this issue is about.

The third case is why I am satisfied rather than merely approving: the test asserts 2 tiles × 32 rows is vocab 64, not 2 — i.e. it pins that the fallback multiplies by the tile row count instead of reading shape[0] as rows. That is a bug the fix itself could have introduced (reading a tiled table's first dimension as the vocabulary), and it is asserted by name. The two refusals are also asserted with the words a reader needs: the message must mention both vocab_size and embedding table, so a future regression cannot quietly become a different error.

One note, not blocking: the kTileRows = 32 constant is now a fact of the container layout living in npu/model.cpp. If a pack ever ships tiles of a different height, this is the line that will be wrong, and it will be wrong as a vocabulary — a plausible number, not an error. A one-line comment saying where 32 comes from (and that Q4NX only emits 32) would make that discoverable; the alternative is a derived value from the container's own metadata if it carries one.

Relevance to F9: this is the second pack-level defect found by running a 1.0.12 Decision pack on our route (the first was #1782's), and it is the kind that would otherwise be recorded as "that model does not work on our engine" rather than as a name the loader insisted on.

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