Repository navigation
studio: honour the gpu selection for image and video loads - #8645
Conversation
The GPU picker was wired into the chat runtime and training only. Neither /images/load nor /video/load carried gpu_ids at all, so both engines placed every module on ordinal 0 whatever the user selected. On a mixed box that is frequently the smaller card, and for a checkpoint that only fits on the larger one it decides whether the load runs at all. Both request models, both routes and both begin_load chains now take gpu_ids, matching the LLM path. Neither engine shards a diffusion checkpoint -- diffusers places whole components and sd.cpp assigns whole modules per backend device -- so a selection of several cards resolves to one, and the most free VRAM wins, the rule auto_select_gpu_ids already applies to training. Picking the first id would land back on ordinal 0 whenever a user selects everything, which is the case this exists to serve. An index this host does not have is refused at the route, before the arbiter evicts chat. For diffusers the index is a new DiffusionDeviceTarget field rather than part of device. The memory, speed, attention and engine-routing policies all compare that string by value against "cuda", so folding the index into it would make every one of them take its non-CUDA branch and load the model with those optimisations silently disabled. Placement reads the new torch_device; the policies keep reading device. The pin itself is torch.cuda.set_device, applied where the target is built: it is thread-local, and the load, generate, ControlNet and re-activation paths each resolve on their own thread. It is also the lever that moves the offload budget, since diffusion_memory reads mem_get_info() for the current device, so the weights and the budget they are sized against stay on the same card. The capability probe is asked of the selected card too, or a mixed-generation box picks its dtype from the wrong GPU. For sd.cpp the selection becomes --backend diffusion=CUDA<n>,te=<n>,vae=<n>, built after the offload policy so --clip-on-cpu / --vae-on-cpu keep those modules on the CPU: they are the deprecated spellings of te=cpu / vae=cpu, and the parser is last-wins, so pinning over them would undo low_vram. Device names come from the load's own binary via --list-devices, and only CUDA / ROCm names are matched, since Vulkan ordinals are a separate namespace with no defined mapping to a physical index. The image and video Advanced panels gain a GPU control, shown only where there is more than one pinnable CUDA / ROCm device. A pick whose card has since disappeared falls back to automatic rather than sending an index the backend would refuse. Part of unslothai#8636.
e73965d to
d1c4281
Compare
The name was only re-exported from gpu-selection, not imported, so useDiffusionGpuChoices failed the frontend build with TS2552.
The first cut resolved lazily from a candidate list, in the wrong id space, and pinned too
late. Each of those is a separate way to end up on the wrong card.
Physical ids now go through the hardware layer that owns the visibility mask.
resolve_requested_gpu_ids validates against the parent-visible set and get_parent_visible_gpu_ids
gives the order torch enumerates, so a physical id maps to its position in that list. Comparing
against torch.cuda.device_count() was wrong twice over: under CUDA_VISIBLE_DEVICES=4,5 it rejects
both valid picks, and under a reordered mask like 1,0 it accepts a pick that targets the other
card. Free VRAM is read on the translated ordinal for the same reason.
The winner is decided once, in begin_load, and carried to the worker as gpu_ordinal. Re-deriving
it per target meant the ranking changed the moment the checkpoint landed: the load picked the
emptiest card, filled it, and a generate-time resolution then moved the current device to a
different GPU while the pipeline stayed put. The resolved ordinal is committed onto _LoadState
with the pipeline, so a load in flight no longer moves the resident model's card, and a load that
fails before teardown leaves it alone.
Every worker that touches a loaded pipeline now pins through _state_device_target before it
builds any device object. torch.cuda.set_device is thread-local, so the load thread's pin did
nothing for the generate thread: image generation placed a freshly downloaded ControlNet with
state.device ("cuda", un-indexed) before the late pin, landing it on a different card than the
base pipeline, and the video generate worker never resolved a target at all, so its H3 memory
probe and every torch.Generator resolved against its own default device.
The precision gate runs against the selected card. assert_precision_available was reached before
the selection was known, so on heterogeneous GPUs it judged an explicit quantization scheme
against the default card: a valid Ampere-or-newer pick could be refused because GPU 0 is older,
or an unsupported one could pass preflight and fail only after eviction.
The sd.cpp --backend pin is built where the flags are handed to a binary, not once up front. A
deferred accelerator install, the post-download re-resolve, and a server start that falls back to
one-shot can all replace the build after the offload policy is computed, and the ggml device
names come from whichever one actually runs.
Both routes only validate a selection on a CUDA or ROCm target. Physical ids have no applicator
on XPU, MPS or CPU, and the request contract says to ignore them there, so validating turned a
documented no-op into a 400.
|
All eight items were reproducible against head and are fixed in b795cab. Three of them shared a root cause, so this is a rework of the selection path rather than eight patches. The first cut resolved the card lazily from a candidate list, in the wrong id space, and pinned the thread too late. Each of those is an independent way to end up on the wrong GPU. Id space. Physical ids now go through the layer that owns the visibility mask: Resolved once. The winner is decided in Pinned per worker. Every path that touches a loaded pipeline goes through Precision gate runs against the selected card, and the sd.cpp Routes validate a selection only on a CUDA or ROCm target, matching the field contract rather than turning a documented no-op into a 400. Also in this branch: 12f0f13 fixes a frontend build break of my own ( Tests: focused files pass with no regression against |
The rework carried the resolved ordinal inside begin_load, but three decisions upstream of it still read the default card. Both routes now resolve the selection once, through a shared _selected_gpu_ordinal that only runs the CUDA resolver when the target reports a CUDA device, and pass the ordinal into every assert_precision_available and assert_video_precision_available call, including the download-plan preflights and the engine-switch re-check. Judging an explicit quantization scheme against the default card refuses a pick the selected card supports, or passes one it cannot and fails after eviction. The video load route also resolves the ordinal before its precision gate rather than after it. The MiniMax-H3 auto denoiser planner takes the ordinal too. It picks the file set and the memory policy from device capacity, so against the wrong card it either chooses the pinned hosted INT8 denoiser without the dense fallback the destination cannot do without, or stages roughly 66 GB of dense shards nothing opens. The Advanced GPU control reads the torch inventory rather than the inference-backend-selected list. On a host running a Vulkan llama.cpp build for chat with CUDA torch for diffusers, the Vulkan branch returned entries marked diffusionPinnable false, so the control never appeared even though the image and video routes honour those physical ids. The two runtimes are independent, so the diffusion picker asks torch.
|
Round 2, all three fixed in 06d97c2. The rework carried the resolved ordinal inside Both routes resolve the selection once through a shared The H3 auto denoiser planner takes the ordinal from the kwargs the load already carries, so its file set and memory policy describe the destination card. The Advanced GPU control reads the torch inventory. The Vulkan branch was returning entries marked Focused tests pass with no regression against upstream/main; ruff and |
Resolving a target with an ordinal is not the same as making that card current, and several probes read the current device rather than the target. The pin is now scoped where it has to be. Route preflights run on the asyncio.to_thread executor, whose threads are reused, so an unrestored torch.cuda.set_device left this request's card current for the next one, including an automatic load with no selection at all. diffusion_device_scope restores the previous device, and both precision preflights use it around their probes, which reach argument-less CUDA calls and bare "cuda" allocations. _resolve_device_target no longer pins as a side effect: the dedicated load and generate workers take the permanent pin explicitly. The ROCm dtype probe asks about the selected card. is_bf16_supported() takes no device argument, so the only way to ask is to make that card current for the call; without it a bf16-capable pick behind an older default was promoted to fp32, and the reverse attempted bf16 on a card that cannot run it. The route hands its ranked ordinal to begin_load instead of the raw list. Both were ranking from live free VRAM, with the network preflight, engine activation and arbiter eviction in between, so a scheme could be approved against one card and the checkpoint placed on another. Prefetch and plan decisions read the selection too: the dense-quant probe and the pre-cast text-encoder resolver take it from the load kwargs, the H3 auto denoiser planner takes it on the download-plan path as well as the load path, and both plan routes pass it through. These size the file set from device capacity, so against the wrong card they stage tens of GB the selected card would replace, or omit what it needs and force an inline fallback after eviction. The image and video plan requests send gpu_ids. Staging precedes loading, so a plan asked without the pick was preflighted against the default card and could refuse a precision the selected card supports before the correctly pinned load was ever reached.
|
Round 3, all seven fixed in 17b0f5e. Same theme one layer deeper: resolving a target with an ordinal is not the same as making that card current, and the ordinal was not reaching every decision. Pin scoping. The sharpest one. Route preflights run on the ROCm dtype. Confirmed against the installed torch that Route to loader. Plan and prefetch. The dense-quant probe and the pre-cast encoder resolver take the ordinal, the H3 planner reads it on the plan path too, both plan routes pass it, and the image and video plan requests now send New tests cover the scope restoring and the ROCm probe asking about the selected card. Focused tests match upstream/main exactly; ruff and |
… refusals Two of these were regressions from the previous commit. The route passes gpu_ordinal to whichever engine it activated, but the native sd.cpp backend still accepted only gpu_ids, so every native GGUF image load raised an unexpected-keyword TypeError before the background load started and the route answered 500. It takes the resolved ordinal now, and stops re-ranking the raw list for itself. diffusion_device_scope caught around its own yield, so an exception raised by the body was swallowed and the generator yielded a second time, which contextlib turns into "generator did not stop after throw()". An explicit-precision refusal reached the route as that instead of its real message. Only entering the context is guarded now, and the body's exceptions travel untouched while the previous device is still restored in a finally. The rest are the same ordinal reaching further: the video pre-cast text-encoder resolver takes it on both the plan and prefetch paths, the image DiT artifact planner reads it from the load kwargs it already receives, and the H3 plan sizing uses the restoring scope rather than the permanently pinning helper, since the plan route reaches it on a pooled executor thread. The transformer-quant smoke cache is keyed by the card the probe ran on rather than by "cuda". A pass on one selected GPU was standing in for a card that was never tested, and a failure on an older card rejected the same scheme on a capable one.
|
Round 4, all six fixed in ab9da2f. Two of them were regressions from the previous commit, and both were worth catching. The native engine one is the serious one: the route hands
The rest carry the ordinal further: the video pre-cast encoder resolver on both plan and prefetch paths, the image DiT artifact planner, and the H3 plan sizing switched to the restoring scope since the plan route reaches it on a pooled thread. The transformer-quant smoke cache is keyed by the card the probe ran on rather than by I have also gone back and resolved the settled threads from rounds 1 to 3, which I should have been doing each round. Focused tests match upstream/main exactly; ruff clean. |
Both plan routes resolved the ordinal twice, once for the precision preflight and again for download_plan. The preflight's smoke probe allocates on the card it tests and other workloads move free VRAM too, so the second ranking could pick a different card and the plan then sized its file set for a GPU the requested precision was never validated on.
|
Round 5, fixed in 36ff50d. Both plan routes were resolving the ordinal twice, once for the precision preflight and again for |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 36ff50d75b
ℹ️ 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".
| try: | ||
| # ONE ranking for the whole request, as the images plan does: a second call after the | ||
| # preflight can pick a different card than the precision was validated on. | ||
| gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids) |
There was a problem hiding this comment.
Return and reuse the download-plan GPU winner
When an API client supplies multiple gpu_ids, this request chooses one card for precision and H3 artifact planning, but the later /video/load request ranks the same list again after staging may have taken minutes. If free VRAM changes, the load can choose a differently sized or differently capable card, so the plan may have omitted the dense 66 GB denoiser needed by the actual destination or validated an explicit precision only on the other card; the image plan/load pair has the same split. Fresh evidence beyond the earlier per-request fix is that no resolved winner is returned by the plan or carried into the separate load request, so return a physical winner and have the client submit that singleton for loading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The shipped control is a single choice, so the UI sends exactly one id and the plan and the load resolve to the same card deterministically; the split only appears for an API client that posts several ids, and there the load's ranking is the authoritative one. A mismatch degrades to fetching an artifact inline, which is what an unselected load does today. Returning a winner in the plan response and having the client echo it back is an API shape change for an input the product does not produce, so it is out of scope here.
…aining is idle Removing the pin from _resolve_device_target left the planning helpers building an indexed target without making that card current, and their selectors read the current device. _dense_quant_prefetch_needed and _dit_prequant_plan_source now run their whole decision inside diffusion_device_scope, so select_transformer_quant_scheme, resolve_dense_quant_candidate and the memory snapshot all measure the card the load will use. The H3 plan scope had the same shape of mistake: it closed right after building the target, leaving the capacity reader and the encoder-scheme probe on the pooled thread's default card, so it now encloses the whole sizing call. The compile-cache fingerprint reads the current device instead of hardcoding index 0. A load pinned to another card compiles for that architecture, and keying the bundle by GPU 0 let two cards share or overwrite each other's artifacts. Both plan routes resolve the GPU only after the training guard has answered. Ranking reads free VRAM per candidate and opens a CUDA context on each, which is exactly what those routes refuse to do while a training subprocess owns the cards.
|
Round 6: four fixed in 9c20c18, one rejected. Two were consequences of my own earlier commits, which is the useful part of this round. Taking the pin out of The H3 plan scope was closing right after building the target, leaving the capacity reader on the default card; it encloses the whole sizing call now. And the compile-cache fingerprint reads I have not taken the plan-to-load handoff item. The shipped control is a single choice, so the UI sends one id and both requests resolve to the same card; the split only appears for an API client posting several ids, where the load's ranking is authoritative and a mismatch costs an inline fetch, the same as an unselected load. Returning a winner in the plan response for the client to echo back is an API shape change for an input the product does not produce. Happy to be argued out of it if there is a caller I am not seeing. Focused tests match upstream/main exactly; ruff clean. |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
|
Before/after evidence for the UI half of this PR, from two isolated Studio installs: BEFORE is the merge base Images, Advanced panel Video, Advanced panel The card list, opened What moved
Both pages default to One thing worth knowing about how this was shotThe control renders only when That also means this is evidence for the picker appearing and offering the right cards, not for the placement actually landing on the chosen one. The multi-card placement behaviour is still only covered by your faked-enumeration tests, and the sd.cpp |
|
@codex review |
1 similar comment
|
@codex review |
|
Pushed three commits to this branch after simulating the change across hosts and engines. Two are regressions the device pin introduced into the native path, both only reachable once a card is actually selected, so nothing on the automatic path changes. The CPU-backend restart stopped working
so the denoiser stays on the card that just aborted and the recovery is a silent no-op: the same The status reported an offload that never happened
Both go through one helper, Smaller things
What was checkedBackend suite in an isolated venv at the merge base and at head: identical pre-existing failures (12 to 13, all chat/provider/subprocess, flaky on this host), 23024 passed at head against 22989 at base. 146 hermetic simulations over sd.cpp argv against fake builds: CUDA, ROCm, Vulkan, MUSA, CPU-only, a CRLF listing, a build that exits non-zero, and one that predates Back-compat also checked directly: both request models still default Frontend: New coverage in this push: the CPU-restart argv, the |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d17292b5b
ℹ️ 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".
| text = _sd_cpp_probe_output(binary, "--list-devices") | ||
| if text is None: | ||
| return None |
There was a problem hiding this comment.
Refuse an unresolved native device pin
When an explicit GPU is selected but sd-cli --list-devices is unsupported, times out, or omits that ordinal, this returns None; device_backend_flags() then emits no --backend argument, so the native image and H3 video paths silently run on sd.cpp's default GPU. On a heterogeneous host this can place the model on the smaller card and OOM despite the user selecting a viable card. Distinguish “no selection” from “selection could not be mapped” and fail the load rather than dropping the pin.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taken, deliberately. Refusing the load would turn an unhonoured selection into an unloadable model on any build that predates --list-devices (upstream #1734, 2026-07-04), and sd.cpp treats an unknown argument as fatal: parse_options returns false and main.cpp exits 1. Studio also accepts a user-supplied binary through SD_CLI_PATH, so that is not a hypothetical build. The fallback is what every native load does today, and the pinned prebuilt does resolve the name, so the only hosts affected are the ones that would otherwise stop loading entirely. It is no longer silent though: an unresolved pin now logs sd_cpp.device_pin_unresolved with the ordinal and whether the probe was unreadable or simply did not list it (e411e6e), so a load that ran on the wrong card can be diagnosed from the log.
Three items from this round, two taken. A pooled worker kept the previous model's GPU. `/images/generate` runs on an `asyncio.to_thread` worker, and those threads are reused, so a load pinned to a non-default card leaves that thread set to it permanently. The next model loaded automatically has no ordinal, so nothing re-pinned the worker, and its bare `cuda` Generators and allocations then targeted the previous card while the weights sat on the default one: a cross-device error, or an allocation on a GPU the user did not choose. The card the weights actually landed on is now recorded with the pipeline as `placed_ordinal` and applied by every worker that touches it. Kept separate from `gpu_ordinal`, so an automatic load still resolves a bare, un-indexed device and reports exactly what it did before. The download-plan routes dropped the selection entirely while training ran. The training guard is there to keep a CUDA context from being opened, which only the free-VRAM ranking does; validating and translating physical ids reads the environment mask and nvidia-smi and opens nothing. Skipping all of it let the plan answer 200 for a GPU the load would then refuse, and size its file set for the default card, after tens of gigabytes had been staged. The ranking still waits for the trainer; the validation no longer does, so the single-card selection the UI sends resolves either way and a bad one is refused at the plan. Not taken: refusing the load when the ggml device name cannot be resolved. The fallback is deliberate. sd.cpp treats an unknown argument as fatal, and `--list-devices` only arrived in upstream unslothai#1734, so a build older than that (a user's own SD_CLI_PATH copy included) would go from "the selection is not honoured here" to "this model cannot load at all" the moment a card is picked. It runs on the build's own device, which is what every native load does today. It now says so in the log rather than dropping the pick in silence.
|
@codex review |
1 similar comment
|
@codex review |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9cf09564b4
ℹ️ 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".
| // Dropped when the chosen card is gone (a driver reset, an eGPU unplugged), so a stale pick loads automatically instead of 400ing. | ||
| gpu_ids: | ||
| selectedGpu !== "auto" && | ||
| gpuChoices.some((d) => String(d.index) === selectedGpu) | ||
| ? [Number(selectedGpu)] | ||
| : undefined, |
There was a problem hiding this comment.
Size picker recommendations for the selected GPU
On a heterogeneous multi-GPU host, this selection is forwarded only as gpu_ids; the task-scoped model picker still computes fit from useGpuInfo().loadDeviceMemoryGb, which represents the default visible ordinal rather than the selected card. Selecting a smaller card can therefore leave rows recommended that do not fit the actual destination, while selecting a larger card can hide viable rows or recommend an unnecessarily small quant. Feed the chosen device's memoryTotalGb into the image and video picker fit budget whenever an explicit GPU is selected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taken. That budget comes from the shared model-picker fit heuristic that the chat and training pickers also use, and it is advisory: every decision that actually gates a load already reads the selected card after this branch, including the precision preflight, the download plan's file set, the memory plan and its capacity gate. A recommendation sized for the default card can suggest a quant that is smaller or larger than ideal, but it cannot let through a load the destination cannot take. Rewiring the shared picker to take a per-request device budget is a feature worth doing on its own, not a correctness fix belonging to this branch.
Three of the four items from this round. The offload hooks went to GPU 0 whatever was selected. apply_memory_plan hands diffusers a bare "cuda", and enable_model_cpu_offload reads the index off that device: with none, `_offload_gpu_id = gpu_id or torch_device.index or 0` settles on 0 and the hooks onload every module to cuda:0 (pipeline_utils.py, diffusers 0.39, confirmed against the installed copy). Generation runs on the selected card, so a low_vram or group-fallback load paged its modules onto the wrong GPU and either failed across devices or filled the card the selection existed to avoid. Placement now takes an indexed device string; the bare one stays for anything reading it as a policy. The GPU choices array changed identity on every render. pinnableGpuContext builds a fresh filtered array per call, so the hook returned a new array each time, which fed the load-advanced snapshot, which fed the download-footprint resolver the GGUF picker's effect depends on: every status poll cleared the companion sizes and re-POSTed a download plan per variant, discarding whatever was in flight. Memoized on the device list. And the pick did not survive a reload. Every other Advanced select is reseeded from the loaded build; this one cannot be, because the status reports the device a pipeline is on and not which physical card, so a refresh reset it to Auto while the model stayed put and the next Reapply moved it to the default GPU. It persists now, and the existing staleness guard still drops an id whose card has gone rather than sending one the backend would refuse. Not taken: sizing the picker's fit recommendations for the selected card. That budget comes from the shared model-picker heuristic that chat and training also use, and it is advisory: the decisions that actually gate a load (the precision preflight, the memory plan, the capacity gate) all read the selected card already. Rewiring the shared picker is a feature, not a fix for this branch.
|
Codex Review: Didn't find any major issues. 👍 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |



Part of #8636 (issue 1). The GPU picker is wired into the chat runtime and training only, so image and video generation silently pin every module to CUDA ordinal 0 whatever the user selects. Both engines are affected, and so is video.
On a mixed multi-GPU box this is not cosmetic: ordinal 0 is frequently the smaller card, and for a checkpoint that only fits on the larger one it decides whether the load runs at all.
What was missing
POST /video/loadandVideoBackend.begin_load()had nogpu_idsparameter at all.POST /images/loadpassed 15 arguments tobegin_load()andgpu_idswas not among them;diffusion.pyhad zero references to it.gpu_idswas consumed only underfeatures/chat/**andfeatures/model-picker/**. The image and video load calls never sent it.So sd.cpp was never given
--backendand fell back to its own default device, whileresolve_diffusion_device_target()returned a bare"cuda"that torch resolved tocuda:0.The change
gpu_idsis threaded through both request models, both routes and bothbegin_loadchains, the same way the LLM path already does it.Neither engine shards a diffusion checkpoint — diffusers places whole components, sd.cpp assigns whole modules per backend device — so a selection of several cards resolves to one, and the most free VRAM wins. That is the rule
auto_select_gpu_idsalready applies to training. Taking the first id instead would land back on ordinal 0 whenever a user selects everything, which is precisely the case this exists to serve. Ties take the lowest index. An index this host does not have is refused at the route, before the arbiter evicts chat.diffusers. The index is a new
DiffusionDeviceTarget.ordinalfield, deliberately kept out ofdevice.diffusion_device.py:34,diffusion_memory.py:139/228,diffusion_speed.py:222,diffusion_attention.py:257and the sd.cpp router all compare that string by value against"cuda", so folding the index into it ("cuda:1") makes every one of them take its non-CUDA branch: the model still loads, with the CUDA-specific optimisations quietly disabled. Placement reads the newtorch_device; the policies keep readingdevice.The pin is
torch.cuda.set_device(), applied where the target is built. It is thread-local, and the load, generate, ControlNet and re-activation paths each resolve on their own thread, so doing it once at load would not reach the denoise. It is also the lever that moves the offload budget:diffusion_memory.py:264readsmem_get_info()for the current device, so setting it steers the weights and the budget they are sized against to the same card. Without that, the offload policy on a mixed box is decided against the wrong card's capacity. The capability probe is asked of the selected card as well, or a mixed-generation box picks its dtype from the wrong GPU; with no selection it stays argument-less as before.sd.cpp. The selection becomes
--backend diffusion=CUDA<n>,te=CUDA<n>,vae=CUDA<n>, built after the offload policy so--clip-on-cpu/--vae-on-cpukeep those modules on the CPU. They are the deprecated spellings ofte=cpu/vae=cpuand the parser is last-wins, so pinning over them would silently undolow_vram. Device names come from the load's own binary via--list-devices, and onlyCUDA/ROCmnames are matched — Vulkan ordinals are a separate namespace with no defined mapping to a physical index, so pinning one would name a card the user did not choose. Anything uncertain (unreadable probe, an index the build does not list) keeps sd.cpp's own choice.UI. The image and video Advanced panels gain a GPU control, shown only where there is more than one pinnable CUDA / ROCm device, reusing the existing
diffusionPinnablenotion. It is a single choice rather than the chat picker's candidate pool, because that is what the engines can honour. A pick whose card has since disappeared falls back to automatic instead of sending an index the backend would refuse.Automatic loads are unchanged throughout: no ordinal, nothing pinned, the same probes as before.
Testing
Focused tests for the ordinal policy (single pick honoured, several cards resolve by free VRAM, ties take the lowest index, unreadable cards sort last, a missing index refused, ignored on MPS), the bare-device invariant, the indexed-override round trip, the sd.cpp flag builder including the
te=cpu/vae=cpuinteraction, the--list-devicesname mapping including the Vulkan refusal, and both routes forwarding the selection and refusing a bad index before the arbiter.Verified on a real GPU that the automatic path is byte-identical, that a selection produces
ordinal=0/torch_device="cuda:0"with the policy fields unchanged, and that the pin lands on a spawned worker thread through the realDiffusionBackendandVideoBackend. The two-card behaviour was exercised against faked torch enumeration (12 GB at ordinal 0, 16 GB at ordinal 1): selecting both resolves to ordinal 1, the reversed box resolves to ordinal 0, and the dtype probe follows the selected card. The sd.cpp probes were run against fakesd-cliexecutables covering CUDA, ROCm, Vulkan, CPU-only and non-zero-exit builds.Not verified end to end on real multi-GPU hardware, and no sd.cpp binary was available here, so the
--backendargv is checked by construction rather than by a render.whisper/ STT has no GPU selection either, left alone as out of scope.