Skip to content

Studio: fall back to CPU when auto-selected Vulkan crashes - #8050

Merged
danielhanchen merged 26 commits into
unslothai:mainfrom
oobabooga:studio-auto-vulkan-cpu-fallback
Aug 8, 2026
Merged

danielhanchen merged 26 commits into
unslothai:mainfrom
oobabooga:studio-auto-vulkan-cpu-fallback

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Summary

On affected Intel systems, Studio's automatically selected Vulkan llama-server can crash while loading a model even though the model works on CPU.

This PR retries that failure once using the same managed installation without its Vulkan plugin. If the CPU retry succeeds, Studio keeps the model loaded and warns that GPU acceleration is disabled for the session.

What changed

  • Retry text and vision startup crashes in a temporary CPU-only runtime.
  • Reuse the Vulkan installation's existing server and CPU libraries, without downloading another build.
  • Preserve CPU mode across respawns and duplicate load requests.
  • Report the fallback through the API, runtime status, and chat UI.
  • Remove the temporary runtime on failure, replacement, or unload.

Scope

Recovery applies only to an Unsloth-managed Vulkan build selected automatically with Auto placement. Explicit Vulkan selection, manual GPU settings, placement overrides, and custom binaries keep their existing behavior. If the CPU retry also fails, Studio returns that failure normally.

Testing

  • 81 focused backend tests passed.
  • Python compilation, Ruff, and git diff --check passed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen self-assigned this Aug 8, 2026
- Keep the requested drafter for the CPU replay: the --spec-default retry
  runs first on a signal crash and re-latches _last_spawn_cmd, so the
  recovered session lost the MTP/DSpark drafter it asked for.
- Compute fallback eligibility after the launch scrubs the environment, so
  an inherited LLAMA_ARG_SPLIT_MODE this launch already dropped no longer
  disqualifies the replay of a child that never saw it.
- Refuse to stage a non-Vulkan managed runtime, so a client-supplied
  cpu_fallback cannot report a Vulkan crash that never happened.
- Restage when the managed install changes under the same path: an update
  swaps the tree in place, so the staged copy went stale silently.
- Retry a failed staged-runtime cleanup instead of dropping the handle;
  TemporaryDirectory.cleanup detaches its finalizer before removing the
  tree, so a locked file on Windows orphaned the directory for good.
@danielhanchen

Copy link
Copy Markdown
Member

Went through this one properly and pushed two commits to the branch.

1. Merged main in. The branch was 62 commits behind and conflicting. One conflict, in studio/backend/core/inference/llama_cpp.py: main wrapped _spawn_and_wait in the _memory_launch_pending try/finally while this PR added the intent.cpu_fallback replay prologue at the same spot. Both are needed, so the prologue runs first and then the guarded spawn. The PR is mergeable again.

2. Fixed five gaps. Each has a regression test in test_gpu_init_crash_message.py that fails without the fix.

  • The drafter was silently dropped from the CPU replay. On an Auto MTP/DSpark load, a Vulkan startup signal hits the --spec-default retry first, which re-latches _last_spawn_cmd to the drafterless argv. The CPU replay then started from that, so the recovered session lost the drafter the CPU runtime could have run, and the user was told speculative decoding was the cause. Now the pre-spec command is kept for the replay and _spec_fallback_reason is cleared when it comes back.

  • Eligibility was snapshotted before the environment scrubs. _cpu_fallback_eligible was computed right after _llama_server_env_for_binary, but a non-tensor Auto load pops an inherited LLAMA_ARG_SPLIT_MODE (and LLAMA_ARG_TENSOR_SPLIT) a few lines later. The crashed child never saw the value that disqualified its own recovery. Moved the check below the scrubs. The intent behind the comment at _CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS is preserved: a placement value that actually reaches the child still blocks the replay.

  • cpu_fallback was not bound to Vulkan. LoadRequest.cpu_fallback reaches GgufLoadIntent through the generic field copy in _gguf_request_intent, and _prepare_cpu_fallback_launch only gated on _is_unsloth_managed_binary. A caller could stage a CPU-only runtime for a managed CUDA or HIP install and have Studio report cpu_fallback_reason="vulkan_startup_crash". Added an _is_vulkan_backend gate.

  • A staged runtime was reused across a llama.cpp update. Reuse keyed on source_binary alone, and an update swaps the install directory in place, so the path is byte-identical and the hardlinked old inode still exists. server_caps is probed from the live binary and drives flag spelling, so a build that gained --spec-draft-ngl would emit it into a staged server that only knows -ngld. Added an inode/size/mtime stamp to _CpuFallbackRuntime.

  • A failed cleanup orphaned the staged directory permanently. TemporaryDirectory.cleanup calls self._finalizer.detach() before removing the tree, and _cleanup_cpu_fallback_runtime nulled the reference first under contextlib.suppress. A locked DLL on Windows (the same class of error install_llama_prebuilt.py already defends against) meant no finalizer, no reference and no retry. Failed handles are now held and retried on the next cleanup. Worth knowing what a leak costs: the staged set is 47 files / about 65 MB on Linux Vulkan and 26 files / about 37 MB on Windows, and the hardlinks keep those inodes alive after the next update unlinks the old tree.

Testing. 17814 passed on the studio backend suite with the CI filter, versus 17809 before. The 82 failures are test_diffusion_*, test_transformers_*, test_video_backend, test_vision_cache, test_training_worker_flash_attn, and they are the same 82 on plain main (torch is absent from that env). Frontend npm run typecheck clean and 901/901 on npm test. Ruff and git diff --check clean. No Vulkan hardware here, so all of this is unit level.

Left alone, worth a follow-up:

  • Pre-existing auto-AMD installs still carry llama_backend: "vulkan" and there is no migration. unsloth studio update re-asserts --llama-backend vulkan and UNSLOTH_FORCE_VULKAN, so it rewrites the marker as explicit again. Those are exactly the users this PR is for, and only a fresh installer run with no backend flag unsticks them. Symmetrically, a pre-Studio: support Vulkan GPU selection and explicit Vulkan installation #7188 auto-Intel install is eligible today but gets promoted to explicit "vulkan" on its first update and loses recovery. Promoting to "auto" instead would preserve the bundle and keep recovery.
  • An env-supplied projector (LLAMA_ARG_MMPROJ / LLAMA_ARG_MMPROJ_URL) still lands with has_audio_input=false, because _mmproj_has_audio only ever comes from launch_mmproj_path. Not a regression, the same gap exists on the pre-crash path, but the fallback carries it forward.
  • ggml_backend_load_best also searches the current working directory. Keeping Studio's cwd for the replay is right for relative paths in user extras, but it means a Studio launched from build/bin can still find libggml-vulkan.so and re-enter the crash.
  • There is no startup sweep for llama-cpu-* under the runtime dir, so an abnormal termination still leaves one behind.
  • The GPU library exclusion regex is a denylist covering 9 of the roughly 15 backends upstream probes. Nothing bites today since a Vulkan bundle only ships the Vulkan one, and ggml-rpc registers no devices without --rpc. An allowlist of ^(?:lib)?ggml-(?:base|cpu) plus everything non-ggml- would not need to track upstream.

Nice work on this, the staging approach is the right call given plugins load before --device none is honoured.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Found by simulating the fallback across [Linux, WSL, Windows, macOS] x
[Vulkan, CUDA, HIP, CPU, custom Vulkan+CUDA] x every marker and
environment state.

- A cpu_fallback request on a runtime that is no longer the Vulkan build
  the recovery came from now loads normally instead of failing. Switching
  the managed backend between a recovered load and its rollback would
  otherwise turn a working load into a hard error.
- The drafter replay falls back to the drafterless command when the build
  has no draft-ngl flag to pin one to CPU, so a binary that cannot replay
  the drafter still recovers rather than losing the fallback entirely.
- Adds a platform matrix over the OS and runtime combinations Studio
  ships, marker states old and new (absent, null, auto, vulkan, unknown,
  force_cpu, corrupt), and the two behaviours above.
@danielhanchen

Copy link
Copy Markdown
Member

Simulated this one properly before signing off, since it adds a hardware path and I wanted to be sure nothing that works today changes.

Is the problem real

Yes. Two independent things check out.

The crash itself is well documented upstream: ggml-org/llama.cpp#20201 (Intel 255H Arrow Lake, device enumerates fine and then the driver dumps batch/BO state), #19327 (Arrow Lake-P, larger models), #17389 (Meteor Lake), #10528 (inconsistent Vulkan segfault), #18946 (Intel 258V, load-time device OOM). Same signature in all of them: the model runs fine on CPU.

The mechanism the staging works around also checks out. Backends are dlopen'd at startup, before any device argument is applied, which is why every log shows load_backend: loaded Vulkan backend from ... and ggml_vulkan: Found N Vulkan devices before argv takes effect. --device none cannot save you from a driver that crashes during registration. Removing the plugin from disk (or GGML_BACKEND_PATH) is the accepted workaround, and this PR does the disk version, which is the safer of the two.

Before and after

Before: an affected Intel or AMD user picks a model, Studio auto-selects the managed Vulkan build, llama-server dies on SIGSEGV during startup, and the load fails with a GPU init crash message. The only exit is to reinstall with --llama-backend cpu or set UNSLOTH_LLAMA_CPP_BACKEND=cpu by hand.

After: the same crash is retried once in a staged copy of the same managed runtime with the ggml GPU backend libraries left out and --gpu-layers 0 --fit off --device none appended. If that comes up healthy the model stays loaded, the session is pinned to CPU across reloads and rollbacks, and the UI warns instead of failing. If it also fails, the original failure is reported exactly as before.

Does it touch anything that already works

I simulated the fallback over the full cartesian product rather than reasoning about it: [Linux, WSL, Windows, macOS] x [Vulkan, CUDA, HIP, CPU-only, custom Vulkan+CUDA, unmanaged] x [marker absent, null, "auto", "vulkan", unknown value, force_cpu, no marker file, corrupt marker] x [clean env, UNSLOTH_FORCE_VULKAN, UNSLOTH_LLAMA_CPP_BACKEND in vulkan/cpu/hip], plus crash modes (SIGSEGV, SIGILL, SIGABRT, SIGBUS, SIGFPE, Windows 0xC0000005, ordinary non-zero exit, healthy first try), placement variants (--device, --gpu-layers, --tensor-split, --n-cpu-moe, --main-gpu, --override-tensor), inherited LLAMA_ARG_*, projector and drafter paths, and lifecycle cases (repeated recovery, unload, missing CPU library, read-only runtime root, cross-device link failure, symlinked wrapper binary, unicode and spaces in the path, two backends staging at once, in-place update, locked cleanup).

777 simulated cases. Result:

  • CUDA, HIP and CPU-only installs: not one behaviour change. Recovery never engages, nothing is staged, no new failure mode.
  • macOS: unreachable, as intended. _installed_ggml_backends only recognises .so and .dll, so a .dylib bundle is never seen as Vulkan.
  • Explicit Vulkan, UNSLOTH_FORCE_VULKAN, UNSLOTH_LLAMA_CPP_BACKEND, force_cpu, and every user placement flag: still refuse recovery. No silent downgrade.
  • Custom multi-backend Vulkan+CUDA builds: refuse, consistent with _is_vulkan_backend deferring to CUDA/HIP everywhere else.
  • Old installs: safe. A missing marker file, a pre-Studio: support Vulkan GPU selection and explicit Vulkan installation #7188 marker with no llama_backend key, a corrupt or non-JSON marker, and an unknown future value all resolve without raising. The only old installs that gain recovery are the automatic ones, which is the intent.
  • Only signal crashes replay. An ordinary non-zero exit or a healthy first launch never stages anything.

Two cases did change behaviour in a way I did not want, both from my previous commit, and both are fixed in 62c6203:

  1. A cpu_fallback request on a runtime that is no longer Vulkan turned a working load into a hard error. If the managed backend is switched between a recovered load and its rollback, the rollback still carries cpu_fallback=true. Gating _prepare_cpu_fallback_launch on _is_vulkan_backend made that path raise "The prior Vulkan CPU fallback could not be reconstructed". It now ignores the flag and loads the request as sent.
  2. A build with no draft-ngl flag lost the recovery entirely. Replaying the original drafter command is right, but _cpu_isolated_replay refuses when a draft model cannot be CPU-pinned, so on those builds the fallback returned nothing where it previously recovered drafterless. It now tries the drafter launch first and falls back to the stripped command.

Test results

  • Studio backend suite with the CI filter: 17842 passed, versus 17715 on plain main. The 82 failures are test_diffusion_*, test_transformers_*, test_video_backend, test_vision_cache, test_training_worker_flash_attn, and they are the identical 82 on main (torch absent from that env).
  • The same 777-case simulation run against the pre-fix head of this branch: 24 failures, all of them the issues fixed here. Against the current head: 0.
  • Frontend npm run typecheck, npm test (901/901) and npm run build all clean.
  • Ruff, AST parse and git diff --check clean.

Browsers

No concern. The frontend diff is state and toast logic only: no navigator, window, document, storage, structuredClone, Intl, EventSource or any other host API, and no CSS. It uses nullish coalescing, optional chaining and object spread, all ES2020, and the app already targets ES2022. Chrome, Edge, Firefox and Safari behave identically because nothing browser-specific was introduced.

Still open, not blocking

  • Pre-existing auto-AMD installs carry llama_backend: "vulkan" with no migration, and unsloth studio update re-asserts --llama-backend vulkan and UNSLOTH_FORCE_VULKAN, so it writes the marker back as explicit. Those users stay ineligible unless they rerun the installer with no backend flag. A pre-Studio: support Vulkan GPU selection and explicit Vulkan installation #7188 auto-Intel marker gets promoted to explicit "vulkan" on its first update and loses recovery the same way. Promoting to "auto" instead would preserve the bundle and keep both eligible.
  • An env-supplied projector still reports has_audio_input=false, because _mmproj_has_audio only ever comes from launch_mmproj_path. Not a regression, the same gap exists before the crash.
  • ggml_backend_load_best also searches the current working directory, so a Studio launched from build/bin can still find the Vulkan library. Keeping Studio's cwd is right for relative paths in user extras, but the isolation is not absolute.
  • No startup sweep for llama-cpu-* under the runtime dir, so an abnormal termination still leaves one behind.

Happy with this now. The approach is sound and the blast radius is confined to automatically-selected Vulkan installs.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

- Persist a forced Vulkan install as automatic when the host has no
  HIP-capable AMD GPU. Those boxes route to Vulkan either way, so the
  bundle is identical, but pre-unslothai#8050 installs (whose every update
  re-asserts --llama-backend vulkan) were left permanently ineligible for
  the CPU crash recovery this PR adds. A host that can run HIP keeps its
  explicit choice explicit.
- Stamp the owning pid into each staged runtime and sweep the ones no live
  process holds. A kill -9 or host crash skips TemporaryDirectory's atexit
  hook, and those hardlinked copies pin the old install's inodes after the
  next update unlinks the tree. Runtimes without a stamp, or written by a
  live process, are left alone.
- Probe an LLAMA_ARG_MMPROJ projector for audio support. It never reaches
  launch_mmproj_path, so an audio-capable env projector reported as
  text-only. Never probes one the unpinnable-projector guard dropped.
@danielhanchen

Copy link
Copy Markdown
Member

Closed the three follow-ups I had left open. fcd9b22.

Pre-#8050 auto-AMD installs can now recover. This was the one that mattered. The PR correctly persists "auto" for the automatic Windows AMD no-HIP route going forward, but every install that already exists carries "vulkan", and unsloth studio update re-asserts --llama-backend vulkan plus UNSLOTH_FORCE_VULKAN, so the marker gets rewritten explicit on every update and those users stay permanently ineligible. They are exactly the users this PR is for.

_route_to_vulkan_prebuilt now persists "auto" on a forced Vulkan run when the host has no HIP-capable AMD GPU. That host routes to Vulkan automatically anyway, so the installed bundle is byte-identical either way and only the recorded provenance changes. A host that can run HIP keeps its explicit choice explicit, and the existing masked-host test still asserts persist == "vulkan".

Abandoned staged runtimes are collected. Each staged runtime now carries an UNSLOTH_OWNER_PID stamp, and the next stage sweeps any whose owner is no longer alive. A kill -9, an OOM-kill or a host crash skips TemporaryDirectory's atexit hook, and those hardlinked copies pin the old install's inodes once the next update unlinks the tree, so they cost real disk that du on the install root does not show. A runtime with no stamp (written by an older Studio) or one held by a live process is left alone, so two Studios sharing a home do not delete each other's work. Liveness uses os.kill(pid, 0) on POSIX and OpenProcess on Windows, the same shape as hub/utils/download_registry.py, and treats pid 0 or negative as dead since those address process groups.

An env-supplied projector reports its audio support. _mmproj_has_audio only ever came from launch_mmproj_path, so an audio-capable projector passed through LLAMA_ARG_MMPROJ reported as text-only and the frontend hid audio upload. It now probes that path too. It deliberately does not probe one the unpinnable-projector guard just dropped, which is what test_the_drop_precedes_everything_the_projector_feeds protects; I updated that test to assert the ordering against the new variable rather than the literal argument, so the invariant is still enforced.

Testing. 17846 passed on the studio backend suite with the CI filter. The 82 failures are byte-identical to plain main (torch absent from that env), verified by diffing the two failure lists.

Two things I caught and fixed before pushing, worth noting since they are easy to miss:

  • The pid stamp initially used write_text / read_text with no encoding, which test_text_io_encoding.py correctly rejects.
  • The first version of the audio probe used launch_mmproj_path or os.environ.get(...), which would have re-probed a projector the Metal paravirtual guard had deliberately cleared. test_the_drop_precedes_everything_the_projector_feeds caught it.

Also re-ran the platform simulation from my previous comment against this state, extended with the sweep cases (dead owner, unreadable stamp, no stamp, live sibling, a plain file sharing the llama-cpu- prefix): 784 cases, all green, and no change to the CUDA, HIP, CPU-only or macOS paths.

Nothing else outstanding from my side. Remaining known gaps, none blocking: a pre-#7188 markerless auto-Intel install is still promoted to explicit "vulkan" on its first update (the comment at llama_cpp_update.py:614 documents why, and promoting to "auto" instead would keep it eligible), and ggml_backend_load_best still searches the current working directory, so a Studio launched from build/bin could find the Vulkan library despite the staging.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 8, 2026 08:40
Windows pins --threads 2 and PASSIVE OpenMP when the plan offloads
everything to the GPU. The replay is that premise falsified, so a recovered
session decoded on two cores no matter how many the host has. It now drops
both alongside the placement flags, and only ever the values Unsloth
injected: the caller reports whether the user set their own --threads.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 4bf6f1de11

ℹ️ 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 +2780 to +2785
if remembered and not _active_rocm_gfx_target(host):
return dataclasses_replace(
host,
has_rocm = True,
rocm_gfx_target = remembered,
rocm_gfx_targets = list(dict.fromkeys([*_host_rocm_gfx_targets(host), remembered])),

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 Ignore remembered ROCm arch after the AMD GPU is removed

When an automatic AMD/Vulkan install is updated after its AMD GPU has been removed, the fresh host probe has neither an active ROCm target nor has_rocm, but this branch restores the stale marker value and unconditionally sets has_rocm=True. The routing logic then treats the nonexistent below-floor AMD device as present and selects Vulkan again instead of moving the now CPU-only host to the CPU bundle, potentially leaving subsequent model loads dependent on a Vulkan backend with no adapter. Only apply the remembered target when the current host still provides independent evidence of an AMD GPU.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Leaving this one. The two hosts are not distinguishable here: HostInfo carries no AMD evidence other than has_rocm and the gfx list, and on Windows both are set only when hipinfo or amd-smi resolves. A driver-only AMD box whose probe stopped resolving looks exactly like a box whose card was removed, so requiring independent evidence would drop the remembered arch on precisely the host it was added for, sending a below-floor AMD card to a bundle it cannot run. The removed-card side is already bounded: _should_auto_vulkan_for_amd_windows refuses the route when has_physical_nvidia is set, so a replacement NVIDIA card wins, and a Vulkan runtime with no adapter reports zero devices rather than mis-selecting one. Between a wrong bundle on a real GPU and a Vulkan bundle on a host that has nothing to accelerate anyway, the current bias is the right one.

…ai#8050

Three gaps in the recovery path:

- MSVC turns GGML_ASSERT into a CRT abort (exit 3) rather than a signal, so
  a Vulkan runtime that asserted during device init on Windows took the
  terminal path while the POSIX SIGABRT recovered. The gate now accepts the
  abort status too, on win32 only: exit 3 is an ordinary failure elsewhere.
- Staging the runtime copies a whole directory, so /unload can land after the
  cancel check and before the spawn, with nothing registered yet for
  unload_model() to remove. The replay rechecks and hands the runtime back.
- TemporaryDirectory registers its exit hook after this backend's, so it runs
  first and cannot delete a runtime whose server is still holding the files
  open. The exit handler retries the removal after the kill.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@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: b4f95f410b

ℹ️ 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 738413a into unslothai:main Aug 8, 2026
77 of 79 checks passed
danielhanchen added a commit that referenced this pull request Aug 8, 2026
…8183)

#8050 gave showAutoLoadSuccess a CPU-fallback description, so the literal
`description: undefined` this asserted became a ternary and the contract went red
on main while the behaviour it guards was unchanged.

Assert the branch and its undefined arm instead: an ordinary auto-load still
carries no description, and a Vulkan-crash fallback still explains itself.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 25, 2026
…r has no device (unslothai#14521)

## Summary

On a Windows PC whose only GPU is an older Intel iGPU (reported on an
i7-6700T with Intel HD Graphics 530), Studio and Desktop install the
Vulkan llama.cpp build automatically. Loading a small GGUF
(DeepSeek-R1-Distill-Qwen-1.5B UD-IQ1_S) then sat on "Loading a
model..." for over 30 minutes and never finished. Settings > System
showed `VULKAN` with "No visible GPU", and the Compute backend picker
was blank.

GGUF chat should always work on such a machine, since the Vulkan build
also carries the llama.cpp CPU backend. This PR makes it fall back to
CPU instead of waiting forever.

## Root cause

1. Starting the Vulkan bundle loads `ggml-vulkan` and initialises the
driver even with `-ngl 0` or `--device none` (see unslothai#7213). A driver stuck
in device init or shader compilation never makes llama-server healthy.
2. The startup wait renews its 600 s stall deadline on any CPU activity,
memory growth or page faults. A spinning driver produces all three, so
the wait never ends. When it did end, the retry rungs relaunched the
same Vulkan child into the same hang.
3. The existing CPU recovery (unslothai#8050: stage the bundle without GPU
libraries, `--device none -ngl 0 --fit off`) only runs after a signal
crash, never after a hang.
4. The Compute backend picker renders blank while `/api/llama/backend`
is still resolving, because the selected value has no item yet.

## What changes

All of this applies only to a managed, auto-selected Vulkan bundle with
automatic placement, i.e. the same gate the existing crash recovery
uses. A Vulkan backend picked in Settings or by
`UNSLOTH_LLAMA_CPP_BACKEND`, a custom llama.cpp folder, explicit
`gpu_ids`, layer counts or tensor splits all keep today's behaviour, as
do CUDA, ROCm, Metal and CPU builds.

The rule throughout: a GPU that might work is never moved to CPU on a
guess. Only a probe that proves there is no device, or a driver that
cannot even enumerate and then does no loading work at all, sends a load
to CPU.

- **Zero Vulkan devices:** when the existing per-load Vulkan probe
completes and lists no device, the load starts directly on the staged
CPU runtime (`cpu_fallback_reason = "vulkan_no_device"`).
- **Probe timed out or faulted:** treated as suspect, not as proof. A
healthy discrete GPU on a busy multi-GPU host can take 20 to 40 s to
answer the 15 s probe, and a driver can fault on exit after listing a
working device. Those launches stay on Vulkan, with a 300 s stall window
instead of 600 s.
- **A Vulkan launch that hangs:** CPU time no longer renews the wait for
these launches (a spinning driver burns CPU forever), and a ceiling
bounds the whole wait: max(stall window, 60 s per GiB of model) after a
timed-out or faulted probe, and three times that (max(1800 s, 180 s per
GiB)) after a probe that listed a device, since that stall only ever
ends with advice and a slow disk or a first shader compile must not trip
it. What happens next depends on the evidence:
- The probe timed out or faulted, and the child did no loading work
(RSS, bytes read, page faults) for the whole window: the load replays
once on the staged CPU runtime before any other retry
(`cpu_fallback_reason = "vulkan_startup_stall"`). If that replay also
fails, the load fails with the classified error, the same as the crash
replay.
- The probe listed a device, or the child was still loading when the
ceiling hit: no CPU replay. The load fails with an error that suggests
choosing CPU in Settings > GGUF inference engine, instead of relaunching
the same driver into the same hang.
- The text-only retry after a projector failure gets the same bounded
wait.
- **Nothing is remembered across loads:** every load re-probes, so one
bad start (a busy disk, a driver that recovered) never pins a build to
CPU for the rest of the session.
- **API and UI:** `cpu_fallback_reason` accepts the two new values. The
chat load notice says the model runs on CPU and why, using the same flow
as the crash recovery.
- **Settings picker:** shows `Loading...` until the status arrives (or
`Unknown` next to the error if it fails), and keeps the current
selection visible when no options resolved, instead of a blank box. No
new i18n keys.

## Testing

A Linux end-to-end harness runs the upstream `b11795` ubuntu-vulkan
bundle as a managed auto-selected install and calls
`LlamaCppBackend.load_model` directly. An `LD_PRELOAD` shim makes
`vkEnumeratePhysicalDevices` spin forever, optionally allocating 2
MiB/s, to mimic the stuck driver. The harness stall window is 60 s on
both sides. The timings were measured on the first revision of this PR;
the last column is what the current rule does, and the two rows marked *
changed with it (covered by the unit tests below, not re-timed).

| Scenario | main | first revision | this PR now |
|---|---|---|---|
| Driver hangs everywhere (probe times out) | never healthy at the 400 s
cap | healthy on the CPU runtime in 93 s, chat OK | same: CPU runtime,
chat OK |
| Same, driver also allocates while stuck | never healthy at the 300 s
cap | healthy on the CPU runtime in 93 s, chat OK | * fails at the
ceiling with the Settings advice (allocation counts as loading work) |
| Probe lists an iGPU, llama-server hangs | never healthy | healthy on
the CPU runtime in 63 s, chat OK | * fails after the stall window with
the Settings advice |
| Reported model, DeepSeek-R1-Distill-Qwen-1.5B UD-IQ1_S, driver hangs |
never healthy | healthy on the CPU runtime in 94 s, chat OK | same: CPU
runtime, chat OK |
| No Vulkan ICD (probe aborts, llama.cpp falls back to CPU itself) | 2.3
s, chat OK | 1.3 s, unchanged path, chat OK | unchanged |
| Working NVIDIA Vulkan device | 31/31 layers on Vulkan0 | 31/31 layers
on Vulkan0, no fallback, one launch | unchanged |
| Vulkan chosen explicitly, driver hangs | never healthy | unchanged,
never healthy (by design) | unchanged |

With the shipped defaults a driver that cannot enumerate reaches CPU
after the 15 s probe plus 300 s of no loading work. The zero-device
route (probe completes and lists nothing) is covered by unit tests; on
this host a missing ICD makes the probe abort instead, which keeps
today's behaviour.

Unit tests:

- `tests/test_vulkan_no_device_cpu_route.py` (new, 40 tests): probe
outcome classification; the route taken only for zero devices; no route
for a listed device, timeout, fault, error, user-chosen Vulkan or
explicit placement; a stall replays on CPU only after a timed-out or
faulted probe with no loading work; a stall after a listed device, or a
child cut off by the ceiling while loading, fails with the Settings
advice and spawns nothing else; a recovered stall is not remembered (the
next load launches Vulkan); the health wait tells "no progress" from
"ceiling" (including a ceiling no longer than the window); a slow but
loading child comes up on its device; the bounded text-only projector
retry; the terminal stall replay; cancellation. 13 of them fail against
the previous revision of this branch.
- Related suites `test_gpu_init_crash_message.py`,
`test_llama_cpp_wait_for_health.py`, `test_llama_cpp_vulkan_probe.py`,
`test_gguf_load_cache_reuse.py`, `test_llama_cpp_placement.py`: 850
passed here; main fails the same 5 placement test IDs (no `gguf` module
in this environment, drafter tests) and nothing else.
- Frontend: the payload, partial-offload, gpu-placement and
mmproj-fallback tests (61) pass, and `npm run typecheck` is clean. The
startup bundle grows by 737 B raw / 288 B transfer over main (measured,
budget raised by that).

Not covered here: real Windows hardware with an Intel Gen9 driver. The
Windows exit-code classification is covered by unit tests only.

## Screenshots

Settings > System > GGUF inference engine, merge base vs this PR,
Chromium.

While `/api/llama/backend` is still answering (held open in the browser,
the resolver can take up to 60 s on a slow host): the picker was blank,
the state from the original report. It now reads `Loading...`.

![Compute backend picker while the status request is pending, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14521/pr14521_pair_00-68aa443a2c01.png)

When the status resolves with no options (here
`UNSLOTH_DISABLE_UPDATE_CHECK=1`), the picker was blank. It now shows
the current selection, `Automatic (CUDA)` on this host.

![Compute backend picker with no resolved options, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14521/pr14521_pair_01-bd46ae9b08c6.png)



Re-checked on the final head `441552d72` against merge base `c9fab474c`
(Settings > System, Chromium, the Studio UI regression run): the Compute
backend picker that rendered blank now shows the current selection.

![Compute backend picker on the final head, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14521/pr14521_system_tab_441552d72-eb8e0221db58.png)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

2 participants