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
9 changes: 9 additions & 0 deletions changelog.d/prompt-preparation-serving-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Prompt preparation counts against the serving width

- A text request now holds its share of the whole-Mac serving allowance from
before its prompt is rendered and tokenized, not only from submission. A full
Mac refuses a request as capacity before preparing its prompt, and prompts
being prepared at the same time count against the serving width. The share
becomes the request's serving allowance at submission, so an admitted
request cannot lose its place between preparation and submission. The
owner's local requests still wait for room at submission.
7 changes: 6 additions & 1 deletion docs/architecture/hardware-support.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Hardware support and the provider memory model

> Last updated: 2026-11-22
> Last updated: 2026-11-24

What hardware the provider runs on and how it decides, in bytes, whether a
model may load and how much KV cache each resident model may use. Read this to
Expand Down Expand Up @@ -655,6 +655,11 @@ through the measured free memory.
request reservation is released (loads and other charges are not counted as
freeable); otherwise it is refused at once as larger than the Mac holds
(`EngineV2Bridge+OwnerMemoryWait.swift`).
- A text request's prompt rendering and tokenization hold one share of the
whole-Mac service allowance (`WholeMacServiceBudget.acquirePreparation`), so
a full Mac refuses a request as capacity before preparing its prompt and
concurrent preparation counts against the serving width. Submission takes
the share over as the request's allowance.
- Reservation age is diagnostic only. `GlobalKVCacheBudget.recordCommitRejection`
logs sustained rejection and keeps every owner's charge until the caller
releases it after its resources retire. The asynchronous allocator-cache
Expand Down
14 changes: 12 additions & 2 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider inference engine

> Last updated: 2026-11-23
> Last updated: 2026-11-24

How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
Expand Down Expand Up @@ -2287,7 +2287,17 @@ the [qualification procedure](../developer/serving-performance-qualification.md)
is required before any width above 8 or model-specific chunk policy activates.
Qualified engines share one whole-Mac service allowance and retain physical KV,
architecture and explicit operator caps. A reservation is released only after
engine retirement, not when a caller merely requests cancellation. Atomic
engine retirement, not when a caller merely requests cancellation. A text
request holds one serving share of that allowance from before its prompt is
rendered and tokenized (`EngineV2Bridge.acquirePromptPreparation`,
`WholeMacServiceBudget.acquirePreparation`): a full Mac refuses it as capacity
before that work, prompts being prepared count against the width, and
submission takes the share over in place as the request's allowance, so it
cannot be lost between preparation and admission. A share not taken over is
returned when preparation ends. The owner's local requests, which wait for room
at submission, take no preparation share. Preparation shares count only toward
admission; reported usage, deadline work and calibration evidence start at
submission, as before. Atomic
deadline admission passes its retirement acknowledgement to the event pump;
an early terminal returns to the caller while the service and KV reservations
remain owned until that acknowledgement completes. With
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,25 @@ extension EngineV2Bridge {
overcommit: takesStoppedRowPlace) ?? true
}

/// The serving share a text prompt holds while it is rendered and
/// tokenized, under the owner ID its submission's allowance takes over
/// (`WholeMacServiceBudget.acquirePreparation`). A full Mac refuses as
/// capacity, as at submission. Nil: no shared budget, or the owner's
/// request, which waits for room at submission (`OwnerMemoryWait`).
func acquirePromptPreparation(requestID: String,
firstContentDeadline: FirstContentDeadline?) throws -> PromptPreparationShare? {
guard let serviceBudget, OwnerMemoryWait.current == nil
|| !OwnerMemoryWait.servesOwnerRequest(firstContentDeadline: firstContentDeadline) else { return nil }
let ownerID = serviceOwnerPrefix + ":" + requestID
guard serviceBudget.acquirePreparation(ownerID: ownerID,
concurrency: currentPerformanceProfile?.wholeMacConcurrency
?? ServingPerformanceProfiles.legacyWholeMacConcurrency,
overcommit: EngineAdmissionPriority.current > 0) else {
throw MultiModelBatchSchedulerEngineError.tokenBudgetExhausted(Self.serviceAllowanceExhausted)
}
return PromptPreparationShare(budget: serviceBudget, ownerID: ownerID)
}

/// Call only at refused pre-submit cleanup or completed engine retirement.
/// The stream's terminal alone does not prove device resources retired.
func releaseServiceAllowance(requestID: String) {
Expand All @@ -160,3 +179,12 @@ extension EngineV2Bridge {
serviceBudget?.release(ownerID: serviceOwnerPrefix + ":" + requestID)
}
}

/// A prompt preparation's serving share (`EngineV2Bridge.acquirePromptPreparation`).
/// `end` drops it unless the submission's allowance already took it over.
struct PromptPreparationShare: Sendable {
let budget: WholeMacServiceBudget
let ownerID: String

func end() { budget.releasePreparation(ownerID: ownerID) }
}
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,19 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
throw MultiModelBatchSchedulerEngineError.mediaUnsupportedByModel(modelId)
}

let requestId = "req-\(UUID().uuidString.prefix(12))"
// Rendering and tokenizing count against the serving width: a full
// Mac refuses before that work, and submission takes the share over.
let preparation: PromptPreparationShare?
do {
preparation = try await engineV2Bridge?.acquirePromptPreparation(
requestID: requestId, firstContentDeadline: firstContentDeadline)
} catch {
await releaseBox.fire()
throw error
}
defer { preparation?.end() }

let promptTokens: [Int]
let prepTiming: ProviderPromptContractPipeline.PrepTiming
do {
Expand Down Expand Up @@ -1253,8 +1266,6 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix,
parsesToolCalls: toolHandler != nil)

let requestId = "req-\(UUID().uuidString.prefix(12))"

// ONE ENGINE (v0.7.5): every production slot — ProviderLoop AND
// the standalone server — carries a v2 bridge; the tokenized
// prompt submits through it. The bridge yields the identical
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ final class WholeMacServiceBudget: @unchecked Sendable {
private var activityEpoch: UInt64 = 0
private var advertisedEligibility: [DeadlineApplicability: Bool] = [:]
private var charges: [String: Charge] = [:]
/// Serving shares held while a request's prompt is prepared
/// (`acquirePreparation`). They count only toward admission; deadline,
/// calibration and reported usage see a request from its `acquire` on.
private var preparations: [String: Double] = [:]
private var retirementWaiters: [String: [CheckedContinuation<Void, Never>]] = [:]
private var unboundedActivities: Set<UUID> = []
private var evidenceGuard = CBv2FirstContentEvidenceGuard()
Expand Down Expand Up @@ -140,12 +144,16 @@ final class WholeMacServiceBudget: @unchecked Sendable {
?? ServiceReservationLifetime.normalizedID(serviceReservationID)
let (acquired, notification) = lock.withLock { () -> (Bool, AsyncStream<Void>.Continuation?) in
guard charges[ownerID] == nil, concurrency > 0 else { return (false, nil) }
// The owner's own preparation share becomes this charge; other
// requests' preparation shares are occupied capacity.
let otherPreparations = preparationFractionLocked(excluding: ownerID)
if requiresIdle, !charges.isEmpty || !unboundedActivities.isEmpty { return (false, nil) }
if let reservationID, charges.values.contains(where: { $0.reservationID == reservationID }) {
return (false, nil)
}
let charge = 1 / Double(concurrency)
guard overcommit || charges.values.reduce(0, { $0 + $1.fraction }) + charge <= 1 + 1e-12 else {
guard overcommit
|| charges.values.reduce(0, { $0 + $1.fraction }) + otherPreparations + charge <= 1 + 1e-12 else {
return (false, nil)
}
// A continuation joins any charge but the recovery's: at width 1 it shares the Mac with a whole-Mac charge,
Expand All @@ -166,12 +174,40 @@ final class WholeMacServiceBudget: @unchecked Sendable {
} else { proof = nil }
charges[ownerID] = Charge(fraction: charge, reservationID: reservationID,
lifetime: serviceReservation, work: work, deadlineProof: proof, exclusive: requiresIdle)
preparations[ownerID] = nil
return (true, observer)
}
notification?.yield()
return acquired
}

/// Holds one serving share for `ownerID` while its prompt is rendered
/// and tokenized, so preparation counts against the serving width before
/// the prompt's size is known. `acquire` with the same owner takes the
/// share over in place; `releasePreparation` drops a share not taken over.
/// `overcommit` as in `acquire`.
func acquirePreparation(ownerID: String, concurrency: Int, overcommit: Bool = false) -> Bool {
lock.withLock {
guard charges[ownerID] == nil, preparations[ownerID] == nil, concurrency > 0 else { return false }
let share = 1 / Double(concurrency)
guard overcommit || charges.values.reduce(0, { $0 + $1.fraction })
+ preparationFractionLocked(excluding: nil) + share <= 1 + 1e-12 else { return false }
preparations[ownerID] = share
return true
}
}

/// No effect once `acquire` took the share over or it was released.
func releasePreparation(ownerID: String) {
_ = lock.withLock { preparations.removeValue(forKey: ownerID) }
}

var preparationCount: Int { lock.withLock { preparations.count } }

private func preparationFractionLocked(excluding ownerID: String?) -> Double {
preparations.reduce(0) { $0 + ($1.key == ownerID ? 0 : $1.value) }
}

func release(ownerID: String) {
let (charge, notification, waiters) = lock.withLock { () -> (Charge?, AsyncStream<Void>.Continuation?, [CheckedContinuation<Void, Never>]) in
guard let charge = charges.removeValue(forKey: ownerID) else { return (nil, nil, []) }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import Foundation
import MLXLMCommon
import MLXLMServer
import Testing
@testable import ProviderCore

/// Renders every conversation to `count` tokens and counts the renders. With
/// `holdsFirstRender`, the first render waits for `releaseFirstRender`; with
/// `failsRenders`, every render throws.
final class CountingRenderTokenizer: MLXLMCommon.Tokenizer, @unchecked Sendable {
struct RenderFailure: Error {}

private let lock = NSLock()
private var calls = 0
private let count: Int
private let holdsFirstRender: Bool
private let failsRenders: Bool
private let gate = DispatchSemaphore(value: 0)

init(count: Int = 8, holdsFirstRender: Bool = false, failsRenders: Bool = false) {
self.count = count
self.holdsFirstRender = holdsFirstRender
self.failsRenders = failsRenders
}

var renders: Int { lock.withLock { calls } }
func releaseFirstRender() { gate.signal() }

func encode(text: String, addSpecialTokens: Bool) -> [Int] { Array(repeating: 1, count: count) }
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { "" }
func convertTokenToId(_ token: String) -> Int? { nil }
func convertIdToToken(_ id: Int) -> String? { nil }
var bosToken: String? { nil }; var eosToken: String? { nil }; var unknownToken: String? { nil }
func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
additionalContext: [String: any Sendable]?) throws -> [Int] {
let call = lock.withLock { calls += 1; return calls }
if holdsFirstRender, call == 1 { _ = gate.wait(timeout: .now() + 20) }
if failsRenders { throw RenderFailure() }
return Array(repeating: 1, count: count)
}
}

/// Counts the requests submitted to it and answers each with one token and a
/// `.finished(.stop)` terminal, so a served request completes without error.
final class PreparationTestEngine: CBv2Engine, @unchecked Sendable {
private let lock = NSLock()
private var count = 0
var submissions: Int { lock.withLock { count } }

func submit(_ request: CBv2Request) throws -> AsyncStream<CBv2Event> {
lock.withLock { count += 1 }
return AsyncStream { continuation in
continuation.yield(.delta(text: "OK", tokens: [9], logprobs: nil))
continuation.yield(.finished(reason: .stop, usage: .init(
promptTokens: request.promptTokens.count, completionTokens: 1)))
continuation.finish()
}
}
func cancel(_ id: CBv2RequestID) {}
func capacity() -> CBv2CapacitySnapshot {
.init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0)
}
func shutdown() async {}
}

/// A text prompt's rendering and tokenization count against the whole-Mac
/// serving width: a full Mac refuses a request as capacity before rendering
/// its prompt, a prompt being prepared holds a share another request cannot
/// take, and the share becomes the request's serving allowance at submission.
@Suite("Prompt preparation counts against the serving width")
struct PromptPreparationAdmissionTests {
private static let model = "preparation/model"
private static let width = ServingPerformanceProfiles.legacyWholeMacConcurrency

private struct Served: Sendable {
let engine: PreparationTestEngine
let serviceBudget: WholeMacServiceBudget
let bridge: EngineV2Bridge
let scheduler: MultiModelBatchSchedulerEngine

/// `busy` of the whole-Mac width's shares are held by other requests.
init(tokenizer: CountingRenderTokenizer, busy: Int) {
let model = PromptPreparationAdmissionTests.model
let width = PromptPreparationAdmissionTests.width
let engine = PreparationTestEngine()
let budget = roomyKVBudget()
for slot in 0..<busy {
precondition(budget.serviceBudget.acquire(ownerID: "busy-\(slot)", concurrency: width))
}
let handle = TokenizerHandle(tokenizer)
let bridge = EngineV2Bridge(engine: engine, modelId: model, tokenizer: handle, eosTokenIds: [],
defaultMaxTokens: 64, maxConcurrentRequests: 1, kvBudget: budget)
self.engine = engine
serviceBudget = budget.serviceBudget
self.bridge = bridge
scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
[model: .init(tokenizer: handle, modelType: "llama", engineV2Bridge: bridge)]
})
}

/// Nil when the request completed; else what it threw.
func complete() async -> (any Error)? {
do {
let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data("""
{"model":"\(PromptPreparationAdmissionTests.model)","messages":[{"role":"user","content":"hi"}],"max_tokens":16}
""".utf8))
for try await _ in try await scheduler.streamChatCompletion(request: request) {}
return nil
} catch { return error }
}

/// The budget once every finished request's allowance has retired.
func settledCount(_ expected: Int) async -> Int {
for _ in 0..<500 where serviceBudget.count != expected {
try? await Task.sleep(for: .milliseconds(10))
}
return serviceBudget.count
}
}

private static let capacity = MultiModelBatchSchedulerEngineError.tokenBudgetExhausted(
EngineV2Bridge.serviceAllowanceExhausted)

@Test("a full Mac refuses a request as capacity before rendering its prompt")
func aFullMacRefusesBeforeRendering() async throws {
let tokenizer = CountingRenderTokenizer()
let served = Served(tokenizer: tokenizer, busy: Self.width)
let error = await served.complete()
#expect(error as? MultiModelBatchSchedulerEngineError == Self.capacity)
#expect(tokenizer.renders == 0)
#expect(served.engine.submissions == 0)
#expect(await served.settledCount(Self.width) == Self.width)
await served.bridge.shutdown()
}

@Test("a prompt being prepared holds the last share: another request is refused before rendering",
.timeLimit(.minutes(1)))
func aPreparingPromptHoldsItsShare() async throws {
let tokenizer = CountingRenderTokenizer(holdsFirstRender: true)
let served = Served(tokenizer: tokenizer, busy: Self.width - 1)
let first = Task { await served.complete() }
while tokenizer.renders == 0 { try await Task.sleep(for: .milliseconds(5)) }
let second = await served.complete()
let rendersWhileHeld = tokenizer.renders
tokenizer.releaseFirstRender()
let firstError = await first.value
#expect(second as? MultiModelBatchSchedulerEngineError == Self.capacity)
#expect(rendersWhileHeld == 1)
#expect(firstError == nil)
#expect(served.engine.submissions == 1)
#expect(await served.settledCount(Self.width - 1) == Self.width - 1)
await served.bridge.shutdown()
}

@Test("a prompt prepared on the last share is served on it, and the share retires with the request")
func theLastShareIsServed() async throws {
let tokenizer = CountingRenderTokenizer()
let served = Served(tokenizer: tokenizer, busy: Self.width - 1)
#expect(await served.complete() == nil)
#expect(tokenizer.renders == 1)
#expect(served.engine.submissions == 1)
#expect(await served.settledCount(Self.width - 1) == Self.width - 1)
// The share is free again: the next request is served on it.
#expect(await served.complete() == nil)
#expect(served.engine.submissions == 2)
await served.bridge.shutdown()
}

@Test("a prompt that fails to render returns its share")
func aFailedRenderReturnsItsShare() async throws {
let tokenizer = CountingRenderTokenizer(failsRenders: true)
let served = Served(tokenizer: tokenizer, busy: Self.width - 1)
#expect(await served.complete() != nil)
#expect(await served.complete() != nil)
// Both rendered: the first failure left the last share free.
#expect(tokenizer.renders == 2)
#expect(served.engine.submissions == 0)
#expect(await served.settledCount(Self.width - 1) == Self.width - 1)
await served.bridge.shutdown()
}
}
Loading
Loading