Repository navigation
Studio: two-Spark serving orchestrator with an async replica router - #10323
danielhanchen wants to merge 314 commits into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 38ffb836f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try: | ||
| await process.stop(timeout = 5.0) | ||
| await process.start() | ||
| except Exception as exc: | ||
| logger.warning("spark serving: relaunch failed to spawn ssh: %s", exc) | ||
| continue | ||
| # Settle: an immediate exit means the peer refuses (port busy, OOM), retry | ||
| # with the next backoff; a live session means the server is loading. | ||
| await asyncio.sleep(3.0) | ||
| if process.alive: | ||
| logger.info( | ||
| "spark serving: peer %s relaunched (remote pid %s)", | ||
| process.name, | ||
| process.remote_pid, | ||
| ) |
There was a problem hiding this comment.
Reload the local model after restarting its RPC server
For layer_split, the peer process is ggml-rpc-server, which owns the remote tensor allocations and handles referenced by the attached local llama-server. Restarting only that empty daemon after a crash cannot restore those allocations or the local process's RPC session, yet this path declares recovery as soon as the new process remains alive for three seconds. Subsequent requests therefore continue failing until the local model is reloaded; recovery must restart/reload the attached llama-server together with the RPC server rather than treating the generic peer-process restart as sufficient.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed on the diagnosis, declining the change. A ggml-rpc-server restart genuinely cannot restore the remote allocations or the local llama-server's RPC session, so for a layer split the peer is not recoverable by a process restart at all. Making that correct means restarting and reloading the attached llama-server, which for the models this path exists to serve is a multi-minute reload of a model that does not fit one node. That is a redesign of the recovery story rather than a bug fix, and it is not something I want to land inside this PR.
| checks = " && ".join(f"test -f {shlex.quote(p)}" for p in needed) | ||
| rc, out, _ = await ssh_run(peer, f"{checks} && echo YES || echo NO", timeout = 25.0) | ||
| self.peer_model_present = rc == 0 and out.strip().endswith("YES") |
There was a problem hiding this comment.
Confirm peer files match the primary before routing traffic
The replica preflight checks only that each path is a regular file. If the peer has an older, partially replaced, or otherwise different GGUF/adapter at the same pathname, its server can become healthy and the router will silently alternate requests between different model weights, corrupting reproducibility and potentially producing different answers within one workload. Compare at least sizes plus a trustworthy artifact identity before admitting the peer rather than treating pathname existence as equivalence.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. Preflight deliberately asks whether the launch's files exist on the peer, and it now expands the full shard set (9499a23). Going further, to comparing sizes or an artifact identity, is guarding against the operator having put a different file at the same path, which is user error rather than legitimate well-formed input. It also costs a stat round trip per file on every replica start, and a size compare would still not establish identity. If the peer's copy is stale the honest fix is in provisioning, which is what rsync over the rail already does, rather than a preflight that can only ever detect some of the ways two files differ.
| out.append(arg) | ||
| out += ["--host", host, "--port", str(port)] |
There was a problem hiding this comment.
Authenticate the replica's cluster-facing listener
In the default configuration the local llama-server has no --api-key, and replica_argv copies that unauthenticated command while changing --host from loopback to the peer's cluster address. Any process able to reach that interface can then invoke the peer directly, bypassing Studio authentication, admission control, monitoring, and request cancellation. Generate a router-to-peer credential for every replica even when direct streaming is disabled, and have the router supply it upstream.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The replica listener binds the peer's cluster-rail address, a private point-to-point link between the two Sparks the same operator owns, and the local llama-server is equally unauthenticated in the default configuration, so this is not an asymmetry the replica introduces. Adding a router-to-peer credential is a product decision about the cluster trust boundary rather than a correctness bug, and it would touch the router's upstream path for every request.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8f8be0d8ff
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| head_dim = n_embd // n_head | ||
| if not (n_layer and n_kv and head_dim): | ||
| return None | ||
| return int(2 * n_layer * int(n_ctx) * n_kv * head_dim * kv_bytes_per_elem(cache_type)) |
There was a problem hiding this comment.
Use architecture-aware KV sizing
For supported non-GQA layouts, this formula prices every block as a conventional two-sided KV cache. The existing backend estimator handles MLA as K-only, hybrid Mamba/KDA models as caching only their attention blocks, and sliding-window layers with reduced cell counts; for models such as Qwen3.5 or Kimi at long contexts, this simplified calculation can overstate KV memory several-fold and make before_load choose an unnecessary layer_split even though the model and its real cache fit on one Spark. Reuse the architecture-aware estimator or mirror those metadata branches in the topology estimate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the reason is the direction of the error. The item's own case is that the formula 'can overstate KV memory several-fold' for MLA, hybrid Mamba/KDA and sliding-window layouts. The docstring already records that choice: SWA layers are charged in full, so the estimate errs high. On this hardware that is deliberate. Overstating costs an unnecessary layer split, which is slower; understating puts a model on a node that cannot hold it, and with 121.69 GiB shared between CPU and GPU the failure is an out-of-memory, not a slowdown. A tighter architecture-aware estimate is the right long-term shape, but it is only an improvement if it can be shown never to err low on the layouts it newly recognises, and that is a bigger piece of work than a topology hint warrants. An item here is genuine if it shows the estimate reading LOW somewhere, which is how 3944437389 was handled.
| if backend.primary: | ||
| # Not ours to restart: LlamaCppBackend respawns its own child on the next | ||
| # failed request, and the router routes around it meanwhile. | ||
| return |
There was a problem hiding this comment.
Respawn a primary evicted by health checks
If the primary dies while idle and the router health loop observes it first, it is marked unhealthy and all subsequent generation requests are routed only to the peer. This callback then does nothing, so no request reaches the dead primary to trigger LlamaCppBackend._respawn_if_dead, contrary to the assumption in the comment; the deployment remains permanently at half capacity until an unrelated direct-primary operation or reload happens. Trigger the backend's recovery from this callback or from the supervisor when health eviction identifies the primary.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The router's health probe re-admits a backend on its own: on a successful probe it sets healthy = True and logs the backend as healthy again, so a primary dropped by consecutive failures returns to rotation without anything in spark_serving acting. That is why _on_backend_down returns early for the primary; LlamaCppBackend respawns its own child on the next request, and the poller then picks it up. Respawning it from here as well would race that.
| process = self.peer_process | ||
| if process is not None and process.alive: | ||
| # Health failed but the ssh session lives: the server may be loading. Give | ||
| # the health loop time; only a dead process triggers a relaunch. | ||
| return |
There was a problem hiding this comment.
Recover peers that remain alive but unhealthy
When a previously healthy peer wedges while its SSH process remains alive, the router removes it after repeated health failures, but this branch returns without scheduling any recovery. Later failed probes cannot invoke this callback again because the backend is already unhealthy, and the supervisor only relaunches an exited process, so a permanently hung peer remains out of rotation indefinitely. After a bounded grace period for transient health failures, terminate and relaunch an alive-but-unhealthy replica.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The early return when the ssh session is alive is deliberate and load-bearing: a peer loading a model that does not fit one node takes minutes over the rail, and killing it because health has not come up yet would turn a slow start into a relaunch loop. The router's health probe re-admits the peer the moment it answers. What is left, a peer that is alive but permanently wedged, degrades to serving on the remaining node rather than breaking, and separating wedged from loading needs a timeout longer than a 70B load over the rail. That is a policy change with a real risk of making the common case worse.
| finally: | ||
| backend.queued -= 1 |
There was a problem hiding this comment.
Wake the next waiter after a queued cancellation
If a slot release wakes the first queued request and that request is cancelled before it increments in_flight, this finally removes it from the queue without notifying another waiter. The slot is then free while the remaining queued requests continue sleeping, and because no in-flight request owns that slot there may be no later _release to wake them; they can stall until the 120-second queue timeout despite available capacity. Notify the condition when a departing waiter leaves room for another queued request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The condition variable guards in-flight room, not queue slots: waiters block on _has_room(backend), which turns on only when _release decrements in_flight, and that path already notifies. A queued waiter leaving creates no in-flight room, so a notify there would wake every waiter to re-test a predicate that has not changed. The queue slot it does free is read directly by _choose on the next arrival, which never waits on the cv.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d723c8868d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not llama_server_supports(PIPELINE_GROUPS_FLAG): | ||
| out["reason"] = f"bundle llama-server lacks {PIPELINE_GROUPS_FLAG}" |
There was a problem hiding this comment.
Probe the llama-server binary the loader will launch
When LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, or the custom llama.cpp folder selects a different executable, this capability check still probes only the managed bundle binary. If the bundle supports --pipeline-groups but the selected runtime does not, before_load injects the unsupported flag into that runtime and every affected layer-split load fails at startup. Resolve and probe the same executable as LlamaCppBackend._find_llama_server_binary, or defer the decision until the actual launch binary is known.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one as a defect: the probe already reads the executable the loader will launch. It goes through llama_server_binary(), which is the backend's own resolver and nothing else:
def llama_server_binary() -> Optional[str]:
"""The llama-server this node will actually LAUNCH, asked of the backend's own
``_find_llama_server_binary`` and never searched for here: a second search order is a
defect, and it was one ..."""
from core.inference.llama_cpp import LlamaCppBackend
found = LlamaCppBackend._find_llama_server_binary()llama_server_help() and llama_server_supports() both default to that, so LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH and a custom llama.cpp folder all select the same binary for the probe and for the launch. There is no separate bundle search left; there used to be, and removing it is what that docstring is about.
The reason this reads as a bug is my fault: llama_server_help's own docstring still said "the bundle llama-server's --help", which is exactly the thing the resolver was changed to stop doing. Corrected in 2bd9922, along with a test, test_the_capability_probe_follows_the_binary_the_loader_will_launch, that points the resolver at two builds with different help text and asserts the answer follows it, so the property is held rather than merely described.
| if pipeline_groups and int(pipeline_groups) > 1: | ||
| out += [PIPELINE_GROUPS_FLAG, str(int(pipeline_groups))] | ||
| if slots is not None: | ||
| out += ["--parallel", str(max(1, int(slots)))] |
There was a problem hiding this comment.
Do not inject a user-denied parallel flag
Whenever the bundle supports pipeline groups, this appends --parallel to request.llama_extra_args, but the request is subsequently passed into _load_model_impl, whose first validation rejects --parallel as an Unsloth-managed flag in llama_server_args.validate_extra_args. Consequently the default pipeline-groups path returns HTTP 400 before llama-server starts, so layer-split loads fail precisely on the builds intended to enable the feature. Carry the adjusted slot count through the first-class n_parallel field or add these arguments only after user-argument validation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one: the slot count already goes through the first-class field, and --parallel is not appended to llama_extra_args.
layer_split_extra_args() emits the RPC device flags only, and says why in its docstring:
The slot count the groups need is NOT emitted here:
-np/--parallelis denied in a pass-through (llama_server_args._DENYLIST_GROUPS), so a--parallelin these extras failed the load with HTTP 400 before llama-server started.
and _with_rpc_args carries it the way you describe:
if int(groups["pipeline_groups"]) > 1:
# --parallel has to be a positive multiple of N, and it is a request field.
updates["n_parallel"] = max(PARALLEL_MIN, int(groups["slots"]))So the default pipeline-groups path does not return 400. It is also covered live: the layer-split runs on this pair launched with the flag present in argv and the server reporting two groups.
|
Checked that the load and chat paths fall through untouched off a paired Spark, with the router only attached once enabled() is true, and the replica and layer split numbers line up with the planner tables in spark_cluster.py. Will get this reviewed once #10280 lands. |
…ovider rpc_serving now strips only the blocks the cluster recorded and asks the provider for the rest, so the fixed two-node block moves here with the even tensor-split constant; a reload still re-plans it as before.
…esolves AutoConfig reads back _attn_implementation = None for a checkpoint that never named one, and the model constructor then takes SDPA, so --pp-backend legacy rejected every ordinary config. The check now resolves the backend the model class will use (SDPA when it supports it, eager otherwise) and still refuses eager.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
subprocess.run(shell=True, timeout=...) kills only the shell, so a timed-out bandwidth check or spark doctor left torchrun and its worker holding the GPU and waiting for rendezvous. The local rank now runs in its own session and a timeout or interrupt stops the whole group (SIGTERM, then SIGKILL).
# Conflicts: # tests/studio/test_spark_cluster_review_fixes.py
… a CPU-only runner
…ator # Conflicts: # unsloth_cli/tests/test_spark_offbox.py
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Stacked on #18277 (N-node serving) and merges #10280 (the DGX Spark toolkit), so until #10280 lands this diff also shows the toolkit. Optional: multi-machine serving no longer depends on this PR.
The helpers this PR introduced and N-node serving shares (binaries and capability probes, GGUF and KV sizing, launch files, ssh and peer processes) now live in
core/inference/rpc_serving.pyin #18277, andspark_servingcalls them through it.rpc_servinghands every load hook tospark_servingwhen it is installed. Replicas, the two-node split and the handoff between a two-Spark split and a cluster config behave as before:test_spark_legacy_golden.pypasses with its fixture unchanged;test_cluster_spark_handoff.py;When Studio or Desktop loads a GGUF on a paired DGX Spark, the backend now picks one of three topologies from
spark_cluster.recommend_topologyand runs it, with both Sparks working whenever the workload allows and nothing ever blocking the event loop. Off a paired Spark none of this runs.Topologies
singlereplicas--host,--portand the node-local slot save path change), behind an in-process router on the main nodelayer_splitggml-rpc-serveron the peer (-H <cluster address>,-cwhen the model file is there), and this node's llama-server launched with--rpc <peer>:<port> --device RPC0,CUDA0 -sm layer. No pipeline flag: llama.cpp enables it itself when the RPC backend advertises async and events, which b10796 does.--pipeline-groups 2is added on top when the bundle's llama-server has it (see below)The
rpc_protocol_preflightfrom #10280 runs before a layer split and its problems are surfaced as the reason for falling back tosingle.Device order. The layer split lists the RPC device first and the local CUDA device last (
--device RPC0,CUDA0). llama.cpp assigns the output layer to the last device, so this keeps the last layers, the output projection and the logits on the local GPU: the wire carries only the hidden state (20 KB per row each way) instead of returning 1 MB per row of F32 logits every decode step, and the sampler reads local memory. Measured on Qwen3.8-27B split across the pair at 32 concurrent: one context 99.7 and 98.1 tok/s against 94.9 and 92.9 with the old order; with--pipeline-groups 2130.4 and 131.3 against 75.5 and 76.3, both GPUs at 76 to 79 percent. The order is a precondition for the groups to pay.Pipeline groups. unslothai/llama.cpp PR 187 adds
llama-server --pipeline-groups N(ready for review, in no prebuilt yet): N contexts from one model, the slots partitioned across them, N interleaved decode loops, so one group's batch runs on the peer's layers while another's runs on this node. Measured on Qwen3.8-27B split across the pair with the device order above, 32 / 64 / 128 concurrent, two repeats, one clock state: one context 99.7 / 117.2 / 124.2 tok/s, two groups 130.4 / 157.2 / 170.1 (1.31x to 1.37x; 1.12x to 1.13x of a single Spark), both GPUs at 76 to 79 percent against 42 to 47. Sospark_serving.pipeline_groups_planadds--pipeline-groups 2by default, with the slot count rounded up to an even number on the request'sn_parallel(never as a pass-through--parallel, whichllama_server_argsdenies) and kept inside the field's 1..64 range, only for alayer_split, and only after the bundle's llama-server has been found to take the flag:llama_server_supports("--pipeline-groups")looks inllama-server --help(probed once per binary path and mtime, 20 s timeout, never raises, False on any failure) and, because the fork takes the flag out of argv intools/serverand never prints it in its usage,llama_server_acceptsthen runsllama-server --pipeline-groups 1 --help, which exits 0 on a build that has it and stops atinvalid argumenton every other (checked against the real prebuilt b10796 and the PR 187 build). A bundle without the flag launches exactly as before;UNSLOTH_SPARK_PIPELINE_GROUPS=0turns it off and=Nsets the count./api/inference/spark/statusreportspipeline_groups(the integer used, or 0 with apipeline_groups_reason). Nothing here runs forsingle,replicasor off a paired Spark. PR 187 commit a1dd7c5e8 gives every pipeline group its own speculative state, so groups and a drafter are no longer either/or, andreconcile_split_speculationpicks between the three configurations on the concurrency the load asked for (the pass-through--parallel/-np, else the slot count, which is the same number the launched--parallelis rounded up from): from 16 concurrent rows up it asks for both, below that it keeps the speculation and drops the groups, and with nothing to speculate with it keeps the groups and launches withspeculative_typeoff so a sidecar drafter the backend would pick on its own is never in the launch. The measurement and the crossover are below. A build without the per-group state is not asked for the combination:llama_server_accepts_groups_with_drafterruns the server for real against a model path that cannot exist, becausetools/servervalidates that pair insideload_model, which--helpexits long before -- a--pipeline-groups N --spec-type draft-mtp --helpprobe exits 0 on the fork that refuses the pair as well as on the fork that runs it, and could never have said no (checked on both real builds). The check sits before the weights are read, so a refusing build stops at it and an accepting build gets past it and stops at the missing file, naming it; the discriminator is the output, not the exit status. No GPU, no file, no listener, 1.5 s once per build. A refusal falls back to keeping the speculation and dropping the groups.n_parallelstays a multiple of the group count, and--mmproj, control vectors and--sleep-idle-secondsare still refused with the groups whatever the speculation, so they cost the groups outright (extra_args_refuse_pipeline_groups). Studio's OWN projector counts too: the backend adds--mmprojfrom the model's repo afterbefore_loadhas run, and downloads it during the load when the cache does not have it, so a model resolved out of a hub snapshot only gets the groups when the load turns vision off (projector_blocks_pipeline_groups); a plain local GGUF with no projector beside it keeps them./api/inference/spark/statusreportssplit_configandsplit_config_reasonbesidemtp, so an operator sees which of the three ran and why. The split also passes--cache-ram 0: the host-RAM prompt cache saves and loads a whole slot state on every handover, mostly on the peer, and measured 75.9 tok/s with a 33 s median TTFT against 99.7 and 7.5 s without it at 32 concurrent (two groups collapse to 6.9 tok/s with it on); the KV prefix reuse inside a slot is untouched. The replicas rule for a model that fits is unchanged: at 32 rows replicas measured 1.91x against 1.12x for the grouped split.recommend_topologyandspark planquote the server-measured numbers in the layer split reason, with the constants inspark_cluster.pybeside the other measured tables.Those pipeline-groups constants are conservative, and deliberately left as they are.
PIPELINE_GROUPS_DECODE_TOKS,PIPELINE_GROUPS_SPLIT_SPEEDUPandPIPELINE_GROUPS_OVER_ONE_CONTEXT(1.31x / 1.34x / 1.37x at 32 / 64 / 128 rows) were all measured without--kv-unified, which Studio always passes -- the same gap that made theGROUPS_X_MTP_*table wrong and had to be re-measured. An independent re-run at 128 rows with--kv-unified, both nodes pinned together at 300,1690 and the pin verified fromclocks.smunder load (local 1678, peer 1683), measured 213.12 tok/s for two groups against 116.22 for one context, 1.83x, against the 1.37x this table carries for that row. Server-sidellamacpp:tokens_predicted_totalagreed with the client count to 8 tokens (the harness's one warmup request) in both arms.So the table understates the split rather than overstating it, and the direction of every decision it drives is unchanged. Only the 128-row cell has been re-measured, and patching that one cell to 1.83x while 32 and 64 stayed on the older configuration would leave a table whose rows came from two different setups, which is worse than one that is uniformly conservative. Replacing it properly needs 32 and 64 (and the one-Spark column of
PIPELINE_GROUPS_DECODE_TOKS) re-measured with--kv-unifiedin a single clock-pinned block.MTP self speculation
A GGUF whose header carries
<arch>.nextn_predict_layersships its own MTP draft head:unsloth/Qwen3.5-4B-MTP-GGUFandunsloth/Qwen3.8-27B-GGUFdo (archqwen35,blk.N.nextn.*),Qwen3.6-35B-A3Bdoes not. llama.cpp b10796 loads those tensors and self-speculates with--spec-type draft-mtp; without them the flag is a no-op. The backend's own speculative path (LlamaCppBackend._build_speculative_flags, modeauto) already emits--spec-type draft-mtpfor such a file when the binary has the flag, with its memory reserve, its sub-3B and MLA gates and a retry without speculation when a drafter fails to build. So the orchestrator emits no second--spec-type(extras that own--spec-typewould switch all of that off). On a paired Spark it reads the header (gguf_nextn_predict_layers: first shard of a split file, the backend's cached streaming reader when importable, else theggufpackage, never raises), probes the bundle'sllama-server --helpfor--spec-type(same probe and cache as pipeline groups) and, when both hold, asks for the Spark-measured draft depth--spec-draft-n-max 3(the backend's GPU default is 2, from a B200 bench) in every topology:single, each replica (the peer copies this node's argv) and the layer split. A caller'sspeculative_type,spec_draft_n_max, or--spec-type/ draft flags in the extras (on the request, or inherited from the previous same-model load) are left alone;UNSLOTH_SPARK_MTP=0launches withspeculative_typeoff./api/inference/spark/statusreportsmtp(enabled,no head,server too old,user override,disabled by env,not launched,unknown) andmtp_reason, reconciled after the load against the argv that launched. Draft models and n-gram speculation stay off by default.Measured on one Spark (b10796 prebuilt,
-c 32768 --parallel 8 -fa on, prompts drawn from a real-text corpus rather than random token ids, npp 128 / ntg 256, one clock state at 1690 MHz; acceptance is accepted / drafted from/metrics; every ratio is aggregate decode tok/s over the same model with no speculation at the same concurrency):Long outputs (ntg 1024) hold up better: 27B draft-mtp 2.81x at 1 user and 2.01x at 8 (acceptance 0.97 / 0.87). Qwen3.6-35B-A3B has no head; a 4B draft model is 0.55x / 0.36x / 0.30x on it and ngram-simple 0.86x / 0.76x from 4 users, so nothing is turned on there. n-max 3 is the mixed-traffic default: 8 wins only at one user or on long outputs and loses at 8 users (acceptance 0.46). The planner carries
MTP_SPEEDUP_27B = {1: 2.61, 4: 1.87, 8: 1.59}andMTP_SPEEDUP_4B = {1: 2.04, 4: 1.67, 8: 1.46}withmtp_speedup()andmtp_note()beside the other measured tables;recommend_topologyanswersmtp_speedupandmtp_note, andspark planprints the note.MTP against two pipeline groups on the two-Spark split, measured (2026-09-06 03:02-03:30 PDT). Same fork build, Qwen3.8-27B UD-Q4_K_XL,
--rpc peer --device RPC0,CUDA0 -sm layer --cache-ram 0,-c 16384 --parallel 32, real-text prompts, npp 128 / ntg 256, one lock acquisition for the whole block.--pipeline-groups 2with MTP is not in this table because the build it ran on refused that combination at argv parse time; it is measured in the block below, on the build that accepts it.At 8 users one context with MTP wins outright, 78.4 against 49.6 and 49.3 for two groups (1.58x, TPOT 90 ms against 149): at 8 rows the batch cannot fill both stages, so the second group buys nothing while MTP turns each step into 2.3 accepted draft tokens per verify. At 32 users two groups win, mean 103.7 against 97.1, about 1.07x, and that is with both groups cells at the lower local clock (1690 and 1800 MHz) against 2390 for the one-context cells; the 1800 MHz repeat reproduced the 1690 MHz cell to within 3 percent, so the grouped split is insensitive to the local clock in this range. MTP still wins TTFT at 32 (3.8 s against 6.5 s). The crossover sits between 8 and 32 rows. MTP over the same one-context split is 1.49x at 8 and 1.07x at 32, with acceptance 0.77 / 0.63 against 0.77 / 0.62 on one Spark, so the RPC hop costs the draft head nothing. The second Spark only pays from 32 rows: at 8 users one Spark with MTP (85.6) beats the split with MTP (78.4) and is 1.73x the grouped split; at 32 the grouped split is 1.24x one Spark. So keeping MTP and dropping the groups is the right call for a small-batch split, which is what the block below now decides on the row count rather than always.
Pipeline groups AND speculative decoding on the same split, measured (2026-09-06). unslothai/llama.cpp PR 187 commit a1dd7c5e8 gives each pipeline group its own speculative state (its own draft or MTP context created against that group's target context, its own
common_speculativesized for the group's sequences), so--pipeline-groups N > 1is accepted together with--spec-type draft-mtpand with--model-draft; it is still refused with--mmproj,--control-vectorand--sleep-idle-seconds,--parallelmust stay a multiple of N, and one group is byte-for-byte unchanged. Measured on the pair with that build, Qwen3.8-27B UD-Q4_K_XL, the same split arguments as above,--parallel 32 --cache-ram 0, npp 128 / ntg 256, two repeats of every cell, aggregate decode tok/s at 8 and 32 concurrent:At 32 rows the combination wins outright: 133.8 tok/s at best and 131.1 on the repeat mean, 1.17x the best one-context MTP cell and 1.16x the best two-group cell (1.15x and 1.17x on the means). At 8 rows one context with MTP wins, 95.5 against 77.1 on the first repeat and 94.6 against 84.6 on the means, because two groups halve the rows per group and neither group then fills a stage; at 8 rows one Spark with MTP (85.6) also beats both split arms, so a model that fits should not be split there at all. Acceptance is unchanged by the second group (0.80 / 0.64 with one context, 0.72 / 0.68 with two), so a group's own drafter costs the head nothing. The crossover therefore sits between 8 and 32 rows; nothing was measured in between, so the rule turns at
GROUPS_X_MTP_CROSSOVER_ROWS = 16, the geometric midpoint of the two bracketing points, with both sides measured. The table, the ratios (GROUPS_X_MTP_DECODE_TOKS,GROUPS_X_MTP_OVER_MTP_ONLY,GROUPS_X_MTP_OVER_GROUPS_ONLY,GROUPS_X_MTP_ACCEPTANCE),groups_x_mtp_wins()andgroups_x_mtp_note()are inspark_cluster.pybeside the other measured tables, andspark_servingmirrors the three numbers it decides on so the decision needs nothing loaded.UNSLOTH_SPARK_PIPELINE_GROUPS=0andUNSLOTH_SPARK_MTP=0still override either half on any row count.Greedy output is not byte identical with MTP on, and that is not a speculation defect. The n-gram arms are byte identical to the baseline's greedy text; the MTP and draft-model arms are not. The control, on the unmodified server with the same four prompts at temperature 0: run one at a time twice they are identical, run one at a time on a later server they are identical, issued all at once prompts 0 and 1 change. The baseline is not batch invariant, and the MTP arms diverge on exactly those two prompts and always late (first differing character 291 to 761 of about 800), the signature of a near-tie flipped by a different floating-point reduction order in a differently shaped batch. Bit-exact reproducibility needs concurrency 1 and no speculation, a constraint that predates this change.
Tests:
test_spark_serving.py+test_spark_router.py47 -> 61 (synthetic GGUF headers with and without the key, split shards, garbage; the--spec-typeprobe true and false; the hidden--pipeline-groupsacceptance probe against a fake that rejects unknown flags like the real parser; the request carrying the depth in single, replicas and layer split; user override in every spelling; the env opt-out; status reconciled from the launched argv; the crossover above, below and at 16 rows; a fake server that takes the flag and takes a drafter but stops on the pair, as the fork before a1dd7c5e8 does;--parallelrounded to a multiple of the group count; mmproj, a control vector and idle sleep costing the groups; a user overriding either flag; and the mirrored constants against the planner's measured cells),test_spark_offbox.py95 -> 96 (planner tables, note,recommend_topologyandplan_deploymentfields).Router (
studio/backend/core/inference/spark_router.py)asynciolistener on loopback, onehttpx.AsyncClientpool per backend, response bodies relayed chunk by chunk as chunked transfer encoding, health probing of/healthand/slotsin a background task, backends taken out of rotation on failure and put back when healthy. The module docstring names the part of vLLM'sAsyncLLMdesign that is mirrored (handlers never block; engine and health work live in background tasks and meet the handlers through asyncio primitives) and the part that is not (the engines are separate llama-server processes, so there is no single engine core and no output queue).generate_chat_completionand popped by the router before forwarding; a session or user id; or a hash of the prompt prefix) maps to a backend by consistent hashing over the healthy set. The same key stays on one backend while both are up, re-maps when one goes down, and comes back when it recovers. Keyless requests use least outstanding. The trade-off (a burst in one conversation cannot spread) is documented in the code.-npslot count plus a small queue; beyond that the router answers 503 withRetry-After. Queue depth and per-backend in-flight counts are on the status endpoint.httpx, soLlamaCppBackend._respawn_if_deadkeeps working unchanged.LlamaCppBackend.base_urlanswers the router's address while replicas are attached, so the threaded chat generator, the OpenAI pass-through, tokenize and health all go through the router without changes.Gating and portability
spark_cluster.is_dgx_spark()plus a configured peer;UNSLOTH_SPARK_SERVING=0is a kill switch andUNSLOTH_SPARK_TOPOLOGYforces a topology. No POSIX-only calls on the import path, no new dependencies (httpx, fastapi and gguf are already required), ssh only spawned once the gate has passed and always as an asyncio subprocess or in a worker thread.GET /api/inference/spark/status(topology, reason, per-backend in-flight and queued counts, peer process and relaunch log) and one additivespark_topologyfield onGET /api/inference/status. No frontend changes.How the existing proxy works today (findings)
routes/inference.pygenerate_streamdrives the synchronous generatorbackend.generate_chat_responsewithawait asyncio.to_thread(next, gen, _DONE)per chunk; the upstream call is a synchronoushttpx.ClientinLlamaCppBackend._open_stream(core/inference/llama_cpp.py) iterated by_iter_text_cancellable. The event loop is not blocked, but each stream costs a worker thread and a thread hop per chunk._openai_passthrough_stream) and the Responses path use a per-requesthttpx.AsyncClientwithConnection: close; non-streaming calls share the per-loop pooled client incore/inference/llama_http.py._probe_mtp_decode(httpx.post),_server_socket_is_open(socket.create_connection) and_wait_for_health, all reached from load or respawn paths that already run in threads.Tests
studio/backend/tests/test_spark_router.pyandtest_spark_serving.pydrive fake llama-servers on loopback (tests/spark_fake_llama.py): fan-out across two backends, sticky routing and re-mapping, health eviction and recovery, streaming order, backpressure limits, mid-stream failure, client disconnect, and the orchestrator's gate, planner contract, command construction and load hooks.GPU functional test
Run on the pair under the GPU locks against the merged branch (c8043c9): the backend started from the worktree,
POST /api/inference/loadofunsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XLwith 16 slots returned in 10.7 s andGET /api/inference/spark/statusreportedreplicaswith the planner's KV-aware reason (35.8 of 113.7 GiB, 1.75x at 16 users). The peer's llama-server came up from the same bundle and both backends went healthy. 16 concurrent streamed chats completed in 2.7 s wall, served main 6 / peer 10, median time to first token 0.98 s, no rejects. A five-turn conversation was served bypeeron every turn.POST /api/inference/unloadreturned 200 and the status went back tosinglewith the router gone.pgrep -x llama-serverandpgrep -x ggml-rpc-serverwere empty on both nodes after teardown.One earlier attempt was killed by the machine's thermal guard (a cooldown was active on the main node), not by this code; the driver now waits out cooldowns before it starts.
The live product-path run on the pair (task #15)
Everything above had been measured with hand-written harnesses. This is the orchestrator itself, on both Sparks:
unsloth studio runandPOST /api/inference/load, the fork build of unslothai/llama.cpp#187 ata1dd7c5e8pointed at withUNSLOTH_LLAMA_CPP_PATH,unsloth/Qwen3.8-27B-GGUFUD-Q4_K_XL from the HF cache,-c 16384, real-text prompts, npp 128 / ntg 256, 2 requests per client. The peer'sggml-rpc-serverwas started by the orchestrator in every cell and never by hand:peer_process.remote_pidmatched/proc/<pid>/cmdlineon the peer and its parent was thesshd: nvidianew@nottysession thatPeerProcessopened.Five defects, all of which failed a real load. Four are fixed here (
7942473,8a9f0c7,02bc6d2), the fifth is recorded.layer_split_extra_argsappended the group slot count as--parallel N, whichllama_server_argshard-denies in a pass-through, so the route answeredHTTP 400: llama-server flag '--parallel' is managed by Unsloth Studio. The count travels as the request'sn_parallelnow, inside its 1..64 range.--pipeline-groups N --spec-type draft-mtp --helpexits 0 on the fork that refuses the pair as well as on the one that runs it, becausetools/servervalidates the pair insideload_model. Checked on the real builds:8de432016anda1dd7c5e8both answered yes. The probe runs the server against a model path that cannot exist instead, which reaches the check without reading any weights:a1dd7c5e8accepted,8de432016refused, the b10796 prebuilt refused, 1.5 s once per build.--mmprojfrom the model's own repo afterbefore_loadhas run, and the server refuses--pipeline-groups > 1together with a projector. The 27B died with--pipeline-groups > 1 is not supported together with multimodal (--mmproj)after four launch attempts; the 35B-A3B died the same way with no projector on disk beforehand, because the load downloaded one. A model out of a hub snapshot now gets the groups only when the load turns vision off.Failed to connect to <peer>:50052and theninvalid device: RPC0. The peer's rpc-server takes one client at a time and the outgoing llama-server still holds it while the replacement starts; a forced reload retires the peer with the old server. A reload the backend restarts withoutforce_reloadstill hits it: that is ordering in the load path, not this module's to fix.spark_servingand the llama.cpp backend disagreed about which llama-server the bundle is (fixed ind5d384c).spark_cluster._BUNDLE_SUBDIRSaccepts<root>/build/bin,<root>/build/bin/Release,<root>/binand<root>; the backend'sllama_server_candidatesaccepts<root>and<root>/build/bin(plusReleaseon Windows only). On a<root>/binlayout the orchestrator probed one binary, decided pipeline groups and MTP from it and handed the peer that build'sggml-rpc-server, while the backend launched a different llama-server: seen live, the two ends of the RPC link were different builds and the preflight refused the split with "its HELLO reply was malformed". See One resolver for llama-server below.Throughput, product path against the hand harness (same model, geometry and prompts; hand-harness figures are the clean cells of the 04:06 block):
At 8 rows every arm agrees inside the spread (93.1 against 93.6 to 95.5; 86.6 against 77.1 to 92.0; 53.3 against 51.5 to 54.0).
The gap is
--kv-unified, which Studio always passes and the harness never did. Three hand cells, two groups plus MTP, 32 rows, both nodes uncapped at 2391 to 2400 MHz: the harness argv 137.1 tok/s (TPOT 202 ms), plus--kv-unified173.7 (151 ms), plus--kv-unified --no-context-shift166.0 (157 ms). So one shared KV buffer is worth 1.27x on a two-group split at 32 rows and--no-context-shiftcosts nothing outside noise. The product cell measured 163.1 rather than 173.7 because its window straddled a thermal cap (1683 to 2405 MHz, mean 2244; every other cell here ran 2244 to 2400 MHz clean).Consequence for the constants:
GROUPS_X_MTP_*inspark_cluster.pywere measured without--kv-unified, so they described a launch the product never makes. The whole table has been re-measured with it; see The table, re-measured with the flags Studio launches below.The status surface reported the chosen configuration and its reason in every cell, e.g. for the default 27B split
split_config = "one context + speculation"withsplit_config_reasonnamingmmproj-F16.gguf, andmtp = "enabled",mtp_reason = "launched with --spec-type draft-mtp --spec-draft-n-max 3"read back from the argv. Single-node checks on the same build: the 27B reportedmtp enabled, the 35B-A3Bno head/no <arch>.nextn_predict_layers in the GGUF header, a caller'sspeculative_type: "off"user override/speculative_type=off, andpipeline_groups_reason/split_config_reasonbothnot a layer split (topology single).Two operational notes from the run, both now fixed.
unsloth studio rundid not exit within 60 to 90 s ofSIGINTin five of five attempts (single node and split alike) and onlySIGTERMstopped it; and when Studio is killed without running its lifespan shutdown, the peer'sggml-rpc-serveris orphaned and keeps holding the peer's GPU, with nothing to reap it on the next start. See Stopping cleanly below. Also seen: the launched--parallelwas clamped to 11 by the backend's memory fit for a load that asked for 32, while the split configuration was chosen on the 32 the caller asked for.One resolver for llama-server (
d5d384c)There is exactly one resolver for the binary that launches, and it is the backend's
LlamaCppBackend._find_llama_server_binary: the load path launches_exec_path_for_launchof it and thebackend's own capability probe probes the same unwrapped path.
spark_serving.llama_server_binarynow asksit and searches nothing itself, with no fallback to a second layout, because falling back is how the two
came apart. The rpc-server follows: it is taken from beside the llama-server that launches, and only then
from
spark_cluster's bundle search, so both ends of the RPC link are one build. Everything the orchestratordecides -- the pipeline groups, the speculation, the draft depth, the build the peer is handed -- is a
statement about the binary that launches, so a second search order here is not a duplicate, it is the defect.
test_the_orchestrator_probes_the_binary_the_backend_launchescompares the two resolvers over every layouteither of them accepts (
<root>/build/bin,<root>,<root>/bin,<root>/build/bin/Release, and a rootwith nothing in it) and fails the moment they disagree again. Against the previous code it fails with exactly
the live symptom: "the orchestrator would probe
<root>/bin/llama-serverwhile the backend launches None".test_the_rpc_server_is_taken_from_beside_the_launched_llama_serverpins the other half. The serving fixturenow also pins the backend's resolver at the test bundle and redirects
HOME, so these never depend on whatthe machine running them has installed.
Stopping cleanly, and a peer process that reaps itself (
d5d384c,e504929)unsloth studio runnow handles SIGINT and SIGTERM.python run.pyinstalls handlers for both in its__main__block; the CLI path never did. SIGTERM therefore had no handler at all and ended the processoutright, so the lifespan shutdown never ran -- which is how the peer's
ggml-rpc-servercame to be orphanedtwice in the live run. And SIGINT arrived only as a
KeyboardInterrupt, which starts the cleanup but boundsnothing after it: the uvicorn thread is joined for five seconds and then the interpreter's own shutdown takes
over, where an atexit join on a worker thread still inside an ssh or a subprocess wait holds the process for
as long as that call takes. One callback now serves both signals: it restores the default disposition first
(so an impatient second signal still force-quits), runs
_graceful_shutdownonce however many signals arrive,and wakes the wait loop; the command then joins the server thread, flushes its streams and leaves through
os._exit, because nothing past that point does work a user is waiting for and nothing past that point mayblock. Checked end to end against the built Studio: SIGTERM now runs the full graceful shutdown and the
process is gone in under five seconds, where before it was a hard kill with no cleanup.
The peer process no longer outlives the Studio that started it. Two links, both polls of
kill -0andsleep, so neither can become the stuck process itself (a read on the ssh channel was rejected for exactlythat reason: a half-open socket never delivers the EOF). Locally the ssh client is given
PR_SET_PDEATHSIG,without which it is simply reparented to init on a SIGKILL and keeps the remote session open, which is how
the orphan survived. On the peer the launched shell reports the server's own pid -- the one teardown and the
status surface already use -- and then watches the sshd session it was started by, killing the one pid it
started when that session goes. The remote half names nothing but its own child, so another Studio's
rpc-server, or a hand-run experiment on the same peer, is never touched. Verified against the real pair with
a harmless remote command and no GPU: SIGKILL to the launcher took the ssh client with it and the peer
process was gone within one poll.
The table, re-measured with the flags Studio launches (
0e3664b)All four arms, at 8 and 32 concurrent, every cell with
--kv-unified, on the same geometry as before(Qwen3.8-27B UD-Q4_K_XL,
--rpc <peer> --device RPC0,CUDA0 -sm layer --cache-ram 0 -c 16384--parallel 32, real-text prompts, npp 128 / ntg 256, the fork of unslothai/llama.cpp#187 ata1dd7c5e8` on both nodes), forward then reversed arm order.Both nodes were pinned at 300,1700 MHz for the whole block. The first attempt was not, and its
eight cells spanned three clock states -- local capped six minutes in, the peer nine minutes after
that -- so no two arms were comparable and it was discarded. The pin costs about 5 to 7 percent
against an uncapped node (the two clean uncapped cells of that attempt read 54.9 and 101.9 for one
context against 51.4 and 97.2 pinned), which is small because the decode is memory bound, and it
applies to every arm equally. No cell in the pinned block straddled anything.
--kv-unifiedmoves the two-group arms and nothing else, which is what one shared KV buffer shoulddo: it only pays once the rows are split over two groups. So the win above the crossover grew,
1.36x of one context with speculation rather than 1.15x, and the loss below it shrank, 0.97x
rather than 0.89x. Acceptance is unchanged by the second group (0.75 / 0.70 with one context against
0.74 / 0.71 with two), so splitting the rows across two draft contexts still costs the draft head
nothing.
The crossover does not move, and 16 is still the right number. The winner flips between the two
measured points in both passes -- one context with speculation at 8 rows (0.96x and 0.97x), both
together at 32 -- nothing between them has been measured, and 16 remains the geometric midpoint of
the two bracketing points with both sides measured. What changed is the stakes: above 16 rows the
prize is larger than the old constants claimed, and below it the two configurations are within 3
percent, so choosing wrong there costs little.
GROUPS_X_MTP_ONE_SPARK_MTP_TOKSis the one row not re-measured and is marked as such in thesource: it carries neither the flag nor the pin, and is used only for the wide margin at 8 rows. A
test now requires
GROUPS_X_MTP_MEASUREMENTand thespark_servingmirror to name--kv-unified,so the next re-measurement has to state the argv it measured.
The draft depth follows the rows, and above 64 rows a split takes no drafter at all (
5ea5852,7b57330)--spec-draft-n-max 3came from the one-Spark table, which was measured at 1 to 8 users. Thetwo-Spark layer split runs 32 to 128 rows and that depth was never swept there. Swept now on the
pair, Qwen3.8-27B UD-Q4_K_XL,
--pipeline-groups 2 --kv-unified --tensor-split 0.5,0.5 --spec-type draft-mtp, PR 187 build a1dd7c5e8, both nodes pinned at 1690 MHz, npp 128 / ntg 256,every speculation cell bracketed forward and reversed, drafter-off anchors at both ends of the
block. Leg means, decode tok/s:
Two rules come out of it, and they are separate constants.
The depth.
MTP_DRAFT_N_MAX = 3becomesmtp_draft_n_max(users): 3 below 32 rows, which iswhere the one-Spark table lives and where nothing here was measured, 2 from 32 and 1 from 64. The
shipped default was the worst of the three depths at every row count on the split.
spark_cluster.pycarries the table and the rule,spark_serving.mtp_plantakes the row countand asks for that depth, and a caller who set a depth, a
speculative_typeor their own--spec-typeis untouched as before.Whether a drafter runs at all.
SPLIT_MTP_OFF_ROWS = 64. Even at its best depth the draftercosts 7.9 percent at 64 rows and 22.9 percent at 128, and there was no path in the orchestrator
that could turn speculation off for a split:
groups_x_mtp_winschose two groups plus MTP above16 rows and one context plus MTP below it, and both branches kept it. Since
--paralleltracksthe offered concurrency clamped into [8, 64], and 128 is reachable on an explicit
throughput-over-latency choice, both losing row counts are launches the product actually makes.
reconcile_split_speculation-- the one place a split's speculation is resolved before the launch-- now drops this module's drafter at or above 64 rows: the launch says
speculative_typeoffwith no depth, so neither
--spec-type draft-mtpnor any draft flag is emitted, and the pipelinegroups stay, because two groups with no drafter is the fastest arm measured at those rows
(186.3 and 212.7 tok/s). Below the boundary nothing changes. 33 to 63 rows is interpolated:
nothing between was measured, so the constant sits on 64, the lower of the two measured points at
which speculation loses, bounded below by 32 where the best depth is worth +11.0 percent. The
status reports
mtp = "off for the split rows"with the numbers inmtp_reason.Neither of those is
GROUPS_X_MTP_CROSSOVER_ROWS, which stays 16 and answers its ownquestion, two pipeline groups against one context. A test asserts it is unmoved. The prose that
ran the two decisions together now states them separately: a split at 8 rows is one context with
MTP, at 32 rows two groups with MTP, and at 64 rows and up two groups with no drafter.
The split only. The matrix was measured on the layer split, and
split_mtp_winsis calledfrom nowhere but the split path. One Spark and two replicas keep the one-Spark answer, where the
head is worth 2.61x / 1.87x / 1.59x at 1 / 4 / 8 users; tests assert the drafter is still emitted
there at the same row counts that turn it off on a split.
Mechanism, from the same block: acceptance is a property of the depth and not of the rows -- 0.87
at n-max 1, 0.78 at 2, 0.69 at 3, flat in rows to within 0.02 -- and a deeper draft accepts
strictly more tokens per step (0.87, 1.56, 2.1) while losing throughput. The accepted tokens are
real and they are not free: the tokens submitted to buy them widen a batch that is already past
the cheap point of the per-token curve. TTFT agrees rather than trading against it: at 64 rows the
best depth is worse on throughput and on median, p90 and p99, and at 128 rows it nearly doubles
p90 and p99 while losing 23 percent. The drafter's memory cost is linear in both axes at 0.077 to
0.084 GiB per row per unit of n-max across nine cells, which corrects a paper model that had
under-predicted these arms by 2.3x by reading the n-max 3 case as a constant.
One earlier figure is withdrawn. "Speculation costs 38 percent at 128 rows" was measured at
n-max 3, which is nobody's best choice there; at the best depth the honest costs are 7.9 percent
at 64 rows and 22.9 at 128, and the gain at 32 rows was understated at 6.6 rather than 11.0
percent. The direction is unchanged and the point where speculation stops paying still sits
between 32 and 64 rows. Also overturned: n-max 1 is not the floor of the loss -- at 32 rows n-max
2 beats it by 6.7 percent -- so the depth curve has an interior optimum that moves with the rows.
149 tests in
studio/backend/tests/test_spark_serving.pyand 333 across it,test_spark_router.pyandunsloth_cli/tests/test_spark_offbox.py-- 149, 20 and 164.These are collected-test counts, so the figure is reproducible from one command:
All 333 pass with nothing skipped (
gguf,torch,safetensorsandunsloth_zoopresent; without them some of these skip rather than run). The earlier figures in this
body, 62 and 176, were the counts when it was written and the branch has grown since;
the per-commit test deltas quoted higher up are likewise a record of those commits, not
of the head.
Training: data parallel is the axis for a model that fits (
ad51b7f)studio/spark_pipeline.pygains--data-parallel: one whole model per rank with DDP over theLoRA gradients, or
--fsdpto shard the base weights withtorch.distributed.fsdp.fully_shardinstead. It reuses the layer split's loader, LoRA config, row generator, loss and 1/M gradient
scaling, so the two topologies are directly comparable on one command line, and at
WORLD_SIZE=1the same code path is the single-Spark control. Exposed asunsloth spark train --data-parallel <model> [--fsdp].Commits
ad51b7f,833a303and089801f. Measured on two DGX Sparks,unsloth/Qwen3.5-2B, seq 512, global batch 64, M=32(1024 tokens per microbatch), LoRA r=16, 20 steps, seed 3407, both nodes uncapped at ~2400 MHz,
NCCL all-reduce verified at 20.31 GB/s. One-Spark control 2613 tok/s, loss@20 12.5806:
unsloth/Qwen3.5-9B(18.0 GiB BF16), identical settings, one-Spark control 850 tok/s:2.05x is perfect scaling inside the noise. Both models scale better than the bubble bound would
suggest for the split, and DDP beats the best schedule by 1.26x at 2B and 1.14x at 9B.
The capacity case: DualPipeV cannot train a 70B on the pair
The two schedules tie above, so the split's default was a coin-flip decided on memory. But the
split is only ever recommended for a model that does not fit on one Spark, and nobody had
measured the schedules at that size.
unsloth/Llama-3.3-70B-Instruct(131.4 GiB), LoRA r=16,seq 512, global batch 16, M=8, 10 steps,
--shard-load --grad-checkpoint, both Sparks pinned at1690 MHz for the whole block so neither arm straddled a thermal cap:
DualPipeV took the local node to
NVRM NV_ERR_NO_MEMORY, the peer's collective timed out after600 s, and the kernel OOM killer ended rank 0. Repeated at half the in-flight tokens (batch 8,
same M) it died again, on step 1, with rank 0 down to 3 GiB available while rank 1 sat at 45.
That is structural rather than a bug. The V layout co-locates the first and last stages on
one rank, so rank 0 carries the embedding, the LM head, the loss, two layer chunks (68.06 GiB
resident against rank 1's 64.14) and the deepest in-flight microbatch set all at once. At 2B that
costs 4 GiB and at 9B 7 GiB, which is invisible; at 70B it does not fit in 121.69 GiB. 1F1B
splits evenly at 66.10 GiB on both ranks and lands the loss on the rank without the embedding.
The memory it spends is not repaid either. DualPipeV's argument is a co-located hop that skips a
send/recv, and this was the first cell where the interconnect could plausibly matter - but the
1F1B run moved 1386 MB in 1079 s, about 2.5 MB/s, against a link measured at 20.31 GB/s of NCCL
busbw. With gradient checkpointing at seq 512 the stages are compute-bound by three orders of
magnitude and the link is idle, so there is no bandwidth there to win.
studio/spark_cluster.py::plan_trainingturns all of that into the rule: a model that fitstrains data parallel, and a model that does not fit is layer-split for capacity with no
speedup claimed and
--schedule 1f1b, which is now the default rather than a memory-tightfallback. The recommendation says explicitly not to substitute DualPipeV at this size and why,
since the 2B/9B tie invites exactly that substitution. DualPipeV's 70B tok/s and peak are
recorded as
None, not as the number it died at: a peak for an arm that never finished a stepreads as though it ran. Five tests in
unsloth_cli/tests/test_spark_offbox.pyfail if the ratiosstop following from the recorded tok/s, if a model without a control is given an over-one-Spark
claim, if the capacity case starts claiming a speedup, or if the capacity default drifts back to
the schedule that leads on the two models that fit.
One earlier number is withdrawn. The 1.96x previously recorded for torch dualpipev at 2B was
a denominator artifact: the schedule's absolute throughput is unchanged (4204 then, 4128 now),
but the 2149 tok/s single-Spark control it was divided by was taken on a node that was missing
causal_conv1dandflash-linear-attention, so Qwen3.5's linear-attention layers fell back toa slow torch path there - worth 2.19x throughput and 39 percent more memory, announced only by a
single warning line. Against a healthy control the best schedule is 1.58x and DDP is the only
arm that reaches 2x on this pair. Nothing outside the Spark paths is touched, and
transformers/TRL/peft versions are unchanged.
Merging the base in: a clean auto-merge that did not compile (
eb3afa7,ef69ea4)feature/dgx-spark-two-nodemerged in again. One conflict, and one hazard that produced noconflict at all and is the more useful of the two to know about.
The conflict was an add/add in
unsloth_cli/commands/spark.py: both sides had independentlyadded the
--grad-checkpointpass-through tospark train's pipeline args, at different points inthe same block. Resolved to a single append; the flags are order-independent, and appending it
twice would have passed
--grad-checkpointto the pipeline twice.The hazard was the same flag's option declaration. Both sides had also added
grad_checkpoint: bool = typer.Option(...)todef train(, at different offsets, with differenthelp text. Git merged those cleanly, with no conflict and no marker anywhere to review, into:
which takes the whole CLI down at import: 153 collection errors across the off-box suite. A
conflict-free auto-merge that does not compile is a sharper hazard than a dropped hunk, because
nothing in the diff flags it and the only thing that catches it is importing the result.
Resolved by keeping the base branch's declaration and dropping this branch's duplicate, that
way round on purpose: keeping this branch's text would silently revert a trunk change when this PR
merges back.
Then swept for the same shape rather than assuming it was the only one: every function in all
29 files the merge touched, parsed and checked for duplicate arguments. 0 further instances.
After the merge: 275 -> 279 collected, 279 passing, nothing skipped,
ruff checkclean.Also in
ef69ea4, two fixes found while re-verifying this PR from a clean slate.unsloth_cli/tests/test_spark_offbox.py's_import_loader_utilscaughtNotImplementedError, theCPU-only-host case, but not
ImportError.unsloth/_gpu_init.pyraisesImportErrorwhenunsloth_zoois absent, so a host with torch installed andunsloth_zoonot failed 37 of thesetests instead of skipping them. Both mean the same thing, that the package will not import here, and
both now read as a skip. Verified by blocking
unsloth_zooatsys.meta_path: 37 skipped, 0failed, where before the arm was added it was 37 failed.
spark_serving.peer_binary_candidatesnow documents why the peer launch does not forwardLD_LIBRARY_PATH. The peer is launched over ssh without it, so the bundle there must resolve itsown shared objects; the shipped prebuilt does, through an
$ORIGINRUNPATH, and a bundle rsynced byspark provisionkeeps that property. A hand-built llama.cpp whose RUNPATH is an absolute path intoits build tree does not, and fails on the peer with
error while loading shared librarieswhileworking locally. Forwarding this process's
LD_LIBRARY_PATHwould not be a fix: the peer's layoutis not this node's, and an absolute directory that exists on both with a different build in it
would shadow the peer's own libraries and put the two ends of the RPC link on mismatched builds --
the defect
d5d384cexists to prevent, and one that fails silently as a malformed HELLO. A missing.sois the better failure, because it names itself in the peer log.Review fixes: three silent failures, and one open design question
Round 1 and 2 of review produced 10 fixes (
9d856ee,f8e8774,5be3322). Three are worthnaming here because none of them crashes -- each one runs, and is wrong.
The peer inherited every
LLAMA_ARG_*the primary refuses.scrub_denied_envdropsDENIED_ENV_VARSfrom the environment the primary spawns with, but it scrubs a copy, so thosevariables are still in
os.environwhenreplica_envreads it, and_REPLICA_ENV_DENYcoveredonly
HOSTandPORT. An operator withLLAMA_ARG_API_KEYorLLAMA_ARG_SSL_*set got areplica demanding auth or speaking TLS while the router health-probes it over plain HTTP, so it
never went healthy and the topology quietly degraded to one node;
LLAMA_ARG_MODELpointed thereplica at a different model, which answers perfectly well.
replica_envnow unions inDENIED_ENV_VARS, imported rather than mirrored so the two cannot drift.A warm reload got a placement a cold one correctly refused. The
gpu_idsandcaller-supplied-
--rpcguards sat below the rpc-server reuse early return. On a cold start therequest fell back to
single, as intended; on a reload with a live rpc-server the same requestreturned past both guards and had
--rpc ... --device RPC0,CUDA0appended -- and the backend thenstrips
--devicewhengpu_idsis set, so the output layer and the logits land on the peer, whichis the measured slow path. Order-dependent placement is the worst version of this, because the
first load looks like proof the guard works. Both guards are pure request inspection and now run
before the reuse shortcut.
gguf_size_bytescould under-report a model's size, which is a never-OOM defect. It summedonly the shards present and swallowed the
OSErrorfor the rest, and a non-Nonereturn blocksthe
remote_gguf_size_bytesfallback. A half-downloaded 120 GiB split model priced as 30 GiB,planned
single, and was found out only after the remaining shards arrived -- as anout-of-memory on a node with 121.69 GiB shared between CPU and GPU, not as a slowdown.
Undercounting is the one error this function must not make, so a missing shard now answers
None,which is a handled state.
One environment/argv class, closed on both routes. Round 3 returned the env twins of two of
these fixes, which is the useful signal: they were right and applied one layer too narrowly.
llama.cpp's
common_argreadsLLAMA_ARG_*itself, so a setting arrives by either route and aguard on one route holds only until somebody uses the other.
replica_envnow absolutises thesidecar paths
replica_argvalready did, andextra_args_refuse_pipeline_groupsnow sees aprojector supplied as
LLAMA_ARG_MMPROJ/_URL. The remaining round-1/2 fixes were swept for thesame shape:
argv_or_env_rpcalready reads both routes by construction,_DENYLISTkeeps deniedflags out of the primary's argv, and the rest have a single route each.
Open, and deliberately not patched: cross-model extras inheritance on a split
_spark_inherited_extra_argsmatches the requested model against the stored one with a substringescape hatch, so
org/qwen-7bmatches storedorg/qwen-7b-instructand inherits its extras. On alayer split this reaches the launch, because
_with_rpc_argsmaterialisesllama_extra_argsand anon-
Nonefield makes the strict_resolve_inherited_extra_argsskip inheritance entirely -- sothe fuzzy list is the only path by which extras reach a split launch, and the strict
identifier-plus-variant check never runs.
Two fixes were considered and both rejected, with the reasoning recorded so it is not re-litigated:
if a != b: return Nonebreaks what the substring test exists for. A hub idunsloth/Qwen3-8B-GGUFagainst a resolved cache path with stemQwen3-8B-UD-Q4_K_XLalso hasdiffering stems and is the same model. No string heuristic separates that from
qwen-7b/qwen-7b-instruct, because-is a separator inside model names too.--mmprojis re-derived by the backend, but--lora,--lora-scaled,--control-vector,--control-vector-scaledand a user-supplied--model-draftare inherited-only: nothing inthe load path re-derives an adapter or a control vector from the request, the repo or the config,
and there is no first-class request field for them. Stripping them would trade a wrong-sidecar
bug for a missing-sidecar one, which is worse -- a wrong
--lorapath usually fails at startup,a missing one is silent and the model answers as the un-adapted base.
The structural fix is to stop the split materialising
llama_extra_argsso the canonical checkstill runs, or to tighten the match rather than the payload --
_spark_inherited_extra_argsreads only
source[0]and dropssource[1], the hf_variant, which the strict resolver doescompare. Left for a follow-up rather than guessed at.
Hazard for whoever adds the next remote probe: sentinels in
spark_serving.pymust be unique per queryThe peer is interrogated by several independent
ssh_runprobes that each print a sentinel andare parsed by matching on it. Adding a probe that reuses another's sentinel makes one query's
answer readable as the other's, and nothing type-checks that.
This is not hypothetical. The peer weight-identity check was first written as
stat -c '%s %Y' <path> || echo MISSING, andMISSINGis already what the remote binarylookup prints (
find_binary_script). The test double matched on the sentinel, answered thebinary lookup for a
statquery, and ten tests failed. It was caught by luck -- the testshappened to overlap -- rather than by anything structural. The probe now prints
NOSTAT.The sentinels currently in use, all distinct:
MISSINGfind_binary_script), for both llama-server and ggml-rpc-serverYES/NOggml-rpc-server -cNOSTATUNSLOTH_SPARK_PID=This is the same one-name-two-meanings shape as the argv/environment twins fixed in
5be3322:one value, two routes, and a guard or a parser that only knows about one of them.
A second one-name-two-meanings hazard, in the tests:
sys.modulesstubs must defer to the real moduleFound while checking that this PR's tests do not collide with anything already in the tree.
studio/backend/tests/test_llama_extra_args_compatibility.pypasses 50/50 on its own and fails6 when it is collected after certain other files. The cause is pre-existing and not otherwise
touched here, but a suite that returns a different answer depending on run order is an unreliable
instrument, so it is fixed at its source rather than by isolating the file that runs second.
Three test files installed stand-in
loggersandstructlogmodules with a baresys.modules.setdefault(...).sys.modulesholds what has been imported, not what isinstalled, so
setdefaultdoes not defer to a real module nothing in the process has touchedyet: the stub wins and shadows it for the rest of the session.
loggersis a real package(
studio/backend/loggers/), so a plainModuleTypestanding in for it has no submodules, andevery module collected afterwards that reaches
loggers.media_progress-- whichroutes/inference.pydoes at import -- died with'loggers' is not a package.Measured one file at a time against that 50-test victim:
test_gguf_reload_inheritance.pytest_llama_cpp_stall_timeout.pytest_spec_retry_status_signals.pytest_llama_cpp_reprompt_guard.py(already guarded, control)The fix is the form
test_llama_cpp_reprompt_guard.pyalready established and documents: try thereal import first and stub only on
ModuleNotFoundError, structlog before loggers becauseloggers.handlersimports structlog, checkexc.nameso a missing structlog is not mistaken fora missing
loggers, and set__path__so the stub is a package.test_gguf_reload_inheritance.pyalready guarded its httpx stub this exact way, for this exact reason, a few lines below -- the
guard was simply never carried across to the two stubs beside it.
Same shape as the sentinel collision above and as the argv/environment twins in
5be3322: onename, two meanings, and a mechanism that only knows about one of them.
Where the review stopped, and why
The reviewer kept producing novel suggestions on every round rather than approving, so "run
until it approves" was not a terminating condition. The rule applied instead: land anything that
is a defect reachable in a shipped configuration -- a wrong result, a leak, a hang, a
resource not cleaned up, an OOM -- and record anything that is only hardening as a follow-up.
Every item returned in the final rounds fell in the first bucket, and each was checked against
the code before being taken rather than accepted from the report. Two of the last four were
regressions introduced by the round before them: the oversized-load refusal left
load_in_progresstrue and the topology overwritten, and it made an already-stale_pre_load_staterestorable. That is the argument for the whole exercise -- a refusal thatleaves state behind is worse than the OOM it prevents -- and for attaching a failing-first test
to every fix.
Nothing is being deferred as hardening: no item in the last three rounds was one.
One reviewer suggestion was wrong and the existing suite caught it. On the managed-RPC item,
"detach whenever
peer_processis present" tears down our OWN split, because that branch isreached by the managed layer split too -- this module is what wrote its
--rpc.test_before_load_reuses_a_live_rpc_server_and_after_load_reconcilesfails immediately on thatversion. The fix compares the endpoint, host and port, and a test pins the case the narrow
reading would have broken.
The
linux ubuntu2404-arm-rootfailure is not from this PRIt fails identically on
feature/dgx-spark-two-nodeand on every recent head of this branch,including the pre-commit.ci bot commits that contain none of this work. It is inherited from the
base and belongs to whoever owns it there.