Repository navigation
feat(provider-swift): migrate BatchScheduler from BatchGenerator to BatchedEngine - #207
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 83065eedb7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let timedOut = activeBridges.filter { _, bridge in | ||
| bridge.firstTokenAt == nil | ||
| && now - bridge.submittedAt >= pendingTimeout | ||
| } |
There was a problem hiding this comment.
Restrict timeout aborts to truly queued requests
expirePlannerTimeouts currently aborts every request that has no first token after pendingTimeout, but firstTokenAt == nil also covers admitted requests that are still prefilling a large prompt. In that case a valid in-progress generation is cancelled and mislabeled as "request timed out waiting for capacity" even when it was already running. This is a regression from the previous behavior, which timed out only the explicit pending queue; the timeout predicate should be tied to actual queue/waiting state, not first-token timing alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this commit — expirePlannerTimeouts now gates on bridge.admittedAt == nil (not firstTokenAt == nil). A long-prefill request has admittedAt set (from the first RequestOutput) but firstTokenAt nil; the new predicate correctly leaves it alone. See recordAdmission for the wiring.
| // Stream closed without a terminal output (engine teardown). | ||
| await scheduler.dropBridge(requestId: id) | ||
| continuation.finish() | ||
| } |
There was a problem hiding this comment.
Emit an error when teardown closes a live request stream
When the engine stream ends without a terminal output, this branch drops bridge state and finishes the stream without yielding .error. ProviderLoop treats plain stream completion as success and emits a normal completion payload, so model unload/shutdown can silently turn aborted in-flight requests into successful responses with partial/empty output. Teardown-initiated closure should surface an explicit error event before finishing.
Useful? React with 👍 / 👎.
| let queuedTokens = snap.pendingRequests.reduce(0) { | ||
| $0 + $1.promptTokenCount + $1.maxOutputTokens | ||
| } | ||
| cancelledUIDs.removeAll() | ||
| pendingSummaryCache = PendingSummary( | ||
| queuedRequests: snap.pendingRequests.count, | ||
| queuedTokens: queuedTokens |
There was a problem hiding this comment.
Stop counting admitted requests as pending budget
refreshPendingSummaryCache derives queuedRequests/queuedTokens from planner.snapshot().pendingRequests, but this integration never advances planner entries out of pending (requests are removed only via planner.cancel on finish). That makes running requests appear both active (activeBridges) and queued, double-counting budget and waiters in heartbeats. The coordinator’s routing gate sums activeTokenBudgetUsed + queuedTokenBudget when deciding admission, so this inflation can falsely reject routable work and underutilize healthy providers.
Useful? React with 👍 / 👎.
| maxNumSeqs: maxConcurrentRequests, | ||
| maxNumBatchedTokens: 8192, | ||
| prefillStepSize: 512, | ||
| streamInterval: 1, | ||
| maxKVCacheTokens: 0 // unlimited — our kvBudget gates by bytes |
There was a problem hiding this comment.
Apply the adaptive cap when starting the engine
The engine is initialized with maxNumSeqs: maxConcurrentRequests (hard cap), while dynamicMaxConcurrentRequests is reset to min(4, maxConcurrentRequests) afterwards and only pushed to the engine later when a performance update changes the cap. This means the intended conservative startup cap is never enforced, so fresh loads can immediately admit up to the hard cap and regress latency/memory behavior before adaptive control even engages.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this commit — engine.setMaxNumSeqs(dynamicMaxConcurrentRequests) is called immediately after engine.start() so the conservative startup cap (min(4, maxConcurrentRequests)) is in effect before any submit lands.
| if !output.newText.isEmpty { | ||
| if !sawFirstToken { | ||
| await scheduler.recordFirstToken(requestId: id, at: .now) | ||
| sawFirstToken = true |
There was a problem hiding this comment.
Track first-token progress from tokens, not emitted text
First-token progress is recorded only when output.newText is non-empty, but the engine can emit token IDs that decode to an empty text chunk (e.g., intermediate/special pieces) before visible text appears. In that case the request is actively decoding yet firstTokenAt stays nil, so the timeout watchdog can incorrectly abort it as "waiting for capacity" after pendingTimeout. The previous implementation marked first-token progress per generated token, so this is a regression in timeout classification.
Useful? React with 👍 / 👎.
83065ee to
05d1569
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 05d1569b7e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let engineBatchedTPS: [(Int, Double)] = await withTaskGroup( | ||
| of: (Int, Double).self | ||
| ) { group in | ||
| for batchSize in [2, 4] { | ||
| group.addTask { |
There was a problem hiding this comment.
Run BatchedEngine benchmark cases sequentially
runDecodeTPSBracket now launches the B=2 and B=4 engine benchmarks in parallel, but both calls share the same ModelContainer and each constructs a BatchedEngine from that container’s ctx.model. That means two engines can drive the same model concurrently, which invalidates the TPS comparison and can trigger nondeterministic runtime failures when live perf tests run. This benchmark path should execute those batch-size cases one at a time (or use isolated model/container instances).
Useful? React with 👍 / 👎.
| ) | ||
| } | ||
| await engine.start() | ||
| defer { Task.detached { await engine.stop() } } |
There was a problem hiding this comment.
Await engine stop before leaving performance helper
runBatchedEngineSingle stops the engine via Task.detached in defer, so the function returns before shutdown completes. Subsequent benchmark stages can start while prior engines are still draining, which skews timings and can inflate memory pressure in live runs. Because this function is used repeatedly in the same test, engine shutdown should be awaited synchronously before returning.
Useful? React with 👍 / 👎.
05d1569 to
a39cf75
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a39cf7571d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ) | ||
| } | ||
| await engine.start() | ||
| defer { Task.detached { await engine.stop() } } |
There was a problem hiding this comment.
Await engine shutdown in live batching helper
The helper returns immediately after scheduling engine.stop() on a detached task, so the next live test/helper invocation can start another engine while the previous one is still draining. In this suite we repeatedly create engines against the same loaded model/container, so overlapping teardown can skew token/TPS measurements and cause nondeterministic live-test failures under load. Make teardown synchronous (await engine.stop()) before returning from the helper.
Useful? React with 👍 / 👎.
| memoryBudgetBytes: 8 * 1024 * 1024 * 1024 | ||
| ) | ||
| let scheduler = loaded.scheduler | ||
| defer { Task { await scheduler.unloadModel() } } |
There was a problem hiding this comment.
Await scheduler unload before leaving live test
This defer launches unloadModel() asynchronously and does not wait for completion, so the test can finish while teardown is still in progress. Because the suite has multiple live tests that each load large models, the next test may begin with the previous model still unloading, leading to transient memory pressure and flaky failures that are unrelated to assertion logic. Teardown should be awaited before the test exits.
Useful? React with 👍 / 👎.
| memoryBudgetBytes: 8 * 1024 * 1024 * 1024 | ||
| ) | ||
| let scheduler = loaded.scheduler | ||
| defer { Task { await scheduler.unloadModel() } } |
There was a problem hiding this comment.
Await scheduler unload in cancel-path live test
The second live test uses the same fire-and-forget unload pattern, so model teardown can continue after the test completes. In practice this creates overlap with subsequent live tests in the serialized suite, causing intermittent memory pressure and timing noise that can hide real regressions. Use an awaited teardown path so the test does not return until unload finishes.
Useful? React with 👍 / 👎.
| } | ||
| } | ||
| await engine.start() | ||
| defer { Task.detached { await engine.stop() } } |
There was a problem hiding this comment.
Await engine stop in eviction/admission live test
This test also detaches engine.stop() in defer, which means cleanup races with later test work and can leave prior engine shutdown running in the background. Because the test drives multiple requests and then immediately exits, overlapping teardown can introduce nondeterministic failures and inflated resource use in subsequent live cases. Teardown should synchronously await engine.stop().
Useful? React with 👍 / 👎.
a39cf75 to
ddd538e
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ddd538e24f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| prompt: promptTokens as AnyHashable, | ||
| samplingParams: sp | ||
| ) | ||
| _ = await engine.core.addRequest(req) |
There was a problem hiding this comment.
Reintroduce aggregate token-budget gating before addRequest
After the migration, requests are forwarded directly to engine.core.addRequest here, but the planner path no longer enforces a cumulative currentTokenBudgetUsed + requestBudget check before admission. planner.admit(...) only validates per-request limits/queue size (see BatchQueuePlanner.admit), so multiple large requests can be accepted simultaneously as long as each one is individually below tokenBudgetMax, which bypasses the previous pending→admit budget gate and can overcommit KV memory under burst traffic.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed — cumulative budget gate at BatchScheduler.swift:316 (activeUsed + requestBudget > tokenBudgetMax). Also at line 296 for per-request cap. See BatchSchedulerBudgetTests for coverage.
| let elapsed = Self.seconds(between: startedAt, and: .now) | ||
| guard epoch == generationEpoch, generator === gen else { | ||
| return false | ||
| recordBatchPerformance(observedBatchSize: max(1, activeBridges.count + 1), tps: tps) |
There was a problem hiding this comment.
Measure adaptive cap from running rows, not bridge count
This uses activeBridges.count + 1 as the observed batch size, but activeBridges includes requests still waiting in the engine queue (not yet admitted/running). Under backlog (e.g., engine cap 2 with many queued requests), the adaptive policy records inflated batch sizes and synthetic aggregate TPS, which can drive incorrect cap adjustments and degrade scheduling stability.
Useful? React with 👍 / 👎.
| var maxTokensPotential: Int64 = 0 | ||
| for entry in active.values { | ||
| for entry in activeBridges.values { | ||
| activeTokens += Int64(entry.promptTokens + entry.completionTokens) |
There was a problem hiding this comment.
Update bridge completion counters before reporting active tokens
backendCapacity() reports activeTokens from entry.promptTokens + entry.completionTokens, but completionTokens in BridgeState is only assigned in recordFinish (after the bridge is removed), so in-flight decode progress is never reflected in heartbeats. This under-reports live token load and skews coordinator-side backlog/health accounting while requests are running.
Useful? React with 👍 / 👎.
ddd538e to
77989fa
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
77989fa to
99e2cd4
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
99e2cd4 to
cc8c973
Compare
cc8c973 to
77989fa
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
77989fa to
cc8c973
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc8c973836
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let engine = await Self.makeBatchedEngine( | ||
| container: container, | ||
| modelId: modelId, | ||
| maxConcurrentRequests: maxConcurrentRequests, | ||
| eosTokenIds: snapshot.eosTokenIds | ||
| ) | ||
| self.engine = engine | ||
| await engine.start() |
There was a problem hiding this comment.
Revalidate generation epoch after awaited engine startup
loadModel checks loadEpoch only before the later await points, but then awaits makeBatchedEngine and engine.start without re-checking whether another loadModel/unloadModel has already advanced generationEpoch. If a second lifecycle call interleaves during those awaits, this stale invocation can still write self.engine, planner state, and watchdog state afterward, resurrecting an engine that should have been superseded and leaving model state inconsistent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed — epoch revalidated at BatchScheduler.swift:148-153 (after makeBatchedEngine) and again at lines 155-159 (after engine.start). Stale invocations now call engine.stop() and bail.
| if output.finished || output.error != nil { | ||
| sawTerminal = true | ||
| // "abort"/non-nil error → .error; "stop"/"length"/nil → .info. | ||
| let isAbort = output.finishReason == "abort" || output.error != nil |
There was a problem hiding this comment.
Surface terminal engine errors instead of cancellation
This branch classifies every terminal output with a non-nil error as cancellation and emits only "request cancelled". When the engine terminates a request due to an internal/runtime failure (i.e., finishReason is not "abort" but error is populated), callers lose the real failure reason and telemetry misattributes server-side faults as cancels, which makes diagnosis and retry behavior incorrect.
Useful? React with 👍 / 👎.
| @@ -183,8 +158,7 @@ struct PerformanceLiveTests { | |||
| let scheduler = loaded.scheduler | |||
| defer { Task { await scheduler.unloadModel() } } | |||
There was a problem hiding this comment.
Await scheduler unload before leaving perf scenarios
The teardown here launches unloadModel() in a detached task, so the scenario can return before model shutdown is complete. In this live performance suite, subsequent cases may begin while previous unload is still draining, which introduces avoidable memory pressure and timing noise that can skew throughput/TTFT measurements.
Useful? React with 👍 / 👎.
…atchedEngine
Replaces the BatchGenerator-driven inference loop with the new
BatchedEngine orchestrator from mlx-swift-lm. Public surface of
BatchScheduler is preserved (ProviderLoop and StandaloneServer
unchanged); only internals swap.
What BatchedEngine gives us (vs BatchGenerator):
- Engine-owned step loop on its own DispatchQueue (no worker task)
- Auto-preemption with re-queue when KV budget exceeded
- Chunked cold prefill interleaved with decode (prefillStepSize=512,
maxNumBatchedTokens=8192) so running decode is not starved
- Per-request stop-sequence state machine (EOS + stopTokenIds +
tokenized stop strings)
- Per-request RequestOutputCollector with non-blocking get + producer
merge on backpressure
- SamplingParams support: temperature, topP, topK, minP, seed,
repetitionPenalty, presencePenalty, frequencyPenalty
- Auto Memory.clearCache() after 8 idle steps (M4 IOKit panic
mitigation)
- First-class cancellation (abortRequest emits terminal RequestOutput
immediately, scheduler frees slot on next step)
Migration design decisions:
- Prefix cache OFF (prefixCacheConfig: nil, prefixCache: nil) with
inline TB-007 security comment. Cross-tenant data persistence risk;
flipping requires a fresh threat-model review.
- MTP OFF (mtpEnabled: false).
- KV budget: ours only. SchedulerConfig.maxKVCacheTokens = 0
(unlimited). Engine never preempts; our byte-level kvBudget +
BatchQueuePlanner are the sole gates. Single source of truth.
- Adaptive cap (AdaptiveBatchCapPolicy) propagates to engine via the
Scheduler.setMaxNumSeqs(_:) API (companion upstream PR #27, now
merged on mlx-swift-lm main).
- Pre-tokenize at submit time via existing tk.inner.applyChatTemplate
and pass [Int] to engine via Request(prompt: tokens as AnyHashable).
Avoids double tokenization and avoids the engine's silent
role:content fallback on chat-template error.
- Distinct error strings: pending-queue 120s timeout emits
.error('request timed out waiting for capacity'); client cancel
emits .error('request cancelled'). Preserves operator
observability.
Kept from previous BatchScheduler (not in BatchedEngine):
- KV-bytes-per-token estimation from config.json (GQA, hybrid, KV
sharing, recurrent layers)
- tokenBudgetMax derived from ProcessInfo.physicalMemory +
MLX.GPU.activeMemory
- GlobalKVCacheBudget (process-wide byte reservation across loaded
models)
- BatchQueuePlanner admission + 120s pending-queue timeout
- AdaptiveBatchCapPolicy + TPS EWMA
- GPUEnforcement.requireMetal()
- capacity()/backendCapacity() heartbeat shape
- Public AsyncStream<GenerationEvent> contract
Submodule bump:
- libs/mlx-swift-lm: d164323f -> 096e792 (upstream main, includes
BOTH PR #26 'Add OpenAI-compatible inference server' (MLXLMServer)
AND PR #27 'feat(scheduler): add runtime setMaxNumSeqs(_:)').
- Provider-swift now references the merged mainline commit, not a
feature-branch tip. MLXLMServer is linked transitively but not yet
consumed by provider-swift code (planned for a separate follow-up
PR replacing StandaloneServer with MLXOpenAIService).
Package.swift bump:
- hummingbird exact 2.22.0 -> exact 2.23.0 to satisfy mlx-swift-lm's
new MLXLMServer target which declares from: 2.23.0. hummingbird-
websocket 2.6.0 remains compatible (verified by swift package
resolve).
Tests:
- ContinuousBatchingLiveTests rewritten to drive BatchedEngine
directly (still bypassing BatchScheduler). Sequence-equivalence
invariants for eviction/admission preserved.
- PerformanceLiveTests bracket repointed to BatchedEngine; header
note added re: baseline numbers needing re-measurement.
- BatchSchedulerEngineIntegrationTests (new, +201 LOC): 4 non-live
GenerationEvent mapping tests + 2 live (env-gated) integration
tests covering submit -> chunk -> info -> finish and cancel ->
error -> finish.
- RowSamplersTests and BatchKVCacheTests kept verbatim.
Verification:
swift build (provider-swift): clean (only pre-existing MLX.GPU.*
deprecation warnings)
swift test (provider-swift, non-live): 213/213 pass (Swift Testing
+ XCTest, 19 suites); 2 live tests
auto-skipped without
DARKBLOOM_LIVE_MLX_TESTS=1.
Live MLX tests still recommended on prod model before merge:
cd provider-swift
DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter ContinuousBatchingLiveTests
DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter BatchSchedulerEngineIntegrationTests
DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter PerformanceLiveTests
Net LOC delta:
BatchScheduler.swift: -56 net (-428 / +372)
ContinuousBatchingLiveTests.swift: +93 net
PerformanceLiveTests.swift: +44 net
BatchSchedulerEngineIntegrationTests.swift: +201 (new)
ProviderLoop.swift, StandaloneServer.swift: untouched
cc8c973 to
512fa03
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
… MTP (#1282) * perf(mimo): default-on decode kernels and target-only adaptive serial MTP Pin mlx-swift-lm to the stack that enables the exact MiMo short-forward decode kernels by default and adds `CBv2MTPConfig.allowsAdaptiveSerialRounds`. - Forward the three kernel rollbacks (`DARKBLOOM_MIMO_FUSED_DECODE_NORMS`, `DARKBLOOM_MIMO_DECODE_EXPERTS`, `DARKBLOOM_MIMO_DECODE_ROUTER_GEMV`, `0`/`false`/`no`/`off`) to the launchd provider job, so an installed provider can restore the stock path. - Build every native MiMo MTP config through `nativeMiMoMTPConfig`, which keeps adaptive plans target-only under serial-target scoring. Each serial draft column costs one ordinary target forward, so those rounds could only slow decode (25-27 tok/s when the controller locked onto depth 3). MTP stays constructed and active with live assistant history; the rectangular opt-in keeps adaptive depth. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(mimo): pin mlx-swift-lm main 1ee8675a mlx-swift-lm main now contains #206, #207 and #219 (landed through #246) and #245. Pin it instead of the stacked SDK branch commit. The pinned tree is identical to the SDK validated with this stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…for reuse (#1299) * fix(mimo): reuse SSD prefix-cache hits and report cached tokens only for reuse Every native MiMo V2.6 SSD prefix-cache hit was discarded. The bridge stages a checkpoint under a placeholder engine request ID and mints the real ID just before submit; the SDK's native import check compared engine IDs, so each staged checkpoint was refused (`unsupportedConsumer`). The request prefilled its whole prompt again and the coordinator received a skipped lookup. - Pin mlx-swift-lm to the receipt-bound native stage check. - EngineV2RequestUsageSignal: client-facing cached tokens (standalone usage and the provider SSE splice) now count only an actual hit. A matched checkpoint whose adoption failed or was skipped used to report its matched tokens, which hid this bug locally. Coordinator usage already came from the resolved lookup and is unchanged. Tests: the native MiMo complete-prefix gate gains a bridge-level repeat (`testNativeCompletePrefixONReusesThePublishedBoundaryThroughTheBridge`): the second submission of the same prompt must adopt the published boundary with a resolved hit, saved prefill and byte-identical text. The existing gates only checked that the first submission published. PrefixCacheReceiptTests pins the cached-token report for a failed adoption. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(mimo): pin mlx-swift-lm main 1ee8675a mlx-swift-lm main now contains #206, #207 and #219 (landed through #246) and #245. Pin it instead of the stacked SDK branch commit. The pinned tree is identical to the SDK validated with this stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* perf(mimo): default-on decode kernels and target-only adaptive serial MTP Pin mlx-swift-lm to the stack that enables the exact MiMo short-forward decode kernels by default and adds `CBv2MTPConfig.allowsAdaptiveSerialRounds`. - Forward the three kernel rollbacks (`DARKBLOOM_MIMO_FUSED_DECODE_NORMS`, `DARKBLOOM_MIMO_DECODE_EXPERTS`, `DARKBLOOM_MIMO_DECODE_ROUTER_GEMV`, `0`/`false`/`no`/`off`) to the launchd provider job, so an installed provider can restore the stock path. - Build every native MiMo MTP config through `nativeMiMoMTPConfig`, which keeps adaptive plans target-only under serial-target scoring. Each serial draft column costs one ordinary target forward, so those rounds could only slow decode (25-27 tok/s when the controller locked onto depth 3). MTP stays constructed and active with live assistant history; the rectangular opt-in keeps adaptive depth. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(mimo): exact rectangular MTP verification by default Pin mlx-swift-lm to the exact rectangular verification stack (row-exact multi-row affine projection, fused norms inside the scalar-dense verifier, scalar-dense default with a guard against drafting through the bulk trunk). - `nativeMiMoVerificationMode` selects rectangular verification by default. A rollback of `DARKBLOOM_MIMO_RECTANGULAR_VERIFY` or of the SDK's scalar-dense switch selects serial-target scoring; the provider never selects the bulk rectangular trunk, whose reductions differ from serial decode. - The native paged profile keeps serial-target MTP independently of the contiguous default. - LaunchAgent forwards the three verification rollbacks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(mimo): pin mlx-swift-lm main 1ee8675a mlx-swift-lm main now contains #206, #207 and #219 (landed through #246) and #245. Pin it instead of the stacked SDK branch commit. The pinned tree is identical to the SDK validated with this stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Swaps `BatchScheduler` internals from the low-level `MLXLMCommon.BatchGenerator` to the new `MLXLMCommon.BatchedEngine` orchestrator. Public surface of `BatchScheduler` is preserved — `ProviderLoop`, `StandaloneServer`, `OpenAIFormatter`, and `LocalTokenizerLoader` are untouched.
What BatchedEngine gives us
Compared to `BatchGenerator` (caller-driven `while gen.hasWork { gen.next() }` loop inside a `container.perform` actor hop):
Migration design decisions
Kept from previous BatchScheduler (not in BatchedEngine)
Race-safety audit (done)
Pre-implementation audit confirmed only ONE production code path drove the model forward outside `BatchScheduler` — the deleted `stepEngine` itself. After migration, `git grep "container.perform"` in `provider-swift/Sources/` returns three sites: `BatchScheduler.loadModel` snapshot pass (metadata-only, runs before `engine.start()`), the engine construction inside `loadModel` (runs once), and `ModelBenchmark` (separate container, doesn't start engine). No concurrent model access after engine start.
Verification
```
$ swift build (provider-swift)
PASS (only pre-existing MLX.GPU.* deprecation warnings)
$ swift test (provider-swift, full non-live suite)
234/234 pass (213 Swift Testing + 21 XCTest, 19 suites)
2 live tests auto-skipped (env-gated)
```
Live MLX tests recommended before merge
`PerformanceLiveTests` is a smoke gate (`#expect(tps > 0)`); the header comment notes baseline TPS numbers must be re-measured against `BatchedEngine` before being used as regression thresholds.
Net LOC
Submodule bump
`libs/mlx-swift-lm`: `d164323f` → `90811a35` (feature-branch tip of Layr-Labs/mlx-swift-lm#27 — `feat(scheduler): add runtime setMaxNumSeqs(_:)`). Once that upstream PR merges, the pointer here will be advanced to the merged `main` commit.
Acknowledged trade-offs (deferred, not blockers)
Audit / review trail
Need help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.