Repository navigation
Studio: keep automatic GPU placement inert on ordinary hosts - #14020
Conversation
Automatic image/video placement returns None when the current device wins (ties included), skips every device and dtype probe on zero/one GPU, Apple, CPU and ROCm, validates direct loads before ranking, keeps nvidia-smi telemetry for identical cards under FASTEST_FIRST, and plans a /v1/models catalog refresh once instead of ranking per pick on homogeneous hosts.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Map FASTEST_FIRST mask ordinals to nvidia-smi rows by PCI bus id out of process instead of assuming identical cards share PCI order. Keep card 0 explicit on mixed cards and drop the duplicate generation pin instead. Rank catalog plans once when card identity is unknown. Answer the route's ranking gate from cached state or on a worker thread.
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…remapping Automatic placement under a CUDA order nvidia-smi does not share still skips ranking, but returns card 0 explicitly unless the cards are identical. The FASTEST_FIRST mask telemetry applies the MIG slice correction on physical rows before translating them to mask ids.
Under a FASTEST_FIRST numeric mask without a bus-id mapping, the torch rows carry mask ids and already report each MIG slice's memory, so the correction keyed on physical nvidia-smi rows could hit the wrong card.
… not SMI rows The identical-card shortcut now fails on any MIG card, whose slice size the physical nvidia-smi row does not show, so card 0 stays explicit there. The catalog compares every physical card when the CUDA order is not nvidia-smi's, since mask ids are then CUDA ordinals rather than rows.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…heck A failed or empty nvidia-smi -L listing no longer reads as no MIG card, so the identical-card shortcut returns unknown, card 0 stays explicit and the catalog ranks once.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f713a92f8
ℹ️ 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".
| if hw._cuda_cards_identical(ids) is True: | ||
| return None |
There was a problem hiding this comment.
Rank identical cards before planning the catalog
When physically identical GPUs have different free VRAM, this shortcut leaves the /v1/models catalog planning against the pooled worker's current device even though an automatic load ranks and may choose another card. Identity does not guarantee the same artifact plan: _pipeline_planned_denoiser_scheme() and _video_seed_stays_resident() explicitly snapshot live free memory when deciding whether dense or prequantized weights remain resident, so the catalog can advertise a model as fully local using a file set different from the subsequent load. Fresh evidence beyond the earlier unknown-identity case is these planners' free-memory-dependent artifact selection; rank once here even when card identities match.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this as is on purpose. Catalog refreshes do no live ranking on homogeneous hosts, matching how they behaved before #13928, and the point of this PR is that ordinary hosts pay nothing extra per refresh. Ranking would not make the listing exact anyway: the dense versus prequantized choice depends on free memory that changes between the catalog snapshot and the load, since the switch evicts the resident model first. The auto-switch already rechecks locality against its own ranked, pinned plan before loading, so a stale catalog entry ends in a refusal rather than an unexpected download. On mixed cards, or when identity is unknown, the catalog still ranks once per refresh.
When a mapped card has MIG instances, or MIG discovery fails, the nvidia-smi rows would advertise whole-card memory for a slice, so the mapped path now falls back to the slice-aware torch telemetry.
…d card The FASTEST_FIRST bus-id mapping now also reads each device's integrated attribute and falls back to the pool-aware torch telemetry when an integrated card is mapped. The identical-card check compares every row nvidia-smi lists instead of a possibly stale torch-fallback count.
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
…e the auto gate [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8d88a8736a
ℹ️ 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".
| # Physical rows hide MIG slice sizes, so a MIG card makes the set mixed. | ||
| mig = hw._nvidia_mig_gpu_indices_or_none() # None (unknown) keeps card 0 explicit | ||
| if mig is not None and not set(visible) & mig: | ||
| return None |
There was a problem hiding this comment.
Keep card 0 explicit after it wins ranking
When identical GPUs have uneven free VRAM and an executor thread was previously pinned to another card, returning None here discards the already-known winner. Subsequent route planning and precision checks use bare CUDA on pooled asyncio.to_thread workers, while the dedicated load worker defaults to card 0; planners such as _video_seed_stays_resident() inspect live free memory, so they can reject the request or stage a different artifact set based on the busier card. Returning ordinal 0 preserves the ranked card across preflight and load, and the new duplicate-pin guard still avoids the extra generation pin.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked on 2x NVIDIA L40S with head 5dd39cdd, through the normal flow:
- Held 30 GB on GPU 0 from another process, loaded SDXL Turbo with automatic GPU (it lands on GPU 1:
staged 6.4 GiB ... onto cuda:1) and generated, so pooled worker threads were left on GPU 1. - Released GPU 0 and held 20 GB more on GPU 1 (GPU 0: 8 MiB used, GPU 1: 32853 MiB used), so card 0 wins the ranking and this branch returns None.
- Requested
/api/inference/video/download-plan12 times each forWan-AI/Wan2.2-TI2V-5B-DiffusersandWan-AI/Wan2.2-T2V-A14B-Diffusers(auto precision).
All 24 plans were identical to the plan on an idle host: 1 distinct plan per model (TI2V-5B: 34201418400 bytes, dense transformer shards; A14B: 126199274206 bytes, dense shards). A separate sweep with both cards equally loaded (GPU free 48, 34, 28, 21, 17 GB) also returned the same plan every time, so the plan does not change with the free VRAM of the card it is computed on. On the image side the planner replaces free with total before sizing (diffusion.py device_memory_override = replace(..., free_mib = ....total_mib)), and capability and total are the same on identical cards. I could not get a different artifact set or a refusal from the pooled-thread case, so I am leaving None for identical cards as is.
There was a problem hiding this comment.
Agreed for the case you describe. Fixed in 438bad8: pin_cuda_ordinal now records when any thread was pinned to a card other than 0, and from then on a card 0 win is returned as an explicit 0, so preflight on a pooled worker that sits on another card and the load both read the ranked card. A process that never pinned away from card 0 keeps None on identical cards, so ordinary multi-GPU hosts still gain no set_device pins (a pinned load is the only way a pooled worker can end up elsewhere). Covered by test_card_zero_stays_explicit_once_a_thread_was_pinned_elsewhere.
| return None | ||
| count = get_physical_gpu_count() | ||
| wanted = list(range(count)) if gpu_ids is None else list(gpu_ids) | ||
| if not set(wanted) <= set(_cuda_card_identities) or len(_cuda_card_identities) < count: |
There was a problem hiding this comment.
Invalidate cached card identities after hardware re-detection
When a GPU is replaced by a different model without changing the physical card count, this condition continues using the old identity rows indefinitely. Hardware re-detection bumps gpu_query._static_gen, but unlike the ordinal mapping cache this cache is not keyed on that generation, so a formerly homogeneous host can still be classified as identical; catalog planning then skips ranking, and a non-PCI CUDA order can leave automatic loads unpinned despite the cards now having different capabilities or capacities. Include the static inventory generation in this cache or clear it during detection invalidation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one as is. The trigger is swapping a GPU for a different model while Studio keeps running and the visible card count stays the same. Internal PCIe cards cannot be swapped under a running driver, and an eGPU attach or detach changes the count, which already re-reads the identity rows (len(_cuda_card_identities) < count). A restart after the swap starts with an empty cache. On the 2x L40S and 2x A10 hosts the identity rows were read once per process and matched nvidia-smi --query-gpu=index,name,memory.total,compute_cap,clocks.max.sm on every refresh I traced.
There was a problem hiding this comment.
Agreed. Fixed in 438bad8: the card identity cache now records the gpu_query static generation it was read under and re-reads when hardware re-detection bumps it, so a card swapped for another model at the same count is no longer classified by the old rows. Covered by test_hardware_redetection_rereads_card_identities.
NilayYadav
left a comment
There was a problem hiding this comment.
Follow-up on 4e55c0705a: the (Python 3.13, a-k) failure on 5ec4f2ad was test_chat_text_encoding.py::test_python_children_are_told_to_emit_utf8 flagging nvidia.py:568 (the bus id probe child decoded as UTF-8 without utf8_child_env). Rerun of that guard plus the PR's GPU selection tests: 5ec4f2ad 1 failed, 332 passed; 4e55c0705a 333 passed, 0 failed. Note that 4e55c0705a carries [skip ci], so the upstream workflows have not run on the current head yet.
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
NilayYadav
left a comment
There was a problem hiding this comment.
Review round closed on 5dd39cdd18: the latest automated review of 5dd39cdd18 found no major issues, and every inline item from the earlier rounds is either fixed or answered on its thread.
- Fix commits since my first pass:
4e55c0705a(bus id probe child getsutf8_child_env; the encoding guard went from 1 failed / 332 passed on5ec4f2adto 333 passed) and8d88a8736a(ROCm settled before the auto gate, ordinal mapping retired on re-detection). On5dd39cdd18the guard plus the PR's GPU selection suites give 400 passed, 0 failed. - Before/after on 2x A10, one
/v1/modelsrefresh with a model on GPU 0: main leaves GPU 1 at 238 MiB (Settings > System "0.23 GiB used") and spawns 8nvidia-smiper refresh; this branch keeps GPU 1 at 3 MiB and spawns 1. - The pooled-thread concern on identical cards (card 0 wins, a worker left on GPU 1) did not change any plan on 2x L40S: 24 video download plans with GPU 1 at 32.8 GB used and GPU 0 idle were identical to the idle-host plan. Details are on that thread.
|
@codex review |
…es follow re-detection [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…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]>
…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>
Problem
#13928 added automatic GPU placement for image and video loads (#8235). On ordinary hosts (zero or one GPU, Apple Silicon, CPU, ROCm, identical cards) it changed behaviour that should have stayed as it was:
_device_targetpin, so every generation calledset_devicetwice instead of once.get_device_capabilityon 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.CUDA_DEVICE_ORDER=FASTEST_FIRSTand a numeric mask,auto_select_gpu_idsswitched to torch telemetry (get_device_propertiesandmem_get_infoper card, which leaves a CUDA context in the Studio process), even on identical cards where the nvidia-smi rows already name the right cards./v1/modelscatalog refresh ran live ranking once per media pick, including on single-GPU and homogeneous hosts.Fix
resolve_auto_cuda_ordinalreturns 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.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 aftervalidate_load_request. Explicitgpu_idskeep their original order and behaviour.auto_select_gpu_idsmaps 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.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
tests/test_media_auto_gpu_ordinary_host.pycounts 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)./v1/modelsmedia, 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 theggufmodule and fails the same way on main.