Skip to content

studio: honour the gpu selection for image and video loads - #8645

Merged
danielhanchen merged 22 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-media-gpu-selection
Aug 13, 2026
Merged

danielhanchen merged 22 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-media-gpu-selection

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

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/load and VideoBackend.begin_load() had no gpu_ids parameter at all.
  • POST /images/load passed 15 arguments to begin_load() and gpu_ids was not among them; diffusion.py had zero references to it.
  • Frontend-side, gpu_ids was consumed only under features/chat/** and features/model-picker/**. The image and video load calls never sent it.

So sd.cpp was never given --backend and fell back to its own default device, while resolve_diffusion_device_target() returned a bare "cuda" that torch resolved to cuda:0.

The change

gpu_ids is threaded through both request models, both routes and both begin_load chains, 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_ids already 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.ordinal field, deliberately kept out of device. diffusion_device.py:34, diffusion_memory.py:139/228, diffusion_speed.py:222, diffusion_attention.py:257 and 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 new torch_device; the policies keep reading device.

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:264 reads mem_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-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 silently undo low_vram. Device names come from the load's own binary via --list-devices, and only CUDA / ROCm names 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 diffusionPinnable notion. 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=cpu interaction, the --list-devices name 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 real DiffusionBackend and VideoBackend. 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 fake sd-cli executables 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 --backend argv is checked by construction rather than by a render.

whisper / STT has no GPU selection either, left alone as out of scope.

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.
@mahiatlinux
mahiatlinux force-pushed the fix/studio-media-gpu-selection branch from e73965d to d1c4281 Compare August 13, 2026 04:29
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

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: 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. Free VRAM is read on the translated ordinal for the same reason.

Resolved once. The winner is decided in begin_load and carried to the worker as gpu_ordinal, then committed onto _LoadState with the pipeline. That fixes the re-ranking flip, keeps a load in flight from moving the resident model's card, and leaves the selection alone when a load fails before teardown.

Pinned per worker. Every path that touches a loaded pipeline goes through _state_device_target before it builds any device object, so the ControlNet placement and the video generate worker no longer resolve state.device against their own default card.

Precision gate runs against the selected card, and the sd.cpp --backend pin is built where the flags are handed to a binary, so a deferred install, the post-download re-resolve and the one-shot fallback each probe the build that actually runs.

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 (pinnableGpuContext was re-exported but never imported, TS2552), which the Tauri Linux job caught.

Tests: focused files pass with no regression against upstream/main, plus new coverage for the mask translation, the reordered-mask case, ordinal-vs-physical VRAM reads, the off-CUDA route no-op, and the per-binary sd.cpp pin. The multi-card behaviour is exercised against faked torch enumeration and fake sd-cli builds; this host has one GPU and no sd.cpp binary, so nothing was confirmed on real multi-GPU hardware.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 13, 2026 05:15
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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Round 2, all three fixed in 06d97c2.

The rework carried the resolved ordinal inside begin_load, but three decisions upstream of it still read the default card, and you found all of them.

Both routes resolve the selection once through a shared _selected_gpu_ordinal (which only runs the CUDA resolver once the target reports a CUDA device) and pass it into every precision preflight, including the download-plan ones and the engine-switch re-check. The video load route now resolves it before its gate instead of after.

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 diffusionPinnable: false, so on a Vulkan-chat plus CUDA-diffusers host the control never appeared even though the routes honour those ids. Chat's Vulkan path is unchanged.

Focused tests pass with no regression against upstream/main; ruff and tsc -b clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

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 asyncio.to_thread executor and its threads are reused, so an unrestored set_device left this request's card current for the next one, including an automatic load. I checked the mechanism rather than assuming it: two successive to_thread calls do land on the same thread. diffusion_device_scope restores the previous device, both precision preflights probe inside it, _resolve_device_target no longer pins as a side effect, and the dedicated load and generate workers take the permanent pin explicitly.

ROCm dtype. Confirmed against the installed torch that is_bf16_supported takes no device argument ((including_emulation: bool = True)), so the only way to ask about the selected card is to make it current for the call. Scoped.

Route to loader. begin_load takes gpu_ordinal and re-ranks only when the caller did not, so the preflighted winner is the card that gets used.

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 gpu_ids.

New tests cover the scope restoring and the ROCm probe asking about the selected card. Focused tests match upstream/main exactly; ruff and tsc -b clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… 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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

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 gpu_ordinal to whichever engine it activated, but SdCppDiffusionBackend.begin_load() still accepted only gpu_ids. I called it to confirm rather than reading it, and it raises unexpected keyword argument 'gpu_ordinal' before the background load starts, so every native GGUF image load would have returned 500. It takes the ordinal now, and no longer re-ranks the list for itself. There is a test asserting both the parameter and a 200 on that path.

diffusion_device_scope was catching around its own yield, so a body exception was swallowed and the generator yielded twice, which contextlib reports as "generator didn't stop after throw()". An explicit-precision refusal arrived at the route as that instead of its real message. Only the context entry is guarded now, the body propagates untouched, and the restore moved into a finally.

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 "cuda", so one card's verdict no longer stands in for another's.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Round 5, fixed in 36ff50d. Both plan routes were resolving the ordinal twice, once for the precision preflight and again for download_plan. Since the preflight's smoke probe allocates on the card it tests, the second ranking could legitimately land elsewhere and the plan would then size its file set for a GPU whose precision was never validated. One resolution at the top of each request now, reused by both.

@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 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".

Comment thread studio/backend/routes/video.py Outdated
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)

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 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

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 _resolve_device_target in round 3 left the planning helpers building an indexed target without making that card current, while their selectors read the current device; both now run their full decision inside diffusion_device_scope. And hoisting the plan ranking in round 5 put it ahead of the training guard, so ranking could open a CUDA context per candidate while a trainer owned the cards. Both plan routes now resolve only once _training_is_active has answered.

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 current_device() rather than hardcoding 0, so two cards can no longer share an architecture-specific bundle.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9c20c18f8e

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

Copy link
Copy Markdown
Member

Before/after evidence for the UI half of this PR, from two isolated Studio installs: BEFORE is the merge base 22cb12ec6, AFTER is head 53c0b1db8. Same scene driven against both, same host, same viewport.

Images, Advanced panel

Images Advanced

Video, Advanced panel

Video Advanced

The card list, opened

GPU options

What moved

BEFORE AFTER
Images Advanced rows Speed, Precision, Attention, Memory, Step cache, CPU offload same plus GPU, between Memory and Step cache
Video Advanced rows Memory, Speed, Precision, Attention, Step cache same plus GPU, same position
GPU options offered none, no control Auto, GPU 0 · 179 GB, GPU 6 · 179 GB
/api/system device_backend cuda, indices [0, 6] identical

Both pages default to Auto, so a load that never touches the control sends no gpu_ids and behaves as before. The system inventory reads the same on both sides, which is what makes this a comparison of the two builds rather than of two hosts.

One thing worth knowing about how this was shot

The control renders only when useDiffusionGpuChoices() finds more than one pinnable CUDA or ROCm device, so the whole visible effect is gated on the Studio seeing at least two cards. My session is assigned a single GPU, and on that mask both halves come out identical and would read as "this PR changed nothing". The two Studios were therefore launched with a two-card CUDA_VISIBLE_DEVICES. Nothing else was faked: the device list behind /api/system comes from nvidia-smi filtered by that mask, and the scene loads no model, so no work ran on either card.

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 --backend argv by construction, as your description says.

@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

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

_restart_server_on_cpu_backend relaunches with state.offload_flags plus --backend cpu. sd.cpp declares --backend with concat = ',' (examples/common/common.cpp), so repeated values are joined into one spec rather than replacing, and module_assignment_name only consults the bare default for modules with no explicit entry. The spec becomes:

backend: "diffusion=CUDA0,te=CUDA0,vae=CUDA0,cpu"

so the denoiser stays on the card that just aborted and the recovery is a silent no-op: the same GGML_ABORT, immediately. Confirmed against the pinned prebuilt master-813-bfbef5b-u13b9d92, which logs that joined spec verbatim.

The status reported an offload that never happened

status() and the saved recipe derive "was anything offloaded?" from the flag tuple being empty, which is how a fast load reports none. The pin lives in that same tuple, so selecting a GPU made cpu_offload read true and offload_policy read active for a load that offloads nothing.

Both go through one helper, without_device_backend_flags, so the pin is dropped where the flags are read as a policy and kept where they are argv.

Smaller things

  • The native backend now resolves a bare gpu_ids itself, as the diffusers and video backends already do. The routes rank and pass the winner, so this only affects a direct caller, but it was the one engine that dropped such a pick silently, and it left resolve_selected_cuda_ordinal imported and unused. That unused import was the Lint CI failure (Import-hoist / alias-rename safety).
  • tests/studio/test_model_picker_contracts.py pinned the exact source line of the Vulkan gate, which this branch deliberately scoped to the GGUF picker. That was the Repo tests (CPU) failure. The assertion now holds the same property against !forDiffusion && inference?.backend === "vulkan".
  • Merged main in. The branch was CONFLICTING: tests: follow the remote-connection contract through its refactor #8467 reformatted that same assertion. Resolved to keep both.

What was checked

Backend 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 [Linux, Windows, WSL, macOS] x [NVIDIA, ROCm, Intel XPU, Apple MPS, CPU-only, no torch]: the automatic target is byte-identical on every host, a selection is honoured only where an index means something, the policy fields do not move when a card is picked, and the scope neither raises nor leaks on a host without that card. Physical-to-ordinal translation was driven through the real hardware layer rather than a stub: unmasked, 4,5, 1,0, "", -1, a UUID mask, a MIG mask, and HIP_VISIBLE_DEVICES, plus free-VRAM ranking read on the translated ordinal. The pin restores on a pooled thread and stays on a dedicated one, and a body exception travels out of the scope unchanged.

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 --list-devices and treats it as a fatal unknown argument. That last one is the back-compat case that matters for an existing SD_CLI_PATH install: the probe returns nothing and no --backend is emitted at all, so an older binary is never handed a flag it would die on.

Back-compat also checked directly: both request models still default gpu_ids to null and reject malformed values as a 422, all three engines take the new keywords as optional, all three planners tolerate them, and the compile-cache fingerprint is unchanged on a single-GPU host, so nothing already on disk is invalidated.

Frontend: tsc clean, 2018 unit tests pass, plus 7 new ones for the rule behind the control. The control renders and is selectable identically in Chromium, Firefox and WebKit with no console errors, which covers the WebView2 and WebKit sides of Tauri as well as a plain browser.

New coverage in this push: the CPU-restart argv, the fast and offloaded status pair, the native self-resolve, both download-plan routes forwarding the selection and refusing a bad index with a 400 (they had none for this field, and they are the routes that size a file set against a card), and the frontend choice rule.

@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: 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".

Comment on lines +375 to +377
text = _sd_cpp_probe_output(binary, "--list-devices")
if text is None:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

pre-commit-ci Bot and others added 2 commits August 13, 2026 12:51
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@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: 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".

Comment on lines +2258 to +2263
// 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,

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 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 👍 / 👎.

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.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: bbb4f90b3d

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

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a9731465b4

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

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