8000 hftokenizer: fix BertNormalizer control/format character filtering and parity by janpfeifer · Pull Request #92 · 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
9 changes: 5 additions & 4 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
## v0.4.42 - 2026-11-29

# `go-huggingface` Changelog
- 2026/11/30:
- `tokenizers/hftokenizer` (#90):
- Fixed `BertNormalizer` `clean_text` character filtering to drop Unicode General Category Other (`Cc`, `Cf`, `Co`) except `\t`/`\n`/`\r` via `isUnicodeOther` / `isBertControl`, matching Hugging Face `tokenizers` (`unicode_categories::is_other`) so format characters such as soft hyphen (`U+00AD`), zero-width space (`U+200B`), and left-to-right mark (`U+200E`) are stripped instead of producing `[UNK]`.
- Fixed `BertNormalizer` parity bugs: respected `n.CleanText` in `applyBertNormalizerWithOffsets`, removed unconditional/duplicate CJK space padding from `cleanText`, and expanded `isWhitespace` from `unicode.Zs` to `unicode.Z` so `U+2028` (`Zl`) and `U+2029` (`Zp`) normalize to `' '`.

## Unreleased
## v0.4.42 - 2026-11-29

- 2026/11/28:
- `models/gguf` (GHSA-v8r9-hqm6-68cf):
Expand Down
29 changes: 17 additions & 12 deletions tokenizers/hftokenizer/normalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,13 @@ func applyBertNormalizer(text string, n *Normalizer) string {
}

func applyBertNormalizerWithOffsets(text string, n *Normalizer) (string, []int) {
// Clean text and optionally lowercase
// Clean text, handle Chinese chars, and optionally strip accents / lowercase.
var result strings.Builder
var offsets []int
origPos := 0
for _, r := range text {
runeLen := len(string(r))
if r == 0 || r == 0xFFFD || isControl(r) {
if n.CleanText && (r == 0 || r == 0xFFFD || isBertControl(r)) {
// Skip this character
origPos += runeLen
continue
Expand All @@ -252,7 +252,7 @@ func applyBertNormalizerWithOffsets(text string, n *Normalizer) (string, []int)
}
result.WriteRune(' ')
offsets = append(offsets, origPos)
} else if isWhitespace(r) {
} else if n.CleanText && isWhitespace(r) {
result.WriteRune(' ')
offsets = append(offsets, origPos)
} else {
Expand Down Expand Up @@ -549,14 +549,10 @@ func tokenizeChineseChars(text string) string {
func cleanText(text string) string {
var result strings.Builder
for _, r := range text {
if r == 0 || r == 0xFFFD || isControl(r) {
if r == 0 || r == 0xFFFD || isBertControl(r) {
continue
}
if isChineseChar(r) {
result.WriteRune(' ')
result.WriteRune(r)
result.WriteRune(' ')
} else if isWhitespace(r) {
if isWhitespace(r) {
result.WriteRune(' ')
} else {
result.WriteRune(r)
Expand All @@ -569,14 +565,23 @@ func isWhitespace(r rune) bool {
if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
return true
}
return unicode.Is(unicode.Zs, r)
return unicode.Is(unicode.Z, r)
}

// isUnicodeOther reports whether r is in Unicode General Category Other
// (Cc, Cf, or Co), matching Rust's unicode_categories::is_other used by
10BC8 // Hugging Face's BertNormalizer.
func isUnicodeOther(r rune) bool {
return unicode.In(r, unicode.Cc, unicode.Cf, unicode.Co)
}

func isControl(r rune) bool {
// isBertControl reports whether BERT's clean_text drops r.
// Tabs and newlines are technically Cc (control) but treated as whitespace by BERT.
func isBertControl(r rune) bool {
if r == '\t' || r == '\n' || r == '\r' {
return false
}
return unicode.IsControl(r)
return isUnicodeOther(r)
}

func removeAccents(text string) string {
Expand Down
169 changes: 164 additions & 5 deletions tokenizers/hftokenizer/normalizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,31 @@ import (

func TestCleanText(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{"hello world", "hello world"},
{"hello\tworld", "hello world"},
{"hello\nworld", "hello world"},
{"hello\x00world", "helloworld"}, // null char removed
{"plain", "hello world", "hello world"},
{"tab to space", "hello\tworld", "hello world"},
{"newline to space", "hello\nworld", "hello world"},
{"carriage return to space", "hello\rworld", "hello world"},
{"null removed", "hello\x00world", "helloworld"},
{"replacement char removed", "hello\ufffdworld", "helloworld"},
{"other Cc removed", "a\x0bb\x0cc\u0085d\x1fe", "abcde"},
{"Cf soft hyphen removed", "co\u00adoperation", "cooperation"},
{"Cf zero-width space removed", "zero\u200bwidth", "zerowidth"},
{"Cf directional mark removed", "left\u200eright", "leftright"},
{"Cf BOM removed", "\ufeffhello", "hello"},
{"Co private use removed", "a\ue000b", "ab"},
{"Cn unassigned preserved", "a\u0378b", "a\u0378b"},
{"Zs NBSP to space", "hello\u00a0world", "hello world"},
{"Zl line separator to space", "hello\u2028world", "hello world"},
{"Zp paragraph separator to space", "hello\u2029world", "hello world"},
{"CJK untouched by cleanText alone", "中文", "中文"},
}

for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
got := cleanText(tt.input)
if got != tt.want {
t.Errorf("cleanText(%q) = %q, want %q", tt.input, got, tt.want)
Expand All @@ -27,6 +41,151 @@ func TestCleanText(t *testing.T) {
}
}

// TestBertNormalizer_CleanTextAndChineseCharsParity verifies that both
// applyBertNormalizer and applyBertNormalizerWithOffsets match Hugging Face's
// BertNormalizer across all combinations of clean_text and handle_chinese_chars,
// including Cc/Cf/Co dropping, Zl/Zp whitespace mapping, and CJK spacing.
func TestBertNormalizer_CleanTextAndChineseCharsParity(t *testing.T) {
tok := &Tokenizer{}
input := "a\x00b\u00adc\u200bd\ue000e\tf\u2028g\u2029h中i文j"
stripFalse := false

cases := []struct {
name string
cleanText bool
handleChineseChars bool
want string
}{
{
name: "clean=false cjk=false",
cleanText: false,
handleChineseChars: false,
want: "a\x00b\u00adc\u200bd\ue000e\tf\u2028g\u2029h中i文j",
},
{
name: "clean=false cjk=true",
cleanText: false,
handleChineseChars: true,
want: "a\x00b\u00adc\u200bd\ue000e\tf\u2028g\u2029h 中 i 文 j",
},
{
name: "clean=true cjk=false",
cleanText: true,
handleChineseChars: false,
want: "abcde f g h中i文j",
},
{
name: "clean=true cjk=true",
cleanText: true,
handleChineseChars: true,
want: "abcde f g h 中 i 文 j",
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
n := &Normalizer{
Type: "BertNormalizer",
CleanText: tc.cleanText,
HandleChineseChars: tc.handleChineseChars,
StripAccents: &stripFalse,
Lowercase: false,
}
gotNoOffsets := tok.applyNormalizer(input, n)
if gotNoOffsets != tc.want {
t.Errorf("applyNormalizer() = %q, want %q", gotNoOffsets, tc.want)
}
gotWithOffsets, offsets := tok.applyNormalizerWithOffsets(input, n)
if gotWithOffsets != tc.want {
t.Errorf("applyNormalizerWithOffsets() = %q, want %q", gotWithOffsets, tc.want)
}
assertOffsetsCoverBytes(t, tc.name, input, gotWithOffsets, offsets)
})
}
}

// TestIssue90_BertNormalizerFormatChars reproduces GitHub issue #90:
// BertNormalizer with clean_text=true must drop Unicode Cf (format) characters
// such as soft hyphen (U+00AD), zero-width space (U+200B), and left-to-right
// mark (U+200E) so words containing them tokenize identically to the clean text
// instead of becoming [UNK].
func TestIssue90_BertNormalizerFormatChars(t *testing.T) {
const bertTokenizerJSON = `{
"version": "1.0",
"added_tokens": [
{"id": 100, "content": "[UNK]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
{"id": 101, "content": "[CLS]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
{"id": 102, "content": "[SEP]", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}
],
"normalizer": {
"type": "BertNormalizer",
"clean_text": true,
"handle_chinese_chars": true,
"strip_accents": null,
"lowercase": true
},
"pre_tokenizer": {"type": "BertPreTokenizer"},
"post_processor": {
"type": "BertProcessing",
"sep": ["[SEP]", 102],
"cls": ["[CLS]", 101]
},
"decoder": {"type": "WordPiece", "prefix": "##"},
"model": {
"type": "WordPiece",
"unk_token": "[UNK]",
"continuing_subword_prefix": "##",
"max_input_chars_per_word": 100,
"vocab": {
"[UNK]": 100,
"[CLS]": 101,
"[SEP]": 102,
"cooperation": 6792,
"zero": 5717,
"##wi": 9148,
"##dt": 11927,
"##h": 2232,
"left": 2187,
"##right": 15950
}
}
}`

tok, err := NewFromContent(nil, []byte(bertTokenizerJSON))
if err != nil {
t.Fatalf("NewFromContent failed: %v", err)
}
if err := tok.With(api.EncodeOptions{AddSpecialTokens: true, IncludeSpans: true}); err != nil {
t.Fatalf("With failed: %v", err)
}

withCf := "co\u00adoperation zero\u200bwidth left\u200eright"
clean := "cooperation zerowidth leftright"

encCf := tok.EncodeWithAnnotations(withCf)
encClean := tok.EncodeWithAnnotations(clean)

wantIDs := []int{101, 6792, 5717, 9148, 11927, 2232, 2187, 15950, 102}
if !intSliceEqual(encClean.IDs, wantIDs) {
t.Fatalf("clean IDs = %v, want %v", encClean.IDs, wantIDs)
}
if !intSliceEqual(encCf.IDs, wantIDs) {
t.Errorf("with Cf IDs = %v, want %v", encCf.IDs, wantIDs)
}

// Verify spans for the input with stripped Cf characters remain valid byte
// ranges into the original string.
if got := withCf[encCf.Spans[1].Start:encCf.Spans[1].End]; got != "co\u00adoperation" {
t.Errorf("cooperation span = %v -> %q, want %q", encCf.Spans[1], got, "co\u00adoperation")
}
if got := withCf[encCf.Spans[2].Start:encCf.Spans[5].End]; got != "zero\u200bwidth" {
t.Errorf("zerowidth span = [%d,%d) -> %q, want %q", encCf.Spans[2].Start, encCf.Spans[5].End, got, "zero\u200bwidth")
}
if got := withCf[encCf.Spans[6].Start:encCf.Spans[7].End]; got != "left\u200eright" {
t.Errorf("leftright span = [%d,%d) -> %q, want %q", encCf.Spans[6].Start, encCf.Spans[7].End, got, "left\u200eright")
}
}

func TestUnicodeNormalization(t *testing.T) {
// Test tokenizer with NFD normalizer
nfdTokenizerJSON := []byte(`{
Expand Down
0