Skip to content

fix(provider): Gemma 4 replies keep characters written as byte tokens - #1703

Merged
davidtai merged 3 commits into
devfrom
fix/gemma-byte-fallback-flush
Nov 3, 2026
Merged

davidtai merged 3 commits into
devfrom
fix/gemma-byte-fallback-flush

Conversation

@jonathan308

@jonathan308 jonathan308 commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A Gemma 4 reply loses the characters its vocabulary writes as byte tokens when they come last, and a long reply can corrupt one mid-stream. A reply made only of such characters comes back empty.

The tokens spell A client receives today
all zipped up 🗜 all zipped up
the sky today is clear 🩵 the sky today is clear
the last syllable 갂 the last syllable
cube root sign ∛ cube root sign
long Korean or CJK text a U+FFFD where a character should be, about every 256 tokens when a byte token lands on that boundary

swift-transformers' ByteFallbackDecoder releases <0xHH> tokens only when a later token arrives. A decode ending in them drops them and shows nothing pending, so:

  • the trailing run of a reply is lost at the end of the stream, in both streaming and non-streaming replies, however long it is;
  • DetokenizerV2 thinks the segment is clean and restarts it at its 256-token soft cap inside the run, keeping only the last byte token, so the character comes out as U+FFFD.

Gemma 4's published tokenizer.json declares that decoder, and characters outside its 262,144-token vocabulary are written that way: 90 of 114 assigned code points in U+1FA70–1FAFF (🩵, 🪩), 170 of 768 in U+1F300–1F5FF, 11,554 of 20,992 in U+4E00–9FFF, 9,439 of 11,172 Hangul syllables.

LocalTokenizerBridge.decode now releases a trailing run itself. A partial run reads as U+FFFD, which DetokenizerV2 already holds back, so its restart can no longer land inside a character. A probe at load turns this on only when a lone byte token decodes to nothing, so other decoders are untouched and a fixed upstream turns it off.

Token IDs, numeric logprobs, sampling, model state and cache keys do not change, with one exception below: a stop string a trailing run completes now matches one token sooner. This changes served text on purpose, so it needs the owner's acceptance.

Target: 0.10.7. It is provider-only, needs no SDK repin, and sits on v0.10.6 (84ddfdba6b). Merges with #1693, #1650, #1668 and #1669 with no conflict. Merge it after #1693: see Limitations.

Linked issue

None; found by the verifier of #1693 during the 0.10.7 sweep, then confirmed on a running provider.

Before And After

flowchart TB
  subgraph B["Before"]
    direction LR
    B1["tokens end in <0xF0> <0x9F> <0x97> <0x9C>"] --> B2["ByteFallbackDecoder: bytes wait for a later token"]
    B2 --> B3["no later token: bytes dropped"]
    B3 --> B4["client: all zipped up"]
  end
  subgraph A["After"]
    direction LR
    A1["tokens end in <0xF0> <0x9F> <0x97> <0x9C>"] --> A2["LocalTokenizerBridge.decode: releases the trailing run"]
    A2 --> A3["partial run reads as U+FFFD, held back by DetokenizerV2"]
    A3 --> A4["client: all zipped up 🗜"]
  end
  B ~~~ A
Loading

Test plan

Arms: v0.10.6 84ddfdba6b (binary e8cba71e…) and this commit (binary 01784ed0…, built from 16d59d9ce; the later commit on this branch changes only a test and the changelog). SDK 7933a0fa, mlx-swift c633d221, mlx 72dffa2d, same metallib. Gemma 4 26B QAT, weights verified against the published manifest, isolated start --local providers on an M3 Ultra, temperature 0, MTP off. Plan fixed before the data: candidates/N7-13-byte-fallback-flush/PLAN.md in the sweep folder.

  • Red/green: new LocalTokenizerByteFallbackTests (7 tests, 9 cases): 42 issues with master's bridge; all pass with the change.

  • Mutations caught: unknown names read as bytes 1 issue, probe removed 2, skipSpecialTokens walk removed 1.

  • Live, 30 exact-repeat lines ending in a character confirmed outside the vocabulary from the published file, fixed before the build:

    Master This PR
    Client text equals the line, streaming 0 of 30 30 of 30
    Client text equals the line, non-streaming 0 of 30 30 of 30
  • Live, 6 long replies, 838 to 1,400 tokens, Hangul and CJK with such characters, no newlines: U+FFFD in client text 12 on master, 1 here, streaming and non-streaming. The one left is the last character of a reply stopped by max_tokens inside a character, which DetokenizerV2's header says happens. Characters delivered 3,425 → 3,642 streaming.

  • Same tokens, non-streaming: per-token numeric logprobs bitwise equal on 36 of 36 requests (6,723 tokens). Completion tokens and finish reasons equal on 72 of 72, streaming included.

  • Same tokens, streaming: the plan's gate failed as written. Numeric logprob lists differ on all 36 streaming requests, by length: master's stream omits the entries of tokens whose text never appeared, the same bytes this change releases, so this PR's list is longer (6,593 → 6,868 entries). Master's list is a subsequence of this PR's on 36 of 36. Reported as a failed gate, not reinterpreted.

  • Frozen 11-request agentic conversation × 10 units with logprobs on: logprobs bitwise equal, content, usage, cached tokens and finish equal, 110 of 110 (6,219 tokens). It has no byte-fallback token, so its text does not move.

  • Other tokenizers: bridge decode equals upstream decode on the published gpt-oss, Nemotron Lightning and Qwen3.5 tokenizers, 2,000 sequences each, both skipSpecialTokens values, 0 differing. None has <0xHH> tokens.

  • Nearby suites on this commit: 112 tests in 17 suites pass. make docs-impact-check BASE=84ddfdba6b…, make docs-check, make changelog-check: pass.

  • Independent verifier (fresh subagent, its own prompts, comparison code and tests, gates fixed in advance, report in the sweep folder): PARTIAL. The fix reproduces and the identity claim needed the two corrections now in this description.

    • Own 88 live requests: text spells the tokens on 88 of 88 here; master loses or corrupts characters on all 88. Stream equals non-streaming on 44 of 44 here, 4 of 44 on master.
    • Against Python tokenizers on the published file, 102,994 comparisons, every ID alone and all 65,536 byte pairs: no wrong text for valid UTF-8. For invalid bytes this writes one U+FFFD per bad sequence, as upstream does mid-run, where Python writes one per byte.
    • Named mutations caught by this PR's tests and by its own. Other tokenizers: about 6,080 sequences each and every single ID, 0 differing. Cost: under 2% on one decode of 256 tokens, 0.5 ms at load.
    • Its identity gate fails on streaming as this PR's does; the same stop-string exception comes from it. The tests added after its report close the gaps it named.
  • Timing: no-regression set under the sweep's quiet rule, kept 2026-11-02 18:59 UTC: the frozen 11-request Gemma 4 26B QAT conversation, --mtp off, same-text A/A 5 pairs then ABBA 10 pairs, v0.10.6 against 16d59d9ce6 (this head adds only tests and the changelog). Total −0.37%, follow-up TTFT −0.40%, first-request TTFT −0.85%, decode +0.30%, non-donor waits −1.54%; no pair beyond its threshold (3.00% on total and follow-up TTFT); outputs and cached tokens equal on 110/110.

  • make provider-test steps on a local combination of v0.10.6, fix(provider): Gemma 4 text keeps its spaces before punctuation (git add . came back as git add.) #1693, Gemma 4 and <think> models: client stop sequences skip reasoning and tool calls #1650, perf(provider): prepare the checkpoint row encoder once per segment (Gemma donor stream end 1.7–2.0 s → 1.0–1.2 s) #1668, perf(provider): check each restored checkpoint row once for non-finite values (Gemma cached follow-up TTFT −26.6%, ~0.2 s per SSD restore) #1669, this PR and the Gemma decode limits candidate (never pushed): 644 XCTest, 129 skipped, 0 failures; 6,736 Swift Testing tests plus 9 isolated runs pass, 0 crashes. The metallib was staged by hand: the Metal Toolchain is not installed here. CI runs the suite on this head. Combined timed A/B against v0.10.6, 2026-11-01, frozen 11-request Gemma conversation, MTP off, same-text A/A 5 pairs then 10 ABBA pairs, under the 25% background-CPU rule with the owner's waiver for iCloud's fileproviderd and bird: summed follow-up TTFT 8.911 → 6.336 s, −28.87%, 10/10 beyond 4.33%; donor waits 5.633 → 2.639 s, −53.07%, 10/10 beyond 4.34%; summed time 20.219 → 14.213 s, −29.74%, 10/10 beyond 3.01%; decode +11.41%; outputs and cached tokens equal on 110/110. One no-regression clause fails as written: non-donor stream-end waits +27.67% against a 13.21% threshold, on all 10 pairs, which is 12 → 16 ms per request.

Refactor pass: dedicated subagent; probe renamed so it no longer shares a name with the stored property, one comment on the non-obvious branch, unused import removed, docs and changelog tightened. No behaviour change. Tests and doc checks re-run on the result.

Limitations

  • Served text changes. A reply cut inside a character by max_tokens now ends in U+FFFD instead of dropping it. /detokenize keeps a trailing run too.
  • Stop strings: one that a trailing run completes now matches when the run completes, so generation ends one token sooner and completion_tokens falls by one (stop: ["🗜"]: 9 → 8). This is the one case where the tokens generated change.
  • logprobs: a streamed reply gains the entries of tokens whose text never appeared. A byte token's token and bytes move from empty to U+FFFD or its ASCII character, not the real byte.
  • Merge after fix(provider): Gemma 4 text keeps its spaces before punctuation (git add . came back as git add.) #1693. With cleanup still on, a printable ASCII byte token landing where cleanup rewrites can be emitted twice (a ..z). The encoder never writes those tokens and none reached the top 20 alternatives at the 10 positions checked. fix(provider): Gemma 4 text keeps its spaces before punctuation (git add . came back as git add.) #1693 turns that cleanup off.
  • A run of only invalid bytes: the detokenizer's segment cannot restart, so decode cost grows with the square of its length: 71 s over 16,384 such tokens, against 1.1 s on master, where that reply returned no text at all. Byte-level tokenizers already cost this on master (gpt-oss 92 s) and so does Gemma's own U+FFFD token (105 s). It needs a model that repeats invalid bytes for thousands of tokens. A hard cap in DetokenizerV2 would close it for every tokenizer; not done here.
  • Synthetic corners, not in any tokenizer on this Mac: a decoder ending in Strip under skipSpecialTokens: true, and a byte token flagged special.
  • Not covered live: the coordinator's sealed path and MTP on. The change is in the tokenizer bridge they share.
  • Other loaders: the SDK's own #huggingFaceTokenizerLoader and the cluster worker's PromptTokenizer don't go through this bridge and keep the old behaviour. The worker's tokenizer serves qualification tools and only prints readable text. The defect itself is upstream in swift-transformers 1.3.3; no upstream PR was opened.
  • Prevalence unknown: bodies are sealed, so how many fleet replies are affected can't be measured. Gemma 4 is 72.8% of requests by the public 7-day counters.

Components touched

  • provider-swift (Swift CLI)
  • native runtime / MLX
  • landing (Next.js)
  • enclave (Swift)
  • CI / provider release
  • docs

Protocol / interface changes

  • No protocol/interface changes
  • Yes — described above and matching side updated

Documentation impact

  • Canonical documentation updated (docs/architecture/inference.md, docs/developer/test.md, changelog.d/gemma-byte-fallback-flush.md)
  • No documentation needed — reason:

AI usage: the code, tests, measurements and this description were produced by Claude (Claude Code, Opus 5.5) during an unattended sweep, at the repository owner's request. A human has not yet reviewed them.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

jonathan308 and others added 2 commits October 31, 2026 15:00
swift-transformers' ByteFallbackDecoder releases <0xHH> tokens only when a
later token arrives, so a decode ending in them drops them and shows nothing
pending. Gemma 4 writes characters outside its vocabulary that way: a reply
ending in one lost it, and DetokenizerV2 could restart its segment inside a
run and corrupt the character. LocalTokenizerBridge.decode now releases a
trailing run itself. Token IDs, sampling, model state and cache keys do not
change; only the text decoded from the same tokens does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests only and the changelog, no source change: a reply of byte tokens alone
longer than any walk bound, a control character written as a byte, and the
unknown-token test loads the tokenizer repeatedly because the probe reads
whichever byte token a dictionary lists first. The changelog now states the
stop-string exception, the streamed logprobs entries, logprobs bytes and
/detokenize.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Error Error Nov 3, 2026 7:16am UTC
d-inference-console-ui-dev Error Error Nov 3, 2026 7:16am UTC
d-inference-landing Ready Ready Preview Nov 3, 2026 7:16am UTC
darkbloom-status Ready Ready Preview Nov 3, 2026 7:16am UTC
eigen-homepages-darkbloom Ready Ready Preview Nov 3, 2026 7:16am UTC

Request Review

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head b1c3d66843e4 against base 84ddfdba6bb7.

Reviewers: anthropic/claude-sonnet-5.5: first pass completed; anthropic/claude-opus-5.5: selected depth completed (2 batches); openai/gpt-6.1-sol: not needed by escalation policy

No actionable findings in the reviewed text. This is not a security approval.

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Scan completed.

Coverage: 56/56 source units; cross-file integration complete. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned.

Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 0 reused batch(es), 0 provider cache-hit tokens.

Saved findings and earlier report · Historical findings are not confirmed resolved.

Bedrock: 25 request(s), 1182442 uncached + 0 cache-read + 0 cache-write input / 15261 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately.
Workload allowance: 26 native request(s), including one shared response repair; 500 emergency ceiling. Selected depth and integration rounds are admitted as their scope becomes known.

@jonathan308
jonathan308 changed the base branch from master to dev November 3, 2026 07:12

@davidtai davidtai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for the 0.10.7 release (David's order, 2026-11-03). Deferred lane, released by David 2026-11-03. Full-diff review: provider-lane-review.md, section Deferred lane. Composition check: draft #1738, CI run 41631482989 green.

@davidtai
davidtai merged commit 2465dcf into dev Nov 3, 2026
24 of 26 checks passed
@davidtai
davidtai deleted the fix/gemma-byte-fallback-flush branch November 3, 2026 12:23
@jonathan308 jonathan308 mentioned this pull request Nov 3, 2026
14 of 17 tasks

This branch had an error being deployed

2 failed and 3 active deployments
Preview – d-inference-landing — b5389971 Deployed Nov 3, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — b5389971 Deployed Nov 3, 2026 by vercel[bot]
Preview – darkbloom-status — b5389971 Deployed Nov 3, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — b5389971 Deployed Nov 3, 2026 by vercel[bot]
Preview – d-inference — b5389971 Deployed Nov 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants