Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Size VRAM from the pool, not the carve-out, on integrated NVIDIA parts (#11208)

Daniel Han77e1a3cbe556
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index b3949bc1a30..4064498d09c 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -10559,14 +10559,19 @@ class LlamaCppBackend:
def _integrated_cuda_probe_is_free() -> bool:
"""True when ``_integrated_cuda_gpu_ids()`` costs no NEW CUDA context.
- That probe pins a ~700 MiB primary context per visible card for the life of
- this process, and the launch preflight runs AFTER the VRAM budget was taken, so
- probing there can OOM a tightly fitted child against a stale budget. So the
- preflight never probes: it reads an answer only if one is cached for this mask.
- ``_get_gpu_memory`` fills that cache on its torch arm before reading any
- free/total figure, which puts the cost inside the snapshot. That is the arm an
- integrated SoC takes anyway (nvidia-smi answers ``[N/A]`` on a Spark, so the CLI
- probe parses nothing); a host whose nvidia-smi answers never pays for it.
+ The launch preflight runs AFTER the VRAM budget was taken, so a probe there
+ would price a tightly fitted child against a stale budget. So the preflight
+ never probes: it reads an answer only if one is cached for this mask.
+ ``_get_gpu_memory`` fills that cache before reading any free/total figure, which
+ puts the cost inside the snapshot.
+
+ BOTH its arms fill it now. The torch arm always did, and that was assumed to be
+ the arm an integrated SoC takes, because nvidia-smi answers ``[N/A]`` on a DGX
+ Spark and the CLI probe parses nothing. A Windows RTX Spark N1X answers 8128 MiB
+ instead -- a real number, scoped to the dedicated carve-out -- so the CLI arm
+ wins there and an integrated host reached the preflight with nothing cached.
+ The probe reads ``get_device_properties`` only, which creates no primary context
+ (measured at 0 MiB on an N1X, against 116 MiB for ``mem_get_info``).
"""
return LlamaCppBackend._integrated_cuda_mask_key() in LlamaCppBackend._INTEGRATED_CUDA_IDS
@@ -10628,6 +10633,147 @@ class LlamaCppBackend:
except Exception:
return set()
+ # {physical id: pool total MiB} per visibility mask, filled beside _INTEGRATED_CUDA_IDS.
+ _INTEGRATED_CUDA_POOL_MIB: dict[tuple, dict[int, int]] = {}
+
+ @staticmethod
+ def _integrated_cuda_pool_total_mib() -> dict[int, int]:
+ """Pool size in MiB for each visible integrated CUDA device.
+
+ ``props.total_memory`` is what an integrated part can actually allocate, and it
+ is the figure nvidia-smi contradicts on a Windows RTX Spark N1X: 46477 MiB here
+ against the 8128 MiB carve-out the CLI reports. Read from the device list, so
+ it costs no primary context (measured at 0 MiB, against 116 MiB for
+ mem_get_info on the same part) and is cached per mask like the flag itself.
+
+ Empty off CUDA, on ROCm and on any error, so callers keep the CLI's total.
+ """
+ key = LlamaCppBackend._integrated_cuda_mask_key()
+ cached = LlamaCppBackend._INTEGRATED_CUDA_POOL_MIB.get(key)
+ if cached is not None:
+ return dict(cached)
+ integrated = LlamaCppBackend._integrated_cuda_gpu_ids()
+ if not integrated:
+ return {}
+ try:
+ import torch
+
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
+ totals: dict[int, int] = {}
+ complete = True
+ for ordinal in range(torch.cuda.device_count()):
+ idx = (
+ physical_ids[ordinal]
+ if physical_ids is not None and ordinal < len(physical_ids)
+ else ordinal
+ )
+ if idx not in integrated:
+ continue
+ try:
+ props = torch.cuda.get_device_properties(ordinal)
+ totals[idx] = int(props.total_memory) // (1024 * 1024)
+ except Exception:
+ complete = False
+ if complete:
+ LlamaCppBackend._INTEGRATED_CUDA_POOL_MIB[key] = totals
+ return totals
+ except Exception:
+ return {}
+
+ @staticmethod
+ def _widen_integrated_cuda_rows(gpus: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
+ """Re-price nvidia-smi rows for an integrated CUDA SoC against its shared pool.
+
+ The torch arm of ``_get_gpu_memory`` already sizes an integrated part this way,
+ but it is only reached when the CLI answers nothing, which is the DGX Spark
+ shape (memory.total reads ``[N/A]`` there) and not the Windows RTX Spark N1X
+ shape, where the CLI answers 8128 MiB of a 46477 MiB budget and the nvidia-smi
+ arm returns first. A model was told it needed "7.9 GB of a 6.9 GB budget" on a
+ machine with 45 GiB. So the same policy is applied to a CLI answer that came
+ back scoped to the carve-out.
+
+ Widening only: a total is replaced solely by a LARGER one, and the free half is
+ floored at the reading it replaces, so no device is offered less than the CLI
+ already vouched for. A discrete host gets its rows back unchanged, having paid
+ one classification that is cached for the life of the process.
+ """
+ try:
+ integrated = LlamaCppBackend._integrated_cuda_gpu_ids()
+ if not integrated or not gpus:
+ return gpus
+ # These rows are nvidia-smi indices; `_integrated_cuda_gpu_ids` answers in
+ # CUDA's, which CUDA_DEVICE_ORDER defaults to FASTEST_FIRST, pinning only
+ # device 0 (docs.nvidia.com/cuda/cuda-programming-guide, environment
+ # variables). An unmappable mask is worse: no physical ids AND, since
+ # `_visible_devices_mask` cannot parse it either, unfiltered CLI rows. Join
+ # only when both halves are mappable, as `_cuda_join_is_unsafe` does.
+ order = (os.environ.get("CUDA_DEVICE_ORDER") or "").strip().upper()
+ raw_mask = os.environ.get("CUDA_VISIBLE_DEVICES")
+ mask_unset = raw_mask is None or not raw_mask.strip()
+ mappable = mask_unset or LlamaCppBackend._resolve_visible_physical_ids() is not None
+ # No single-row exemption: `gpus` is what SURVIVED parsing (the N1X's own
+ # NPU row does not), so it is not a device count. main.py:19 sets PCI_BUS_ID,
+ # so every Spark, Jetson and N1X still qualifies below.
+ if not (mappable and order == "PCI_BUS_ID"):
+ logger.debug(
+ "Not widening integrated CUDA rows: CUDA_DEVICE_ORDER is %r and "
+ "the mask %s, so a CUDA id cannot be joined to an nvidia-smi index "
+ "here.",
+ order or "unset (FASTEST_FIRST)",
+ "resolves to no physical ids" if not mappable else "is mappable",
+ )
+ return gpus
+ totals = LlamaCppBackend._integrated_cuda_pool_total_mib()
+ avail = LlamaCppBackend._available_system_memory_mib()
+ cgroup_mib = LlamaCppBackend._cgroup_available_memory_mib()
+ # One pool, however many integrated devices draw on it: the same reason the
+ # torch arm divides. No shipping product pairs two integrated SoCs, so this
+ # is a division by 1 everywhere it currently runs.
+ shared_count = max(1, sum(1 for idx, _f, _t in gpus if idx in integrated))
+ out: list[tuple[int, int, int]] = []
+ for idx, free_mib, total_mib in gpus:
+ if idx not in integrated:
+ out.append((idx, free_mib, total_mib))
+ continue
+ cli_total_mib = total_mib
+ pool_mib = totals.get(idx) or 0
+ if pool_mib > total_mib:
+ total_mib = pool_mib
+ raw_mib = free_mib
+ # MemAvailable, as the torch arm uses: both free readings undercount here
+ # (#9889). A zero total means unsized, so it never becomes a cap.
+ if avail is not None and total_mib > 0:
+ raw_mib = min(total_mib, max(raw_mib, avail))
+ cgroup_bound = False
+ if cgroup_mib is not None and cgroup_mib <= raw_mib:
+ # Charged to the cgroup, so publish no total and let the fit price
+ # off the free reading, which IS the container's ceiling.
+ raw_mib = cgroup_mib
+ cgroup_bound = True
+ if shared_count > 1:
+ raw_mib //= shared_count
+ total_mib //= shared_count
+ capped = _apply_igpu_host_reserve_mib(raw_mib, True)
+ # Never below what the driver already vouched for. NOT under a cgroup:
+ # allocations are charged to memory.max, so the floor would hand the fit
+ # planner a budget the kernel kills.
+ if not cgroup_bound:
+ capped = max(capped, free_mib // shared_count)
+ # Only when something moved: _get_gpu_memory is uncached and
+ # _wait_for_vram_settle polls it every 0.25 s.
+ if capped != free_mib or total_mib != cli_total_mib:
+ logger.info(
+ f"CUDA device {idx} is a unified-memory SoC sharing system RAM; "
+ f"sizing it against the shared pool "
+ f"({free_mib}->{capped}MiB free, "
+ f"{pool_mib or total_mib}MiB pool)"
+ )
+ out.append((idx, capped, 0 if cgroup_bound else total_mib))
+ return sorted(out, key = lambda g: g[0])
+ except Exception as e:
+ logger.debug(f"integrated CUDA pool sizing failed: {e}")
+ return gpus
+
@staticmethod
def _integrated_cuda_unified_memory(gpu_indices = None) -> bool:
"""True when a credited CUDA device is an integrated (unified-memory) SoC.
@@ -12689,7 +12835,8 @@ class LlamaCppBackend:
gpus.sort(key = lambda g: g[0])
if gpus:
LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True
- return gpus
+ # The CLI row is the carve-out, not the pool. Discrete rows unchanged.
+ return LlamaCppBackend._widen_integrated_cuda_rows(gpus)
except Exception as e:
logger.debug(f"nvidia-smi probe failed: {e}")
@@ -12697,7 +12844,8 @@ class LlamaCppBackend:
nvml_gpus = LlamaCppBackend._get_gpu_memory_nvml()
if nvml_gpus:
LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True
- return nvml_gpus
+ # nvidia-smi IS NVML: same carve-out, same PCI indexing, same correction.
+ return LlamaCppBackend._widen_integrated_cuda_rows(nvml_gpus)
# ── AMD ROCm via amd-smi ─────────────────────────────────────
rocm_gpus = LlamaCppBackend._get_gpu_memory_amd_smi(
diff --git a/studio/backend/tests/test_dgx_spark_gpu_inventory.py b/studio/backend/tests/test_dgx_spark_gpu_inventory.py
index aed3d47eba8..6da0141c3bc 100644
--- a/studio/backend/tests/test_dgx_spark_gpu_inventory.py
+++ b/studio/backend/tests/test_dgx_spark_gpu_inventory.py
@@ -140,22 +140,32 @@ def test_rocm_is_not_classified_by_the_cuda_integrated_flag(monkeypatch):
# ── nothing above may reach a host that is not one of these parts ────────────
-def test_a_readable_smi_host_never_consults_torch(monkeypatch):
- """The repair is scoped to hosts with a missing capacity.
-
- /api/system is polled every 5s by the floating monitor and every 3s from Settings.
- A discrete card answers memory.total, so it must leave that poll exactly as it was:
- no torch import, no property query, no new failure mode on a machine that was fine.
+def test_a_readable_smi_host_is_classified_but_never_rewritten(monkeypatch):
+ """A readable capacity is still compared against torch, and still wins.
+
+ This test used to assert that torch was never consulted when every row carried a
+ number. That shortcut WAS the bug: a Windows RTX Spark N1X answers memory.total with
+ its 8128 MiB dedicated carve-out rather than ``[N/A]``, so "the CLI answered" stopped
+ being a reason to trust the answer. The classification now runs on every poll, at a
+ measured 7 microseconds, because get_device_properties is served from the driver's
+ device list.
+
+ What must not change is the verdict on a discrete card, and what must never happen
+ on a 3-5 s poll is a primary context. Both are asserted here; the context guarantee
+ has its own file (test_system_poll_no_cuda_context.py).
"""
_cuda_host(monkeypatch, _DiscreteProps())
_smi_rows(monkeypatch, 23.99)
def _forbidden(*args, **kwargs):
- raise AssertionError("torch inventory consulted on a host with nothing to repair")
+ raise AssertionError("mem_get_info pins a primary context on the /api/system poll")
- monkeypatch.setattr(hw, "_torch_get_device_inventory", _forbidden)
+ monkeypatch.setattr(hw, "trusted_mem_get_info", _forbidden)
+
+ device = hw.get_backend_visible_gpu_info()["devices"][0]
- assert hw.get_backend_visible_gpu_info()["devices"][0]["memory_total_gb"] == 23.99
+ assert device["memory_total_gb"] == 23.99
+ assert device.get("unified_memory") is not True
def test_multi_gpu_smi_host_is_untouched(monkeypatch):
@@ -493,8 +503,19 @@ def test_a_known_usage_still_gets_its_percentage(monkeypatch):
Filling the total is what makes the percentage computable, so a device that already
carries a usage must not be skipped: it was the one case where both operands existed
and the monitor still showed an unknown.
+
+ The host counter has to be stubbed. On one shared pool the used half is
+ ``max(host_used, cli_used)``, so without this the assertion below reads whatever the
+ machine running the suite happens to be using and the test passes or fails by how
+ busy the runner is. Held at 20 GiB, under the 30.0 the CLI reports, so the CLI's own
+ figure is the larger one and the assertion is about the rule rather than the host.
"""
_cuda_host(monkeypatch, _SparkProps())
+ monkeypatch.setattr(
+ psutil,
+ "virtual_memory",
+ lambda: types.SimpleNamespace(total = 121 * GIB, available = 101 * GIB),
+ )
utilization = {
"devices": [
{
@@ -511,6 +532,7 @@ def test_a_known_usage_still_gets_its_percentage(monkeypatch):
device = utilization["devices"][0]
assert device["vram_total_gb"] == SPARK_TOTAL_GB
- # The CLI's own figure, not the host counter that stands in when it is absent.
+ # Whichever of the two is larger. Both are lower bounds on occupancy of one pool,
+ # and here the CLI's own figure is the larger one.
assert device["vram_used_gb"] == 30.0
assert device["vram_utilization_pct"] == round((30.0 / SPARK_TOTAL_GB) * 100, 1)
diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.py
index 82a1c9a9aad..e8b89330d10 100644
--- a/studio/backend/tests/test_gpu_selection.py
+++ b/studio/backend/tests/test_gpu_selection.py
@@ -7,6 +7,7 @@ import os
import re
import sys
import unittest
+import types
from contextlib import nullcontext
from pathlib import Path
from types import ModuleType, SimpleNamespace
@@ -224,9 +225,28 @@ class TestVisibleGpuUtilization(_GpuCacheResetMixin, unittest.TestCase):
},
]
+ # Two discrete cards. Stubbed rather than left to the host's own torch: the
+ # integrated-memory reconciliation reads props.total_memory for every CUDA row,
+ # so on a unified-memory machine (an RTX Spark N1X) a real 45.39 GiB pool was
+ # joined onto this fake 24 GiB row and the assertion below read the runner's
+ # hardware instead of the fixture.
+ _discrete = types.SimpleNamespace(
+ name = "NVIDIA RTX 4090",
+ total_memory = 24 * (1 << 30),
+ is_integrated = 0,
+ gcnArchName = "",
+ )
+
with (
patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA),
patch.object(_hw_module, "IS_ROCM", False),
+ patch(
+ "utils.hardware.hardware._torch_get_device_module",
+ return_value = (
+ types.SimpleNamespace(get_device_properties = lambda ordinal: _discrete),
+ "cuda",
+ ),
+ ),
patch(
"utils.hardware.hardware._get_parent_visible_gpu_spec",
return_value = {"raw": "5,3", "numeric_ids": [5, 3]},
diff --git a/studio/backend/tests/test_unified_memory_carve_out_vram.py b/studio/backend/tests/test_unified_memory_carve_out_vram.py
new file mode 100644
index 00000000000..9d88f0a3df6
--- /dev/null
+++ b/studio/backend/tests/test_unified_memory_carve_out_vram.py
@@ -0,0 +1,761 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""An integrated CUDA SoC whose nvidia-smi ANSWERS, with the wrong number.
+
+test_dgx_spark_gpu_inventory.py covers the shape where nvidia-smi answers ``[N/A]`` for
+memory.total and the capacity had to be filled in. This file covers the other shape of
+the same fault, measured on an NVIDIA RTX Spark N1X (Blackwell, compute capability 12.1,
+unified memory) running Windows on ARM64:
+
+ nvidia-smi memory.total 8128 MiB the dedicated carve-out ONLY
+ torch props.total_memory 46477 MiB what CUDA can actually allocate
+ torch mem_get_info()[1] 46477 MiB agrees with props
+ llama.cpp --list-devices 46477 MiB agrees with props
+ props.is_integrated 1
+
+An under-report of about 5.7x, and a readable number rather than a blank, so every
+"fill in what the CLI could not answer" repair skipped it. A 270M model was judged not
+to fit ("usable_gb=0.3 required_gb=2.251"), and speculative decoding was refused for
+wanting "7.9 GB of a 6.9 GB budget" on a machine with 45 GiB.
+
+Hermetic: torch, nvidia-smi and host memory are stubbed, so these run anywhere. The
+figures above are real, and are used as the stub values.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import psutil
+import pytest
+import utils.hardware.hardware as hw
+from core.inference.llama_cpp import LlamaCppBackend
+from utils.hardware import nvidia
+
+GIB = 1 << 30
+MIB = 1 << 20
+
+# Measured on the RTX Spark N1X.
+N1X_POOL_MIB = 46477
+N1X_POOL_BYTES = 48735117312
+N1X_POOL_GB = round(N1X_POOL_BYTES / GIB, 2) # 45.39
+N1X_CARVE_OUT_MIB = 8128
+N1X_CARVE_OUT_GB = round(N1X_CARVE_OUT_MIB * MIB / GIB, 2) # 7.94
+N1X_USED_GB = 5.73
+HOST_TOTAL_GB = 54.21
+HOST_AVAILABLE_GB = 42.55
+
+
+class _N1XProps:
+ """cudaDeviceProp as torch surfaces it for an RTX Spark N1X."""
+
+ name = "NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)"
+ total_memory = N1X_POOL_BYTES
+ is_integrated = 1
+ gcnArchName = ""
+
+
+class _DiscreteProps:
+ name = "NVIDIA GeForce RTX 4090"
+ total_memory = 24 * GIB
+ is_integrated = 0
+ gcnArchName = ""
+
+
+def _torch_module(props_by_ordinal) -> types.SimpleNamespace:
+ def _get(ordinal):
+ try:
+ return props_by_ordinal[ordinal]
+ except (IndexError, KeyError):
+ raise RuntimeError("Invalid device id")
+
+ return types.SimpleNamespace(get_device_properties = _get)
+
+
+def _not_hip(monkeypatch) -> None:
+ """Stub the torch the CUDA classifier asks for HIP, so a ROCm runner does not invert
+ every assertion here (the same trap test_dgx_spark_gpu_inventory.py documents)."""
+ monkeypatch.setitem(
+ sys.modules, "torch", types.SimpleNamespace(version = types.SimpleNamespace(hip = None))
+ )
+
+
+def _cuda_host(
+ monkeypatch,
+ *props,
+ numeric_ids = None,
+) -> None:
+ ids = [0] if numeric_ids is None else numeric_ids
+ _not_hip(monkeypatch)
+ monkeypatch.setattr(hw, "IS_ROCM", False)
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: list(ids))
+ monkeypatch.setattr(
+ hw,
+ "_get_parent_visible_gpu_spec",
+ lambda: {
+ "raw": ",".join(str(i) for i in ids),
+ "numeric_ids": list(ids),
+ "supports_explicit_gpu_ids": True,
+ },
+ )
+ monkeypatch.setattr(hw, "_cuda_order_matches_smi", lambda: True)
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (_torch_module(props), "cuda"))
+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: len(props))
+
+
+def _host_memory(
+ monkeypatch,
+ total_gb = HOST_TOTAL_GB,
+ available_gb = HOST_AVAILABLE_GB,
+) -> None:
+ monkeypatch.setattr(
+ psutil,
+ "virtual_memory",
+ lambda: types.SimpleNamespace(total = int(total_gb * GIB), available = int(available_gb * GIB)),
+ )
+
+
+def _util_row(
+ index = 0,
+ ordinal = 0,
+ total_gb = N1X_CARVE_OUT_GB,
+ used_gb = N1X_USED_GB,
+) -> dict:
+ """A row exactly as nvidia.py::_build_gpu_metrics emits it."""
+ return {
+ "index": index,
+ "index_kind": "physical",
+ "visible_ordinal": ordinal,
+ "gpu_utilization_pct": 0.0,
+ "temperature_c": 36.0,
+ "vram_used_gb": used_gb,
+ "vram_total_gb": total_gb,
+ "vram_utilization_pct": (
+ round(used_gb / total_gb * 100, 1)
+ if used_gb is not None and total_gb not in (None, 0)
+ else None
+ ),
+ "power_draw_w": 0.34,
+ "power_limit_w": None,
+ "power_utilization_pct": None,
+ }
+
+
+def _smi_utilization(
+ monkeypatch,
+ rows,
+ numeric_ids = None,
+) -> None:
+ ids = [0] if numeric_ids is None else numeric_ids
+ monkeypatch.setattr(
+ hw,
+ "_smi_query",
+ lambda *a, **k: {
+ "available": True,
+ "devices": rows,
+ "backend_cuda_visible_devices": None,
+ "parent_visible_gpu_ids": list(ids),
+ "index_kind": "physical",
+ },
+ )
+
+
+def _smi_inventory(monkeypatch, rows) -> None:
+ monkeypatch.setattr(nvidia, "_query_gpu_inventory", lambda caller: rows)
+
+
+# ── the fault itself ─────────────────────────────────────────────────────────
+
+
+def test_a_readable_carve_out_total_is_widened_to_the_pool(monkeypatch):
+ """The regression: 7.94 GiB published for a device that can allocate 45.39 GiB."""
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB
+
+
+def test_the_free_half_grows_with_the_total(monkeypatch):
+ """A widened total paired with the carve-out's own used figure is still wrong.
+
+ memory.used is scoped to the carve-out, so it is a floor on pool occupancy rather
+ than a measure of it. The host counter spans the same ground the widened total does,
+ which is the rule _rocm_windows_unified_used_bytes states for the AMD twin.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+ free_gb = device["vram_total_gb"] - device["vram_used_gb"]
+
+ # Host used is 54.21 - 42.55 = 11.66, which is larger than the carve-out's 5.73.
+ assert device["vram_used_gb"] == pytest.approx(HOST_TOTAL_GB - HOST_AVAILABLE_GB, abs = 0.02)
+ # The number the training gate reads. It was 7.94 - 5.73 = 2.21.
+ assert free_gb > 30
+ assert device["vram_utilization_pct"] == pytest.approx(25.7, abs = 0.5)
+
+
+def test_a_270m_model_now_fits(monkeypatch):
+ """The reported symptom, end to end through the helper the training gate uses.
+
+ "Falling back to all visible GPUs; model may not fit:
+ model=unsloth/gemma-3-270m-it usable_gb=0.3 required_gb=2.251"
+ """
+ from routes.training_vram import _free_vram_by_index
+
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ free = _free_vram_by_index(hw.get_visible_gpu_utilization()["devices"])
+
+ assert free[0] > 2.251
+
+
+def test_the_system_inventory_is_widened_too(monkeypatch):
+ """Settings > System reads get_backend_visible_gpu_info, a different probe.
+
+ It showed "7.94 GiB total" for the card while Settings > About, which reads torch,
+ showed 45.39 GiB for the same machine in the same session.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _smi_inventory(
+ monkeypatch,
+ [{"index": 0, "name": _N1XProps.name, "memory_total_gb": N1X_CARVE_OUT_GB}],
+ )
+
+ device = hw.get_backend_visible_gpu_info()["devices"][0]
+
+ assert device["memory_total_gb"] == N1X_POOL_GB
+ assert device["unified_memory"] is True
+ # The pool IS system memory, so the frontend must count it once, not twice.
+ assert device["shared_memory_host_backed_gb"] == N1X_POOL_GB
+
+
+def test_llama_cpp_prices_the_gguf_fit_against_the_pool(monkeypatch):
+ """llama.cpp has its own probe, and its nvidia-smi arm wins on this host.
+
+ "Speculative decoding disabled for this load: the model fits in VRAM at context
+ 83968 but its drafter does not (needs 7.9 GB of a 6.9 GB budget, on any GPU subset)"
+ """
+ _integrated_llama_host(monkeypatch)
+ _smi_free_total(monkeypatch, [(0, 2256, N1X_CARVE_OUT_MIB)])
+
+ gpus = LlamaCppBackend._get_gpu_memory()
+
+ assert len(gpus) == 1
+ idx, free_mib, total_mib = gpus[0]
+ assert idx == 0
+ assert total_mib == N1X_POOL_MIB
+ # It was 2256 MiB. The drafter needed 7.9 GB.
+ assert free_mib > 8 * 1024
+
+
+# ── the constraint: never shrink, never touch a discrete card ────────────────
+
+
+def test_a_discrete_card_is_byte_identical(monkeypatch):
+ """A 4090 answers memory.total correctly and nothing here may second-guess it."""
+ _cuda_host(monkeypatch, _DiscreteProps())
+ _host_memory(monkeypatch)
+ rows = [_util_row(total_gb = 23.99, used_gb = 1.5)]
+ before = [dict(row) for row in rows]
+ _smi_utilization(monkeypatch, rows)
+
+ devices = hw.get_visible_gpu_utilization()["devices"]
+
+ assert devices == before
+
+
+def test_a_discrete_inventory_is_byte_identical(monkeypatch):
+ _cuda_host(monkeypatch, _DiscreteProps())
+ _smi_inventory(
+ monkeypatch,
+ [{"index": 0, "name": _DiscreteProps.name, "memory_total_gb": 23.99}],
+ )
+
+ device = hw.get_backend_visible_gpu_info()["devices"][0]
+
+ assert device["memory_total_gb"] == 23.99
+ assert device.get("unified_memory") is not True
+ assert device.get("shared_memory") is not True
+
+
+def test_llama_cpp_leaves_discrete_rows_alone(monkeypatch):
+ _discrete_llama_host(monkeypatch)
+ _smi_free_total(monkeypatch, [(0, 20000, 24564), (1, 24000, 24564)])
+
+ assert LlamaCppBackend._get_gpu_memory() == [(0, 20000, 24564), (1, 24000, 24564)]
+
+
+def test_a_larger_cli_total_is_never_shrunk(monkeypatch):
+ """The rule the ROCm path already encodes: adopt only a LARGER total.
+
+ A driver that under-reports props.total_memory while the CLI is right must not cost
+ the device its capacity, because a too-small total hides models the device can hold.
+ """
+
+ class _UnderReportingProps(_N1XProps):
+ total_memory = 4 * GIB
+
+ _cuda_host(monkeypatch, _UnderReportingProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row(total_gb = 16.0, used_gb = 2.0)])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == 16.0
+ assert device["vram_used_gb"] == 2.0
+
+
+def test_totals_that_agree_within_rounding_are_left_alone(monkeypatch):
+ """props.total_memory is exact bytes; nvidia-smi rounds to whole MiB.
+
+ An integrated part whose CLI total is already pool-scoped must not churn its own
+ figures over the difference.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row(total_gb = N1X_POOL_GB - 0.01, used_gb = 3.0)])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB - 0.01
+ assert device["vram_used_gb"] == 3.0
+
+
+def test_free_bytes_never_shrink_when_the_host_is_nearly_full(monkeypatch):
+ """The widening must not cost a device free bytes the driver already vouched for.
+
+ A host with 2 GiB of 54 GiB available would otherwise publish a 45 GiB pool with
+ less free memory than the 8 GiB carve-out it replaced.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch, total_gb = HOST_TOTAL_GB, available_gb = 2.0)
+ _smi_utilization(monkeypatch, [_util_row(total_gb = N1X_CARVE_OUT_GB, used_gb = 1.0)])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+ free_gb = device["vram_total_gb"] - device["vram_used_gb"]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB
+ # The carve-out promised 7.94 - 1.0 = 6.94 GiB and that promise is kept.
+ assert free_gb >= N1X_CARVE_OUT_GB - 1.0 - 0.02
+
+
+def test_llama_cpp_free_never_shrinks(monkeypatch):
+ _integrated_llama_host(monkeypatch, avail_mib = 512)
+ _smi_free_total(monkeypatch, [(0, 6000, N1X_CARVE_OUT_MIB)])
+
+ _idx, free_mib, total_mib = LlamaCppBackend._get_gpu_memory()[0]
+
+ assert total_mib == N1X_POOL_MIB
+ assert free_mib >= 6000
+
+
+# ── the NPU, which must stay honestly unknown ────────────────────────────────
+
+
+def test_the_npu_row_is_left_unknown(monkeypatch):
+ """nvidia-smi enumerates an "NVIDIA NPU" as GPU 1 on this machine.
+
+ It runs under MCDM rather than WDDM and ``nvidia-smi -q -i 1`` genuinely answers
+ ``FB Memory Usage: Total: N/A``. torch does not enumerate it at all. There is no
+ number to publish for it and inventing one would be worse than a blank.
+ """
+ _cuda_host(monkeypatch, _N1XProps(), numeric_ids = [0, 1])
+ _host_memory(monkeypatch)
+ _smi_utilization(
+ monkeypatch,
+ [_util_row(), _util_row(index = 1, ordinal = 1, total_gb = None, used_gb = None)],
+ numeric_ids = [0, 1],
+ )
+
+ devices = hw.get_visible_gpu_utilization()["devices"]
+
+ assert devices[0]["vram_total_gb"] == N1X_POOL_GB
+ assert devices[1]["vram_total_gb"] is None
+ assert devices[1]["vram_used_gb"] is None
+ assert devices[1]["vram_utilization_pct"] is None
+
+
+def test_the_npu_cannot_drag_down_the_training_budget(monkeypatch):
+ """An unmeasurable row must be absent from the free-VRAM map, not present as zero.
+
+ Present as a zero it would rank as a real device with no memory, and a multi-GPU
+ split would be sized against a card that cannot hold anything.
+ """
+ from routes.training_vram import _free_vram_by_index
+
+ _cuda_host(monkeypatch, _N1XProps(), numeric_ids = [0, 1])
+ _host_memory(monkeypatch)
+ _smi_utilization(
+ monkeypatch,
+ [_util_row(), _util_row(index = 1, ordinal = 1, total_gb = None, used_gb = None)],
+ numeric_ids = [0, 1],
+ )
+
+ free = _free_vram_by_index(hw.get_visible_gpu_utilization()["devices"])
+
+ assert set(free) == {0}
+
+
+# ── mixed hosts and index spaces ─────────────────────────────────────────────
+
+
+def test_only_the_integrated_device_is_widened_on_a_mixed_host(monkeypatch):
+ """A discrete card beside an integrated one keeps its own, correct capacity."""
+ _cuda_host(monkeypatch, _N1XProps(), _DiscreteProps(), numeric_ids = [0, 1])
+ _host_memory(monkeypatch)
+ _smi_utilization(
+ monkeypatch,
+ [
+ _util_row(),
+ _util_row(index = 1, ordinal = 1, total_gb = 23.99, used_gb = 1.5),
+ ],
+ numeric_ids = [0, 1],
+ )
+
+ devices = hw.get_visible_gpu_utilization()["devices"]
+
+ assert devices[0]["vram_total_gb"] == N1X_POOL_GB
+ assert devices[1]["vram_total_gb"] == 23.99
+ assert devices[1]["vram_used_gb"] == 1.5
+
+
+def test_a_mismatched_device_order_refuses_the_join(monkeypatch):
+ """CUDA enumerates FASTEST_FIRST while nvidia-smi reports PCI order.
+
+ Joining them anyway attaches one card's capacity to another card's row. The widening
+ uses the same gate the rest of the module already applies, so it declines instead.
+ """
+ _cuda_host(monkeypatch, _N1XProps(), numeric_ids = [0, 1])
+ _host_memory(monkeypatch)
+ monkeypatch.setattr(hw, "_cuda_order_matches_smi", lambda: False)
+ _smi_utilization(monkeypatch, [_util_row()], numeric_ids = [0, 1])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_CARVE_OUT_GB
+
+
+def test_a_uuid_mask_joins_on_the_visible_ordinal(monkeypatch):
+ """A UUID or MIG mask resolves to numeric_ids=None and has no physical ids.
+
+ nvidia.py resolves the mask itself and returns rows in its order, which is the order
+ torch enumerates, so visible_ordinal is the join.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ monkeypatch.setattr(
+ hw,
+ "_get_parent_visible_gpu_spec",
+ lambda: {"raw": "GPU-f9df3c40", "numeric_ids": None, "supports_explicit_gpu_ids": False},
+ )
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB
+
+
+# ── cost: no primary context on a polling path ───────────────────────────────
+
+
+def test_the_poll_never_pins_a_cuda_context(monkeypatch):
+ """mem_get_info attaches a primary context the process never gives back.
+
+ Measured at 116 MiB on the N1X and ~612 MiB elsewhere. get_device_properties
+ attaches none (measured at 0 MiB), and this whole repair is built on that
+ difference, so nothing here may reach for the other call.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ def _forbidden(*args, **kwargs):
+ raise AssertionError("mem_get_info pins a primary context on the /api/system poll")
+
+ monkeypatch.setattr(hw, "trusted_mem_get_info", _forbidden)
+ monkeypatch.setattr(hw, "_torch_get_per_device_info", _forbidden)
+
+ assert hw.get_visible_gpu_utilization()["devices"][0]["vram_total_gb"] == N1X_POOL_GB
+
+
+# ── hosts that cannot answer at all ──────────────────────────────────────────
+
+
+def test_a_torch_that_cannot_answer_keeps_the_cli_rows(monkeypatch):
+ """A CPU-only build, or no torch: the CLI reading stands, unchanged."""
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (None, None))
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_CARVE_OUT_GB
+ assert device["vram_used_gb"] == N1X_USED_GB
+
+
+def test_a_host_memory_probe_failure_still_widens_the_total(monkeypatch):
+ """psutil is the numerator's source, not the total's.
+
+ Losing it must not cost the device the capacity, which is the half that decides
+ whether a model is offered at all.
+ """
+ _cuda_host(monkeypatch, _N1XProps())
+
+ def _boom():
+ raise RuntimeError("no host counters here")
+
+ monkeypatch.setattr(psutil, "virtual_memory", _boom)
+ _smi_utilization(monkeypatch, [_util_row()])
+
+ device = hw.get_visible_gpu_utilization()["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB
+ # memory.used is scoped to the carve-out, so pairing it with the POOL total would
+ # advertise the whole difference as free on no pool-scoped evidence. The capacity
+ # still widens, which is the half that decides whether a model is offered at all;
+ # the budget stays the one the CLI vouched for.
+ cli_free_gb = round(N1X_CARVE_OUT_GB - N1X_USED_GB, 2)
+ assert device["vram_total_gb"] - device["vram_used_gb"] == pytest.approx(cli_free_gb, abs = 0.01)
+
+
+def test_the_predicate_is_the_whole_rule():
+ """Direct table for the one function every site above shares."""
+ # A blank CLI total: the DGX Spark shape, always widened.
+ assert hw._integrated_total_is_understated(None, 121.0) is True
+ # A carve-out: the N1X shape.
+ assert hw._integrated_total_is_understated(N1X_CARVE_OUT_GB, N1X_POOL_GB) is True
+ # Equal, and within rounding of equal: nothing to do.
+ assert hw._integrated_total_is_understated(45.39, 45.39) is False
+ assert hw._integrated_total_is_understated(45.39, 45.40) is False
+ # Smaller: never adopted.
+ assert hw._integrated_total_is_understated(45.39, 8.0) is False
+ # Nothing to adopt.
+ assert hw._integrated_total_is_understated(8.0, None) is False
+ assert hw._integrated_total_is_understated(8.0, 0) is False
+
+
+# ── llama.cpp host stubs ─────────────────────────────────────────────────────
+
+
+def _llama_common(monkeypatch, avail_mib):
+ monkeypatch.setattr(LlamaCppBackend, "_INTEGRATED_CUDA_IDS", {})
+ monkeypatch.setattr(LlamaCppBackend, "_INTEGRATED_CUDA_POOL_MIB", {})
+ monkeypatch.setattr(LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: None))
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b: False))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: avail_mib)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))
+ monkeypatch.setattr(LlamaCppBackend, "_visible_devices_mask", staticmethod(lambda name: None))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: None)
+ )
+ # `_resolve_visible_physical_ids` returning None means NO MASK here, so the env has
+ # to say the same or the runner's own CUDA_VISIBLE_DEVICES is read as one. The
+ # ordering mirrors main.py:19, which sets PCI_BUS_ID on import.
+ for _var in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_var, raising = False)
+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
+
+
+def _integrated_llama_host(monkeypatch, avail_mib = int(HOST_AVAILABLE_GB * 1024)):
+ _llama_common(monkeypatch, avail_mib)
+ monkeypatch.setattr(LlamaCppBackend, "_integrated_cuda_gpu_ids", staticmethod(lambda: {0}))
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_integrated_cuda_pool_total_mib",
+ staticmethod(lambda: {0: N1X_POOL_MIB}),
+ )
+
+
+def _discrete_llama_host(monkeypatch, avail_mib = 32000):
+ _llama_common(monkeypatch, avail_mib)
+ monkeypatch.setattr(LlamaCppBackend, "_integrated_cuda_gpu_ids", staticmethod(lambda: set()))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_integrated_cuda_pool_total_mib", staticmethod(lambda: {})
+ )
+
+
+def _smi_free_total(monkeypatch, rows):
+ """Stand in for `nvidia-smi --query-gpu=index,memory.free,memory.total`."""
+ stdout = "\n".join(f"{idx}, {free}, {total}" for idx, free, total in rows)
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: types.SimpleNamespace(returncode = 0, stdout = stdout, stderr = ""),
+ )
+
+
+def test_a_cgroup_ceiling_survives_the_never_shrink_floor(monkeypatch):
+ """Inside a container the floor must not hand back memory `memory.max` forbids.
+
+ The free half is floored at the reading nvidia-smi already vouched for, which is
+ right on bare metal and wrong inside a cgroup: allocations on a unified part are
+ charged to it, so republishing the larger carve-out figure prices a fit against
+ memory the kernel will not give and the child is killed rather than offloaded.
+ """
+ _integrated_llama_host(monkeypatch, avail_mib = 40000)
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: 2048))
+
+ rows = LlamaCppBackend._widen_integrated_cuda_rows([(0, 6000, N1X_CARVE_OUT_MIB)])
+
+ assert rows[0][1] <= 2048, rows
+ # A cgroup-bound row publishes no total, which is the shared-pool marker.
+ assert rows[0][2] == 0
+
+
+def test_an_unmappable_mask_refuses_the_join_under_any_ordering(monkeypatch):
+ """A UUID or MIG mask leaves torch ordinals and nvidia-smi indices unjoinable.
+
+ `_resolve_visible_physical_ids()` returns None there, so `_integrated_cuda_gpu_ids`
+ falls back to the ordinal, while `_visible_devices_mask` also returns None and the
+ CLI rows are NOT filtered to match. Re-pricing row 1 because ordinal 1 is integrated
+ would advertise a discrete card with a system-RAM-sized pool.
+ """
+ _llama_common(monkeypatch, avail_mib = 43000)
+ # A real UUID mask: `_resolve_visible_physical_ids` cannot parse it, and neither can
+ # `_visible_devices_mask`, so the CLI rows are never filtered to match. PCI_BUS_ID
+ # ordering does not help, and main.py sets it by default, so the refusal cannot be
+ # left to the ordering alone.
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-deadbeef-0000-0000-0000-000000000003")
+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
+ monkeypatch.setattr(LlamaCppBackend, "_integrated_cuda_gpu_ids", staticmethod(lambda: {1}))
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_integrated_cuda_pool_total_mib",
+ staticmethod(lambda: {1: N1X_POOL_MIB}),
+ )
+ smi_rows = [(0, 2256, N1X_CARVE_OUT_MIB), (1, 20000, 24564)]
+
+ assert LlamaCppBackend._widen_integrated_cuda_rows(list(smi_rows)) == smi_rows
+
+
+def test_a_blank_total_is_still_filled_on_a_discrete_card(monkeypatch):
+ """MIG and vGPU rows read [N/A] for memory.total on a card that is not integrated.
+
+ Filling those was this function's original job and is not part of the widening; a
+ row left blank sends the whole response down get_backend_visible_gpu_info's torch
+ fallback instead of publishing the nvidia-smi rows it already has.
+ """
+ _cuda_host(monkeypatch, _DiscreteProps())
+ devices = [{"index": 0, "visible_ordinal": 0, "memory_total_gb": None}]
+
+ complete = hw._repair_smi_visible_devices(devices, [0])
+
+ assert complete is True
+ assert devices[0]["memory_total_gb"] == 24.0
+ assert devices[0].get("unified_memory") is not True
+ assert devices[0].get("shared_memory") is not True
+
+
+def test_a_numeric_mask_under_fastest_first_refuses_the_join(monkeypatch):
+ """A numeric CUDA_VISIBLE_DEVICES carries CUDA's indices, not PCI ones.
+
+ CUDA_DEVICE_ORDER defaults to FASTEST_FIRST, which pins only device 0 and leaves the
+ rest unspecified, while nvidia-smi numbers by the kernel's NVML enumeration. Joining
+ the two spaces can hand a discrete card the shared pool, so the widening is refused
+ unless the ordering is provably PCI_BUS_ID.
+ """
+ _llama_common(monkeypatch, avail_mib = 43000)
+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")
+ monkeypatch.setattr(
+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: [0, 1])
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_integrated_cuda_gpu_ids", staticmethod(lambda: {1}))
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_integrated_cuda_pool_total_mib",
+ staticmethod(lambda: {1: N1X_POOL_MIB}),
+ )
+ smi_rows = [(0, 2256, N1X_CARVE_OUT_MIB), (1, 20000, 24564)]
+
+ assert LlamaCppBackend._widen_integrated_cuda_rows(list(smi_rows)) == smi_rows
+
+ # PCI_BUS_ID makes the same join provable, so the integrated row widens.
+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
+ widened = LlamaCppBackend._widen_integrated_cuda_rows(list(smi_rows))
+ assert widened[0] == smi_rows[0]
+ assert widened[1][2] == N1X_POOL_MIB
+
+
+def test_the_widened_utilization_is_capped_by_the_cgroup(monkeypatch):
+ """psutil reads host-wide counters in most containers, and unified-memory
+ allocations are charged to memory.max, so the published free bytes must not exceed
+ what this process can still charge."""
+ _cuda_host(monkeypatch, _N1XProps())
+ _host_memory(monkeypatch)
+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: 2048))
+ utilization = {
+ "devices": [
+ {
+ "index": 0,
+ "visible_ordinal": 0,
+ "vram_total_gb": N1X_CARVE_OUT_GB,
+ "vram_used_gb": N1X_USED_GB,
+ "vram_utilization_pct": 72.2,
+ }
+ ]
+ }
+
+ hw._reconcile_cuda_integrated_memory(utilization, [0])
+ device = utilization["devices"][0]
+
+ assert device["vram_total_gb"] == N1X_POOL_GB
+ free_gb = device["vram_total_gb"] - device["vram_used_gb"]
+ assert free_gb == pytest.approx(2.0, abs = 0.01), device
+
+
+def test_one_surviving_row_is_not_proof_of_one_gpu(monkeypatch):
+ """`gpus` is what survived parsing, not what the host has.
+
+ The N1X's own NPU row is dropped because its memory.free does not parse, so a
+ single surviving row says nothing about how many cards are present: a host whose
+ DISCRETE row dropped would otherwise have had that row widened under an ordering
+ that cannot be joined.
+ """
+ _llama_common(monkeypatch, avail_mib = 43000)
+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")
+ monkeypatch.setattr(LlamaCppBackend, "_integrated_cuda_gpu_ids", staticmethod(lambda: {1}))
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_integrated_cuda_pool_total_mib",
+ staticmethod(lambda: {1: N1X_POOL_MIB}),
+ )
+ # Index 1 here is the DISCRETE card; the integrated part is the row that dropped.
+ smi_rows = [(1, 20000, 24564)]
+
+ assert LlamaCppBackend._widen_integrated_cuda_rows(list(smi_rows)) == smi_rows
+
+
+def test_the_nvml_fallback_is_widened_too(monkeypatch):
+ """nvidia-smi IS NVML, so the fallback reports the same carve-out.
+
+ It is reached whenever the CLI is absent, hung or unparseable, and returning its
+ raw rows reproduced the fit failure this change exists to remove.
+ """
+ _integrated_llama_host(monkeypatch)
+ # The nvidia-smi arm finds nothing, so the NVML arm answers.
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: types.SimpleNamespace(returncode = 1, stdout = "", stderr = "no smi"),
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_get_gpu_memory_nvml",
+ staticmethod(lambda: [(0, 2256, N1X_CARVE_OUT_MIB)]),
+ )
+
+ rows = LlamaCppBackend._get_gpu_memory()
+
+ assert rows[0][2] == N1X_POOL_MIB, rows
+ assert rows[0][1] > N1X_CARVE_OUT_MIB, rows
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 9ccfc82d56e..762b3473822 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -3813,58 +3813,167 @@ def _integrated_cuda_inventory(
return {td["index"]: td for td in inventory}, "index"
-def _reconcile_cuda_integrated_memory(
- utilization: Dict[str, Any], device_indices: Optional[list[int]]
-) -> None:
- """Fill the VRAM columns nvidia-smi leaves at ``[N/A]`` on an integrated CUDA SoC.
+# props.total_memory is exact bytes, nvidia-smi rounds to whole MiB, so agreeing
+# sources still differ by a hair. 1% floored at 64 MiB separates that from a carve-out,
+# which is small by a multiple (8128 against 46477 MiB, measured).
+_INTEGRATED_TOTAL_ADOPT_FRACTION = 0.01
+_INTEGRATED_TOTAL_ADOPT_FLOOR_GB = 0.0625
+
+
+def _integrated_total_is_understated(
+ cli_total_gb: Optional[float], torch_total_gb: Optional[float]
+) -> bool:
+ """Whether an integrated part's CLI total is smaller than the pool torch can reach.
+
+ ``None`` from the CLI is the DGX Spark shape: nvidia-smi answers ``[N/A]`` for
+ memory.total, which NVIDIA documents, and anything is wider than nothing. A NUMBER
+ from the CLI is the Windows RTX Spark N1X shape, where the figure is real, readable
+ and scoped to the dedicated carve-out rather than to the CUDA budget.
- The monitor names a Spark's GB10 and prints "Unknown / 0.00 GiB" beside it (#10691).
+ Only ever True for a LARGER torch total, which is what makes every caller below a
+ widening and never a shrink.
+ """
+ if torch_total_gb is None or torch_total_gb <= 0:
+ return False
+ if cli_total_gb is None:
+ return True
+ return torch_total_gb - cli_total_gb > max(
+ cli_total_gb * _INTEGRATED_TOTAL_ADOPT_FRACTION, _INTEGRATED_TOTAL_ADOPT_FLOOR_GB
+ )
+
+
+def _integrated_cuda_rows(
+ device_indices: Optional[list[int]],
+) -> tuple[Dict[Any, Dict[str, Any]], str]:
+ """``_integrated_cuda_inventory`` reduced to the rows torch calls integrated.
+
+ Deliberately NOT cached. The old check was "is a total missing", which a discrete
+ host answers no to without touching torch; widening a total nvidia-smi DID answer
+ cannot be decided without asking torch, and this runs on the 3-5 s /api/system poll,
+ so the cost was measured rather than assumed: 7 microseconds, because
+ get_device_properties is answered from the driver's device list and creates no
+ primary context (0 MiB on an RTX Spark N1X, against 116 MiB for mem_get_info). A
+ memo would buy nothing at that price and would have to be invalidated correctly.
+
+ Empty on a discrete host, and on any host the two sources cannot be joined, so every
+ caller keeps whatever the CLI reported.
+ """
+ inventory, key_field = _integrated_cuda_inventory(device_indices)
+ return {k: td for k, td in inventory.items() if td.get("_cuda_integrated")}, key_field
+
+
+def _cgroup_available_memory_gb() -> Optional[float]:
+ """What this process can still charge to an enforcing cgroup, or None.
+
+ Reuses the llama.cpp reader rather than a second copy: it walks the process's
+ cgroup AND its ancestors, since an ancestor slice can be the binding limit and
+ carries sibling usage a leaf never sees, and it handles v2 and legacy v1.
+ Imported lazily and only from the widening branch, so a discrete host, which
+ returns before ever reaching here, pays nothing for it.
+ """
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ mib = LlamaCppBackend._cgroup_available_memory_mib()
+ return None if mib is None else mib / 1024.0
+ except Exception as e: # noqa: BLE001 - no readable limit means keep the host reading
+ logger.debug("cgroup budget probe failed while sizing an integrated GPU: %s", e)
+ return None
+
+
+def _host_memory_used_gb() -> Optional[float]:
+ """Host memory in use, or None. On one shared pool this is not an approximation of
+ the GPU's used half, it is the same measurement."""
+ try:
+ import psutil
+ vm = psutil.virtual_memory()
+ return round((int(vm.total) - int(vm.available)) / (1024**3), 2)
+ except Exception as e: # noqa: BLE001 - a total alone still beats Unknown / 0.00
+ logger.debug("host memory probe failed while sizing an integrated GPU: %s", e)
+ return None
- NOT _torch_get_per_device_info, which the ROCm twin above can afford and this cannot:
- this is the /api/system poll, and mem_get_info pins a ~612 MiB primary context for
- the life of the process (test_system_poll_no_cuda_context.py). Both figures here are
- context-free. Host counters are not an approximation of the used half on one shared
- pool, they are the same measurement.
- Writes only what the CLI could not answer, only on a confirmed integrated device.
+def _reconcile_cuda_integrated_memory(
+ utilization: Dict[str, Any], device_indices: Optional[list[int]]
+) -> None:
+ """Publish the pool an integrated CUDA SoC can reach, not its dedicated carve-out.
+
+ Two shapes of one fault. On a DGX Spark nvidia-smi answers ``[N/A]`` for
+ memory.total and the monitor printed "Unknown / 0.00 GiB" beside a 121 GiB part
+ (#10691). On a Windows RTX Spark N1X it answers a number, 8128 MiB, which is the
+ carve-out and not the 46477 MiB budget the same device reports through
+ ``props.total_memory``: an under-report of about 5.7x, which judged a 270M model
+ not to fit. Filling only the blanks repaired the first and left the second standing,
+ because a wrong number is not a missing one.
+
+ NOT _torch_get_per_device_info, which the ROCm twin above can afford and this
+ cannot: this is the /api/system poll, and mem_get_info pins a primary context for
+ the life of the process (test_system_poll_no_cuda_context.py). Both figures here
+ are context-free.
+
+ Widens only, in both directions it could be read: a total the CLI reported LARGER
+ than torch's is left alone, and the free bytes published here are floored at the
+ free bytes the row already promised, so no device loses capacity it was trusted
+ with before this ran.
"""
- missing = [dev for dev in utilization.get("devices", []) if dev.get("vram_total_gb") is None]
- if not missing:
+ devices = utilization.get("devices", [])
+ if not devices:
return
try:
- inventory, key_field = _integrated_cuda_inventory(device_indices)
+ integrated, key_field = _integrated_cuda_rows(device_indices)
except Exception as e: # noqa: BLE001 - reached on a host that HAS nvidia-smi
logger.debug("torch inventory unavailable while sizing an integrated GPU: %s", e)
return
- integrated = {key: td for key, td in inventory.items() if td.get("_cuda_integrated")}
if not integrated:
+ # Every discrete host leaves here, having paid one memoised classification.
return
- used_gb = None
- try:
- import psutil
- vm = psutil.virtual_memory()
- used_gb = round((int(vm.total) - int(vm.available)) / (1024**3), 2)
- except Exception as e: # noqa: BLE001 - a total alone still beats Unknown / 0.00
- logger.debug("host memory probe failed while sizing an integrated GPU: %s", e)
- for dev in missing:
+
+ host_used_gb = _host_memory_used_gb()
+
+ for dev in devices:
td = integrated.get(dev.get(key_field))
if td is None:
+ # A row torch does not enumerate. An NVIDIA NPU is one: it runs under MCDM
+ # rather than WDDM and the driver publishes no memory telemetry for it at
+ # all, so "unknown" is the only honest answer and nothing here invents one.
continue
total_gb = td["total_gb"]
+ cli_total_gb = dev.get("vram_total_gb")
+ cli_used_gb = dev.get("vram_used_gb")
+ if not _integrated_total_is_understated(cli_total_gb, total_gb):
+ continue
+ # What the row promised before this ran, so widening cannot cost free bytes.
+ cli_free_gb = (
+ max(cli_total_gb - cli_used_gb, 0.0)
+ if cli_total_gb is not None and cli_used_gb is not None
+ else None
+ )
dev["vram_total_gb"] = total_gb
- # The CLI's own used figure wins where it has one: memory.used can be readable
- # on a row whose memory.total is [N/A], and filling the total is exactly what
- # makes the percentage computable. Host counters stand in only where it is not.
- pool_used_gb = dev.get("vram_used_gb")
- if pool_used_gb is None:
- if used_gb is None:
- continue
- pool_used_gb = min(used_gb, total_gb)
- dev["vram_used_gb"] = pool_used_gb
- if dev.get("vram_utilization_pct") is None:
- dev["vram_utilization_pct"] = (
- round((min(pool_used_gb, total_gb) / total_gb) * 100, 1) if total_gb > 0 else None
- )
+
+ # A pool total needs a pool-scoped numerator (_rocm_windows_unified_used_bytes
+ # states the same rule). memory.used is carve-out scoped, so it is a lower bound
+ # like the host counter is: take the larger, neither dominates.
+ numerators = [n for n in (host_used_gb, cli_used_gb) if n is not None]
+ if not numerators:
+ continue
+ pool_used_gb = min(max(numerators), total_gb)
+ if host_used_gb is None and cli_free_gb is not None:
+ # No pool-scoped occupancy left, so pairing the carve-out's used with the
+ # pool total would invent free bytes (45.39/5.73 reads as 39.66 free where
+ # the CLI vouched for 2.21). Widen the total, keep the budget.
+ pool_used_gb = max(pool_used_gb, total_gb - cli_free_gb)
+ if cli_free_gb is not None:
+ # The floor. A host whose RAM is nearly full would otherwise publish a pool
+ # emptier of free bytes than the carve-out reading it replaced.
+ pool_used_gb = min(pool_used_gb, max(total_gb - cli_free_gb, 0.0))
+ # Last, so it beats the floor: psutil reads host-wide counters in most
+ # containers while the allocations are charged to memory.max.
+ cgroup_free_gb = _cgroup_available_memory_gb()
+ if cgroup_free_gb is not None:
+ pool_used_gb = min(max(pool_used_gb, total_gb - cgroup_free_gb), total_gb)
+ dev["vram_used_gb"] = round(pool_used_gb, 2)
+ dev["vram_utilization_pct"] = (
+ round((pool_used_gb / total_gb) * 100, 1) if total_gb > 0 else None
+ )
def _reconcile_primary_rocm_unified_memory(
@@ -5519,32 +5628,41 @@ def _repair_smi_visible_devices(
The integrated flag rides along because the reason the capacity is unreadable is that
this part has no memory of its own, and a total published without it is counted twice.
- A host whose nvidia-smi CAN answer returns above without touching torch, so the 3-5s
- poll is unchanged and a readable part is never reclassified as unified.
+ A readable total is not a right one. nvidia-smi answers 8128 MiB on a Windows RTX
+ Spark N1X, the dedicated carve-out of a part whose CUDA budget is 46477 MiB, so the
+ old shortcut here -- return early whenever every row carried a number -- published a
+ 45 GiB device as a 7.94 GiB one on the System tab while the About tab, which reads
+ torch, showed 45.39 GiB for the same machine. So a BLANK total is still filled on any
+ part, as it always was, and a READABLE one is additionally widened on a confirmed
+ integrated part, and on nothing else.
"""
if not devices:
return False
- if all(dev.get("memory_total_gb") is not None for dev in devices):
- return True
try:
inventory, key_field = _integrated_cuda_inventory(parent_visible_ids)
except Exception as e: # noqa: BLE001 - the caller keeps the rows nvidia-smi found
logger.debug("torch inventory unavailable while repairing a GPU capacity: %s", e)
- return False
+ return all(dev.get("memory_total_gb") is not None for dev in devices)
for dev in devices:
td = inventory.get(dev.get(key_field))
if td is None:
continue
+ # A BLANK total is filled whatever the part is, as this function always did:
+ # dropping that sent MIG and vGPU rows down the torch fallback instead.
if dev.get("memory_total_gb") is None:
dev["memory_total_gb"] = td["total_gb"]
- if td.get("_cuda_integrated"):
- dev["unified_memory"] = True
- # `shared_memory` as well, not just the host-backed figure: gpu-vram.ts
- # splits the pools on THAT flag alone and only then reads the figure, so a
- # row carrying one without the other is added to the dedicated total and
- # counted a second time beside the same system RAM.
- dev["shared_memory"] = True
- dev["shared_memory_host_backed_gb"] = dev["memory_total_gb"]
+ if not td.get("_cuda_integrated"):
+ continue
+ # A READABLE total is only widened on a confirmed integrated part.
+ if _integrated_total_is_understated(dev.get("memory_total_gb"), td["total_gb"]):
+ dev["memory_total_gb"] = td["total_gb"]
+ dev["unified_memory"] = True
+ # `shared_memory` as well, not just the host-backed figure: gpu-vram.ts splits
+ # the pools on THAT flag alone and only then reads the figure, so a row carrying
+ # one without the other is added to the dedicated total and counted a second
+ # time beside the same system RAM.
+ dev["shared_memory"] = True
+ dev["shared_memory_host_backed_gb"] = dev["memory_total_gb"]
return all(dev.get("memory_total_gb") is not None for dev in devices)