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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## Unreleased

- 2026/11/24:
- `tokenizers/hftokenizer`:
- Unigram tokenization picks the best-scoring split with Viterbi over the vocab scores, matching HuggingFace `tokenizers` (e.g. `Munich` → `▁`+`Munich` with deberta-v3 / GLiNER, previously greedy `▁Munic`+`h`).
- Unknown characters score `min_score - 10`, consecutive unknowns fuse into one token, and `byte_fallback` emits `<0xXX>` tokens.
- `Model` gains `Scores` and `UnkID`; GGUF Unigram tokenizers pass `tokenizer.ggml.scores` through.
- `model.unk_id` takes precedence over an `[UNK]`/`<unk>` added token; Viterbi steps over rune boundaries only.
- Added `unigram_test.go` with ids generated by `internal/py/unigram_parity.py`, `NewFromGGUF` Unigram and `unk_id` tests, plus a network parity test skipped under `-short`.

- 2026/11/16:
- `models/gguf`:
- Stored `TensorInfo` and `KeyValue` by value in `File.tensorByName` (`map[string]TensorInfo`) and `File.kvByKey` (`map[string]KeyValue`) instead of pointers into `File.TensorInfos` / `File.KeyValues`, fixing `GetTensorInfo` returning mismatched entries after `slices.SortFunc(file.TensorInfos, ...)` reordered the slice (GHSA-372p-cjj6-v33v).
Expand Down
19 changes: 19 additions & 0 deletions internal/py/unigram_parity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Writes tokenizers/hftokenizer/testdata/unigram_parity.json; run from the repo root with tokenizers and huggingface_hub.
import json
from huggingface_hub import hf_hub_download
from tokenizers import Tokenizer

repo = "onnx-community/gliner_multi-v2.1"
texts = [
"Munich",
"Angela Merkel visited Munich on Tuesday.",
"Der Bundeskanzler traf sich in Zürich mit Vertretern der Schweizerischen Nationalbank.",
"La présidente française a inauguré l'exposition à Marseille.",
"東京都庁は新宿区にあります。",
"Москва является столицей России.",
"Contact: jane.doe@example.com, +41 44 123 45 67 🙂",
]
tok = Tokenizer.from_file(hf_hub_download(repo, "tokenizer.json"))
cases = [{"text": t, "ids": tok.encode(t).ids} for t in texts]
with open("tokenizers/hftokenizer/testdata/unigram_parity.json", "w") as f:
f.write(json.dumps({"repo": repo, "cases": cases}, ensure_ascii=False).replace("}, {", "},\n{") + "\n")
5 changes: 5 additions & 0 deletions tokenizers/hftokenizer/gguf.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,14 @@ func NewFromGGUF(config *api.Config, params GGUFTokenizerParams) (*Tokenizer, er
PrependScheme: prependScheme,
AddPrefixSpace: addSpacePrefix,
}
scores := make([]float64, len(params.Scores))
for i, score := range params.Scores {
scores[i] = float64(score)
}
tj.Model = Model{
Type: "Unigram",
Vocab: vocab,
Scores: scores,
UnkToken: unkStr,
ByteFallback: hasByteTokens,
}
Expand Down
26 changes: 25 additions & 1 deletion tokenizers/hftokenizer/hftokenizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func (m *Model) UnmarshalJSON(data []byte) error {
var vocabArray [][]interface{}
if err := json.Unmarshal(raw.Vocab, &vocabArray); err == nil {
m.Vocab = make(map[string]int, len(vocabArray))
m.Scores = make([]float64, len(vocabArray))
for idx, pair := range vocabArray {
if len(pair) >= 1 {
token, ok := pair[0].(string)
Expand All @@ -64,6 +65,9 @@ func (m *Model) UnmarshalJSON(data []byte) error {
m.Vocab[token] = idx
}
}
if len(pair) >= 2 {
m.Scores[idx], _ = pair[1].(float64)
}
}
} else {
m.Vocab = make(map[string]int)
Expand Down Expand Up @@ -182,6 +186,22 @@ func NewFromStruct(config *api.Config, tj *TokenizerJSON) (*Tokenizer, error) {
}
}

if tj.Model.Type == "Unigram" {
minScore := -1.0
if len(tj.Model.Scores) > 0 {
minScore = tj.Model.Scores[0]
}
for token := range tj.Model.Vocab {
t.unigramMaxPiece = max(t.unigramMaxPiece, len(token))
}
for _, score := range tj.Model.Scores {
if score < minScore {
minScore = score
}
}
t.unigramUnkScore = minScore - 10
}

// Resolve special token IDs
t.resolveSpecialTokens()

Expand All @@ -197,14 +217,18 @@ func (t *Tokenizer) resolveSpecialTokens() {
}
}

if id := t.tokenizer.Model.UnkID; id != nil {
t.unkID = *id
}

// Then check added tokens for special tokens
for _, at := range t.tokenizer.AddedTokens {
if !at.Special {
continue
}
content := at.Content
switch {
case content == "[UNK]" || content == "<unk>":
case (content == "[UNK]" || content == "<unk>") && t.tokenizer.Model.UnkID == nil:
t.unkID = at.ID
case content == "[PAD]" || content == "<pad>":
t.padID = at.ID
Expand Down
7 changes: 7 additions & 0 deletions tokenizers/hftokenizer/testdata/unigram_parity.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{"repo": "onnx-community/gliner_multi-v2.1", "cases": [{"text": "Munich", "ids": [1, 260, 82693, 2]},
{"text": "Angela Merkel visited Munich on Tuesday.", "ids": [1, 260, 64817, 55118, 260, 65919, 260, 82693, 352, 19235, 261, 2]},
{"text": "Der Bundeskanzler traf sich in Zürich mit Vertretern der Schweizerischen Nationalbank.", "ids": [1, 1684, 23056, 503, 121359, 100635, 1400, 282, 260, 83307, 750, 435, 165744, 273, 443, 58495, 167837, 5140, 6094, 261, 2]},
{"text": "La présidente française a inauguré l'exposition à Marseille.", "ids": [1, 502, 260, 36013, 266, 53828, 260, 263, 282, 68055, 9472, 260, 281, 278, 90982, 260, 370, 78986, 261, 2]},
{"text": "東京都庁は新宿区にあります。", "ids": [1, 101053, 89190, 536, 79550, 3412, 128913, 307, 2]},
{"text": "Москва является столицей России.", "ids": [1, 20893, 260, 397, 12147, 83035, 17469, 8089, 261, 2]},
{"text": "Contact: jane.doe@example.com, +41 44 123 45 67 🙂", "ids": [1, 6399, 268, 77259, 261, 538, 266, 1062, 151217, 261, 285, 262, 745, 4454, 4695, 19177, 2716, 9935, 260, 8692, 2]}]}
105 changes: 66 additions & 39 deletions tokenizers/hftokenizer/tokenize.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package hftokenizer

import (
"github.com/gomlx/go-huggingface/tokenizers/api"
"fmt"
"strings"
"unicode/utf8"

"github.com/gomlx/go-huggingface/tokenizers/api"
)

// spanForSubword returns the original text span [origStart, origEnd] for a subword
Expand Down Expand Up @@ -205,55 +208,79 @@ func (t *Tokenizer) bpeTokenizeWithSpans(word wordWithOffset) ([]int, []api.Toke
return ids, offsets
}

// unigramTokenizeWithSpans implements Unigram tokenization with offset tracking.
// unigramTokenizeWithSpans picks the pieces with the highest total score (Viterbi), as HuggingFace's Unigram model does.
func (t *Tokenizer) unigramTokenizeWithSpans(word wordWithOffset) ([]int, []api.TokenSpan) {
text := word.text
text, model := word.text, &t.tokenizer.Model
if text == "" {
return nil, nil
}
best := make([]float64, len(text)+1)
from := make([]int, len(text)+1)
pieceID := make([]int, len(text)+1)
for i := range from {
from[i] = -1
}
relax := func(start, end, id int, score float64) {
if s := best[start] + score; from[end] < 0 || s > best[end] {
best[end], from[end], pieceID[end] = s, start, id
}
}
for start := 0; start < len(text); {
_, charLen := utf8.DecodeRuneInString(text[start:])
hasChar := false
for end := start + charLen; end <= min(len(text), start+t.unigramMaxPiece); {
if id, ok := model.Vocab[text[start:end]]; ok {
score := -1.0 // Fewest pieces win when the model has no scores.
if id >= 0 && id < len(model.Scores) {
score = model.Scores[id]
}
relax(start, end, id, score)
hasChar = hasChar || end == start+charLen
}
if end == len(text) {
break
}
_, size := utf8.DecodeRuneInString(text[end:])
end += size
}
if !hasChar {
relax(start, start+charLen, -1, t.unigramUnkScore)
}
start += charLen
}

var ends []int
// Trace the best path back from the end, fusing each run of consecutive unknown pieces into one span.
for end := len(text); end > 0; end = from[end] {
if pieceID[end] >= 0 || len(ends) == 0 || pieceID[ends[len(ends)-1]] >= 0 {
ends = append(ends, end)
}
}
var ids []int
var offsets []api.TokenSpan
runes := []rune(text)
start := 0
runeLen := len(runes)

for start < runeLen {
end := runeLen
found := false

for end > start {
substr := string(runes[start:end])
if id, ok := t.tokenizer.Model.Vocab[substr]; ok {
ids = append(ids, id)

// Calculate offsets - map from rune position to byte position
startByte := len(string(runes[:start]))
endByte := len(string(runes[:end]))

offsets = append(offsets, word.spanForSubword(startByte, endByte))
found = true
start = end
break
for i := len(ends) - 1; i >= 0; i-- {
start, end := 0, ends[i]
if i+1 < len(ends) {
start = ends[i+1]
}
span := word.spanForSubword(start, end)
if id := pieceID[end]; id >= 0 {
ids, offsets = append(ids, id), append(offsets, span)
continue
}
var byteIDs []int
for j := start; model.ByteFallback && j < end; j++ {
if id, ok := model.Vocab[fmt.Sprintf("<0x%02X>", text[j])]; ok {
byteIDs = append(byteIDs, id)
}
end--
}

if !found {
// Single character fallback
char := string(runes[start])
startByte := len(string(runes[:start]))
endByte := len(string(runes[:start+1]))

if id, ok := t.tokenizer.Model.Vocab[char]; ok {
ids = append(ids, id)
} else if t.unkID >= 0 {
ids = append(ids, t.unkID)
if len(byteIDs) == end-start {
for _, id := range byteIDs {
ids, offsets = append(ids, id), append(offsets, span)
}
offsets = append(offsets, word.spanForSubword(startByte, endByte))
start++
} else if t.unkID >= 0 {
ids, offsets = append(ids, t.unkID), append(offsets, span)
}
}

return ids, offsets
}
5 changes: 5 additions & 0 deletions tokenizers/hftokenizer/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ type Model struct {
Type string `json:"type"`
Vocab map[string]int `json:"-"` // Custom unmarshaling handles both map and array formats
Merges []string `json:"-"` // Custom unmarshaling handles both string and array formats
Scores []float64 `json:"-"` // Unigram log probabilities, indexed by token ID.
UnkToken string `json:"unk_token"`
UnkID *int `json:"unk_id"`
ContinuingSubwordPrefix string `json:"continuing_subword_prefix"`
MaxInputCharsPerWord int `json:"max_input_chars_per_word"`
FuseUnk bool `json:"fuse_unk"`
Expand All @@ -130,6 +132,9 @@ type Tokenizer struct {
idToToken map[int]string
mergeRanks map[string]int // For BPE: maps "token1 token2" to merge priority

unigramMaxPiece int // Longest Unigram piece in bytes.
unigramUnkScore float64 // Score of an unknown character: lowest piece score minus 10, as in HuggingFace.

// Special token IDs
unkID int
padID int
Expand Down
105 changes: 105 additions & 0 deletions tokenizers/hftokenizer/unigram_test.go
96F6
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package hftokenizer

import (
"encoding/json"
"fmt"
"os"
"slices"
"testing"

"github.com/gomlx/go-huggingface/hub"
)

func TestUnigram_ViterbiUnknownAndByteFallback(t *testing.T) {
for _, byteFallback := range []bool{false, true} {
tok, err := NewFromContent(nil, fmt.Appendf(nil, `{"version": "1.0",
"added_tokens": [{"id": 0, "content": "<unk>", "special": true}],
"pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
"model": {"type": "Unigram", "unk_id": 0, "byte_fallback": %t, "vocab": [["<unk>", 0.0], ["▁", -2.0], ["▁ab", -10.0],
["▁a", -1.0], ["b", -1.0], ["c", -3.0], ["<0xC3>", -5.0], ["<0xA9>", -5.0]]}}`, byteFallback))
if err != nil {
t.Fatal(err)
}
tok.options.IncludeSpans = true
// Expected ids come from HuggingFace tokenizers on the same tokenizer.json.
want := map[string][]int{"ab": {3, 4}, "abc": {3, 4, 5}, "axyb": {3, 0, 4}, "é": {1, 0}, "éé": {1, 0}}
if byteFallback {
want["é"], want["éé"] = []int{1, 6, 7}, []int{1, 6, 7, 6, 7}
}
for text, ids := range want {
if got := tok.Encode(text); !slices.Equal(got, ids) {
t.Errorf("byte_fallback=%t Encode(%q) = %v, want %v", byteFallback, text, got, ids)
}
}
spans := tok.EncodeWithAnnotations("éé").Spans
for _, span := range spans[1:] {
if span != spans[1] || span.End-span.Start != len("éé") {
t.Errorf("byte_fallback=%t spans(%q) = %v, want one shared span over both runes", byteFallback, "éé", spans)
}
}
}
}

func TestUnigram_ModelUnkID(t *testing.T) {
for _, added := range []string{``, `{"id": 0, "content": "<unk>", "special": true}`} {
tok, err := NewFromContent(nil, fmt.Appendf(nil, `{"version": "1.0", "added_tokens": [%s],
"pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
"model": {"type": "Unigram", "unk_id": 3, "vocab": [["<unk>", 0.0], ["▁", -2.0], ["a", -1.0], ["<UNK>", 0.0]]}}`, added))
if err != nil {
t.Fatal(err)
}
if got := tok.Encode("axa"); !slices.Equal(got, []int{1, 2, 3, 2}) {
t.Errorf("added_tokens=%q Encode(\"axa\") = %v, want [1 2 3 2]", added, got)
}
}
}

func TestNewFromGGUF_Unigram(t *testing.T) {
params := GGUFTokenizerParams{
Model: "llama",
Tokens: []string{"<unk>", "▁", "▁ab", "▁a", "b"},
UnknownTokenID: 0, BosTokenID: -1, EosTokenID: -1, SepTokenID: -1, PadTokenID: -1, ClsTokenID: -1, MaskTokenID: -1,
}
for _, c := range []struct {
scores []float32
want []int
}{{[]float32{0, -2, -10, -1, -1}, []int{3, 4}}, {nil, []int{2}}} {
params.Scores = c.scores
tok, err := NewFromGGUF(nil, params)
if err != nil {
t.Fatal(err)
}
if got := tok.Encode("ab"); !slices.Equal(got, c.want) {
t.Errorf("scores=%v Encode(\"ab\") = %v, want %v", c.scores, got, c.want)
}
}
}

func TestUnigram_HuggingFaceParity(t *testing.T) {
if testing.Short() {
t.Skip("downloads tokenizer.json")
}
data, err := os.ReadFile("testdata/unigram_parity.json")
if err != nil {
t.Fatal(err)
}
var parity struct {
Repo string `json:"repo"`
Cases []struct {
Text string `json:"text"`
IDs []int `json:"ids"`
} `json:"cases"`
}
if err := json.Unmarshal(data, &parity); err != nil {
t.Fatal(err)
}
tok, err := New(nil, hub.New(parity.Repo))
if err != nil {
t.Fatal(err)
}
for _, c := range parity.Cases {
if got := tok.Encode(c.Text); !slices.Equal(got, c.IDs) {
t.Errorf("Encode(%q)\n got %v\nwant %v", c.Text, got, c.IDs)
}
}
}
0