8000 hftokenizer: pick the best-scoring Unigram split with Viterbi by daescha · Pull Request #84 · gomlx/go-huggingface · GitHub
[go: up one dir, main page]

Skip to content

hftokenizer: pick the best-scoring Unigram split with Viterbi - #84

Merged
janpfeifer merged 2 commits into
gomlx:mainfrom
daescha:unigram-viterbi
Nov 24, 2026
Merged

janpfeifer merged 2 commits into
gomlx:mainfrom
daescha:unigram-viterbi

Conversation

@daescha
@daescha daescha commented Nov 24, 2026
Copy link
Copy Markdown
Contributor

Unigram tokenization picks the split with the best total piece score (Viterbi), as HuggingFace tokenizers does. Greedy longest-match gives different ids for SentencePiece vocabularies such as deberta-v3: Munich encodes as ▁Munic+h instead of ▁+Munich, which breaks parity with models trained on HuggingFace ids (e.g. GLiNER).

  • Unknown characters score min_score - 10, consecutive unknowns fuse into one token, and byte_fallback emits <0xXX> tokens, following the Rust implementation.
  • Model gains Scores and UnkID; GGUF Unigram tokenizers pass tokenizer.ggml.scores through (equal scores when absent, so fewest pieces win).
  • unigram_test.go checks ids generated by internal/py/unigram_parity.py for English, German, French, Russian, Japanese and emoji text. A network parity test against onnx-community/gliner_multi-v2.1 runs without -short.

Open points for review:

  • Ties between equal-score splits prefer the shorter first piece.
  • Offsets of unknown and byte-fallback tokens are not compared against HuggingFace, only ids.

Matches Hugging Face tokenizers: piece scores, unk penalty with fused unknowns, byte fallback.
Parity test against onnx-community/gliner_multi-v2.1 ids from internal/py/unigram_parity.py.
@janpfeifer
Copy link
Copy Markdown
Contributor

Thank you so much for finding/fixing this issue 🙏🏻 , I was not aware of it.

  • About the tie-breaking: you are already doing what Hugging Face does ("shorter first piece"), so that's perfect.
  • About the offsets: the AI tells me that your code does what HuggingFace also do -- merge the unknown tokens into a chunk, and output that as the span.

Now the AI also had some comments about the code itself, for your consideration:

@janpfeifer
Copy link
Copy Markdown
Contributor

Here are a few suggestions and edge cases noticed while reviewing the PR:

Correctness & edge cases

  1. AddedTokens overwrites Model.UnkID in resolveSpecialTokens() (tokenizers/hftokenizer/hftokenizer.go)
    t.unkID = *id from Model.UnkID is set before the AddedTokens loop, where case content == "[UNK]" || content == "<unk>": t.unkID = at.ID unconditionally overwrites t.unkID. If a Unigram model sets model.unk_id to a different ID than a special token named "[UNK]" / "<unk>" in added_tokens, AddedTokens will clobber it. Consider only setting t.unkID from AddedTokens when t.unkID < 0 (or applying Model.UnkID after the loop).

  2. minScore initialization & NaN safety (tokenizers/hftokenizer/hftokenizer.go)
    Initializing minScore := 0.0 and updating with Go's min(minScore, score) has a few small edge cases:

    • If all scores are positive (unlikely in real log-prob models, possible in synthetic/test vocabs), minScore clamps to 0.0.
    • When Scores is empty, unigramUnkScore is -10.0 while fallback known pieces score -1.0 (so the penalty is 9 rather than 10; initializing minScore = -1.0 when empty keeps it consistent).
    • Unlike Rust's f64::min, Go's min(a, NaN) returns NaN, which would poison unigramUnkScore.
      Initializing minScore from Scores[0] when non-empty (or -1.0 when empty) and updating with if score < minScore { minScore = score } avoids all three.
  3. Small defensive guards & readability (tokenizers/hftokenizer/tokenize.go)

    • Restoring the if text == "" { return nil, nil } early return avoids allocating 3 length-1 slices on empty words.
    • if id >= 0 && id < len(model.Scores) guards against negative IDs in manually constructed Model structs.
    • Adding a brief comment on the ends backtracking loop explaining that it both traces back the argmax path (end = from[end]) and fuses consecutive pieceID < 0 unknowns makes the backward pass immediately clear to readers.

Performance

  1. Step the inner loop by UTF-8 rune boundaries (tokenizers/hftokenizer/tokenize.go)
    for end := start + 1; end <= min(len(text), start+t.unigramMaxPiece); end++ increments by 1 byte, doing model.Vocab[text[start:end]] map lookups on invalid mid-rune slices (~2/3 of lookups on CJK/Cyrillic/emoji, plus the first 2 bytes of every 3-byte ▁ Metaspace prefix). Stepping end with utf8.DecodeRuneInString(text[end:]) avoids all mid-rune lookups and guarantees transitions stay on rune boundaries.

  2. Optional follow-ups (no need to block this PR)

    • Precomputing a [256]int byte-token ID table in NewFromStruct when ByteFallback is enabled would avoid fmt.Sprintf("<0x%02X>", ...) allocations per fallback byte.
    • Scanning up to t.unigramMaxPiece bytes per rune is $O(N \cdot L_{\max})$ map lookups (where $L_{\max}$ can be 32–128 bytes in SentencePiece vocabs); a trie could be considered later if profiling shows Unigram tokenization is hot.

Test coverage

  1. Suggested additional tests (unigram_test.go / gguf_test.go)
    • NewFromGGUF with Unigram: gguf.go was updated to pass params.Scores, so a test covering both populated scores and missing scores (verifying "fewest pieces win") would be great.
    • Model.UnkID independently: TestUnigram_ViterbiUnknownAndByteFallback also includes {"id": 0, "content": "<unk>", "special": true} in added_tokens, so Model.UnkID isn't currently exercised without added_tokens already resolving unkID = 0.
    • Consecutive unknowns with byte_fallback: true (e.g., "éé") and an EncodeWithAnnotations span check.
    • Minor repo convention: TestUnigram_HuggingFaceParity can call New(nil, hub.New(parity.Repo)) directly (which uses repo.ReadFile) instead of DownloadFile + NewFromFile.

model.unk_id wins over added [UNK]/<unk>; min score is NaN-safe; Viterbi steps by rune.
Adds NewFromGGUF Unigram, unk_id and fused byte-fallback span tests.
@daescha
daescha commented Nov 24, 2026
Copy link
Copy Markdown
Contributor Author

Thanks for the review! Pushed 6d796c1 addressing items 1–4 and 6:

  1. model.unk_id now takes precedence; [UNK]/<unk> in added_tokens only sets the unk id when unk_id is absent. TestUnigram_ModelUnkID covers both cases.
  2. minScore starts from Scores[0] (or -1.0 without scores) and updates with an explicit <, so NaN can't poison it.
  3. Empty-text early return restored, score lookup bounds-guarded, and a one-line comment on the backtracking loop.
  4. The inner loop steps by rune with utf8.DecodeRuneInString; ids are unchanged and the HuggingFace parity test still passes.
  5. Added tests for NewFromGGUF with Unigram (with scores, and without: fewest pieces win), éé with and without byte_fallback plus an EncodeWithAnnotations span check, and the parity test now uses New(nil, hub.New(parity.Repo)).

I left item 5 for later, as suggested.

One thing I noticed while adding the span test: for "éé" the annotated spans come out as {0 3} and {3 7}, past the 4-byte input. The cause is on main and outside this PR. metaspacePreTokenizeWithOffsets replaces each 1-byte space with the 3-byte ▁ without extending offsets, so spanForSubword falls back to positions in the ▁-prefixed text. Plain "hello world" gives {0 8} and {5 13} instead of {0 5} and {5 11}. It is the same drift as #67, in the pre-tokenizer instead of the Replace normalizer. The test here only checks that the fused tokens share one span; I can send the fix as a separate PR, if you like.

@janpfeifer
janpfeifer merged commit 309964e into gomlx:main Nov 24, 2026
1 check passed
@janpfeifer
Copy link
Copy Markdown
Contributor

Thank you for the clean up @daescha 🙏🏻

And the PR for the problem you mentioned about the replacement breaking the spans would be most welcome!!!

@daescha
daescha deleted the unigram-viterbi branch November 24, 2026 19:25
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

0