Repository navigation
Studio: isolate the RAG embedder's first GPU allocation so a driver segfault cannot kill the backend - #8601
Studio: isolate the RAG embedder's first GPU allocation so a driver segfault cannot kill the backend#8601danielhanchen wants to merge 11 commits into
Conversation
…egfault cannot kill the backend A ROCm wheel built for the wrong gfx arch does not raise, it SIGSEGVs on the first real allocation. The RAG embeddings warm made that allocation in-process on a daemon thread, so the fault took uvicorn down before any model was selected. A signal never becomes a Python exception, so no handler on that path could have caught it. Ask a short-lived child to allocate first, and treat its death as the answer: on a condemned ROCm host the embedder loads on CPU instead. Same backend, same model, so the vectors are unchanged and no knowledge base needs reindexing. Closes #8474
… the settings path Three fixes from review. The probe child is a fresh interpreter, and os.add_dll_directory registrations are process-local, so on Windows ROCm it could not import torch at all and the fail-closed verdict condemned a healthy AMD GPU to CPU for the process. The bin directories are now discovered parent-side and registered before the import, as main.py and core/training/worker.py already do for the same reason. active_backend_is_llama() runs inside PUT /embedding-model. It reached the resolver, and through it either the probe (a cold torch import is allowed 120s) or the in-process AMD GPU-memory query. It now answers ROCm and detection-not-settled without asking either. False there leaves the ST pickle gate engaged, which is the safe direction for a security check. Detection state is tri-state now, so 'not yet known' is no longer collapsed into 'not ROCm', which was what let that query stay reachable. The backend builder caches its answer, so it settles detection first rather than taking the provisional one.
…fault-guard # Conflicts: # studio/backend/main.py
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
Holding back the resolver for every host whose detection had not settled was too broad. settings.py reads that provisional answer as 'not llama' and stops applying its GGUF handling, so a valid local .gguf could transiently 409 on a CPU or macOS host that never had an AMD GPU. The caution now applies only where ROCm is actually possible, decided without torch and without detection: never on macOS, by ROCm's own KFD topology node on Linux (which utils/hardware/hardware.py already reads), and by the presence of a ROCm install on Windows. Each branch is a file-existence test. Unsure still means possible, so the crash guard keeps the safe side.
…equest path, reap a stuck probe child An installed HIP SDK is not a ROCm host. main.py already refuses to let HIP_PATH/ROCM_PATH pick a backend for exactly that reason, so a Windows CUDA or CPU box carrying the SDK was being handed the provisional answer and losing its GGUF handling. The signal is now torch.version.hip, a build attribute that initialises no driver, read only when torch is already imported; without torch loaded, Windows claims nothing rather than guessing. The settings gate no longer goes through the resolver once ROCm is ruled out. ensure_hardware_detected() holds _DETECT_LOCK across a cold torch import, so that path could park a request for the whole detection pass. The rest of auto needs no detection, so it is split out and called directly. A child that outlives SIGKILL is retained and reaped on a daemon thread. SIGKILL is not delivered while a task sits in an uninterruptible driver wait, and a wedged GPU is how a task gets there, which is the scenario this module exists to survive; dropping the last reference was the one way it became an unreaped stray.
…e backend lifetime Reading only torch.version.hip was narrower than detection's own test. AMD SDK wheels leave it unset and say rocm only in torch.__version__, which hardware.py already falls back to, and a torch that is in sys.modules while still executing has neither attribute yet. Both were being read as not-ROCm, which let the request path reach the in-process AMD query on exactly the hosts this change protects. Missing metadata now stays possibly-ROCm. The probe child is adopted by the process-lifetime reaper and gets the parent-death binding the other GPU children use. It can sit in a cold torch import or a driver ioctl for the whole timeout, so a Studio killed in that window was leaving it reparented and running against the GPU the next backend probes. A child handed to the reaper stays adopted until it is really gone.
… imported The pre-import Windows branch was the last place a real ROCm host could be classified non-ROCm and sent through the in-process AMD query: there is no KFD node there, and an installed HIP SDK says nothing about which wheel is present. Guessing either way traded one host's crash for another's GGUF handling. torch/version.py is generated literals, and find_spec locates the package without executing it, so the same two facts hardware detection reads are readable while torch is still unimported. hip set, or rocm in __version__, matching detection's own test. Unreadable or absent falls back to the platform, and Windows now keeps the caution rather than the convenience. Cached: it is filesystem I/O on a request path and an install does not change under a running backend.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9bccde1751
ℹ️ 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".
| # _DETECT_LOCK across a cold torch import, so going through _resolve_auto here | ||
| # would park the request on exactly the wait this branch exists to avoid. ROCm | ||
| # is ruled out by now, and the rest of auto needs no detection at all. | ||
| key = _resolve_auto() if is_rocm is False else _resolve_by_gpu_and_binary() |
There was a problem hiding this comment.
Keep the settings classification on a truly nonblocking path
When hardware detection is unsettled but ROCm has been ruled out, this calls _resolve_by_gpu_and_binary() from the settings request. That helper invokes LlamaCppBackend._get_gpu_free_memory(), which imports torch after a missing/empty nvidia-smi result and can also run the 15-second Vulkan subprocess probe. Thus a CPU host, or an NVIDIA host without nvidia-smi, can still block PUT /embedding-model on the same cold torch detection/import this branch is intended to avoid. Use a strictly torch-free, nonblocking classification here rather than the general GPU-memory resolver.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, because the branch it describes is byte-for-byte what this path already did before the PR.
_resolve_by_gpu_and_binary is not new logic; it is the pre-PR body of _resolve_auto, lifted out unchanged so the settings path could keep calling it without the ROCm handling in front. On main today, active_backend_is_llama() with no backend built calls _resolve_auto(), which is exactly _get_gpu_free_memory() then _find_llama_server_binary(). So on a CPU host, or an NVIDIA host without nvidia-smi, PUT /embedding-model reaches the same torch import and the same Vulkan probe now as it did before, and no host is slower than it was. The change only ever removes work from this path: a ROCm or possibly-ROCm host returns before any of it.
Making the classification strictly torch-free would be a real change in behaviour rather than a restoration, and it is the change the earlier rounds argued against: this is precisely where routes/settings.py decides whether a local .gguf needs HF verification, and answering it without the GPU query is what produced the transient 409 in the pending-detection and HIP SDK findings. I would rather leave a pre-existing cost in place than trade it for a wrong answer.
Happy to look at making that gate cheap for everyone, but as its own change against main, where it can be judged on its merits instead of riding along with a crash fix.
… bound itself preexec_fn forks this multithreaded, possibly torch-initialised server and runs Python before exec. A lock another uvicorn thread held at fork time is still held in the child, which can hang it before exec while the parent waits inside Popen, where the timeout does not yet apply. Python's own docs call preexec_fn unsafe in the presence of threads, and it also disables subprocess's vfork fast path. The orphan protection it was there for now lives in the child: a watchdog that exits it well after the parent's own deadline, so a Studio killed mid-probe leaves something that stops by itself. adopt_pid still gives shutdown its backstop. The watchdog needs daemon set explicitly. A Timer is a Thread and is not daemon by default, so without it the child could not exit until the watchdog fired and every probe on every host timed out. Caught running the real child, and now pinned by a test that executes it against a stubbed torch.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
I created #8609 after this PR was submitted, so treat this as a comparison rather than a review. Both PRs isolate the first torch allocation in a child. I recommend using #8609 as the base and closing this one because it contains the change without adding ROCm classification to
I have now ported the stronger child-process handling from this PR to #8609:
|
…res fail closed find_spec returning nothing means torch is not installed, which is decisive rather than unknown: there is no ROCm torch path to protect. Reporting unknown made Windows cautious forever, and on a --no-torch install where detection never settles that cost PUT /embedding-model the llama answer auto really resolves to, rejecting a valid local GGUF. Unknown is now reserved for a torch that is present but unreadable. communicate() can also raise OSError on a pipe or handle failure, which escaped a function documented never to raise and left the child running to its watchdog. It is caught, the child is torn down, and the verdict fails closed like the spawn and timeout paths.
… uncovered An OSError from the post-kill read was raised inside the timeout branch, where the outer OSError handler was a sibling rather than an ancestor, so it escaped a function documented never to raise and left the child unreaped. Terminate and kill now escalate through one loop with a single pair of handlers, so every attempt is covered the same way, and anything not confirmed dead reaches the reaper whether it outlived SIGKILL or could not be read.
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
|
Closing in favour of #8609, which fixes the same crash with better scope. Detailed review there: #8609 (comment). Short version of why that one is the better base: It leaves Its verdict rule is also narrower and better argued: only a fatal signal or a timeout marks a device unusable, and an ordinary Python failure is left to the loader, which raises it identically and reports it more accurately than a silent CPU downgrade. Its probe does an fp16 matmul, so it initialises the vendor BLAS rather than only touching the allocator, and it was validated on real hardware with genuine child-process access violations instead of my mocks. @oobabooga has already ported the child-process handling from here: no Linux Three things from this branch are worth carrying over and are in the review on that PR: "could not spawn" and "could not read the result" should fail closed rather than proceed to the in-process allocation, Leaving #8474 open until #8609 lands. Branch stays up if anything else is wanted from it. |
Closes #8474.
What happens today
On the gfx1151 Strix Halo host in #7331, the Studio backend dies with a bare
Segmentation fault.#8480 fixed the wheel mismatch that triggers it. This is the separate reason a mismatched wheel takes down the whole backend rather than one feature: the RAG embedder makes the process's first GPU allocation in-process, with nothing between it and a signal.
The embedder walks to
SentenceTransformer(load_target, device = "cuda")._device()mapsDeviceType.CUDAto"cuda", and ROCm isDeviceType.CUDAinternally, so there is no ROCm branch, no arch check, no isolation and no CPU fallback anywhere before the load.The handlers that look like they cover this cannot.
except Exception as st_errinembeddings.pyis a Python handler; a SIGSEGV insidelibamdhip64never becomes a Python exception, and signal disposition is per process, so the fault takes uvicorn with it.Rebased onto #8564, which changed the trigger but not the hazard. That PR removed the eager
_warm_rag_embedderstartup warm, so embeddings now stay cold until something actually asks for vectors. The crash is therefore no longer at startup: it moves to first embedding use, reached fromcore/rag/ingestion.py,core/rag/retrieval.py,core/rag/web_rank.pyand therag-folder-syncthread. All four funnel through the same_get_backend()->_get()allocation, in the backend process, so the process still dies; a user now just has to touch RAG first. This PR no longer changesmain.pyat all.The reporter's own data narrows this usefully: on that host
torch.cuda.is_available()returnsTrueand the GPU enumerates correctly. Detection and device-property queries survive. Only the first real allocation dies. So the fix belongs at the allocation site, not at the detection layer.The fix
The question "can this device allocate" cannot be answered in the process that has to survive the answer. A short-lived child is asked to allocate first, and the child dying is the answer.
New
studio/backend/utils/device_allocation_probe.py. The child allocates one element, writes to it, and synchronizes. The synchronize is the part that matters: device execution is asynchronous, so without it an allocation that faults in the kernel can outlive the statement that queued it and the child exits 0 while the fault is still in flight.torch.emptyalone is too weak for the same reason.Everything that is not a clean exit fails closed: a signal, any nonzero exit, a timeout, a failed spawn. Timeout is classified before the terminate/kill ladder, so the signal we sent is never reported as the driver's doing. The parent side imports only the standard library, so it stays importable on a
--no-torchinstall and is not what finally drags torch into the lean main process.Three things were deliberately left out. No
multiprocessing: uvicorn is multithreaded, HIP and CUDA are fork-hostile, andset_start_methodis process-global state this module does not own. No model load in the child: the parent would have to load it again, paying the download, the deserialization and the security gate twice. No on-disk cache: a negative verdict that outlived a driver or wheel repair would pin a healthy machine to CPU with no way to tell why. The verdict is memoized per process, keyed by the device and byCUDA_VISIBLE_DEVICES,HIP_VISIBLE_DEVICES,ROCR_VISIBLE_DEVICESandHSA_OVERRIDE_GFX_VERSION, since that last one is exactly the spoof behind #7331.Degrading to CPU, not to llama-server
_build_st_backend_or_fallbackalready degrades to the GGUF llama-server embedder, and it would have been the smaller diff to reuse. It is the wrong target here: llama-server embeds into a different vector space, so every knowledge base already indexed with sentence-transformers would need reindexing, for a host whose only problem is that it cannot use its GPU.A condemned host keeps the sentence-transformers backend and moves the device to CPU. Same backend, same model, identical vectors, no reindex.
bge-smallis small enough that this is a slowdown, not a loss of function. llama-server remains the fallback for genuine Python-level load failures, unchanged.The degraded load also drops fp16, which is a win on the GPU and a slow, patchily supported path on CPU. Only the degraded case switches: a host that never had a GPU still loads exactly as it did before. That pre-existing fp16-on-CPU load for genuine CPU and Apple hosts is untouched here.
_resolve_autowas steering into the crash_resolve_auto()picks the backend by askingLlamaCppBackend._get_gpu_free_memory(), and its docstring claimed that check is "torch-free (nvidia-smi)". That is true on NVIDIA and false on AMD, where it falls back to torchmem_get_infoin this process. So the one genuinely pre-load step was actively steering an affected host toward the fault rather than away from it. The docstring is corrected.A ROCm host now answers without asking it, because the answer is fixed: auto resolves to sentence-transformers whatever the GPU turns out to be, since a working GPU takes it and a condemned one is placed on CPU at the load. No allocation probe runs there either; the device decision belongs to the load site.
Deciding "is this ROCm" without importing torch or waiting for detection
active_backend_is_llama()runs insidePUT /embedding-modelviaroutes/settings.py:_llama_backend_active, feeding the ST pickle security gate and deciding whether a local.ggufneeds HF verification. It therefore cannot block, and it cannot be wrong.It cannot block: hardware detection imports torch under
_DETECT_LOCK, and the probe child is allowed a 120s cold import, so neither may sit on that path. Detection state is tri-state (Nonewhile unsettled) and the request path never forces it.It cannot be wrong either, because answering "possibly ROCm" too eagerly is not free:
settings.pyreads that as "not llama" and drops its GGUF handling, so a valid local.ggufgets a transient 409 on a host that never had an AMD GPU. Several plausible signals turned out to be wrong in one direction or the other, and the review found each of them:main.pyalready refuses to letHIP_PATH/ROCM_PATHalone pick a backend, for exactly that reasontorch.version.hipalone is narrower than detection's own test, which also falls back torocmintorch.__version__for AMD SDK wheels, and a torch that is insys.moduleswhile still executing has neither attribute yetWhat settles it is the installed wheel.
torch/version.pyis generated literals, andfind_speclocates the package without executing it, so the same two facts detection uses are readable while torch is still unimported. Absent torch is a definite non-ROCm answer rather than an unknown, which matters on a--no-torchWindows install where detection never settles and auto really does resolve to llama-server.The probe child
Three things the child needs that are not obvious:
Windows ROCm DLL directories.
os.add_dll_directoryregistrations are process-local, so a fresh interpreter does not inheritmain.py's and cannot findamdhip64.dll. It would fail to import torch, exit nonzero, and failing closed would condemn a healthy AMD GPU for the life of the process.core/training/worker.pyalready carries this note for its own child. The directories are discovered parent-side, which keeps the version ordering testable, and registered before the import.No pre-exec hook. The repo's lifetime helper binds children with
preexec_fn, and that forks this multithreaded server and runs Python before exec, where a lock another uvicorn thread held at fork time is still held. The child can hang there while the parent waits insidePopen, ahead of the timeout. Python's own docs callpreexec_fnunsafe in the presence of threads. The long-lived GPU workers accept that trade; a short probe should not.So the child bounds itself, with a watchdog past the parent's own deadline, which covers the orphan case the hook was wanted for.
adopt_pidstill gives shutdown its backstop. That watchdog neededdaemonset explicitly: aTimeris aThreadand is not daemon by default, so the first version could not exit until it fired and every probe on every host timed out. Running the real child is what caught it.Cost on unaffected hosts
The probe only runs on ROCm, and only at the embedder load. NVIDIA, Intel XPU, Apple, CPU-only and
--no-torchinstalls spawn no child and behave byte-identically to before. A healthy ROCm host pays one child once per process.main.pyis untouched: #8564 deleted the warm this PR originally logged around, and that deletion is taken as-is.Tests
70 new tests.
tests/test_device_allocation_probe.py(39) fakes the child and pins the classification: SIGSEGV, SIGABRT/SIGILL/SIGBUS/SIGFPE, a Windows access violation in both its signed and unsigned forms, any ordinary nonzero exit, a timeout, a failed spawn and a failed read all come back "do not allocate in this process"; the teardown escalates terminate to kill and hands anything not confirmed dead to the reaper; memoization holds per device and breaks on each of the four device-identity variables; the Windows DLL directories are registered, newest version first, strictly before the import; and the child script is executed against a stubbed torch to prove it exits promptly.That last one is not ceremony. Three bugs in this PR were found by running things rather than reading them: a signed
0xC0000005read as "killed by signal 1073741819", the naive fix for it then misreading-11as a native fault (-11 & 0xFFFFFFFFalso lands above0xC0000000, so sign cannot separate them, only magnitude), and a watchdogTimerleft non-daemon, which made the child unable to exit until it fired and so timed out every probe on every host.test_rag_embeddings.pygains 10, covering the device decision: a failed probe moves the embedder to CPU and a passing one leaves it on the GPU; NVIDIA, XPU, Apple and CPU are never probed; the degraded load uses float32 while a genuine CPU host still gets float16; the security gate is not bypassed by the CPU fallback; and an end-to-end case asserting that on the #7331 shape the load completes, encode returns vectors and the process is still alive.test_rag_embed_llama_server.pygains 21, covering the request path and the ROCm signal: the settings gate fails the test if it forces detection, reaches the probe, or reaches the AMD GPU query; a CPU, macOS, non-ROCm or--no-torchhost keeps its llama/GGUF answer; an installed HIP SDK alone does not make a host ROCm while an AMD SDK wheel withouthipmetadata does; a half-imported torch stays cautious; and the on-disk read is exercised against a fake package whose__init__raises if anything imports it.Locally,
studio/backend/tests/: 22384 passed, with a failing set byte-identical to the pre-change baseline on this machine (that set is missing optional backend deps, not code). Staging CI is green, 11 workflows, after one network flake fetching the diffusers archive passed on re-run.The probe was also run for real against a healthy NVIDIA
cuda:0: passes in ~2s, and a bad ordinal or a garbage device string fails closed with a truncated reason rather than raising.There is no AMD hardware and no ROCm CI in this repo, so the ROCm behaviour, including the Windows DLL path, is mock-based throughout and has not been validated on real silicon.
Not in this change
llama_cpp._get_gpu_free_memory()'s torch fallback,hardware.py's torch memory and property fallbacks, andembed_llama_server.py's auto GPU selection all have the same torch-on-ROCm shape and could consume the same cached verdict. They are left alone because on the #7331 host those calls demonstrably succeeded, and widening this PR on speculation is how a startup fix becomes a hardware-detection rewrite.Also untouched: the in-process
pipe.to(device)in the diffusion and video backends, which is a real second in-process allocation site but not a startup one, and the fact that therag-folder-syncthread reaches the embedder without any user action while not being gated byUNSLOTH_STUDIO_DISABLE_TORCH_WARM. That thread goes through the same_get_backend()choke point, so it inherits this fix; the env-var asymmetry is separate.