Skip to content

Studio: automatic image/video loads pick the freest GPU, and GPU picks respect what each card can run - #13928

Merged
danielhanchen merged 7 commits into
mainfrom
r7e-studio-auto-gpu
Oct 16, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
r7e-studio-auto-gpu

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Problem

Three GPU selection gaps on multi-GPU NVIDIA hosts:

  • Image / video auto mode (Studio: diffusion budgets against one GPU, so a multi-GPU host offloads to RAM instead of using the second card #8235): with the GPU picker on Automatic, the frontend sends no GPU ids and the load ran on the current device, which is PCI slot 0 under Studio's PCI_BUS_ID order. A busy card 0 made the load offload to RAM while an idle card sat beside it. The most-free-VRAM ranking only ran for manual picks.
  • llama.cpp CUDA SM gate: the gate passed when any visible GPU was new enough. With an RTX 4090 and a GTX 1060, a pick that included the 1060 launched a bundle without sm_61 kernels and died with "no kernel image is available".
  • CUDA_DEVICE_ORDER=FASTEST_FIRST: auto-select ranked GPUs by nvidia-smi PCI index. Under an explicit FASTEST_FIRST, the training worker could get a different card from the one ranked.

Fix

  • Studio: diffusion budgets against one GPU, so a multi-GPU host offloads to RAM instead of using the second card #8235, resolve_auto_cuda_ordinal() in diffusion_device.py:
    • Automatic image and video loads go to the single card with the most free VRAM, like auto_select_gpu_ids and Ollama's single-GPU fit. It uses nvidia-smi telemetry mapped through the parent mask, with no CUDA context per card.
    • Readings within 256 MiB count as a tie and go to the lowest card, so an idle host of identical cards stays on card 0.
    • It keeps the current device for one visible card, a UUID or MIG mask, a mask entry naming no card, ROCm, an integrated GPU, an explicit non-PCI CUDA_DEVICE_ORDER, or missing telemetry or compute capabilities.
    • Only cards at least as capable as card 0 compete, so a freer older card the installed torch may not run is never picked.
    • The route's decision, including "keep the current device", is reused by the diffusers, video and sd.cpp loaders and by the auto-switch, so the locality check and the load use the same card.
    • Explicit picks are unchanged.
  • SM gate:
    • _cuda_sm_gate_error checks the picked cards when there is a pick and they are nvidia-smi indices, and keeps today's rule otherwise. It runs again after a projector or drafter widens the pick.
    • Cards too old for the bundle are dropped from the automatic llama-server pool. If none survive, the existing refusal is shown.
  • Device order:
    • apply_gpu_ids sets CUDA_DEVICE_ORDER=PCI_BUS_ID under an explicit non-PCI order with no inherited mask, only when the picked ids came from nvidia-smi rows, which is how the llama.cpp, sd.cpp and managed-engine children are already pinned. Ids picked through torch keep the user's order.
    • Auto-select ranks through torch when a numeric mask meets an explicit non-PCI order.
    • Display telemetry is unchanged.

Tests

  • New test files: tests/test_diffusion_auto_gpu.py, tests/test_cuda_sm_gate_pinned.py and tests/test_gpu_ids_cuda_device_order.py.
  • Base vs head: the behavioural tests fail on main and pass here; the resolver tests target the new function directly.
  • 135 related test files: the same failures on main and here.
  • On this 8x B200 host, read-only: the resolver read the real telemetry and picked card 5, which nvidia-smi reports as the freest (182630 MiB free; card 0 had 169254 MiB). Main's automatic load uses card 0.

- llama.cpp CUDA SM gate checks the GPUs a launch is pinned to, and auto
  placement drops cards older than the installed bundle's oldest arch
- apply_gpu_ids pins CUDA_DEVICE_ORDER=PCI_BUS_ID when the ids are
  nvidia-smi rows; a numeric mask under a non-PCI order reads torch telemetry
- Automatic image/video loads rank visible GPUs by free VRAM (#8235)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-16T00:26:40.003767Z 9a9bde6 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T19:59:01.423633Z 88db640 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 3a74db6344

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
…s decision for the backend; gate pinned ids only in nvidia-smi's index space, re-gate a companion-widened mask; keep the explicit CUDA order for torch-fallback ids
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 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. Delightful!

Reviewed commit: 9a9bde6af6

ℹ️ 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 added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 16, 2026
…port (#1809)

## Summary

`Core zoo (HF=4.57.6 + TRL<1)` on unslothai/unsloth#13928 failed
`tests/test_vllm_retry_releases_failed_engine.py::test_load_vllm_frees_every_failed_engine_including_the_last`
(4 cases) with:

```
AttributeError: <module 'vllm' from '/tmp/pytest-of-runner/.../test_forced_vendored_import_ig0/vllm/__init__.py'> has no attribute 'LLM'
```

That `vllm` is the fake package
`test_triton_kernels_adapter.py::test_forced_vendored_import_ignores_cached_top_level_children`
(#1769) writes into `tmp_path`. The test deletes any real `vllm.*`
modules through monkeypatch, which restores them afterwards, but the
fake `vllm`, `vllm.third_party` and `vllm.third_party.triton_kernels.*`
it imports are new keys that monkeypatch never knew about, so they stay
in `sys.modules`. On a runner without vLLM, the next
`pytest.importorskip("vllm")` on the same xdist worker then returns the
fake instead of skipping. Whether it fails depends on which worker the
two files land on, which is why it shows up on some runs only.

Product code is not involved; the leak is in the test fixture.

## Change

The `fresh` fixture in `tests/test_triton_kernels_adapter.py` now
snapshots `sys.modules` and, at teardown, removes any `vllm.*` or
`triton_kernels.*` module a test imported. Modules that existed before
are still restored by monkeypatch, which runs after this teardown, so a
real installed vLLM comes back untouched.

## Testing

Reproduced on zoo main (970c083), CPU, no vLLM installed, running the
vendored test followed by the vLLM retry test in one process:

- before: 4 failed with the CI `AttributeError`
- after: 7 passed, 4 skipped (the vLLM tests skip as intended)
- `tests/test_triton_kernels_adapter.py` +
`tests/test_vllm_retry_releases_failed_engine.py` together: 39 passed, 5
skipped
@danielhanchen
danielhanchen merged commit c1dc273 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the r7e-studio-auto-gpu branch October 16, 2026 04:01
Chroma01 pushed a commit to Chroma01/unsloth that referenced this pull request Oct 17, 2026
…ai#14020)

## Problem

unslothai#13928 added automatic GPU placement for image and video loads (unslothai#8235).
On ordinary hosts (zero or one GPU, Apple Silicon, CPU, ROCm, identical
cards) it changed behaviour that should have stayed as it was:

1. When the best card was the current device, or the cards tied, auto
mode returned an explicit ordinal 0 instead of None. In the video engine
an explicit ordinal turns on the `_device_target` pin, so every
generation called `set_device` twice instead of once.
2. Every automatic request resolved the full device and dtype target
before deciding whether ranking applied at all. That meant
`get_device_capability` on single-GPU hosts and the MPS bf16 probe on
Apple Silicon. A direct load with an invalid model also hit the
capability lookup before validation refused it.
3. With an explicit `CUDA_DEVICE_ORDER=FASTEST_FIRST` and a numeric
mask, `auto_select_gpu_ids` switched to torch telemetry
(`get_device_properties` and `mem_get_info` per card, which leaves a
CUDA context in the Studio process), even on identical cards where the
nvidia-smi rows already name the right cards.
4. A `/v1/models` catalog refresh ran live ranking once per media pick,
including on single-GPU and homogeneous hosts.

## Fix

- When card 0 wins (ties included) on identical cards,
`resolve_auto_cuda_ordinal` returns None, so those hosts keep the old
unpinned path. On mixed cards card 0 stays explicit, so a pooled thread
left on another card cannot preflight against the wrong card. Generation
no longer pins the same card twice when the load ordinal and the placed
card match. A freer card on a multi-GPU host is still picked.
- New `auto_cuda_ranking_possible()` is a cheap gate that only reads the
cached device and the mask: NVIDIA CUDA with at least two parent-visible
GPUs. The route, the backend fallbacks (diffusers, video, sd.cpp) and
the locality planner check it before resolving any device target. The
backends now resolve the automatic ordinal after
`validate_load_request`. Explicit `gpu_ids` keep their original order
and behaviour.
- For the FASTEST_FIRST numeric-mask case, `auto_select_gpu_ids` maps
each CUDA ordinal to its nvidia-smi row by PCI bus id. A short child
process reads the bus ids through the driver API (`cuInit`, no context)
and the mapping is cached per environment and hardware re-detection
generation, so ranking uses nvidia-smi telemetry for the right cards
without a CUDA context in Studio. If the mapping cannot be established,
the torch path is kept.
- The route answers the ranking gate from state already in memory.
Anything that might run nvidia-smi (cold detection, an uncounted host, a
UUID mask) goes to a worker thread.
- A catalog refresh picks one ordinal and pins it for every pick. On one
GPU or on identical cards (name, total memory, compute capability and
max SM clock from one cached nvidia-smi query), that ordinal is the
current device and nothing is ranked. On mixed cards, or when identity
is unknown, it ranks once per refresh instead of once per pick.

Under a FASTEST_FIRST numeric mask that falls back to torch telemetry,
automatic GPU selection no longer applies the MIG slice correction,
which is keyed on physical nvidia-smi rows, to rows that carry mask ids;
torch already reports each MIG slice's own memory, so the correction
could shrink the wrong card. On the bus-id mapped path the correction
now runs on the physical rows before they are translated to mask ids,
and when the CUDA order is not nvidia-smi's, card 0 stays an explicit
pick unless every card is identical. The identical-card shortcut
compares every physical card when mask ids are not nvidia-smi rows, and
never applies when a compared card has MIG instances, since physical
rows hide slice sizes; a failed or empty MIG listing counts as unknown,
not identical. On the mapped FASTEST_FIRST path, failed MIG discovery or
any mapped MIG card falls back to torch telemetry, which reports slice
memory itself, as does a mapped integrated card (its nvidia-smi row is a
carve-out); identity compares every listed row, not a possibly stale
count.

## Tests

- New `tests/test_media_auto_gpu_ordinary_host.py` counts calls with
mocks. It covers: None when the current device wins (an explicit 0 once
a thread was pinned to another card), card identities re-read after
hardware re-detection, no extra video pin, no target resolution or
ranking in the route or the backend fallbacks on one GPU, zero GPUs,
Apple, CPU and ROCm (including a cold ROCm detection), invalid direct
loads refused before any probe, FASTEST_FIRST masks ranked from
nvidia-smi rows joined by bus id, including a tie order that differs
from PCI order (torch only when the mapping is unknown), mixed cards
keeping card 0 explicit with a single generation pin, the route gate
staying off the event loop when it could probe, card identity read only
once, and catalog refreshes that do not rank on ordinary hosts but rank
once on mixed cards. Most of its cases fail on current main; the ones
that pass there are positive controls (multi-GPU ranking still happens).
- Updated the existing auto GPU tests so ties and a winning card 0 now
expect None, and so route and auto-switch tests that exercise ranking
enable the gate explicitly.
- Related backend suites (diffusion, video, sd.cpp, media auto-switch
and locality, `/v1/models` media, CUDA SM gate, GPU selection and
training GPU selection, refactor guard): 3231 passed, 1 skipped. The
only failure, `test_mirrored_base_still_trips_the_flux2_shape_guard`,
needs the `gguf` module and fails the same way on main.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Processware-AI pushed a commit to Processware-AI/unsloth that referenced this pull request Oct 17, 2026
…ai#14020)

## Problem

unslothai#13928 added automatic GPU placement for image and video loads (unslothai#8235).
On ordinary hosts (zero or one GPU, Apple Silicon, CPU, ROCm, identical
cards) it changed behaviour that should have stayed as it was:

1. When the best card was the current device, or the cards tied, auto
mode returned an explicit ordinal 0 instead of None. In the video engine
an explicit ordinal turns on the `_device_target` pin, so every
generation called `set_device` twice instead of once.
2. Every automatic request resolved the full device and dtype target
before deciding whether ranking applied at all. That meant
`get_device_capability` on single-GPU hosts and the MPS bf16 probe on
Apple Silicon. A direct load with an invalid model also hit the
capability lookup before validation refused it.
3. With an explicit `CUDA_DEVICE_ORDER=FASTEST_FIRST` and a numeric
mask, `auto_select_gpu_ids` switched to torch telemetry
(`get_device_properties` and `mem_get_info` per card, which leaves a
CUDA context in the Studio process), even on identical cards where the
nvidia-smi rows already name the right cards.
4. A `/v1/models` catalog refresh ran live ranking once per media pick,
including on single-GPU and homogeneous hosts.

## Fix

- When card 0 wins (ties included) on identical cards,
`resolve_auto_cuda_ordinal` returns None, so those hosts keep the old
unpinned path. On mixed cards card 0 stays explicit, so a pooled thread
left on another card cannot preflight against the wrong card. Generation
no longer pins the same card twice when the load ordinal and the placed
card match. A freer card on a multi-GPU host is still picked.
- New `auto_cuda_ranking_possible()` is a cheap gate that only reads the
cached device and the mask: NVIDIA CUDA with at least two parent-visible
GPUs. The route, the backend fallbacks (diffusers, video, sd.cpp) and
the locality planner check it before resolving any device target. The
backends now resolve the automatic ordinal after
`validate_load_request`. Explicit `gpu_ids` keep their original order
and behaviour.
- For the FASTEST_FIRST numeric-mask case, `auto_select_gpu_ids` maps
each CUDA ordinal to its nvidia-smi row by PCI bus id. A short child
process reads the bus ids through the driver API (`cuInit`, no context)
and the mapping is cached per environment and hardware re-detection
generation, so ranking uses nvidia-smi telemetry for the right cards
without a CUDA context in Studio. If the mapping cannot be established,
the torch path is kept.
- The route answers the ranking gate from state already in memory.
Anything that might run nvidia-smi (cold detection, an uncounted host, a
UUID mask) goes to a worker thread.
- A catalog refresh picks one ordinal and pins it for every pick. On one
GPU or on identical cards (name, total memory, compute capability and
max SM clock from one cached nvidia-smi query), that ordinal is the
current device and nothing is ranked. On mixed cards, or when identity
is unknown, it ranks once per refresh instead of once per pick.

Under a FASTEST_FIRST numeric mask that falls back to torch telemetry,
automatic GPU selection no longer applies the MIG slice correction,
which is keyed on physical nvidia-smi rows, to rows that carry mask ids;
torch already reports each MIG slice's own memory, so the correction
could shrink the wrong card. On the bus-id mapped path the correction
now runs on the physical rows before they are translated to mask ids,
and when the CUDA order is not nvidia-smi's, card 0 stays an explicit
pick unless every card is identical. The identical-card shortcut
compares every physical card when mask ids are not nvidia-smi rows, and
never applies when a compared card has MIG instances, since physical
rows hide slice sizes; a failed or empty MIG listing counts as unknown,
not identical. On the mapped FASTEST_FIRST path, failed MIG discovery or
any mapped MIG card falls back to torch telemetry, which reports slice
memory itself, as does a mapped integrated card (its nvidia-smi row is a
carve-out); identity compares every listed row, not a possibly stale
count.

## Tests

- New `tests/test_media_auto_gpu_ordinary_host.py` counts calls with
mocks. It covers: None when the current device wins (an explicit 0 once
a thread was pinned to another card), card identities re-read after
hardware re-detection, no extra video pin, no target resolution or
ranking in the route or the backend fallbacks on one GPU, zero GPUs,
Apple, CPU and ROCm (including a cold ROCm detection), invalid direct
loads refused before any probe, FASTEST_FIRST masks ranked from
nvidia-smi rows joined by bus id, including a tie order that differs
from PCI order (torch only when the mapping is unknown), mixed cards
keeping card 0 explicit with a single generation pin, the route gate
staying off the event loop when it could probe, card identity read only
once, and catalog refreshes that do not rank on ordinary hosts but rank
once on mixed cards. Most of its cases fail on current main; the ones
that pass there are positive controls (multi-GPU ranking still happens).
- Updated the existing auto GPU tests so ties and a winning card 0 now
expect None, and so route and auto-switch tests that exercise ranking
enable the gate explicitly.
- Related backend suites (diffusion, video, sd.cpp, media auto-switch
and locality, `/v1/models` media, CUDA SM gate, GPU selection and
training GPU selection, refactor guard): 3231 passed, 1 skipped. The
only failure, `test_mirrored_base_still_trips_the_flux2_shape_guard`,
needs the `gguf` module and fails the same way on main.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 18, 2026
…rs, never blocks the event loop (unslothai#14118)

## Problem

Three small costs in the automatic GPU placement added by unslothai#14020, all on
multi-GPU NVIDIA hosts:

1. `hardware._nvidia_mig_gpu_indices_or_none()` ran its own `nvidia-smi
-L`, bypassing the MIG discovery cache from unslothai#14017. A successful listing
was served by gpu_query's cache, but a failed one had no backoff, and
with `UNSLOTH_GPU_QUERY_CACHE=0` every call spawned nvidia-smi (one per
automatic route, two per catalog refresh).
2. Under `CUDA_DEVICE_ORDER=FASTEST_FIRST` with a numeric mask, a failed
bus-id join was never cached, so every `auto_select_gpu_ids()`
re-spawned the driver-API child (about 300 ms here, up to its 15 s
timeout on a hung driver).
3. nvidia-smi CSV output is not quoted, so a GPU name containing a comma
made `get_card_identities()` return nothing. Every catalog refresh then
ranked live, and identical cards under FASTEST_FIRST got an explicit
card 0 instead of staying unpinned.

4. On a MIG host, automatic image/video placement ranked cards by their
physical nvidia-smi rows and could return card 1, which CUDA maps to a
MIG slice (or to nothing before driver R570). Main before unslothai#13928 stayed
on the current card there.
5. The event-loop gate `auto_cuda_ranking_possible_cached()` called
`get_device()` for non-CUDA hosts, which waits on the hardware-detection
lock while a detection pass runs, stalling the event loop (about 1.3 s
per call in a spoofed run) on Mac, CPU and XPU hosts too.

## Fix

1. `_nvidia_mig_gpu_indices_or_none()` delegates to
`nvidia.get_mig_gpu_indices_or_none()`, so it shares that cache, its
failure backoff and its sequence-number rules.
2. A failed bus-id join is remembered for 300 s per (mask, order, static
generation); hardware re-detection still retires it at once.
3. Card identities rejoin a name that spans several CSV fields, as the
inventory parser already does.

4. A row-ranked winner other than card 0 is only taken when MIG
discovery confirms no MIG card among the visible ones; otherwise card 0
stays explicit.
5. The cached gate answers from memory only: non-CUDA or ROCm is False,
and detection still in flight defers to the worker thread.

Single-GPU, CPU, Apple and ROCm hosts never reach items 1-4.

## Tests

- New `tests/test_media_auto_gpu_mig_and_event_loop.py`: 6 of 7 fail on
main, all pass here.

- New `tests/test_media_auto_gpu_probe_caches.py`: 3 of its 5 tests fail
on main, all pass here.
- `test_mig_listing_parses_slices` disables gpu_query's cache in its
stub now that the helper shares it.
- GPU / hardware / media suites: 3467 passed, 3 skipped. The 3 failures
in `test_rocm_windows_vram_7452.py` are the same on main.

---------

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.

1 participant