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
10 changes: 10 additions & 0 deletions changelog.d/deadline-decode-rate-min-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### A short reply no longer moves the deadline decode rate once a longer one has

Deadline admission's decode rate now follows the published rate's rule once a
request that generated at least 32 tokens (or a calibration cell) has moved it:
from then on a shorter request leaves it unchanged. Until then, on a new slot
or after the decode evidence expired, every completed request moves it as
before, so a slot that serves only short replies keeps a rate that follows them
and is priced for deadline requests as before. The heartbeat's
`observed_decode_tps`, the rate's age and `performance_measurements` are
unchanged.
11 changes: 11 additions & 0 deletions changelog.d/new-slot-deadline-decode-cadence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### A new slot prices deadline requests from the requests it is decoding

Before its first completed request, a slot refused every request with a
first-content deadline that arrived while another request was decoding: it had
no decode rate (`decode_rate_unavailable`). It now prices that decode work at
the slowest delivered cadence among the requests decoding on it, once one has
8 tokens after its first, charged per row, and admits the request only if the
projection meets the deadline. With no such request, or with
`DARKBLOOM_TTFT_ADMISSION_FIXES=0`, it refuses as before. The
heartbeat's `observed_decode_tps` and `performance_measurements` are
unchanged.
9 changes: 4 additions & 5 deletions changelog.d/published-decode-rate-min-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ request that generated at least 32 tokens, matching the coordinator's own
`completion_tokens >= 32` convention. A shorter request's rate is mostly its
first steps or its tail: one short reply could pull a Mac that measured 80–100
tok/s down to about 11, and routing then ranked it behind slower Macs. Shorter
requests still feed the deadline decode rate, the rate's age and
`performance_measurements` exactly as before, so deadline admission and the
idle age are unchanged. A slot that has served only short replies publishes no
decode rate, as a slot with no samples does, and the coordinator prices it from
its profile or the fleet.
requests still feed the rate's age and `performance_measurements` exactly as
before, so the idle age is unchanged. A slot that has served only short replies
publishes no decode rate, as a slot with no samples does, and the coordinator
prices it from its profile or the fleet.
22 changes: 17 additions & 5 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3052,11 +3052,23 @@ only on a request that generated at least 32 tokens
`completion_tokens >= 32` convention; `updatePublishedDecodeTps` keeps the same
EWMA and restart rule over those samples): one short reply measures mostly its
first steps or tail and could pull a Mac measuring 80–100 tok/s down to about
11. A shorter request still feeds the deadline decode rate, the rate's age and
`performance_measurements`, as before, so a slot that serves only short
replies is still priced for deadline admission and never ages out while
serving; it publishes no rate until a longer one. Deadline admission is
unchanged: it charges the measured step shape. The projection also mirrors the
11. A shorter request still feeds the rate's age and `performance_measurements`,
as before, so a slot that serves only short replies never ages out while
serving; it publishes no rate until a longer one. The deadline decode rate
(`observedDecodeTpsEwma` and its measured step) follows the same 32-token rule
once a counted request (32 tokens or more, or calibration) has moved it since
it last restarted (`decodeEwmaCounted`, reset with it on calibration or when
the decode evidence expired). Until then every completed request moves it as
before, so a slot that serves only short replies keeps a rate that follows them
and is still priced for deadline admission. Before that first sample, a deadline
request beside decoding rows is priced at the slowest delivered cadence among
requests decoding on the slot now (tokens after the first emission over the
time since the first token, once a request has 8 such tokens;
`EngineV2Bridge.liveDecodeCadence`), charged per row; with no such request, or
with `DARKBLOOM_TTFT_ADMISSION_FIXES=0`, the decode rate stays unavailable and
the request is refused as before. None of
this reaches the heartbeat. Deadline admission otherwise charges the measured
step shape. The projection also mirrors the
live MTP plan's depth gates
(`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift`,
`CBv2MTPRoundDriver.speculationDepthCeiling`): a step with more decode rows
Expand Down
6 changes: 5 additions & 1 deletion docs/developer/serving-performance-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ separates exactly two conversions. The idle age of the heartbeat's decode rate
changes only the `observed_decode_tps` an idle slot advertises to routing, not
admission, measurements or any profile.
The rate's age on the heartbeat (`observed_decode_tps_age_ms`) needs none
either: it is informational and changes no rate, admission or profile.
either: it is informational and changes no rate, admission or profile. Nor does
the decode rate a slot uses before its first completed request (the slowest
delivered cadence of requests decoding on it, charged per row; see
[deadlines](../architecture/inference.md#deadlines)): a request carrying a
reviewed calibration never takes it.
Profile qualification is separate work required to introduce a measured
prediction-error envelope.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,14 @@ extension EngineV2Bridge {
}
guard prefillRate != nil || calibration != nil || nativeMedia else { return nil }
// The decode EWMA is a per-request rate: charge one measured step per
// projected batch step, not every row's tokens.
// projected batch step, not every row's tokens. Before its first
// sample, requests decoding here now give the rate.
let perRequestRate = ewmaInitialized && observedDecodeTpsEwma.isFinite && observedDecodeTpsEwma > 0
? observedDecodeTpsEwma : nil
let decode = DeadlineAdmissionFixes.decodeCharge(
perRequestRate: ewmaInitialized && observedDecodeTpsEwma.isFinite && observedDecodeTpsEwma > 0
? observedDecodeTpsEwma : nil,
measuredStep: observedDecodeStep, enabled: admissionFixes, calibrated: calibration != nil)
perRequestRate: perRequestRate,
measuredStep: observedDecodeStep, enabled: admissionFixes, calibrated: calibration != nil,
liveRate: admissionFixes && perRequestRate == nil && calibration == nil ? liveDecodeCadence() : nil)

return CBv2FirstTokenDeadlineAdmission(
deadline: deadline.instant,
Expand All @@ -135,6 +138,24 @@ extension EngineV2Bridge {
decodeRateShape: decode.shape)
}

/// The fewest tokens after its first emission a decoding request needs
/// before its cadence prices deadline admission.
static let minimumLiveDecodeTokens = 8

/// The slowest delivered cadence among requests decoding on this slot now:
/// tokens after the first emission over the time since the first token,
/// as `recordFinish` measures a delivered rate. nil when no request has
/// `minimumLiveDecodeTokens` yet. Waiting between tokens only lowers it.
func liveDecodeCadence(now: ContinuousClock.Instant = .now) -> Double? {
active.values.compactMap { state -> Double? in
let tokens = state.completionTokens - state.firstEmissionTokens
guard let firstTokenAt = state.firstTokenAt, tokens >= Self.minimumLiveDecodeTokens else { return nil }
let seconds = WedgeMonitor.seconds(now - firstTokenAt)
let rate = Double(tokens) / seconds
return seconds > 0 && rate.isFinite && rate > 0 ? rate : nil
}.min()
}

/// Nothing but `requestID` occupies this engine and, through the shared
/// service budget, no other model's request or device activity holds the Mac.
private func macIdle(except requestID: String?) -> Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,9 @@ extension EngineV2Bridge {
/// The fewest generated tokens whose decode rate may move the published
/// rate (`observed_decode_tps`); the coordinator's own
/// `completion_tokens >= 32` convention. A shorter request's rate is mostly
/// its first steps or its tail. It still feeds the deadline decode rate,
/// the rate's age and the performance measurements.
/// its first steps or its tail. It still feeds the rate's age and the
/// performance measurements, and moves the deadline decode rate until a
/// counted sample has.
static let minimumPublishedDecodeTokens = 32

static func setsPublishedDecodeRate(completionTokens: Int) -> Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ struct EngineRateObservation: Sendable {
var decodeShape = CBv2DecodeRateShape(batchRows: 1)
/// Decode only: false for a completed request that generated fewer than
/// `EngineV2Bridge.minimumPublishedDecodeTokens` tokens. Such a sample
/// still feeds every estimate except the published rate.
/// never moves the published rate, and moves the deadline decode rate only
/// while no counted sample has moved it since it last restarted; it feeds
/// the performance measurements and their age as before.
var setsPublishedDecode = true
}

Expand Down Expand Up @@ -58,8 +60,15 @@ extension EngineV2Bridge {
if isDecode && value.aggregate {
if calibration || performanceMeasurements.rateExpiration("decode").map({ value.at > $0 }) == true {
ewmaInitialized = false
decodeEwmaCounted = false
}
// Short replies move the deadline rate as before until a counted
// sample has; from then on only counted samples move it.
let counted = calibration || value.setsPublishedDecode
if counted || !decodeEwmaCounted {
updateDecodeTpsEwma(value.tps, shape: value.decodeShape)
decodeEwmaCounted = decodeEwmaCounted || counted
}
updateDecodeTpsEwma(value.tps, shape: value.decodeShape)
if calibration || value.setsPublishedDecode {
updatePublishedDecodeTps(value.tps, at: value.at, restart: calibration)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,9 @@ public actor EngineV2Bridge {
var generationRequestsTotal: Int64 = 0
var observedDecodeTpsEwma: Double = 0
var ewmaInitialized = false
/// A counted sample (calibration, or `minimumPublishedDecodeTokens` or
/// more) has moved `observedDecodeTpsEwma` since it last restarted.
var decodeEwmaCounted = false
/// The published decode rate (`updatePublishedDecodeTps`) and the newest
/// sample behind it.
var publishedDecodeTps: Double = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ enum DeadlineAdmissionFixes {
/// per-row conversion is its only fallback, so calibrated policies keep it.
/// The step is smoothed and reset with the per-request EWMA, which alone
/// says whether decode evidence exists.
///
/// Without that evidence an uncalibrated policy with the fixes on takes
/// `liveRate`, the cadence of requests decoding on this slot now
/// (`EngineV2Bridge.liveDecodeCadence`), charged per row; nil, or the fixes
/// off, still leaves the decode rate unavailable.
static func decodeCharge(
perRequestRate: Double?, measuredStep: MeasuredDecodeStep, enabled: Bool, calibrated: Bool
perRequestRate: Double?, measuredStep: MeasuredDecodeStep, enabled: Bool, calibrated: Bool,
liveRate: Double? = nil
) -> (rate: Double?, shape: CBv2DecodeRateShape?) {
if enabled, !calibrated, perRequestRate == nil, let liveRate { return (liveRate, nil) }
guard enabled, !calibrated else { return (perRequestRate, nil) }
return (perRequestRate == nil ? nil : measuredStep.tokensPerSecond, measuredStep.shape)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import Foundation
import MLX
@testable import MLXLMCommon
import Testing
@testable import ProviderCore

/// A slot without a completed decode sample prices a deadline request beside a
/// decoding row from the cadence of the requests decoding on it now. The real
/// engine projects the queue: one row is frozen mid-decode, so the new prompt's
/// steps carry decode work. The bridge's decoding rows are set directly.
@Suite("New-slot decode cadence admission", .serialized)
struct NewSlotDecodeCadenceAdmissionTests {
private struct Fixture {
let engine: EngineV2
let bridge: EngineV2Bridge
let decoder: AsyncStream<CBv2Event>

func release() async {
await bridge.removeDecodingRowsForTesting()
engine.loopForTesting.onEngineQueueSync {
engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil
}
for await _ in decoder {}
await bridge.shutdown()
}
}

/// One request has prefilled and decoded once; the loop then stops before
/// its next step. Prefill is priced at 1,000 tok/s; there is no decode sample.
private func makeFixture(admissionFixes: Bool = true) async throws -> Fixture {
let model = DeadlineAdmissionFixtureModel()
let engine = EngineV2(model: model, layerKinds: model.kinds,
backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20)),
cacheProvider: CBv2LayerCacheBank(layerKinds: model.kinds),
sampler: CBv2GreedySampler(), schedulerConfig: .init(
maxConcurrentRequests: 2, maxBatchedTokensPerStep: 64,
prefillChunkSize: 32, maxConcurrentPartialPrefills: 1,
maxWaiting: 4, enablePrefixCache: false))
engine.loopForTesting.onEngineQueueSync {
engine.loopForTesting.suspendStepExecutionAtCountForTesting = 2
}
let decoder = try engine.submit(.init(id: .init(910_001), promptTokens: [1], maxTokens: 64))
let deadline = ContinuousClock.now.advanced(by: .seconds(30))
while engine.stepCount < 2, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(5))
}
try #require(engine.stepCount == 2)
let bridge = EngineV2Bridge(engine: engine, modelId: "new-slot-fixture",
tokenizer: TokenizerHandle(PrefillStubTokenizer()), eosTokenIds: [],
prefillDeadlineMode: .enforce, admissionFixes: admissionFixes)
await bridge.updatePrefillTpsEwma(1_000, isolated: true)
#expect(await bridge.ewmaInitialized == false)
return Fixture(engine: engine, bridge: bridge, decoder: decoder)
}

private func submit(_ fixture: Fixture, id: UInt64, budgetMilliseconds: Int64) async throws
-> (CBv2FirstTokenDeadlineAdmission, CBv2FirstTokenDeadlineResult)
{
let policy = try #require(await fixture.bridge.firstTokenDeadlineAdmission(
deadline: .init(relativeBudgetMilliseconds: budgetMilliseconds),
isMultimodal: false))
let result = try await fixture.engine.submit(
.init(id: .init(id), promptTokens: Array(repeating: 2, count: 100), maxTokens: 1),
firstTokenDeadline: policy)
return (policy, result)
}

@Test("a new slot admits a deadline request beside a decoding row at that row's cadence")
func admitsAtLiveCadence() async throws {
let fixture = try await makeFixture()
// 20 tokens after the first in one second: 20 tok/s.
await fixture.bridge.addDecodingRowForTesting("decoding", tokensAfterFirst: 20, since: .seconds(1))
let (policy, result) = try await submit(fixture, id: 910_002, budgetMilliseconds: 10_000)
let rate = try #require(policy.conservativeDecodeTokensPerSecond)
#expect(rate > 19 && rate <= 20)
#expect(policy.decodeRateShape == nil, "a live cadence is charged per row")
guard case .admitted(let stream, .bounded(let work, _), _, _) = result else {
Issue.record("expected a priced admission, got \(result)")
await fixture.release()
return
}
#expect(work.decodeTokens > 0, "the projection carries the decoding row's work")
await fixture.release()
for await _ in stream {}
}

@Test("a new slot whose decoding rows' cadence predicts a miss refuses with a priced projection")
func refusesWhenCadencePredictsMiss() async throws {
let fixture = try await makeFixture()
// The slower row prices admission: 1 tok/s, not 100.
await fixture.bridge.addDecodingRowForTesting("fast", tokensAfterFirst: 100, since: .seconds(1))
await fixture.bridge.addDecodingRowForTesting("slow", tokensAfterFirst: 9, since: .seconds(9))
let (policy, result) = try await submit(fixture, id: 910_003, budgetMilliseconds: 1_000)
let rate = try #require(policy.conservativeDecodeTokensPerSecond)
#expect(rate > 0.9 && rate <= 1)
guard case .deadlineUnreachable(.bounded(let work, let duration)) = result else {
Issue.record("expected deadline_unreachable from a priced projection, got \(result)")
await fixture.release()
return
}
#expect(work.decodeTokens > 0)
#expect(duration > .seconds(1))
await fixture.release()
}

@Test("with no row past 8 tokens after its first the decode rate stays unavailable")
func noRowPastMinimumStaysUnavailable() async throws {
let fixture = try await makeFixture()
await fixture.bridge.addDecodingRowForTesting("young", tokensAfterFirst: 7, since: .seconds(1))
let (policy, result) = try await submit(fixture, id: 910_004, budgetMilliseconds: 10_000)
#expect(policy.conservativeDecodeTokensPerSecond == nil)
guard case .deadlineUnreachable(.unbounded(reason: .decodeRateUnavailable)) = result else {
Issue.record("expected decode_rate_unavailable, got \(result)")
await fixture.release()
return
}
await fixture.release()
}

@Test("with the admission fixes off a new slot's decode rate stays unavailable beside a decoding row")
func fixesOffStaysUnavailable() async throws {
let fixture = try await makeFixture(admissionFixes: false)
await fixture.bridge.addDecodingRowForTesting("decoding", tokensAfterFirst: 20, since: .seconds(1))
let (policy, result) = try await submit(fixture, id: 910_005, budgetMilliseconds: 10_000)
#expect(policy.conservativeDecodeTokensPerSecond == nil)
#expect(policy.decodeRateShape == nil)
guard case .deadlineUnreachable(.unbounded(reason: .decodeRateUnavailable)) = result else {
Issue.record("expected decode_rate_unavailable, got \(result)")
await fixture.release()
return
}
await fixture.release()
}
}

private extension EngineV2Bridge {
func addDecodingRowForTesting(_ id: String, tokensAfterFirst: Int, since: Duration) {
let firstTokenAt = ContinuousClock.now - since
active[Self.decodingRowPrefix + id] = ActiveRequestState(promptTokens: 1, maxTokens: 1_024,
completionTokens: tokensAfterFirst + 1, submittedAt: firstTokenAt,
firstTokenAt: firstTokenAt, firstEmissionTokens: 1)
}

static var decodingRowPrefix: String { "live-row-" }

func removeDecodingRowsForTesting() {
for id in active.keys where id.hasPrefix(Self.decodingRowPrefix) { active.removeValue(forKey: id) }
}
}
Loading
Loading