Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

mlx: match publisher tokenizer semantics (#18779)

Daniel Hiltgen195f4cdca118
diff --git a/.github/workflows/test-tokenizer.yaml b/.github/workflows/test-tokenizer.yaml
new file mode 100644
index 000000000..a1f5ee2af
--- /dev/null
+++ b/.github/workflows/test-tokenizer.yaml
@@ -0,0 +1,41 @@
+name: test-tokenizer
+
+on:
+ pull_request:
+ paths:
+ - 'mlxrunner/tokenizer/**'
+ - '.github/workflows/test-tokenizer.yaml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ reference:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ env:
+ FETCH_TOKENIZERS: '1'
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: go.mod
+ - name: Cache tokenizer data
+ uses: actions/cache@v4
+ with:
+ path: .cache/tokenizers
+ key: tokenizers-${{ hashFiles('mlxrunner/tokenizer/tokenizer_reference_test.go') }}
+ restore-keys: tokenizers-
+ - name: Test published tokenizers
+ run: |
+ set -euo pipefail
+ go test -race -count=1 -timeout=10m -v ./mlxrunner/tokenizer/... | tee "${RUNNER_TEMP}/tokenizer-test.log"
+ if grep -q -- '--- SKIP' "${RUNNER_TEMP}/tokenizer-test.log"; then
+ echo "Tokenizer CI must run every case without skips" >&2
+ exit 1
+ fi
diff --git a/mlxrunner/tokenizer/tokenizer.go b/mlxrunner/tokenizer/tokenizer.go
index 1acfcd7bd..e326ff590 100644
--- a/mlxrunner/tokenizer/tokenizer.go
+++ b/mlxrunner/tokenizer/tokenizer.go
@@ -7,8 +7,6 @@
package tokenizer
-import "regexp"
-
// TokenizerType identifies the tokenization algorithm
type TokenizerType int
@@ -35,14 +33,16 @@ type Vocabulary struct {
// Tokenizer handles BPE and SentencePiece tokenization
type Tokenizer struct {
- vocab *Vocabulary
- pretokenizer *regexp.Regexp
- pretokenizerSpaceBeforePunctuation bool
- specialTokens map[string]int32 // Special tokens for direct lookup
- sortedSpecialTokens []string // Special tokens sorted by length, longest first
- typ TokenizerType // Algorithm type
- normalizeNFC bool
- metaspace *metaspace
+ vocab *Vocabulary
+ pretokenizer []pretokenizer
+ specialTokens map[string]int32 // Special tokens for direct lookup
+ specialTokenMatcher addedTokenMatcher
+ normalizedTokenMatcher addedTokenMatcher
+ typ TokenizerType // Algorithm type
+ normalizeNFC bool
+ normalizeSpaces bool
+ ignoreMerges bool
+ metaspace *metaspace
}
type metaspace struct {
diff --git a/mlxrunner/tokenizer/tokenizer_added.go b/mlxrunner/tokenizer/tokenizer_added.go
new file mode 100644
index 000000000..2ee46fd83
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_added.go
@@ -0,0 +1,66 @@
+package tokenizer
+
+// addedTokenMatcher is a byte trie, built at load time and read-only during
+// encoding. Matching walks token prefixes rather than rescanning the remaining
+// input for every added token after each match.
+type addedTokenMatcher struct {
+ children map[byte]*addedTokenMatcher
+ token string // Original content, even when the matching spelling is normalized.
+}
+
+func (m *addedTokenMatcher) add(pattern, token string) {
+ if pattern == "" {
+ return
+ }
+ for i := range len(pattern) {
+ if m.children == nil {
+ m.children = make(map[byte]*addedTokenMatcher)
+ }
+ if m.children[pattern[i]] == nil {
+ m.children[pattern[i]] = &addedTokenMatcher{}
+ }
+ m = m.children[pattern[i]]
+ }
+ if m.token == "" {
+ m.token = token
+ }
+}
+
+func (m *addedTokenMatcher) split(s string) []encodeChunk {
+ if s == "" {
+ return nil
+ }
+ if len(m.children) == 0 {
+ return []encodeChunk{{text: s}}
+ }
+
+ var result []encodeChunk
+ start := 0
+ for i := 0; i < len(s); {
+ end, token := i, ""
+ node := m
+ for j := i; j < len(s); j++ {
+ node = node.children[s[j]]
+ if node == nil {
+ break
+ }
+ if node.token != "" {
+ end, token = j+1, node.token
+ }
+ }
+ if token == "" {
+ i++
+ continue
+ }
+ // Keep the longest match at the earliest position.
+ if start < i {
+ result = append(result, encodeChunk{text: s[start:i]})
+ }
+ result = append(result, encodeChunk{text: token, isSpecial: true})
+ i, start = end, end
+ }
+ if start < len(s) {
+ result = append(result, encodeChunk{text: s[start:]})
+ }
+ return result
+}
diff --git a/mlxrunner/tokenizer/tokenizer_bpe.go b/mlxrunner/tokenizer/tokenizer_bpe.go
index 41b375452..b860df691 100644
--- a/mlxrunner/tokenizer/tokenizer_bpe.go
+++ b/mlxrunner/tokenizer/tokenizer_bpe.go
@@ -1,8 +1,9 @@
package tokenizer
-import "container/heap"
+import "unicode/utf8"
type bpeMergeNode struct {
+ start int
prev int
next int
token string
@@ -15,83 +16,107 @@ type bpePair struct {
value string
}
-type bpePairHeap []*bpePair
+type bpePairHeap []bpePair
-func (h bpePairHeap) Len() int { return len(h) }
-
-func (h bpePairHeap) Less(i, j int) bool {
+func (h bpePairHeap) less(i, j int) bool {
return h[i].rank < h[j].rank || (h[i].rank == h[j].rank && h[i].left < h[j].left)
}
-func (h bpePairHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
-
-func (h *bpePairHeap) Push(x any) {
- *h = append(*h, x.(*bpePair))
+// Store pairs by value so each candidate merge does not allocate separately.
+func (h bpePairHeap) push(pair bpePair) bpePairHeap {
+ h = append(h, pair)
+ for i := len(h) - 1; i > 0; {
+ parent := (i - 1) / 2
+ if !h.less(i, parent) {
+ break
+ }
+ h[i], h[parent] = h[parent], h[i]
+ i = parent
+ }
+ return h
}
-func (h *bpePairHeap) Pop() any {
- old := *h
- n := len(old)
- item := old[n-1]
- *h = old[:n-1]
- return item
+func (h bpePairHeap) pop() (bpePairHeap, bpePair) {
+ pair := h[0]
+ last := len(h) - 1
+ h[0] = h[last]
+ h[last] = bpePair{}
+ h = h[:last]
+ for i := 0; 2*i+1 < len(h); {
+ child := 2*i + 1
+ if child+1 < len(h) && h.less(child+1, child) {
+ child++
+ }
+ if !h.less(child, i) {
+ break
+ }
+ h[i], h[child] = h[child], h[i]
+ i = child
+ }
+ return h, pair
}
-// encodeBPEMerge encodes using BPE merge algorithm.
-// Uses the heap/linked-list pair merge strategy from tokenizer/bytepairencoding.go:
-// merge the lowest-rank valid pair, then only recheck adjacent pairs.
+// encodeBPEMerge merges the lowest-rank valid pair, breaking ties left to right.
+// Only neighboring pairs need to be rechecked after each merge.
func (t *Tokenizer) encodeBPEMerge(encoded string, ids []int32) []int32 {
- runes := []rune(encoded)
- if len(runes) == 0 {
+ if encoded == "" {
return ids
}
- nodes := make([]bpeMergeNode, len(runes))
- for i := range runes {
- nodes[i] = bpeMergeNode{
+ // Normalize malformed UTF-8 to replacement runes before using byte offsets.
+ if !utf8.ValidString(encoded) {
+ encoded = string([]rune(encoded))
+ }
+ // Most pretokenized pieces fit here; append grows for longer pieces.
+ nodes := make([]bpeMergeNode, 0, 32)
+ for offset, r := range encoded {
+ i := len(nodes)
+ nodes = append(nodes, bpeMergeNode{
+ start: offset,
prev: i - 1,
next: i + 1,
- token: string(runes[i]),
- }
+ token: encoded[offset : offset+utf8.RuneLen(r)],
+ })
}
- pairwise := func(left, right int) *bpePair {
+ pairwise := func(left, right int) (bpePair, bool) {
if left < 0 || right >= len(nodes) {
- return nil
+ return bpePair{}, false
}
if nodes[left].token == "" || nodes[right].token == "" {
- return nil
+ return bpePair{}, false
}
leftToken, rightToken := nodes[left].token, nodes[right].token
rank, ok := t.vocab.Merges[leftToken+" "+rightToken]
if !ok {
- return nil
+ return bpePair{}, false
}
- value := leftToken + rightToken
+ // Merged tokens remain contiguous spans of the encoded input.
+ value := encoded[nodes[left].start : nodes[right].start+len(rightToken)]
if _, ok := t.vocab.Reverse[value]; !ok {
- return nil
+ return bpePair{}, false
}
- return &bpePair{
+ return bpePair{
left: left,
right: right,
rank: rank,
value: value,
- }
+ }, true
}
- pairs := bpePairHeap{}
- heap.Init(&pairs)
- for i := range len(runes) - 1 {
- if pair := pairwise(i, i+1); pair != nil {
- heap.Push(&pairs, pair)
+ pairs := make(bpePairHeap, 0, 32)
+ for i := range len(nodes) - 1 {
+ if pair, ok := pairwise(i, i+1); ok {
+ pairs = pairs.push(pair)
}
}
- for pairs.Len() > 0 {
- pair := heap.Pop(&pairs).(*bpePair)
+ for len(pairs) > 0 {
+ var pair bpePair
+ pairs, pair = pairs.pop()
left, right := nodes[pair.left], nodes[pair.right]
if left.token == "" || right.token == "" {
continue
@@ -110,11 +135,11 @@ func (t *Tokenizer) encodeBPEMerge(encoded string, ids []int32) []int32 {
nodes[right.next].prev = pair.left
}
- if pair := pairwise(nodes[pair.left].prev, pair.left); pair != nil {
- heap.Push(&pairs, pair)
+ if pair, ok := pairwise(nodes[pair.left].prev, pair.left); ok {
+ pairs = pairs.push(pair)
}
- if pair := pairwise(pair.left, nodes[pair.left].next); pair != nil {
- heap.Push(&pairs, pair)
+ if pair, ok := pairwise(pair.left, nodes[pair.left].next); ok {
+ pairs = pairs.push(pair)
}
}
diff --git a/mlxrunner/tokenizer/tokenizer_bpe_spans_test.go b/mlxrunner/tokenizer/tokenizer_bpe_spans_test.go
new file mode 100644
index 000000000..a44e8490d
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_bpe_spans_test.go
@@ -0,0 +1,99 @@
+package tokenizer
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestBPEMergeSpans(t *testing.T) {
+ tok := &Tokenizer{vocab: &Vocabulary{
+ Reverse: map[string]int32{"a": 1, "b": 2, "c": 3, "ab": 4, "bc": 5, "abc": 6, "é": 7, "�": 8, "�a": 9, "aa": 10},
+ Merges: map[string]int{"b c": 0, "a b": 1, "ab c": 2, "� a": 3, "a a": 4},
+ }}
+ for _, tc := range []struct {
+ name, input string
+ want []int32
+ }{
+ {"competing merges", "abc", []int32{1, 5}},
+ {"equal rank merges leftmost", "aaa", []int32{10, 1}},
+ {"invalid UTF8", "\xffa", []int32{9}},
+ {"replacement rune", "�a", []int32{9}},
+ {"adjacent invalid bytes", "\xff\xfea", []int32{8, 9}},
+ {"truncated UTF8", "\xe2\x82a", []int32{8, 9}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tok.encodeBPEMerge(tc.input, nil); !slices.Equal(got, tc.want) {
+ t.Fatalf("encodeBPEMerge(%q) = %v, want %v", tc.input, got, tc.want)
+ }
+ })
+ }
+ // Overlapping candidates exercise heap growth, rank ordering and stale pairs.
+ for _, n := range []int{31, 32, 33, 255, 256, 257} {
+ t.Run(fmt.Sprintf("equal rank/%d", n), func(t *testing.T) {
+ input := strings.Repeat("a", n)
+ want := slices.Repeat([]int32{10}, n/2)
+ if n%2 != 0 {
+ want = append(want, 1)
+ }
+ if got := tok.encodeBPEMerge(input, nil); !slices.Equal(got, want) {
+ t.Fatalf("encodeBPEMerge(%q) = %v, want %v", input, got, want)
+ }
+ })
+ t.Run(fmt.Sprintf("competing ranks/%d", n), func(t *testing.T) {
+ input := strings.Repeat("abc", n)
+ want := slices.Repeat([]int32{1, 5}, n)
+ if got := tok.encodeBPEMerge(input, nil); !slices.Equal(got, want) {
+ t.Fatalf("encodeBPEMerge(%q) = %v, want %v", input, got, want)
+ }
+ })
+ }
+ for _, n := range []int{29, 30, 31, 255, 256, 257} {
+ input := strings.Repeat("é", n) + "abc"
+ want := append(slices.Repeat([]int32{7}, n), 1, 5)
+ if got := tok.encodeBPEMerge(input, nil); !slices.Equal(got, want) {
+ t.Fatalf("encodeBPEMerge with %d multibyte runes = %v, want %v", n, got, want)
+ }
+ }
+}
+
+func TestByteFallback(t *testing.T) {
+ vocab := &Vocabulary{Reverse: map[string]int32{
+ "<0xC3>": 0, "<0xA9>": 1, "<0xF0>": 2, "<0x9F>": 3,
+ "<0x98>": 4, "<0x80>": 5, "<0x61>": 6,
+ }}
+ for _, tc := range []struct {
+ name string
+ typ TokenizerType
+ input string
+ want []int32
+ }{
+ {"BPE empty", TokenizerBPE, "", nil},
+ {"BPE ASCII", TokenizerBPE, "a", []int32{6}},
+ {"BPE missing byte", TokenizerBPE, "x", nil},
+ {"SentencePiece empty", TokenizerSentencePiece, "", nil},
+ {"SentencePiece two byte rune", TokenizerSentencePiece, "é", []int32{0, 1}},
+ {"SentencePiece four byte rune", TokenizerSentencePiece, "😀", []int32{2, 3, 4, 5}},
+ {"SentencePiece missing byte", TokenizerSentencePiece, "x", nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tok := &Tokenizer{typ: tc.typ, vocab: vocab}
+ initByteTokens(tok)
+ if got := tok.appendByteFallback(nil, tc.input); !slices.Equal(got, tc.want) {
+ t.Errorf("appendByteFallback(%q) = %v, want %v", tc.input, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestByteLevelMapping(t *testing.T) {
+ for b, r := range byteToRune {
+ if got, ok := decodeByteLevelRune(r); !ok || got != byte(b) {
+ t.Errorf("decodeByteLevelRune(%U) = %d, %v, want %d, true", r, got, ok, b)
+ }
+ }
+ if _, ok := decodeByteLevelRune('😀'); ok {
+ t.Error("decodeByteLevelRune accepted a rune outside the byte alphabet")
+ }
+}
diff --git a/mlxrunner/tokenizer/tokenizer_config_test.go b/mlxrunner/tokenizer/tokenizer_config_test.go
new file mode 100644
index 000000000..f1b913287
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_config_test.go
@@ -0,0 +1,104 @@
+package tokenizer
+
+import (
+ "slices"
+ "testing"
+)
+
+func TestSpecialTokenConfig(t *testing.T) {
+ const data = `{
+ "model":{"type":"BPE","vocab":{"a":0},"merges":[]},
+ "added_tokens":[
+ {"id":1,"content":"<generation>"},
+ {"id":2,"content":"<model>"},
+ {"id":3,"content":"<tokenizer>"},
+ {"id":4,"content":"<map>"},
+ {"id":5,"content":"<pad>"}
+ ]
+ }`
+ for _, tc := range []struct {
+ name string
+ config *TokenizerConfig
+ bos, pad int32
+ eos []int32
+ addBOS, addEOS bool
+ }{
+ {name: "no companion files", bos: -1, pad: -1},
+ {
+ name: "generation wins including token zero",
+ config: &TokenizerConfig{
+ GenerationConfigJSON: []byte(`{"bos_token_id":0,"eos_token_id":[1,2]}`),
+ ConfigJSON: []byte(`{"bos_token_id":2,"eos_token_id":2}`),
+ TokenizerConfigJSON: []byte(`{"bos_token":"<tokenizer>","eos_token":"<tokenizer>","pad_token":"<pad>","add_bos_token":false,"add_eos_token":true}`),
+ SpecialTokensMapJSON: []byte(`{"bos_token":"<map>","eos_token":"<map>","pad_token":"<map>"}`),
+ },
+ bos: 0, eos: []int32{1, 2}, pad: 5, addEOS: true,
+ },
+ {
+ name: "model fills only missing IDs",
+ config: &TokenizerConfig{
+ GenerationConfigJSON: []byte(`{"eos_token_id":1}`),
+ ConfigJSON: []byte(`{"bos_token_id":2,"eos_token_id":2}`),
+ },
+ bos: 2, eos: []int32{1}, pad: -1,
+ },
+ {
+ name: "tokenizer strings and objects",
+ config: &TokenizerConfig{
+ TokenizerConfigJSON: []byte(`{"bos_token":{"content":"<tokenizer>"},"eos_token":"<tokenizer>","pad_token":{"content":"<pad>"},"add_bos_token":true,"add_eos_token":true}`),
+ },
+ bos: 3, eos: []int32{3}, pad: 5, addBOS: true, addEOS: true,
+ },
+ {
+ name: "special token map fallback",
+ config: &TokenizerConfig{
+ SpecialTokensMapJSON: []byte(`{"bos_token":"<map>","eos_token":{"content":"<map>"},"pad_token":"<pad>"}`),
+ },
+ bos: 4, eos: []int32{4}, pad: 5,
+ },
+ {
+ name: "map fills only missing tokens",
+ config: &TokenizerConfig{
+ TokenizerConfigJSON: []byte(`{"bos_token":"<tokenizer>"}`),
+ SpecialTokensMapJSON: []byte(`{"bos_token":"<map>","eos_token":"<map>","pad_token":"<pad>"}`),
+ },
+ bos: 3, eos: []int32{4}, pad: 5,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tok, err := LoadFromBytesWithConfig([]byte(data), tc.config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tok.BOS() != tc.bos || tok.PAD() != tc.pad || !slices.Equal(tok.EOSTokens(), tc.eos) {
+ t.Fatalf("BOS/PAD/EOS = %d/%d/%v, want %d/%d/%v", tok.BOS(), tok.PAD(), tok.EOSTokens(), tc.bos, tc.pad, tc.eos)
+ }
+ if tok.AddBOS() != tc.addBOS || tok.vocab.AddEOS != tc.addEOS {
+ t.Errorf("AddBOS/AddEOS = %v/%v, want %v/%v", tok.AddBOS(), tok.vocab.AddEOS, tc.addBOS, tc.addEOS)
+ }
+ for _, id := range []int32{0, 1, 2, 3, 4, 5, 6} {
+ want := slices.Contains(tc.eos, id)
+ if got := tok.IsEOS(id); got != want {
+ t.Errorf("IsEOS(%d) = %v, want %v", id, got, want)
+ }
+ }
+ for _, input := range []struct {
+ text string
+ want []int32
+ }{
+ {"", nil},
+ {"a", []int32{0}},
+ } {
+ for _, addBOS := range []bool{false, true} {
+ want := input.want
+ if addBOS && tc.bos >= 0 {
+ want = append([]int32{tc.bos}, want...)
+ }
+ if got := tok.Encode(input.text, addBOS); !slices.Equal(got, want) {
+ t.Errorf("Encode(%q, %v) = %v, want %v", input.text, addBOS, got, want)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/mlxrunner/tokenizer/tokenizer_correctness_test.go b/mlxrunner/tokenizer/tokenizer_correctness_test.go
index 842b01103..48eaa36a0 100644
--- a/mlxrunner/tokenizer/tokenizer_correctness_test.go
+++ b/mlxrunner/tokenizer/tokenizer_correctness_test.go
@@ -2,6 +2,7 @@ package tokenizer
import (
"runtime"
+ "slices"
"strings"
"testing"
)
@@ -59,109 +60,71 @@ func TestSplitBySpecialTokensGreedyLongest(t *testing.T) {
tok, err := LoadFromBytes(data)
if err != nil {
- t.Fatalf("failed to load tokenizer: %v", err)
+ t.Fatal(err)
}
-
- input := "a<tag>xb"
- want := []string{"a", "<tag>x", "b"}
-
- got := tok.splitBySpecialTokens(input)
- if len(got) != len(want) {
- t.Fatalf("split length mismatch: got %v want %v", got, want)
- }
- for i := range want {
- if got[i] != want[i] {
- t.Fatalf("split mismatch at %d: got %v want %v", i, got, want)
+ for _, input := range []struct {
+ text string
+ want []encodeChunk
+ }{
+ {"a<tag>xb", []encodeChunk{{text: "a"}, {text: "<tag>x", isSpecial: true}, {text: "b"}}},
+ {"<tag>x<tag>", []encodeChunk{{text: "<tag>x", isSpecial: true}, {text: "<tag>", isSpecial: true}}},
+ {"a<tag><tag>xb", []encodeChunk{{text: "a"}, {text: "<tag>", isSpecial: true}, {text: "<tag>x", isSpecial: true}, {text: "b"}}},
+ {"a<tag", []encodeChunk{{text: "a<tag"}}},
+ {"<<tag>x", []encodeChunk{{text: "<"}, {text: "<tag>x", isSpecial: true}}},
+ {"<tag><ta", []encodeChunk{{text: "<tag>", isSpecial: true}, {text: "<ta"}}},
+ {strings.Repeat("a<tag>x", 800), slices.Repeat([]encodeChunk{{text: "a"}, {text: "<tag>x", isSpecial: true}}, 800)},
+ {"", nil},
+ } {
+ if got := tok.specialTokenMatcher.split(input.text); !slices.Equal(got, input.want) {
+ t.Errorf("split(%q) = %v, want %v", input.text, got, input.want)
}
}
}
-func TestSplitBySpecialTokensFallbackWithoutCache(t *testing.T) {
- data := []byte(`{
- "model": {
- "type": "BPE",
- "vocab": {"a": 0, "b": 1},
- "merges": []
- },
- "added_tokens": [
- {"id": 2, "content": "<tag>", "special": true},
- {"id": 3, "content": "<tag>x", "special": true}
- ]
- }`)
-
- tok, err := LoadFromBytes(data)
- if err != nil {
- t.Fatalf("failed to load tokenizer: %v", err)
- }
-
- input := "a<tag>xb"
- want := []string{"a", "<tag>x", "b"}
-
- // Simulate construction outside loader path where cache is not set.
- tok.sortedSpecialTokens = nil
+func TestEncodeDeterministicAcrossGOMAXPROCS(t *testing.T) {
+ tok := benchmarkLoadMiniLlama(t)
- got := tok.splitBySpecialTokens(input)
- if len(got) != len(want) {
- t.Fatalf("split length mismatch: got %v want %v", got, want)
- }
- for i := range want {
- if got[i] != want[i] {
- t.Fatalf("split mismatch at %d: got %v want %v", i, got, want)
- }
- }
-}
+ prev := runtime.GOMAXPROCS(0)
+ defer runtime.GOMAXPROCS(prev)
-func TestAdjustWhitespaceBoundary(t *testing.T) {
- tests := []struct {
- name string
- part string
- boundary int
- spaceBeforePunct bool
- want int
+ for _, tc := range []struct {
+ name, text string
}{
- {name: "letter", part: " word", boundary: 2, want: 1},
- {name: "punctuation without optional prefix", part: " }", boundary: 2, want: 2},
- {name: "punctuation with optional prefix", part: " }", boundary: 2, spaceBeforePunct: true, want: 1},
- {name: "tab before letter", part: "\tword", boundary: 1, want: 0},
- {name: "tab before mark", part: "\t\u0301", boundary: 1, spaceBeforePunct: true, want: 1},
- {name: "tab before punctuation", part: "\t}", boundary: 1, spaceBeforePunct: true, want: 1},
- {name: "number", part: " 1", boundary: 2, want: 2},
- {name: "newline", part: " \nword", boundary: 2, want: 2},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- curr := tokenMatch{end: tt.boundary}
- next := tokenMatch{start: tt.boundary, end: len(tt.part)}
-
- adjustWhitespaceBoundary(tt.part, &curr, &next, tt.spaceBeforePunct)
-
- if curr.end != tt.want || next.start != tt.want {
- t.Fatalf("boundary = (%d, %d), want (%d, %d)", curr.end, next.start, tt.want, tt.want)
+ {"ASCII", strings.Repeat("The quick brown fox jumps over the lazy dog. ", 640)},
+ {"Unicode and special tokens", strings.Repeat("e\u0301日本😀<|end_of_text|>", 640)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ runtime.GOMAXPROCS(1)
+ seq := tok.Encode(tc.text, false)
+
+ runtime.GOMAXPROCS(max(2, prev))
+ par := tok.Encode(tc.text, false)
+
+ if !equalIDs(seq, par) {
+ t.Fatalf("encode mismatch between sequential and parallel paths: seq=%d par=%d", len(seq), len(par))
}
})
}
}
-func TestEncodeDeterministicAcrossGOMAXPROCS(t *testing.T) {
- tok := benchmarkLoadMiniLlama(t)
-
- input := strings.Repeat("The quick brown fox jumps over the lazy dog. ", 640)
-
- prev := runtime.GOMAXPROCS(0)
- defer runtime.GOMAXPROCS(prev)
-
- runtime.GOMAXPROCS(1)
- seq := tok.Encode(input, false)
-
- if prev < 2 {
- runtime.GOMAXPROCS(2)
- } else {
- runtime.GOMAXPROCS(prev)
+func FuzzAddedTokenMatcher(f *testing.F) {
+ var matcher addedTokenMatcher
+ for _, token := range []string{"<tag>", "<tag>x", "éé", "\x00"} {
+ matcher.add(token, token)
}
- par := tok.Encode(input, false)
-
- if !equalIDs(seq, par) {
- t.Fatalf("encode mismatch between sequential and parallel paths: seq=%d par=%d", len(seq), len(par))
+ for _, input := range []string{"", "plain", "a<tag>xb", "<tag>x<tag>", "<<tag", "aééa", "\xff<tag>\x00"} {
+ f.Add(input)
}
+ f.Fuzz(func(t *testing.T, input string) {
+ remaining := input
+ for _, part := range matcher.split(input) {
+ if part.text == "" || !strings.HasPrefix(remaining, part.text) {
+ t.Fatalf("split(%q) changed or inserted text: %q", input, part.text)
+ }
+ remaining = remaining[len(part.text):]
+ }
+ if remaining != "" {
+ t.Fatalf("split(%q) dropped suffix %q", input, remaining)
+ }
+ })
}
diff --git a/mlxrunner/tokenizer/tokenizer_encode.go b/mlxrunner/tokenizer/tokenizer_encode.go
index 7659bca8e..9817ffd02 100644
--- a/mlxrunner/tokenizer/tokenizer_encode.go
+++ b/mlxrunner/tokenizer/tokenizer_encode.go
@@ -2,10 +2,8 @@ package tokenizer
import (
"runtime"
- "sort"
"strings"
"sync"
- "unicode"
"unicode/utf8"
"golang.org/x/text/unicode/norm"
@@ -16,122 +14,22 @@ const (
encodeParallelMinChunksPerWorker = 8
)
-type tokenMatch struct {
- start int
- end int
-}
-
type encodeChunk struct {
text string
isSpecial bool
}
-// isNonNewlineWhitespace returns true if s contains only whitespace characters (no newlines)
-func isNonNewlineWhitespace(s string) bool {
- if s == "" {
- return false
- }
- for _, r := range s {
- if r == '\n' || r == '\r' {
- return false
- }
- if !unicode.IsSpace(r) {
- return false
- }
- }
- return true
-}
-
-// splitBySpecialTokens splits text into parts, keeping special tokens as separate elements
-func (t *Tokenizer) splitBySpecialTokens(s string) []string {
- if len(t.specialTokens) == 0 {
- return []string{s}
- }
-
- tokens := t.sortedSpecialTokens
- if len(tokens) == 0 {
- // Fallback for tokenizers constructed outside the loaders.
- tokens = make([]string, 0, len(t.specialTokens))
- for tok := range t.specialTokens {
- tokens = append(tokens, tok)
- }
- sort.Slice(tokens, func(i, j int) bool {
- return len(tokens[i]) > len(tokens[j])
- })
+func (t *Tokenizer) normalize(s string) string {
+ if t.normalizeNFC {
+ s = norm.NFC.String(s)
}
-
- var result []string
- remaining := s
-
- for len(remaining) > 0 {
- found := false
- for _, tok := range tokens {
- if strings.HasPrefix(remaining, tok) {
- result = append(result, tok)
- remaining = remaining[len(tok):]
- found = true
- break
- }
- }
- if !found {
- // Find next special token position
- nextPos := len(remaining)
- for _, tok := range tokens {
- if idx := strings.Index(remaining, tok); idx != -1 && idx < nextPos {
- nextPos = idx
- }
- }
- if nextPos > 0 {
- result = append(result, remaining[:nextPos])
- }
- remaining = remaining[nextPos:]
- }
- }
-
- return result
-}
-
-func adjustWhitespaceBoundary(part string, curr, next *tokenMatch, spaceBeforePunct bool) {
- m := part[curr.start:curr.end]
- nextText := part[next.start:next.end]
-
- if !isNonNewlineWhitespace(m) || len(nextText) == 0 {
- return
- }
-
- firstRune, _ := utf8.DecodeRuneInString(nextText)
- shiftASCIIOnly := !unicode.IsLetter(firstRune)
- if shiftASCIIOnly && (!spaceBeforePunct || unicode.IsNumber(firstRune) || unicode.IsSpace(firstRune)) {
- return
- }
-
- lastSpaceStart := curr.end
- for j := curr.end; j > curr.start; {
- r, size := utf8.DecodeLastRuneInString(part[curr.start:j])
- if unicode.IsSpace(r) {
- if shiftASCIIOnly && r != ' ' {
- return
- }
- lastSpaceStart = j - size
- break
- }
- j -= size
- }
- if lastSpaceStart > curr.start {
- curr.end = lastSpaceStart
- next.start = lastSpaceStart
- } else {
- next.start = curr.start
- curr.end = curr.start
+ if t.normalizeSpaces {
+ s = strings.ReplaceAll(s, " ", "▁")
}
+ return s
}
func (t *Tokenizer) forEachPartChunk(part string, fn func(encodeChunk)) {
- if _, ok := t.specialTokens[part]; ok {
- fn(encodeChunk{text: part, isSpecial: true})
- return
- }
-
if t.pretokenizer == nil {
if t.metaspace != nil && t.metaspace.Split {
start := 0
@@ -148,34 +46,16 @@ func (t *Tokenizer) forEachPartChunk(part string, fn func(encodeChunk)) {
return
}
- re := t.pretokenizer
- offset := 0
- loc := re.FindStringIndex(part[offset:])
- if loc == nil {
- return
- }
-
- curr := tokenMatch{start: offset + loc[0], end: offset + loc[1]}
- offset += loc[1]
-
- for {
- loc = re.FindStringIndex(part[offset:])
- if loc == nil {
- if curr.end > curr.start {
- fn(encodeChunk{text: part[curr.start:curr.end], isSpecial: false})
- }
- return
+ parts := []string{part}
+ for _, stage := range t.pretokenizer {
+ var next []string
+ for _, text := range parts {
+ next = append(next, stage.split(text)...)
}
-
- next := tokenMatch{start: offset + loc[0], end: offset + loc[1]}
- offset += loc[1]
-
- adjustWhitespaceBoundary(part, &curr, &next, t.pretokenizerSpaceBeforePunctuation)
-
- if curr.end > curr.start {
- fn(encodeChunk{text: part[curr.start:curr.end], isSpecial: false})
- }
- curr = next
+ parts = next
+ }
+ for _, text := range parts {
+ fn(encodeChunk{text: text})
}
}
@@ -193,29 +73,48 @@ func (t *Tokenizer) appendEncodedChunk(ids []int32, c encodeChunk) []int32 {
// Encode tokenizes text to token IDs.
// Parallel encoding is used only for very large inputs with enough chunks per worker.
func (t *Tokenizer) Encode(s string, addBOS bool) []int32 {
- // First: split by special tokens
- parts := t.splitBySpecialTokens(s)
- for i, part := range parts {
- if _, ok := t.specialTokens[part]; ok {
- continue
+ // Match normalized=false tokens first so normalization cannot change their
+ // identity. Normalized tokens match anywhere in the remaining text, before
+ // pretokenizer prefixes are inserted.
+ parts := t.specialTokenMatcher.split(s)
+ for i := range parts {
+ if !parts[i].isSpecial {
+ parts[i].text = t.normalize(parts[i].text)
}
- if t.normalizeNFC {
- part = norm.NFC.String(part)
+ }
+ if len(t.normalizedTokenMatcher.children) > 0 {
+ var normalized []encodeChunk
+ for _, part := range parts {
+ if part.isSpecial {
+ normalized = append(normalized, part)
+ } else {
+ normalized = append(normalized, t.normalizedTokenMatcher.split(part.text)...)
+ }
}
- if t.metaspace != nil {
- part = strings.ReplaceAll(part, " ", "▁")
- if (t.metaspace.PrependScheme == "always" || (t.metaspace.PrependScheme == "first" && i == 0)) && !strings.HasPrefix(part, "▁") {
- part = "▁" + part
+ parts = normalized
+ }
+ if t.metaspace != nil {
+ for i, part := range parts {
+ if part.isSpecial {
+ continue
}
+ part.text = strings.ReplaceAll(part.text, " ", "▁")
+ if (t.metaspace.PrependScheme == "always" || (t.metaspace.PrependScheme == "first" && i == 0)) && !strings.HasPrefix(part.text, "▁") {
+ part.text = "▁" + part.text
+ }
+ parts[i] = part
}
- parts[i] = part
}
// Fast path: encode sequentially without materializing chunk slices.
- if len(s) < encodeParallelMinInputBytes {
+ if len(s) < encodeParallelMinInputBytes || runtime.GOMAXPROCS(0) == 1 {
var ids []int32
for _, part := range parts {
- t.forEachPartChunk(part, func(c encodeChunk) {
+ if part.isSpecial {
+ ids = t.appendEncodedChunk(ids, part)
+ continue
+ }
+ t.forEachPartChunk(part.text, func(c encodeChunk) {
ids = t.appendEncodedChunk(ids, c)
})
}
@@ -229,7 +128,11 @@ func (t *Tokenizer) Encode(s string, addBOS bool) []int32 {
// For large inputs collect chunks to enable parallel processing.
var allChunks []encodeChunk
for _, part := range parts {
- t.forEachPartChunk(part, func(c encodeChunk) {
+ if part.isSpecial {
+ allChunks = append(allChunks, part)
+ continue
+ }
+ t.forEachPartChunk(part.text, func(c encodeChunk) {
allChunks = append(allChunks, c)
})
}
@@ -310,9 +213,12 @@ func (t *Tokenizer) encodeChunkInto(s string, ids []int32) []int32 {
encoded = sb.String()
}
- // Fast path: check if entire chunk is a single token
- if id, ok := t.vocab.Reverse[encoded]; ok {
- return append(ids, id)
+ // A whole-vocabulary match can bypass ranked merges only when the model
+ // requests it. Otherwise a higher-priority pair may split that same word.
+ if t.ignoreMerges || utf8.RuneCountInString(encoded) == 1 {
+ if id, ok := t.vocab.Reverse[encoded]; ok {
+ return append(ids, id)
+ }
}
return t.encodeBPEMerge(encoded, ids)
diff --git a/mlxrunner/tokenizer/tokenizer_load.go b/mlxrunner/tokenizer/tokenizer_load.go
index d79fb0716..7f2ea40f7 100644
--- a/mlxrunner/tokenizer/tokenizer_load.go
+++ b/mlxrunner/tokenizer/tokenizer_load.go
@@ -3,9 +3,6 @@ package tokenizer
import (
"encoding/json"
"fmt"
- "regexp"
- "sort"
- "strings"
)
// TokenizerConfig holds optional configuration data that can be passed to LoadFromBytesWithConfig.
@@ -46,19 +43,25 @@ func LoadFromBytesWithConfig(data []byte, config *TokenizerConfig) (*Tokenizer,
func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
var raw struct {
Model struct {
- Type string `json:"type"` // "BPE"
- Vocab map[string]int32 `json:"vocab"`
- Merges json.RawMessage `json:"merges"` // Can be []string or [][]string (BPE only)
+ Type string `json:"type"` // "BPE"
+ IgnoreMerges bool `json:"ignore_merges"`
+ Vocab map[string]int32 `json:"vocab"`
+ Merges json.RawMessage `json:"merges"` // Can be []string or [][]string (BPE only)
} `json:"model"`
PreTokenizer json.RawMessage `json:"pre_tokenizer"`
Normalizer struct {
- Type string `json:"type"`
+ Type string `json:"type"`
+ Pattern struct {
+ String *string `json:"String"`
+ } `json:"pattern"`
+ Content string `json:"content"`
} `json:"normalizer"`
Decoder json.RawMessage `json:"decoder"`
AddedTokens []struct {
- ID int32 `json:"id"`
- Content string `json:"content"`
- Special bool `json:"special"`
+ ID int32 `json:"id"`
+ Content string `json:"content"`
+ Special bool `json:"special"`
+ Normalized bool `json:"normalized"`
} `json:"added_tokens"`
}
@@ -124,6 +127,10 @@ func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
// if it's a "truly special" token like BOS/EOS/PAD, but for tokenization we need
// to treat all added_tokens as special to match HuggingFace behavior.
for _, tok := range raw.AddedTokens {
+ // Hugging Face ignores empty added tokens; they cannot consume input.
+ if tok.Content == "" {
+ continue
+ }
if int(tok.ID) >= len(t.vocab.Values) {
newValues := make([]string, tok.ID+1)
copy(newValues, t.vocab.Values)
@@ -145,6 +152,8 @@ func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
}
t.normalizeNFC = raw.Normalizer.Type == "NFC"
+ t.normalizeSpaces = raw.Normalizer.Type == "Replace" && raw.Normalizer.Pattern.String != nil && *raw.Normalizer.Pattern.String == " " && raw.Normalizer.Content == "▁"
+ t.ignoreMerges = raw.Model.IgnoreMerges
var pre struct {
Type string `json:"type"`
metaspace
@@ -161,39 +170,30 @@ func loadFromTokenizerJSON(data []byte) (*Tokenizer, error) {
t.metaspace = &pre.metaspace
t.typ = TokenizerSentencePiece
}
- // Parse and compile pretokenizer pattern (BPE only).
if t.typ == TokenizerBPE {
- pattern := extractPretokenizer(raw.PreTokenizer)
- if pattern == "" {
- pattern = `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`
- }
- re, err := regexp.Compile(rewritePatternForRE2(pattern))
+ var err error
+ t.pretokenizer, err = loadPretokenizers(raw.PreTokenizer)
if err != nil {
- return nil, fmt.Errorf("failed to compile pretokenizer regex %q: %w", pattern, err)
+ return nil, err
}
- t.pretokenizer = re
- t.pretokenizerSpaceBeforePunctuation = strings.Contains(pattern, ` ?[^\s\p{L}\p{N}]`)
}
- cacheSortedSpecialTokens(t)
-
- return t, nil
-}
-
-func cacheSortedSpecialTokens(t *Tokenizer) {
- if len(t.specialTokens) == 0 {
- t.sortedSpecialTokens = nil
- return
+ // Hugging Face gives special tokens precedence when normalization maps
+ // different added-token spellings to the same pattern.
+ for _, special := range []bool{true, false} {
+ for _, tok := range raw.AddedTokens {
+ if tok.Special != special {
+ continue
+ }
+ if tok.Normalized {
+ t.normalizedTokenMatcher.add(t.normalize(tok.Content), tok.Content)
+ } else {
+ t.specialTokenMatcher.add(tok.Content, tok.Content)
+ }
+ }
}
- tokens := make([]string, 0, len(t.specialTokens))
- for tok := range t.specialTokens {
- tokens = append(tokens, tok)
- }
- sort.Slice(tokens, func(i, j int) bool {
- return len(tokens[i]) > len(tokens[j])
- })
- t.sortedSpecialTokens = tokens
+ return t, nil
}
type specialTokenConfigData struct {
@@ -346,33 +346,6 @@ func extractTokenString(v interface{}) string {
return ""
}
-// rewritePatternForRE2 rewrites HuggingFace pretokenizer regex patterns to be
-// compatible with Go's regexp package (RE2). HuggingFace patterns use PCRE features:
-// - (?!\S) negative lookahead - RE2 doesn't support this
-// - (?i:...) inline case-insensitive groups - RE2 doesn't support this
-//
-// We replace \s+(?!\S)|\s+ with \s+ and fix whitespace boundaries in encodeWithRegex().
-// The lookahead version splits "a b" into ["a", " ", " b"] (space prepended to word).
-// Simple \s+ would give ["a", " ", "b"]. We post-process to match Python's behavior.
-func rewritePatternForRE2(pattern string) string {
- // Replace lookahead pattern with simple \s+ - we fix boundaries in encodeWithRegex()
- pattern = strings.ReplaceAll(pattern, `\s+(?!\S)|\s+`, `\s+`)
-
- // Handle the pattern when it appears with a ? suffix (optional contractions in GPT-4o style)
- // IMPORTANT: Must be done before the non-optional version to avoid partial replacement
- pattern = strings.ReplaceAll(pattern,
- `(?i:'s|'t|'re|'ve|'m|'ll|'d)?`,
- `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?`)
-
- // Expand case-insensitive contraction pattern to explicit alternations
- // (?i:'s|'t|'re|'ve|'m|'ll|'d) -> '[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD]
- pattern = strings.ReplaceAll(pattern,
- `(?i:'s|'t|'re|'ve|'m|'ll|'d)`,
- `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])`)
-
- return pattern
-}
-
// loadSpecialTokenConfigFromBytes loads special token configuration from byte slices.
func loadSpecialTokenConfigFromBytes(t *Tokenizer, config *TokenizerConfig) {
applySpecialTokenConfig(t, specialTokenConfigData{
@@ -436,43 +409,3 @@ func initByteTokens(t *Tokenizer) {
}
}
}
-
-// extractPretokenizer extracts the regex pattern from the pre_tokenizer config
-func extractPretokenizer(data json.RawMessage) string {
- if data == nil {
- return ""
- }
-
- // Try to parse as a single Split pretokenizer
- var single struct {
- Type string `json:"type"`
- Pattern struct {
- Regex string `json:"Regex"`
- } `json:"pattern"`
- }
- if err := json.Unmarshal(data, &single); err == nil && single.Pattern.Regex != "" {
- return single.Pattern.Regex
- }
-
- // Try to parse as Sequence of pretokenizers - use first Split pattern
- var seq struct {
- Type string `json:"type"`
- Pretokenizers []struct {
- Type string `json:"type"`
- Pattern struct {
- Regex string `json:"Regex"`
- } `json:"pattern"`
- } `json:"pretokenizers"`
- }
- if err := json.Unmarshal(data, &seq); err == nil && seq.Type == "Sequence" {
- for _, pt := range seq.Pretokenizers {
- if pt.Type == "Split" && pt.Pattern.Regex != "" {
- if _, err := regexp.Compile(rewritePatternForRE2(pt.Pattern.Regex)); err == nil {
- return pt.Pattern.Regex
- }
- }
- }
- }
-
- return ""
-}
diff --git a/mlxrunner/tokenizer/tokenizer_load_test.go b/mlxrunner/tokenizer/tokenizer_load_test.go
index 7f9299677..d5633c321 100644
--- a/mlxrunner/tokenizer/tokenizer_load_test.go
+++ b/mlxrunner/tokenizer/tokenizer_load_test.go
@@ -1,12 +1,49 @@
package tokenizer
import (
- "encoding/json"
+ "fmt"
"slices"
"strings"
"testing"
)
+func TestEmptyAddedToken(t *testing.T) {
+ tok, err := LoadFromBytes([]byte(`{
+ "model":{"type":"BPE","vocab":{"a":0},"merges":[]},
+ "added_tokens":[
+ {"id":1,"content":"","special":true},
+ {"id":2,"content":"","special":false,"normalized":true}
+ ]
+ }`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := tok.GetSpecialToken(""); ok {
+ t.Fatal("empty added token must not be registered: it cannot consume input")
+ }
+ if got := tok.Encode("a", false); !slices.Equal(got, []int32{0}) {
+ t.Fatalf("Encode(a) = %v, want [0]", got)
+ }
+}
+
+func TestEmptyMetaspaceInput(t *testing.T) {
+ for _, scheme := range []string{"always", "first", "never"} {
+ t.Run(scheme, func(t *testing.T) {
+ data := fmt.Sprintf(`{
+ "model":{"type":"BPE","vocab":{"▁":0,"a":1},"merges":[]},
+ "pre_tokenizer":{"type":"Metaspace","replacement":"▁","prepend_scheme":%q,"split":true}
+ }`, scheme)
+ tok, err := LoadFromBytes([]byte(data))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := tok.Encode("", false); len(got) != 0 {
+ t.Fatalf("Encode(empty) = %v, want no tokens", got)
+ }
+ })
+ }
+}
+
func TestLoadFromBytesRejectsWordPiece(t *testing.T) {
data := []byte(`{
"model": {
@@ -25,87 +62,6 @@ func TestLoadFromBytesRejectsWordPiece(t *testing.T) {
}
}
-func TestExtractPretokenizerSkipsUnsupportedSequenceSplit(t *testing.T) {
- data := []byte(`{
- "type": "Sequence",
- "pretokenizers": [
- {
- "type": "Split",
- "pattern": {
- "Regex": "(?:\\r?\\n)+(?!\\r?\\n)"
- }
- },
- {
- "type": "Split",
- "pattern": {
- "Regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
- }
- }
- ]
- }`)
-
- pattern := extractPretokenizer(data)
- if pattern == "" {
- t.Fatal("expected supported Split pretokenizer")
- }
- if strings.Contains(pattern, `(?!\r?\n)`) {
- t.Fatalf("selected unsupported newline splitter: %q", pattern)
- }
-}
-
-func TestLoadPretokenizerOptionalPunctuationSpace(t *testing.T) {
- tests := []struct {
- name string
- pattern string
- want []string
- }{
- {
- name: "o200k optional space",
- pattern: ` ?[^\s\p{L}\p{N}]+[\r\n/]*|\s+(?!\S)|\s+`,
- want: []string{" ", " }\n"},
- },
- {
- name: "punctuation without optional space",
- pattern: `[^\s\p{L}\p{N}]+[\r\n/]*|\s+(?!\S)|\s+`,
- want: []string{" ", "}\n"},
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- data, err := json.Marshal(map[string]any{
- "model": map[string]any{
- "type": "BPE",
- "vocab": map[string]int{"}": 0},
- "merges": []string{},
- },
- "pre_tokenizer": map[string]any{
- "type": "Split",
- "pattern": map[string]string{
- "Regex": tt.pattern,
- },
- },
- })
- if err != nil {
- t.Fatal(err)
- }
-
- tok, err := LoadFromBytes(data)
- if err != nil {
- t.Fatal(err)
- }
-
- var got []string
- tok.forEachPartChunk(" }\n", func(chunk encodeChunk) {
- got = append(got, chunk.text)
- })
- if strings.Join(got, "\x00") != strings.Join(tt.want, "\x00") {
- t.Fatalf("chunks = %q, want %q", got, tt.want)
- }
- })
- }
-}
-
func TestMetaspace(t *testing.T) {
data := []byte(`{
"model": {"type":"BPE", "vocab":{"▁":0,"a":1,"b":2,"▁a":3,"▁b":4,"▁▁":5,"<s>":6},"merges":["▁ a","▁ b","▁ ▁"]},
@@ -139,18 +95,35 @@ func TestMetaspace(t *testing.T) {
}
}
-func TestNFCNormalization(t *testing.T) {
- tok, err := LoadFromBytes([]byte(`{
- "model":{"type":"BPE","vocab":{"Ã":0,"©":1,"é":2,"[é]":3},"merges":["à ©"]},
- "normalizer":{"type":"NFC"},
- "added_tokens":[{"id":3,"content":"[é]","special":true}]
- }`))
- if err != nil {
- t.Fatal(err)
- }
- for _, text := range []string{"é[e\u0301]", "e\u0301[e\u0301]"} {
- if got := tok.Encode(text, false); !slices.Equal(got, []int32{2, 3}) {
- t.Errorf("Encode(%q) = %v, want [2 3]", text, got)
- }
+func TestIgnoreMerges(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ setting string
+ want []int32
+ }{
+ {"default", "", []int32{0, 4}},
+ {"false", `,"ignore_merges":false`, []int32{0, 4}},
+ {"true", `,"ignore_merges":true`, []int32{5}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ // The higher-priority b+c merge prevents ab+c, despite abc being
+ // in the vocabulary. HF BPE emits [a, bc] unless ignore_merges is set.
+ data := `{"model":{"type":"BPE","vocab":{"a":0,"b":1,"c":2,"ab":3,"bc":4,"abc":5},"merges":[["b","c"],["a","b"],["ab","c"]]` + tc.setting + `}}`
+ tok, err := LoadFromBytes([]byte(data))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, input := range []struct {
+ text string
+ want []int32
+ }{
+ {"abc", tc.want},
+ {"abca", []int32{0, 4, 0}},
+ } {
+ if got := tok.Encode(input.text, false); !slices.Equal(got, input.want) {
+ t.Errorf("Encode(%q) = %v, want %v", input.text, got, input.want)
+ }
+ }
+ })
}
}
diff --git a/mlxrunner/tokenizer/tokenizer_normalization_test.go b/mlxrunner/tokenizer/tokenizer_normalization_test.go
new file mode 100644
index 000000000..fcf8f0cae
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_normalization_test.go
@@ -0,0 +1,264 @@
+package tokenizer
+
+import (
+ "slices"
+ "strings"
+ "testing"
+)
+
+// These synthetic vocabularies isolate added-token normalization from prefix
+// insertion.
+func TestAddedTokenNormalization(t *testing.T) {
+ const mixed = " ▁▁ "
+ const repeats = encodeParallelMinInputBytes/len(mixed) + 1
+ type normalizationCase struct {
+ name, input string
+ want []int32
+ }
+ for _, fixture := range []struct {
+ name string
+ tokenizer string
+ cases []normalizationCase
+ }{
+ {
+ name: "nfc_special_token",
+ tokenizer: `{
+ "model":{"type":"BPE","vocab":{"Ã":0,"©":1,"é":2,"[é]":3},"merges":["à ©"]},
+ "normalizer":{"type":"NFC"},
+ "pre_tokenizer":{"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":true},
+ "added_tokens":[{"id":3,"content":"[é]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true}]
+ }`,
+ cases: []normalizationCase{
+ {name: "composed text", input: "é[e\u0301]", want: []int32{2, 3}},
+ {name: "decomposed text", input: "e\u0301[e\u0301]", want: []int32{2, 3}},
+ },
+ },
+ {
+ name: "added_nfc_false",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 3, "content": "éé", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": false}
+ ],
+ "normalizer": {"type": "NFC"},
+ "pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true, "use_regex": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"Ã": 0, "©": 1, "é": 2, "éé": 3, "a": 4},
+ "merges": [["Ã", "©"]]
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "composed", input: "éé", want: []int32{3}},
+ {name: "decomposed", input: "e\u0301e\u0301", want: []int32{2, 2}},
+ {name: "prefix", input: "aéé", want: []int32{4, 2, 2}},
+ {name: "suffix", input: "ééa", want: []int32{2, 2, 4}},
+ {name: "interior", input: "aééa", want: []int32{4, 2, 2, 4}},
+ {name: "repeated", input: "éééé", want: []int32{2, 2, 2, 2}},
+ {name: "literal interior", input: "aééa", want: []int32{4, 3, 4}},
+ {name: "mixed literal and normalized", input: "ééaéé", want: []int32{3, 4, 2, 2}},
+ },
+ },
+ {
+ name: "added_nfc_true",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 3, "content": "éé", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false}
+ ],
+ "normalizer": {"type": "NFC"},
+ "pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true, "use_regex": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"Ã": 0, "©": 1, "é": 2, "éé": 3, "a": 4},
+ "merges": [["Ã", "©"]]
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "composed", input: "éé", want: []int32{3}},
+ {name: "decomposed", input: "e\u0301e\u0301", want: []int32{3}},
+ {name: "prefix", input: "aéé", want: []int32{4, 3}},
+ {name: "suffix", input: "ééa", want: []int32{3, 4}},
+ {name: "interior", input: "aééa", want: []int32{4, 3, 4}},
+ {name: "repeated", input: "éééé", want: []int32{3, 3}},
+ {name: "literal interior", input: "aééa", want: []int32{4, 3, 4}},
+ {name: "mixed literal and normalized", input: "ééaéé", want: []int32{3, 4, 3}},
+ },
+ },
+ {
+ name: "normalized_spelling_and_raw_precedence",
+ tokenizer: `{
+ "normalizer": {"type": "NFC"},
+ "pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true, "use_regex": true},
+ "model": {"type": "BPE", "vocab": {"a": 0, "Ã": 1, "©": 2, "é": 3, "éé": 4, "é": 5, "e": 6}, "merges": [["Ã", "©"]]},
+ "added_tokens": [
+ {"id": 4, "content": "éé", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false},
+ {"id": 5, "content": "é", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
+ {"id": 6, "content": "e", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false}
+ ]
+}`,
+ cases: []normalizationCase{
+ {name: "normalized spelling", input: "ae\u0301e\u0301a", want: []int32{0, 4, 0}},
+ {name: "raw tokens win", input: "éé", want: []int32{5, 5}},
+ {name: "raw token separates normalized matches", input: "e\u0301ée\u0301", want: []int32{3, 5, 3}},
+ {name: "normalize before matching", input: "e\u0301", want: []int32{3}},
+ {name: "unchanged normalized token", input: "aea", want: []int32{0, 6, 0}},
+ },
+ },
+ {
+ name: "normalized_collision",
+ tokenizer: `{
+ "normalizer": {"type": "NFC"},
+ "model": {"type": "BPE", "vocab": {"é": 0, "é": 1}, "merges": []},
+ "added_tokens": [
+ {"id": 0, "content": "é", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false},
+ {"id": 1, "content": "é", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": true}
+ ]
+}`,
+ cases: []normalizationCase{
+ {name: "composed", input: "é", want: []int32{1}},
+ {name: "decomposed", input: "e\u0301", want: []int32{1}},
+ },
+ },
+ {
+ name: "added_metaspace_replace_false",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 1, "content": "▁▁", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": false},
+ {"id": 3, "content": "▁a", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": false}
+ ],
+ "normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": "▁"},
+ "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"▁": 0, "▁▁": 1, "a": 2, "▁a": 3}, "merges": []
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "spaces", input: " ", want: []int32{0, 0}},
+ {name: "space word", input: " a", want: []int32{0, 2}},
+ {name: "prefix only", input: "a", want: []int32{0, 2}},
+ {name: "literal token", input: "▁a", want: []int32{3}},
+ {name: "mixed", input: mixed, want: []int32{0, 0, 1, 0, 0}},
+ {name: "large mixed", input: strings.Repeat(mixed, repeats), want: slices.Repeat([]int32{0, 0, 1, 0, 0}, repeats)},
+ },
+ },
+ {
+ name: "added_metaspace_replace_true",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 1, "content": "▁▁", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false},
+ {"id": 3, "content": "▁a", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false}
+ ],
+ "normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": "▁"},
+ "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"▁": 0, "▁▁": 1, "a": 2, "▁a": 3}, "merges": []
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "spaces", input: " ", want: []int32{1}},
+ {name: "space word", input: " a", want: []int32{3}},
+ {name: "prefix only", input: "a", want: []int32{0, 2}},
+ {name: "literal token", input: "▁a", want: []int32{3}},
+ {name: "interior", input: "a a", want: []int32{0, 2, 1, 0, 2}},
+ {name: "adjacent", input: " a a", want: []int32{3, 3}},
+ {name: "mixed", input: mixed, want: []int32{1, 1, 1}},
+ {name: "large mixed", input: strings.Repeat(mixed, repeats), want: slices.Repeat([]int32{1, 1, 1}, repeats)},
+ },
+ },
+ {
+ name: "added_metaspace_first",
+ tokenizer: `{
+ "normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": "▁"},
+ "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "first", "split": true},
+ "model": {"type": "BPE", "vocab": {"▁": 0, "▁▁": 1, "a": 2}, "merges": []},
+ "added_tokens": [{"id": 1, "content": "▁▁", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false}]
+}`,
+ cases: []normalizationCase{
+ {name: "interior", input: "a a", want: []int32{0, 2, 1, 2}},
+ {name: "initial", input: " a", want: []int32{1, 2}},
+ {name: "suffix", input: "a ", want: []int32{0, 2, 1}},
+ },
+ },
+ {
+ name: "added_metaspace_prefix_false",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 1, "content": "▁▁", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": false},
+ {"id": 3, "content": "▁a", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": false}
+ ],
+ "normalizer": null,
+ "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"▁": 0, "▁▁": 1, "a": 2, "▁a": 3}, "merges": []
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "spaces", input: " ", want: []int32{0, 0}},
+ {name: "space word", input: " a", want: []int32{0, 2}},
+ {name: "prefix only", input: "a", want: []int32{0, 2}},
+ {name: "literal token", input: "▁a", want: []int32{3}},
+ },
+ },
+ {
+ name: "added_metaspace_prefix_true",
+ tokenizer: `{
+ "version": "1.0", "truncation": null, "padding": null,
+ "added_tokens": [
+ {"id": 1, "content": "▁▁", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false},
+ {"id": 3, "content": "▁a", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": false}
+ ],
+ "normalizer": null,
+ "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
+ "post_processor": null, "decoder": null,
+ "model": {
+ "type": "BPE", "dropout": null, "unk_token": null,
+ "continuing_subword_prefix": null, "end_of_word_suffix": null,
+ "fuse_unk": false, "byte_fallback": false, "ignore_merges": false,
+ "vocab": {"▁": 0, "▁▁": 1, "a": 2, "▁a": 3}, "merges": []
+ }
+}`,
+ cases: []normalizationCase{
+ {name: "spaces", input: " ", want: []int32{0, 0}},
+ {name: "space word", input: " a", want: []int32{0, 2}},
+ {name: "prefix only", input: "a", want: []int32{0, 2}},
+ {name: "literal token", input: "▁a", want: []int32{3}},
+ },
+ },
+ } {
+ t.Run(fixture.name, func(t *testing.T) {
+ tok, err := LoadFromBytes([]byte(fixture.tokenizer))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range fixture.cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tok.Encode(tc.input, false); !slices.Equal(got, tc.want) {
+ t.Errorf("Encode(%q) = %v, want %v", tc.input, got, tc.want)
+ }
+ })
+ }
+ })
+ }
+}
diff --git a/mlxrunner/tokenizer/tokenizer_pretokenizer.go b/mlxrunner/tokenizer/tokenizer_pretokenizer.go
new file mode 100644
index 000000000..d1113c174
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_pretokenizer.go
@@ -0,0 +1,315 @@
+package tokenizer
+
+import (
+ "encoding/json"
+ "fmt"
+ "iter"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+const defaultBPEPattern = `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`
+
+type pretokenizer struct {
+ re *regexp.Regexp
+ whitespaceGroup int
+ rightDigits bool
+ behavior string
+ invert bool
+ prefixSpace bool
+ byteLevel bool
+}
+
+func loadPretokenizers(data json.RawMessage) ([]pretokenizer, error) {
+ if len(data) == 0 || string(data) == "null" {
+ pt, err := compileSplit(defaultBPEPattern, "Isolated", false)
+ return []pretokenizer{pt}, err
+ }
+ var all []pretokenizer
+ pending := []json.RawMessage{data}
+ for len(pending) > 0 {
+ data := pending[len(pending)-1]
+ pending = pending[:len(pending)-1]
+ var raw struct {
+ Type string `json:"type"`
+ Pretokenizers []json.RawMessage `json:"pretokenizers"`
+ Pattern struct {
+ Regex string `json:"Regex"`
+ String *string `json:"String"`
+ } `json:"pattern"`
+ Behavior string `json:"behavior"`
+ Invert bool `json:"invert"`
+ UseRegex *bool `json:"use_regex"`
+ AddPrefixSpace bool `json:"add_prefix_space"`
+ }
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return nil, fmt.Errorf("invalid pretokenizer: %w", err)
+ }
+ var pt pretokenizer
+ var err error
+ switch raw.Type {
+ case "Sequence":
+ // Stack children in reverse to retain their published execution order.
+ for i := len(raw.Pretokenizers) - 1; i >= 0; i-- {
+ pending = append(pending, raw.Pretokenizers[i])
+ }
+ continue
+ case "Split":
+ pattern := raw.Pattern.Regex
+ if raw.Pattern.String != nil {
+ pattern = regexp.QuoteMeta(*raw.Pattern.String)
+ }
+ pt, err = compileSplit(pattern, raw.Behavior, raw.Invert)
+ case "ByteLevel":
+ if raw.UseRegex == nil || *raw.UseRegex {
+ pt, err = compileSplit(defaultBPEPattern, "Isolated", false)
+ }
+ pt.prefixSpace = raw.AddPrefixSpace
+ pt.byteLevel = true
+ default:
+ return nil, fmt.Errorf("unsupported pretokenizer %q", raw.Type)
+ }
+ if err != nil {
+ return nil, err
+ }
+ all = append(all, pt)
+ }
+ for i, pt := range all {
+ // Byte mapping happens in encodeChunkInto, after the splitting pipeline.
+ if pt.byteLevel {
+ if i != len(all)-1 {
+ return nil, fmt.Errorf("ByteLevel must be the final pretokenizer")
+ }
+ if pt.re == nil && !pt.prefixSpace {
+ all = all[:i]
+ }
+ }
+ }
+ return all, nil
+}
+
+func compileSplit(pattern, behavior string, invert bool) (pretokenizer, error) {
+ pt := pretokenizer{behavior: behavior, invert: invert, whitespaceGroup: -1}
+ switch behavior {
+ case "", "Isolated", "Removed", "MergedWithPrevious", "MergedWithNext", "Contiguous":
+ default:
+ return pt, fmt.Errorf("unsupported split behavior %q", behavior)
+ }
+ switch pattern {
+ // RE2 cannot express these lookaheads. Decimal groups are matched from
+ // the right at a Unicode word boundary; a maximal newline run already
+ // satisfies the negative newline lookahead.
+ case `\d{1,3}(?=(?:\d{3})*\b)`:
+ pt.rightDigits = true
+ pattern = `\p{Nd}+`
+ case `(?:\r?\n)+(?!\r?\n)`:
+ pattern = `(?:\r?\n)+`
+ }
+ // Only the matched trailing-whitespace alternative may backtrack. Other
+ // alternatives that consume whitespace keep their original boundaries.
+ const whitespaceSuffix = `\s+(?!\S)|\s+`
+ prefix := strings.TrimSuffix(pattern, whitespaceSuffix)
+ alternative := strings.HasSuffix(prefix, "|")
+ if alternative {
+ // An odd number of backslashes makes the pipe a literal.
+ for i := len(prefix) - 2; i >= 0 && prefix[i] == '\\'; i-- {
+ alternative = !alternative
+ }
+ }
+ trailingWhitespace := strings.HasSuffix(pattern, whitespaceSuffix) && (prefix == "" || alternative)
+ if trailingWhitespace {
+ pattern = prefix + `(\s+)|\s+`
+ }
+ // Only noncapturing groups and the publisher contraction groups are
+ // supported here. Oniguruma's other flag groups can differ from RE2:
+ // full case folding matches ss to ß, and m changes dot/newline behavior.
+ const contractions = `(?i:'s|'t|'re|'ve|'m|'ll|'d)`
+ groups := strings.ReplaceAll(strings.ReplaceAll(pattern, contractions, ""), "(?:", "")
+ if strings.Contains(groups, "(?") {
+ return pt, fmt.Errorf("unsupported pretokenizer group in %q", pattern)
+ }
+ // Oniguruma's whitespace class is Unicode; Go's \s is ASCII only.
+ const spaces = `\p{Z}\x{85}\x{9}-\x{D}`
+ var rewritten strings.Builder
+ inClass := false
+ for i := 0; i < len(pattern); i++ {
+ switch pattern[i] {
+ case '[':
+ if inClass {
+ return pt, fmt.Errorf("unsupported nested character class in %q", pattern)
+ }
+ inClass = true
+ case ']':
+ inClass = false
+ case '&':
+ if inClass && i+1 < len(pattern) && pattern[i+1] == '&' {
+ return pt, fmt.Errorf("unsupported character-class intersection in %q", pattern)
+ }
+ case '^', '$':
+ if !inClass {
+ return pt, fmt.Errorf("unsupported pretokenizer anchor in %q", pattern)
+ }
+ case '\\':
+ if i+1 < len(pattern) {
+ next := pattern[i+1]
+ if next == 's' || next == 'd' || next == 'w' || next == 'S' || next == 'D' || next == 'W' {
+ class := spaces
+ switch next {
+ case 'd', 'D':
+ class = `\p{Nd}`
+ case 'w', 'W':
+ class = `\p{L}\p{M}\p{N}\p{Pc}`
+ }
+ negated := next >= 'A' && next <= 'Z'
+ if negated && inClass {
+ return pt, fmt.Errorf("unsupported negated Unicode class in %q", pattern)
+ }
+ if !inClass {
+ rewritten.WriteByte('[')
+ if negated {
+ rewritten.WriteByte('^')
+ }
+ }
+ rewritten.WriteString(class)
+ if !inClass {
+ rewritten.WriteByte(']')
+ }
+ i++
+ continue
+ }
+ if next == 'b' || next == 'B' || next == 'A' || next == 'z' {
+ return pt, fmt.Errorf("unsupported pretokenizer boundary in %q", pattern)
+ }
+ rewritten.WriteByte(pattern[i])
+ rewritten.WriteByte(next)
+ i++
+ continue
+ }
+ }
+ rewritten.WriteByte(pattern[i])
+ }
+ var err error
+ pt.re, err = regexp.Compile(rewritten.String())
+ if err != nil {
+ return pt, fmt.Errorf("unsupported pretokenizer regex %q: %w", pattern, err)
+ }
+ if pt.re.MatchString("") {
+ return pt, fmt.Errorf("pretokenizer regex %q matches empty input", pattern)
+ }
+ if trailingWhitespace {
+ pt.whitespaceGroup = pt.re.NumSubexp()
+ }
+ return pt, nil
+}
+
+func (p pretokenizer) matches(text string) iter.Seq2[int, int] {
+ return func(yield func(int, int) bool) {
+ for offset := 0; offset < len(text); {
+ loc := p.re.FindStringSubmatchIndex(text[offset:])
+ if loc == nil {
+ break
+ }
+ start, end := offset+loc[0], offset+loc[1]
+ if p.rightDigits {
+ r, _ := utf8.DecodeRuneInString(text[end:])
+ if end == len(text) || !(unicode.IsLetter(r) || unicode.IsMark(r) || unicode.IsNumber(r) || unicode.Is(unicode.Pc, r)) {
+ count := utf8.RuneCountInString(text[start:end])
+ size := count % 3
+ if size == 0 {
+ size = 3
+ }
+ cursor := start
+ for i, r := range text[start:end] {
+ size--
+ if size == 0 {
+ next := start + i + utf8.RuneLen(r)
+ if !yield(cursor, next) {
+ return
+ }
+ cursor = next
+ size = 3
+ }
+ }
+ }
+ offset = end
+ continue
+ }
+ if p.whitespaceGroup > 0 && loc[2*p.whitespaceGroup] >= 0 && end < len(text) {
+ _, size := utf8.DecodeLastRuneInString(text[start:end])
+ if end-start > size {
+ end -= size
+ }
+ }
+ if !yield(start, end) {
+ return
+ }
+ offset = end
+ }
+ }
+}
+
+func (p pretokenizer) split(text string) []string {
+ if text == "" {
+ return nil
+ }
+ if p.prefixSpace && !strings.HasPrefix(text, " ") {
+ text = " " + text
+ }
+ if p.re == nil {
+ return []string{text}
+ }
+ var result []string
+ pending := ""
+ previousDelimiter := false
+ emit := func(text string, delimiter bool) {
+ switch p.behavior {
+ case "Removed":
+ if !delimiter {
+ result = append(result, text)
+ }
+ case "MergedWithPrevious":
+ if delimiter && !previousDelimiter && len(result) > 0 {
+ result[len(result)-1] += text
+ } else {
+ result = append(result, text)
+ }
+ case "MergedWithNext":
+ if delimiter {
+ if pending != "" {
+ result = append(result, pending)
+ }
+ pending = text
+ } else {
+ result = append(result, pending+text)
+ pending = ""
+ }
+ case "Contiguous":
+ if len(result) > 0 && delimiter == previousDelimiter {
+ result[len(result)-1] += text
+ } else {
+ result = append(result, text)
+ }
+ default:
+ result = append(result, text)
+ }
+ previousDelimiter = delimiter
+ }
+ offset := 0
+ for start, end := range p.matches(text) {
+ if start > offset {
+ emit(text[offset:start], p.invert)
+ }
+ emit(text[start:end], !p.invert)
+ offset = end
+ }
+ if offset < len(text) {
+ emit(text[offset:], p.invert)
+ }
+ if pending != "" {
+ result = append(result, pending)
+ }
+
+ return result
+}
diff --git a/mlxrunner/tokenizer/tokenizer_pretokenizer_test.go b/mlxrunner/tokenizer/tokenizer_pretokenizer_test.go
new file mode 100644
index 000000000..657a62349
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_pretokenizer_test.go
@@ -0,0 +1,142 @@
+package tokenizer
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+)
+
+const rightAlignedDigitsPretokenizer = `{
+ "type": "Sequence",
+ "pretokenizers": [
+ {"type":"Split","pattern":{"Regex":"\\d{1,3}(?=(?:\\d{3})*\\b)"},"behavior":"Isolated","invert":false},
+ {"type":"Split","pattern":{"Regex":"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+ ]
+}`
+
+const mergedNewlinesPretokenizer = `{
+ "type": "Sequence",
+ "pretokenizers": [
+ {"type":"Split","pattern":{"Regex":"(?:\\r?\\n)+(?!\\r?\\n)"},"behavior":"MergedWithNext","invert":false},
+ {"type":"Split","pattern":{"Regex":"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+ ]
+}`
+
+// Split expectations were checked with Hugging Face tokenizers 0.22.2.
+func TestPretokenizerSplits(t *testing.T) {
+ for _, tc := range []struct {
+ name, pretokenizer, text string
+ want []string
+ }{
+ {"whitespace suffix", `{"type":"Split","pattern":{"Regex":"\\s+(?!\\S)|\\s+"},"behavior":"Isolated"}`, " x", []string{" ", " ", "x"}},
+ {"alternative after literal backslash", `{"type":"Split","pattern":{"Regex":"a\\\\|\\s+(?!\\S)|\\s+"},"behavior":"Isolated"}`, `a\ x`, []string{`a\`, " ", " ", "x"}},
+ {"punctuation optional space", `{"type":"Split","pattern":{"Regex":" ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s+(?!\\S)|\\s+"}}`, " }\n", []string{" ", " }\n"}},
+ {"punctuation without optional space", `{"type":"Split","pattern":{"Regex":"[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s+(?!\\S)|\\s+"}}`, " }\n", []string{" ", " ", "}\n"}},
+ {"delimiter Isolated", `{"type":"Split","pattern":{"String":" "},"behavior":"Isolated","invert":false}`, " a b ", []string{" ", " ", "a", " ", " ", "b", " ", " "}},
+ {"delimiter Removed", `{"type":"Split","pattern":{"String":" "},"behavior":"Removed","invert":false}`, " a b ", []string{"a", "b"}},
+ {"delimiter MergedWithPrevious", `{"type":"Split","pattern":{"String":" "},"behavior":"MergedWithPrevious","invert":false}`, " a b ", []string{" ", " ", "a ", " ", "b ", " "}},
+ {"delimiter MergedWithNext", `{"type":"Split","pattern":{"String":" "},"behavior":"MergedWithNext","invert":false}`, " a b ", []string{" ", " a", " ", " b", " ", " "}},
+ {"delimiter Contiguous", `{"type":"Split","pattern":{"String":" "},"behavior":"Contiguous","invert":false}`, " a b ", []string{" ", "a", " ", "b", " "}},
+ {"inverted contiguous", `{"type":"Split","pattern":{"String":" "},"behavior":"Contiguous","invert":true}`, " a b ", []string{" ", "a", " ", "b", " "}},
+ {"inverted words", `{"type":"Split","pattern":{"Regex":"\\w+"},"behavior":"Removed","invert":true}`, "abc ! def", []string{"abc", "def"}},
+ {"Unicode \\s+", `{"type":"Split","pattern":{"Regex":"\\s+"},"behavior":"Isolated","invert":false}`, "a\u0085\u0085١٢३́ b", []string{"a", "\u0085\u0085", "١٢३́", " ", "b"}},
+ {"Unicode [^\\s]+", `{"type":"Split","pattern":{"Regex":"[^\\s]+"},"behavior":"Isolated","invert":false}`, "a\u0085\u0085١٢३́ b", []string{"a", "\u0085\u0085", "١٢३́", " ", "b"}},
+ {"Unicode \\S+", `{"type":"Split","pattern":{"Regex":"\\S+"},"behavior":"Isolated","invert":false}`, "a\u0085\u0085١٢३́ b", []string{"a", "\u0085\u0085", "١٢३́", " ", "b"}},
+ {"Unicode \\d+", `{"type":"Split","pattern":{"Regex":"\\d+"},"behavior":"Isolated","invert":false}`, "a\u0085\u0085١٢३́ b", []string{"a\u0085\u0085", "١٢३", "́ b"}},
+ {"Unicode \\w+", `{"type":"Split","pattern":{"Regex":"\\w+"},"behavior":"Isolated","invert":false}`, "a\u0085\u0085١٢३́ b", []string{"a", "\u0085\u0085", "١٢३́", " ", "b"}},
+ {"right aligned digits", rightAlignedDigitsPretokenizer, "1234567", []string{"1", "234", "567"}},
+ {"digit stage whitespace", rightAlignedDigitsPretokenizer, " 1234", []string{" ", "1", "234"}},
+ {"digit word suffix", rightAlignedDigitsPretokenizer, "1234a", []string{"123", "4", "a"}},
+ {"digits combining mark", rightAlignedDigitsPretokenizer, "1234́", []string{"123", "4", "́"}},
+ {"Unicode digits", rightAlignedDigitsPretokenizer, "١٢٣٤", []string{"١", "٢٣٤"}},
+ {"digit joiner", rightAlignedDigitsPretokenizer, "1234\u200d", []string{"1", "234", "\u200d"}},
+ {"newline stage 'a\\n\\nb'", mergedNewlinesPretokenizer, "a\n\nb", []string{"a", "\n\n", "b"}},
+ {"newline stage 'a\\r\\n\\r\\n'", mergedNewlinesPretokenizer, "a\r\n\r\n", []string{"a", "\r\n\r\n"}},
+ {"newline stage 'a\\n\\n 1'", mergedNewlinesPretokenizer, "a\n\n 1", []string{"a", "\n\n", " ", "1"}},
+ {"ByteLevel regex False prefix False", `{"type":"ByteLevel","add_prefix_space":false,"trim_offsets":false,"use_regex":false}`, "hello world", []string{"hello world"}},
+ {"ByteLevel regex True prefix False", `{"type":"ByteLevel","add_prefix_space":false,"trim_offsets":false,"use_regex":true}`, "hello world", []string{"hello", " world"}},
+ {"ByteLevel regex False prefix True", `{"type":"ByteLevel","add_prefix_space":true,"trim_offsets":false,"use_regex":false}`, "hello world", []string{" hello world"}},
+ {"ByteLevel regex True prefix True", `{"type":"ByteLevel","add_prefix_space":true,"trim_offsets":false,"use_regex":true}`, "hello world", []string{" hello", " world"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ data := []byte(`{"model":{"type":"BPE","vocab":{},"merges":[]},"pre_tokenizer":` + tc.pretokenizer + `}`)
+ tok, err := LoadFromBytes(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ tok.forEachPartChunk(tc.text, func(c encodeChunk) { got = append(got, c.text) })
+ if !slices.Equal(got, tc.want) {
+ t.Fatalf("chunks for %q = %q, want %q", tc.text, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestUnsupportedPretokenizerStage(t *testing.T) {
+ for _, pattern := range []string{`x(?=y)`, `(?i:ss)`, `(?mi:ss)`, `(?m:.)`, `[[:space:]]+`, `[a-z&&[^aeiou]]+`, `[a&&b]+`, `^x`, `\b`, `a\|\s+(?!\S)|\s+`, `a\\\|\s+(?!\S)|\s+`} {
+ t.Run(pattern, func(t *testing.T) {
+ quoted, err := json.Marshal(pattern)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data := `{"model":{"type":"BPE","vocab":{},"merges":[]},"pre_tokenizer":{"type":"Sequence","pretokenizers":[{"type":"Split","pattern":{"Regex":` + string(quoted) + `},"behavior":"Isolated","invert":false},{"type":"Split","pattern":{"Regex":".+"},"behavior":"Isolated","invert":false}]}}`
+ if _, err := LoadFromBytes([]byte(data)); err == nil {
+ t.Fatal("unsupported stage must not be skipped in favor of the later Split")
+ }
+ })
+ }
+}
+
+func FuzzPretokenizer(f *testing.F) {
+ for _, pretokenizer := range []string{
+ `{"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":true}`,
+ `{"type":"Sequence","pretokenizers":[
+ {"type":"Split","pattern":{"Regex":"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+]}`,
+ `{"type":"Sequence","pretokenizers":[
+ {"type":"Split","pattern":{"Regex":"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":false,"use_regex":false}
+]}`,
+ `{"type":"Sequence","pretokenizers":[
+ {"type":"Split","pattern":{"Regex":"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+]}`,
+ `{"type":"Sequence","pretokenizers":[
+ {"type":"Split","pattern":{"Regex":"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+]}`,
+ `{"type":"Sequence","pretokenizers":[
+ {"type":"Split","pattern":{"Regex":"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"},"behavior":"Isolated","invert":false},
+ {"type":"ByteLevel","add_prefix_space":false,"trim_offsets":true,"use_regex":false}
+]}`,
+ rightAlignedDigitsPretokenizer,
+ mergedNewlinesPretokenizer,
+ } {
+ for _, text := range []string{"", " 1234\n\nword", "हिन्दी \u0085!"} {
+ f.Add([]byte(pretokenizer), text)
+ }
+ }
+ f.Fuzz(func(t *testing.T, data []byte, text string) {
+ stages, err := loadPretokenizers(data)
+ if err != nil {
+ return
+ }
+ preservesText := true
+ for _, stage := range stages {
+ if stage.behavior == "Removed" || stage.prefixSpace {
+ preservesText = false
+ }
+ }
+ tok := Tokenizer{pretokenizer: stages}
+ var joined strings.Builder
+ tok.forEachPartChunk(text, func(c encodeChunk) { joined.WriteString(c.text) })
+ if preservesText && joined.String() != text {
+ t.Fatalf("split input %q became %q", text, joined.String())
+ }
+ })
+}
diff --git a/mlxrunner/tokenizer/tokenizer_reference_benchmark_test.go b/mlxrunner/tokenizer/tokenizer_reference_benchmark_test.go
new file mode 100644
index 000000000..d33efa0c9
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_reference_benchmark_test.go
@@ -0,0 +1,49 @@
+package tokenizer_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+func BenchmarkTokenizerReference(b *testing.B) {
+ for _, model := range []struct{ name, special string }{
+ {"qwen3.5:0.8b-mxfp8", "<|endoftext|>"},
+ {"nemotron-3.5-lightning:30b-a3b-nvfp4", "<unk>"},
+ {"muse-glimmer:30b-nvfp4", "<|begin_of_text|>"},
+ } {
+ b.Run(model.name, func(b *testing.B) {
+ tok, err := tokenizer.LoadFromBytes(loadTokenizerReference(b, model.name))
+ if err != nil {
+ b.Fatal(err)
+ }
+ if _, ok := tok.GetSpecialToken(model.special); !ok {
+ b.Fatalf("missing special token %q", model.special)
+ }
+ for _, input := range []struct {
+ name string
+ text string
+ }{
+ {"short", "The quick brown fox jumps over the lazy dog. "},
+ {"270KB", strings.Repeat("The quick brown fox jumps over the lazy dog. ", 6000)},
+ {"special100", strings.Repeat("x"+model.special, 100)},
+ {"special800", strings.Repeat("x"+model.special, 800)},
+ } {
+ b.Run(input.name, func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(len(input.text)))
+ b.ResetTimer()
+ var ids []int32
+ for range b.N {
+ ids = tok.Encode(input.text, false)
+ }
+ b.StopTimer()
+ if len(ids) == 0 {
+ b.Fatal("encoding produced no tokens")
+ }
+ })
+ }
+ })
+ }
+}
diff --git a/mlxrunner/tokenizer/tokenizer_reference_model_test.go b/mlxrunner/tokenizer/tokenizer_reference_model_test.go
new file mode 100644
index 000000000..2f9d8190a
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_reference_model_test.go
@@ -0,0 +1,223 @@
+package tokenizer_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/ollama/ollama/manifest"
+ "github.com/ollama/ollama/transfer"
+ "github.com/ollama/ollama/types/model"
+)
+
+func loadTokenizerReference(t testing.TB, modelName string) []byte {
+ t.Helper()
+ name := model.ParseName(modelName)
+ fetch := os.Getenv("FETCH_TOKENIZERS") != "" || os.Getenv("VERIFY_TOKENIZERS") != ""
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
+ defer cancel()
+
+ var m *manifest.Manifest
+ if fetch {
+ // Resolve the tag on every fetch run so cached data cannot hide updates.
+ url := name.BaseURL().JoinPath("v2", name.DisplayNamespaceModel(), "manifests", name.Tag)
+ m = fetchTokenizerManifest(t, ctx, url.String(), "")
+ if m.MediaType == manifest.MediaTypeManifestList {
+ child, err := manifest.SelectManifestReferenceForRunner(m.Manifests, manifest.RunnerMLX)
+ if err != nil {
+ t.Fatal(err)
+ }
+ digest := child.BlobDigest()
+ if digest == "" {
+ t.Fatal("MLX manifest reference has no digest")
+ }
+ url = name.BaseURL().JoinPath("v2", name.DisplayNamespaceModel(), "blobs", digest)
+ m = fetchTokenizerManifest(t, ctx, url.String(), digest)
+ }
+ } else {
+ var err error
+ m, err = manifest.ParseNamedManifestForRunner(name, manifest.RunnerMLX)
+ if errors.Is(err, os.ErrNotExist) || errors.Is(err, manifest.ErrNoCompatibleManifest) {
+ t.Skipf("%s is not installed; set FETCH_TOKENIZERS=1 to download tokenizer data only", modelName)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ layer, ok := m.ConfigLayer("tokenizer.json")
+ if !ok {
+ t.Fatalf("%s manifest has no tokenizer.json", modelName)
+ }
+ path, err := manifest.BlobsPath(layer.Digest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(path)
+ if errors.Is(err, os.ErrNotExist) && fetch {
+ // These blobs have no model manifest: keep them out of model-store pruning.
+ cacheDir := filepath.Join("..", "..", ".cache", "tokenizers")
+ if err := transfer.Download(ctx, transfer.DownloadOptions{
+ BaseURL: name.BaseURL().String(),
+ Repository: name.DisplayNamespaceModel(),
+ DestDir: cacheDir,
+ Blobs: []transfer.Blob{{Digest: layer.Digest, Size: layer.Size}},
+ }); err != nil {
+ t.Fatalf("fetch %s tokenizer: %v", modelName, err)
+ }
+ path = filepath.Join(cacheDir, strings.ReplaceAll(layer.Digest, ":", "-"))
+ data, err = os.ReadFile(path)
+ }
+ if errors.Is(err, os.ErrNotExist) && !fetch {
+ t.Skipf("%s tokenizer is missing; set FETCH_TOKENIZERS=1 to download tokenizer data only", modelName)
+ }
+ if err != nil {
+ t.Fatalf("read %s tokenizer: %v", modelName, err)
+ }
+ if int64(len(data)) != layer.Size {
+ t.Fatalf("%s tokenizer size = %d, want %d", modelName, len(data), layer.Size)
+ }
+ if got := fmt.Sprintf("sha256:%x", sha256.Sum256(data)); got != layer.Digest {
+ t.Fatalf("%s tokenizer digest = %s, want %s", modelName, got, layer.Digest)
+ }
+ return data
+}
+
+func fetchTokenizerManifest(t testing.TB, ctx context.Context, url, digest string) *manifest.Manifest {
+ t.Helper()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Accept", manifest.MediaTypeManifestList+", "+manifest.MediaTypeManifest)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("fetch manifest %s: %s", url, resp.Status)
+ }
+ const maxManifestSize = 16 << 20
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxManifestSize+1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(data) > maxManifestSize {
+ t.Fatalf("manifest %s exceeds %d bytes", url, maxManifestSize)
+ }
+ if digest != "" {
+ if got := fmt.Sprintf("sha256:%x", sha256.Sum256(data)); got != digest {
+ t.Fatalf("manifest %s digest = %s, want %s", url, got, digest)
+ }
+ }
+ var m manifest.Manifest
+ if err := json.Unmarshal(data, &m); err != nil {
+ t.Fatalf("decode manifest %s: %v", url, err)
+ }
+ return &m
+}
+
+func TestTokenizerReferenceFetch(t *testing.T) {
+ root := t.TempDir()
+ t.Setenv("OLLAMA_MODELS", filepath.Join(root, "models"))
+ t.Setenv("FETCH_TOKENIZERS", "1")
+ t.Setenv("VERIFY_TOKENIZERS", "")
+ work := filepath.Join(root, "work", "tokenizer")
+ if err := os.MkdirAll(work, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Chdir(work)
+
+ tokenizers := [][]byte{[]byte(`{"version":"first"}`), []byte(`{"version":"updated"}`)}
+ digests := make([]string, len(tokenizers))
+ manifests := make([][]byte, len(tokenizers))
+ blobs := make(map[string][]byte)
+ for i, data := range tokenizers {
+ digests[i] = fmt.Sprintf("sha256:%x", sha256.Sum256(data))
+ blobs[digests[i]] = data
+ m := manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifest,
+ Runner: manifest.RunnerMLX,
+ Layers: []manifest.Layer{
+ {MediaType: "application/vnd.ollama.image.json", Name: "tokenizer.json", Digest: digests[i], Size: int64(len(data))},
+ {MediaType: "application/vnd.ollama.image.tensor", Digest: "sha256:" + strings.Repeat("1", 64), Size: 1 << 30},
+ },
+ }
+ var err error
+ manifests[i], err = json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ childDigest := fmt.Sprintf("sha256:%x", sha256.Sum256(manifests[1]))
+ blobs[childDigest] = manifests[1]
+ child, err := manifest.NewManifestReference(childDigest, manifest.RunnerMLX, manifest.FormatSafetensors)
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifests[1], err = json.Marshal(manifest.Manifest{
+ SchemaVersion: 2,
+ MediaType: manifest.MediaTypeManifestList,
+ Manifests: []manifest.Manifest{{Runner: manifest.RunnerLlamaCPP}, child},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var mu sync.Mutex
+ current := manifests[0]
+ requests := make(map[string]int)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ requests[r.URL.Path]++
+ data := blobs[strings.TrimPrefix(r.URL.Path, "/v2/library/reference/blobs/")]
+ if r.URL.Path == "/v2/library/reference/manifests/latest" {
+ data = current
+ }
+ mu.Unlock()
+ if data == nil {
+ t.Errorf("unexpected registry request: %s", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ w.Write(data)
+ }))
+ t.Cleanup(ts.Close)
+
+ var firstDownloads int
+ for i, version := range []int{0, 0, 1} {
+ mu.Lock()
+ current = manifests[version]
+ mu.Unlock()
+ if got := loadTokenizerReference(t, ts.URL+"/library/reference:latest"); !bytes.Equal(got, tokenizers[version]) {
+ t.Fatalf("run %d tokenizer = %s, want %s", i, got, tokenizers[version])
+ }
+ mu.Lock()
+ downloads := requests["/v2/library/reference/blobs/"+digests[0]]
+ mu.Unlock()
+ if i == 0 {
+ firstDownloads = downloads
+ } else if downloads != firstDownloads {
+ t.Fatalf("cached tokenizer was downloaded again: requests = %d, want %d", downloads, firstDownloads)
+ }
+ }
+ mu.Lock()
+ manifestRequests := requests["/v2/library/reference/manifests/latest"]
+ mu.Unlock()
+ if manifestRequests != 3 {
+ t.Fatalf("manifest requests = %d, want 3", manifestRequests)
+ }
+}
diff --git a/mlxrunner/tokenizer/tokenizer_reference_test.go b/mlxrunner/tokenizer/tokenizer_reference_test.go
new file mode 100644
index 000000000..73675569f
--- /dev/null
+++ b/mlxrunner/tokenizer/tokenizer_reference_test.go
@@ -0,0 +1,582 @@
+package tokenizer_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/mlxrunner/tokenizer"
+)
+
+type tokenizerReferenceCase struct {
+ name string
+ input string
+ want []int32
+}
+
+// Default runs use installed MLX models and skip models whose tokenizer data is missing.
+// FETCH_TOKENIZERS=1 downloads missing tokenizer blobs, without model weights.
+// VERIFY_TOKENIZERS=1 also fetches missing data and selects Hugging Face tokenizers
+// in python3 instead of Go, checking the same inputs and expectations.
+func TestTokenizerReference(t *testing.T) {
+ verify := os.Getenv("VERIFY_TOKENIZERS") != ""
+ if verify {
+ if output, err := exec.CommandContext(t.Context(), "python3", "-c", "import tokenizers").CombinedOutput(); err != nil {
+ t.Fatalf("VERIFY_TOKENIZERS requires Hugging Face tokenizers in python3: %v\n%s", err, output)
+ }
+ }
+ cases := []struct {
+ name, input string
+ want map[string][]int32
+ }{
+ {name: "empty", input: "", want: map[string][]int32{
+ "qwen": {},
+ "nemotron": {},
+ "nimble": {},
+ "north": {},
+ "laguna": {},
+ "gemma": {},
+ "muse": {},
+ }},
+ {name: "word", input: "hello", want: map[string][]int32{
+ "qwen": {14556},
+ "nemotron": {29706},
+ "nimble": {14556},
+ "north": {28373},
+ "laguna": {11339},
+ "gemma": {23391},
+ "muse": {25681},
+ }},
+ {name: "leading space", input: " hello", want: map[string][]int32{
+ "qwen": {23066},
+ "nemotron": {52528},
+ "nimble": {23066},
+ "north": {39821},
+ "laguna": {21433},
+ "gemma": {29104},
+ "muse": {47244},
+ }},
+ {name: "repeated spaces", input: "a b", want: map[string][]int32{
+ "qwen": {64, 220, 292},
+ "nemotron": {1097, 1032, 1289},
+ "nimble": {64, 220, 292},
+ "north": {69, 225, 290},
+ "laguna": {134, 290, 360},
+ "gemma": {236746, 138, 236763},
+ "muse": {77, 220, 297},
+ }},
+ {name: "space before number", input: " 1", want: map[string][]int32{
+ "qwen": {220, 220, 16},
+ "nemotron": {1032, 1032, 1049},
+ "nimble": {220, 220, 16},
+ "north": {261, 21},
+ "laguna": {290, 290, 86},
+ "gemma": {138, 236770},
+ "muse": {220, 220, 29},
+ }},
+ {name: "spaces before punctuation", input: " !", want: map[string][]int32{
+ "qwen": {256, 729},
+ "nemotron": {1256, 2662},
+ "nimble": {256, 729},
+ "north": {261, 1350},
+ "laguna": {328, 1319},
+ "gemma": {139, 236888},
+ "muse": {256, 1239},
+ }},
+ {name: "spaces before combining mark", input: " \u0301", want: map[string][]int32{
+ "qwen": {220, 220, 52033},
+ "nemotron": {1032, 1032, 1204, 1129},
+ "nimble": {220, 220, 52033},
+ "north": {225, 225, 34145},
+ "laguna": {290, 290, 41879},
+ "gemma": {138, 238288},
+ "muse": {220, 184604},
+ }},
+ {name: "tab before number", input: " \t1", want: map[string][]int32{
+ "qwen": {220, 197, 16},
+ "nemotron": {1032, 1009, 1049},
+ "nimble": {220, 197, 16},
+ "north": {10680, 21},
+ "laguna": {290, 267, 86},
+ "gemma": {236743, 255968, 236770},
+ "muse": {220, 197, 29},
+ }},
+ {name: "whitespace only", input: " \t\n", want: map[string][]int32{
+ "qwen": {16957},
+ "nemotron": {29356, 1010},
+ "nimble": {16957},
+ "north": {97799},
+ "laguna": {14875, 268},
+ "gemma": {236743, 255968, 107},
+ "muse": {124731},
+ }},
+ {name: "trailing spaces", input: "end ", want: map[string][]int32{
+ "qwen": {400, 262},
+ "nemotron": {1474, 1293},
+ "nimble": {400, 262},
+ "north": {432, 298},
+ "laguna": {506, 341},
+ "gemma": {643, 139},
+ "muse": {431, 277},
+ }},
+ {name: "double newline", input: "a\n\nb", want: map[string][]int32{
+ "qwen": {64, 271, 65},
+ "nemotron": {1097, 1267, 1098},
+ "nimble": {64, 271, 65},
+ "north": {69, 300, 70},
+ "laguna": {134, 350, 135},
+ "gemma": {236746, 108, 236763},
+ "muse": {77, 368, 78},
+ }},
+ {name: "trailing double newline", input: "a\n\n", want: map[string][]int32{
+ "qwen": {64, 271},
+ "nemotron": {1097, 1267},
+ "nimble": {64, 271},
+ "north": {69, 300},
+ "laguna": {134, 350},
+ "gemma": {236746, 108},
+ "muse": {77, 368},
+ }},
+ {name: "newline before number", input: "a\n\n1", want: map[string][]int32{
+ "qwen": {64, 271, 16},
+ "nemotron": {1097, 1267, 1049},
+ "nimble": {64, 271, 16},
+ "north": {69, 300, 21},
+ "laguna": {134, 350, 86},
+ "gemma": {236746, 108, 236770},
+ "muse": {77, 368, 29},
+ }},
+ {name: "crlf", input: "a\r\n\r\nb", want: map[string][]int32{
+ "qwen": {64, 845, 65},
+ "nemotron": {1097, 1013, 1010, 1013, 1010, 1098},
+ "nimble": {64, 845, 65},
+ "north": {69, 5026, 70},
+ "laguna": {134, 1336, 135},
+ "gemma": {236746, 251, 107, 251, 107, 236763},
+ "muse": {77, 57966, 78},
+ }},
+ {name: "punctuation newline", input: "!\n\nb", want: map[string][]int32{
+ "qwen": {0, 271, 65},
+ "nemotron": {5338, 1098},
+ "nimble": {0, 271, 65},
+ "north": {3127, 70},
+ "laguna": {70, 350, 135},
+ "gemma": {236888, 108, 236763},
+ "muse": {28655, 78},
+ }},
+ {name: "spaces then vertical tab", input: " \u000b", want: map[string][]int32{
+ "qwen": {256, 199},
+ "nemotron": {1256, 1011},
+ "nimble": {256, 199},
+ "north": {261, 204},
+ "laguna": {328, 269},
+ "gemma": {138, 249},
+ "muse": {256, 199},
+ }},
+ {name: "spaces vertical tab word", input: " \u000bb", want: map[string][]int32{
+ "qwen": {256, 199, 65},
+ "nemotron": {1256, 1011, 1098},
+ "nimble": {256, 199, 65},
+ "north": {261, 204, 70},
+ "laguna": {328, 269, 135},
+ "gemma": {138, 249, 236763},
+ "muse": {256, 199, 78},
+ }},
+ {name: "form feed", input: "\f\f1", want: map[string][]int32{
+ "qwen": {200, 200, 16},
+ "nemotron": {1012, 1012, 1049},
+ "nimble": {200, 200, 16},
+ "north": {205, 205, 21},
+ "laguna": {270, 270, 86},
+ "gemma": {250, 250, 236770},
+ "muse": {200, 200, 29},
+ }},
+ {name: "nonbreaking space", input: "a\u00a0\u00a0b", want: map[string][]int32{
+ "qwen": {64, 3966, 3966, 65},
+ "nemotron": {1097, 3997, 3997, 1098},
+ "nimble": {64, 3966, 3966, 65},
+ "north": {69, 3637, 3637, 70},
+ "laguna": {134, 757, 52591},
+ "gemma": {236746, 432, 398, 432, 398, 236763},
+ "muse": {77, 394, 41585},
+ }},
+ {name: "em space", input: "a\u2003\u2003b", want: map[string][]int32{
+ "qwen": {64, 373, 225, 373, 225, 65},
+ "nemotron": {1097, 1287, 1131, 1287, 1131, 1098},
+ "nimble": {64, 373, 225, 373, 225, 65},
+ "north": {69, 29787, 29787, 70},
+ "laguna": {134, 52788, 52788, 135},
+ "gemma": {236746, 464, 366, 369, 464, 366, 369, 236763},
+ "muse": {77, 22393, 22393, 78},
+ }},
+ {name: "unicode line separator", input: "a\u2028\u2028b", want: map[string][]int32{
+ "qwen": {64, 373, 101, 373, 101, 65},
+ "nemotron": {1097, 1287, 1168, 1287, 1168, 1098},
+ "nimble": {64, 373, 101, 373, 101, 65},
+ "north": {69, 488, 106, 488, 106, 70},
+ "laguna": {134, 34036, 34036, 135},
+ "gemma": {236746, 464, 366, 406, 464, 366, 406, 236763},
+ "muse": {77, 178448, 178448, 78},
+ }},
+ {name: "unicode space newline", input: "\u3000\u3000\nword", want: map[string][]int32{
+ "qwen": {41993, 198, 1119},
+ "nemotron": {114840, 114840, 1010, 3494},
+ "nimble": {41993, 198, 1119},
+ "north": {65827, 203, 1936},
+ "laguna": {34318, 268, 1318},
+ "gemma": {465, 366, 366, 465, 366, 366, 107, 3017},
+ "muse": {15884, 198, 1769},
+ }},
+ {name: "contractions", input: "we'll I'M they're", want: map[string][]int32{
+ "qwen": {868, 3172, 353, 26708, 781, 2224},
+ "nemotron": {1808, 7534, 1362, 1039, 1077, 2127, 6185},
+ "nimble": {868, 3172, 353, 26708, 781, 2224},
+ "north": {217525, 212963, 7402},
+ "laguna": {2299, 3091, 397, 46809, 948, 2264},
+ "gemma": {977, 236789, 859, 564, 236789, 236792, 901, 236789, 500},
+ "muse": {900, 8961, 5384, 57, 28661},
+ }},
+ {name: "digit grouping", input: "1234567", want: map[string][]int32{
+ "qwen": {16, 17, 18, 19, 20, 21, 22},
+ "nemotron": {1049, 1050, 1051, 1052, 1053, 1054, 1055},
+ "nimble": {16, 17, 18, 19, 20, 21, 22},
+ "north": {21, 13877, 22180},
+ "laguna": {86, 87, 88, 89, 90, 91, 92},
+ "gemma": {236770, 236778, 236800, 236812, 236810, 236825, 236832},
+ "muse": {7235, 19596, 35},
+ }},
+ {name: "code", input: "if x > 1:\n return x\n", want: map[string][]int32{
+ "qwen": {331, 830, 835, 220, 220, 16, 25, 198, 262, 460, 830, 198},
+ "nemotron": {1391, 2460, 3006, 1032, 1032, 1049, 1877, 1293, 1850, 2460, 1010},
+ "nimble": {331, 830, 835, 220, 220, 16, 25, 198, 262, 460, 830, 198},
+ "north": {359, 1150, 1518, 261, 21, 638, 298, 758, 1150, 203},
+ "laguna": {406, 854, 981, 290, 290, 86, 95, 268, 341, 658, 854, 268},
+ "gemma": {584, 1123, 1890, 138, 236770, 236787, 107, 140, 2060, 1123, 107},
+ "muse": {364, 831, 1299, 220, 220, 29, 600, 277, 677, 831, 198},
+ }},
+ {name: "json", input: "{\n \"count\": 12\n}\n", want: map[string][]int32{
+ "qwen": {90, 198, 220, 328, 1767, 763, 220, 220, 16, 17, 198, 92, 198},
+ "nemotron": {2030, 1032, 1429, 12296, 2811, 1032, 1032, 1049, 1050, 1010, 2002},
+ "nimble": {90, 198, 220, 328, 1767, 763, 220, 220, 16, 17, 198, 92, 198},
+ "north": {955, 225, 373, 8227, 1023, 261, 740, 203, 732},
+ "laguna": {160, 268, 290, 444, 3177, 1034, 290, 290, 86, 87, 268, 162, 268},
+ "gemma": {236782, 107, 138, 236775, 2861, 1083, 138, 236770, 236778, 107, 236783, 107},
+ "muse": {785, 220, 392, 7263, 1217, 220, 220, 738, 198, 714},
+ }},
+ {name: "unicode NFC", input: "cafe\u0301 \u00e9 \u4e2d \U0001f30d", want: map[string][]int32{
+ "qwen": {895, 56868, 3825, 220, 95789, 10838, 234, 235},
+ "nemotron": {3173, 3070, 1204, 1129, 1782, 30549, 119685, 1140, 1141},
+ "nimble": {895, 56868, 3825, 220, 95789, 10838, 234, 235},
+ "north": {148414, 34145, 1897, 61196, 96019, 240},
+ "laguna": {88394, 41879, 10757, 32294, 88219, 305},
+ "gemma": {101727, 238288, 1559, 17346, 236743, 244906},
+ "muse": {179383, 7908, 1119, 14351, 85275, 235},
+ }},
+ {name: "decomposed acute", input: "e\u0301", want: map[string][]int32{
+ "qwen": {933},
+ "nemotron": {1101, 1204, 1129},
+ "nimble": {933},
+ "north": {73, 34145},
+ "laguna": {138, 41879},
+ "gemma": {236744, 238288},
+ "muse": {81, 7908},
+ }},
+ {name: "multiple combining marks", input: "a\u0301\u0308", want: map[string][]int32{
+ "qwen": {1886, 136, 230},
+ "nemotron": {1097, 1204, 1129, 129636},
+ "nimble": {1886, 136, 230},
+ "north": {69, 34145, 117207},
+ "laguna": {134, 41879, 206, 300},
+ "gemma": {236746, 238288, 241151},
+ "muse": {77, 7908, 50508},
+ }},
+ {name: "combining mark decomposition", input: "\u0344", want: map[string][]int32{
+ "qwen": {136, 230, 52033},
+ "nemotron": {1205, 1132},
+ "nimble": {136, 230, 52033},
+ "north": {142, 231},
+ "laguna": {207, 296},
+ "gemma": {246735},
+ "muse": {148, 226},
+ }},
+ {name: "angstrom sign normalization", input: "\u212b", want: map[string][]int32{
+ "qwen": {169111},
+ "nemotron": {29246, 1171},
+ "nimble": {169111},
+ "north": {16284, 109},
+ "laguna": {15553, 174},
+ "gemma": {464, 370, 409},
+ "muse": {11840, 117},
+ }},
+ {name: "Hindi combining marks", input: "\u0939\u093f\u0928\u094d\u0926\u0940", want: map[string][]int32{
+ "qwen": {215989, 150127, 177453},
+ "nemotron": {3086, 75790, 2063},
+ "nimble": {90703, 181077, 28640, 148651, 42201},
+ "north": {2990, 140177, 1297},
+ "laguna": {50000, 25825, 171, 15992, 169, 28543},
+ "gemma": {16017, 70249},
+ "muse": {2471, 9028, 98999},
+ }},
+ {name: "Devanagari virama", input: "\u0915\u094d", want: map[string][]int32{
+ "qwen": {149567},
+ "nemotron": {2622, 1891},
+ "nimble": {62516, 28640},
+ "north": {2149, 1218},
+ "laguna": {33892, 15306},
+ "gemma": {1445},
+ "muse": {1541, 823},
+ }},
+ {name: "joiner before combining mark", input: "a\u200d\u0301", want: map[string][]int32{
+ "qwen": {64, 373, 235, 52033},
+ "nemotron": {1097, 29568, 1204, 1129},
+ "nimble": {64, 373, 235, 52033},
+ "north": {69, 36649, 34145},
+ "laguna": {134, 48560, 41879},
+ "gemma": {236746, 237243, 238288},
+ "muse": {77, 12817, 7908},
+ }},
+ {name: "accent before punctuation", input: "a\u0301!", want: map[string][]int32{
+ "qwen": {1886, 0},
+ "nemotron": {1097, 1204, 1129, 1033},
+ "nimble": {1886, 0},
+ "north": {69, 34145, 5},
+ "laguna": {134, 41879, 70},
+ "gemma": {236746, 238288, 236888},
+ "muse": {77, 7908, 13},
+ }},
+ {name: "leading combining mark", input: "\u0301a", want: map[string][]int32{
+ "qwen": {52033, 64},
+ "nemotron": {1204, 1129, 1097},
+ "nimble": {52033, 64},
+ "north": {34145, 69},
+ "laguna": {41879, 134},
+ "gemma": {229580},
+ "muse": {7908, 77},
+ }},
+ {name: "accent on composed letter", input: "\u00e9\u0301", want: map[string][]int32{
+ "qwen": {933, 52033},
+ "nemotron": {1337, 1204, 1129},
+ "nimble": {933, 52033},
+ "north": {487, 34145},
+ "laguna": {2097, 41879},
+ "gemma": {236859, 238288},
+ "muse": {397, 7908},
+ }},
+ {name: "long s", input: "\u017f", want: map[string][]int32{
+ "qwen": {129, 123},
+ "nemotron": {1197, 1191},
+ "nimble": {129, 123},
+ "north": {67879},
+ "laguna": {199, 193},
+ "gemma": {238071},
+ "muse": {129813},
+ }},
+ {name: "dotted capital i", input: "\u0130", want: map[string][]int32{
+ "qwen": {46186},
+ "nemotron": {29522},
+ "nimble": {46186},
+ "north": {26402},
+ "laguna": {67570},
+ "gemma": {237848},
+ "muse": {12327},
+ }},
+ {name: "nonbreaking and zero width space", input: "\u00a0\u200b", want: map[string][]int32{
+ "qwen": {3966, 15231},
+ "nemotron": {3997, 26580},
+ "nimble": {3966, 15231},
+ "north": {3637, 12624},
+ "laguna": {757, 22446},
+ "gemma": {432, 398, 237141},
+ "muse": {394, 4093},
+ }},
+ {name: "file separator control", input: "a\u001cb", want: map[string][]int32{
+ "qwen": {64, 216, 65},
+ "nemotron": {1097, 1028, 1098},
+ "nimble": {64, 216, 65},
+ "north": {69, 221, 70},
+ "laguna": {134, 286, 135},
+ "gemma": {236746, 266, 236763},
+ "muse": {77, 216, 78},
+ }},
+ {name: "unit separator before number", input: " \u001f1", want: map[string][]int32{
+ "qwen": {220, 220, 219, 16},
+ "nemotron": {1032, 1032, 1031, 1049},
+ "nimble": {220, 220, 219, 16},
+ "north": {225, 225, 224, 21},
+ "laguna": {290, 290, 289, 86},
+ "gemma": {138, 253998, 236770},
+ "muse": {220, 220, 219, 29},
+ }},
+ {name: "embedded byte order mark", input: "a\ufeffb", want: map[string][]int32{
+ "qwen": {64, 3121, 65},
+ "nemotron": {1097, 1239, 1187, 1191, 1098},
+ "nimble": {64, 3121, 65},
+ "north": {69, 158731, 70},
+ "laguna": {134, 9851, 135},
+ "gemma": {236746, 237922, 236763},
+ "muse": {77, 38420, 78},
+ }},
+ {name: "mixed case identifiers", input: "parseHTTPResponse XMLHttpRequest", want: map[string][]int32{
+ "qwen": {6199, 8957, 2497, 44310},
+ "nemotron": {9245, 30499, 6566, 126379, 4967},
+ "nimble": {6199, 8957, 2497, 44310},
+ "north": {7386, 151305, 130902, 3095},
+ "laguna": {7335, 8689, 3165, 46797},
+ "gemma": {7240, 22005, 6126, 99210},
+ "muse": {5329, 19117, 3907, 115915, 2843},
+ }},
+ {name: "comment after call", input: "call();\n// comment\nnext", want: map[string][]int32{
+ "qwen": {6450, 2061, 198, 320, 3847, 198, 3480},
+ "nemotron": {19881, 35674, 7739, 1010, 6651},
+ "nimble": {6450, 2061, 198, 320, 3847, 198, 3480},
+ "north": {10465, 40241, 4889, 203, 8831},
+ "laguna": {7361, 772, 268, 464, 4758, 268, 4954},
+ "gemma": {6639, 1086, 107, 715, 5739, 107, 4874},
+ "muse": {10551, 26440, 7146, 198, 4011},
+ }},
+ {name: "non-special added reasoning tokens", input: "<think>e\u0301</think>é", want: map[string][]int32{
+ "qwen": {248068, 933, 248069, 933},
+ "nemotron": {12, 1101, 1204, 1129, 13, 1337},
+ "nimble": {248068, 933, 248069, 933},
+ "north": {36231, 748, 143978, 34145, 654, 37182, 34, 487},
+ "laguna": {18, 138, 41879, 19, 2097},
+ "gemma": {236820, 36345, 236813, 236744, 238288, 954, 36345, 236813, 236859},
+ "muse": {26911, 1007, 42, 81, 7908, 695, 66873, 42, 397},
+ }},
+ {name: "unassigned Unicode byte fallback", input: "\U0010ffff\u0378", want: map[string][]int32{
+ "qwen": {176, 237, 123, 123, 137, 116},
+ "nemotron": {1244, 1143, 1191, 1191, 1205, 1184},
+ "nimble": {176, 237, 123, 123, 137, 116},
+ "north": {181, 242, 128, 128, 142, 121},
+ "laguna": {246, 307, 193, 193, 207, 186},
+ "gemma": {482, 381, 429, 429, 443, 422},
+ "muse": {187, 237, 136, 136, 148, 129},
+ }},
+ }
+ models := []struct {
+ family, model string
+ cases []tokenizerReferenceCase
+ }{
+ {family: "qwen", model: "qwen3.5:0.8b-mxfp8", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <|endoftext|>b", []int32{64, 256, 248044, 65}},
+ {"repeated special token", "<|endoftext|>x<|endoftext|>", []int32{248044, 87, 248044}},
+ }},
+ {family: "qwen", model: "qwen3.8:27b-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <|endoftext|>b", []int32{64, 256, 248044, 65}},
+ {"repeated special token", "<|endoftext|>x<|endoftext|>", []int32{248044, 87, 248044}},
+ }},
+ {family: "nemotron", model: "nemotron-3.5-lightning:30b-a3b-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <unk>b", []int32{1097, 1256, 0, 1098}},
+ {"repeated special token", "<unk>x<unk>", []int32{0, 1120, 0}},
+ }},
+ {family: "nimble", model: "nimble:9b-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <|endoftext|>b", []int32{64, 256, 248044, 65}},
+ {"repeated special token", "<|endoftext|>x<|endoftext|>", []int32{248044, 87, 248044}},
+ }},
+ {family: "north", model: "north-mini-code-1.0:mlx-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <PAD>b", []int32{69, 261, 0, 70}},
+ {"repeated special token", "<PAD>x<PAD>", []int32{0, 92, 0}},
+ }},
+ {family: "laguna", model: "laguna-xs.2:nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a \u3008|UNK|\u3009b", []int32{134, 328, 0, 135}},
+ {"repeated special token", "\u3008|UNK|\u3009x\u3008|UNK|\u3009", []int32{0, 157, 0}},
+ }},
+ {family: "gemma", model: "gemma4:e2b-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <pad>b", []int32{236746, 138, 0, 236763}},
+ {"repeated special token", "<pad>x<pad>", []int32{0, 236781, 0}},
+ }},
+ {family: "muse", model: "muse-glimmer:30b-nvfp4", cases: []tokenizerReferenceCase{
+ {"special token boundary", "a <|begin_of_text|>b", []int32{77, 256, 200000, 78}},
+ {"repeated special token", "<|begin_of_text|>x<|begin_of_text|>", []int32{200000, 100, 200000}},
+ }},
+ }
+ for _, tt := range models {
+ t.Run(tt.model, func(t *testing.T) {
+ data := loadTokenizerReference(t, tt.model)
+ var modelCases []tokenizerReferenceCase
+ for _, tc := range cases {
+ modelCases = append(modelCases, tokenizerReferenceCase{tc.name, tc.input, tc.want[tt.family]})
+ }
+ modelCases = append(modelCases, tt.cases...)
+ var tok *tokenizer.Tokenizer
+ var reference [][]int32
+ if verify {
+ reference = referenceTokenIDs(t, data, modelCases)
+ } else {
+ var err error
+ tok, err = tokenizer.LoadFromBytes(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, tc := range modelCases {
+ t.Run(tc.name, func(t *testing.T) {
+ var got []int32
+ if verify {
+ got = reference[i]
+ } else {
+ got = tok.Encode(tc.input, false)
+ }
+ if tc.want == nil || !slices.Equal(got, tc.want) {
+ t.Errorf("token IDs for %q:\n got: %v\nwant: %v", tc.input, got, tc.want)
+ if verify {
+ t.Logf("PYTHON OUTPUT (copy-paste as want):\n%#v", got)
+ }
+ }
+ })
+ }
+ })
+ }
+}
+
+func referenceTokenIDs(t *testing.T, data []byte, cases []tokenizerReferenceCase) [][]int32 {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "tokenizer.json")
+ if err := os.WriteFile(path, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ inputs := make([]string, len(cases))
+ for i, tc := range cases {
+ inputs[i] = tc.input
+ }
+ payload, err := json.Marshal(inputs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Match Encode(text, false): no padding, truncation, or automatic special tokens.
+ const script = `
+import json, sys, tokenizers
+tokenizer = tokenizers.Tokenizer.from_file(sys.argv[1])
+tokenizer.no_padding()
+tokenizer.no_truncation()
+inputs = json.load(sys.stdin)
+print(json.dumps({"version": tokenizers.__version__, "ids": [
+ tokenizer.encode(text, add_special_tokens=False).ids for text in inputs
+]}))
+`
+ cmd := exec.CommandContext(t.Context(), "python3", "-c", script, path)
+ cmd.Stdin = bytes.NewReader(payload)
+ var stderr strings.Builder
+ cmd.Stderr = &stderr
+ output, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("Python tokenizer reference failed: %v\n%s", err, stderr.String())
+ }
+ var result struct {
+ Version string `json:"version"`
+ IDs [][]int32 `json:"ids"`
+ }
+ if err := json.Unmarshal(output, &result); err != nil {
+ t.Fatalf("decode Python reference: %v", err)
+ }
+ if len(result.IDs) != len(cases) {
+ t.Fatalf("Python returned %d results, want %d", len(result.IDs), len(cases))
+ }
+ t.Logf("Python reference: tokenizers %s", result.Version)
+ return result.IDs
+}