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.

fix(studio): distinguish dedicated vram from shared gpu memory (#9242)

yzxcj79793402937c321
diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.py
index 7455e868809..37467fc934f 100644
--- a/studio/backend/tests/test_gpu_selection.py
+++ b/studio/backend/tests/test_gpu_selection.py
@@ -410,8 +410,11 @@ class TestVisibleGpuUtilization(_GpuCacheResetMixin, unittest.TestCase):
self.assertTrue(result["available"])
self.assertEqual(result["index_kind"], "relative")
- self.assertEqual(result["devices"][0]["index"], 0)
- self.assertEqual(result["devices"][0]["visible_ordinal"], 0)
+ device = result["devices"][0]
+ self.assertEqual(device["index"], 0)
+ self.assertEqual(device["visible_ordinal"], 0)
+ self.assertTrue(device["shared_memory"])
+ self.assertEqual(device["shared_memory_host_backed_gb"], 64.0)
def test_discrete_vulkan_inference_gpu_info(self):
with (
diff --git a/studio/backend/tests/test_rocm_windows_vram_7072.py b/studio/backend/tests/test_rocm_windows_vram_7072.py
index d2366791ba2..afd4171f5df 100644
--- a/studio/backend/tests/test_rocm_windows_vram_7072.py
+++ b/studio/backend/tests/test_rocm_windows_vram_7072.py
@@ -557,9 +557,7 @@ IGPU_DGPU_ADAPTERS = [
def test_igpu_and_dgpu_each_report_their_own(win_rocm, monkeypatch):
- """Both visible: two different cards, two counters, and identity says which
- is which. Capacity ranking cannot: the dGPU's 1.2 GiB would also fit the
- 2 GiB iGPU, so the two are swappable and it reports both unknown."""
+ """The dGPU keeps its LUID usage while the shared iGPU declines."""
monkeypatch.setitem(
sys.modules, "torch", _fake_torch(IGPU_DGPU_DEVICES, free_equals_total = True)
)
@@ -576,11 +574,8 @@ def test_igpu_and_dgpu_each_report_their_own(win_rocm, monkeypatch):
)
devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
- assert [d["used_gb"] for d in devices] == [
- pytest.approx(0.5, abs = 0.01),
- pytest.approx(1.2, abs = 0.01),
- ]
- assert aggregate == pytest.approx(1.7, abs = 0.01)
+ assert [d["used_gb"] for d in devices] == [None, pytest.approx(1.2, abs = 0.01)]
+ assert aggregate is None
def test_a_name_the_two_sides_spell_differently_still_joins(win_rocm, monkeypatch):
@@ -602,10 +597,7 @@ def test_a_name_the_two_sides_spell_differently_still_joins(win_rocm, monkeypatc
)
devices, _ = hw._rocm_windows_per_device_vram([0, 1])
- assert [d["used_gb"] for d in devices] == [
- pytest.approx(0.5, abs = 0.01),
- pytest.approx(1.2, abs = 0.01),
- ]
+ assert [d["used_gb"] for d in devices] == [None, pytest.approx(1.2, abs = 0.01)]
def test_the_arch_answers_when_the_names_do_not(win_rocm, monkeypatch):
@@ -627,11 +619,8 @@ def test_the_arch_answers_when_the_names_do_not(win_rocm, monkeypatch):
)
devices, aggregate = hw._rocm_windows_per_device_vram([0, 1])
- assert [d["used_gb"] for d in devices] == [
- pytest.approx(0.5, abs = 0.01),
- pytest.approx(1.2, abs = 0.01),
- ]
- assert aggregate == pytest.approx(1.7, abs = 0.01)
+ assert [d["used_gb"] for d in devices] == [None, pytest.approx(1.2, abs = 0.01)]
+ assert aggregate is None
def test_a_partial_name_pass_still_lets_the_arch_finish_the_job(win_rocm, monkeypatch):
@@ -825,6 +814,29 @@ def test_registry_reads_the_amd_adapters_and_skips_the_rest(on_windows, monkeypa
}
+def test_registry_reads_optional_dedicated_memory(on_windows, monkeypatch):
+ monkeypatch.setitem(
+ sys.modules,
+ "winreg",
+ _fake_winreg(
+ {
+ "{bbbbbbbb-0000-0000-0000-000000000000}": {
+ **AMD_RECORD,
+ "DedicatedVideoMemory": 32 * GB,
+ "DedicatedSystemMemory": 2 * GB,
+ }
+ }
+ ),
+ )
+ assert hw._windows_amd_adapter_records_by_luid() == {
+ 0x14CF5: {
+ "name": "AMD Radeon RX 9060 XT",
+ "gfx": "gfx1200",
+ "dedicated_memory_bytes": 34 * GB,
+ }
+ }
+
+
def test_a_record_that_will_not_read_declines_the_whole_map(on_windows, monkeypatch):
"""A partial map is indistinguishable from a complete one at the join, which
would then hand a visible card its hidden twin's counter."""
@@ -1287,9 +1299,9 @@ def _mixed_host(monkeypatch):
monkeypatch.setattr(
torch.cuda,
"mem_get_info",
- lambda i: (96 * GB, 128 * GB)
- if i == 0
- else pytest.fail("a discrete card must not be asked"),
+ lambda i: (
+ (96 * GB, 128 * GB) if i == 0 else pytest.fail("a discrete card must not be asked")
+ ),
)
return torch
@@ -1769,12 +1781,12 @@ def test_the_windows_path_is_inert_off_windows(win_rocm, monkeypatch, system):
# ----------------------------------------------------------------------------- #
-# An APU the shared classifier cannot name
+# an apu the shared classifier cannot name without the exact-arch extension
#
# _rocm_classify_unified_memory names an APU from hipDeviceProp_t::integrated or
# from the shared-pool arch set that drives the memory-fraction cap. A gfx1103
-# Phoenix iGPU on a runtime that leaves the flag at 0 is in neither, so
-# _rocm_props_are_positively_unified said no -- while on Windows PAL had already
+# phoenix igpu on a runtime that leaves the flag at 0 is in neither, while on
+# windows pal has already
# added the WDDM shared heap to globalMemSize_ for it, because that inflation
# keys off Pal::GpuType::Integrated and not off what the props struct reports.
#
@@ -1824,7 +1836,7 @@ def _phoenix_host(
return torch
-def test_a_phoenix_apu_the_classifier_misses_reads_as_an_unnamed_apu(win_rocm):
+def test_a_phoenix_apu_is_positively_unified_by_exact_arch(win_rocm):
"""gfx1103 is an integrated part and never shipped as a discrete board, so
naming it cannot upgrade anything whose total is really carve-out scoped."""
@@ -1834,15 +1846,14 @@ def test_a_phoenix_apu_the_classifier_misses_reads_as_an_unnamed_apu(win_rocm):
total_memory = int(PHOENIX_POOL)
is_integrated = 0 # pre-6.2 HIP leaves it 0 on Windows
- assert hw._rocm_props_are_positively_unified(_P()) is False # unchanged
- assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+ assert hw._rocm_props_are_positively_unified(_P()) is True
_P.gcnArchName = "gfx1103:xnack-" # suffixes and case must not hide it
- assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+ assert hw._rocm_props_are_positively_unified(_P()) is True
_P.gcnArchName = "GFX1103"
- assert hw._rocm_props_are_an_unnamed_apu(_P()) is True
+ assert hw._rocm_props_are_positively_unified(_P()) is True
-def test_a_discrete_card_is_neither_positively_unified_nor_an_unnamed_apu(win_rocm):
+def test_a_discrete_card_is_not_positively_unified(win_rocm):
"""The guarantee the numerator rests on: shared bytes are host memory a
discrete card's props.total_memory never counted."""
@@ -1853,10 +1864,8 @@ def test_a_discrete_card_is_neither_positively_unified_nor_an_unnamed_apu(win_ro
is_integrated = 0
assert hw._rocm_props_are_positively_unified(_P()) is False
- assert hw._rocm_props_are_an_unnamed_apu(_P()) is False
_P.gcnArchName, _P.name = "gfx1201", "AMD Radeon RX 9070 XT"
assert hw._rocm_props_are_positively_unified(_P()) is False
- assert hw._rocm_props_are_an_unnamed_apu(_P()) is False
def test_a_phoenix_pool_total_takes_the_shared_sum_not_the_plateau(win_rocm, monkeypatch):
diff --git a/studio/backend/tests/test_system_poll_no_cuda_context.py b/studio/backend/tests/test_system_poll_no_cuda_context.py
index a3e944ae7b0..a9de34923ec 100644
--- a/studio/backend/tests/test_system_poll_no_cuda_context.py
+++ b/studio/backend/tests/test_system_poll_no_cuda_context.py
@@ -857,6 +857,7 @@ def test_inventory_totals_match_the_occupancy_path(monkeypatch, totals):
assert [d["index"] for d in inventory] == [d["index"] for d in occupancy]
assert [d["visible_ordinal"] for d in inventory] == [d["visible_ordinal"] for d in occupancy]
assert all(d["used_gb"] is None for d in inventory)
+ assert all(d["shared_memory"] is False for d in inventory)
def test_inventory_never_touches_mem_get_info(monkeypatch):
@@ -907,6 +908,7 @@ def test_visibility_endpoint_uses_inventory_not_occupancy(monkeypatch):
"name": "MI300X",
"total_gb": 192.0,
"used_gb": None,
+ "shared_memory": False,
},
{
"index": 1,
@@ -914,6 +916,7 @@ def test_visibility_endpoint_uses_inventory_not_occupancy(monkeypatch):
"name": "MI300X",
"total_gb": 192.0,
"used_gb": None,
+ "shared_memory": True,
},
],
)
@@ -921,6 +924,7 @@ def test_visibility_endpoint_uses_inventory_not_occupancy(monkeypatch):
assert result["available"] is True
assert [d["memory_total_gb"] for d in result["devices"]] == [192.0, 192.0]
assert [d["name"] for d in result["devices"]] == ["MI300X", "MI300X"]
+ assert [d["shared_memory"] for d in result["devices"]] == [False, True]
assert result["index_kind"] == "physical"
@@ -964,6 +968,8 @@ def test_rocm_apu_inventory_keeps_the_gtt_total(monkeypatch):
assert inventory[0]["total_gb"] == occupancy[0]["total_gb"] == 100.0
assert inventory[0]["total_gb"] != round(_APU_CARVE_OUT / (1024**3), 2)
+ assert inventory[0]["shared_memory"] is True
+ assert inventory[0]["shared_memory_host_backed_gb"] == 92.0
class _FakeRocmProps(_FakeProps):
@@ -995,7 +1001,9 @@ def test_rocm_discrete_inventory_stays_context_free(monkeypatch):
monkeypatch.setattr(hw, "IS_ROCM", True)
monkeypatch.setattr(hw, "_hip_runtime_version", lambda: (6, 4))
monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
- assert hw._torch_get_device_inventory([0])[0]["total_gb"] == 178.35
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 178.35
+ assert inventory["shared_memory"] is False
def test_an_apu_shaped_name_on_cuda_stays_context_free(monkeypatch):
@@ -1017,7 +1025,323 @@ def test_rocm_apu_keeps_the_carve_out_when_the_driver_total_fails(monkeypatch):
mod.mem_get_info = _fail
monkeypatch.setattr(hw, "IS_ROCM", True)
monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
- assert [d["total_gb"] for d in hw._torch_get_device_inventory([0])] == [8.0]
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 8.0
+ assert inventory["shared_memory"] is False
+
+
+def test_windows_rocm_apu_keeps_shared_scope_when_driver_total_fails(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+
+ def _fail(o):
+ raise RuntimeError("hipMemGetInfo unavailable")
+
+ mod.mem_get_info = _fail
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is True
+ assert inventory["shared_memory_host_backed_gb"] is None
+
+
[email protected](("system", "expected_shared"), [("Linux", False), ("Windows", True)])
+def test_rocm_apu_equal_driver_total_scope_is_platform_specific(
+ monkeypatch, system, expected_shared
+):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: system)
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is expected_shared
+
+
+def test_windows_rocm_apu_reports_only_the_host_backed_pool_overlap(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x14CF5: {
+ "name": "AMD Radeon(TM) 8060S Graphics",
+ "dedicated_memory_bytes": 32 * 1024**3,
+ }
+ },
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["shared_memory"] is True
+ assert result["devices"][0]["memory_total_gb"] == 100.0
+ assert result["devices"][0]["shared_memory_host_backed_gb"] == 68.0
+
+
+def test_windows_rocm_apu_uses_arch_when_registry_name_differs(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x14CF5: {
+ "name": "AMD Radeon(TM) Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 32 * 1024**3,
+ },
+ 0x24CF5: {
+ "name": "AMD Radeon 8060S Graphics",
+ "gfx": "gfx1103",
+ "dedicated_memory_bytes": 2 * 1024**3,
+ },
+ },
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["shared_memory_host_backed_gb"] == 68.0
+
+
+def test_windows_rocm_apu_declines_an_ambiguous_arch_fallback(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x14CF5: {
+ "name": "AMD Radeon(TM) Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 32 * 1024**3,
+ },
+ 0x24CF5: {
+ "name": "AMD Radeon(TM) Graphics 2",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 16 * 1024**3,
+ },
+ },
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["shared_memory_host_backed_gb"] is None
+
+
+def test_windows_rocm_apu_accepts_equal_duplicate_carve_outs(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x14CF5: {
+ "name": "AMD Radeon 8060S Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ 0x24CF5: {
+ "name": "AMD Radeon 8060S Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ },
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["shared_memory_host_backed_gb"] == 92.0
+
+
+def test_windows_rocm_apu_declines_a_conflicting_arch_candidate(monkeypatch):
+ mod = _apu_mod(gtt_total = _APU_GTT_TOTAL, carve_out = _APU_GTT_TOTAL)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x14CF5: {
+ "name": "AMD Radeon 8060S Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ 0x24CF5: {
+ "name": "AMD Radeon 8060S Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ 0x34CF5: {
+ "name": "AMD Radeon(TM) Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 32 * 1024**3,
+ },
+ },
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["shared_memory_host_backed_gb"] is None
+
+
+def test_windows_rocm_shared_pool_requires_a_complete_record_matching(monkeypatch):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(
+ hw,
+ "_windows_amd_adapter_records_by_luid",
+ lambda: {
+ 0x01: {"name": "AMD Radeon Graphics", "dedicated_memory_bytes": 8 * 1024**3},
+ 0x02: {
+ "name": "AMD Radeon Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ 0x03: {
+ "name": "AMD Radeon Graphics",
+ "gfx": "gfx1151",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ },
+ 0x04: {
+ "name": "AMD Radeon 780M",
+ "gfx": "gfx1103",
+ "dedicated_memory_bytes": 16 * 1024**3,
+ },
+ 0x05: {
+ "name": "AMD Radeon 8060S",
+ "gfx": "gfx1150",
+ "dedicated_memory_bytes": 32 * 1024**3,
+ },
+ },
+ )
+ devices = [
+ {
+ "index": index,
+ "name": "AMD Radeon Graphics",
+ "total_gb": 100.0,
+ "shared_memory": True,
+ "_rocm_gfx": gfx,
+ }
+ for index, gfx in enumerate(("gfx1103", "gfx1150", "gfx1151"))
+ ]
+
+ assert hw._windows_rocm_shared_pool_host_gb_by_index(devices) == {}
+
+
+ ("torch_total", "sysfs_total", "expected_shared"),
+ [(_APU_GTT_TOTAL, _APU_CARVE_OUT, True), (_APU_CARVE_OUT, _APU_CARVE_OUT, False)],
+)
[email protected](("hip_mask", "cuda_mask"), [(None, None), ("0", None), ("0", "0")])
+def test_linux_rocm_apu_uses_sysfs_to_confirm_equal_total_scope(
+ monkeypatch, torch_total, sysfs_total, expected_shared, hip_mask, cuda_mask
+):
+ mod = _apu_mod(gtt_total = torch_total, carve_out = torch_total)
+ for var in (
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "CUDA_VISIBLE_DEVICES",
+ "GPU_DEVICE_ORDINAL",
+ ):
+ monkeypatch.delenv(var, raising = False)
+ if hip_mask is not None:
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", hip_mask)
+ if cuda_mask is not None:
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", cuda_mask)
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ monkeypatch.setattr(hw, "_rocm_kfd_gpu_pci_ids", lambda: {0: "0000:03:00.0"})
+ monkeypatch.setattr(
+ hw,
+ "_rocm_linux_sysfs_vram_by_pci_gb",
+ lambda: {"0000:03:00.0": (1.0, sysfs_total / (1024**3))},
+ )
+
+ result = hw.get_backend_visible_gpu_info()
+
+ assert result["devices"][0]["memory_total_gb"] == torch_total / (1024**3)
+ assert result["devices"][0]["shared_memory"] is expected_shared
+ assert result["devices"][0]["shared_memory_host_backed_gb"] == (
+ round((torch_total - sysfs_total) / (1024**3), 2) if expected_shared else None
+ )
+
+
[email protected]("ambiguous_var", ["ROCR_VISIBLE_DEVICES", "GPU_DEVICE_ORDINAL"])
+def test_linux_rocm_shared_pool_declines_ambiguous_masks(monkeypatch, ambiguous_var):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.setenv(ambiguous_var, "0")
+ monkeypatch.setattr(hw, "_rocm_kfd_gpu_pci_ids", lambda: {0: "0000:03:00.0"})
+ monkeypatch.setattr(
+ hw, "_rocm_linux_sysfs_vram_by_pci_gb", lambda: {"0000:03:00.0": (1.0, 8.0)}
+ )
+ devices = [{"index": 0, "total_gb": 100.0, "_rocm_known_unified": True}]
+
+ assert hw._rocm_linux_shared_pool_host_gb_by_index(devices) == {}
+
+
+def test_linux_rocm_shared_pool_declines_a_compacted_numeric_mask(monkeypatch):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("GPU_DEVICE_ORDINAL", raising = False)
+ monkeypatch.setattr(
+ hw,
+ "_rocm_kfd_gpu_pci_ids",
+ lambda: {0: "0000:03:00.0", 1: "0000:04:00.0"},
+ )
+ monkeypatch.setattr(
+ hw,
+ "_rocm_linux_sysfs_vram_by_pci_gb",
+ lambda: {
+ "0000:03:00.0": (1.0, 8.0),
+ "0000:04:00.0": (1.0, 16.0),
+ },
+ )
+ devices = [{"index": 0, "total_gb": 100.0, "_rocm_known_unified": True}]
+
+ assert hw._rocm_linux_shared_pool_host_gb_by_index(devices) == {}
+
+
+def test_linux_rocm_shared_pool_maps_lone_uuid_mask(monkeypatch):
+ monkeypatch.setattr(hw.platform, "system", lambda: "Linux")
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("GPU_DEVICE_ORDINAL", raising = False)
+ monkeypatch.setenv("ROCR_VISIBLE_DEVICES", "GPU-DEADBEEFDEADBEEF")
+ monkeypatch.setattr(hw, "_rocm_kfd_gpu_pci_ids", lambda: {0: "0000:03:00.0"})
+ monkeypatch.setattr(
+ hw,
+ "_rocm_linux_sysfs_vram_by_pci_gb",
+ lambda: {"0000:03:00.0": (1.0, 8.0)},
+ )
+ devices = [{"index": 0, "total_gb": 100.0, "_rocm_known_unified": True}]
+
+ assert hw._rocm_linux_shared_pool_host_gb_by_index(devices) == {0: 92.0}
def test_rocm_apu_sysfs_overlay_still_declines_against_the_gtt_total(monkeypatch):
@@ -1068,7 +1392,19 @@ def test_rocm_unclassified_apu_keeps_the_driver_total_on_an_older_runtime(monkey
monkeypatch.setattr(hw, "IS_ROCM", True)
monkeypatch.setattr(hw, "_hip_runtime_version", lambda: (6, 1))
monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
- assert hw._torch_get_device_inventory([0])[0]["total_gb"] == 100.0
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is True
+
+
+def test_rocm_unclassified_apu_keeps_the_driver_total_with_a_legacy_flag(monkeypatch):
+ mod = _rocm_mod(_FakeUnclassifiedApuProps())
+ monkeypatch.setattr(hw, "IS_ROCM", True)
+ monkeypatch.setattr(hw, "_hip_runtime_version", lambda: (6, 4))
+ monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is True
def test_rocm_unclassified_apu_keeps_the_driver_total_without_the_flag(monkeypatch):
@@ -1078,7 +1414,9 @@ def test_rocm_unclassified_apu_keeps_the_driver_total_without_the_flag(monkeypat
monkeypatch.setattr(hw, "IS_ROCM", True)
monkeypatch.setattr(hw, "_hip_runtime_version", lambda: (6, 4))
monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
- assert hw._torch_get_device_inventory([0])[0]["total_gb"] == 100.0
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is True
def test_rocm_props_that_cannot_be_classified_keep_the_driver_total(monkeypatch):
@@ -1094,7 +1432,9 @@ def test_rocm_props_that_cannot_be_classified_keep_the_driver_total(monkeypatch)
monkeypatch.setattr(hw, "IS_ROCM", True)
monkeypatch.setattr(hw, "_hip_runtime_version", lambda: (6, 4))
monkeypatch.setattr(hw, "_torch_get_device_module", lambda: (mod, "cuda"))
- assert hw._torch_get_device_inventory([0])[0]["total_gb"] == 100.0
+ inventory = hw._torch_get_device_inventory([0])[0]
+ assert inventory["total_gb"] == 100.0
+ assert inventory["shared_memory"] is False
def test_hip_runtime_version_reads_both_wheel_spellings(monkeypatch):
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index d143c251c2e..18555413772 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -1466,6 +1466,20 @@ def _hip_runtime_version() -> Optional[tuple[int, int]]:
_ROCM_UNNAMED_APU_ARCHES = frozenset({"gfx1103"})
+def _rocm_props_unified_status(props: Any) -> Optional[bool]:
+ try:
+ from core.training.worker import _rocm_classify_unified_memory
+
+ classification = _rocm_classify_unified_memory(props)
+ arch = str(classification[0] or "")
+ return bool(classification[1]) or (
+ arch.split(":")[0].strip().lower() in _ROCM_UNNAMED_APU_ARCHES
+ )
+ except Exception as e:
+ logger.debug("ROCm unified-memory classification failed: %s", e)
+ return None
+
+
def _rocm_props_are_positively_unified(props: Any) -> bool:
"""Whether this part is KNOWN to be unified memory, not merely unclassified.
@@ -1487,36 +1501,7 @@ def _rocm_props_are_positively_unified(props: Any) -> bool:
"""
if not IS_ROCM:
return False
- try:
- from core.training.worker import _rocm_classify_unified_memory
- return bool(_rocm_classify_unified_memory(props)[1])
- except Exception as e:
- logger.debug("ROCm unified-memory classification failed: %s", e)
- return False
-
-
-def _rocm_props_are_an_unnamed_apu(props: Any) -> bool:
- """True for an APU arch the shared classifier's positive set omits.
-
- Only ever asked of a LONE visible device, and only to settle the numerator.
- Beside a discrete card the same chip's props.total_memory is the one number
- this module cannot scope -- #9198 keeps a hybrid iGPU on its carve-out for
- exactly that reason, and the Dedicated+Shared sum needs a single adapter
- above the noise floor to be attributable in the first place, so upgrading
- there could only take a reading away. On a lone APU neither applies.
-
- Indexed rather than unpacked so a classifier that grows its tuple (#9198)
- keeps working.
- """
- if not IS_ROCM:
- return False
- try:
- from core.training.worker import _rocm_classify_unified_memory
- arch = str(_rocm_classify_unified_memory(props)[0] or "")
- except Exception as e:
- logger.debug("ROCm unified-memory classification failed: %s", e)
- return False
- return arch.split(":")[0].strip().lower() in _ROCM_UNNAMED_APU_ARCHES
+ return _rocm_props_unified_status(props) is True
def _rocm_props_total_is_carve_out(props: Any) -> bool:
@@ -1552,12 +1537,7 @@ def _rocm_props_total_is_carve_out(props: Any) -> bool:
"""
if not IS_ROCM:
return False
- try:
- from core.training.worker import _rocm_classify_unified_memory
- if _rocm_classify_unified_memory(props)[1]:
- return True
- except Exception as e:
- logger.debug("ROCm unified-memory classification failed: %s", e)
+ if _rocm_props_unified_status(props) is not False:
return True
hip_version = _hip_runtime_version()
return (
@@ -1591,18 +1571,36 @@ def _torch_get_device_inventory(device_indices: list[int]) -> list[Dict[str, Any
try:
# torch ordinals are 0-based relative to CUDA_VISIBLE_DEVICES.
props = mod.get_device_properties(ordinal)
- total_bytes = props.total_memory
+ props_total_bytes = int(props.total_memory)
+ total_bytes = props_total_bytes
+ known_unified = _rocm_props_are_positively_unified(props)
+ shared_memory = known_unified and platform.system() == "Windows"
+ shared_memory_host_backed_bytes = None
try:
if _rocm_props_total_is_carve_out(props) and hasattr(mod, "mem_get_info"):
# Only a WIDER total, same as _rocm_windows_per_device_vram.
# The classifier fails open, so a discrete card reaches here
# too, and a total below props.total_memory would hide models
# this device can hold.
- total_bytes = max(int(mod.mem_get_info(ordinal)[1]), int(total_bytes))
+ driver_total_bytes = int(mod.mem_get_info(ordinal)[1])
+ shared_memory = known_unified and (
+ driver_total_bytes > int(total_bytes)
+ or (
+ platform.system() == "Windows"
+ and driver_total_bytes == int(total_bytes)
+ )
+ )
+ if shared_memory and driver_total_bytes > props_total_bytes:
+ shared_memory_host_backed_bytes = driver_total_bytes - props_total_bytes
+ total_bytes = max(driver_total_bytes, int(total_bytes))
except Exception as e:
# Keep the carve-out rather than dropping the device: an
# understated total still beats no device at all.
logger.debug("ROCm APU driver total failed for ordinal %d: %s", ordinal, e)
+ try:
+ rocm_gfx = str(getattr(props, "gcnArchName", "") or "")
+ except Exception:
+ rocm_gfx = ""
devices.append(
{
"index": phys_idx,
@@ -1610,6 +1608,14 @@ def _torch_get_device_inventory(device_indices: list[int]) -> list[Dict[str, Any
"name": props.name,
"total_gb": round(total_bytes / (1024**3), 2),
"used_gb": None,
+ "shared_memory": shared_memory,
+ "shared_memory_host_backed_gb": (
+ round(shared_memory_host_backed_bytes / (1024**3), 2)
+ if shared_memory_host_backed_bytes is not None
+ else None
+ ),
+ "_rocm_known_unified": known_unified,
+ "_rocm_gfx": rocm_gfx,
}
)
except Exception as e:
@@ -2253,10 +2259,11 @@ def _parse_adapter_family_gfx(family: str) -> str:
return ""
-def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
- """``{luid: {"name": description, "gfx": arch}}`` for the AMD adapters DirectX records.
+def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, Any]]:
+ """DirectX registry metadata for AMD adapters, keyed by LUID.
``gfx`` is absent when the driver wrote no ``AdapterFamily``.
+ ``dedicated_memory_bytes`` is absent when neither dedicated-memory value is available.
All or nothing: a record this cannot read makes the map incomplete, and an
incomplete map is indistinguishable from a complete one at the join, which
@@ -2271,7 +2278,7 @@ def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
import winreg
except ImportError:
return {}
- by_luid: dict[int, Dict[str, str]] = {}
+ by_luid: dict[int, Dict[str, Any]] = {}
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _WINDOWS_DIRECTX_KEY) as dx_key:
for index in range(winreg.QueryInfoKey(dx_key)[0]):
@@ -2290,6 +2297,18 @@ def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
family, _ = winreg.QueryValueEx(adapter_key, "AdapterFamily")
except OSError:
family = ""
+ dedicated_memory_bytes = 0
+ has_dedicated_memory = False
+ for value_name in ("DedicatedVideoMemory", "DedicatedSystemMemory"):
+ try:
+ value, _ = winreg.QueryValueEx(adapter_key, value_name)
+ value = int(value)
+ if value < 0:
+ raise ValueError(value)
+ dedicated_memory_bytes += value
+ has_dedicated_memory = True
+ except (OSError, TypeError, ValueError):
+ pass
name = str(description).strip()
if not name:
# An AMD adapter this cannot name: see the all-or-nothing note.
@@ -2298,6 +2317,8 @@ def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
gfx = _parse_adapter_family_gfx(str(family))
if gfx:
record["gfx"] = gfx
+ if has_dedicated_memory:
+ record["dedicated_memory_bytes"] = dedicated_memory_bytes
by_luid[int(luid)] = record
except Exception as e:
logger.debug("DirectX adapter registry read declined: %s", e)
@@ -2305,6 +2326,99 @@ def _windows_amd_adapter_records_by_luid() -> dict[int, Dict[str, str]]:
return by_luid
+def _windows_rocm_shared_pool_host_gb_by_index(devices: list[Dict[str, Any]]) -> Dict[int, float]:
+ """Map shared ROCm devices to the host-backed part of their Windows pool."""
+ if platform.system() != "Windows":
+ return {}
+ records = list(_windows_amd_adapter_records_by_luid().values())
+ shared_positions = [
+ position for position, device in enumerate(devices) if device.get("shared_memory")
+ ]
+ gfx_available = (
+ bool(records)
+ and all(record.get("gfx") for record in records)
+ and all(devices[position].get("_rocm_gfx") for position in shared_positions)
+ )
+ candidates_by_position: dict[int, set[int]] = {}
+ for position in shared_positions:
+ device = devices[position]
+ device_name = _normalize_adapter_name(str(device.get("name", "")))
+ device_gfx = _parse_adapter_family_gfx(str(device.get("_rocm_gfx", "")))
+ candidates: set[int] = set()
+ for record_position, record in enumerate(records):
+ record_name = _normalize_adapter_name(str(record.get("name", "")))
+ record_gfx = _parse_adapter_family_gfx(str(record.get("gfx", "")))
+ name_matches = bool(device_name) and device_name == record_name
+ if name_matches and device_gfx and record_gfx and device_gfx != record_gfx:
+ name_matches = False
+ gfx_matches = gfx_available and bool(device_gfx) and device_gfx == record_gfx
+ if name_matches or gfx_matches:
+ candidates.add(record_position)
+ if candidates:
+ candidates_by_position[position] = candidates
+
+ dedicated_bytes_by_position: dict[int, int] = {}
+ remaining_positions = set(candidates_by_position)
+ while remaining_positions:
+ first = remaining_positions.pop()
+ component_positions = {first}
+ component_records = set(candidates_by_position[first])
+ while True:
+ connected = {
+ position
+ for position in remaining_positions
+ if candidates_by_position[position] & component_records
+ }
+ if not connected:
+ break
+ remaining_positions -= connected
+ component_positions |= connected
+ for position in connected:
+ component_records |= candidates_by_position[position]
+ if len(component_records) < len(component_positions):
+ continue
+ record_owner: dict[int, int] = {}
+
+ def assign_record(position: int, seen: set[int]) -> bool:
+ for record_position in candidates_by_position[position]:
+ if record_position not in component_records or record_position in seen:
+ continue
+ seen.add(record_position)
+ owner = record_owner.get(record_position)
+ if owner is None or assign_record(owner, seen):
+ record_owner[record_position] = position
+ return True
+ return False
+
+ if not all(assign_record(position, set()) for position in component_positions):
+ continue
+ try:
+ dedicated_values = {
+ int(records[record_position]["dedicated_memory_bytes"])
+ for record_position in component_records
+ }
+ except (KeyError, TypeError, ValueError):
+ continue
+ if len(dedicated_values) != 1:
+ continue
+ dedicated_bytes = dedicated_values.pop()
+ if dedicated_bytes < 0:
+ continue
+ for position in component_positions:
+ dedicated_bytes_by_position[position] = dedicated_bytes
+
+ host_gb_by_index: Dict[int, float] = {}
+ for position, dedicated_bytes in dedicated_bytes_by_position.items():
+ device = devices[position]
+ index = device.get("index")
+ total_gb = float(device.get("total_gb") or 0.0)
+ dedicated_gb = float(dedicated_bytes) / (1024**3)
+ if not isinstance(index, int) or total_gb <= 0 or not (0 <= dedicated_gb <= total_gb):
+ continue
+ host_gb_by_index[index] = round(total_gb - dedicated_gb, 2)
+ return host_gb_by_index
+
+
def _adapter_counter_capacity(meta: Dict[str, Any]) -> float:
"""The capacity a ``Dedicated Usage`` counter for this device can actually fill.
@@ -2719,21 +2833,6 @@ def _rocm_windows_per_device_vram(
# probe that throws must cost this device its correction, not its
# place in the list.
unified = _rocm_props_are_positively_unified(props)
- if not unified and len(device_indices) == 1:
- # The classifier names an APU from hipDeviceProp_t::integrated
- # or from the shared-pool arch set that sizes the memory-fraction
- # cap. A gfx1103 Phoenix on a pre-6.2 runtime is in neither, and
- # PAL does not consult either: it adds the WDDM shared heap to
- # globalMemSize_ for any Pal::GpuType::Integrated part, which is
- # a fact about the DEVICE. So that part reaches here with a
- # pool-scoped total and, unpatched, the Dedicated-only numerator
- # that plateaus at the BIOS carve-out -- the same overstated-free
- # reading on a device the classifier misses. Reported shape: a
- # Windows 780M on 24295 MiB of RAM reads a 17303 MiB total
- # (ComfyUI-Zluda#387), which is an 8 GiB carve-out plus 75% of
- # the WDDM shared heap. Hold 12 GiB there and Dedicated is 7.90,
- # so free publishes as 9.00 with 12 GiB resident.
- unified = _rocm_props_are_an_unnamed_apu(props)
if unified and hasattr(mod, "mem_get_info"):
pool_bytes = int(mod.mem_get_info(ordinal)[1])
# >= not >, and the equal case is the ONLY one that occurs.
@@ -3243,32 +3342,50 @@ def _rocm_visibility_mask_active() -> bool:
return False
-def _rocm_system_wide_vram_by_index(
- devices: list[Dict[str, Any]],
-) -> Dict[int, tuple[float, float]]:
- """Decide the system-wide overlay without applying it.
+def _rocm_single_numeric_mask_matches(devices: list[Dict[str, Any]]) -> bool:
+ if _rocm_device_ordinal_active() or _rocm_visibility_masks_are_stacked():
+ return False
- Returns ``{physical index: (used_gb, total_gb)}`` for every device sysfs can
- speak for, and omits the ones it cannot. Split out from
- _overlay_system_wide_vram so a caller can ask whether sysfs covers the whole
- visible set BEFORE paying torch for occupancy it would then discard. Reads
- only ``vram_total_gb`` off ``devices``; it never mutates them.
- """
+ selected_mask = None
+ for var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ if var in os.environ:
+ selected_mask = os.environ[var]
+ break
+ if selected_mask is None:
+ return False
+ tokens = [token.strip() for token in selected_mask.split(",") if token.strip()]
+ try:
+ numeric_ids = [int(token) for token in tokens]
+ except ValueError:
+ return False
+ return len(set(numeric_ids)) == len(numeric_ids) and numeric_ids == [
+ dev.get("index") for dev in devices
+ ]
+
+
+def _rocm_linux_sysfs_vram_by_index(
+ devices: list[Dict[str, Any]], *, allow_numeric_mask: bool = False
+) -> Dict[int, tuple[float, float]]:
+ """Map safe physical ROCm indices to their raw Linux sysfs VRAM readings."""
if not devices or platform.system() != "Linux":
return {}
- # Match by PCI identity, never list position: index N in KFD topology is ROCm
- # physical device N and carries its PCI address, which DRM sysfs keys on too.
- # The two gates below verify ``index`` really is a host-physical ordinal
- # (torch exposes no PCI id to check directly):
- # * No visibility mask -- any mask makes ``index`` container/ROCR-relative
- # rather than a host ordinal.
- # * Device count == host GPU count -- rules out a device-cgroup container
- # that sets no env var yet compacts torch's indices from zero.
pci_by_ordinal = _rocm_kfd_gpu_pci_ids()
if not pci_by_ordinal:
return {}
- if _rocm_visibility_mask_active() or len(devices) != len(pci_by_ordinal):
+ if len(devices) != len(pci_by_ordinal):
return {}
+ if _rocm_visibility_mask_active():
+ unambiguous_single = (
+ allow_numeric_mask
+ and len(devices) == 1
+ and len(pci_by_ordinal) == 1
+ and not _rocm_device_ordinal_active()
+ and not _rocm_visibility_masks_are_stacked()
+ )
+ if not unambiguous_single and (
+ not allow_numeric_mask or not _rocm_single_numeric_mask_matches(devices)
+ ):
+ return {}
vram_by_pci = _rocm_linux_sysfs_vram_by_pci_gb()
resolved: Dict[int, tuple[float, float]] = {}
for dev in devices:
@@ -3276,6 +3393,28 @@ def _rocm_system_wide_vram_by_index(
if not isinstance(index, int) or not (0 <= index < len(pci_by_ordinal)):
continue
entry = vram_by_pci.get(pci_by_ordinal[index].lower())
+ if entry is None:
+ continue
+ resolved[index] = entry
+ return resolved
+
+
+def _rocm_system_wide_vram_by_index(
+ devices: list[Dict[str, Any]],
+) -> Dict[int, tuple[float, float]]:
+ """Decide the system-wide overlay without applying it.
+
+ Returns ``{physical index: (used_gb, total_gb)}`` for every device sysfs can
+ speak for, and omits the ones it cannot. Split out from
+ _overlay_system_wide_vram so a caller can ask whether sysfs covers the whole
+ visible set BEFORE paying torch for occupancy it would then discard. Reads
+ only ``vram_total_gb`` off ``devices``; it never mutates them.
+ """
+ raw = _rocm_linux_sysfs_vram_by_index(devices)
+ resolved: Dict[int, tuple[float, float]] = {}
+ for dev in devices:
+ index = dev.get("index")
+ entry = raw.get(index)
if entry is None:
continue
used, total = entry
@@ -3292,6 +3431,24 @@ def _rocm_system_wide_vram_by_index(
return resolved
+def _rocm_linux_shared_pool_host_gb_by_index(devices: list[Dict[str, Any]]) -> Dict[int, float]:
+ """Map known APUs to the host-backed part above the reserved sysfs heap."""
+ raw = _rocm_linux_sysfs_vram_by_index(devices, allow_numeric_mask = True)
+ shared: Dict[int, float] = {}
+ for dev in devices:
+ if not dev.get("_rocm_known_unified"):
+ continue
+ index = dev.get("index")
+ entry = raw.get(index)
+ if entry is None:
+ continue
+ _used, sysfs_total = entry
+ torch_total = dev.get("total_gb") or 0.0
+ if sysfs_total > 0 and torch_total - sysfs_total > 0.1 * torch_total:
+ shared[index] = round(torch_total - sysfs_total, 2)
+ return shared
+
+
def _apply_system_wide_vram(
devices: list[Dict[str, Any]], resolved: Dict[int, tuple[float, float]]
) -> None:
@@ -4495,6 +4652,17 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
# there is nothing here worth a permanent driver context.
torch_devices = _torch_get_device_inventory(torch_indices)
if torch_devices:
+ if IS_ROCM and platform.system() == "Linux":
+ shared_host_gb = _rocm_linux_shared_pool_host_gb_by_index(torch_devices)
+ for td in torch_devices:
+ if td["index"] in shared_host_gb:
+ td["shared_memory"] = True
+ td["shared_memory_host_backed_gb"] = shared_host_gb[td["index"]]
+ elif IS_ROCM and platform.system() == "Windows":
+ shared_host_gb = _windows_rocm_shared_pool_host_gb_by_index(torch_devices)
+ for td in torch_devices:
+ if td["index"] in shared_host_gb:
+ td["shared_memory_host_backed_gb"] = shared_host_gb[td["index"]]
devices = [
{
"index": td["index"],
@@ -4502,6 +4670,8 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
"visible_ordinal": td["visible_ordinal"],
"name": td["name"],
"memory_total_gb": td["total_gb"],
+ "shared_memory": bool(td.get("shared_memory")),
+ "shared_memory_host_backed_gb": td.get("shared_memory_host_backed_gb"),
}
for td in torch_devices
]
@@ -4534,6 +4704,7 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
"devices": [],
"index_kind": "relative",
}
+ memory_total_gb = round(mem.get("total_gb", 0), 2)
return {
"available": True,
"backend": _backend_label(device),
@@ -4545,7 +4716,9 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
"index_kind": "relative",
"visible_ordinal": 0,
"name": mem.get("device_name", "MLX"),
- "memory_total_gb": round(mem.get("total_gb", 0), 2),
+ "memory_total_gb": memory_total_gb,
+ "shared_memory": True,
+ "shared_memory_host_backed_gb": memory_total_gb,
}
],
"index_kind": "relative",
diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsx
index 68fb69d9e01..d43c2dc485e 100644
--- a/studio/frontend/src/components/floating-monitor.tsx
+++ b/studio/frontend/src/components/floating-monitor.tsx
@@ -7,7 +7,7 @@ import {
useMonitorFrameStore,
useMonitorOverlayStore,
} from "@/features/settings";
-import { resolveGpuVramUsedGb } from "@/hooks/gpu-vram";
+import { gpuMemoryTotalsGb, resolveGpuVramUsedGb } from "@/hooks/gpu-vram";
import { aggregateGpuMemoryTotalGb, useSystemInfo } from "@/hooks/use-system";
import { useT } from "@/i18n";
import {
@@ -465,7 +465,9 @@ function FloatingMonitorPanel({
? aggregateGpuMemoryTotalGb(separateInferenceGpu.devices)
: 0;
const devices = displayedGpu?.devices ?? [];
- const vramTotal = aggregateGpuMemoryTotalGb(devices);
+ const memoryTotals = gpuMemoryTotalsGb(devices);
+ const vramTotal = memoryTotals.total;
+ const hasSharedPool = memoryTotals.shared > 0;
// null usage = unknown (e.g. Windows ROCm perf counter); 0 would fabricate a
// readout. The host figure can still be known when no device's is (#7452).
const resolvedVramUsed = resolveGpuVramUsedGb(displayedGpu);
@@ -596,7 +598,12 @@ function FloatingMonitorPanel({
</div>
<div className="text-xs text-muted-foreground font-mono tabular-nums">
{vramUsageKnown ? formatGiB(vramUsed) : unknownLabel} /{" "}
- {formatGiB(vramTotal)}
+ {hasSharedPool
+ ? t("settings.resources.environment.vramWithShared", {
+ vram: formatGiB(memoryTotals.dedicated),
+ shared: formatGiB(memoryTotals.shared),
+ })
+ : formatGiB(vramTotal)}
</div>
<Progress
value={vramUsageKnown ? vramPercent : 0}
diff --git a/studio/frontend/src/features/hub/catalog/models-header.tsx b/studio/frontend/src/features/hub/catalog/models-header.tsx
index 0d15d7b4ed7..09b7b85471b 100644
--- a/studio/frontend/src/features/hub/catalog/models-header.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-header.tsx
@@ -44,6 +44,7 @@ export function ModelsHeader({
localCount,
isDataset,
gpuLabel,
+ gpuSharedLabel,
ramLabel,
coreLabel,
activeCheckpoint,
@@ -55,6 +56,7 @@ export function ModelsHeader({
localCount: number;
isDataset: boolean;
gpuLabel: string;
+ gpuSharedLabel: string | null;
ramLabel: string;
coreLabel: string;
activeCheckpoint: string | null;
@@ -63,6 +65,9 @@ export function ModelsHeader({
onEject: () => void;
}) {
const openSettings = useSettingsDialogStore((s) => s.openDialog);
+ const gpuMemoryValue = gpuSharedLabel
+ ? `${gpuLabel} VRAM + ${gpuSharedLabel}`
+ : gpuLabel;
return (
<header className="font-heading flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
<PageHeading
@@ -88,7 +93,11 @@ export function ModelsHeader({
label="Local"
value={String(localCount)}
/>
- <StatPill icon={ChipIcon} label="VRAM" value={gpuLabel} />
+ <StatPill
+ icon={ChipIcon}
+ label={gpuSharedLabel ? "shared" : "VRAM"}
+ value={gpuMemoryValue}
+ />
<StatPill icon={RamMemoryIcon} label="RAM" value={ramLabel} />
<StatPill icon={CpuIcon} label="CPU" value={coreLabel} />
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 5750d64ed96..010752acd24 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -1294,8 +1294,12 @@ export function ModelsPage() {
const { vramInfo, minMemory } = useHubModelVram(selectedModel, gpu);
const gpuLabel = gpu.available
- ? `${Math.round(gpu.memoryTotalGb)} GiB`
+ ? `${Math.round(gpu.dedicatedMemoryTotalGb)} GiB`
: "Unavailable";
+ const gpuSharedLabel =
+ gpu.available && gpu.memorySharedGb > 0
+ ? `${Math.round(gpu.memorySharedGb)} GiB`
+ : null;
const ramLabel =
gpu.systemRamTotalGb > 0
? `${Math.round(gpu.systemRamTotalGb)} GiB`
@@ -1937,6 +1941,7 @@ export function ModelsPage() {
localCount={visibleLocalCount}
isDataset={isDatasetMode}
gpuLabel={gpuLabel}
+ gpuSharedLabel={gpuSharedLabel}
ramLabel={ramLabel}
coreLabel={coreLabel}
activeCheckpoint={activeCheckpoint}
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index 46ba3e6a9eb..6d65d428d32 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -2869,6 +2869,7 @@ export function ModelConfigPage({
pinnedGpuIds && pinnedGpuIds.length > 0
? gpuDevices.filter((device) => pinnedGpuIds.includes(device.index))
: [],
+ hostDevices: gpuDevices,
hostGpuTotalGb: inferenceGpu.memoryTotalGb,
hostDedicatedGpuTotalGb: inferenceGpu.dedicatedMemoryTotalGb,
hostSharesSystemRam: inferenceGpu.sharedMemory,
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts
index 3a53f05b402..1ec4090e8c0 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/recommended-fit.ts
@@ -168,11 +168,22 @@ export function loadScopedGpu<
memoryTotalGb: number;
maxDeviceMemoryGb: number;
loadDeviceMemoryGb: number;
+ loadDeviceSharedMemory?: boolean;
+ systemRamAvailableGb: number;
+ systemRamAvailableHostGb?: number;
},
>(gpu: T, taskScoped: boolean): T {
if (!taskScoped || !gpu.available) return gpu;
const deviceGb = gpu.loadDeviceMemoryGb || gpu.maxDeviceMemoryGb;
- return deviceGb > 0 ? { ...gpu, memoryTotalGb: deviceGb } : gpu;
+ if (deviceGb <= 0) return gpu;
+ return {
+ ...gpu,
+ memoryTotalGb: deviceGb,
+ systemRamAvailableGb:
+ gpu.loadDeviceSharedMemory === false
+ ? (gpu.systemRamAvailableHostGb ?? gpu.systemRamAvailableGb)
+ : gpu.systemRamAvailableGb,
+ };
}
/** One fit predicate for both search lists (curated matches and the Hub rows
diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
index e9a3be902ff..f3dfb7f54ba 100644
--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
@@ -11,6 +11,7 @@ import {
pickHuggingFaceCacheDir,
} from "@/features/native-intents";
import {
+ gpuMemoryTotalsGb,
gpuVramUsedIsPerDevice,
resolveGpuVramUsedGb,
} from "@/hooks/gpu-vram";
@@ -247,7 +248,8 @@ export function ResourcesTab() {
const diskFree = systemInfo.disk?.free_gb ?? 0;
const diskUsed = Math.max(0, diskTotal - diskFree);
const diskPercent = diskTotal > 0 ? (diskUsed / diskTotal) * 100 : 0;
- const vramTotal = aggregateGpuMemoryTotalGb(devices);
+ const gpuMemoryTotals = gpuMemoryTotalsGb(devices);
+ const vramTotal = gpuMemoryTotals.total;
// null usage = unknown (e.g. Windows ROCm perf counter); 0 would fabricate a
// total, so the device's own row stays unknown. The host figure can still be
// known when no device's is (#7452).
@@ -282,6 +284,8 @@ export function ResourcesTab() {
diskUsed,
diskPercent,
vramTotal,
+ vramDedicated: gpuMemoryTotals.dedicated,
+ vramShared: gpuMemoryTotals.shared,
vramUsed,
vramFree,
vramPercent,
@@ -388,6 +392,13 @@ export function ResourcesTab() {
.join(" · ")
: null;
const unknownLabel = t("settings.resources.environment.unknown");
+ const vramCapacityLabel =
+ metrics.vramShared > 0
+ ? t("settings.resources.environment.vramWithShared", {
+ vram: formatGiB(metrics.vramDedicated),
+ shared: formatGiB(metrics.vramShared),
+ })
+ : formatGiB(metrics.vramTotal);
// The placeholder's cpu backend and empty package list are not facts about the host either.
const hostReading = (value: string) => (hostUnread ? unknownLabel : value);
@@ -476,8 +487,8 @@ export function ResourcesTab() {
? unknownLabel
: hasGpu
? metrics.vramUsageKnown
- ? `${formatGiB(metrics.vramUsed)} / ${formatGiB(metrics.vramTotal)}`
- : `${unknownLabel} / ${formatGiB(metrics.vramTotal)}`
+ ? `${formatGiB(metrics.vramUsed)} / ${vramCapacityLabel}`
+ : `${unknownLabel} / ${vramCapacityLabel}`
: t("settings.resources.liveMonitor.noGpu")
}
detail={
diff --git a/studio/frontend/src/hooks/gpu-selection.ts b/studio/frontend/src/hooks/gpu-selection.ts
index c9aa7a9f5cd..f9e998924ae 100644
--- a/studio/frontend/src/hooks/gpu-selection.ts
+++ b/studio/frontend/src/hooks/gpu-selection.ts
@@ -15,6 +15,8 @@ export interface SystemGpuDevice {
* these with a discrete card, and a pin naming only the discrete card can
* still spill to host RAM. */
sharedMemory: boolean;
+ /** host-backed portion of memoryTotalGb when sharedMemory is true. */
+ sharedMemoryHostBackedGb?: number | null;
/** Whether `index` is safe to send as gpu_ids. */
pinnable: boolean;
/** Whether the separate DiffusionGemma runner can use this physical ID. */
diff --git a/studio/frontend/src/hooks/gpu-vram.ts b/studio/frontend/src/hooks/gpu-vram.ts
index a7d956ab458..05e130682fe 100644
--- a/studio/frontend/src/hooks/gpu-vram.ts
+++ b/studio/frontend/src/hooks/gpu-vram.ts
@@ -13,6 +13,14 @@ export interface MemoryTotalDevice {
memory_total_gb?: number;
/** True when the reported GPU budget comes from shared system memory. */
shared_memory?: boolean;
+ /** host-backed portion of the shared pool; the rest is reserved GPU memory. */
+ shared_memory_host_backed_gb?: number | null;
+}
+
+export interface GpuMemoryTotalsGb {
+ dedicated: number;
+ shared: number;
+ total: number;
}
export interface VramReportingGpu {
@@ -30,26 +38,131 @@ export interface VramReportingGpu {
export function aggregateGpuMemoryTotalGb(
devices: MemoryTotalDevice[],
): number {
- // A probe reading, so it is not trusted to be a usable number: `?? 0` only defends
- // against null and undefined, and one NaN or Infinity in the list poisons the sum
- // and every fit verdict measured against it.
+ return gpuMemoryTotalsGb(devices).total;
+}
+
+export function gpuMemoryTotalsGb(
+ devices: MemoryTotalDevice[],
+): GpuMemoryTotalsGb {
const size = (device: MemoryTotalDevice) => {
const total = device.memory_total_gb ?? 0;
return Number.isFinite(total) && total > 0 ? total : 0;
};
- const dedicated = devices
- .filter((device) => !device.shared_memory)
- .reduce((sum, device) => sum + size(device), 0);
- const shared = Math.max(
- 0,
- ...devices.filter((device) => device.shared_memory).map(size),
+ const dedicatedDevices = roundToDevicePrecision(
+ devices
+ .filter((device) => !device.shared_memory)
+ .reduce((sum, device) => sum + size(device), 0),
+ );
+ const sharedPool = devices
+ .filter((device) => device.shared_memory)
+ .reduce(
+ (totals, device) => {
+ const total = size(device);
+ const hostBackedReported = device.shared_memory_host_backed_gb;
+ const hostBackedKnown =
+ Number.isFinite(hostBackedReported) &&
+ (hostBackedReported as number) >= 0;
+ const hostBacked = hostBackedKnown
+ ? Math.min(total, hostBackedReported as number)
+ : total;
+ return {
+ hostBacked: Math.max(totals.hostBacked, hostBacked),
+ reserved:
+ totals.reserved + (hostBackedKnown ? total - hostBacked : 0),
+ };
+ },
+ { hostBacked: 0, reserved: 0 },
+ );
+ const shared = roundToDevicePrecision(sharedPool.hostBacked);
+ const dedicated = roundToDevicePrecision(
+ dedicatedDevices + sharedPool.reserved,
+ );
+ return {
+ dedicated,
+ shared,
+ total: roundToDevicePrecision(dedicated + shared),
+ };
+}
+
+export function gpuSharedHostMemoryGb(devices: MemoryTotalDevice[]): number {
+ return gpuMemoryTotalsGb(devices).shared;
+}
+
+export function systemRamAvailableOutsideSharedPoolGb(
+ availableGb: number,
+ hostBackedSharedPoolGb: number,
+): number {
+ const available =
+ Number.isFinite(availableGb) && availableGb > 0 ? availableGb : 0;
+ const shared =
+ Number.isFinite(hostBackedSharedPoolGb) && hostBackedSharedPoolGb > 0
+ ? hostBackedSharedPoolGb
+ : 0;
+ return roundToDevicePrecision(
+ Math.max(0, available - shared),
);
- return Math.round((dedicated + shared) * 100) / 100;
+}
+
+function roundToDevicePrecision(value: number): number {
+ return Math.round(value * 100) / 100;
+}
+
+export interface MemoryCapacityDevice {
+ memoryTotalGb: number;
+ sharedMemory: boolean;
+ sharedMemoryHostBackedGb?: number | null;
+}
+
+function budgetedGpuMemoryGb(
+ devices: MemoryCapacityDevice[],
+ budget: number,
+): { total: number; independent: number } {
+ let dedicated = 0;
+ let reserved = 0;
+ let partialSharedDemand = 0;
+ let fullySharedDemand = 0;
+ let sharedPool = 0;
+ for (const device of devices) {
+ const total =
+ Number.isFinite(device.memoryTotalGb) && device.memoryTotalGb > 0
+ ? device.memoryTotalGb
+ : 0;
+ const deviceCapacity = total * budget;
+ if (!device.sharedMemory) {
+ dedicated += deviceCapacity;
+ continue;
+ }
+ const reportedHostBacked = device.sharedMemoryHostBackedGb;
+ const hostBacked =
+ Number.isFinite(reportedHostBacked) &&
+ (reportedHostBacked as number) >= 0
+ ? Math.min(total, reportedHostBacked as number)
+ : total;
+ const deviceReserved = total - hostBacked;
+ reserved += Math.min(deviceReserved, deviceCapacity);
+ const deviceSharedDemand = Math.max(0, deviceCapacity - deviceReserved);
+ if (deviceReserved > 0) {
+ partialSharedDemand += deviceSharedDemand;
+ } else {
+ // fully shared vulkan rows may be duplicate icd views of one physical device.
+ fullySharedDemand = Math.max(fullySharedDemand, deviceSharedDemand);
+ }
+ sharedPool = Math.max(sharedPool, hostBacked);
+ }
+ return {
+ total: roundToDevicePrecision(
+ dedicated +
+ reserved +
+ Math.min(sharedPool, partialSharedDemand + fullySharedDemand),
+ ),
+ independent: roundToDevicePrecision(dedicated + reserved),
+ };
}
export interface MemoryCapacityInput {
/** The devices a pin names, or empty when the load may use the whole host. */
- pinnedDevices: { memoryTotalGb: number; sharedMemory: boolean }[];
+ pinnedDevices: MemoryCapacityDevice[];
+ hostDevices?: MemoryCapacityDevice[];
/** Aggregate GPU budget of the whole inventory, for the unpinned case. */
hostGpuTotalGb: number;
/** The same aggregate with shared-memory devices left out, for the unpinned case.
@@ -87,15 +200,16 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {
/** One pool for both figures, so a caller shows one number rather than two. */
singleMemoryPool: boolean;
} {
- const pinnedGpuCapacityGb = aggregateGpuMemoryTotalGb(
+ const pinnedTotals = gpuMemoryTotalsGb(
input.pinnedDevices.map((device) => ({
memory_total_gb: device.memoryTotalGb,
shared_memory: device.sharedMemory,
+ shared_memory_host_backed_gb: device.sharedMemoryHostBackedGb,
})),
);
// One flag for both answers, so the capacity and the pool question cannot
// disagree about which devices they are describing.
- const pinGoverns = pinnedGpuCapacityGb > 0;
+ const pinGoverns = pinnedTotals.total > 0;
// The host figure comes from aggregateGpuMemoryTotalGb on the caller's side, which
// guards itself, but this is a plain number on a public interface and a non-finite
// one here would make every figure below NaN.
@@ -103,19 +217,12 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {
Number.isFinite(input.hostGpuTotalGb) && input.hostGpuTotalGb > 0
? input.hostGpuTotalGb
: 0;
- const rawGpuCapacityGb = pinGoverns ? pinnedGpuCapacityGb : hostGpuTotalGb;
+ const rawGpuCapacityGb = pinGoverns ? pinnedTotals.total : hostGpuTotalGb;
// The dedicated-only figure for the same governing set. A pin answers for itself;
// unpinned takes the caller's, falling back to the full aggregate, which is the
// right answer on every host that has no shared device at all.
const rawDedicatedCapacityGb = pinGoverns
- ? aggregateGpuMemoryTotalGb(
- input.pinnedDevices
- .filter((device) => !device.sharedMemory)
- .map((device) => ({
- memory_total_gb: device.memoryTotalGb,
- shared_memory: false,
- })),
- )
+ ? pinnedTotals.dedicated
: Number.isFinite(input.hostDedicatedGpuTotalGb) &&
(input.hostDedicatedGpuTotalGb as number) >= 0
? (input.hostDedicatedGpuTotalGb as number)
@@ -131,8 +238,27 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {
input.gpuBudgetFraction <= 1
? input.gpuBudgetFraction
: 1;
- const gpuCapacityGb = Math.round(rawGpuCapacityGb * budget * 100) / 100;
+ const capacityDevices = pinGoverns
+ ? input.pinnedDevices
+ : (input.hostDevices ?? []);
+ const capacityDeviceTotals = gpuMemoryTotalsGb(
+ capacityDevices.map((device) => ({
+ memory_total_gb: device.memoryTotalGb,
+ shared_memory: device.sharedMemory,
+ shared_memory_host_backed_gb: device.sharedMemoryHostBackedGb,
+ })),
+ );
+ const canBudgetByDevice =
+ capacityDevices.length > 0 &&
+ Math.abs(capacityDeviceTotals.total - rawGpuCapacityGb) <= 0.01;
+ const budgetedGpuMemory = canBudgetByDevice
+ ? budgetedGpuMemoryGb(capacityDevices, budget)
+ : null;
+ const gpuCapacityGb =
+ budgetedGpuMemory?.total ??
+ Math.round(rawGpuCapacityGb * budget * 100) / 100;
const dedicatedCapacityGb =
+ budgetedGpuMemory?.independent ??
Math.round(rawDedicatedCapacityGb * budget * 100) / 100;
// Same guard as the device totals: psutil's figure arrives over the wire too, and a
// non-finite one would turn the ceiling below into NaN, which classifyMemoryFit
@@ -146,8 +272,7 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {
// calling that one pool hides the GPU verdict on the only figure that would catch
// a fixed placement too large for the card.
const sharesSystemRam = pinGoverns
- ? input.pinnedDevices.length > 0 &&
- input.pinnedDevices.every((device) => device.sharedMemory)
+ ? pinnedTotals.shared > 0 && pinnedTotals.dedicated === 0
: input.hostSharesSystemRam;
const singleMemoryPool = input.unifiedMemory || sharesSystemRam;
return {
@@ -251,6 +376,8 @@ export interface FreeVramDevice {
memoryTotalGb?: number;
/** True when this device's budget is a capped view of the host's own RAM. */
sharedMemory?: boolean;
+ /** Host-backed portion of memoryTotalGb when sharedMemory is true. */
+ sharedMemoryHostBackedGb?: number | null;
}
/**
@@ -265,8 +392,9 @@ export interface FreeVramDevice {
* total of 0 (`hardware.py` zeroes it for an iGPU on one path), and `usableFreeVramGb`
* then falls back to the raw free reading with no reserve subtracted at all.
*
- * Several shared devices are several views of one pool, so the largest is taken
- * rather than their sum -- two iGPUs on one host do not have two pools.
+ * Fully shared devices are views of one pool, so only the largest is taken. A
+ * partially shared APU also has an independent reserved segment, which remains
+ * additive while its host-backed demand is capped by the common pool.
*/
export function aggregateUsableFreeVramGb(
devices: FreeVramDevice[],
@@ -274,14 +402,63 @@ export function aggregateUsableFreeVramGb(
): number {
const usable = (device: FreeVramDevice) =>
usableFreeVramGb(device.memoryFreeGb ?? 0, device.memoryTotalGb ?? 0, fraction);
- const dedicated = devices
- .filter((device) => !device.sharedMemory)
- .reduce((sum, device) => sum + usable(device), 0);
- const shared = Math.max(
- 0,
- ...devices.filter((device) => device.sharedMemory).map(usable),
- );
+ let dedicated = 0;
+ let reserved = 0;
+ let partialSharedDemand = 0;
+ let partialSharedFree = 0;
+ let fullySharedDemand = 0;
+ let fullySharedFree = 0;
+ for (const device of devices) {
+ const deviceUsable = usable(device);
+ if (!device.sharedMemory) {
+ dedicated += deviceUsable;
+ continue;
+ }
+ const total =
+ Number.isFinite(device.memoryTotalGb) && (device.memoryTotalGb as number) > 0
+ ? (device.memoryTotalGb as number)
+ : 0;
+ if (total === 0) {
+ fullySharedDemand = Math.max(fullySharedDemand, deviceUsable);
+ fullySharedFree = Math.max(fullySharedFree, deviceUsable);
+ continue;
+ }
+ const reportedHostBacked = device.sharedMemoryHostBackedGb;
+ const hostBacked =
+ Number.isFinite(reportedHostBacked) &&
+ (reportedHostBacked as number) >= 0
+ ? Math.min(total, reportedHostBacked as number)
+ : total;
+ const deviceReserved = total - hostBacked;
+ const deviceCapacity = usableFreeVramGb(total, total, fraction);
+ const deviceSharedCapacity = Math.max(0, deviceCapacity - deviceReserved);
+ const deviceSharedDemand = Math.min(deviceUsable, deviceSharedCapacity);
+ reserved += Math.min(
+ deviceReserved,
+ Math.max(0, deviceUsable - deviceSharedDemand),
+ );
+ if (deviceReserved > 0) {
+ partialSharedDemand += deviceSharedDemand;
+ const free =
+ Number.isFinite(device.memoryFreeGb) && (device.memoryFreeGb as number) > 0
+ ? (device.memoryFreeGb as number)
+ : 0;
+ const deviceSharedFree = Math.min(hostBacked, free);
+ partialSharedFree = Math.max(partialSharedFree, deviceSharedFree);
+ } else {
+ fullySharedDemand = Math.max(fullySharedDemand, deviceSharedDemand);
+ fullySharedFree = Math.max(fullySharedFree, deviceSharedDemand);
+ }
+ }
+ const sharedFree = Math.max(partialSharedFree, fullySharedFree);
// Devices arrive rounded to 2dp and the reserve is a fraction of them, so the sum
// reintroduces float error the same way the totals aggregate does.
- return Math.round((dedicated + shared) * 100) / 100;
+ return (
+ Math.round(
+ (dedicated +
+ reserved +
+ Math.min(sharedFree, partialSharedDemand + fullySharedDemand)) *
+ 100,
+ ) / 100
+ );
}
diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.ts
index bb5671a0d63..a8a704914f3 100644
--- a/studio/frontend/src/hooks/use-gpu-info.ts
+++ b/studio/frontend/src/hooks/use-gpu-info.ts
@@ -12,9 +12,13 @@ import {
reconcileGpuSelection,
resolveGpuSelectionContext,
} from "./gpu-selection";
+import {
+ gpuMemoryTotalsGb,
+ gpuSharedHostMemoryGb,
+ systemRamAvailableOutsideSharedPoolGb,
+} from "./gpu-vram";
import {
type SystemInfoResponse,
- aggregateGpuMemoryTotalGb,
fetchSystemInfo,
getCachedSystemInfo,
subscribeSystemInfo,
@@ -32,8 +36,7 @@ export {
export interface GpuInfo {
available: boolean;
budgetKnown: boolean;
- /** A Vulkan iGPU: memoryTotalGb is a capped view of system RAM, not a pool
- * beside it, so callers must not add systemRamTotalGb on top of it. */
+ /** true when the visible GPUs use only the host memory pool. */
sharedMemory: boolean;
/** The backend torch resolved: cuda, rocm, xpu, mlx, cpu. Carried on every path, including the
* GPU-less one, because "which runtimes can this host place" is exactly the question a host
@@ -41,6 +44,7 @@ export interface GpuInfo {
backend: string;
name: string;
memoryTotalGb: number;
+ memorySharedGb: number;
/** The same aggregate with shared-memory devices left out: the VRAM that is a pool
* BESIDE system RAM rather than a capped view of it. */
dedicatedMemoryTotalGb: number;
@@ -48,20 +52,13 @@ export interface GpuInfo {
maxDeviceMemoryGb: number;
/** VRAM of the device an image/video load actually lands on: the lowest visible ordinal, since resolve_diffusion_device_target() returns a bare "cuda" and torch places on the current device. On a heterogeneous host this is NOT maxDeviceMemoryGb, and sizing a pick against the larger card would recommend a checkpoint that OOMs the smaller one. */
loadDeviceMemoryGb: number;
+ /** true when the image/video load device uses the host memory pool. */
+ loadDeviceSharedMemory: boolean;
cpuCore: number;
cpuThread: number;
- /** Host RAM free right now, ZEROED on a host where any device shares that RAM.
- * The zero belongs to the SUM: every reader of this field adds it to the GPU
- * budget, and on a shared-memory host that would offer the same bytes twice. */
+ /** host RAM free after removing the host-backed shared GPU pool. */
systemRamAvailableGb: number;
- /** Host RAM free right now as the probe reported it, whatever the devices share.
- *
- * The field above cannot answer "is host RAM under pressure", because on a
- * dGPU + iGPU box it is permanently 0 -- `devices.some(...)` is a host-level OR, so
- * ONE Vulkan iGPU in the inventory zeroes the reading for the whole machine, and it
- * stays 0 even when the user has pinned the discrete card and host RAM is genuinely
- * a separate pool. `sharesSystemRam` in gpu-vram.ts already answers the pool
- * question per pin, which is the half that is right; this is the reading it needs. */
+ /** raw host RAM free as the probe reported it. */
systemRamAvailableHostGb: number;
systemRamTotalGb: number;
}
@@ -73,9 +70,11 @@ const DEFAULT_GPU: GpuInfo = {
backend: "",
name: "Unknown",
memoryTotalGb: 0,
+ memorySharedGb: 0,
dedicatedMemoryTotalGb: 0,
maxDeviceMemoryGb: 0,
loadDeviceMemoryGb: 0,
+ loadDeviceSharedMemory: false,
cpuCore: 0,
cpuThread: 0,
systemRamAvailableGb: 0,
@@ -103,39 +102,28 @@ function toGpuInfo(
if (!gpuData?.available || !devices.length) {
return { ...DEFAULT_GPU, ...base, budgetKnown: data !== null };
}
+ const memoryTotals = gpuMemoryTotalsGb(devices);
+ const loadDevice = pickLoadDevice(devices);
return {
...base,
- // A Vulkan iGPU's reported budget is capped shared system RAM, not an
- // independent VRAM pool. Do not offer the same RAM again for CPU offload.
- // `systemRamAvailableHostGb` deliberately keeps `base`'s reading through this
- // spread: the zero is about not double-counting a SUM, not a claim that the
- // machine has no free RAM, and a caller asking about host pressure needs the
- // number itself.
- systemRamAvailableGb: devices.some((device) => device.shared_memory)
- ? 0
- : base.systemRamAvailableGb,
- // EVERY, not some, and deliberately different from the zeroing above. That one
- // is about a SUM: one shared device is enough to make "GPU total + system RAM"
- // count the same bytes twice. This one answers "is there only one pool", which a
- // discrete card sitting beside an iGPU makes false. Reading it as some() marked a
- // mixed inventory single-pool, and the row shows a lone Shared figure there and
- // drops the GPU verdict, so a fixed Manual placement larger than the discrete
- // card read as a fit against a combined ceiling it will never spill into.
- // Length-guarded because every() on an empty list is true, and a host with
- // nothing probed has no pool to be single.
- sharedMemory:
- devices.length > 0 && devices.every((device) => device.shared_memory),
+ systemRamAvailableGb: systemRamAvailableOutsideSharedPoolGb(
+ base.systemRamAvailableGb,
+ gpuSharedHostMemoryGb(devices),
+ ),
+ sharedMemory: memoryTotals.shared > 0 && memoryTotals.dedicated === 0,
available: true,
budgetKnown: true,
name: devices[0]?.name ?? "Unknown",
- // Shared-memory (Vulkan iGPU) devices report the same system RAM pool, so they are counted once rather than summed.
- memoryTotalGb: aggregateGpuMemoryTotalGb(devices),
- dedicatedMemoryTotalGb: aggregateGpuMemoryTotalGb(
- devices.filter((device) => !device.shared_memory),
+ memoryTotalGb: memoryTotals.total,
+ dedicatedMemoryTotalGb: memoryTotals.dedicated,
+ memorySharedGb: memoryTotals.shared,
+ maxDeviceMemoryGb: devices.reduce(
+ (max, d) => Math.max(max, d.memory_total_gb ?? 0),
+ 0,
),
- maxDeviceMemoryGb: devices.reduce((max, d) => Math.max(max, d.memory_total_gb ?? 0), 0),
// Lowest visible ordinal = torch's current device = where the pipeline lands.
- loadDeviceMemoryGb: pickLoadDevice(devices)?.memory_total_gb ?? 0,
+ loadDeviceMemoryGb: loadDevice?.memory_total_gb ?? 0,
+ loadDeviceSharedMemory: loadDevice?.shared_memory === true,
};
}
@@ -170,6 +158,7 @@ function toGpuDevices(
memoryTotalGb: d.memory_total_gb ?? 0,
memoryFreeGb: d.vram_free_gb ?? 0,
sharedMemory: d.shared_memory === true,
+ sharedMemoryHostBackedGb: d.shared_memory_host_backed_gb,
pinnable: picksAccepted && d.index_kind === "vulkan",
// The DiffusionGemma runner is torch-side and never speaks ggml
// ordinals, so a Vulkan pick is not usable there.
@@ -196,6 +185,7 @@ function toGpuDevices(
memoryTotalGb: d.memory_total_gb ?? 0,
memoryFreeGb: d.vram_free_gb ?? 0,
sharedMemory: d.shared_memory === true,
+ sharedMemoryHostBackedGb: d.shared_memory_host_backed_gb,
// The XPU ban is about torch-xpu ordinals no applicator speaks, so /load
// and /validate 400 them. A Vulkan ordinal is not one of those, so it
// stays pickable even when this list arrives from an XPU host.
diff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.ts
index 93477d50400..40a0a5e0ff5 100644
--- a/studio/frontend/src/hooks/use-system.ts
+++ b/studio/frontend/src/hooks/use-system.ts
@@ -20,6 +20,8 @@ export interface GpuDevice {
vram_utilization_pct?: number | null;
/** True when the reported GPU budget comes from shared system memory. */
shared_memory?: boolean;
+ /** host-backed portion of the shared pool; the rest is reserved GPU memory. */
+ shared_memory_host_backed_gb?: number | null;
}
export interface SystemGpuInfo {
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 54c0b9f4902..17daf9b8087 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1189,6 +1189,7 @@ export const ar = {
processMemory: "ذاكرة العملية",
notInstalled: "غير مثبّت",
unknown: "غير معروف",
+ vramWithShared: "{vram} VRAM + {shared} ذاكرة مشتركة",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index c0370c4a927..5c120aed803 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1218,6 +1218,7 @@ export const de = {
processMemory: "Prozessspeicher",
notInstalled: "Nicht installiert",
unknown: "Unbekannt",
+ vramWithShared: "{vram} VRAM + {shared} gemeinsam genutzter Speicher",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index d71501a57c2..4684b6e2739 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1185,6 +1185,8 @@ export const en = {
processMemory: "Process memory",
notInstalled: "Not installed",
unknown: "Unknown",
+ // {vram} is the dedicated total, {shared} the shared pool beside it.
+ vramWithShared: "{vram} VRAM + {shared} shared",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 52fe9793eaf..02f418e0763 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1212,6 +1212,7 @@ export const es = {
processMemory: "Memoria del proceso",
notInstalled: "No instalado",
unknown: "Desconocido",
+ vramWithShared: "{vram} de VRAM + {shared} de memoria compartida",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1887089b468..07fb5d5400c 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1216,6 +1216,7 @@ export const fr = {
processMemory: "Mémoire du processus",
notInstalled: "Non installé",
unknown: "Inconnu",
+ vramWithShared: "{vram} de VRAM + {shared} de mémoire partagée",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 1f6228e21fc..5ece1a4b923 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1192,6 +1192,7 @@ export const hi = {
processMemory: "प्रोसेस मेमोरी",
notInstalled: "इंस्टॉल नहीं है",
unknown: "अज्ञात",
+ vramWithShared: "{vram} VRAM + {shared} साझा मेमोरी",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index c14a5be2b56..51dfebcaabf 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1184,6 +1184,7 @@ export const it = {
processMemory: "Memoria del processo",
notInstalled: "Non installato",
unknown: "Sconosciuto",
+ vramWithShared: "{vram} di VRAM + {shared} di memoria condivisa",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 32e5deff609..326cc38a1c8 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1172,6 +1172,7 @@ export const ja = {
processMemory: "プロセスメモリ",
notInstalled: "未インストール",
unknown: "不明",
+ vramWithShared: "{vram} VRAM + {shared} 共有メモリ",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 0b9dcfa63cb..0d22f6723c7 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1186,6 +1186,7 @@ export const ko = {
processMemory: "프로세스 메모리",
notInstalled: "설치되지 않음",
unknown: "알 수 없음",
+ vramWithShared: "{vram} VRAM + {shared} 공유 메모리",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index f6bb6baedef..79c57b028fe 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1200,6 +1200,7 @@ export const ptBR = {
processMemory: "Memória do processo",
notInstalled: "Não instalado",
unknown: "Desconhecido",
+ vramWithShared: "{vram} de VRAM + {shared} de memória compartilhada",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 7d1f1701624..3843d277234 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1195,6 +1195,7 @@ export const ru = {
processMemory: "Память процесса",
notInstalled: "Не установлено",
unknown: "Неизвестно",
+ vramWithShared: "{vram} VRAM + {shared} общей памяти",
},
},
agents: {
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 7713c2cb85b..a474bf12734 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1165,6 +1165,7 @@ export const zhCN = {
processMemory: "进程内存",
notInstalled: "未安装",
unknown: "未知",
+ vramWithShared: "{vram} 显存 + {shared} 共享内存",
},
},
agents: {
diff --git a/studio/frontend/tests/gpu-vram-split.test.ts b/studio/frontend/tests/gpu-vram-split.test.ts
new file mode 100644
index 00000000000..827de5d7f96
--- /dev/null
+++ b/studio/frontend/tests/gpu-vram-split.test.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ aggregateGpuMemoryTotalGb,
+ gpuMemoryTotalsGb,
+ gpuSharedHostMemoryGb,
+ systemRamAvailableOutsideSharedPoolGb,
+} from "../src/hooks/gpu-vram.ts";
+
+test("dedicated and shared split the aggregate (#9242)", () => {
+ const devices = [
+ { memory_total_gb: 15.92 },
+ { memory_total_gb: 12.15, shared_memory: true },
+ ];
+ const { dedicated, shared } = gpuMemoryTotalsGb(devices);
+ const aggregate = aggregateGpuMemoryTotalGb(devices);
+
+ assert.equal(dedicated, 15.92);
+ assert.equal(shared, 12.15);
+ assert.ok(
+ Math.abs(dedicated + shared - aggregate) < 1e-9,
+ "dedicated + shared must equal the aggregate the usage math uses",
+ );
+});
+
+test("a shared pool counts once even when several devices report it", () => {
+ const devices = [
+ { memory_total_gb: 8 },
+ {
+ memory_total_gb: 12.15,
+ shared_memory: true,
+ shared_memory_host_backed_gb: 10.15,
+ },
+ {
+ memory_total_gb: 12.15,
+ shared_memory: true,
+ shared_memory_host_backed_gb: 10.15,
+ }, // same host pool, separate reserved heaps
+ ];
+ assert.deepEqual(gpuMemoryTotalsGb(devices), {
+ dedicated: 12,
+ shared: 10.15,
+ total: 22.15,
+ });
+});
+
+test("host RAM outside a shared pool remains available for CPU offload", () => {
+ const devices = [{ memory_total_gb: 12.15, shared_memory: true }];
+ const hostBackedGb = gpuSharedHostMemoryGb(devices);
+ assert.equal(hostBackedGb, 12.15);
+ assert.equal(systemRamAvailableOutsideSharedPoolGb(40, hostBackedGb), 27.85);
+ assert.equal(systemRamAvailableOutsideSharedPoolGb(8, hostBackedGb), 0);
+ assert.equal(systemRamAvailableOutsideSharedPoolGb(40, 0), 40);
+});
+
+test("reserved framebuffer memory is not subtracted from host RAM twice", () => {
+ const devices = [
+ {
+ memory_total_gb: 89.47,
+ shared_memory: true,
+ shared_memory_host_backed_gb: 57.47,
+ },
+ ];
+ assert.deepEqual(gpuMemoryTotalsGb(devices), {
+ dedicated: 32,
+ shared: 57.47,
+ total: 89.47,
+ });
+ const hostBackedGb = gpuSharedHostMemoryGb(devices);
+ assert.equal(hostBackedGb, 57.47);
+ assert.equal(systemRamAvailableOutsideSharedPoolGb(64, hostBackedGb), 6.53);
+});
+
+test("fully host-backed unified memory is not counted twice", () => {
+ const devices = [
+ {
+ memory_total_gb: 64,
+ shared_memory: true,
+ shared_memory_host_backed_gb: 64,
+ },
+ ];
+ assert.deepEqual(gpuMemoryTotalsGb(devices), {
+ dedicated: 0,
+ shared: 64,
+ total: 64,
+ });
+ assert.equal(
+ systemRamAvailableOutsideSharedPoolGb(
+ 40,
+ gpuSharedHostMemoryGb(devices),
+ ),
+ 0,
+ );
+});
+
+test("all-dedicated systems report zero shared", () => {
+ const devices = [{ memory_total_gb: 24 }, { memory_total_gb: 24 }];
+ assert.deepEqual(gpuMemoryTotalsGb(devices), {
+ dedicated: 48,
+ shared: 0,
+ total: 48,
+ });
+});
+
+test("float error does not leak into the halves", () => {
+ // 2dp inputs; the derived halves must stay at the same precision.
+ const devices = [{ memory_total_gb: 179.06 }, { memory_total_gb: 179.06 }];
+ assert.equal(gpuMemoryTotalsGb(devices).dedicated, 358.12);
+});
diff --git a/studio/frontend/tests/hub-shared-memory-display.test.ts b/studio/frontend/tests/hub-shared-memory-display.test.ts
new file mode 100644
index 00000000000..4db37361591
--- /dev/null
+++ b/studio/frontend/tests/hub-shared-memory-display.test.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const hubPage = readFileSync(
+ new URL("../src/features/hub/hub-page.tsx", import.meta.url),
+ "utf8",
+);
+const modelsHeader = readFileSync(
+ new URL("../src/features/hub/catalog/models-header.tsx", import.meta.url),
+ "utf8",
+);
+
+test("Model Hub separates dedicated VRAM from shared GPU memory", () => {
+ assert.match(hubPage, /gpu\.dedicatedMemoryTotalGb/);
+ assert.match(hubPage, /gpu\.memorySharedGb/);
+ assert.match(hubPage, /gpuSharedLabel=\{gpuSharedLabel\}/);
+ assert.match(modelsHeader, /`\$\{gpuLabel\} VRAM \+ \$\{gpuSharedLabel\}`/);
+ assert.match(modelsHeader, /label=\{gpuSharedLabel \? "shared" : "VRAM"\}/);
+});
diff --git a/studio/frontend/tests/memory-estimate-capacity.test.ts b/studio/frontend/tests/memory-estimate-capacity.test.ts
index a10f1c6e002..9690641e8d5 100644
--- a/studio/frontend/tests/memory-estimate-capacity.test.ts
+++ b/studio/frontend/tests/memory-estimate-capacity.test.ts
@@ -298,6 +298,101 @@ test("a pin decides the pool question for the cards it names", () => {
assert.equal(onBoth.totalCapacityGb, 107);
});
+test("a partially host-backed APU keeps its reserved memory beside system RAM", () => {
+ const apu = {
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ const capacity = resolveMemoryCapacityGb({
+ pinnedDevices: [apu],
+ hostGpuTotalGb: 100,
+ hostDedicatedGpuTotalGb: 8,
+ hostSharesSystemRam: false,
+ systemRamTotalGb: 128,
+ unifiedMemory: false,
+ });
+ assert.equal(capacity.gpuCapacityGb, 100);
+ assert.equal(capacity.totalCapacityGb, 136);
+ assert.equal(capacity.singleMemoryPool, false);
+});
+
+test("the gpu budget does not discount a partial APU reserve twice", () => {
+ const apu = {
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ const common = {
+ hostDevices: [apu],
+ hostGpuTotalGb: 100,
+ hostDedicatedGpuTotalGb: 8,
+ hostSharesSystemRam: false,
+ systemRamTotalGb: 128,
+ unifiedMemory: false,
+ gpuBudgetFraction: 0.8,
+ };
+ const pinned = resolveMemoryCapacityGb({
+ ...common,
+ pinnedDevices: [apu],
+ });
+ const unpinned = resolveMemoryCapacityGb({
+ ...common,
+ pinnedDevices: [],
+ });
+ assert.equal(pinned.gpuCapacityGb, 80);
+ assert.equal(pinned.totalCapacityGb, 136);
+ assert.deepEqual(unpinned, pinned);
+});
+
+test("the gpu budget is applied to each APU sharing one host pool", () => {
+ const apu = {
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ const common = {
+ hostDevices: [apu, apu],
+ hostGpuTotalGb: 108,
+ hostDedicatedGpuTotalGb: 16,
+ hostSharesSystemRam: false,
+ systemRamTotalGb: 128,
+ unifiedMemory: false,
+ gpuBudgetFraction: 0.8,
+ };
+ const pinned = resolveMemoryCapacityGb({
+ ...common,
+ pinnedDevices: [apu, apu],
+ });
+ const unpinned = resolveMemoryCapacityGb({
+ ...common,
+ pinnedDevices: [],
+ });
+ assert.equal(pinned.gpuCapacityGb, 108);
+ assert.equal(pinned.totalCapacityGb, 144);
+ assert.deepEqual(unpinned, pinned);
+});
+
+test("duplicate fully shared Vulkan views do not erase the gpu budget", () => {
+ const igpu = {
+ memoryTotalGb: 12,
+ sharedMemory: true,
+ };
+ const capacity = resolveMemoryCapacityGb({
+ pinnedDevices: [],
+ hostDevices: [igpu, igpu],
+ hostGpuTotalGb: 12,
+ hostDedicatedGpuTotalGb: 0,
+ hostSharesSystemRam: true,
+ systemRamTotalGb: 12,
+ unifiedMemory: false,
+ gpuBudgetFraction: 0.8,
+ });
+ assert.equal(capacity.gpuCapacityGb, 9.6);
+ assert.equal(capacity.totalCapacityGb, 12);
+ assert.equal(capacity.singleMemoryPool, true);
+});
+
test("a discrete-only host is unchanged by the dedicated-only ceiling", () => {
// The regression guard: with no shared device the two figures are equal, so every
// ordinary machine keeps exactly the ceiling it had.
diff --git a/studio/frontend/tests/memory-estimate-free-vram.test.ts b/studio/frontend/tests/memory-estimate-free-vram.test.ts
index b38ceb841f4..e02a3107db8 100644
--- a/studio/frontend/tests/memory-estimate-free-vram.test.ts
+++ b/studio/frontend/tests/memory-estimate-free-vram.test.ts
@@ -107,6 +107,43 @@ test("two shared devices of different sizes report the larger, not their sum", (
assert.ok(Math.abs(mixed - usableFreeVramGb(40, 40, 1)) < 0.01);
});
+test("partial APUs retain each reserved segment beside one shared pool", () => {
+ const apu = {
+ memoryFreeGb: 100,
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ assert.equal(aggregateUsableFreeVramGb([apu], 0.8), 80);
+ assert.equal(aggregateUsableFreeVramGb([apu, apu], 0.8), 108);
+});
+
+test("busy partial APUs do not repeat the currently free shared pool", () => {
+ const apu = {
+ memoryFreeGb: 50,
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ assert.equal(aggregateUsableFreeVramGb([apu, apu], 0.8), 50);
+});
+
+test("a smaller partial APU does not cap a larger shared aperture", () => {
+ const large = {
+ memoryFreeGb: 100,
+ memoryTotalGb: 100,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 92,
+ };
+ const small = {
+ memoryFreeGb: 20,
+ memoryTotalGb: 20,
+ sharedMemory: true,
+ sharedMemoryHostBackedGb: 12,
+ };
+ assert.equal(aggregateUsableFreeVramGb([large, small], 0.8), 96);
+});
+
test("the VRAM Budget reserve is applied per device inside the aggregate", () => {
// _select_gpus' own example: a 24 GB card with 10 GB free at an 80% budget offers
// 10 - (1 - 0.8) * 24 = 5.2, not 8.
diff --git a/studio/frontend/tests/recommended-catalog-seeds.test.ts b/studio/frontend/tests/recommended-catalog-seeds.test.ts
index e0e25a33116..6e8d83b6442 100644
--- a/studio/frontend/tests/recommended-catalog-seeds.test.ts
+++ b/studio/frontend/tests/recommended-catalog-seeds.test.ts
@@ -258,6 +258,28 @@ test("a task row is sized against the device the load lands on", () => {
assert.equal(hfModelFitsDevice(sdxl, loadScopedGpu(twoCards, true)), false);
});
+test("a dedicated task device keeps RAM reserved by a shared GPU", () => {
+ const mixedHost = {
+ available: true,
+ budgetKnown: true,
+ memoryTotalGb: 48,
+ maxDeviceMemoryGb: 32,
+ loadDeviceMemoryGb: 16,
+ loadDeviceSharedMemory: false,
+ systemRamAvailableGb: 8,
+ systemRamAvailableHostGb: 40,
+ };
+ const sharedLoadDevice = {
+ ...mixedHost,
+ loadDeviceMemoryGb: 32,
+ loadDeviceSharedMemory: true,
+ };
+
+ assert.equal(loadScopedGpu(mixedHost, true).systemRamAvailableGb, 40);
+ assert.equal(loadScopedGpu(sharedLoadDevice, true).systemRamAvailableGb, 8);
+ assert.equal(loadScopedGpu(mixedHost, false), mixedHost);
+});
+
test("both search lists judge a curated id the same way", () => {
const oneCard = {
available: true,
diff --git a/studio/frontend/tests/resources-shared-memory-display.test.ts b/studio/frontend/tests/resources-shared-memory-display.test.ts
new file mode 100644
index 00000000000..b39d9a42484
--- /dev/null
+++ b/studio/frontend/tests/resources-shared-memory-display.test.ts
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const resourcesTab = readFileSync(
+ new URL("../src/features/settings/tabs/resources-tab.tsx", import.meta.url),
+ "utf8",
+);
+
+test("Resources separates dedicated VRAM from shared GPU memory", () => {
+ assert.match(resourcesTab, /gpuMemoryTotalsGb\(devices\)/);
+ assert.match(resourcesTab, /metrics\.vramShared > 0/);
+ assert.match(resourcesTab, /environment\.vramWithShared/);
+ assert.match(resourcesTab, /vram: formatGiB\(metrics\.vramDedicated\)/);
+ assert.match(resourcesTab, /shared: formatGiB\(metrics\.vramShared\)/);
+ assert.match(resourcesTab, /\$\{vramCapacityLabel\}/);
+});