Repository navigation
npu: import and run a 1-bit sentence-embedding encoder (trit-embed-3l), host path first (#1311) - #1312
Conversation
…), 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
left a comment
There was a problem hiding this comment.
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.
|
#1312 ready for review at |
…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.
|
#1312 updated at |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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
34a57b1dis two commits:d14bc8a(the NPU GEMM hook, #1311 step 2) and49f5cb0(notices plus the*.embedexemption). npu/embed/embed_npu.his 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 > 128is refused, not truncated, and the model's own cap is 128 tokens.- Failure is safe.
tern_linearreturns false and the encoder returns an empty result withwhy, so a partly accumulatedxis 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_testandembed_wordpiece_testunderthermal-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 fixturetests/fixtures/trit_embed_tinyis synthetic (synthetic_model(seed=1311), 32-token vocab, d=8), so no model weights are committed. The*.embedexemption is for a binary container with no comment syntax.copyright.py --checkrc 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.
|
Re-verdict requested at The description is purged of the kernel-perf internals you listed — the per-design per-call timings, the Two code-comment fixes at the new head (no behaviour change; this is why the sha moved, so the re-verdict is at
Verified at this head, host only: |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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.mdwas already clean. - The
embed_npu.hcomment now matches the code (c961dec): a device failure fillswhy, 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
c961decis aCMakeLists.txtcomment 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".
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 ternarycodes 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.embedis a 16 KiB JSON header plus the payload it names.Measured
codes * scale: worst |Δw| 0, value set {-1,0,+1}, ~32 % zeros. int8 embedding tables and their row scales byte-identical. Container 18.9 MBapp/wordpiece.hvs the referenceBertTokenizer: 0 id mismatches on 2,552 distinct STS-B test sentences (exact ids incl.[CLS]/[SEP]and the 128-token truncation)trit_embed.pyctest embed_model embed_wordpiece trit_embed_pack3/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 testedembed_npu_gate_probe, 1,000 fixed sentences, onenpu-holdticket (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 inputonebit_npu_gemm_q8_probe) reports PASS on each of them: the device's int32 accumulators equal the host's integer sumstools/copyright.py --checkThe 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 thefc2 blocks — generated by the arena's pinned toolchain (
~/lb/zr1-elfgen.sh, full ELF only, no xclbin). Becausethe 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 samegemm_q8_rawthe ONNX EP's QDQ leg uses).app/embed_modelgrew a GEMM hook that hands the quantised activation (codes + power-of-two block scales) to abackend, 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/verifyfortrit-packed-v1→1bit-embed-1.app/wordpiece.h— the reference'sBertTokenizerpipeline (clean, CJK per character, lowercase, stripaccents, 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 activationemulation (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.
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 npuand the/v1/embeddingsroute with array input) and theHRX/CPU comparison; the NPU and host rows above are already the NPU-vs-CPU half of the measurement.