Skip to content
Closed
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
6 changes: 6 additions & 0 deletions changelog.d/glm-capture-under-load.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
### GLM prefix checkpoints under load

- GLM-5.3-Flash now captures a repeated prompt's checkpoints while other requests are decoding. Their decode tokens shortened every prefill chunk below 2,048, so no chunk ended on the 256-token checkpoint grid and the donor was silently not cached (one of six donors in a concurrent burst on an M5 Ultra). A donor the cache will write now ends a prefill range at its demanded boundaries whatever its company; in the same burst six of six were captured and written.
- GLM checkpoints now land on any 256-token boundary instead of every 2,048: a 32,682-token prompt restores 32,512 tokens instead of 30,720 (hit time to first token 3.1–3.7 s, was about 4.0 s).
- A GLM cache hit served beside decoding requests no longer waits for a full 2,048-token chunk and cold-restarts after three waits; it resumes under ordinary chunking.
- A GLM store now queues up to eight donations behind its writer instead of one, so donors that finish together are no longer dropped as `write_queue_full`.
7 changes: 6 additions & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,12 @@ the page table and runs the contiguous arithmetic over it
so its retained reads are bounded by the history, not the chunk. The GLM
scheduler installs 2,048-token prefill chunks and steps, bounded by the context,
and disables solo stripes (`EngineV2Factory.glm5NextMaximumStepTokens`,
`glm5NextServingScheduler`). The price splits into setup bytes for the step
`glm5NextServingScheduler`). Decode rows share that step budget and push every
prefill range off the 256-token checkpoint grid, so with the GLM complete store
the scheduler also ends a cacheable request's range on its checkpoint
boundaries (`EngineV2Factory.demandedCaptureBoundaryMinimumTokens`; see
[streamed complete checkpoints](prefix-cache.md#streamed-complete-checkpoints)).
The price splits into setup bytes for the step
geometry and a rate per context token of each request, which covers the
request's index metadata reads, pooled index planes, latent reads and page
tables in both its step and the chained decode successor
Expand Down
31 changes: 31 additions & 0 deletions docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,37 @@ live in `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/Dem
`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift`
(`executeMixed`). Existing checkpoint count/byte and storage floors remain.

GLM-5.3-Flash captures its KDA state under the same range-end rule, but it has
no solo stripe and its prefill chunk shares one 2,048-token step budget with
the decode rows of other requests (`EngineV2Factory.glm5NextMaximumStepTokens`).
Beside a decoding request every range is 2,044–2,047 tokens and none ends on
the 256-token grid, so such a donor captured nothing, with no disarm or counter
(one of six donors in a concurrent burst). The protected GLM engine with its
GLM store therefore sets `CBv2SchedulerConfig.demandedCaptureBoundaryMinimumTokens`
to the store floor (`EngineV2Factory.demandedCaptureBoundaryMinimumTokens`). A
request the store would write (a hint at or above the floor, or no hint) ends a
range at its hinted fork target and at the deepest aligned boundary below its
prompt end, whatever chunk its company left it. A range that would stop less
than one 128-token query block short of such a boundary ends on the query grid
instead, so the range that reaches the boundary keeps the ordinary prefill
kernels. A hint below the floor marks a fleet-novel prompt and keeps the
ordinary geometry. The same cut lowers GLM's reuse granularity from 2,048 to
256 tokens (a 32,682-token prompt publishes 32,512 instead of 30,720). GLM
adopters resume under ordinary chunking: a forced donor-sized chunk waited
whenever decode rows shortened the budget and cold-restarted the hit after
three waits
(`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineV2+CompleteCheckpoint.swift`,
`completeCheckpointLookup`). GLM's cold prefill depends
on its partition (the KDA four-token groups, the attention history/current
split and MoE routing), so as for the MoE Qwen a checkpoint is exactly the
state its own donor computed. On an M5 Ultra, solo donors of one prompt wrote
bit-identical checkpoints; a donor beside decoding requests differed from its
first partial KDA group on (relative L2 about 0.1 in the deepest layers), and
first-token logprobs of three partitions spread over 0.1 nat while each
partition repeated exactly. The partition is `demandedCaptureBoundaryRange` in
`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/DemandedShortCheckpointRange.swift`;
it shares `demandedCheckpointRange` with the first-token projection.

The benchmark SPI can explicitly select
`EngineV2BenchmarkCheckpointPartition.demandedRecurrentQualification` to measure
other actual recurrent paged complete-checkpoint models and longer demanded
Expand Down
1 change: 1 addition & 0 deletions docs/reference/ssd-kv-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ All constants are code constants of `SSDPrefixCachePolicy` and
| Payload/staging cap | `defaultMaxStageBytes = 1024 * 1_048_576`; `defaultMaxStageMillis = 1000` at `conservativeStageBytesPerSecond = 1_500_000_000`. Complete checkpoints on Macs with at least `largeMemoryThresholdBytes = 48 << 30` physical memory default to `largeMemoryCompleteCheckpointStageBytes = 7168 * 1_048_576` and `largeMemoryCompleteCheckpointStageMillis = 15_000`; a full-size file estimates about 5 s at the planning rate, so the byte cap binds. Both caps gate capture and read. Measured Qwen 3.8 MTP checkpoint files grow about 76 KB per token over a 154 MB base ([publication cost](../reports/2026-09-05-ssd-prefix-cache-model-check.md#publication-cost-and-memory)), so on the 4,096-token prefill grid 1 GiB fits 8,192 restored tokens and 7 GiB about 94,000. Explicit settings win where the process receives them; the daily write cap is unchanged | `SSDPrefixCachePolicy.swift` (`completeCheckpointMaxStageBytes`), `SSDHybridCheckpointStoreFactory.swift`, `SSDHybridCheckpointStore.swift` (`acceptsCheckpoint`) |
| Attention donation floor | `prefixTokens > adoptionBoundTokens + minEffectiveTokens`, whole blocks only; `defaultMinEffectiveTokens = 1024`, raised to 1_536 for `.frozenFullReplay` with bound ≥ 25_600 | `SSDPrefixCache.swift` (`donate`), `PrefixCachePolicy.swift` |
| Write-behind queue | `writeQueueMaxJobs = 2`, `writeQueueMaxBytes = 512 * 1_048_576`, `writeQueueSlackBytes = 256 * 1_048_576`; overflow drops the donation | `SSDPrefixCachePolicy.swift`, `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDWriteBehind.swift` |
| Complete-checkpoint write queue | A store writes one donation at a time and holds `completeCheckpointWriteQueueJobs` more behind it: 1, or `glm5NextCompleteCheckpointWriteQueueJobs = 8` for GLM5-Next stores; overflow settles `write_queue_full`. A donor offers its checkpoints one at a time, so the depth bounds donors finishing together. A queued GLM donation pins its donor's pages and KDA copies, which stay charged to the admission ledger until the write settles | `SSDPrefixCachePolicy.swift` (`completeCheckpointWriteQueueJobs`), `SSDHybridCheckpointStoreFactory.swift`, `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDHybridCheckpointStore+Write.swift` (`prepareWriteJob`) |
| Staging RAM | Reserved per staged entry in `GlobalKVCacheBudget`; the engine keeps its full slot grant | `provider-swift/Sources/ProviderCore/Inference/Memory/GlobalKVCacheBudget.swift` |

The production factories attach one persistent, root-wide rolling-day accounting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ extension EngineV2Factory {
hasRecurrentState: recurrent?.cbv2RecurrentStateSpec.layers.isEmpty == false)
}

/// GLM captures at aligned prefill range ends, but its prefill chunk and
/// decode rows share one step budget, so beside other requests no range end
/// lands on the grid. Its protected engine with the GLM complete store ends
/// demanded ranges on the store's boundaries instead (SDK
/// `CBv2SchedulerConfig.demandedCaptureBoundaryMinimumTokens`).
static func demandedCaptureBoundaryMinimumTokens(
model: any LanguageModel, store: (any CBv2CompletePrefixCache)?
) -> Int? {
guard model is GLM5NextProtectedModel, let store = store as? SSDHybridCheckpointStore,
store.config.backendLayout == CBv2CompleteCheckpointManifest.glm5NextPagedLayout
else { return nil }
return store.config.minEffectiveTokens
}

/// Host-only policy shared by the actual assembly and qualification tests.
/// A benchmark request cannot qualify another backend or lower a floor.
static func benchmarkRecurrentShortCheckpointMinimumTokens(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ extension EngineV2Factory {
benchmarkDemandedCheckpointPartitionIncludesLongPrompts(
model: model, backend: preparedBackend.kind, store: completePrefixCache,
constructionPurpose: constructionPurpose, checkpointPartition: checkpointPartition)
schedulerConfig.demandedCaptureBoundaryMinimumTokens = demandedCaptureBoundaryMinimumTokens(
model: model, store: completePrefixCache)
let processOwner: (any CBv2ProcessMemoryOwner)?
if let glmNative {
guard glmNative.resources.backend === backend,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ extension SSDHybridCheckpointStore {
let refusal: PrefixCacheDonationOutcome? = lock.withLock {
guard !closed else { return .cacheClosed }
guard !writing.contains(short) else { return .alreadyQueued }
guard writing.count < 2 else { return .writeQueueFull }
guard writing.count <= config.writeQueueJobs else { return .writeQueueFull }
writing.insert(short)
return nil
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public final class SSDHybridCheckpointStore: CBv2NativeCompletePrefixCache, CBv2
// Monotonic, stage-local deadline clock. Default preserves first-attempt
// timing; injected clocks keep retry boundary tests deterministic.
var stageNow: @Sendable () -> ContinuousClock.Instant = { .now }
/// Donations held behind the one being written; more settle
/// `write_queue_full` (`SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs`).
var writeQueueJobs = 1
}

public let identity: CBv2CompleteCheckpointIdentity
Expand Down Expand Up @@ -104,7 +107,7 @@ public final class SSDHybridCheckpointStore: CBv2NativeCompletePrefixCache, CBv2
writeBudget: writeBudget, nowSeconds: writeNowSeconds)
self.writeDemand = SSDCheckpointDemand(ttlSeconds: config.ttlSeconds)
self.pipeline = BoundedSingleConsumerPipeline(
capacity: 1,
capacity: config.writeQueueJobs,
onDropped: { [weak self] job in self?.settle(job, positions: []) ?? job.finish([]) },
consume: { [weak self] job in
guard let self else { job.finish([]); return }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ enum SSDHybridCheckpointStoreFactory {
minEffectiveTokens: SSDPrefixCachePolicy.minEffectiveTokens(environment: environment),
ttlSeconds: ttl, strictFsync: SSDPrefixCachePolicy.strictFsync(environment: environment),
nowSeconds: { Int64(Date().timeIntervalSince1970) }, diskBudgetBytes: budget,
maintainWholeRoot: maintain), kekKey: material.key, kvBudget: kvBudget,
maintainWholeRoot: maintain,
writeQueueJobs: SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs(
backendLayout: backendLayout)), kekKey: material.key, kvBudget: kvBudget,
maxWriteBytesPerDay: maxWriteBytesPerDay,
usesEphemeralKey: material.ephemeral,
writeBudget: writeBudget)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
// TTFT-oracle window). SEC-035 stays the accepted residual.

import Foundation
import MLXLMCommon

enum SSDPrefixCachePolicy {

Expand Down Expand Up @@ -243,4 +244,19 @@ enum SSDPrefixCachePolicy {
static let writeQueueMaxBytes = 512 * 1_048_576
/// Headroom above `maxStageBytes` in the effective queue-byte cap.
static let writeQueueSlackBytes = 256 * 1_048_576

/// Complete-checkpoint donations a store holds behind the one it is
/// writing; more settle `write_queue_full`. A donor offers its checkpoints
/// one at a time, so this bounds donors that finish together. Every GLM
/// donor of a burst captures (the SDK capture-boundary partition), and on
/// an M5 Ultra two donors finishing within 27 ms lost both of one donor's
/// files to a single slot. A queued GLM donation pins its donor's pages
/// and KDA copies, which stay charged to the admission ledger until the
/// write settles; a 32k donation writes in about 0.3 s.
static let glm5NextCompleteCheckpointWriteQueueJobs = 8

static func completeCheckpointWriteQueueJobs(backendLayout: String) -> Int {
backendLayout == CBv2CompleteCheckpointManifest.glm5NextPagedLayout
? glm5NextCompleteCheckpointWriteQueueJobs : 1
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ struct GLM5NextProtectedFactoryTests {
#expect(engine.completePrefixCache === store)
#expect(engine.completeCheckpointCodec?.isNativePagedGLM5Next == true)
#expect(engine.schedulerConfig.enablePrefixCache)
#expect(
engine.schedulerConfig.demandedCaptureBoundaryMinimumTokens
== store.config.minEffectiveTokens)
#expect(
store.config.writeQueueJobs
== SSDPrefixCachePolicy.glm5NextCompleteCheckpointWriteQueueJobs)
#expect(engine.schedulerConfig.maxConcurrentRequests == 2)
let context = fixture.sizing.maxContextLength
#expect(engine.schedulerConfig.maxBatchedTokensPerStep
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,17 @@ struct NemotronDemandedShortCheckpointTests {
model: model, backend: .paged, store: store,
constructionPurpose: .benchmark, checkpointPartition: .demandedRecurrentQualification))
}

@Test("the capture-boundary partition stays with GLM's protected engine")
func captureBoundaryPartitionIsGLMOnly() throws {
let fixture = try NemotronShortCheckpointFixture()
defer { fixture.remove() }
let model = NemotronH35Model(fixture.configuration)
#expect(EngineV2Factory.demandedCaptureBoundaryMinimumTokens(model: model, store: nil) == nil)
for layout in [CBv2CompleteCheckpointManifest.pagedLayout,
CBv2CompleteCheckpointManifest.glm5NextPagedLayout] {
#expect(EngineV2Factory.demandedCaptureBoundaryMinimumTokens(
model: model, store: try fixture.store(layout: layout)) == nil)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ final class SSDHybridCheckpointTestFixture: @unchecked Sendable {
diskBudgetBytes: @escaping @Sendable () -> Int = { 1 << 30 },
donationRecorder: any PrefixCacheDonationRecording = PrefixCacheDonationTelemetry.shared,
keyFingerprint: String = "fixture-key",
writeQueueJobs: Int = 1,
writeNowSeconds: @escaping @Sendable () -> Double = { Date().timeIntervalSince1970 }) throws -> SSDHybridCheckpointStore {
let epochStore: SSDCacheEpochStore? = epoch ? try .init(root: modelRoot, binding: .init(
modelId: "fixture-model", modelAggregateHash: identity.modelAggregateHash,
Expand All @@ -79,7 +80,8 @@ final class SSDHybridCheckpointTestFixture: @unchecked Sendable {
backendLayout: backendLayout,
root: modelRoot, dedicatedRoot: root, epochStore: epochStore, maxReadBytes: readCap,
maxStageMillis: 1000, minEffectiveTokens: 256, ttlSeconds: 3600, strictFsync: false,
nowSeconds: { Int64(Date().timeIntervalSince1970) }, diskBudgetBytes: diskBudgetBytes, maintainWholeRoot: {}),
nowSeconds: { Int64(Date().timeIntervalSince1970) }, diskBudgetBytes: diskBudgetBytes, maintainWholeRoot: {},
writeQueueJobs: writeQueueJobs),
kekKey: key, kvBudget: useGlobalBudget ? budget : nil, diskBudget: diskBudget,
maxWriteBytesPerDay: maxWriteBytesPerDay, writeBudget: writeBudget,
donationRecorder: donationRecorder, writeNowSeconds: writeNowSeconds)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import Foundation
@testable import MLXLMCommon
import Testing
@testable import ProviderCore

@Suite("Complete-checkpoint write queue", .serialized)
struct SSDCheckpointWriteQueueTests {
@Test("GLM5-Next stores queue eight donations behind the writer; other layouts keep one")
func queueDepthFollowsLayout() {
#expect(SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs(
backendLayout: CBv2CompleteCheckpointManifest.glm5NextPagedLayout) == 8)
for layout in [CBv2CompleteCheckpointManifest.layout, CBv2CompleteCheckpointManifest.pagedLayout,
CBv2CompleteCheckpointManifest.historicalAttentionLayout,
CBv2CompleteCheckpointManifest.diffusionBlockLayout] {
#expect(SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs(backendLayout: layout) == 1)
}
}

@Test("donors finishing together queue behind a busy writer up to the store's depth")
func donorsFinishingTogetherQueueBehindTheWriter() async throws {
let fixture = try SSDHybridCheckpointTestFixture(tokenCount: 6_145)
defer { fixture.remove() }
let outcomes = PrefixCacheDonationTelemetry()
let store = try fixture.makeStore(donationRecorder: outcomes, writeQueueJobs: 3)
defer { store.close() }
let barrier = SSDCheckpointCoordinationTestSupport.Barrier()
defer { barrier.release() }
store.afterPublishBeforeIndexForTesting = { try? barrier.block() }
store.registerDonationDemand(.init(repeatedPrefixTokens: 5_120), requestID: .init(8))
func donate(_ position: Int) throws -> Task<[Int], Never> {
let source = try fixture.source(position: position)
return Task {
await withCheckedContinuation { continuation in
store.donate(source, requestID: .init(8), tokens: fixture.tokens, cacheSalt: "tenant-a") {
continuation.resume(returning: $0)
}
}
}
}
let written = try donate(1_024)
try await SSDCheckpointCoordinationTestSupport.waitUntil { barrier.isEntered }
let queuedPositions = [2_048, 3_072, 4_096]
let queued = try queuedPositions.map(donate)
try await SSDCheckpointCoordinationTestSupport.waitUntil {
store.lock.withLock { store.writing.count == 4 }
}
#expect(try await fixture.donate(store, receipt: 8, position: 5_120).isEmpty)
#expect(outcomes.snapshot().first { $0.outcome == .writeQueueFull }?.count == 1)
barrier.release()
#expect(await written.value == [1_024])
for (task, position) in zip(queued, queuedPositions) {
#expect(await task.value == [position])
}
#expect(store.stats().filesWritten == 4)
#expect(outcomes.snapshot().first { $0.outcome == .donated }?.count == 4)
#expect(store.lock.withLock { store.writing.isEmpty })
await store.closeAndWait()
#expect(store.stats().stagedBytesInUse == 0)
}
}
Loading