Skip to content

npu: import and run a 1-bit sentence-embedding encoder (trit-embed-3l), host path first (#1311) - #1312

Merged
bong-water-water-bong merged 5 commits into
mainfrom
1bit/npu-embed-trit
Nov 7, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
1bit/npu-embed-trit

Conversation

@bong-water-water-bong

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

Copy link
Copy Markdown
Collaborator

What this is

The first half of #1311, measured device-free: the import, the tokenizer and the encoder forward for
a 1-bit sentence-embedding model, reproducing the reference's numbers. The NPU GEMM path, the serve flags and the
HRX/CPU/NPU timing rows are the rest of the issue and are not in this PR (see the issue comment for exactly
what remains).

First model: Cyronius/trit-embed-3l (MIT; NOTICE entry added). 3 post-norm BERT layers, width 384, 12 heads,
FFN 1536, 30522 WordPiece pieces, ≤128 tokens, mean pooling, 384-dim unit vectors.

Why the container is not a q4nx one

q4nx's quantised tensors are 32×256 chunk grids. This model's rows are 384/1536 wide with one scale per output
row
and 2-bit ternary codes, so tiling would pad K to 512 and re-round the scale into per-128-block fp16 —
moving numbers the gate compares exactly. The importer (tools/trit_embed_pack.py) therefore widens the ternary
codes to int8 (values unchanged; XDNA2 has no ternary datapath, so the widening belongs to the format) and
keeps the model's own per-row scale in f32. model.embed is a 16 KiB JSON header plus the payload it names.

Measured

row result
importer known answer (the gate's foundation) all 18 ternary linears decode to exactly the reference's codes * scale: worst |Δw| 0, value set {-1,0,+1}, ~32 % zeros. int8 embedding tables and their row scales byte-identical. Container 18.9 MB
tokenizer app/wordpiece.h vs the reference BertTokenizer: 0 id mismatches on 2,552 distinct STS-B test sentences (exact ids incl. [CLS]/[SEP] and the 128-token truncation)
gate: cosine vs trit_embed.py 1,000 fixed sentences (first 1,000 unique STS-B test sentences, file order): min cosine 0.999706, mean 0.9999945, 0 sentences below the 0.999 gate
independent cross-check a numpy forward written from the model card's documented arithmetic reproduces the C++ numbers (worst |Δp| 4.2e-3, min cosine 0.99971), so the C++ is not agreeing with itself
reference's own noise floor its batching alone moves vectors by max |Δp| 2.2e-3 / min cosine 0.99988, i.e. the 0.999 gate has ~10× headroom over the reference's own packing sensitivity
STS-B Spearman ×100 (reference) 82.75 on 1,379 pairs at the 128-token cap (model card 82.87; the gate allows ±0.3) — the evaluator is the card's
STS-B Spearman ×100 (this engine's forward) 82.7538 over 1,379 pairs, 128-token cap — the reference scores 82.7538 on the same evaluator and the model card says 82.87, so |engine − card| = 0.116 against the gate's 0.3
CI ctest embed_model embed_wordpiece trit_embed_pack 3/3; the C++ encoder agrees with the fixture's independent numpy reference to 1.2e-7; importer refusals (reserved ternary code 3, unknown format) are tested
the same gate on the NPU embed_npu_gate_probe, 1,000 fixed sentences, one npu-hold ticket (10 s wait, 279 s held): min cosine 0.9997062, mean 0.999994544, 0 below 0.999 — identical to the host path on the same binary and input
rate, single binary, one input NPU 28.3 sentences/s (35.3 s / 1,000 sentences) vs host 4.1 sentences/s (243.2 s / 1,000) — 6.9×
q8 GEMM exactness, our three shapes the engine's own probe (onebit_npu_gemm_q8_probe) reports PASS on each of them: the device's int32 accumulators equal the host's integer sums
tools/copyright.py --check rc 0

The host forward is 3.8 sentences/s here (naive O(T²) attention, scalar loops, one thread) — that is the baseline
the NPU row has to beat, recorded rather than dressed up.

The device path

Three full-ELF designs cover the encoder — (K384,N384) for q/k/v/o, (K384,N1536) for fc1, (K256,N384) for the
fc2 blocks — generated by the arena's pinned toolchain (~/lb/zr1-elfgen.sh, full ELF only, no xclbin). Because
the container already holds int8 codes and the array executes int8×int8→int32, the device path is not a
re-quantisation: codes and the reference's int8 activations go to the buffers unchanged and the scales multiply the
int32 sums on the host (npu/embed/embed_npu.h, calling the same gemm_q8_raw the ONNX EP's QDQ leg uses).

app/embed_model grew a GEMM hook that hands the quantised activation (codes + power-of-two block scales) to a
backend, so a device path cannot silently see a float activation; the host dot remains the default. One measured
constraint shaped the design: fc2's 1536-wide input must keep the reference's per-256-block scales — replacing
them with one per-token scale puts 73 of 1,000 gate sentences below 0.999 — so fc2 is computed per 256-channel
block, with each block's scale applied to its partial sums before they are added up.

What is in the diff

  • tools/trit_embed_pack.py — pack / verify for trit-packed-v1 → 1bit-embed-1.
  • app/wordpiece.h — the reference's BertTokenizer pipeline (clean, CJK per character, lowercase, strip
    accents, punctuation split, greedy longest-match with ##, whole-word [UNK], [CLS]/[SEP], truncation).
  • app/embed_model.{h,cpp} — container reader + post-norm BERT-3L forward with the reference's int8 activation
    emulation (power-of-two per-token scale, per-256-block when the width calls for it, half-to-even, clamp ±127),
    masked mean pooling, output projection, L2; refusals for off-vocabulary ids / empty / over-length sequences.
  • tests: the importer's known answers and refusals, the tokenizer rules, and a 32 KB tiny fixture (container +
    vocab + expected vectors) the C++ encoder loads.
  • docs/npu.md — "Sentence embeddings (1-bit encoder containers)"; NOTICE — the model's attribution (Cyronius,
    MIT, bge-micro-v2 lineage).

refs #1311 — two of the issue's five items are done (import, NPU forward). What remains is the serving item
(--embed MODEL --device npu / --embedding --device npu and the /v1/embeddings route with array input) and the
HRX/CPU comparison; the NPU and host rows above are already the NPU-vs-CPU half of the measurement.

…), host path first (#1311)

The first half of #1311, measured device-free: the importer, the WordPiece tokenizer the model's ids depend
on, and the encoder forward, all reproducing the reference's numbers.

* tools/trit_embed_pack.py: trit-packed-v1 safetensors -> a 1bit-embed-1 container. The ternary codes are
  widened to int8 (XDNA2 has no ternary datapath) and the model's own per-output-row scale is kept in f32, so
  code*scale is bit-identical to the reference's decode (worst |dw| 0, not a tolerance). A container of its
  own rather than q4nx tiles because q4nx tiles are 32x256 and this model's rows are 384/1536 wide: tiling
  would pad K and re-round the scale into per-128-block fp16, which moves numbers the gate compares exactly.
* app/wordpiece.h: the reference's BertTokenizer pipeline (clean, CJK per character, lowercase, strip accents,
  punctuation split, greedy longest-match with ## continuations, whole-word [UNK]). Measured: 0 id mismatches
  on 2,552 distinct STS-B test sentences.
* app/embed_model.{h,cpp}: post-norm BERT-3L forward with the reference's int8 activation emulation (power-of-two
  per-token scale, round-half-to-even, clamp +-127, dequantise), masked mean pooling, output projection, L2.
  Measured against the model's own trit_embed.py on 1,000 fixed sentences: min cosine 0.999706, mean 0.999995.
* tests: importer known answers and refusals, the tokenizer rules, and a tiny fixture the C++ encoder loads
  (worst |dv| 1.2e-7 against an independent implementation of the documented arithmetic).

The NPU GEMM path (a 384-geometry full-ELF set -- the probe compiles: full_i8_Q_K384_N384.elf, 1 s), the serve
flags and the HRX/CPU/NPU measurement are the rest of #1311 and are not in this PR.

@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 34a57b1d — I re-packed the real model on this box and got the author's container byte for byte, and its own known-answer verify comes back exact; the three tests that ship with the PR all pass here, two of them ones I compiled myself.

The importer is deterministic and exact on the real model (device-free, 14 MB source):

tools/trit_embed_pack.py pack   ~/models/embed/trit-embed-3l  /tmp/…/embedpk
  source: 74 tensors, vocab 30522, d 384, heads 12, ffn 1536, layers 3, max_pos 128, pool mean, gelu tanh
  wrote model.embed  17914344 B, 74 tensors, 18 ternary linears
sha256   mine aae921532c3be2a2…   author's ~/models/embed/trit-embed-3l-1bit/model.embed aae921532c3be2a2…   identical

tools/trit_embed_pack.py verify ~/models/embed/trit-embed-3l /tmp/…/embedpk
  ternary linears: 18 checked, worst |dw| vs the reference 0
  int8 tables and row scales: word/pos byte-identical to the source
  embedding lookup (ids [1019, 1996, 2456]): first row norms [1.259027, 1.196662, 1.475901], identical to the source
  verify: OK

Worst |Δw| of zero across 18 ternary linears is the right shape for a format whose whole claim is "widening {-1,0,+1} to int8 loses nothing", and the byte-identical container means the import has no hidden nondeterminism (key order, float formatting) that would make a future rebuild differ from a published artifact.

The shipped tests, run here — tests/trit_embed_pack_test.py (pack + verify: OK, plus both refusals: reserved ternary code 3, unknown format), and the two C++ ones compiled standalone with the tree's include set (g++-16 -std=c++20 -Iapp -DSRC_DIR=…):

embed_wordpiece: ok
embed_model: ok      case 4 / case 6: 8 tokens, worst |dv| 1.192e-07, norm 0.999999973 / 0.999999960

The model test compares against the committed tests/fixtures/trit_embed_tiny/expected.json with a 2e-5 tolerance and asserts unit norm to 1e-5; what I measured is 1.19e-07, i.e. ~170x inside the tolerance — so the tolerance is not doing the work. The WordPiece test covers the pipeline the ids depend on (cleaning, case, accents, CJK, ##, [CLS]/[SEP], truncation), which is where a BERT-family importer usually breaks silently.

Nit, one number, and I checked it by building the thing: CMakeLists.txt:769 says the real model's gate "needs the 13.9 MB container". 13.9 MB is the safetensors source (~/models/embed/trit-embed-3l/model.safetensors = 13,901,928 B); the container the importer writes is 17,914,344 B (17.9 MB) — int8 codes plus one f32 scale per output row are larger than the packed 1-bit source. Since the same paragraph is about what has to be present for the gate to run, the two numbers should not be swapped.

Scope is honest and I am holding the verdict to it: the NPU GEMM path, the serve flags and the HRX/CPU/NPU timing rows are explicitly out (#1311's remaining half), NOTICE gains the MIT entry for Cyronius/trit-embed-3l, and the docs say plainly that the real-model gate (min cosine 0.9997 vs the reference on 1,000 sentences) is a measured row rather than a test. I did not re-run that row: it needs a serve path this PR does not add, and the reference trit_embed.py on disk is the author's harness. What I can say is that everything the PR does ship runs green here, and that the container it produces is reproducible to the byte.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#1312 ready for review at 34a57b1d — the STS-B row is in the body now: this engine's forward scores 82.7538 on the card's evaluator (reference 82.7538, card 82.87, gate ±0.3), and the cosine gate on 1,000 fixed sentences is min 0.999706 (0 below 0.999). The NPU GEMM path, the serve flags and the NPU/HRX/CPU timings are the rest of #1311, tracked on the issue.

pi-npufeat added 2 commits November 6, 2026 23:37
…GEMM (#1311 step 2)

The container already holds int8 codes with one per-row scale, and the array executes int8*int8 -> int32, so
the device path is not a re-quantisation: codes and the reference's int8 activations go to the buffers as they
are and the scales multiply the int32 sums on the host. The call is the engine's own gemm_q8_raw (the ONNX EP's
QDQ leg), which writes both buffers verbatim and hands back exact accumulators.

* app/embed_model: a GEMM hook that receives the quantised activation (codes + power-of-two block scales), so a
  device backend cannot silently see a float activation.
* npu/embed/embed_npu.h: the hook. Widths 384 (q,k,v,o,fc1) launch once; fc2's 1536-wide input keeps the
  reference's per-256-block scales as six K=256 launches, because dropping them puts 73/1000 gate sentences
  below 0.999 (measured).
* npu/embed/embed_gate_probe.cpp + CMake (ONEBIT_NPU builds only): the gate from the tree.

Measured on one binary and one input, 1000 fixed sentences (npu-hold ticket, 10 s wait, 279 s held):
  NPU   min cosine 0.9997062  mean 0.999994544  28.3 sentences/s (33,000 launches)
  host  min cosine 0.9997062  mean 0.999994544   4.1 sentences/s
i.e. the same vectors 6.9x faster, and the three 384-geometry designs are exact against the host accumulators
(full_i8_Q_K384_N384 / GU_K384_N1536 / D_K256_N384, generated by the arena's pinned toolchain).
…; the container fixture is exempt

copyright.py --check flagged both: the two new Python files had the SPDX lines but not the licence body, and
the 18 KB binary fixture has no comment style. The rule for the fixture is the same one tests/golden/*.bin
already has.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#1312 updated at 49f5cb0c: the NPU path is in. Three full-ELF designs (K384N384, K384N1536, K256N384), the engine's own int8 GEMM, and the gate re-run from the tree: min cosine 0.9997062 on 1,000 sentences (0 below 0.999, identical to the host path) at 28.3 sentences/s vs 4.1 host = 6.9x, one ticket 279 s. Remaining for #1311: the serve flags and /v1/embeddings, and the HRX comparison.

@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 at 49f5cb0c4b7cc32f4e0221450eb1674a4cf83cf0. Body text only: the code is fine. This public engine PR's description carries kernel-perf internals, which the lane rules keep out of public PR text. Edit the description, leave the head as it is, and I'll re-post READY at this same sha.

What to take out of the description (it can stay in your state file or #1311's private evidence):

  • "q8 GEMM exactness, our three shapes … 1.164 / 3.615 / 0.861 ms per call at M=128": per-design kernel timings;
  • "33,000 launches" and the per-shape "49,152 / 196,608 / 49,152 values" in the probe row;
  • "a launch costs the same for a 6-token sentence as for a 128-token one", as a statement about kernel cost, in the device-path section.

End-to-end, model-level rows are fine to keep: the gate cosines, NPU 28.3 vs host 4.1 sentences/s, STS-B. docs/npu.md is already clean; nothing per-kernel is in it.

Checked here, at this head (host only)

  • The delta since the other reviewer's READY at 34a57b1d is two commits: d14bc8a (the NPU GEMM hook, #1311 step 2) and 49f5cb0 (notices plus the *.embed exemption).
  • npu/embed/embed_npu.h is correct. Codes are transposed once per (weight, k-block). For fc2, each 256-channel block is gathered into contiguous rows, the int32 sums are rescaled by that block's per-row activation scale and the weight's per-row scale, and they are accumulated across the six blocks. The bias is added once. rows > 128 is refused, not truncated, and the model's own cap is 128 tokens.
  • Failure is safe. tern_linear returns false and the encoder returns an empty result with why, so a partly accumulated x is never used. Nit: embed_npu.h's comment "the caller keeps its host result" is not what happens. There is no host fallback; the request fails with the reason. Reword it, or add the fallback.
  • Build: embed_model_test and embed_wordpiece_test under thermal-run.sh, rc 0. ctest -R 'embed_model|embed_wordpiece|trit_embed_pack' → 3/3 passed.
  • Licensing: the NOTICE entry for Cyronius/trit-embed-3l (MIT) is under "downloaded separately, not redistributed". The fixture tests/fixtures/trit_embed_tiny is synthetic (synthetic_model(seed=1311), 32-token vocab, d=8), so no model weights are committed. The *.embed exemption is for a binary container with no comment syntax. copyright.py --check rc 0.

Not re-run: the NPU gate (1,000 sentences, min cosine 0.9997062 identical to host) and the rate rows. They need the generated ELFs and an npu-hold ticket, and nothing in this verdict depends on them.

…eds the 17.9 MB container

Two comment-level corrections from review: embed_npu.h's hook said the caller keeps its host result, which is
not what happens (a device failure fails the request with the reason -- a caller wanting the host dot simply
does not install the hook), and CMakeLists.txt called the 17.9 MB container 13.9 MB, which is the source
safetensors. No behaviour change: the three embedding tests and the probe still build and pass.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Re-verdict requested at c961decf.

The description is purged of the kernel-perf internals you listed — the per-design per-call timings, the
launch count, the per-shape accumulator counts, and the "a launch costs the same for a 6-token sentence as for a
128-token one" claim are all gone. I also reworded the fc2 sentence so it describes the arithmetic (each
256-channel block's scale is applied to its own partial sums before they are added) instead of how many GEMM calls
that takes. What is left in the device section is the model-level story: three full-ELF designs, int8 codes and the
reference's int8 activations into the buffers unchanged, scales applied on the host, and the per-block constraint
as a gate number (73/1000 sentences below 0.999 without it). End-to-end rows kept as you said: NPU/host cosines,
28.3 vs 4.1 sentences/s, STS-B 82.7538. grep -E 'ms/call|launches|49,152|196,608|1\.164|3\.615|0\.861' on the new
body returns nothing.

Two code-comment fixes at the new head (no behaviour change; this is why the sha moved, so the re-verdict is at
c961decf rather than 49f5cb0c):

  1. npu/embed/embed_npu.h: the hook's comment now says what actually happens — a device failure fills why and the
    encoder returns nothing, i.e. there is no silent host fallback; a caller that wants the host dot simply does
    not install the hook (the probe's --host arm is that caller). status()/used_device() described as they are.
  2. CMakeLists.txt:769: the gate needs the 17.9 MB container; 13.9 MB is the source safetensors. Both numbers
    named so the paragraph cannot be read as swapped.

Verified at this head, host only: copyright.py --check rc 0, ninja embed_model_test embed_wordpiece_test embed_npu_gate_probe rc 0 under thermal-run.sh, ctest -R 'embed_model|embed_wordpiece|trit_embed_pack' 3/3.

Comment thread app/embed_model.cpp Fixed
Comment thread app/embed_model.cpp Fixed
Comment thread app/embed_model.cpp Fixed
Comment thread app/embed_model.cpp Fixed

@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 c961decf0b97eff7bb15632626fd89d044539108. Both points from my CHANGES at 49f5cb0c are resolved.

  • The kernel-perf internals are out of the public description. The per-design ms/call, the launch count and the per-shape probe value counts are gone. What remains is model-level (the gate cosines, NPU 28.3 vs host 4.1 sentences/s end to end, STS-B), and the q8 probe row now says only PASS. docs/npu.md was already clean.
  • The embed_npu.h comment now matches the code (c961dec): a device failure fills why, the encoder returns an empty vector, and there is no silent host fallback. used_device() = launches_ > 0 && !failed_, so a row can't claim the array after a failed launch.
  • The only other change in c961dec is a CMakeLists.txt comment correcting the container size (17.9 MB written, from a 13.9 MB source). It is a comment, not a build change.

Everything else from my review at 49f5cb0c stands: the fc2 per-block rescale is correct, the 128-row refusal, ctest embed_model|embed_wordpiece|trit_embed_pack 3/3, the synthetic fixture, and the NOTICE entry.

Nit: the description's opening paragraph still says "The NPU GEMM path, the serve flags and the HRX/CPU/NPU timing rows are the rest of the issue and are not in this PR". Since d14bc8a, the NPU GEMM path is in it, and its table measures it. Change that to "the serve flags and the HRX timing rows are not".

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.

2 participants