8000 hftokenizer: fix ByteLevel spans & trim_offsets (#91); modeltests: teacher-forced generation checks by janpfeifer · Pull Request #93 · 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: 1 addition & 1 deletion .agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Manages downloading and access to HuggingFace repositories.
- `SpecialTokenID(SpecialToken) (int, error)`: Standardized lookup for `[BOS]`, `[EOS]`, `[PAD]`, `[UNK]`, `[MASK]`, `[CLS]`.
- **`hftokenizer`**:
- Pure Go implementation that unmarshals `tokenizer.json`, or builds directly from embedded GGUF `tokenizer.ggml.*` metadata via `NewFromGGUF(config, GGUFTokenizerParams)` (supporting BERT WordPiece with `llama.cpp` `\u2581` PhantomSpace normalization, ByteLevel BPE, and SentencePiece Unigram).
- Handles normalizers (BERT normalizer, lowercase, strip accents, replace), pre-tokenizers (whitespace, ByteLevel, Metaspace, BertPreTokenizer), models (BPE with byte fallback, WordPiece with `##` prefix, Unigram with Viterbi search), and post-processors (TemplateProcessing, BertProcessing, RobertaProcessing).
- Handles normalizers (BERT normalizer, lowercase, strip accents, replace), pre-tokenizers (whitespace, ByteLevel, Metaspace, BertPreTokenizer), models (BPE with byte fallback, WordPiece with `##` prefix, Unigram with Viterbi search), and post-processors (TemplateProcessing, BertProcessing, RobertaProcessing, ByteLevel, Sequence, including `trim_offsets`).
- **`tokenizers/bucket`**:
- Asynchronously batches streamed sentences into discrete length buckets to minimize zero-padding overhead in neural network inputs.
- Strategies:
Expand Down
7 changes: 7 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
- 2026/11/30:
- `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.
- Documented teacher-forced verification methodology in `docs/ModelTests.md`.
- `tokenizers/hftokenizer` (#91):
- Fixed `ByteLevel` pre-tokenizer offset tracking (`byteLevelPreTokenizeWithOffsets` and `byteLevelEncodeNoSplit`) so every UTF-8 byte of GPT-2 mapped characters (such as 2-byte `Ġ`, `Ċ`, and multi-byte UTF-8 characters) maps back to the original byte span instead of falling back to remapped byte lengths that shifted spans and exceeded input bounds. Also preserved the segment's starting offset when `add_prefix_space` prepends a space after an added token.
- Implemented `trim_offsets` and `add_prefix_space` support in `RobertaProcessing`, `ByteLevel`, and `Sequence` post-processors (matching HuggingFace `tokenizers`' `byte_level::process_offsets`), and applied post-processor offset trimming in `EncodeWithAnnotations` even when `AddSpecialTokens` is `false`.
- `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 `' '`.
Expand Down
21 changes: 14 additions & 7 deletions docs/ModelTests.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ Examples:
- `TestModels/minilm-l6-v2-gguf/Q4_K_M/go:quant_cached/embed_single`
- `TestModels/gemma4-e4b/default/xla:cuda/prefill_logits`
- `TestModels/gemma4-e4b/default/xla:cuda/kvcache_parity`
- `TestModels/gemma4-e4b/default/xla:cuda/greedy_generate`
- `TestModels/gemma4-e4b/default/xla:cuda/teacher_forced_generate`

---

Expand Down Expand Up @@ -304,11 +304,18 @@ For **generative LLM** variants, each variant includes a `"generate"` section al
2. **Batched padded execution**: Pads all sentences in a batch with `padID` + passes `seqLen` / attention mask, validating that every non-padded row still matches the reference vector within tolerance (catches masking/padding/RoPE bugs).
3. **Metrics**: Reports and asserts cosine similarity, max absolute difference, mean absolute difference, and (when provided) pairwise cosine similarity matrix error.

### 6.3 Generative LLMs (`prefill_logits`, `kvcache_parity`, `greedy_generate`)
Greedy decoding (`temperature = 0`) can diverge across runtimes/dtypes if two candidate tokens are nearly tied. Therefore generative tests use a **two-tier verification**:
1. **Prefill / Teacher-Forced Top-K Logits (`prefill_logits`)**: Runs a single forward pass on the prompt token IDs and checks the top-K (e.g. top-16) reference token logits (cosine similarity, max abs diff, and top-1 agreement when margin > tolerance). Fast, deterministic, and isolates math errors from decoding drift.
2. **Internal KV-Cache Parity (`kvcache_parity`)**: Runs a short greedy rollout (e.g., 16 tokens) with both naive (no KV cache) and KV-cached generation inside GoMLX and asserts **exact token parity + tight logit agreement**. Directly catches KV-cache, sliding-window, RoPE offset, and Gated DeltaNet state bugs with zero cross-framework noise.
3. **Greedy Generation (`greedy_generate`)**: Runs `temperature = 0` generation for `max_new_tokens` on low-entropy prompts and compares generated token IDs and decoded text against the reference (`min_exact_prefix_tokens` / exact match).
### 6.3 Generative LLMs (`prefill_logits`, `kvcache_parity`, `teacher_forced_generate`)
Free-running greedy decoding (`temperature = 0`) is inherently brittle across runtimes and low-precision dtypes (especially `BFloat16`, where 1 ULP at logit magnitude `~20` is `0.125`): if two candidate tokens are nearly tied and a 1-ULP rounding difference flips step `k`, feeding the flipped token back into step `k+1` causes all subsequent token distributions to diverge completely. To test autoregressive decoding deterministically and with tighter numerical coverage, generative checks use **teacher-forced multi-step verification**:

1. **Prefill Top-K Logits (`prefill_logits`)**: Runs a single forward pass on `prompt_token_ids` and checks the top-K (e.g., top-16) reference token logits from PyTorch (`logit_min_cosine_sim`, `logit_max_abs_diff`, and exact top-1 agreement whenever `top1 - top2 >= top1_margin_tolerance`). Fast, deterministic, and isolates prefill math errors from decode state.
2. **Teacher-Forced KV-Cache Parity (`kvcache_parity`)**: Verifies internal KV-cache / recurrent-state equivalence against a non-cached causal forward pass over `kvcache_parity_tokens` steps (default `8`) using the same forced token sequence $t_0, \dots, t_{N-2}$ (from `greedy_token_ids`, or from the KV path if absent):
- **Naive path (single causal forward pass)**: Runs one full-sequence forward pass on $[\text{prompt}, t_0, \dots, t_{N-2}]$ (length $P + N - 1$) and extracts the next-token logits at positions $P-1, \dots, P+N-2$.
- **KV-cache path (prefill + $N-1$ decode steps)**: Runs prefill on `prompt` (producing step 0 logits and initial cache), then feeds each forced token $t_{k-1}$ at position $P + k - 1$ for $k = 1 \dots N-1$ to obtain the cached decode logits.
- **Checks at every step $k$**: Asserts full-vocabulary cosine similarity (`>= logit_min_cosine_sim`), full-vocabulary max absolute difference (`<= 2 * logit_max_abs_diff`, accounting for extreme-value tail outliers across full 200k+ vocabularies), and exact top-1 argmax agreement whenever the naive logit margin (`top1 - top2`) is `>= top1_margin_tolerance`. Directly catches KV-cache, sliding-window, RoPE offset, and Gated DeltaNet state bugs with zero cross-framework noise and no cascading tie-break drift.
3. **Teacher-Forced Generation (`teacher_forced_generate`)**: Tests multi-step KV-cached decoding (or single-pass naive forward when `use_naive_only: true`) against the reference `greedy_token_ids` ($t_0, \dots, t_{M-1}$) across all prompts:
- Runs prefill on `prompt_token_ids` to predict $t_0$, then at each step $k = 1 \dots M-1$ forces the reference token $t_{k-1}$ into the next decode step so a 1-ULP tie at step $k$ never corrupts steps $k+1 \dots M-1$.
- **Per-step logit gap check**: At every step $k$, computes $\Delta_k = \max_v \text{logits}[k][v] - \text{logits}[k][t_k]$ (which is `0` on an exact top-1 match). If GoMLX logits agree with the reference within $\epsilon = \text{logit\_max\_abs\_diff}$, the reference greedy token can trail GoMLX's top-1 logit by at most $2\epsilon$; every step must satisfy $\Delta_k \le 2 \cdot \text{logit\_max\_abs\_diff}$.
- **Exact top-1 floor**: Also asserts that the total number of exact top-1 matches across all $M$ steps is `>= min_exact_prefix_tokens` (from `spec.json`, defaulting to $M$).

### 6.4 Time-Series Models (`timeseries_test.go`)
- Loads binary `.f32` context and expected forecast tensors (e.g., Timestral 28M & 123M), validates `max_abs_diff < 1e-4` across backends, and supports `-force_f32` / backend capability handling automatically.
Expand Down Expand Up @@ -409,7 +416,7 @@ Fix issues from the bottom up:
2. **`variables` fails**: Fix weight name mapping / config parsing in `models/transformer` (`config.go`, `model.go`, `gguf.go`).
3. **`embed_*` or `prefill_logits` fails**: Re-run with `-debug_layers` to identify the exact first layer where activations diverge.
4. **`kvcache_parity` fails**: Inspect KV-cache, sliding-window, RoPE position offset, or linear-attention recurrent state updates.
5. **`greedy_generate` fails**: Check chat templates, BOS/EOS stop tokens, logit soft-capping, or tied/untied `lm_head` weights.
5. **`teacher_forced_generate` fails**: Check chat templates, logit soft-capping, RoPE/KV-cache decode positions, or tied/untied `lm_head` weights.

### Step 4: Test Across Backends
```bash
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ require (
github.com/eliben/go-sentencepiece v0.7.0
github.com/gofrs/flock v0.13.0
github.com/gomlx/compute v0.1.36
github.com/gomlx/gomlx v0.28.41
github.com/gomlx/gomlx v0.28.42-0.20261130080819-1a52f7a748f7
github.com/google/uuid v1.6.0
github.com/parquet-go/parquet-go v0.29.0
github.com/pkg/errors v0.9.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ github.com/gomlx/go-darwinml v0.1.14 h1:po/TCO/kYU1RMK5sGAq+ngphX/t5pgglIjQniM2c
github.com/gomlx/go-darwinml v0.1.14/go.mod h1:T4w++nyZFB6sKXhSMnQ+nzVp/jbtmLBHJBiqcOs5hiM=
github.com/gomlx/go-xla v0.4.36 h1:lK+De6Eo8+BZsiLAZY+ZqVyZi1MGnlHWL7AEGgZs+zY=
github.com/gomlx/go-xla v0.4.36/go.mod h1:CjImtxda5XX+k1MZPH86UzMKcHiVAzWu+ASwL5D8cjY=
github.com/gomlx/gomlx v0.28.41 h1:jId0mlbcfxA0iA9KsF8YddmYS5iSYmnyUk8QlXMPTn8=
github.com/gomlx/gomlx v0.28.41/go.mod h1:EQPFUlmNd9YVrRyJPKxi4A6WDqIoPfR4Gr6WweaZgfE=
github.com/gomlx/gomlx v0.28.42-0.20261130080819-1a52f7a748f7 h1:CA5PNo59LmGriICaGrYJcghWKpTs0yekOf10g8vi4VY=
github.com/gomlx/gomlx v0.28.42-0.20261130080819-1a52f7a748f7/go.mod h1:EQPFUlmNd9YVrRyJPKxi4A6WDqIoPfR4Gr6WweaZgfE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand Down
6 changes: 3 additions & 3 deletions modeltests/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,11 @@ type TopKLogit struct {

// GenerateTolerances controls numerical thresholds for generative LLM checks.
type GenerateTolerances struct {
LogitMaxAbsDiff float64 `json:"logit_max_abs_diff,omitempty"` // Default 0.5
LogitMaxAbsDiff float64 `json:"logit_max_abs_diff,omitempty"` // Default 0.5 (teacher_forced_generate allows logit gap <= 2*LogitMaxAbsDiff)
LogitMinCosineSim float64 `json:"logit_min_cosine_sim,omitempty"` // Default 0.995
Top1MarginTolerance float64 `json:"top1_margin_tolerance,omitempty"` // Allow top-1 flip if ref top1-top2 margin < this (default 0.25)
MinExactPrefixTokens int `json:"min_exact_prefix_tokens,omitempty"` // Minimum matching greedy prefix tokens (default: all)
KVCacheParityTokens int `json:"kvcache_parity_tokens,omitempty"` // Number of tokens for KV-cache vs naive check (default 8)
MinExactPrefixTokens int `json:"min_exact_prefix_tokens,omitempty"` // Minimum exact top-1 matches in teacher_forced_generate (default: all)
KVCacheParityTokens int `json:"kvcache_parity_tokens,omitempty"` // Number of teacher-forced steps for KV-cache vs naive logit parity (default 8)
}

// TimeSeriesSpec configures time-series model parity tests (e.g., Timestral).
Expand Down
Loading
0