Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
18 changes: 17 additions & 1 deletion .github/workflows/swift.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,23 @@ jobs:
xcodebuild test-without-building \
-scheme mlx-swift-lm-Package \
-destination 'platform=macOS' \
-skipPackagePluginValidation -skipMacroValidation
-skipPackagePluginValidation -skipMacroValidation \
-skip-testing:MLXLMTests/SchedulerUpgradeParityTests

# The upgrade-parity suite pauses a decode thread mid-forward (a
# blocking gate) and releases it only after the second request makes
# scheduler-actor progress. Under the full bundle's concurrency the
# cooperative thread pool can starve that hop — the pause never
# releases and the whole test process wedges until the runner kills
# it, taking every in-flight test down with it. Run the suite in its
# own quiet invocation instead (skipped from the bundle above).
- name: Run scheduler upgrade parity suite (isolated)
run: |
xcodebuild test-without-building \
-scheme mlx-swift-lm-Package \
-destination 'platform=macOS' \
-skipPackagePluginValidation -skipMacroValidation \
-only-testing:MLXLMTests/SchedulerUpgradeParityTests

# On failure, ship the .xcresult bundles (crash reports included) so a
# test-runner death that prints nothing to stdout — a wedged process, a
Expand Down
249 changes: 196 additions & 53 deletions Libraries/MLXLMCommon/Batching/EngineDriver.swift

Large diffs are not rendered by default.

504 changes: 425 additions & 79 deletions Libraries/MLXLMCommon/Batching/InferenceScheduler.swift

Large diffs are not rendered by default.

25 changes: 24 additions & 1 deletion Libraries/MLXLMCommon/Batching/LRUPromptCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,21 @@ public final class LRUPromptCache: PromptCaching {
input: LMInput,
parameters: GenerateParameters,
model: any LanguageModel
) -> Bool {
inputSupportsPromptCache(input: input, parameters: parameters)
&& modelSupportsPromptCache(model: model, parameters: parameters)
}

/// The input/parameters half of ``canUsePromptCache(input:parameters:model:)``.
///
/// Kept separate from the model half so an actor can evaluate it without
/// passing the non-`Sendable` `LMInput` through one of its isolated
/// methods: a request bound for a `sending` hand-off (`EngineDriver.submit`)
/// must stay region-disconnected from the actor, and a plain isolated-method
/// parameter would merge it into the actor's region.
static func inputSupportsPromptCache(
input: LMInput,
parameters: GenerateParameters
) -> Bool {
guard input.image == nil, input.video == nil, input.audio == nil else { return false }
// Masked / pre-batched inputs prefill at mask-derived positions that
Expand All @@ -447,7 +462,15 @@ public final class LRUPromptCache: PromptCaching {
guard input.text.mask == nil else { return false }
let tokens = input.text.tokens
guard tokens.ndim == 1 || (tokens.ndim == 2 && tokens.dim(0) == 1) else { return false }
guard parameters.kvBits == nil, parameters.kvScheme == nil else { return false }
return parameters.kvBits == nil && parameters.kvScheme == nil
}

/// The model half of ``canUsePromptCache(input:parameters:model:)``:
/// policy opt-in plus a compatibility probe of the model's cache topology.
static func modelSupportsPromptCache(
model: any LanguageModel,
parameters: GenerateParameters
) -> Bool {
guard model.defaultPromptCachePolicy == .exact else { return false }
return isCacheCompatible(model.newCache(parameters: parameters))
}
Expand Down
39 changes: 35 additions & 4 deletions Libraries/MLXLMCommon/Batching/RowSamplers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ public func makeRowProcessorSource(_ parameters: GenerateParameters) -> RowProce
///
/// Behavior, matching the single-request `TopPSampler` in `Evaluate.swift`
/// (which mirrors `mlx_lm.sample_utils.make_sampler`):
/// - `temperature <= 0`: return `greedySampler` (no RNG, deterministic).
/// - `temperature > 0`: optionally mask the unscaled logprobs to top-P
/// - `temperature == 0`: return `greedySampler` (no RNG, deterministic).
/// ONLY exact zero is greedy — `GenerateParameters.sampler()` treats a
/// negative temperature as a real divisor (sampling the inverted
/// distribution), so the batched path must too.
/// - otherwise: optionally mask the unscaled logprobs to top-P
/// then min-P then top-K, scale by `1/temperature`, and sample
/// categorically. The order (filter first, temperature at the draw)
/// means one batched row reproduces single-stream sampling for the
Expand All @@ -67,18 +70,25 @@ public func makeRowProcessorSource(_ parameters: GenerateParameters) -> RowProce
/// - topK: number of top tokens to keep (0 = disabled).
/// - minP: min-P threshold relative to the most likely token (0 = disabled).
/// - seed: optional RNG seed; nil uses MLX's global PRNG.
/// - advancedBy: number of draws the request already consumed elsewhere
/// (the single→batch upgrade path); the seeded key chain is
/// fast-forwarded past them so the next draw CONTINUES the sequence
/// instead of bit-identically replaying it. 0 (a fresh request) is a
/// no-op.
public func makeRowSampler(
temperature: Float = 0.0,
topP: Float = 1.0,
topK: Int = 0,
minP: Float = 0.0,
seed: UInt64? = nil
seed: UInt64? = nil,
advancedBy priorDraws: Int = 0
) -> RowSampler {
if temperature <= 0 {
if temperature == 0 {
return greedySampler
}

let keyHolder = SamplerKeyHolder(seed: seed)
keyHolder.advance(by: priorDraws)
let temp = temperature
let p = topP
let k = topK
Expand Down Expand Up @@ -210,4 +220,25 @@ final class SamplerKeyHolder: Sendable {
return drawKey
}
}

/// Fast-forward the key chain by `draws` splits without yielding keys,
/// exactly as if ``next()`` had been called `draws` times. Because the
/// chain is bit-identical to the single path's seeded `RandomState`
/// (see ``next()``), the single→batch upgrade uses this to make a fresh
/// holder CONTINUE the sequence at the draw the single iterator would
/// have consumed next, instead of replaying draws 1..N. Unseeded holders
/// stay keyless. No-op for `draws <= 0`.
func advance(by draws: Int) {
guard draws > 0 else { return }
key.withLockUnchecked { current in
guard var value = current else { return }
for _ in 0 ..< draws {
value = MLXRandom.split(key: value).0
}
// Materialize the advanced state so the skipped splits do not
// accumulate as one deep lazy graph evaluated at the next draw.
eval(value)
current = value
}
}
}
13 changes: 12 additions & 1 deletion Libraries/MLXLMCommon/Batching/SchedulerRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,24 @@ struct SchedulerRequest {
/// Optional wired-memory ticket.
var wiredMemoryTicket: WiredMemoryTicket?

/// Whether ``PromptCachePolicy`` permits prompt-cache use for this
/// request (`LRUPromptCache.canUsePromptCache`), decided ONCE by the
/// scheduler at submit and threaded through so the driver's prefix fetch
/// AND its write-back flags both respect policy — no path re-derives (or
/// silently ignores) it. Defaults to `true` for callers that construct
/// requests directly (tests), preserving the opt-in-by-`promptCache`
/// behavior; the scheduler always passes its computed decision.
var cacheEligible: Bool

init(
input: LMInput,
parameters: GenerateParameters,
inputTokens: [Int],
modelName: String,
promptCache: (any PromptCaching)? = nil,
promptCacheSalt: UInt64 = 0,
wiredMemoryTicket: WiredMemoryTicket? = nil
wiredMemoryTicket: WiredMemoryTicket? = nil,
cacheEligible: Bool = true
) {
self.input = input
self.parameters = parameters
Expand All @@ -50,5 +60,6 @@ struct SchedulerRequest {
self.promptCache = promptCache
self.promptCacheSalt = promptCacheSalt
self.wiredMemoryTicket = wiredMemoryTicket
self.cacheEligible = cacheEligible
}
}
12 changes: 12 additions & 0 deletions Libraries/MLXLMCommon/ModelContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ public final class ModelContainer: Sendable {
self.promptCache = promptCache
}

deinit {
// Release the scheduler binding so a future container can attach:
// without an explicit detach the scheduler stays bound to this
// container's ObjectIdentifier forever — and a recycled identity
// could even pass its owner check and be served the dead container's
// retained context. `deinit` is nonisolated, so capture the identity
// and the scheduler reference before hopping to the scheduler actor.
guard let scheduler else { return }
let owner = ObjectIdentifier(self)
Task { await scheduler.detach(owner: owner) }
Comment on lines +102 to +104

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make scheduler detachment deterministic before reuse

If client code releases one container and immediately calls generate on a new container sharing the scheduler, this unstructured task is not guaranteed to run before the new container checks currentOwner. The new call can therefore nondeterministically see the dead container's owner and throw schedulerAlreadyAttached, despite this change intending to make scheduler reuse possible. Provide an awaitable/ordered release mechanism rather than relying solely on a deinit-scheduled task.

Useful? React with 👍 / 👎.

}

/// Perform an action on the model and/or tokenizer. Callers _must_ eval any `MLXArray` before returning as
/// `MLXArray` is not `Sendable`.
@available(*, deprecated, message: "prefer perform(_:) that uses a ModelContext")
Expand Down
162 changes: 162 additions & 0 deletions Tests/MLXLMTests/InferenceSchedulerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,14 @@ struct CacheMigrationTests {
#expect(InferenceScheduler.migrateCaches([ChunkedKVCache()]) == nil)
}

@Test("An empty topology (cacheless model) does not migrate")
func emptyTopologyReturnsNil() {
// BatchGenerationEngine.init rejects models with no per-layer caches;
// a vacuous [] here would approve an upgrade the engine then refuses,
// truncating the running request mid-generation.
#expect(InferenceScheduler.migrateCaches([]) == nil)
}

@Test("A mixed list with one unsupported layer fails the whole migration")
func mixedListFailsClosed() {
let mixed: [KVCache] = [KVCacheSimple(), QuantizedKVCache()]
Expand Down Expand Up @@ -250,6 +258,13 @@ struct SchedulerValueTests {
// row.
#expect(InferenceScheduler.rowSampler(for: params) == nil)

// Negative temperature is NOT greedy: single-path parity —
// GenerateParameters.sampler() special-cases only temperature == 0,
// so a negative divisor samples the inverted distribution there and
// must do the same when batched.
params.temperature = -1
#expect(InferenceScheduler.rowSampler(for: params) != nil)

// Non-zero temperature yields a real sampler.
params.temperature = 0.7
let sampler = InferenceScheduler.rowSampler(for: params)
Expand Down Expand Up @@ -281,6 +296,137 @@ struct SchedulerValueTests {
}
}

// MARK: - Seeded sampler PRNG continuity

@Suite("SamplerKeyHolder PRNG continuity")
struct SamplerKeyHolderTests {

@Test("advance(by: n) matches a fresh holder that consumed n draws")
func advanceMatchesConsumedDraws() throws {
// The upgrade path fast-forwards a fresh holder past the draws the
// single iterator already consumed; draw n+1 must be bit-identical
// to the chain a live holder would continue.
let consumed = SamplerKeyHolder(seed: 42)
for _ in 0 ..< 5 {
_ = consumed.next()
}
let advanced = SamplerKeyHolder(seed: 42)
advanced.advance(by: 5)

let expected = try #require(consumed.next())
let actual = try #require(advanced.next())
#expect(expected.asArray(UInt32.self) == actual.asArray(UInt32.self))
}

@Test("advance(by: 0) leaves the chain at its first draw")
func advanceZeroIsIdentity() throws {
let fresh = SamplerKeyHolder(seed: 7)
let advanced = SamplerKeyHolder(seed: 7)
advanced.advance(by: 0)

let expected = try #require(fresh.next())
let actual = try #require(advanced.next())
#expect(expected.asArray(UInt32.self) == actual.asArray(UInt32.self))
}

@Test("Unseeded holder stays keyless through advance")
func unseededAdvanceStaysNil() {
let holder = SamplerKeyHolder(seed: nil)
holder.advance(by: 3)
// nil key = "use MLX's global PRNG"; advancing must not invent one.
#expect(holder.next() == nil)
}
}

// MARK: - Attach / detach lifecycle

@Suite("Scheduler attach lifecycle")
struct SchedulerAttachLifecycleTests {

/// Stand-in for a `ModelContainer`: attach/detach key purely on
/// `ObjectIdentifier`, so any class instance works as an owner.
private final class Owner {}

private func makeContext(name: String) -> ModelContext {
ModelContext(
configuration: ModelConfiguration(id: name),
model: UnusedLanguageModel(),
processor: StandInUserInputProcessor(),
tokenizer: TestTokenizer(vocabularySize: 16)
)
}

@Test("Detach releases the owner; a new owner attaches and replaces the context")
func detachThenReattachReplacesContext() async throws {
let scheduler = InferenceScheduler()
// Keep both owners alive for the whole test so their identities can
// never alias through address reuse.
let a = Owner()
let b = Owner()
let ownerA = ObjectIdentifier(a)
let ownerB = ObjectIdentifier(b)

let attachedA = await scheduler.attach(
owner: ownerA,
context: SendableBox(makeContext(name: "test/model-a")),
promptCache: nil
)
#expect(attachedA)
#expect(await scheduler.currentOwner == ownerA)
#expect(await scheduler.attachedModelName == "test/model-a")

// A different container cannot steal the binding while A owns it.
let stolen = await scheduler.attach(
owner: ownerB,
context: SendableBox(makeContext(name: "test/model-b")),
promptCache: nil
)
#expect(stolen == false)

// Detach from the wrong owner is a no-op.
await scheduler.detach(owner: ownerB)
#expect(await scheduler.currentOwner == ownerA)

// Detach from the bound owner releases the binding; the context is
// retained only for in-flight work.
await scheduler.detach(owner: ownerA)
#expect(await scheduler.currentOwner == nil)

// A new owner now attaches — and REPLACES the retained context, so
// its requests never run on the dead container's model.
let attachedB = await scheduler.attach(
owner: ownerB,
context: SendableBox(makeContext(name: "test/model-b")),
promptCache: nil
)
#expect(attachedB)
#expect(await scheduler.currentOwner == ownerB)
#expect(await scheduler.attachedModelName == "test/model-b")
}

@Test("Same-owner re-attach keeps the first context")
func sameOwnerReattachIsIdempotent() async throws {
let scheduler = InferenceScheduler()
let a = Owner()
let ownerA = ObjectIdentifier(a)

#expect(
await scheduler.attach(
owner: ownerA,
context: SendableBox(makeContext(name: "test/model-a")),
promptCache: nil
))
#expect(
await scheduler.attach(
owner: ownerA,
context: SendableBox(makeContext(name: "test/model-a2")),
promptCache: nil
))
// The first-bound context stays (the second box is not consumed).
#expect(await scheduler.attachedModelName == "test/model-a")
}
}

// MARK: - Helpers

private struct CollectedGeneration {
Expand Down Expand Up @@ -319,3 +465,19 @@ private func collectTokenGenerations(_ stream: AsyncStream<TokenGeneration>) asy
}
return CollectedTokenGeneration(tokens: tokens, info: info)
}

/// A structurally-conforming `LanguageModel` for lifecycle tests that never
/// run a decode. `callAsFunction` traps to make accidental use obvious
/// (mirrors `NoopLanguageModel` in the ModelContainer batching tests).
private final class UnusedLanguageModel: Module, LanguageModel, KVCacheDimensionProvider {
let vocabularySize = 16
var kvHeads: [Int] { [1] }

func prepare(_ input: LMInput, cache: [any KVCache], windowSize: Int?) throws -> PrepareResult {
.tokens(input.text)
}

func callAsFunction(_ inputs: MLXArray, cache: [any KVCache]?) -> MLXArray {
fatalError("UnusedLanguageModel must not be run by lifecycle tests")
}
}
Loading