Skip to content

enable studio for intel GPU - #4724

Merged
oobabooga merged 41 commits into
unslothai:mainfrom
leizhenyuan:zhenyuan_enable_studio
Jul 24, 2026
Merged

oobabooga merged 41 commits into
unslothai:mainfrom
leizhenyuan:zhenyuan_enable_studio

Conversation

@leizhenyuan

Copy link
Copy Markdown
Contributor

No description provided.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements support for Intel XPU (Intel GPUs) across the backend by replacing hardcoded CUDA logic with hardware-agnostic utility functions. It adds XPU detection, utilization tracking via xpu-smi, and environment variable handling for device visibility. Feedback highlights a logic error in parsing xpu-smi output where memory utilization is incorrectly assigned to temperature, a lack of multi-GPU support in the monitoring command, and an inconsistency in the version reporting format for XPU.

Comment on lines +390 to +454
def _get_xpu_utilization() -> Dict[str, Any]:
"""Return a live snapshot of Intel XPU GPU utilization via ``xpu-smi`` or torch.xpu."""
try:
import subprocess

result = subprocess.run(
["xpu-smi", "dump", "-d", "0", "-m", "0,1,2,18"],
capture_output = True,
text = True,
timeout = 5,
)
if result.returncode == 0 and result.stdout.strip():
# xpu-smi dump outputs CSV: Timestamp, DeviceId, GPU Utilization (%), ...
lines = result.stdout.strip().splitlines()
for line in reversed(lines):
if line.startswith("Timestamp") or line.startswith("#"):
continue
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 4:
gpu_util = float(parts[2]) if parts[2] not in ("", "N/A") else None
temp = float(parts[3]) if parts[3] not in ("", "N/A") else None
break
else:
gpu_util = None
temp = None
else:
gpu_util = None
temp = None
except Exception:
gpu_util = None
temp = None

# Get VRAM from torch.xpu
vram_used_gb = None
vram_total_gb = None
try:
import torch

idx = torch.xpu.current_device()
props = torch.xpu.get_device_properties(idx)
vram_total_gb = round(props.total_memory / (1024**3), 2)
vram_used_gb = round(torch.xpu.memory_allocated(idx) / (1024**3), 2)
except Exception:
pass

vram_pct = (
round((vram_used_gb / vram_total_gb) * 100, 1)
if vram_used_gb is not None and vram_total_gb and vram_total_gb > 0
else None
)

has_any = any(v is not None for v in [gpu_util, temp, vram_used_gb])
if not has_any:
return {"available": False, "backend": "xpu"}

return {
"available": True,
"backend": "xpu",
"gpu_utilization_pct": gpu_util,
"temperature_c": temp,
"vram_used_gb": vram_used_gb,
"vram_total_gb": vram_total_gb,
"vram_utilization_pct": vram_pct,
"power_draw_w": None,
"power_limit_w": None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The _get_xpu_utilization function contains a logic error in metric parsing and lacks support for multi-GPU configurations:

  1. Metric Index Bug: With the requested metrics -m 0,1,2,18, the CSV output indices are: 2 (GPU Util), 3 (GPU Mem Util), 4 (GPU Temp), and 5 (GPU Power). The current code incorrectly assigns parts[3] (Memory Util) to temp.
  2. Hardcoded Device: It always queries physical device 0 via xpu-smi -d 0. This should be mapped from the current torch device index, especially when ZE_AFFINITY_MASK is active to restrict visibility.
  3. Power Data: Metric 18 (Power) is requested in the command but not parsed into the return dictionary.

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.

Valid on the old parser; the whole xpu-smi telemetry path was removed in the rebase, telemetry now goes through torch.xpu only.

Comment on lines +321 to +322
if hasattr(torch, "xpu") and torch.xpu.is_available():
versions["xpu"] = True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Setting versions["xpu"] = True is inconsistent with other entries in the versions dictionary, which typically contain version strings (e.g., from importlib.metadata). It would be more useful to provide a string indicating support or the version of the Intel Extension for PyTorch (IPEX) if applicable.

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.

Fixed in the rebase: versions['xpu'] is now the torch.version.xpu string, 'available' when present but unknown, None on failure.

@danielhanchen danielhanchen left a comment

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.

Thank you for the PR! The goal of this PR is to enable Unsloth Studio on Intel XPU GPUs. As a summary, this PR replaces hardcoded CUDA-only code paths in Studio audio inference, training, and cache clearing with device-agnostic helpers (get_torch_device_str(), clear_gpu_cache()), adds XPU detection/telemetry in hardware.py, and updates error messaging to mention Intel GPUs.

I pushed a commit fixing the issues below. Here is a summary of findings after reviewing:

Reviewers Severity Finding
10/10 High _get_xpu_utilization() used -m 0,1,2,18 which mapped parts[3] to temperature incorrectly -- it was GPU Memory Utilization, not temperature. Fixed to use -m 0,2,3 (Utilization, Power, Core Temperature) with correct column parsing.
10/10 High xpu-smi dump without -n 1 runs indefinitely until the timeout kills it. Added -n 1 to request exactly one sample.
10/10 Medium Hardcoded -d 0 in xpu-smi call ignores which device is active. Fixed to use torch.xpu.current_device().
10/10 Medium Dead code in get_visible_gpu_count() -- XPU re-check at line 1357 was unreachable because the XPU block above always returns first. Removed the dead branch.
8/10 Medium versions["xpu"] = True was a bool in a Dict[str, Optional[str]]. Changed to getattr(torch.version, "xpu", "available") to return the actual XPU version string.
7/10 Low power_draw_w was always None in the returned dict even though power data was being requested from xpu-smi. Now correctly populated.

All fixes are in the latest commit. Concrete suggestions for each finding above.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for Intel XPU (Intel GPUs) across the inference and training modules by abstracting device-specific logic into utility functions like get_torch_device_str and clear_gpu_cache. Key changes include updated hardware detection, XPU utilization monitoring via xpu-smi, and safety measures to disable multiprocessing on XPU devices to prevent memory context corruption. Feedback is provided regarding the use of broad, silent exception handling in the XPU utilization logic, which should be refined to include explicit error handling and logging.

Comment on lines +413 to +418
result = subprocess.run(
["xpu-smi", "dump", "-d", str(dev_idx), "-m", "0,2,3", "-n", "1"],
capture_output = True,
text = True,
timeout = 10,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The subprocess.run call for xpu-smi might raise a FileNotFoundError. While the broad except Exception block at line 430 catches this, it is better to explicitly handle FileNotFoundError. Additionally, ensure the exception is logged (even at a debug level) rather than silently ignored, as per repository rules to aid in future debugging.

References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

The xpu-smi subprocess call was removed in the rebase, so this path no longer exists.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@savvadesogle

Copy link
Copy Markdown

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for Intel XPU hardware by abstracting device-specific logic into hardware-agnostic utility functions like get_torch_device_str and clear_gpu_cache. Key updates include enhanced hardware detection, XPU utilization tracking via xpu-smi, and improved handling of device visibility and multiprocessing on Intel GPUs. Review feedback focuses on improving code organization by moving local imports to the module level and enhancing observability by logging exceptions in broad try-except blocks instead of using silent pass statements.

Comment on lines +1646 to +1647
from utils.hardware import get_torch_device_str

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

For better code organization and to avoid repeated imports within a function, please move the import of get_torch_device_str to the top of the file. You can add it to the existing from utils.hardware import ... block at line 21.

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.

The in-function imports were dropped in the rebase; the audio path now derives the autocast device from model.device.

Comment on lines +1441 to +1442
from utils.hardware import clear_gpu_cache

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To improve code organization and adhere to Python's best practices, please move this import to the top of the file. This will make dependencies clearer and avoid re-importing within methods.

This also applies to the local imports of get_torch_device_str on lines 3020 and 3096.

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.

llama_cpp.py was reset to main in the rebase; the PR no longer touches this file. Intel GGUF inference is the Vulkan build from #5819.

Comment thread studio/backend/core/training/trainer.py Outdated
Comment on lines +1535 to +1536
from utils.hardware import get_torch_device_str

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To improve code organization and avoid redundant imports, please move the import of get_torch_device_str to the top of the file. It can be added to the existing from utils.hardware import ... block at line 36.

Additionally, clear_gpu_cache is already imported at the top, so its local imports (e.g., at lines 1713, 1945, and 2162) can be removed. This change should be applied to all local imports from utils.hardware throughout this file.

References
  1. Avoid redundant inline imports if the module is already imported at the top of the file.

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.

Fixed in the rebase: the local imports were dropped; clear_gpu_cache comes from the module-level utils.hardware import.

Comment on lines +437 to +438
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This broad except Exception: pass block silently ignores all errors that might occur when running xpu-smi, including timeouts or parsing errors. This can make debugging difficult. Please log the exception to aid in future troubleshooting, even if it's at a debug level. This aligns with the general rule to avoid silent exception handlers.

Suggested change
except Exception:
pass
except Exception as e:
logger.debug("Failed to get XPU utilization from xpu-smi: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

The xpu-smi block and its silent except were removed in the rebase.

Comment on lines +450 to +451
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Similar to the xpu-smi call, this except Exception: pass block silently ignores errors when querying VRAM from torch.xpu. Logging these errors would be beneficial for debugging potential issues with the Intel GPU tooling or PyTorch's XPU support.

Suggested change
except Exception:
pass
except Exception as e:
logger.debug("Failed to get XPU VRAM info from torch.xpu: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

That VRAM block was removed; the surviving per-device query logs failures at debug level in _torch_get_per_device_info.

import torch

_visible_gpu_count = torch.xpu.device_count()
except Exception:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This except Exception: block silently catches any error from torch.xpu.device_count() and proceeds to a fallback. To improve debuggability, please log the exception that was caught. This will help diagnose issues if torch.xpu is available but device_count() fails unexpectedly.

For example:

        except Exception as e:
            logger.debug("torch.xpu.device_count() failed: %s", e)
            if xpu_visible:
                # ...
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

Fixed in the rebase: the except now logs the device_count failure at debug level before falling back to mask parsing.

Adds first-class Intel XPU support to unsloth studio across hardware
detection, GPU selection, visibility reporting, telemetry, cache
clearing, OOM messaging, and the DAC autocast path, matching feature
parity with the existing CUDA and ROCm backends. This is a rebased
linear version of the leizhenyuan/zhenyuan_enable_studio branch with
three rounds of review-loop fixes layered in.

Originally authored by leizhenyuan. Rebased and review fixes by
danielhanchen.

Highlights:

hardware.py
  - detect_hardware: promote DeviceType.XPU when torch.xpu is
    available and CUDA is not, preserving CPU / MLX / ROCm paths.
  - New helpers: _parse_ze_mask_roots, _resolve_xpu_smi_device_id,
    _get_xpu_utilization (xpu-smi -m 0,1,3 with cached binary path
    resolution and robust N/A parsing).
  - _get_parent_visible_gpu_spec adds an XPU branch that honors
    ZE_AFFINITY_MASK, including subdevice syntax (0.0,0.1) and
    wildcard / unparseable masks, and mirrors the CUDA UUID / MIG
    path by returning numeric_ids=None for subdevice masks so the
    rest of the stack enumerates torch-visible ordinals and can
    still shard.
  - _backend_visible_devices_env routes XPU through ZE_AFFINITY_MASK
    so /system-info and get_backend_visible_gpu_info report the
    active mask instead of a stale or None CUDA_VISIBLE_DEVICES.
  - get_visible_gpu_utilization and get_backend_visible_gpu_info
    short-circuit on "no devices visible" masks (ZE_AFFINITY_MASK=""
    or CUDA_VISIBLE_DEVICES="" / "-1") so the torch-ordinal
    enumeration fallback does not report hidden devices.
  - get_visible_gpu_count and get_device_map add XPU branches that
    prefer torch.xpu.device_count() and fall back to ZE mask roots
    (str.isdecimal() to reject Unicode superscripts).
  - apply_gpu_ids routes XPU through ZE_AFFINITY_MASK but leaves
    inherited CUDA_VISIBLE_DEVICES alone so hybrid NVIDIA+Intel
    hosts that hid CUDA via CUDA_VISIBLE_DEVICES="" stay on XPU.
  - auto_select_gpu_ids and prepare_gpu_selection allow XPU in the
    accelerator guard and use "non_accelerator" as the selection
    mode label for CPU / MLX.
  - resolve_requested_gpu_ids error message covers "CUDA and Intel
    XPU devices" and mentions ZE_AFFINITY_MASK for XPU.
  - clear_gpu_cache XPU branch guards synchronize and empty_cache
    with hasattr so older torch-xpu builds do not propagate
    AttributeError.
  - dataset_map_num_proc returns None only when
    torch.xpu.is_initialized exists and returns True, so older
    torch-xpu builds still get pre-init CPU dataset parallelism.
  - get_package_versions reports torch.version.xpu alongside cuda.

utils/utils.py
  - format_error_message recognises Intel XPU OOM strings including
    out_of_device_memory, out_of_host_memory, memory allocation
    failed, and bare MemoryError instances, labelling messages as
    "Intel GPU" when DeviceType is XPU.

core/inference/inference.py
  - _generate_dac derives autocast device from model.device.type
    instead of the global backend, clamps to cuda/xpu/mps/cpu, and
    falls through to nullcontext on cpu/xpu float32 (unsupported by
    torch.amp.autocast).

core/inference/llama_cpp.py
  - _start_process pins the llama-server subprocess via
    ZE_AFFINITY_MASK on XPU hosts and CUDA_VISIBLE_DEVICES elsewhere
    so SYCL builds of llama-server respect the selected GPUs.
  - unload_model clears the XPU cache via the backend-neutral
    clear_gpu_cache helper.
  - init_audio_codec / generate_audio_response retain the pre-PR
    "cuda if torch.cuda.is_available() else cpu" fallback for the
    SNAC / BiCodec / DAC codecs because those upstream codecs are
    not yet validated on Intel XPU.

core/training/trainer.py
  - clear_gpu_cache is hoisted to the module-level import block.
  - _preprocess_snac_dataset / _preprocess_bicodec_dataset /
    _preprocess_dac_dataset keep the pre-PR CPU fallback on
    non-CUDA hosts for Spark-TTS BiCodec, SNAC, and OuteTTS DAC /
    Whisper preprocessing.

tests/test_gpu_selection.py
  - Replace TestXpuRejection with TestXpuSelection (positive tests
    for auto_select_gpu_ids and prepare_gpu_selection on XPU).
  - Update non-accelerator rejection assertion to the new
    "CUDA and Intel XPU" wording.
  - Update test_explicit_ids_are_rejected_for_uuid_parent_visibility
    regex to match the broadened "uses non-numeric or subdevice"
    error message.

tests/test_gpu_selection_sandbox.py
  - Rename test_non_cuda_returns_none to
    test_non_accelerator_returns_none and assert
    selection_mode="non_accelerator".
@danielhanchen
danielhanchen force-pushed the zhenyuan_enable_studio branch from 9ce735d to b759a03 Compare April 11, 2026 12:50
@danielhanchen danielhanchen added auto-approved Auto-review approved the PR and removed auto-reviewing Auto-review in progress auto-approved Auto-review approved the PR labels Apr 11, 2026
danielhanchen and others added 4 commits April 16, 2026 07:24
…vation, FLAT hierarchy, backend-aware GGUF discovery

Six targeted changes following the 10-reviewer pass on this PR:

1. studio/backend/core/inference/llama_cpp.py
   Remove env.pop("CUDA_VISIBLE_DEVICES", None) in the XPU llama-server
   spawn branch. The pop contradicted the documented preservation in
   apply_gpu_ids() for hybrid NVIDIA+Intel hosts where the parent sets
   CUDA_VISIBLE_DEVICES="" to force Studio onto Intel/SYCL. Added a
   comment referencing that design note.

2. studio/backend/core/inference/llama_cpp.py
   Make _get_gpu_free_memory backend-aware. NVIDIA keeps the cheap
   nvidia-smi fast path; AMD ROCm and Intel XPU fall through to
   get_visible_gpu_utilization so GGUF offload selection has per-GPU
   free memory on all backends, not just NVIDIA. Returns an empty list
   only when no telemetry is available.

3. studio/backend/utils/hardware/hardware.py
   detect_hardware now honors a non-empty ZE_AFFINITY_MASK as an
   explicit XPU hint. On a hybrid host with both torch.cuda and
   torch.xpu available, ZE_AFFINITY_MASK=... picks XPU before CUDA so
   users can pin Intel without also setting CUDA_VISIBLE_DEVICES="".

4. studio/backend/utils/hardware/hardware.py
   Add _xpu_hierarchy_is_composite() and gate the Level Zero mask
   parsing on it. In the FLAT hierarchy (oneAPI 2024+ default)
   numeric ZE_AFFINITY_MASK entries are tile or device handles, not
   root GPU IDs. _get_parent_visible_gpu_spec now returns
   supports_explicit_gpu_ids=False in FLAT so explicit gpu_ids are
   rejected; _resolve_xpu_smi_device_id returns None so callers skip
   "xpu-smi -d <wrong_tile>" and fall back to torch.xpu VRAM
   telemetry. COMPOSITE retains the original root-ID mapping.

5. studio/backend/utils/hardware/hardware.py
   Conservative XPU used_gb fallback. When torch.xpu lacks
   mem_get_info, _torch_get_per_device_info now returns used_gb=None
   instead of torch.xpu.memory_allocated (process-local and
   misleading for multi-tenant placement). get_visible_gpu_utilization
   guards against None during percent computation; downstream
   auto_select_gpu_ids already filters None entries.

6. studio/backend/models/inference.py, studio/backend/models/training.py
   gpu_ids Field descriptions now mention the Intel XPU
   ZE_AFFINITY_MASK subdevice and FLAT-hierarchy restrictions
   alongside the existing CUDA UUID/MIG note.

Testing:

- 96 PR-authored tests still pass (test_gpu_selection,
  test_gpu_selection_sandbox, test_utils).
- 234 additional simulation tests across two isolated uv venvs
  cover fix-fix interactions, malformed inputs, cross-platform
  behavior (Linux, macOS, Windows), real subprocess env propagation,
  JSON/Pydantic schema roundtrips, concurrency, and fuzz.
- 6/6 CUDA scenarios on 8xB200 hardware are byte-identical to the
  pre-fix baseline. Zero CUDA regression.
- ROCm, MLX, and CPU regression tests all pass. AMD HIP_VISIBLE_DEVICES
  and ROCR_VISIBLE_DEVICES propagation is unchanged.

Backend support after these changes: NVIDIA CUDA, AMD ROCm, Intel XPU
(both COMPOSITE and FLAT hierarchies), CPU, and Apple Silicon MLX.
…s, FLAT numerics

Follow-up to 6c55664 addressing the four findings from the second
10-reviewer pass. Each fix is narrow and additive; the CUDA, ROCm,
MLX, and CPU paths remain byte-identical to the pre-round-2 baseline.

A. studio/backend/core/inference/llama_cpp.py
   Replace `dict.get(a) or dict.get(b)` with explicit `is None`
   fallbacks when reading vram_total_gb / vram_used_gb in the generic
   free-memory path. An idle GPU with vram_used_gb=0.0 was being
   treated as missing telemetry and dropped, which pushed GGUF
   placement into the non-placement fallback whenever the best free
   card was fully idle. 9/10 reviewers in the round-2 pass flagged
   this; every suggestion was the same patch.

B. studio/backend/utils/hardware/hardware.py
   Tighten the ZE_AFFINITY_MASK -> XPU detection hint from
   "any non-empty mask wins" to "non-empty mask plus one of:
   CUDA_VISIBLE_DEVICES explicitly hidden (empty / -1), or
   UNSLOTH_FORCE_XPU=1, or CUDA simply not available". Prevents a
   stray ZE_AFFINITY_MASK=0 inherited from unrelated Intel tooling
   from silently flipping existing hybrid CUDA deployments onto XPU.
   Intel-only hosts are unaffected (CUDA unavailable -> hint is
   honoured).

C. studio/backend/core/inference/llama_cpp.py
   Refuse to use device indices returned from
   get_visible_gpu_utilization when index_kind != "physical".
   Relative ordinals (reported for subdevice / wildcard / UUID
   parent masks) are not safe to round-trip back into
   ZE_AFFINITY_MASK / CUDA_VISIBLE_DEVICES; returning [] lets the
   launcher skip placement and inherit the parent's visibility
   unchanged.

D. studio/backend/utils/hardware/hardware.py
   Relax _get_parent_visible_gpu_spec in FLAT hierarchy. Per Intel's
   Level Zero device-hierarchy docs, numeric ZE_AFFINITY_MASK entries
   in FLAT mode ARE stable flat ordinals that torch.xpu honours
   1-to-1 with the child process. Previously we blanket-rejected all
   FLAT numeric masks, which meant Studio could not do XPU
   auto-selection under the default oneAPI configuration. Now:
     - FLAT + numeric mask -> accept as numeric_ids
     - FLAT + unset mask -> expose range(device_count)
     - FLAT + subdevice "N.M" -> reject (invalid syntax in FLAT)
     - FLAT + wildcard / non-numeric -> reject
     - COMPOSITE semantics unchanged (numeric -> root IDs)
   _resolve_xpu_smi_device_id continues to return None in FLAT
   because xpu-smi -d addresses root IDs, not flat ordinals; the
   telemetry path falls back to torch.xpu VRAM.

Testing:

- 96 PR-authored tests still pass
  (test_gpu_selection_sandbox, test_gpu_selection, test_utils).
- 264 simulation tests pass across two isolated uv venvs. The
  round-2 tests include explicit coverage for:
    Fix A: idle GPU preserved, None still skipped, 0.0 total ok
    Fix B: bare mask on hybrid -> CUDA wins; CVD="" or "-1" hint ->
           XPU; UNSLOTH_FORCE_XPU=1 -> XPU; CUDA unavailable -> XPU;
           UNSLOTH_FORCE_XPU=0 (literal) not activated
    Fix C: relative ordinals not returned; physical ordinals
           returned; missing index_kind treated as physical
    Fix D: FLAT numeric accepted; FLAT unset auto-enumerated;
           FLAT subdevice rejected; FLAT wildcard rejected;
           xpu-smi resolver still None in FLAT; COMPOSITE unchanged
- 6/6 CUDA scenarios on 8xB200 remain byte-identical to baseline.
- ROCm, MLX, CPU regression tests all pass.
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces comprehensive support for Intel XPU (Intel GPUs) across the backend, including inference, training, and hardware utility modules. Key updates include backend-aware GPU memory querying, support for the ZE_AFFINITY_MASK environment variable for device visibility, and integrated telemetry via xpu-smi. Additionally, the changes address XPU-specific constraints in multiprocessing and improve error reporting for device memory issues. Feedback was provided regarding the logic for calculating visible GPU counts when parsing ZE_AFFINITY_MASK, specifically to better distinguish between wildcard and invalid masks.

Comment on lines +1802 to +1807
roots = _parse_ze_mask_roots(xpu_visible)
# Non-digit wildcards (e.g. "*") yield an empty roots list;
# treat those as "all physical XPUs visible".
_visible_gpu_count = (
len(set(roots)) if roots else get_physical_gpu_count()
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The fallback logic for _visible_gpu_count when roots is empty is incorrect. It treats any mask that results in an empty roots list (like invalid masks ",," or non-numeric wildcards *) as a signal to use all physical GPUs. This is only correct for a wildcard like "*". For invalid or empty-like masks, the count should be 0.

This can lead to an incorrect number of visible GPUs being reported, potentially causing issues with resource allocation.

I suggest refining the logic to explicitly handle the wildcard case and treat other non-parsing masks as yielding zero devices.

Suggested change
roots = _parse_ze_mask_roots(xpu_visible)
# Non-digit wildcards (e.g. "*") yield an empty roots list;
# treat those as "all physical XPUs visible".
_visible_gpu_count = (
len(set(roots)) if roots else get_physical_gpu_count()
)
# Non-digit wildcards (e.g. "*") should be treated as "all physical XPUs visible",
# while other invalid or empty masks should result in 0.
if xpu_visible.strip() == "*":
_visible_gpu_count = get_physical_gpu_count()
else:
roots = _parse_ze_mask_roots(xpu_visible)
_visible_gpu_count = len(set(roots))

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.

Fixed in the rebase: '*' maps to the physical count and unparseable masks count as 0 visible devices.

danielhanchen and others added 2 commits April 16, 2026 08:34
…rd fallback

Follow-up to eebf077 addressing three findings from the third
10-reviewer pass and Gemini review 4119296322. All changes are in
studio/backend/utils/hardware/hardware.py; CUDA/ROCm/MLX/CPU paths
remain byte-identical to the pre-round-3 baseline.

E. _get_parent_visible_gpu_spec in FLAT hierarchy now refuses explicit
   gpu_ids. Per Intel's "flattening-gpu-tile-hierarchy" doc and the
   Level Zero spec, numeric ZE_AFFINITY_MASK entries in FLAT mode are
   tile / device-handle ordinals, not physical GPU IDs -- accepting
   them as "Physical GPU indices" breaks the API contract documented
   in models/inference.py and models/training.py. numeric_ids is still
   populated so display and auto-selection enumerate devices, but
   supports_explicit_gpu_ids is False in FLAT regardless of mask
   presence. Users who need explicit tile-level selection can opt in
   with ZE_FLAT_DEVICE_HIERARCHY=COMPOSITE. COMPOSITE semantics are
   unchanged -- numeric masks still resolve to root GPU IDs. Flagged
   by 6/10 reviewers in the third pass.

F. detect_hardware restructured so UNSLOTH_FORCE_XPU=1 is a standalone
   trigger. Previously the outer "if ze_mask:" gate swallowed the
   force knob unless ZE_AFFINITY_MASK was also set, which meant the
   documented override did not work on a common hybrid NVIDIA+Intel
   scenario. Now the preference check is:
     prefer_xpu = force_xpu or (ze_mask and (cuda_hidden or cuda_unavailable))
   The "stray ZE_AFFINITY_MASK flips CUDA to XPU" protection from
   round 2 is preserved: a bare mask without CUDA-hidden still keeps
   CUDA. Flagged by 3/10 reviewers in the third pass.

G. get_visible_gpu_count torch-fallback path: only "*" wildcard counts
   as "all physical XPUs visible". Other non-parseable masks (",,,",
   "GPU-uuid", random garbage) now return 0 visible devices rather
   than silently exposing the full fleet. The happy path (torch.xpu
   .device_count() succeeds) is unchanged. Suggested by the Gemini
   review bot.

Testing:

- 96 PR-authored tests still pass
  (test_gpu_selection_sandbox, test_gpu_selection, test_utils).
- 284 simulation tests pass across two isolated uv venvs. New
  test_round3_fixes.py covers each round-3 finding explicitly:
    Fix E: FLAT rejects gpu_ids via prepare_gpu_selection; FLAT unset
           also rejects; COMPOSITE still accepts; FLAT auto-select
           gracefully falls to inherit_parent_visible mode.
    Fix F: force_xpu alone picks XPU; force_xpu=0 does not;
           no-xpu-torch falls back to CUDA; force_xpu + mask works;
           CVD="" + mask path unchanged; bare mask still keeps CUDA.
    Fix G: "*" -> all_physical; ",,," -> 0; "GPU-abc" -> 0;
           "0,1,*" -> 2 (partial wildcard); subdevice -> 1 root;
           no mask unchanged; torch happy path bypasses fallback.
- 6/6 CUDA scenarios on 8xB200 byte-identical to pre-fix baseline.
- ROCm, MLX, CPU regression tests all pass.
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements comprehensive support for Intel XPU (Intel GPUs) across the inference and training backends. Key updates include backend-aware hardware detection, GPU utilization monitoring via xpu-smi, and the correct application of ZE_AFFINITY_MASK for device pinning. The changes also refine autocast logic for diverse hardware and update error handling to recognize XPU-specific memory issues. The review feedback focuses on improving observability by replacing silent exception handlers with debug logging in the hardware utility module.

Comment on lines +247 to +248
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This broad except Exception: pass could hide unexpected errors during the cache clearing process. It's better to log the exception, even at a debug level, to aid in future debugging. This aligns with the general rule of avoiding silent exception handlers.

Suggested change
except Exception:
pass
except Exception as e:
logger.debug("Failed to clear XPU cache: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

Fixed in the rebase: the XPU cache-clear except logs at debug level and the calls are hasattr-guarded.

Comment on lines +680 to +681
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Silently passing on all exceptions here can obscure issues with xpu-smi. It would be beneficial to log the exception at a debug level to help with troubleshooting, in line with the general rule to avoid silent exception handlers.

Suggested change
except Exception:
pass
except Exception as e:
logger.debug("xpu-smi query failed: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

The xpu-smi query was removed in the rebase.

Comment on lines +696 to +697
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This except Exception: pass block could hide errors when querying VRAM information from torch.xpu. Logging the exception at a debug level would be helpful for diagnostics, following the general rule to avoid silent exception handlers.

Suggested change
except Exception:
pass
except Exception as e:
logger.debug("torch.xpu VRAM query failed: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

That block was removed; the surviving query path logs its exceptions.

Comment on lines +1798 to +1817
except Exception:
if xpu_visible:
# Fallback: count unique root device IDs from the mask.
# ZE_AFFINITY_MASK can use "device.subdevice" notation,
# so "0.0,0.1" is 1 root device, not 2. Without torch we
# cannot know which hierarchy mode is active, so fall back
# to root-device counting (the more conservative choice).
if xpu_visible == "*":
# Documented wildcard: all physical XPUs visible.
_visible_gpu_count = get_physical_gpu_count()
else:
roots = _parse_ze_mask_roots(xpu_visible)
# Non-parseable masks (",,,", "GPU-abc", etc.) yield an
# empty roots list and are treated as 0 visible devices,
# not "all visible" -- we have no evidence the user
# intended to expose the whole fleet.
_visible_gpu_count = len(set(roots))
else:
_visible_gpu_count = get_physical_gpu_count()
return _visible_gpu_count

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The except Exception block here correctly implements fallback logic, but it doesn't log the exception that occurred. It would be valuable for debugging to log the error from torch.xpu.device_count() at a debug level before proceeding with the fallback.

Suggested change
except Exception:
if xpu_visible:
# Fallback: count unique root device IDs from the mask.
# ZE_AFFINITY_MASK can use "device.subdevice" notation,
# so "0.0,0.1" is 1 root device, not 2. Without torch we
# cannot know which hierarchy mode is active, so fall back
# to root-device counting (the more conservative choice).
if xpu_visible == "*":
# Documented wildcard: all physical XPUs visible.
_visible_gpu_count = get_physical_gpu_count()
else:
roots = _parse_ze_mask_roots(xpu_visible)
# Non-parseable masks (",,,", "GPU-abc", etc.) yield an
# empty roots list and are treated as 0 visible devices,
# not "all visible" -- we have no evidence the user
# intended to expose the whole fleet.
_visible_gpu_count = len(set(roots))
else:
_visible_gpu_count = get_physical_gpu_count()
return _visible_gpu_count
except Exception as e:
logger.debug("torch.xpu.device_count() failed, falling back to mask parsing: %s", e)
if xpu_visible:
# Fallback: count unique root device IDs from the mask.
# ZE_AFFINITY_MASK can use "device.subdevice" notation,
# so "0.0,0.1" is 1 root device, not 2. Without torch we
# cannot know which hierarchy mode is active, so fall back
# to root-device counting (the more conservative choice).
if xpu_visible == "*":
# Documented wildcard: all physical XPUs visible.
_visible_gpu_count = get_physical_gpu_count()
else:
roots = _parse_ze_mask_roots(xpu_visible)
# Non-parseable masks (",,,", "GPU-abc", etc.) yield an
# empty roots list and are treated as 0 visible devices,
# not "all visible" -- we have no evidence the user
# intended to expose the whole fleet.
_visible_gpu_count = len(set(roots))
else:
_visible_gpu_count = get_physical_gpu_count()
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

Fixed in the rebase: the fallback logs the device_count failure at debug level.

Comment on lines 1838 to 1839
except Exception:
_visible_gpu_count = get_physical_gpu_count()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Similar to other fallbacks in this file, it would be beneficial to log the exception from torch.cuda.device_count() at a debug level before falling back to get_physical_gpu_count(). This aids in debugging scenarios where the PyTorch call fails unexpectedly.

Suggested change
except Exception:
_visible_gpu_count = get_physical_gpu_count()
except Exception as e:
logger.debug("torch.cuda.device_count() failed, falling back to physical count: %s", e)
_visible_gpu_count = get_physical_gpu_count()
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

This fallback is main's original CUDA tail kept byte-identical on purpose; the XPU path this PR adds logs its failures. Logging changes to the shared CUDA fallback are out of scope for this PR.

Comment on lines +2077 to +2080
except Exception:
# Treat a failing probe as "runtime not touched yet" so
# pre-init CPU preprocessing can still parallelize.
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The comment explains the fallback behavior, but silently passing on the exception could hide underlying issues with the torch.xpu.is_initialized() call. Logging the exception at a debug level would provide more insight during troubleshooting, while still allowing the safe fallback to proceed.

Suggested change
except Exception:
# Treat a failing probe as "runtime not touched yet" so
# pre-init CPU preprocessing can still parallelize.
pass
except Exception as e:
# Treat a failing probe as "runtime not touched yet" so
# pre-init CPU preprocessing can still parallelize.
logger.debug("torch.xpu.is_initialized() check failed, assuming not initialized: %s", e)
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

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.

Fixed in the rebase: the is_initialized probe failure is logged at debug level before the safe fallback.

Gemini's fourth review pass (pullrequestreview-4119484559) flagged six
bare `except Exception: pass` blocks in hardware.py where silent failures
could hide real driver or runtime problems. Each site now logs at DEBUG
level with the exception message, so operators have a diagnostic trail
when something goes wrong, while the control flow stays unchanged and the
same fallback path is taken:

1. clear_gpu_cache() XPU branch: log "Failed to clear XPU cache"
2. _resolve_xpu_smi_device_id(): log "torch.xpu.current_device() probe failed"
3. _get_xpu_utilization() xpu-smi call: log "xpu-smi query failed"
4. _get_xpu_utilization() torch.xpu VRAM query: log "torch.xpu VRAM query failed"
5. get_visible_gpu_count() torch.xpu fallback: log and still count mask roots
6. get_visible_gpu_count() torch.cuda fallback: log and still use physical count
7. dataset_map_num_proc() is_initialized probe: log "torch.xpu.is_initialized() probe failed"

These are logging-only edits; every test in the PR's own suite, the two
simulation harnesses (284 tests), and the 8x B200 CUDA behavior matrix
(6/6 scenarios byte-identical) pass unchanged.

@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: 6df063f23d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

# deliberately hidden CUDA and leave the ZE mask unnarrowed.
_cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
_cuda_hidden = _cvd is not None and _cvd.strip() in ("", "-1")
_xpu_hinted = bool(os.environ.get("ZE_AFFINITY_MASK")) and _cuda_hidden

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 Keep CUDA hidden for XPU workers without a ZE mask

When a hybrid/dual CUDA+XPU build is launched with CUDA_VISIBLE_DEVICES="" to force the normal detect_hardware() fallback onto XPU, but no ZE_AFFINITY_MASK is set, this pre-detect branch does not treat the hidden-CUDA state as XPU unless a ZE mask is already present. In COMPOSITE mode or with explicit XPU gpu_ids, the worker therefore writes the resolved XPU IDs into CUDA_VISIBLE_DEVICES, re-exposes CUDA, and the subsequent detection can select/run on CUDA instead of narrowing XPU. Fresh evidence beyond the earlier ZE-mask fix is that the fallback XPU path above still selects XPU when CUDA is hidden even without a ZE mask.

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.

Fixed in 202a1b4 two ways. Root cause: the real worker flows no longer guess at all -- the spawning parent records its detected backend in the worker config (device_backend) and apply_gpu_ids trusts it, so the mask target matches detection by construction. For direct callers, the heuristic now prefers XPU on hidden CUDA even without a ZE mask, matching detection's fall-through. Regression-tested.

Comment on lines +2320 to +2321
if os.environ.get("UNSLOTH_FORCE_XPU") == "1":
_is_xpu = _xpu_build

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 Follow CUDA fallback when forced XPU has no device

When UNSLOTH_FORCE_XPU=1 is set on a host where the torch build has XPU symbols but torch.xpu.is_available() is false, detect_hardware() deliberately falls through to CUDA, but this pre-detect worker path routes the mask to ZE_AFFINITY_MASK based only on the build flag. In that CUDA-fallback case explicit/auto CUDA gpu_ids never reach CUDA_VISIBLE_DEVICES, so the worker can run on all parent-visible CUDA GPUs instead of the selected set. Fresh evidence beyond the earlier fix is that the current predicate still does not mirror detect_hardware()'s availability check.

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.

Fixed in 202a1b4: the parent's detected backend is propagated to the worker (device_backend in the worker config, passed to apply_gpu_ids), so the forced-XPU-without-device case follows the parent's actual CUDA fallback exactly, including its torch.xpu.is_available() check, with no pre-mask runtime probe in the worker. Regression test covers backend=cuda winning over the forced-XPU build heuristic.

The pre-detect heuristics in apply_gpu_ids can only approximate what
detect_hardware() will decide (they cannot probe XPU availability without
initializing the runtime against the unmasked environment). Make the real
worker flows exact instead: the spawning parent records its detected
backend in the worker config (device_backend, set in the shared training
config builder and the inference orchestrator), and both workers pass it to
apply_gpu_ids(), which trusts it over any heuristic. This mirrors
detect_hardware's XPU availability check and CUDA fallback by construction.

For direct callers without a parent backend, extend the heuristic per the
review: hidden CUDA on an XPU-capable build prefers XPU even without a ZE
mask (detection falls through to XPU in that state; writing the ids to
CUDA_VISIBLE_DEVICES would re-expose the hidden CUDA).

Regression tests cover both backend param directions, the hidden-CUDA
no-mask case, and the existing pre-detect matrix.
@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: 202a1b418e

ℹ️ 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 +559 to +564
if hasattr(torch, "xpu") and torch.xpu.is_available():
# torch.version.xpu may be None on modern builds; fall back to
# "available" so the UI distinguishes present-but-unknown from
# "package not found".
xpu_ver = getattr(torch.version, "xpu", None)
versions["xpu"] = xpu_ver if xpu_ver is not None else "available"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Isolate the XPU probe from CUDA version reporting

When torch.xpu.is_available() raises (the detection path already treats XPU availability probes as fallible), this broad try jumps to the except and overwrites the already-read versions["cuda"] and versions["rocm"] with None. On CUDA/ROCm hosts with a broken or missing Intel runtime, /api/system/hardware would incorrectly lose the CUDA/ROCm runtime versions; keep the XPU probe in its own guarded block so only versions["xpu"] is affected.

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.

Fixed in 6439a34: the XPU probe now has its own guarded block inside get_package_versions, so a broken Intel runtime raising in is_available() only nulls the xpu entry and the cuda/rocm versions survive. Regression test spoofs a raising is_available on a CUDA host.

A broken Intel runtime raising in torch.xpu.is_available() jumped to the
shared except and blanked the already-read cuda/rocm versions on
NVIDIA/AMD hosts. The probe now has its own guarded block so only the
xpu entry is affected. Regression-tested.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6439a343a9

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

/gemini review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds comprehensive support for Intel XPU hardware backends across the inference and training pipelines, including hardware detection, VRAM telemetry, device-specific environment variable masking (using ZE_AFFINITY_MASK), and a dedicated XPU spoof pipeline test suite. Feedback on the changes highlights a missing import for clear_gpu_cache in trainer.py that will cause a runtime NameError, and suggests simplifying the autocast logic in inference.py to use a null context for unsupported dtypes across all device types.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

gc.collect()
torch.cuda.empty_cache()

clear_gpu_cache()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The function clear_gpu_cache is called here but is not imported in this file, which will cause a NameError at runtime. Please add from utils.hardware import clear_gpu_cache to the imports at the top of studio/backend/core/training/trainer.py.

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.

clear_gpu_cache is imported at the top of trainer.py (line 35, first name in the module-level from utils.hardware import block), and all five call sites resolve; CI is green on this head. No NameError is possible here.

Comment on lines +1776 to +1780
autocast_dtype_supported = model.dtype in (torch.bfloat16, torch.float16)
if device_type in ("cpu", "xpu") and not autocast_dtype_supported:
autocast_ctx = contextlib.nullcontext()
else:
autocast_ctx = torch.amp.autocast(device_type, dtype = model.dtype)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Autocast is only designed for low-precision mixed precision (such as float16 or bfloat16). If the model's dtype is float32 (or any other non-low-precision dtype), running autocast is redundant and will raise a ValueError in PyTorch on other backends like CUDA or MPS. We can simplify this check to use contextlib.nullcontext() whenever autocast_dtype_supported is False, regardless of the device type.

Suggested change
autocast_dtype_supported = model.dtype in (torch.bfloat16, torch.float16)
if device_type in ("cpu", "xpu") and not autocast_dtype_supported:
autocast_ctx = contextlib.nullcontext()
else:
autocast_ctx = torch.amp.autocast(device_type, dtype = model.dtype)
autocast_dtype_supported = model.dtype in (torch.bfloat16, torch.float16)
if not autocast_dtype_supported:
autocast_ctx = contextlib.nullcontext()
else:
autocast_ctx = torch.amp.autocast(device_type, dtype = model.dtype)

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.

The fp32 skip is deliberately limited to cpu/xpu, where autocast raises on fp32. CUDA warns and disables autocast for fp32, which is exactly the behavior main has always shipped (the current code produces a context identical to main's hardcoded autocast('cuda', dtype=model.dtype) for every CUDA model). Extending the skip to CUDA/MPS would change NVIDIA behavior, which is out of scope for this Intel enablement PR.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6439a343a9

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

@benhadad

benhadad commented Jul 16, 2026 •

Copy link
Copy Markdown

Any help needed to test this @rolandtannous

danielhanchen and others added 4 commits July 20, 2026 13:13
Narrows the existing GGUF multi-GPU selection to a set of correctness fixes
for the gpu_ids pin path, without changing any other behavior:

- Raw-vs-narrowed GPU-pin dedup: record the raw requested pin
  (_requested_gpu_ids) separately from the fit-narrowed effective pin
  (gpu_ids). /status keeps echoing the effective pin, while load dedupe
  (_already_in_target_state and the route's _request_matches_loaded_settings)
  compares the raw pin, so a [0, 1] narrowed to [0] and re-sent as [0, 1]
  still dedupes instead of needlessly reloading.

- Vulkan preflight before the kill: validate an explicit Vulkan ordinal
  against the ggml-probed device set before killing the running server, so a
  stale gpu_ids that does not enumerate returns a clean error and leaves the
  live model untouched instead of killing it and then failing.

- Physical-id validate 400: the /validate endpoint resolves gpu_ids the same
  way /load does (physical ids, or Vulkan ordinals on a Vulkan build) and
  returns a clear 400 on a bad id, so a preflight agrees with the follow-up
  load. Vulkan physical picks are accepted (validated as ordinals) rather than
  blanket-rejected; only a diffusion GGUF on a Vulkan build is rejected up
  front. The training-coexistence guard sizes a Vulkan GGUF selection against
  the busiest visible GPU (ggml ordinals are a separate index space from CUDA
  ids).

- Fitted-pin recording: record the pin actually applied (the fit-selected
  subset, else the raw request) for /status and dedupe, and fail loudly on an
  explicit Vulkan ordinal absent from the ggml probe rather than fitting onto
  an unselected device.
@oobabooga

Copy link
Copy Markdown
Member

The following integration follow-up was prepared in 0663dc5529:

  • Merged current main and Studio: refine GGUF per-GPU selection (gpu_ids) #7239 into the branch.
  • Resolved the hardware documentation conflict by retaining both GGUF GPU pinning and XPU visibility-mask behavior.
  • Resolved the training coexistence conflict by retaining Vulkan placement sizing together with CUDA and XPU default-deny safeguards.
  • Resolved the memory telemetry conflict by retaining Windows ROCm unknown-memory handling together with the XPU telemetry fallback.

The resulting cumulative tree passed 1,234 affected Python tests, with 15 expected skips and 4 subtests, plus the frontend TypeScript check.

@oobabooga

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

if device in (DeviceType.CUDA, DeviceType.XPU):

P2 Badge Report XPU FLAT masks as relative

When Intel XPU runs with the default FLAT hierarchy and a numeric ZE_AFFINITY_MASK, _get_parent_visible_gpu_spec() deliberately marks those entries as not supporting explicit physical GPU IDs because they are tile handles. This XPU visibility path then treats any non-empty parent_visible_ids as index_kind='physical', so /api/system/gpu-visibility exposes unpinnable tile ordinals as physical IDs; clients using index_kind can offer gpu_ids that the resolver later rejects or that do not map to root GPUs. Keep these XPU unsupported specs on relative ordinals instead.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f537d65f17

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@oobabooga
oobabooga merged commit 47fa4ca into unslothai:main Jul 24, 2026
45 of 47 checks passed
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.

7 participants