Skip to content

feat(studio): round-trip gpu_ids and gguf_memory_mode in load+status - #7417

Closed
Souravrajvi0 wants to merge 97 commits into
unslothai:mainfrom
Souravrajvi0:feat/expose-gpu-ids-status-661b
Closed

Souravrajvi0 wants to merge 97 commits into
unslothai:mainfrom
Souravrajvi0:feat/expose-gpu-ids-status-661b

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

Summary

Fixes #7210.

Ports the GGUF placement round-trip work from #7188 (host-memory gguf_memory_mode + requested_gpu_ids pool echo) and completes the Vulkan diffusion preflight ordering so status-hydrated reloads preserve GPU picks without tearing down the active model.

Backend

  • gguf_memory_mode (auto / pinned / resident) on load, validate, LoadResponse, and InferenceStatusResponse
  • requested_gpu_ids echoed alongside effective gpu_ids after fit-time narrowing
  • LlamaCppBackend.memory_mode / requested_memory_mode properties
  • Vulkan diffusion + gpu_ids classified before Phase 1 teardown (local + remote)
  • Vulkan ordinal probe skipped for physical CUDA IDs (gpu_ids_are_vulkan_ordinals=False)

Frontend

  • Host Memory control in model run settings (Default / Locked RAM / RAM copy)
  • gguf_memory_mode wired through load, validate, status hydration, compare loads, rollback, and per-model remember
  • requested_gpu_ids preferred over fitted gpu_ids when hydrating the GPU picker

Test plan

  • tests/test_llama_cpp_memory_mode.py (168 tests)
  • tests/test_gpu_memory_mode.py
  • tests/test_inference_model_validation.py
  • tests/studio/test_model_picker_contracts.py
  • tests/studio/test_chat_preset_load_config.py

Notes

Stacks on the same placement surface as open #7188; this PR targets the #7210 round-trip gap specifically. Related: #7205 diffusion preflight fix included in the llama_cpp ordering commit.

danielhanchen and others added 30 commits April 11, 2026 12:49
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".
…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.
…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.
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.
Round-4 review (10 parallel reviewers on PR unslothai#4724) produced a unanimous
consensus finding plus two isolated but real regressions. This commit
addresses all three.

[10/10] studio/backend/utils/hardware/hardware.py
_get_parent_visible_gpu_spec() on Intel XPU with ZE_FLAT_DEVICE_HIERARCHY
unset (the oneAPI default FLAT hierarchy) and no ZE_AFFINITY_MASK was
internally inconsistent: it returned numeric_ids=[0..N) with
supports_explicit_gpu_ids=False. Downstream, get_visible_gpu_utilization()
treated those ordinals as numeric_ids!=None, labeled them
index_kind="physical", and llama.cpp's _get_gpu_free_memory() would
round-trip tile/device-handle ordinals back into ZE_AFFINITY_MASK as if
they were stable root-GPU IDs. Collapse the FLAT+no-mask case to
numeric_ids=None so the telemetry path falls into its relative-ordinal
branch and auto-selection uniformly returns inherit_parent_visible. Users
who need explicit Intel selection opt in via ZE_FLAT_DEVICE_HIERARCHY
=COMPOSITE.

[1/10] studio/backend/core/inference/llama_cpp.py
LlamaCppBackend._get_gpu_free_memory() always probed nvidia-smi before
falling back to the generic telemetry path. On a hybrid NVIDIA+Intel host
running Studio in XPU mode, nvidia-smi returned NVIDIA indices and those
ordinals were then used to build a ZE_AFFINITY_MASK for llama-server,
pinning the server to the wrong device. Gate the nvidia-smi fast path on
get_device() == CUDA and IS_ROCM=False so other backends skip straight
to the backend-aware telemetry path.

[1/10] studio/backend/utils/utils.py
format_error_message() dropped the broad "memory"/"cuda" match in favor
of specific substrings. That stopped matching common CUDA allocation
failures such as "CUDA error: CUBLAS_STATUS_ALLOC_FAILED", so users saw
the raw backend exception instead of the friendly "Not enough GPU memory"
hint. Re-add the CUBLAS, cuda-error+alloc, and xpu-alloc patterns while
keeping the matcher narrow enough that non-memory CUDA errors (e.g.
"device-side assert triggered") still pass through unchanged.

Verified: PR-authored tests (96 + 4 skipped), sim suite v1 (174), sim
suite v2 (128 incl. 14 new round-5 coverage), 8x B200 CUDA matrix
(6/6 scenarios byte-identical to pre-fix baseline).
Round-5 review (10 parallel reviewers on PR unslothai#4724) narrowed to two real
correctness issues in the XPU path introduced by round-5's numeric_ids
handling. This commit addresses both.

[4/10] studio/backend/utils/hardware/hardware.py -- get_device_map()
The "numeric_ids is None and visible_count > 1 -> balanced" heuristic
was meant for CUDA UUID/MIG masks, but after round 5 collapsed FLAT
no-mask XPU into numeric_ids=None, the heuristic started firing on the
default Intel FLAT hierarchy and forced balanced sharding across tile
handles even though the same module had already classified those
ordinals as non-physical. Restrict the heuristic to CUDA so XPU stays
on sequential loading unless the caller passes explicit gpu_ids (via
ZE_FLAT_DEVICE_HIERARCHY=COMPOSITE or prepare_gpu_selection).

[3/10] studio/backend/utils/hardware/hardware.py -- get_visible_gpu_utilization,
get_backend_visible_gpu_info
FLAT numeric masks like ZE_AFFINITY_MASK="0,1" populate numeric_ids
for telemetry display but have supports_explicit_gpu_ids=False because
the tokens are tile/device-handle ordinals per Intel's Level Zero
docs. Both helpers still labeled those ordinals index_kind="physical",
which let LlamaCppBackend._get_gpu_free_memory() round-trip them back
into ZE_AFFINITY_MASK as if they were stable root GPU IDs. Gate the
"physical" label on parent_visible_spec["supports_explicit_gpu_ids"]
and clear parent_visible_gpu_ids in the payload when it's False, so
API consumers and llama.cpp skip the placement path.

Verified: PR-authored tests (96 + 4 skipped), sim suite v1 (174, one
updated), sim suite v2 (141 incl. 13 new round-6 tests), 8x B200 CUDA
matrix (6/6 scenarios byte-identical to round-5 baseline).
Round-7 review (10 parallel reviewers on PR unslothai#4724) produced a strong
convergent finding (7/10 independent reviewers on the same underlying
issue): the PR is titled "enable Studio for Intel GPU" but on the
default Intel oneAPI runtime (ZE_FLAT_DEVICE_HIERARCHY=FLAT, no
ZE_AFFINITY_MASK set), Studio still couldn't auto-select or shard
across multiple visible XPUs. Users had to manually opt into COMPOSITE
hierarchy for the PR's advertised feature to actually work.

The reviewers correctly noted that this is fixable without relaxing the
"physical IDs only" contract of the public prepare_gpu_selection() API.
torch.xpu ordinals are stable within a single worker process's inherited
ZE_AFFINITY_MASK scope: Studio can safely generate them internally for
auto-selection, narrow the mask via apply_gpu_ids(), and let the child
process inherit the same torch.xpu device set. Round-trip stays 1:1
within the process boundary the ordinals were observed in.

[7/10] studio/backend/utils/hardware/hardware.py -- auto_select_gpu_ids()
When get_device()==XPU and supports_explicit_gpu_ids=False (FLAT
hierarchy cases), instead of immediately bailing out with
selection_mode="inherit_parent_visible" and selected=None, fall back to
list(range(get_visible_gpu_count())) as the candidate set and continue
into the VRAM-based selection logic. This path is flagged via a new
metadata key xpu_relative_auto_select=True so telemetry stays
introspectable. The public prepare_gpu_selection() API is unchanged
and still refuses user-supplied explicit gpu_ids on these masks,
because end users can't reason about FLAT tile handles; only Studio's
own auto-selection (which controls the worker-process env) can use
these ordinals safely.

[3/10] studio/backend/core/inference/llama_cpp.py -- _get_gpu_free_memory()
The index_kind="relative" guard was rejecting XPU ordinals alongside
CUDA UUID/MIG fallbacks. CUDA relative indices stay unsafe (the parent
has hidden the physical ID mapping, so re-exporting them into
CUDA_VISIBLE_DEVICES would re-expose hidden GPUs). XPU relative
ordinals are stable for the current worker scope, so accept them and
let VRAM-based GGUF placement work on default Intel FLAT hosts.

Verified: PR tests (96 + 4 skipped), sim_pr4724 (174), sim_fixes_v2
(153 incl. 11 new round-7 tests, 3 updated to new contract), 8x B200
CUDA matrix (6/6 scenarios byte-identical to round-5 baseline).
Round-7 added a relative-ordinal fallback so default Intel FLAT hosts
could use multiple visible XPUs via auto-selection and VRAM-based
llama.cpp placement. Round-8 review (6/10 convergent finding on 10
parallel reviewers of PR unslothai#4724) showed that fallback triggered even
when the parent process had already narrowed visibility via
ZE_AFFINITY_MASK, which silently retargeted child processes onto
different Level Zero handles than the parent exposed.

Example: parent sets ZE_AFFINITY_MASK="3,5" to expose tiles 3 and 5.
torch.xpu in the parent sees ordinals 0 (=tile 3) and 1 (=tile 5).
Round-7 auto_select returned [0, 1]; apply_gpu_ids() rewrote
ZE_AFFINITY_MASK="0,1"; the child inherited that and saw tile 0 and
tile 1, not the originally-exposed 3 and 5. Same regression on
subdevice masks like "0.0,0.1".

studio/backend/utils/hardware/hardware.py -- auto_select_gpu_ids()
Gate xpu_relative_auto_select on parent_visible_spec["raw"] is None.
When a parent mask is already set, defer to inherit_parent_visible so
the child inherits the exact visibility the parent intended.

studio/backend/core/inference/llama_cpp.py -- _get_gpu_free_memory()
Gate the relative-XPU acceptance on os.environ.get("ZE_AFFINITY_MASK")
is None. Inherited masks (numeric "3,5", subdevice "0.0,0.1",
wildcard "*") are preserved via the existing "return []" fall-through.

Verified: PR tests (96 + 4 skipped), sim_pr4724 (174), sim_fixes_v2
(162 incl. 9 new round-8 tests + 2 updated to the new inherited-mask
contract), 8x B200 CUDA matrix (6/6 scenarios byte-identical).
Gemini review 4120214370 caught that LlamaCppBackend._get_gpu_free_memory()
built its CUDA_VISIBLE_DEVICES filter with int(x.strip()) for x in
cvd.split(","), which raises ValueError on an empty token from a shell-
exported value like "0,1," (trailing comma) or "0,,1" (doubled comma).
The surrounding try/except swallowed the crash but left ``allowed=None``,
which silently disables the filter so every nvidia-smi GPU becomes a
placement candidate even though the user clearly narrowed visibility.

Skip empty tokens during the parse so trailing/doubled/leading commas
still produce a valid filter, matching the "if token.strip()" pattern
already used in utils/hardware/hardware.py.
Round-7 added a relative-ordinal fallback so default Intel FLAT hosts
could auto-select multiple visible XPUs. Round-9 review (4/10 convergent
plus related findings on 10 parallel reviewers of PR unslothai#4724) showed that
on multi-tile Intel devices (Data Center GPU Max, 2 tiles per root),
the synthesized torch.xpu ordinals enumerate tiles rather than distinct
root GPUs. Writing them back via apply_gpu_ids() then rewrote
ZE_AFFINITY_MASK with tile handles -- narrowing the worker onto a
subset of one card instead of spreading across the parent-visible set.

This revert + replacement keeps multi-XPU sharding working on default
Intel FLAT without any environment-visible ordinal round-trip:

studio/backend/utils/hardware/hardware.py -- auto_select_gpu_ids()
Reverted R7-A. When the parent-visible spec cannot expose stable
physical GPU IDs (FLAT no-mask, FLAT numeric, wildcard, subdevice),
defer to inherit_parent_visible with selected_gpu_ids=None. No more
synthesized worker-local ordinals written back into ZE_AFFINITY_MASK.

studio/backend/core/inference/llama_cpp.py -- _get_gpu_free_memory()
Reverted R7-B. XPU relative telemetry is rejected for placement just
like CUDA UUID/MIG. llama-server inherits the parent's mask unchanged
and uses its own multi-device machinery.

studio/backend/utils/hardware/hardware.py -- get_device_map()
New path: when device==XPU and caller did not pass gpu_ids, return
"balanced" whenever more than one torch.xpu device is visible (either
via unresolved mask or FLAT numeric mask that populates numeric_ids
but does not support explicit selection). HF Transformers uses the
torch ordinals directly -- scope-local within the worker process, no
ZE_AFFINITY_MASK rewrite, so tile-vs-root ambiguity cannot leak out.
Explicit gpu_ids=[0] continues to produce sequential so the caller's
deliberate single-device choice is respected.

Verified: PR tests (96 + 4 skipped), sim_pr4724 (174, one contract
update), sim_fixes_v2 (183 incl. 15 new round-10 tests + 10 updated
for the reverted contracts), 8x B200 CUDA matrix (6/6 scenarios
byte-identical).
Shorten multi-line design-rationale comments to 1-3 lines each.
The surrounding code and commit history carry the full context;
inline comments should state the rule, not re-derive the reasoning.

Net reduction: ~107 comment lines removed across 2 files.
No behavior change.
Bring the Intel XPU Studio enablement up to date with main (post unslothai#5819) and
resolve the four conflicts additively, keeping every non-XPU backend
(NVIDIA CUDA, AMD ROCm, CPU, Apple MLX) byte-for-byte unchanged.

- utils/hardware/hardware.py: re-apply the XPU points on top of main's
  refactor -- detect_hardware explicit-XPU hint, XPU as a supported
  selection backend (auto_select_gpu_ids, prepare_gpu_selection,
  get_device_map), ZE_AFFINITY_MASK visibility (_get_parent_visible_gpu_spec,
  get_visible_gpu_count, _backend_visible_devices_env, apply_gpu_ids),
  backend-aware clear_gpu_cache, package versions, per-device info, and the
  fork-after-Level-Zero-init guard. CUDA/ROCm/CPU/MLX paths are untouched.
- core/training/trainer.py: route the three codec cache clears through the
  backend-aware clear_gpu_cache(); keep codec device as CUDA-or-CPU because
  the SNAC/Spark-TTS/OuteTTS codecs are not yet validated on XPU.
- core/inference/llama_cpp.py: take main's Vulkan GGUF design verbatim;
  llama.cpp Intel inference (Vulkan) is decoupled from torch XPU training.
- tests/test_gpu_selection.py: XPU is now a supported selection backend.
Fake torch.xpu on a GPU-less / NVIDIA CI runner so the Studio hardware
selection and training-device path (detect -> select -> apply -> device_map
-> cache clear) runs exactly as the CUDA path, with no Intel hardware.

- tests/studio/test_xpu_spoof_pipeline.py: fakes the full torch.xpu surface
  hardware.py uses (device_count, get_device_properties.total_memory,
  mem_get_info including the Arc B580 / Lunar Lake RuntimeError, memory_allocated,
  is_initialized, synchronize, empty_cache, torch.version.xpu) and drives 16
  pipeline checks, plus a canary that a stray inherited ZE_AFFINITY_MASK never
  steals a CUDA host.
- studio-backend-ci.yml: run it in the isolated state-sensitive spoof step
  (it fresh-imports hardware under the spoof) and ignore it in the
  auto-discovered repo-tests step.
Comment-only pass: compress the verbose XPU comments and docstrings added by
this PR while keeping every load-bearing rationale (FLAT vs COMPOSITE Level-Zero
hierarchy, why a bare ZE_AFFINITY_MASK is not enough, the Arc B580 / Lunar Lake
mem_get_info RuntimeError guard, not clearing CUDA_VISIBLE_DEVICES on XPU, the
os.fork / Level-Zero corruption guard). No code changes (AST-verified).
…sses

The lint's HOISTED-IMPORT-UNUSED check counts only name loads, so a new
re-export import in __init__.py is flagged as unused (__all__ strings do
not count). Mirror the existing export_capability wrapper pattern instead.
The xpu-smi telemetry path was removed in the rebase; XPU free-VRAM
telemetry comes from torch.xpu only.
On a CUDA+XPU host, UNSLOTH_FORCE_XPU=1 made Studio report XPU while
spawned workers still trained on CUDA: unsloth's device_type checks
torch.cuda.is_available() before torch.xpu and does not read the
Studio-only env var. Set CUDA_VISIBLE_DEVICES="" at the moment the
forced-XPU branch commits, so the whole process tree lands on XPU.
Only fires with UNSLOTH_FORCE_XPU=1 plus a working XPU; a forced host
without XPU falls through to CUDA untouched (regression-tested).
Two review findings on the XPU enablement:

1. apply_gpu_ids() decided the backend via get_device(), which lazily runs
   detect_hardware(). Workers call apply_gpu_ids() before detection, so the
   lazy detect probed torch.cuda against the unmasked parent environment and
   latched device enumeration before CUDA_VISIBLE_DEVICES / ZE_AFFINITY_MASK
   was written, leaving the worker on the parent-visible GPU set. Decide
   pre-detect from env + torch build attributes only (version.xpu with no
   cuda/hip), mirroring the existing ROCm mirror in the same function; the
   detected DEVICE is used when present.

2. routes/training_vram.py gated both coexistence guards on CUDA only, so an
   Intel host could load a chat model over resident training unchecked and
   overcommit the XPU. Both guards now treat XPU like CUDA and size the load
   with the same telemetry (fail-closed on sizing errors); CPU/MLX keep the
   blanket outcome under the renamed non_accelerator mode.

Regression tests: pre-detect apply_gpu_ids never triggers detection on either
build flavor; XPU keep-guard sizes like CUDA; XPU overcommit load is refused.
Two follow-ups on the pre-detect masking:

1. torch.version.xpu can be None on a working XPU build (this file already
   treats that as valid in get_package_versions), which routed Intel-only
   workers to CUDA_VISIBLE_DEVICES and dropped multi-XPU pinning. Accept
   torch.xpu._is_compiled() as the build signal too; it is a pure
   symbol-presence check with no runtime initialization.

2. UNSLOTH_FORCE_XPU=1 alone no longer proves XPU pre-detect: on a build
   without XPU support, detect_hardware() falls back to CUDA, so the mask
   now follows that fallback and writes CUDA_VISIBLE_DEVICES instead of a
   dead ZE_AFFINITY_MASK.

Both cases regression-tested.
danielhanchen and others added 4 commits July 26, 2026 19:26
…nslothai#7417

Merge origin/main. Three conflicts:

- use-chat-model-runtime.ts: main added the staged pendingLoadConfig payload,
  this branch added gguf_memory_mode propagation. Both are kept. The staged GPU
  pick is now reconciled WITH pendingLoadConfig.selectedGpuIndexKind: main's
  call site passed the ids alone, so a remembered physical CUDA pick loaded on
  a Vulkan build survived the reconcile and was re-sent as ggml ordinals,
  pinning llama-server to a different card. loadMemoryMode follows the same
  "staged config wins, else store" rule as the other knobs, in the click-time
  snapshot and in the cross-model reset.
- test_gguf_load_cache_reuse.py: kept main's stronger version (rindex anchoring
  on the GGUF branch that owns the load marker, plus the
  _resolve_inherited_extra_args ordering assertion and the inherited-extras
  coverage). Its _resolve_gguf_gpu_ids_for_request stub now returns the
  (ids, are_vulkan_ordinals) tuple this branch introduced.
- model-config-page.tsx: additive on both sides (isDiffusion vs the two
  NumericValueInput refs); both kept.

Fixes:

- Reject an explicit host-memory mode on a diffusion GGUF BEFORE Phase 1
  teardown. The check needs the GGUF header, so it ran after _kill_process()
  and a "pinned"/"resident" load of a DiffusionGemma model the route could not
  classify by name tore down the running model and then returned 400. It now
  shares the pre-teardown classification with the Vulkan gpu_ids preflight
  (unslothai#7205), and the Phase 2 call still reuses _preflight_model_path so nothing
  is fetched twice. An auto/omitted mode skips the preflight entirely, so a
  plain load keeps downloading after teardown as before.
- Canonicalize llama.cpp long-flag underscore aliases. common/arg.cpp runs
  std::replace(arg.begin(), arg.end(), '_', '-') on any '--' token before the
  option lookup, so --no_mmap, --load_mode and --spec_draft_device are the same
  flags to the child. Studio matched only the hyphen forms, so a pass-through
  arg could last-wins-override a Studio-owned setting: an inherited --no_mmap
  survived the gguf_memory_mode strip, and --spec_draft_device CUDA1 escaped
  both the gpu_ids pin guard and the zero-offload GPU-visibility check that
  keeps a pinned child from aborting. The existing _canonical_long_flag is now
  the single shared implementation, used by the boundary validator's _flag_name
  (denylist + every strip group + the ctx/cache/split parsers) and by the
  draft-device / draft-offload scanners.

Tests:

- Pre-teardown rejection for the local and remote diffusion paths, the
  no-second-fetch guarantee, the auto/omitted no-op, and a non-diffusion load
  with an explicit mode.
- Underscore aliases across the denylist, every strip group, the parsers, the
  draft-device pin, the draft CPU-offload probe and the device-pin detector,
  plus proof that values carrying underscores are never rewritten.
- test_gguf_placement_os_gpu_matrix.py: [Windows, Linux, WSL, macOS] x
  [NVIDIA, AMD, CPU-only] plus the Vulkan bundle, spoofing the installed
  llama.cpp layout, so /api/system's picker gate and /load's resolver are
  proven to agree per cell. Also pins the old paths: no gpu_ids sent, a single
  GPU, a GPU-less host, a CPU-only build, and pre-feature load/status payloads.
- tests/studio/test_gguf_gpu_ids_hardware_matrix.py: the same matrix driven
  through the real hardware layer with torch spoofed by
  _zoo_aggressive_cuda_spoof / _zoo_rocm_spoof, so the DeviceType each vendor
  produces is observed rather than assumed.
- tests/studio/test_per_model_config_gpu_namespace_compat.py: configs persisted
  before selectedGpuIndexKind / ggufMemoryMode existed still apply, the older
  unsloth_load_settings blob an upgrading install leaves behind still migrates
  with its GPU pick, and the reconcile matrix over host namespaces (legacy,
  physical, vulkan, single GPU, no GPU, cold cache).
…othai#7417

GPU index namespace:
- savePerModelConfig keeps the namespace already on record when the incoming
  settings snapshot carries none. That snapshot reads the namespace from the
  shared /api/system cache, so a save taken while the cache is still cold wrote
  the pick back untagged, and an untagged entry re-reads as a legacy physical
  pick, which discards a saved Vulkan selection on the very host it was made on.

DiffusionGemma:
- Gate the Host Memory control on the staged model too, not only the loaded one.
  _classify_diffusion_gguf identifies an un-downloaded DiffusionGemma repo from
  its name alone, so the staged Load flow offered Locked RAM and RAM copy and
  the load that followed failed with a 400. The config page now applies the same
  name check the backend uses before the download.
- Hide the GPU picker when the device namespace is ggml Vulkan and the model is
  DiffusionGemma. _resolve_gguf_gpu_ids_for_request sets
  ids_are_vulkan_ordinals to False for a confirmed diffusion GGUF, so the ids go
  through the CUDA physical resolver while /api/system still advertises Vulkan
  ordinals for the same integers, and picking Vulkan1 could start the diffusion
  runner on a different card.

Tests:
- A cold-cache re-save keeps a saved Vulkan pick usable, driven through the real
  per-model-config.ts, currentRuntimePerModelConfig and reconcilePersistedGpuIds
  under node.
- The frontend DiffusionGemma name check matches the backend rule over a table
  of identities.
- /load resolves a diffusion GGUF's gpu_ids as CUDA physical ids on a Vulkan
  bundle while /api/system tags the same indices vulkan, and the CUDA
  requirement still rejects every other host.
- Source contracts for the three gates.
@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: 3dae338089

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a38ee84025

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

@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: 86b712696e

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

# The route validated these as CUDA physical IDs (it classified the model as
# diffusion from a name hint on an uncached remote GGUF); the header
# disagrees, so the Vulkan pin below would reinterpret them as ggml ordinals.
if is_vulkan_backend and gpu_ids and gpu_ids_are_vulkan_ordinals is False:

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 Reject header disagreements before tearing down

When a normal GGUF has DiffusionGemma in its repo or path, the route classifies the requested IDs as CUDA physical IDs, while this preflight downloads the file and correctly finds _preflight_is_diffusion == false. However, the mismatch is not raised here until after _kill_process() has terminated the healthy server, so the request then fails while leaving no model running. Move this disagreement check into the pre-Phase-1 block where the header result is already available.

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.

Confirmed, and it is destructive. Repro: a normal GGUF (plain llama header) named owner/DiffusionGemma-derivative, Vulkan build, gpu_ids=[1], gpu_ids_are_vulkan_ordinals=False, with a healthy server already loaded. The preflight above Phase 1 downloads and classifies it as not-diffusion, so the if _preflight_is_diffusion: block is skipped, the stale-ordinal check is gated on is not False and is skipped too, Phase 1 kills the process, and only then does the post-metadata check raise. Before: is_loaded=True -> after: terminated=True is_loaded=False process=None, request failed, nothing running. Same on both the local gguf_path and the remote hf_repo branch.

Fixed in 1c5e833 in the shape #7415 used: the header result is already in hand at the pre-Phase-1 block, so the disagreement is rejected there and the post-metadata copy stays as a final defense, with one shared message helper so the two spellings cannot drift. _preflight_is_diffusion becomes tri-state (None until a header is actually read) so an unclassified load can never trip the new reject.

Negative control: reverting the new elif gives assert [True] == [] on both test_local_physical_id_mismatch_rejected_before_teardown and test_remote_physical_id_mismatch_rejected_before_teardown; restoring it greens both. The remote test also asserts downloads == [True], so the pre-teardown classification is the same fetch Phase 2 would have made, not an extra one.

Comment thread studio/backend/main.py Outdated
is_vulkan = LlamaCppBackend._is_vulkan_backend()
vulkan_devices = LlamaCppBackend._get_vulkan_gpu_info() if is_vulkan else []
if vulkan_devices:
enriched_devices = vulkan_devices

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 Preserve PyTorch GPU metrics when exposing Vulkan pins

On a CUDA/ROCm host using the new forced-Vulkan llama.cpp backend, replacing enriched_devices here makes the global /api/system.gpu.devices list describe Vulkan rather than the PyTorch devices used for training and non-GGUF inference. useGpuInfo() sums this same list for Hub fit filtering and training model sizing, so Vulkan-only devices such as an iGPU or devices outside PyTorch's visibility mask can inflate the reported accelerator memory and lead users toward configurations that do not fit the actual training backend. Expose the Vulkan ordinal records separately for the GGUF picker instead of replacing the general GPU metrics.

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.

Confirmed on both halves. main.py did enriched_devices = vulkan_devices, a full replacement, and also rewrote visibility_info to available: True, backend: "vulkan". And useGpuInfo() really does sum that same list: toGpuInfo returns devices.reduce((sum, d) => sum + (d.memory_total_gb ?? 0), 0) off data.gpu.devices, which feeds hub-page.tsx (gpuGb), use-hub-model-vram.ts, recommended-fit.ts, pickers.tsx and model-section.tsx. The Settings VRAM monitor in resources-tab.tsx sums systemInfo.gpu?.devices directly, so it was a third consumer.

Repro on a 2 x 8 GB CUDA host with a forced-Vulkan llama.cpp build and one 64 GB shared-memory iGPU in the ggml probe:

/api/system gpu.backend            : vulkan       (host is CUDA)
/api/system gpu.devices names      : ["AMD Radeon Graphics (iGPU)"]
useGpuInfo().memoryTotalGb (sum)   : 64.0 GB      (real accelerator budget: 16.0 GB)

Fix in 1c5e833 is ADDITIVE, not a repurpose: the ordinal records move to a new gpu.gguf_gpu_devices key and devices, available and backend go back to describing the PyTorch-visible accelerators exactly as they did before this PR. I chose additive because an older frontend reads only devices; had I kept the replacement and added a "real" list alongside, every pre-#7164 install would keep sizing training against ggml devices. The picker loses nothing: useGpuDevices() (its only consumers are model-config-page.tsx and the cachedPinnableGpuIndices / cachedPinnableGpuIndexKind helpers) now prefers gguf_gpu_devices when non-empty and falls back to devices, so an old backend that omits the key behaves as before. Same repro after the fix: backend: cuda, devices ["GPU0","GPU1"], sum 16.0 GB, picker still on ["vulkan","vulkan"].

Negative control: restoring the two replacing lines fails 12 tests, including test_vulkan_ordinals_never_replace_the_pytorch_gpu_metrics with assert ["iGPU"] == ["GPU0", "GPU1"]; restoring the fix greens all 12. For the frontend half, reverting the toGpuDevices selection fails the new node-executed test_gguf_pin_candidates_read_their_own_channel with assert ["physical","physical"] == ["vulkan","vulkan"], and greens on restore.

@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: 332cb7bf11

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

</div>
)}
{/* The diffusion runner has no host-memory modes and /load rejects them. */}
{!isDiffusion && (

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 Clear hidden host-memory values for diffusion models

When a DiffusionGemma already has a remembered ggufMemoryMode of pinned or resident—for example, from a version before this gate—this conditional only hides the selector; it does not remove the value from config. handleSubmit later persists and passes the unchanged effectiveRuntimeConfig to onRun, so /validate or /load still returns 400 and the user has no visible control with which to clear the invalid setting. Fresh evidence beyond the earlier host-memory comment is that the new gate leaves pre-existing persisted values intact; normalize ggufMemoryMode to undefined for diffusion before saving/loading.

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.

Correct, fixed in 9938480.

Reachable today: the gate reads looksLikeDiffusionGemma(target.id) only, while the backend _classify_diffusion_gguf reads identifier + gguf_hf_repo + gguf_file and, when a header is available, the header itself. So a GGUF the backend classifies as diffusion but whose target.id does not carry the family name (an exported fine-tune keyed by run name, a native drag-drop pick keyed by display label, a self-converted file) renders Host Memory while staged. handleRun calls savePerModelConfig before onRun, so the mode is persisted even though the load then 400s, and from there every entry point that loads from the remembered config re-sends it without ever rendering this page (Hub Run, startup autoload, picker row click, compare pane Send). Once the model is classified diffusion the control is hidden and the page copy comes from loadedConfig, which carries no mode, so the stranded value is invisible.

Normalization direction: on submit only, not on save. The two cases are asymmetric.

  • Active and header-confirmed diffusion: config is seeded from loadedConfig, whose ggufMemoryMode is always undefined (a diffusion load sets _requested_memory_mode = None, so the response echoes null). There is nothing to strip, and the save already rewrites the entry without a mode.
  • Staged: the classification is only the name stand-in. Clearing on save would destroy a mode that is valid the moment the same id loads with a header saying it is not diffusion, which is exactly the DiffusionGemma-derivative case in the sibling comment. So the mode is dropped from the payload handed to onRun and kept in storage.

diffusionSafeLoadConfig in apply-per-model-config.ts returns the config unchanged when the model is not gated or has no mode, so nothing else copies.

Tests: tests/studio/test_per_model_config_gpu_namespace_compat.py::test_hidden_host_memory_mode_never_reaches_the_load runs the real helper under node and asserts the payload loses the mode while the caller object keeps it. Negative control: replacing the body with a pass-through reddens that test; restoring it greens. tests/studio/test_model_picker_contracts.py::test_load_never_carries_a_hidden_host_memory_mode guards the handleRun wiring, including that savePerModelConfig still receives the unstripped config.

Not covered: the Hub / autoload / compare entry points read the remembered config directly and never render this page, so they still send a stranded mode. That is a separate surface with no classification available at that point, and I did not widen the fix into it.

danielhanchen and others added 2 commits July 27, 2026 03:18
… keep Vulkan ordinals off the PyTorch GPU metrics

A normal GGUF whose repo id or path carries the DiffusionGemma name hint has its
gpu_ids classified as CUDA physical IDs by the route, which the local header then
contradicts. That mismatch was only raised after Phase 1 had already killed the
running llama-server, so the request failed leaving nothing loaded. The preflight
above Phase 1 already reads the header, so reject there instead and keep the
post-metadata raise as a final defense. Both spellings now share one message.

/api/system also replaced its device list with the ggml Vulkan probe records on a
forced-Vulkan llama.cpp build. That list is summed for the Settings VRAM monitor,
Hub fit filtering and training model sizing, none of which run on ggml's devices,
so a Vulkan-only iGPU or a card outside PyTorch's visibility mask inflated the
reported accelerator budget and steered users to configurations the training
backend cannot fit. Publish the ordinal records on a new gguf_gpu_devices key
instead: devices, available and backend keep their pre-feature meaning, and the
GGUF picker reads the new key when present and falls back to devices otherwise.
@danielhanchen

Copy link
Copy Markdown
Member

The merge of main into this branch had never had CI signal, so I replicated it onto a staging repo and ran the cross-platform matrix there rather than adding to the org queue. Result on the staged merge commit: 24 passing, 0 failures, across Ubuntu, macOS and Windows (2 runs still going). The runs that show as cancelled are concurrency-group supersessions from the two-commit staging push, not failures.

Separately, on the 8 tests/studio/test_hardware_dispatch_matrix.py failures anyone will see running the whole tests/studio suite locally: they are not from this branch. Pristine origin/main gives the same 8 failures and the same 2 collection errors, name for name, and the file passes 23/23 in isolation on both trees. It is suite ordering that already exists on main.

Head has moved since that staging run (1c5e833ac) for the two fixes below, so the cross-platform result covers the merge, not the current tip.

@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: 419e8be8ec

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

Comment on lines +659 to +660
const isDiffusionModel =
(isActiveModel && loadedIsDiffusion) || looksLikeDiffusionGemma(target.id);

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 Prefer the loaded diffusion classification for active models

When an active, header-confirmed ordinary GGUF has DiffusionGemma in its repo or path (for example, a normal DiffusionGemma-derivative), loadedIsDiffusion is false but the name fallback still makes isDiffusionModel true. This incorrectly hides both the Host Memory control and, on Vulkan, the GPU picker even though the backend's authoritative header classification supports those settings; use the name fallback only for staged models whose loaded classification is unavailable.

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.

Correct, fixed in 9938480.

Reproduced by tracing: for an active owner/DiffusionGemma-derivative whose header says ordinary, the backend returns is_diffusion: false, loadedIsDiffusion is false, and (isActiveModel && loadedIsDiffusion) || looksLikeDiffusionGemma(target.id) still resolves true. Host Memory is hidden and, on a Vulkan build, gpuIdsMeanOtherDevices hides the GPU picker as well, even though _classify_diffusion_gguf header-probes the same local file, returns False, and /load would accept both. The sidebar is the surface that bites: chat-page.tsx and the sampling dialog pass modelId = checkpoint with !modelLoading, so the model there is always the loaded one.

This is the same name-versus-header confusion as the backend half, resolved the same way. resolveIsDiffusion(loaded, ...parts) in model-identity.ts takes a tri-state DiffusionClassification = boolean | null and returns loaded ?? looksLikeDiffusionGemma(...parts): the header answer decides whenever it exists, including when it says no, and the name only fills a null. The page supplies isActiveModel ? loadedIsDiffusion : null, so the name is consulted for a staged pick only. That keeps the two halves consistent: _preflight_is_diffusion stays None until a header is really read so a name hint cannot trip a reject, and the page keeps the name as a pre-load stand-in only, matching the backend fallback that 400s a staged DiffusionGemma before any download.

isActiveModel is a sound stand-in for "classified": every load path sets loadedIsDiffusion from the response in the same update as the checkpoint and the GPU fields (use-chat-model-runtime.ts, shared-composer.tsx, chat-adapter.ts, apply-inference-status-to-store.ts sets it before setCheckpoint), so no render sees a checkpoint whose classification is stale.

Tests: tests/studio/test_per_model_config_gpu_namespace_compat.py::test_loaded_header_classification_beats_the_diffusion_name runs the real resolveIsDiffusion under node across the loaded-false / loaded-true / staged matrix, including a loaded diffusion model whose id says nothing. Negative control: changing the body to loaded === true || looksLikeDiffusionGemma(...parts), the name OR-d back on top, reddens it; restoring greens it. test_loaded_diffusion_classification_outranks_the_name_hint guards the tri-state at the call site.

…onGemma name, and keep a hidden host-memory mode off the load

The config page resolved the diffusion gate as (active && loadedIsDiffusion) || name,
so an ordinary GGUF carrying DiffusionGemma in its id lost the Host Memory control and,
on a Vulkan build, the GPU picker, even though the backend had read its header and
classified it as a normal model. Resolve the gate from a tri-state instead, mirroring
_preflight_is_diffusion: the loaded classification decides whenever it exists, and the
name only stands in for a staged pick whose header neither side has read.

The gate also only hid the Host Memory control; a remembered pinned or resident mode
stayed on the config, and handleRun passed it to onRun, so /validate and /load kept
400ing with no visible control to clear it. Strip the mode from the load payload only.
Storage keeps it: staged, the gate is just the name stand-in, and the mode is valid
again as soon as the same model loads with a header saying it is not diffusion.

@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: 9938480ae3

ℹ️ 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 +61 to +64
// Stay untagged while the device cache is cold: persisting a guessed
// namespace would make a later reconcile drop the saved pick.
selectedGpuIndexKind:
selectedGpuIds == null ? null : cachedPinnableGpuIndexKind(),

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 Tag first-time Vulkan GPU saves after cache warmup

On a Vulkan host, if an active model with selected GPU IDs is opened and remembered before /api/system resolves, this memoized snapshot stores selectedGpuIndexKind as undefined and never recomputes when the cache warms. Fresh evidence beyond the earlier re-save case is a model with no existing stored config: keepStoredGpuIndexKind has no prior namespace to recover, so the first saved entry remains untagged; reconcilePersistedGpuIds later treats that legacy entry as physical and drops the valid Vulkan IDs. Await the cache before the first save or make the namespace update reactive.

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.

Confirmed reachable, and it is not even a narrow race. Fixed in bc10580.

Ordering: applyInferenceStatusToStore seeds selectedGpuIds from requested_gpu_ids on the first /api/inference/status hydration and never awaits the device cache. Nothing in the chat page mounts a GPU hook either, so fetchSystemOnce() has not been called at that point at all: the only useGpuInfo / useGpuDevices consumers are the hub page, the model picker, onboarding and the studio model section. So the useActiveModelConfig memo recomputes on that seed with cachedSystem === null and stores selectedGpuIndexKind: undefined. When the user later opens the config sheet, GpuMemorySettings mounts useGpuDevices() and the cache warms, but no memo dependency changed, so the snapshot stays untagged; savePerModelConfig gets it verbatim through initial.config -> config -> runtimeConfig. With no earlier entry, keepStoredGpuIndexKind has nothing to recover, the entry is stored untagged, and reconcilePersistedGpuIds(ids, undefined) defaults expectedIndexKind to physical against a vulkan host and returns null. Silent loss of the pick.

Shape chosen: reactive, not await. usePinnableGpuIndexKind() in hooks/use-gpu-info.ts mirrors useGpuDevices (state seeded from the cache, effect re-reads after fetchSystemOnce() resolves) and useActiveModelConfig consumes it as a memo dependency. Awaiting was the weaker option here: the save is synchronous, and fetchSystemOnce resolves to null and clears systemPromise when the backend is not up, so an await would either block the save on an endpoint that may never answer or fall through to the same untagged value. With the hook, a cache that never resolves leaves the value undefined, which is the honest answer (the namespace is genuinely unknown, so guessing one would drop the ids just as surely) and still lets keepStoredGpuIndexKind recover a namespace already on record.

Covered by test_first_gpu_save_waits_for_the_vulkan_namespace, which runs the real use-active-model-config.ts and the real use-gpu-info.ts under node against a gated /api/system, then feeds the snapshot into the real savePerModelConfig and reconcilePersistedGpuIds. Negative control, restoring the one-shot cachedPinnableGpuIndexKind() read:

>       assert result["warmKind"] == "vulkan"
E       AssertionError: assert 'undefined' == 'vulkan'
E         - vulkan
E         + undefined
FAILED tests/studio/test_model_picker_contracts.py::test_active_model_snapshot_retags_when_the_device_cache_warms
FAILED tests/studio/test_per_model_config_gpu_namespace_compat.py::test_first_gpu_save_waits_for_the_vulkan_namespace

restored: 61 passed.

Comment on lines 768 to +770
gpu_ids: validateGpuIds ?? undefined,
...(isGguf ? { gpu_memory_mode: loadGpuMemoryMode } : {}),
gguf_memory_mode: validateMemoryMode,

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 Sanitize remembered diffusion modes on every load path

When a remembered DiffusionGemma config contains pinned or resident, selecting that model directly from the picker passes the persisted value here and /validate rejects the load with a 400. Fresh evidence beyond the earlier hidden-control issue is that diffusionSafeLoadConfig is only called by ModelConfigPage.handleSubmit; direct remembered selections, startup auto-load, and compare loads bypass it and still forward the invalid mode. Apply the diffusion normalization at a shared validation/load boundary rather than only on the settings-page submit path.

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.

Correct, and this is the gap the last round left open rather than a new one. Fixed in bc10580.

Boundary chosen: loadModel and validateModel in studio/frontend/src/features/chat/api/chat-api.ts. They are the only two functions that build the /api/inference/load and /api/inference/validate bodies, so every load path passes through them:

  • settings-page Load/Reload and picker row click on a remembered model -> performLoad in use-chat-model-runtime.ts (validate at 770, load at 934)
  • Hub Run and startup selection -> hub-page.tsx / chat-page.tsx -> same performLoad
  • startup auto-load (remembered candidate and the default GGUF download) -> chat-adapter.ts canAutoLoad + loadAutoLoadCandidate (1603/1637) and the default path (1948/1979)
  • compare pane Send -> shared-composer.tsx (1110/1179)
  • failed-switch rollback -> use-chat-model-runtime.ts 1164

diffusionSafeMemoryMode now runs inside both builders, so none of them can send a mode the diffusion runner rejects.

The on-save reasoning is preserved. Nothing is cleared from storage, and the tri-state is still the only classification: resolveIsDiffusion(loaded, ...parts) moved to a dependency-free @/lib/diffusion-model so the API layer can share it without pulling a feature barrel into the request path, and model-identity.ts re-exports it rather than restating it. LoadModelRequest gained a client-only loadedIsDiffusion hint, stripped before the request exactly like nativePathLease; a same-model reload passes the header answer so a DiffusionGemma-derivative that loaded with an ordinary header keeps the mode /load accepts for it. Omitting the hint only falls back to the stricter name check, so a caller that forgets it can never let a rejected mode through.

Covered by test_host_memory_gate_covers_every_load_path, which drives the real chat-api.ts under node and inspects the bodies it posts. Negative control, reverting the two hunks:

>       assert result["validate"] == expected
E       AssertionError: assert [pinned, r...nt, 'pinned'] == [None, None, ...one, 'pinned']
E         At index 0 diff: 'pinned' != None
FAILED tests/studio/test_model_picker_contracts.py::test_host_memory_gate_sits_on_the_shared_request_boundary
FAILED tests/studio/test_per_model_config_gpu_namespace_compat.py::test_host_memory_gate_covers_every_load_path

restored: 61 passed.

danielhanchen and others added 2 commits July 27, 2026 04:47
…and retag a late Vulkan namespace

Host-memory modes were only stripped on the settings-page submit path, so a
picker row click on a remembered model, the startup auto-load, Hub Run, a
compare pane's Send and the failed-load rollback all still forwarded a
remembered pinned/resident mode for a DiffusionGemma GGUF, which /validate and
/load both reject with a 400 while the control that would clear it is hidden.
Every one of those paths funnels into loadModel/validateModel, so the gate now
lives there. The tri-state classification moves to a dependency-free @/lib
module both features share, and a client-only loadedIsDiffusion hint lets a
same-model reload keep the mode when the loaded header already said the model
is not diffusion; a caller that omits the hint only falls back to the stricter
name check, so it can never let a rejected mode through.

useActiveModelConfig also read the pinnable GPU index namespace once, during a
render that can happen long before /api/system answers (selectedGpuIds is
seeded from /api/inference/status, which never warms the device cache). Nothing
else in the memo changes when the cache fills, so the snapshot froze untagged,
and on a first save there is no earlier entry for keepStoredGpuIndexKind to
recover a namespace from: the entry stayed untagged and the next reconcile read
it as a legacy physical pick and dropped valid Vulkan ids. It now reads the
namespace through a hook that re-renders when the fetch lands, and still
refuses to guess while the cache is cold.

Both are covered by node-executed tests over the real modules: the request
bodies chat-api actually posts, and the real useActiveModelConfig driven across
the /api/system resolution.

@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: 2c23d2e4a9

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

return
if LlamaCppBackend._canonical_memory_mode(memory_mode) is None:
return
if _classify_diffusion_gguf(config) is True:

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 Classify uncached diffusion GGUFs before accepting memory modes

For a remote, uncached diffusion GGUF whose repo/file name does not contain DiffusionGemma, _classify_diffusion_gguf() returns None, so /validate accepts pinned or resident; /load then downloads the header, recognizes diffusion, and rejects the same request. In the primary frontend flow, the healthy model is unloaded between those calls (use-chat-model-runtime.ts:830-833), causing an avoidable failed switch and rollback. Unlike the previously covered name-based cases, the fresh evidence here is the header-only classification of a renamed diffusion GGUF; validation must resolve that classification before approving the mode, or the frontend must defer teardown until this preflight completes.

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.

Reproduced the sequence, but not changing it: the only way to close it is to download the weights inside /validate, which costs more than the defect.

What reproduces. For owner/renamed-block-model-GGUF (a real diffusion GGUF whose name says nothing about diffusion), uncached, with gguf_memory_mode="pinned":

_classify_diffusion_gguf(config) -> None            (tri-state "unknown")
/validate  _reject_diffusion_memory_mode -> ACCEPTED
frontend   use-chat-model-runtime.ts:831 await unloadModel({ model_path: currentCheckpoint })
/load      _reject_diffusion_memory_mode -> ACCEPTED
backend    load_model -> ValueError: GGUF host-memory modes are not supported for DiffusionGemma models. Use Auto.
           downloads performed by the preflight: [("owner/renamed-block-model-GGUF", "Q4_K_M")]
           backend process teardown before the raise: none

So the chain is real. Three things bound it.

1. It is strictly better than main, not a regression. origin/main has no _reject_diffusion_memory_mode at all and validateModel does not send gguf_memory_mode, so on main every diffusion host-memory load takes exactly this path, cached or not. This PR closes the cached case and the name case; the uncached renamed case is the residual. The teardown at use-chat-model-runtime.ts:831 is untouched by this PR.

2. It is self-limiting to the first load. The failed attempt leaves the GGUF in the HF cache, so the retry classifies locally and rejects before any teardown:

_classify_diffusion_gguf(config) -> True
/validate -> 400: Explicit gguf_memory_mode is not supported for diffusion (DiffusionGemma) GGUF models.
rejected BEFORE the frontend unload: no teardown, no rollback

The one-time cost is an unload plus a rollback reload of the previous model. The rollback at use-chat-model-runtime.ts:1131 restores the full placement, including loadedIsDiffusion for the model it is rolling back to, and the download is not wasted: the next Auto load reuses it.

3. Closing it means downloading in /validate. There is no remote header reader here; resolve_local_gguf_path is documented as "Read-only, never triggers a download", which is precisely why the classification is None when uncached. Resolving it at /validate means calling _download_gguf on multi-GB weights inside the endpoint whose contract is "does NOT load model weights", and /validate holds neither guard that /load acquires before its own preflight download:

validate_model      _hub_download_blocks_gguf_load=False  gguf_load_in_flight=False
_load_model_impl    _hub_download_blocks_gguf_load=True   gguf_load_in_flight=True

Downloading there would race the download manager and skip the in-flight marker, and it would fire on fetchGgufStagedMetadata-shaped probes that today are guaranteed download-free. Deferring the frontend teardown instead is not scoped to diffusion either: any /load that can only fail after the header is read (corrupt GGUF, OOM, llama-server start failure) takes the same unload-then-rollback path, which is what that rollback exists for.

The tri-state is doing what it was built to do: stay None rather than guess. Trading a one-time rollback for a blind multi-GB download on a hot path is the wrong side of that trade.

@danielhanchen

Copy link
Copy Markdown
Member

This PR is getting too large and out of scope - tbh I'm uncertain what this is fixing - closing for now - thanks for the PR

@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

Hey Daniel, not asking to reopen this. More trying to understand how you'd prefer outside contributors to approach PRs going forward since you're the one reviewing most of mine.

A few things I'd find useful if you're open to sharing:

Should we always wait for a go ahead on an issue before opening a PR, or is opening early fine if it's marked draft?

How do you decide a PR is too big? Is there a rough rule like one bug one PR, or keep it under a certain number of files?

For Studio stuff specifically, what's fair game for outside PRs vs what you'd rather handle internally?

And when you do close something, is it usually scope, product direction, or the fix not actually solving the linked issue? Just trying to calibrate before I open more.

No rush on a long reply. Even a few sentences on what a good PR looks like to you would help a lot. Thanks for all the review time on my stuff.

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.

Studio: expose gpu_ids / gguf_memory_mode in load+status responses and wire the frontend so they round-trip

5 participants