Repository navigation
[Studio] multi gpu finetuning/inference via "balanced_low0/sequential" device_map - #4602
Conversation
Datta0
commented
Mar 25, 2026
- multi gpu finetuning/inference via "balanced_low0/sequential" device_map
- API has support to choose a subset of the visible GPUs and so does the UI
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
/gemini review |
|
Warning Gemini is experiencing higher than usual traffic and was unable to create the review. Please try again in a few hours by commenting |
|
/gemini review |
|
Warning Gemini is experiencing higher than usual traffic and was unable to create the review. Please try again in a few hours by commenting |
… tests - balanced_low0 -> balanced_low_0 (transformers/accelerate rejects the old string) - get_parent_visible_gpu_ids() now handles UUID/MIG CUDA_VISIBLE_DEVICES gracefully instead of crashing on int() parse - _get_backend_visible_gpu_info() set() or None bug: empty set is falsy so CUDA_VISIBLE_DEVICES=-1 would disable filtering and report all GPUs - test_gpu_selection.py: add missing get_visible_gpu_utilization import and add required job_id arg to start_training() calls
|
Pushed a fix commit ( 1. transformers/accelerate only accept 2. UUID/MIG
3. allowed_indices = set(gpu_info["parent_visible_gpu_ids"]) or NoneWhen 4. Broken tests in
|
danielhanchen
left a comment
There was a problem hiding this comment.
Thank you for the PR! The goal of this PR is to add multi-GPU support to Unsloth Studio so users can select specific GPUs for training and inference. As a summary, this PR adds gpu_ids fields to training/inference API models, validates GPU selections against parent-visible devices, sets CUDA_VISIBLE_DEVICES in worker subprocesses, passes a computed device_map into all model loading paths, and adds GPU visibility/utilization endpoints.
I pushed a fix commit (c224f729) addressing the critical issues (see details below). Remaining items are lower priority but worth considering.
| Reviewers | Severity | Finding | Status |
|---|---|---|---|
| 8/8 | High | get_parent_visible_gpu_ids() crashes on UUID/MIG CUDA_VISIBLE_DEVICES values (bare int(), no try/except) |
Fixed in c224f72 |
| 4/8 | High | get_device_map() returned "balanced_low0" but transformers/accelerate only accept "balanced_low_0" |
Fixed in c224f72 |
| 6/8 | Medium | Tests don't run: missing get_visible_gpu_utilization import + missing job_id in start_training() calls |
Fixed in c224f72 |
| 5/8 | Medium | set([]) or None bug in _get_backend_visible_gpu_info() reports all GPUs when none should be visible |
Fixed in c224f72 |
| 3/8 | Medium | get_device_map() unconditionally returns balanced_low_0 when >1 GPU is visible, even for small models that fit on 1 GPU |
Open |
| 2/8 | Low | GGUF/llama.cpp inference path silently ignores gpu_ids |
Open |
| 2/8 | Low | _parse_smi_value duplicated as local function in get_visible_gpu_utilization() (identical to existing module-level one in get_gpu_utilization()) |
Open |
| 1/8 | Low | apply_gpu_ids() has redundant import os (already imported at module level) |
Open |
| 1/8 | Low | _get_backend_visible_gpu_info() shells out to nvidia-smi without checking DeviceType first (unlike get_visible_gpu_utilization() which short-circuits) |
Open |
Concrete suggestions for each remaining finding below.
|
|
||
| def get_device_map() -> str: | ||
| device = get_device() | ||
| if device == DeviceType.CUDA and get_visible_gpu_count() > 1: |
There was a problem hiding this comment.
[3/8 reviewers] get_device_map() unconditionally returns balanced_low_0 when multiple GPUs are visible, regardless of model size. A 1B model on a 4-GPU machine gets sharded across all 4 GPUs, adding inter-GPU communication overhead for no benefit.
Consider checking if the model actually needs multiple GPUs, or at least defaulting to sequential and only using balanced_low_0 when the user explicitly requests multi-GPU via gpu_ids with >1 GPU.
| if device == DeviceType.CUDA and get_visible_gpu_count() > 1: | |
| def get_device_map(gpu_ids=None) -> str: | |
| device = get_device() | |
| if device == DeviceType.CUDA and gpu_ids is not None and len(gpu_ids) > 1: | |
| return "balanced_low_0" | |
| return "sequential" |
This way single-GPU remains the default, and multi-GPU sharding only activates when the user explicitly selects multiple GPUs.
| None, | ||
| description = "KV cache data type for both K and V (e.g. 'f16', 'bf16', 'q8_0', 'q4_1', 'q5_1')", | ||
| ) | ||
| gpu_ids: Optional[List[int]] = Field( |
There was a problem hiding this comment.
[2/8 reviewers] gpu_ids is accepted here for all inference loads, but the GGUF/llama.cpp branch in routes/inference.py never forwards it to llama_backend.load_model(). If a user loads a GGUF model with gpu_ids=[0,1], the request succeeds silently but llama-server uses its own GPU auto-selection, ignoring the requested subset.
Either forward gpu_ids to the llama.cpp backend as well, or reject the combination early:
| gpu_ids: Optional[List[int]] = Field( | |
| gpu_ids: Optional[List[int]] = Field( | |
| None, | |
| description = "List of GPU indices to use (e.g. [0, 1]). If None, uses all visible GPUs. Note: not yet supported for GGUF models.", | |
| ) |
| "devices": [], | ||
| } | ||
|
|
||
| def _parse_smi_value(raw: str): |
There was a problem hiding this comment.
[2/8 reviewers] This _parse_smi_value local function is identical to the one already defined inside get_gpu_utilization() (around line 380). Having two copies means a fix to parsing logic (e.g. handling new nvidia-smi output formats) needs to be applied in two places.
Consider extracting it to a single module-level _parse_smi_value and reusing it in both functions.
| def _parse_smi_value(raw: str): | |
| parent_visible_ids = get_parent_visible_gpu_ids() |
(Move the _parse_smi_value definition to module level near the existing one in get_gpu_utilization, then reference it directly here instead of redefining.)
| return | ||
|
|
||
| global _visible_gpu_count | ||
| import os |
There was a problem hiding this comment.
[1/8 reviewers] Minor: import os is redundant here since this PR already adds import os at the module level (line 19).
| import os | |
| global _visible_gpu_count |
| from utils.cache_cleanup import clear_unsloth_compiled_cache | ||
|
|
||
|
|
||
| def _get_backend_visible_gpu_info() -> dict: |
There was a problem hiding this comment.
[1/8 reviewers] Minor: unlike get_visible_gpu_utilization() which short-circuits with if device != DeviceType.CUDA: return ..., this function always shells out to nvidia-smi even on CPU-only machines. On systems without nvidia-smi this is caught by the except Exception: pass, but it adds a subprocess timeout delay (10s) on every /api/system call on non-CUDA machines.
Consider adding an early DeviceType check:
from utils.hardware import get_device, DeviceType
if get_device() != DeviceType.CUDA:
return gpu_info # skip nvidia-smi on non-CUDA36af079 to
ef81606
Compare
…_ids edge case 1. vram_estimation.py: compute_lora_params now includes shared experts (n_shared_experts) alongside routed experts when computing MoE LoRA adapter parameters. Previously only n_experts were counted, causing the estimator to undercount adapter, optimizer, and gradient memory for DeepSeek/GLM-style models with shared experts. 2. hardware.py: _torch_get_per_device_info now uses mem_get_info (which reports system-wide VRAM usage) instead of memory_allocated (which only reports this process's PyTorch allocations). This prevents auto-selection from treating a GPU as mostly free when another process is consuming VRAM. Falls back to memory_allocated when mem_get_info is unavailable. 3. hardware.py: apply_gpu_ids([]) now returns early instead of setting CUDA_VISIBLE_DEVICES="" which would disable CUDA entirely. Empty list inherits the parent visibility, same as None. 4. hardware.py: Upgraded fallback_all GPU selection log from debug to warning so operators are notified when the model likely will not fit in available VRAM.
get_visible_gpu_utilization and get_backend_visible_gpu_info now catch OSError (nvidia-smi not found) and TimeoutExpired internally instead of relying on callers to wrap every invocation. Returns the standard available=False sentinel on failure so the torch-based fallback in hardware.py can take over.
danielhanchen
left a comment
There was a problem hiding this comment.
Thank you for the PR! The goal of this PR is to add multi-GPU finetuning and inference support to Unsloth Studio via balanced/sequential device_map, with API-level GPU selection and automatic VRAM-based auto-selection. As a summary, this PR threads a new gpu_ids parameter through training and inference APIs, adds GPU visibility/utilization endpoints, introduces VRAM estimation for MoE/MLA architectures, and applies per-subprocess CUDA_VISIBLE_DEVICES pinning.
| Reviewers | Severity | Finding |
|---|---|---|
| 4/8 | Medium | compute_lora_params did not include shared experts (n_shared_experts) alongside routed experts for MoE models -- underestimates adapter, optimizer, and gradient memory for DeepSeek/GLM-style models. Fixed in e0f522c. |
| 3/8 | Low | balanced_low_0 auto-selection mismatch: GPU 0 counted at full free capacity during selection but balanced_low_0 puts less weight on it. Acceptable for Studio's single-stream chat inference. |
| 2/8 | Medium | _torch_get_per_device_info used memory_allocated (process-only) instead of mem_get_info (system-wide), causing auto-selection to treat GPUs as free when other processes consume VRAM. Fixed in e0f522c. |
| 2/8 | Medium | apply_gpu_ids([]) set CUDA_VISIBLE_DEVICES="" which disables CUDA entirely. Now returns early for empty lists, inheriting parent visibility. Fixed in e0f522c. |
| 2/8 | Low | nvidia.py subprocess calls (get_visible_gpu_utilization, get_backend_visible_gpu_info) did not internally catch OSError/TimeoutExpired, relying on callers. Fixed in 2f9e754. |
| 2/8 | Low | fallback_all GPU selection logged at debug level; operators get no warning when model likely won't fit. Upgraded to logger.warning. Fixed in e0f522c. |
| 1/8 | Low | adamw_torch optimizer bytes set to 6 instead of 8 -- debatable since the comment says "fused, no master copy". Standard AdamW uses 8 bytes/param for two fp32 moment vectors. |
| 1/8 | Low | vram_estimation.py activation sizing uses classic QKV formula even for MLA models, though MLA actually uses less memory so this is a conservative overestimate. |
| 1/8 | Low | Per-GPU minimum VRAM check silently skipped when vram_breakdown is empty (fallback estimation path). |
Concrete suggestions for each finding above. All high/medium issues have been fixed and pushed directly. Remaining low-severity items are informational.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a comprehensive GPU management system, including automatic GPU selection based on VRAM estimation, support for explicit GPU ID selection, and enhanced hardware monitoring. The changes span across inference and training workflows, adding robust validation and error handling for GPU configurations. My feedback focuses on improving the robustness of the nvidia-smi output parsing by recommending the use of the csv module to correctly handle GPU names containing commas.
| parts = [p.strip() for p in line.split(",")] | ||
| if len(parts) < 3: | ||
| continue | ||
| try: | ||
| idx = int(parts[0]) | ||
| except (ValueError, TypeError): | ||
| continue | ||
| if visible_ordinals is not None and idx not in visible_ordinals: | ||
| continue | ||
| # Use split with limit to handle GPU names containing commas | ||
| name = parts[1] if len(parts) == 3 else ", ".join(parts[1:-1]) | ||
| try: | ||
| mem_total_mb = int(parts[-1]) | ||
| except (ValueError, TypeError): | ||
| continue |
There was a problem hiding this comment.
The current method of parsing the nvidia-smi CSV output using line.split(',') is not robust against GPU names that contain commas. While you've added a heuristic to handle this, a more reliable approach would be to use Python's built-in csv module, which correctly handles quoted fields.
This will prevent parsing errors for GPUs with names like "NVIDIA GeForce RTX 4090, Founder's Edition".
You'll need to add import csv and import io at the top of the file.
try:
# Use csv reader to handle names with commas
parts = next(csv.reader(io.StringIO(line)))
except StopIteration:
continue
if len(parts) < 3:
continue
try:
idx = int(parts[0])
name = parts[1]
mem_total_mb = int(parts[2])
except (ValueError, TypeError):
continue
if visible_ordinals is not None and idx not in visible_ordinals:
continue1. nvidia.py: get_primary_gpu_utilization now catches OSError and TimeoutExpired internally, matching the pattern already used in get_visible_gpu_utilization and get_backend_visible_gpu_info. All three nvidia-smi callers are now self-contained. 2. test_gpu_selection.py: Added _GpuCacheResetMixin that resets the module-level _physical_gpu_count and _visible_gpu_count caches in tearDown. Applied to all test classes that exercise GPU selection, device map, or visibility functions. This prevents stale cache values from leaking between tests and causing flaky results on machines with real GPUs.
1. hardware.py: get_gpu_utilization, get_visible_gpu_utilization, and
get_backend_visible_gpu_info now check result.get("available") before
returning the nvidia-smi result. When nvidia-smi is unavailable or
returns no data (e.g., containers without nvidia-smi, UUID/MIG masks),
the functions fall through to the torch-based fallback instead of
returning an empty result. This fixes a regression where the internal
exception handling in nvidia.py prevented the caller's except block
from triggering the fallback.
2. hardware.py: resolve_requested_gpu_ids now separates negative-ID
validation from physical upper-bound validation. The physical count
check is only enforced when it is plausibly a true physical count
(i.e., higher than the largest parent-visible ID), since
torch.cuda.device_count() under CUDA_VISIBLE_DEVICES returns the
visible count, not the physical total. The parent-visible-set check
remains authoritative in all cases. This prevents valid physical IDs
like [2, 3] from being rejected as "out of range" when nvidia-smi is
unavailable and CUDA_VISIBLE_DEVICES="2,3" makes torch report only
2 devices.
When CUDA_VISIBLE_DEVICES uses UUID or MIG identifiers, get_parent_visible_gpu_ids() returns [] because the tokens are non-numeric. The torch fallback in get_visible_gpu_utilization() and get_backend_visible_gpu_info() previously passed that empty list to _torch_get_per_device_info(), getting nothing back. Now both functions detect the empty-list case and fall back to enumerating torch-visible ordinals (0..device_count-1) with index_kind="relative". This means the UI and auto-selection still see real device data in Kubernetes, MIG, and Slurm-style UUID environments where nvidia-smi output cannot be mapped to physical indices. Updated test_uuid_parent_visibility to verify the new torch fallback path returns available=True with relative ordinals.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements multi-GPU selection logic for both inference and training backends. It introduces a sophisticated VRAM estimation module to automatically select the minimum number of GPUs required for a model, while also allowing for explicit GPU ID selection. The changes include updates to the orchestrator and worker processes to handle GPU isolation via environment variables, new API endpoints for monitoring GPU visibility, and support for Intel XPU hardware. Feedback was provided regarding the addition of a missing type hint for the gpu_ids parameter in the orchestrator's load_model method to maintain consistency across the codebase.
| load_in_4bit: bool = True, | ||
| hf_token: Optional[str] = None, | ||
| trust_remote_code: bool = False, | ||
| gpu_ids = None, |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a robust multi-GPU selection and VRAM estimation system for both inference and training backends. Key additions include a greedy auto-selection algorithm that picks the minimum number of GPUs required based on model architecture (supporting dense, MoE, and MLA models), a detailed VRAM estimation logic, and support for Intel XPU devices. The changes also refactor GPU visibility reporting into centralized utilities, add new API endpoints for GPU status, and include a comprehensive suite of unit and sandbox tests to ensure reliability across different hardware configurations. I have no feedback to provide.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff9be38c4f
ℹ️ 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".
| min_per_gpu_gb = vram_breakdown.get(min_key) | ||
| if min_per_gpu_gb is not None: | ||
| smallest_free = min(free_by_index[gpu_id] for gpu_id in selected) | ||
| per_gpu_fits = smallest_free >= min_per_gpu_gb | ||
|
|
There was a problem hiding this comment.
Enforce per-GPU fit for inference auto-selection
The per-GPU safety check is effectively disabled for inference: this branch only checks smallest_free >= min_per_gpu_N, but min_per_gpu_* is only populated in the training estimation path, so inference auto-selection can pass on aggregate usable_gb even when one chosen GPU cannot hold its shard. In heterogeneous-memory setups this leads to model load attempting CPU/disk offload and then failing via raise_if_offloaded, which breaks “auto” GPU selection for valid requests.
Useful? React with 👍 / 👎.
| metadata["selected_gpu_ids"] = parent_ids | ||
| return parent_ids, metadata | ||
|
|
||
| ranked = sorted(gpu_candidates, key = lambda item: (-item["free_gb"], item["index"])) |
There was a problem hiding this comment.
Order selected GPUs to match balanced_low_0 sharding
Auto-selection sorts GPUs by free VRAM descending and keeps that order in selected; that order is later written to CUDA_VISIBLE_DEVICES and used with inference device_map='balanced_low_0', which puts less weight on the first visible GPU and more on later ones. With uneven free VRAM, this causes heavier shards to land on lower-free GPUs, creating avoidable OOM/offload failures even when the same GPU set would fit if ordered differently.
Useful? React with 👍 / 👎.
…" device_map (unslothai#4602) * [WIP] balanced device map for studio * gpus as a request parameter * API for multi GPU stuff * return multi gpu util in new API * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use balanced_low0 instead of balanced * Use balanced_low0 instead of balanced * Fix device_map typo, UUID parsing crash, set() filter bug, and broken tests - balanced_low0 -> balanced_low_0 (transformers/accelerate rejects the old string) - get_parent_visible_gpu_ids() now handles UUID/MIG CUDA_VISIBLE_DEVICES gracefully instead of crashing on int() parse - _get_backend_visible_gpu_info() set() or None bug: empty set is falsy so CUDA_VISIBLE_DEVICES=-1 would disable filtering and report all GPUs - test_gpu_selection.py: add missing get_visible_gpu_utilization import and add required job_id arg to start_training() calls * Smart GPU determinism using estimates * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * disallow gpu selection for gguf for now * cleanup * Slightly larger baseline * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Treat empty list as auto * Verbose logging/debug * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Cleanup and revert unnecessary deletions * Cleanup excessive logs and guard against disk/cpu offload * auth for visibility API. cleanup redundant imports. Adjust QLoRA estimate * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * support for non cuda gpus * Fix multi-GPU auto-selection memory accounting The multi_gpu_factor was applied uniformly to all GPUs including the first one, which unfairly penalizes single-GPU capacity when transitioning to multi-GPU. This created a discontinuity where a model that barely fits 1 GPU would suddenly require 2 GPUs because the first GPU's free memory was discounted by 20%. Now the first GPU keeps its full free memory, and only additional GPUs have an overhead factor (0.85) applied to account for inter-GPU communication and sharding overhead. This gives more accurate auto-selection and avoids unnecessary multi-GPU for models that comfortably fit on one device. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add sandbox tests for multi-GPU selection logic 24 tests covering model size estimation, memory requirements, automatic GPU selection, device map generation, GPU ID validation, and multi-GPU overhead accounting. All tests use mocks so they run without GPUs on Linux, macOS, and Windows. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix reviewer findings: 4bit inference estimate, fallback, GGUF gpu_ids, retry 1. 4-bit inference now uses reduced memory estimate (model_size/3 + buffer) instead of the FP16 1.3x multiplier. This prevents over-sharding quantized models across unnecessary GPUs. 2. When model size estimation fails, auto_select_gpu_ids now falls back to all visible GPUs instead of returning None (which could default to single-GPU loading for an unknown-size model). 3. GGUF inference route now treats gpu_ids=[] as auto-selection (same as None) instead of rejecting it as an unsupported explicit request. 4. Training retry path for "could not get source code" now preserves the gpu_ids parameter so the retry lands on the same GPUs. 5. Updated sandbox tests to cover the new 4-bit inference estimate branch. * Remove accidentally added unsloth-zoo submodule * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix UUID/MIG visibility and update test expectations 1. nvidia.py: When CUDA_VISIBLE_DEVICES uses UUID/MIG tokens, the visibility APIs now return "unresolved" with empty device lists instead of exposing all physical GPUs. This prevents the UI from showing GPUs that the backend process cannot actually use. 2. test_gpu_selection.py: Updated test expectations to match the new multi-GPU overhead accounting (first GPU at full capacity, 0.85x for additional GPUs) and 4-bit inference memory estimation formula. All 60 tests now pass. * Add CPU/disk offload guard to audio inference path The audio model loading branch returned before the common get_offloaded_device_map_entries() check, so audio models loaded with a multi-GPU device_map that spilled layers to CPU/disk would be accepted instead of rejected. Now audio loads also verify no modules are offloaded. * Improve VRAM requirement estimates * Replace balanced_low_0 with balanced * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refine calculations for slightly easier nums * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * adjust estimates * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use nums instead of obj to avoid seralisation error * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Harden nvidia-smi parsing and fix fallback GPU list 1. nvidia.py: Wrap int() casts for GPU index and memory in try/except so MIG slices, N/A values, or unexpected nvidia-smi output skip the unparseable row instead of aborting the entire GPU list. 2. nvidia.py: Handle GPU names containing commas by using the last field as memory instead of a fixed positional index. 3. hardware.py: fallback_all now uses gpu_candidates (GPUs with verified VRAM data) instead of raw devices list, which could include GPUs with null VRAM that were excluded from the ranking. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * cleanup * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * consolidate raise_if_offload * Improve MoE support. Guard against nvidia-smi failures * Improve MoE support. Guard against nvidia-smi failures * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix shared-expert LoRA undercount, torch VRAM fallback, and apply_gpu_ids edge case 1. vram_estimation.py: compute_lora_params now includes shared experts (n_shared_experts) alongside routed experts when computing MoE LoRA adapter parameters. Previously only n_experts were counted, causing the estimator to undercount adapter, optimizer, and gradient memory for DeepSeek/GLM-style models with shared experts. 2. hardware.py: _torch_get_per_device_info now uses mem_get_info (which reports system-wide VRAM usage) instead of memory_allocated (which only reports this process's PyTorch allocations). This prevents auto-selection from treating a GPU as mostly free when another process is consuming VRAM. Falls back to memory_allocated when mem_get_info is unavailable. 3. hardware.py: apply_gpu_ids([]) now returns early instead of setting CUDA_VISIBLE_DEVICES="" which would disable CUDA entirely. Empty list inherits the parent visibility, same as None. 4. hardware.py: Upgraded fallback_all GPU selection log from debug to warning so operators are notified when the model likely will not fit in available VRAM. * Guard nvidia-smi subprocess calls against OSError and TimeoutExpired get_visible_gpu_utilization and get_backend_visible_gpu_info now catch OSError (nvidia-smi not found) and TimeoutExpired internally instead of relying on callers to wrap every invocation. Returns the standard available=False sentinel on failure so the torch-based fallback in hardware.py can take over. * Guard get_primary_gpu_utilization and reset GPU caches between tests 1. nvidia.py: get_primary_gpu_utilization now catches OSError and TimeoutExpired internally, matching the pattern already used in get_visible_gpu_utilization and get_backend_visible_gpu_info. All three nvidia-smi callers are now self-contained. 2. test_gpu_selection.py: Added _GpuCacheResetMixin that resets the module-level _physical_gpu_count and _visible_gpu_count caches in tearDown. Applied to all test classes that exercise GPU selection, device map, or visibility functions. This prevents stale cache values from leaking between tests and causing flaky results on machines with real GPUs. * Fix nvidia-smi fallback regression and physical GPU count validation 1. hardware.py: get_gpu_utilization, get_visible_gpu_utilization, and get_backend_visible_gpu_info now check result.get("available") before returning the nvidia-smi result. When nvidia-smi is unavailable or returns no data (e.g., containers without nvidia-smi, UUID/MIG masks), the functions fall through to the torch-based fallback instead of returning an empty result. This fixes a regression where the internal exception handling in nvidia.py prevented the caller's except block from triggering the fallback. 2. hardware.py: resolve_requested_gpu_ids now separates negative-ID validation from physical upper-bound validation. The physical count check is only enforced when it is plausibly a true physical count (i.e., higher than the largest parent-visible ID), since torch.cuda.device_count() under CUDA_VISIBLE_DEVICES returns the visible count, not the physical total. The parent-visible-set check remains authoritative in all cases. This prevents valid physical IDs like [2, 3] from being rejected as "out of range" when nvidia-smi is unavailable and CUDA_VISIBLE_DEVICES="2,3" makes torch report only 2 devices. * Fix UUID/MIG torch fallback to enumerate devices by ordinal When CUDA_VISIBLE_DEVICES uses UUID or MIG identifiers, get_parent_visible_gpu_ids() returns [] because the tokens are non-numeric. The torch fallback in get_visible_gpu_utilization() and get_backend_visible_gpu_info() previously passed that empty list to _torch_get_per_device_info(), getting nothing back. Now both functions detect the empty-list case and fall back to enumerating torch-visible ordinals (0..device_count-1) with index_kind="relative". This means the UI and auto-selection still see real device data in Kubernetes, MIG, and Slurm-style UUID environments where nvidia-smi output cannot be mapped to physical indices. Updated test_uuid_parent_visibility to verify the new torch fallback path returns available=True with relative ordinals. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add type hint for gpu_ids parameter in InferenceOrchestrator.load_model --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Han <[email protected]>