Skip to content

Studio: contain RAG embedder torch allocation crashes - #8609

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-rag-embed-device-probe
Aug 13, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-rag-embed-device-probe

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Problem

#8564 removed the eager RAG embedder warmup, so a mismatched torch build no longer kills Studio during startup. The underlying crash still occurs on the first RAG operation: embeddings._get() loads SentenceTransformer on the detected accelerator, and an incompatible ROCm stack can terminate the backend during its first allocation (#7331, gfx1151).

Fatal driver signals cannot be caught by the existing Python exception handlers. Lazy loading therefore changed when the crash happens, not whether it happens.

Fix

Probe the selected torch device in a short-lived child before loading sentence-transformers. The probe performs an fp16 allocation and matmul, which also initializes the vendor BLAS library.

A fatal signal or timeout marks the device unusable. Ordinary Python exceptions and spawn failures are left to the existing in-process loader so the probe does not reject a working device based on an incomplete result.

The fallback order is:

  1. Use the selected accelerator when its probe succeeds.
  2. Fall back to CPU when only the accelerator probe fails. This keeps the same sentence-transformers model and embedding space, so existing indexes remain queryable.
  3. Raise TorchDeviceUnusableError when CPU also fails, allowing the existing llama-server fallback to take over.

Probe results are cached per device. Set UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE=1 to restore the previous behavior.

Scope

This protects the initial torch allocation and BLAS initialization. A fatal signal during a later encode() call can still terminate the backend and would require isolating every encode operation.

Verification

  • Focused embedding and startup suites: 254 passed, 1 skipped.
  • Wider RAG suite: 266 passed, 1 skipped.
  • Tests use genuine child-process access violations on POSIX and Windows paths, and cover accelerator to CPU to llama-server fallback.
  • On an RTX 6000 Ada host, the probe passed and Studio completed ingestion and dense retrieval using the CUDA sentence-transformers backend.

Closes #8474.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Agreed on consolidating here, and thanks for porting the child-process handling across. I am closing #8601 in favour of this one.

Your scoping call is the right one. Leaving _resolve_auto() and active_backend_is_llama() alone is what I should have done: the ROCm classification I added to the PUT /embedding-model path caused four rounds of self-inflicted regressions in #8601 (transient 409s on CPU, macOS, HIP-SDK-on-CUDA and --no-torch Windows hosts), and the risk it was protecting against, _get_gpu_free_memory() reaching torch mem_get_info on AMD, is unproven: on the #7331 host every driver query succeeded and only the allocation faulted. I said as much in my own review thread there. Not worth the blast radius.

Your narrower verdict rule is also better than mine, and for the right reason: isolation only needs to cover what cannot be caught in-process. An ordinary Python exception from the child will be raised identically by the loader, which reports it better than a silent CPU downgrade does. The fp16 matmul is a more faithful probe than my empty plus zero_ too, since it initialises the vendor BLAS, and validating on real hardware with genuine access violations beats my mocks.

Three things I would fix before this lands. The first is the one place I would not follow you.

1. "No information" should fail closed, not open.

device_can_allocate() returns True when the child cannot be spawned and when its result cannot be read. Both paths then proceed to the in-process allocation this PR exists to prevent, which on an affected host is the crash rather than an exception. The asymmetry matters: failing closed costs CPU-speed embedding, failing open costs the backend.

I agree with you that an ordinary Python failure from a child that ran and reported should defer to the loader. But a probe that never ran, or whose verdict we could not read, has not told us the device is fine, only that we do not know. Suggest keeping your signal and timeout rule and adding "could not run" and "could not be read" to the unusable side.

2. _terminate_and_drain() can raise, and on the path where the device really did fail.

The post-kill communicate() catches only TimeoutExpired. The except OSError at the bottom is a sibling of the outer except subprocess.TimeoutExpired, so it cannot catch anything raised while handling that timeout:

except subprocess.TimeoutExpired:
    try:
        process.kill()
    except OSError:
        pass
    try:
        _, stderr = process.communicate(timeout = _TERMINATE_GRACE_SECONDS)
    except subprocess.TimeoutExpired:   # an OSError here escapes
        _reap_later(process)
except OSError:                          # sibling, never sees the above
    pass

An OSError there escapes device_can_allocate() from inside the timeout branch, so the return False never happens: a device that genuinely timed out ends up raising instead of degrading to CPU, the existing handler sends it to llama-server rather than keeping the same embedding space, and the child never reaches _reap_later. Because lru_cache does not cache exceptions, the next call re-runs the full 120s probe.

This is the same bug Codex found in #8601 at the last round; the shape came across with the port. I fixed it by escalating terminate and kill through one loop with a single pair of handlers, so no attempt sits in a branch the handlers cannot see, and anything not confirmed dead reaches the reaper: 8101abdde.

3. _died_by_signal() condemns on SIGKILL and SIGTERM.

On POSIX any negative return code counts, so a probe child killed by the OOM killer, by a container stop, or by an operator marks a perfectly healthy GPU unusable for the life of the process. LlamaCppBackend._is_signal_crash() deliberately excludes SIGKILL and SIGTERM for this reason and matches only SIGILL, SIGABRT, SIGBUS, SIGFPE and SIGSEGV. Worth mirroring, since your rule is otherwise exactly its hard-fault set.

Two smaller notes, neither blocking:

UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE=1 knowingly restores a process-killing path. I deliberately added no opt-out in #8601 for that reason, though I can see the argument for an escape hatch. If it stays, it is worth saying in the docstring that the failure it restores is a hard crash and not an error.

Your scope note is right that a fatal signal during a later encode() can still take the backend down. Worth an issue so it is tracked rather than implied.

…atal-signal set

Three fixes on top of the probe.

A probe that could not be spawned, or whose result could not be read, was
treated as proof the device works, so the backend went on to make the
in-process allocation this exists to prevent. It is not evidence either way, and
the two ways of being wrong are not symmetric: CPU costs embedding speed, the
accelerator costs the process. Unknown now means unusable for an accelerator.

It keeps meaning usable for CPU, which is the opposite trade. A CPU load cannot
fault a GPU driver, and condemning it would send the caller past its CPU
fallback to the GGUF backend, changing the embedding space and forcing a reindex
over what may be a passing failure to fork.

_terminate_and_drain could raise on the path where the device really had failed.
The post-kill read sat inside the timeout branch, where the trailing except
OSError was a sibling and could not see it, so a pipe failure escaped
device_can_allocate: a timed-out device raised instead of returning False, the
child never reached the reaper, and since lru_cache does not cache exceptions the
next call re-ran the whole probe. Terminate and kill now escalate through one
loop with a single pair of handlers.

_died_by_signal counted every negative return code, so a probe killed by the OOM
killer, a container stop or an operator condemned a healthy GPU for the life of
the process. Narrowed to the hard-fault set LlamaCppBackend._is_signal_crash
already uses, which excludes SIGKILL and SIGTERM for the same reason.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed the three review items to the branch directly (ef49978) since maintainer edits are on, rather than leave you to apply them. Shout if you would rather I had opened a PR against your fork instead.

One of them changed shape once I traced it through your fallback chain, and that is worth explaining.

Failing closed on "no verdict" is right for an accelerator, but applying it to CPU as well would have been a regression. _load_device() probes CPU as its second step, so a failure to fork would have condemned both, raised TorchDeviceUnusableError, and sent the caller to the GGUF backend, changing the embedding space and forcing a reindex over what may be a passing resource problem. A CPU load cannot fault a GPU driver, so there is nothing to protect against there. Unknown therefore means unusable for an accelerator and usable for CPU, which keeps the degradation on the path you designed:

spawn fails, accelerator -> False
spawn fails, cpu         -> True     # still lands on CPU, same vectors, no reindex

The other two are as described. _terminate_and_drain now escalates terminate and kill through one loop with a single pair of handlers, so the post-kill read is no longer sitting in a branch the except OSError cannot see; anything not confirmed dead reaches the reaper. _died_by_signal now matches the same hard-fault set as LlamaCppBackend._is_signal_crash (SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV) so an OOM-killed probe no longer condemns a healthy GPU for the life of the process.

Your deferral rule is untouched: a child that RAN and raised an ordinary exception still returns true, so the loader reports it. Verified against a real GPU here, where a bad ordinal exits nonzero without a signal and correctly defers:

real cuda:0     -> True
bad ordinal     -> True    (exception, not a fault)

Tests: your test_torch_device_probe.py updated for the new verdicts, plus test_an_unrunnable_probe_still_leaves_cpu_available, test_a_read_failure_during_teardown_does_not_escape, and SIGKILL/SIGTERM/SIGINT cases in the _died_by_signal table. Full backend suite is 22354 passed with a failing set byte-identical to main on this machine (that set is missing optional deps here, not code). Formatters and ruff clean.

Two things from my earlier comment are still open and both are yours to take or leave: the UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE=1 docstring saying plainly that what it restores is a hard crash rather than an error, and an issue tracking the encode() case your scope note calls out.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…n the XPU selectors

The self-limit was a threading.Timer, which cannot fire in the one case it exists
for: a torch hung inside a native call never returns to the interpreter loop, so
the GIL is never released and the callback never runs. SIGALRM with no handler
installed is enforced by the kernel, runs no Python and needs no GIL, so an
orphaned probe stops on time. Windows has no alarm and keeps the timer.

The cache key covered the CUDA and ROCm selectors but not the Intel ones, while
_TORCH_DEVICE maps DeviceType.XPU to "xpu", so the probe runs there too. A change
to ZE_AFFINITY_MASK or ONEAPI_DEVICE_SELECTOR moves the silicon underneath a
cached verdict: a stale pass skips the probe on an untested device, a stale
failure pins a working one to CPU.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: c74d703fae

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

@oobabooga

Copy link
Copy Markdown
Member Author

c74d703 correctly addresses the GIL-dependent deadline and XPU cache identity. Adding ONEAPI_DEVICE_SELECTOR was also necessary.

Two code details remain:

  1. The self-deadline is still classified as success. On Windows the timer exits with status 70; on POSIX signal.alarm() exits with -SIGALRM. Neither matches _FATAL_SIGNALS, so both currently reach return True. Both should return False as timeouts.
  2. Set SIGALRM to SIG_DFL before arming it. An ignored signal disposition can survive exec, so an inherited SIG_IGN makes signal.alarm() ineffective. I reproduced this with a parent ignoring SIGALRM; the child armed an alarm, slept past it, and exited normally.

The module docstring and PR description also still state that spawn failures defer to the in-process loader, which no longer matches ef499782de for accelerators. The cache description should say that results are keyed by device and device-identity environment.

For completeness, the XPU identity tuple could also include SYCL_DEVICE_FILTER and SYCL_DEVICE_ALLOWLIST, since the runtime still supports both as device filters even though SYCL_DEVICE_FILTER is deprecated.

A child that stopped itself hung, and a hang is a device failure, but neither
form of it was recognised. SIGALRM is not a hard fault so the kernel-enforced
deadline fell through _died_by_signal, and the Windows watchdog status is an
ordinary non-zero exit. Both were reported as a healthy device, which then let
the parent make the allocation the probe stands in front of. Reachable when the
parent did not enforce its own shorter timeout first, such as a suspended
backend.

Both forms now return False, and the exit status the child writes is pinned
against the constant the parent matches on.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

hardware.py already counts GPU_DEVICE_ORDINAL as a live ROCm visibility mask, so
changing it renames the silicon behind "cuda" exactly as the other masks do. The
cache key did not include it, so a verdict taken before the change was reused for
a device that was never probed, and a stale pass is the direction that costs the
backend.

Also pins the cache key against the set hardware.py honours, so the two lists
cannot drift apart again.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two ways the probe reported a device it had not cleared.

exec keeps an inherited SIG_IGN and an inherited blocked signal mask, so under a
supervisor that ignores or blocks SIGALRM the child deadline was unenforceable
and an orphaned probe could sit on a hung driver indefinitely. Verified: with the
disposition inherited the child ran to completion and exited 0. It now restores
SIG_DFL and unblocks the signal before arming the alarm.

A native abort() on Windows leaves the CRT's plain exit status 3 rather than an
NTSTATUS, so it read as an ordinary non-zero exit and the crashing device came
back usable, which let the parent repeat the crash in its own process. Status 3
is now a hard fault there, matching LlamaCppBackend._is_abort_exit, with a test
pinning the two to the same value.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from oobabooga Aug 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e378a4a466

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

test_chat_text_encoding enforces that anything spawning a Python child and
decoding it as utf-8 also tells the child to write utf-8, and it reads the Popen
call itself. The wrapper was applied several lines earlier, so the probe was
flagged and the check failed on this branch. Wrapping at the call site keeps the
same single application and puts it where the policy test can see it.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A probe killed by SIGKILL or SIGTERM is not a hard fault, so it is no evidence
against the device, but it is not the clean run that earns a pass either. It was
returning true, and importing torch and building its device context is enough on
its own to trip a cgroup or host OOM, so the very condition that killed the probe
sent the caller on to a much larger load in the backend process.

Unclassified child deaths now take the existing no-verdict path: unusable for an
accelerator, still usable for CPU, which cannot fault a driver and whose fallback
would otherwise change the embedding backend. The module docstring was describing
the older fail-open behaviour and is corrected with it.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 22f59f8f3d

ℹ️ 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 ec9db28 into unslothai:main Aug 13, 2026
35 of 40 checks passed
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.

Studio: RAG embeddings warm makes the first GPU allocation in-process, so a driver-level segfault kills the backend

3 participants