Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Decode tokens incrementally and losslessly (#118)

Andrey Mikhaylovacefaf173b2a
diff --git a/Package.swift b/Package.swift
index bc450f93..3430eed7 100644
--- a/Package.swift
+++ b/Package.swift
@@ -29,6 +29,7 @@ let package = Package(
dependencies: [
"TurboFieldfareFormat",
.product(name: "Tokenizers", package: "swift-transformers"),
+ .product(name: "Hub", package: "swift-transformers"),
],
path: "Sources/TurboFieldfare",
resources: [
@@ -119,7 +120,13 @@ let package = Package(
),
.testTarget(
name: "TurboFieldfareTestsCore",
- dependencies: ["TurboFieldfare", "TurboFieldfareValidationSupport", "TurboFieldfareRepackCore", "TurboFieldfareCLICore"],
+ dependencies: [
+ "TurboFieldfare",
+ "TurboFieldfareValidationSupport",
+ "TurboFieldfareRepackCore",
+ "TurboFieldfareCLICore",
+ .product(name: "Hub", package: "swift-transformers"),
+ ],
path: "Tests/TurboFieldfare/Core"
),
.testTarget(
diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
index 3bae8cae..2f3108c5 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
@@ -116,7 +116,8 @@ public func runRawCompletion(producer: any LogitProducer,
}
let computedPrefillTokens = promptIds.count - cachedPromptTokens
- var detok = GFDetokenizer(tokenizer: tokenizer)
+ var detok = GFDetokenizer(tokenizer: tokenizer,
+ barrierTokenIDs: tokenizer.structuralMarkerIDs)
var history = Array(promptIds.prefix(cachedPromptTokens))
history.reserveCapacity(promptIds.count + config.maxNewTokens)
diff --git a/Sources/TurboFieldfare/Tokenization/Detokenizer.swift b/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
index 6d967dd7..558a6437 100644
--- a/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
@@ -1,103 +1,76 @@
import Foundation
import Tokenizers
-/// Streaming detokenizer for generation loops.
+/// Streaming detokenizer for generation loops. `GFTokenizer.decode` is a
+/// push-loop over this type, so batch and streaming decode agree by
+/// construction.
///
-/// Two challenges drive the design:
+/// Emits each token's own contribution to the output as it arrives. Two
+/// properties make that safe:
///
-/// 1. BPE byte-fallback splits multi-byte codepoints (e.g. emoji) across several
-/// tokens. Naively decoding each token in isolation yields broken UTF-8.
-/// 2. swift-transformers' decoder silently drops byte-fallback tokens that sit
-/// at the **end** of the decoded sequence (the bytes are committed only once
-/// a non-byte-fallback token follows). For us this matters at `flush()`.
+/// 1. The Gemma decoder sequence (`Replace`, `ByteFallback`, `Fuse`) is
+/// position-independent, so the decode of a token stream is the
+/// concatenation of its per-token fragments. `GemmaDecoding` reproduces that
+/// sequence without HF's `clean_up_tokenization_spaces` pass, which is the
+/// one stage that rewrites already-decoded text and is wrong for this
+/// tokenizer anyway (see `GemmaDecoding`).
+/// 2. BPE byte fallback splits a multi-byte codepoint across several tokens, so
+/// a run of `<0xXX>` tokens is held until the token that closes it and
+/// commits as a whole, with the reference decoder's semantics (see
+/// `ByteFallbackRun`). Skipped special tokens are filtered before the run
+/// logic — matching the library, which drops special IDs before its decoder
+/// chain — so a run fuses across them; in keep mode a special is an ordinary
+/// token and closes the run.
///
-/// Strategy:
-/// - During `push(_:)` we decode the longest prefix of accumulated IDs that
-/// does NOT end with byte-fallback tokens, then emit the delta vs. previously
-/// emitted text. Any trailing byte-fallback IDs are held back.
-/// - During `flush()` we decode the stable prefix as above AND manually
-/// assemble the trailing byte-fallback bytes into a UTF-8 string. This
-/// recovers text the library would otherwise drop on a sequence-ending
-/// codepoint.
+/// `barrierTokenIDs` carves out an exception to the fuse rule for the
+/// generation pipeline: the channel/tool markers structure assistant output,
+/// and text held back across one would surface after the marker and be routed
+/// under the wrong channel state (thought text leaking into the visible
+/// answer). A barrier commits the run and returns its text as the marker's own
+/// delta, which `StructuredAssistantDecoder.consume` routes under the channel
+/// in effect before the marker switches it. Plain `decode` passes no barriers,
+/// keeping full library parity.
+///
+/// Cost is O(1) per token and independent of how much has already been
+/// generated. The previous implementation re-decoded the entire accumulated
+/// token list on every push, which made a generation O(n²) — roughly 3.6·10⁹
+/// dictionary lookups over the app's 64K-token budget — and compared the result
+/// against the full emitted prefix to recover a delta.
struct GFDetokenizer {
- @usableFromInline let tokenizer: any Tokenizer
- @usableFromInline var stableIDs: [Int] = []
- @usableFromInline var trailingByteIDs: [Int] = []
- @usableFromInline var emitted: String = ""
+ let tokenizer: any Tokenizer
+ let skipSpecialTokens: Bool
+ private let specialTokenIDs: Set<Int32>
+ private let barrierTokenIDs: Set<Int32>
+ /// In-flight byte-fallback run.
+ private var run = ByteFallbackRun()
- init(tokenizer: GFTokenizer) {
+ init(tokenizer: GFTokenizer,
+ skipSpecialTokens: Bool = true,
+ barrierTokenIDs: Set<Int32> = []) {
self.tokenizer = tokenizer.tokenizer
+ self.skipSpecialTokens = skipSpecialTokens
+ self.specialTokenIDs = tokenizer.specialTokenIDs
+ self.barrierTokenIDs = barrierTokenIDs
}
+ /// Text contributed by `id`, ready to append to the stream.
+ ///
+ /// Returns `""` while a byte-fallback run is still open and valid; those
+ /// bytes come out with the token that closes the run, at a barrier marker,
+ /// or at `flush()`.
mutating func push(_ id: Int32) -> String {
- let tokenID = Int(id)
- let token = tokenizer.convertIdToToken(tokenID) ?? ""
- if Self.isByteFallback(token) {
- trailingByteIDs.append(tokenID)
- return ""
- }
-
- if !trailingByteIDs.isEmpty {
- stableIDs.append(contentsOf: trailingByteIDs)
- trailingByteIDs.removeAll(keepingCapacity: true)
+ // An unknown ID contributes nothing and leaves the run open, matching
+ // the library, whose decode compactMap-drops unresolvable IDs.
+ guard let token = tokenizer.convertIdToToken(Int(id)) else { return "" }
+ if skipSpecialTokens, specialTokenIDs.contains(id) {
+ return barrierTokenIDs.contains(id) ? run.commit() : ""
}
- stableIDs.append(tokenID)
-
- let current = tokenizer.decode(tokens: stableIDs, skipSpecialTokens: true)
- return commitDelta(current)
+ if let byte = GemmaDecoding.byteValue(token) { return run.push(byte) }
+ return run.commit() + GemmaDecoding.fragment(token)
}
+ /// Remainder held back at a stop boundary.
mutating func flush() -> String {
- let stableText = stableIDs.isEmpty
- ? ""
- : tokenizer.decode(tokens: stableIDs, skipSpecialTokens: true)
-
- let trailingText = assembleByteFallback(trailingByteIDs)
- let fullText = stableText + trailingText
- return commitDelta(fullText)
- }
-
- @usableFromInline
- mutating func commitDelta(_ current: String) -> String {
- // A combining mark can extend the last emitted grapheme, so compare the
- // append-only prefix without using Character boundaries.
- let currentUTF8 = current.utf8
- var boundary = currentUTF8.startIndex
- for byte in emitted.utf8 {
- guard boundary != currentUTF8.endIndex,
- currentUTF8[boundary] == byte else {
- // Decoder altered the prefix — extremely rare in append-only streams.
- // Resync rather than emit garbage; the user-visible loss is bounded
- // to whatever was retokenized.
- emitted = current
- return ""
- }
- currentUTF8.formIndex(after: &boundary)
- }
- let delta = String(current[boundary...])
- emitted = current
- return delta
- }
-
- @usableFromInline
- func assembleByteFallback(_ ids: [Int]) -> String {
- var bytes: [UInt8] = []
- bytes.reserveCapacity(ids.count)
- for id in ids {
- guard let tok = tokenizer.convertIdToToken(id) else { continue }
- guard Self.isByteFallback(tok),
- let byte = UInt8(tok.dropFirst(3).dropLast(), radix: 16)
- else { continue }
- bytes.append(byte)
- }
- return String(bytes: bytes, encoding: .utf8) ?? ""
- }
-
- @usableFromInline
- static func isByteFallback(_ token: String) -> Bool {
- token.count == 6
- && token.hasPrefix("<0x")
- && token.hasSuffix(">")
- && token.dropFirst(3).dropLast().allSatisfy { $0.isHexDigit }
+ run.commit()
}
}
diff --git a/Sources/TurboFieldfare/Tokenization/GemmaDecoding.swift b/Sources/TurboFieldfare/Tokenization/GemmaDecoding.swift
new file mode 100644
index 00000000..4f6284ae
--- /dev/null
+++ b/Sources/TurboFieldfare/Tokenization/GemmaDecoding.swift
@@ -0,0 +1,126 @@
+import Foundation
+import Tokenizers
+
+/// The pinned Gemma 4 detokenization pipeline, without HF's cleanup pass.
+///
+/// `tokenizer.json` declares `decoder: Sequence[Replace("▁" -> " "),
+/// ByteFallback, Fuse]`. swift-transformers runs that sequence and then applies
+/// `clean_up_tokenization_spaces`, which defaults to **true** when the key is
+/// absent — and Gemma's `tokenizer_config.json` omits it.
+///
+/// That cleanup pass is a legacy heuristic for whitespace tokenizers and is
+/// wrong for a metaspace + byte-fallback BPE, which is lossless by
+/// construction. It rewrites text the model deliberately produced:
+///
+/// ```text
+/// "he said ' ok ' now" -> "he said'ok'now"
+/// "step 1 . done" -> "step 1. done"
+/// " . indented" -> " . indented"
+/// ```
+///
+/// So `decode(encode(x)) != x`. It also breaks streaming: because the pass runs
+/// over the whole string on every call, appending a token can rewrite text that
+/// was already emitted, which no append-only stream can represent.
+///
+/// This type reproduces the declared decoder sequence and stops there. Both the
+/// batch (`GFTokenizer.decode`) and streaming (`GFDetokenizer`) paths go through
+/// it, so they agree by construction.
+enum GemmaDecoding {
+ /// `<0xXX>` byte-fallback token, e.g. `<0xE2>`.
+ static func isByteFallback(_ token: String) -> Bool {
+ token.count == 6
+ && token.hasPrefix("<0x")
+ && token.hasSuffix(">")
+ && token.dropFirst(3).dropLast().allSatisfy { $0.isHexDigit }
+ }
+
+ static func byteValue(_ token: String) -> UInt8? {
+ guard isByteFallback(token) else { return nil }
+ return UInt8(token.dropFirst(3).dropLast(), radix: 16)
+ }
+
+ /// One token's contribution to the output: the `Replace` decoder's
+ /// `"▁" -> " "` substitution. Byte-fallback tokens are handled by
+ /// `ByteFallbackRun` instead — they only decode as a complete run.
+ static func fragment(_ token: String) -> String {
+ // Runs once per generated token; most tokens contain no "▁", and the
+ // guard returns them without Foundation bridging or an allocation.
+ guard token.unicodeScalars.contains(sentencePieceUnderline) else { return token }
+ var scalars = String.UnicodeScalarView()
+ for scalar in token.unicodeScalars {
+ scalars.append(scalar == sentencePieceUnderline ? " " : scalar)
+ }
+ return String(scalars)
+ }
+
+ private static let sentencePieceUnderline: Unicode.Scalar = "\u{2581}"
+}
+
+/// A run of `<0xXX>` byte-fallback tokens, decoded with the reference HF
+/// `tokenizers` ByteFallback semantics: the run commits as a whole — valid
+/// UTF-8 becomes its text, anything else (including an incomplete trailing
+/// sequence) becomes one U+FFFD per byte of the run. The swift-transformers
+/// port differs here (it decodes invalid runs leniently and drops a trailing
+/// run outright — issue #58); we follow the Rust reference.
+///
+/// Streaming: while the run is valid so far, nothing can be emitted, because
+/// one more byte can invalidate the whole run retroactively. The moment the
+/// run becomes invalid its fate is sealed — every byte, past and future,
+/// decodes to exactly one U+FFFD — so an invalid run streams replacement
+/// characters live rather than freezing the stream, and buffers nothing.
+struct ByteFallbackRun {
+ private var bytes: [UInt8] = []
+ private var poisoned = false
+ /// Continuation bytes still owed by the current lead, and the allowed
+ /// range for the next one (RFC 3629 constrains the first continuation
+ /// after E0/ED/F0/F4 leads).
+ private var pendingContinuations = 0
+ private var nextContinuation: ClosedRange<UInt8> = 0x80...0xBF
+
+ /// Text this byte contributes to the stream: `""` while the run is valid
+ /// so far, replacement characters once it can no longer become valid.
+ mutating func push(_ byte: UInt8) -> String {
+ if poisoned { return "\u{FFFD}" }
+ bytes.append(byte)
+ if accept(byte) { return "" }
+ poisoned = true
+ defer { bytes.removeAll(keepingCapacity: true) }
+ return String(repeating: "\u{FFFD}", count: bytes.count)
+ }
+
+ /// Close the run: a non-byte token follows, or the stream ends.
+ mutating func commit() -> String {
+ defer {
+ bytes.removeAll(keepingCapacity: true)
+ poisoned = false
+ pendingContinuations = 0
+ nextContinuation = 0x80...0xBF
+ }
+ guard !poisoned, !bytes.isEmpty else { return "" }
+ return String(bytes: bytes, encoding: .utf8)
+ ?? String(repeating: "\u{FFFD}", count: bytes.count)
+ }
+
+ /// Advance the incremental UTF-8 validator. `false` means no suffix can
+ /// ever make the run valid again.
+ private mutating func accept(_ byte: UInt8) -> Bool {
+ if pendingContinuations > 0 {
+ guard nextContinuation.contains(byte) else { return false }
+ pendingContinuations -= 1
+ nextContinuation = 0x80...0xBF
+ return true
+ }
+ switch byte {
+ case 0x00...0x7F: break
+ case 0xC2...0xDF: pendingContinuations = 1
+ case 0xE0: pendingContinuations = 2; nextContinuation = 0xA0...0xBF
+ case 0xE1...0xEC, 0xEE, 0xEF: pendingContinuations = 2
+ case 0xED: pendingContinuations = 2; nextContinuation = 0x80...0x9F
+ case 0xF0: pendingContinuations = 3; nextContinuation = 0x90...0xBF
+ case 0xF1...0xF3: pendingContinuations = 3
+ case 0xF4: pendingContinuations = 3; nextContinuation = 0x80...0x8F
+ default: return false // stray continuation, overlong lead, or > U+10FFFF
+ }
+ return true
+ }
+}
diff --git a/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift b/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift
index 6c17d6c6..d3ea19e8 100644
--- a/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift
+++ b/Sources/TurboFieldfare/Tokenization/StructuredAssistantDecoder.swift
@@ -33,14 +33,32 @@ public final class StructuredAssistantDecoder: @unchecked Sendable {
public func consume(tokenID: Int32, delta: String) throws -> [StructuredAssistantEvent] {
guard !failed else { throw GemmaToolCallParserError.malformed }
+
+ // A non-empty delta on a control token is text the detokenizer held
+ // back from BEFORE the token (a skipped special contributes nothing of
+ // its own), so it belongs to the channel state in effect now — route
+ // it before the token changes that state. Inside a tool call the held
+ // bytes are part of the payload, which is re-decoded from its IDs at
+ // toolCallEnd, so nothing is lost by not routing there.
+ let isControl = tokenID == tokenizer.channelStartID
+ || tokenID == tokenizer.channelEndID
+ || tokenID == tokenizer.toolCallStartID
+ || tokenID == tokenizer.toolCallEndID
+ || tokenID == tokenizer.toolResponseID
+ || tokenID == tokenizer.toolResponseEndID
+ var events: [StructuredAssistantEvent] = []
+ if isControl, !delta.isEmpty, toolTokens == nil {
+ events = routeText(delta)
+ }
+
if tokenID == tokenizer.channelStartID {
label = ""
channel = .label
- return []
+ return events
}
if tokenID == tokenizer.channelEndID {
channel = .visible
- return []
+ return events
}
if tokenID == tokenizer.toolCallStartID {
guard toolTokens == nil else {
@@ -48,7 +66,7 @@ public final class StructuredAssistantDecoder: @unchecked Sendable {
throw GemmaToolCallParserError.malformed
}
toolTokens = []
- return []
+ return events
}
if tokenID == tokenizer.toolCallEndID {
guard let tokens = toolTokens else {
@@ -61,7 +79,7 @@ public final class StructuredAssistantDecoder: @unchecked Sendable {
let call = try GemmaToolCallParser().parse(
text, allowedTools: allowedTools, id: idGenerator())
emittedCalls += 1
- return [.toolCall(call)]
+ return events + [.toolCall(call)]
} catch {
failed = true
throw error
@@ -72,7 +90,7 @@ public final class StructuredAssistantDecoder: @unchecked Sendable {
failed = true
throw GemmaToolCallParserError.malformed
}
- return []
+ return events
}
if var tokens = toolTokens {
tokens.append(tokenID)
@@ -83,6 +101,20 @@ public final class StructuredAssistantDecoder: @unchecked Sendable {
toolTokens = tokens
return []
}
+ return routeText(delta)
+ }
+
+ /// Route text flushed at a stop boundary through the current channel
+ /// state. The flush tail is not tied to a token ID, so it cannot go
+ /// through `consume`; without this a generation cut off inside the
+ /// thought channel would leak its held-back bytes into visible content.
+ public func consumeTail(_ text: String) throws -> [StructuredAssistantEvent] {
+ guard !failed else { throw GemmaToolCallParserError.malformed }
+ guard toolTokens == nil, !text.isEmpty else { return [] }
+ return routeText(text)
+ }
+
+ private func routeText(_ delta: String) -> [StructuredAssistantEvent] {
switch channel {
case .thought:
return []
diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
index 045d3064..ac845f26 100644
--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
@@ -1,10 +1,14 @@
import Foundation
+import Hub
import Tokenizers
public enum GFTokenizerError: Error, CustomStringConvertible {
case missingSpecialToken(String)
case invalidChatTemplate(String)
case missingToolTemplate
+ case missingTokenizerConfig
+ case unsupportedDecoder(actual: String)
+ case invalidTokenID(token: String, id: Int)
public var description: String {
switch self {
@@ -12,6 +16,13 @@ public enum GFTokenizerError: Error, CustomStringConvertible {
case .invalidChatTemplate(let detail): return "invalid chat messages: \(detail)"
case .missingToolTemplate:
return "installed tokenizer is missing chat_template.jinja; reinstall the model"
+ case .missingTokenizerConfig:
+ return "tokenizer_config.json is missing or unreadable"
+ case .unsupportedDecoder(let actual):
+ return "tokenizer decoder is not the pinned Gemma 4 sequence "
+ + "Sequence[Replace(▁→␣), ByteFallback, Fuse]; found: \(actual)"
+ case .invalidTokenID(let token, let id):
+ return "tokenizer declares out-of-range ID \(id) for token \(token)"
}
}
}
@@ -44,6 +55,18 @@ public struct GFTokenizer: @unchecked Sendable {
public let channelEndID: Int32
public let stopTokenIDs: Set<Int32>
public let vocabSize: Int
+ /// The channel/tool markers that structure assistant output. Streaming
+ /// treats them as detokenizer barriers: a byte-fallback run must not span
+ /// one, or its text would surface after the marker and be routed under the
+ /// wrong channel state.
+ public var structuralMarkerIDs: Set<Int32> {
+ [toolCallStartID, toolCallEndID, toolResponseID, toolResponseEndID,
+ channelStartID, channelEndID]
+ }
+ /// IDs that `decode(skipSpecialTokens: true)` strips — the
+ /// `added_tokens[special == true]` set from `tokenizer.json`, identical to
+ /// the filter the library's own decode applies before its decoder chain.
+ let specialTokenIDs: Set<Int32>
@usableFromInline
let tokenizer: any Tokenizer
@@ -82,21 +105,99 @@ public struct GFTokenizer: @unchecked Sendable {
}
static func loadUncached(pretrained modelID: String = Self.modelID) async throws -> GFTokenizer {
- let underlying = try await AutoTokenizer.from(pretrained: modelID)
- return try GFTokenizer(tokenizer: underlying)
+ try await make(from: LanguageModelConfigurationFromHub(modelName: modelID))
}
static func loadUncached(from folder: URL) async throws -> GFTokenizer {
- let underlying = try await AutoTokenizer.from(modelFolder: folder)
- return try GFTokenizer(tokenizer: underlying)
+ try await make(from: LanguageModelConfigurationFromHub(modelFolder: folder))
+ }
+
+ /// Build from the raw tokenizer configs so the decoder pipeline and the
+ /// special-token set can be validated against `tokenizer.json` itself.
+ /// Same fetch/caching path `AutoTokenizer.from(pretrained:)` uses internally.
+ private static func make(from hub: LanguageModelConfigurationFromHub) async throws -> GFTokenizer {
+ guard let tokenizerConfig = try await hub.tokenizerConfig else {
+ throw GFTokenizerError.missingTokenizerConfig
+ }
+ let tokenizerData = try await hub.tokenizerData
+ let underlying = try AutoTokenizer.from(
+ tokenizerConfig: tokenizerConfig, tokenizerData: tokenizerData)
+ return try GFTokenizer(tokenizer: underlying, tokenizerData: tokenizerData)
}
private static func hasTokenizerJSON(in folder: URL, fileManager: FileManager) -> Bool {
fileManager.fileExists(atPath: folder.appendingPathComponent("tokenizer.json").path)
}
- public init(tokenizer: any Tokenizer) throws {
+ /// Reject a tokenizer whose declared decoder is not the pinned Gemma 4
+ /// sequence.
+ ///
+ /// `GemmaDecoding` reproduces `Sequence[Replace("▁" -> " "), ByteFallback,
+ /// Fuse]` rather than calling `Tokenizers.decode`, so that decode stays
+ /// lossless and per-token (see `GemmaDecoding`). The installed tokenizer is
+ /// pinned and hash-validated, but `TURBO_FIELDFARE_TOKENIZER_DIR` can point
+ /// at any directory. Without this check a tokenizer declaring a different
+ /// decoder would decode subtly wrong text instead of failing.
+ ///
+ /// The check reads `tokenizer.json`'s decoder declaration structurally, so
+ /// it rejects any foreign decoder — including one whose behavior happens to
+ /// coincide on a handful of probe strings — without asserting the library's
+ /// exact runtime output, which a benign dependency bump may change.
+ /// Behavioral agreement with the library is pinned by the differential
+ /// tests instead.
+ static func verifyDecoderConfiguration(_ tokenizerData: Config) throws {
+ let decoder = tokenizerData["decoder"]
+ let steps = decoder.decoders.array(or: [])
+ guard decoder.type.string() == "Sequence",
+ steps.count == 3,
+ steps[0].type.string() == "Replace",
+ steps[0].pattern.String.string() == "▁",
+ steps[0].content.string() == " ",
+ steps[1].type.string() == "ByteFallback",
+ steps[2].type.string() == "Fuse"
+ else {
+ throw GFTokenizerError.unsupportedDecoder(actual: decoder.description)
+ }
+ }
+
+ /// Resolve a special token to its ID, rejecting `<unk>` substitution.
+ ///
+ /// BPE's `convertTokenToId` returns the unknown-token ID — not `nil` — for
+ /// a token absent from the vocab, so a plain `guard let` never fires and a
+ /// missing marker would silently bind to `<unk>`, colliding with every
+ /// other missing marker. The round-trip through `convertIdToToken` detects
+ /// any substitution.
+ static func requireTokenID(_ tokenizer: any Tokenizer, _ token: String) throws -> Int32 {
+ guard let id = tokenizer.convertTokenToId(token),
+ tokenizer.convertIdToToken(id) == token else {
+ throw GFTokenizerError.missingSpecialToken(token)
+ }
+ return try int32ID(token, id)
+ }
+
+ /// Config-supplied IDs are full-range `Int`; a trapping `Int32(_:)` would
+ /// crash on a corrupt tokenizer instead of taking the typed error path
+ /// every other malformed-config case uses.
+ private static func int32ID(_ token: String, _ id: Int) throws -> Int32 {
+ guard let value = Int32(exactly: id) else {
+ throw GFTokenizerError.invalidTokenID(token: token, id: id)
+ }
+ return value
+ }
+
+ public init(tokenizer: any Tokenizer, tokenizerData: Config) throws {
self.tokenizer = tokenizer
+ try Self.verifyDecoderConfiguration(tokenizerData)
+
+ // The same `added_tokens[special == true]` ID set the library's
+ // `decode(skipSpecialTokens: true)` filters before running its decoder.
+ var specials: Set<Int32> = []
+ for added in tokenizerData["addedTokens"].array(or: []) {
+ guard added["special"].boolean(or: false),
+ let id = added["id"].integer() else { continue }
+ try specials.insert(Self.int32ID(added.content.string() ?? "added token", id))
+ }
+ self.specialTokenIDs = specials
guard let bos = tokenizer.bosTokenId else {
throw GFTokenizerError.missingSpecialToken("<bos>")
@@ -104,33 +205,16 @@ public struct GFTokenizer: @unchecked Sendable {
guard let eos = tokenizer.eosTokenId else {
throw GFTokenizerError.missingSpecialToken("<eos>")
}
- guard let pad = tokenizer.convertTokenToId("<pad>") else {
- throw GFTokenizerError.missingSpecialToken("<pad>")
- }
- guard let eot = tokenizer.convertTokenToId("<turn|>") else {
- throw GFTokenizerError.missingSpecialToken("<turn|>")
- }
- guard let toolResponse = tokenizer.convertTokenToId("<|tool_response>") else {
- throw GFTokenizerError.missingSpecialToken("<|tool_response>")
- }
- guard let toolCallStart = tokenizer.convertTokenToId("<|tool_call>"),
- let toolCallEnd = tokenizer.convertTokenToId("<tool_call|>"),
- let toolResponseEnd = tokenizer.convertTokenToId("<tool_response|>"),
- let channelStart = tokenizer.convertTokenToId("<|channel>"),
- let channelEnd = tokenizer.convertTokenToId("<channel|>") else {
- throw GFTokenizerError.missingSpecialToken("Gemma tool/channel markers")
- }
-
- self.bosID = Int32(bos)
- self.eosID = Int32(eos)
- self.padID = Int32(pad)
- self.endOfTurnID = Int32(eot)
- self.toolCallStartID = Int32(toolCallStart)
- self.toolCallEndID = Int32(toolCallEnd)
- self.toolResponseID = Int32(toolResponse)
- self.toolResponseEndID = Int32(toolResponseEnd)
- self.channelStartID = Int32(channelStart)
- self.channelEndID = Int32(channelEnd)
+ self.bosID = try Self.int32ID("<bos>", bos)
+ self.eosID = try Self.int32ID("<eos>", eos)
+ self.padID = try Self.requireTokenID(tokenizer, "<pad>")
+ self.endOfTurnID = try Self.requireTokenID(tokenizer, "<turn|>")
+ self.toolCallStartID = try Self.requireTokenID(tokenizer, "<|tool_call>")
+ self.toolCallEndID = try Self.requireTokenID(tokenizer, "<tool_call|>")
+ self.toolResponseID = try Self.requireTokenID(tokenizer, "<|tool_response>")
+ self.toolResponseEndID = try Self.requireTokenID(tokenizer, "<tool_response|>")
+ self.channelStartID = try Self.requireTokenID(tokenizer, "<|channel>")
+ self.channelEndID = try Self.requireTokenID(tokenizer, "<channel|>")
self.stopTokenIDs = [self.eosID, self.endOfTurnID, self.toolResponseID]
self.vocabSize = 262_144
}
@@ -147,8 +231,20 @@ public struct GFTokenizer: @unchecked Sendable {
}
/// Decode token IDs to text. `skipSpecialTokens` strips BOS/EOS/turn markers from the output.
+ ///
+ /// Runs the pinned Gemma decoder sequence directly (see `GemmaDecoding`)
+ /// rather than `Tokenizers.decode`, whose trailing
+ /// `clean_up_tokenization_spaces` pass defaults to on for this tokenizer and
+ /// rewrites model output (`"he said ' ok ' now"` -> `"he said'ok'now"`),
+ /// breaking `decode(encode(x)) == x`. Batch decode is a push-loop over
+ /// `GFDetokenizer`, so batch and streaming decode agree by construction.
public func decode(_ ids: [Int32], skipSpecialTokens: Bool = true) -> String {
- tokenizer.decode(tokens: ids.map(Int.init), skipSpecialTokens: skipSpecialTokens)
+ var detok = GFDetokenizer(tokenizer: self, skipSpecialTokens: skipSpecialTokens)
+ var text = ""
+ for id in ids {
+ text += detok.push(id)
+ }
+ return text + detok.flush()
}
// MARK: - Chat template
diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swift
index d141c275..6277dc99 100644
--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift
@@ -548,15 +548,7 @@ public actor ServerModelSession: ServerInferenceBackend {
shouldStop: { shouldStop }) { progress in
guard decodingError == nil else { return }
do {
- switch progress {
- case .prefill:
- break
- case .token(_, let tokenID, let delta):
- let events = if let decoder {
- try decoder.consume(tokenID: tokenID, delta: delta)
- } else {
- delta.isEmpty ? [] : [StructuredAssistantEvent.content(delta)]
- }
+ func handle(_ events: [StructuredAssistantEvent]) {
for event in events {
switch event {
case .content(let text):
@@ -571,12 +563,28 @@ public actor ServerModelSession: ServerInferenceBackend {
onEvent(.toolCall(call))
}
}
+ }
+ switch progress {
+ case .prefill:
+ break
+ case .token(_, let tokenID, let delta):
+ let events = if let decoder {
+ try decoder.consume(tokenID: tokenID, delta: delta)
+ } else {
+ delta.isEmpty ? [] : [StructuredAssistantEvent.content(delta)]
+ }
+ handle(events)
case .tail(let text):
- let visible = stopMatcher.push(text)
- if !visible.isEmpty {
- content += visible
- onEvent(.content(visible))
+ // The flush tail is not tied to a token ID, so it must
+ // go through the decoder's channel state explicitly;
+ // appending it directly would leak text held back
+ // inside the thought channel or a tool call.
+ let events = if let decoder {
+ try decoder.consumeTail(text)
+ } else {
+ text.isEmpty ? [] : [StructuredAssistantEvent.content(text)]
}
+ handle(events)
}
} catch {
decodingError = error
diff --git a/Tests/TurboFieldfare/Core/Tokenization/DecoderConfigTests.swift b/Tests/TurboFieldfare/Core/Tokenization/DecoderConfigTests.swift
new file mode 100644
index 00000000..9692df29
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Tokenization/DecoderConfigTests.swift
@@ -0,0 +1,69 @@
+import Hub
+import Testing
+@testable import TurboFieldfare
+
+/// Structural verification of `tokenizer.json` decoder declarations, driven by
+/// `Config` literals — no network and no tokenizer fixture required.
+@Suite("Decoder configuration")
+struct DecoderConfigTests {
+ private static func data(decoder: Config) -> Config {
+ ["decoder": decoder]
+ }
+
+ private static let pinned: Config = [
+ "type": "Sequence",
+ "decoders": [
+ ["type": "Replace", "pattern": ["String": "▁"], "content": " "],
+ ["type": "ByteFallback"],
+ ["type": "Fuse"],
+ ],
+ ]
+
+ @Test("Pinned Gemma decoder sequence passes")
+ func pinnedSequencePasses() throws {
+ try GFTokenizer.verifyDecoderConfiguration(Self.data(decoder: Self.pinned))
+ }
+
+ @Test("A non-Sequence decoder is rejected")
+ func nonSequenceRejected() {
+ #expect(throws: GFTokenizerError.self) {
+ try GFTokenizer.verifyDecoderConfiguration(Self.data(decoder: [
+ "type": "Metaspace", "replacement": "▁", "prependScheme": "first",
+ ]))
+ }
+ }
+
+ @Test("A sequence missing Fuse is rejected")
+ func missingFuseRejected() {
+ #expect(throws: GFTokenizerError.self) {
+ try GFTokenizer.verifyDecoderConfiguration(Self.data(decoder: [
+ "type": "Sequence",
+ "decoders": [
+ ["type": "Replace", "pattern": ["String": "▁"], "content": " "],
+ ["type": "ByteFallback"],
+ ],
+ ]))
+ }
+ }
+
+ @Test("A Replace step with a different pattern is rejected")
+ func differentReplacePatternRejected() {
+ #expect(throws: GFTokenizerError.self) {
+ try GFTokenizer.verifyDecoderConfiguration(Self.data(decoder: [
+ "type": "Sequence",
+ "decoders": [
+ ["type": "Replace", "pattern": ["String": "_"], "content": " "],
+ ["type": "ByteFallback"],
+ ["type": "Fuse"],
+ ],
+ ]))
+ }
+ }
+
+ @Test("A missing decoder declaration is rejected")
+ func missingDecoderRejected() {
+ #expect(throws: GFTokenizerError.self) {
+ try GFTokenizer.verifyDecoderConfiguration(["model": ["type": "BPE"]])
+ }
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
index df4e9379..8fb29152 100644
--- a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
@@ -1,4 +1,5 @@
import Foundation
+import Hub
import Testing
@testable import TurboFieldfare
@@ -32,6 +33,77 @@ struct TokenizerTests {
#expect(tok.stopTokenIDs.count == 3)
}
+ @Test("convertTokenToId substitutes unk for absent tokens")
+ func convertTokenToIdSubstitutesUnk() {
+ // Pins the library behavior `requireTokenID` exists for: BPE resolves an
+ // absent token to the unknown-token ID, never nil, so a plain `guard
+ // let` cannot detect a missing special marker.
+ let id = tok.tokenizer.convertTokenToId("<no-such-token-xyzzy>")
+ #expect(id != nil)
+ #expect(id == tok.tokenizer.unknownTokenId)
+ }
+
+ @Test("Marker resolution rejects unk substitution")
+ func markerResolutionRejectsUnk() throws {
+ #expect(throws: GFTokenizerError.self) {
+ _ = try GFTokenizer.requireTokenID(tok.tokenizer, "<no-such-token-xyzzy>")
+ }
+ let pad = try GFTokenizer.requireTokenID(tok.tokenizer, "<pad>")
+ #expect(pad == tok.padID)
+ }
+
+ @Test("Special-token ID set matches the library's skip filter")
+ func specialTokenSetMatchesLibrary() {
+ // The config-derived set must reproduce the semantics the old runtime
+ // probe encoded: a special token decodes to nothing when skipped and to
+ // its literal text when kept.
+ var probes = randomIDs(count: 64, seed: 0xDEAD_BEEF_CAFE_F00D)
+ probes += [tok.bosID, tok.eosID, tok.padID, tok.endOfTurnID,
+ tok.toolCallStartID, tok.toolCallEndID, tok.toolResponseID,
+ tok.toolResponseEndID, tok.channelStartID, tok.channelEndID]
+ for id in probes {
+ let skipped = tok.tokenizer.decode(tokens: [Int(id)], skipSpecialTokens: true)
+ let kept = tok.tokenizer.decode(tokens: [Int(id)], skipSpecialTokens: false)
+ let librarySpecial = skipped.isEmpty && !kept.isEmpty
+ #expect(tok.specialTokenIDs.contains(id) == librarySpecial,
+ "id \(id) special-set membership diverged from library semantics")
+ }
+ }
+
+ @Test("Out-of-range added-token IDs are rejected, not trapped")
+ func outOfRangeAddedTokenIDRejected() {
+ // Config.integer() returns full-range Int; a trapping Int32(_:) on a
+ // corrupt tokenizer.json would crash at load instead of throwing.
+ let data: Config = [
+ "decoder": [
+ "type": "Sequence",
+ "decoders": [
+ ["type": "Replace", "pattern": ["String": "▁"], "content": " "],
+ ["type": "ByteFallback"],
+ ["type": "Fuse"],
+ ],
+ ],
+ "added_tokens": [
+ ["id": 3_000_000_000, "content": "<huge>", "special": true],
+ ],
+ ]
+ #expect(throws: GFTokenizerError.self) {
+ _ = try GFTokenizer(tokenizer: tok.tokenizer, tokenizerData: data)
+ }
+ }
+
+ @Test("Library fuses a split codepoint across byte-fallback tokens")
+ func libraryFusesSplitCodepoint() throws {
+ // The behavioral half of the old init-time decoder probe, kept as a
+ // test: the library remains the oracle for the pinned chain's
+ // ByteFallback/Fuse behavior. The run needs a trailing non-byte token
+ // because the library drops trailing byte runs (issue #58).
+ let ids = try ["<0xC3>", "<0xA9>", "the"].map {
+ Int(try GFTokenizer.requireTokenID(tok.tokenizer, $0))
+ }
+ #expect(tok.tokenizer.decode(tokens: ids, skipSpecialTokens: false) == "éthe")
+ }
+
// MARK: - Encode / decode
@Test("Round-trip ASCII", arguments: [
@@ -45,6 +117,21 @@ struct TokenizerTests {
#expect(tok.decode(ids) == text)
}
+ @Test("Decode keeps spaces before punctuation", arguments: [
+ "step 1 . done",
+ "x , y",
+ "he said ' ok ' now",
+ "a . b",
+ "wait ! really ?",
+ ])
+ func decodePreservesSpacingBeforePunctuation(_ text: String) {
+ // HF's clean_up_tokenization_spaces collapsed these ("he said ' ok ' now"
+ // became "he said'ok'now"), which broke decode(encode(x)) == x for a
+ // tokenizer that is lossless by construction.
+ let ids = tok.encode(text, addBOS: false)
+ #expect(tok.decode(ids) == text)
+ }
+
@Test("Round-trip multi-byte UTF-8", arguments: [
"你好,世界。",
"漢字",
@@ -122,34 +209,232 @@ struct TokenizerTests {
#expect(!tail.unicodeScalars.contains("\u{FFFD}"))
}
- @Test("Streaming delta preserves graphemes extended by later scalars")
- func streamingExtendedGraphemes() {
- let cases = [
- ("ห", "ห้าม", "้าม"),
- ("e", "e\u{301}", "\u{301}"),
- ("ا", "ا\u{64E}", "\u{64E}"),
- ("ש", "ש\u{5B8}", "\u{5B8}"),
- ("क", "क्ष", "्ष"),
- ("\u{1100}", "\u{1100}\u{1161}", "\u{1161}"),
- ("\u{263A}", "\u{263A}\u{FE0F}", "\u{FE0F}"),
- ("\u{1F44D}", "\u{1F44D}\u{1F3FD}", "\u{1F3FD}"),
- ("1", "1\u{FE0F}\u{20E3}", "\u{FE0F}\u{20E3}"),
- ("\u{1F1EC}", "\u{1F1EC}\u{1F1E7}", "\u{1F1E7}"),
- ("\u{1F469}", "\u{1F469}\u{200D}\u{1F4BB}", "\u{200D}\u{1F4BB}"),
- ]
- for (prefix, current, expectedDelta) in cases {
+ @Test("Streaming reassembles graphemes extended by later scalars", arguments: [
+ "ห้าม",
+ "e\u{301}",
+ "ا\u{64E}",
+ "ש\u{5B8}",
+ "क्ष",
+ "\u{1100}\u{1161}",
+ "\u{263A}\u{FE0F}",
+ "\u{1F44D}\u{1F3FD}",
+ "1\u{FE0F}\u{20E3}",
+ "\u{1F1EC}\u{1F1E7}",
+ "\u{1F469}\u{200D}\u{1F4BB}",
+ ])
+ func streamingExtendedGraphemes(_ text: String) {
+ assertStreams(text)
+ }
+
+ @Test("Whitespace run before punctuation survives streaming")
+ func streamingWhitespaceThenPunctuation() {
+ // Encoder-unreachable but generator-reachable: the normalizer maps " " to
+ // "▁", so no encode() call produces a bare whitespace run followed by
+ // punctuation. A generating model emits it freely — in indented markdown
+ // and in code. HF's clean_up_tokenization_spaces rewrote " ." to "."
+ // across that boundary, which made the streaming delta drop the
+ // punctuation token entirely and silently.
+ for (run, mark) in [("▁▁▁▁", "."), ("▁▁", ","), ("▁▁▁▁", "?"), ("▁▁", "!")] {
+ guard let runID = tok.tokenizer.convertTokenToId(run),
+ let markID = tok.tokenizer.convertTokenToId(mark) else {
+ Issue.record("vocabulary is missing \(run) or \(mark)")
+ continue
+ }
+ let ids = [Int32(runID), Int32(markID)]
var detok = GFDetokenizer(tokenizer: tok)
- #expect(detok.commitDelta(prefix) == prefix)
- #expect(detok.commitDelta(current) == expectedDelta)
+ var assembled = ""
+ for id in ids { assembled += detok.push(id) }
+ assembled += detok.flush()
+
+ #expect(assembled == tok.decode(ids))
+ #expect(assembled == String(repeating: " ", count: run.count) + mark,
+ "expected the whitespace run and '\(mark)' intact, got '\(assembled)'")
+ }
+ }
+
+ @Test("Decode differs from the library only by its cleanup pass")
+ func decodeDiffersFromLibraryOnlyByCleanup() {
+ // The streaming test below compares against our own batch decode, so it
+ // cannot catch a fault shared by both. This one keeps swift-transformers
+ // as an independent oracle: our decode, run through the cleanup pass we
+ // deliberately dropped, must reproduce the library byte for byte. That
+ // pins the intended differences and covers special-token filtering,
+ // byte-fallback grouping, and the "▁" mapping. Besides the cleanup
+ // pass, we intentionally diverge from the Swift port on byte-fallback
+ // runs — invalid runs decode to one U+FFFD per byte and trailing runs
+ // are flushed, both per the reference Rust decoder, where the port
+ // decodes leniently and drops trailing runs (issue #58). The fixed
+ // seeds produce no multi-byte-token runs, so those divergences do not
+ // reach this comparison; the byte-soup test covers them against a
+ // reference-semantics oracle.
+ var ids = randomIDs(count: 256, seed: 0x2545_F491_4F6C_DD1D)
+ ids += [tok.bosID, tok.eosID, tok.endOfTurnID, tok.channelStartID, tok.padID]
+ // The library drops byte-fallback tokens that end a sequence (issue #58)
+ // while we assemble them, so the two only agree when a regular token
+ // closes the stream. End on one rather than depend on where the random
+ // IDs happen to land.
+ if let trailing = tok.tokenizer.convertTokenToId("the") {
+ ids.append(Int32(trailing))
+ }
+ for skipSpecialTokens in [true, false] {
+ let mine = tok.decode(ids, skipSpecialTokens: skipSpecialTokens)
+ let library = tok.tokenizer.decode(tokens: ids.map(Int.init),
+ skipSpecialTokens: skipSpecialTokens)
+ #expect(Self.huggingFaceCleanUp(mine) == library,
+ "decode diverged from the library beyond the cleanup pass (skipSpecialTokens: \(skipSpecialTokens))")
+ }
+ }
+
+ // MARK: - Byte-fallback runs
+
+ @Test("Byte run fuses across a skipped special token")
+ func byteRunFusesAcrossSkippedSpecial() throws {
+ // The library filters skipped special IDs before its decoder chain, so
+ // a byte run must fuse ACROSS a skipped special. In keep mode the
+ // special is an ordinary token and closes the run instead, leaving two
+ // single-byte runs that are invalid on their own - one U+FFFD each.
+ let ids: [Int32] = try [
+ tokenID("<0xC3>"), tok.eosID, tokenID("<0xA9>"), tokenID("the"),
+ ]
+ #expect(tok.decode(ids, skipSpecialTokens: true) == "éthe")
+ var detok = GFDetokenizer(tokenizer: tok)
+ var assembled = ""
+ for id in ids { assembled += detok.push(id) }
+ assembled += detok.flush()
+ #expect(assembled == "éthe")
+ #expect(tok.decode(ids, skipSpecialTokens: false) == "\u{FFFD}<eos>\u{FFFD}the")
+ }
+
+ @Test("Invalid byte runs stream replacement characters immediately")
+ func invalidByteRunsStreamImmediately() throws {
+ // Once a run can no longer become valid UTF-8, every byte - past and
+ // future - decodes to exactly one U+FFFD, so the stream emits them
+ // live instead of freezing and buffering until the next regular token.
+ var detok = GFDetokenizer(tokenizer: tok)
+ let stray = try tokenID("<0x80>")
+ for _ in 0..<64 {
+ #expect(detok.push(stray) == "\u{FFFD}")
+ }
+ #expect(detok.flush() == "")
+
+ detok = GFDetokenizer(tokenizer: tok)
+ #expect(try detok.push(tokenID("<0xC3>")) == "")
+ #expect(try detok.push(tokenID("<0xFF>")) == "\u{FFFD}\u{FFFD}")
+
+ // E0's first continuation is constrained to A0-BF, so 0x80 poisons the
+ // run even though it is a continuation byte.
+ detok = GFDetokenizer(tokenizer: tok)
+ #expect(try detok.push(tokenID("<0xE0>")) == "")
+ #expect(try detok.push(tokenID("<0x80>")) == "\u{FFFD}\u{FFFD}")
+ }
+
+ @Test("An incomplete trailing sequence invalidates the whole run")
+ func incompleteTailInvalidatesWholeRun() throws {
+ // The reference decoder validates the run as a whole, so an incomplete
+ // tail turns even a valid prefix into per-byte replacement characters.
+ var detok = GFDetokenizer(tokenizer: tok)
+ #expect(try detok.push(tokenID("<0xE2>")) == "")
+ #expect(try detok.push(tokenID("<0x82>")) == "")
+ #expect(detok.flush() == "\u{FFFD}\u{FFFD}")
+
+ detok = GFDetokenizer(tokenizer: tok)
+ for token in ["<0xC3>", "<0xA9>", "<0xE2>", "<0x82>"] {
+ #expect(try detok.push(tokenID(token)) == "")
}
+ #expect(detok.flush() == String(repeating: "\u{FFFD}", count: 4))
}
- @Test("Streaming delta resynchronizes after a rewritten prefix")
- func streamingPrefixResync() {
+ @Test("A valid byte run commits with the token that closes it")
+ func validByteRunCommitsAtBoundary() throws {
var detok = GFDetokenizer(tokenizer: tok)
- #expect(detok.commitDelta("abc") == "abc")
- #expect(detok.commitDelta("ax") == "")
- #expect(detok.commitDelta("axy") == "y")
+ for token in ["<0xF0>", "<0x9F>", "<0x98>", "<0x80>"] {
+ #expect(try detok.push(tokenID(token)) == "")
+ }
+ #expect(try detok.push(tokenID("the")) == "😀the")
+ }
+
+ @Test("A barrier marker commits the run as its own delta")
+ func barrierMarkerCommitsHeldRun() throws {
+ // The generation pipeline must not let a byte run span a channel/tool
+ // marker: the held text surfaces as the marker's own delta, so the
+ // structured decoder can route it under the pre-switch channel state.
+ var detok = GFDetokenizer(tokenizer: tok,
+ barrierTokenIDs: tok.structuralMarkerIDs)
+ for token in ["<0xF0>", "<0x9F>", "<0x98>", "<0x80>"] {
+ #expect(try detok.push(tokenID(token)) == "")
+ }
+ #expect(detok.push(tok.channelEndID) == "😀")
+ // Non-barrier specials still fuse: a codepoint split around eos stays
+ // whole, preserving decode parity for everything but the markers.
+ #expect(try detok.push(tokenID("<0xC3>")) == "")
+ #expect(detok.push(tok.eosID) == "")
+ #expect(try detok.push(tokenID("<0xA9>")) == "")
+ #expect(try detok.push(tokenID("the")) == "éthe")
+ }
+
+ @Test("Byte-token soup matches batch decode and reference run semantics")
+ func byteSoupMatchesReference() throws {
+ // Adversarial byte-run coverage the encoder can never produce: mostly
+ // byte tokens with occasional regular tokens, checked against a direct
+ // reimplementation of the reference decoder's run semantics
+ // (from_utf8, else one U+FFFD per byte) and against our own streaming.
+ let byteIDs: [Int32] = try (0...255).map {
+ try tokenID(String(format: "<0x%02X>", $0))
+ }
+ let theID = try tokenID("the")
+ var state: UInt64 = 0xA076_1D64_78BD_642F
+ func next() -> UInt64 {
+ state ^= state << 13
+ state ^= state >> 7
+ state ^= state << 17
+ return state
+ }
+ for round in 0..<16 {
+ var ids: [Int32] = []
+ var expected = ""
+ var run: [UInt8] = []
+ func closeRun() {
+ guard !run.isEmpty else { return }
+ expected += String(bytes: run, encoding: .utf8)
+ ?? String(repeating: "\u{FFFD}", count: run.count)
+ run.removeAll()
+ }
+ for _ in 0..<256 {
+ let r = next()
+ if r % 8 == 0 {
+ closeRun()
+ ids.append(theID)
+ expected += "the"
+ } else {
+ let byte = UInt8(truncatingIfNeeded: r >> 8)
+ ids.append(byteIDs[Int(byte)])
+ run.append(byte)
+ }
+ }
+ closeRun()
+
+ #expect(tok.decode(ids) == expected, "round \(round) batch diverged")
+ var detok = GFDetokenizer(tokenizer: tok)
+ var assembled = ""
+ for id in ids { assembled += detok.push(id) }
+ assembled += detok.flush()
+ #expect(assembled == expected, "round \(round) streaming diverged")
+ }
+ }
+
+ @Test("Streaming matches batch decode for arbitrary token streams")
+ func streamingMatchesBatchForArbitraryIDs() {
+ // Every other streaming test round-trips encode() output, which can only
+ // produce token sequences the encoder itself emits. A generating model is
+ // under no such constraint, so drive the detokenizer with raw IDs.
+ for round in 0..<16 {
+ let ids = randomIDs(count: 256, seed: 0x9E37_79B9_7F4A_7C15 &+ UInt64(round))
+ var detok = GFDetokenizer(tokenizer: tok)
+ var assembled = ""
+ for id in ids { assembled += detok.push(id) }
+ assembled += detok.flush()
+ #expect(assembled == tok.decode(ids), "round \(round) diverged from batch decode")
+ }
}
@Test("Streaming detokenizer matches full decode for complex Unicode", arguments: [
@@ -226,6 +511,35 @@ struct TokenizerTests {
// MARK: - Helpers
+ private func tokenID(_ token: String) throws -> Int32 {
+ try GFTokenizer.requireTokenID(tok.tokenizer, token)
+ }
+
+ /// Deterministic xorshift64 IDs — token streams the encoder cannot produce
+ /// but a generating model can.
+ private func randomIDs(count: Int, seed: UInt64) -> [Int32] {
+ var state = seed == 0 ? 0x9E37_79B9_7F4A_7C15 : seed
+ return (0..<count).map { _ in
+ state ^= state << 13
+ state ^= state >> 7
+ state ^= state << 17
+ return Int32(state % UInt64(tok.vocabSize))
+ }
+ }
+
+ /// swift-transformers' `clean_up_tokenization_spaces` pass, reproduced here
+ /// so the differential test can pin our only intended difference from the
+ /// library to exactly this pass. Not used in production — see `GemmaDecoding`.
+ private static func huggingFaceCleanUp(_ text: String) -> String {
+ let replacements = [
+ (" .", "."), (" ?", "?"), (" !", "!"), (" ,", ","), (" ' ", "'"),
+ (" n't", "n't"), (" 'm", "'m"), (" 's", "'s"), (" 've", "'ve"), (" 're", "'re"),
+ ]
+ return replacements.reduce(text) { partial, rule in
+ partial.replacingOccurrences(of: rule.0, with: rule.1)
+ }
+ }
+
private func assertStreams(_ target: String) {
let ids = tok.encode(target, addBOS: false)
var detok = GFDetokenizer(tokenizer: tok)
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index 11f07fcf..18a8b254 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -461,6 +461,82 @@ struct GemmaToolCallTests {
.content("visible"),
])
}
+
+ @Test func routesControlTokenDeltaThroughCurrentChannel() async throws {
+ // A non-empty delta on a control token is text the detokenizer held
+ // back from before that token; it belongs to the channel in effect
+ // now and must not vanish with the control token's early return.
+ let tokenizer = try await GFTokenizer.load()
+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])
+ #expect(try decoder.consume(tokenID: tokenizer.channelStartID, delta: "leftover") == [
+ .content("leftover"),
+ ])
+ // The channel switch still happened: this resolves the label.
+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "thought\n").isEmpty)
+ // In the thought channel the routed delta is correctly dropped.
+ #expect(try decoder.consume(tokenID: tokenizer.channelEndID, delta: "hidden").isEmpty)
+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "ok") == [.content("ok")])
+ }
+
+ @Test func tailDuringThoughtChannelIsSuppressed() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])
+ #expect(try decoder.consume(tokenID: tokenizer.channelStartID, delta: "").isEmpty)
+ #expect(try decoder.consume(tokenID: tokenizer.bosID, delta: "thought\n").isEmpty)
+ #expect(try decoder.consumeTail("secret").isEmpty)
+ #expect(try decoder.consume(tokenID: tokenizer.channelEndID, delta: "").isEmpty)
+ #expect(try decoder.consumeTail("ok") == [.content("ok")])
+ }
+
+ @Test func tailDuringUnresolvedLabelEmitsNothing() async throws {
+ // Generation ended before the channel label line completed; the text
+ // cannot be attributed, so nothing may surface.
+ let tokenizer = try await GFTokenizer.load()
+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])
+ #expect(try decoder.consume(tokenID: tokenizer.channelStartID, delta: "").isEmpty)
+ #expect(try decoder.consumeTail("final-but-no-newline").isEmpty)
+ }
+
+ @Test func heldBytesBeforeChannelMarkerStayInTheirChannel() async throws {
+ // Thought text ending in a byte-fallback character right before
+ // <channel|> must not leak into the visible answer. The barrier
+ // detokenizer commits the held character as the marker's delta, and
+ // consume routes it under the still-thought channel.
+ let tokenizer = try await GFTokenizer.load()
+ var detok = GFDetokenizer(tokenizer: tokenizer,
+ barrierTokenIDs: tokenizer.structuralMarkerIDs)
+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])
+ var events: [StructuredAssistantEvent] = []
+ func feed(_ id: Int32) throws {
+ events += try decoder.consume(tokenID: id, delta: detok.push(id))
+ }
+
+ try feed(tokenizer.channelStartID)
+ for id in tokenizer.encode("thought\n", addBOS: false) { try feed(id) }
+ for token in ["<0xF0>", "<0x9F>", "<0x98>", "<0x80>"] {
+ try feed(GFTokenizer.requireTokenID(tokenizer.tokenizer, token))
+ }
+ try feed(tokenizer.channelEndID)
+ for id in tokenizer.encode("ok", addBOS: false) { try feed(id) }
+ events += try decoder.consumeTail(detok.flush())
+
+ let visible = events.compactMap { event -> String? in
+ if case .content(let text) = event { return text }
+ return nil
+ }.joined()
+ #expect(visible == "ok", "thought-channel bytes leaked: '\(visible)'")
+ }
+
+ @Test func tailAfterFailureThrows() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let decoder = StructuredAssistantDecoder(tokenizer: tokenizer, allowedTools: [])
+ #expect(throws: GemmaToolCallParserError.self) {
+ try decoder.consume(tokenID: tokenizer.toolCallEndID, delta: "")
+ }
+ #expect(throws: GemmaToolCallParserError.self) {
+ try decoder.consumeTail("x")
+ }
+ }
}
@Suite("Streaming stop matcher")