Skip to content

Studio: run native image generation on Vulkan when torch is CPU-only on an AMD or Arc GPU - #13697

Merged
danielhanchen merged 21 commits into
mainfrom
r6/sd-cpp-vulkan-cpu-torch
Oct 14, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
r6/sd-cpp-vulkan-cpu-torch

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Fixes #13666

Problem

When torch on a host is CPU-only, the native image engine (stable-diffusion.cpp) always installs and runs the CPU build, even when a GPU that Vulkan can drive is present:

  • resolve_diffusion_device_target() returns backend cpu.
  • _INSTALL_ACCELERATOR has no cpu entry, so _install_accelerator_for("cpu") gives auto.
  • The installer reads auto as the plain CPU build.

This hits:

  • AMD cards that get no ROCm torch wheel on purpose: Vega gfx900, RDNA 1 gfx101x and Polaris gfx803 on Linux.
  • Any Windows AMD card on CPU torch.
  • An Intel Arc whose XPU wheel was replaced by a CPU one.

On those same hosts llama.cpp already runs on Vulkan, and so does audio.cpp since #13298. Lemonade also allows its Vulkan sd.cpp build on any AMD GPU.

Fix

Routing. image_install_accelerator() returns vulkan for backend cpu when _vulkan_gpu_for_cpu_torch() holds. Unpinned sd.cpp renders on the first Vulkan device it finds, so the route is only taken when that device is known to be the AMD or Arc card:

  • Platform: Linux x86_64 or Windows x64, the only platforms the pinned release ships -vulkan bundles for.
  • Cards: the inventory lists an AMD card or an Intel Arc, and both the inventory and the NVIDIA probe answered.
  • Linux render nodes: an openable node of any other or unreadable vendor keeps the CPU build.
  • No NVIDIA anywhere. That covers nvidia-smi, a sysfs 0x10de device (Nouveau, or no proprietary driver), and on Windows the DirectX adapter registry, corroborated by the live adapter scan.
  • No UHD iGPU Vulkan could see, and on Linux no render node from another vendor (virtio-gpu, VMware).
  • Linux: only cards whose /dev/dri render node this process can open count, so a container that mounts only the AMD node still qualifies.
  • Masks: a mask for the card's own vendor keeps the CPU build, because Vulkan reads none of them. CUDA (which HIP also honours), HIP and ROCR cover AMD; ZE_AFFINITY_MASK covers Intel. GGML_VK_VISIBLE_DEVICES must be a list of ordinals.
  • Driver and loader: a hardware ICD for one of those vendors is loadable (RADV as radeon_icd or radv_icd, AMDVLK, Adrenalin, ANV), and libvulkan.so.1 / vulkan-1.dll opens.

Selection, native_binary_installed and _resolved_accelerator all call image_install_accelerator, so they agree. Video keeps its own ladder.

Fallback. _ACCELERATOR_FALLBACK gains vulkan -> cpu, and preferred_accelerator walks the whole ladder. Decisive Vulkan failures (ErrorIncompatibleDriver, ErrorDeviceLost, VK_ERROR_INITIALIZATION_FAILED) are recorded, so the next load starts on the CPU build rather than dropping to diffusers. A server start that fails this way drops a cached sd-cli from the failed build.

Placement. The load records where the running build actually renders. It reads the install record, or an unowned binary's own --list-devices, and is recomputed after the deferred upgrade and after every server-to-one-shot fallback. A CUDA load that starts on the resident CPU bundle keeps the card the route selected. Auto memory mode offloads on Vulkan, because torch never measured that card.

GPU arbiter. /images/load takes the DIFFUSION claim for this route and for a retained managed Vulkan build, including one behind an unowned SD_SERVER_PATH. After selection the claim follows the binaries that will actually run: when every one is a managed CPU install (a recorded Vulkan failure, a failed Vulkan install that kept the CPU bundle, a CPU diffusers fallback, or a GPU torch whose GPU builds all failed), no claim is taken, so a CPU-only image load does not evict a GPU model.

Overrides that still take precedence:

  • UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK=0 turns the route off.
  • UNSLOTH_DIFFUSION_SD_CPP_DEVICE, UNSLOTH_DIFFUSION_SD_CPP=0 and UNSLOTH_DIFFUSION_ENGINE keep their meaning.

Results on a real Radeon (gfx1151, Radeon 8060S, CPU torch 2.14.1+cpu)

SD-Turbo q8_0, 512x512, 8 steps, three one-shot runs per state:

before after
Linux build CPU (bin-Linux-Ubuntu-22.04-x86_64.zip) Vulkan, Vulkan0: AMD Radeon Graphics (RADV GFX1151)
Linux time per image (median) 19.64 s 3.80 s
Windows build CPU (bin-win-cpu-x64.zip) Vulkan, AMD Radeon(TM) 8060S Graphics
Windows time per image (median) 19.79 s 3.79 s

Repeat spread is under 0.5 s on every arm. The first Vulkan run in a process takes longer while it builds its pipelines: 4.35 s on Linux and 6.63 s on Windows.

Tests

  • New test_sd_cpp_vulkan_cpu_torch.py, 65 cases:
    • the host matrix;
    • NVIDIA via sysfs and the Windows registry;
    • UHD with and without a reachable node;
    • other-vendor render nodes;
    • per-vendor masks;
    • ICD naming and vendor matching;
    • Windows driver filters;
    • unsupported platforms, GPU torch and video unchanged;
    • the fallback ladder;
    • the pinned release's real asset names.
  • test_sd_cpp_backend.py:
    • placement for Vulkan, CPU and unowned builds;
    • the deferred upgrade keeping the selected card;
    • the cached sd-cli after a server failure;
    • the arbiter preflight.
  • test_diffusion_routes.py: the arbiter claim for the route, for a retained Vulkan build, and after a recorded failure.
  • 21 related router, sd.cpp and video test files: 1939 passed / 0 failed on the merge base, 2023 passed / 0 failed here, also on a merge with current main. The new file errors on all 65 cases against merge-base code.
  • Staging:
    • ubuntu-latest and macos-15 are green.
    • windows-latest has 611 passed / 4 failed. The 4 failures are existing compile-gated tests in test_diffusion_routes.py that fail without Triton. They fail the same way on the merge base with compile disabled.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-14T16:13:36.077244Z f548b0e Manual request
🔒 Security Review ⚠️ Failed 2026-10-14T09:10:58.190040Z f586402 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.

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ip UHD-first and unmounted render nodes, walk the whole fallback ladder
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits October 14, 2026 10:42
…K bypass on mixed hosts; place for the running build after every fallback; arbiter follows the preferred build
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 772828feea

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

getattr(fallback, "binary", None)
)
mode = "oneshot"
device, offload = _placement(*_running())

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 Release the claim after a live Vulkan-to-CPU fallback

When a CPU-torch Vulkan server starts under an acquired DIFFUSION claim and fails with a decisive marker such as ErrorIncompatibleDriver, _resolve_engine() can select the CPU CLI and this line correctly changes placement to CPU. The route has already returned from begin_load, however, and nothing releases the claim after the worker commits that CPU state, so subsequent chat/video loads unnecessarily unload the usable CPU image model; reconcile arbiter ownership when this fallback commits.

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.

Leaving this one. The failure that triggers the in-load fallback is recorded, so the next load already starts on the CPU build without the claim (test_cpu_torch_load_after_a_failed_vulkan_build_skips_arbiter). In the current load the claim errs on the safe side: it can evict another GPU model unnecessarily, but it never lets two processes share the card. Releasing it from the worker after commit means reconciling arbiter ownership off the route's thread, which is more machinery than one load's worth of over-claiming justifies.

… filters, arbiter for a retained Vulkan build
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7643bf9410

ℹ️ 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 +3203 to +3204
vulkan = torch_device == "cpu" and off_torch is None and klass == "vulkan"
placed = "vulkan" if vulkan else torch_device

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 Honor every GPU class reported by custom binaries

When SD_SERVER_PATH or SD_CLI_PATH selects an unowned CUDA or ROCm build on a CPU-only torch installation, sd_cpp_listed_device() correctly returns that GPU class, but only klass == "vulkan" changes placed away from torch_device == "cpu". The load is consequently reported as CPU and returns no offload flags, so even an explicit low_vram or balanced request is discarded while the binary actually renders on the GPU, which can cause large models to exhaust VRAM. Treat every probed GPU backend as off-CPU placement rather than special-casing Vulkan.

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.

Leaving this one out of this PR. An unowned CUDA or ROCm build under a CPU-only torch is placed as cpu on main today, and that is unchanged here. This PR only adds the Vulkan route a CPU torch is now sent to (#13666), and placement only had to follow that build. Labelling a ROCm / CUDA build run under CPU torch also needs a device name the rest of the load path and status handle; ROCm loads are reported as cuda there today. That is a separate change, so I'd rather do it in its own PR than widen this one.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…nd driver of one vendor, server failure drops a cached sd-cli of the failed build
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dec66091b4

ℹ️ 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 4012 to +4014
fallback = fallback_accelerator_for(accelerator)
if fallback:
# The CPU rung is the branch below, which also releases the GPU placement.
if fallback and fallback != "cpu":

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 Record a failed Vulkan probe before taking the CPU rung

When the requested Vulkan build is successfully installed but its device probe fails, this condition skips the only block that records the failing accelerator because its fallback is now cpu; the generic branch below installs CPU but never calls note_accelerator_runtime_failure. Consequently an XPU video host repeats the Vulkan install/probe followed by a CPU replacement on every load instead of eventually making preferred_accelerator("vulkan") select CPU directly.

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.

Leaving this as is. On main, _ACCELERATOR_FALLBACK has no Vulkan entry, so a failed Vulkan video probe never recorded anything and the generic CPU branch ran on every load. That is exactly the behaviour this guard restores. Recording a Vulkan failure from the video path would also start steering image loads (the record is shared), which is a separate change from the image route this PR adds.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

This comment was marked as resolved.

…CPU, claim re-settled on the activated engine, neutral fallback hint
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…the claim follows the binaries selection installed
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f548b0e166

ℹ️ 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 81cfe76 into main Oct 14, 2026
@danielhanchen
danielhanchen deleted the r6/sd-cpp-vulkan-cpu-torch branch October 14, 2026 16:33
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…Vulkan; a UHD iGPU beside a card no longer vetoes Vulkan (unslothai#14610)

## Summary
Follow-up to unslothai#13697 from a post-merge review. unslothai#13697 added a Vulkan to
CPU step to the native image engine's fallback ladder for every host,
and counted Vulkan "device lost" errors as strikes. Two transient
device-lost faults therefore moved Intel Arc hosts (whose image build is
always Vulkan) and ROCm hosts already on their Vulkan fallback to the
CPU sd.cpp build, and the record persisted across restarts. The Vulkan
spec treats a lost device as recoverable by recreating it (Windows TDR
and amdgpu recovery reset it routinely), so it is not proof the build
cannot run.

## What changes
- **Device lost is not a build failure** on any host.
- **Records written under the old rule** (`rule: 2` now) keep only their
decisive evidence, so old device-lost strikes stop diverting to CPU.
- **Scope of the Vulkan to CPU step:** ambiguous failures move only a
CPU-torch host (the route unslothai#13697 added the step for) to CPU sd.cpp. XPU
hosts and ROCm hosts on their Vulkan fallback leave Vulkan only on a
decisive failure, such as an incompatible driver, so a provably
unrunnable build still never leaves them without an image engine.
- **A UHD iGPU beside an AMD card or an Arc no longer vetoes the Vulkan
route.** The pinned sd.cpp (master-982) picks a discrete GPU before an
iGPU (`get_default_backend_name`). A UHD iGPU alone, or a
`GGML_VK_VISIBLE_DEVICES` list (whose ordinals may name the iGPU), keeps
today's answer. `GGML_VK_VISIBLE_DEVICES` separated by spaces is
accepted, as ggml reads it.
- **One `--list-devices` cache** for the five readers that only need the
listing, keyed by binary path, size, mtime and the device-selection
environment (the Vulkan list, ICD variables and CUDA/HIP/ROCR masks).
Timeouts and unreadable answers are never cached. The accelerator
verdict still probes afresh, since a load's re-check relies on seeing a
changed listing, and it refreshes the cache.

## Tests
`tests/test_sd_cpp_vulkan_cpu_torch.py`: two lost devices keep Vulkan
(CPU torch and GPU torch); ambiguous strikes move only the CPU-torch
host while decisive evidence moves every host; an old ambiguous record
is ignored and an old proven one holds; UHD + Vega routes to Vulkan
(also with both render nodes mounted); a space-separated mask is
accepted; three listing reads cost one probe and an environment change
re-probes; an unreadable listing is not cached. On main exactly the 10
new or updated tests fail. Related suites (diffusion routes, sd.cpp
backend, VRAM budget, ROCm Vulkan fallback, H3 matrix, native GPU
decision): 1003 passed on this branch.

Not run on real Arc, ROCm-Vulkan or UHD + discrete hardware.



**Repeated device loss.** A host that loses the Vulkan device on every
render (for example a Windows TDR on a slow iGPU) no longer fails every
request after the single respawn. If the respawned sd-server loses the
device too in the same request, that load moves to the CPU backend
(`--backend cpu`, same checkpoint, slower) with a warning in the log,
and later requests on that load stay there. Nothing is persisted: no
strike, no failure record, so the next load resolves and tries the
Vulkan build again. This only happens where the Vulkan-to-CPU rung
already applied, which is the CPU-torch host routed to Vulkan with
`UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK` left on. A GPU the user
picked (a `gpu_ids` pool or `UNSLOTH_DIFFUSION_SD_CPP_DEVICE`) is never
moved to CPU, and Arc / ROCm hosts keep Vulkan. In those cases the
second loss returns the original error plus a hint (Low VRAM mode, a
smaller resolution or quant, or reload to retry on the GPU), and the
hint text matches no failure marker, so it records no strike either. A
single loss still respawns once on the same device with its pin and
LoRAs, as before.

---------

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.

[Feature] Vulkan fallback for ROCm-unsupported AMD cards in stable-diffusion.cpp

1 participant