Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -91,35 +91,6 @@ enum EngineV2KVSizing {
return Int(min(remaining, UInt64(Int.max)))
}

/// Net a v2 engine's admission ceiling of the slot's MEASURED
/// engine-retained residency overhead — the shared MoE fused gate+up
/// cache the VLM text extraction eagerly builds (v0.7.3, PR#508
/// finding 2).
///
/// `engineKVBytesCapacity` derives the ceiling from WEIGHTS + reserves
/// BEFORE the engine build runs, but on a VLM-extracted Gemma slot the
/// build then materializes ~8–15 GiB of fused expert cache —
/// module-retained ACTIVE memory that behaves exactly like weights (the
/// pool reclaimer cannot touch it) yet appears in neither
/// `scheduler.modelWeightBytes` nor any parameter sum. An unadjusted
/// ceiling — and the heartbeat `active_token_budget_max` derived from
/// it — therefore over-advertises by exactly the cache size (~1.7× on
/// the incident's 64 GB/8-bit profile): the coordinator over-routes and
/// the shared KV gate (which sees the cache in live MLX `active`)
/// rejects the excess post-acceptance — a mild replay of the v0.7.2
/// black hole, mitigated only by coordinator-side cooldowns. Subtracting
/// the measured cache here keeps the engine's private ledger, the
/// heartbeat max, and the shared gate consistent. Clamps to 0 — a slot
/// whose cache consumed the whole KV budget falls back to legacy via
/// `makeProductionEngine`'s `noKVHeadroom` throw.
static func netOfEngineResidentOverhead(
_ baseCapacity: Int, overheadBytes: Int
) -> Int {
let base = max(0, baseCapacity)
let overhead = max(0, overheadBytes)
return base > overhead ? base - overhead : 0
}

/// CURRENT KV byte budget for an EXISTING v2 engine — the HEARTBEAT
/// figure, not an engine resize (round-3 PR#499 P2).
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,7 @@ public actor EngineV2Runtime {
/// from live inputs (`EngineV2KVSizing.liveEngineKVBytesBudget`).
public struct FleetKVContext: Sendable {
/// Σ resident model weights across ALL slots (v2 AND legacy),
/// including each bridge's own model — PLUS each slot's measured
/// engine-retained residency overhead (the shared MoE fused gate+up
/// cache a VLM extraction eagerly builds), which behaves like
/// weights for budget purposes but appears in no parameters() sum.
/// including each bridge's own model.
public let totalResidentWeightBytes: UInt64
/// Operator `memory_reserve_gb`, in bytes (see `EngineV2KVSizing`).
public let configReserveBytes: UInt64
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,10 @@ enum EngineV2VLMTextExtraction {

/// Result of one extraction: the CBv2-adapted text model (sharing the
/// wrapper's weight arrays) plus the parity probe's max |Δlogit| for the
/// slot factory's log line (nil when the parity gate was disabled), the
/// number of MoE layers whose fused gate+up cache is shared between
/// the wrapper and the extracted model (the v0.7.3 black-hole fix), and
/// the MEASURED total bytes of that fused cache — module-retained
/// active memory the slot factory must net out of the v2 engine's
/// weights-derived KV admission ceiling (PR#508 finding 2).
/// slot factory's log line (nil when the parity gate was disabled).
struct Extraction {
let model: Gemma4TextModel
let parityMaxAbsLogitDiff: Float?
let sharedFusedMoELayerCount: Int
let fusedMoECacheBytes: Int
}

/// Build an MLXLLM `Gemma4TextModel` over the weight arrays of a loaded
Expand Down Expand Up @@ -162,24 +155,7 @@ enum EngineV2VLMTextExtraction {
try skeleton.update(
parameters: ModuleParameters.unflattened(textWeights), verify: [.all])

// 4. Share the MoE fused gate+up caches (v0.7.3 — the 64 GB
// black-hole fix). `MLXLMCommon.SwitchGLU` lazily concatenates a
// fused copy of its gate+up expert weights on FIRST FORWARD and
// retains it on the module (~540 MB/layer, ~15 GiB model-wide on
// gemma-4-26b-8bit). The wrapper's tree and this extracted tree
// each hold their own SwitchGLU instances, so without sharing the
// load-time parity probe below (or, with the gate disabled, the
// first live request on each path) builds TWO identical multi-GiB
// copies — pushing weights+caches past the 90% unified-memory cap
// on 64 GB (8-bit) and 36 GB (qat-4bit) boxes, after which the
// shared KV gate rejected every request (the v0.7.2 incident).
// Pairing wrapper↔extracted instances keeps the total at ONE
// fused copy, built eagerly here where the load path's admission
// guards can see it. Runs before the probe so neither probe
// forward can trigger a private build.
let sharedFusedLayers = shareMoEFusedCaches(wrapper: wrapper, extracted: skeleton)

// 5. Load-time forward parity gate (env-gated, default on).
// 4. Load-time forward parity gate (env-gated, default on).
var parityDiff: Float? = nil
if parityCheckEnabled(environment: environment) {
// Return the probe's transient buffers to the OS before the load
Expand All @@ -195,78 +171,7 @@ enum EngineV2VLMTextExtraction {
wrapper: wrapper, extracted: skeleton, vocabSize: textConfig.vocabSize)
}

// Measure AFTER the probe: on the (defensive) path where some layer
// pair was NOT shared, the probe's forwards are what lazily built
// each tree's private cache, and the capacity derivation must see
// the full retained footprint either way.
let fusedBytes = fusedMoECacheBytes(of: [wrapper, skeleton])

return Extraction(
model: skeleton,
parityMaxAbsLogitDiff: parityDiff,
sharedFusedMoELayerCount: sharedFusedLayers,
fusedMoECacheBytes: fusedBytes)
}

/// Total bytes of MoE fused gate+up caches retained across `roots`,
/// counting each cache ONCE even when it is shared between trees
/// (`shareFusedGateUpCache` hands the SAME `MLXArray` instances to both
/// SwitchGLUs, so dedup is by weight-buffer identity). This is the
/// engine-retained residency overhead the v2 capacity derivation nets
/// out (`EngineV2KVSizing.netOfEngineResidentOverhead`) and the load
/// path records on the model slot — the fused arrays are plain module
/// properties, so they appear in neither `parameters()` sums nor
/// `scheduler.modelWeightBytes`. Zero for dense checkpoints and before
/// any cache is built.
static func fusedMoECacheBytes(of roots: [Module]) -> Int {
var seen = Set<ObjectIdentifier>()
var total = 0
for root in roots {
for (_, module) in root.namedModules() {
guard let glu = module as? SwitchGLU,
let weight = glu.fusedGateUpWeightForVerification
else { continue }
guard seen.insert(ObjectIdentifier(weight)).inserted else { continue }
total += glu.fusedGateUpCacheBytes
}
}
return total
}

/// Pair every MoE `SwitchGLU` in the wrapper's language model with its
/// counterpart in the extracted text model (same dotted module path minus
/// the `language_model.` prefix — the exact re-keying the parameter
/// update used) and share ONE fused gate+up cache between each pair.
/// Returns the number of pairs shared. Zero for dense checkpoints (no
/// SwitchGLU anywhere) — and, defensively, when the two trees' module
/// paths ever diverge, in which case each side keeps its lazy build (the
/// pre-v0.7.2 behavior) rather than failing the extraction.
private static func shareMoEFusedCaches(
wrapper: MLXVLM.Gemma4, extracted: Gemma4TextModel
) -> Int {
var extractedSwitchGLUs: [String: SwitchGLU] = [:]
for (path, module) in extracted.namedModules() {
if let glu = module as? SwitchGLU {
extractedSwitchGLUs[path] = glu
}
}
guard !extractedSwitchGLUs.isEmpty else { return 0 }

var shared = 0
for (path, module) in wrapper.namedModules() {
guard let wrapperGLU = module as? SwitchGLU,
path.hasPrefix(languageModelPrefix),
let extractedGLU =
extractedSwitchGLUs[String(path.dropFirst(languageModelPrefix.count))]
else { continue }
// Counts only pairs where a cache actually exists and is shared —
// an ineligible layer (opt-out env, cache limit, non-quantized)
// propagates its no-fusion verdict but is not "shared".
if wrapperGLU.shareFusedGateUpCache(with: extractedGLU) {
shared += 1
}
}
return shared
return Extraction(model: skeleton, parityMaxAbsLogitDiff: parityDiff)
}

// MARK: - Steps
Expand Down
12 changes: 1 addition & 11 deletions provider-swift/Sources/ProviderCore/ProviderLoop+Capacity.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,8 @@ extension ProviderLoop {
var totalResidentWeightBytes: UInt64 = 0
for (_, slot) in modelSlots {
let weights = await slot.scheduler.modelWeightBytes
// Engine-retained residency overhead (the shared MoE fused
// gate+up cache a VLM extraction built) counts like weights:
// module-retained active memory that `modelWeightBytes`
// cannot see. Omitting it would let the live budget clamp
// recompute OTHER bridges' budgets against a rosier resident
// set than the shared KV gate actually observes.
var slotResident = UInt64(max(0, weights))
let (withOverhead, overheadOverflow) = slotResident
.addingReportingOverflow(slot.engineResidentOverheadBytes)
slotResident = overheadOverflow ? .max : withOverhead
let (sum, overflow) = totalResidentWeightBytes
.addingReportingOverflow(slotResident)
.addingReportingOverflow(UInt64(max(0, weights)))
totalResidentWeightBytes = overflow ? .max : sum
}
let engineV2 = await engineV2Runtime.capacitySummary(
Expand Down
41 changes: 3 additions & 38 deletions provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -142,18 +142,8 @@ extension ProviderLoop {
var existingEngineKVCapacities: [Int] = []
for (slotModelId, slot) in modelSlots where slotModelId != modelId {
let slotWeights = await slot.scheduler.modelWeightBytes
// Count the slot's engine-retained residency overhead (the
// shared MoE fused gate+up cache a VLM extraction eagerly
// built) like weights: it is module-retained ACTIVE memory that
// `modelWeightBytes` (a parameters() sum) does not see, so
// omitting it would size THIS engine's ceiling against memory
// that co-resident slot is already holding.
var slotResident = UInt64(max(0, slotWeights))
let (withOverhead, overheadOverflow) = slotResident
.addingReportingOverflow(slot.engineResidentOverheadBytes)
slotResident = overheadOverflow ? .max : withOverhead
let (sum, overflow) = coResidentWeightBytes
.addingReportingOverflow(slotResident)
.addingReportingOverflow(UInt64(max(0, slotWeights)))
coResidentWeightBytes = overflow ? .max : sum
if let existingBridge = slot.engineV2 {
existingEngineKVCapacities.append(
Expand Down Expand Up @@ -215,41 +205,16 @@ extension ProviderLoop {
// build the engine on that; any extraction/verify/parity
// failure throws into the factory's engine_v2_fallback WARN.
let servingModel: any LanguageModel
var grantedKVBytesCapacity = kvBytesCapacity
if isVLM {
guard let loadedModelDirectory else {
throw EngineV2VLMTextExtractionError.missingModelDirectory
}
let extraction = try EngineV2VLMTextExtraction.extractTextModel(
from: snapshot.model, modelDirectory: loadedModelDirectory)
// PR#508 finding 2: `kvBytesCapacity` was derived from
// WEIGHTS before this extraction materialized the shared
// MoE fused gate+up cache (~8–15 GiB on Gemma 4) —
// module-retained active memory the shared KV gate sees
// in live MLX usage but the static derivation did not.
// Net the MEASURED cache out of the engine's admission
// ceiling so the heartbeat max (derived from the
// engine's grant), the engine's private ledger, and the
// shared gate agree; an unadjusted ceiling over-routes
// by exactly the cache size (~1.7× on the incident's
// 64 GB profile) and replays a mild v0.7.2. A 0 result
// throws noKVHeadroom below → legacy fallback.
grantedKVBytesCapacity = EngineV2KVSizing.netOfEngineResidentOverhead(
kvBytesCapacity, overheadBytes: extraction.fusedMoECacheBytes)
if let parityDiff = extraction.parityMaxAbsLogitDiff {
let fusedGiB = String(
format: "%.2f",
Double(extraction.fusedMoECacheBytes) / (1024 * 1024 * 1024))
let grantedGiB = String(
format: "%.2f",
Double(grantedKVBytesCapacity) / (1024 * 1024 * 1024))
slotLogger.info(
"engine_v2: \(modelId) VLM text-model extraction passed the "
+ "load-time forward parity gate (max |Δlogit| \(parityDiff), "
+ "fused MoE gate+up cache shared across "
+ "\(extraction.sharedFusedMoELayerCount) layer(s), "
+ "\(fusedGiB) GiB netted out of the KV ceiling → "
+ "\(grantedGiB) GiB)")
+ "load-time forward parity gate (max |Δlogit| \(parityDiff))")
}
servingModel = extraction.model
} else {
Expand All @@ -258,7 +223,7 @@ extension ProviderLoop {
return try EngineV2Factory.makeProductionEngine(
model: servingModel,
tokenizer: tokenizer.inner,
kvBytesCapacity: grantedKVBytesCapacity)
kvBytesCapacity: kvBytesCapacity)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,32 +343,17 @@ extension ProviderLoop {

// Post-BRIDGE measured-headroom guard (v0.7.3): the engine build
// can retain additional load-time memory beyond the weights the
// check above measured — the VLM extraction eagerly builds the
// (shared) MoE fused gate+up cache, ~15 GiB on gemma-4-26b-8bit.
// Re-measure AFTER the bridge so a box whose full load-time
// footprint leaves no serveable KV unloads and 503s (coordinator
// reroutes, telemetry fires) instead of advertising a model whose
// every request the shared KV gate rejects — the v0.7.2
// black-hole failure shape. Runs for ANY VLM slot, not just when
// the bridge built: the extraction builds the fused cache BEFORE
// its parity gate, so a parity/init failure that fell back to
// legacy (nil bridge) has still grown resident memory. Trim the
// pool first, mirroring the post-load check. (unregister/shutdown
// check above measured. Re-measure AFTER the bridge so a box
// whose full load-time footprint leaves no serveable KV unloads
// and 503s (coordinator reroutes, telemetry fires) instead of
// advertising a model whose every request the shared KV gate
// rejects — the v0.7.2 black-hole failure shape. Runs for ANY
// VLM slot, not just when the bridge built: an extraction that
// failed after materializing load-time state (e.g. a parity
// mismatch) has still grown resident memory. Trim the pool
// first, mirroring the post-load check. (unregister/shutdown
// are safe no-ops on the nil-bridge path.)
var engineResidentOverheadBytes: UInt64 = 0
if engineV2Bridge != nil || slotIsVLM {
// Measure the engine build's retained residency overhead —
// the shared MoE fused gate+up cache the VLM extraction
// eagerly builds (resident even when the bridge then FAILED,
// e.g. a parity mismatch after the cache build). Recorded on
// the slot so later v2 engine ceilings and the heartbeat
// fleet-budget clamp count it like resident weights
// (`modelWeightBytes` is a parameters() sum and cannot see
// it). The wrapper tree carries the shared arrays on every
// path, so scanning the loaded model is sufficient.
engineResidentOverheadBytes = await container.perform { ctx in
UInt64(max(0, EngineV2VLMTextExtraction.fusedMoECacheBytes(of: [ctx.model])))
}
MLX.Memory.clearCache()
if !(await scheduler.hasServeableKVHeadroom()) {
let headroomGb = String(
Expand All @@ -392,7 +377,6 @@ extension ProviderLoop {
tokenizer: tokenizer,
isVLM: slotIsVLM,
modelType: modelInfo.modelType,
engineResidentOverheadBytes: engineResidentOverheadBytes,
lastInferenceAt: .now
)

Expand Down
10 changes: 0 additions & 10 deletions provider-swift/Sources/ProviderCore/ProviderLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -548,16 +548,6 @@ public actor ProviderLoop {
/// drop window while the slot is still resident (a Gemma build would
/// otherwise fall back to the qwen3 parser and leak <think> tokens).
let modelType: String?
/// MEASURED engine-retained residency overhead beyond the weights —
/// the shared MoE fused gate+up cache the VLM text extraction
/// eagerly builds (~8–15 GiB on Gemma 4; PR#508 finding 2). Plain
/// module properties, so it appears in neither
/// `scheduler.modelWeightBytes` (a parameters() sum) nor any
/// pending-load estimate; the sizing paths that treat weights as
/// resident memory (later v2 engine ceilings, the heartbeat fleet
/// budget clamp) must add this alongside them. 0 for non-VLM slots
/// and dense checkpoints.
var engineResidentOverheadBytes: UInt64 = 0
var lastInferenceAt: ContinuousClock.Instant
}

Expand Down
Loading
Loading