diff --git a/CHANGELOG.md b/CHANGELOG.md index e897e8dd4e..eaf320c1ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,804 @@ or console deployment, feature activation, model promotion or hardware qualification. Sections marked historical retain the original candidate's qualification, opt-in and deployment limits rather than claiming activation. -## v0.10.5 — candidate (unpublished) +## v0.10.6 — candidate (unpublished) -Prepared on 2026-10-30; tagging and publication are separate steps. +Prepared on 2026-10-31; tagging and publication are separate steps. + +### Upgrade and rollout notes + +- This is the first production release with two-Mac clusters (#1628 with #1407, #1426 and #1577, and the cluster PRs merged after it): run `darkbloom cluster` on each of two Apple silicon Macs joined by one Thunderbolt 5 cable, pick a model, and the pair serves it together. Both Macs need macOS 26.2 or later, RDMA over Thunderbolt turned on by an administrator (System Settings on macOS 27, `rdma_ctl enable` in Recovery on macOS 26) and the same Darkbloom release. The planner chooses tensor parallel or a pipeline; GLM-5.3-Flash and Qwen3.8-27B can serve in tensor parallel, with images and video. `darkbloom cluster local` serves a pair without any coordinator. A Mac that never runs `darkbloom cluster` keeps serving alone. +- Releases carry their cluster runtime facts (#1692): every release lane computes them from the final signed app and shows them in its job summary, and the registration carries them as `cluster_runtime` only while that environment's repository variable is `true`. A coordinator with darkbloom-platform#643 and `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` derives from them the build's cluster approvals, their pair-serving grants and the public qualifications of GLM-5.3-Flash and Qwen3.8-27B in pipeline and tensor parallel (the owner's decisions of 2026-10-31); every other model's clusters serve their owner only. A pair without a cluster approval serves only on its leading Mac's local API, with the `darkbloom start --local` key. +- A production registration carries the block only once `PROD_CLUSTER_RUNTIME_ENABLED=true`, which is set only after the following, and before the tag, because a release registered without the block can never gain one. A coordinator without #643 refuses a registration that carries the block, and the release then fails after signing. + - The production coordinator runs #643, with migration 58 applied and three cluster settings: `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`, `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` and `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` (without it no member connection attaches to pair control behind production's TLS-terminating proxy). Approvals derived from releases are its only approval source: `EIGENINFERENCE_CLUSTER_PAIRS`, the operator's approval table, stays unset. App Attest serving is on for every account (`EIGENINFERENCE_APP_ATTEST_SERVING=true`, `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT=production`, `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT=100`), because a member on macOS 27 without MDM pairs only through App Attest. +- This release was not proven on DevNet first: its derived approvals and a pair session under one are first checked in production. The entry "A Mac pair registers with the coordinator as a cluster member by itself (DevNet)" below predates this: with the coordinator above, production has pair control and serves the approvals derived from this release. +- Single-Mac serving needs no coordinator change and no provider-version floor, but three answers to coordinator requests change, all with codes the coordinator already knows. A content part of an unknown type is refused with 400 instead of being answered from the remaining text. Media the model's processor refuses answers 400 `invalid_media` instead of the retryable 503. A `response_format` answer cut off by `max_tokens` is a client error (`client_error`) instead of the retryable `tool_noncompliance`, so the coordinator no longer retries it on another provider. After the tag the platform snapshots its provider contracts from the tagged commit and sets `LatestProviderVersion` to `0.10.6`; of the 34 snapshotted inputs only `ProviderCore.swift` changes since v0.10.5. +- The local API of one Mac (`darkbloom start --local`) changes too. A request that fails to decode is normalized as on the coordinator path (a scalar `stop`, the `developer` role, messages without content, hosted tools) and decoded again before it is refused. It returns `logprobs` where the model captures them and reports `usage.completion_tokens_details.reasoning_tokens`, and it answers a `response_format` request cut off by `max_tokens` with 422 and a message that says so, instead of "Internal inference failure.". Two operator changes have no entry of their own: `provider.toml` is written owner-only (a group- or world-readable file is tightened at its next save), and the 0.10.6 updater (`darkbloom update` and the automatic update) extracts the next release under `umask 022`, as the installer has since v0.10.0. +- Recent cluster fixes: a registered pair's cluster service is no longer restarted many times a day by its own part's heartbeats (#1690); pair members register GLM-5.3-Flash and Qwen3.8-27B under their pair-serving grant instead of ending a second after they start (#1686); a single Qwen3.8-27B request in tensor parallel decodes about 6% faster on two M5 Ultra with an M5 Ultra verify-window layout (#1680). On every Mac, `darkbloom models download` and the `darkbloom start` picker show one progress line (#1683); without a terminal they print a plain line at most every 30 seconds, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. +- MLX pins: `libs/mlx` and the nested `mlx` (`72dffa2d`) and `libs/mlx-swift` (`c633d221`) are unchanged from v0.10.5. `libs/mlx-swift-lm` moves from `2beb401f` to `7933a0fa`, its fork's `main` (#1680, #1684): SDK #373 adds an M5 Ultra layout table to `AffineQuantizedVectors`, which only the cluster's Qwen tensor-parallel exact projections use, and a layout never changes a result. The MLX core is unchanged, so the tag build's `metallib_hash` should equal v0.10.5's `98bab9d7…614be`, which the dev-branch build of this preparation's base (`a0413a8a`) also registered on DevNet. Complete SSD checkpoints stay per build, because their namespace binds the binary hash: 0.10.6 does not restore those 0.10.5 wrote. Cluster entries below that describe MLX or SDK work (steel tiles, `MLX_QMV_BATCH_INVARIANT`, fast-fence ordering, GPU streams that no longer spin on each other's fences, the GLM-5.3-Flash SDK speedups) describe code that v0.10.5's pins already contain. +- The 107 entries below are the pending fragments rendered verbatim, in filename order. Most were written on the cluster branch, and some record steps that newer entries supersede, wherever those sit in the list: "Fixed" predates GLM-5.3-Flash tensor parallel; widened Qwen tensor-parallel owners keep fast fences, not the event path; the pair's SSD prefix records are `balanced` by default, not exact; and Qwen3.8 27B tensor-parallel text speculation ships (automatic setup drafts three tokens a round). Four single-Mac statements repeat changes that v0.10.0 published: `previous_response_id` on one Mac, "Preserve truncated reasoning in collected responses", the local API's reasoning by model type (two bullets of the `darkbloom cluster local` entry) and the start-time weight hash without the file cache (in the MiMo entry). #1666 (approval check follow-ups) and #1674 (CI shards) have no entry. + +### One progress line for model downloads + +- `darkbloom models download` and the `darkbloom start` picker show one line for the whole model, redrawn in place at most four times a second: a bar, the percent, the bytes, the rate and the time left, leaving out what does not fit the window's width. They no longer print a line for every file or a block of per-file bars. +- The line keeps its shape while the window keeps its width: each figure has a fixed column, sized for its widest form, so the bar and the figures do not move as the numbers change. The rate and the time left appear after 2 seconds, and a time left over 24 hours is not shown. +- The line reads "Verifying" while the files are checked, then ends with one line: `✓ Downloaded (16.3 GB in 2m 10s)`, `✓ is already downloaded (16.3 GB)`, where the download stopped, or `Verification of failed: `. The picker no longer adds its own "Downloaded" line, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. +- Without a terminal (a pipe, a log, the desktop app) the download prints plain lines with no carriage returns: the first at once, then at most one per 30 s and 10 points, one at 100%, and the same last lines. The desktop app reads its download progress from them. +- `darkbloom cluster` shows a model download or a copy over the cable on its live line instead of adding a line every second. A plain transcript keeps the first report, about one per 30 s and 10 points, and the lines for the record. +- Sizes in the line are decimal, as the catalog gives them. + +### Identical Macs split a model evenly + +- When cuts predict the same request time (identical Macs, or equal measured speeds), the placement planner now chooses the one that uses each Mac's hardware capacity most evenly, instead of the earliest cut the second Mac's free memory held at that moment. Two M5 Ultra 256 GB had planned GLM-5.3-Flash 11/34 and then 5/40 of its 45 layers; they now plan it 22/23 whichever Mac leads. A faster split is never traded for balance, and the "Quit apps first" refusal is unchanged. This applies to every model the cluster plans. + +### Bonsai FP32 residual stream and the cluster memory gate under pressure + +- Bonsai (Prism) packs keep their FP32 residual stream on the fused Qwen 3.5 decode, verify and stage paths. The fused residual step rounded each FP32 branch to the stream's FP16 embedding dtype, so the stream stayed FP16 and a Bonsai producer stage's residual left its FP32 contract; such a stream now takes the unfused sum, as the unfused forward computes it. Qwen 27B and the other uniform-dtype rows are unchanged. +- The cluster load gate's room-making pass runs only at normal memory pressure. Above it the gate withdraws all file cache on purpose, and a refusal now stands on the gate's own sample instead of a fresh one taken after the pass. + +### Two-Mac cluster capability honesty + +- A cluster member registers image and video input only when its pair's placed mode serves media (GLM-5.3-Flash and Qwen3.8 27B in tensor parallel), so the coordinator no longer routes media to a pipeline pair that answers text only; a pair registered for media serves only while both Macs report the media contract. +- `darkbloom cluster status` and the pair's `/metrics` report MTP on for GLM-5.3-Flash in tensor parallel, which always decodes with its NextN head (depth 2); they said "MTP off". +- A content part of an unknown type (`input_file`, `input_video`, `refusal`, ...) is refused with HTTP 400 naming the type on the local API of one Mac and of a pair, and with the closed invalid-request error on coordinator requests, instead of being answered from the remaining text. +- With images or video, a GLM-5.3-Flash pair answers the output controls as one Mac does: it withholds hidden reasoning (`reasoning.exclude`, `include_reasoning: false`, `thinking.display: "omitted"`) and refuses a `response_format` JSON answer or a required or named tool call with 400 before any media decode. +- A `response_format` answer the service validates that was cut off by `max_tokens` (a reasoning model can think through the whole budget) now returns 422 saying so, instead of "Internal inference failure." GLM-5.3-Flash, which validates its withheld JSON itself, keeps its typed 422. + +### Cluster models pin the manifest a Mac downloads + +- The cluster worker now pins the model CDN's `manifest.json` bytes for every registered model. GLM-5.3-Flash pinned bytes that no Mac could fetch, so a downloaded GLM was never described and the cluster refused it. Qwen3.5 35B A3B, Qwen3.6 35B A3B, Nemotron 3.5 Lightning, GPT-OSS 20B, MiMo V2.6 Flash and the three Gemma 4 26B entries pinned the production coordinator's re-encoding, whose `created_at` is different on each environment, so DevNet could not use them. The files and aggregate digests are unchanged; only the pinned serialization of each manifest is different. +- A cluster folder with the earlier bytes is repaired when setup next lists the models, with no hand step. This includes a folder copied over the cable from the other Mac, which has no download receipt on this Mac. The cluster store fetches the published manifest (the CDN first, then the coordinator) and writes it in place only when it names the same model, version, aggregate and files and this Mac's worker takes it. Weight files are not written. When nothing answers, the folder stays as it is and the repair is tried again a minute later. When the published manifest names other files, the folder stays as it is and the worker refuses it as before. + +### Derived cluster control leader, failover, `darkbloom cluster` on every member + +- If one Mac goes away the cluster keeps itself running and re-forms by itself when it is back; `darkbloom cluster` works on either Mac. +- The cluster's control leader is derived, not the Mac where onboarding started: once a plan is adopted its rank 0 leads (requests enter there and registration v3 treats the plan's first member as the head); otherwise the member present that holds the model alone, then the most memory, the most GPU cores and the lowest member identity (from its Secure Enclave key pin). Leadership is a claim with a term, persisted in each Mac's setup record so a restart re-forms the same way; claims are totally ordered (term, then identity), travel only over the pairing-keyed link control channel, and a member refuses a superseded claim so a stale leader steps down. A leader acts on the cluster only after every plan member confirmed its claim. +- The leader renews a control lease with each member at the rank lease's cadence (5 s / 30 s) on a listener and edge epoch of its own. When the leader's lease expires the survivor takes over at the next term; a leader left alone serves the model on that Mac alone when the planner said it holds it alone (the ordinary single-Mac local server under the Mac's own identity: "degraded: serving on this Mac alone"), and otherwise says it cannot serve and runs nothing. When the missing Mac answers again the pair re-forms by itself and control returns to rank 0. +- `darkbloom cluster` works on any member: status, test request, model change, stop and start, and a verify-teardown summary of every Mac are forwarded to the control leader and its answer is shown. A model change while serving drains both Macs' parts before the setup changes. +- Failover serves alone only on a verdict for the plan saved now: the planner's alone verdicts are recorded with the plan's SHA-256, travel with the lease under it and are dropped for any other plan, and a refused (stale) lease never rewrites them; a member that has a new setup but not yet its verdicts says it cannot serve rather than load a model the planner never checked for it. A Mac re-paired with another Mac starts a new leadership history at term 0 instead of carrying the old pair's claim (which named the gone Mac and not the new one). +- Serving alone waits for the absence grace (10 minutes of peer or link absence, for every model and Mac): control still fails over at lease expiry (30 s), but until the grace ends the leader keeps its part ready for the missing Mac, its status says how long until it serves alone, and a Mac back before the grace re-forms the pair with nobody serving alone. A developer (debug) build may shorten the grace with `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS`. +- A Mac restarted with a saved leader claim acts as the leader (model change, setup write, start, stop; forwarded or typed) only once the other Mac confirmed the claim, or once the confirmation window passed with no member reachable; a superseded claim steps down first and the command goes to the current leader. +- The control lease runs on the continuous clock, which keeps counting while a Mac sleeps: a woken leader no longer counts a Mac that left during the sleep as present, and a woken member gives its leader one lease time awake before it takes over. +- The solo readiness check names this Mac's own solo server (its process, checked by start time, holds the listening socket) instead of trusting any server on the port; another program on the port is reported as such. +- `darkbloom cluster verify-teardown` counts only this cluster's processes: its workers carry this Mac's member identity, its owners run this install's executable or own one of its workers. Other cluster homes' processes (another identity or install, a check's fake workers) are listed apart and do not fail the check. +- A rank 0 told to stop while it is still starting exits promptly: the signal handler is installed first (a stop is latched, never lost), the wait for the follower ends within 0.2 s of the stop, and the cluster service repeats SIGTERM every 5 s while it waits (never SIGKILL). + +### A Mac pair registers with the coordinator as a cluster member by itself (DevNet) + +- After the Test stage passes, `darkbloom cluster` reads the cluster approvals the coordinator serves (`GET /v1/cluster/approvals`, from the operator approval file) and takes the entry whose model, prefill schedule and eight digests match this pair's installed app and model. Each Mac checks it against its own files before it saves it, and both Macs save it, or neither does. Both Macs then run as coordinator-paired members, owner-only, and the status says "Registered with the coordinator as a cluster member" with the approval and its end. +- The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching entry when the saved one ends within a day. An approval that ended is removed before a part starts, and the pair serves on the leader's local API again. +- When the coordinator gives no answer for 10 minutes (the absence grace), the pair serves on the leader's local API, and it is registered again when the coordinator answers with a matching entry. +- A coordinator without pair control (production, staging) or without a matching entry changes nothing: the saved setups stay byte for byte as they were. `darkbloom cluster local` never asks the coordinator. A pair approval saved by hand with `darkbloom cluster configure` is never removed. + +### Cluster: degraded mode only where single-Mac Darkbloom serves the model + +- When the other Mac goes away, a Mac serves the model alone only if single-Mac Darkbloom would serve that model on it (the same runtime requirements `darkbloom start --local` applies, such as an Apple M5 chip for Qwen3.8 27B) and the planner said it fits in that Mac's memory. Otherwise its status says it cannot serve the model alone and waits for the other Mac; the cluster re-forms by itself when it is back. A single-Mac server that still ends right after starting three times in a row is not started again until the cluster re-forms. +- The deployment line ("Serving … across both Macs: pipeline, M5 Ultra 40 layers / M3 Ultra 8 layers") is the same on whichever Mac leads, also when the model's first part runs on the other Mac. Models are listed by their catalog names. +- A stopped cluster's `darkbloom cluster` offers `v` (check that both Macs released their memory) on the leading Mac too, not only on a member. + +### Cluster setup finds models a dev install downloaded + +- `darkbloom-dev cluster` (and a staging install's) lists and uses the models that install downloaded. The cluster's model lookup read only production's `refs/main`, while a dev or staging install records its downloads under its own ref (`refs/darkbloom-dev`), so on a Mac with only a dev install the leader's download step failed with "downloaded, but the product's model store does not list it". It now reads the install's own ref, then production's, as single-Mac model discovery does. + +### GLM pair: a joining prompt no longer stalls decoding lanes + +- While other lanes decode on a GLM-5.3-Flash tensor-parallel pair, a joining lane's prefill runs in layer slices of about 500 ms, one slice a step, with every decoding lane's step after it, so decoding streams wait about 0.6 s instead of a whole 8K chunk (about 2.3 s). The lane with the shortest remaining prompt prefills first, and a prompt that fits one slice runs between another prompt's slices. Tokens are the same as a request served alone. + +### GLM pair: logprobs on lanes, reasoning exclusion and MTP metrics + +- A GLM-5.3-Flash tensor-parallel pair serves `logprobs` / `top_logprobs` on batch lanes (it refused them with 503 when lanes were on), clamps `top_logprobs` to 20 as single-Mac does, accepts `reasoning: {"exclude": true}` (it answered 400), and reports MTP rounds, proposals and acceptances, its KV ledger, waiting requests and prefix-cache status on `/metrics`. + +### GLM tensor-parallel setup reads metadata once, beside the link + +- A GLM-5.3-Flash tensor-parallel rank parses its model metadata once (the prepared loader's inventory) and does that work on its own thread while the link comes up, instead of serially before it; tensor-name matching runs on bytes. Setup before the load intent drops from about 5.7 s to about 3 s a rank, and `open` to about 0. Loaded weights are byte-identical and every file is still hashed. + +### GLM images and video on a tensor-parallel pair + +- A GLM-5.3-Flash pair serving in tensor parallel accepts image and video input as the single-Mac product does: the leader runs the product's media decode, processor and prompt expansion, rank 0 reproduces the same patches (checked by digest) off its executor and runs the vision tower when the request opens, and both ranks prefill the same spliced embeddings. Batch lanes carry media requests too, with the same arithmetic as a request served alone. Media requests decode with MTP rounds like text (the NextN history is primed with the media features) and without prefix reuse. Rank 0 now loads the vision tower (1.13 GB) with the tensor-parallel shard. + +### GLM tensor-parallel prefill: 8K micro-batches on long prompts + +- Long prompts on a GLM-5.3-Flash tensor-parallel pair prefill in 32K-token graphs with 8,192-row micro-batches where every micro-batch's cross-Mac sums stay hidden behind the rest of the graph; shorter prompts keep their current plan. Prompt prefixes are still kept every 4,096 tokens, and DSA top-k selection keeps each row's original candidates, so outputs are bit-identical. A 31.5K-token prompt prefills about 4 % faster on two M5 Ultra. + +### GLM tensor-parallel prefill: faster bit-identical kernels + +- GLM-5.3-Flash prompts prefill a little faster on a tensor-parallel pair: each hyper-connection site (89 per forward on both Macs) computes the expanded residual streams inside the products that read them, about 9 % faster per site, roughly 5 ms per 4,096 prompt tokens. Outputs are bit-identical. + +### GLM-5.3-Flash tensor-parallel prefix SSD tier + +- A GLM-5.3-Flash pair serving in tensor parallel keeps its prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt starts with its prefix restored after both Macs restart. Each Mac writes its own state at a prompt's kept 4,096-token boundary (its heads' linear-attention state, its copy of the sparse-attention histories and the MTP history) behind serving, once the request finished, read from the memory tier's pages without copying them first. The sealed prefix vote now counts SSD records; a boundary taken from an SSD record on either Mac is restored only after a second exchange confirms both Macs have it, otherwise both prefill from zero. A restored request writes the record into its own pages. Records store the sparse-attention latents at the pair's checkpoint precision (`balanced` by default, older rows approximate after a restore; see the quantized SSD prompt-prefix records entry); with `native` records a restored request produces the same tokens and logits as a request that prefilled the whole prompt. Records are scoped by the artifact, both builds and the MTP policy, never by the session. The same `DARKBLOOM_CLUSTER_PREFIX_SSD_*` settings, budgets and daily write limit apply. The prefix agreement field becomes `glm5-next-tensor-parallel-prefix-v2`. + +### GLM pair: experimental speculative depth by load (off by default) + +- A GLM-5.3-Flash tensor-parallel pair can verify one NextN proposal a round while three or more requests decode together and two otherwise (`DARKBLOOM_GLM_TP_MTP_DEPTH_POLICY=load`, threshold `DARKBLOOM_GLM_TP_MTP_LOAD_LANES`, 2 through 8, default 3), with `DARKBLOOM_GLM_TP_WIDTH_INVARIANT=1` (implied by `load`) giving verification rows one arithmetic in more window shapes. It is off by default: on two M5 Ultra Macs it raised the aggregate of 4 and 8 concurrent requests by about 11 %, but some concurrent requests' outputs differed from the same request alone, so it stays a diagnostic until that is fixed. Both Macs' cluster services must set the same values; the default keeps today's outputs bit for bit. + +### Clearer cluster setup and recovery + +- Follow five visible setup stages, see the default model before pressing Enter, and use a shorter status menu on either Mac. +- Preserve plain text when output is redirected or color is disabled. +- Report a failed test request with a status-and-retry step instead of announcing that setup succeeded. + +### Hardware-only cluster split, prompt-prefix cache for every family, GLM cluster residency + +- The split across the Macs is chosen from each Mac's hardware and measured speed alone: free pages, cached files and what other programs hold never move it. A range fits a Mac when its whole need is within the GPU's working set, the allocator's and buffer limits, and what the Mac's memory gate can admit at rest (physical memory less the system's own wired share and the file cache macOS always keeps, 10/27 of the rest). The live answer per Mac is still shown ("Quit apps on … first") and the load gate still decides each load. +- Gemma 4 pairs keep and reuse the prompt prefix too: each sliding-window layer's window is kept at every frontier and restored exactly, so a repeated 3,521-token prompt's first token comes in 0.08 s instead of 0.98 s on an M3 Ultra + M5 Max pair, and after both Macs restart the SSD tier gives it back in 0.23 s. +- GLM-5.3-Flash pairs keep and reuse the prompt prefix (resident and encrypted SSD tiers) with the same two-rank agreement as the other families: DSA histories are kept once per prompt, KDA state per frontier. +- A GLM stage holds standing GPU residency, as MiMo's does: without it every command buffer made its tens of gigabytes of weights resident again and decode fell to 0.5 tok/s (30 tok/s on one Mac with it, same tokens). +- A GLM pair always uses the keyed, encrypted data plane, including over the paired link; a model `config.json` up to 32 MiB is accepted (GLM's NVFP4 configuration is 10 MB); a model folder whose bytes are a catalog entry's is listed by that entry's name. + +- Compact GLM convolution and recurrent cache states at transaction ownership boundaries before using the smaller retained-state reservation. Keep pending prefill histories and cast allocations charged per layer, enabling automatic 2048-token placement without choosing a hardware-specific split. + +### Cluster planning accepts a DevNet app's install path + +- Planning a two-Mac cluster with a DevNet build no longer fails every model with "Peer installation paths must be absolute and shell-safe". The DevNet app is installed as `Darkbloom Dev.app`; a saved cluster setup now accepts a space in the installed owner and worker executables, the model directory, and the native member's metallib and resource library. +- Shell syntax, relative paths and `..` are still refused, and the developer SSH route still checks every path it puts in a remote command. +- The orphan sweep, the teardown check and `cancel-all` now find a DevNet build's `darkbloom-dev cluster worker-owner`, and the cluster service stop finds a `darkbloom-dev cluster service`. Before, they knew only the production `darkbloom` name. + +### Independent cluster lane withdrawal + +Fixed cluster batch cancellation so withdrawing an admitted request that has +not started retires that request without interrupting another request waiting +for token credit. Accepting a start command closes the withdrawal window, and +duplicate cancellation messages share the pending retirement acknowledgment. + +### `darkbloom cluster local`: a Mac pair serving without a coordinator + +- `darkbloom cluster local [model]` sets up and serves the pair exactly as `darkbloom cluster` does, but no Mac of the cluster contacts a coordinator: no registration, heartbeat, public traffic or billing, and serving needs no network beyond the cable. A coordinator can therefore never refuse the start. +- The API is on the leading Mac's local endpoint with the same API key as `darkbloom start --local`; it listens on every network of that Mac (LAN or tailnet) unless `--bind` names an address (`--bind 127.0.0.1` keeps it on the Mac). `darkbloom local` prints the base URL, a `network:` URL and the key. +- The choice is kept across restarts and reboots until changed: in `darkbloom cluster`, `l` serves locally only and `p` serves through Darkbloom again; a serving cluster restarts its leading part that way and the screen waits until it serves. +- A cable moved to another Thunderbolt port no longer leaves both Macs unreachable: each cluster service follows the cable to the new port within a few seconds. +- A cluster set up from the plain `darkbloom` command (the installer's link on the PATH) now starts its leading part; it used to stop with "Installed local owner is unsafe or not executable". +- `darkbloom cluster local` on the Mac that joins a pairing carries on to the model choice (it runs on the leader over the cable) instead of sending you to the other Mac. +- The model list shows one line per model (its size and how it is split, or how it gets onto the Macs); what moves and the planner's reason are said once a model is chosen, and the public-traffic line only when serving through Darkbloom. Two models with the same name show their ids. A part that keeps ending the same way is said after three tries instead of repeating, errors read as words (not `invalid("…")`), and pairing waits for the cable's address instead of failing with developer options. +- A smaller Mac takes the share of a model it can hold: the stage memory gate's 6 GiB floor and 4 GiB loading headroom (measured on 256 GiB Macs) now scale with the Mac's memory below 96 GiB (36 GB Mac: 2.25 / 1.5 GiB). A one-layer part on a 36 GB Mac was refused before. "Restart to free memory" is said only when nothing else frees enough; a choice made on the member survives a leader restart; the model list keeps the last catalog it read when the catalog does not answer. +- Hardware run on an M4 Max 36 GB + M5 Max 128 GB pair (Gemma 4 26B QAT, local only): another server on port 8000 (oMLX) no longer makes every start end after both Macs loaded: the port is checked before anything loads and the leading part takes the next free port; Gemma's thought-channel markers no longer reach `content` on the local API (the cluster's API parses reasoning by the model's type, as the coordinator path does); the leader no longer re-sends its cache settings every 15 s to a member that drove the onboarding; the ready screen's deployment line is the running setup's, not one recorded for an earlier start. +- The leading Mac downloads a catalog model the cluster serves whatever its chip: Qwen 3.8 27B's single-Mac requirement (an M5's neural accelerators) no longer stops an M4 Max leader from fetching it for the pair; single-Mac serving keeps its own check. +- Models the cluster takes from this Mac's own model store (Qwen 3.5 9B, a freshly downloaded Qwen 3.8 27B) are offered and copied again: their manifest is the catalog's exact file (the CDN lists the files in another order, which was refused), and a copy written earlier is corrected once. +- On a 36 GB Mac the prompt-prefix cache works: a memory-bound context keeps room for it (a repeated 5.5K-token prompt starts in 0.28 s instead of 7.1 s); a thinking model's reasoning streams from its first token on the cluster's API; each Mac keeps its worker's own log (`~/.darkbloom/cluster-setup/worker.log`). +- `darkbloom cluster local` answers at the same address and with the same key whichever Mac the plan makes rank 0: the other Mac passes the same port to the API over the cable, both Macs keep one API key, and `darkbloom local` shows it on either Mac. The port is 8000 when both Macs have it free, else the lowest port from 8000 to 8020 free on both, and it is kept while it stays free on both (another server on 8000 on one Mac no longer puts the API on 8000 or 8001 by which Mac is rank 0). +- A model chosen on a member is fetched there (it said "Nothing to copy: plan again."); a model's manifest is the encoding this Mac's worker accepts (GPT-OSS 20B was refused); the plan uses the other Mac's served speeds; the start screen no longer prints index estimates as seconds; the test request counts a thinking model's reasoning. +- PrismML Bonsai 2 27B serves on a pair with a 36 GB Mac: the worker's idle context check no longer recomputes the stage plan's constants for every step of its search (it outlasted the 10 s a request waits, so every request failed); a failing local request leaves a line in the log. +- A Mac whose memory moved after the plan (apps opened, cache refilled) no longer makes the pair retry the same split forever: after two load refusals for memory the leading Mac plans the model again on the memory now. +- The local API (single Mac and cluster alike) parses Gemma 4's thought channel and GPT-OSS's Harmony markers out of `content` by the model's type; think-tag models keep the raw stream there, as before, so the cluster still answers exactly as a single Mac does. +- Before a part starts, the model's own pages are dropped from the Mac's file cache (no privileges; the files are untouched): the load gate does not count active cache, and right after a download a 36 GB Mac's share was refused. +- The relay on the Mac that is not rank 0 is hardened: it listens only when the API listens on every address, bounds its connections and idle time, never closes a descriptor another thread may reuse, survives running out of descriptors, and leaves another local server's discovery file alone. +- A 36 GB Mac in everyday use keeps its share: a request on a loaded part asks only for what it needs plus headroom, and when the gate is short only because it does not count file cache the kernel could drop, the worker lets the kernel drop it first (stopped at any sign of compression, swap or pressure); "Quit apps" is no longer said for that case. +- When the cable moves to a Thunderbolt port that was never set up, `darkbloom cluster` says so and sets it up with one key (f); the service's log says what to do. +- The local API (single Mac and cluster) puts every model's reasoning in its own field, Qwen and Nemotron included, on chat completions and the Responses API; a stream whose prompt opens no think block still streams its answer at once. +- Shorter onboarding screens: models held back for the same reason share one line, two Macs running different Darkbloom builds are named as such ("install the same Darkbloom on both") instead of "Planning failed (Peer native build differs from the capability)", models the cluster cannot run say "not supported on a cluster yet", and the development-build service line says only what to do after a restart (the reason is in the service log). + +- Guided cluster setup shows five stages, names the default model choice, refreshes peer labels from the authenticated Mac, and reports completion only after the test response succeeds. Terminal color respects `NO_COLOR`; redirected output stays plain. + +- Cluster members prevent idle sleep while a deployment is serving or waiting for its peer; assertions remain held until the child and relay stop, then are released. +- A cluster service recovering a model process from its previous run keeps waiting after the cleanup deadline, keeps that process visible and protected from idle sleep, and starts no replacement model until it exits. + +- Raise cluster worker output support from 4,096 to 32,768 tokens, with 65,536 combined prompt/output tokens subject to model and live per-rank memory limits. Refuse requests over the advertised bounds rather than truncating them. + +- Keep fixed-scope model reservations at their full serving context when recent short requests tune automatic placement. GLM placement includes the native transport buffers and allocator bounds, so those requests cannot make an oversized split appear loadable. + +### A Mac pair serves locally when its coordinator has no cluster support + +- A cluster whose coordinator cannot take its cluster member role (unreachable, or a coordinator that answers the member's registration as an ordinary provider's because it predates the role) now serves on the leader's local API only, with the same local token as `darkbloom start --local`, instead of restarting every 38 s without ever serving. No public traffic reaches it and nothing is advertised to the coordinator; the Macs stay held for the cluster as before. +- The onboarding screen and `darkbloom cluster` status say so in one line: "Serving locally on this Mac's API; public serving needs a coordinator with cluster support." The next start registers normally once the coordinator supports the role. +- A coordinator that refuses this member or its pairing is still a refusal: that start fails as before. + +### Cluster pairs register GLM-5.3-Flash and Qwen3.8 27B as cluster members + +A pair started with a coordinator approval (DevNet) now registers both Macs as cluster members for GLM-5.3-Flash and Qwen3.8 27B. Before, each Mac's member part ended about a second after it started, with "Cluster member control connection ended", and after three tries the pair served on the leader's local API only. + +The member applied the single-Mac requirements (`mlx_nax`, and `glm5_next_v1` for GLM) to its model in two places: before connecting, and when building its registration, which left the model out of `cluster_models`. A member reports hardware-only capabilities, and its pair-serving grant admits its model, so both places now follow the grant. A solo provider keeps the single-Mac requirements. + +### Cluster member refusals and stops release what they hold + +- A cluster member that refuses an inference request because it has no live pair slot now sends `service_reservation_released` with its 503, on the receive path, in the dispatcher and in the request handler. A request that raced a pair-slot retirement left its reservation held on the coordinator before. The handler refusal also settles the request's prefix-cache lookup receipt. The 503 answer is unchanged. +- A session that ends while the leader still forms its pair (slot publication and warmup canary) retires the published slot before the leader sends `native_pair_owner_released`. The receipt went out while the slot was still published before. + +### Cluster member restarts re-register when the coordinator comes back + +- A cluster member (leader or follower) that starts while its coordinator is briefly away keeps its reconnects inside its registration wait: a retry the backoff would place after the wait is made at its end and is given its own terms, as is an attempt already under way when the wait ends, so a coordinator that returns before the wait ends is reached and its in-time acceptance is honoured. +- A wait in which the coordinator was never reached now says so ("The coordinator could not be reached …") instead of "Coordinator did not accept the control-only member role."; the role check itself is unchanged. + +### MiMo V2.6 Flash on the two-Mac pair + +- MiMo V2.6 Flash can be served by an M5 Ultra and an M3 Ultra together. +- MiMo pair runs produce qualification records (the reference names its request and is compared on it), and MiMo V2.6 Flash is granted on an M5 Ultra + M3 Ultra pair by its six records (pipeline at the planner's cut, in the order the records passed; the mirrored order is refused). +- The provider's start-time weight hash reads with the file cache off (`F_NOCACHE`, same digest, earlier readers kept as fallbacks), so hashing a 172 GB model no longer fills the Mac's file cache before the memory gate decides. The memory gate is unchanged. + +### Pair-serving grants bound to the mode their records ran + +- A qualification record now grants only its own mode family (pipeline variants, pipeline with speculative rounds, tensor parallel, or the off-by-default hand-off modes) and only the chip classes in the roles it ran; a phase-split pass no longer opens pipeline or tensor-parallel placements. A diverged record withholds its own family; an inconclusive one neither grants nor withholds. The planner keeps to the same rule, and a start checked without its mode is refused. +- Seven pipeline qualification records on an M3 Ultra + M5 Ultra pair at the planner's sharded cut (Qwen3.5 9B and Qwen3.8 27B at cut 4 and 8 and Nemotron 3.5 Lightning at cut 8 with the M3 Ultra leading; both Qwen 35B A3B models at cut 36 and Ternary Bonsai 2 27B at cut 56 with the M5 Ultra leading; GPT-OSS 20B at cut 20, which stays withheld by its earlier diverged pipeline records) are bundled: every model the pair served only through phase-split records on these Macs now has a pipeline grant of its own. +- The onboarding offers exactly what a start serves: a model whose chosen placement any rank's grant check would refuse (GPT-OSS 20B, withheld by its diverged pipeline records although cut 20 passed) is listed as not served, with the reason, instead of being offered and then refused at start. + +### A Mac pair keeps its DevNet cluster approval across provider updates + +- The coordinator can serve a model approval: a cluster approval that names the model, its prefill schedule and its serving terms, but no build. The pair takes it when its model, schedule and artifact are the saved setup's, and it computes no build facts for it. Entries pinned to one build are matched as before. +- After an update, the re-adopted setups find the same model approval at the next check, so the pair is registered with the coordinator again with no new entry from the operator. +- Under a model approval each Mac registers its plan with its own runtime (worker, capability, resource policy and profile), and a session starts only with that runtime. Each Mac hashes its worker against its saved setup and its metallib and resource library against the digests it took when it registered. +- When the pair set a model approval aside because its parts kept failing, the next update can take it again. The same build does not take it again. + +### Changing a serving cluster's model plans again once its memory is free + +- Changing the model of a serving two-Mac cluster (`m` in `darkbloom cluster`, or `darkbloom cluster local `) now plans again after both Macs have stopped their parts and given back their memory, and starts that plan. Before, it started the plan made while the old parts still held the memory, where tensor parallel did not fit, so a pipeline started instead. GLM-5.3-Flash on two M5 Ultras came back at less than half the speed (47.9 instead of 126.9 tokens/s in the setup's test request), serving the pipeline's 65,536-token context instead of its native 1,048,576. +- The leading Mac's own re-plan after two load refusals for memory starts the plan made once both parts stopped and gave back their memory, too. + +### Cluster model provisioning without manual downloads + +- `darkbloom cluster` needs no `--model-dir`: the cluster keeps its models in a store beside the product's model cache, and models single-Mac Darkbloom installed are cloned in (APFS clones, the catalog's exact manifest bytes). +- A model one Mac lacks is copied over the Thunderbolt cable on the pairing-keyed link control channel (encrypted records, 4 MiB chunks acknowledged after the receiver wrote and hashed them, resumable). The receiving Mac accepts only a manifest whose digest this build's qualification records pin, refuses hard links, unexpected files, an occupied destination and too little free disk, writes uncached, and has its own worker check the staged files before an exclusive rename into place. +- A catalog model neither Mac has is downloaded once on the leader (the product downloader, written and verified uncached through the new opt-in `ModelDownloader.uncachedWrites`), then copied. A copy predicted under 30 s at the rate measured on these Macs starts by itself (`n` within 3 s stops it). + +### Animated Darkbloom cluster setup + +`darkbloom cluster` setup now opens with the Darkbloom mark, which blooms in on color UTF-8 terminals at least 40 columns wide. Stage headings show a step meter, and long work (cable check, reading both Macs, planning, loading, first tokens) shows a live line that the next transcript line replaces. `DARKBLOOM_NO_ANIMATION` or `CI` keeps the mark and meter but stops the motion. Narrow or non-UTF-8 terminals keep colored headings only. `NO_COLOR`, `TERM=dumb` and redirected output stay byte-for-byte plain. The model-free onboarding checks cover all four presentations (438 checks). + +### Cluster setup names "this Mac" and "the other Mac" + +- `darkbloom cluster` names the two Macs from the screen that shows them: "this Mac" and "the other Mac (Apple M5 Ultra, 256 GB)" in pairing, the machine list, each model's split ("this Mac 50% / the other Mac 50%"), the serving and API lines, status, teardown checks and copies. Two identical Macs were both "Apple M5 Ultra, 256 GB", and the API line did not say it was on the other Mac. Answers the leader gives to the other Mac are worded for that Mac's screen. +- The Mac that joins a waiting leader stops after pairing, also when started with `darkbloom cluster local`; it says to run that on the Mac that leads instead of showing a second model list. +- A model one Mac holds twice (the catalog's download beside the cluster's own copy of the same files) is listed once, and a supported model is never listed as "not supported on a cluster yet" for a copy the cluster worker does not take. + +### Darkbloom mark on every `darkbloom cluster` run + +Running `darkbloom cluster` again on a Mac that is already in a cluster (the leader or a member) now opens with the same Darkbloom mark as the first setup, beside "Darkbloom cluster" and what can be done there (status, test, change model, stop). It follows the same terminal rules as the setup: color UTF-8 terminals with room for the mark draw it, `DARKBLOOM_NO_ANIMATION` or `CI` keep it still, and `NO_COLOR`, `TERM=dumb` and redirected output print the two heading lines as plain text. The onboarding checks cover the leader and the member, in color and plain. + +### Cluster setup in narrow terminal windows + +In a colour terminal between 40 and 56 columns wide, `darkbloom cluster` setup no longer smears the Darkbloom mark: the mark and its bloom appear only when its widest row fits, and narrower windows keep the step meter and live lines. A live progress line wider than the window is now cut to one row, so the line that replaces it no longer leaves its first half in scrollback. + +### One command for a cluster: `darkbloom cluster` + +- Run `darkbloom cluster` on each Mac, pick a model, done. `darkbloom cluster setup` is the same command; with no terminal it says where to run it. +- Choosing the model starts it (3 s to press n); no second question. The screen then says how the model is served in one line, for example "Serving Qwen3.8-27B across both Macs: pipeline, M3 Ultra 40 layers / M5 Ultra 24 layers", and where the API is ("API at http://localhost:8000 on "). +- Models that fit in the Macs' free memory now are listed first, a model that does not fit says what frees the memory, and the fit is checked again right before the start. A model the pair may not serve with this release is listed under "Not offered" ("Not yet qualified on this pair of Macs") instead of failing after a long wait. +- Two cables: the onboarding asks which one to use. The cable check prints plain lines ("Cable found.", "Cable ready."). macOS's one Local Network prompt is announced before it appears, and a denied prompt is named with where to allow it. +- After a Darkbloom update the cluster sets itself up again by itself ("Updating the cluster setup after a Darkbloom update."). After a restart, the screen says whether the Mac comes back by itself (automatic login) or once someone logs in (FileVault). +- A start that does not finish shows each Mac's last error and offers `d` to save a redacted diagnostics file. Error messages name only `darkbloom cluster`; `plan`, `configure`, `console`, `pair` and the other developer subcommands and options are hidden from the help. + +### Cluster KV in pages + +- GLM-5.3-Flash tensor-parallel ranks, GLM pipeline stages, Qwen 3.5 pipeline stages (MTP heads included), Qwen tensor-parallel shards, Gemma 4 stages (any lane count) and Nemotron 3.5 stages keep request KV in page pools instead of contiguous per-request arrays. Prefix entries share pages (refcounted, copy on write at a shared partial page) instead of copying histories, and a GLM tensor-parallel request is charged its pages (about 18.4 KB a token a rank) rather than the contiguous growth charge. Outputs are bitwise the contiguous ones. `DARKBLOOM_CLUSTER_GLM_PAGED_KV=0` keeps contiguous GLM tensor-parallel KV for diagnosis. +- GLM tensor-parallel (solo) and GLM pipeline requests start with their prompt's pages plus a 1,024-token granule and grow between steps, with no context cap; a request whose growth the memory gate refuses ends at `length` without touching others. GLM page pools compile their kernels at load and keep up to `DARKBLOOM_CLUSTER_GLM_PAGED_RETAIN_MB` (2,048 MB a rank) of slabs between requests. + +### A coordinator deploy no longer takes a cluster pair off public traffic + +- A pair registered with the coordinator serves on the leader's local API instead when its coordinator-paired parts end three times in a row right after starting. A part that ended because the coordinator did not accept its registration within the 10-second window counted too, although the coordinator decided that end: it happens during a coordinator deploy, right after a restart, or while the coordinator is slow. Such an end no longer counts. Ends with a local cause, such as a changed input or a crash, still count. +- This complements a coordinator that ends each pair session before it shuts down, which makes a deploy's ends cleaner: the provider rule still covers coordinators without that change, coordinator crashes and slow registrations. +- A pair set aside this way is offered to the coordinator again with the same approval an hour later, or at once with a later approval. Before, only a later approval, the approval's end or a Darkbloom update brought it back, so it could serve only the leader's local API for the rest of the release. + +### Pair Macs set up with `darkbloom cluster` do not update themselves yet + +- Darkbloom on a Mac set up with `darkbloom cluster` does not update itself yet. To update a pair, run `darkbloom update` on both Macs, then log out and back in, so that the cluster service runs the new release. If `darkbloom cluster` status then says that Qwen's speculative assistant is not offered for public traffic, press `m` once in `darkbloom cluster` to plan the model again. + +### Speculative rounds on the pipeline, recorded and on by default + +- A qualification (recording) request now runs a pipeline's speculative rounds (`pipeline_mtp_v1`) as served, and its decoding rank records the accepted timeline: one step per selected token (its row's digest and highest candidates), so the near-tie rule reads every accepted token. Drafts never change the accepted output. +- A qualification record may carry the decode speed timed runs of its own placement and request measured, in its mode and as the plain pipeline (`darkbloom-cluster-pair-check record --timing-mode/--timing-plain`). A passing `pipeline_mtp_v1` record grants the pipeline-with-speculative-rounds family, and the planner credits the rounds with its measured speed-up until the pair has served the same placement both with and without the rounds and its own speed-up replaces it: the rounds are planned by default where lossless and measured faster. The onboarding line reads "pipeline with speculative decoding". +- Records on an M3 Ultra + M5 Ultra pair at the planner's sharded shapes: Qwen3.8 27B at cut 8 (tokens equal to both single-Mac references and to the plain pipeline; 57.7 against 35.6 tok/s), Qwen3.5 9B at cut 4 (near tie at a true tie; 130.9 against 75.1 tok/s) and MiMo V2.6 Flash at cut 47 (tokens equal at 1,024 and 4,096 prompt tokens; 59.2 against 43.1 tok/s). Output matches a single Mac's up to near ties, as the pipeline's does: the verify window's arithmetic differs in its last bits from one-token decode. +- A member's roster plan may name `pipeline_mtp_v1`; a role-aware coordinator must list it too before it accepts such a plan. + +### Cluster planner pricing fixes + +- GLM-5.3 Flash tensor parallel: the plan now counts the NextN (MTP) layer every Mac holds beside its share (4.2 GB), the request memory its speculative rounds add, and the decode speed-up the rounds measured, so it no longer admits a pair the load gate then refuses or predicts decode too slow. Two M5 Ultra 256 GB still plan it as tensor parallel on equal shares with eight concurrent requests, on a new pair and after the first load measured the link. +- A pipeline's prompt hop across the cable is priced by the bytes it carries (a GLM chunk is 64 MiB), from the link probe's two record sizes, instead of as one 4 MiB record. +- Requests that answer fewer than 64 tokens (the warm-up canary, the setup's test answer, readiness probes, a quick "Say hi") are no longer speed records, so they no longer choose the mode or the request a plan is made for. +- A Mac with a model loaded no longer runs the GPU speed benchmark when the other Mac checks for updates every minute or plans: it uses the speed index it last measured while idle. + +### Two-Mac cluster prompt prefixes per tenant + +Both Macs of a cluster now keep and reuse prompt prefixes, in memory and in their encrypted SSD tiers, only for the request's own tenant, as one Mac does: the leader gives both ranks each request's cache switch and a SHA-256 digest of its cache scope (never the scope itself), every prefix key and SSD record scope carries that digest, and a request whose prefix cache is off (a remote request without a cache scope, or a GLM or Qwen request with images or video) reuses and keeps nothing on either Mac. Before, every request on the pair shared one prefix cache. Requests from the local endpoint carry no partition and keep the earlier behavior and bytes. Both ranks bind the partition into the request fingerprint they compare, so ranks given different partitions fail the request. `darkbloom-cluster-pair-check request --request-prefix-cache off|tenant:SALT` writes a qualification request with a partition. + +### A request's tokens do not depend on what it is batched with on the new MLX core + +- Cluster workers, the single-Mac reference and the tensor-parallel check now set `MLX_QMV_BATCH_INVARIANT=1` before MLX starts, unless their launcher set it. The cluster's MLX core then keeps quantized products of a few rows (speculative verify windows, rows of several requests in one launch) on its per-vector kernels, as before it took MLX main's new kernels for 6 to 16 NVFP4 rows and 8 or more affine rows, whose results change with the row count. A request served beside others keeps the bytes it gets alone. Each process logs `darkbloom-qmv-batch-invariant-v1` with the value and who set it. Single-Mac serving is unchanged. + +### Faster Qwen tensor-parallel decode on two M5 Ultra + +- Qwen3.8 27B tensor parallel on two M5 Ultra decodes about 6% faster for one request (75.8 to 80.5 tok/s at 256 tokens, 62.7 to 66.8 at 1,024). The exact decode projections take a layout measured on the M5 Ultra for a verify window's vectors (rows in registers). Outputs are unchanged byte for byte, and other chips keep their layouts. + +### Pack Qwen MoE tensor-parallel expert and shared reductions + +Qwen routed-expert tensor parallelism now carries the shared expert's float32 +partial in the routed experts' collective: two collectives per layer instead of +three, with every summed and rounded value unchanged. The load agreement +(`qwen-moe-down-projections-f32-sum-before-weighting-packed-v3`) and the +tensor-parallel check's launch version refuse mixed builds. Placement now +charges the top-K expert rows once per layer instead of the largest payload on +every collective, and the request ledger charges the packed payload's source +partials. Full-model hardware qualification on the pair is still required. + +### Qwen3.8 27B pairs register with the coordinator by default + +- A Qwen3.8 27B pair set up with `darkbloom cluster` now registers with the coordinator and can serve public traffic. With the default `[backend] mtp_mode = "auto"`, the setup used to carry the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry. The other Mac therefore refused every cluster approval ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"), and the pair served on the leader's local API only, although the setup said it was qualified for public traffic. +- The assistant's speculative decoding has no parity qualification, so it stays on local clusters. Under `auto`, a cluster served through Darkbloom is planned without it, as are the re-plans after an update or a memory refusal. `darkbloom cluster local` keeps it. The cost is speed: on two M5 Ultras, one request decodes at about 40 tokens/s without the assistant and about 93 tokens/s with it. +- `mtp_mode = "on"` keeps the assistant in either case. A cluster served through Darkbloom is then not offered to the coordinator, and the setup says so in its public-traffic line instead of claiming qualification. +- The leader now checks a coordinator's approval with every rule the save applies, the assistant rule included, before it stops either Mac's part or sends anything over the cable. The pair is not offered, with the reason in one line: `Not offered for pairing: this Mac's check refused it: Qwen's speculative assistant serves local clusters only …`. +- Public speculative decoding for Qwen pairs needs qualification evidence of its own and is a follow-up. + +### Request-owned tensor-parallel lanes for every Qwen row + +- Every Qwen tensor-parallel row (Qwen3.5 9B, Qwen3.8 27B, Qwen3.5 and Qwen3.6 35B A3B) now serves through the request-owned batch path the 27B used: main's paged KV host, independent lanes at capacities 1 to 8, the resident and SSD prompt-prefix tiers, committed-token logprobs, and automatic widening that keeps the running shares. Each row's LOAD reservation, placement quote and widening quote are priced by its own geometry (its per-rank KV heads and recurrent state, and a routed-expert row's packed MoE partials). Capacity one is the same path one lane wide. A row that can also run the pipeline keeps the pipeline as a planning candidate while tensor parallel is priced by its quote. +- A routed-expert cohort runs each row's router, shared expert and selected experts with that row's own arithmetic and sends every row's packed expert and shared partials in one collective, so a wider cohort still issues two collectives a layer and every row's tokens equal its solo bytes (`moe-rows-one-collective-v1` in the load agreement). +- The Qwen3.5 9B's inline head now runs as the tensor-parallel speculative assistant beside the 27B's (the assistant inventory and quote follow each row's configuration). The A3B rows' heads are routed-expert layers the tensor assistant does not load, so they serve without speculation. +- Each rank's cut of a row-parallel projection, expert bank or expert input column is copied once into a row-major buffer at LOAD. The interior-axis gather left a transposed view, which every quantized matmul and expert gather copied whole at each call: a routed-expert decode step copied the rank's gate/up and down expert banks for every layer, and every row copied each dense row-parallel weight. Values are unchanged. +- A tensor-parallel decode step is submitted to the GPU layer by layer while it is built (`Qwen35LayerSubmission`), and decode steps, assistant rounds and their selection encode into command buffers of up to 100 operations instead of the worker's 16, as GLM's TP decode does. Tokens are unchanged. +- Batched decode rows take each row-parallel projection's cached FP32 scales and biases, the ones its single-row forward reuses (`QuantizedLinear.independentRowsForward`), instead of widening the BF16 constants inside every quantized matmul, where MLX made that widening on the thread's default GPU stream rather than the caller's. A widened step no longer spans two GPU streams there, and two kernels a projection a step go away. Values are unchanged. +- The single-lane tensor-parallel owner is retired with its own page pool, its prefix cache and `DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV`; Qwen tensor parallel now requires the authenticated sealed data plane, and each lane reserves its full context at LOAD instead of growing by granules. +- Full-artifact qualification on the pair is still required. + +### Qwen27 tensor-parallel prefix SSD tier + +Keep the Qwen27 TP batch owner's prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt restores its prefix after both Macs restart. Each rank writes its own shard (and the assistant's trusted history) behind serving after bilateral clean retirement. The sealed vote now counts SSD records, and a second exchange confirms that both ranks restored, or both prefill from zero. Records are scoped by plan, shares, artifact, storage, both builds and assistant policy, never by membership epoch. The prefix agreement field becomes `qwen-tensor-parallel-prefix-v2`. + +### Qwen27 tensor-parallel ranks reserve only their own heads + +Each tensor-parallel rank now reserves the request state it actually holds: its own KV heads, linear-attention heads, and its own rows and columns of the fused projections and projection constants under the chosen split. The replicated assistant, hidden-width buffers and gathered logits stay whole on both ranks. Setup quotes both ranks of every supported split. Placement charges each Mac its own figure. It keeps a split for later widening only when, on each Mac, the serving owner's weights and request plus the widened load fit, because widening is previewed before the old owner is released. On a busy second Mac, onboarding can therefore pick a split that widens to two speculating requests instead of one that never can. The whole-model figure remains the bound either rank stays under. + +### Qwen27 tensor-parallel resident assistant + +Discover and fully quote the catalog Qwen27 embedded assistant during normal cluster setup, retaining the native inventory policy through bilateral launch and READY. Eligible concurrent requests keep independent histories and accepted-token credits while sharing captured target verification; ordinary media, logprob and history-filter paths retain their capabilities. Price surviving cohort backing, the next verification window and assistant prefix ownership through checked retirement. Explicit MTP off retains the fully quoted ordinary target. Full-artifact correctness and release qualification remain separate from component fixtures. Bound the assistant's trusted-history flush to evaluated 512-row blocks (first draft and ordinary decode), and price a verify window by what it writes: partial-page replacements and segment slack, not a second history. At the 64K profile the whole-model bound for one speculating request fell from about 66 GiB to 22 GiB, and for two from 96 GiB to 36 GiB; installed qualification is separate. The saved setup's status binding carries the speculation the session derives, so a pair serving the resident assistant reads as ready instead of stale and automatic setup finishes; capacity-one refusals keep their capacity or deadline reason. The resident owner's memory gate measures compression and swap-out from the start of each served scope instead of the owner's whole life (limits unchanged), so ordinary background compression on a busy Mac no longer refuses later requests. Concurrent speculative requests verify each request's draft window with that request's own single-window arithmetic inside one collective per row-parallel projection, so they emit exactly the tokens they emit alone. One batched product changed kernel at four three-column windows and altered near-tie tokens. + +### Qwen tensor-parallel decode with batch-invariant projections + +Every Qwen tensor-parallel plain decode step, verify window and batched row +(the 9B, the 27B and the dense projections of both 35B A3B rows) now projects +through the SDK's batch-invariant affine kernel. Each position of a speculative +verify window therefore has the bits of the plain decode step that computes the +same token, and each concurrent row the bits it has alone, at any cohort width. +This changes the rounding of every decode projection relative to MLX's own +kernels, so recorded tensor-parallel references must be regenerated once. + +A row-parallel projection reads its bf16 activation directly and writes its +FP32 partial (no separate widening launch and no FP32 copy of its scales), and +its rounded all-sum feeds the fused residual step, so a step runs far fewer GPU +launches. Each rank logs the arithmetic it resolved once per load +(`darkbloom-aqv-kernel-v1`: exact vectors, the kernel's arithmetic and words +per lane on that GPU family, its layouts), and the pair binds whether exact +vectors are on into its load agreement, so two ranks that resolved it +differently refuse to load. `DARKBLOOM_QWEN_TP_EXACT_VECTORS=0` (diagnostic +only, never forwarded to an installed rank) keeps MLX's kernels. + +### Qwen tensor-parallel ranks wait for each all-sum in the kernel that reads it + +The Qwen 3.5 residual step (`ResidualRMSNorm`) now reads its FP32 tensor-parallel +all-sum as a fenced input, as GLM's hyper-connection sites already did, and a +worker turns `MLX_METAL_FENCED_INPUTS` on for every tensor-parallel family whose +kernels read their sums that way (`ClusterResidentModelCatalog.Family +.tensorParallelSumsAreFencedInputs`; a launcher's own value is kept). The kernel +that reads a sum then waits for the CPU itself instead of MLX's separate +fence-wait launch, about 128 of them per verify window of the 27B. MLX consults +the setting only for inputs a kernel declares fenced, so every other launch is +unchanged, and only where the GPU waits changes, never a value. The fused fence +update stays a launcher's choice. Each rank logs the choice (`fenced_sums=` in +`darkbloom-aqv-kernel-v1`) and binds it into the load agreement. + +### Qwen tensor-parallel speculative rounds keep the GPU busy + +A single-request speculative round no longer waits for each assistant draft +step before building the next one, and no longer waits for the drafts before +building the verify window: the draft chain and the window are submitted back +to back, and the window itself is submitted layer by layer as a decode step +already was. The drafted tokens' vocabulary check is evaluated with the window +and read when the window is confirmed. Every rank still runs the same +collectives in the same order, the emitted tokens are unchanged, and a failure +on either rank fails the round on both. Batched rounds keep their draft +schedule. `DARKBLOOM_QWEN_TP_MTP_PIPELINED_DRAFT=0` (diagnostic only) waits for +each draft step. + +### Faster Qwen tensor-parallel verification: windows evaluated whole + +Qwen tensor-parallel speculative verify windows are evaluated whole instead of +being submitted to the GPU one decoder layer at a time. On two M5 Ultra Macs +serving Qwen3.8 27B this makes a single request about 18 % faster (60 against +51 tokens per second) and four concurrent requests about 5 % faster, with +identical outputs. `DARKBLOOM_QWEN_TP_WINDOW_LAYER_SUBMISSION=1` (diagnostic, +never forwarded to an installed rank) submits windows by layer again; both +ranks bind the choice into their load agreement. + +### Qwen3.8 27B at its native context on a tensor-parallel pair + +- A Qwen3.8 27B pair serving in tensor parallel accepts the context a single Mac serves: prompts up to 262,143 tokens and up to 32,768 output tokens within 262,144 (previously 32,768 + 32,768 within 65,536). LOAD and the planner still size the pair for the 32,768 + 32,768 request at every width (one to eight lanes), so no lane reserves KV for the whole context in advance. Each longer request is charged at its own context when a rank reserves it, and each rank's live memory gate admits it or refuses it alone (HTTP 503 with the context the pair serves now) while other requests keep running. Readiness and keep-warm answers carry that serving context. The 27B's pipeline modes and every other Qwen row keep their limits. +- Qwen tensor-parallel paged lanes reserve their prompt and a 1,024-token granule when they open and grow between steps, instead of reserving every page of the prompt and output at once. Outputs are unchanged byte for byte. +- The 27B's worker profile, load agreement and installed setup fingerprints change. Existing 27B setups re-plan after the update, and 27B pair qualification records are recorded again. + +### RDMA setup guidance for macOS 27 + +When RDMA over Thunderbolt is turned off, `darkbloom cluster` and its setup screens now point a Mac on macOS 27 or later to Apple's switch in System Settings (Privacy & Security, RDMA over Thunderbolt, then restart) instead of macOS Recovery. Macs on macOS 26 keep the Recovery steps with `rdma_ctl enable`. Darkbloom still never changes the setting itself. + +### Releases carry their cluster runtime facts + +- Every release lane (dev branch, staging, prod) now computes the cluster runtime facts of its final signed app with that app's own CLI and worker: the digests of the cluster worker, placement tool, Metal library and paged-attention source, and for each model the build qualifies on a cluster and the environment's catalog has, the digests of its capability and its pair-serving grant. The job summary and a run artifact show them in every release. +- Each model's pair-serving grant lets a coordinator form its two-Mac pairs: a pair member reports only hardware capabilities, so without a grant no pair of GLM-5.3-Flash or Qwen3.8-27B forms. A declared public model's grant names its declared mode families; any other model's is the grant of the build's own qualification records, or none. +- GLM-5.3-Flash and Qwen3.8-27B are declared for public cluster traffic in pipeline and tensor parallel (owner decisions, 2026-10-31): their entries carry parity qualifications from which a coordinator derives their public qualifications, and it applies them to each declared mode family on any Apple silicon pair, with sampling and tools, and in tensor parallel images and video as the environment's catalog lists them. The qualifications name the evidence placement (two Apple M5 Ultras; a pipeline cut at half the model's layers), not a limit; no pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record, so both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash runs the serial prefill schedule only, so its schedule 2 entries are inert. Every other model's clusters serve their owner only. The setup says a declared model is qualified for public traffic in pipeline and tensor parallel. +- The release registration carries the facts as `cluster_runtime` only when that environment's repository variable (`DEV_CLUSTER_RUNTIME_ENABLED`, `STAGING_CLUSTER_RUNTIME_ENABLED`, `PROD_CLUSTER_RUNTIME_ENABLED`) is `true`; a coordinator that accepts the block then approves the build's two-Mac clusters automatically. Unset, the registration is unchanged and a failure to compute the facts only warns. +- `darkbloom cluster runtime-facts` (hidden) prints schema `darkbloom_cluster_runtime_v2`: the same digests as before plus each model's `pair_serving_grant` and `parity_qualifications`. + +### Cluster runtime facts leave out another model's catalog ID of a shared artifact + +- A release's cluster runtime facts no longer fail when one artifact is listed under the catalog IDs of two registered models. Production lists `gemma-4-26b` and `gemma-4-26b-8bit` for the same Gemma 4 26B artifact, and the build registers them as two runtime models that only the manifest tells apart. Only the 8-bit one is qualified on a pair, so `darkbloom cluster runtime-facts --release-candidates` stopped with "Qualified cluster models the release cannot describe: gemma-4-26b", and a production release with `PROD_CLUSTER_RUNTIME_ENABLED=true` would have stopped after signing. +- A catalog model ID whose candidates the build's worker describes only as another registered model is now that model's: it is left out of the facts and named on standard error (`note: left out, the catalog model ID of another registered model: …`). A catalog model ID of which the worker describes no candidate at all still fails the step. + +### Cluster served speeds count only for the build that served them + +- A two-Mac pair's planner and request router now use a served request's speed only for the worker build that served it. Each speed record in `~/.darkbloom/cluster/served-speed.json` names every rank's worker build; records from another build, including every record written before this release, give no speed and age out of the file, so a new build plans from the share probes and link measurements until it has served. Speeds served by older, slower builds no longer hold a tensor-parallel split where the current build's own probes balance it. The plan is still made for the prompt and answer lengths the pair's clients send. +- The plan says how many records it left out (`N record(s) from other worker builds ignored`). `darkbloom-cluster-plan plan --served` and `route --served` use records only for the build named with `--served-build SHA256`. + +### The cluster comes back after a reboot + +- After a restart each Mac serves again once it is logged in (by itself with automatic login on); `darkbloom cluster` says which applies to each Mac. +- `darkbloom cluster` (leader and members) installs this Mac's cluster service as a per-user LaunchAgent (`io.darkbloom.cluster-service.`): launchd starts it at login and runs it under the cluster supervisor (`darkbloom cluster service --supervise`), which restarts it after 15 s doubling to 300 s and parks it after three quick failures; launchd restarts only a supervisor that crashed. Running `darkbloom cluster` again keeps an unchanged agent, replaces a changed one, restarts a parked one, and takes over from a service an earlier version started in a terminal. Nothing is asked beyond the cluster link's one approval. +- `darkbloom cluster stop` stops this Mac's cluster service and removes its login agent (on the leader the cluster stops serving first); unpairing the last pairing (`darkbloom cluster pair --forget`) removes it too. `darkbloom status` shows whether the cluster service starts at login, whether it runs, and its supervisor's phase. + +### Cluster background network identity + +- Associate the cluster login service with its enclosing app so macOS can retain Local Network approval when the setup terminal exits. +- Replace older unassociated jobs through the normal cluster command; preserve idempotent startup and stop behavior. +- Keep socket failure details in lease diagnostics and explain the session lifetime of an ad-hoc development service. + +### The cluster service is no longer restarted while its pair is registered + +A pair registered with the coordinator could restart the cluster service of a Mac many times a day (about every 15 minutes on one DevNet leader: "heartbeat missing for 75 s while its process is alive"), and each restart dropped the pair for a short time. The Mac's part inherited the service's heartbeat file and wrote its own heartbeats into it, and the supervisor does not count a heartbeat from another process. The part now writes its heartbeats to a file of its own (`~/.darkbloom/cluster-setup/part-health.json`). + +### Cluster sessions without a fixed lifetime; rank lease and keep-warm + +- A model served by two Macs stays loaded and serving until you stop it, and a Mac that disappears is reported at once instead of stalling. +- A two-Mac cluster session has no fixed lifetime and no request count any more. The 300-second session (1,800 for MiMo), the sixteen-request cap, the installed session's teardown at its deadline, the rotation to a new session after sixteen requests and the member session's 900-second cap are removed; a loaded model stays resident and serving until it is stopped (`darkbloom stop`, an operator unload, an autopilot model switch) or a real failure is detected. The capability record drops `maxLifetimeSeconds` and `maxRequests`. +- Each worker holds a renewable rank lease instead (S03): armed before its weights load at most one grant away, renewed every 5 s for 30 s by its owner with an `extendDeadline` line on the worker's control pipe, which the worker reads from launch, through the load. An owner that stops renewing (it stopped, died or lost its link) leaves the worker to end by itself within the time to live, through the forced exit that releases MLX's wired memory first. The leader renews each remote owner's lease the same way (`renew` frames), and each owner renews its own worker's. +- A cluster member honors the coordinator's grant lease (S15): `native_pair_lease` frames move its deadline (a grant may leave at most 120 s plus 5 s of clock allowance); an established session survives a dropped control connection for the 90-second grace, and the member claims it again with `resume` in its registration. +- Keep-warm, on by default (S27): a GPU pulse on each worker's own executor every half second while idle once the first request has run (back-off for a minute after a slow submission), and a 1x16 data-plane exchange both ranks run about once a second while idle, sequenced by the leader; a failed exchange ends the session cleanly. `darkbloom-cluster-pair-check --keep-warm off` and the worker's `--keep-warm off` turn it off for comparison. +- `darkbloom-cluster-pair-check` takes any number of repetitions, idle gaps between them (`--idle-seconds`) and a qualification switch that stops renewing both leases (`--stop-renewals-after-seconds`). +- A Mac that vanishes from a cluster is a stated failure, not a stall: when the other member's link control connection closes or goes silent and does not come back within the link's own re-dial time (5 s for a closed connection, 10 s for a silent one with the default link timing, never past the 30 s rank lease), the leader fails the request in flight at once with the reason (`link edge: follower lost: ...`), stops waiting for cleanup proofs that can no longer arrive (the session is quarantined, rank 1 stays unproven, the other Mac's own lease and device journal still end its rank), and exits instead of lingering for minutes; the follower likewise fences a vanished leader's session at once instead of at the end of its lease. A follower that releases a session without a cleanup proof (its owner ended at launch) ends the leader's wait the same way. The follower now says why its rank ended (its worker's last word, e.g. the stage-load memory gate's refusal) and the leader's incident carries it, so such a start is classified `memory_gate_refused` with the follower's own numbers instead of an unexplained `peer_lost`. A cluster member whose coordinator control connection ends or loses trust says why (`Distributed serving stops: .`) and exits with a failure status. The stale bootstrap-directory check no longer connects to a listener's socket (a connect could fail a live launch); it reads the descriptor tables instead. +- Nothing of a dead cluster session is left behind (orphan eradication, ported from the owner's oMLX and ThunderMLX lifecycle work). An orphan sweep runs at every member's start and end and before every supervised restart, and on demand as `darkbloom cluster reap [--json] [--no-wait]`: a worker or owner whose parent process is gone is given its own contract (the rank lease, the owner's longest signal allowance and the forced exit's dead-man) to end, then SIGTERM, and SIGKILL only after the kill margin, and only while its process number still holds the same process (same start time; a reused number is never signalled); a device journal whose owner died is cleared through `cluster recover`'s proof; bootstrap directories whose socket no process holds any more are removed. `darkbloom cluster verify-teardown [--json] [--baseline-wired-bytes N] [--samples N]` reports, after a stop, whether any cluster process, wired memory above the baseline (tolerance: the larger of 1 GiB and 1/128 of physical memory), stranded journal or bootstrap directory is left (`darkbloom_cluster_teardown_verification_v1`, exit 1 when not clean). `darkbloom cluster cancel-all` force-cancels every request served on this Mac on its own: SIGUSR1 makes an owner fence its worker (the protocol's own drain) and a worker end its requests through the forced exit. A forced exit whose release keeps completing durable writes (`ProcessForcedExit.noteProgress`) gets its 20 s dead-man extended exactly once, to 40 s, and never otherwise. Every rank is started with MLX's command-buffer bounds (`MLX_MAX_OPS_PER_BUFFER=16`, `MLX_MAX_MB_PER_BUFFER=512`) unless the operator pinned them. + +### Cluster setup respects model reasoning defaults + +- Cluster setup tests a response using each model's default reasoning controls, so GLM-5.3 Flash no longer rejects the generic probe because it sends a binary thinking override. Reasoning-only output remains visible when the test token budget expires. + +### Cluster pairs serve sharded deployments by default + +- The planner chooses tensor parallel or a pipeline for the Macs it detects; phase split, phase split with MTP, the pipeline-prefill/tensor-decode hybrid and the per-request "alone" route are kept but off by default, reachable only behind `DARKBLOOM_CLUSTER_HANDOFF_MODES=1`, and a setup saved with one of them is refused at start without it. The onboarding's deployment line names the sharded mode. +- Qwen models with an MTP head and MiMo V2.6 Flash can decode as speculative rounds across the pipeline (`pipeline_mtp_v1`): the last Mac holds the head and a copy of the token embedding, drafts, and both Macs verify the drafts in one window. The planner credits the rounds only from what the same placement served with and without them, and a pair serves them only where its own qualification records pass. +- MiMo V2.6 Flash keeps prompt prefixes on both Macs, in memory and in the encrypted SSD tier, restored on both or neither. +- The pair's SSD prompt-cache tier carries its daily write cap across restarts, keeps other plans' records within one byte budget instead of wiping them, stores speculative history once per record, reads records page-aligned without a copy, and hashes model files in parallel. + +### Quantized SSD prompt-prefix records on the two-Mac cluster + +- The pair's encrypted SSD prompt-prefix records now store attention rows at the single-Mac checkpoint precision, `balanced` by default, like every other model's checkpoints: older rows in 4-bit keys and values (affine groups of 64, FP32 scale and offset, keys Hadamard-rotated) and each record's newest 128 rows exact. Recurrent, convolution and speculative-head state stays exact. A Qwen 3.8 27B tensor-parallel rank's attention rows at 32,768 tokens take about 3.2 times fewer bytes; GLM-5.3-Flash DSA layers about 1.8 times fewer, in pipeline and tensor parallel (BF16 latents; its index keys, pool gates and MTP history stay exact). Live KV stays native. +- A prefix restored from a quantized record is close to, not identical with, computing it again. `engine_v2_kv_checkpoint_quantization = "native"` (or `DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION=native`, per model with `engine_v2_kv_checkpoint_quantization_by_model`) keeps the pair's records byte-exact. Both Macs must resolve the same precision: the leader does not sync it, and the ranks bind it into their load agreement and refuse to load otherwise. Records of one precision are never restored under another. +- Quantizing a decoded row again does not give it back (the codec is not idempotent on its own output), so a record written from a request that was itself restored from a record keeps the restored rows' first encoding instead of quantizing them again: through repeated restore-and-extend cycles, such as a long conversation, each restored row stays as it was first stored. +- `darkbloom-cluster-tp-check run --prefix-records native|balanced|k8v4|k8v8` measures a record on real weights: per-layer errors, bytes against a native record, the prompt tail scored from the captured and the restored state, and the output after the restore. `darkbloom-cluster-pair-check --prefix-ssd-quantization` selects the workers' record precision. + +### Two-Mac clusters follow the provider's KV quantization + +- A pair's stage KV now uses the same live precision a single Mac uses for the + model: `engine_v2_kv_quantization` (global or per model) and + `DARKBLOOM_CBV2_KV_QUANTIZATION`, resolved on each Mac and passed to its + worker. The default stays native; pairs whose Macs keep it are unchanged. +- With `balanced`, `k8v4` or `k8v8`, the Qwen 3.5 family (Bonsai included), + Gemma 4 and Nemotron 3.5 stages and every Qwen tensor-parallel row's + request-owned lanes (9B, 27B, Qwen3.5/3.6 35B A3B, any capacity) store packed KV on the provider's own pool, after the same kernel check, + and their memory planning counts packed rows. Both Macs must resolve the same + precision; otherwise their load agreements differ and the pair refuses to + load. Set the pair's model to `native` per model to keep a packed global + setting off the pair. +- Packed stages keep no prompt prefixes, as on one Mac for packed KV. Phase + split, GPT-OSS and GLM refuse a packed precision; MiMo stays native. The pair's SSD prefix records stay exact native states. +- `DARKBLOOM_CLUSTER_KV_BACKEND=contiguous` is removed: cluster stage KV is + paged only. + +### Steadier, visible tensor-parallel choice in two-Mac clusters + +- Keep each pair's last eight link measurements from the last 30 days and plan + on their median, so one fast or slow load no longer switches a model between + tensor parallel and a pipeline. Link files from earlier releases still read. +- End a model's line in the setup's model list with a short reason when the + model supports tensor parallel but is split otherwise, such as "tensor + parallel: slower here"; models without tensor parallel show nothing extra. +- Explain that Qwen3.8 27B leaves out the pipeline because only tensor parallel + keeps images, video and logprobs, instead of saying no pipeline fits. +- Read the saved link measurements in `darkbloom-cluster-plan plan` when + `--link` is not given (or `--link-probes FILE`), say so, and print reduction + costs in ms or µs. + +### Cluster stop ordering + +- A paired leader now retires its owned part before asking its follower to stop, preserving the native shutdown channel. Failed retirement or missing peer acknowledgement keeps the login service available for recovery and returns an error. + +Require a fresh local supervision acknowledgement before stopping the peer so stale idle status cannot bypass a child start already in flight. + +Keep follower lease intent alive through local planned drain; serialize background serve/stop reconciliation and wait for outstanding running leases before publishing stop acknowledgement. A stop the pair could not finish exits with status 1 and the pair's reason, without usage text. + +### Stop a cluster Mac whose peer is gone + +`darkbloom cluster stop --local-only` stops only this Mac's cluster service and removes its login agent. It never asks the other Mac, for when that Mac is gone for good. Without the flag, a leader still drains the pair first and keeps its service when the member cannot acknowledge. The output says that the other Mac was not asked to stop. + +### Two-Mac clusters place tensor parallel first wherever it fits + +- A model whose tensor-parallel layout fits both Macs is now set up in tensor parallel even where the speed estimate favored a pipeline; the setup says so ("the model fits, so both Macs share every layer of every token") instead of claiming a gain it does not predict. A setup that loads now still goes ahead of tensor parallel that would not, and predictions are still shown. +- A new pair's first setup is tensor parallel too: before any load has measured the cable, it plans on the same assumed sealed reduction a forced plan uses, labelled as assumed. +- Automatic widening never assumes a link cost: it plans only on the pair's own recent sealed link measurement, and without one it keeps the running setup. +- `darkbloom-cluster-plan plan --tensor-parallel-first` plans the same way; without the flag the plan tool keeps the speed comparison. + +### A tensor-parallel cluster registers with the coordinator + +- A pair that serves a model in tensor parallel (GLM-5.3-Flash, Qwen3.8-27B) now registers its roster plan with the coordinator. The plan names `tensor_parallel_v1` and no layer cut, as the coordinator requires; before, the member registered the stage end as a cut, refused its own plan, and the pair served only its local API. A setup with unequal tensor-parallel shares is refused at registration until the plan carries its shares. +- The onboarding's start line for a cluster that serves through Darkbloom no longer says public serving is off in this build: it serves its owner's requests, and public requests where Darkbloom has qualified the model and split. +- A plan in `pipeline_prefill_tensor_decode_v1` (pipeline prefill, tensor-parallel decode) also registers: the coordinator lists the mode, and the member no longer refuses its own plan. + +### Tensor-parallel shares balanced by each Mac's measured speed + +- Time each Mac's own share of a dense Qwen model when it loads in tensor + parallel (at most about a second and a half, alone, nothing crossing the + cable), and keep each Mac's newest timing per share and model for 30 days on + the leading Mac. The next plan balances the shares by those timings: with the + timings an M3 Ultra and an M5 Max measured, Qwen3.8 27B is planned 1:1 + instead of 2:1 after one load. A Mac short of memory skips the timing, and it + never fails a load. +- Stop predicting a larger tensor-parallel share faster than a smaller one: a + Mac's measured shares are no longer drawn toward its whole-model speed, and + what the pair served corrects all of a Mac's measured shares alike. +- Read the saved share timings in `darkbloom-cluster-plan plan` (or + `--share-probes FILE`) and name the shares used, as the setup plans. +- A load that serves the speculative head balances its shares on each Mac's measured verify window rather than its single-token step, because its rounds run windows: on the Qwen3.8 27B pair that moves the split from 3:2 to about even. + +### Fixed + +- Automatic cluster planning considers tensor-parallel placements independently + of pipeline layer cuts and counts enumerated candidates instead of unused + pipeline-cut combinations against its search limit. Unsupported runtime modes and rank counts now explain the pipeline + fallback before requesting a link measurement, without claiming an unmeasured + speedup. This does not enable tensor parallelism for GLM. + +### Cluster validation, tensor batching and media ownership + +- Repair local two-Mac setup, installed lane propagation, encrypted peer agreement, + request-scoped placement and delayed automatic batch replacement without + weakening native teardown, memory or failed-qualification gates. +- Preserve measured shard rates and independently price native batch capacity; + exact Qwen3.8 27B retains feature-preserving TP selection with the complete + native request reservation coexisting with LOAD scratch and allocator demand. +- Preview Qwen27 widths 8, 4 and 2 against current bilateral memory before + replacing the serving owner, then recheck the exact proposed width after release. +- Pass the indexed devices, recorded keyed pair-link costs and filtered served + history into automatic replacement, allowing its tensor candidates to be + considered instead of silently using an unmeasured link. +- Add Qwen27 independent TP histories, grouped collectives, per-request sampling + and captured logprobs, with checked bilateral cancellation and retirement. +- Coalesce nearby Qwen27 TP token acknowledgments within the existing bounded + scheduling window so ready rows can decode together; joining, prefill, + cancellation and retirement continue without waiting for a silent client. +- Reuse mutually held original-grid Qwen27 TP prefixes with bounded resident + snapshots, fresh per-request histories, separately priced capture/cache banks + and publication only after bilateral clean retirement. +- Route exact Qwen27 images and video through bounded provider preparation and + the native vision owner, retaining encoded data and host/native allowances + until their respective completion fences. Unsupported controls refuse explicitly. +- Bind streamed logprobs to committed content events and repair local HTTP + reasoning, sampling, usage and tool/constraint parity handling. +- Repair Qwen expert reductions and mixed-router accounting; add Bonsai packed-row + arithmetic and qualification coverage; preserve Gemma prompt arithmetic, + catalog aliases and prefix restore/chunk semantics. +- Repair GPT-OSS, MiMo and Nemotron native independent-history batching, paging, + cancellation and prefix behavior, including existing MiMo speculative/phase + state accounting. Historical phase support is not TP release qualification. +- Order fast Metal fence waits after current-pass GPU producers through the + matching native core pin; installed clustered-concurrency validation remains required. +- Retain explicit full-model hardware gates. Component tests and source support + do not establish universal TP, media parity or release readiness; Qwen27 TP + text speculation remains unfinished; full-artifact prefix/media qualification + and final automatic-planner validation remain separate gates. + +- Preserve an explicit local fast-synchronization diagnostic choice through both installed TP owner and native worker launches. Only canonical `0` or `1` is forwarded; normal defaults and placement remain unchanged. + +Every tensor-parallel worker, widened Qwen rows included, keeps fast synchronization; explicit local synchronization choices still take precedence. Native batching and model capabilities remain enabled. + +Authenticated Qwen3.8 27B TP owners now use the same fully priced request-owned execution at one lane and wider capacities. Automatic capacity changes preserve the tensor split, preventing capacity changes from switching the attention path or repartitioning arithmetic. The original exact-output acceptance gate remains required. + +- Forward an explicit local eager-fence-commit diagnostic through the installed tensor owner and native worker, reporting its canonical value at startup while preserving the default. +- Report completed decode steps by actual batch width once per retired or failed scope, without request content or extra memory samples. + +### Cluster worker protocol 2: prompts cross as packed token IDs + +- A cluster reservation carries its prompt as packed little-endian token IDs (base64) with an explicit count instead of a JSON number array, and the leader builds a relayed command's link wire once. A 31.5K-token reservation decodes in about 1 ms per hop instead of about 12 ms, which shortens time to first token on long prompts. Both Macs must run the same release: a Mac on the previous protocol is refused at setup or pairing ("Install the same Darkbloom release on both Macs, then run `darkbloom cluster` again"), never in the middle of a request. + +### Preserve truncated reasoning in collected responses + +- Keep unfinished prompt-side thinking in reasoning fields for collected Chat and Responses, retrieval and continued history. Preserve explicit parser overrides, native parsed channels and token usage. + +### Distributed startup signal restoration + +Distributed startup restores both SIGTERM and SIGINT dispositions, including +handler flags and blocked signals, even when one signal was already ignored. +A termination request received before serving starts remains latched. + +### GLM cluster prefill and finite-calibration placement + +- Scan all structural cuts against current local device bounds and choose a common feasible cut through the existing performance-aware planner. +- Run the selected cut through the installed signed quotation and finite owner path; preserve explicit diagnostic cuts. +- Keep predicted speed, measured-best throughput and calibrated serving eligibility distinct. Public GLM endpoint eligibility is unchanged. +- Raise the registered GLM NVFP4 cluster candidate's prefill chunk cap to 2048 while retaining bounded authenticated logical arrays, raw frames and records. Keep the workspace conservative pending scope-matched native/host peak qualification; other models' default caps and public qualification records remain unchanged. +- Allow finite calibration up to 2048 prompt/chunk tokens with the existing 16-output cap and at most 2064 context. Automatic chunk hints ignore prompts shorter than their configured chunk and match artifact identity when available; fallback uses the current model/worker caps without creating a qualification grant. + +### Bounded GLM cluster still-image candidate + +- Add bounded encoded PNG ingress, rank-0 native GLM vision loading and causal feature splicing to the private two-rank pipeline, with additive memory charges and cold media prefix isolation. +- Require the explicit local image qualification profile through `darkbloom cluster local glm-5.3-flash --private-glm-image-qualification`; ordinary text serving rejects images before reservation and excludes the vision tower from planning and LOAD. +- Keep video unqualified and audio refused. Full-model image correctness, memory, cancellation and real CLI/HTTP qualification remain required before a serving modality can be advertised. + +### GLM-5.3-Flash SDK speedups shared with the single-Mac release + +- The SDK's pipelined KDA prefill recurrence now also covers 64 heads on an 80-core M5 Ultra (two + value-row ranges per GPU core): one Mac and each GLM pipeline stage prefill faster with bit-identical + outputs; a tensor-parallel rank's 32 heads keep their cut, so tensor-parallel GLM is unchanged. +- The CBv2 MTP loop can submit every draft step as soon as it is built (on for the single-Mac GLM + profile); the two-Mac GLM path runs its own speculation loop and is unchanged. + +### GLM tensor-parallel decode command buffers and sum fences + +- GLM tensor-parallel decode steps, MTP rounds and lane rounds encode up to 100 operations a Metal command buffer instead of the rank guard's 16, which prefill keeps; each further buffer cost about 10 µs of GPU time (13.24 to 12.56 ms a decode step on two M5 Ultra, tokens identical). +- GLM tensor-parallel workers let the hyper-connection site wait for each all-sum in-kernel (`MLX_METAL_FENCED_INPUTS`; a launcher value is kept). The fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: its multi-threadgroup path (partials above 32 KB) never signals the CPU, which stalled batched lanes about 0.7 s a round. + +### GLM tensor-parallel MTP rounds submit their proposals early + +- A GLM tensor-parallel MTP round (solo or batched lanes) submits its NextN priming and proposals as soon as they are built, so the GPU computes them while the host builds the verification forward instead of idling through the whole round's build: a depth-2 round 23.06 to 21.64 ms (95.9 to 102.7 tok/s) and two lanes 115.2 to 121.6 tok/s on two M5 Ultra, tokens and top logits identical. `darkbloom-cluster-tp-check glm --mtp-early none|proposals|layers` compares the modes. + +### GLM tensor-parallel greedy MTP rounds split the head's vocabulary + +- A greedy GLM tensor-parallel MTP round (solo or batched lanes) reads out only its half of the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum (each rank's half maximum and argmax; rank 0's lower index wins a tie, as MLX's argmax does): a depth-2 round 21.32 to 21.05 ms on two M5 Ultra, tokens and top logits identical. Sampled rounds keep the whole head. `darkbloom-cluster-tp-check glm --mtp-vocab-split yes|no` compares them. + +### GLM-5.3-Flash runs tensor parallel across two Macs + +- `darkbloom cluster` can now serve GLM-5.3-Flash text requests with both Macs working on every layer (tensor parallel) instead of each Mac holding half the layers. On two M5 Ultra 256 GB it chooses this by itself once the cable has been measured: the setup's test answered at 51 tokens/s against 42 for the layer split, and long prompts prefill at about 3,300 tokens/s against 1,450 (one Mac alone: about 1,800), and decode runs at 53 tokens/s. Every byte between the Macs stays encrypted. A repeated prompt prefix (a chat's history) is reused on both Macs instead of prefilled again. Image requests still use the layer split. +- The cable measurement that decides between the two modes now times the encrypted sum as a running model pays it, not cold: it had read three times slower and kept tensor parallel from being chosen. +- The Macs exchange GLM's per-layer sums at half the size: the model's own 16-bit values instead of the same values widened to 32 bits, with an identical result. Prompts prefill about 14% faster. +- Tensor-parallel decode is faster: the worker lets each GPU command buffer take whole expert banks instead of committing one at every expert layer (about 88 commits a token instead of 22), and MLX spends less host time per kernel launch. On two M5 Ultra, decode went from 53 to about 57 tokens/s through the API (62 in the bench). +- Fixed a hang where the GPU could wait forever on an encrypted sum between two GPU steps. +- What a tensor-parallel setup served no longer resets the speeds the planner learned from a pipeline the same Macs served: it corrects only the tensor-parallel figures. Before, after serving in tensor parallel the planner priced the layer split as fast as one Mac alone and switched back to it. This applies to every model the cluster plans. +- The hardware speed prior no longer counts every routed expert of a mixture-of-experts model as read on each decode step. It counts only the experts a token is routed to, and it does not count replicated weights as divided by a tensor-parallel share. +- Greedy GLM-5.3-Flash requests in tensor parallel now decode speculatively with the model's own next-token-prediction layer, which each Mac now also loads (about 4.2 GB more per Mac): each step checks the layer's guess together with the next token and keeps both when the guess is right, so greedy decode produces more tokens per step (two guesses a step: about 76 tokens/s against 63 in the bench on two M5 Ultra). Sampled requests decode as before. +- Tensor-parallel prefill is faster: each encrypted sum between the Macs is now sealed, sent, opened and added in 256 KiB pieces as they become ready instead of as one block, so the encryption overlaps the transfer (a 15.7K-token prompt prefilled at 3,812 tokens/s against 3,554 in the bench). Every piece is still authenticated, and a piece that does not open fails the request. +- Tensor-parallel decode no longer waits between steps for the serving process's answer to each token (whether to go on). The token is handed over at once and the answer is read once the next step is running, so its round trip overlaps the GPU work (two M5 Ultra through the API: about 73.5 to 77 tokens/s). A stop request still ends the output exactly where it was asked for; one extra step may be computed and is never sent. +- GLM-5.3-Flash decodes and prefills faster on Apple silicon, on one Mac and across two: fewer and faster GPU launches for the hyper-connection, mixture-of-experts and sparse-attention steps, and less CPU time per launch. Outputs are unchanged bit for bit. On two M5 Ultra through the API, decode went from about 78 to 90 tokens/s and long-prompt prefill from about 3,470 to 3,540 tokens/s. + +### GLM-5.3-Flash native prerequisites + +- Use one peer-status observation for each finite GLM terminal-context decision, avoiding a false transport-loss rejection across an expected peer close while preserving exact acknowledgment consumption, frozen connection identity and durable owner/fence retirement. Encrypted loopback CPU coverage does not qualify model, GPU, RDMA or serving behavior. + +### Models load when every model's minimum KV fits + +- Loading a model beside others no longer fails with "would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance" while the KV budget still covers every model's minimum. The split gave each model a share in proportion to its per-token KV cost alone. A resident model with a small per-token cost and a fixed per-request workspace, such as Nemotron 3.5 Lightning with its assistant on, could get less than its own minimum and block every further load. Now, when that would happen, each model gets its minimum first and the rest of the budget is split as before; the message now appears only when the minimums together exceed the budget. The model being loaded counts only the 1 GB base minimum until it is built, so Lightning itself can still fail to load, with no KV headroom, when it joins several high-rate models. +- A split that already gives every model its minimum is unchanged. Unloading a model, or a change to the activation reserve, no longer shrinks another model below its minimum. + +### The local Responses API continues a conversation from `previous_response_id` + +- `/v1/responses` on a single Mac and on a cluster now honours `previous_response_id`: the request continues the earlier input and that response's output, as with OpenAI. A follow-up that sends only a `function_call_output` item resolves its tool call instead of failing with 400, and a later turn remembers earlier ones. +- An ID this process does not hold (never served, sent with `"store": false`, dropped from the bounded in-memory store, or from before a restart) returns 400 with code `previous_response_not_found`. + +### Media the model's processor refuses answers 400 on one Mac and on a pair + +- An image or video the model's processor refuses now returns HTTP 400 `Invalid media input.` (`invalid_media`) on one Mac and on a two-Mac pair: for Qwen 3.5 and 3.8 a side below 32 pixels (a 16×16 PNG, for one; the processor does not upscale it) or an aspect ratio above 200:1, a video without a decodable track, or more media than a processor takes. It returned the retryable 503 capacity answer, so the coordinator tried other providers that refuse it the same way. + +### A request's `min_p` now applies on one Mac too + +- A request's `min_p` now applies on one Mac too, as it already did on a cluster pair: tokens less likely than `min_p` times the most likely token are dropped before sampling (values above 1 count as 1). Requests without `min_p`, or with 0, are unchanged. + +### One GPU stream per decode graph, and no GPU-on-GPU fence spins + +With MLX fast fences (`MLX_METAL_FAST_SYNCH=1`) a widened Qwen 3.8 27B +tensor-parallel owner could stop at its first multi-row plain decode (the c14, +c17 and c39 stalls). MLX cast each batched 4-bit projection's bfloat16 scales +and biases to float32 on the thread's default GPU stream instead of the stream +the caller passed, and mlx-swift runs everything else on its own process-wide +stream, so that decode graph ran on two GPU streams. A fast GPU fence wait is a +kernel that spins on its queue until the other queue's timestamp arrives, and +Metal does not promise that the other queue runs meanwhile, so both queues +stopped. The casts (and MLX's other helper ops that dropped the caller's +stream) now stay on the caller's stream, and a GPU stream never spins on +another GPU stream: it waits on a shared event, while the CPU <-> GPU +collective waits keep the spinning fast path. Synchronization only: tokens are +unchanged. Widened Qwen 3.8 27B owners stay on the event path until a two-Mac +acceptance with fast fences passes on this fix. + +### Pair-check reservations keep their media + +- `darkbloom-cluster-pair-check` hands each worker the whole reservation when it moves the deadline to that worker's clock. It dropped still images and Qwen image/video input, so those qualification requests reached the workers without their media. The owner and peer-link hops re-time reservations with the same field-preserving copy. + +### Faster prompts on Macs without neural accelerators + +- MLX's steel affine quantized matmul computes prompt-sized products (256 rows + or more, 64-aligned outputs) in 64-row x 32-column tiles for 16-bit inputs and + 32 x 64 for FP32 partials instead of 32 x 32 on GPUs without neural + accelerators (M1-M4, and the M3 Ultra rank of a pair). On the M3 Ultra alone a + 4,096-token prompt took 2.5% less time (27B 12.37 -> 12.06 s, 9B 3.55 -> 3.46 s) + with the same tokens. `MLX_QMM_STEEL_TILE=32` restores the previous tile. +- Qwen tensor-parallel prompt frames are submitted to the GPU every four layers + while they are built (`DARKBLOOM_QWEN_TP_PREFILL_STRIDE=0` restores whole-frame + evaluation). With both changes the 27B pair at 1:1 reached its first token + 1.4-3.1% sooner (4K 8.22 -> 8.08 s, 16K 36.7 -> 35.5 s, 32K 81.8 -> 80.0 s) and + the 9B pair 1.1-2.3% sooner (4K 2.63 -> 2.60 s, 32K 27.5 -> 26.9 s), with the + same tokens. +- Diagnostics: `darkbloom-cluster-tp-check qwen-prefill` (one rank's prompt + frames, layers and projections), `DARKBLOOM_QWEN_TP_PREFILL_FRAME_TIMING=1` + and `pair-check --worker-environment`. + +### Concurrent tensor-parallel requests draft together + +- When several speculative requests on a two-Mac tensor-parallel pair draft in the same round, their assistant steps now run as one batch: one head call and one pair of sealed exchanges per draft step for every row, instead of one per row. Six concurrent requests need about a third of the reductions they needed before, and every request still produces exactly the tokens it produces alone. + +### Concurrent tensor-parallel requests verify together + +- Concurrent speculative requests on a two-Mac tensor-parallel pair now stay in one verify cohort. A request that still has up to one round of accepted tokens waiting joins the next round from its own settled position instead of waiting for its queue to drain, so requests that started a step apart no longer take turns verifying alone. Every request still produces exactly the tokens it produces alone. + +### Concurrent tensor-parallel requests share each draft step's weight reads + +- On a two-Mac tensor-parallel pair, speculative drafts now use the same batch-invariant kernel as decoding. When several requests draft in the same round, every draft step after the first runs all of them through one assistant pass, and every head call serves all of them, so each weight is read once per step for the whole batch instead of once per request. With eight concurrent Qwen3.8 27B requests, a round's draft work on one Mac fell from about 38 to 24 ms. +- A request proposes the same tokens alone and in a batch of any size, and every request still produces exactly the tokens the model produces without speculation. Proposals can differ from the previous kernels at near-ties, so the share of accepted proposals can shift slightly; the output never does. +- Both Macs must use the same draft kernel or the pair refuses to load. `DARKBLOOM_QWEN_TP_MTP_EXACT_DRAFTS=0` (diagnostic only, never forwarded to an installed rank) keeps the previous kernels. Single-Mac speculative decoding is unchanged. + +### Six-request tensor-parallel batches + +- Automatic batching on a two-Mac tensor-parallel pair can now choose six concurrent requests, between four and eight, when eight do not fit. Pipeline batching keeps its widths of two, four and eight. + +### Qwen tensor-parallel verification keeps its measured weight-read tiles + +- Two-Mac tensor-parallel Qwen pairs verify concurrent requests with tiles of at most five vectors per weight read again (tiles of four past five), instead of whole-cohort tiles of eight or sixteen. On two M5 Ultra Macs serving Qwen3.8 27B, four concurrent requests reach about 90 tokens per second together instead of 73, with identical outputs. + +### Widened Qwen tensor-parallel owners keep fast fences + +Qwen tensor-parallel owners with more than one lane (Qwen3.8 27B, and the Qwen3.5 9B and both 35B A3B rows) keep MLX's fast fence waits instead of the slower event path. The stall that once stopped a widened pair right after a request finished is fixed at its cause: MLX kept a batched step on one GPU stream, and batched rows no longer convert their scales each step. + +### Wider automatic batching on two-Mac pairs + +- A two-Mac tensor-parallel owner now reserves much less memory per request, so automatic batching can widen past two concurrent requests when the Macs have room. A request no longer reserves its own full-history attention gather (decode and verification read pages in place, and one shared gather serves the single prompt frame a step runs). After a speculative round, a request keeps only its own recurrent rows instead of the whole round's. A long prompt's draft history moves into the assistant's cache as the prompt is read instead of waiting whole for the first draft. For Qwen3.8 27B with 32K-token prompts and 32K-token outputs, two, four and eight requests reserve 16.1, 25.7 and 45.5 GiB per Mac at an equal split, down from 21.4, 40.5 and 86.0 GiB. Qwen3.5 9B and the 35B A3B rows shrink the same way. +- Before replacing a running owner with a wider one, the preview now counts that owner's loaded weights on each Mac as free, because they are released before the wider owner loads. It does so only for a replacement that keeps the same split. The owner's unused request reservation is never counted, and the memory check after release is unchanged. A width that fails that check is not credited again for 10 minutes. +- Every width that automatic batching refuses is logged as one line, `cluster.batch_replan refused lanes=N`. It gives the phase (preview or after release), the reason, and each Mac's need, admissible memory, shortfall, weights and fit, in bytes. +- Every request still produces exactly the tokens it produces alone. + +### Qwen27 feature-preserving cluster modes + +Keep images, video and committed-token logprobs in the registered Qwen3.8 27B cluster route by admitting tensor parallel before unchanged speed ranking. Replan old pipeline setups instead of silently serving fewer features, retain native link/shape/memory gates, and require matching actual media READY and logprob support before creating the bridge. Other model and GLM mode policies remain unchanged. + +### Qwen27 media response formats + +- Accept image/video `response_format` requests through the cluster's existing + Qwen27 media path, using the same JSON prompt preparation and nonstream + JSON/schema post-validation as standalone serving. +- Preserve forced-media-tool refusals and default processor policy. Streaming + remains prompt-guided; this does not add token-level grammar enforcement or + establish full-model media/schema accuracy. + +### Qwen27 tensor-parallel greedy choices without full-vocabulary gathers + +Qwen27 tensor-parallel speculative decoding no longer moves complete vocabulary rows between the Macs for greedy work. Each draft step and each greedy verification column reduces a rank's vocabulary shard to its maximum and first index (plus a non-finite count when verifying), and one small exchange gives both Macs the same choice: the complete row's first maximum, with the lower index winning ties. Greedy verification also drops its separate choice broadcast. Sampled requests and logprobs still gather complete rows. + +### Qwen 3.8 27B pair media: preparation on its own stream, refused alone + +- A Qwen 3.8 27B tensor-parallel pair no longer ends both workers when rank 0's + media preparation fails. Rank 0 prepares a request's image or video patches at + admission, on a CPU stream of its own while its executor waits, so another + thread's failed CPU work can no longer fail the preparation (after the main + merge, MLX overlaps evaluations across threads and hands a stream's stored + error to whichever caller synchronizes it next; the pair's media requests + failed this way after a dozen had passed). A preparation that does not + reproduce the leader's patches refuses that request alone with a retryable + error and its reason in the worker log, and the pair keeps serving. A vision + tower failure still ends the workers. + +### Qwen27 tensor-parallel speculative depth 3 + +Automatic Qwen27 tensor-parallel setup now drafts three tokens a round instead of two. On the installed pair the assistant's first and second drafts were accepted 87% and 84% of the time, so a third proposal adds about 0.6 tokens a round for one more draft step; the verify window stays bound by one weight pass. Every emitted token is still the target's own choice. + +### Faster concurrent Qwen27 tensor-parallel verification + +Concurrent Qwen27 tensor-parallel requests now share each quantized projection's call when verifying their speculative windows, as long as the combined rows stay below MLX's vector-kernel limit for the device. Every request keeps the arithmetic it has alone. Draft proposals no longer need their own broadcast: both Macs read them from the same small exchange. A new `darkbloom-tp-mtp-profile-v1` worker line splits each round's time into draft, build, verify, gather, choose and settle. + +### Fewer weight reads for concurrent Qwen27 verification + +Concurrent Qwen27 tensor-parallel speculative windows now go through an exact four-bit projection kernel where it is faster than MLX's own calls: it reads each projection's weights once for up to eight verify rows (two four-column windows), where MLX's vector kernel reads them once for every five. On the M5 Max it keeps one output row per thread (up to 20% faster); on the M3 Ultra the row-parallel FP32 partials use two rows per thread (1.5-2.1x faster) and other projections keep MLX's calls. Each row keeps MLX's own `qmv_wide` reduction, so every request still gets byte-identical results to running alone; other GPU families keep MLX's calls. + +## v0.10.5 + +Published 2026-10-30 ([release](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5)). ### Upgrade and rollout notes diff --git a/changelog.d/cli-download-progress-line.md b/changelog.d/cli-download-progress-line.md deleted file mode 100644 index e882171317..0000000000 --- a/changelog.d/cli-download-progress-line.md +++ /dev/null @@ -1,8 +0,0 @@ -### One progress line for model downloads - -- `darkbloom models download` and the `darkbloom start` picker show one line for the whole model, redrawn in place at most four times a second: a bar, the percent, the bytes, the rate and the time left, leaving out what does not fit the window's width. They no longer print a line for every file or a block of per-file bars. -- The line keeps its shape while the window keeps its width: each figure has a fixed column, sized for its widest form, so the bar and the figures do not move as the numbers change. The rate and the time left appear after 2 seconds, and a time left over 24 hours is not shown. -- The line reads "Verifying" while the files are checked, then ends with one line: `✓ Downloaded (16.3 GB in 2m 10s)`, `✓ is already downloaded (16.3 GB)`, where the download stopped, or `Verification of failed: `. The picker no longer adds its own "Downloaded" line, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. -- Without a terminal (a pipe, a log, the desktop app) the download prints plain lines with no carriage returns: the first at once, then at most one per 30 s and 10 points, one at 100%, and the same last lines. The desktop app reads its download progress from them. -- `darkbloom cluster` shows a model download or a copy over the cable on its live line instead of adding a line every second. A plain transcript keeps the first report, about one per 30 s and 10 points, and the lines for the record. -- Sizes in the line are decimal, as the catalog gives them. diff --git a/changelog.d/cluster-balanced-equal-cut.md b/changelog.d/cluster-balanced-equal-cut.md deleted file mode 100644 index 1f720fec21..0000000000 --- a/changelog.d/cluster-balanced-equal-cut.md +++ /dev/null @@ -1,3 +0,0 @@ -### Identical Macs split a model evenly - -- When cuts predict the same request time (identical Macs, or equal measured speeds), the placement planner now chooses the one that uses each Mac's hardware capacity most evenly, instead of the earliest cut the second Mac's free memory held at that moment. Two M5 Ultra 256 GB had planned GLM-5.3-Flash 11/34 and then 5/40 of its 45 layers; they now plan it 22/23 whichever Mac leads. A faster split is never traded for balance, and the "Quit apps first" refusal is unchanged. This applies to every model the cluster plans. diff --git a/changelog.d/cluster-bonsai-residual-and-gate-pressure.md b/changelog.d/cluster-bonsai-residual-and-gate-pressure.md deleted file mode 100644 index 4bac41a79f..0000000000 --- a/changelog.d/cluster-bonsai-residual-and-gate-pressure.md +++ /dev/null @@ -1,4 +0,0 @@ -### Bonsai FP32 residual stream and the cluster memory gate under pressure - -- Bonsai (Prism) packs keep their FP32 residual stream on the fused Qwen 3.5 decode, verify and stage paths. The fused residual step rounded each FP32 branch to the stream's FP16 embedding dtype, so the stream stayed FP16 and a Bonsai producer stage's residual left its FP32 contract; such a stream now takes the unfused sum, as the unfused forward computes it. Qwen 27B and the other uniform-dtype rows are unchanged. -- The cluster load gate's room-making pass runs only at normal memory pressure. Above it the gate withdraws all file cache on purpose, and a refusal now stands on the gate's own sample instead of a fresh one taken after the pass. diff --git a/changelog.d/cluster-capability-honesty.md b/changelog.d/cluster-capability-honesty.md deleted file mode 100644 index f2a482d364..0000000000 --- a/changelog.d/cluster-capability-honesty.md +++ /dev/null @@ -1,7 +0,0 @@ -### Two-Mac cluster capability honesty - -- A cluster member registers image and video input only when its pair's placed mode serves media (GLM-5.3-Flash and Qwen3.8 27B in tensor parallel), so the coordinator no longer routes media to a pipeline pair that answers text only; a pair registered for media serves only while both Macs report the media contract. -- `darkbloom cluster status` and the pair's `/metrics` report MTP on for GLM-5.3-Flash in tensor parallel, which always decodes with its NextN head (depth 2); they said "MTP off". -- A content part of an unknown type (`input_file`, `input_video`, `refusal`, ...) is refused with HTTP 400 naming the type on the local API of one Mac and of a pair, and with the closed invalid-request error on coordinator requests, instead of being answered from the remaining text. -- With images or video, a GLM-5.3-Flash pair answers the output controls as one Mac does: it withholds hidden reasoning (`reasoning.exclude`, `include_reasoning: false`, `thinking.display: "omitted"`) and refuses a `response_format` JSON answer or a required or named tool call with 400 before any media decode. -- A `response_format` answer the service validates that was cut off by `max_tokens` (a reasoning model can think through the whole budget) now returns 422 saying so, instead of "Internal inference failure." GLM-5.3-Flash, which validates its withheld JSON itself, keeps its typed 422. diff --git a/changelog.d/cluster-cdn-manifest-pins.md b/changelog.d/cluster-cdn-manifest-pins.md deleted file mode 100644 index 1c56afb2fd..0000000000 --- a/changelog.d/cluster-cdn-manifest-pins.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster models pin the manifest a Mac downloads - -- The cluster worker now pins the model CDN's `manifest.json` bytes for every registered model. GLM-5.3-Flash pinned bytes that no Mac could fetch, so a downloaded GLM was never described and the cluster refused it. Qwen3.5 35B A3B, Qwen3.6 35B A3B, Nemotron 3.5 Lightning, GPT-OSS 20B, MiMo V2.6 Flash and the three Gemma 4 26B entries pinned the production coordinator's re-encoding, whose `created_at` is different on each environment, so DevNet could not use them. The files and aggregate digests are unchanged; only the pinned serialization of each manifest is different. -- A cluster folder with the earlier bytes is repaired when setup next lists the models, with no hand step. This includes a folder copied over the cable from the other Mac, which has no download receipt on this Mac. The cluster store fetches the published manifest (the CDN first, then the coordinator) and writes it in place only when it names the same model, version, aggregate and files and this Mac's worker takes it. Weight files are not written. When nothing answers, the folder stays as it is and the repair is tried again a minute later. When the published manifest names other files, the folder stays as it is and the worker refuses it as before. diff --git a/changelog.d/cluster-control-leader-failover.md b/changelog.d/cluster-control-leader-failover.md deleted file mode 100644 index b6e338be34..0000000000 --- a/changelog.d/cluster-control-leader-failover.md +++ /dev/null @@ -1,13 +0,0 @@ -### Derived cluster control leader, failover, `darkbloom cluster` on every member - -- If one Mac goes away the cluster keeps itself running and re-forms by itself when it is back; `darkbloom cluster` works on either Mac. -- The cluster's control leader is derived, not the Mac where onboarding started: once a plan is adopted its rank 0 leads (requests enter there and registration v3 treats the plan's first member as the head); otherwise the member present that holds the model alone, then the most memory, the most GPU cores and the lowest member identity (from its Secure Enclave key pin). Leadership is a claim with a term, persisted in each Mac's setup record so a restart re-forms the same way; claims are totally ordered (term, then identity), travel only over the pairing-keyed link control channel, and a member refuses a superseded claim so a stale leader steps down. A leader acts on the cluster only after every plan member confirmed its claim. -- The leader renews a control lease with each member at the rank lease's cadence (5 s / 30 s) on a listener and edge epoch of its own. When the leader's lease expires the survivor takes over at the next term; a leader left alone serves the model on that Mac alone when the planner said it holds it alone (the ordinary single-Mac local server under the Mac's own identity: "degraded: serving on this Mac alone"), and otherwise says it cannot serve and runs nothing. When the missing Mac answers again the pair re-forms by itself and control returns to rank 0. -- `darkbloom cluster` works on any member: status, test request, model change, stop and start, and a verify-teardown summary of every Mac are forwarded to the control leader and its answer is shown. A model change while serving drains both Macs' parts before the setup changes. -- Failover serves alone only on a verdict for the plan saved now: the planner's alone verdicts are recorded with the plan's SHA-256, travel with the lease under it and are dropped for any other plan, and a refused (stale) lease never rewrites them; a member that has a new setup but not yet its verdicts says it cannot serve rather than load a model the planner never checked for it. A Mac re-paired with another Mac starts a new leadership history at term 0 instead of carrying the old pair's claim (which named the gone Mac and not the new one). -- Serving alone waits for the absence grace (10 minutes of peer or link absence, for every model and Mac): control still fails over at lease expiry (30 s), but until the grace ends the leader keeps its part ready for the missing Mac, its status says how long until it serves alone, and a Mac back before the grace re-forms the pair with nobody serving alone. A developer (debug) build may shorten the grace with `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS`. -- A Mac restarted with a saved leader claim acts as the leader (model change, setup write, start, stop; forwarded or typed) only once the other Mac confirmed the claim, or once the confirmation window passed with no member reachable; a superseded claim steps down first and the command goes to the current leader. -- The control lease runs on the continuous clock, which keeps counting while a Mac sleeps: a woken leader no longer counts a Mac that left during the sleep as present, and a woken member gives its leader one lease time awake before it takes over. -- The solo readiness check names this Mac's own solo server (its process, checked by start time, holds the listening socket) instead of trusting any server on the port; another program on the port is reported as such. -- `darkbloom cluster verify-teardown` counts only this cluster's processes: its workers carry this Mac's member identity, its owners run this install's executable or own one of its workers. Other cluster homes' processes (another identity or install, a check's fake workers) are listed apart and do not fail the check. -- A rank 0 told to stop while it is still starting exits promptly: the signal handler is installed first (a stop is latched, never lost), the wait for the follower ends within 0.2 s of the stop, and the cluster service repeats SIGTERM every 5 s while it waits (never SIGKILL). diff --git a/changelog.d/cluster-coordinator-paired-approval.md b/changelog.d/cluster-coordinator-paired-approval.md deleted file mode 100644 index eb30795823..0000000000 --- a/changelog.d/cluster-coordinator-paired-approval.md +++ /dev/null @@ -1,6 +0,0 @@ -### A Mac pair registers with the coordinator as a cluster member by itself (DevNet) - -- After the Test stage passes, `darkbloom cluster` reads the cluster approvals the coordinator serves (`GET /v1/cluster/approvals`, from the operator approval file) and takes the entry whose model, prefill schedule and eight digests match this pair's installed app and model. Each Mac checks it against its own files before it saves it, and both Macs save it, or neither does. Both Macs then run as coordinator-paired members, owner-only, and the status says "Registered with the coordinator as a cluster member" with the approval and its end. -- The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching entry when the saved one ends within a day. An approval that ended is removed before a part starts, and the pair serves on the leader's local API again. -- When the coordinator gives no answer for 10 minutes (the absence grace), the pair serves on the leader's local API, and it is registered again when the coordinator answers with a matching entry. -- A coordinator without pair control (production, staging) or without a matching entry changes nothing: the saved setups stay byte for byte as they were. `darkbloom cluster local` never asks the coordinator. A pair approval saved by hand with `darkbloom cluster configure` is never removed. diff --git a/changelog.d/cluster-degraded-mode-admission.md b/changelog.d/cluster-degraded-mode-admission.md deleted file mode 100644 index 3a07971197..0000000000 --- a/changelog.d/cluster-degraded-mode-admission.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster: degraded mode only where single-Mac Darkbloom serves the model - -- When the other Mac goes away, a Mac serves the model alone only if single-Mac Darkbloom would serve that model on it (the same runtime requirements `darkbloom start --local` applies, such as an Apple M5 chip for Qwen3.8 27B) and the planner said it fits in that Mac's memory. Otherwise its status says it cannot serve the model alone and waits for the other Mac; the cluster re-forms by itself when it is back. A single-Mac server that still ends right after starting three times in a row is not started again until the cluster re-forms. -- The deployment line ("Serving … across both Macs: pipeline, M5 Ultra 40 layers / M3 Ultra 8 layers") is the same on whichever Mac leads, also when the model's first part runs on the other Mac. Models are listed by their catalog names. -- A stopped cluster's `darkbloom cluster` offers `v` (check that both Macs released their memory) on the leading Mac too, not only on a member. diff --git a/changelog.d/cluster-dev-install-model-ref.md b/changelog.d/cluster-dev-install-model-ref.md deleted file mode 100644 index 2cc1136b94..0000000000 --- a/changelog.d/cluster-dev-install-model-ref.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup finds models a dev install downloaded - -- `darkbloom-dev cluster` (and a staging install's) lists and uses the models that install downloaded. The cluster's model lookup read only production's `refs/main`, while a dev or staging install records its downloads under its own ref (`refs/darkbloom-dev`), so on a Mac with only a dev install the leader's download step failed with "downloaded, but the product's model store does not list it". It now reads the install's own ref, then production's, as single-Mac model discovery does. diff --git a/changelog.d/cluster-glm-lane-prefill-slices.md b/changelog.d/cluster-glm-lane-prefill-slices.md deleted file mode 100644 index 1efb613b86..0000000000 --- a/changelog.d/cluster-glm-lane-prefill-slices.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: a joining prompt no longer stalls decoding lanes - -- While other lanes decode on a GLM-5.3-Flash tensor-parallel pair, a joining lane's prefill runs in layer slices of about 500 ms, one slice a step, with every decoding lane's step after it, so decoding streams wait about 0.6 s instead of a whole 8K chunk (about 2.3 s). The lane with the shortest remaining prompt prefills first, and a prompt that fits one slice runs between another prompt's slices. Tokens are the same as a request served alone. diff --git a/changelog.d/cluster-glm-pair-parity.md b/changelog.d/cluster-glm-pair-parity.md deleted file mode 100644 index 9153b83e0f..0000000000 --- a/changelog.d/cluster-glm-pair-parity.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: logprobs on lanes, reasoning exclusion and MTP metrics - -- A GLM-5.3-Flash tensor-parallel pair serves `logprobs` / `top_logprobs` on batch lanes (it refused them with 503 when lanes were on), clamps `top_logprobs` to 20 as single-Mac does, accepts `reasoning: {"exclude": true}` (it answered 400), and reports MTP rounds, proposals and acceptances, its KV ledger, waiting requests and prefix-cache status on `/metrics`. diff --git a/changelog.d/cluster-glm-tp-load-setup.md b/changelog.d/cluster-glm-tp-load-setup.md deleted file mode 100644 index ea61b8cc10..0000000000 --- a/changelog.d/cluster-glm-tp-load-setup.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel setup reads metadata once, beside the link - -- A GLM-5.3-Flash tensor-parallel rank parses its model metadata once (the prepared loader's inventory) and does that work on its own thread while the link comes up, instead of serially before it; tensor-name matching runs on bytes. Setup before the load intent drops from about 5.7 s to about 3 s a rank, and `open` to about 0. Loaded weights are byte-identical and every file is still hashed. diff --git a/changelog.d/cluster-glm-tp-media.md b/changelog.d/cluster-glm-tp-media.md deleted file mode 100644 index b65a8e4cd1..0000000000 --- a/changelog.d/cluster-glm-tp-media.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM images and video on a tensor-parallel pair - -- A GLM-5.3-Flash pair serving in tensor parallel accepts image and video input as the single-Mac product does: the leader runs the product's media decode, processor and prompt expansion, rank 0 reproduces the same patches (checked by digest) off its executor and runs the vision tower when the request opens, and both ranks prefill the same spliced embeddings. Batch lanes carry media requests too, with the same arithmetic as a request served alone. Media requests decode with MTP rounds like text (the NextN history is primed with the media features) and without prefix reuse. Rank 0 now loads the vision tower (1.13 GB) with the tensor-parallel shard. diff --git a/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md b/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md deleted file mode 100644 index 6ea8da946f..0000000000 --- a/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel prefill: 8K micro-batches on long prompts - -- Long prompts on a GLM-5.3-Flash tensor-parallel pair prefill in 32K-token graphs with 8,192-row micro-batches where every micro-batch's cross-Mac sums stay hidden behind the rest of the graph; shorter prompts keep their current plan. Prompt prefixes are still kept every 4,096 tokens, and DSA top-k selection keeps each row's original candidates, so outputs are bit-identical. A 31.5K-token prompt prefills about 4 % faster on two M5 Ultra. diff --git a/changelog.d/cluster-glm-tp-prefill-levers.md b/changelog.d/cluster-glm-tp-prefill-levers.md deleted file mode 100644 index aa8c26fda4..0000000000 --- a/changelog.d/cluster-glm-tp-prefill-levers.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel prefill: faster bit-identical kernels - -- GLM-5.3-Flash prompts prefill a little faster on a tensor-parallel pair: each hyper-connection site (89 per forward on both Macs) computes the expanded residual streams inside the products that read them, about 9 % faster per site, roughly 5 ms per 4,096 prompt tokens. Outputs are bit-identical. diff --git a/changelog.d/cluster-glm-tp-ssd-prefix-tier.md b/changelog.d/cluster-glm-tp-ssd-prefix-tier.md deleted file mode 100644 index 3d7a9db4e8..0000000000 --- a/changelog.d/cluster-glm-tp-ssd-prefix-tier.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM-5.3-Flash tensor-parallel prefix SSD tier - -- A GLM-5.3-Flash pair serving in tensor parallel keeps its prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt starts with its prefix restored after both Macs restart. Each Mac writes its own state at a prompt's kept 4,096-token boundary (its heads' linear-attention state, its copy of the sparse-attention histories and the MTP history) behind serving, once the request finished, read from the memory tier's pages without copying them first. The sealed prefix vote now counts SSD records; a boundary taken from an SSD record on either Mac is restored only after a second exchange confirms both Macs have it, otherwise both prefill from zero. A restored request writes the record into its own pages. Records store the sparse-attention latents at the pair's checkpoint precision (`balanced` by default, older rows approximate after a restore; see the quantized SSD prompt-prefix records entry); with `native` records a restored request produces the same tokens and logits as a request that prefilled the whole prompt. Records are scoped by the artifact, both builds and the MTP policy, never by the session. The same `DARKBLOOM_CLUSTER_PREFIX_SSD_*` settings, budgets and daily write limit apply. The prefix agreement field becomes `glm5-next-tensor-parallel-prefix-v2`. diff --git a/changelog.d/cluster-glm-tp-width-invariant.md b/changelog.d/cluster-glm-tp-width-invariant.md deleted file mode 100644 index 6e84420020..0000000000 --- a/changelog.d/cluster-glm-tp-width-invariant.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: experimental speculative depth by load (off by default) - -- A GLM-5.3-Flash tensor-parallel pair can verify one NextN proposal a round while three or more requests decode together and two otherwise (`DARKBLOOM_GLM_TP_MTP_DEPTH_POLICY=load`, threshold `DARKBLOOM_GLM_TP_MTP_LOAD_LANES`, 2 through 8, default 3), with `DARKBLOOM_GLM_TP_WIDTH_INVARIANT=1` (implied by `load`) giving verification rows one arithmetic in more window shapes. It is off by default: on two M5 Ultra Macs it raised the aggregate of 4 and 8 concurrent requests by about 11 %, but some concurrent requests' outputs differed from the same request alone, so it stays a diagnostic until that is fixed. Both Macs' cluster services must set the same values; the default keeps today's outputs bit for bit. diff --git a/changelog.d/cluster-guided-setup.md b/changelog.d/cluster-guided-setup.md deleted file mode 100644 index 6708f5b7e2..0000000000 --- a/changelog.d/cluster-guided-setup.md +++ /dev/null @@ -1,5 +0,0 @@ -### Clearer cluster setup and recovery - -- Follow five visible setup stages, see the default model before pressing Enter, and use a shorter status menu on either Mac. -- Preserve plain text when output is redirected or color is disabled. -- Report a failed test request with a status-and-retry step instead of announcing that setup succeeded. diff --git a/changelog.d/cluster-hardware-split-prefix-everywhere.md b/changelog.d/cluster-hardware-split-prefix-everywhere.md deleted file mode 100644 index 306b24009c..0000000000 --- a/changelog.d/cluster-hardware-split-prefix-everywhere.md +++ /dev/null @@ -1,9 +0,0 @@ -### Hardware-only cluster split, prompt-prefix cache for every family, GLM cluster residency - -- The split across the Macs is chosen from each Mac's hardware and measured speed alone: free pages, cached files and what other programs hold never move it. A range fits a Mac when its whole need is within the GPU's working set, the allocator's and buffer limits, and what the Mac's memory gate can admit at rest (physical memory less the system's own wired share and the file cache macOS always keeps, 10/27 of the rest). The live answer per Mac is still shown ("Quit apps on … first") and the load gate still decides each load. -- Gemma 4 pairs keep and reuse the prompt prefix too: each sliding-window layer's window is kept at every frontier and restored exactly, so a repeated 3,521-token prompt's first token comes in 0.08 s instead of 0.98 s on an M3 Ultra + M5 Max pair, and after both Macs restart the SSD tier gives it back in 0.23 s. -- GLM-5.3-Flash pairs keep and reuse the prompt prefix (resident and encrypted SSD tiers) with the same two-rank agreement as the other families: DSA histories are kept once per prompt, KDA state per frontier. -- A GLM stage holds standing GPU residency, as MiMo's does: without it every command buffer made its tens of gigabytes of weights resident again and decode fell to 0.5 tok/s (30 tok/s on one Mac with it, same tokens). -- A GLM pair always uses the keyed, encrypted data plane, including over the paired link; a model `config.json` up to 32 MiB is accepted (GLM's NVFP4 configuration is 10 MB); a model folder whose bytes are a catalog entry's is listed by that entry's name. - -- Compact GLM convolution and recurrent cache states at transaction ownership boundaries before using the smaller retained-state reservation. Keep pending prefill histories and cast allocations charged per layer, enabling automatic 2048-token placement without choosing a hardware-specific split. diff --git a/changelog.d/cluster-installed-paths-with-spaces.md b/changelog.d/cluster-installed-paths-with-spaces.md deleted file mode 100644 index 53345c0999..0000000000 --- a/changelog.d/cluster-installed-paths-with-spaces.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster planning accepts a DevNet app's install path - -- Planning a two-Mac cluster with a DevNet build no longer fails every model with "Peer installation paths must be absolute and shell-safe". The DevNet app is installed as `Darkbloom Dev.app`; a saved cluster setup now accepts a space in the installed owner and worker executables, the model directory, and the native member's metallib and resource library. -- Shell syntax, relative paths and `..` are still refused, and the developer SSH route still checks every path it puts in a remote command. -- The orphan sweep, the teardown check and `cancel-all` now find a DevNet build's `darkbloom-dev cluster worker-owner`, and the cluster service stop finds a `darkbloom-dev cluster service`. Before, they knew only the production `darkbloom` name. diff --git a/changelog.d/cluster-lane-withdrawal.md b/changelog.d/cluster-lane-withdrawal.md deleted file mode 100644 index 63f1c1c6e2..0000000000 --- a/changelog.d/cluster-lane-withdrawal.md +++ /dev/null @@ -1,6 +0,0 @@ -### Independent cluster lane withdrawal - -Fixed cluster batch cancellation so withdrawing an admitted request that has -not started retires that request without interrupting another request waiting -for token credit. Accepting a start command closes the withdrawal window, and -duplicate cancellation messages share the pending retirement acknowledgment. diff --git a/changelog.d/cluster-local-only.md b/changelog.d/cluster-local-only.md deleted file mode 100644 index 59e702be00..0000000000 --- a/changelog.d/cluster-local-only.md +++ /dev/null @@ -1,34 +0,0 @@ -### `darkbloom cluster local`: a Mac pair serving without a coordinator - -- `darkbloom cluster local [model]` sets up and serves the pair exactly as `darkbloom cluster` does, but no Mac of the cluster contacts a coordinator: no registration, heartbeat, public traffic or billing, and serving needs no network beyond the cable. A coordinator can therefore never refuse the start. -- The API is on the leading Mac's local endpoint with the same API key as `darkbloom start --local`; it listens on every network of that Mac (LAN or tailnet) unless `--bind` names an address (`--bind 127.0.0.1` keeps it on the Mac). `darkbloom local` prints the base URL, a `network:` URL and the key. -- The choice is kept across restarts and reboots until changed: in `darkbloom cluster`, `l` serves locally only and `p` serves through Darkbloom again; a serving cluster restarts its leading part that way and the screen waits until it serves. -- A cable moved to another Thunderbolt port no longer leaves both Macs unreachable: each cluster service follows the cable to the new port within a few seconds. -- A cluster set up from the plain `darkbloom` command (the installer's link on the PATH) now starts its leading part; it used to stop with "Installed local owner is unsafe or not executable". -- `darkbloom cluster local` on the Mac that joins a pairing carries on to the model choice (it runs on the leader over the cable) instead of sending you to the other Mac. -- The model list shows one line per model (its size and how it is split, or how it gets onto the Macs); what moves and the planner's reason are said once a model is chosen, and the public-traffic line only when serving through Darkbloom. Two models with the same name show their ids. A part that keeps ending the same way is said after three tries instead of repeating, errors read as words (not `invalid("…")`), and pairing waits for the cable's address instead of failing with developer options. -- A smaller Mac takes the share of a model it can hold: the stage memory gate's 6 GiB floor and 4 GiB loading headroom (measured on 256 GiB Macs) now scale with the Mac's memory below 96 GiB (36 GB Mac: 2.25 / 1.5 GiB). A one-layer part on a 36 GB Mac was refused before. "Restart to free memory" is said only when nothing else frees enough; a choice made on the member survives a leader restart; the model list keeps the last catalog it read when the catalog does not answer. -- Hardware run on an M4 Max 36 GB + M5 Max 128 GB pair (Gemma 4 26B QAT, local only): another server on port 8000 (oMLX) no longer makes every start end after both Macs loaded: the port is checked before anything loads and the leading part takes the next free port; Gemma's thought-channel markers no longer reach `content` on the local API (the cluster's API parses reasoning by the model's type, as the coordinator path does); the leader no longer re-sends its cache settings every 15 s to a member that drove the onboarding; the ready screen's deployment line is the running setup's, not one recorded for an earlier start. -- The leading Mac downloads a catalog model the cluster serves whatever its chip: Qwen 3.8 27B's single-Mac requirement (an M5's neural accelerators) no longer stops an M4 Max leader from fetching it for the pair; single-Mac serving keeps its own check. -- Models the cluster takes from this Mac's own model store (Qwen 3.5 9B, a freshly downloaded Qwen 3.8 27B) are offered and copied again: their manifest is the catalog's exact file (the CDN lists the files in another order, which was refused), and a copy written earlier is corrected once. -- On a 36 GB Mac the prompt-prefix cache works: a memory-bound context keeps room for it (a repeated 5.5K-token prompt starts in 0.28 s instead of 7.1 s); a thinking model's reasoning streams from its first token on the cluster's API; each Mac keeps its worker's own log (`~/.darkbloom/cluster-setup/worker.log`). -- `darkbloom cluster local` answers at the same address and with the same key whichever Mac the plan makes rank 0: the other Mac passes the same port to the API over the cable, both Macs keep one API key, and `darkbloom local` shows it on either Mac. The port is 8000 when both Macs have it free, else the lowest port from 8000 to 8020 free on both, and it is kept while it stays free on both (another server on 8000 on one Mac no longer puts the API on 8000 or 8001 by which Mac is rank 0). -- A model chosen on a member is fetched there (it said "Nothing to copy: plan again."); a model's manifest is the encoding this Mac's worker accepts (GPT-OSS 20B was refused); the plan uses the other Mac's served speeds; the start screen no longer prints index estimates as seconds; the test request counts a thinking model's reasoning. -- PrismML Bonsai 2 27B serves on a pair with a 36 GB Mac: the worker's idle context check no longer recomputes the stage plan's constants for every step of its search (it outlasted the 10 s a request waits, so every request failed); a failing local request leaves a line in the log. -- A Mac whose memory moved after the plan (apps opened, cache refilled) no longer makes the pair retry the same split forever: after two load refusals for memory the leading Mac plans the model again on the memory now. -- The local API (single Mac and cluster alike) parses Gemma 4's thought channel and GPT-OSS's Harmony markers out of `content` by the model's type; think-tag models keep the raw stream there, as before, so the cluster still answers exactly as a single Mac does. -- Before a part starts, the model's own pages are dropped from the Mac's file cache (no privileges; the files are untouched): the load gate does not count active cache, and right after a download a 36 GB Mac's share was refused. -- The relay on the Mac that is not rank 0 is hardened: it listens only when the API listens on every address, bounds its connections and idle time, never closes a descriptor another thread may reuse, survives running out of descriptors, and leaves another local server's discovery file alone. -- A 36 GB Mac in everyday use keeps its share: a request on a loaded part asks only for what it needs plus headroom, and when the gate is short only because it does not count file cache the kernel could drop, the worker lets the kernel drop it first (stopped at any sign of compression, swap or pressure); "Quit apps" is no longer said for that case. -- When the cable moves to a Thunderbolt port that was never set up, `darkbloom cluster` says so and sets it up with one key (f); the service's log says what to do. -- The local API (single Mac and cluster) puts every model's reasoning in its own field, Qwen and Nemotron included, on chat completions and the Responses API; a stream whose prompt opens no think block still streams its answer at once. -- Shorter onboarding screens: models held back for the same reason share one line, two Macs running different Darkbloom builds are named as such ("install the same Darkbloom on both") instead of "Planning failed (Peer native build differs from the capability)", models the cluster cannot run say "not supported on a cluster yet", and the development-build service line says only what to do after a restart (the reason is in the service log). - -- Guided cluster setup shows five stages, names the default model choice, refreshes peer labels from the authenticated Mac, and reports completion only after the test response succeeds. Terminal color respects `NO_COLOR`; redirected output stays plain. - -- Cluster members prevent idle sleep while a deployment is serving or waiting for its peer; assertions remain held until the child and relay stop, then are released. -- A cluster service recovering a model process from its previous run keeps waiting after the cleanup deadline, keeps that process visible and protected from idle sleep, and starts no replacement model until it exits. - -- Raise cluster worker output support from 4,096 to 32,768 tokens, with 65,536 combined prompt/output tokens subject to model and live per-rank memory limits. Refuse requests over the advertised bounds rather than truncating them. - -- Keep fixed-scope model reservations at their full serving context when recent short requests tune automatic placement. GLM placement includes the native transport buffers and allocator bounds, so those requests cannot make an oversized split appear loadable. diff --git a/changelog.d/cluster-local-serving.md b/changelog.d/cluster-local-serving.md deleted file mode 100644 index 5dd2441c14..0000000000 --- a/changelog.d/cluster-local-serving.md +++ /dev/null @@ -1,5 +0,0 @@ -### A Mac pair serves locally when its coordinator has no cluster support - -- A cluster whose coordinator cannot take its cluster member role (unreachable, or a coordinator that answers the member's registration as an ordinary provider's because it predates the role) now serves on the leader's local API only, with the same local token as `darkbloom start --local`, instead of restarting every 38 s without ever serving. No public traffic reaches it and nothing is advertised to the coordinator; the Macs stay held for the cluster as before. -- The onboarding screen and `darkbloom cluster` status say so in one line: "Serving locally on this Mac's API; public serving needs a coordinator with cluster support." The next start registers normally once the coordinator supports the role. -- A coordinator that refuses this member or its pairing is still a refusal: that start fails as before. diff --git a/changelog.d/cluster-member-install-grant.md b/changelog.d/cluster-member-install-grant.md deleted file mode 100644 index 869cb8c71b..0000000000 --- a/changelog.d/cluster-member-install-grant.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster pairs register GLM-5.3-Flash and Qwen3.8 27B as cluster members - -A pair started with a coordinator approval (DevNet) now registers both Macs as cluster members for GLM-5.3-Flash and Qwen3.8 27B. Before, each Mac's member part ended about a second after it started, with "Cluster member control connection ended", and after three tries the pair served on the leader's local API only. - -The member applied the single-Mac requirements (`mlx_nax`, and `glm5_next_v1` for GLM) to its model in two places: before connecting, and when building its registration, which left the model out of `cluster_models`. A member reports hardware-only capabilities, and its pair-serving grant admits its model, so both places now follow the grant. A solo provider keeps the single-Mac requirements. diff --git a/changelog.d/cluster-member-refusal-releases-reservation.md b/changelog.d/cluster-member-refusal-releases-reservation.md deleted file mode 100644 index 6df4c98753..0000000000 --- a/changelog.d/cluster-member-refusal-releases-reservation.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster member refusals and stops release what they hold - -- A cluster member that refuses an inference request because it has no live pair slot now sends `service_reservation_released` with its 503, on the receive path, in the dispatcher and in the request handler. A request that raced a pair-slot retirement left its reservation held on the coordinator before. The handler refusal also settles the request's prefix-cache lookup receipt. The 503 answer is unchanged. -- A session that ends while the leader still forms its pair (slot publication and warmup canary) retires the published slot before the leader sends `native_pair_owner_released`. The receipt went out while the slot was still published before. diff --git a/changelog.d/cluster-member-restart-registration.md b/changelog.d/cluster-member-restart-registration.md deleted file mode 100644 index bc2e222c28..0000000000 --- a/changelog.d/cluster-member-restart-registration.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster member restarts re-register when the coordinator comes back - -- A cluster member (leader or follower) that starts while its coordinator is briefly away keeps its reconnects inside its registration wait: a retry the backoff would place after the wait is made at its end and is given its own terms, as is an attempt already under way when the wait ends, so a coordinator that returns before the wait ends is reached and its in-time acceptance is honoured. -- A wait in which the coordinator was never reached now says so ("The coordinator could not be reached …") instead of "Coordinator did not accept the control-only member role."; the role check itself is unchanged. diff --git a/changelog.d/cluster-mimo-pair-qualification.md b/changelog.d/cluster-mimo-pair-qualification.md deleted file mode 100644 index 2a1d20cf40..0000000000 --- a/changelog.d/cluster-mimo-pair-qualification.md +++ /dev/null @@ -1,5 +0,0 @@ -### MiMo V2.6 Flash on the two-Mac pair - -- MiMo V2.6 Flash can be served by an M5 Ultra and an M3 Ultra together. -- MiMo pair runs produce qualification records (the reference names its request and is compared on it), and MiMo V2.6 Flash is granted on an M5 Ultra + M3 Ultra pair by its six records (pipeline at the planner's cut, in the order the records passed; the mirrored order is refused). -- The provider's start-time weight hash reads with the file cache off (`F_NOCACHE`, same digest, earlier readers kept as fallbacks), so hashing a 172 GB model no longer fills the Mac's file cache before the memory gate decides. The memory gate is unchanged. diff --git a/changelog.d/cluster-mode-bound-grants.md b/changelog.d/cluster-mode-bound-grants.md deleted file mode 100644 index a29612cdac..0000000000 --- a/changelog.d/cluster-mode-bound-grants.md +++ /dev/null @@ -1,5 +0,0 @@ -### Pair-serving grants bound to the mode their records ran - -- A qualification record now grants only its own mode family (pipeline variants, pipeline with speculative rounds, tensor parallel, or the off-by-default hand-off modes) and only the chip classes in the roles it ran; a phase-split pass no longer opens pipeline or tensor-parallel placements. A diverged record withholds its own family; an inconclusive one neither grants nor withholds. The planner keeps to the same rule, and a start checked without its mode is refused. -- Seven pipeline qualification records on an M3 Ultra + M5 Ultra pair at the planner's sharded cut (Qwen3.5 9B and Qwen3.8 27B at cut 4 and 8 and Nemotron 3.5 Lightning at cut 8 with the M3 Ultra leading; both Qwen 35B A3B models at cut 36 and Ternary Bonsai 2 27B at cut 56 with the M5 Ultra leading; GPT-OSS 20B at cut 20, which stays withheld by its earlier diverged pipeline records) are bundled: every model the pair served only through phase-split records on these Macs now has a pipeline grant of its own. -- The onboarding offers exactly what a start serves: a model whose chosen placement any rank's grant check would refuse (GPT-OSS 20B, withheld by its diverged pipeline records although cut 20 passed) is listed as not served, with the reason, instead of being offered and then refused at start. diff --git a/changelog.d/cluster-model-approvals.md b/changelog.d/cluster-model-approvals.md deleted file mode 100644 index 8f02cae17f..0000000000 --- a/changelog.d/cluster-model-approvals.md +++ /dev/null @@ -1,6 +0,0 @@ -### A Mac pair keeps its DevNet cluster approval across provider updates - -- The coordinator can serve a model approval: a cluster approval that names the model, its prefill schedule and its serving terms, but no build. The pair takes it when its model, schedule and artifact are the saved setup's, and it computes no build facts for it. Entries pinned to one build are matched as before. -- After an update, the re-adopted setups find the same model approval at the next check, so the pair is registered with the coordinator again with no new entry from the operator. -- Under a model approval each Mac registers its plan with its own runtime (worker, capability, resource policy and profile), and a session starts only with that runtime. Each Mac hashes its worker against its saved setup and its metallib and resource library against the digests it took when it registered. -- When the pair set a model approval aside because its parts kept failing, the next update can take it again. The same build does not take it again. diff --git a/changelog.d/cluster-model-change-replans-after-stop.md b/changelog.d/cluster-model-change-replans-after-stop.md deleted file mode 100644 index 2bd4d6d938..0000000000 --- a/changelog.d/cluster-model-change-replans-after-stop.md +++ /dev/null @@ -1,4 +0,0 @@ -### Changing a serving cluster's model plans again once its memory is free - -- Changing the model of a serving two-Mac cluster (`m` in `darkbloom cluster`, or `darkbloom cluster local `) now plans again after both Macs have stopped their parts and given back their memory, and starts that plan. Before, it started the plan made while the old parts still held the memory, where tensor parallel did not fit, so a pipeline started instead. GLM-5.3-Flash on two M5 Ultras came back at less than half the speed (47.9 instead of 126.9 tokens/s in the setup's test request), serving the pipeline's 65,536-token context instead of its native 1,048,576. -- The leading Mac's own re-plan after two load refusals for memory starts the plan made once both parts stopped and gave back their memory, too. diff --git a/changelog.d/cluster-model-provisioning.md b/changelog.d/cluster-model-provisioning.md deleted file mode 100644 index 82207df882..0000000000 --- a/changelog.d/cluster-model-provisioning.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster model provisioning without manual downloads - -- `darkbloom cluster` needs no `--model-dir`: the cluster keeps its models in a store beside the product's model cache, and models single-Mac Darkbloom installed are cloned in (APFS clones, the catalog's exact manifest bytes). -- A model one Mac lacks is copied over the Thunderbolt cable on the pairing-keyed link control channel (encrypted records, 4 MiB chunks acknowledged after the receiver wrote and hashed them, resumable). The receiving Mac accepts only a manifest whose digest this build's qualification records pin, refuses hard links, unexpected files, an occupied destination and too little free disk, writes uncached, and has its own worker check the staged files before an exclusive rename into place. -- A catalog model neither Mac has is downloaded once on the leader (the product downloader, written and verified uncached through the new opt-in `ModelDownloader.uncachedWrites`), then copied. A copy predicted under 30 s at the rate measured on these Macs starts by itself (`n` within 3 s stops it). diff --git a/changelog.d/cluster-onboarding-brand.md b/changelog.d/cluster-onboarding-brand.md deleted file mode 100644 index 11ad8048c6..0000000000 --- a/changelog.d/cluster-onboarding-brand.md +++ /dev/null @@ -1,3 +0,0 @@ -### Animated Darkbloom cluster setup - -`darkbloom cluster` setup now opens with the Darkbloom mark, which blooms in on color UTF-8 terminals at least 40 columns wide. Stage headings show a step meter, and long work (cable check, reading both Macs, planning, loading, first tokens) shows a live line that the next transcript line replaces. `DARKBLOOM_NO_ANIMATION` or `CI` keeps the mark and meter but stops the motion. Narrow or non-UTF-8 terminals keep colored headings only. `NO_COLOR`, `TERM=dumb` and redirected output stay byte-for-byte plain. The model-free onboarding checks cover all four presentations (438 checks). diff --git a/changelog.d/cluster-onboarding-mac-names.md b/changelog.d/cluster-onboarding-mac-names.md deleted file mode 100644 index cb7194c746..0000000000 --- a/changelog.d/cluster-onboarding-mac-names.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster setup names "this Mac" and "the other Mac" - -- `darkbloom cluster` names the two Macs from the screen that shows them: "this Mac" and "the other Mac (Apple M5 Ultra, 256 GB)" in pairing, the machine list, each model's split ("this Mac 50% / the other Mac 50%"), the serving and API lines, status, teardown checks and copies. Two identical Macs were both "Apple M5 Ultra, 256 GB", and the API line did not say it was on the other Mac. Answers the leader gives to the other Mac are worded for that Mac's screen. -- The Mac that joins a waiting leader stops after pairing, also when started with `darkbloom cluster local`; it says to run that on the Mac that leads instead of showing a second model list. -- A model one Mac holds twice (the catalog's download beside the cluster's own copy of the same files) is listed once, and a supported model is never listed as "not supported on a cluster yet" for a copy the cluster worker does not take. diff --git a/changelog.d/cluster-onboarding-mark-on-every-run.md b/changelog.d/cluster-onboarding-mark-on-every-run.md deleted file mode 100644 index b3a07a23ba..0000000000 --- a/changelog.d/cluster-onboarding-mark-on-every-run.md +++ /dev/null @@ -1,3 +0,0 @@ -### Darkbloom mark on every `darkbloom cluster` run - -Running `darkbloom cluster` again on a Mac that is already in a cluster (the leader or a member) now opens with the same Darkbloom mark as the first setup, beside "Darkbloom cluster" and what can be done there (status, test, change model, stop). It follows the same terminal rules as the setup: color UTF-8 terminals with room for the mark draw it, `DARKBLOOM_NO_ANIMATION` or `CI` keep it still, and `NO_COLOR`, `TERM=dumb` and redirected output print the two heading lines as plain text. The onboarding checks cover the leader and the member, in color and plain. diff --git a/changelog.d/cluster-onboarding-narrow-windows.md b/changelog.d/cluster-onboarding-narrow-windows.md deleted file mode 100644 index c9fe35337d..0000000000 --- a/changelog.d/cluster-onboarding-narrow-windows.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup in narrow terminal windows - -In a colour terminal between 40 and 56 columns wide, `darkbloom cluster` setup no longer smears the Darkbloom mark: the mark and its bloom appear only when its widest row fits, and narrower windows keep the step meter and live lines. A live progress line wider than the window is now cut to one row, so the line that replaces it no longer leaves its first half in scrollback. diff --git a/changelog.d/cluster-one-command.md b/changelog.d/cluster-one-command.md deleted file mode 100644 index eb0ccad1ec..0000000000 --- a/changelog.d/cluster-one-command.md +++ /dev/null @@ -1,8 +0,0 @@ -### One command for a cluster: `darkbloom cluster` - -- Run `darkbloom cluster` on each Mac, pick a model, done. `darkbloom cluster setup` is the same command; with no terminal it says where to run it. -- Choosing the model starts it (3 s to press n); no second question. The screen then says how the model is served in one line, for example "Serving Qwen3.8-27B across both Macs: pipeline, M3 Ultra 40 layers / M5 Ultra 24 layers", and where the API is ("API at http://localhost:8000 on "). -- Models that fit in the Macs' free memory now are listed first, a model that does not fit says what frees the memory, and the fit is checked again right before the start. A model the pair may not serve with this release is listed under "Not offered" ("Not yet qualified on this pair of Macs") instead of failing after a long wait. -- Two cables: the onboarding asks which one to use. The cable check prints plain lines ("Cable found.", "Cable ready."). macOS's one Local Network prompt is announced before it appears, and a denied prompt is named with where to allow it. -- After a Darkbloom update the cluster sets itself up again by itself ("Updating the cluster setup after a Darkbloom update."). After a restart, the screen says whether the Mac comes back by itself (automatic login) or once someone logs in (FileVault). -- A start that does not finish shows each Mac's last error and offers `d` to save a redacted diagnostics file. Error messages name only `darkbloom cluster`; `plan`, `configure`, `console`, `pair` and the other developer subcommands and options are hidden from the help. diff --git a/changelog.d/cluster-paged-kv.md b/changelog.d/cluster-paged-kv.md deleted file mode 100644 index d81a3fcf6d..0000000000 --- a/changelog.d/cluster-paged-kv.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster KV in pages - -- GLM-5.3-Flash tensor-parallel ranks, GLM pipeline stages, Qwen 3.5 pipeline stages (MTP heads included), Qwen tensor-parallel shards, Gemma 4 stages (any lane count) and Nemotron 3.5 stages keep request KV in page pools instead of contiguous per-request arrays. Prefix entries share pages (refcounted, copy on write at a shared partial page) instead of copying histories, and a GLM tensor-parallel request is charged its pages (about 18.4 KB a token a rank) rather than the contiguous growth charge. Outputs are bitwise the contiguous ones. `DARKBLOOM_CLUSTER_GLM_PAGED_KV=0` keeps contiguous GLM tensor-parallel KV for diagnosis. -- GLM tensor-parallel (solo) and GLM pipeline requests start with their prompt's pages plus a 1,024-token granule and grow between steps, with no context cap; a request whose growth the memory gate refuses ends at `length` without touching others. GLM page pools compile their kernels at load and keep up to `DARKBLOOM_CLUSTER_GLM_PAGED_RETAIN_MB` (2,048 MB a rank) of slabs between requests. diff --git a/changelog.d/cluster-pipeline-speculative-records.md b/changelog.d/cluster-pipeline-speculative-records.md deleted file mode 100644 index 441957f4ce..0000000000 --- a/changelog.d/cluster-pipeline-speculative-records.md +++ /dev/null @@ -1,6 +0,0 @@ -### Speculative rounds on the pipeline, recorded and on by default - -- A qualification (recording) request now runs a pipeline's speculative rounds (`pipeline_mtp_v1`) as served, and its decoding rank records the accepted timeline: one step per selected token (its row's digest and highest candidates), so the near-tie rule reads every accepted token. Drafts never change the accepted output. -- A qualification record may carry the decode speed timed runs of its own placement and request measured, in its mode and as the plain pipeline (`darkbloom-cluster-pair-check record --timing-mode/--timing-plain`). A passing `pipeline_mtp_v1` record grants the pipeline-with-speculative-rounds family, and the planner credits the rounds with its measured speed-up until the pair has served the same placement both with and without the rounds and its own speed-up replaces it: the rounds are planned by default where lossless and measured faster. The onboarding line reads "pipeline with speculative decoding". -- Records on an M3 Ultra + M5 Ultra pair at the planner's sharded shapes: Qwen3.8 27B at cut 8 (tokens equal to both single-Mac references and to the plain pipeline; 57.7 against 35.6 tok/s), Qwen3.5 9B at cut 4 (near tie at a true tie; 130.9 against 75.1 tok/s) and MiMo V2.6 Flash at cut 47 (tokens equal at 1,024 and 4,096 prompt tokens; 59.2 against 43.1 tok/s). Output matches a single Mac's up to near ties, as the pipeline's does: the verify window's arithmetic differs in its last bits from one-token decode. -- A member's roster plan may name `pipeline_mtp_v1`; a role-aware coordinator must list it too before it accepts such a plan. diff --git a/changelog.d/cluster-planner-pricing-fixes.md b/changelog.d/cluster-planner-pricing-fixes.md deleted file mode 100644 index 6bc24ba908..0000000000 --- a/changelog.d/cluster-planner-pricing-fixes.md +++ /dev/null @@ -1,6 +0,0 @@ -### Cluster planner pricing fixes - -- GLM-5.3 Flash tensor parallel: the plan now counts the NextN (MTP) layer every Mac holds beside its share (4.2 GB), the request memory its speculative rounds add, and the decode speed-up the rounds measured, so it no longer admits a pair the load gate then refuses or predicts decode too slow. Two M5 Ultra 256 GB still plan it as tensor parallel on equal shares with eight concurrent requests, on a new pair and after the first load measured the link. -- A pipeline's prompt hop across the cable is priced by the bytes it carries (a GLM chunk is 64 MiB), from the link probe's two record sizes, instead of as one 4 MiB record. -- Requests that answer fewer than 64 tokens (the warm-up canary, the setup's test answer, readiness probes, a quick "Say hi") are no longer speed records, so they no longer choose the mode or the request a plan is made for. -- A Mac with a model loaded no longer runs the GPU speed benchmark when the other Mac checks for updates every minute or plans: it uses the speed index it last measured while idle. diff --git a/changelog.d/cluster-prefix-tenant-scope.md b/changelog.d/cluster-prefix-tenant-scope.md deleted file mode 100644 index 71c6a1fe1a..0000000000 --- a/changelog.d/cluster-prefix-tenant-scope.md +++ /dev/null @@ -1,3 +0,0 @@ -### Two-Mac cluster prompt prefixes per tenant - -Both Macs of a cluster now keep and reuse prompt prefixes, in memory and in their encrypted SSD tiers, only for the request's own tenant, as one Mac does: the leader gives both ranks each request's cache switch and a SHA-256 digest of its cache scope (never the scope itself), every prefix key and SSD record scope carries that digest, and a request whose prefix cache is off (a remote request without a cache scope, or a GLM or Qwen request with images or video) reuses and keeps nothing on either Mac. Before, every request on the pair shared one prefix cache. Requests from the local endpoint carry no partition and keep the earlier behavior and bytes. Both ranks bind the partition into the request fingerprint they compare, so ranks given different partitions fail the request. `darkbloom-cluster-pair-check request --request-prefix-cache off|tenant:SALT` writes a qualification request with a partition. diff --git a/changelog.d/cluster-qmv-batch-invariant.md b/changelog.d/cluster-qmv-batch-invariant.md deleted file mode 100644 index ebd2c65b38..0000000000 --- a/changelog.d/cluster-qmv-batch-invariant.md +++ /dev/null @@ -1,3 +0,0 @@ -### A request's tokens do not depend on what it is batched with on the new MLX core - -- Cluster workers, the single-Mac reference and the tensor-parallel check now set `MLX_QMV_BATCH_INVARIANT=1` before MLX starts, unless their launcher set it. The cluster's MLX core then keeps quantized products of a few rows (speculative verify windows, rows of several requests in one launch) on its per-vector kernels, as before it took MLX main's new kernels for 6 to 16 NVFP4 rows and 8 or more affine rows, whose results change with the row count. A request served beside others keeps the bytes it gets alone. Each process logs `darkbloom-qmv-batch-invariant-v1` with the value and who set it. Single-Mac serving is unchanged. diff --git a/changelog.d/cluster-qwen-m5-ultra-window-layout.md b/changelog.d/cluster-qwen-m5-ultra-window-layout.md deleted file mode 100644 index 9ded5678e0..0000000000 --- a/changelog.d/cluster-qwen-m5-ultra-window-layout.md +++ /dev/null @@ -1,3 +0,0 @@ -### Faster Qwen tensor-parallel decode on two M5 Ultra - -- Qwen3.8 27B tensor parallel on two M5 Ultra decodes about 6% faster for one request (75.8 to 80.5 tok/s at 256 tokens, 62.7 to 66.8 at 1,024). The exact decode projections take a layout measured on the M5 Ultra for a verify window's vectors (rows in registers). Outputs are unchanged byte for byte, and other chips keep their layouts. diff --git a/changelog.d/cluster-qwen-moe-packed-collective.md b/changelog.d/cluster-qwen-moe-packed-collective.md deleted file mode 100644 index 041037b5c3..0000000000 --- a/changelog.d/cluster-qwen-moe-packed-collective.md +++ /dev/null @@ -1,10 +0,0 @@ -### Pack Qwen MoE tensor-parallel expert and shared reductions - -Qwen routed-expert tensor parallelism now carries the shared expert's float32 -partial in the routed experts' collective: two collectives per layer instead of -three, with every summed and rounded value unchanged. The load agreement -(`qwen-moe-down-projections-f32-sum-before-weighting-packed-v3`) and the -tensor-parallel check's launch version refuse mixed builds. Placement now -charges the top-K expert rows once per layer instead of the largest payload on -every collective, and the request ledger charges the packed payload's source -partials. Full-model hardware qualification on the pair is still required. diff --git a/changelog.d/cluster-qwen-tensor-lanes-every-row.md b/changelog.d/cluster-qwen-tensor-lanes-every-row.md deleted file mode 100644 index 94f0b0cd9a..0000000000 --- a/changelog.d/cluster-qwen-tensor-lanes-every-row.md +++ /dev/null @@ -1,10 +0,0 @@ -### Request-owned tensor-parallel lanes for every Qwen row - -- Every Qwen tensor-parallel row (Qwen3.5 9B, Qwen3.8 27B, Qwen3.5 and Qwen3.6 35B A3B) now serves through the request-owned batch path the 27B used: main's paged KV host, independent lanes at capacities 1 to 8, the resident and SSD prompt-prefix tiers, committed-token logprobs, and automatic widening that keeps the running shares. Each row's LOAD reservation, placement quote and widening quote are priced by its own geometry (its per-rank KV heads and recurrent state, and a routed-expert row's packed MoE partials). Capacity one is the same path one lane wide. A row that can also run the pipeline keeps the pipeline as a planning candidate while tensor parallel is priced by its quote. -- A routed-expert cohort runs each row's router, shared expert and selected experts with that row's own arithmetic and sends every row's packed expert and shared partials in one collective, so a wider cohort still issues two collectives a layer and every row's tokens equal its solo bytes (`moe-rows-one-collective-v1` in the load agreement). -- The Qwen3.5 9B's inline head now runs as the tensor-parallel speculative assistant beside the 27B's (the assistant inventory and quote follow each row's configuration). The A3B rows' heads are routed-expert layers the tensor assistant does not load, so they serve without speculation. -- Each rank's cut of a row-parallel projection, expert bank or expert input column is copied once into a row-major buffer at LOAD. The interior-axis gather left a transposed view, which every quantized matmul and expert gather copied whole at each call: a routed-expert decode step copied the rank's gate/up and down expert banks for every layer, and every row copied each dense row-parallel weight. Values are unchanged. -- A tensor-parallel decode step is submitted to the GPU layer by layer while it is built (`Qwen35LayerSubmission`), and decode steps, assistant rounds and their selection encode into command buffers of up to 100 operations instead of the worker's 16, as GLM's TP decode does. Tokens are unchanged. -- Batched decode rows take each row-parallel projection's cached FP32 scales and biases, the ones its single-row forward reuses (`QuantizedLinear.independentRowsForward`), instead of widening the BF16 constants inside every quantized matmul, where MLX made that widening on the thread's default GPU stream rather than the caller's. A widened step no longer spans two GPU streams there, and two kernels a projection a step go away. Values are unchanged. -- The single-lane tensor-parallel owner is retired with its own page pool, its prefix cache and `DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV`; Qwen tensor parallel now requires the authenticated sealed data plane, and each lane reserves its full context at LOAD instead of growing by granules. -- Full-artifact qualification on the pair is still required. diff --git a/changelog.d/cluster-qwen-tensor-prefix-ssd.md b/changelog.d/cluster-qwen-tensor-prefix-ssd.md deleted file mode 100644 index 7ea897783f..0000000000 --- a/changelog.d/cluster-qwen-tensor-prefix-ssd.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel prefix SSD tier - -Keep the Qwen27 TP batch owner's prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt restores its prefix after both Macs restart. Each rank writes its own shard (and the assistant's trusted history) behind serving after bilateral clean retirement. The sealed vote now counts SSD records, and a second exchange confirms that both ranks restored, or both prefill from zero. Records are scoped by plan, shares, artifact, storage, both builds and assistant policy, never by membership epoch. The prefix agreement field becomes `qwen-tensor-parallel-prefix-v2`. diff --git a/changelog.d/cluster-qwen-tensor-rank-ledger.md b/changelog.d/cluster-qwen-tensor-rank-ledger.md deleted file mode 100644 index 2f563b5195..0000000000 --- a/changelog.d/cluster-qwen-tensor-rank-ledger.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel ranks reserve only their own heads - -Each tensor-parallel rank now reserves the request state it actually holds: its own KV heads, linear-attention heads, and its own rows and columns of the fused projections and projection constants under the chosen split. The replicated assistant, hidden-width buffers and gathered logits stay whole on both ranks. Setup quotes both ranks of every supported split. Placement charges each Mac its own figure. It keeps a split for later widening only when, on each Mac, the serving owner's weights and request plus the widened load fit, because widening is previewed before the old owner is released. On a busy second Mac, onboarding can therefore pick a split that widens to two speculating requests instead of one that never can. The whole-model figure remains the bound either rank stays under. diff --git a/changelog.d/cluster-qwen-tensor-speculation.md b/changelog.d/cluster-qwen-tensor-speculation.md deleted file mode 100644 index 606c05b54b..0000000000 --- a/changelog.d/cluster-qwen-tensor-speculation.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel resident assistant - -Discover and fully quote the catalog Qwen27 embedded assistant during normal cluster setup, retaining the native inventory policy through bilateral launch and READY. Eligible concurrent requests keep independent histories and accepted-token credits while sharing captured target verification; ordinary media, logprob and history-filter paths retain their capabilities. Price surviving cohort backing, the next verification window and assistant prefix ownership through checked retirement. Explicit MTP off retains the fully quoted ordinary target. Full-artifact correctness and release qualification remain separate from component fixtures. Bound the assistant's trusted-history flush to evaluated 512-row blocks (first draft and ordinary decode), and price a verify window by what it writes: partial-page replacements and segment slack, not a second history. At the 64K profile the whole-model bound for one speculating request fell from about 66 GiB to 22 GiB, and for two from 96 GiB to 36 GiB; installed qualification is separate. The saved setup's status binding carries the speculation the session derives, so a pair serving the resident assistant reads as ready instead of stale and automatic setup finishes; capacity-one refusals keep their capacity or deadline reason. The resident owner's memory gate measures compression and swap-out from the start of each served scope instead of the owner's whole life (limits unchanged), so ordinary background compression on a busy Mac no longer refuses later requests. Concurrent speculative requests verify each request's draft window with that request's own single-window arithmetic inside one collective per row-parallel projection, so they emit exactly the tokens they emit alone. One batched product changed kernel at four three-column windows and altered near-tie tokens. diff --git a/changelog.d/cluster-qwen-tp-exact-vectors.md b/changelog.d/cluster-qwen-tp-exact-vectors.md deleted file mode 100644 index f3d7f771a8..0000000000 --- a/changelog.d/cluster-qwen-tp-exact-vectors.md +++ /dev/null @@ -1,19 +0,0 @@ -### Qwen tensor-parallel decode with batch-invariant projections - -Every Qwen tensor-parallel plain decode step, verify window and batched row -(the 9B, the 27B and the dense projections of both 35B A3B rows) now projects -through the SDK's batch-invariant affine kernel. Each position of a speculative -verify window therefore has the bits of the plain decode step that computes the -same token, and each concurrent row the bits it has alone, at any cohort width. -This changes the rounding of every decode projection relative to MLX's own -kernels, so recorded tensor-parallel references must be regenerated once. - -A row-parallel projection reads its bf16 activation directly and writes its -FP32 partial (no separate widening launch and no FP32 copy of its scales), and -its rounded all-sum feeds the fused residual step, so a step runs far fewer GPU -launches. Each rank logs the arithmetic it resolved once per load -(`darkbloom-aqv-kernel-v1`: exact vectors, the kernel's arithmetic and words -per lane on that GPU family, its layouts), and the pair binds whether exact -vectors are on into its load agreement, so two ranks that resolved it -differently refuse to load. `DARKBLOOM_QWEN_TP_EXACT_VECTORS=0` (diagnostic -only, never forwarded to an installed rank) keeps MLX's kernels. diff --git a/changelog.d/cluster-qwen-tp-fenced-sums.md b/changelog.d/cluster-qwen-tp-fenced-sums.md deleted file mode 100644 index 5ee109ff4b..0000000000 --- a/changelog.d/cluster-qwen-tp-fenced-sums.md +++ /dev/null @@ -1,13 +0,0 @@ -### Qwen tensor-parallel ranks wait for each all-sum in the kernel that reads it - -The Qwen 3.5 residual step (`ResidualRMSNorm`) now reads its FP32 tensor-parallel -all-sum as a fenced input, as GLM's hyper-connection sites already did, and a -worker turns `MLX_METAL_FENCED_INPUTS` on for every tensor-parallel family whose -kernels read their sums that way (`ClusterResidentModelCatalog.Family -.tensorParallelSumsAreFencedInputs`; a launcher's own value is kept). The kernel -that reads a sum then waits for the CPU itself instead of MLX's separate -fence-wait launch, about 128 of them per verify window of the 27B. MLX consults -the setting only for inputs a kernel declares fenced, so every other launch is -unchanged, and only where the GPU waits changes, never a value. The fused fence -update stays a launcher's choice. Each rank logs the choice (`fenced_sums=` in -`darkbloom-aqv-kernel-v1`) and binds it into the load agreement. diff --git a/changelog.d/cluster-qwen-tp-pipelined-draft.md b/changelog.d/cluster-qwen-tp-pipelined-draft.md deleted file mode 100644 index 0835796e1b..0000000000 --- a/changelog.d/cluster-qwen-tp-pipelined-draft.md +++ /dev/null @@ -1,12 +0,0 @@ -### Qwen tensor-parallel speculative rounds keep the GPU busy - -A single-request speculative round no longer waits for each assistant draft -step before building the next one, and no longer waits for the drafts before -building the verify window: the draft chain and the window are submitted back -to back, and the window itself is submitted layer by layer as a decode step -already was. The drafted tokens' vocabulary check is evaluated with the window -and read when the window is confirmed. Every rank still runs the same -collectives in the same order, the emitted tokens are unchanged, and a failure -on either rank fails the round on both. Batched rounds keep their draft -schedule. `DARKBLOOM_QWEN_TP_MTP_PIPELINED_DRAFT=0` (diagnostic only) waits for -each draft step. diff --git a/changelog.d/cluster-qwen-tp-window-submission-switch.md b/changelog.d/cluster-qwen-tp-window-submission-switch.md deleted file mode 100644 index 400a0037ae..0000000000 --- a/changelog.d/cluster-qwen-tp-window-submission-switch.md +++ /dev/null @@ -1,9 +0,0 @@ -### Faster Qwen tensor-parallel verification: windows evaluated whole - -Qwen tensor-parallel speculative verify windows are evaluated whole instead of -being submitted to the GPU one decoder layer at a time. On two M5 Ultra Macs -serving Qwen3.8 27B this makes a single request about 18 % faster (60 against -51 tokens per second) and four concurrent requests about 5 % faster, with -identical outputs. `DARKBLOOM_QWEN_TP_WINDOW_LAYER_SUBMISSION=1` (diagnostic, -never forwarded to an installed rank) submits windows by layer again; both -ranks bind the choice into their load agreement. diff --git a/changelog.d/cluster-qwen27-native-context.md b/changelog.d/cluster-qwen27-native-context.md deleted file mode 100644 index 3a66dcc032..0000000000 --- a/changelog.d/cluster-qwen27-native-context.md +++ /dev/null @@ -1,5 +0,0 @@ -### Qwen3.8 27B at its native context on a tensor-parallel pair - -- A Qwen3.8 27B pair serving in tensor parallel accepts the context a single Mac serves: prompts up to 262,143 tokens and up to 32,768 output tokens within 262,144 (previously 32,768 + 32,768 within 65,536). LOAD and the planner still size the pair for the 32,768 + 32,768 request at every width (one to eight lanes), so no lane reserves KV for the whole context in advance. Each longer request is charged at its own context when a rank reserves it, and each rank's live memory gate admits it or refuses it alone (HTTP 503 with the context the pair serves now) while other requests keep running. Readiness and keep-warm answers carry that serving context. The 27B's pipeline modes and every other Qwen row keep their limits. -- Qwen tensor-parallel paged lanes reserve their prompt and a 1,024-token granule when they open and grow between steps, instead of reserving every page of the prompt and output at once. Outputs are unchanged byte for byte. -- The 27B's worker profile, load agreement and installed setup fingerprints change. Existing 27B setups re-plan after the update, and 27B pair qualification records are recorded again. diff --git a/changelog.d/cluster-rdma-system-settings.md b/changelog.d/cluster-rdma-system-settings.md deleted file mode 100644 index efe4fe0268..0000000000 --- a/changelog.d/cluster-rdma-system-settings.md +++ /dev/null @@ -1,3 +0,0 @@ -### RDMA setup guidance for macOS 27 - -When RDMA over Thunderbolt is turned off, `darkbloom cluster` and its setup screens now point a Mac on macOS 27 or later to Apple's switch in System Settings (Privacy & Security, RDMA over Thunderbolt, then restart) instead of macOS Recovery. Macs on macOS 26 keep the Recovery steps with `rdma_ctl enable`. Darkbloom still never changes the setting itself. diff --git a/changelog.d/cluster-release-runtime-facts.md b/changelog.d/cluster-release-runtime-facts.md deleted file mode 100644 index f61e8f7068..0000000000 --- a/changelog.d/cluster-release-runtime-facts.md +++ /dev/null @@ -1,7 +0,0 @@ -### Releases carry their cluster runtime facts - -- Every release lane (dev branch, staging, prod) now computes the cluster runtime facts of its final signed app with that app's own CLI and worker: the digests of the cluster worker, placement tool, Metal library and paged-attention source, and for each model the build qualifies on a cluster and the environment's catalog has, the digests of its capability and its pair-serving grant. The job summary and a run artifact show them in every release. -- Each model's pair-serving grant lets a coordinator form its two-Mac pairs: a pair member reports only hardware capabilities, so without a grant no pair of GLM-5.3-Flash or Qwen3.8-27B forms. A declared public model's grant names its declared mode families; any other model's is the grant of the build's own qualification records, or none. -- GLM-5.3-Flash and Qwen3.8-27B are declared for public cluster traffic in pipeline and tensor parallel (owner decisions, 2026-10-31): their entries carry parity qualifications from which a coordinator derives their public qualifications, and it applies them to each declared mode family on any Apple silicon pair, with sampling and tools, and in tensor parallel images and video as the environment's catalog lists them. The qualifications name the evidence placement (two Apple M5 Ultras; a pipeline cut at half the model's layers), not a limit; no pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record, so both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash runs the serial prefill schedule only, so its schedule 2 entries are inert. Every other model's clusters serve their owner only. The setup says a declared model is qualified for public traffic in pipeline and tensor parallel. -- The release registration carries the facts as `cluster_runtime` only when that environment's repository variable (`DEV_CLUSTER_RUNTIME_ENABLED`, `STAGING_CLUSTER_RUNTIME_ENABLED`, `PROD_CLUSTER_RUNTIME_ENABLED`) is `true`; a coordinator that accepts the block then approves the build's two-Mac clusters automatically. Unset, the registration is unchanged and a failure to compute the facts only warns. -- `darkbloom cluster runtime-facts` (hidden) prints schema `darkbloom_cluster_runtime_v2`: the same digests as before plus each model's `pair_serving_grant` and `parity_qualifications`. diff --git a/changelog.d/cluster-served-speed-build-scope.md b/changelog.d/cluster-served-speed-build-scope.md deleted file mode 100644 index eaa8d9c7b3..0000000000 --- a/changelog.d/cluster-served-speed-build-scope.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster served speeds count only for the build that served them - -- A two-Mac pair's planner and request router now use a served request's speed only for the worker build that served it. Each speed record in `~/.darkbloom/cluster/served-speed.json` names every rank's worker build; records from another build, including every record written before this release, give no speed and age out of the file, so a new build plans from the share probes and link measurements until it has served. Speeds served by older, slower builds no longer hold a tensor-parallel split where the current build's own probes balance it. The plan is still made for the prompt and answer lengths the pair's clients send. -- The plan says how many records it left out (`N record(s) from other worker builds ignored`). `darkbloom-cluster-plan plan --served` and `route --served` use records only for the build named with `--served-build SHA256`. diff --git a/changelog.d/cluster-service-after-reboot.md b/changelog.d/cluster-service-after-reboot.md deleted file mode 100644 index 2918761099..0000000000 --- a/changelog.d/cluster-service-after-reboot.md +++ /dev/null @@ -1,5 +0,0 @@ -### The cluster comes back after a reboot - -- After a restart each Mac serves again once it is logged in (by itself with automatic login on); `darkbloom cluster` says which applies to each Mac. -- `darkbloom cluster` (leader and members) installs this Mac's cluster service as a per-user LaunchAgent (`io.darkbloom.cluster-service.`): launchd starts it at login and runs it under the cluster supervisor (`darkbloom cluster service --supervise`), which restarts it after 15 s doubling to 300 s and parks it after three quick failures; launchd restarts only a supervisor that crashed. Running `darkbloom cluster` again keeps an unchanged agent, replaces a changed one, restarts a parked one, and takes over from a service an earlier version started in a terminal. Nothing is asked beyond the cluster link's one approval. -- `darkbloom cluster stop` stops this Mac's cluster service and removes its login agent (on the leader the cluster stops serving first); unpairing the last pairing (`darkbloom cluster pair --forget`) removes it too. `darkbloom status` shows whether the cluster service starts at login, whether it runs, and its supervisor's phase. diff --git a/changelog.d/cluster-service-network-identity.md b/changelog.d/cluster-service-network-identity.md deleted file mode 100644 index 6170edb0d2..0000000000 --- a/changelog.d/cluster-service-network-identity.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster background network identity - -- Associate the cluster login service with its enclosing app so macOS can retain Local Network approval when the setup terminal exits. -- Replace older unassociated jobs through the normal cluster command; preserve idempotent startup and stop behavior. -- Keep socket failure details in lease diagnostics and explain the session lifetime of an ad-hoc development service. diff --git a/changelog.d/cluster-service-part-heartbeat.md b/changelog.d/cluster-service-part-heartbeat.md deleted file mode 100644 index 031989696d..0000000000 --- a/changelog.d/cluster-service-part-heartbeat.md +++ /dev/null @@ -1,3 +0,0 @@ -### The cluster service is no longer restarted while its pair is registered - -A pair registered with the coordinator could restart the cluster service of a Mac many times a day (about every 15 minutes on one DevNet leader: "heartbeat missing for 75 s while its process is alive"), and each restart dropped the pair for a short time. The Mac's part inherited the service's heartbeat file and wrote its own heartbeats into it, and the supervisor does not count a heartbeat from another process. The part now writes its heartbeats to a file of its own (`~/.darkbloom/cluster-setup/part-health.json`). diff --git a/changelog.d/cluster-session-rank-lease-keep-warm.md b/changelog.d/cluster-session-rank-lease-keep-warm.md deleted file mode 100644 index 37780be89e..0000000000 --- a/changelog.d/cluster-session-rank-lease-keep-warm.md +++ /dev/null @@ -1,10 +0,0 @@ -### Cluster sessions without a fixed lifetime; rank lease and keep-warm - -- A model served by two Macs stays loaded and serving until you stop it, and a Mac that disappears is reported at once instead of stalling. -- A two-Mac cluster session has no fixed lifetime and no request count any more. The 300-second session (1,800 for MiMo), the sixteen-request cap, the installed session's teardown at its deadline, the rotation to a new session after sixteen requests and the member session's 900-second cap are removed; a loaded model stays resident and serving until it is stopped (`darkbloom stop`, an operator unload, an autopilot model switch) or a real failure is detected. The capability record drops `maxLifetimeSeconds` and `maxRequests`. -- Each worker holds a renewable rank lease instead (S03): armed before its weights load at most one grant away, renewed every 5 s for 30 s by its owner with an `extendDeadline` line on the worker's control pipe, which the worker reads from launch, through the load. An owner that stops renewing (it stopped, died or lost its link) leaves the worker to end by itself within the time to live, through the forced exit that releases MLX's wired memory first. The leader renews each remote owner's lease the same way (`renew` frames), and each owner renews its own worker's. -- A cluster member honors the coordinator's grant lease (S15): `native_pair_lease` frames move its deadline (a grant may leave at most 120 s plus 5 s of clock allowance); an established session survives a dropped control connection for the 90-second grace, and the member claims it again with `resume` in its registration. -- Keep-warm, on by default (S27): a GPU pulse on each worker's own executor every half second while idle once the first request has run (back-off for a minute after a slow submission), and a 1x16 data-plane exchange both ranks run about once a second while idle, sequenced by the leader; a failed exchange ends the session cleanly. `darkbloom-cluster-pair-check --keep-warm off` and the worker's `--keep-warm off` turn it off for comparison. -- `darkbloom-cluster-pair-check` takes any number of repetitions, idle gaps between them (`--idle-seconds`) and a qualification switch that stops renewing both leases (`--stop-renewals-after-seconds`). -- A Mac that vanishes from a cluster is a stated failure, not a stall: when the other member's link control connection closes or goes silent and does not come back within the link's own re-dial time (5 s for a closed connection, 10 s for a silent one with the default link timing, never past the 30 s rank lease), the leader fails the request in flight at once with the reason (`link edge: follower lost: ...`), stops waiting for cleanup proofs that can no longer arrive (the session is quarantined, rank 1 stays unproven, the other Mac's own lease and device journal still end its rank), and exits instead of lingering for minutes; the follower likewise fences a vanished leader's session at once instead of at the end of its lease. A follower that releases a session without a cleanup proof (its owner ended at launch) ends the leader's wait the same way. The follower now says why its rank ended (its worker's last word, e.g. the stage-load memory gate's refusal) and the leader's incident carries it, so such a start is classified `memory_gate_refused` with the follower's own numbers instead of an unexplained `peer_lost`. A cluster member whose coordinator control connection ends or loses trust says why (`Distributed serving stops: .`) and exits with a failure status. The stale bootstrap-directory check no longer connects to a listener's socket (a connect could fail a live launch); it reads the descriptor tables instead. -- Nothing of a dead cluster session is left behind (orphan eradication, ported from the owner's oMLX and ThunderMLX lifecycle work). An orphan sweep runs at every member's start and end and before every supervised restart, and on demand as `darkbloom cluster reap [--json] [--no-wait]`: a worker or owner whose parent process is gone is given its own contract (the rank lease, the owner's longest signal allowance and the forced exit's dead-man) to end, then SIGTERM, and SIGKILL only after the kill margin, and only while its process number still holds the same process (same start time; a reused number is never signalled); a device journal whose owner died is cleared through `cluster recover`'s proof; bootstrap directories whose socket no process holds any more are removed. `darkbloom cluster verify-teardown [--json] [--baseline-wired-bytes N] [--samples N]` reports, after a stop, whether any cluster process, wired memory above the baseline (tolerance: the larger of 1 GiB and 1/128 of physical memory), stranded journal or bootstrap directory is left (`darkbloom_cluster_teardown_verification_v1`, exit 1 when not clean). `darkbloom cluster cancel-all` force-cancels every request served on this Mac on its own: SIGUSR1 makes an owner fence its worker (the protocol's own drain) and a worker end its requests through the forced exit. A forced exit whose release keeps completing durable writes (`ProcessForcedExit.noteProgress`) gets its 20 s dead-man extended exactly once, to 40 s, and never otherwise. Every rank is started with MLX's command-buffer bounds (`MLX_MAX_OPS_PER_BUFFER=16`, `MLX_MAX_MB_PER_BUFFER=512`) unless the operator pinned them. diff --git a/changelog.d/cluster-setup-reasoning-probe.md b/changelog.d/cluster-setup-reasoning-probe.md deleted file mode 100644 index e245dee258..0000000000 --- a/changelog.d/cluster-setup-reasoning-probe.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup respects model reasoning defaults - -- Cluster setup tests a response using each model's default reasoning controls, so GLM-5.3 Flash no longer rejects the generic probe because it sends a binary thinking override. Reasoning-only output remains visible when the test token budget expires. diff --git a/changelog.d/cluster-sharded-deployments.md b/changelog.d/cluster-sharded-deployments.md deleted file mode 100644 index f95092b978..0000000000 --- a/changelog.d/cluster-sharded-deployments.md +++ /dev/null @@ -1,6 +0,0 @@ -### Cluster pairs serve sharded deployments by default - -- The planner chooses tensor parallel or a pipeline for the Macs it detects; phase split, phase split with MTP, the pipeline-prefill/tensor-decode hybrid and the per-request "alone" route are kept but off by default, reachable only behind `DARKBLOOM_CLUSTER_HANDOFF_MODES=1`, and a setup saved with one of them is refused at start without it. The onboarding's deployment line names the sharded mode. -- Qwen models with an MTP head and MiMo V2.6 Flash can decode as speculative rounds across the pipeline (`pipeline_mtp_v1`): the last Mac holds the head and a copy of the token embedding, drafts, and both Macs verify the drafts in one window. The planner credits the rounds only from what the same placement served with and without them, and a pair serves them only where its own qualification records pass. -- MiMo V2.6 Flash keeps prompt prefixes on both Macs, in memory and in the encrypted SSD tier, restored on both or neither. -- The pair's SSD prompt-cache tier carries its daily write cap across restarts, keeps other plans' records within one byte budget instead of wiping them, stores speculative history once per record, reads records page-aligned without a copy, and hashes model files in parallel. diff --git a/changelog.d/cluster-ssd-prefix-quantized-records.md b/changelog.d/cluster-ssd-prefix-quantized-records.md deleted file mode 100644 index 380fe69bfe..0000000000 --- a/changelog.d/cluster-ssd-prefix-quantized-records.md +++ /dev/null @@ -1,6 +0,0 @@ -### Quantized SSD prompt-prefix records on the two-Mac cluster - -- The pair's encrypted SSD prompt-prefix records now store attention rows at the single-Mac checkpoint precision, `balanced` by default, like every other model's checkpoints: older rows in 4-bit keys and values (affine groups of 64, FP32 scale and offset, keys Hadamard-rotated) and each record's newest 128 rows exact. Recurrent, convolution and speculative-head state stays exact. A Qwen 3.8 27B tensor-parallel rank's attention rows at 32,768 tokens take about 3.2 times fewer bytes; GLM-5.3-Flash DSA layers about 1.8 times fewer, in pipeline and tensor parallel (BF16 latents; its index keys, pool gates and MTP history stay exact). Live KV stays native. -- A prefix restored from a quantized record is close to, not identical with, computing it again. `engine_v2_kv_checkpoint_quantization = "native"` (or `DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION=native`, per model with `engine_v2_kv_checkpoint_quantization_by_model`) keeps the pair's records byte-exact. Both Macs must resolve the same precision: the leader does not sync it, and the ranks bind it into their load agreement and refuse to load otherwise. Records of one precision are never restored under another. -- Quantizing a decoded row again does not give it back (the codec is not idempotent on its own output), so a record written from a request that was itself restored from a record keeps the restored rows' first encoding instead of quantizing them again: through repeated restore-and-extend cycles, such as a long conversation, each restored row stays as it was first stored. -- `darkbloom-cluster-tp-check run --prefix-records native|balanced|k8v4|k8v8` measures a record on real weights: per-layer errors, bytes against a native record, the prompt tail scored from the captured and the restored state, and the output after the restore. `darkbloom-cluster-pair-check --prefix-ssd-quantization` selects the workers' record precision. diff --git a/changelog.d/cluster-stage-kv-quantization.md b/changelog.d/cluster-stage-kv-quantization.md deleted file mode 100644 index 0dbf1978c8..0000000000 --- a/changelog.d/cluster-stage-kv-quantization.md +++ /dev/null @@ -1,17 +0,0 @@ -### Two-Mac clusters follow the provider's KV quantization - -- A pair's stage KV now uses the same live precision a single Mac uses for the - model: `engine_v2_kv_quantization` (global or per model) and - `DARKBLOOM_CBV2_KV_QUANTIZATION`, resolved on each Mac and passed to its - worker. The default stays native; pairs whose Macs keep it are unchanged. -- With `balanced`, `k8v4` or `k8v8`, the Qwen 3.5 family (Bonsai included), - Gemma 4 and Nemotron 3.5 stages and every Qwen tensor-parallel row's - request-owned lanes (9B, 27B, Qwen3.5/3.6 35B A3B, any capacity) store packed KV on the provider's own pool, after the same kernel check, - and their memory planning counts packed rows. Both Macs must resolve the same - precision; otherwise their load agreements differ and the pair refuses to - load. Set the pair's model to `native` per model to keep a packed global - setting off the pair. -- Packed stages keep no prompt prefixes, as on one Mac for packed KV. Phase - split, GPT-OSS and GLM refuse a packed precision; MiMo stays native. The pair's SSD prefix records stay exact native states. -- `DARKBLOOM_CLUSTER_KV_BACKEND=contiguous` is removed: cluster stage KV is - paged only. diff --git a/changelog.d/cluster-steady-visible-tensor-parallel.md b/changelog.d/cluster-steady-visible-tensor-parallel.md deleted file mode 100644 index 175f6f5a82..0000000000 --- a/changelog.d/cluster-steady-visible-tensor-parallel.md +++ /dev/null @@ -1,13 +0,0 @@ -### Steadier, visible tensor-parallel choice in two-Mac clusters - -- Keep each pair's last eight link measurements from the last 30 days and plan - on their median, so one fast or slow load no longer switches a model between - tensor parallel and a pipeline. Link files from earlier releases still read. -- End a model's line in the setup's model list with a short reason when the - model supports tensor parallel but is split otherwise, such as "tensor - parallel: slower here"; models without tensor parallel show nothing extra. -- Explain that Qwen3.8 27B leaves out the pipeline because only tensor parallel - keeps images, video and logprobs, instead of saying no pipeline fits. -- Read the saved link measurements in `darkbloom-cluster-plan plan` when - `--link` is not given (or `--link-probes FILE`), say so, and print reduction - costs in ms or µs. diff --git a/changelog.d/cluster-stop-leader-drain.md b/changelog.d/cluster-stop-leader-drain.md deleted file mode 100644 index 23c1be8823..0000000000 --- a/changelog.d/cluster-stop-leader-drain.md +++ /dev/null @@ -1,7 +0,0 @@ -### Cluster stop ordering - -- A paired leader now retires its owned part before asking its follower to stop, preserving the native shutdown channel. Failed retirement or missing peer acknowledgement keeps the login service available for recovery and returns an error. - -Require a fresh local supervision acknowledgement before stopping the peer so stale idle status cannot bypass a child start already in flight. - -Keep follower lease intent alive through local planned drain; serialize background serve/stop reconciliation and wait for outstanding running leases before publishing stop acknowledgement. A stop the pair could not finish exits with status 1 and the pair's reason, without usage text. diff --git a/changelog.d/cluster-stop-local-only.md b/changelog.d/cluster-stop-local-only.md deleted file mode 100644 index ed2b565fa1..0000000000 --- a/changelog.d/cluster-stop-local-only.md +++ /dev/null @@ -1,3 +0,0 @@ -### Stop a cluster Mac whose peer is gone - -`darkbloom cluster stop --local-only` stops only this Mac's cluster service and removes its login agent. It never asks the other Mac, for when that Mac is gone for good. Without the flag, a leader still drains the pair first and keeps its service when the member cannot acknowledge. The output says that the other Mac was not asked to stop. diff --git a/changelog.d/cluster-tensor-parallel-first.md b/changelog.d/cluster-tensor-parallel-first.md deleted file mode 100644 index 9a8e3f13c1..0000000000 --- a/changelog.d/cluster-tensor-parallel-first.md +++ /dev/null @@ -1,6 +0,0 @@ -### Two-Mac clusters place tensor parallel first wherever it fits - -- A model whose tensor-parallel layout fits both Macs is now set up in tensor parallel even where the speed estimate favored a pipeline; the setup says so ("the model fits, so both Macs share every layer of every token") instead of claiming a gain it does not predict. A setup that loads now still goes ahead of tensor parallel that would not, and predictions are still shown. -- A new pair's first setup is tensor parallel too: before any load has measured the cable, it plans on the same assumed sealed reduction a forced plan uses, labelled as assumed. -- Automatic widening never assumes a link cost: it plans only on the pair's own recent sealed link measurement, and without one it keeps the running setup. -- `darkbloom-cluster-plan plan --tensor-parallel-first` plans the same way; without the flag the plan tool keeps the speed comparison. diff --git a/changelog.d/cluster-tensor-parallel-roster-plans.md b/changelog.d/cluster-tensor-parallel-roster-plans.md deleted file mode 100644 index 9e6ac732e4..0000000000 --- a/changelog.d/cluster-tensor-parallel-roster-plans.md +++ /dev/null @@ -1,5 +0,0 @@ -### A tensor-parallel cluster registers with the coordinator - -- A pair that serves a model in tensor parallel (GLM-5.3-Flash, Qwen3.8-27B) now registers its roster plan with the coordinator. The plan names `tensor_parallel_v1` and no layer cut, as the coordinator requires; before, the member registered the stage end as a cut, refused its own plan, and the pair served only its local API. A setup with unequal tensor-parallel shares is refused at registration until the plan carries its shares. -- The onboarding's start line for a cluster that serves through Darkbloom no longer says public serving is off in this build: it serves its owner's requests, and public requests where Darkbloom has qualified the model and split. -- A plan in `pipeline_prefill_tensor_decode_v1` (pipeline prefill, tensor-parallel decode) also registers: the coordinator lists the mode, and the member no longer refuses its own plan. diff --git a/changelog.d/cluster-tensor-share-probes.md b/changelog.d/cluster-tensor-share-probes.md deleted file mode 100644 index e0b39d92f9..0000000000 --- a/changelog.d/cluster-tensor-share-probes.md +++ /dev/null @@ -1,15 +0,0 @@ -### Tensor-parallel shares balanced by each Mac's measured speed - -- Time each Mac's own share of a dense Qwen model when it loads in tensor - parallel (at most about a second and a half, alone, nothing crossing the - cable), and keep each Mac's newest timing per share and model for 30 days on - the leading Mac. The next plan balances the shares by those timings: with the - timings an M3 Ultra and an M5 Max measured, Qwen3.8 27B is planned 1:1 - instead of 2:1 after one load. A Mac short of memory skips the timing, and it - never fails a load. -- Stop predicting a larger tensor-parallel share faster than a smaller one: a - Mac's measured shares are no longer drawn toward its whole-model speed, and - what the pair served corrects all of a Mac's measured shares alike. -- Read the saved share timings in `darkbloom-cluster-plan plan` (or - `--share-probes FILE`) and name the shares used, as the setup plans. -- A load that serves the speculative head balances its shares on each Mac's measured verify window rather than its single-token step, because its rounds run windows: on the Qwen3.8 27B pair that moves the split from 3:2 to about even. diff --git a/changelog.d/cluster-tp-feasibility.md b/changelog.d/cluster-tp-feasibility.md deleted file mode 100644 index 86d6d2d1e4..0000000000 --- a/changelog.d/cluster-tp-feasibility.md +++ /dev/null @@ -1,7 +0,0 @@ -### Fixed - -- Automatic cluster planning considers tensor-parallel placements independently - of pipeline layer cuts and counts enumerated candidates instead of unused - pipeline-cut combinations against its search limit. Unsupported runtime modes and rank counts now explain the pipeline - fallback before requesting a link measurement, without claiming an unmeasured - speedup. This does not enable tensor parallelism for GLM. diff --git a/changelog.d/cluster-validation-and-tensor-batching.md b/changelog.d/cluster-validation-and-tensor-batching.md deleted file mode 100644 index df1c35ace2..0000000000 --- a/changelog.d/cluster-validation-and-tensor-batching.md +++ /dev/null @@ -1,47 +0,0 @@ -### Cluster validation, tensor batching and media ownership - -- Repair local two-Mac setup, installed lane propagation, encrypted peer agreement, - request-scoped placement and delayed automatic batch replacement without - weakening native teardown, memory or failed-qualification gates. -- Preserve measured shard rates and independently price native batch capacity; - exact Qwen3.8 27B retains feature-preserving TP selection with the complete - native request reservation coexisting with LOAD scratch and allocator demand. -- Preview Qwen27 widths 8, 4 and 2 against current bilateral memory before - replacing the serving owner, then recheck the exact proposed width after release. -- Pass the indexed devices, recorded keyed pair-link costs and filtered served - history into automatic replacement, allowing its tensor candidates to be - considered instead of silently using an unmeasured link. -- Add Qwen27 independent TP histories, grouped collectives, per-request sampling - and captured logprobs, with checked bilateral cancellation and retirement. -- Coalesce nearby Qwen27 TP token acknowledgments within the existing bounded - scheduling window so ready rows can decode together; joining, prefill, - cancellation and retirement continue without waiting for a silent client. -- Reuse mutually held original-grid Qwen27 TP prefixes with bounded resident - snapshots, fresh per-request histories, separately priced capture/cache banks - and publication only after bilateral clean retirement. -- Route exact Qwen27 images and video through bounded provider preparation and - the native vision owner, retaining encoded data and host/native allowances - until their respective completion fences. Unsupported controls refuse explicitly. -- Bind streamed logprobs to committed content events and repair local HTTP - reasoning, sampling, usage and tool/constraint parity handling. -- Repair Qwen expert reductions and mixed-router accounting; add Bonsai packed-row - arithmetic and qualification coverage; preserve Gemma prompt arithmetic, - catalog aliases and prefix restore/chunk semantics. -- Repair GPT-OSS, MiMo and Nemotron native independent-history batching, paging, - cancellation and prefix behavior, including existing MiMo speculative/phase - state accounting. Historical phase support is not TP release qualification. -- Order fast Metal fence waits after current-pass GPU producers through the - matching native core pin; installed clustered-concurrency validation remains required. -- Retain explicit full-model hardware gates. Component tests and source support - do not establish universal TP, media parity or release readiness; Qwen27 TP - text speculation remains unfinished; full-artifact prefix/media qualification - and final automatic-planner validation remain separate gates. - -- Preserve an explicit local fast-synchronization diagnostic choice through both installed TP owner and native worker launches. Only canonical `0` or `1` is forwarded; normal defaults and placement remain unchanged. - -Every tensor-parallel worker, widened Qwen rows included, keeps fast synchronization; explicit local synchronization choices still take precedence. Native batching and model capabilities remain enabled. - -Authenticated Qwen3.8 27B TP owners now use the same fully priced request-owned execution at one lane and wider capacities. Automatic capacity changes preserve the tensor split, preventing capacity changes from switching the attention path or repartitioning arithmetic. The original exact-output acceptance gate remains required. - -- Forward an explicit local eager-fence-commit diagnostic through the installed tensor owner and native worker, reporting its canonical value at startup while preserving the default. -- Report completed decode steps by actual batch width once per retired or failed scope, without request content or extra memory samples. diff --git a/changelog.d/cluster-worker-protocol-2.md b/changelog.d/cluster-worker-protocol-2.md deleted file mode 100644 index 909797a2af..0000000000 --- a/changelog.d/cluster-worker-protocol-2.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster worker protocol 2: prompts cross as packed token IDs - -- A cluster reservation carries its prompt as packed little-endian token IDs (base64) with an explicit count instead of a JSON number array, and the leader builds a relayed command's link wire once. A 31.5K-token reservation decodes in about 1 ms per hop instead of about 12 ms, which shortens time to first token on long prompts. Both Macs must run the same release: a Mac on the previous protocol is refused at setup or pairing ("Install the same Darkbloom release on both Macs, then run `darkbloom cluster` again"), never in the middle of a request. diff --git a/changelog.d/collected-reasoning-truncation.md b/changelog.d/collected-reasoning-truncation.md deleted file mode 100644 index 8dd3382c77..0000000000 --- a/changelog.d/collected-reasoning-truncation.md +++ /dev/null @@ -1,3 +0,0 @@ -### Preserve truncated reasoning in collected responses - -- Keep unfinished prompt-side thinking in reasoning fields for collected Chat and Responses, retrieval and continued history. Preserve explicit parser overrides, native parsed channels and token usage. diff --git a/changelog.d/distributed-start-signal-restoration.md b/changelog.d/distributed-start-signal-restoration.md deleted file mode 100644 index c57f1cfb13..0000000000 --- a/changelog.d/distributed-start-signal-restoration.md +++ /dev/null @@ -1,5 +0,0 @@ -### Distributed startup signal restoration - -Distributed startup restores both SIGTERM and SIGINT dispositions, including -handler flags and blocked signals, even when one signal was already ignored. -A termination request received before serving starts remains latched. diff --git a/changelog.d/glm-automatic-finite-placement.md b/changelog.d/glm-automatic-finite-placement.md deleted file mode 100644 index 98f8bc77d9..0000000000 --- a/changelog.d/glm-automatic-finite-placement.md +++ /dev/null @@ -1,7 +0,0 @@ -### GLM cluster prefill and finite-calibration placement - -- Scan all structural cuts against current local device bounds and choose a common feasible cut through the existing performance-aware planner. -- Run the selected cut through the installed signed quotation and finite owner path; preserve explicit diagnostic cuts. -- Keep predicted speed, measured-best throughput and calibrated serving eligibility distinct. Public GLM endpoint eligibility is unchanged. -- Raise the registered GLM NVFP4 cluster candidate's prefill chunk cap to 2048 while retaining bounded authenticated logical arrays, raw frames and records. Keep the workspace conservative pending scope-matched native/host peak qualification; other models' default caps and public qualification records remain unchanged. -- Allow finite calibration up to 2048 prompt/chunk tokens with the existing 16-output cap and at most 2064 context. Automatic chunk hints ignore prompts shorter than their configured chunk and match artifact identity when available; fallback uses the current model/worker caps without creating a qualification grant. diff --git a/changelog.d/glm-cluster-still-images.md b/changelog.d/glm-cluster-still-images.md deleted file mode 100644 index 499cee9629..0000000000 --- a/changelog.d/glm-cluster-still-images.md +++ /dev/null @@ -1,5 +0,0 @@ -### Bounded GLM cluster still-image candidate - -- Add bounded encoded PNG ingress, rank-0 native GLM vision loading and causal feature splicing to the private two-rank pipeline, with additive memory charges and cold media prefix isolation. -- Require the explicit local image qualification profile through `darkbloom cluster local glm-5.3-flash --private-glm-image-qualification`; ordinary text serving rejects images before reservation and excludes the vision tower from planning and LOAD. -- Keep video unqualified and audio refused. Full-model image correctness, memory, cancellation and real CLI/HTTP qualification remain required before a serving modality can be advertised. diff --git a/changelog.d/glm-single-mac-speed-shared.md b/changelog.d/glm-single-mac-speed-shared.md deleted file mode 100644 index 80729b4b13..0000000000 --- a/changelog.d/glm-single-mac-speed-shared.md +++ /dev/null @@ -1,7 +0,0 @@ -### GLM-5.3-Flash SDK speedups shared with the single-Mac release - -- The SDK's pipelined KDA prefill recurrence now also covers 64 heads on an 80-core M5 Ultra (two - value-row ranges per GPU core): one Mac and each GLM pipeline stage prefill faster with bit-identical - outputs; a tensor-parallel rank's 32 heads keep their cut, so tensor-parallel GLM is unchanged. -- The CBv2 MTP loop can submit every draft step as soon as it is built (on for the single-Mac GLM - profile); the two-Mac GLM path runs its own speculation loop and is unchanged. diff --git a/changelog.d/glm-tensor-parallel-decode-command-buffers.md b/changelog.d/glm-tensor-parallel-decode-command-buffers.md deleted file mode 100644 index 4271676539..0000000000 --- a/changelog.d/glm-tensor-parallel-decode-command-buffers.md +++ /dev/null @@ -1,4 +0,0 @@ -### GLM tensor-parallel decode command buffers and sum fences - -- GLM tensor-parallel decode steps, MTP rounds and lane rounds encode up to 100 operations a Metal command buffer instead of the rank guard's 16, which prefill keeps; each further buffer cost about 10 µs of GPU time (13.24 to 12.56 ms a decode step on two M5 Ultra, tokens identical). -- GLM tensor-parallel workers let the hyper-connection site wait for each all-sum in-kernel (`MLX_METAL_FENCED_INPUTS`; a launcher value is kept). The fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: its multi-threadgroup path (partials above 32 KB) never signals the CPU, which stalled batched lanes about 0.7 s a round. diff --git a/changelog.d/glm-tensor-parallel-mtp-early-proposals.md b/changelog.d/glm-tensor-parallel-mtp-early-proposals.md deleted file mode 100644 index 08aed4b3db..0000000000 --- a/changelog.d/glm-tensor-parallel-mtp-early-proposals.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel MTP rounds submit their proposals early - -- A GLM tensor-parallel MTP round (solo or batched lanes) submits its NextN priming and proposals as soon as they are built, so the GPU computes them while the host builds the verification forward instead of idling through the whole round's build: a depth-2 round 23.06 to 21.64 ms (95.9 to 102.7 tok/s) and two lanes 115.2 to 121.6 tok/s on two M5 Ultra, tokens and top logits identical. `darkbloom-cluster-tp-check glm --mtp-early none|proposals|layers` compares the modes. diff --git a/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md b/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md deleted file mode 100644 index c335241dba..0000000000 --- a/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel greedy MTP rounds split the head's vocabulary - -- A greedy GLM tensor-parallel MTP round (solo or batched lanes) reads out only its half of the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum (each rank's half maximum and argmax; rank 0's lower index wins a tie, as MLX's argmax does): a depth-2 round 21.32 to 21.05 ms on two M5 Ultra, tokens and top logits identical. Sampled rounds keep the whole head. `darkbloom-cluster-tp-check glm --mtp-vocab-split yes|no` compares them. diff --git a/changelog.d/glm-tensor-parallel.md b/changelog.d/glm-tensor-parallel.md deleted file mode 100644 index 5f2eb5fe06..0000000000 --- a/changelog.d/glm-tensor-parallel.md +++ /dev/null @@ -1,13 +0,0 @@ -### GLM-5.3-Flash runs tensor parallel across two Macs - -- `darkbloom cluster` can now serve GLM-5.3-Flash text requests with both Macs working on every layer (tensor parallel) instead of each Mac holding half the layers. On two M5 Ultra 256 GB it chooses this by itself once the cable has been measured: the setup's test answered at 51 tokens/s against 42 for the layer split, and long prompts prefill at about 3,300 tokens/s against 1,450 (one Mac alone: about 1,800), and decode runs at 53 tokens/s. Every byte between the Macs stays encrypted. A repeated prompt prefix (a chat's history) is reused on both Macs instead of prefilled again. Image requests still use the layer split. -- The cable measurement that decides between the two modes now times the encrypted sum as a running model pays it, not cold: it had read three times slower and kept tensor parallel from being chosen. -- The Macs exchange GLM's per-layer sums at half the size: the model's own 16-bit values instead of the same values widened to 32 bits, with an identical result. Prompts prefill about 14% faster. -- Tensor-parallel decode is faster: the worker lets each GPU command buffer take whole expert banks instead of committing one at every expert layer (about 88 commits a token instead of 22), and MLX spends less host time per kernel launch. On two M5 Ultra, decode went from 53 to about 57 tokens/s through the API (62 in the bench). -- Fixed a hang where the GPU could wait forever on an encrypted sum between two GPU steps. -- What a tensor-parallel setup served no longer resets the speeds the planner learned from a pipeline the same Macs served: it corrects only the tensor-parallel figures. Before, after serving in tensor parallel the planner priced the layer split as fast as one Mac alone and switched back to it. This applies to every model the cluster plans. -- The hardware speed prior no longer counts every routed expert of a mixture-of-experts model as read on each decode step. It counts only the experts a token is routed to, and it does not count replicated weights as divided by a tensor-parallel share. -- Greedy GLM-5.3-Flash requests in tensor parallel now decode speculatively with the model's own next-token-prediction layer, which each Mac now also loads (about 4.2 GB more per Mac): each step checks the layer's guess together with the next token and keeps both when the guess is right, so greedy decode produces more tokens per step (two guesses a step: about 76 tokens/s against 63 in the bench on two M5 Ultra). Sampled requests decode as before. -- Tensor-parallel prefill is faster: each encrypted sum between the Macs is now sealed, sent, opened and added in 256 KiB pieces as they become ready instead of as one block, so the encryption overlaps the transfer (a 15.7K-token prompt prefilled at 3,812 tokens/s against 3,554 in the bench). Every piece is still authenticated, and a piece that does not open fails the request. -- Tensor-parallel decode no longer waits between steps for the serving process's answer to each token (whether to go on). The token is handed over at once and the answer is read once the next step is running, so its round trip overlaps the GPU work (two M5 Ultra through the API: about 73.5 to 77 tokens/s). A stop request still ends the output exactly where it was asked for; one extra step may be computed and is never sent. -- GLM-5.3-Flash decodes and prefills faster on Apple silicon, on one Mac and across two: fewer and faster GPU launches for the hyper-connection, mixture-of-experts and sparse-attention steps, and less CPU time per launch. Outputs are unchanged bit for bit. On two M5 Ultra through the API, decode went from about 78 to 90 tokens/s and long-prompt prefill from about 3,470 to 3,540 tokens/s. diff --git a/changelog.d/glm53-native-prerequisites.md b/changelog.d/glm53-native-prerequisites.md deleted file mode 100644 index 23b01b2874..0000000000 --- a/changelog.d/glm53-native-prerequisites.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM-5.3-Flash native prerequisites - -- Use one peer-status observation for each finite GLM terminal-context decision, avoiding a false transport-loss rejection across an expected peer close while preserving exact acknowledgment consumption, frozen connection identity and durable owner/fence retirement. Encrypted loopback CPU coverage does not qualify model, GPU, RDMA or serving behavior. diff --git a/changelog.d/local-responses-previous-response-id.md b/changelog.d/local-responses-previous-response-id.md deleted file mode 100644 index 3454d2ce8a..0000000000 --- a/changelog.d/local-responses-previous-response-id.md +++ /dev/null @@ -1,4 +0,0 @@ -### The local Responses API continues a conversation from `previous_response_id` - -- `/v1/responses` on a single Mac and on a cluster now honours `previous_response_id`: the request continues the earlier input and that response's output, as with OpenAI. A follow-up that sends only a `function_call_output` item resolves its tool call instead of failing with 400, and a later turn remembers earlier ones. -- An ID this process does not hold (never served, sent with `"store": false`, dropped from the bounded in-memory store, or from before a restart) returns 400 with code `previous_response_not_found`. diff --git a/changelog.d/media-processor-refusals-400.md b/changelog.d/media-processor-refusals-400.md deleted file mode 100644 index 6fa2b41053..0000000000 --- a/changelog.d/media-processor-refusals-400.md +++ /dev/null @@ -1,3 +0,0 @@ -### Media the model's processor refuses answers 400 on one Mac and on a pair - -- An image or video the model's processor refuses now returns HTTP 400 `Invalid media input.` (`invalid_media`) on one Mac and on a two-Mac pair: for Qwen 3.5 and 3.8 a side below 32 pixels (a 16×16 PNG, for one; the processor does not upscale it) or an aspect ratio above 200:1, a video without a decodable track, or more media than a processor takes. It returned the retryable 503 capacity answer, so the coordinator tried other providers that refuse it the same way. diff --git a/changelog.d/mlx-fast-fence-gpu-queue-starvation.md b/changelog.d/mlx-fast-fence-gpu-queue-starvation.md deleted file mode 100644 index 6acb490979..0000000000 --- a/changelog.d/mlx-fast-fence-gpu-queue-starvation.md +++ /dev/null @@ -1,16 +0,0 @@ -### One GPU stream per decode graph, and no GPU-on-GPU fence spins - -With MLX fast fences (`MLX_METAL_FAST_SYNCH=1`) a widened Qwen 3.8 27B -tensor-parallel owner could stop at its first multi-row plain decode (the c14, -c17 and c39 stalls). MLX cast each batched 4-bit projection's bfloat16 scales -and biases to float32 on the thread's default GPU stream instead of the stream -the caller passed, and mlx-swift runs everything else on its own process-wide -stream, so that decode graph ran on two GPU streams. A fast GPU fence wait is a -kernel that spins on its queue until the other queue's timestamp arrives, and -Metal does not promise that the other queue runs meanwhile, so both queues -stopped. The casts (and MLX's other helper ops that dropped the caller's -stream) now stay on the caller's stream, and a GPU stream never spins on -another GPU stream: it waits on a shared event, while the CPU <-> GPU -collective waits keep the spinning fast path. Synchronization only: tokens are -unchanged. Widened Qwen 3.8 27B owners stay on the event path until a two-Mac -acceptance with fast fences passes on this fix. diff --git a/changelog.d/pair-check-reservation-fields.md b/changelog.d/pair-check-reservation-fields.md deleted file mode 100644 index e84ba46281..0000000000 --- a/changelog.d/pair-check-reservation-fields.md +++ /dev/null @@ -1,3 +0,0 @@ -### Pair-check reservations keep their media - -- `darkbloom-cluster-pair-check` hands each worker the whole reservation when it moves the deadline to that worker's clock. It dropped still images and Qwen image/video input, so those qualification requests reached the workers without their media. The owner and peer-link hops re-time reservations with the same field-preserving copy. diff --git a/changelog.d/qwen-prefill-steel-tiles.md b/changelog.d/qwen-prefill-steel-tiles.md deleted file mode 100644 index bfe0771e00..0000000000 --- a/changelog.d/qwen-prefill-steel-tiles.md +++ /dev/null @@ -1,17 +0,0 @@ -### Faster prompts on Macs without neural accelerators - -- MLX's steel affine quantized matmul computes prompt-sized products (256 rows - or more, 64-aligned outputs) in 64-row x 32-column tiles for 16-bit inputs and - 32 x 64 for FP32 partials instead of 32 x 32 on GPUs without neural - accelerators (M1-M4, and the M3 Ultra rank of a pair). On the M3 Ultra alone a - 4,096-token prompt took 2.5% less time (27B 12.37 -> 12.06 s, 9B 3.55 -> 3.46 s) - with the same tokens. `MLX_QMM_STEEL_TILE=32` restores the previous tile. -- Qwen tensor-parallel prompt frames are submitted to the GPU every four layers - while they are built (`DARKBLOOM_QWEN_TP_PREFILL_STRIDE=0` restores whole-frame - evaluation). With both changes the 27B pair at 1:1 reached its first token - 1.4-3.1% sooner (4K 8.22 -> 8.08 s, 16K 36.7 -> 35.5 s, 32K 81.8 -> 80.0 s) and - the 9B pair 1.1-2.3% sooner (4K 2.63 -> 2.60 s, 32K 27.5 -> 26.9 s), with the - same tokens. -- Diagnostics: `darkbloom-cluster-tp-check qwen-prefill` (one rank's prompt - frames, layers and projections), `DARKBLOOM_QWEN_TP_PREFILL_FRAME_TIMING=1` - and `pair-check --worker-environment`. diff --git a/changelog.d/qwen-tp-batched-cohort-drafts.md b/changelog.d/qwen-tp-batched-cohort-drafts.md deleted file mode 100644 index b4f1ffbff4..0000000000 --- a/changelog.d/qwen-tp-batched-cohort-drafts.md +++ /dev/null @@ -1,3 +0,0 @@ -### Concurrent tensor-parallel requests draft together - -- When several speculative requests on a two-Mac tensor-parallel pair draft in the same round, their assistant steps now run as one batch: one head call and one pair of sealed exchanges per draft step for every row, instead of one per row. Six concurrent requests need about a third of the reductions they needed before, and every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen-tp-cohort-synchronization.md b/changelog.d/qwen-tp-cohort-synchronization.md deleted file mode 100644 index 718e459b0b..0000000000 --- a/changelog.d/qwen-tp-cohort-synchronization.md +++ /dev/null @@ -1,3 +0,0 @@ -### Concurrent tensor-parallel requests verify together - -- Concurrent speculative requests on a two-Mac tensor-parallel pair now stay in one verify cohort. A request that still has up to one round of accepted tokens waiting joins the next round from its own settled position instead of waiting for its queue to drain, so requests that started a step apart no longer take turns verifying alone. Every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen-tp-exact-batched-drafts.md b/changelog.d/qwen-tp-exact-batched-drafts.md deleted file mode 100644 index db5790ab94..0000000000 --- a/changelog.d/qwen-tp-exact-batched-drafts.md +++ /dev/null @@ -1,5 +0,0 @@ -### Concurrent tensor-parallel requests share each draft step's weight reads - -- On a two-Mac tensor-parallel pair, speculative drafts now use the same batch-invariant kernel as decoding. When several requests draft in the same round, every draft step after the first runs all of them through one assistant pass, and every head call serves all of them, so each weight is read once per step for the whole batch instead of once per request. With eight concurrent Qwen3.8 27B requests, a round's draft work on one Mac fell from about 38 to 24 ms. -- A request proposes the same tokens alone and in a batch of any size, and every request still produces exactly the tokens the model produces without speculation. Proposals can differ from the previous kernels at near-ties, so the share of accepted proposals can shift slightly; the output never does. -- Both Macs must use the same draft kernel or the pair refuses to load. `DARKBLOOM_QWEN_TP_MTP_EXACT_DRAFTS=0` (diagnostic only, never forwarded to an installed rank) keeps the previous kernels. Single-Mac speculative decoding is unchanged. diff --git a/changelog.d/qwen-tp-six-lane-batches.md b/changelog.d/qwen-tp-six-lane-batches.md deleted file mode 100644 index ebf886a234..0000000000 --- a/changelog.d/qwen-tp-six-lane-batches.md +++ /dev/null @@ -1,3 +0,0 @@ -### Six-request tensor-parallel batches - -- Automatic batching on a two-Mac tensor-parallel pair can now choose six concurrent requests, between four and eight, when eight do not fit. Pipeline batching keeps its widths of two, four and eight. diff --git a/changelog.d/qwen-tp-vector-tiles-measured.md b/changelog.d/qwen-tp-vector-tiles-measured.md deleted file mode 100644 index 5c94abcf3d..0000000000 --- a/changelog.d/qwen-tp-vector-tiles-measured.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen tensor-parallel verification keeps its measured weight-read tiles - -- Two-Mac tensor-parallel Qwen pairs verify concurrent requests with tiles of at most five vectors per weight read again (tiles of four past five), instead of whole-cohort tiles of eight or sixteen. On two M5 Ultra Macs serving Qwen3.8 27B, four concurrent requests reach about 90 tokens per second together instead of 73, with identical outputs. diff --git a/changelog.d/qwen-tp-widened-fast-fences.md b/changelog.d/qwen-tp-widened-fast-fences.md deleted file mode 100644 index 024b0eb0cd..0000000000 --- a/changelog.d/qwen-tp-widened-fast-fences.md +++ /dev/null @@ -1,3 +0,0 @@ -### Widened Qwen tensor-parallel owners keep fast fences - -Qwen tensor-parallel owners with more than one lane (Qwen3.8 27B, and the Qwen3.5 9B and both 35B A3B rows) keep MLX's fast fence waits instead of the slower event path. The stall that once stopped a widened pair right after a request finished is fixed at its cause: MLX kept a batched step on one GPU stream, and batched rows no longer convert their scales each step. diff --git a/changelog.d/qwen-tp-wider-automatic-batching.md b/changelog.d/qwen-tp-wider-automatic-batching.md deleted file mode 100644 index 300a8f1b49..0000000000 --- a/changelog.d/qwen-tp-wider-automatic-batching.md +++ /dev/null @@ -1,6 +0,0 @@ -### Wider automatic batching on two-Mac pairs - -- A two-Mac tensor-parallel owner now reserves much less memory per request, so automatic batching can widen past two concurrent requests when the Macs have room. A request no longer reserves its own full-history attention gather (decode and verification read pages in place, and one shared gather serves the single prompt frame a step runs). After a speculative round, a request keeps only its own recurrent rows instead of the whole round's. A long prompt's draft history moves into the assistant's cache as the prompt is read instead of waiting whole for the first draft. For Qwen3.8 27B with 32K-token prompts and 32K-token outputs, two, four and eight requests reserve 16.1, 25.7 and 45.5 GiB per Mac at an equal split, down from 21.4, 40.5 and 86.0 GiB. Qwen3.5 9B and the 35B A3B rows shrink the same way. -- Before replacing a running owner with a wider one, the preview now counts that owner's loaded weights on each Mac as free, because they are released before the wider owner loads. It does so only for a replacement that keeps the same split. The owner's unused request reservation is never counted, and the memory check after release is unchanged. A width that fails that check is not credited again for 10 minutes. -- Every width that automatic batching refuses is logged as one line, `cluster.batch_replan refused lanes=N`. It gives the phase (preview or after release), the reason, and each Mac's need, admissible memory, shortfall, weights and fit, in bytes. -- Every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen27-feature-preserving-modes.md b/changelog.d/qwen27-feature-preserving-modes.md deleted file mode 100644 index cb48e56b54..0000000000 --- a/changelog.d/qwen27-feature-preserving-modes.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 feature-preserving cluster modes - -Keep images, video and committed-token logprobs in the registered Qwen3.8 27B cluster route by admitting tensor parallel before unchanged speed ranking. Replan old pipeline setups instead of silently serving fewer features, retain native link/shape/memory gates, and require matching actual media READY and logprob support before creating the bridge. Other model and GLM mode policies remain unchanged. diff --git a/changelog.d/qwen27-media-response-format.md b/changelog.d/qwen27-media-response-format.md deleted file mode 100644 index e62632ca6d..0000000000 --- a/changelog.d/qwen27-media-response-format.md +++ /dev/null @@ -1,8 +0,0 @@ -### Qwen27 media response formats - -- Accept image/video `response_format` requests through the cluster's existing - Qwen27 media path, using the same JSON prompt preparation and nonstream - JSON/schema post-validation as standalone serving. -- Preserve forced-media-tool refusals and default processor policy. Streaming - remains prompt-guided; this does not add token-level grammar enforcement or - establish full-model media/schema accuracy. diff --git a/changelog.d/qwen27-tp-greedy-exchange.md b/changelog.d/qwen27-tp-greedy-exchange.md deleted file mode 100644 index 5528876c68..0000000000 --- a/changelog.d/qwen27-tp-greedy-exchange.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel greedy choices without full-vocabulary gathers - -Qwen27 tensor-parallel speculative decoding no longer moves complete vocabulary rows between the Macs for greedy work. Each draft step and each greedy verification column reduces a rank's vocabulary shard to its maximum and first index (plus a non-finite count when verifying), and one small exchange gives both Macs the same choice: the complete row's first maximum, with the lower index winning ties. Greedy verification also drops its separate choice broadcast. Sampled requests and logprobs still gather complete rows. diff --git a/changelog.d/qwen27-tp-media-preparation-refusal.md b/changelog.d/qwen27-tp-media-preparation-refusal.md deleted file mode 100644 index 3a677aacf0..0000000000 --- a/changelog.d/qwen27-tp-media-preparation-refusal.md +++ /dev/null @@ -1,12 +0,0 @@ -### Qwen 3.8 27B pair media: preparation on its own stream, refused alone - -- A Qwen 3.8 27B tensor-parallel pair no longer ends both workers when rank 0's - media preparation fails. Rank 0 prepares a request's image or video patches at - admission, on a CPU stream of its own while its executor waits, so another - thread's failed CPU work can no longer fail the preparation (after the main - merge, MLX overlaps evaluations across threads and hands a stream's stored - error to whichever caller synchronizes it next; the pair's media requests - failed this way after a dozen had passed). A preparation that does not - reproduce the leader's patches refuses that request alone with a retryable - error and its reason in the worker log, and the pair keeps serving. A vision - tower failure still ends the workers. diff --git a/changelog.d/qwen27-tp-mtp-depth3.md b/changelog.d/qwen27-tp-mtp-depth3.md deleted file mode 100644 index ec2c9e8443..0000000000 --- a/changelog.d/qwen27-tp-mtp-depth3.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel speculative depth 3 - -Automatic Qwen27 tensor-parallel setup now drafts three tokens a round instead of two. On the installed pair the assistant's first and second drafts were accepted 87% and 84% of the time, so a third proposal adds about 0.6 tokens a round for one more draft step; the verify window stays bound by one weight pass. Every emitted token is still the target's own choice. diff --git a/changelog.d/qwen27-tp-shared-verify-windows.md b/changelog.d/qwen27-tp-shared-verify-windows.md deleted file mode 100644 index 6cb72d2b1d..0000000000 --- a/changelog.d/qwen27-tp-shared-verify-windows.md +++ /dev/null @@ -1,3 +0,0 @@ -### Faster concurrent Qwen27 tensor-parallel verification - -Concurrent Qwen27 tensor-parallel requests now share each quantized projection's call when verifying their speculative windows, as long as the combined rows stay below MLX's vector-kernel limit for the device. Every request keeps the arithmetic it has alone. Draft proposals no longer need their own broadcast: both Macs read them from the same small exchange. A new `darkbloom-tp-mtp-profile-v1` worker line splits each round's time into draft, build, verify, gather, choose and settle. diff --git a/changelog.d/qwen27-tp-wide-verify-kernel.md b/changelog.d/qwen27-tp-wide-verify-kernel.md deleted file mode 100644 index cd1095bc62..0000000000 --- a/changelog.d/qwen27-tp-wide-verify-kernel.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fewer weight reads for concurrent Qwen27 verification - -Concurrent Qwen27 tensor-parallel speculative windows now go through an exact four-bit projection kernel where it is faster than MLX's own calls: it reads each projection's weights once for up to eight verify rows (two four-column windows), where MLX's vector kernel reads them once for every five. On the M5 Max it keeps one output row per thread (up to 20% faster); on the M3 Ultra the row-parallel FP32 partials use two rows per thread (1.5-2.1x faster) and other projections keep MLX's calls. Each row keeps MLX's own `qmv_wide` reduction, so every request still gets byte-identical results to running alone; other GPU families keep MLX's calls. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index d351ca1964..c91f96c2e6 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-26 +> Last updated: 2026-10-31 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -556,6 +556,22 @@ Unknown or saturated policy evidence and a fixed pool that cannot meet the floor fail closed. `resliceMeetsServiceabilityFloor` rejects the unattainable `Int.max` sentinel rather than accepting it as a usable grant. +Every re-slice passes those floors to `resliceGrants`; a newcomer, whose engine +does not exist yet, has only the base `minimumServiceableGrantBytes`. When the +proportional split already gives each slot at least its floor, that split is the +result. Otherwise, if the floors sum to no more than the budget, each slot +receives its floor plus its weighted share of the rest; if they do not, the +proportional split stands and `resliceMeetsServiceabilityFloor` refuses the load +or reserve raise. Regrowth after an unload or rollback uses the same floors, so +it never shrinks a slot below its floor. Without this, a slot with a small KV +rate and a fixed per-request workspace, such as `nvidia-nemotron-3.5-lightning` +with its embedded assistant, falls below its floor beside high-rate models even +when every floor fits (`EngineV2KVSizing.resliceGrants`, +`ProviderLoop.resliceAndBuildEngineV2Bundle`, `ProviderLoop.resliceGrowSurvivorsLocked`). +A newcomer's own floor is checked only when its engine is assembled, so such a +model loaded last can still receive less than its floor and fail with +`no_kv_headroom` (`EngineV2Bridge.requireServiceableOrdinaryGrant`). + A private hybrid-cache carve is added once to the engine floor. The bridge retains the total requested grant for exact rollback instead of feeding an already-carved engine grant back through the carve. Physically retained cache @@ -831,8 +847,10 @@ grant or reported capacity field changes, so replaces the first term with its own claim's ledger room, which keeps no load reserve — `ProviderLoop.evictUntilNemotronSuperFits`, `nemotronSuperLoadIsCertainToFail`. -6. Load-time re-slicing refuses a newcomer if any resulting engine share falls - below `minimumServiceableGrantBytes`; shrink preserves existing ownership — +6. Load-time re-slicing refuses a newcomer only when the slots' + `minimumServiceableGrantBytes` floors sum to more than the fleet KV budget; + otherwise every engine share is at least its floor. Shrink preserves existing + ownership — `EngineV2KVSizing.resliceGrants`, `EngineV2KVSizing.resliceMeetsServiceabilityFloor`, `AdmissionV2.updateBytesCapacity`. 7. `freeForLoadGb` applies no multiplicative discount; the only padding is the scanner's `memoryOverheadFactor` on weights — `ModelLoadAdmission.swift`, @@ -846,6 +864,7 @@ grant or reported capacity field changes, so | Start refused: Metal unavailable | `GPUEnforcement.requireMetal()` threw | `GPUEnforcement.swift` | | Load refused: "… need N GB to serve — unloaded" | Post-load `hasServeableKVHeadroom` false (live KV headroom below `minimumLoadKVBytes`) | `ProviderLoop+ModelLoading.swift`, `KVHeadroomProbe.swift` | | Load refused with `no_kv_headroom` | Slot KV sizing overflowed or no serviceable grant during construction | `EngineV2Config.swift` (`EngineV2RefusalReason.noKVHeadroom`), `EngineV2SlotFactory.swift` | +| Load refused: "loading '…' would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance (fleet KV budget … B across … slots) — refused" | The slots' `minimumServiceableGrantBytes` floors sum to more than the fleet KV budget | `ProviderLoop+EngineV2.swift` (`resliceAndBuildEngineV2Bundle`), `EngineV2Reslice.swift` (`resliceGrants`) | | Catalog says the tier fits, provider refuses | Static cap arithmetic passes but `freeForLoadGb` (real free minus `loadReserveBytes` and in-flight reservations) is below `requiredToLoadGb` | `ModelLoadAdmission.swift`, `ProviderLoop+ModelLoading.swift` | | Nemotron Super refused: "Insufficient memory (… GB of LOAD room, need … GB) …" | The claim's ledger room cannot hold its narrowest configuration, even after evicting every idle model | `provider-swift/Sources/ProviderCore/NemotronSuper/ProviderLoop+NemotronSuperAdmission.swift` | | New request cannot fit | Its complete request promise exceeds the slot grant, or live ownership/OS pressure leaves no process headroom | `AdmissionV2.swift`, `ProcessMemoryLedger.swift` | diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9d0af10a80..d62304aa35 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -982,7 +982,11 @@ adapter is dropped from the advertised set at scan time and never loads Slot construction carries the engine's immutable admission watermark into the bridge so future load and reserve-raise checks can preserve a serviceable total grant. These [workspace-aware floors](hardware-support.md#kv-slot-grants) do not -lower the activation reserve or replace actual per-request byte admission. +lower the activation reserve or replace actual per-request byte admission. Every +re-slice, including regrowth, funds those floors first when the proportional +split alone would leave a slot below one, so the re-slice refuses a load only +when the floors together exceed the fleet KV budget. A newcomer counts only the +base floor until its engine is assembled. ### GLM5Next implementation boundary @@ -4427,18 +4431,32 @@ synchronizes before dropping request caches on completion or failure. Copies share immutable old pages; a later write replaces the affected page handle. Sliding histories release old pages when they repack or enter the fixed ring. +Sliding pages also keep the ring's wrapped flag: a one-token write that rotates +sets it, and a chunk or trim clears it. Their `metaState` is the seven values the +pinned SDK writes for `RotatingKVCache(maxSize: window)` in the same state: keep, +window, step, offset, write index, capacity origin and wrapped flag +(`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, +and only with the rows that ring holds: its first `index` rows, or the whole +window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a +kept prefix, and any other step, window or capacity origin. It also refuses an +unwrapped ring that has evicted rows but holds fewer than `window - 1`, which the +SDK's `trim` after eviction can leave: pages cap masks and trims by the offset, +the SDK by the rows it holds. GPT-OSS serving never reads or restores this +metadata. + `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's allocator bound separately, the gathered attention view, and partial-page copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. -CPU parity against the actual SDK caches covers ring/page/chunk boundaries and -sinks. Real two-Mac numerical acceptance, resource release and performance -remain separate qualification gates. +CPU parity against the actual SDK caches covers ring/page/chunk boundaries, +metadata, restores and sinks. Real two-Mac numerical acceptance, resource release +and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` -(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, +(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` +(`GPTOSSSlidingRing`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Resident/GPTOSSResidentAdmission.swift` (`loadAgreementFingerprint`). See [focused cache checks](../developer/test.md#gpt-oss-cluster-paged-kv-checks). @@ -5367,7 +5385,9 @@ does not establish an installed distributed-model pass. The Qwen3.5 9B's artifact ships the same dense one-layer inline head, so its tensor owner runs the same resident assistant (`QwenTensorParallelMTPPolicy.models`, `ClusterQwenTensorAssistantPolicy.runtimeModelIDs`): `QwenTensorParallelMTPInventory.Head` derives every expected head tensor from the row's configuration and `QwenTensorParallelMTPBudget` prices the row's own widths (the 27B's inventory fingerprint and quotes are unchanged). The 9B's READY carries the assistant without the 27B's media contract. The routed-expert rows' heads are expert layers this assistant does not load; those rows serve their request-owned lanes without speculation, and planning never asks them for an assistant. -For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-two cohort quote. The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. +For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote. The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. + +The assistant serves local clusters only. Its verify windows are a computation that no parity qualification covers: the coordinator qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. A setup saved for coordinator pairing therefore carries none (`ClusterConfiguration.validate`). The guided setup plans a cluster served through Darkbloom under `auto` as under `off` (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). Explicit `on` is kept; the plan's public-traffic line then says the pair is not offered, and the leader refuses the coordinator's approval before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation). Public speculative decoding needs qualification evidence of the assisted placement. The assistant stays resident across admitted widths. Each request owns its history, assistant pages, target frontier and bounded accepted-token queue. Each row's round starts with its own B=1 assistant step over its own history (the step that also feeds its trusted history); the round's later steps run every row of a cohort through one assistant forward (`Qwen35InlineMTPAssistant.draftHiddens`, see [Batch-invariant tensor-parallel decode projections](#batch-invariant-tensor-parallel-decode-projections)). In a cohort, one head call per draft step chooses every row's proposal (`QwenTensorParallelMTPDecoder.stepBatch`; the SDK's `Qwen35InlineMTPAssistant.draftHidden`, `draftHiddens` and `recordDraft`): the rows' hidden states go through the vocabulary-sharded head together, and the cohort's draft step is one evaluation holding two collectives (rank zero's hidden rows, then the score exchange) in the same order on both ranks, instead of one evaluation and two collectives per row. Each row's choice equals its own call's: both collectives are element-wise, the head shard computes every row with the batch-invariant kernel (`QwenTensorParallelMTPProjection.exactRows`; with exact drafts off, each row as its own single-vector MLX product, `rowsAlone`, because one plain multi-row call would let MLX pick `qmv_wide` on Apple GPU family 15 and later and change rows), and the first maximum is taken per row. `QwenTensorParallelMTPHeadRowsTests` checks the head rows byte for byte for two to eight rows, and `QwenTensorParallelBatchMTPTransitionTests.batchedCohortDraftsMatchRowByRowDraftsWithOneHeadCallPerStep` checks tokens, MTP statistics and native state against row-by-row drafting (collective reductions per run: 577 to 401 at two rows, 1,633 to 401 at eight). A one-row round runs the same per-step functions with one row, so a request proposes the same tokens alone and in a cohort. Both ranks read every proposal from the same exchanged (maximum, index) pairs, so no proposal broadcast is needed. Eligible requests then share one captured target rectangle: `QwenTensorParallelMTPDecoder.stepBatch` verifies their seed and proposals, settles every row to its independently accepted prefix, and confirms the entire ordered cohort before publishing any result. Accepted suffixes consume the existing per-token credits without another native step. Request RNG and stopping remain independent. diff --git a/docs/developer/build.md b/docs/developer/build.md index d94463d575..d369902d0d 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -177,23 +177,30 @@ importing its certificate. See [release qualification](test.md#sdk-27-release-qu ## The `dev` branch -The `dev` branch is master plus one commit. On it, a plain `swift build` is a -DevNet build: `DARKBLOOM_RELEASE_ENVIRONMENT` defaults to `dev`, so the -provider talks to `https://api.dev.darkbloom.dev` and nothing else. On master -the default is `prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a -production binary from the `dev` branch. +On the `dev` branch a plain `swift build` is a DevNet build: +`DARKBLOOM_RELEASE_ENVIRONMENT` defaults to `dev`, so the provider talks to +`https://api.dev.darkbloom.dev` and nothing else. On master the default is +`prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a production binary +from the `dev` branch. Use the `dev` branch to run a provider from source against the DevNet -coordinator. Published dev providers do not come from this branch: a master -push that changes the provider publishes one through `release-swift.yml` +coordinator. A push to `dev` that changes the provider publishes the DevNet +release through `.github/workflows/release-dev-branch.yml` (see `docs/operations/provider-release.md`). Rules for the branch: -- Merge master into `dev` to update it. Never merge `dev` into master. -- Never tag a commit on `dev`. Tags publish production. -- Code changes go to master through a pull request, then reach `dev` by - merging master. Only the default-environment commit lives on `dev` alone. +- Changes reach `dev` through pull requests into `dev`, which land as merge + commits, and through merges of master into `dev`. +- `dev`'s changes reach master through pull requests into master. + [#1688](https://github.com/Layr-Labs/d-inference/pull/1688) merged a snapshot + branch of `dev` with a merge commit, for which an admin briefly allowed merge + commits on the squash-only master ruleset; 0.10.6's cluster changes reached + master as a squash-merged pull request of `dev` with master merged in. +- Master keeps one commit of its own, `e9babca4`, which sets plain builds back + to `prod`. A merge of master into `dev` reverts that commit on its sync + branch, so `dev` keeps its DevNet default. +- Never tag a commit on `dev`. Tags publish production, from master. `scripts/provider-release-cache.py` separates optimized and qualification Swift caches by compiler/SDK, architecture, absolute checkout/toolchain paths, diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..3c10bfbbc9 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1823,9 +1823,11 @@ swift test --package-path libs/darkbloom-cluster -c release \ --filter GPTOSSPagedKVTests ``` -`GPTOSSPagedKVTests` compares exact rows, masks, offsets and learned-sink SDPA -results with `StandardKVCache` and `RotatingKVCache`. It also checks demand -allocation, bounded sliding retention, copy/trim isolation and owner release. +`GPTOSSPagedKVTests` compares exact rows, masks, offsets, ring metadata and +learned-sink SDPA results with `StandardKVCache` and `RotatingKVCache`. It also +checks demand allocation, bounded sliding retention, copy/trim isolation, owner +release, and that sliding pages restore only ring metadata they can continue, +then continue exactly as that ring. `GPTOSSStageChecks` checks each page's allocator overhead and sliding repack charge. These are CPU correctness checks, not native transport, MXFP4 model parity or performance evidence. Retain the existing two-Mac reference comparator diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index de728c8616..b00c7d71f3 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -27,45 +27,135 @@ runs the resolve, build, qualification, signing, R2 staging and publication chain for one environment. To find the newest dev release, read `https://api.dev.darkbloom.dev/v1/releases/latest`. -`ProviderCore.version` is prepared as `0.10.5`, a patch release over `v0.10.4`. -`darkbloom sandbox` sets up, checks, pauses, resumes and removes the Darkbloom -Sandbox add-on from the provider CLI. GPT-OSS client stop sequences match only -the Harmony final message, which ends its reasoning-only empty answers, and Qwen -3.5 and 3.6 no longer loop to `max_tokens` when sampling is omitted. A dense Qwen -follow-up restores its checkpoint from just below the previous prompt end. SSD -checkpoint restores, eviction, maintenance, reads and donations are faster, -expired checkpoints no longer count as corrupt and cache sweeps no longer stall -lookups. The provider reconnects faster after a long session or a 1012 close, -keeps prompt-cache hits across batch promotion, drops response chunks processed -while disconnected and keeps a model download's completion. The MLX pins move to -their forks' `main`. See the [`v0.10.5` changelog entry](../../CHANGELOG.md) for the full -scope. - -Before tagging `v0.10.5`: +`ProviderCore.version` is prepared as `0.10.6`, a patch release over `v0.10.5` +and the first production release with two-Mac clusters. `darkbloom cluster` +sets up two Macs joined by one Thunderbolt 5 cable (macOS 26.2 or later, RDMA +over Thunderbolt) to serve one model together, GLM-5.3-Flash and Qwen3.8-27B in +tensor parallel, and `darkbloom cluster local` serves a pair without a +coordinator. Every release lane computes the build's +[cluster runtime facts](#cluster-runtime-facts), from which a coordinator with +darkbloom-platform#643 derives the build's cluster approvals, pair-serving +grants and public qualifications. A registered pair's cluster service is no +longer restarted by its own part's heartbeats (#1690), pair members register the +models their pair-serving grant admits (#1686), a single Qwen3.8-27B request in +tensor parallel decodes about 6% faster on two M5 Ultra (#1680) and model +downloads show one progress line (#1683). Single-Mac serving needs no +coordinator change and no provider-version floor, though three answers to +coordinator requests and the local API change. See the +[`v0.10.6` changelog entry](../../CHANGELOG.md) for the full scope. + +Before tagging `v0.10.6`: - Confirm that the tagged commit pins `libs/mlx` and the nested `mlx` to - `72dffa2d`, `libs/mlx-swift` to `c633d221` and `libs/mlx-swift-lm` to - `2beb401f`, all on their forks' `main`. The 0.10.2 hotfix branches are no - longer pinned; the NAX head-dim split fix they carried (`mlx` `31f550af`) is - in `72dffa2d`'s `jit_kernels.cpp`. -- The tag build's `metallib_hash` differs from v0.10.4's - `6ccc62966bb452b767fbd7261175b06c7653259a25f657524f1c1ef71f556d45`: twelve - Metal backend files change between the `mlx` pins, including - `kernels/fence.metal`. Record the new hash. Complete SSD checkpoints that 0.10.4 - wrote are not restored by 0.10.5, because their namespace binds the binary and - loaded-metallib hashes. + `72dffa2d` and `libs/mlx-swift` to `c633d221`, as v0.10.5 did, and + `libs/mlx-swift-lm` to `7933a0fa`, its fork's `main`. Only the SDK pin moves + (from `2beb401f`, through #1680 and #1684): SDK #373 changes + `AffineQuantizedVectors.swift` alone. +- The tag build's `metallib_hash` should equal v0.10.5's + `98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be`: the MLX + core is unchanged, and the dev-branch release of this preparation's base, + `0.10.5-dev.branch.18` from `a0413a8a`, registered that hash on DevNet. A + different hash needs an explanation, such as a changed Metal toolchain. +- The tag is the first production run of the release steps that came with the + cluster: the build and signing of the [cluster helpers](#cluster-helpers) and + the cluster runtime facts. The dev-branch lane runs the same reusable + workflow; its run + [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) + passed both, and DevNet's coordinator accepted its block. That proves neither + the derived approvals nor pairing; step 5 below checks both in production. +- Before step 3 below, check that the production catalog lists `glm-5.3-flash` + and `EigenLabs/Qwen3.8-27B-4bit-mtp`, because the facts step leaves out a + model the environment's catalog lacks. Check that the coordinator's catalog + has room within its bounds of 64 approvals, 64 pair-serving grants and 256 + parity qualifications, which newer releases fill first, each release whole: + 0.10.6 adds at most 24 approvals and 24 grants (`s1` and `s2` for each of at + most 12 models) and 8 parity qualifications (4 each for GLM-5.3-Flash and + Qwen3.8-27B). See [cluster runtime facts](#cluster-runtime-facts). +- The tagged commit is this preparation's squash commit on `master`, and + `changelog.d/` must hold only its `README.md` there. On the `master` checkout + you tag: + + ```bash + git log -1 --format=%s # must print: Prepare provider 0.10.6 (#) + make changelog-check # must print: changelog: 0 valid fragment(s) + ``` + + A fragment at the tag reached `master` without an entry in this release's + changelog. Roll out in this order; each step is a separate approval: -1. Tag `v0.10.5` ([step 4](#4-tag-and-push-production-source)). No coordinator - deployment is needed first, and no provider-version floor applies. -2. The platform snapshots its provider contracts from the tagged commit +1. No DevNet proof: this release goes to production without one. DevNet's + coordinator accepted the block of `0.10.5-dev.branch.18` but derived no + approvals, so production is the first coordinator to derive them, and step 5 + checks them. +2. Production platform: deploy a `darkbloom-platform` coordinator with + [darkbloom-platform#643](https://github.com/Layr-Labs/darkbloom-platform/pull/643). + #643's code reaches the platform's `master` only with its `dev` to `master` + merge; its twin, + [darkbloom-platform#644](https://github.com/Layr-Labs/darkbloom-platform/pull/644), + carries only migration 58 (the `releases.cluster_runtime` column), which no + code on `master` reads. Production runs one combined coordinator, not + DevNet's split Provider Edge and Conductor. Apply migration 58 and set, in + the same deploy: + - `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` (approvals + derived from releases, the only approval source: + `EIGENINFERENCE_CLUSTER_PAIRS`, the operator's approval table, stays + unset); + - `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` (the + production coordinator listens on plain HTTP behind Caddy on the same + host, which reaches it over loopback, so without this setting no member + connection attaches to pair control); + - `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` (public traffic for qualified + clusters). + + App Attest serving must be on for every account: + `EIGENINFERENCE_APP_ATTEST_SERVING=true`, + `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT=production` and + `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT=100`. A member holds either the + legacy MDM path or an App Attest serving authorization, so a member on + macOS 27 without MDM pairs only through App Attest. +3. Confirm from production's `/health` `build_commit` that it runs the platform + revision of step 2. Check the catalog as above, and re-run the release's + facts step read-only against it: + `scripts/provider-cluster-runtime-facts.sh darkbloom prod `, + with an unsigned app staged from this preparation's source the way the build + job stages it (`scripts/provider-signing-validation.py stage`). It reads the + catalog and the CDN, sends nothing, and must exit 0: a catalog row that the + worker cannot describe stops the release after signing once the variable is + set. Then set the repository variable `PROD_CLUSTER_RUNTIME_ENABLED=true`. + Never before step 2: a coordinator without #643 refuses a registration that + carries `cluster_runtime`, and the release then fails after signing. Set it + before the tag: a release registered without the block never gains one, + because a re-registration must repeat the stored block (409 + `cluster_runtime_conflict`). +4. Merge into `master`, each squash-merged after its approval: first the + two-Mac clustering pull request, then this preparation. The clustering pull + request carries #1690 and #1692 from `dev`, with `master` merged in so plain + builds keep `master`'s `prod` default, and the fixes found while preparing + this release, such as the release facts fix (a catalog model ID that the + worker describes as another registered model is left out). After its squash, + restack this preparation with `scripts/restack-after-squash.py` + ([pull-request stacks](../developer/pull-requests.md)). Let SDK 27 release + preparation pass on `master`. This step does not depend on steps 1 to 3 and + may come first. +5. Tag `v0.10.6` on this preparation's squash commit once the checks above pass + ([step 4](#4-tag-and-push-production-source)). After registration, check the + coordinator log for `release cluster approvals omitted` and + `GET /v1/cluster/approvals` for the derived `release/0.10.6//s<1|2>` + approvals. Then a production pair, the owner's two Macs with App Attest, + must form a session under one of them. Record the run and the session. +6. The platform snapshots its provider contracts from the tagged commit (`python3 scripts/provider-contracts.py snapshot `), sets - `LatestProviderVersion` to `0.10.5` in the coordinator's `server.go` in the + `LatestProviderVersion` to `0.10.6` in the coordinator's `server.go` in the same change and adds the revision row to its provider-contract reference. Of - the 34 snapshotted inputs, pinned at v0.10.4's `8effff7f`, only - `contracts/provider/ProviderCore.swift` should change. `LatestProviderVersion` - is a fallback and does not gate publication. + the 34 snapshotted inputs, only `contracts/provider/ProviderCore.swift` + changes from v0.10.5. `LatestProviderVersion` is a fallback and does not gate + publication. + +Without steps 2 and 3 the tag still publishes with an unchanged registration, +but 0.10.6 then never derives cluster approvals, and a production pair serves +only on its leading Mac's local API. 0.10.2's remaining enablement steps do not wait for this tag and still apply; each is a separate approval: @@ -79,24 +169,35 @@ each is a separate approval: tuple to the allowlist and list `logprobs` in Super's catalog row. Catalog changes, allowlist changes and model registration are separate -approvals. This preparation does not tag, register, upload, deploy or enable -anything. +approvals. This preparation tags, deploys and enables nothing; merging it into +`master` publishes nothing, because the staging lane runs only while +`STAGING_ENABLED` is `true`. -Platform evidence, inspected on 2026-10-30 (recheck before tagging): +Platform evidence, inspected on 2026-10-31 (recheck before tagging): | Claim | Source | |---|---| -| The provider-contract snapshot pins d-inference `8effff7f` (v0.10.4), and its 34 inputs equal this preparation's except `ProviderCore.swift` | [`contracts/provider/manifest.json` at `cb31f6b4`](https://github.com/Layr-Labs/darkbloom-platform/blob/cb31f6b44af25500eab72fa0adb01eb6c69864d6/contracts/provider/manifest.json) (`source_revision`) | +| Platform `master` (`2847f27d`) pins the provider contracts at d-inference `8effff7f` (v0.10.4) and keeps `LatestProviderVersion` at `0.10.4`; darkbloom-platform#639 (open) pins v0.10.5's `d3bbcd06`. The 34 inputs equal this preparation's except `ProviderCore.swift` | [`contracts/provider/manifest.json` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/contracts/provider/manifest.json) and [at #639's `422ca1d4`](https://github.com/Layr-Labs/darkbloom-platform/blob/422ca1d428849c775daa950691a185154f117c18/contracts/provider/manifest.json) (`source_revision`) | | `LatestProviderVersion` must equal the snapshotted `ProviderCore.version` | [`provider_version_sync_test.go` at `5ba280d8`](https://github.com/Layr-Labs/darkbloom-platform/blob/5ba280d89aa5e9bd4fbf05e0dfa848059cd3b585/coordinator/tests/api/provider_version_sync_test.go) (`TestLatestProviderVersionMatchesProviderCore`) | - -`v0.10.4` was [published on 2026-10-28](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.4) +| #643 is merged into platform `dev` (`df61dd6f`), not `master`; #644 (open) carries only its migration to `master`. Only `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` derives entries from releases, and public routing needs an approval source | [`cluster_pair_config.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/api/cluster_pair_config.go) (`ClusterPairConfig`) | +| Migration 58 adds `releases.cluster_runtime`, and a re-registration must repeat the stored block (409 `cluster_runtime_conflict`) | [`00058_release_cluster_runtime.sql` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/schema/migrations/00058_release_cluster_runtime.sql); [`releases.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/releases.go) (`SetRelease`) | +| A coordinator without #643 refuses a registration body that carries `cluster_runtime` | [`release_handlers.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/api/releases/release_handlers.go) (`DisallowUnknownFields`) | +| Of the platform's deploy configuration, only DevNet's overlay sets `EIGENINFERENCE_CLUSTER_PAIRS`, `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES` and `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING`, and it also sets `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1` | [`env-overrides` (DevNet) at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/deploy/gcp/dev/env-overrides) | +| A member connection attaches to pair control only after its own TLS handshake or through a listed TLS proxy. The production coordinator listens on plain HTTP behind Caddy, and in the split deployment only the trusted-proxy path attaches a member | [`configuration.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/configuration.md) ("Trusted TLS proxy trade-off") | +| A pair member holds the legacy MDM path or an App Attest serving authorization; App Attest serving reads `EIGENINFERENCE_APP_ATTEST_SERVING`, `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT` and `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT` | [`cluster-control-protocol.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/cluster-control-protocol.md) ("Member trust"); [`config.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/appattest/service/config.go) (`ConfigFromEnvironment`) | +| DevNet runs `df61dd6f` and accepted the block of `0.10.5-dev.branch.18` (registered 04:33Z), yet its `GET /v1/cluster/approvals` listed only 26 operator approvals, with no `release/` entry, at 04:44Z, 04:57Z, 05:04Z and 05:09Z | DevNet `/health` and `/v1/cluster/approvals`; run [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) (`CLUSTER_RUNTIME_SEND: true`) | + +The production coordinator was not inspected for this preparation; step 3 +checks its `/health`. + +`v0.10.5` was [published on 2026-10-30](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5) +from `d3bbcd064ea290fbeb500e5c51c7870e3695741c`, `v0.10.4` was +[published on 2026-10-28](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.4) from `8effff7f7067fec70b2e3b58de0a4ba47ea3986c`, `v0.10.3` was [published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.3) from `3ddd11ce8d7204cc5aadefd2050376c583da4ff8`, `v0.10.2` was [published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.2) -from `f9d1af3d0d3e1838974a5cfdff0a08142977b45e`, `v0.10.1` was -[published on 2026-10-24](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.1) -from `9034a5a0f3526dec83ab6384e5264db595cb7549`. Publication does not establish +from `f9d1af3d0d3e1838974a5cfdff0a08142977b45e`. Publication does not establish that every optional feature or environment has been activated. ## Prerequisites @@ -507,7 +608,7 @@ requirement of `scripts/install.sh` and the self-updater's | Item | Dev-branch lane | |---|---| | Version | `X.Y.Z-dev.branch.`, stamped by `scripts/resolve-provider-release.sh` and accepted by `scripts/check-release-version.sh` | -| Source gate | Job `resolve-env` runs master's copy of `scripts/provider-release-resume.py verify-source`. The gate must accept a `refs/heads/dev` push for environment `dev`; until master carries that change, the lane fails at the gate. | +| Source gate | Job `resolve-env` runs master's copy of `scripts/provider-release-resume.py verify-source`, which accepts a `refs/heads/dev` push for environment `dev` only. | | Signing and notarization secrets | `APPLE_CERTIFICATE_P12`, `APPLE_CERTIFICATE_PASSWORD`, `PROVISIONING_PROFILE_BASE64`, `APPLE_ID`, `APPLE_APP_PASSWORD`, read only in job `build-and-release` | | Publication secrets | `DEV_R2_*`, `DEV_COORDINATOR_URL`, `DEV_RELEASE_KEY` | | GitHub environment | None. All of these are repository secrets. | @@ -524,11 +625,11 @@ re-run failed jobs only after the signing job passed, and push a new commit to rebuild. The `release-dev-branch` group does not cancel a running run, but a newer dev push cancels a run that is still pending in the group. -Review is not enforced on `dev` today. Its rules are required signatures and the -"Darkbloom PR access control" ruleset, which lets only the accounts on that -ruleset's bypass list create or update a ref. Because a dev push gets the -Developer ID signature, `dev` needs a pull_request rule before the lane runs. A -repository administrator adds that rule. +Because a dev push gets the Developer ID signature, pull requests into `dev` +need one approving review and land as merge commits (ruleset "Dev pull +requests"). `dev` also requires signed commits, and the "Darkbloom PR access +control" ruleset lets only the accounts on its bypass list create or update a +ref. The dev coordinator can still hold `X.Y.Z-dev.` releases from the master dev lane; `0.10.4-dev.224` is the latest dev release on 2026-10-28. @@ -698,14 +799,19 @@ Every lane (dev branch, staging, prod) runs the step 6. The final CLI computes the facts: ` cluster runtime-facts --app --release-candidates `. The app's own worker describes each candidate (`--describe-runtime`); every - catalog model ID of a listed artifact gets one entry, with its pair-serving - grant. A declared model gets one parity qualification per declared family - and schedule; a tensor-parallel envelope admits the media its catalog entry - lists, a pipeline's text only. A declared pipeline whose `config.json` has - no layer count is left out and named on standard error, in the job log. The - step fails when a catalog model ID of a listed artifact has no candidate the - worker describes as the listed model, when no model is left, or when an ID a - coordinator would derive exceeds 128 bytes. + catalog model ID of a listed artifact that it describes as the listed model + gets one entry, with its pair-serving grant. A declared model gets one + parity qualification per declared family and schedule; a tensor-parallel + envelope admits the media its catalog entry lists, a pipeline's text only. A + declared pipeline whose `config.json` has no layer count is left out and + named on standard error, in the job log. One artifact can be two registered + models that only the manifest tells apart (production lists `gemma-4-26b` + and `gemma-4-26b-8bit` for one artifact): a catalog model ID whose + candidates the worker describes only as another registered model is that + model's, so it is left out and named on standard error too. The step fails + when the worker describes no candidate of a catalog model ID of a listed + artifact at all, when no model is left, or when an ID a coordinator would + derive exceeds 128 bytes. The steps `Show the cluster runtime facts` and `Retain the cluster runtime facts` then write the block (or the failure) to the job summary and upload @@ -744,10 +850,12 @@ again with [Resume Signing From A Retained Unsigned Build](#resume-signing-from-a-retained-unsigned-build). Turn a variable on only after the coordinator of that environment accepts the -block (`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES`, darkbloom-platform); -a coordinator that does not accept it yet must never receive it. Public cluster +block (darkbloom-platform#643); a coordinator that does not accept it yet must +never receive it. It derives approvals from the block only with +`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`. Public cluster routing also needs `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` on that -coordinator. +coordinator, and a coordinator behind a TLS-terminating proxy attaches members +only through `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES`. Before a release with the block registers, make sure the coordinator's catalog has room. It holds at most 64 approvals (the operator's per-build and per-model @@ -776,9 +884,34 @@ Rollout order: 3. This change merges to `dev`. The next dev-branch release registers with the block; check the coordinator log for an omitted release. A pair registers by itself after it updates. -4. Both repositories go `dev` to `master`. The production coordinator deploys - with its switch on, a person checks its catalog's room and sets - `PROD_CLUSTER_RUNTIME_ENABLED=true`, and the release tag follows. +4. Production follows in this order, without waiting for a DevNet proof; each + step is a separate approval: + 1. The production coordinator deploys with darkbloom-platform#643 and + migration 58, and with `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`, + `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` and + `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` in its settings. + `EIGENINFERENCE_CLUSTER_PAIRS` stays unset, so approvals derived from + releases are the only source. Its `/health` `build_commit` must be that + revision. + 2. A person checks the production catalog's room and sets + `PROD_CLUSTER_RUNTIME_ENABLED=true`. + 3. The release tag follows. + 4. After the registration, `GET /v1/cluster/approvals` lists the release's + derived approvals, `release/0.10.6//s<1|2>` for 0.10.6, and the + coordinator log has no `release cluster approvals omitted` for it. The + pair-serving grants (`/grant`) and parity qualifications + (`/q`) derived beside them are not on that list: a pair + that forms under a derived approval shows its qualification as + `qualification_id` in its owner's + [`GET /v1/me/cluster-pairs`](https://github.com/Layr-Labs/darkbloom-platform/blob/master/docs/reference/api-contracts.md#owner-cluster-views). + + Keep the order. A coordinator without #643 refuses a registration that + carries the block, so the release fails after signing. A version whose + first registration carries no block never gains one: a re-registration must + repeat the stored block, and the coordinator answers any other with 409 + `cluster_runtime_conflict`. So if 0.10.6 registers while + `PROD_CLUSTER_RUNTIME_ENABLED` is not `true`, it derives no approvals at + all, and only a later version can carry the block. To compute the facts of an installed or downloaded app by hand, give the models explicitly. Run that app's own CLI, so the public declaration and the records diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 557fb57fb4..abab9afda0 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -2453,7 +2453,7 @@ defines the response and supported saved widths. Source: ### Qwen27 TP assistant setup and native diagnostics -Run the normal `darkbloom cluster` setup for the catalog Qwen3.8 27B model. Its embedded assistant is discovered and fully priced under the existing `backend.mtp_mode` setting; no internal verification or inventory option is required in the normal flow. Verify the saved policy against both workers' actual READY before serving. Explicit `off` retains the ordinary target with its complete width-one quote. See [configuration](../reference/configuration.md#qwen27-tp-assistant-policy) and [native ownership](../architecture/inference.md#qwen27-tensor-parallel-resident-assistant). +Run `darkbloom cluster local` for the catalog Qwen3.8 27B model to serve it with its embedded assistant. The assistant is discovered and fully priced under the existing `backend.mtp_mode` setting; no internal verification or inventory option is required in the normal flow. Verify the saved policy against both workers' actual READY before serving. Plain `darkbloom cluster` serves through Darkbloom, and under the default `auto` it plans the model without the assistant, because a setup registered with the coordinator carries none (the assistant is not qualified for public traffic). Explicit `on` keeps the assistant there too, and the pair is then not offered to the coordinator. Explicit `off` retains the ordinary target with its complete width-one quote. See [configuration](../reference/configuration.md#qwen27-tp-assistant-policy), [the speed tradeoff](two-mac-cluster.md#the-steps-once) and [native ownership](../architecture/inference.md#qwen27-tensor-parallel-resident-assistant). The internal worker still accepts diagnostic `--mtp-depth N` in 1...4 for keyed 9B or 27B Qwen TP with paged KV (the A3B rows' heads are not loaded, so an explicit depth is refused for them). Installed launches also carry the pinned inventory and typed verification mode from the saved policy; these are implementation arguments, not user setup choices. Omitted policy preserves the legacy ordinary contract. Unsupported model, memory, backend, startup and conflicting speculative controls are refused before serving. diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 4d17cf1a98..d4b21423f9 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -1,6 +1,6 @@ # Keep a cluster member always on -> Last updated: 2026-10-20 +> Last updated: 2026-10-31 `darkbloom cluster` on each Mac does all of this. Nothing below is needed: it explains what the onboarding sets up and how to check it. @@ -27,10 +27,18 @@ the cluster comes back by itself, with no command run on either Mac (see [After a restart or a power cut](#after-a-restart-or-a-power-cut)). - launchd runs `darkbloom cluster service --supervise`: the same supervisor as - below, around `darkbloom cluster service`. A service that ends is restarted - after 15 s, doubling to 300 s; three runs in a row each shorter than 120 s - park it (nothing runs) until `darkbloom cluster` is run again, which - restarts it and resets the budget. + below, around `darkbloom cluster service`, without its update slot. A service + that ends is restarted after 15 s, doubling to 300 s; three runs in a row each + shorter than 120 s park it (nothing runs) until `darkbloom cluster` is run + again, which restarts it and resets the budget. +- Nothing updates Darkbloom on these Macs: the supervisor runs with automatic + updates off (`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, + `runSupervisor`), this Mac's part runs no updater + (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift`, which starts + `startAutoUpdateMonitor` only for a single-Mac provider), and the single-Mac + provider does not run beside the cluster. Run `darkbloom update` on both Macs + ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)); + automatic updates for a pair are a follow-up. - `RunAtLoad`, and `KeepAlive` only after an unsuccessful exit (throttled to the budget's first backoff): launchd brings back a supervisor that crashed, never one that was stopped. @@ -246,7 +254,7 @@ it. It documents the developer route that runs `darkbloom start | The leader's pair engine stays wedged (its own watchdog's verdict) for 180 s | Same recycle | | An active request made no progress at all for `clamp(120, 120 + prompt tokens / 1000, 900)` s (when the member reports one) | Same recycle | | A pair forms | The leader runs one greedy 8-token warmup request before the pair accepts work; if it fails or takes over 300 s the pair is retired and formed again (`DARKBLOOM_CLUSTER_WARMUP=0` turns this off) | -| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together | +| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), on this route only, with `auto_update` on (the default) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together. The cluster service of `darkbloom cluster` has no update slot ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)) | | `darkbloom stop` | Drains, stops the member and keeps it stopped across reboots | | Before every run, and at the member's own start and end | Orphan sweep: a worker or owner whose parent is gone is given its own contract to end, then SIGTERM, SIGKILL only after the kill margin; a stranded device journal is cleared once nothing it names runs; bootstrap directories whose socket no process holds any more are removed (read from the descriptor tables; nothing connects). One log line when it found something (`darkbloom cluster reap --json` runs the same sweep by hand) | diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 3da69fd26d..74ec3a42d6 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -1,6 +1,6 @@ # Direct mode: a local OpenAI-compatible endpoint -> Last updated: 2026-10-26 +> Last updated: 2026-10-31 Run the provider's inference engine as an OpenAI-compatible HTTP server on your own Mac, either standalone (`darkbloom start --local`, no coordinator, no @@ -53,7 +53,10 @@ See [inference and logprob admission](../architecture/inference.md). when `[backend] startup_preload` is enabled (the default). When a load is short of headroom the server first releases retained paged KV segments and drops the MLX buffer cache once, then evicts the least recently used idle - slot (`StandaloneServer.ensureMemoryHeadroomForLoad`). The explicit + slot (`StandaloneServer.ensureMemoryHeadroomForLoad`). Resident models share + the KV budget as [KV slot grants](../architecture/hardware-support.md#kv-slot-grants) + describes; a load that would leave any model below its minimum grant fails + with HTTP 503 (`StandaloneServer.resliceKeepsSlotsServiceable`). The explicit `preload_models` list takes precedence; slot and memory limits can skip a model, which still loads on request. A local GLM qualification load reads its weights for its own per-file SHA-256 verification and the tensor reads only; diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 57473bd6cf..d8688b78b8 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -1,6 +1,6 @@ # Two Macs as one provider (guided setup) -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Two Apple Silicon Macs joined by one Thunderbolt 5 cable serve a model together: each Mac holds part of its layers, and the pair serves as one provider. Setting @@ -74,6 +74,35 @@ cluster plan` says how many records it left out). A request that answers fewer than 64 tokens (the setup's test answer, a quick "Say hi") is not counted as a speed and does not shape the plan. +Qwen3.8 27B in tensor parallel can also decode with the speculative assistant +its artifact ships, but only on a cluster that serves locally only. The +assistant is not qualified for public traffic, and a setup registered with the +coordinator never carries it. So, with the default `[backend] mtp_mode` of +`auto`: + +| You run | Qwen3.8 27B decodes | One request on two M5 Ultras (2026-10-31) | The coordinator | +|---|---|---|---| +| `darkbloom cluster` | without the assistant | about 40 tokens/s | the pair registers when the coordinator serves a matching approval | +| [`darkbloom cluster local`](#serving-locally-only) | with the assistant | about 93 tokens/s | never contacted | + +With `mtp_mode = "on"`, `darkbloom cluster` keeps the assistant too. That pair +is then not offered to the coordinator: its plan says "not offered for public +traffic", and it serves on the leader's local API. A serving cluster switched +with `l` or `p` keeps the setup it has; press `m` to plan the model again for +the new way of serving. Public speculative decoding for Qwen pairs needs +qualification evidence of its own, which no record holds yet. Rules: +[Qwen27 TP assistant policy](../reference/configuration.md#qwen27-tp-assistant-policy). + +A JSON `response_format` request that a single Mac would answer under a grammar +(no tools or `tool_choice`, no media, a schema the grammar covers) is refused on +a Qwen pair before any output: a pair's ranks cannot apply the grammar +(`constrained_decoding_unsupported`, HTTP 400). The coordinator moves a public +request refused this way to a single Mac, which constrains it +(darkbloom-platform `fix/coord-pair-refusal-failover`); a request to the owner's +local cluster API gets the refusal. Other JSON requests are served with the +format instruction only, as on one Mac +([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)). + | # | Where | What you do | What it asks | |---|---|---|---| | 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready."). Nobody waits on the cable yet, so it says **"On your other Mac, run `darkbloom cluster`."** and waits (q cancels). With two cables it asks which one to use. | one macOS administrator approval when the selected port needs configuration ("Darkbloom needs network access for the cluster cable") | @@ -109,15 +138,23 @@ clusters. A coordinator that refuses this pair is not treated this way; the start fails and says why. To serve without any coordinator, use [`darkbloom cluster local`](#serving-locally-only). -## Registered with the coordinator as a cluster member (DevNet) - -When the coordinator's operator approval file holds a cluster approval for this -pair's model (DevNet only), the pair registers with the coordinator by itself. -Nothing is typed and no file is copied. Production and staging serve no -approvals, and the pair serves as described above. The pair -serves its owner's own requests, and public requests too once the coordinator's -operator has turned public cluster routing on and qualified the pair's model and -split ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). +## Registered with the coordinator as a cluster member + +When the coordinator serves a cluster approval for this pair's model, the pair +registers with the coordinator by itself. Nothing is typed and no file is +copied. DevNet's coordinator serves the approvals its operator posts. +Production's derives them from each release's +[cluster runtime facts](../operations/provider-release.md#cluster-runtime-facts), +from 0.10.6 on, once it runs darkbloom-platform#643 with +`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`; such an approval +names one release's build, so a pair registers with it only on that release. +Before that deploy production serves no approvals (`GET /v1/cluster/approvals` +answers 404), staging serves none, and the pair serves as described above. The +pair serves its owner's own requests, and public requests too once the +coordinator has public cluster routing on and a parity qualification for the +pair's model and split; a release's cluster runtime facts carry them for +GLM-5.3-Flash and Qwen3.8-27B +([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). A tensor-parallel pair registers like a pipeline one; its plan names no cut. 1. Run `darkbloom cluster` and choose a model, as in [the steps](#the-steps-once). @@ -138,7 +175,9 @@ A tensor-parallel pair registers like a pipeline one; its plan names no cut. There is no local API in this mode. `darkbloom cluster` status shows the same line. -An approval ends at its `not_after`, which the operator sets. The +An approval ends at its `not_after`, which the operator sets; one derived from +a release ends 90 days after that release registered +([`releaseApprovalExpiry`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_release_approvals.go)). The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching approval when the saved one ends within a day. A Mac whose approval @@ -150,10 +189,16 @@ The pair also serves on the leader's local API, both Macs without the approval, when the coordinator gives no answer for the absence grace (10 minutes, the same grace as in [if a Mac goes away](#if-a-mac-goes-away)), when it no longer lists the approval, or when the coordinator-paired parts end three -times in a row right after starting. When the coordinator lists a matching -approval again, the pair registers again (after repeated failures, only with a -later approval). Both Macs carry the same approval, or neither does: the leader -compares the two at every check. +times in a row right after starting. An end the coordinator decides is not +counted: one because it could not be reached, or because it did not accept the +part's registration in time, as during a coordinator deploy. This complements +the coordinator's side: a coordinator that ends each pair session before its +shutdown closes the members' connections gives a deploy cleaner ends, and this +rule still covers a coordinator without that change, a coordinator crash and a +slow registration. When the coordinator lists a matching approval again, the +pair registers again (after repeated failures, with the same approval an hour +later, or at once with a later one). Both Macs carry the same approval, or +neither does: the leader compares the two at every check. What `darkbloom cluster` status says in each mode: @@ -162,9 +207,9 @@ What `darkbloom cluster` status says in each mode: | Registered | `Registered with the coordinator as a cluster member: approval , until .` | | Coordinator gave no answer for the grace | The API line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | | Approval no longer listed | The API line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | -| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API until the coordinator lists a later one.` | +| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | | Approval ended | The API line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | -| No approval (production, staging, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | +| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | Approval sources, checks and saved fields: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). @@ -190,7 +235,9 @@ to keep waiting (it leads) and the other says so and joins it. choice, planner, copies, speculative decoding, caches, failover and stop as `darkbloom cluster`, but no Mac of the cluster contacts a coordinator. Nothing registers, sends heartbeats, takes public traffic or bills, and serving needs -no network beyond the cable. +no network beyond the cable. It is also where Qwen3.8 27B in tensor parallel +decodes with its speculative assistant under the default `mtp_mode` +([above](#the-steps-once)). 1. On the leader, run: @@ -482,12 +529,37 @@ a restart, and writes why to `~/.darkbloom/cluster-setup/service.log`. After a restart or power cut a Mac serves again once it is logged in. With automatic login on (System Settings → Users & Groups; needs FileVault off) that -happens by itself; `darkbloom cluster` says which applies to each Mac. After a -Darkbloom update, the cluster sets itself up again by itself ("Updating the -cluster setup after a Darkbloom update."). The leader checks for an update -every minute; while a Mac serves, those checks and any plan made then use the -speed it measured while idle and never run a GPU benchmark beside the model -([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +happens by itself; `darkbloom cluster` says which applies to each Mac. + +## Updating Darkbloom on the pair + +The Macs of a pair do not update by themselves. The cluster service runs with +automatic updates off, its parts run no updater, and the single-Mac provider, +whose updater keeps one Mac current, does not run beside the cluster. +Automatic updates for a pair are a follow-up. Until then, update by hand: + +1. On each Mac, run: + + ```bash + darkbloom update + ``` + + It installs the release. Its last line, "Restart the provider for the new + version to take effect.", does not apply here: no single-Mac provider runs on + a pair Mac. +2. Wait. The leader compares each Mac's installed cluster worker with the saved + setup every minute while the cluster serves. When one changed, it stops both + parts, plans the same model again and serves it from the new release + ("Updating the cluster setup after a Darkbloom update."). Its log, + `~/.darkbloom/cluster-setup/service.log`, says + `Darkbloom changed on the other Mac: setting the cluster up again for ` + (or this Mac, or both Macs). An update of the second Mac sets it up once more. + While a Mac serves, these checks and any plan made then use the speed it + measured while idle and never run a GPU benchmark beside the model + ([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +3. Log out and back in on each Mac, or restart it. The cluster service itself + keeps running the release it started with until it starts again, as it does + at login. ## When something is in the way @@ -548,6 +620,8 @@ and they must match. ## Not yet in this build +- A pair does not update itself: run `darkbloom update` on both Macs + ([updating Darkbloom on the pair](#updating-darkbloom-on-the-pair)). - The login agent and macOS's one Local Network approval need the signed Darkbloom.app ([always on](cluster-always-on.md)). - A setup with unequal tensor-parallel shares cannot register with the diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 4f18264fac..0aa1e29379 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -938,9 +938,16 @@ type computes every value: (`ClusterRuntimeApprovalFacts`). The hidden command `darkbloom cluster runtime-facts --app --model =` prints them in their canonical form; run the app's own CLI, so the declaration and the -records are that build's. No value is typed by hand. Only a build-pinned entry -needs these facts. A model approval names no runtime digest, and the provider -computes no facts for it ([model approvals](#model-approvals)). +records are that build's. With `--release-candidates ` (the release +lane) it describes every model the build lists from its environment's catalog +metadata (`ClusterRuntimeApprovalFacts.release`). One artifact can be two +registered models that only the manifest tells apart (production lists +`gemma-4-26b` and `gemma-4-26b-8bit` for one artifact): a catalog model ID +whose candidates the worker describes only as another registered model is that +model's, so it is left out and named on standard error. No value is typed by +hand. Only a build-pinned entry needs these facts. A model approval names no +runtime digest, and the provider computes no facts for it +([model approvals](#model-approvals)). | Field | Value | |---|---| @@ -1086,15 +1093,15 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Step | Rule | Source | |---|---|---| -| Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: production, staging) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | +| Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: staging, and production until its coordinator derives approvals from releases) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | | Match | The entry whose `model` is the setup's `publicModelID`, whose `schedule` is its prefill schedule (`1` serial, `2` one-chunk lookahead), and that is still current. A model approval matches when its `artifact_sha256` is the saved setup's `capability.artifactSHA256`; no runtime facts are computed for it. A build-pinned entry matches when its eight digests all equal this Mac's own cluster runtime facts (computed at most once per check from the helpers beside the setup's worker and the setup's model folder). Latest `not_after` first, across both shapes. An entry for another build or another copy of the model does not match | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift` (`select`) | | Check | On each Mac, against its own files: every digest of a build-pinned entry (`ClusterApprovalAttachment.mismatches`), or the artifact of a model approval (refusal: "the approval's artifact_sha256 differs from this Mac's setup"); the member's own start refusals (`requireLocalRankGranted`); the roster of this Mac's pairing (S17); `validate` below | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift` (`attachment`) | | Save | Both parts stop. The leader checks the entry, sends it to the other Mac over the cable (service command `approval`), and saves it only after the other Mac checked and saved it. A refusal on either Mac saves it on neither. Both parts then start as cluster members | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift` (`run`, `receive`) | | When | After the guided setup's Test stage passed (control operation `register`, run by the control leader: `OnboardingLive.localRegister`), once at each start of the control leader's cluster service and after an update re-adopted the setups (the re-adopted setups find the same model approval again, because it names no build), and every minute while a serving pair is offered or has its approval kept aside (`ClusterService.checkApproval`). A local-only cluster never asks (`ClusterApprovalSync.asks`) | as named | | Lifetime | A saved approval with more than `renewWithinSeconds = 86_400` left is kept. Within that day a later matching entry replaces it. An entry that the operator replaced under the same `id` (other bytes, for example a new `not_after`) is no longer the saved approval: a matching entry replaces it, else it is withdrawn (Serve locally). An ended one is removed: each Mac saves its setup without it before its part starts, and its part then serves on the leader's local API (`ClusterService.supervise`) | `ClusterApprovalLifetime.decide` | -| Serve locally | Both Macs save their setups without the approval, the other Mac first, and the pair serves on the leader's local API, when: no request gets an HTTP answer for the absence grace (`ClusterService.soloGraceSeconds`: 600 s; `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS` in a development build); the coordinator answers (a 404, or a list) without the saved approval as saved and serves no other matching entry; or either Mac's coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds = 3` times in a row right after starting (each Mac's status, `memberQuickEnds`; an end because the coordinator was out of reach is not counted). When either Mac cannot save, both keep the approval and the next check tries again. The leader keeps the approval, the reason and the setup's worker digest in its setup record (`approvalSetAside`, `runtimeBinarySHA256`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, only a later entry, or the same entry after an update installs another worker (a record without the worker digest keeps the same entry aside on every build) | `ClusterApprovalCheck.step`, `ClusterApprovalSync.serveLocally`; `ClusterService.checkApproval` | +| Serve locally | Both Macs save their setups without the approval, the other Mac first, and the pair serves on the leader's local API, when: no request gets an HTTP answer for the absence grace (`ClusterService.soloGraceSeconds`: 600 s; `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS` in a development build); the coordinator answers (a 404, or a list) without the saved approval as saved and serves no other matching entry; or either Mac's coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds = 3` times in a row right after starting (each Mac's status, `memberQuickEnds`). An end the coordinator decided is not counted: one because it was out of reach (`ClusterMemberControlError.coordinatorUnreachable`, which also starts the count again) or because it did not accept the member role in its negotiation window (`negotiationFailed`, which leaves the count as it is; a part that ran `quickEndSeconds = 120` or longer starts it again, as always) (`ClusterApprovalCheck.memberQuickEnds`). It complements a coordinator that ends each pair session before its shutdown closes the members' connections, which makes a deploy's ends cleaner; the rule still covers coordinators without that change, coordinator crashes and slow negotiation. When either Mac cannot save, both keep the approval and the next check tries again. The leader keeps the approval, the reason, the setup's worker digest and the time in its setup record (`approvalSetAside`, `runtimeBinarySHA256`, `setAt`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, a later entry at once, the same entry `ClusterApprovalFallback.failingSeconds = 3_600` after it was set aside, or the same entry after an update installs another worker. A record without `setAt` (an older build's) is past that bound | `ClusterApprovalCheck.step`, `ClusterApprovalSync.serveLocally`; `ClusterService.checkApproval` | | Both or neither | A send whose reply is lost may come after the other Mac saved: the leader gives it its setup back. Each Mac's status names its saved cluster approval (`approvalID`, `""` for none; a build without the field is unknown and never compared). On every check the leader compares it with its own; while they differ, it gives the other Mac its approval (while offered) or none, and saves its own setup without an approval it does not offer; when the other Mac refuses its approval, it saves its own setup without it too | `ClusterApprovalCheck.peerApprovalID`, `macsDiffer`, `ClusterApprovalSync.converge` | -| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files, so no part stops for an approval it refuses. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply` | +| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files and with every rule the save applies to the setup with the approval attached (`ClusterConfiguration.validate`, which refuses a saved `tensorAssistant` beside `nativeMember`: "Qwen's speculative assistant serves local clusters only …", `tensorAssistantServesLocally`), so no part stops and nothing is sent for an approval either Mac must refuse. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply`, `ClusterApprovalAttachment.attachment` | A coordinator that answers 404, serves no matching entry or serves only ended entries leaves both saved setups byte for byte as they were: nothing is sent @@ -1621,12 +1628,12 @@ For the existing `qwen35-dense-layer-stage` / `registered_qwen38_27b` / `registe ### Qwen27 TP assistant policy -Normal setup discovers the embedded assistant from the native quote; the saved fields below bind that decision through both workers' actual READY. +Normal setup discovers the embedded assistant from the native quote on a cluster that serves locally only; the saved fields below bind that decision through both workers' actual READY. The assistant's speculative decoding has no parity qualification, so a setup saved for coordinator pairing carries none; public speculative decoding for Qwen pairs needs qualification evidence of its own. | Setting | Bound and behavior | Source | |---|---|---| -| `[backend] mtp_mode` | Existing `auto`/`on` allow embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`); `off` retains the ordinary fully quoted target. Automatic discovery selects depth `3` and admitted-cohort verification. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `automaticCandidate`, `automaticDepth` | -| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy` | +| `[backend] mtp_mode` | Selects embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`) by how the cluster serves (`ClusterServingScope`): `auto` (default) discovers it for a cluster that serves locally only (`darkbloom cluster local`) and plans a cluster served through Darkbloom without it, as the re-plans after an update or a memory refusal do; `on` discovers it either way, and a cluster served through Darkbloom then is not offered to the coordinator (its public-traffic line says so, `ClusterPairOwnerServing.tensorAssistantNotOffered`); `off` retains the ordinary fully quoted target. Automatic discovery selects depth `3` and admitted-cohort verification. The developer six-step wizard and `darkbloom cluster plan` discover it as for a local cluster. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `discoveryMode`, `automaticCandidate`, `automaticDepth`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` (`OnboardingLive.localPlanModels`) | +| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. Never beside `nativeMember`: such a setup is refused when saved or loaded ("Qwen's speculative assistant serves local clusters only …"), and the leader refuses a coordinator's approval for it before any part stops. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy`; `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`tensorAssistantServesLocally`) | | Saved `tensorAssistant.verification` | `singleton_ready_set_v1` is the omitted legacy value; `admitted_target_cohort_v1` verifies eligible rows together up to the completely priced capacity. Unknown/null values are refused. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `Verification` | | Native worker `--mtp-depth`, `--tp-mtp-inventory-sha256`, `--tp-mtp-verification` | Installed launch arguments derived from saved policy, bilaterally bound at LOAD. Normal setup does not ask the user to choose them. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift`; `libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift` | | `DARKBLOOM_QWEN_MTP_SERIAL`, `DARKBLOOM_QWEN_MTP_DOUBLE_FORWARD`, `DARKBLOOM_QWEN_MTP_SHORTLIST` | True serial/double-forward overrides and any shortlist setting other than `0` conflict with this TP policy and are refused; complete vocabulary scores and captured target settlement remain authoritative. | `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPolicy.swift`, `require` | diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift index 5758b05c08..f09a2678b7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift @@ -94,32 +94,39 @@ final class GPTOSSPagedKVCache: KVCache { get { gathered() } set { precondition(newValue.count == 2 && newValue[0].dim(2) > 0) - let previousOffset = offset - let previousIndex = layout.index + let previous = layout let window = maxSize pages = []; shape = nil; layout = .init(window: window) _ = update(keys: newValue[0], values: newValue[1]) if window != nil { // Like RotatingKVCache, metadata restoration supplies position // separately. Preserve the old position until it is restored. - layout.restore(count: newValue[0].dim(2), offset: max(previousOffset, newValue[0].dim(2)), - index: min(previousIndex, newValue[0].dim(2))) + layout.restore(count: newValue[0].dim(2), offset: max(previous.offset, newValue[0].dim(2)), + index: min(previous.index, newValue[0].dim(2)), wrapped: previous.wrapped) } } } + /// Sliding pages write and restore exactly the metadata the pinned SDK's + /// ring writes in the same state (`GPTOSSSlidingRing`). var metaState: [String] { get { - if let window = maxSize { return ["0", String(window), "256", String(offset), String(layout.index)] } - return [""] + guard let window = maxSize else { return [""] } + guard let metadata = GPTOSSSlidingRing.metadata(window: window, + at: .init(offset: offset, index: layout.index, wrapped: layout.wrapped)) else { + preconditionFailure("The pinned SDK writes another sliding-ring metadata layout") + } + return metadata } set { guard let window = maxSize else { precondition(newValue == [""]); return } - precondition(newValue.count == 5 && newValue[0] == "0" && Int(newValue[1]) == window - && Int(newValue[2]) == 256) - layout.restore(count: layout.count, offset: Int(newValue[3])!, index: Int(newValue[4])!) + guard let position = GPTOSSSlidingRing.position(of: newValue, window: window, rows: layout.count) else { + preconditionFailure("GPT-OSS sliding pages restore only the SDK ring's metadata for their rows") + } + layout.restore(count: layout.count, offset: position.offset, index: position.index, + wrapped: position.wrapped) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift new file mode 100644 index 0000000000..9b9ccc3250 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift @@ -0,0 +1,41 @@ +import MLXLMCommon + +/// The metadata (`RotatingKVCache.metaState`) of GPT-OSS's sliding-window +/// ring, `RotatingKVCache(maxSize: window)` (`makeSlidingWindowKVCache`), in +/// the layout the pinned SDK writes: keep, window, step, offset, write index, +/// capacity origin and whether the ring has wrapped. Writes move only the +/// offset, the index and the flag. The ring's state holds its first `index` +/// rows, or the whole window once wrapped. +enum GPTOSSSlidingRing { + struct Position: Equatable { + let offset: Int, index: Int, wrapped: Bool + } + + private static let offsetField = 3, indexField = 4, wrappedField = 6 + + /// The metadata of a ring of `window` positions at `position`; nil when a + /// fresh ring writes another layout. + static func metadata(window: Int, at position: Position) -> [String]? { + var fields = RotatingKVCache(maxSize: window).metaState + guard fields.count == 7, fields[offsetField] == "0", fields[indexField] == "0", + fields[wrappedField] == "false" else { return nil } + fields[offsetField] = String(position.offset); fields[indexField] = String(position.index) + fields[wrappedField] = String(position.wrapped) + return fields + } + + /// The position `metadata` gives a ring of `window` positions holding + /// `rows` rows; nil unless that ring writes exactly this metadata and + /// pages can continue it. Pages cap masks and trims by the offset, so an + /// unwrapped ring that has evicted rows must still hold at least + /// window - 1 rows; the SDK's trim after eviction can leave fewer. + static func position(of metadata: [String], window: Int, rows: Int) -> Position? { + guard metadata.count > wrappedField, let offset = Int(metadata[offsetField]), + let index = Int(metadata[indexField]), let wrapped = Bool(metadata[wrappedField]) else { return nil } + let position = Position(offset: offset, index: index, wrapped: wrapped) + guard metadata == Self.metadata(window: window, at: position), offset >= rows, + wrapped ? rows == window && index >= 0 && index <= rows + : index == rows && (offset == rows || rows >= window - 1) else { return nil } + return position + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift index 85968beff6..c514e925e7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift @@ -10,6 +10,9 @@ struct GPTOSSPagedKVLayout: Equatable { private(set) var offset = 0 private(set) var count = 0 private(set) var index = 0 + /// RotatingKVCache's wrapped flag: a one-token write that rotates sets it; + /// a chunk or a trim clears it. + private(set) var wrapped = false struct Update: Equatable { /// Nil keeps the existing pages. Otherwise these old physical rows @@ -45,7 +48,7 @@ struct GPTOSSPagedKVLayout: Equatable { return kept.isEmpty ? nil : kept } let kept = ranges.reduce(0) { $0 + $1.count } - count = kept + n; index = count + count = kept + n; index = count; wrapped = false return .init(retained: ranges, writeOffset: kept, count: count) } var retained: [Range]? @@ -53,7 +56,7 @@ struct GPTOSSPagedKVLayout: Equatable { retained = [(count - window).. Int { guard isTrimmable else { return 0 } let removed = min(offset, max(0, n)) - offset -= removed; count = offset; index = offset + offset -= removed; count = offset; index = offset; wrapped = false return removed } - mutating func restore(count: Int, offset: Int, index: Int) { + mutating func restore(count: Int, offset: Int, index: Int, wrapped: Bool) { precondition(count >= 0 && offset >= count && index >= 0 && index <= count) - self.count = count; self.offset = offset; self.index = index + self.count = count; self.offset = offset; self.index = index; self.wrapped = wrapped } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift index 5d5d7a9ba2..86b8ac821f 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift @@ -129,6 +129,103 @@ struct GPTOSSPagedKVTests { } } + @Test func slidingPagesRestoreOnlyTheSDKRingsMetadataForTheirRows() { + Device.withDefaultDevice(.cpu) { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + var checked = 0 + // Short, chunked past the window, wrapped, wrapped back to its end, chunked again. + for (step, count) in ([3, 1, 512] + Array(repeating: 1, count: 128) + [2]).enumerated() { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + guard [0, 2, 3, 130, 131].contains(step) else { continue } + let metadata = ring.metaState, held = ring.state[0].dim(2) + guard let position = GPTOSSSlidingRing.position(of: metadata, window: 128, rows: held) else { + Issue.record("The SDK ring's own metadata \(metadata) was refused"); continue + } + checked += 1 + #expect(GPTOSSSlidingRing.metadata(window: 128, at: position) == metadata) + #expect(GPTOSSSlidingRing.position(of: metadata, window: 128, rows: held - 1) == nil) + #expect(GPTOSSSlidingRing.position(of: metadata, window: 64, rows: held) == nil) + func replacing(_ field: Int, _ value: String) -> [String] { + var fields = metadata; fields[field] = value; return fields + } + // Legacy, rewind reserve, kept prefix, other step, requested origin, non-canonical offset, + // fewer positions than rows. + for refused in [Array(metadata.prefix(5)), metadata + ["2"], replacing(0, "1"), replacing(2, "64"), + replacing(5, "requested"), replacing(3, "+\(position.offset)"), + replacing(3, String(held - 1))] { + #expect(GPTOSSSlidingRing.position(of: refused, window: 128, rows: held) == nil) + } + // A flipped flag claims other rows, except at a full window's end. + if position.index != held || held != 128 { + #expect(GPTOSSSlidingRing.position(of: replacing(6, String(!position.wrapped)), + window: 128, rows: held) == nil) + } + } + #expect(checked == 5) + } + } + + /// Restores pages from the SDK ring's own state and metadata, then checks + /// they continue exactly as a copy of that ring. + private func expectRestoredPagesContinue(_ ring: RotatingKVCache) { + guard GPTOSSSlidingRing.position(of: ring.metaState, window: 128, rows: ring.state[0].dim(2)) != nil else { + Issue.record("Pages refused the SDK ring's metadata \(ring.metaState)"); return + } + let pages = GPTOSSPagedKVCache(window: 128), expected = ring.copy() + pages.state = ring.state; pages.metaState = ring.metaState + #expect(pages.metaState == ring.metaState) + for n in [1, 2, 1] { + for returnArray in [false, true] { + equalMask(pages.makeMask(n: n, windowSize: 128, returnArray: returnArray), + expected.makeMask(n: n, windowSize: 128, returnArray: returnArray)) + } + let next = rows(n, start: expected.offset) + let a = pages.update(keys: next.0, values: next.1) + let b = expected.update(keys: next.0, values: next.1) + equal(a.0, b.0); equal(a.1, b.1) + #expect(pages.offset == expected.offset && pages.isTrimmable == expected.isTrimmable + && pages.metaState == expected.metaState) + } + } + + @Test func slidingPagesRestoredFromTheSDKRingContinueAsThatRing() { + Device.withDefaultDevice(.cpu) { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + var restored = 0 + // Short, full, wrapped, chunked past the window, wrapped back to its end, chunked again. + for (step, count) in ([3, 1, 124, 1, 512] + Array(repeating: 1, count: 128) + [2]).enumerated() { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + guard [0, 2, 3, 4, 132, 133].contains(step) else { continue } + expectRestoredPagesContinue(ring) + restored += 1 + } + #expect(restored == 6) + } + } + + @Test func aRingTrimmedAfterEvictionRestoresOnlyWithWindowMinusOneRows() { + Device.withDefaultDevice(.cpu) { + func ring(_ counts: [Int]) -> RotatingKVCache { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + for count in counts { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + } + return ring + } + // Pages cap masks and trims by the offset; the ring caps them by the rows it holds. + let evicted = ring([300, 2]), wrapped = ring([129, 1]) + #expect(evicted.trim(2) == 2 && evicted.state[0].dim(2) == 127 && evicted.offset == 300) + expectRestoredPagesContinue(evicted) + for (trimmed, count, held) in [(evicted, 1, 126), (evicted, 97, 29), (wrapped, 80, 48)] { + #expect(trimmed.trim(count) == count && trimmed.state[0].dim(2) == held) + #expect(GPTOSSSlidingRing.position(of: trimmed.metaState, window: 128, rows: held) == nil) + } + } + } + @Test func slidingPagesStayBoundedAndRequestRetirementDropsEveryOwner() { Device.withDefaultDevice(.cpu) { weak var released: GPTOSSPagedKVCache? diff --git a/provider-swift/Package.swift b/provider-swift/Package.swift index e04193d90d..c8be5b8a35 100644 --- a/provider-swift/Package.swift +++ b/provider-swift/Package.swift @@ -8,7 +8,7 @@ import Foundation // DARKBLOOM_RELEASE_ENVIRONMENT. On the dev branch every other build is dev: // it talks to the DevNet coordinator. On master it is prod. let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" + .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" precondition(["prod", "dev", "staging"].contains(releaseEnvironment), "DARKBLOOM_RELEASE_ENVIRONMENT must be prod, dev or staging") let buildEnvironmentSwiftSettings: [SwiftSetting] diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift index 9470e84406..eb481decf4 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift @@ -104,6 +104,14 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { /// run different Darkbloom builds); the onboarding says it in plain words (`ClusterSetupPlanning.differentBuilds`). static let peerBuildDiffers = "Peer native build differs from the capability" + /// The refusal of a tensor assistant beside `nativeMember`. Its speculative decoding has no parity qualification, + /// so it serves local clusters only; the guided setup plans a cluster served through Darkbloom without it under + /// `auto` (`ClusterPlacementTensorAssistantSelection.discoveryMode`). The leader's check of a coordinator's + /// approval runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach + /// the leader whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). + static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only (not qualified for " + + "public traffic); with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" + func validate(capability: ClusterRuntimeCapability, rawCapabilitySHA256: String) throws { func require(_ value: Bool, _ message: String) throws { guard value else { throw ClusterConfigurationError.invalid(message) } @@ -161,8 +169,9 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { try require(ClusterQwenTensorAssistantPolicy.runtimeModelIDs.contains(capability.runtimeModelID) && capability.adapterID == ClusterRuntimeAdapter.qwen35Dense.rawValue && selectedGenerationMode == .tensorParallel && selectedPrefillSchedule == .serial - && !capability.hasPrivateImages && nativeMember == nil, - "A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup") + && !capability.hasPrivateImages, + "A tensor assistant requires Qwen TP on a row with an inline head and serial prefill") + try require(nativeMember == nil, Self.tensorAssistantServesLocally) } try require(ClusterConfigurationSyntax.ipv4(coordinator.address) && (1...65535).contains(coordinator.port), "Invalid JACCL coordinator address") if let linkControl { diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift index 412a58fcd6..8e43fc4489 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift @@ -39,45 +39,54 @@ extension ClusterRuntimeApprovalFacts { /// The facts a release registers. For every model in `models` and every /// catalog model ID among the candidates of its artifact (a member may have /// installed the artifact under any of them), the first candidate the - /// worker describes as that model. Candidates of an artifact not in - /// `models` are never described, and a listed model with no candidate is - /// left out: the environment's catalog does not have it, and the fetch - /// step names it. Each candidate's catalog entry gives a declared model's - /// request envelope its media. Fails naming every catalog model ID that has - /// no candidate the worker describes as the listed model, and when no - /// model is left. + /// worker describes as that model. One artifact can be two registered + /// models, told apart by the manifest (`gemma-4-26b` and `gemma-4-26b-8bit`): + /// a catalog model ID whose candidates the worker describes only as another + /// registered model is that model's, so it is left out and named through + /// `note`. Candidates of an artifact not in `models` are never described, + /// and a listed model with no candidate is left out: the environment's + /// catalog does not have it, and the fetch step names it. Each candidate's + /// catalog entry gives a declared model's request envelope its media. Fails + /// naming every catalog model ID of which the worker describes no candidate + /// at all, and when no model is left (naming what was left out). public static func release(installation: Installation, candidates: [ModelFiles], models: [ReleaseModel] = ClusterRuntimeApprovalFacts.releaseModels, publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, - decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions) throws -> Self { + decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions, + note: (String) -> Void = { _ in }) throws -> Self { let installed = try HashedInstallation(installation) let parsed = try candidates.map { ($0, try catalogArtifact($0)) } - var entries: [Model] = [], failures: [String] = [] + var entries: [Model] = [], failures: [String] = [], leftOut: [String] = [] for listed in models { let ofArtifact = parsed.filter { $0.1.aggregateSHA256 == listed.artifactSHA256 } var catalogIDs: [String] = [] for (_, artifact) in ofArtifact where !catalogIDs.contains(artifact.modelID) { catalogIDs.append(artifact.modelID) } for catalogID in catalogIDs { - var refusals: [String] = [], chosen: Model? + var refusals: [String] = [], chosen: Model?, describedAsAnother = false for (files, artifact) in ofArtifact where artifact.modelID == catalogID { do { let described = try installed.describe(files, publicModels: publicModels, decisions: decisions) if described.runtimeModelID == listed.runtimeModelID { chosen = described.entry; break } + describedAsAnother = true refusals.append("\(files.manifest.path) is \(described.runtimeModelID)") } catch { refusals.append("\(files.manifest.path): \(error)") } } + let reasons = "\(catalogID) (\(listed.runtimeModelID), \(listed.artifactSHA256)): " + refusals.joined(separator: "; ") if let chosen { entries.append(chosen) } - else { failures.append("\(catalogID) (\(listed.runtimeModelID), \(listed.artifactSHA256)): " + refusals.joined(separator: "; ")) } + else if describedAsAnother { leftOut.append("left out, the catalog model ID of another registered model: " + reasons) } + else { failures.append(reasons) } } } guard failures.isEmpty else { throw ClusterConfigurationError.invalid("Qualified cluster models the release cannot describe: " + failures.joined(separator: " | ")) } guard !entries.isEmpty else { - throw ClusterConfigurationError.invalid("No candidate folder holds a model this build qualifies on a cluster") + throw ClusterConfigurationError.invalid("No candidate folder holds a model this build qualifies on a cluster" + + leftOut.map { "; \($0)" }.joined()) } + leftOut.forEach(note) return try installed.facts(entries) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift index b4fade5d30..be47f2ab48 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift @@ -42,6 +42,9 @@ extension ClusterSetupOperations { /// An explicit test/qualification override. Normal setup discovers the /// catalog model's embedded assistant and pins the native quote. public var tensorAssistants: [String: ClusterQwenTensorAssistantPolicy] = [:] + /// How this run of `darkbloom cluster` was asked to serve (`darkbloom cluster local`); nil keeps the scope + /// the setup record saved. The onboarding plans for it (`OnboardingLive.planningScope`). + public var servingScope: ClusterServingScope? = nil public var privateImageQualification: Bool { privateMiMoImageQualification || privateGLMImageQualification } public init(providerConfiguration: URL, darkbloomExecutable: URL, sessionArguments: [String], @@ -517,8 +520,10 @@ final class LiveContext: @unchecked Sendable { // MARK: - Planning /// `keeping`: the mode each model id keeps when it is planned again after a Darkbloom update (the service's - /// re-plan), as `ClusterSetupPlanning.decide` takes it; empty for every other plan. - func plan(peer: ClusterSetupReport, keeping: [String: ClusterGenerationMode] = [:]) -> ClusterSetupPlansResult { + /// re-plan), as `ClusterSetupPlanning.decide` takes it; empty for every other plan. `coordinator`: the setup will + /// serve through the coordinator (the onboarding's public scope); the six-step wizard's local sessions leave it off. + func plan(peer: ClusterSetupReport, keeping: [String: ClusterGenerationMode] = [:], + coordinator: Bool = false) -> ClusterSetupPlansResult { let input = pairInput() guard let description = input.description, let memberID = input.pair?.memberID, let local = description.members.first(where: { $0.id == memberID }) else { @@ -555,6 +560,9 @@ final class LiveContext: @unchecked Sendable { let mtpMode: MTPMode do { mtpMode = try ConfigManager.loadOrDefaults(from: settings.providerConfiguration).backend.mtpMode } catch { return .failed("The provider configuration could not be read: \(clean(ClusterConsoleText.bounded(error)))") } + // A setup that serves through the coordinator carries no speculative assistant: under `auto` its plan quotes + // the ordinary target only. + let discovery = ClusterPlacementTensorAssistantSelection.discoveryMode(mtpMode, coordinator: coordinator) let readings = models.filter { settings.privateGLMImageQualification ? ClusterGLMOnboardingSelection.accepts($0) : ClusterMiMoOnboardingSelection.accepts($0, qualifying: settings.privateMiMoImageQualification) @@ -607,14 +615,14 @@ final class LiveContext: @unchecked Sendable { } else { let discovered = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: mtpMode, chunkTokens: chunk, deadline: deadline()) + mode: discovery, chunkTokens: chunk, deadline: deadline()) assistantQuote = discovered.map { .success($0) } // Capacity changes keep the shares, so the first widening's complete // quote steers the initial split; without it the choice is speed-only. if discovered != nil { discoveredWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: mtpMode, chunkTokens: chunk, deadline: deadline(), lanes: 2) + mode: discovery, chunkTokens: chunk, deadline: deadline(), lanes: 2) } // Only a discovered assistant may give way to the ordinary target (`assistantOrTarget`). if discovered?.assistant != nil { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift index 5b283848fe..111da1b1df 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift @@ -180,7 +180,8 @@ enum ClusterSetupPlanning { var plan = summary(decided.result, chosen: chosen, lines: decided.lines, localMemberID: localMemberID, profiles: [localMemberID: localProfile, peerID: peerProfile]) plan.publicTraffic = ClusterPairServingGrants.publicTrafficLine(runtimeModelID: capability.record.runtimeModelID, - artifactSHA256: capability.record.artifactSHA256, mode: chosen.mode) + artifactSHA256: capability.record.artifactSHA256, mode: chosen.mode, + tensorAssistant: assistantQuote?.assistant != nil && chosen.mode == .tensorParallel) return .init(option: .init(model: reading.model, onOtherMac: onOther, blocker: nil, plan: plan), setup: decided.setup, capability: (capability.data, capability.sha256)) } catch is ClusterPairServingRefusal { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index 161f42053d..6314ae9957 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -97,16 +97,21 @@ public struct ClusterSetupRecord: Codable, Sendable, Equatable { public var approvalSetAside: ApprovalSetAside? = nil /// The cluster approval both Macs saved their setups without, and why (`ClusterApprovalCheck`): the leader checks - /// the coordinator every minute while it is set, and does not take an approval its parts kept failing with again. + /// the coordinator every minute while it is set, and does not take an approval its parts kept failing with again + /// for `ClusterApprovalFallback.failingSeconds`. public struct ApprovalSetAside: Codable, Sendable, Equatable { public var approval: ClusterRuntimeApproval public var reason: ClusterApprovalFallback /// The setup's worker digest (`capability.runtimeBinarySHA256`) when the approval was set aside: an approval /// its parts kept failing with is not taken again by the same build, but a model approval, which names no - /// build, is taken again after an update. Nil in a record from an older build: its `id` alone is not taken. + /// build, is taken again after an update. Nil in a record from an older build, which names no `setAt` either. public var runtimeBinarySHA256: String? - public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback, runtimeBinarySHA256: String? = nil) { - self.approval = approval; self.reason = reason; self.runtimeBinarySHA256 = runtimeBinarySHA256 + /// When the approval was set aside (wall-clock seconds since 1970): one its parts kept failing with is taken + /// again `ClusterApprovalFallback.failingSeconds` later. Nil in a record from an older build, which is past it. + public var setAt: Double? + public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback, runtimeBinarySHA256: String? = nil, + setAt: Double? = nil) { + self.approval = approval; self.reason = reason; self.runtimeBinarySHA256 = runtimeBinarySHA256; self.setAt = setAt } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift index 14495aff1b..5fba413b74 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift @@ -660,14 +660,17 @@ public enum ClusterPairServingGrants { /// The one line a plan or the onboarding shows about public traffic for a /// model served in `mode`: qualified in the families its records grant or - /// the owner declared public (`ClusterPublicModels`). + /// the owner declared public (`ClusterPublicModels`), unless the placement + /// decodes with Qwen's speculative assistant (`tensorAssistant`), which no + /// qualification covers. public static func publicTrafficLine(runtimeModelID: String, artifactSHA256: String? = nil, mode: ClusterGenerationMode?, - decisions: ClusterPairServingDecisions = decisions, + tensorAssistant: Bool = false, decisions: ClusterPairServingDecisions = decisions, publicModels: [ClusterPublicModel] = ClusterPublicModels.declared) -> String { let grant = try? grant(runtimeModelID: runtimeModelID, publicModelID: runtimeModelID, artifactSHA256: artifactSHA256, decisions: decisions) return ClusterPairOwnerServing.publicTrafficLine(grant: grant, declared: ClusterPublicModels.families( - runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, in: publicModels), mode: mode) + runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, in: publicModels), mode: mode, + tensorAssistant: tensorAssistant) } /// One rank of a placement, checked on the Mac that runs it with that @@ -782,6 +785,11 @@ public enum ClusterPairServingGrants { public struct ClusterPairOwnerServing: Sendable, Equatable { /// The one line shown for a model or placement with no public grant. public static let notYetQualified = "not yet qualified for public traffic" + /// The one line shown for a placement of a qualified model and mode that decodes with Qwen's speculative + /// assistant: the assistant serves local clusters only, so the setup is never offered to the coordinator + /// (`ClusterConfiguration.tensorAssistantServesLocally`). + public static let tensorAssistantNotOffered = "not offered for public traffic: it decodes with Qwen's speculative " + + "assistant, which serves local clusters only (with [backend] mtp_mode \"auto\", a cluster served through Darkbloom is planned without it)" public let runtimeModelID: String /// The records' public grant; nil when no passing record of the installed @@ -808,11 +816,12 @@ public struct ClusterPairOwnerServing: Sendable, Equatable { } static func publicTrafficLine(grant: ClusterPairServingGrant?, declared: [ClusterPairServingModeFamily], - mode: ClusterGenerationMode?) -> String { + mode: ClusterGenerationMode?, tensorAssistant: Bool = false) -> String { let families = Set((grant?.families ?? []) + declared).sorted() guard !families.isEmpty, mode.map({ families.contains($0.servingFamily) }) ?? true else { return notYetQualified } + guard !tensorAssistant else { return tensorAssistantNotOffered } let named = (mode.map { [$0.servingFamily] } ?? families).map(\.description).joined(separator: " and ") return "qualified for public traffic in \(named) mode (the coordinator's parity qualification decides each placement)" } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift index ae8e63ce6d..76dd399aba 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift @@ -8,8 +8,8 @@ import DarkbloomClusterSecurity /// saves the setup without one. Nothing another Mac or a file says is taken on trust: a build-pinned approval's digests /// must be this Mac's cluster runtime facts (`ClusterRuntimeApprovalFacts`, every digest of the release's block), a /// model approval's artifact must be the saved setup's (the member takes the runtime from its own setup), the roster -/// must be the one this Mac countersigned when it paired (S17), and the saved setup's own checks -/// (`ClusterNativeMemberAttachment.validate`) run as at every load. +/// must be the one this Mac countersigned when it paired (S17), and the saved setup's own checks with the approval +/// attached (`ClusterConfiguration.validate`, which runs `ClusterNativeMemberAttachment.validate`) run as at every load. enum ClusterApprovalAttachment { /// The block digests of a build-pinned `approval` that are not this Mac's facts, by their contract names; `model` /// when the facts describe no entry for the approval's model. A model approval is never compared with facts. @@ -131,9 +131,12 @@ enum ClusterApprovalAttachment { let attachment = ClusterNativeMemberAttachment(ownerSHA256: owner, metallibPath: tools.metallib.path, resourceLibraryPath: tools.resourceLibrary.path, clusterApproval: approval, roster: paired.roster, memberPins: paired.pins, edges: edge.map { [$0] }) - // The saved setup's own checks, as at every load: the approval names this setup's model, artifact and schedule - // (and a build-pinned one its runtime, capability and profile), and the roster's pins are its members in rank order. - try attachment.validate(configuration: configuration.replacingNativeMember(attachment), capability: saved.capability) + // Every check the save runs on the setup with the attachment, as at every load: the approval names this setup's + // model, artifact and schedule (and a build-pinned one its runtime, capability and profile), the roster's pins + // are its members in rank order, and nothing the setup carries is refused beside an approval (a tensor + // assistant serves local clusters only). So no part stops for an approval either Mac must refuse at the save. + try configuration.replacingNativeMember(attachment).validate(capability: saved.capability, + rawCapabilitySHA256: configuration.capabilitySHA256) return attachment } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift index c6ee9cc525..04b5e8b75b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift @@ -7,10 +7,14 @@ public enum ClusterApprovalFallback: String, Codable, Equatable, Sendable { /// The coordinator answers (404, or a list without the saved approval) and serves no other matching entry. case withdrawn /// The coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds` times in a row right after - /// starting with the approval (the rule for a solo server that keeps ending). The approval itself is not taken - /// again; a later matching one is. + /// starting with the approval (the rule for a solo server that keeps ending; `ClusterApprovalCheck.memberQuickEnds`). + /// The approval itself is taken again `failingSeconds` after it was set aside; a later matching one at once. case failing + /// How long the same build does not take an approval set aside as `failing` again. Meanwhile each Mac's part that + /// serves locally starts its count of quick ends again (`ClusterService`), so the approval comes back with none. + public static let failingSeconds: Double = 3_600 + /// The one line for the screen, the log and the status. func line(_ approval: ClusterRuntimeApproval, grace: Double) -> String { switch self { @@ -22,8 +26,8 @@ public enum ClusterApprovalFallback: String, Codable, Equatable, Sendable { + "until it lists a matching one again" case .failing: return "The coordinator-paired parts ended \(ClusterControlSoloAdmission.maximumQuickEnds) times in a row right after " - + "starting with cluster approval \(approval.id): the pair serves on the leader's local API until the " - + "coordinator lists a later one" + + "starting with cluster approval \(approval.id): the pair serves on the leader's local API for " + + "\(Int(Self.failingSeconds / 60)) minutes, then it is offered again with it, or sooner with a later one the coordinator lists" } } } @@ -121,10 +125,13 @@ enum ClusterApprovalCheck { watch.unreachableSince = nil guard answered else { return .keep } // Not offered now: the first matching entry, or one listed again for a pair that serves locally. An approval its - // parts kept failing with is not taken again by the same build (by any build for a record without one). + // parts kept failing with is not taken again by the same build (by any build for a record without one) for + // `ClusterApprovalFallback.failingSeconds` after it was set aside. A record from an older build names no time + // and is past that bound, as is one whose time lies ahead of a clock that was set back. var answer = fetched if let setAside, setAside.reason == .failing, setAside.runtimeBinarySHA256.map({ $0 == saved.capability.runtimeBinarySHA256 }) ?? true, + let setAt = setAside.setAt, (0.. Int { if lastError?.contains(unreachableMemberEnd) == true { return 0 } + if lastError?.contains(notAcceptedMemberEnd) == true, ranSeconds < ClusterControlSoloAdmission.quickEndSeconds { return count } return ClusterControlSoloAdmission.quickEnds(after: count, ranSeconds: ranSeconds) } /// How a member's error line starts when its registration wait never reached the coordinator. static let unreachableMemberEnd = String(ClusterMemberControlError.coordinatorUnreachable.rawValue.prefix(40)) + /// A member's error line when the coordinator kept its registration open past the negotiation window without an + /// acknowledgement that fits it. + static let notAcceptedMemberEnd = ClusterMemberControlError.negotiationFailed.rawValue + + /// What the leader keeps once both Macs applied `step` (`ClusterSetupRecord.approvalSetAside`): the approval a + /// fallback set aside, with the saved setup's worker digest and the wall-clock seconds it was set aside at; nil for + /// any other step. + static func setAside(by step: Step, worker: String, now: Double) -> ClusterSetupRecord.ApprovalSetAside? { + guard case .serveLocally(let approval, let reason) = step else { return nil } + return .init(approval: approval, reason: reason, runtimeBinarySHA256: worker, setAt: now) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index b38f593264..0c36b8ddce 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -269,11 +269,11 @@ final class OnboardingLive: @unchecked Sendable { case .failure(let failure): return .init(lines: failure.lines, failed: true, leaderID: leaderID) } case .planModels: - switch localPlanModels() { + switch localPlanModels(scope: request.scope) { case .success(let choices): return .init(lines: [], failed: false, leaderID: leaderID, choices: choices) case .failure(let failure): return .init(lines: failure.lines, failed: true, leaderID: leaderID) } - case .adopt: return lines(localAdopt(request.index ?? -1, model: request.model)) + case .adopt: return lines(localAdopt(request.index ?? -1, model: request.model, scope: request.scope)) case .serve: return lines(localServe()) case .stop: return lines(localStop()) case .readiness: @@ -597,14 +597,23 @@ final class OnboardingLive: @unchecked Sendable { } func planModels() -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { - let result = routed(.init(op: .planModels), seconds: 240, acting: false, local: { localPlanModels() }) { $0.choices ?? [] } + let request = ClusterControlRequest(op: .planModels, scope: context.settings.servingScope) + let result = routed(request, seconds: 240, acting: false, local: { localPlanModels() }) { $0.choices ?? [] } if case .success(let listed) = result { lock.withLock { listedChoices = listed } } return result } + /// How the cluster will serve the setup being planned: the way a forwarded command names, else the one this run + /// was asked for (`darkbloom cluster local`), else the one saved on this Mac. A cluster served through Darkbloom + /// is planned for its coordinator (`ClusterPlacementTensorAssistantSelection.discoveryMode`). + func planningScope(_ named: ClusterServingScope? = nil) -> ClusterServingScope { + named ?? context.settings.servingScope ?? leadership?.scope ?? .publicServing + } + /// `keeping`: the mode each model id keeps (`LiveContext.plan`); the service's re-plan after an update passes the - /// mode the pair served the model in. - func localPlanModels(keeping: [String: ClusterGenerationMode] = [:]) -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { + /// mode the pair served the model in. `scope`: the way of serving a forwarded command names (`planningScope`). + func localPlanModels(keeping: [String: ClusterGenerationMode] = [:], + scope: ClusterServingScope? = nil) -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { // The plan judges each Mac by the memory its report sampled. A report taken before this Mac stopped the // cluster's parts still counts the other Mac's old part (the re-plan after an update stops them first): // ask again, so both Macs are priced with that memory given back. 2026-10-22: the other Mac's report was @@ -621,7 +630,7 @@ final class OnboardingLive: @unchecked Sendable { // Folders copied over the cable (no receipt on this Mac) are repaired before the plan describes them. ClusterProductModelStore.updateClusterStore(store, providerConfiguration: settings.service.wizard.providerConfiguration, accepts: context.workerAcceptsManifest) - switch context.plan(peer: peer, keeping: keeping) { + switch context.plan(peer: peer, keeping: keeping, coordinator: !planningScope(scope).isLocalOnly) { case .failed(let reason): return .failure(.init("Planning failed: \(reason)")) case .ready(let options): let localName = ClusterPairingProvider.displayName(chipName: context.snapshot().local.mac.chip) @@ -1036,16 +1045,18 @@ final class OnboardingLive: @unchecked Sendable { let model = lock.withLock { listedChoices.indices.contains(index) ? (listedChoices[index].modelID ?? listedChoices[index].title) : nil } // The leader may stop both parts (up to 5 minutes to drain), wait for their memory (`releaseWaitSeconds`), plan // again and retry the device lease: the reply can take that long. - return routed(.init(op: .adopt, index: index, model: model), seconds: 600, acting: true, local: { localAdopt(index) }) { $0.lines } + let request = ClusterControlRequest(op: .adopt, index: index, model: model, scope: context.settings.servingScope) + return routed(request, seconds: 600, acting: true, local: { localAdopt(index) }) { $0.lines } } /// `model`: the id of the model the list showed at `index` (a choice forwarded from another Mac). When this Mac's /// list is gone (its service restarted) or no longer shows that model there, it plans again and adopts it by id. - func localAdopt(_ index: Int, model: String? = nil) -> Result<[String], ClusterOnboardingFailure> { + /// `scope`: the way of serving the forwarded choice was listed for; every plan made here follows it. + func localAdopt(_ index: Int, model: String? = nil, scope: ClusterServingScope? = nil) -> Result<[String], ClusterOnboardingFailure> { var index = index if let model, lock.withLock({ !choices.indices.contains(index) || choices[index].title != model }) { if case .failure(let failure) = localReachMembers({ _ in }) { return .failure(failure) } - if case .failure(let failure) = localPlanModels() { return .failure(failure) } + if case .failure(let failure) = localPlanModels(scope: scope) { return .failure(failure) } guard let found = lock.withLock({ choices.firstIndex { $0.title == model } }) else { return .failure(.init("\(model) is not offered on these Macs any more; run `darkbloom cluster` again to choose.")) } @@ -1070,7 +1081,7 @@ final class OnboardingLive: @unchecked Sendable { // plan stands (a failed plan replaces neither `choices` nor the decisions `context.adopt` reads): it was // priced with less memory than there is now. awaitReleased() - if case .success(let replanned) = localPlanModels() { + if case .success(let replanned) = localPlanModels(scope: scope) { // `localPlanModels` set `choices` in the order of the list it returned. Both are read under one lock, // and the entry must still name the chosen model: a plan forwarded from the other Mac may replace // `choices` meanwhile. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index cf6dfb574b..980bc6cf43 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -1128,8 +1128,9 @@ public final class ClusterService: @unchecked Sendable { try? self.store.updateRecord { stored in if let note = result.note { stored.approvalNote = note } // The approval set aside is kept while the pair serves locally and dropped once one is saved again. - if case .serveLocally(let approval, let reason) = step, result.changed { - stored.approvalSetAside = .init(approval: approval, reason: reason, runtimeBinarySHA256: decided.worker) + if result.changed, let setAside = ClusterApprovalCheck.setAside(by: step, worker: decided.worker, + now: Date().timeIntervalSince1970) { + stored.approvalSetAside = setAside } if case .save = step, result.changed { stored.approvalSetAside = nil } } @@ -1297,7 +1298,8 @@ public final class ClusterService: @unchecked Sendable { nextStart = Date().addingTimeInterval(ran >= 120 ? 3 : backoff) } // A coordinator-paired part that keeps ending right after its start makes the leader serve locally - // (`ClusterApprovalCheck.step`); an end because the coordinator was out of reach is not counted. + // (`ClusterApprovalCheck.step`); an end the coordinator decided (out of reach, or the member role not + // accepted in time) is not counted. if lock.withLock({ childIsMember }) { let lastError = Self.lastError(in: serviceFiles.rankLog, from: lock.withLock { childLogOffset }) lock.withLock { memberQuickEnds = ClusterApprovalCheck.memberQuickEnds(after: memberQuickEnds, ranSeconds: ran, lastError: lastError) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index bdf2cb521b..4464993892 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -308,9 +308,12 @@ public enum ClusterPlacementFlow { + "(\(records.restrictedFamilies.sorted().map(\.description).joined(separator: ", ")) modes): \(records.failedShapesText). " + "Those exact shapes are not planned; every other placement is, on any Macs.") } - // Public traffic in one line (owner serving never waits for it): the coordinator's parity qualification decides. + // Public traffic in one line (owner serving never waits for it): the coordinator's parity qualification decides, + // and a setup that decodes with Qwen's speculative assistant is never offered to it. + let assistant = (batchScope?.tensorParallelQuote ?? tensorAssistantQuote)?.assistant let publicLine = ClusterPairServingGrants.publicTrafficLine(runtimeModelID: capability.runtimeModelID, - artifactSHA256: capability.artifactSHA256, mode: result.chosen?.mode) + artifactSHA256: capability.artifactSHA256, mode: result.chosen?.mode, + tensorAssistant: assistant != nil && result.chosen?.mode == .tensorParallel) lines.append("Public traffic") lines.append(" " + publicLine.prefix(1).uppercased() + publicLine.dropFirst() + ".") var setup: ClusterPlacementSetup? @@ -327,8 +330,7 @@ public enum ClusterPlacementFlow { lines.append(" Request deadline " + deadline.basis + ".") } let value = try ClusterPlacementSetup.synthesize(description: described, capability: capability, - chosen: chosen, batchLanes: batchScope?.lanes, - tensorAssistant: (batchScope?.tensorParallelQuote ?? tensorAssistantQuote)?.assistant?.policy) + chosen: chosen, batchLanes: batchScope?.lanes, tensorAssistant: assistant?.policy) lines.append("What happens next") lines += value.narration(localMemberID: localMemberID).map { " " + $0 } setup = value diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift index e2a95123e5..1b2ad56cee 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift @@ -37,6 +37,16 @@ enum ClusterPlacementTensorAssistantSelection { /// stays bound by one weight pass. static let automaticDepth = 3 + /// The `backend.mtp_mode` discovery runs under for a plan whose setup serves through the coordinator + /// (`coordinator`) or on a local cluster. The assistant's speculative decoding has no parity qualification, so a + /// setup saved for coordinator pairing carries none (`ClusterConfiguration.tensorAssistantServesLocally`): under + /// `auto` such a plan quotes the ordinary target only. `on` is the operator's explicit choice and is kept; the + /// plan then says it is not offered for public traffic, and the leader refuses the coordinator's approval before + /// any part stops. + static func discoveryMode(_ configured: MTPMode, coordinator: Bool) -> MTPMode { + coordinator && configured == .auto ? .off : configured + } + static func automaticCandidate(mode: MTPMode, runtimeModelID: String, modelDirectory: URL, publicModelID: String, artifactSHA256: String, manifestSHA256: String, diff --git a/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift b/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift index 85d29eb3a6..1223b2126c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift @@ -25,10 +25,12 @@ // boxes. Invariant: Σ(grants) ≤ fleetBudget at all times. // // Serviceability floor: a load whose re-slice would leave ANY slot below -// the minimum serveable KV (`UnifiedMemoryCap.minimumLoadKVBytes`, the same -// 1 GiB figure the post-load headroom guard enforces) is REFUSED — fail -// loud (503, coordinator reroutes) rather than thrashing every co-resident -// model below serviceability. +// its floor (the 1 GiB `UnifiedMemoryCap.minimumLoadKVBytes` plus that +// slot's fixed request workspace and admission watermark) is REFUSED — +// fail loud (503, coordinator reroutes) rather than thrashing every +// co-resident model below serviceability. Given the floors, a split that +// would leave a slot below its floor is replaced by floors first and the +// remainder by weight, so only a budget smaller than Σ(floors) refuses. import Foundation @@ -68,12 +70,19 @@ extension EngineV2KVSizing { /// * Σ(shares) ≤ budget always (floor division; the ≤ slot-count /// remainder bytes are deliberately left unassigned). /// + /// `minimumGrantBytes` (the floors `resliceMeetsServiceabilityFloor` + /// checks) keeps the proportional result whenever it clears every + /// floor. Otherwise, if Σ(floors) fits the budget, each slot gets its + /// floor and the rest of the budget is split by the same weights; if it + /// does not, the proportional result stands and the floor check refuses. + /// /// Returns modelId → grant bytes. The caller enforces the /// serviceability floor (`resliceMeetsServiceabilityFloor`) on LOAD. static func resliceGrants( existing: [ResliceSlot], newcomer: ResliceSlot?, - fleetKVBudgetBytes: UInt64 + fleetKVBudgetBytes: UInt64, + minimumGrantBytes: [String: Int]? = nil ) -> [String: Int] { var all = existing if let newcomer { all.append(newcomer) } @@ -86,6 +95,31 @@ extension EngineV2KVSizing { return [all[0].modelId: Int(budget)] } + let proportional = proportionalGrants(all, budget: budget) + guard let minimumGrantBytes, + !resliceMeetsServiceabilityFloor(proportional, minimumGrantBytes: minimumGrantBytes) + else { return proportional } + + var floors: [Int] = [] + var floorTotal: UInt64 = 0 + for slot in all { + let floor = serviceabilityFloor(slot.modelId, minimumGrantBytes: minimumGrantBytes) + let (total, overflow) = floorTotal.addingReportingOverflow(UInt64(floor)) + guard floor < Int.max, !overflow, total <= budget else { return proportional } + floors.append(floor) + floorTotal = total + } + let remainder = proportionalGrants(all, budget: budget - floorTotal) + var grants: [String: Int] = [:] + for (slot, floor) in zip(all, floors) { + grants[slot.modelId] = floor + (remainder[slot.modelId] ?? 0) + } + return grants + } + + /// `budget` split across ≥ 2 slots by their weights (equal split when + /// any rate is unknown), Σ ≤ budget. + private static func proportionalGrants(_ all: [ResliceSlot], budget: UInt64) -> [String: Int] { // Per-model weights. Any unknown rate degrades the WHOLE slice to // an equal split — mixing real weights with a guessed one would // silently starve whichever side the guess was wrong about. @@ -161,8 +195,14 @@ extension EngineV2KVSizing { minimumGrantBytes: [String: Int] = [:] ) -> Bool { grants.allSatisfy { modelId, grant in - let floor = max(Int(minimumServiceableGrantBytes), minimumGrantBytes[modelId] ?? 0) + let floor = serviceabilityFloor(modelId, minimumGrantBytes: minimumGrantBytes) return floor < Int.max && grant >= floor } } + + /// One slot's floor: its total from `minimumGrantBytes`, never below + /// the base `minimumServiceableGrantBytes`. + private static func serviceabilityFloor(_ modelId: String, minimumGrantBytes: [String: Int]) -> Int { + max(Int(minimumServiceableGrantBytes), minimumGrantBytes[modelId] ?? 0) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift index 8a600a5a9a..a98ae7f27a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift @@ -38,9 +38,12 @@ public struct ChatCompletionRequest: Codable, Sendable { /// OpenAI `top_logprobs` (0–20, meaningful when `logprobs == true`). /// v2 engine path only; ignored by legacy. public let top_logprobs: Int? - /// OpenAI-compatible `min_p`. Applied on a cluster pair only (its decoding - /// rank samples with the product's min-p); the single-Mac serving - /// translator does not expose it (`EngineV2Translation.samplingParams`). + /// OpenAI-compatible `min_p`. Applied on every slot: a single Mac's v2 + /// engine gets it from `EngineV2Bridge` after translation + /// (`EngineV2Translation.samplingParams` leaves it 0), and a cluster pair's + /// decoding rank samples with it. The samplers count a value above 1 as 1 + /// and ignore 0, negative and NaN values; MiMo native media and Nemotron + /// Super refuse a non-zero value instead. public let min_p: Float? public init( diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift index 523fde57ff..37319a171c 100644 --- a/provider-swift/Sources/ProviderCore/ProviderCore.swift +++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift @@ -5,5 +5,5 @@ public enum ProviderCore { /// Release identity consumed by CLI output, registration and packaging. /// scripts/check-release-version.sh verifies this provider-owned identity /// against the requested release tag and reported binary version. - public static let version = "0.10.5" + public static let version = "0.10.6" } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift index ef96bfcd0a..beed4d1a47 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift @@ -246,15 +246,21 @@ extension ProviderLoop { ) async -> Bool { let survivors = await existingSlotGrants(excludingModelId: "", excludingModelIDs: excludingModelIDs) guard !survivors.isEmpty else { return true } + let minimumGrants = Self.minimumGrantBytes(survivors) let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, fleetKVBudgetBytes: fleetKVBudgetBytes( extraWeightBytes: 0, activationReserveBytes: reserveBytes, - excludingModelIDs: excludingModelIDs)) - return EngineV2KVSizing.resliceMeetsServiceabilityFloor( - targets, minimumGrantBytes: Dictionary(uniqueKeysWithValues: - survivors.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + excludingModelIDs: excludingModelIDs), + minimumGrantBytes: minimumGrants) + return EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: minimumGrants) + } + + /// Every slot's serviceability floor by model, for `resliceGrants` and + /// `resliceMeetsServiceabilityFloor`. + private static func minimumGrantBytes(_ slots: [ExistingSlotGrant]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: slots.map { ($0.slot.modelId, $0.minimumGrantBytes) }) } /// Existing v2 slots eligible for re-slicing: live (not mid-unload) @@ -414,13 +420,13 @@ extension ProviderLoop { modelId: modelId, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength) + let minimumGrants = Self.minimumGrantBytes(existing) var fleetBudget = fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes) var targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) - let minimumGrants = Dictionary(uniqueKeysWithValues: - existing.map { ($0.slot.modelId, $0.minimumGrantBytes) }) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) // Serviceability floor (fail loud): a slice that would leave ANY // slot below the minimum serveable grant is refused outright — @@ -445,7 +451,8 @@ extension ProviderLoop { targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) } guard EngineV2KVSizing.resliceMeetsServiceabilityFloor( targets, minimumGrantBytes: minimumGrants) @@ -544,14 +551,15 @@ extension ProviderLoop { modelId: String, weightBytes: Int, fp16KVBytesPerToken: Int, maxContextLength: Int ) async throws -> NewcomerReslice { let existing = await existingSlotGrants(excludingModelId: modelId) + let minimumGrants = Self.minimumGrantBytes(existing) let fleetBudget = fleetKVBudgetBytes(extraWeightBytes: weightBytes) let targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: .init(modelId: modelId, fp16KVBytesPerToken: fp16KVBytesPerToken, maxContextLength: maxContextLength), - fleetKVBudgetBytes: fleetBudget) - guard EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: - Dictionary(uniqueKeysWithValues: existing.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) + guard EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: minimumGrants) else { EngineV2Factory.emitRefusalTelemetry(modelId: modelId, reason: .resliceFloor, error: nil, emitTelemetry: engineV2SlotHooks?.emitTelemetry) @@ -646,7 +654,9 @@ extension ProviderLoop { /// Regrow body — caller holds the re-slice gate. Shrink targets, if /// the budget somehow contracted, are applied first so the Σ ≤ budget /// invariant holds throughout. Used directly by `ensureModelLoaded`'s - /// post-bridge-guard failure path, which already holds the gate. + /// post-bridge-guard failure path, which already holds the gate. The + /// floors keep a slot a load funded to its floor from being shrunk + /// back below it. internal func resliceGrowSurvivorsLocked() async { guard nativeMiMoAllowsReclamation() else { return } let survivors = await existingSlotGrants(excludingModelId: "") @@ -656,7 +666,8 @@ extension ProviderLoop { let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: Self.minimumGrantBytes(survivors)) for entry in survivors { if let target = targets[entry.slot.modelId], target < entry.previousGrant { await entry.bridge.updateKVBytesCapacity(target) diff --git a/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift b/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift index b2db116688..c201bb7463 100644 --- a/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift +++ b/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift @@ -372,7 +372,8 @@ extension StandaloneServer { let targets = EngineV2KVSizing.resliceGrants(existing: existing.map(\.slot), newcomer: .init(modelId: modelID, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength), - fleetKVBudgetBytes: fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes)) + fleetKVBudgetBytes: fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes), + minimumGrantBytes: Self.minimumGrantBytes(existing)) guard Self.resliceKeepsSlotsServiceable(targets, existing: existing) else { EngineV2Factory.emitRefusalTelemetry(modelId: modelID, reason: .resliceFloor, error: nil, emitTelemetry: v2TestHooks?.emitTelemetry) diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index 40966cc3c6..f3eb5d087a 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -1040,7 +1040,8 @@ public actor StandaloneServer { existing: survivors.map(\.slot), newcomer: nil, fleetKVBudgetBytes: fleetKVBudgetBytes( - extraWeightBytes: 0, activationReserveBytes: reserveBytes)) + extraWeightBytes: 0, activationReserveBytes: reserveBytes), + minimumGrantBytes: Self.minimumGrantBytes(survivors)) return Self.resliceKeepsSlotsServiceable(targets, existing: survivors) } @@ -1071,8 +1072,13 @@ public actor StandaloneServer { _ targets: [String: Int], existing: [ExistingSlotGrant] ) -> Bool { EngineV2KVSizing.resliceMeetsServiceabilityFloor( - targets, minimumGrantBytes: Dictionary(uniqueKeysWithValues: - existing.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + targets, minimumGrantBytes: minimumGrantBytes(existing)) + } + + /// Every slot's serviceability floor by model, for `resliceGrants` and + /// `resliceKeepsSlotsServiceable`. + nonisolated static func minimumGrantBytes(_ existing: [ExistingSlotGrant]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: existing.map { ($0.slot.modelId, $0.minimumGrantBytes) }) } private struct SlotBuild { @@ -1201,11 +1207,13 @@ public actor StandaloneServer { modelId: modelId, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength) + let minimumGrants = Self.minimumGrantBytes(existing) var fleetBudget = fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes) var targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) // Serviceability floor (fail loud): refuse a load that would leave // any slot below the minimum serveable live-KV grant. @@ -1225,7 +1233,8 @@ public actor StandaloneServer { targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) } guard Self.resliceKeepsSlotsServiceable(targets, existing: existing) else { @@ -1369,7 +1378,8 @@ public actor StandaloneServer { /// Grow the surviving slots back to their re-sliced shares after an /// eviction (a lone survivor gets the FULL fleet budget back). Called - /// from the eviction path, i.e. inside `isLoadingAny`. + /// from the eviction path, i.e. inside `isLoadingAny`. The floors keep + /// a slot a load funded to its floor from being shrunk back below it. func resliceGrowSurvivors() async { guard nativeMiMoReclaimAllowed else { return } let survivors = await existingSlotGrants(excludingModelId: "") @@ -1379,7 +1389,8 @@ public actor StandaloneServer { let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: Self.minimumGrantBytes(survivors)) for entry in survivors { guard nativeMiMoReclaimAllowed else { return } if let target = targets[entry.slot.modelId], target < entry.previousGrant { diff --git a/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift b/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift index 81c1481385..88d2da7770 100644 --- a/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift @@ -7,11 +7,12 @@ extension Cluster { /// printed in their canonical form: the digests a cluster approval of that /// build pins, each model's pair-serving grant, and the parity /// qualifications of the models this build declares public - /// (`ClusterPublicModels`). A declared family left without a qualification - /// is named on standard error. The release lane runs the final signed app's - /// own CLI, so the declaration and the records are that build's. It reads - /// metadata only: no model weights, no GPU, no configuration, no network - /// and no secret. + /// (`ClusterPublicModels`). What it leaves out is named on standard error: a + /// declared family without a qualification and, with release candidates, + /// another registered model's catalog ID. The release lane runs the final + /// signed app's own CLI, so the declaration and the records are that + /// build's. It reads metadata only: no model weights, no GPU, no + /// configuration, no network and no secret. struct RuntimeFacts: ParsableCommand { static let configuration = CommandConfiguration(commandName: "runtime-facts", abstract: "Print the cluster runtime facts of an app bundle's cluster helpers and models.", shouldDisplay: false) @@ -48,7 +49,8 @@ extension Cluster { let installation = ClusterRuntimeApprovalFacts.Installation(app: URL(fileURLWithPath: app, isDirectory: true)) if let releaseCandidates { let facts = try ClusterRuntimeApprovalFacts.release(installation: installation, - candidates: try ClusterRuntimeApprovalFacts.candidates(in: URL(fileURLWithPath: releaseCandidates, isDirectory: true))) + candidates: try ClusterRuntimeApprovalFacts.candidates(in: URL(fileURLWithPath: releaseCandidates, isDirectory: true)), + note: Self.note) // The release registers these bytes: they must read back under the strict decoder, and every ID a // coordinator derives for this build's version must fit. let bytes = try facts.canonicalBytes() @@ -68,7 +70,9 @@ extension Cluster { } static func note(_ facts: ClusterRuntimeApprovalFacts) { - for line in facts.unqualifiedDeclaredFamilies() { FileHandle.standardError.write(Data("note: \(line)\n".utf8)) } + for line in facts.unqualifiedDeclaredFamilies() { note(line) } } + + static func note(_ line: String) { FileHandle.standardError.write(Data("note: \(line)\n".utf8)) } } } diff --git a/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift b/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift index b033f1ed97..a7a24525b3 100644 --- a/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift @@ -103,6 +103,7 @@ extension Cluster.Setup { var service = try Self.serviceSettings(config: config, modelDir: modelDir, worker: worker) service.wizard.privateMiMoImageQualification = request.privateMiMoImageQualification service.wizard.privateGLMImageQualification = request.privateGLMImageQualification + service.wizard.servingScope = request.scope let arguments = ["cluster", "service"] + (config.map { ["--config", $0] } ?? []) + (worker.map { ["--worker", $0] } ?? []) return .init(service: service, serviceArguments: arguments) diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift new file mode 100644 index 0000000000..5dbeb80d8d --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift @@ -0,0 +1,22 @@ +import Testing +import ProviderCore +@testable import darkbloom + +/// UNRUN: CLI parsing/settings binding only; no live onboarding or child starts. How `darkbloom cluster` was asked to +/// serve reaches the settings the guided setup plans with (`ClusterSetupOperations.LiveSettings.servingScope`): +/// `darkbloom cluster local` plans a local cluster, which keeps Qwen's speculative assistant, and plain +/// `darkbloom cluster` plans for the scope the setup record saved. +struct ClusterOnboardingScopeSettingsTests { + @Test func theScopeAskedForReachesTheSettingsThePlanReads() throws { + let local = try #require(try Darkbloom.parseAsRoot(["cluster", "local", "--bind", "127.0.0.1"]) as? Cluster.Local) + let localLive = try Cluster.Setup.onboardingSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil, + request: local.onboardingRequest) + #expect(localLive.service.wizard.servingScope == .localOnly(bind: "127.0.0.1")) + let plain = try Cluster.Setup.onboardingSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil, + request: .init()) + #expect(plain.service.wizard.servingScope == nil) + // The cluster service plans from the record (its re-plans after an update or a memory refusal), never from a run. + let service = try Cluster.Setup.serviceSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil) + #expect(service.wizard.servingScope == nil) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift index 6841118e77..f9da9b1e1b 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift @@ -5,11 +5,12 @@ import Testing @Suite("Build environment defaults") struct BuildEnvironmentTests { - /// A plain build of the dev branch is a dev build. DARKBLOOM_RELEASE_ENVIRONMENT, read by Package.swift when - /// the tests are built, selects another: CI builds prod, the identity the provider suites pin. - @Test func devBranchBuildsDefaultToDevNet() throws { + /// A plain build of master is a prod build (on the dev branch it is a dev build). DARKBLOOM_RELEASE_ENVIRONMENT, + /// read by Package.swift when the tests are built, selects another: CI builds prod, the identity the provider + /// suites pin. + @Test func plainBuildsTakeTheBranchDefault() throws { let requested = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" + .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" let built = try #require(BuildEnvironment(rawValue: requested)) let coordinator = built.coordinatorWebSocketURL let hardware = HardwareInfo( diff --git a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift index 0039c575fb..af09d07f5e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift @@ -12,6 +12,8 @@ import DarkbloomClusterRuntime @Suite("Cluster runtime approval facts") struct ClusterRuntimeApprovalFactsTests { static let qwenArtifact = "127de76b4ef82b7aaa0acaac0ee31c784cff066eda64291f521f051469b7c24b" + /// One Gemma 4 26B artifact: `gemma-4-26b` and `gemma-4-26b-8bit` name it. + static let gemmaArtifact = "a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6" /// The release version the decoder rows name (`init(canonical:releaseVersion:)`). static let releaseVersion = "1.2.3" @@ -644,6 +646,55 @@ struct ClusterRuntimeApprovalFactsTests { #expect(try !f.calls().contains { $0.contains("2-unlisted") }) } + /// Production's catalog lists one artifact under two catalog IDs that the build registers as two + /// runtime models (`gemma-4-26b` and `gemma-4-26b-8bit`, one configuration), and only the 8-bit one + /// is a listed model. The ID the worker describes as the other model is that model's, not a failure. + @Test func releaseLeavesOutACatalogIDTheWorkerDescribesAsAnotherRegisteredModel() throws { + let f = try Fixture() + let candidates = try Self.gemmaCandidates(f) + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [Self.gemma8Bit]) + #expect(facts.models.map(\.model) == ["gemma-4-26b-8bit"]) + #expect(facts.models.allSatisfy { $0.artifactSHA256 == Self.gemmaArtifact }) + #expect(try f.calls().count == 2) + } + + @Test func releaseNamesTheCatalogIDOfAnotherRegisteredModelItLeavesOut() throws { + let f = try Fixture() + let candidates = try Self.gemmaCandidates(f) + var notes: [String] = [] + _ = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [Self.gemma8Bit], note: { notes.append($0) }) + #expect(notes.count == 1) + #expect(notes.first?.hasPrefix("left out, the catalog model ID of another registered model: gemma-4-26b (registered_gemma4_26b_8bit, \(Self.gemmaArtifact)): ") == true) + #expect(notes.first?.contains("0-gemma/manifest.json is registered_gemma4_26b") == true) + // Listed alone, the other model keeps its own ID and leaves out the 8-bit one. + let other = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_gemma4_26b", artifactSHA256: Self.gemmaArtifact) + notes = [] + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [other], note: { notes.append($0) }) + #expect(facts.models.map(\.model) == ["gemma-4-26b"]) + #expect(notes.count == 1 && notes.first?.contains("gemma-4-26b-8bit (registered_gemma4_26b, ") == true) + } + + static let gemma8Bit = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_gemma4_26b_8bit", + artifactSHA256: gemmaArtifact) + + /// Two candidates of the one Gemma 4 26B artifact, as production's catalog lists it: `gemma-4-26b` + /// (registered_gemma4_26b) and `gemma-4-26b-8bit` (registered_gemma4_26b_8bit), one configuration. + private static func gemmaCandidates(_ f: Fixture) throws -> URL { + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + _ = try f.model("0-gemma", parent: candidates, fixture: "registered-gemma4-26b") + let eightBitManifest = try Data(contentsOf: Fixture.metadataFixtures + .appendingPathComponent("registered-gemma4-26b-8bit.manifest.json")) + let eightBit = try f.model("1-gemma-8bit", parent: candidates, fixture: "registered-gemma4-26b", manifest: eightBitManifest) + try ClusterRuntimeCapabilityCodec.encode(ClusterResidentModelCatalog.describe( + configuration: Data(contentsOf: eightBit.appendingPathComponent("config.json")), + manifest: eightBitManifest, runtimeBinarySHA256: f.workerSHA256)) + .write(to: eightBit.appendingPathComponent("capability.out")) + return candidates + } + @Test func releaseNamesEveryCatalogModelItCannotDescribeAndRefusesAnEmptyResult() throws { let f = try Fixture() let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) @@ -660,8 +711,12 @@ struct ClusterRuntimeApprovalFactsTests { #expect(refused.contains("Qwen3.5-9B (registered_qwen35_9b, \(Self.qwenArtifact))") && refused.contains("refused/manifest.json")) _ = try f.model("accepted", parent: candidates) + // Described only as another registered model: left out, so no model is left, and the refusal names it. let another = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_other", artifactSHA256: Self.qwenArtifact) - #expect(message([another]).contains("is registered_qwen35_9b")) + let leftOut = message([another]) + #expect(leftOut.hasPrefix("No candidate folder holds a model this build qualifies on a cluster; left out, the catalog model ID " + + "of another registered model: Qwen3.5-9B (registered_other, \(Self.qwenArtifact)): ")) + #expect(leftOut.contains("is registered_qwen35_9b")) let absent = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_glm53_flash", artifactSHA256: ClusterGLMImageCandidate.artifactSHA256) #expect(message([absent]).contains("No candidate folder holds a model this build qualifies on a cluster")) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift index fa28745c52..c8c7660c87 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift @@ -29,7 +29,15 @@ final class ClusterApprovalMacs: @unchecked Sendable { static let model = "fixture/qwen" static let chip = ClusterChipClass(chipName: "Apple M3 Ultra") + /// What both Macs' setups place: the Qwen3.5 9B pipeline, or Qwen3.8 27B in tensor parallel as the guided setup + /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`). + enum Shape { + case pipeline + case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?) + } + let root: URL + let shape: Shape /// The setups' capability: the installed build's (`readopt` saves the setups of a new build). private(set) var capability: ClusterRuntimeCapability private(set) var capabilitySHA256: String @@ -39,10 +47,11 @@ final class ClusterApprovalMacs: @unchecked Sendable { var follower: Mac { macs[1] } /// `coordinatorURL`: the coordinator both provider configurations name. - init(coordinatorURL: String) throws { + init(coordinatorURL: String, shape: Shape = .pipeline) throws { let base = try NativePairMemberFixture.privateRoot() root = base - let installed = try Self.capability(runtime: Self.hash("a")) + self.shape = shape + let installed = try Self.capability(runtime: Self.hash("a"), shape: shape) capability = installed capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(installed)) @@ -91,22 +100,35 @@ final class ClusterApprovalMacs: @unchecked Sendable { } /// The capability the worker of the build whose worker digest is `runtime` describes for the fixture model. - static func capability(runtime: String) throws -> ClusterRuntimeCapability { + static func capability(runtime: String, shape: Shape = .pipeline) throws -> ClusterRuntimeCapability { let h = Self.hash - let profile = ClusterWorkerProfile(id: "registered_qwen35_9b_greedy_generation_v1", vocabularySize: 248320, - maximumPromptTokens: 8192, maximumOutputTokens: 128, maximumChunkTokens: 512, maximumContextTokens: 8320) - return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, - runtimeModelID: "registered_qwen35_9b", artifactSHA256: h("b"), configurationSHA256: h("c"), manifestSHA256: h("d"), - profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ - .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 16, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), - .init(rank: 1, sourceLayerStart: 16, sourceLayerEnd: 32, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], - arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5")) + switch shape { + case .pipeline: + let profile = ClusterWorkerProfile(id: "registered_qwen35_9b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: 8192, maximumOutputTokens: 128, maximumChunkTokens: 512, maximumContextTokens: 8320) + return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, + runtimeModelID: "registered_qwen35_9b", artifactSHA256: h("b"), configurationSHA256: h("c"), manifestSHA256: h("d"), + profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 16, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), + .init(rank: 1, sourceLayerStart: 16, sourceLayerEnd: 32, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], + arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5")) + case .qwen27TensorParallel: + let profile = ClusterWorkerProfile(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536) + return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, + runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, artifactSHA256: h("b"), configurationSHA256: h("c"), + manifestSHA256: h("d"), profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 32, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), + .init(rank: 1, sourceLayerStart: 32, sourceLayerEnd: 64, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], + arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5"), + supportedGenerationModes: [.pipeline, .tensorParallel]) + } } /// What an update does to both Macs' setups (`ClusterService`, "set the cluster up again after the update"): the /// same model and placement re-adopted for the new build's worker `runtime`, with no cluster approval. func readopt(runtime: String) throws { - capability = try Self.capability(runtime: runtime) + capability = try Self.capability(runtime: runtime, shape: shape) capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)) try saveSetups() } @@ -122,7 +144,7 @@ final class ClusterApprovalMacs: @unchecked Sendable { "ownerExecutable": other.owner.path, "workerExecutable": other.worker.path, "modelDirectory": other.model.path, "runtimeBinarySHA256": capability.runtimeBinarySHA256, "jacclDevice": "rdma_en7"] } - let configuration: [String: Any] = ["schema": ClusterConfiguration.schemaName, "clusterID": record.clusterID, + var configuration: [String: Any] = ["schema": ClusterConfiguration.schemaName, "clusterID": record.clusterID, "memberID": mac.memberID, "role": mac.rank == 0 ? "leader" : "follower", "publicModelID": Self.model, "capabilitySHA256": capabilitySHA256, "selectedPlanSHA256": h("f"), "prefillSchedule": "serial_v1", "chunkTokens": 16, "requestTimeoutSeconds": 300, "peers": macs.map(peer), @@ -130,6 +152,10 @@ final class ClusterApprovalMacs: @unchecked Sendable { "linkControl": ["schema": ClusterLinkControlAttachment.schemaName, "port": 47999, "linkEpoch": record.link.linkEpoch, "edgeID": record.link.edgeID, "secretFile": secret.path], "tokenizerFiles": [["path": "tokenizer.json", "sha256": h("6"), "purpose": "tokenizer"]]] + if case .qwen27TensorParallel(let assistant) = shape { + configuration["generationMode"] = ClusterGenerationMode.tensorParallel.rawValue + if let assistant { configuration["tensorAssistant"] = assistant.object } + } let input = mac.scratch.appendingPathComponent("setup.json"), capabilityInput = mac.scratch.appendingPathComponent("capability.json") try JSONSerialization.data(withJSONObject: configuration, options: [.sortedKeys]).write(to: input) try capabilityData.write(to: capabilityInput) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift new file mode 100644 index 0000000000..5964fb7a8a --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift @@ -0,0 +1,74 @@ +import Foundation +import Testing +import DarkbloomClusterProtocol +@testable import ProviderCore + +/// A Qwen3.8 27B tensor-parallel pair and the coordinator's cluster approval, with each Mac's real configuration +/// store, pairing store and installed files (`ClusterApprovalMacs`). The model's embedded speculative assistant +/// (`ClusterConfiguration.tensorAssistant`) has no public qualification and serves local clusters only, so a setup +/// saved for coordinator pairing carries none: a pair planned without it is saved on both Macs, and a setup with it is +/// refused by the leader's own check, before any part stops and before anything reaches the other Mac. +@Suite("Cluster approval and the Qwen tensor assistant", .serialized) +struct ClusterApprovalTensorAssistantTests { + static func assistant() throws -> ClusterQwenTensorAssistantPolicy { + try ClusterQwenTensorAssistantPolicy(depth: 3, inventorySHA256: ClusterApprovalMacs.hash("8"), verification: .admittedCohort) + } + + static let refusedHere = "Not offered for pairing: this Mac's check refused it: " + + @Test func aQwenTensorParallelPairWithoutTheAssistantIsSavedOnBothMacs() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", shape: .qwen27TensorParallel(assistant: nil)) + let approval = macs.approval(), facts = try macs.facts() + let result = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts) + #expect(result == .init(changed: true, line: ClusterApprovalLifetime.offeredLine(approval), note: .some(nil))) + for mac in macs.macs { + let saved = try macs.saved(mac).configuration + #expect(saved.nativeMember?.clusterApproval == approval, "rank \(mac.rank) saved no approval") + #expect(saved.selectedGenerationMode == .tensorParallel && saved.tensorAssistant == nil, "rank \(mac.rank)") + } + } + + @Test func theLeaderRefusesATensorAssistantSetupBeforeAnyPartStops() throws { + let policy = try Self.assistant() + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", shape: .qwen27TensorParallel(assistant: policy)) + for mac in macs.macs { #expect(try macs.saved(mac).configuration.tensorAssistant == policy, "rank \(mac.rank)") } + let approval = macs.approval(), facts = try macs.facts(), before = try macs.macs.map(macs.bytes) + let sent = ClusterApprovalRecorder() + var stops = 0, serves = 0 + // The control leader's minute check (`ClusterService.checkApproval`): no part stops, nothing is sent to the + // other Mac, nothing starts again, and the reason is the status note. + let checked = ClusterApprovalSync.apply(.save(approval), grace: 600, paths: macs.leader.paths, + providerConfiguration: macs.leader.provider, pairingStore: macs.leader.pairing, scratch: macs.leader.scratch, + now: Date().timeIntervalSince1970, stop: { stops += 1; return nil }, serve: { serves += 1 }, + sendToPeer: macs.cable(facts: facts, sent: sent), chipClass: ClusterApprovalMacs.chip, facts: { _ in facts }) + #expect(stops == 0 && serves == 0 && sent.values.isEmpty, "stops \(stops), serves \(serves), sent \(sent.values.map(\.op))") + #expect(!checked.changed && checked.line?.hasPrefix(Self.refusedHere) == true, "\(checked.line ?? "")") + #expect(checked.line == Self.refusedHere + ClusterConfiguration.tensorAssistantServesLocally) + #expect(checked.note == .some(checked.line)) + #expect(try macs.macs.map(macs.bytes) == before) + // The registration after the guided setup's Test stage (`OnboardingLive.localRegister`, `run`): this Mac's own + // check refuses it too, so nothing reaches the other Mac. + let registered = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts, sent: sent) + #expect(!registered.changed && sent.values.isEmpty, "sent \(sent.values.map(\.op))") + #expect(registered.line?.hasPrefix(Self.refusedHere) == true, "\(registered.line ?? "")") + #expect(try macs.macs.map(macs.bytes) == before) + } + + /// The other Mac checks the same rule itself before it saves anything, so a leader of an earlier build that sends + /// the approval anyway gets the reason in plain words, and the other Mac's setup stays as it was. + @Test func theOtherMacRefusesATensorAssistantSetupWithThePlainReason() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", + shape: .qwen27TensorParallel(assistant: try Self.assistant())) + let before = try macs.bytes(macs.follower) + var command = ClusterServiceCommand(op: .approval) + command.approval = macs.approval() + command.approvalEdge = ClusterEdge(peerPin: macs.leader.pin, transport: "rdma", measuredMbps: 1, measuredRTTMicros: 1) + let refused = #expect(throws: (any Error).self) { try macs.cable(facts: try macs.facts())(command) } + let reason = refused.map(ClusterApprovalSync.refusal) ?? "" + #expect(reason.hasSuffix(ClusterApprovalSync.peerRefusalPrefix + ClusterConfiguration.tensorAssistantServesLocally), "\(reason)") + #expect(try macs.bytes(macs.follower) == before) + // The same setup without an approval (the leader serving locally) is saved as it is: nothing to refuse. + try macs.cable(facts: try macs.facts())(ClusterServiceCommand(op: .approval)) + #expect(try macs.bytes(macs.follower) == before) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift index 12befc1dd2..d2aa09f109 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift @@ -27,11 +27,12 @@ struct ClusterApprovalWatchTests { private func step(_ macs: ClusterApprovalMacs, _ fetched: ClusterApprovalFetch.Outcome, setAside: ClusterSetupRecord.ApprovalSetAside? = nil, quickEnds: Int = 0, peer: String?? = nil, - scope: ClusterServingScope = .publicServing, _ watched: Watched, clock: Double) throws -> ClusterApprovalCheck.Step { + scope: ClusterServingScope = .publicServing, _ watched: Watched, clock: Double, + now: Double = Date().timeIntervalSince1970) throws -> ClusterApprovalCheck.Step { let facts = try macs.facts() return ClusterApprovalCheck.step(saved: try macs.saved(macs.leader), fetched: fetched, setAside: setAside, scope: scope, memberQuickEnds: quickEnds, peerApprovalID: peer, watch: &watched.watch, clock: clock, - grace: grace, now: Date().timeIntervalSince1970, facts: { _ in facts }) + grace: grace, now: now, facts: { _ in facts }) } /// The other Mac's saved cluster approval ID, as its status reports it. @@ -158,7 +159,7 @@ struct ClusterApprovalWatchTests { #expect(try step(macs, noAnswer, quickEnds: limit, watch, clock: 0) == .serveLocally(approval, .failing)) _ = serveLocally(macs, approval, facts: facts, reason: .failing) - let failing = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing) + let failing = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing, setAt: Date().timeIntervalSince1970) #expect(try step(macs, .approvals([approval]), setAside: failing, watch, clock: 0) == .keep) let later = macs.approval(endsIn: 20 * 86_400, id: "later") #expect(try step(macs, .approvals([approval, later]), setAside: failing, watch, clock: 0) == .save(later)) @@ -173,8 +174,8 @@ struct ClusterApprovalWatchTests { } /// A model approval names no build and keeps its `id` across updates: its parts failing on one build set it aside - /// for that build only, so the build an update installs takes it again. A record from an older build, which names - /// no build, keeps it aside by its `id`. + /// for that build only, so the build an update installs takes it again. A record from an older build names neither + /// the build nor the time it was set aside: it is past the hour, so any build takes the approval again. @Test func aModelApprovalSetAsideAsFailingIsTakenAgainByTheNextBuild() throws { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") let model = macs.modelApproval(), facts = try macs.facts(), watch = Watched() @@ -183,21 +184,124 @@ struct ClusterApprovalWatchTests { #expect(try step(macs, .approvals([model]), quickEnds: limit, watch, clock: 0) == .serveLocally(model, .failing)) #expect(serveLocally(macs, model, facts: facts, reason: .failing).changed) let failing = ClusterSetupRecord.ApprovalSetAside(approval: model, reason: .failing, - runtimeBinarySHA256: try macs.saved(macs.leader).capability.runtimeBinarySHA256) + runtimeBinarySHA256: try macs.saved(macs.leader).capability.runtimeBinarySHA256, setAt: Date().timeIntervalSince1970) // The build its parts kept failing on does not take it again. #expect(try step(macs, .approvals([model]), setAside: failing, watch, clock: 0) == .keep) - // A record saved by an older build reads without the field. + // A record saved by an older build reads without the fields it did not write. var object = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(failing)) as? [String: Any]) let removed = object.removeValue(forKey: "runtimeBinarySHA256") as? String #expect(removed == failing.runtimeBinarySHA256) + let removedTime = object.removeValue(forKey: "setAt") as? Double + #expect(removedTime == failing.setAt) let older = try JSONDecoder().decode(ClusterSetupRecord.ApprovalSetAside.self, from: JSONSerialization.data(withJSONObject: object)) #expect(older == ClusterSetupRecord.ApprovalSetAside(approval: model, reason: .failing)) + #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .save(model)) // An update re-adopts both setups for a new worker: the new build takes the same model approval again. try macs.readopt(runtime: ClusterApprovalMacs.hash("9")) #expect(try step(macs, .approvals([model]), setAside: failing, watch, clock: 0) == .save(model)) - #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .keep) + #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .save(model)) + } + + /// Ends the coordinator decides are not the pair's failures: a registration it did not accept in its negotiation + /// window (during a deploy, right after a restart, or when it is slow; twice within three minutes during an e2e + /// model change) leaves the count of quick ends as it is. Read from the parts' own log lines, as the cluster service + /// reads them, any number of them never sets the approval aside. + @Test func coordinatorSideEndsDoNotReachTheFailingLimit() throws { + let (macs, approval, _) = try offered() + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("rank-log-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let log = folder.appendingPathComponent("rank.log") + #expect(FileManager.default.createFile(atPath: log.path, contents: nil)) + let notAccepted = ClusterMemberControlError.negotiationFailed.rawValue + var count = 0 + for ran in [13.0, 12, 40, 3, 90] { + // Each part writes after where the one before it stopped. + let handle = try FileHandle(forWritingTo: log) + let offset = try handle.seekToEnd() + try handle.write(contentsOf: Data("cluster-member pair serving: follower (dials the leader)\nError: \(notAccepted)\n".utf8)) + try handle.close() + count = ClusterApprovalCheck.memberQuickEnds(after: count, ranSeconds: ran, lastError: ClusterService.lastError(in: log, from: offset)) + } + #expect(count == 0) + #expect(try step(macs, .approvals([approval]), quickEnds: count, Watched(), clock: 0) == .keep) + // Between local quick ends it neither adds one nor starts the count again; a part that ran long before the + // coordinator ended it still starts it again, as any long run does. + #expect(ClusterApprovalCheck.memberQuickEnds(after: 2, ranSeconds: 12, lastError: notAccepted) == 2) + #expect(ClusterApprovalCheck.memberQuickEnds(after: 2, ranSeconds: ClusterControlSoloAdmission.quickEndSeconds, + lastError: notAccepted) == 0) + } + + /// Ends with a local cause still count, with ends the coordinator decided between them: a changed input (the DevNet + /// trigger), a crash that wrote no error line and a member that ended before it registered set the approval aside. + @Test func localQuickEndsStillSetTheApprovalAside() throws { + let (macs, approval, _) = try offered() + let notAccepted = ClusterMemberControlError.negotiationFailed.rawValue + let ends: [String?] = ["Installed input identity or SHA-256 differs", notAccepted, nil, notAccepted, + ClusterMemberControlError.connectionEnded.rawValue] + var count = 0, counts: [Int] = [] + for lastError in ends { + count = ClusterApprovalCheck.memberQuickEnds(after: count, ranSeconds: 8, lastError: lastError) + counts.append(count) + } + #expect(counts == [1, 1, 2, 2, ClusterControlSoloAdmission.maximumQuickEnds]) + #expect(try step(macs, .approvals([approval]), quickEnds: count, Watched(), clock: 0) == .serveLocally(approval, .failing)) + } + + /// An approval set aside as failing is offered again, by the same build, `ClusterApprovalFallback.failingSeconds` + /// after the cluster service set it aside (a later matching one at once, as before). Each Mac's part that served + /// locally meanwhile started its count of quick ends again, so the pair is offered with none. + @Test func aFailingApprovalIsOfferedAgainAnHourAfterItWasSetAside() throws { + let (macs, approval, facts) = try offered() + let watch = Watched(), limit = ClusterControlSoloAdmission.maximumQuickEnds, hour = ClusterApprovalFallback.failingSeconds + let fallback = ClusterApprovalCheck.Step.serveLocally(approval, .failing) + #expect(try step(macs, .approvals([approval]), quickEnds: limit, watch, clock: 0) == fallback) + #expect(serveLocally(macs, approval, facts: facts, reason: .failing).changed) + let worker = try macs.saved(macs.leader).capability.runtimeBinarySHA256, now = Date().timeIntervalSince1970 + func setAside(at time: Double) throws -> ClusterSetupRecord.ApprovalSetAside { + try #require(ClusterApprovalCheck.setAside(by: fallback, worker: worker, now: time)) + } + // What the cluster service keeps: the approval, why, the setup's worker digest and when. + #expect(try setAside(at: now) == .init(approval: approval, reason: .failing, runtimeBinarySHA256: worker, setAt: now)) + #expect(ClusterApprovalCheck.setAside(by: .save(approval), worker: worker, now: now) == nil) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now), watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now - hour + 60), watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now - hour), watch, clock: 0, now: now) == .save(approval)) + // A time ahead of a clock that was set back holds it aside no longer either. + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now + 600), watch, clock: 0, now: now) == .save(approval)) + #expect(ClusterApprovalFallback.failing.line(approval, grace: grace).hasSuffix( + "the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists")) + + // Saved on both Macs again, the pair is offered and stays offered while its parts' new count is under the limit. + #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed) + #expect(try step(macs, .approvals([approval]), quickEnds: 0, watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), quickEnds: limit, watch, clock: 0, now: now) == fallback) + } + + /// The leader's record as the current build writes it (the set-aside names its approval, reason and worker digest, + /// no time) reads cleanly with every field kept, and is past the hour: the approval is offered again. A set-aside + /// this build writes keeps its time through the store. + @Test func aSetAsideInTheCurrentRecordFormatReadsCleanlyAndIsPastTheHour() throws { + let (macs, approval, facts) = try offered() + #expect(serveLocally(macs, approval, facts: facts, reason: .failing).changed) + let worker = try macs.saved(macs.leader).capability.runtimeBinarySHA256, now = Date().timeIntervalSince1970 + let store = ClusterSetupStore(paths: ClusterSetupPaths(paths: macs.leader.paths)) + let note = ClusterApprovalFallback.failing.line(approval, grace: grace) + let current = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing, runtimeBinarySHA256: worker) + try store.updateRecord { $0.approvalNote = note; $0.approvalSetAside = current } + let written = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: store.paths.record)) as? [String: Any]) + let keys = try #require(written["approvalSetAside"] as? [String: Any]).keys.sorted() + #expect(keys == ["approval", "reason", "runtimeBinarySHA256"]) + let read = try store.readRecord() + #expect(read.approvalSetAside == current && read.approvalSetAside?.setAt == nil && read.approvalNote == note) + #expect(try step(macs, .approvals([approval]), setAside: read.approvalSetAside, Watched(), clock: 0, now: now) == .save(approval)) + + let dated = try #require(ClusterApprovalCheck.setAside(by: .serveLocally(approval, .failing), worker: worker, now: now)) + try store.updateRecord { $0.approvalSetAside = dated } + #expect(try store.readRecord().approvalSetAside?.setAt == now) + #expect(try step(macs, .approvals([approval]), setAside: store.readRecord().approvalSetAside, Watched(), clock: 0, now: now) == .keep) } @Test func aClusterThatServesLocallyOnlyNeverAsksTheCoordinatorAndChangesNothing() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift index 17853b78e4..0f2ff762e8 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift @@ -108,6 +108,23 @@ import DarkbloomClusterProcess == ClusterPairOwnerServing.notYetQualified) } + /// A placement that decodes with Qwen's speculative assistant is never said to be qualified for public traffic: + /// the assistant serves local clusters only, so its setup is never offered to the coordinator. Without it, the + /// same model and mode are qualified as before; a model or mode that is not qualified says so either way. + @Test func aPlacementThatDecodesWithTheAssistantIsNotOfferedForPublicTraffic() { + let q27 = ClusterPublicModels.declared.first { $0.runtimeModelID == "registered_qwen38_27b" }! + let none = ClusterPairServingDecisions(records: []) + func line(_ mode: ClusterGenerationMode, assistant: Bool, model: String = q27.runtimeModelID) -> String { + ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, artifactSHA256: model == q27.runtimeModelID ? q27.artifactSHA256 : nil, + mode: mode, tensorAssistant: assistant, decisions: none) + } + #expect(line(.tensorParallel, assistant: false).hasPrefix("qualified for public traffic in tensor parallel mode")) + #expect(line(.tensorParallel, assistant: true) == ClusterPairOwnerServing.tensorAssistantNotOffered) + #expect(ClusterPairOwnerServing.tensorAssistantNotOffered.hasPrefix("not offered for public traffic")) + #expect(line(.pipelineMTP, assistant: true) == ClusterPairOwnerServing.notYetQualified) + #expect(line(.tensorParallel, assistant: true, model: "registered_qwen35_9b") == ClusterPairOwnerServing.notYetQualified) + } + /// With a passing pipeline record the pipeline family is qualified for public traffic, tensor parallel is not; both /// are served for the owner. (Records only: no model is declared public here.) @Test func publicTrafficFollowsThePassingRecordsOnly() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift index b69b82102d..f4f253479c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift @@ -44,11 +44,14 @@ final class DistributedAutomaticBatchPlannerTests { return p } - private func fixture() throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementBatchScope) { - let model = "registered_qwen38_27b" + /// `artifact`: the artifact digest every record names (default a constructed one; the registered digest makes the + /// model one its owner declared public, `ClusterPublicModels`). + private func fixture(artifact: String? = nil) throws + -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementBatchScope) { + let model = "registered_qwen38_27b", artifact = artifact ?? hash("b") let part = ClusterModelLayout.Part(storedBytes: 2 * gib, loadedBytes: 2 * gib, largestTensorBytes: gib / 4, tensorCount: 16) let end = ClusterModelLayout.Part(storedBytes: gib / 2, loadedBytes: gib / 2, largestTensorBytes: gib / 2, tensorCount: 1) - let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), layers: (0..<2).map { .init(index: $0, kind: "fixture", weights: part, stateFixedBytes: 1024, stateBytesPerToken: 1024, cost: 1) }, ingress: end, egress: end, excluded: .init(), admittedCuts: [1], structuralCuts: [1], generationModes: [.pipeline, .tensorParallel], prefillSchedules: [.serial], @@ -62,7 +65,7 @@ final class DistributedAutomaticBatchPlannerTests { object["tensorParallel"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(tensor)) let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) let cap = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, - runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), manifestSHA256: hash("d"), + runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), manifestSHA256: hash("d"), profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536), profileFingerprint: hash("e"), partitions: [.init(planSHA256: hash("f"), stages: [ @@ -79,7 +82,7 @@ final class DistributedAutomaticBatchPlannerTests { linkSecretFile: "/fixture/\(id).secret") }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased())) - let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), promptTokens: 1024, outputTokens: 128, maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestChargeEveryRankBytes: gib) let quote = try ClusterPlacementTensorBatchQuote(request: request, lanes: 4, chunkTokens: 128, @@ -721,7 +724,8 @@ final class DistributedAutomaticBatchPlannerTests { try ClusterModelFeaturePolicy.requireReady(valid, identity: id, profile: profile) } - @Test func automaticAssistantUsesVerifiedInlineArtifactAndRespectsDisabledModes() throws { + /// A catalog folder whose artifact declares and ships an inline speculative head (one tensor), with its manifest. + private func inlineAssistantArtifact() throws -> (directory: URL, modelID: String, aggregate: String, manifest: Data) { let directory = try home(), modelID = "fixture-inline-qwen" let header = try JSONSerialization.data(withJSONObject: ["mtp.weight": ["dtype": "F32", "shape": [1], "data_offsets": [0, 4]]]) var length = UInt64(header.count).littleEndian @@ -738,6 +742,11 @@ final class DistributedAutomaticBatchPlannerTests { "aggregate_sha256": aggregate, "total_size_bytes": shard.count, "files": [["path": files[0].path, "size_bytes": files[0].sizeBytes, "sha256": files[0].sha256]]]) try manifest.write(to: directory.appendingPathComponent("manifest.json")) + return (directory, modelID, aggregate, manifest) + } + + @Test func automaticAssistantUsesVerifiedInlineArtifactAndRespectsDisabledModes() throws { + let (directory, modelID, aggregate, manifest) = try inlineAssistantArtifact() func candidate(_ mode: MTPMode, id: String? = nil, digest: String? = nil, environment: [String: String] = [:]) throws -> Bool { try ClusterPlacementTensorAssistantSelection.automaticCandidate(mode: mode, @@ -759,6 +768,26 @@ final class DistributedAutomaticBatchPlannerTests { #expect(!disabledMalformed) } + /// Which plans ask for Qwen's speculative assistant (`discoveryMode`): under the default `auto`, a cluster that + /// serves locally only, as before, and never one served through the coordinator, whose setup may not carry it; + /// an explicit `on` in either case; never `off`. + @Test func aClusterServedThroughTheCoordinatorAsksForTheAssistantOnlyUnderAnExplicitOn() throws { + let artifact = try inlineAssistantArtifact() + func asks(_ configured: MTPMode, coordinator: Bool) throws -> Bool { + try ClusterPlacementTensorAssistantSelection.automaticCandidate( + mode: ClusterPlacementTensorAssistantSelection.discoveryMode(configured, coordinator: coordinator), + runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, modelDirectory: artifact.directory, + publicModelID: artifact.modelID, artifactSHA256: artifact.aggregate, + manifestSHA256: ClusterConfigurationCodec.sha256(artifact.manifest), environment: [:]) + } + #expect(try asks(.auto, coordinator: false)) + #expect(try !asks(.auto, coordinator: true)) + #expect(try asks(.on, coordinator: false) && asks(.on, coordinator: true)) + #expect(try !asks(.off, coordinator: false) && !asks(.off, coordinator: true)) + #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: true) == .off) + #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: false) == .auto) + } + @Test func automaticQuotePinsNativeInventoryAndCompleteWidthOneScope() throws { let (_, cap, _, _) = try fixture() func quote(_ verification: ClusterQwenTensorAssistantPolicy.Verification = .admittedCohort, @@ -796,9 +825,11 @@ final class DistributedAutomaticBatchPlannerTests { #expect(!plainArgs.contains("--mtp-depth") && plainArgs.contains("--batch-lanes")) } + /// `assistant` false: the same request's ordinary target quote, as discovery reads it without the assistant. private func assistantQuote(_ lanes: Int, depth: Int = ClusterPlacementTensorAssistantSelection.automaticDepth, - verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton) throws -> ClusterPlacementTensorBatchQuote { - let (_, _, _, scope) = try fixture() + verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton, + artifact: String? = nil, assistant: Bool = true) throws -> ClusterPlacementTensorBatchQuote { + let (_, _, _, scope) = try fixture(artifact: artifact) return try .init(request: scope.request, lanes: lanes, chunkTokens: 128, perLaneStateBytes: gib, sharedBytesExcludingCollectives: 2 * gib, allowance: .init(maximumContextTokens: 65536, maximumChunkTokens: 512, @@ -806,8 +837,8 @@ final class DistributedAutomaticBatchPlannerTests { maximumCollectivePayloadBytes: max(512 * 4096, lanes * 248320 * 4), maximumCollectiveFrameBytes: max(512 * 4096, lanes * 248320 * 4) + 1024, allocationBound: { (($0 + 16383) / 16384) * 16384 }), - assistant: .init(policy: .init(depth: depth, inventorySHA256: hash("8"), verification: verification), - residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib)) + assistant: assistant ? ClusterPlacementTensorAssistantQuote(policy: .init(depth: depth, inventorySHA256: hash("8"), + verification: verification), residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib) : nil) } @Test func wideningQuoteSteersTheRetainedSplitTowardOneThatCanWiden() throws { @@ -897,6 +928,47 @@ final class DistributedAutomaticBatchPlannerTests { #expect(kept.quote == fits && kept.decision.result.chosen != nil) } + /// The onboarding's public-traffic line (`ClusterSetupPlanning.decide`, `publicTraffic`) for Qwen3.8 27B, whose + /// owner declared tensor parallel public (`ClusterPublicModels`): a plan without the speculative assistant is + /// qualified; a plan that decodes with it is not said to be, since a setup saved for coordinator pairing carries + /// no assistant (`ClusterConfiguration.validate`). + @Test func onlyAPlanWithoutTheAssistantSaysItIsQualifiedForPublicTraffic() throws { + let home = try home(); record(home) + let artifact = try #require(ClusterPublicModels.declared.first { + $0.runtimeModelID == ClusterQwenTensorAssistantPolicy.runtimeModelID }).artifactSHA256 + let (pair, cap, layout, _) = try fixture(artifact: artifact) + let data = try ClusterRuntimeCapabilityCodec.encode(cap), digest = ClusterConfigurationCodec.sha256(data) + let model = ClusterSetupLocalModel(folder: "Qwen3.8-27B-4bit-mtp-fixture", modelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", + version: "fixture", artifactSHA256: artifact, totalBytes: 16_320_415_757) + let link = try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])) + let local = try profile(), peer = try profile() + func plan(_ quote: ClusterPlacementTensorBatchQuote) throws -> (line: String?, explanation: [String], setup: ClusterConfiguration) { + let reading = ClusterSetupPlanning.ModelReading(model: model, layout: .success(layout), + capability: .success((cap, data, digest)), tokenizerFiles: pair.tokenizerFiles, tensorAssistantQuote: .success(quote)) + let decided = try #require(onLargeStack { + ClusterSetupPlanning.decide(readings: [reading], description: pair, localMemberID: "a", + localProfile: local, peerProfile: peer, peerModels: [model], measurements: [], link: link) + }.first) + let summary = try #require(decided.option.plan, "not offered: \(decided.option.blocker ?? "")") + let bytes = try #require(decided.setup?.configurations["a"]) + return (summary.publicTraffic, summary.explanation, + try ClusterConfigurationCodec.decode(bytes, capability: cap, capabilitySHA256: digest)) + } + let target = try plan(try assistantQuote(1, artifact: artifact, assistant: false)) + #expect(target.setup.selectedGenerationMode == .tensorParallel && target.setup.tensorAssistant == nil) + #expect(target.line?.hasPrefix("qualified for public traffic in tensor parallel mode") == true, "\(target.line ?? "")") + let assisted = try plan(try assistantQuote(1, verification: .admittedCohort, artifact: artifact)) + #expect(assisted.setup.tensorAssistant != nil) + #expect(assisted.line?.hasPrefix("qualified for public traffic") == false, "\(assisted.line ?? "")") + #expect(assisted.line?.hasPrefix("not offered for public traffic") == true, "\(assisted.line ?? "")") + #expect(assisted.line == ClusterPairOwnerServing.tensorAssistantNotOffered) + // The plan's own explanation (`darkbloom cluster plan`, the six-step wizard) says the same under "Public traffic". + func publicSection(_ lines: [String]) -> String? { lines.firstIndex(of: "Public traffic").map { lines[$0 + 1] } } + #expect(publicSection(target.explanation)?.hasPrefix(" Qualified for public traffic in tensor parallel mode") == true) + #expect(publicSection(assisted.explanation)?.hasPrefix(" Not offered for public traffic: it decodes with Qwen's speculative assistant") == true, + "\(publicSection(assisted.explanation) ?? "")") + } + @Test func testAssistantSingletonAndWiderPlansPersistSamePolicyAndBilateralArguments() throws { for verification in [ClusterQwenTensorAssistantPolicy.Verification.singleton, .admittedCohort] { let home = try home(); record(home) @@ -1008,6 +1080,21 @@ final class DistributedAutomaticBatchPlannerTests { } +/// Runs `body` on a thread with a 16 MiB stack and returns its result: the guided setup's whole planning step +/// (`ClusterSetupPlanning.decide` over `ClusterPlacementFlow.decide`) outgrows a test task's thread stack in a debug +/// build. +private func onLargeStack(_ body: @escaping @Sendable () -> T) -> T { + let result = LargeStackResult(), done = DispatchSemaphore(value: 0) + let thread = Thread { result.value = body(); done.signal() } + thread.stackSize = 16 << 20 + thread.start() + done.wait() + return result.value! +} + +/// The value `onLargeStack`'s thread hands back; written once before the semaphore signals, read after it. +private final class LargeStackResult: @unchecked Sendable { var value: T? } + private final class FeatureReadyOwner: DistributedResidentExecutionOwner, @unchecked Sendable { let ready: DistributedResidentReadiness? init(_ ready: DistributedResidentReadiness?) { self.ready = ready } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift new file mode 100644 index 0000000000..d7f19723aa --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift @@ -0,0 +1,256 @@ +// Copyright © 2026 Eigen Labs. +// +// Re-slice orchestration against slots whose floors include real fixed +// request workspace (`ResliceFloorScenario`). Residents are real EngineV2 +// instances over a contiguous backend, so `minimumServiceableGrantBytes` +// and serving width come from production code; the newcomer is built by +// the scripted hook engine. No weights, requests or GPU work. + +import Foundation +import MLXLMCommon +import MLXNN +import Testing + +@testable import ProviderCore + +private final class FloorStubLanguageModel: Module, LanguageModel { + func prepare(_ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters) throws + -> PrepareResult { + .tokens(input.text) + } + func newCache(parameters: GenerateParameters?) -> [KVCache] { [] } +} + +private struct FloorStubProcessor: UserInputProcessor { + struct Unsupported: Error {} + func prepare(input: UserInput) async throws -> LMInput { throw Unsupported() } +} + +private func makeFloorContainer() -> ModelContainer { + ModelContainer(context: ModelContext( + configuration: ModelConfiguration(id: "test/reslice-floor"), + model: FloorStubLanguageModel(), processor: FloorStubProcessor(), + tokenizer: StubBridgeTokenizer())) +} + +/// The production default `memory_reserve_gb`; it does not bind on 150+ GB. +private let floorConfigReserveBytes: UInt64 = 4 << 30 + +private func makeFloorLoop(physicalBytes: UInt64) throws -> ProviderLoop { + let config = ProviderLoopConfig( + coordinatorURL: "ws://127.0.0.1:0/ignored", + hardware: HardwareInfo( + machineModel: "Mac14,14", chipName: "Apple M2 Ultra", chipFamily: .m2, chipTier: .ultra, + memoryGb: physicalBytes >> 30, memoryAvailableGb: (physicalBytes >> 30) - 8, + cpuCores: CpuCores(total: 24, performance: 16, efficiency: 8), + gpuCores: 76, memoryBandwidthGbs: 800), + models: [], + config: ProviderConfig( + provider: ProviderSettings(name: "reslice-floor-test", memoryReserveGB: 4), + backend: BackendSettings(idleTimeoutMins: 0, maxModelSlots: 8), + coordinator: CoordinatorSettings(heartbeatIntervalSecs: 60))) + return try ProviderLoop(config: config, attestationSigner: nil, + kvBudgetForTesting: ScriptedProviderMemory.budget( + physicalBytes: physicalBytes, configReserveBytes: floorConfigReserveBytes)) +} + +/// Fleet KV budget for `models` resident on the scenario machine. +private func floorBudget(_ models: [ResliceFloorScenario.Model], physicalBytes: UInt64) -> UInt64 { + UnifiedMemoryCap.kvBudgetBytes(physicalBytes: physicalBytes, + residentWeightBytes: UInt64(models.reduce(0) { $0 + $1.weightsBytes }), + configReserveBytes: floorConfigReserveBytes) +} + +/// Residents at the shares the six-slot re-slice gave them, installed on +/// `install`. Each bridge must report the scenario's floor. +private func installResidents( + physicalBytes: UInt64, + install: (ResliceFloorScenario.Model, EngineV2Bridge) async -> Void +) async throws -> [String: EngineV2Bridge] { + let residents = try ResliceFloorScenario.residents() + let shares = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: floorBudget(residents, physicalBytes: physicalBytes)) + var bridges: [String: EngineV2Bridge] = [:] + for resident in residents { + let bridge = ResliceFloorScenario.makeBridge(modelId: resident.id, + fixedRequestBytes: resident.fixedRequestBytes, grant: try #require(shares[resident.id]), + kvBytesPerToken: resident.fp16KVBytesPerToken) + #expect(await bridge.minimumServiceableGrantBytes() == resident.minimumGrantBytes, "\(resident.id)") + await install(resident, bridge) + bridges[resident.id] = bridge + } + return bridges +} + +/// Every resident keeps at least its floor and can still serve a request. +private func expectResidentsServiceable(_ bridges: [String: EngineV2Bridge]) async { + for (id, bridge) in bridges { + let grant = await bridge.engineKVBytesCapacity() + #expect(grant >= (await bridge.minimumServiceableGrantBytes()), "\(id) grant \(grant)") + #expect(await bridge.effectiveServingConcurrency(allowExpansion: true) >= 1, "\(id)") + } +} + +@Suite("KV re-slice keeps every slot's floor (orchestration)", .serialized) +struct EngineV2ResliceFloorWiringTests { + private static let physical = ResliceFloorScenario.physicalBytes + + @Test("ProviderLoop admits a seventh model when Σ floors fits the fleet budget", + arguments: [ResliceFloorScenario.gemmaQAT.id, ResliceFloorScenario.gptOSS.id]) + func providerLoopAdmitsSeventhModel(newcomerID: String) async throws { + let newcomer = newcomerID == ResliceFloorScenario.gptOSS.id + ? ResliceFloorScenario.gptOSS : ResliceFloorScenario.gemmaQAT + let loop = try makeFloorLoop(physicalBytes: Self.physical) + let runtime = EngineV2Runtime() + await loop.setEngineV2RuntimeForTesting(runtime) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + let all = try ResliceFloorScenario.residents() + [newcomer] + let budget = floorBudget(all, physicalBytes: Self.physical) + // The proportional share alone would leave Lightning below its floor. + let lightning = try #require(all.first { $0.id == ResliceFloorScenario.lightningID }) + let proportional = EngineV2KVSizing.resliceGrants(existing: all.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: budget) + let lightningShare = try #require(proportional[lightning.id]) + #expect(lightningShare < lightning.minimumGrantBytes) + #expect(UInt64(all.reduce(0) { $0 + $1.minimumGrantBytes }) <= budget) + + let bridge = try await loop.resliceAndBuildEngineV2SlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + + await expectResidentsServiceable(residents) + let newcomerGrant = await bridge.engineKVBytesCapacity() + #expect(newcomerGrant >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + var total = UInt64(newcomerGrant) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= budget) + await bridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("StandaloneServer admits a seventh model when Σ floors fits the fleet budget") + func standaloneAdmitsSeventhModel() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let server = StandaloneServer(models: []) + await server.setV2TestHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await server.installSlotForTesting(modelId: model.id, bridge: bridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: model.sizing, modelType: model.modelType) + } + + let bridge = try await server.buildSlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + + await expectResidentsServiceable(residents) + #expect(await bridge.engineKVBytesCapacity() >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + await bridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("a seventh model whose floors exceed the fleet budget is still refused") + func infeasibleSeventhModelIsRefused() async throws { + let physical: UInt64 = 150 << 30 + let newcomer = ResliceFloorScenario.gemmaQAT + let all = try ResliceFloorScenario.residents() + [newcomer] + #expect(UInt64(all.reduce(0) { $0 + $1.minimumGrantBytes }) > floorBudget(all, physicalBytes: physical)) + let loop = try makeFloorLoop(physicalBytes: physical) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + var before: [String: Int] = [:] + for (id, bridge) in residents { before[id] = await bridge.engineKVBytesCapacity() } + + do { + _ = try await loop.resliceAndBuildEngineV2SlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + Issue.record("an infeasible re-slice was admitted") + } catch InferenceError.modelLoadFailed(let message) { + #expect(message.contains("would leave a model without its fixed request workspace")) + #expect(message.contains("across 7 slots")) + } + for (id, bridge) in residents { + #expect(await bridge.engineKVBytesCapacity() == before[id], "\(id)") + await bridge.shutdown() + } + } + + @Test("regrow and the reserve preflight keep a starved slot at its floor") + func regrowAndPreflightKeepFloors() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let loop = try makeFloorLoop(physicalBytes: Self.physical) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + let newcomerBridge = EngineV2Bridge(engine: InertStubEngine(kvBytesCapacity: 4 << 30), + modelId: newcomer.id, tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: []) + await loop.installModelSlotForTesting(modelId: newcomer.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: newcomerBridge, + sizing: newcomer.sizing, modelType: newcomer.modelType) + + #expect(await loop.reserveRaiseKeepsSurvivorsServiceable( + reserveBytes: UnifiedMemoryCap.defaultActivationReserveBytes)) + await loop.resliceGrowSurvivorsForTesting() + + await expectResidentsServiceable(residents) + let all = try ResliceFloorScenario.residents() + [newcomer] + var total = UInt64(await newcomerBridge.engineKVBytesCapacity()) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= floorBudget(all, physicalBytes: Self.physical)) + await newcomerBridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("StandaloneServer regrow and the reserve check keep a starved slot at its floor") + func standaloneRegrowAndReserveKeepFloors() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let server = StandaloneServer(models: []) + await server.setV2TestHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await server.installSlotForTesting(modelId: model.id, bridge: bridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: model.sizing, modelType: model.modelType) + } + let newcomerBridge = EngineV2Bridge(engine: InertStubEngine(kvBytesCapacity: 4 << 30), + modelId: newcomer.id, tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: []) + await server.installSlotForTesting(modelId: newcomer.id, bridge: newcomerBridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: newcomer.sizing, modelType: newcomer.modelType) + // The server's own budget: its proportional share alone starves Lightning. + let budget = await server.fleetKVBudgetBytes(extraWeightBytes: 0) + let all = try ResliceFloorScenario.residents() + [newcomer] + let lightning = try #require(all.first { $0.id == ResliceFloorScenario.lightningID }) + let proportional = EngineV2KVSizing.resliceGrants(existing: all.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: budget) + #expect(try #require(proportional[lightning.id]) < lightning.minimumGrantBytes) + + #expect(await server.reserveKeepsSurvivorsServiceable( + reserveBytes: await server.resolvedActivationReserveBytes)) + await server.resliceGrowSurvivors() + + await expectResidentsServiceable(residents) + var total = UInt64(await newcomerBridge.engineKVBytesCapacity()) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= budget) + await newcomerBridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift new file mode 100644 index 0000000000..12ff78b434 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift @@ -0,0 +1,139 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLX + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import ProviderCore + +/// The 0.10.5 "would leave a model without its fixed request workspace" +/// refusal: six catalog models resident on a 192 GB Mac, then +/// gemma-4-26b-qat-4bit or gpt-oss-20b as the seventh slot. Configuration +/// only: no weights, forward pass or tensor evaluation. +/// +/// KV rates are the engine's marginal fp16 rate (full-attention rows only). +/// Weights are the production catalog's `total_size_bytes`. Fixed request +/// workspace is each engine's recurrent state per request, a lower bound: +/// it leaves out allocator rounding, convolution state for Nemotron, and +/// assistant history. A slot's floor is what `EngineV2Bridge +/// .minimumServiceableGrantBytes` reports for that workspace. +enum ResliceFloorScenario { + struct Model { + let id: String + let modelType: String + let fp16KVBytesPerToken: Int + let maxContextLength: Int + let weightsBytes: Int + let fixedRequestBytes: Int + + var resliceSlot: EngineV2KVSizing.ResliceSlot { + .init(modelId: id, fp16KVBytesPerToken: fp16KVBytesPerToken, maxContextLength: maxContextLength) + } + + var sizing: SlotSizingSnapshot { + .init(weightsBytes: weightsBytes, fp16KVBytesPerToken: fp16KVBytesPerToken, + maxContextLength: maxContextLength, defaultMaxTokens: 8192) + } + + var minimumGrantBytes: Int { ResliceFloorScenario.minimumGrantBytes(fixedRequestBytes: fixedRequestBytes) } + } + + static let physicalBytes: UInt64 = 192 << 30 + + /// The fleet budgets the reporting provider logged for the two refusals. + static let reportedGemmaBudget: UInt64 = 51_467_271_830 + static let reportedGPTOSSBudget: UInt64 = 54_999_766_706 + + static let gemmaQAT = Model(id: "gemma-4-26b-qat-4bit", modelType: "gemma4", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 15_641_239_295, fixedRequestBytes: 0) + static let gptOSS = Model(id: "gpt-oss-20b", modelType: "gpt_oss", + fp16KVBytesPerToken: 24_576, maxContextLength: 131_072, + weightsBytes: 12_104_215_835, fixedRequestBytes: 0) + + /// The resident set. Its Qwen recurrent rows come from decoding each + /// model's text configuration. With MTP on (`mtp_mode = auto`), Qwen + /// adds one compact-replay generation to the three base generations; + /// Nemotron Lightning's request-stateful assistant at the tested depth + /// adds depth − 1. + static func residents() throws -> [Model] { + let base = CBv2RecurrentStateSpec.maximumLiveGenerations + let depth = CBv2MTPConfig.testedMaxDraftTokens + let wide = try qwenGeneration(wide: true) + let narrow = try qwenGeneration(wide: false) + // 23 Mamba-2 layers, FP32 SSM state [64 heads, 64, 128] each. + let lightningGeneration = 23 * 64 * 64 * 128 * 4 + return [ + Model(id: "ternary-bonsai-2-27b", modelType: "prism_hadamard_qwen35", + fp16KVBytesPerToken: 65_536, maxContextLength: 262_144, + weightsBytes: 8_608_670_713, fixedRequestBytes: base * wide), + Model(id: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: "qwen3_5_moe", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 21_308_856_601, fixedRequestBytes: (base + 1) * narrow), + Model(id: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: "qwen3_5", + fp16KVBytesPerToken: 65_536, maxContextLength: 262_144, + weightsBytes: 16_320_415_757, fixedRequestBytes: (base + 1) * wide), + Model(id: "gemma-4-26b", modelType: "gemma4", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 27_986_040_506, fixedRequestBytes: 0), + Model(id: "qwen3.5-35b-a3b", modelType: "qwen3_5_moe", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 20_893_747_852, fixedRequestBytes: (base + 1) * narrow), + Model(id: "nvidia-nemotron-3.5-lightning", modelType: "nemotron_h", + fp16KVBytesPerToken: 6_144, maxContextLength: 262_144, + weightsBytes: 19_059_595_830, fixedRequestBytes: (base + depth - 1) * lightningGeneration), + ] + } + + static let lightningID = "nvidia-nemotron-3.5-lightning" + + /// An ordinary engine's floor at the SDK's default admission watermark; + /// an engine with no fixed workspace reports the base minimum. + static func minimumGrantBytes(fixedRequestBytes: Int) -> Int { + guard fixedRequestBytes > 0 else { return Int(EngineV2KVSizing.minimumServiceableGrantBytes) } + let watermark = AdmissionV2.Config().watermarkFraction + let capacity = 16 << 30 + return EngineV2Bridge.minimumOrdinaryGrantBytes( + fixedRequestBytes: fixedRequestBytes, capacityBytes: capacity, + admissibleCapacityBytes: capacity - Int(Double(capacity) * watermark), + watermarkFraction: watermark) + } + + /// A real ordinary engine over a contiguous backend holding `grant`, with + /// `fixedRequestBytes` of workspace per request at the SDK's default + /// watermark: its bridge reports the production floor and serving width. + static func makeBridge(modelId: String, fixedRequestBytes: Int, grant: Int, + kvBytesPerToken: Int = 0) -> EngineV2Bridge { + let fixture = DeadlineAdmissionFixtureModel() + let admission = AdmissionV2.Config(elementBytes: 4, fixedBytesPerRequest: fixedRequestBytes) + let engine = EngineV2(model: fixture, layerKinds: fixture.kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: grant)), + cacheProvider: CBv2LayerCacheBank(layerKinds: fixture.kinds), + schedulerConfig: .init(maxConcurrentRequests: 4, enablePrefixCache: false), + admissionConfig: admission) + return EngineV2Bridge(engine: engine, modelId: modelId, + tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: [], + kvBytesPerToken: kvBytesPerToken, fixedRequestBytes: engine.resolvedFixedBytesPerRequest, + admissionWatermarkFraction: admission.watermarkFraction, kvBackendKind: .contiguous) + } + + /// One recurrent generation of the dense 27B (`wide`) or the 35B-A3B + /// Qwen text tower. + private static func qwenGeneration(wide: Bool) throws -> Int { + let fields: [String: Any] = [ + "hidden_size": wide ? 5120 : 2048, + "num_hidden_layers": wide ? 64 : 40, + "num_attention_heads": wide ? 24 : 16, + "num_key_value_heads": wide ? 4 : 2, + "head_dim": 256, "full_attention_interval": 4, + "linear_num_key_heads": 16, "linear_key_head_dim": 128, + "linear_num_value_heads": wide ? 48 : 32, + "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, + "max_position_embeddings": 262_144, + ] + let config = try JSONDecoder().decode(Qwen35TextConfiguration.self, + from: JSONSerialization.data(withJSONObject: fields)) + return try config.cbv2RecurrentStateSpec(activationDType: .bfloat16).fixedBytesPerRequest() + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift new file mode 100644 index 0000000000..f70216b22c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift @@ -0,0 +1,150 @@ +// Copyright © 2026 Eigen Labs. +// +// `EngineV2KVSizing.resliceGrants` given each slot's serviceability floor: +// the reported 0.10.5 refusal (`ResliceFloorScenario`), the unchanged +// proportional result whenever it already clears every floor, refusal when +// Σ(floors) exceeds the budget, and Σ(grants) ≤ budget throughout. + +import Foundation +import Testing + +@testable import ProviderCore + +@Suite("EngineV2 KV re-slice with slot floors (pure)") +struct EngineV2ResliceFloorTests { + private static let gib = 1 << 30 + + private static func floors(_ models: [ResliceFloorScenario.Model]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: models.map { ($0.id, $0.minimumGrantBytes) }) + } + + private static func sum(_ grants: [String: Int]) -> UInt64 { + grants.values.reduce(UInt64(0)) { $0 + UInt64($1) } + } + + @Test("the reported refusal: Lightning starves under the proportional split; floors first admits", + arguments: [ + (ResliceFloorScenario.gemmaQAT.id, ResliceFloorScenario.reportedGemmaBudget), + (ResliceFloorScenario.gptOSS.id, ResliceFloorScenario.reportedGPTOSSBudget), + ]) + func reportedRefusalIsAdmitted(newcomerID: String, budget: UInt64) throws { + let newcomer = newcomerID == ResliceFloorScenario.gptOSS.id + ? ResliceFloorScenario.gptOSS : ResliceFloorScenario.gemmaQAT + let residents = try ResliceFloorScenario.residents() + // The newcomer has only the base floor, as on the load path. + let minimums = Self.floors(residents) + let floorTotal = residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + } + #expect(UInt64(floorTotal) * 5 < budget) + + let proportional = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget) + #expect(!EngineV2KVSizing.resliceMeetsServiceabilityFloor(proportional, minimumGrantBytes: minimums)) + let lightningFloor = try #require(minimums[ResliceFloorScenario.lightningID]) + let lightningShare = try #require(proportional[ResliceFloorScenario.lightningID]) + #expect(lightningShare < lightningFloor) + + let grants = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget, minimumGrantBytes: minimums) + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: minimums)) + #expect(grants.count == 7 && Self.sum(grants) <= budget) + // Each slot holds its floor plus its weighted share of the rest. + let remainder = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget - UInt64(floorTotal)) + for slot in residents + [newcomer] { + let floor = minimums[slot.id] ?? Int(EngineV2KVSizing.minimumServiceableGrantBytes) + #expect(grants[slot.id] == floor + (remainder[slot.id] ?? 0), "\(slot.id)") + } + } + + @Test("a proportional split that clears every floor is returned unchanged") + func clearingSplitIsUnchanged() throws { + let residents = try ResliceFloorScenario.residents() + let sixSlotBudget: UInt64 = 65_459_679_896 + let six = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: sixSlotBudget) + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(six, minimumGrantBytes: Self.floors(residents))) + #expect(EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: sixSlotBudget, minimumGrantBytes: Self.floors(residents)) == six) + + let pair = [ResliceFloorScenario.gemmaQAT.resliceSlot] + let budget = UInt64(40 * Self.gib) + #expect(EngineV2KVSizing.resliceGrants(existing: pair, newcomer: ResliceFloorScenario.gptOSS.resliceSlot, + fleetKVBudgetBytes: budget, minimumGrantBytes: [:]) + == EngineV2KVSizing.resliceGrants(existing: pair, newcomer: ResliceFloorScenario.gptOSS.resliceSlot, + fleetKVBudgetBytes: budget)) + } + + @Test("Σ floors above the budget, or an unprovable floor, keeps the proportional split and refuses") + func infeasibleFloorsStillRefuse() throws { + let residents = try ResliceFloorScenario.residents() + let newcomer = ResliceFloorScenario.gemmaQAT + let minimums = Self.floors(residents) + let floorTotal = residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + } + var unprovable = minimums + unprovable["gemma-4-26b"] = Int.max + let cases: [(UInt64, [String: Int])] = [ + (UInt64(floorTotal - 1), minimums), + (ResliceFloorScenario.reportedGemmaBudget, unprovable), + ] + for (budget, floors) in cases { + let proportional = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget) + let grants = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget, minimumGrantBytes: floors) + #expect(grants == proportional) + #expect(!EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: floors)) + } + } + + @Test("Σ grants ≤ budget at every budget; every floor is met exactly when Σ floors fits") + func budgetInvariantAcrossBudgets() throws { + let residents = try ResliceFloorScenario.residents() + let slots = residents.map(\.resliceSlot) + let newcomer = ResliceFloorScenario.gptOSS.resliceSlot + let minimums = Self.floors(residents) + let floorTotal = UInt64(residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + }) + var budgets: [UInt64] = [0, floorTotal - 1, floorTotal, floorTotal + 1, UInt64(Int.max)] + var step = floorTotal / 2 + while step < 4 * ResliceFloorScenario.reportedGPTOSSBudget { + budgets.append(step) + step += 997_001_003 + } + for budget in budgets { + let grants = EngineV2KVSizing.resliceGrants(existing: slots, newcomer: newcomer, + fleetKVBudgetBytes: budget, minimumGrantBytes: minimums) + #expect(Self.sum(grants) <= min(budget, UInt64(Int.max)), "budget \(budget)") + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: minimums) + == (floorTotal <= budget), "budget \(budget)") + } + // At the boundary every slot holds exactly its floor. + let tight = EngineV2KVSizing.resliceGrants(existing: slots, newcomer: newcomer, + fleetKVBudgetBytes: floorTotal, minimumGrantBytes: minimums) + for slot in slots + [newcomer] { + #expect(tight[slot.modelId] == minimums[slot.modelId] ?? Self.gib, "\(slot.modelId)") + } + } + + @Test("an unknown rate splits what remains after the floors equally") + func unknownRateSplitsRemainderEqually() { + let starved = EngineV2KVSizing.ResliceSlot(modelId: "a", fp16KVBytesPerToken: 0, maxContextLength: 0) + let other = EngineV2KVSizing.ResliceSlot(modelId: "b", fp16KVBytesPerToken: 20_480, maxContextLength: 131_072) + let budget = UInt64(6 * Self.gib) + let grants = EngineV2KVSizing.resliceGrants(existing: [starved], newcomer: other, + fleetKVBudgetBytes: budget, minimumGrantBytes: ["a": 4 * Self.gib]) + #expect(grants == ["a": 4 * Self.gib + Self.gib / 2, "b": Self.gib + Self.gib / 2]) + } + + @Test("a single slot keeps the whole budget whatever its floor") + func singleSlotKeepsWholeBudget() { + let budget = UInt64(3 * Self.gib) + let grants = EngineV2KVSizing.resliceGrants(existing: [], newcomer: ResliceFloorScenario.gemmaQAT.resliceSlot, + fleetKVBudgetBytes: budget, minimumGrantBytes: [ResliceFloorScenario.gemmaQAT.id: 8 * Self.gib]) + #expect(grants == [ResliceFloorScenario.gemmaQAT.id: Int(budget)]) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift index 1f52708d15..f1d5168c67 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift @@ -55,14 +55,36 @@ extension NemotronSuperManagedSlotTests { #expect(await fixture.budget.outstandingReservedBytes() == 0) } - /// The build is checked against its grant with the planned lane and - /// round; publication re-slices it beside the resident models. Beside an - /// idle model with a far larger KV share (the fixture owner publishes its - /// 1,024-token context against that model's 8,192), Super's grant is a few - /// MiB and serves no request: the load fails, the slot is unpublished and - /// retired, and the co-resident model keeps its grant and is not evicted. + /// Beside an idle model with a far larger KV share (the fixture owner + /// publishes its 1,024-token context against that model's 8,192), Super's + /// proportional share is a few MiB. Both floors fit the budget, so Super + /// is funded to its floor and loads; the co-resident model keeps its own. @Test(.timeLimit(.minutes(2))) - func publishedGrantThatServesNoRequestFailsTheLoad() async throws { + func superBesideALargerKVShareLoadsAtItsFloor() async throws { + let fixture = try await Self.coResidentFixture(weightsGiB: 1, availableGiB: 110) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let loop = fixture.loop + await loop.setEngineV2SlotHooksForTesting(ProviderLoop.EngineV2SlotHooks( + physicalMemoryBytes: 128 << 30, makeEngine: { _, _ in throw CancellationError() })) + try await loop.ensureModelLoaded(modelId: Self.modelID, allowEviction: false, + revisionDirectory: fixture.directory) + let owner = try #require(await loop.nemotronSuperOwnerForTesting(modelId: Self.modelID)) + let grant = await owner.bridge.resliceAdmissionBytesClaim() + #expect(grant >= (await owner.bridge.minimumServiceableGrantBytes())) + #expect(await owner.bridge.superGrantRefusal(grantBytes: grant, requests: 1) == nil) + let coResidentGrant = try #require(fixture.idle.capacityUpdates.last) + #expect(coResidentGrant >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + #expect(await loop.modelLoadingResidentIDs() == [Self.coResidentID, Self.modelID].sorted()) + #expect(await loop.unloadModel(Self.modelID)) + } + + /// The newcomer check counts Super's planned lane and round beside its + /// grant. A co-resident model whose own floor leaves less than Super's + /// base floor of that budget refuses the load before anything is built: + /// nothing is published or retained, and the co-resident model keeps its + /// grant and is not evicted. + @Test(.timeLimit(.minutes(2))) + func floorsAboveTheBudgetRefuseTheLoadBeforeTheBuild() async throws { let fixture = try await Self.coResidentFixture(weightsGiB: 1, availableGiB: 110) defer { try? FileManager.default.removeItem(at: fixture.directory) } let loop = fixture.loop @@ -70,6 +92,11 @@ extension NemotronSuperManagedSlotTests { physicalMemoryBytes: 128 << 30, makeEngine: { _, _ in throw CancellationError() })) await loop.resliceGrowSurvivorsForTesting() let lone = try #require(fixture.idle.capacityUpdates.last) + // Its floor leaves 1.75 GiB of the lone budget, less than Super's + // planned reservations and base floor need. + let coResident = ResliceFloorScenario.makeBridge(modelId: Self.coResidentID, + fixedRequestBytes: Int(Double(lone - (7 << 28)) * 0.95) - (1 << 30), grant: lone) + await loop.modelLoadingInstallSlot(Self.coResidentID, bridge: coResident, weightsBytes: 1 << 30) var refusal: Error? do { try await loop.ensureModelLoaded(modelId: Self.modelID, allowEviction: false, @@ -77,15 +104,15 @@ extension NemotronSuperManagedSlotTests { } catch { refusal = error } let error = try #require(refusal) #expect(ProviderLoop.loadErrorStatusCode(for: error) == 503) - #expect("\(error)".contains("serves 1 concurrent request(s)"), "\(error)") - #expect(await loop.modelLoadingLastLoadError()?.message.contains("serves 1 concurrent request(s)") == true) + #expect("\(error)".contains("below its serviceable KV grant"), "\(error)") + #expect(await loop.modelLoadingLastLoadError()?.message.contains("below its serviceable KV grant") == true) #expect(await loop.nemotronSuperOwnerForTesting(modelId: Self.modelID) == nil) #expect(await loop.engineV2Runtime.bridge(forModel: Self.modelID) == nil) #expect(await loop.modelLoadingResidentIDs() == [Self.coResidentID]) - #expect(fixture.idle.shutdownCalls == 0) - #expect(fixture.idle.capacityUpdates.last == lone, "the co-resident model's grant is restored") + #expect(await coResident.engineKVBytesCapacity() == lone, "the co-resident model keeps its grant") #expect(await fixture.budget.outstandingReservedBytes() == 0) #expect(await loop.nemotronSuperRetainedWeightBytesForTesting() == 0) + await coResident.shutdown() } /// A load whose native work did not retire keeps the installation's size