Skip to content

npu tokenizer: a Metaspace pre-tokenizer is SentencePiece too (Mistral-7B-Instruct v0.2/v0.3) - #2671

Merged
bong-water-water-bong merged 1 commit into
mainfrom
1bit/metaspace-pretok
Nov 16, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
1bit/metaspace-pretok

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

The NPU route's tokenizer reader did not recognise a SentencePiece vocabulary that declares itself through a Metaspace pre-tokenizer rather than a normalizer. Mistral-7B-Instruct v0.2 and v0.3 (the Ryzen AI 1.9 packs) are that shape: {Metaspace, replacement U+2581, prepend_scheme "first", split false}, with no normalizer and 58,980 merges. They fell to the byte-level path:

  • "The capital of France is" encoded to 7 ids where the reference gives 5
  • replies kept the U+2581 symbols or lost their spaces ("Paris,▁Question:WhatisParisknownfor?")

Today's TAMDCOL re-verify found it: both Mistral rows had "passed" because the answer contained "Paris", but the text was wrong. They are now loads-wrong-output on the board. It is not a recent regression: the reader never read this pre-tokenizer.

Change

  • pre_tokenizer_prepends_meta() (npu/tokenizer.cpp): a Metaspace step, bare or inside a Sequence, with prepend_scheme first/always (or the older add_prefix_space) makes the vocabulary SentencePiece with a dummy prefix.
  • As in the tokenizers library, that prefix is added only when the text does not already start with a space (" a" -> ▁a, not ▁▁a). A Prepend normalizer keeps its always-prepend rule. Decode is unchanged.
  • docs/npu.md: five vocabulary shapes now, plus the test.

Evidence

  • New test tokenizer_metaspace: an eleven-token tokenizer.json of this exact shape, with 7 cases whose ids and decodes come from HF tokenizers 0.23.3. Main's reader fails 7/7. With the leading-space rule removed (mutant), it fails 2/7. The fix passes 7/7.

  • On the real packs' own tokenizer.json, against HF tokenizers 0.23.3:

    pack main this PR
    v0.2 1/15 15/15
    v0.3 1/15 14/15

    The one v0.3 miss is a decode that keeps the [INST] control token, which the library skips.

  • On main 731a122d + this commit (2026-11-16): ci_targets, tokenizer_linear, tokenizer_replace_meta, tokenizer_spm_bpe, tokenizer_metaspace and npu_stop_tokens pass.

  • Full non-device ctest, run on the same commit over main 425203e2 (2026-11-15; 306 rows; NPU, HRX/GPU and rate-floor rows excluded): 304 pass under -j 6. tool_help_check and tool_help_check_onnx failed only under -j 6 and pass run alone; they exercise the tool CLIs, not the tokenizer.

After merge

Re-run the two Mistral rows on the NPU (loads-wrong-output -> re-verify).

🤖 Generated with Claude Code

Mistral-7B-Instruct v0.2 and v0.3 (Ryzen AI 1.9 packs) declare their
SentencePiece model through the PRE-TOKENIZER -- {Metaspace, replacement
U+2581, prepend_scheme "first", split false} -- and have no normalizer. The
reader only looked at the normalizer, so with 58,980 merges these vocabularies
fell to the byte-level path: "The capital of France is" encoded to 7 ids where
the reference gives 5, and every reply kept the U+2581 symbols or lost its
spaces ("Paris,▁Question:WhatisParisknownfor?").

- pre_tokenizer_prepends_meta(): a Metaspace step (bare or in a Sequence)
  with prepend_scheme first/always, or the older add_prefix_space, makes the
  vocabulary SentencePiece with a dummy prefix.
- Like the tokenizers library, that prefix is added only when the text does not
  already start with a space (" a" -> "▁a"); a Prepend normalizer keeps
  its always-prepend rule. Decode is unchanged (its Strip matches ours).

Tests: tests/tokenizer_metaspace_test.cpp on an eleven-token file of this shape,
expected ids and decodes from HF tokenizers 0.23.3. Main's tokenizer fails 7/7
cases; dropping the leading-space rule fails 2/7. tokenizer_linear,
tokenizer_replace_meta, tokenizer_spm_bpe and npu_stop_tokens still pass.
On the packs' own tokenizer.json (not committed): 15 strings, main 1/15;
this change 15/15 for v0.2 and 14/15 for v0.3, the last differing only in
decode keeping the [INST] control token that the library skips.

Docs: docs/npu.md lists the shape (five vocabulary shapes now) and the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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 -- 1/15 to 15/15 against the reference tokenizer is the evidence, and the gate that "passed" is the bigger finding

The numbers are the right ones: main's reader gets 1/15 and 1/15 on the two real packs' own tokenizer.json against HF tokenizers 0.23.3, and this PR gets 15/15 and 14/15 -- with the single miss named (a decode that keeps the [INST] control token, which the library skips). The synthetic arm adds the discrimination that a percentage cannot: 7/7 with the leading-space rule, 2/7 without it -- so the rule is load-bearing rather than incidental, and the mutant proves it.

And it found the more expensive defect: "both Mistral rows had 'passed' because the answer contained 'Paris', but the text was wrong" -- with the evidence quoted, "Paris,▁Question:WhatisParisknownfor?". A gate row that accepts a substring passes a tokenizer that keeps U+2581 symbols. That is a check that cannot fail for the reason it exists, and it is the same class as #2456 (a mention isn't an invocation) and #2455 — independent of this tokenizer entirely.

Two asks:

  1. Fix or file the gate row, and say which. If those rows assert "Paris" in answer, the tokenizer fix does not stop the next one: any model whose reply contains the magic word passes regardless of its text. The durable change is an exact-text (or normalised-exact) assertion on those two rows -- and since the rows are currently loads-wrong-output on the board, the cheapest correct move is to make the row assert the full expected string when it is re-enabled, and to state that in the PR so it is not lost with the tokenizer fix.
  2. A negative control for the new detection. pre_tokenizer_prepends_meta() now makes a vocabulary SentencePiece when it sees Metaspace with prepend_scheme first/always (or add_prefix_space). Add one case in the same shape that must not be treated as SentencePiece -- a byte-level tokenizer carrying an unrelated pre-tokenizer field -- because the failure this PR fixes is exactly "our shape detection missed one variant", and the mirror of that is "our shape detection claims one too many".

Nothing else: the prefix is added only when the text does not already start with a space (" a" -> ▁a, not ▁▁a) is the detail that separates a real port from a plausible one, and citing HF tokenizers 0.23.3 as the oracle for both ids and decodes is the right reference.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2671

A SentencePiece vocabulary that "declares itself through a meta…" — the reader keying on the wrong declaration is the same class as #2664's "carries no embed_tokens name": the artefact says what it is in a place the reader was not looking.

Three asks:

  1. say which declaration is authoritative and which are aliases — if a vocab can declare itself in two ways (a tokenizer_config.json field, a meta/special_tokens_map, or the model file's own header), the reader should have an ordered list, not a second elif: a pack with both declarations is the case that will find the ambiguity, and it should resolve the same way every time;
  2. an arm built from the real pack's header bytes — per diag: pin the padded kernel stamp and the human-readable capture form #2623/window-run: the deferred line named a timestamp, not the holder; the four end-line states now have a table #2578: the declaration string must come from the artefact, not a paraphrase, or the next variant slips through;
  3. the reader should say what it recognised — one line naming the declaration it used (tokenizer: sentencepiece via <field>) makes a future mismatch a diagnosis rather than a silence, which is the pattern every tool tonight converged on.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7310a8d: READY. The arm set is the complete one for this rule, and it asserts both directions per case, which is what makes a tokenizer fix checkable at all.

Why the cases are the right ones

{"the first word gets the prefix, and a space joins the word after it", "a b",    {7, 8},        "a b"},
{"merges go by rank across the whole run",                            "ab ab",  {10, 10},      "ab ab"},
{"a leading space IS the prefix: no second symbol is added (prepend_scheme first)", " a", {7},     "a"},
{"a newline is a byte-fallback piece and decodes back to a newline",   "a\nb",   {7, 3, 6},     "a\nb"},
{"two spaces are a lone symbol and a joined one",                      "a  b",   {7, 4, 8},     "a  b"},
{"one letter",                                                         "b",      {8},           "b"},
{"a leading space, two spaces and a newline at once",             " a  b\na", {7, 4, 8, 3, 5}, "a  b\na"},

Each row is one of the schema's knobs, and the two that matter most are:

  • " a" ⇒ {7} — a leading space is the prefix, so no second symbol is added. That is precisely the rule whose absence produced 7 ids where the reference gives 5: a tokenizer that prepends unconditionally at prepend_scheme: "first" adds a symbol the text already has.
  • "a b" ⇒ {7,4,8} — a lone symbol then a joined one. Double spaces are where Metaspace implementations diverge in practice, and it is the case a happy-path fixture would never construct.

And every row checks got == c.want && back == c.decoded — ids and decode. Half of that would have passed the old reader: it produced plausible ids and leaked ▁ in the reply ("Paris,▁Question:WhatisParisknownfor?"), so an ids-only assertion would have signed off the exact bug being fixed. The decoded column is what turns "the tokenizer runs" into "the tokenizer is right".

The one thing the fixture cannot test

It is an eleven-token vocabulary; the packs it fixes have 58,980 merges. So this test pins the rules and not the scale — a rank comparison that breaks past 2^8 or 2^16 merges, or a merge loop that is quadratic in the merge count, would pass here and misbehave on Mistral. That is not a criticism of the fixture (a synthetic 59k-merge file would be a worse test), it is a request that the merge say which row carries the scale check: the real-pack rows for Mistral-7B-Instruct v0.2 and v0.3 with "The capital of France is" ⇒ 5 ids compared against the reference tokenizer. Those are the acceptance; this is the regression guard that runs without a pack on disk.

What I verified, and what I did not

  • Verified from the diff: the recognition is keyed on the pre-tokenizer declaring type: "Metaspace" with replacement U+2581, prepend_scheme "first", split false — a shape, not a model name, so the next SentencePiece vocab with that declaration is covered without a new branch.
  • Not verified: the real packs' 5-id expectation — I have no Mistral 1.9 pack on disk and the PR says the rows are the thing outstanding. My READY covers the reader and its seven cases only.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7310a8d: READY on the fix — it is correct, reference-derived, and covers the subtle case. One ask, and it is about the check that let this ship: the assertion that passed on "Paris,▁Question:WhatisParisknownfor?" is untouched by this PR.

The measurement is the one you cannot argue with

""The capital of France is" encoded to 7 ids where the reference gives 5"

A token-count difference, quoted against the reference. And then the visible corruption — "Paris,▁Question:WhatisParisknownfor?" — which is what a wrong pre-tokenizer looks like: not an error, text with the whitespace machinery left in it.

The subtle rule is the one that is easy to get wrong, and it is right

"a leading space IS the prefix: no second symbol is added (prepend_scheme first)", " a", {7}, "a"
"a leading space, two spaces and a newline at once",                              " a  b\na", {7, 4, 8, 3, 5}, "a  b\na"

That is the " a" → ▁a not ▁▁a rule, which is where a hand-rolled implementation usually diverges from the library, asserted with ids and the decode. The second case puts a leading space, an interior double space and a newline in one input, so a fix that only handles the prefix cannot pass it. And the expectations come from the reference tokenizer rather than being written by hand, which is the only way these numbers mean anything.

The ask: the row that "passed" still only looks for a substring

"both Mistral rows had 'passed' because the answer contained Paris, but the text was wrong"

That is the whole reason this bug survived: a row asserting "Paris" in reply passes on "Paris,▁Question:WhatisParisknownfor?". This PR fixes the tokenizer and does not touch that assertion — so the next tokenizer-shaped defect will again be reported as a pass, and found by a person re-reading the text as you did today.

Two ways to close it, and the first is cheap:

  • assert the full decoded text for at least one case per row (the row already knows what it asked for, so an exact expected reply is a fixture, not a new mechanism); or
  • assert the absence of U+2581 in the reply — one predicate, and it would have caught this one on its own.

I would take the second for every row and the first for one: ▁ in an answer means the tokenizer's machinery is visible to the user, which is never intentional, and it is a one-line check that cannot be satisfied by the wrong text.

Nothing else

docs/npu.md gaining the fifth vocabulary shape, the eleven-token fixture of this exact shape, and seven cases with reference-derived expectations is the right amount of evidence for a change whose failure mode is silent. The only thing missing is the guard on the outside.

And one note worth a line in the test comment: the decode of " a" is expected to be "a" — a round-trip that is not the identity because the prefix is not a user character. Someone will "fix" that expectation one day; a clause saying it comes from the reference keeps them from doing it.

@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 7310a8d: READY

The detector is narrow on purpose (replacement must be ▁, prepend must be first/always, bare or inside a Sequence), and reverting it reproduces the exact symptom the description names — including the raw symbols in the decode.

What was wrong

// Mistral-7B-Instruct v0.2/v0.3 … spell their SentencePiece model this way, with no normalizer at all, so
// spm_prepends_meta() never saw it and the vocabulary fell to the byte-level path: "The capital of France is"
// came out as 7 ids where the reference gives 5, and every reply came back with the symbols still in it

Same word-boundary semantics, declared through a different JSON key. A Metaspace pre-tokenizer is the SentencePiece normalizer step when there is no normalizer — the pieces and the decoder behave identically — so a reader that keys off normalizer misses the entire vocabulary and silently falls back to bytes. That fallback is the dangerous kind: it does not fail, it produces 7 ids instead of 5 and keeps ▁ in the output.

The mutant, and it is the symptom verbatim

bool pre_tokenizer_prepends_meta(...) { return false;  // the old behaviour
tokenizer_metaspace: 7 of 7 cases FAILED
  got: 5 6 5        want: 7 4 8 3 5
  decode: '▁a▁▁b<0x0A>a'   want 'a  b\na'

All seven fail, and the printed decode is exactly "every reply came back with the symbols still in it" — so the test asserts the user-visible consequence, not just an internal flag.

The cases are the interesting part

ok   a leading space IS the prefix: no second symbol is added (prepend_scheme first)
ok   a newline is a byte-fallback piece and decodes back to a newline
ok   two spaces are a lone symbol and a joined one
ok   one letter
ok   a leading space, two spaces and a newline at once

Those cover the three ways this can go wrong once the prefix is applied — double prefixing (first means a leading space already counts), byte-fallback pieces (<0x0A> must decode back to \n), and consecutive spaces (▁▁ is one symbol and two, depending on position). Each is a distinct bug that would have produced plausible-looking output.

It is wired as a ctest (add_test + add_dependencies(onebit …)) with a checked-in fixture (tests/data/tokenizer_metaspace.json), so the case set is reproducible rather than depending on a local model.

tokenizer_metaspace: ok (7 cases).

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Prefix Logic Inconsistency

The logic for determining when to prepend the metaspace symbol in spm_merged and spm functions is inconsistent. In spm_merged, the condition checks !spm_no_prefix_ && !(spm_prefix_unless_leading_ && !text.empty() && text[0] == ' '), while in spm, it checks !(spm_prefix_unless_leading_ && !text.empty() && text[0] == ' '). This inconsistency could lead to different behavior when the text starts with a space, potentially causing incorrect tokenization for certain inputs.

    if (!spm_no_prefix_ && !(spm_prefix_unless_leading_ && !text.empty() && text[0] == ' ')) s += kMeta;
    for (char c : text) {
        if (c == ' ') s += kMeta;
        else s += c;
    }
    return bpe(s, /*byte_fallback=*/true);
}

// SentencePiece: spaces become U+2581 ("\xe2\x96\x81", the metaspace symbol) with a
// leading one for the whole run, then greedy longest-match over the vocabulary
// with byte fallback for anything unmatched.  This reproduces llama.cpp's ids
// for the SPM models the converter emits as BPE-with-no-merges (MiniCPM4:
// "The capital of France is" -> 1507 8107 1379 8360 1410, matching the oracle).
std::vector<int> Tokenizer::spm(const std::string& text) const {
    if (spm_merges_) return spm_merged(text);
    static const char kMeta[] = "\xE2\x96\x81";
    std::string s;
    s.reserve(text.size() + 3);
    if (!(spm_prefix_unless_leading_ && !text.empty() && text[0] == ' ')) s += kMeta;
Missing Error Handling

The pre_tokenizer_prepends_meta function does not validate that the prepend_scheme value is one of the expected strings ("first", "always") or that add_prefix_space is a boolean. If an unexpected value is provided, the function may return false, potentially causing the tokenizer to fall back to the byte-level path incorrectly.

bool pre_tokenizer_prepends_meta(const nlohmann::json& p) {
    if (!p.is_object()) return false;
    if (p.value("type", "") == "Metaspace") {
        if (p.value("replacement", "\xE2\x96\x81") != "\xE2\x96\x81") return false;
        if (p.contains("prepend_scheme")) {
            const std::string s = p.value("prepend_scheme", "");
            return s == "first" || s == "always";
        }
        return p.value("add_prefix_space", true);
    }
    if (p.contains("pretokenizers"))
        for (const auto& sub : p["pretokenizers"])
            if (pre_tokenizer_prepends_meta(sub)) return true;
    return false;
}

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Answering the asks on the READYs (cl-npurt). The head stays 7310a8d. Nothing below changes the code under review, so I did not push and spend the verdicts already given.

The check that let it ship is fixed where it lives. The "contains Paris" assertion is in the TAMDCOL re-verify harness (strixhalo ~/.cache/scratch-cl-npurt/amdcol/reverify*.sh), not in the engine. All six variants now fail a row when any of its three replies contains U+2581 or a raw <0xNN> byte token: tokenizer machinery in a reply is never intended. The verdict line says TOKENIZER-LEAK. I re-judged the saved replies from 11-15 with the new code:

row (saved replies, main's tokenizer) old check new check
Mistral-7B-Instruct v0.2 PASS FAIL, TOKENIZER-LEAK (Paris,▁Question:WhatisParisknownfor?…)
Mistral-7B-Instruct v0.3 PASS FAIL, TOKENIZER-LEAK (Paris.▁Question▁2:▁What▁is…)
Qwen2.5-7B-Instruct PASS PASS
Meta-Llama-3-8B PASS PASS

~/lb/amd-rai-sweep.sh does not judge reply text, so it has nothing to change.

Which declaration wins: it is an ordered rule already, not a second elif. The normalizer is read first. The pre-tokenizer counts only when the normalizer prepends nothing (pre_prepends = !norm_prepends && ...), so a file with both resolves to the normalizer's rule every time, the way the library applies its normalizer before its pre-tokenizer.

Real-pack bytes in the arm: not in-tree, on purpose. AMD's tokenizer.json files are not redistributed (TAMDCOL rule), so the fixture is an eleven-token file of the same shape. The real files were checked against HF tokenizers 0.23.3: 15/15 (v0.2) and 14/15 (v0.3, an [INST] decode difference), as in the body.

"Say what it recognised": not added to the reader. The tokenizer has no logging today and is constructed per container load, so a stderr line there is noise for every model. If wanted, a describe() accessor that serve prints once would be the place, but that is a separate change.

" a" decodes to "a", not " a". That expectation is the reference library's output (HF tokenizers 0.23.3 on this vocabulary), not a choice. The dummy prefix is not a user character.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant