Skip to content

fix(memory,registry): make the activation reserve shape-aware and trust real decode measurements - #584

Closed
Gajesh2007 wants to merge 3 commits into
masterfrom
paged-kv/w1-memory-routing
Closed

Gajesh2007 wants to merge 3 commits into
masterfrom
paged-kv/w1-memory-routing

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

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

UnifiedMemoryCap hardcoded a 3 GiB activation reserve regardless of prefill shape. The coordinator's mirror in servability.go hardcoded servabilityActivationReserveGB = 3.0 separately — 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
  end
Loading

Downstream 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

k was fitted to a sqrt(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 moves k 0.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, gofmt clean; registry suites green; goldens recomputed.


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

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)
Copilot AI review requested due to automatic review settings July 25, 2026 21:23
@vercel

vercel Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jul 25, 2026 9:23pm
d-inference-console-ui-dev Ready Ready Preview Jul 25, 2026 9:23pm
d-inference-landing Ready Ready Preview Jul 25, 2026 9:23pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

This PR makes purely mechanical improvements to activation-memory sizing math inside UnifiedMemoryCap.swift; it does not touch any authentication, encryption, attestation, or key-management path, and introduces no new attack surface.


Trust Boundaries Touched

  • TB-003 (Provider Operator vs. Process) — indirectly, via inference memory layout
  • TB-007 (Provider Inference Engine) — primary boundary; this file is the memory-cap layer for the in-process MLX engine

Threat Assessment

Threat Finding Notes
T-028 — Residual inference data in GPU Metal buffers ℹ️ Neutral The PR resizes the reservation for activation memory but does not add or remove any Metal buffer zeroing. The pre-existing open limitation (GPU-side MLX buffers not explicitly zeroed between requests) is unchanged.
T-007 — Provider serves manipulated model outputs ℹ️ Neutral Weight-hash enforcement and model-routing logic are untouched. The activation-reserve change affects scheduler capacity, not integrity controls.
T-029 — Idle GPU timeout / resource monopolisation ℹ️ Neutral Memory cap changes could in theory affect whether a model remains resident (if the cap calculation now returns a smaller available-KV headroom), but IdleTimeoutPolicy logic itself is not modified. No regression path visible.

New Attack Surface

None. ActivationReserveShape and activationReserveBytes(for:) are pure sizing computations with no I/O, no credential handling, and no trust-state mutation. All inputs are scheduler config integers derived from coordinator-clamped values (maxBatchedTokensPerStep, prefillChunkSize, etc.); there is no consumer-controlled input path into this function.

One minor observation: querySubBlockSize == 0 is documented as a kill-switch that collapses to the full prefill chunk size, and spanChunkMaxL == 0 disables the vision path. Both are fail-safe defaults. No concern.


Open Findings Resolved

None — this PR does not address any SEC-* finding.


Summary for Reviewers

The security-relevant files listed in the diff map (UnifiedMemoryCap.swift → T-007) are the only changed file in the focused diff. The 11 coordinator-side files (concurrency_cap.go, scheduler.go, servability*.go, warm_pool_*.go, etc.) were not shown in the diff; if any of those touch registry admission logic, provider trust state, or routing gate conditions, they should be separately reviewed against T-006 (registry flooding), T-007 (weight-hash enforcement, SEC-007), and T-009 (trust-level assignment). Request that diff to be included in the next review cycle if those files changed substantively.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines +52 to +54
// 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
Comment on lines +143 to +147
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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +430 to +431
guard let shape else { return defaultActivationReserveBytes }
return activationReserveBytes(for: shape)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

@blacksmith-sh

blacksmith-sh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/
TestIntegrationMixedVersionReleasedV0712Provider
View Logs

Fix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

@Gajesh2007

Copy link
Copy Markdown
Member Author

Closing as superseded by #590, which now targets the release/v0.8.0 accumulator branch rather than master.

Containment was verified by per-file blob comparison against the integration branch, not by ancestry.

⚠️ Both P1s land verbatim in #590 — servability.go and UnifiedMemoryCap.swift are byte-identical between this head and integration. Tracking them there:

  • ActivationReserveShape has zero production call sites (5 mentions, all inside UnifiedMemoryCap.swift), so all four gates take the flat 3 GiB. Meanwhile servability.go did adopt the piecewise model — so this PR creates the provider/coordinator desync it claims to remove. The 9.200→5.906 GiB figure is not reproducible from this tree.
  • EIGENINFERENCE_MODEL_SOLO_TPS_SEED exists only in prod.env, which is not the authoritative runtime file; it is absent from release-env-defaults and required-env-keys.txt.

Also note the description's claim that the provider 'does now' send decode_tps is contradicted by the tree — the field is declared and encoded but never assigned, and routing.md:153 now documents that as deliberate.

@Gajesh2007 Gajesh2007 closed this Jul 26, 2026

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 2861b617 Deployed Jul 25, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 2861b617 Deployed Jul 25, 2026 by vercel[bot]
benchmarks — 2861b617 Deployed Jul 25, 2026 by Gajesh2007 via E2E Benchmarks #1881
Preview – d-inference-landing — 2861b617 Deployed Jul 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants