Skip to content

cluster, provider: a Gemma 4 pair serves its whole 262,144-token context in both modes, cuts an oversized max_tokens, and refuses in one Mac's words before any SSE header — R-FULL D2/D3 - #1923

Merged
jonathan308 merged 11 commits into
devfrom
rfull/d2-gemma-pair-context
Nov 9, 2026

Conversation

@jonathan308

@jonathan308 jonathan308 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

R-FULL D2 and D3 (R-FULL.md §3), from journey 2b on pair-2 (validation-evidence/journey-2b.md, J2b-1 and J2b-2, 2026-11-08). On the pair, Gemma 4 26B (tensor parallel and pipeline):

  • advertised a 65,536-token context, while one Mac serves the model's 262,144 (journey 1: 254,953 tokens served on the Studio);
  • failed every prompt above ~32K tokens with no typed refusal. Bisect: TP 31,885 OK, ~40.6K and ~58K fail; pipeline 31,892 OK, ~58K fails. Each failure was an HTTP 200 SSE that ended at once in finish_reason: "error", server_error "Response generation failed". The leader's local endpoint in "Both, me first" has no pair HTTP writer, so the pair's typed refusal (prompt_too_long) went in-band after the 200 head;
  • refused an oversized max_tokens (400 output_too_long) where one Mac cuts it (provider: a single Mac serves its model's whole window and holds every request to it #1893).

Now, on a Gemma 4 26B pair, in both modes:

  1. The model's whole context. The profile is the declared context: prompts up to 262,143 tokens and up to 32,768 output tokens (the catalog's max_output_length) within 262,144 (Gemma4ResidentAdapterDefinition.contextLimits, .native). LOAD, every quote and the planner still size the pair for the standard 32,768 + 32,768-token request (memoryProfile), so placement and LOAD are unchanged. Both ranks bind that plan into their load agreement.
  2. Tensor parallel (D2). Gemma4TensorParallelRequestCharge charges a longer request at its own context: this rank's KV heads, attention transient, partials, vocabulary rows and prefix capture. At 262,144 tokens that is 10.4 GB a rank, against LOAD's 2.6 GB. READY's capacity covers that request; it is a ceiling, never a grant. READY and every keep-warm answer carry the longest context the reservation gate admits now (servingContextTokens, refreshServingContext, now wired in NativeWorkerRuntime for this owner, single and lanes). The bounds that held Gemma's state and request geometry to 65,536 now take any context the wire carries.
  3. Pipeline (D3, the same shape). A layer-stage family's stages serve what its adapter says (LayerStageResidentAdmission.servedProfile reads ClusterRuntimeAdapter.pipelineServesWholeProfile, true for .gemma4LayerStage only; every other family's stages serve the memory plan). The provider reads the same flag for what the pair advertises, so the two never differ. requireWithinMemoryProfile is now requireWithinServedProfile, and a stage logs the context it serves (darkbloom-resident-context-v1 … limit=). Gemma's stages serve its whole profile. Each stage charges the whole model's ledger at the request's own context (6.4 GB at 262,144, plus an 8.6 GB prompt frame on a stage with a full-attention layer), admitted by its live gate. READY's capacity covers the longest request, and each stage's serving context is searched up to 262,144; the pair serves the smaller of the two. The lookahead prefill's 32,768-token bounds take any prompt the wire carries. Every other family is unchanged.
  4. One Mac's answers. The provider holds a request to what the mode serves (ClusterModelFeaturePolicy.servedProfile, from the same adapter flag: a Gemma pipeline's whole profile):
    • a max_tokens past the output limit, or past what the prompt leaves of the context, is cut (EngineV2Bridge.pairServedLimits), on any pair;
    • a prompt that fills the context gets one Mac's 400 context_length_exceeded, in one Mac's words (DistributedRequestRefusal.contextLengthExceeded, which the coordinator classes as exceeding context): "The prompt fills this model's context window of 262144 tokens, leaving no room for an answer. Shorten the prompt or start a new conversation.";
    • a request longer than the context both Macs admit now gets one Mac's memory 503: "This Mac's memory can't hold this request right now. …";
    • every refusal is thrown before any stream exists, on the leader's local endpoint as on the pair's own API. A nonthrowing caller still reads it typed.
  5. Listed as served. The leader's /v1/models and darkbloom cluster local list context_length 262,144 and max_output_length 32,768, and an omitted max_tokens defaults within them. The advertised context always equals what the mode serves.

Before

flowchart LR
  subgraph api["The leader's local API (Both, me first), Gemma 4 26B on the pair"]
    A["Prompt of ~40K tokens,<br/>streamed"]
    B["max_tokens 300,000"]
    C["Prompt of 263K tokens"]
  end
  A --> P{"Pair profile, both modes:<br/>prompt 32,768, output 32,768,<br/>context 65,536"}
  B --> P
  C --> P
  P -->|"prompt past 32,768"| R1["200, then 'Response generation failed'<br/>(non-streamed: 400 prompt_too_long)"]
  P -->|"max_tokens past 32,768"| R2["400 output_too_long"]
  L["GET /v1/models"] --> L1["context_length 65,536<br/>(one Mac: 262,144)"]

  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#0f172a
  classDef step fill:#f1f5f9,stroke:#475569,color:#0f172a
  classDef bad fill:#fee2e2,stroke:#b91c1c,color:#0f172a
  class A,B,C,L input
  class P step
  class R1,R2,L1 bad
Loading

Blue: requests. Grey: code. Red: what a caller met.

After

flowchart LR
  subgraph api["The leader's local API or the pair's own API, Gemma 4 26B on the pair"]
    A["Prompt of 64K or 128K tokens"]
    B["max_tokens 300,000"]
    C["Prompt of 262,144+ tokens"]
  end
  A --> O["outputTokens: cut to the output<br/>and the context the mode serves"]
  B --> O
  C --> O
  O --> P{"Pair profile, both modes:<br/>prompt 262,143, output 32,768,<br/>context 262,144"}
  P -->|"prompt fills the context"| R1["400 context_length_exceeded,<br/>one Mac's words, before any SSE"]
  P -->|"longer than both Macs admit now"| R2["503, one Mac's memory words,<br/>before any SSE"]
  P -->|"fits"| G["Each TP rank or stage charges it<br/>at its own context; its live gate admits it"]
  G --> S["200; finish_reason stop,<br/>or length at the cut"]
  L["GET /v1/models"] --> L1["context_length 262,144,<br/>max_output_length 32,768"]

  classDef input fill:#dbeafe,stroke:#1d4ed8,color:#0f172a
  classDef new fill:#dcfce7,stroke:#15803d,color:#0f172a
  classDef refusal fill:#fef3c7,stroke:#b45309,color:#0f172a
  class A,B,C,L input
  class O,P,G,S,L1 new
  class R1,R2 refusal
Loading

Blue: requests. Green: what this PR adds or changes. Amber: refusals in one Mac's code and words.

Tests (red first)

Red: 91fef63 on dev c76445a. Its tests use only the APIs that existed.

  • Gemma4NativeContextTests (new; joins the plan's Gemma suites). 4 tests fail before any reaches Metal (12 issues): the profile is 32,768 + 32,768 in 65,536, the state budget and the TP charge refuse past 65,536, and the lookahead allowance refuses past 32,768. Its two-rank parity test (two in-process ranks of a synthetic checkpoint, the request reserved past 65,536 on contiguous hosts, bit-identical to each other, to the whole model's tokens and to the same request reserved at its own length) needs Metal's allocator, so CI runs it.
  • ResidentAdmissionGemma4Tests: the profile pins, a 32,769-token prompt and a 262,143 + 1 request admitted, the named-state ceiling at 262,144 (3 tests, 5 issues).
  • PairContextWindowTests (new): the leader's local API over a fabricated pair at Gemma's limits. A full prompt gets 400 context_length_exceeded in one Mac's words before any SSE header, streamed or not. max_tokens 300,000 is cut and served. The memory 503 comes before any SSE header. A nonthrowing caller reads the refusal typed. Gemma's pipeline serves its whole profile, and darkbloom cluster local lists what its mode serves (6 of 6, 27 issues).
  • LocalContextWindowTests.aPairCutsToWhatItServes (was aPairKeepsItsOwnLimits).

Fix: e750aec, with tests of the new API:

  • Gemma4NativeContextTests: LOAD's quote is the memory plan's; READY's capacity is one native request; the serving-context gate on synthetic observations (the longest that fits, the next token refused, kept prefixes as room, the smallest request when nothing fits).
  • ResidentAdmissionGemma4Tests: the served and memory profiles, the placement family's profile, the stage gate and the load agreement.
  • ResidentAdmission27BTests: Qwen's stages keep the memory plan.
  • DistributedCBv2EngineTests: the new refusal and its words.

Updated for the cut: DistributedHTTPCompletionTests. An oversized max_tokens is now cut and served, and the "refused before any SSE header" case uses logprobs, which the fixture's mode doesn't capture. Also ClusterPairSlotTests' comment, and the worker's Gemma capability check (prompt 262,143, context 262,144).

Validation

CPU-only, Xcode 27.2, nice -n 19, in a sandbox that denies ~/.darkbloom* and the GPU; one suite per process:

Head What Result
91fef63 (red) the suites above ✘ as listed
e750aec DarkbloomClusterRuntimeTests: Gemma4NativeContextTests 5, ResidentAdmissionGemma4Tests 13, ResidentAdmission27BTests 8, QwenTensorParallelNativeContextTests 8, LongContextLimitsTests 7, ContextAdmissionTests 6, GPTOSSBatchSettingsTests 3, GLM5NextNativeContextTests 8; every Gemma suite, 35 tests in 10 suites ✔
e750aec PlacementChecks (1,646 checks, goldens unchanged), PrefillScheduleChecks' CPU check; the worker's DarkbloomClusterWorker target builds ✔
e750aec ProviderCoreTests: PairContextWindowTests 6, LocalContextWindowTests 10, DistributedCBv2EngineTests 18, DistributedHTTPCompletionTests 10, ClusterPairSlotTests 11, DistributedPairMeasurementTests 9, LocalDefaultOutputTests 3, ClusterAPIParityTests 7, DistributedLocalServerTests 10, ClusterRuntimeApprovalFactsTests 23; filters Distributed 235, Cluster 522, EngineV2Bridge|LocalEndpoint|ProviderLoop|Pair 374 ✔ except image preprocessing (below)
f26c74c (dev 34d446d merged) the cluster suites above; the provider suites above; #1910's and #1912's LocalHeadHoldTests, LocalPrefillProgressTests, MeFirstGiveWayTests, MeFirstWordsTests, LocalRouterPairLeaderTests and 6 more (90 tests); Distributed|Cluster|EngineV2Bridge|LocalEndpoint|ProviderLoop|Pair, 977 tests in 162 suites ✔ except image preprocessing
399b8b1 (dev efb61cc merged) the provider suites above, LocalModelReasoningTests 7, LocalRouterPairLeaderTests, LocalHeadHoldTests ✔
CI on 399b8b1 Cluster Focused Checks shard 1: GLMImageAdmissionChecks didn't compile (DistributedResidentExecution.swift: EngineV2Bridge isn't in its closure) ✘ → 2ad9a62
2ad9a62 the refusal's text moves out of the bridge, where the cluster checks compile it; since 10d9db5 it is the one text both paths use (DistributedRequestRefusal.contextLengthExceededMessage(contextTokens:)); GLMImageAdmissionChecks (40 CPU checks), PairContextWindowTests, DistributedCBv2EngineTests, LocalContextWindowTests, DistributedHTTPCompletionTests, DistributedLogprobAdmissionTests ✔
af2db28 (dev 5347bc3, #1894, merged) 14 suites, 162 tests: #1894's ClusterPairMemberRelayTests, ClusterApprovalServiceStartTests, ClusterServiceRecoveryTests, and the provider suites above ✔
CI on af2db28 (run 42550069113) all 22 jobs: both builds, the CI plans, Cluster Focused Checks 1–2, Cluster Runtime Tests 1–5, Cluster GPU Tests 1–3, Cluster Release Build Checks, Provider Unit Tests 1–2 and the Provider Tests gate. In runtime shard 5, with Metal: ranksReservedPastTheStandardRequestAgreeWithTheWholeModel (100.5 s), aRequestPastTheStandardOneHasItsState (3 cases) and the base Gemma selection, 61 tests in 9 suites ✔ (the Vercel d-inference and d-inference-console-ui-dev deployments fail, as on dev 5347bc3)
10d9db5, dec9a23 (the refactor pass, below) the same suites before and after, the same wide test lists and the same 9 image-preprocessing issues; CI runs 42560537326 and 42565012712, all 21 test and plan jobs, the parity test with Metal (111.8 s, 113.8 s) ✔
3c03cd1 (99881ca: the pass's findings; dev c498607 merged: #1906, #1911, #1924, #1925) Gemma4NativeContextTests 6, ResidentAdmissionGemma4Tests 13, ResidentAdmission27BTests 8, QwenTensorParallelNativeContextTests 8, LongContextLimitsTests 7, ContextAdmissionTests 6; PairContextWindowTests 6, LocalContextWindowTests 10, DistributedCBv2EngineTests 18, DistributedHTTPCompletionTests 10, ClusterPairSlotTests 11, DistributedLocalServerTests 11, LocalModelReasoningTests 7, SlotRequestLimitsWireTests 2 ✔

make docs-check (211 files), make docs-impact-check BASE=origin/dev, make changelog-check, cluster-test-plan.py audit and test-cluster-test-plan.py pass.

Not run here:

  • Metal. 41 Gemma tests need Metal, among them this change's parity test and the state test's stage geometry. So do 19 provider tests and suites. They stop at metal::load_device in this sandbox; CI ran them (above). The parity test adds about 110 s to CI's base Gemma selection.
  • Image preprocessing. 6 media-ingress tests (each stops the process with a fatal error), GLMClusterTensorParallelMediaTests.imageRequestLeavesWithTheProductsPromptAndAnEnvelope and GLM's two image parity cases fail in image and video preprocessing (ingress.prepare, one Mac's media path). This change doesn't touch that code; CI runs them.

Proof on pair-2 (W1)

This change is proven on hardware by Gemma 4 26B at 64K- and 128K-token prompts, in tensor parallel and in the pipeline, on pair-2. Both Macs must run this PR's head, or a dev build that contains it.

P2=~/build/merge/mainnet/overnight/tp-perf/bin/p2
SSHF="-F ~/build/merge/mainnet/pair2-evidence/ssh_config"
E=~/build/merge/mainnet/overnight/local-first/validation-evidence/journey-2b
# 0. Both Macs on the build with this PR; record it.
$P2 p2-ultra '~/.darkbloom-dev/bin/darkbloom-dev cluster status --details --json' > $E/w1-before.json
$P2 p2-max '~/.darkbloom-dev/bin/darkbloom-dev cluster status'
# 1. Tensor parallel: on the Studio, `darkbloom-dev cluster` → Gemma 4 26B, tensor parallel, "Both, me first"
#    (as journey 2b §3). Then copy the probe below to the Studio and run it there:
scp $SSHF gemma-native-probe.py p2-ultra:lf-val/
$P2 p2-ultra 'python3 ~/lf-val/gemma-native-probe.py ~/.darkbloom-dev/bin/darkbloom-dev tp' | tee $E/w1-gemma-tp.txt
# 2. Pipeline: switch the pair to Gemma 4 26B in the pipeline (journey 2b's split: M3 Ultra 1 layer / M5 Max 29), then:
$P2 p2-ultra 'python3 ~/lf-val/gemma-native-probe.py ~/.darkbloom-dev/bin/darkbloom-dev pipeline' | tee $E/w1-gemma-pipeline.txt
# 3. Both modes: crash counts unchanged, the pair still serving.
$P2 p2-ultra '~/.darkbloom-dev/bin/darkbloom-dev cluster status'; $P2 p2-max '~/.darkbloom-dev/bin/darkbloom-dev cluster status'

gemma-native-probe.py (stdlib only; it reads the leader's address and key from darkbloom-dev local --json on the Studio):

#!/usr/bin/env python3
import json, subprocess, sys, time, urllib.error, urllib.request
cli, mode = sys.argv[1], sys.argv[2]
info = json.loads(subprocess.run([cli, "local", "--json"], capture_output=True, text=True, check=True).stdout)
base, key, model = info["base_url"].rstrip("/"), info["api_key"], "gemma-4-26b-qat-4bit"
base = base if base.endswith("/v1") else base + "/v1"
WORDS = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa".split()

def call(body=None, path="/chat/completions", timeout=3600):
    data = None if body is None else json.dumps(body).encode()
    request = urllib.request.Request(base + path, data=data, method="GET" if data is None else "POST",
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
    started = time.time()
    try:
        with urllib.request.urlopen(request, timeout=timeout) as reply:
            return reply.status, reply.headers.get("Content-Type", ""), reply.read().decode(), time.time() - started
    except urllib.error.HTTPError as error:
        return error.code, error.headers.get("Content-Type", ""), error.read().decode(), time.time() - started

def chat(words, max_tokens=64, stream=False, ask="Name three primary colors."):
    text = " ".join(WORDS[i % len(WORDS)] + str(i % 997) for i in range(words))
    body = {"model": model, "stream": stream, "max_tokens": max_tokens, "messages": [
        {"role": "user", "content": text + "\n\nIgnore the text above. " + ask}]}
    return call(body)

def report(label, answer):
    status, kind, text, seconds = answer
    line = f"{mode} {label}: {status} {kind.split(';')[0]} {seconds:.1f}s"
    if kind.startswith("text/event-stream"):
        frames = [f[6:] for f in text.split("\n\n") if f.startswith("data: ") and f[6:] != "[DONE]"]
        finish = [c.get("finish_reason") for f in frames for c in json.loads(f).get("choices", []) if c.get("finish_reason")]
        progress, failed = text.count(": prefill in progress"), '"error"' in text
        line += f" finish={finish} progress={progress} error={failed}"
    else:
        body = json.loads(text)
        if "error" in body:
            line += f" code={body['error'].get('code')} message={body['error'].get('message')!r}"
        else:
            line += f" finish={body['choices'][0]['finish_reason']} usage={body.get('usage')}"
    print(line, flush=True)
    return text

listed = json.loads(call(path="/models")[2])
entry = next(m for m in listed["data"] if m["id"] == model)
print(f"{mode} models: context_length={entry.get('context_length')} max_output_length={entry.get('max_output_length')}")
usage = json.loads(report("calibrate 2,000 words", chat(2_000, max_tokens=1)))["usage"]
per_word = usage["prompt_tokens"] / 2_000
for label, tokens in [("64K", 65_000), ("128K", 130_000)]:
    words = int(tokens / per_word)
    report(f"{label} non-streamed", chat(words))
    report(f"{label} streamed", chat(words, stream=True))
report("max_tokens 300,000", chat(200, max_tokens=300_000))
over = int(275_000 / per_word)  # well past 262,144, whatever the estimate's error
report("over the context, non-streamed", chat(over))
report("over the context, streamed", chat(over, stream=True))
if sys.argv[3:] == ["heavy"]:  # a ~9-minute prefill, then output until the context is full
    report("near the context, cut", chat(int(258_000 / per_word), max_tokens=300_000,
        ask="Count upward from 1, one number per line, and never stop."))

Pass, in each mode:

  • models: context_length=262144 max_output_length=32768;
  • 64K and 128K, both ways: 200 and finish=['stop'] (or stop in the JSON), no "error", prompt_tokens about 65,000 and 130,000, and streamed progress above 0. Was: 200 then finish=['error'] "Response generation failed";
  • max_tokens 300,000: 200, served. Was: 400 output_too_long;
  • over the context, both ways: 400 application/json, code=context_length_exceeded, message "The prompt fills this model's context window of 262144 tokens, leaving no room for an answer. Shorten the prompt or start a new conversation." Neither Mac's worker sees it;
  • optional, heavy (append heavy to the command; a ~9-minute prefill, then output until the context is full): near the context, cut is 200 with finish=length and prompt_tokens + completion_tokens = 262,144.

A memory 503 needs a request longer than both Macs admit now. pair-2's Macs hold a 262,144-token Gemma request at rest, so that case rests on the tests.

What MiMo V2.6 tensor parallel needs (proof later on the M5 Ultras)

The provider needs nothing new: tensor parallel already serves the whole profile, the cut, the one-Mac context_length_exceeded and the memory 503 before any SSE head are family-agnostic, and MiMo's pipeline keeps the memory plan (pipelineServesWholeProfile is false for .mimoV26LayerStage). The worker needs the same shape, not built here:

  1. A native profile in MiMoRegisteredSpecification (1,048,576 context, the catalog's 131,072 output) beside a memory profile at the standard request; today contextLimits() is the standard request. Both ranks bind the memory plan into their load agreement, as Gemma's memory= does.
  2. The pipeline keeps the memory plan wherever it reads the profile: MiMoResidentRuntime, its context search (LayerStageContextGate.admitted(profile:)), and the stage ledgers MiMoRequestStateBudget and MiMoPagedKVAllowance. Otherwise MiMo's pipeline would search and admit up to 1M while the provider advertises 65,536.
  3. LOAD at the memory plan. MiMoTensorParallelResidentRuntime.load quotes requestBudget(… contextTokens: profile.maximumContextTokens …); it must quote the memory plan's context.
  4. READY's capacity becomes max(LOAD's quote, one request at the native context), as Gemma's capacityBytes does: reserve refuses a charge above baseReady.requestCapacityBytes.
  5. A serving context: a charge with admits and servingContextTokens that mirror its requireLiveMemory, as Gemma4TensorParallelRequestCharge does, and refreshServingContext wired into NativeWorkerRuntime (both refreshes return nil for .mimoV26TensorParallel today).
  6. Sizing, the real blocker. MiMoTensorParallelRequestBudget charges a chunk's full-layer FP32 attention scores as if materialized. A request at 65,536 tokens is 6.25 GB a rank (4.29 GB of scores); at 1,048,576 it is 94.59 GB (68.72 GB of scores, 25.69 GB of history), beside a 10.27 GB rank reserve, the 4 GiB headroom and about 84 GB of weights: about 193 GB a rank. Serving 1M on 256 GB Macs needs that term priced as the fused or chunked kernel runs it.
  7. No other cap on the TP path: its request budget accepts any context. (MiMoPhaseSplit's (1...32_768) prompt bound is the pipeline hand-off's, not tensor parallel's; the prefill window and lookahead bounds this PR lifted are shared.)
  8. Proof: a CPU two-rank synthetic test reserved past the standard request, bit-identical to the whole model (as ranksReservedPastTheStandardRequestAgreeWithTheWholeModel); long-position parity on the M5 Ultras at 128K, 256K and 1M against the one-process oracle; a capacity 503 when a rank can't hold it. The coordinator then routes MiMo TP by request_limits 1,048,575 / 131,072 / 1,048,576.

Limitations

  • The CPU parity covers a reservation past 65,536, not long positions. The two-rank oracle runs a 40-token prompt reserved for 65,540 tokens. Real positions past 65,536 (RoPE and sliding windows at depth) rest on the pair-2 proof above.
  • The first-token budget. A 262,143-token prompt's allowance is the setup's per-token share at that length, as for the 27B's native context; a long prefill on pair-2 is unmeasured.
  • A pipeline with lanes keeps READY's serving context (no keep-warm refresh for lane owners, as for every stage mode). Each reservation is still gated live, so a request that no longer fits gets a 503 alone.
  • The coordinator still routes by request_limits, now 262,143, 32,768 and 262,144 for Gemma in both modes, and the release's public envelope for Gemma's pipeline grows to match. The cut applies to every request that reaches a pair.
  • Gemma on a pair is still text-only (J2b-3); not in this PR.
  • The memory 503 keeps one Mac's words ("This Mac's memory …") on a pair, as R-FULL asks.
  • Gemma's profile fingerprint changes (capability record, load agreements, installed start), so Gemma setups re-plan after the update. Bundled qualification records don't bind it.

Review and refactor pass

Refactor pass: done (refactor-1923.md; heads 10d9db53d9, dec9a23cec; behaviour-preserving):

  • one rule for what a Gemma pair serves (ClusterRuntimeAdapter.pipelineServesWholeProfile, read by the provider and the worker's stages; Gemma's override is gone);
  • one cut for one Mac and a pair (EngineV2Bridge.outputTokens), and one text for context_length_exceeded (DistributedRequestRefusal.contextLengthExceededMessage(contextTokens:); EngineV2Bridge.promptExceedsContextMessage is removed);
  • one place for a pair's default output and listed limits (DistributedEngineFactory.defaultMaxTokens(_:), LocalModelLimits(served:)), and for a Gemma TP rank's charges (Gemma4TensorParallelRequestCharge.budget(…));
  • 12 mutants: 11 caught by the suites; the twelfth (the charge ignoring a request's cache-off capture) is caught by dec9a23cec's aRequestIsChargedTheRanksTermsAtItsOwnContext.

Its findings, fixed in 99881ca78a: a stage logs the context it serves (limit=, not the memory plan's 65,536 beside admitted=262144); requireWithinServedProfile's refusal no longer says "only tensor parallel serves the model's native context"; SlotRequestLimits.maxOutputTokens and LocalModelLimits(window:) say the bridge cuts. Left as a follow-up: provider-swift/Tests/ClusterConfigurationChecks/run.sh doesn't compile on dev (no CI job runs it).

Independent review: in progress on dec9a23cec, with this delta.

Coordination: #1908, #1910, #1912, #1914, #1894, #1906, #1911, #1924 and #1925 are merged in (dev c498607). Overlap was textual only: the bridge's submission path (#1912's head hold is one Mac's; a pair's refusal is thrown before its stream), EngineV2Bridge, ProviderLoop+LocalEndpoint and the docs. A member's relay (#1894) passes the leader's answers on, so a member's local request meets the same 400s, 503 and cut.

jonathan308 and others added 5 commits November 8, 2026 15:00
…okens, cuts an oversized max_tokens, and refuses a full prompt in one Mac's words (red)

R-FULL D2 and D3 (`R-FULL.md` §3), from journey 2b on pair-2
(`validation-evidence/journey-2b.md`, Gemma 4 26B, 2026-11-08): the pair
advertised 65,536 tokens of context where one Mac serves the model's
262,144; a streamed prompt past its 32,767-token prompt limit got a 200 and
then "Response generation failed"; a `max_tokens` above 32,768 got a 400
`output_too_long` where one Mac cuts it.

Red first.

DarkbloomClusterRuntimeTests (compile against today's sources):
- Gemma4NativeContextTests (new; joins the plan's Gemma suites):
  - every registered row's profile is the declared context, 262,144: prompt
    262,143, output 32,768 (the catalog's), in both modes;
  - a request past the standard 65,536 tokens has its state (full layers
    every token, sliding layers their ring) up to the wire's longest
    context, and no further;
  - a tensor-parallel rank charges such a request at its own context; the
    standard request's quote is as before;
  - the pipeline's lookahead prefill takes a prompt past 32,768 tokens with
    the same one-frame allowance;
  - two ranks whose request is reserved past the standard request agree bit
    for bit with each other, with the whole model's tokens, and with the
    same request reserved at its own length (a synthetic checkpoint on
    contiguous hosts, on the CPU; MLX's allocator needs Metal, so CI runs it).
- ResidentAdmissionGemma4Tests: the profile pins move to 262,143 and
  262,144; a 32,769-token prompt, and a 262,143-token prompt with one output
  token, are admitted; 262,144 is refused; the named-state ceiling is the
  ledger at 262,144.

ProviderCoreTests:
- PairContextWindowTests (new): the leader's local API over a fabricated
  pair at Gemma's native limits. A prompt that fills the context is a 400
  `context_length_exceeded` in one Mac's words before any SSE header,
  streamed or not; a `max_tokens` of 300,000 is cut to what the prompt
  leaves and served, `finish_reason` "length"; a request the ranks' memory
  can't hold now gets one Mac's memory 503 before any SSE header; a
  nonthrowing caller reads the refusal typed; Gemma's pipeline serves its
  whole profile (GLM 5.3's keeps the memory plan's request); `darkbloom
  cluster local` lists what its mode serves.
- LocalContextWindowTests: aPairKeepsItsOwnLimits becomes
  aPairCutsToWhatItServes (a pair cuts as one Mac does).
- DistributedLocalServerTestSupport: LocalHostTestSession(served:).

On c76445a: Gemma4NativeContextTests fails 4 tests, each before it
reaches Metal (12 issues); then the parity test stops at
`metal::load_device` in the GPU-denying sandbox (every MLX array needs
Metal's allocator, so it and the state test's stage geometry run in CI's
Gemma shard). ResidentAdmissionGemma4Tests fails 3 (5 issues),
PairContextWindowTests 6 of 6 (27 issues: a 200 then an in-band error when
streamed, `prompt_too_long`, `output_too_long`, the memory plan's 65,536),
LocalContextWindowTests 1 (2 issues).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…kens in both modes, cuts an oversized max_tokens, and refuses before any SSE header

R-FULL D2 and D3, on the red commit's tests (91fef63).

Gemma 4 26B on a pair:
- Its profile is the model's declared context
  (`Gemma4ResidentAdapterDefinition.contextLimits`, `.native`): 262,144
  tokens, prompts up to 262,143, output 32,768 (the catalog's
  `max_output_length`). LOAD, every quote and the planner still size a pair
  for the memory plan's request (`memoryProfile`, the standard 32,768 +
  32,768), so placement and LOAD are as before. Both ranks agree on that
  plan in their load agreement.
- Tensor parallel: `Gemma4TensorParallelRequestCharge` charges a request
  past the memory plan at its own context (its own KV heads, attention
  transient, partials, vocabulary rows and prefix capture). READY's capacity
  covers one request at 262,144 (a ceiling, never a grant). READY and each
  keep-warm answer carry the longest context the reservation gate admits now
  (`servingContextTokens`, `refreshServingContext`, which
  `NativeWorkerRuntime` now calls for this owner, single and lanes).
- Pipeline (D3): a layer-stage family names the requests its stages serve
  (`LayerStageResidentAdmission.servedProfile`, the memory plan by default).
  Gemma's is its whole profile: each stage charges the whole model's ledger
  at the request's own context when it is reserved, admitted by that rank's
  live gate. READY's capacity covers the longest, the stage KV host's bound
  is the served profile's (a ceiling: pages grow with each request), and the
  serving context searches up to it (the pair takes the smaller of the two
  stages', as before). `requireWithinMemoryProfile` is now
  `requireWithinServedProfile`; every other family is unchanged.
- The bounds that held a Gemma request to the standard 65,536 tokens take
  any context the wire carries (`Gemma4StateBudget`, the Gemma request
  geometry, the lookahead prefill's allowance and window). The profile holds
  a request to the model's own.

The provider:
- `ClusterModelFeaturePolicy.servedProfile`: a Gemma pipeline serves its
  whole profile, as tensor parallel does; every other pipeline its memory
  plan.
- A prompt that fills the context the pair serves is refused with one Mac's
  400: `context_length_exceeded`, in one Mac's words
  (`DistributedRequestRefusal.contextLengthExceeded`, which the coordinator
  classes as exceeding context).
- A `max_tokens` past the output or the context a pair serves is cut to fit,
  as one Mac cuts to its window (`EngineV2Bridge.pairServedLimits`). An
  omitted one defaults within the served limits.
- A pair's refusal of a request, and a request both Macs' memory can't hold
  now (one Mac's memory 503), are thrown before any stream exists on every
  API. A streamed request gets its status, not a 200 and then "Response
  generation failed" (the leader's local endpoint in "Both, me first" has no
  pair HTTP writer). A nonthrowing caller still reads the refusal typed.
- `darkbloom cluster local` lists and defaults from what its mode serves.

Tests with the new API: Gemma4NativeContextTests (the charge's LOAD quote,
READY capacity and serving-context gate, on synthetic observations),
ResidentAdmissionGemma4Tests (served and memory profiles, the stage gate,
the load agreement), ResidentAdmission27BTests (Qwen's stages keep the
memory plan), DistributedCBv2EngineTests (the new refusal and its words).
Updated for the cut: DistributedHTTPCompletionTests (an oversized
`max_tokens` is cut and served; the refusal case is now logprobs, which the
fixture's mode does not capture), ClusterPairSlotTests' comment, and the
worker's Gemma capability check (prompt 262,143, context 262,144).

Green (CPU-only, Xcode 27.2, `nice -n 19`, the GPU-denying sandbox):
- DarkbloomClusterRuntimeTests: Gemma4NativeContextTests 5, ResidentAdmission
  Gemma4Tests 13, ResidentAdmission27BTests 8, QwenTensorParallelNativeContext
  Tests 8, LongContextLimitsTests 7, ContextAdmissionTests 6, GPTOSSBatch
  SettingsTests 3, GLM5NextNativeContextTests 8; every `Gemma` suite, 35 tests
  in 10 suites. The 41 that need Metal (this change's parity test and the
  state test's stage geometry among them) run in CI's Gemma shards.
- PlacementChecks (1,646 checks), PrefillScheduleChecks' CPU check, and the
  worker's `DarkbloomClusterWorker` target builds.
- ProviderCoreTests: PairContextWindowTests 6, LocalContextWindowTests 10,
  DistributedCBv2EngineTests 18, DistributedHTTPCompletionTests 10,
  ClusterPairSlotTests 11, DistributedPairMeasurementTests 9,
  LocalDefaultOutputTests 3, ClusterAPIParityTests 7, DistributedLocalServer
  Tests 10, ClusterRuntimeApprovalFactsTests 23; `Distributed` 235 tests,
  `Cluster` 522 and `EngineV2Bridge|LocalEndpoint|ProviderLoop|Pair` 374,
  with Metal-needing tests skipped. The only failures are image and video
  preprocessing (Qwen and GLM media ingress, GLM's image parity cases),
  which this change does not touch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1904, #1916, #1910, #1912) into rfull/d2-gemma-pair-context

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d one Mac's refusals before any SSE header

- inference: a new "Gemma 4 native context on a pair" section: the profile
  and the memory plan, what tensor parallel and the pipeline charge a longer
  request (10.4 GB a tensor-parallel rank at 262,144 tokens; a stage's 6.4 GB
  ledger and 8.6 GB prompt frame), READY's capacity and serving context, the
  provider's cut and refusals, and the fingerprints that change. The 27B's
  section names `requireWithinServedProfile`; the placement table's
  `requestAllowance` is the memory plan's.
- hardware-support: the Gemma rank's LOAD quote is the memory plan's, and a
  longer request is charged at its own context.
- two-mac-cluster, "Response length": Gemma 4 26B's native limits in both
  modes; an oversized `max_tokens` is cut on any pair; a full prompt gets
  `context_length_exceeded` and a memory shortfall one Mac's 503, both before
  any streamed byte.
- protocol-messages: `request_limits` as the cluster now applies them (a
  larger `max_tokens` is cut; a prompt that fills the context is refused), and
  Gemma's pipeline limits.
- changelog.d/gemma-pair-native-context.md.

`make docs-check`, `make docs-impact-check BASE=origin/dev` and
`make changelog-check` pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
d-inference Error Error Nov 9, 2026 5:29am UTC
d-inference-console-ui-dev Error Error Nov 9, 2026 5:29am UTC
d-inference-landing Ready Ready Preview Nov 9, 2026 5:29am UTC
darkbloom-status Ready Ready Preview Nov 9, 2026 5:29am UTC
eigen-homepages-darkbloom Ready Ready Preview Nov 9, 2026 5:29am UTC

Request Review

jonathan308 and others added 2 commits November 8, 2026 18:10
…ac's words, so the cluster checks' closures compile

Cluster Focused Checks (shard 1, run 42547335815) stopped at
GLMImageAdmissionChecks: `DistributedResidentExecution.swift:344: cannot find
'EngineV2Bridge' in scope`. Several cluster checks compile that file without
the bridge (GLMImageAdmissionChecks, ProcessChecks, ClusterConsoleChecks, and
the provider's placement, installed-session and diagnostics checks). So
`DistributedRequestRefusal.contextLengthExceeded` keeps its own copy of
`EngineV2Bridge.promptExceedsContextMessage`'s words, and
PairContextWindowTests and DistributedCBv2EngineTests hold the two equal.

GLMImageAdmissionChecks passes (40 CPU checks). PairContextWindowTests 6,
DistributedCBv2EngineTests 18, LocalContextWindowTests 10,
DistributedHTTPCompletionTests 10 and DistributedLogprobAdmissionTests 3 pass
(CPU-only, Xcode 27.2, `nice -n 19`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ne cut and one text for one Mac and a pair

The refactor pass for #1923 (d-inference AGENTS.md, "Required Refactor
Pass"). Behaviour preserved; no assertion weakened.

- One place for the pipeline rule. `ClusterRuntimeAdapter.pipelineServesWholeProfile`
  (Gemma 4 only) is read by the provider's `ClusterModelFeaturePolicy.servedProfile`
  (what a pair advertises and holds a request to) and by the worker's
  `LayerStageResidentAdmission.servedProfile` (what its stages admit), so
  the two can no longer differ. The Gemma override goes; `servedProfile` is
  no longer a requirement a family could override.
- One cut. `EngineV2Bridge.outputTokens` cuts an explicit `max_tokens` by one
  rule on one Mac and a pair: at most the output limit and what the prompt
  leaves of the context (one Mac's output limit is its window).
- One text for `context_length_exceeded`.
  `DistributedRequestRefusal.contextLengthExceededMessage` is what both one
  Mac and a pair refuse a full prompt in (the pair kept its own copy, held
  equal by tests); it lives beside the pair's refusals because the cluster
  checks compile that file without the bridge.
  `EngineV2Bridge.promptExceedsContextMessage` goes. The in-band refusal
  marker has one encoder (`distributedRefusalMessage(_:text:)`).
- One place for a pair's default output
  (`DistributedEngineFactory.defaultMaxTokens`: the bridge and both local
  APIs) and for how a pair lists its limits (`LocalModelLimits(served:)`:
  the leader's and `cluster local`'s `/v1/models`).
- One place for a Gemma tensor-parallel rank's charges.
  `Gemma4TensorParallelRequestCharge.budget` takes the terms for LOAD's quote,
  a reservation or lane at its own context, the share probe, READY's
  capacity and the serving context; the runtime's `requestBudget` and
  `requestChargeBytes` go.
- The smallest useful request is `LayerStageContextGate.minimumContextTokens`
  in the Gemma charge and the stage runtime; the stage READY capacity's two
  prefill allowances share one local function.
- Comments say the invariants: the advertised context is what the mode
  serves; a request is charged at its own context (the Gemma stage's
  `requestAllowance`); refusals are typed and thrown before any stream, as on
  one Mac. Stale comments fixed (`served` said a pipeline always serves the
  memory plan; the Gemma budget said LOAD quotes the profile's prompt).
- Tests: the memory 503's words are one helper (`memoryRefusalWords`) in
  `PairContextWindowTests` and `LocalContextWindowTests`; one expectation
  added: only Gemma 4's adapter serves its whole profile in the pipeline.
- Docs: `inference.md` names the one rule and the one text;
  `direct-mode.md` cites where the window refusal's words now live.

CPU-only, Xcode 27.2, `nice -n 19`, in a sandbox without the GPU, before and
after on the same build folders: provider `Distributed|Cluster|EngineV2Bridge|
LocalEndpoint|ProviderLoop|Pair`, 1,016 tests in 164 suites, the same list
and the same 9 image-preprocessing issues; 22 focused provider suites pass;
cluster `Gemma` 35 tests and `ResidentAdmission|LongContext|ContextAdmission|
NativeContext|Prefill|ServingContext|LayerStage` 138 tests, the same lists
(one Metal issue in both); 8 focused cluster suites pass;
`GLMImageAdmissionChecks` (40) and `PlacementChecks` (1,646, output
identical) pass; the worker target builds. `docs-check`, `docs-impact-check`,
`changelog check`, the cluster test plan's audit and tests, and
`git diff --check` pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…terms at its own context, its capture only when its cache is on

The refactor pass's mutants (CPU) showed one rule of
`Gemma4TensorParallelRequestCharge.budget` that no CPU test held: a request
whose own cache is off (or the share probe) is charged no prompt capture,
whatever the rank keeps. `Gemma4NativeContextTests.aRequestIsChargedTheRanksTermsAtItsOwnContext`
now does, for a rank that keeps prefixes and one that doesn't, at 8,320,
131,072 and 262,144 tokens: each charge equals LOAD's terms
(`Gemma4TensorParallelRequestBudget.derive`) at that context, prompt and
chunk. The mutant that ignores the request's override fails it (4 issues).

Gemma4NativeContextTests 6/6, ResidentAdmissionGemma4Tests 13,
ResidentAdmission27BTests 8 and every Gemma suite (36 tests) pass (CPU-only,
Xcode 27.2, `nice -n 19`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 and others added 2 commits November 8, 2026 21:26
…efusal and two doc comments say what is true now

The refactor pass's "Found and not changed" (`refactor-1923.md`), findings 1, 2, 3 and 6:

- `darkbloom-resident-context-v1 … limit=` logs the served profile's context
  (`admission.servedProfile`), the one the admitted context is searched up
  to. A Gemma stage logged `limit=65536 admitted=262144`. No test pins the
  line.
- `requireWithinServedProfile`'s refusal no longer ends "only tensor
  parallel serves the model's native context": it isn't true of a family
  whose stages serve their whole profile (Gemma 4). What remains is right
  for every family, Qwen's included. No test pins the text.
- `SlotRequestLimits.maxOutputTokens`: the bridge cuts before the engine; the
  engine's `output_too_long` is left for a caller that submits to it
  directly.
- `LocalModelLimits(window:)`: a `max_tokens` past an advertised context is
  cut too (#1893), not refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gemma-pair-context

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

2 failed (outdated) and 3 active deployments
Preview – d-inference-landing — 3c03cd1f Deployed Nov 9, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — 3c03cd1f Deployed Nov 9, 2026 by vercel[bot]
Preview – darkbloom-status — 3c03cd1f Deployed Nov 9, 2026 by vercel[bot]
Preview – d-inference — 10d9db53 Deployed Nov 9, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 10d9db53 Deployed Nov 9, 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.

1 participant