Skip to content

npu tokenizer: a SentencePiece vocabulary that keeps its merges is merged by rank (closes #1189) - #1209

Merged
bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-phi35-layers
Nov 6, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-phi35-layers

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Root cause

npu/tokenizer.cpp decided "this vocabulary is SentencePiece" from

spm_ = merges.empty() && has_meta;

A SentencePiece model exported to tokenizer.json keeps its merges (as ["▁","t"] pairs), so a
pack whose normalizer is {Prepend "▁", Replace " " -> "▁"} and which ships 61,249 merges fell through
to the byte-level GPT-2 path. That path byte-maps each byte of the metaspace (▁ = E2 96 81) into
characters the vocabulary does not spell byte-wise, so the text was encoded into pieces the model has
never seen.

Measured on the Phi-3.5-mini OGA pack (the pack named in #1189):

prompt ids for "The capital of France is" result
pack's own tokenizer.json (Hugging Face tokenizers) 5 — 450 7483 310 3444 338 —
engine before 11 top-1 'A', margin +0.032, mean +27.778, then 'Awesome'
engine after 5 top-1 'Paris', margin +4.491, mean +36.776, then '.'

So the model was never wrong: it was fed off-distribution ids. Same container, same weight tiles, both
runs host-GEMM, only the prompt text path changed. The 'Awesome'/<0x0A> garbage in the issue is
this bug's downstream symptom (the model emitting byte-fallback tokens).

The fix

Two narrow changes:

  1. Detection also accepts a non-empty merge list when the normalizer prepends the metaspace —
    the prefix spm() synthesises anyway. A normalizer that only rewrites spaces (ZAYA, laya) does not
    ask for a one and is left exactly as it was; byte-level vocabularies (Qwen, Llama, LFM, Gemma) are
    untouched because they carry Ġ, not ▁.
  2. Encoding for such a vocabulary merges the lowest-ranked adjacent pair, leftmost first, over the
    normalised text — the same heap the byte-level BPE already uses, plus the <0xNN> byte fallback the
    model's decoder reverses. Greedy longest-match is not a substitute: it disagrees with the reference
    on 6 of 20 measured strings of this pack's vocabulary, so a merge-list tokenizer is merged, not
    matched.

Verification

  • New committed fixture tests/data/spm_bpe_tokenizer.json + golden generated by Hugging Face
    tokenizers on that same file
    (an outside implementation, not a transcript of our output):
    0/10 before, 10/10 after. Wired as ctest tokenizer_spm_bpe; needs no model.
  • No regression on the existing paths, run against pack-provided tokenizers with HF-generated goldens:
    Phi-3.5 pack 29/30 (the one miss is a literal-metaspace string whose round trip Hugging Face
    itself loses), Qwen3-1.7B 30/30, Llama-3.2-1B 30/30 (specials excluded — the engine adds BOS
    from config.json), Zamba2-1.2B 8/8 (same shape, previously wrong for the same reason).
  • tokenizer_linear still passes: the rank merge is the heap path, O(n log n), so a long prompt does
    not go quadratic.

Oracle cross-check (same hour, AMD's own 1.8.0 stack on the same pack, npu-hold ticket, 12 s, amdxdna ERROR 0 -> 0)

top-5 std margin text
AMD OGA on the Phi pack . , and \n ; 3.454 +0.500 The capital of France is Paris.
our engine after this fix . , and \n ; 3.459 +0.540 Paris.

Identical top-5 order, std and margin, and AMD's own mean logit is +40.5 — i.e. the "+25-nat
offset" the issue treated as a candidate defect is this pack's normal behaviour, not our bug.

Closes #1189.

…rged by rank, not byte-level BPE (closes #1189)

The SentencePiece test was `merges.empty() && has_meta`. A SentencePiece model exported to
tokenizer.json keeps its merges as ["\u2581","t"] pairs, so a pack whose normalizer is
{Prepend \u2581, Replace space -> \u2581} and which ships 61,249 merges took the byte-level GPT-2
path, byte-mapping a metaspace the vocabulary does not spell byte-wise.

Measured on the Phi-3.5-mini OGA pack (engine#1189): "The capital of France is" encoded to 11
ids instead of the pack's 5 (450 7483 310 3444 338), so the model was fed off-distribution ids and
the same container answered 'Awesome' (top-1 'A', margin +0.032, near-flat logits) instead of
'Paris'.

Two changes, both narrow:

* detection also accepts a non-empty merge list when the normalizer PREPENDS the metaspace -- the
  prefix spm() synthesises anyway. A normalizer that only rewrites spaces (ZAYA, laya) does not ask
  for one and is left exactly as it was;
* such a vocabulary is encoded by merging the lowest-ranked adjacent pair, leftmost first, over the
  normalised text -- the same heap the byte-level BPE already uses, with the <0xNN> byte fallback
  the model's decoder reverses. Greedy longest-match is not a substitute: it disagrees with the
  reference on 6 of 20 measured strings of this pack's vocabulary.

Before/after, same container, same prompt text:
  before  11 prompt ids, top-1 'A',     margin +0.032, mean +27.778
  after    5 prompt ids, top-1 'Paris', margin +4.491, mean +36.776

Tests: tests/data/spm_bpe_tokenizer.json (+ golden from Hugging Face `tokenizers` on that same
file, so the expectation is an outside implementation) is 0/10 before and 10/10 after. The Phi-3.5
pack's own 30-case golden is 29/30 (the miss is a literal-metaspace round trip that Hugging Face
loses too), qwen3 30/30, llama-3.2-1B 30/30 with specials excluded, the Zamba2 family's
tokenizer.json 8/8, and the linear-time tokenizer test is unchanged.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Two notes for the reviewer, both measured after the PR was opened:

  1. Added tokens mid-prompt: ids still match the reference ('The capital<|endoftext|>of France' → [450, 7483, 32000, 310, 3444] on both sides). The decode differs cosmetically on such a stream ('…<|endoftext|> of France' vs '…<|endoftext|>of France') — pre-existing behaviour of the SPM decode path, unchanged by this PR, ids unaffected.
  2. Scope: this container's only serving route is forward-serve with NPU_INFER_HOST_GEMM=1 (1bit unified needs per-shape npu/ kernels, which this pack does not have yet), so every number in the body comes from that route. tokenizer_spm_bpe passes under ctest -R tokenizer (0/10 before the change, 10/10 after), and tokenizer_linear is unchanged.

@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 5df645ef.

The bug is real and I reproduced it on the real pack, not the fixture. The box has the actual
models/oga/Phi-3.5-mini-instruct_rai_1.8.0_npu_4K/tokenizer.json: model.type BPE, 61,249 merges,
normalizer Sequence[Prepend "▁", Replace " " -> "▁"], pre_tokenizer null, decoder Replace + ByteFallback —
exactly the shape the commit message describes. Oracle built with Hugging Face tokenizers 0.23.3 on that
same file, 19 round-trip-safe strings, tokenizer_test against it:

main (be8df65b), same oracle:  1/19 cases match   (rc 1)
this head (5df645ef):         19/19 cases match   (rc 0)

"The capital of France is" — HF wants [450,7483,310,3444,338] (5 ids, as the commit says); main produced
[1576,31937,5030,2410,31937,974,31937,16066,31937,275]. So the classification slip is as described and the fix
closes it.

The fixture's golden is genuinely HF-derived: re-encoded all 10 spm_bpe_tokenizer_golden.json cases with
tokenizers 0.23.3 on spm_bpe_tokenizer.json — 10/10 byte-identical to the committed ids. ctest -R tokenizer
on this head is 2/2 (the new tokenizer_spm_bpe exists only here; main has 1 tokenizer test), and tokenizer_test
exits 1 on failure (not the #657 zero-case-exits-0 shape).

No regression on the two paths that must not move. Qwen3-0.6B (byte-level GPT-2 vocab, Ġ escapes, no ▁) —
main 14/14, this head 14/14 on tests/data/qwen3_tokenizer_golden.json. Merge-less SPM path
(tokenizer_linear_test, and spm_ = merges.empty() still short-circuits spm_merges_) — identical output on
both arms: many pre-tokens 1048577 -> 1048577 ids, many added tokens 1048590 -> 139812, all cases ok.

Your "greedy is not a substitute" claim is right, and I measured it rather than taking it: rebuilt this head
with spm_merges_ forced to false (one line, nothing else) and re-ran the same oracle — 11/19, i.e. 8 strings
wrong, against 19/19 with rank merging.

Nits, none blocking:

  1. The commit message says the wrong-path encode was "11 ids"; I measure 10 on this box for that string with
    this same oracle (ids above). Worth correcting so the number survives re-derivation.
  2. "disagrees with the reference on 6 of 20 strings" for greedy — my set of 19 gives 8, count FAIL lines in
    the forced-off run. The direction is proven; the exact count depends on your string set, so it should be named
    by set or dropped.
  3. The classification has a silent branch with no test: a vocabulary with merges whose normalizer is
    {Replace " " -> "▁"} without Prepend deliberately stays on the byte-level path. One more fixture case
    (Replace only, merges kept, ids from HF) would make that branch falsifiable instead of documented.

Measured on pi prs, no model, no device, CPU only (thermal-run, Tctl <= 63 C).

@bong-water-water-bong
bong-water-water-bong merged commit ce2b6b2 into main Nov 6, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-phi35-layers branch November 6, 2026 03:27
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1189 - Partially compliant

Compliant requirements:

  • Fix the tokenizer to correctly detect SentencePiece vocabularies with merge lists
  • Ensure Phi-3.5-mini pack imports correctly and produces valid text output
  • Add test cases to verify the fix works

Non-compliant requirements:

  • Update documentation to reflect the change in tokenizer behavior (not addressed in this PR)

Requires further human verification:

  • Verification that the fix works on actual hardware with the Phi-3.5-mini pack
  • Manual testing of the tokenizer behavior with the specific pack mentioned in the issue
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect SentencePiece Detection

The tokenizer's detection logic for SentencePiece models was incorrectly relying only on an empty merge list. This caused SentencePiece models that keep their merge lists (like Phi-3.5-mini) to be treated as byte-level BPE models, leading to incorrect tokenization and garbage output. The fix correctly identifies SentencePiece models by checking both the presence of metaspace prefixes and whether the normalizer prepends the metaspace.

spm_ = has_meta && (merges.empty() || (root.contains("normalizer") && spm_prepends_meta(root["normalizer"])));
spm_merges_ = spm_ && !merges.empty();
Missing Byte Fallback Handling

The bpe function was modified to accept a byte_fallback parameter, but the original implementation did not handle byte fallback properly for SentencePiece vocabularies with merges. The new logic correctly handles byte fallback for such cases, ensuring that characters not found in the vocabulary are properly converted to byte fallback tokens.

std::vector<int> Tokenizer::bpe(const std::string& chars, bool byte_fallback) const {
    std::vector<std::string> word;
    for (size_t i = 0; i < chars.size();) {
        const size_t len = utf8_len(static_cast<unsigned char>(chars[i]));
        word.push_back(chars.substr(i, len));
        i += len;
    }
    // Merge the lowest-ranked adjacent pair, leftmost first, until none applies. The pairs sit
    // in a heap ordered by (rank, position) over a linked list of symbols, so a long piece costs
    // O(n log n) rather than a full rescan per merge; the merges and their order are unchanged.
    const size_t n = word.size();
    std::vector<size_t> prev(n), next(n);
    std::vector<uint32_t> ver(n, 0);
    for (size_t i = 0; i < n; ++i) {
        prev[i] = i - 1;  // wraps to SIZE_MAX for the first symbol
        next[i] = i + 1;  // n for the last
    }
    struct Pair {
        int rank;
        size_t left, right;
        uint32_t vl, vr;
        bool operator>(const Pair& o) const { return rank != o.rank ? rank > o.rank : left > o.left; }
    };
    std::priority_queue<Pair, std::vector<Pair>, std::greater<Pair>> heap;
    auto push = [&](size_t l, size_t r) {
        if (l >= n || r >= n) return;
        auto it = merge_ranks_.find(word[l] + "\x1f" + word[r]);
        if (it != merge_ranks_.end()) heap.push({it->second, l, r, ver[l], ver[r]});
    };
    for (size_t i = 0; i + 1 < n; ++i) push(i, i + 1);
    while (!heap.empty()) {
        const Pair p = heap.top();
        heap.pop();
        // stale: a side was merged away or changed since this pair was queued
        if (ver[p.left] != p.vl || ver[p.right] != p.vr || next[p.left] != p.right) continue;
        word[p.left] += word[p.right];
        word[p.right].clear();
        ++ver[p.left];
        ver[p.right] = UINT32_MAX;  // never matches a queued pair again
        next[p.left] = next[p.right];
        if (next[p.left] < n) prev[next[p.left]] = p.left;
        push(prev[p.left], p.left);
        push(p.left, next[p.left]);
    }
    std::vector<int> ids;
    for (size_t i = 0; i < n; i = next[i]) {
        if (auto it = vocab_.find(word[i]); it != vocab_.end()) { ids.push_back(it->second); continue; }
        // A SentencePiece vocabulary covers its text with <0xNN> pieces for anything its merges
        // cannot spell (the byte fallback the model's decoder reverses); a byte-level vocabulary
        // has no such pieces and drops the symbol, which is what it always did.
        if (!byte_fallback) continue;
        for (unsigned char b : word[i])
            if (auto fb = byte_fallback_.find(b); fb != byte_fallback_.end()) ids.push_back(fb->second);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

1 participant