Skip to content

Studio: reserve the DSpark/DFlash sidecar in --fit-target and recover from a Metal out-of-memory - #14431

Merged
danielhanchen merged 86 commits into
mainfrom
studio-dspark-sidecar-fit-metal-oom
Oct 26, 2026
Merged

danielhanchen merged 86 commits into
mainfrom
studio-dspark-sidecar-fit-metal-oom

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

What broke

A Mac user loading unsloth/DeepSeek-V4.1-Flash-1017-GGUF (UD-IQ1_S) with the DSpark sidecar, --fit on, -c 8192 --parallel 4 reported:

  1. The first prefill died with kIOGPUCommandBufferCallbackErrorOutOfMemory on Metal.
  2. After that, llama-server answered every request with Compute error. (HTTP 500) until the model was reloaded by hand. /health stayed 200, so nothing in Studio noticed.
  3. After a manual reload, the draft context ran out of memory again.
  4. Studio had also picked -c 8192 because the Metal memory probe (llama-fit-params) failed, and the reason was neither logged nor retried, so the input embeddings stayed charged for the whole session.

Root causes

  1. The sidecar was never budgeted. DSpark and DFlash drafts borrow the target's token_embd / output, so llama.cpp's --fit cannot build a standalone draft context to measure them (common/fit.cpp logs "failed to measure the memory of the extra model, fitting without it"). The fitter then packs the target right up to --fit-target, and the ~8 GB drafter allocates past it. Studio already priced the drafter for its own context choice and even logged "~8.0 GB is not reserved", but never passed that reserve to the child.
  2. A poisoned Metal backend was kept alive. ggml-metal sets a sticky error after a failed command buffer ("recreate the backend to recover"). Studio retires a server on Vulkan device loss, but had no equivalent for Metal.
  3. The Metal fit probe failed silently. One None covered missing / not executable / timeout / non-zero exit / unparsable output, and that failure was cached for the session. Source builds on macOS did not build llama-fit-params at all.

Fixes

Sidecar reserve (--fit-target)

  • When a DSpark/DFlash drafter is on the target's device and the fitter runs, its bytes (weights, draft KV, the 224 MiB draft compute floor) are added on top of Studio's margin, the Metal wired-headroom floor, and any --fit-target the user passed through extras or LLAMA_ARG_FIT_TARGET.
  • The reserve is priced at the context the child is launched with (a pass-through -c or a positive inherited LLAMA_ARG_CTX_SIZE when Studio leaves -c out). It covers only the drafter's own share: the target's rollback copies are left to the fitter, which measures them.
  • The reserve is repriced from scratch at every spawn from the final argv and env: context (an omitted -c scales with the final slots and KV layout), draft cache types, slot count (--parallel / -np in extras), KV layout, flash attention and the draft micro-batch (--spec-draft-n-ubatch). Studio's earlier reserve-bearing margins are removed first, so the reserve can fall as well as rise; the user's own margin stays. This covers extras that turn the fitter on, every draft-model spelling, the --fit off to --fit on startup retry, and the --flash-attn off retry (which repads the draft V cache).
    • The one-slot retry (unified KV refused) reprices for one sequence.
    • A retry that ends up on several GPUs reprices the reserve as a per-device --fit-target list.
    • The drafter-free fallback removes exactly the pairs Studio added.
  • No reserve is added in these cases, which keep the previous behaviour:
    • a drafter on CPU (-ngld 0);
    • a drafter split with the host (a positive -ngld below its depth);
    • a drafter placed by a draft tensor override (-otd, --override-tensor-draft, --spec-draft-override-tensor) or the draft CPU-MoE switches (flags or LLAMA_ARG_SPEC_DRAFT_*CPU_MOE);
    • a drafter pinned to another device (on Apple Silicon, a pin to anything but the Metal GPU);
    • multi-device launches the reserve cannot be placed on: --split-mode tensor (the cards fold into one device), --rpc devices, and cards named by --device that Studio cannot map. Other layer-split launches get a per-device --fit-target list, each card keeping its share of the drafter (rounded up to whole draft layers). A CPU child (--device none) gets none either.
  • The reserve stands down when the llama.cpp build measures the draft itself. That is detected by a string the new fit code compiles in, read from llama-server (also behind the installer's wrapper script) or libllama-common; there is no --help flag or meaningful build number for it. Older builds fail closed and keep the reserve.

Metal Auto mode

  • With speculative decoding on Auto, the sidecar is dropped (drafter_no_vram) when the target alone fits unified memory but target plus sidecar does not. The check uses the floor context, or an explicit context as it launches, and for an explicit context also the readable wired limit. It needs a KV estimate. The drafter's charges and embedding discount are then released, so Auto picks the same context as Off.
  • An explicit DSpark/DFlash request, a user-owned --model-draft, or a drafter only partly on the card keeps the drafter.

Metal OOM recovery

  • The log scanner treats the Metal poisoned-backend lines (error lines only) as a fatal device error. The server is retired only after a one-token completion confirms the failure (Compute error. or failed to process speculative batch), so request text echoed into the log cannot trigger it.
  • An Auto launch with a sidecar reloads once without speculative decoding. Any other first strike respawns on the next request. A second out-of-memory error on the same load stops respawning and leaves a clear message. An explicit reload starts a fresh episode.
  • Retirement holds the respawn and load locks, so a model swap in the middle cannot inherit the strike, and a retired child is never reused by an identical load.

Metal fit probe

  • The probe returns and logs a reason. Timeouts and non-zero exits are not cached. The cache key includes the file mode, so a permission fix re-probes.
  • studio/setup.sh builds llama-fit-params on macOS source builds, as the prebuilt bundles already do.

Also checked

  • Studio never emits its own -ot / --override-tensor together with --fit on for DeepSeek-V4.1. Its tensor spill always uses --fit off, and nothing in Studio places the Engram tables, since the loader already keeps them on CPU. A user -ot in extras still reaches llama.cpp unchanged.
  • The DSpark picker selects dspark-DeepSeek-V4.1-Flash-1017-Q8_0.gguf from that repo, ahead of the BF16 copy under dspark/.

Reproduction on a real GPU

I ran DeepSeek-V4.1-Flash-1017 UD-IQ1_S with the dspark-...-Q8_0.gguf sidecar on one B200. The llama.cpp build was the unslothai prebuilt (cuda13). Another process held memory so that 116.7 GiB stayed free. Each arm got the argv Studio emits (--parallel 4 -c 8192 -ub 2048 --fit on plus the DSpark flags) and ran twice.

Arm Loads What happened
main 0 of 2 --fit on leaves no room for the drafter, and its 7602 MiB allocation on device 0 fails with an out-of-memory error
This branch (--fit-target 12021) 2 of 2 The server is up with draft-dspark active and 117,334 MiB in use. Draft acceptance was 1.00, with a mean accepted length of 3.97

llama.cpp still logs failed to measure the memory of the extra model, fitting without it, which is why Studio has to carry this reserve itself. That run also showed the DSpark prompt graph scaling with the micro-batch size, and the estimate now prices it. Throughput is not compared here, because the host was shared.

Tests

New tests in studio/backend/tests/:

  • test_spec_sidecar_fit_reserve.py and _r2 through _r22
  • test_metal_fit_params_probe_reasons.py
  • test_llama_cpp_metal_poisoned_respawn.py

Results:

Check main This branch
New test files (366 cells) 292 failed, 1 error, 73 passed, 1 skipped (the passing cells are controls) 366 passed
Related suites, 45 files (fit, spec, metal, device_lost, sidecar, dspark, dflash, mtp_reserve, vram_fit) 3412 passed, 36 skipped, 2 failed 3548 passed, 36 skipped, 2 failed
Wider suites, 53 files (test_llama_cpp*, gpu arch gate, CUDA kernel image, mtp, speculative, slot) 3113 passed, 8 skipped 3113 passed, 8 skipped
  • The 2 failures in the related suites are the same test IDs on both sides, in test_tool_result_fits_window.py, and are unrelated to this change.
  • The capability check was run on a real build: a libllama-common.so built from the llama.cpp fit change is detected, and an older build is not.
  • ruff check is clean, and the changed files are formatted with the repo's kwarg-spacing formatter.

Known limits

  • On a multi-GPU --fit on launch, per-device reserves follow free memory past each card's margin and llama.cpp's whole-layer split, with the vocabulary graph on the output card. The fitter's exact layer outcome is not knowable before it runs, so a residual one-layer mismatch can remain. A launch the kernel-image retry narrows to one card gets that card's full reserve.
  • When --spec-type mtp comes from the user's extras, the drafter-free recovery changes the load's identity, so the strike count restarts once (at most one extra respawn).
  • Unrelated to the sidecar: a tensor-spill launch that crashes and takes the --flash-attn off retry gets --fit on back while the spill's -ot stays in argv (_enable_managed_fit_for_no_flash should drop the spill first). llama.cpp only logs a warning there and keeps the user's placement.

Not proven here

  • There was no Apple Silicon machine with enough memory for this model. The Metal paths are covered by simulated unified-memory budgets and by the log scanner fed the real ggml-metal error lines. The confirmation request is covered by its response predicate; the retirement tests stub it.
  • A real Metal OOM, and the recovery after it, has not been run on a Mac. The macOS leg of cross-platform CI runs the tests on Apple Silicon once this PR exists, but those runners do not have 128 GB.
  • The SIGBUS exit (-10) from an earlier run in the same report had no native log, so it is not addressed here.

…t repeat

llama-fit-params failures were all logged as 'missing or unreadable' and a
timeout or crash stayed cached for the session. Name the cause (not found,
not executable, exit code with the output tail, timeout, no breakdown),
cache only success and unparsable output, and key the cache on the probe's
mode so an exec-bit repair re-probes. Build llama-fit-params in the macOS
source-build path too, as the prebuilt bundles already ship it.
After a failed command buffer (Metal out of memory) ggml-metal rejects every
later graph, so the server stayed up and answered each request with
'Compute error.' until a manual reload. Retire it from the server log like a
lost Vulkan device. An Auto launch carrying a DSpark or DFlash sidecar, whose
memory llama.cpp's --fit cannot reserve, reloads once without the drafter; a
second out-of-memory on the same load stops respawning with a clear error.
llama.cpp's fitter cannot measure a drafter that borrows the target's
token_embd/output, so it packs the target up to --fit-target and the
draft then allocates past it (Metal OOM at the first prefill). Add the
planner's existing drafter reserve on top of the child's margin, and on
Metal let Auto drop a sidecar whose reserve is what stops the target
fitting; an explicit request keeps it.
…the child's sidecar, release dropped drafter charges
…ned drafters, carry the sidecar reserve through retries and user margins
…r, recompute the Metal embedding discount on drop, no reuse of a retired child
Price the DSpark/DFlash reserve off the argv being launched: retries that turn the
fitter on or pad the draft V to f16 now carry and re-price it, the reserve includes the
draft decode-graph floor and the native context when Manual + Auto omits -c, launches
spanning several devices get no scalar reserve, the drafter-free fallback removes every
pair Studio added and only the margin pair of the integrity block, and the Metal Auto
drop prices the target with its drafter-free embedding discount.
…ed device's margin and the drafter's own share; reset a terminal Metal OOM on an explicit reload
…uto drop for a drafter partly off the card, reprice the reserve for the one-slot and multi-GPU retries
…V layout, treat draft CPU-MoE as a placement, honour a single named device and an inherited context, scan a wrapped static server
…the final context, slots and draft micro-batch
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T12:01:16.832158Z 9ddd273 Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T13:08:05.880368Z
We couldn’t complete this review. Comment @codex security review to try again.
3d6565d Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…ing the Metal GPU; pin the discrete-GPU sidecar tests off Apple Silicon
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 21, 2026
danielhanchen and others added 2 commits October 20, 2026 23:35
…e live flash-attention plan

The reprice closure read load_model's env before it is assigned in source order and froze
planned_flash_attn in a default argument, so a layer-split downgrade that re-plans flash
attention left the draft reserve priced for the old mode. Take the child env as an argument
at both spawn sites and read planned_flash_attn when the reserve is priced.

[skip ci]
… is discrete

- A --device the build does not list, or a card Vulkan Auto filtered out of the
  probe, now keeps the host-resident draft KV charged instead of falling back to the
  planned discrete card.
- A one-card draft pin, or --split-mode none (main card 0 by default), narrows the
  check to the card the drafter runs on.
- DSpark and DFlash share one fit warning verdict, which reads the effective --fit and
  skips a drafter that carries its own tensors (llama.cpp sizes it).

[skip ci]
- With no shared-memory card on the host, whichever card the drafter lands on is
  discrete, so the host-resident draft KV leaves the reserve without mapping ordinals.
- On a mixed host the child's device names are mapped to physical cards only under an
  order the child provably shares and a numeric visibility mask; otherwise the KV
  stays charged. A --device of another backend (Vulkan1 on a CUDA launch) never
  counts as that backend's card.
- A CPU child (--device none / cpu, an empty written mask) gets no sidecar reserve and
  no reserve report.
- A Metal retirement thread that cannot start releases the pending poison flag.

[skip ci]
- A llama-fit-params timeout or crash is still not cached across loads, but within one
  load the second budget pass reuses the failure instead of waiting on another probe.
  The Metal fit lines it produces are logged once per load.
- The Auto sidecar drop runs the draft-free embedding probe only when the target and
  the drafter do not fit together.
- A pageable-embedding discount the drop unlocks is logged like the one above it.

[skip ci]
After a first Metal out-of-memory strike or a lost device, the next request finds the
port closed and went through the MTP crash fallback first: that request failed and the
reload dropped MTP. The fallback now leaves a retired child to _respawn_if_dead, both at
its entry and in a reload queued before the retirement, and the retirement marker is
set before the kill a racing request can observe. The Metal drafter-free reload keeps
its own path.

[skip ci]
_kill_process stopped it, but a retirement (Metal out of memory, a lost device) killed
the child without it, so after a terminal Metal strike the poller kept hitting the dead
child's loopback port, which another server may reuse. Both paths now share one stop
helper; the replacement's load starts its own poller as before.

[skip ci]
…tops for good

Nothing respawns it, so it was left half torn down: attempt log, pid record, codec,
temp files and plan stayed, a kept slot stayed registered and CHAT stayed claimed.
The terminal strike now runs unload_model() under the same load lock, then, outside the
backend locks, the routes drop its kept slot once no request holds it (a held one on a
later routed request) and release CHAT, as a crashed worker's reap does. Runtime
teardown includes such a slot. A first strike still respawns with the same settings.

[skip ci]
…its owner

A kept slot whose llama-server the terminal Metal strike unloaded is dead: it holds
nothing a request could still use, so it is dropped right away even while a request
holds a reference, instead of lingering until a later sweep where training, the
updater and filtered teardown each misread it. The chat residency is the primary's:
a retired kept slot no longer clears it, and a retired primary clears its own and its
claim the way a manual unload does.

[skip ci]
…server

- The retirement's routes cleanup ran after the backend locks were released, so a reload
  queued behind them could land first; the stale cleanup then killed the replacement's
  kept slot or cleared the replacement primary's sharers. It now receives the unload
  epoch the retirement left and acts only while the backend still carries it with no
  process, under the load lock every load takes, and never on a slot still filling.
- The borrowed-draft check on a warm capability probe read the whole server binary for
  its linked libraries on every load; the embedded names are now read once per file
  version, existence still checked each call.

[skip ci]
…cleanup

The GGUF handoff before an MLX / Transformers / audio / managed-engine / NPU load
skipped a backend that was already unloaded, so the unload epoch stayed at the
terminal retirement's value and its pending cleanup cleared the replacement's
chat sharers or dropped the kept slot it loaded into. The handoff now always
unloads under _serial_load_lock, which advances the epoch and waits for a cleanup
already past its check. The cleanup also leaves a primary seat or kept slot alone
while a non-GGUF model holds or is loading into it.

[skip ci]
…wait after the handoff kill

The Metal Auto drop priced the floor context even for an explicit one, which launches
verbatim, so Auto kept a sidecar that then made the request refuse while Off loaded it.
An explicit context is now priced as launched (SWA checkpoints included) and also against
the wired limit its refusal uses. The drop also requires a KV estimate, as the discrete
drop does. The standard-load handoff now waits for VRAM to settle after killing a
starting or recovering llama-server, as it does for a loaded one.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: c34fc22d15

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 58987cc6c8

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

# Conflicts:
#	studio/backend/core/inference/llama_cpp.py
#	studio/setup.sh
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9ddd27363f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +29271 to +29274
_weights = [
max(1.0, float(f) - max(b, m))
for f, m, b in zip(_spawn_free, _spawn_margins, _bases)
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Account for the fitter's rewritten split before assigning reserves

For an unpinned multi-GPU launch where fitting changes the target's placement, these pre-fit free-memory ratios do not determine the drafter's eventual placement. In the inspected llama.cpp implementation, common_params_fit_impl writes per-device fitted layer counts into params.tensor_split, and common_base_params_to_speculative subsequently copies that rewritten split into the draft parameters. The shares computed here can therefore reserve draft weights and the entire vocabulary graph on different cards from those that actually receive them, leaving the real allocation card without sufficient headroom despite the added reserve. Derive the reserve from a placement that the child actually preserves, or use conservative per-card bounds when the fitter's resulting split is not known.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this. When every card meets its margin, llama.cpp keeps its default free-memory split unchanged (common/fit.cpp, the 'no changes needed' return), which is what these shares price. Only a refill rewrites tensor_split back to front, and there the per-card draft layers can differ by about one layer. main reserves nothing for the drafter on any card in that case, so this is never worse than today. Reproducing the refill exactly needs the per-layer device memory only the child measures.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 9ddd27363f

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 215039a into main Oct 26, 2026
7 of 62 checks passed
@danielhanchen
danielhanchen deleted the studio-dspark-sidecar-fit-metal-oom branch October 26, 2026 12:45
danielhanchen added a commit that referenced this pull request Oct 27, 2026
Brings in the DSpark/DFlash sidecar --fit-target reserve and Metal OOM
recovery (#14431) and the lookup-table host/disk pricing (#14465).

- Layout: per_layer_embd_bytes is its own bucket beside token_embd_bytes
  (main's semantics); the planner's host side adds both and subtracts the
  lazily read share.
- Lazy mode: main's resident-table --lazy-mode off takes precedence; when
  it is emitted the planner's own -lzm is skipped and the plan prices the
  table resident. With no -lzm of its own the seam prices the fit's
  lazy_read_bytes; an emitted -lzm still decides.
- Speculative flags: the rebuilt _spec_slice sizes the sidecar per
  placement argv (main's _sidecar_fit_sized) and keeps the Vulkan draft
  backend-sampling flag.
- Retries revoke the spill plan and drop the managed lazy mode; the spawn
  keeps both _fit_on_recovered and _sidecar_fit_reserve_mib.

[skip ci]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants