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
14 changes: 8 additions & 6 deletions Libraries/MLXGuidedGeneration/GuidedGenerationLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import MLXLMCommon
///
/// When the grammar forces deterministic tokens (e.g. JSON structural
/// characters `{`, `}`, `,`, `:`), they're fed through the model one at
/// a time to update the KV cache. Each pass uses the optimized T_q=1
/// Metal kernel.
/// a time to update the KV cache, after the sampled token that preceded
/// them. Each pass uses the optimized T_q=1 Metal kernel.
///
/// The loop overlaps grammar mask computation (CPU) with the model forward
/// pass (GPU). After committing a token, the grammar state is ready for the
Expand Down Expand Up @@ -384,15 +384,17 @@ public enum GuidedGenerationLoop {

if shouldStopAfterFF { break }

// Process FF tokens one at a time to update KV cache.
// Feed the sampled token before its FF tokens, so later logits
// condition on the same tokens as the output.
// Batching (T_q > 1 with populated cache) triggers an MLX
// bug: scaledDotProductAttention in .causal mode creates a
// mask of shape (T_q, T_q) instead of (T_q, T_kv), causing
// a broadcast failure on models with global attention layers
// (e.g., Gemma 3). Single-token passes (T_q=1) use the
// optimized Metal kernel and skip the mask entirely.
for (i, ffToken) in ffTokens.enumerated() {
let tokenInput = LMInput.Text(tokens: MLXArray([ffToken]))
let fedTokens = [Int32(tokenId)] + ffTokens
for (i, fedToken) in fedTokens.enumerated() {
let tokenInput = LMInput.Text(tokens: MLXArray([fedToken]))
let result = model(
tokenInput[text: .newAxis],
cache: cacheStorage.cache.isEmpty ? nil : cacheStorage.cache,
Expand All @@ -401,7 +403,7 @@ public enum GuidedGenerationLoop {
cacheStorage.commitProcessedTokens(tokenInput.cacheSequenceLength)
modelState = result.state
// Only need logits from the last FF token
if i == ffTokens.count - 1 {
if i == fedTokens.count - 1 {
logits = result.logits
}
}
Expand Down
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ let package = Package(
"MLXGuidedGeneration",
"MLXLMCommon",
.product(name: "MLX", package: "mlx-swift"),
.product(name: "MLXNN", package: "mlx-swift"),
],
path: "Tests/MLXGuidedGenerationTests"
),
Expand Down
102 changes: 102 additions & 0 deletions Tests/MLXGuidedGenerationTests/GuidedForwardStateTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX
import MLXLMCommon
import MLXNN
import Testing

@testable import MLXGuidedGeneration

/// Byte-level tokenizer: token id = byte value, 255 = EOS.
private struct ByteTokenizer: MLXLMCommon.Tokenizer {
func encode(text: String, addSpecialTokens: Bool) -> [Int] { text.utf8.map(Int.init) }
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
String(bytes: tokenIds.filter { $0 != 255 }.map(UInt8.init), encoding: .utf8) ?? ""
}
func convertTokenToId(_ token: String) -> Int? {
if token == "<eos>" { return 255 }
return token.utf8.count == 1 ? token.utf8.first.map(Int.init) : nil
}
func convertIdToToken(_ id: Int) -> String? {
if id == 255 { return "<eos>" }
return id >= 0 && id < 255 ? String(UnicodeScalar(UInt8(id))) : nil
}
var bosToken: String? { nil }
var eosToken: String? { "<eos>" }
var unknownToken: String? { nil }
func applyChatTemplate(
messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
additionalContext: [String: any Sendable]?
) throws -> [Int] { [] }
}

private struct UnusedProcessor: UserInputProcessor {
func prepare(input: UserInput) async throws -> LMInput {
fatalError("the test supplies the prepared input")
}
}

/// Records every token it is fed. Its logits prefer EOS, so the grammar
/// decides the output.
private final class RecordingModel: Module, LanguageModel {
var forwarded: [Int] = []

func prepare(
_ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters
) throws -> PrepareResult { .tokens(input.text) }

func newCache(parameters: GenerateParameters?) throws -> [KVCache] { [] }

func callAsFunction(
_ input: LMInput.Text, cache: [KVCache]?, state: LMOutput.State?
) -> LMOutput {
let ids = input.tokens.flattened().asArray(Int32.self).map(Int.init)
forwarded += ids
var row = (0 ..< 256).map { -Float($0) / 1000 }
row[255] = 20
let rows = Array(repeating: row, count: ids.count).flatMap { $0 }
return LMOutput(logits: MLXArray(rows).reshaped(1, ids.count, 256))
}
}

@Suite(.serialized)
struct GuidedForwardStateTests {

/// The model must see exactly the prompt followed by every emitted token,
/// including a sampled token that the grammar follows with forced tokens.
@Test(arguments: [false, true])
func modelSeesEveryEmittedToken(fastForward: Bool) throws {
try Stream.withNewDefaultStream(device: .cpu) {
let tokenizer = ByteTokenizer()
let vocabulary = (0 ..< 256).map { String(format: "<0x%02X>", $0) }
let grammarTokenizer = try GrammarTokenizer(
vocab: vocabulary, vocabType: .byteFallback, eosTokenId: 255)
let grammar = #"root ::= "{\"key\":\"" ("A" | "B") "\"}""#
let constraint = try GrammarConstraint(
tokenizer: grammarTokenizer, grammar: grammar, fastForward: fastForward,
hostTokenizer: tokenizer)
let model = RecordingModel()
let context = ModelContext(
configuration: ModelConfiguration(id: "recording"), model: model,
processor: UnusedProcessor(), tokenizer: tokenizer)
let prompt: [Int32] = [1, 2, 3]
let sink = GuidedGenerationDiagnosticSink()
var output = ""
_ = try GuidedGenerationDiagnosticSink.$current.withValue(sink) {
try GuidedGenerationLoop.run(
input: LMInput(tokens: MLXArray(prompt)), context: context,
constraint: constraint, maxTokens: 64, vocabSize: 256
) {
output += $0
return true
}
}

#expect(output == #"{"key":"A"}"#)
#expect(sink.grammarTerminated)
#expect(sink.fastForwardTokenIDs.isEmpty != fastForward)
#expect(model.forwarded == prompt.map(Int.init) + output.utf8.map(Int.init))
}
}
}