Repository navigation
fix(memory,registry): make the activation reserve shape-aware and trust real decode measurements - #584
fix(memory,registry): make the activation reserve shape-aware and trust real decode measurements#584Gajesh2007 wants to merge 3 commits into
Conversation
defaultActivationReserveBytes was a flat 3 GiB whose own doc called it a conservative safety floor, justified by a measurement taken at 4-concurrent. Nothing in it scaled with batch, context or heads. It is already wrong at B=4: the prefill score tensor is [concurrent_prefills, heads, C, kL] in fp32 on the composed fallback -- gemma-4's head_dim 256/512 never reaches MLX's fused kernel -- which is 0.66 GB at ctx 10k and 6.6 GB at ctx 100k. The second exceeds the whole reserve. Replaces the constant with peakPrefillScoreBytes over an ActivationReserveShape whose every field names its single upstream owner (maxBatchedTokensPerStep, prefillChunkSize, queryBlockSize, queryHeads, headDim, maxContextLength) and carries NO defaults, because restating an engine default here would recreate exactly the drifting parallel constant this change deletes. Two subtleties the shape has to capture: - Query sub-blocking (#85) bounds the score tensor to O(1) in chunk length for TEXT only. Span-bearing vision chunks keep the single-call path and are the only prefill path whose L can exceed prefillChunkSize. gemma-4 serves as a VLM slot, so the span path is costed at full L -- text-only slots come out exactly 4x cheaper. - Concurrency is budget-derived, B = maxBatchedTokensPerStep / prefillChunkSize, which is what the plan's table column means and reproduces all four of its cells. The floor stays and keeps its name: the estimate only ever RAISES it, since it covers the score tensor and not the rest of the working set. Env semantics are untouched -- DARKBLOOM_ACTIVATION_RESERVE_GB still treats <=0/non-finite as unset and still wins outright when set. Coordinator mirror: servability.go:44-50 hardcoded 3.0 to predict a COLD provider's post-load budget before any heartbeat exists. That is the real mirror -- freeMemoryAdmits is reserve-blind by design and was the wrong file. Now a piecewise floor/per-token model. Two hardcoded goldens recomputed with the arithmetic shown in the test comments: wantRoomy 110565 -> 101920 (the score branch now binds above the 49152 crossover); the gemma 48GB-on-28GB shape is UNCHANGED at 23911 because the flat floor still binds there. Verified: swift build clean; swift test --filter 'UnifiedMemoryCap| activationReserve' 29/29; the shipped formula compiled standalone against a scratch driver, 26/26 checks, reproducing the plan's table to x1.0312 (the added [C,kL] bool mask). go build ./... OK; go test ./registry/ PASS. Downstream effect is real: a 48 GiB box with 31 GiB of weights serving 100k VLM moves its KV budget 9.200 -> 5.906 GiB. (cherry picked from commit b026ad9)
effectiveTPSLoadFactor was 0.27, fitted on legacy-engine Qwen2.5-7B rows (92.8/69.5/35.9/29.6). Against the CBv2 gemma-4 measurements (101.8/59.6/38.0/24.7 at B=1/2/4/8) it is wrong by 23.4% MAPE and, more importantly, wrong in the LENIENT direction: it predicts 32.2 tok/s at B=8 where we measure 24.7, i.e. it UNDER-predicts degradation by 30% at exactly the operating point this migration moves to. Re-fit to 0.39. Median of implied k over B=2/4/8, the same method that produced 0.27 -- validated by reproducing 0.2669 from the legacy rows before applying it. Least-squares cross-check agrees to 0.2%; residuals fall to 2.9% MAPE. Functional form rate(B)=solo/(1+k*B) is kept: a power law fits B=2/4/8 identically and the shifted form fits materially worse. The comment now carries the residual table and the SIGN of the old error, not just the new value, because the plan of record had the direction backwards and a bare constant would let that recur. Note this makes the cap TIGHTER, not looser -- the B=8 solo threshold rises from 39.3 to 50.1 tok/s. Re-fitting does not unblock B=8; it moves the goalpost away. It is landed anyway because k also drives the warm-pool target and the TTFT backlog, and a coefficient that under-predicts degradation at the target batch is a latent shedding bug. What actually unblocks B=8 is the solo rate. The Swift provider never assigns decode_tps anywhere, so resolvedDecodeTPS falls through to sqrt(memory_bandwidth) -- a model-agnostic hardware proxy at 16-28 tok/s against a measured ~99.5 gemma solo. THAT proxy is what produces cap 2. prod.env now seeds EIGENINFERENCE_MODEL_SOLO_TPS_SEED, which clears the 50.1 threshold with margin and reaches 8 at both 0.27 and 0.39, so the seed and the re-fit are independent. The per-model overcommit route was rejected: reaching 8 that way needs a multiplier above 7.0, which is a cap bypass wearing an allowance's clothes. Cap tests now derive their expectations instead of hardcoding literals, so the registry suite is green at both 0.27 and 0.39. Verified: go build ./... OK; go test ./registry/ -run 'TestQuality|TestConcurrency|TestSolo|TestWarmPool' 50 tests PASS; full ./registry/ package PASS; gofmt and go vet clean. NOTE FOR OPS: prod.env is a sanitized reference. The authoritative file is /etc/d-inference/env on the coordinator VM, so this seed is NOT set in production by this commit -- it needs the human-approved operator action recorded in JOURNAL.md. (cherry picked from commit 8368af3)
The reason B=8 delivered nothing for gemma-4 was not a missing field. observed_decode_tps IS populated by the provider (EngineV2Bridge+Capacity.swift:146, an alpha=0.3 per-model EWMA) and IS already ingested as solo samples (registry.go:3046-3053, solo-gated RecordSolo). The blocker was qualityCapSoloMinSamples = 5: below that floor the chain skipped a real, solo-gated, per-model measurement and fell straight to sqrt(memory_bandwidth) -- a model-agnostic hardware proxy at 16-28 tok/s against a measured ~99.5 gemma-4 solo. That proxy is what produced cap 2. Inserts a relaxed tier between the trusted medians and the seed: the same two medians at >= 1 sample, cross-class still seed-clamped. Hoists the seed-clamp so it applies at both floors, not only the trusted one. No new wire field and zero Swift changes -- worth noting because adding a field to BackendSlotCapacity during a mixed-version rollout is a cost we should not pay when the data is already there. Deliberately does NOT populate RegisterMessage.decode_tps. Different field, declared and coded in Swift but never assigned, and correctly so: one provider-level benchmark on a multi-model box lends one model's rate to another, which is the postmortem failure the per-model resolver exists to prevent. Arithmetic, asserted by bisection against the closed form rather than literals: cap 8 needs solo >= 50.1 tok/s at floor 15, k 0.39, overcommit 1.2. Measured gemma-4 is 99.5, a 1.99x margin, giving min(floor((99.5/15-1)/0.39), 8) = 8 -- granted on quality merit, not dependent on the overcommit multiplier. Projected B=8 per-request rate 24.2 tok/s, above the floor. Even a fully B=2-contaminated first reading of 55.9 still yields 8, so it does not rest on a converged EWMA. Cold start: a provider reports NOTHING before its first completion -- encodeIfNonZero omits the key rather than sending 0, and ingest requires >0, so the chain falls to seed then proxy. It is never capped at 1 by its own silence: the proxy gives cap 2 for a dedicated model, and the existing DecodeTPS<=0 && !perModel guard leaves a non-dedicated model's reported base untouched. The prod.env seed MUST STAY, now as a cold-start floor rather than the steady-state driver: the TPS registry is in-memory and restart-wiped, so every coordinator restart returns all ~94 boxes to the no-samples state, and gemma-4 is dedicated so the non-dedicated guard does not cover it. The seed is also the upper bound on cross-class median transfer. Also updates docs/architecture/operations/routing.md, which documented a 3-step decode-rate fallback chain that is now 5 steps. (cherry picked from commit 1a1010d)
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR makes purely mechanical improvements to activation-memory sizing math inside Trust Boundaries Touched
Threat Assessment
New Attack SurfaceNone. One minor observation: Open Findings ResolvedNone — this PR does not address any SEC-* finding. Summary for ReviewersThe security-relevant files listed in the diff map ( 🔐 Threat model: |
There was a problem hiding this comment.
Pull request overview
This PR updates the provider/coordinator memory and routing models to better reflect real CBv2 behavior: activation/working-memory reserve is now shape-aware (instead of a flat 3 GiB), and routing/admission decisions are tightened to use measured decode behavior (including improved solo-TPS fallback logic) rather than relying on model-agnostic proxies after restarts.
Changes:
- Provider: introduce a parametric activation reserve (
ActivationReserveShape) and use it (when available) in activation-reserve resolution. - Coordinator: re-fit and apply the CBv2 load degradation coefficient (
effectiveTPSLoadFactor = 0.39) and adjust solo-TPS resolution to prefer under-sampled but solo-gated measurements over the sqrt-bandwidth proxy. - Ops/docs/tests: update routing documentation, production env seed guidance, and expand tests to pin the new fallback tiers and piecewise cold-budget estimator.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| provider-swift/Sources/ProviderCore/Inference/UnifiedMemoryCap.swift | Adds shape-aware activation reserve sizing and integrates it into reserve resolution. |
| coordinator/registry/scheduler.go | Updates load-scaling factor (k) and documents CBv2 measurement basis; maintains effective TPS fallback chain. |
| coordinator/registry/concurrency_cap.go | Adjusts solo-TPS resolver to include an under-sampled measured tier before seed/proxy fallback. |
| coordinator/registry/concurrency_cap_test.go | Refactors expectations to be k-derived, adds inversion/inequality pinning and restart/seed regression coverage. |
| coordinator/registry/servability.go | Replaces flat activation reserve in cold budget estimation with a piecewise model using a per-token activation surcharge. |
| coordinator/registry/servability_test.go | Pins piecewise estimator behavior (floor regime, score regime, continuity across crossover). |
| coordinator/registry/servability_provider_fit_test.go | Updates fit tests to match the floor-regime behavior for gemma-4 cold-load budgeting. |
| coordinator/registry/warm_pool_target.go | Adds clarifying comment on operational sensitivity to mismeasured k. |
| coordinator/registry/warm_pool_controller_test.go | Makes quality-concurrency test resilient to future k re-measurements by pinning closed-form vs defining inequality. |
| coordinator/registry/solo_tps_test.go | Adds coverage for the relaxed ≥1-sample tier and restart/seed behavior. |
| docs/architecture/operations/routing.md | Updates decode-TPS fallback documentation (now 5-step solo chain) and reflects new k. |
| deploy/environments/prod.env | Adds per-model solo-TPS seed guidance/config to support B=8 rollout under the quality cap. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // servabilityActivationBytesPerToken mirrors the CONTEXT-SCALING half | ||
| // (UnifiedMemoryCap.peakPrefillScoreBytes), which the provider gained when | ||
| // the flat 3 GiB reserve stopped being true. A model whose head_dim misses |
| Step 5 is reached in production only at **cold start**. The Swift provider | ||
| never sends `decode_tps` at registration (deliberately: on a multi-model box a | ||
| single provider-level benchmark lends one model's rate to another — the | ||
| postmortem layer-6 failure), and a provider that has completed no request | ||
| reports no `observed_decode_tps` at all, so `p.DecodeTPS` is 0 and the proxy is |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2861b6175c
ℹ️ 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".
| guard let shape else { return defaultActivationReserveBytes } | ||
| return activationReserveBytes(for: shape) |
There was a problem hiding this comment.
Pass the activation shape into production memory gates
For composed-attention models at long contexts, the calculated reserve can exceed the 3 GiB floor, but no production caller constructs an ActivationReserveShape or passes shape here: loadHeadroomBytes, kvBudgetBytes, and liveKVHeadroomBytes all continue calling this resolver without it. Consequently this guard always returns the old flat reserve, so the load and runtime KV gates can admit several GiB more memory than the new estimate allows, defeating the advertised shape-aware cap and risking memory-pressure failures/OOMs. Thread the slot's scheduler/model shape—or its resolved reserve—through every production gate.
AGENTS.md reference: AGENTS.md:L234-L234
Useful? React with 👍 / 👎.
| # Note gpt-oss-20b is not a dedicated model, so today it is uncapped at the | ||
| # flat 24; a seed makes its cap real (8 against a reported 8). That is | ||
| # intentional. | ||
| EIGENINFERENCE_MODEL_SOLO_TPS_SEED=gemma-4-26b-qat-4bit=70,gpt-oss-20b=70 |
There was a problem hiding this comment.
Add the solo-rate seed to the consumed production defaults
On a normal production environment refresh, this value is never installed: this file's header explicitly says it is an unconsumed sanitized reference, while deploy/gcp/prod/refresh-env.sh adds variables only from deploy/gcp/prod/release-env-defaults, where this key is absent. Unless an operator happens to add it manually, every coordinator restart therefore begins with no seed or in-memory samples, and dedicated Gemma providers fall back to the 16–28 tok/s hardware proxy and remain capped around 2 rather than the intended reported concurrency of 8. Put the seed in the authoritative release-default/migration path.
Useful? React with 👍 / 👎.
|
Found 1 test failure on Blacksmith runners: Failure
|
|
Closing as superseded by #590, which now targets the Containment was verified by per-file blob comparison against the integration branch, not by ancestry.
Also note the description's claim that the provider 'does now' send |
![Fix with [code]smith](https://pr-comments-assets.blacksmith.sh/codesmith/fix-with-codesmith-light.png)
Three coordinator/provider fixes to the memory and routing model. None of them need paged; all of them are needed by paged, and they independently unblock B=8 on contiguous.
1. The activation reserve was a constant, and the wrong one
UnifiedMemoryCaphardcoded a 3 GiB activation reserve regardless of prefill shape. The coordinator's mirror inservability.gohardcodedservabilityActivationReserveGB = 3.0separately — so a provider-side change could silently desynchronize the two.The reserve is now a function of prefill shape on both sides.
flowchart LR subgraph Before A1[model load gate] --> B1["reserve = 3.0 GiB constant"] C1[coordinator cold estimate] --> D1["servabilityActivationReserveGB = 3.0 — separate literal"] B1 -.->|can desync silently| D1 end subgraph After A2[model load gate] --> B2["reserve = f(prefill shape)"] C2[coordinator cold estimate] --> B2 endDownstream effect on a 48 GiB box with 31 GiB of weights serving 100k VLM: KV budget moves 9.200 → 5.906 GiB.
2. The decode load factor was fitted against a legacy proxy
kwas fitted to asqrt(memory_bandwidth)proxy rather than measured decode rates, because the Swift provider never sent a decode rate at all. It does now. Re-fitting against the engine's measured rates movesk0.27 → 0.39 (MAPE 23.4% → 2.9%).This makes the cap tighter, not looser — the B=8 threshold rises 39.3 → 50.1 tok/s. The plan expected re-fitting to unblock B=8; it moves the goalpost away. What actually unblocks it is the coordinator now inferring from real measurements.
3. A real solo measurement below the 5-sample floor was discarded
The trust floor required 5 samples before believing a solo rate, so a restart returned all 94 boxes to the no-samples state and fell straight through to the
sqrt(memory_bandwidth)seed. A relaxed tier (≥1 sample) now sits between the trusted median and the seed. gemma-4 is dedicated, so the non-dedicated guard did not protect it.Also updates
docs/architecture/operations/routing.md, which documented a 3-step decode-rate fallback chain that is now 5 steps.Verified:
go build ./...,go vet,gofmtclean; registry suites green; goldens recomputed.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.