Repository navigation
Add fixed-batch token and decoded generation streams #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ronaldmannak
wants to merge
16
commits into
codex/quantized-batch-kvcache
Choose a base branch
from
codex/batched-generation-streams
base: codex/quantized-batch-kvcache
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
a7d3c70
Add fixed-batch token and decoded generation streams
ronaldmannak e41b0d0
Complete cancelled batch rows when prefill throws
ronaldmannak 84a3adf
Handle main's steering event in the batch stream test helper
ronaldmannak 6e27b10
Merge PR 94 into PR 97
ronaldmannak 316cacd
Settle the batch on the stream captured at its start
ronaldmannak 058907f
Merge PR 94 into PR 97; drive the batch stream from iterator events
ronaldmannak 2eb1b49
Merge PR 94 into PR 97
ronaldmannak 522d71c
Report a row that cannot join as its own failure, not the stream's
ronaldmannak 48f689a
Merge PR 94 into PR 97
ronaldmannak eef185c
Merge PR 94 into PR 97
ronaldmannak 8eb03f3
Test cancellation during a later row's prefill in the stream
ronaldmannak 05786a9
Merge PR 94 into PR 97
ronaldmannak 2aef5be
Merge PR 94 into PR 97
ronaldmannak 9fcb0d3
Merge PR 94 into PR 97
ronaldmannak 65d8b65
Merge PR 94 into PR 97
ronaldmannak 9f75ec3
Merge PR 94 into PR 97
ronaldmannak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,340 @@ | ||
| // Copyright © 2026 Apple Inc. | ||
|
|
||
| import Foundation | ||
| import MLX | ||
|
|
||
| /// Completion information for one row of a fixed batch. | ||
| public struct BatchCompletionInfo: Sendable { | ||
| public let promptTokenCount: Int | ||
| public let generationTokenCount: Int | ||
| public let stopReason: GenerateStopReason | ||
| /// Time until this row's first model token, including the batch's sequential prefills. | ||
| /// Nil when the row was cancelled before its first token. | ||
| public let timeToFirstToken: TimeInterval? | ||
| /// Time from starting the batch worker until this row finished. | ||
| public let elapsedTime: TimeInterval | ||
| } | ||
|
|
||
| /// An output, final completion or failure event, attributed to its zero-based prompt index. | ||
| /// | ||
| /// Every row ends with exactly one `info` or `failed` event, after its last output. | ||
| /// Completion is reported by the outer `info` case, not an embedded `Generation.info` or | ||
| /// `TokenGeneration.info`. Batch timings do not represent isolated per-row prefill costs. | ||
| public enum BatchGenerationEvent<Output: Sendable>: Sendable { | ||
| case output(uid: Int, Output) | ||
| case info(uid: Int, BatchCompletionInfo) | ||
| /// The row could not join the batch and produced no tokens, for example because its | ||
| /// supplied cache does not match the other rows or its prefill threw. The other rows | ||
| /// carry on. | ||
| case failed(uid: Int, any Error) | ||
|
|
||
| public var uid: Int { | ||
| switch self { | ||
| case .output(let uid, _), .info(let uid, _), .failed(let uid, _): uid | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public enum BatchGenerationError: Error, LocalizedError, Equatable { | ||
| case emptyPrompt(index: Int) | ||
| case cacheCountMismatch | ||
| case invalidTokenLimit | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .emptyPrompt(let index): "Prompt \(index) must contain at least one token." | ||
| case .cacheCountMismatch: "Supply one cache entry per prompt." | ||
| case .invalidTokenLimit: "The token limit must be positive." | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Streams raw token events from a fixed batch. For cancellation and deterministic MLX | ||
| /// cleanup, use ``batchGenerateTokensTask(model:prompts:tokenizer:modelConfiguration:caches:maxTokens:stopTokens:sampler:processor:prefill:includeStopToken:wiredMemoryTicket:)``. | ||
| /// | ||
| /// Events are buffered without dropping tokens. Consume the stream to completion or cancel | ||
| /// its consumer; a plain `break` does not reliably terminate an `AsyncThrowingStream`. | ||
| public func batchGenerateTokens( | ||
| model: any LanguageModel, prompts: [[Int]], tokenizer: Tokenizer, | ||
| modelConfiguration: ModelConfiguration, caches: [[KVCache]?]? = nil, | ||
| maxTokens: Int = 128, stopTokens: Set<Int> = [], sampler: LogitSampler = ArgMaxSampler(), | ||
| processor: LogitProcessor? = nil, prefill: PrefillParameters = .init(), | ||
| includeStopToken: Bool = false, wiredMemoryTicket: WiredMemoryTicket? = nil | ||
| ) throws -> AsyncThrowingStream<BatchGenerationEvent<TokenGeneration>, Error> { | ||
| try batchGenerateTokensTask( | ||
| model: model, prompts: prompts, tokenizer: tokenizer, | ||
| modelConfiguration: modelConfiguration, caches: caches, maxTokens: maxTokens, | ||
| stopTokens: stopTokens, sampler: sampler, processor: processor, prefill: prefill, | ||
| includeStopToken: includeStopToken, wiredMemoryTicket: wiredMemoryTicket | ||
| ).0 | ||
| } | ||
|
|
||
| /// Streams raw tokens and per-row completion information using one batch iterator. | ||
| /// | ||
| /// EOS and unknown tokens end their own row. `includeStopToken` controls whether the terminal | ||
| /// token is emitted and counted. A cancelled task completes unfinished rows as `.cancelled`. | ||
| /// A row that cannot join the batch ends with a `failed` event while the other rows carry on; | ||
| /// an error from a batched model step terminates the stream. Await `task.value` after cancelling | ||
| /// to wait for GPU work and cache cleanup. The model and supplied caches must not be used | ||
| /// concurrently until the task completes. Admission, prefix reuse and budgets remain caller-owned. | ||
| public func batchGenerateTokensTask( | ||
| model: any LanguageModel, prompts: [[Int]], tokenizer: Tokenizer, | ||
| modelConfiguration: ModelConfiguration, caches: [[KVCache]?]? = nil, | ||
| maxTokens: Int = 128, stopTokens: Set<Int> = [], sampler: LogitSampler = ArgMaxSampler(), | ||
| processor: LogitProcessor? = nil, prefill: PrefillParameters = .init(), | ||
| includeStopToken: Bool = false, wiredMemoryTicket: WiredMemoryTicket? = nil | ||
| ) throws -> ( | ||
| AsyncThrowingStream<BatchGenerationEvent<TokenGeneration>, Error>, Task<Void, Never> | ||
| ) { | ||
| try batchGenerationTask( | ||
| model: model, prompts: prompts, tokenizer: tokenizer, | ||
| modelConfiguration: modelConfiguration, caches: caches, maxTokens: maxTokens, | ||
| stopTokens: stopTokens, sampler: sampler, processor: processor, prefill: prefill, | ||
| includeStopToken: includeStopToken, wiredMemoryTicket: wiredMemoryTicket, | ||
| handlers: prompts.map { _ in RawTokenLoopHandler() }) | ||
| } | ||
|
|
||
| /// Streams decoded text, reasoning and tool-call events from a fixed batch. | ||
| /// | ||
| /// Each row has independent decoder state. Output is lossless and buffered; use the task | ||
| /// variant when a consumer may stop before the whole batch finishes. | ||
| public func batchGenerateText( | ||
| model: any LanguageModel, prompts: [[Int]], tokenizer: Tokenizer, | ||
| modelConfiguration: ModelConfiguration, caches: [[KVCache]?]? = nil, | ||
| maxTokens: Int = 128, stopTokens: Set<Int> = [], sampler: LogitSampler = ArgMaxSampler(), | ||
| processor: LogitProcessor? = nil, prefill: PrefillParameters = .init(), | ||
| tools: [[String: any Sendable]]? = nil, toolCallPolicy: ToolCallPolicy = .init(), | ||
| wiredMemoryTicket: WiredMemoryTicket? = nil | ||
| ) throws -> AsyncThrowingStream<BatchGenerationEvent<Generation>, Error> { | ||
| try batchGenerateTextTask( | ||
| model: model, prompts: prompts, tokenizer: tokenizer, | ||
| modelConfiguration: modelConfiguration, caches: caches, maxTokens: maxTokens, | ||
| stopTokens: stopTokens, sampler: sampler, processor: processor, prefill: prefill, | ||
| tools: tools, toolCallPolicy: toolCallPolicy, wiredMemoryTicket: wiredMemoryTicket | ||
| ).0 | ||
| } | ||
|
|
||
| /// Runs one batch with an independent text/tool/reasoning handler for every prompt. | ||
| /// | ||
| /// A stop string or protocol boundary removes only the matching row. Cancelling the task | ||
| /// cancels the whole fixed batch. Await the task to observe completion of MLX cleanup. | ||
| /// Shared output is buffered without dropping events; this API supplies no serving scheduler. | ||
| public func batchGenerateTextTask( | ||
| model: any LanguageModel, prompts: [[Int]], tokenizer: Tokenizer, | ||
| modelConfiguration: ModelConfiguration, caches: [[KVCache]?]? = nil, | ||
| maxTokens: Int = 128, stopTokens: Set<Int> = [], sampler: LogitSampler = ArgMaxSampler(), | ||
| processor: LogitProcessor? = nil, prefill: PrefillParameters = .init(), | ||
| tools: [[String: any Sendable]]? = nil, toolCallPolicy: ToolCallPolicy = .init(), | ||
| wiredMemoryTicket: WiredMemoryTicket? = nil | ||
| ) throws -> (AsyncThrowingStream<BatchGenerationEvent<Generation>, Error>, Task<Void, Never>) { | ||
| let handlers = prompts.map { prompt in | ||
| TextToolTokenLoopHandler( | ||
| tokenizer: tokenizer, stopStrings: modelConfiguration.effectiveStopStrings, | ||
| format: modelConfiguration.toolCallFormat ?? .json, tools: tools, | ||
| toolCallPolicy: toolCallPolicy, | ||
| reasoning: modelConfiguration.reasoningConfig.map { | ||
| ( | ||
| config: $0, | ||
| primedInside: ReasoningEventEmitter.promptEndsInsideReasoning( | ||
| promptTokens: prompt, config: $0, tokenizer: tokenizer) | ||
| ) | ||
| }) | ||
| } | ||
| return try batchGenerationTask( | ||
| model: model, prompts: prompts, tokenizer: tokenizer, | ||
| modelConfiguration: modelConfiguration, caches: caches, maxTokens: maxTokens, | ||
| stopTokens: stopTokens, sampler: sampler, processor: processor, prefill: prefill, | ||
| includeStopToken: false, wiredMemoryTicket: wiredMemoryTicket, handlers: handlers) | ||
| } | ||
|
|
||
| private struct BatchStreamRow { | ||
| var tokenCount = 0 | ||
| var firstTokenTime: TimeInterval? | ||
| var finished = false | ||
| } | ||
|
|
||
| private func batchGenerationTask<Handler: TokenLoopHandler>( | ||
| model: any LanguageModel, prompts: [[Int]], tokenizer: Tokenizer, | ||
| modelConfiguration: ModelConfiguration, caches: [[KVCache]?]?, maxTokens: Int, | ||
| stopTokens: Set<Int>, sampler: LogitSampler, processor: LogitProcessor?, | ||
| prefill: PrefillParameters, includeStopToken: Bool, wiredMemoryTicket: WiredMemoryTicket?, | ||
| handlers: consuming [Handler] | ||
| ) throws -> (AsyncThrowingStream<BatchGenerationEvent<Handler.Output>, Error>, Task<Void, Never>) { | ||
| if let index = prompts.firstIndex(where: { $0.isEmpty }) { | ||
| throw BatchGenerationError.emptyPrompt(index: index) | ||
| } | ||
| guard caches.map({ $0.count == prompts.count }) ?? true else { | ||
| throw BatchGenerationError.cacheCountMismatch | ||
| } | ||
| guard maxTokens > 0 else { throw BatchGenerationError.invalidTokenLimit } | ||
|
|
||
| var terminalTokens = buildStopTokenIds( | ||
| modelConfiguration: modelConfiguration, tokenizer: tokenizer) | ||
| terminalTokens.formUnion(stopTokens) | ||
| let handlerStopTokens = terminalTokens | ||
| if let unknown = tokenizer.unknownTokenId { terminalTokens.insert(unknown) } | ||
| let iteratorStopTokens = terminalTokens | ||
| // The stream this batch runs on, settled at the end, as the single-sequence loop does. | ||
| let executionStream = StreamOrDevice.default.stream | ||
| let payload = SendableBox((model, caches, sampler, processor, handlers)) | ||
| let (stream, continuation) = AsyncThrowingStream<BatchGenerationEvent<Handler.Output>, Error> | ||
| .makeStream() | ||
| let task = Task { | ||
| let worker = GenerationWorker() | ||
| let performIteration = { @Sendable in | ||
| let clock = ContinuousClock() | ||
| let start = clock.now | ||
| let (model, caches, sampler, processor, initialHandlers) = payload.consume() | ||
| var handlers = initialHandlers | ||
| var iterator = BatchTokenIterator( | ||
| model: model, sampler: sampler, processor: processor, | ||
| stopTokens: iteratorStopTokens, | ||
| maxTokens: maxTokens, prefill: prefill) | ||
| if !Task.isCancelled { _ = iterator.insert(prompts: prompts, caches: caches) } | ||
| var rows = prompts.map { _ in BatchStreamRow() } | ||
| func elapsed() -> TimeInterval { | ||
| let duration = start.duration(to: clock.now).components | ||
| return Double(duration.seconds) + Double(duration.attoseconds) / 1e18 | ||
| } | ||
| func emit(_ uid: Int, _ output: sending Handler.Output) -> Bool { | ||
| if case .terminated = continuation.yield(.output(uid: uid, output)) { return false } | ||
| return true | ||
| } | ||
| func finish(_ uid: Int, reason: GenerateStopReason) { | ||
| guard !rows[uid].finished else { return } | ||
| rows[uid].finished = true | ||
| var reason = reason | ||
| switch handlers[uid].onGenerationEnd(emit: { emit(uid, $0) }) { | ||
| case .more: break | ||
| case .stop: if reason != .cancelled { reason = .stop } | ||
| case .cancelled: reason = .cancelled | ||
| } | ||
| _ = continuation.yield( | ||
| .info( | ||
| uid: uid, | ||
| BatchCompletionInfo( | ||
| promptTokenCount: prompts[uid].count, | ||
| generationTokenCount: rows[uid].tokenCount, stopReason: reason, | ||
| timeToFirstToken: rows[uid].firstTokenTime, elapsedTime: elapsed()))) | ||
| } | ||
| func fail(_ uid: Int, _ error: any Error) { | ||
| guard !rows[uid].finished else { return } | ||
| rows[uid].finished = true | ||
| _ = handlers[uid].onGenerationEnd(emit: { emit(uid, $0) }) | ||
| _ = continuation.yield(.failed(uid: uid, error)) | ||
| } | ||
|
|
||
| var failure: Error? | ||
| var terminated = false | ||
| do { | ||
| // Cancellation is checked before next(), which pipelines more MLX work. | ||
| while !Task.isCancelled, !terminated { | ||
| guard let events = try iterator.next() else { break } | ||
| let responseTime = elapsed() | ||
| // The rows the iterator ends this step; it drops them itself. | ||
| var endedByIterator = Set<Int>() | ||
| for case .finished(let id, _, _) in events { endedByIterator.insert(id) } | ||
| var semanticStops: [Int] = [] | ||
| for event in events { | ||
| let uid = event.id | ||
| let token: Int | ||
| let iteratorStop: Bool | ||
| switch event { | ||
| case .prefill: | ||
| continue | ||
| case .failed(_, let error): | ||
| // A prefill stopped by this task's cancellation is a cancelled | ||
| // row, not a failed one. | ||
| if error is CancellationError, Task.isCancelled { | ||
| finish(uid, reason: .cancelled) | ||
| } else { | ||
| fail(uid, error) | ||
| } | ||
| continue | ||
| case .finished(_, let reason, nil): | ||
| // A length finish follows the row's last token. | ||
| finish(uid, reason: reason) | ||
| continue | ||
| case .finished(_, _, let stopToken?): | ||
| token = stopToken | ||
| iteratorStop = true | ||
| case .token(_, let generated): | ||
| token = generated | ||
| iteratorStop = false | ||
| } | ||
| if rows[uid].firstTokenTime == nil { | ||
| rows[uid].firstTokenTime = responseTime | ||
| } | ||
| var reason: GenerateStopReason? | ||
| let semanticStop = handlers[uid].additionalStopTokenIDs.contains(token) | ||
| let disposition: TokenLoopDisposition | ||
| // A token is recorded as emitted exactly when it is counted, as the | ||
| // single-sequence loop does. | ||
| if iteratorStop || semanticStop { | ||
| if includeStopToken { | ||
| rows[uid].tokenCount += 1 | ||
| iterator.recordEmittedToken(id: uid, token: token) | ||
| } | ||
| if includeStopToken | ||
| || (handlers[uid].receivesStopTokens | ||
| && (semanticStop || handlerStopTokens.contains(token))) | ||
| { | ||
| disposition = handlers[uid].onStopToken( | ||
| token, logProbabilities: nil, emit: { emit(uid, $0) }) | ||
| } else { | ||
| disposition = .more | ||
| } | ||
| reason = .stop | ||
| } else { | ||
| rows[uid].tokenCount += 1 | ||
| iterator.recordEmittedToken(id: uid, token: token) | ||
| disposition = handlers[uid].onToken( | ||
| token, logProbabilities: nil, emit: { emit(uid, $0) }) | ||
| } | ||
| switch disposition { | ||
| case .more: break | ||
| case .stop: reason = .stop | ||
| case .cancelled: | ||
| reason = .cancelled | ||
| terminated = true | ||
| } | ||
| if let reason { | ||
| if !endedByIterator.contains(uid) { semanticStops.append(uid) } | ||
| finish(uid, reason: reason) | ||
| } | ||
| if terminated { break } | ||
| } | ||
| // Natural stops are already filtered by next(); semantic stops share one gather. | ||
| if !semanticStops.isEmpty { iterator.remove(semanticStops) } | ||
| } | ||
| for uid in rows.indices where !rows[uid].finished { | ||
| finish(uid, reason: .cancelled) | ||
| } | ||
| } catch is CancellationError where Task.isCancelled { | ||
| for uid in rows.indices where !rows[uid].finished { | ||
| finish(uid, reason: .cancelled) | ||
| } | ||
| } catch { | ||
| failure = error | ||
| for uid in rows.indices where !rows[uid].finished { | ||
| _ = handlers[uid].onGenerationEnd(emit: { emit(uid, $0) }) | ||
|
ronaldmannak marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
| // Every row, including the ones that ended in the last step, so each processor is | ||
| // finalized once even when the loop stopped early. | ||
| iterator.remove(Array(prompts.indices)) | ||
| // Cache owners and consumers may proceed only after queued device work settles. | ||
| executionStream.synchronize() | ||
| continuation.finish(throwing: failure) | ||
| } | ||
| if let ticket = wiredMemoryTicket { | ||
| await WiredMemoryTicket.withWiredLimit(ticket) { await worker.run(performIteration) } | ||
| } else { | ||
| await worker.run(performIteration) | ||
| } | ||
| } | ||
| continuation.onTermination = { termination in | ||
| if case .cancelled = termination { task.cancel() } | ||
| } | ||
| return (stream, task) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If cancellation occurs during a later prompt's chunked prefill after an earlier row was admitted, checking cancellation only before
iterator.next()does not prevent new GPU work.BatchTokenIterator.admit()catches the later row'sCancellationError, then samples the previously admitted rows, andnext()proceeds intodecode()despite the cancelled task. The new.failedhandling runs only after those forwards have been submitted; withmaxTokens: 1, the earlier row even completes as.lengthinstead of.cancelled. Ensure cancellation interrupts admission before sampling or batched decoding, while still finalizing all unfinished rows and synchronizing already-submitted work.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.