Skip to content

Studio: reload without MTP when llama-server dies mid-generation on any MTP launch - #13316

Merged
danielhanchen merged 6 commits into
mainfrom
fix-13253-mtp-runtime-fallback
Oct 11, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
fix-13253-mtp-runtime-fallback

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Fixes #13253

Problem

Gemma 4 GGUFs turn on the MTP drafter in Auto. When llama-server passes /health with the drafter attached and then dies on a decode (the report: Gemma 4 E2B on an 8 GB M2, every chat request returns 500), Studio respawns the exact same MTP launch, so every following request crashes again. The only way out was turning speculative decoding off by hand.

Studio already has a fallback for this: when llama-server dies mid-generation it reloads once without speculative decoding, records runtime_error as the fallback reason, and keeps the requested mode so the UI shows why. That fallback was armed only for tensor-parallel launches, so a single-device Mac never got it.

Changes

  1. Arm the mid-generation MTP fallback (watchdog + reload without speculative decoding) for every MTP launch, not only under --split-mode tensor. The load-time decode probe stays tensor-only, so normal MTP loads get no extra work.
  2. Start llama-server through the existing spawn_on_lifetime_thread. On Linux PR_SET_PDEATHSIG fires when the forking thread exits, and the MTP-free reload runs on a short-lived thread, so the replacement server was sent SIGTERM about 100 ms after it came up. The next request then respawned it once more and the runtime_error notice was lost. macOS and Windows spawn exactly as before.
  3. Recovery no longer claims a connection error while llama-server is alive and still listening, so a transient error keeps its normal retry (before, an armed launch failed the request and then found the server alive).
  4. After recovering a launch whose MTP came from the user's own --spec-type extras, the requested mode is restored as None, which is what the duplicate-load match expects. Before, an identical Apply looked like a new request and relaunched the crashing MTP.
  5. Log and comment text no longer says "tensor".

Trade-off: recovery keys on the process exiting, not on why. A llama-server killed from outside Studio (for example the OOM killer) on an MTP launch now comes back without speculative decoding until the next load, where before it was respawned with MTP. Deliberate unloads, model switches and Studio's own kills stop the watchdog first, so they are unaffected.

Evidence

Studio's real LlamaCppBackend with a real llama-server (b11541 CPU build), unsloth/gemma-4-E2B-it-GGUF UD-Q4_K_XL plus mtp-gemma-4-E2B-it.gguf, Auto mode. A SIGABRT is sent to a healthy draft-mtp server once it starts a task, matching "loads fine, dies on the first decode":

Arm Requests OK Behaviour
main 0 / 6 each request: exited (code -6); respawning, same MTP launch, crashes again
this PR first request fails, later requests OK once the reload is up reload without MTP, status auto + runtime_error
this PR, no crash injected 6 / 6 MTP stays on, draft acceptance 1.00

New tests in studio/backend/tests/test_mtp_runtime_fallback_any_launch.py: 5 pass on this branch; on main the two that pin the fix fail.

Apple Silicon (staging CI, macos-15 and macos-26, Apple M1 Virtual, 7 GB)

Same backend comparison on macOS (Studio pins GGUF to the CPU there because the runner's Metal device is paravirtual), main vs this PR, same model, drafter and llama.cpp b11541:

Arm macos-15 macos-26
main, decode abort injected 0 / 6 OK, 6 aborts, respawned into MTP each time 0 / 6 OK, 6 aborts
this PR, decode abort injected 1 abort, then 5 / 5 OK, server alive without MTP, reason runtime_error, mode auto same
this PR, no abort 6 / 6 OK, MTP still on 6 / 6 OK, MTP still on

The new test file there: 4 passed, 1 skipped (the Linux-only PDEATHSIG test).

Raw llama-server with Gemma 4 E2B + MTP (draft-mtp n=2 and ngram-mod,draft-mtp n=3) on the b11160 and b11541 macOS builds served every request on these runners, but they show no layer offload, so they ran on the CPU and do not reproduce the reporter's M2 Metal crash. That crash itself is not reproduced here; this PR makes Studio recover from it instead of failing every request.

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@chatgpt-codex-connector

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 🔄 Running since 2026-10-11T11:07:18.350964Z 4acff76 PR opened
ℹ️ 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 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-11T12:54:31.038053Z 96dc38e 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security 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: 4acff76ece

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

t.join()
time.sleep(1.0)
# The control proves the hazard is real on this host.
assert procs["direct"].poll() is not None

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 Skip the control when PDEATHSIG is unavailable

On Linux hosts where PR_SET_PDEATHSIG is blocked by seccomp or prctl is otherwise unavailable, child_popen_kwargs() deliberately degrades without raising, so the directly spawned child remains alive and this assertion always fails. The skip condition currently checks only sys.platform; gate the test on _pdeathsig_available() or skip when the direct control remains alive so the suite remains runnable in restricted Linux containers.

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.

Fixed in 4d58739: gated on process_lifetime._pdeathsig_available(), as test_data_recipe_worker_lifetime.py does.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@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. You're on a roll.

Reviewed commit: 4d58739fc9

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

@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. Delightful!

Reviewed commit: 3f7b17223e

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

@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. Keep it up!

Reviewed commit: 96dc38e6b8

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
…ver recovers on every API route (unslothai#15138)

Every Studio route that proxies to llama-server built its own URL, auth
header, per-request client, cancel watcher and crash-respawn retry:
eight copies across `/v1/chat/completions`, `/v1/messages`,
`/v1/responses`, `/v1/completions` and `/v1/embeddings`, holding 20
hand-built llama-server URLs and headers in `routes/inference.py`. Fixes
landed one copy at a time:
- unslothai#8999 gave `/v1/chat/completions` the respawn `/v1/messages` already
had, and stopped there.
- unslothai#13011 found `/v1/completions`, `/v1/embeddings`, the Responses stream
and `/v1/messages` still sending no per-launch key.
- The disconnect handling was copied path by path in unslothai#10096, unslothai#9312,
unslothai#11961 and unslothai#9616.

So when llama-server was killed and relaunched on a new port, only chat
recovered fully. `/v1/messages` recovered from a refused connection but
not from a connection dropped before upstream response headers, and
every other route failed each request until something else reloaded the
model.

## Changes

- `_LlamaUpstream` owns a request's calls to llama-server:
  - the URL and per-launch key, which move together after a relaunch;
- one respawn per request, on a lost connection and never on a timeout;
  - a per-request client that a Stop or a disconnect closes;
- a recovery wait that continues streaming keepalives and lets cancelled
requests release their resources while the backend reload finishes
independently;
  - the rule that tells a cancel from a transport error.
- `_monitored_llama_call` replaces the swap-gate and API-monitor shell
that `/v1/completions` and `/v1/embeddings` each spelled out.
- `_llama_stream_client` replaces four streaming client constructions
that disagreed on keep-alive.
- Every llama-server request in `routes/inference.py` goes through
`_LlamaUpstream`. The source scan that counted call sites for the key
now checks that instead.
- The non-streaming OpenAI passthrough's pooled-client branch is gone.
Production always passes a request, so only tests reached it; they now
patch the per-request client.

## Crash recovery

- **Streaming `/v1/responses` (Codex) now respawns.** It had no retry,
so after a crash every Codex request failed with "Lost connection to the
model server" until a chat request or a manual reload.
- **`/v1/completions` and `/v1/embeddings` now respawn.** Non-streaming,
they previously surfaced the raw `ConnectError` as a 500.
- **`/v1/messages` now retries lost connections**
(`RemoteProtocolError`, `ReadError`), not only a refused connection,
which is the rule chat already used. Streaming recovery applies only
before upstream response headers arrive; a server can send those headers
before prefill finishes. A failure after headers is not replayed. Its
non-streaming nudge retry shares the request's one respawn.
- **Responses, completions and embeddings now hand an MTP crash to its
recovery (unslothai#13316)** before respawning; they never called it.
- **A Stop that lands between two POSTs of one request now reports 499
instead of a server error.** This covers an embeddings `/tokenize` call
or a `/v1/messages` nudge retry sent after the Stop closed the client.
- **Streaming chat errors after recovery keepalives use the SSE
response.** If recovery outlasts the pre-header status window, the
response can already be HTTP 200; a later failure is delivered as an
error event. Recovery failures completed within that window still return
502.

Reloads still run in the shared thread pool and are serialized by the
backend. Burst-load behavior during a reload is unmeasured.

## Validation

- **Teardown and tokenization:** 1,096 selected backend tests passed; 1
skipped. Six new cases cover cancellation during watcher cleanup on all
four non-streaming paths and embedding truncation after another request
restarts the server, including a restart between the two tokenization
calls.
- **Recovery-wait follow-up:** 80 recovery tests and 1,317 other
selected backend tests passed; 1 skipped. These cover delayed reload
keepalives, Stop/disconnect and task cancellation, admission and
registration cleanup, retry limits, refreshed URL/key pairs, and
cancellation at reload completion. The broad-suite and live socket
checks below preceded this follow-up; no live model reload was repeated.
- **Initial Linux, Python 3.13, CPU run:** I ran the 344 backend test
files that import `routes/inference.py` (CI's serial-only and
live-server exclusions applied). 23,011 passed and 386 skipped.
- **Existing failures, not from this change:** 261 failures and errors
in torch-backed diffusion, audio and GPU tests also fail on `main` with
this sandbox's broken torch. None fails only on this branch.
- **Count-the-call-sites guards:** three source scans counted copies
(the auth-header scan, the five-client `trust_env` scan and the
direct-counter placement scan). They now check the one owner instead.
- `test_llama_upstream_single_owner.py` exercises refused connections
and connections dropped before upstream headers, along with blocked
reloads that verify keepalives and prompt Stop/disconnect cleanup
without a retry after cancellation.
- Formatted with `scripts/run_ruff_format.py` (ruff 0.6.9); `ruff check`
(0.16.10) is clean.

Initial live crash check: a real stand-in llama-server process on a real
port, either SIGKILLed or exiting mid-request, then relaunched by
`_respawn_if_dead` on a new port with a new key. Each route was driven
over real sockets.

| Case | Before | After |
|---|---|---|
| `/v1/responses` stream (Codex), server killed | `response.failed`:
"Lost connection to the model server" | Answers from the relaunched
server |
| `/v1/completions`, server killed | 500 Internal Server Error
(`ConnectError`) | Answers |
| `/v1/completions` stream, server killed | Error chunk: "Lost
connection…" | Answers |
| `/v1/embeddings`, server killed | 500 Internal Server Error
(`ConnectError`) | Answers |
| `/v1/messages`, server dies mid-prefill | 500 Internal Server Error
(`RemoteProtocolError`) | Answers |
| `/v1/messages` stream, connection drops before upstream headers |
`error` event: "Lost connection…" | Answers |
| `/v1/chat/completions`, stream and non-stream, both crashes | Answers
| Answers |

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Internal error due to MTP set on by default on Apple Silicon

1 participant