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
10 changes: 9 additions & 1 deletion Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ public struct CBv2Request: Sendable {
/// sampler byte-for-byte. Required/named/none tool choices install a
/// row-local machine compiled before submission.
public var tokenConstraint: (any CBv2TokenConstraint)?
/// Coordinator-observed length, in tokens, of the prefix other prompts
/// share with this one; nil without a hint, 0 for a fleet-novel prompt.
/// Historical checkpoint retention keeps the stride-aligned boundary at
/// or below it as the fork target. A retention hint only: it never
/// changes what is computed, sampled or admitted.
public var prefixCheckpointTargetTokens: Int?

public init(
id: CBv2RequestID, promptTokens: [Int], sampling: CBv2SamplingParams = .init(),
Expand All @@ -129,7 +135,8 @@ public struct CBv2Request: Sendable {
positionState: CBv2PositionState? = nil,
hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil,
prefixCacheReceiptID: CBv2RequestID? = nil,
tokenConstraint: (any CBv2TokenConstraint)? = nil
tokenConstraint: (any CBv2TokenConstraint)? = nil,
prefixCheckpointTargetTokens: Int? = nil
) {
self.id = id
self.promptTokens = promptTokens
Expand All @@ -146,6 +153,7 @@ public struct CBv2Request: Sendable {
self.hybridPrefixIdentity = hybridPrefixIdentity
self.prefixCacheReceiptID = prefixCacheReceiptID
self.tokenConstraint = tokenConstraint
self.prefixCheckpointTargetTokens = prefixCheckpointTargetTokens
}
}

Expand Down
6 changes: 4 additions & 2 deletions Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ final class CBv2InFlightStep {
var recurrentEvaluations: [CBv2RequestID: CBv2RecurrentStateEvaluation] = [:]
var forwardShapes: CBv2ForwardShapeStep?
var recurrentCheckpointChunkSizes: [CBv2RequestID: Int] = [:]
var historicalCheckpoints: [CBv2RequestID: CBv2CapturedCompleteCheckpoint] = [:]
var historicalCheckpoints: [CBv2RequestID: [CBv2CapturedCompleteCheckpoint]] = [:]
var permitsChainedSuccessor: Bool {
mtpRound == nil && historicalCheckpoints.isEmpty && attentionPacket == nil
}
Expand Down Expand Up @@ -3067,7 +3067,9 @@ public final class EngineLoopV2: @unchecked Sendable {
}
var groups: [PackedGroup] = []
for row in work where !row.isDecode {
guard row.rec.prefixReusePlan?.recurrentChunkSize == nil else { continue }
guard row.rec.prefixReusePlan?.recurrentChunkSize == nil,
row.rec.prefixReusePlan?.excludesPackedPrefill != true
else { continue }
// A multimodal request's text-only chunks remain packable.
// A span-bearing chunk needs explicit rectangular embedding
// and row-mask capability from both model and cache provider.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,58 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable {
let store: any CBv2CompletePrefixCache
let queue = DispatchQueue(label: "cbv2.complete-checkpoint-retirement", qos: .utility)
var staged: [CBv2RequestID: [CBv2CapturedCompleteCheckpoint]] = [:]
/// Historical donors keep at most the first boundary, the coordinator's
/// fork target and the rolling latest (`CBv2HistoricalCheckpointRetention`).
/// Engine-queue owned, created with a request's first staged checkpoint
/// and removed with its staged list.
var historicalRetention: [CBv2RequestID: CBv2HistoricalCheckpointRetention] = [:]
/// Staged window copies share the slot's ordinary admission ceiling
/// (`AdmissionV2.reserveTransient`). Over 1/16 of that capacity a donor
/// gives up its first, then its fork target, and always keeps its rolling
/// latest: the same order as the slot-wide cap. Windows per checkpoint:
/// gpt-oss-20b ~7 MB (12 owners x 128 tokens, float32 K/V), gemma-4-26b
/// ~216 MB (25 owners x 1,024 tokens, 16-bit K/V).
static let historicalStagedByteBudgetDivisor = 16
/// Test seam; production reads the admission capacity at every commit so
/// a resized slot budget is honored by requests already in flight.
var historicalStagedByteBudgetOverride: Int?
var historicalStagedByteBudget: Int {
historicalStagedByteBudgetOverride
?? max(0, codec.admission.bytesCapacity) / Self.historicalStagedByteBudgetDivisor
}
/// Staged historical windows across ALL donors may hold at most 1/8 of
/// the slot's admission capacity (`CBv2HistoricalStagingCap`), read at
/// each capture because the slot can be re-sliced at runtime. Test seam.
var historicalSlotStagedByteCapOverride: Int?
var historicalSlotStagedByteCap: Int {
historicalSlotStagedByteCapOverride
?? max(0, codec.admission.bytesCapacity) / CBv2HistoricalStagingCap.capacityDivisor
}
/// Window bytes a donor's checkpoints still hold while its files are
/// written: `publish` moves them out of `staged`, but their reservations
/// are released only when the batch closes after the last file. Written
/// on the engine queue, cleared on the retirement queue, read by either.
private let publishingLock = NSLock()
private var publishingHistoricalBytes: [CBv2RequestID: Int] = [:]
var publishingHistoricalBytesTotal: Int {
publishingLock.withLock { publishingHistoricalBytes.values.reduce(0, +) }
}
/// Window bytes of every donor's historical checkpoints that still hold
/// a reservation: staged, or in publication. Both count against the
/// slot-wide cap, so donors finishing together cannot lift new donors'
/// staging above it.
var stagedHistoricalBytes: Int {
staged.values.reduce(publishingHistoricalBytesTotal) { total, captures in
captures.reduce(total) { $0 + $1.stagedHistoricalBytes }
}
}
/// Net window bytes prepared by the step now launching and not yet
/// committed: candidates minus the rolling latest each replaces. A step
/// holding candidates never chains a successor
/// (`CBv2InFlightStep.permitsChainedSuccessor`), so every candidate is
/// committed or closed before the next step prepares and resets this.
var inFlightHistoricalBytes = 0
var historicalCheckpointStrideTokens = CBv2RecurrentCheckpointGeometry.historicalCheckpointStrideTokens
// Deterministic native construction/evaluation fault seam, engine-queue
// only. Production always uses the ordinary private historical owner.
var makeHistoricalWindow: (PagedSequenceKV, Int, AdmissionV2) throws -> CBv2HistoricalWindow = {
Expand Down Expand Up @@ -126,6 +178,7 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable {
/// A final queued drop follows that request's rolling retirement copies.
/// The engine counts this callback in its existing shutdown drain barrier.
func drop(requestID: CBv2RequestID, completion: @escaping @Sendable () -> Void) -> Bool {
historicalRetention.removeValue(forKey: requestID)
guard let captures = staged.removeValue(forKey: requestID) else { return false }
queue.async {
captures.forEach { $0.finishEvaluationAndClose() }
Expand All @@ -141,7 +194,22 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable {
state: [CBv2SequenceKV?],
completion: @escaping @Sendable ([Int]) -> Void
) {
let captures = staged.removeValue(forKey: intent.requestID) ?? []
// Historical donors publish deepest first, then the fork target, then
// the first: the store's queue, quota and demand gates see the most
// valuable endpoint before a shallower one can consume them. A target
// that turned out adjacent to the final deepest boundary is retired
// unwritten. Recurrent publication order is unchanged.
var captures = staged.removeValue(forKey: intent.requestID) ?? []
let retention = historicalRetention.removeValue(forKey: intent.requestID)
if codec.historicalLayout != nil {
let dropped = Set(retention?.publication.drop ?? [])
let retiring = captures.filter { $0.position.map(dropped.contains) ?? false }
captures.removeAll { $0.position.map(dropped.contains) ?? false }
captures.sort { ($0.position ?? 0) > ($1.position ?? 0) }
if !retiring.isEmpty {
queue.async { retiring.forEach { $0.finishEvaluationAndClose() } }
}
}
var exports: [CBv2CompleteCheckpointExport] = []
for capture in captures where intent.allowsCompletePublication {
if let checkpoint = capture.historical {
Expand All @@ -156,9 +224,26 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable {
}
}
}
let publishingBytes = captures.reduce(0) { $0 + $1.stagedHistoricalBytes }
var onRetired: (@Sendable () -> Void)?
if publishingBytes > 0 {
let requestID = intent.requestID
publishingLock.withLock { publishingHistoricalBytes[requestID, default: 0] += publishingBytes }
onRetired = { [self] in
publishingLock.withLock {
let remaining = (publishingHistoricalBytes[requestID] ?? 0) - publishingBytes
if remaining > 0 {
publishingHistoricalBytes[requestID] = remaining
} else {
publishingHistoricalBytes.removeValue(forKey: requestID)
}
}
}
}
let batch = CBv2CompleteCheckpointPublication(
captures: captures, exports: exports, receiptID: intent.receiptID,
tokens: intent.tokens, cacheSalt: intent.cacheSalt, completion: completion)
tokens: intent.tokens, cacheSalt: intent.cacheSalt,
onRetired: onRetired, completion: completion)
queue.async { [self] in
guard !isClosed, batch.prepare(),
let scratch = try? codec.admission.reserveTransient(
Expand Down Expand Up @@ -188,6 +273,8 @@ final class CBv2CapturedCompleteCheckpoint: @unchecked Sendable {
private(set) var historical: CBv2HistoricalCompleteCheckpoint?
var evaluationRoots: [MLXArray] { checkpoint?.evaluationRoots ?? historical?.evaluationRoots ?? [] }
var position: Int? { checkpoint?.position ?? historical?.position }
/// Transient admission bytes this staged historical capture holds.
var stagedHistoricalBytes: Int { historical?.reservedBytes ?? 0 }
private var reservation: CBv2CheckpointReservation?

init(checkpoint: CBv2RecurrentCheckpoint, reservation: CBv2CheckpointReservation) {
Expand Down Expand Up @@ -218,6 +305,8 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable {
private var completedPositions: [Int] = []
private var cursor = 0
private var completion: (@Sendable ([Int]) -> Void)?
/// Runs once the captures' reservations are released, before completion.
private var onRetired: (@Sendable () -> Void)?
let receiptID: CBv2RequestID?
let tokens: [Int]
let cacheSalt: String?
Expand All @@ -226,13 +315,15 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable {
init(
captures: [CBv2CapturedCompleteCheckpoint], exports: [CBv2CompleteCheckpointExport],
receiptID: CBv2RequestID?, tokens: [Int], cacheSalt: String?,
onRetired: (@Sendable () -> Void)? = nil,
completion: @escaping @Sendable ([Int]) -> Void
) {
self.captures = captures
self.exports = exports
self.receiptID = receiptID
self.tokens = tokens
self.cacheSalt = cacheSalt
self.onRetired = onRetired
self.completion = completion
}

Expand Down Expand Up @@ -262,6 +353,9 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable {
exports.removeAll()
captures.forEach { $0.finishEvaluationAndClose() }
captures.removeAll()
let retired = onRetired
onRetired = nil
retired?()
scratch?.release()
scratch = nil
let callback = completion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,12 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable {
manifest.mediaTargetOnly == request.usesTargetOnlyMediaCheckpoint,
manifest.position < request.promptTokens.count,
manifest.prefixTokens.elementsEqual(request.promptTokens.prefix(manifest.position)),
manifest.chunkSize >= minimumChunkSize, manifest.chunkSize <= maximumChunkSize,
// Recurrent adopters continue the donor's exact chunk geometry, so
// its stride must be one this engine can schedule. Historical
// layouts resume with ordinary chunking; their recorded stride is
// only the manifest's position alignment.
historicalLayout != nil
|| (manifest.chunkSize >= minimumChunkSize && manifest.chunkSize <= maximumChunkSize),
CBv2AttentionV1.queryBlockSize <= 0 || manifest.chunkSize % CBv2AttentionV1.queryBlockSize == 0,
manifest.assistantCodecID == (manifest.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID),
manifest.attentionLayers == historicalLayout?.layers,
Expand Down
Loading
Loading