8000 hftokenizer: apply GPT-2 ByteLevel regex when use_regex is true (#94) by janpfeifer · Pull Request #95 · gomlx/go-huggingface · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
- 2026/11/30:
- `tokenizers/hftokenizer` (#94):
- Updated `ByteLevel` pre-tokenization with `use_regex: true` (`byteLevelPreTokenizeWithOffsets`) to split input using HuggingFace's GPT-2 regex (`'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`, with Unicode `White_Space` and `\s+(?!\S)` lookahead emulation) before byte remapping, preventing BPE merges across letter/number/punctuation/contraction boundaries while preserving no-split behavior when `use_regex: false`.
- `modeltests`, `docs/ModelTests.md`:
- Switched `kvcache_parity` to teacher-forced multi-step logit parity (single-pass causal naive forward vs. KV-cache prefill + forced single-token decode steps), asserting full-vocabulary cosine similarity, max abs diff, and top-1 agreement whenever logit margin exceeds `top1_margin_tolerance`.
- Replaced free-running `greedy_generate` with `teacher_forced_generate`, feeding each golden `greedy_token_ids[k-1]` into step `k` and asserting both per-step logit gap (`max(logits) - logits[wantID] <= 2 * logit_max_abs_diff`) and minimum exact top-1 match count, preventing 1-ULP BFloat16 near-ties from cascading across subsequent tokens.
Expand Down
101 changes: 66 additions & 35 deletions tokenizers/hftokenizer/pretokenizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,56 +214,87 @@ func appendByteLevelRune(dst *strings.Builder, offsets *[]int, text string, norm
}
}

// byteLevelEncodeNoSplit maps bytes to GPT-2 byte-level unicode characters without splitting on spaces.
// Used when ByteLevel has use_regex: false (e.g., after a Split pre-tokenizer in Qwen/Llama-3/DeepSeek).
func byteLevelEncodeNoSplit(text string, normOffsets []int) []wordWithOffset {
if len(text) == 0 {
return nil
}
// byteLevelGPT2Re implements HuggingFace's ByteLevel pre-tokenizer regex:
//
// 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
//
// Two adjustments bridge Go's RE2 engine to Rust's onig/fancy-regex used by HuggingFace tokenizers:
// 1. RE2's \s is ASCII-only ([\t\n\f\r ]), whereas Rust's \s matches Unicode White_Space
// ([\t\n\x0b\f\r \x{85}\p{Z}]).
// 2. RE2 does not support negative lookahead (?!\S), so \s+(?!\S)|\s+ is rewritten to a named
// capturing group (?P<ws_not_S>...) whose trailing whitespace rune is trimmed in
// byteLevelPreTokenizeWithOffsets when at least two whitespace runes precede a non-whitespace rune.
var (
byteLevelGPT2Re = regexp.MustCompile(
`'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\t\n\x0b\f\r \x{85}\p{Z}\p{L}\p{N}]+|(?P<ws_not_S>[\t\n\x0b\f\r \x{85}\p{Z}]+)`,
)
byteLevelGPT2WSGroupIdx = byteLevelGPT2Re.SubexpIndex("ws_not_S")
)

// encodeByteLevelSpan encodes text[start:end] using the GPT-2 byte-to-unicode table and
// tracks per-byte original offsets.
func encodeByteLevelSpan(text string, normOffsets []int, start, end int) wordWithOffset {
var current strings.Builder
currentOffsets := make([]int, 0, len(text))
for i := 0; i < len(text); {
_, runeLen := utf8.DecodeRuneInString(text[i:])
currentOffsets := make([]int, 0, end-start)
for i := start; i < end; {
_, runeLen := utf8.DecodeRuneInString(text[i:end])
appendByteLevelRune(&current, &currentOffsets, text, normOffsets, i, runeLen)
i += runeLen
}
return []wordWithOffset{{
return wordWithOffset{
text: current.String(),
start: currentOffsets[0],
end: currentOffsets[len(currentOffsets)-1] + 1,
offsets: currentOffsets,
}}
}
}

// byteLevelEncodeNoSplit maps bytes to GPT-2 byte-level unicode characters without splitting on spaces.
// Used when ByteLevel has use_regex: false (e.g., after a Split pre-tokenizer in Qwen/Llama-3/DeepSeek).
func byteLevelEncodeNoSplit(text string, normOffsets []int) []wordWithOffset {
if len(text) == 0 {
return nil
}
return []wordWithOffset{encodeByteLevelSpan(text, normOffsets, 0, len(text))}
}

// byteLevelPreTokenizeWithOffsets handles byte-level BPE pre-tokenization with offsets.
// byteLevelPreTokenizeWithOffsets splits text using the GPT-2 ByteLevel regex and encodes each
// piece to GPT-2 byte-level unicode characters with per-byte offset tracking.
func byteLevelPreTokenizeWithOffsets(text string, normOffsets []int) []wordWithOffset {
if len(text) == 0 {
return nil
}
var words []wordWithOffset
var current strings.Builder
var currentOffsets []int
flush := func() {
if current.Len() == 0 {
return
for pos := 0; pos < len(text); {
sub := byteLevelGPT2Re.FindStringSubmatchIndex(text[pos:])
if sub == nil {
words = append(words, encodeByteLevelSpan(text, normOffsets, pos, len(text)))
break
}
words = append(words, wordWithOffset{
text: current.String(),
start: currentOffsets[0],
end: currentOffsets[len(currentOffsets)-1] + 1,
offsets: currentOffsets,
})
current.Reset()
currentOffsets = nil
}

for i := 0; i < len(text); {
r, runeLen := utf8.DecodeRuneInString(text[i:])
if r == ' ' {
flush()
mStart := pos + sub[0]
mEnd := pos + sub[1]
if mStart > pos {
words = append(words, encodeByteLevelSpan(text, normOffsets, pos, mStart))
}
if byteLevelGPT2WSGroupIdx > 0 && sub[byteLevelGPT2WSGroupIdx*2] >= 0 && mEnd < len(text) {
// Emulate \s+(?!\S): leave the final whitespace rune for the next match
// (e.g., " a" -> " " + " a", "\r\nb" -> "\r" + "\n" + "b") when at least
// two whitespace runes matched before a non-whitespace rune.
_, lastSize := utf8.DecodeLastRuneInString(text[mStart:mEnd])
if mEnd-lastSize > mStart {
mEnd -= lastSize
}
}
if mEnd > mStart {
words = append(words, encodeByteLevelSpan(text, normOffsets, mStart, mEnd))
}
if mEnd == pos {
_, sz := utf8.DecodeRuneInString(text[pos:])
pos += max(sz, 1)
} else {
pos = mEnd
}
appendByteLevelRune(&current, &currentOffsets, text, normOffsets, i, runeLen)
i += runeLen
}
flush()

return words
}

Expand Down
128 changes: 128 additions & 0 deletions tokenizers/hftokenizer/pretokenizer_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hftokenizer

import (
"fmt"
"testing"

"github.com/gomlx/go-huggingface/tokenizers/api"
Expand Down Expand Up @@ -206,3 +207,130 @@ func TestByteLevelPreTokenizeSpans(t *testing.T) {
t.Errorf("subword é: span %v, want {5 7}", got)
}
}

// TestByteLevelUseRegex is a regression test for issue #94: with use_regex: true,
// ByteLevel splits on GPT-2 regex boundaries (e.g. letter-number) before BPE merges;
// with use_regex: false, it keeps the whole input as a single piece and permits the merge.
func TestByteLevelUseRegex(t *testing.T) {
tests := []struct {
name string
useRegex bool
wantIDs []int
wantSpans []api.TokenSpan
}{
{
name: "use_regex=true preserves letter-number boundary",
useRegex: true,
wantIDs: []int{0, 1},
wantSpans: []api.TokenSpan{{Start: 0, End: 1}, {Start: 1, End: 2}},
},
{
name: "use_regex=false allows merge across boundary",
useRegex: false,
wantIDs: []int{2},
wantSpans: []api.TokenSpan{{Start: 0, End: 2}},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := []byte(fmt.Sprintf(`{
"version": "1.0",
"normalizer": null,
"pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true, "use_regex": %t},
"model": {"type": "BPE", "unk_token": null, "vocab": {"a": 0, "1": 1, "a1": 2}, "merges": [["a", "1"]]}
}`, tt.useRegex))
tok, err := NewFromContent(nil, cfg)
if err != nil {
t.Fatalf("NewFromContent failed: %v", err)
}
if err := tok.With(api.EncodeOptions{IncludeSpans: true}); err != nil {
t.Fatalf("With failed: %v", err)
}
got := tok.EncodeWithAnnotations("a1")
if !intSliceEqual(got.IDs, tt.wantIDs) {
t.Errorf("IDs = %v, want %v", got.IDs, tt.wantIDs)
}
if !spansEqual(got.Spans, tt.wantSpans) {
t.Errorf("Spans = %v, want %v", got.Spans, tt.wantSpans)
}
})
}
}

func TestByteLevelGPT2RegexParity(t *testing.T) {
type piece struct {
text string
start int
end int
}
// Reference outputs verified against HuggingFace tokenizers 0.22.2
// ByteLevel(add_prefix_space=False, trim_offsets=True, use_regex=True).
tests := []struct {
input string
want []piece
}{
{"", nil},
{"a1", []piece{{"a", 0, 1}, {"1", 1, 2}}},
{"1a", []piece{{"1", 0, 1}, {"a", 1, 2}}},
{"café123", []piece{{"café", 0, 5}, {"123", 5, 8}}},
{"Hello, world! Isn't it great?", []piece{
{"Hello", 0, 5}, {",", 5, 6}, {"Ġworld", 6, 12}, {"!", 12, 13},
{"ĠIsn", 13, 17}, {"'t", 17, 19}, {"Ġit", 19, 22}, {"Ġgreat", 22, 28}, {"?", 28, 29},
}},
{"I'm's't're've'll'd", []piece{
{"I", 0, 1}, {"'m", 1, 3}, {"'s", 3, 5}, {"'t", 5, 7},
{"'re", 7, 10}, {"'ve", 10, 13}, {"'ll", 13, 16}, {"'d", 16, 18},
}},
{"I'M'S", []piece{
{"I", 0, 1}, {"'", 1, 2}, {"M", 2, 3}, {"'", 3, 4}, {"S", 4, 5},
}},
{"a 's", []piece{{"a", 0, 1}, {"Ġ'", 1, 3}, {"s", 3, 4}}},
{"foo_bar-baz.qux", []piece{
{"foo", 0, 3}, {"_", 3, 4}, {"bar", 4, 7}, {"-", 7, 8},
{"baz", 8, 11}, {".", 11, 12}, {"qux", 12, 15},
}},
{"a b", []piece{{"a", 0, 1}, {"Ġ", 1, 2}, {"Ġb", 2, 4}}},
{"a b", []piece{{"a", 0, 1}, {"ĠĠ", 1, 3}, {"Ġb", 3, 5}}},
{"a ", []piece{{"a", 0, 1}, {"ĠĠĠ", 1, 4}}},
{" ", []piece{{"ĠĠĠ", 0, 3}}},
{" \na", []piece{{"Ġ", 0, 1}, {"Ċ", 1, 2}, {"a", 2, 3}}},
{"\n a", []piece{{"Ċ", 0, 1}, {"Ġa", 1, 3}}},
{" \n a", []piece{{"ĠĊ", 0, 2}, {"Ġa", 2, 4}}},
{"a\r\nb", []piece{{"a", 0, 1}, {"č", 1, 2}, {"Ċ", 2, 3}, {"b", 3, 4}}},
{"a\n\nb", []piece{{"a", 0, 1}, {"Ċ", 1, 2}, {"Ċ", 2, 3}, {"b", 3, 4}}},
{"a\t b", []piece{{"a", 0, 1}, {"ĉ", 1, 2}, {"Ġb", 2, 4}}},
{"a \tb", []piece{{"a", 0, 1}, {"Ġ", 1, 2}, {"ĉ", 2, 3}, {"b", 3, 4}}},
{"a \n", []piece{{"a", 0, 1}, {"ĠĠĠĊ", 1, 5}}},
{"I café 日本語!", []piece{
{"I", 0, 1}, {"Ġcafé", 1, 7}, {"ĠæĹ¥æľ¬èªŀ", 7, 17}, {"!", 17, 18},
}},
// Unicode White_Space (\u00a0, \u0085, \u2028, \u3000, \x0b, \x0c) must match \s, not punctuation.
{"a\u00a0!b", []piece{{"a", 0, 1}, {"Âł", 1, 3}, {"!", 3, 4}, {"b", 4, 5}}},
{"a\u00a0\u00a0b", []piece{{"a", 0, 1}, {"Âł", 1, 3}, {"Âł", 3, 5}, {"b", 5, 6}}},
{"a\u0085!b", []piece{{"a", 0, 1}, {"Âħ", 1, 3}, {"!", 3, 4}, {"b", 4, 5}}},
{"a\u2028!b", []piece{{"a", 0, 1}, {"â̍", 1, 4}, {"!", 4, 5}, {"b", 5, 6}}},
{"a\u3000!b", []piece{{"a", 0, 1}, {"ãĢĢ", 1, 4}, {"!", 4, 5}, {"b", 5, 6}}},
{"a\x0b!b", []piece{{"a", 0, 1}, {"ċ", 1, 2}, {"!", 2, 3}, {"b", 3, 4}}},
{"a\x0c!b", []piece{{"a", 0, 1}, {"Č", 1, 2}, {"!", 2, 3}, {"b", 3, 4}}},
}

for _, tt := range tests {
words := byteLevelPreTokenizeWithOffsets(tt.input, identityOffsets(len(tt.input)))
if len(words) != len(tt.want) {
t.Errorf("input %q: got %d words %+v, want %d %+v", tt.input, len(words), words, len(tt.want), tt.want)
continue
}
for i, w := range words {
want := tt.want[i]
if len(w.offsets) != len(w.text) {
t.Errorf("input %q word %d (%q): len(offsets)=%d != len(text)=%d", tt.input, i, w.text, len(w.offsets), len(w.text))
}
span := w.spanForSubword(0, len(w.text))
if w.text != want.text || span.Start != want.start || span.End != want.end {
t.Errorf("input %q word %d: got (%q, [%d,%d)), want (%q, [%d,%d))",
tt.input, i, w.text, span.Start, span.End, want.text, want.start, want.end)
}
}
}
}
0