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.

Studio: tune llama.cpp env for data-center GPUs (#6098)

Daniel Han25ccfebc0b21
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 8cf37ed9ec3..3393f2b4be9 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1329,6 +1329,105 @@ class LlamaCppBackend:
return False
return False
+ # Datacenter / professional NVIDIA parts that benefit from the llama.cpp
+ # FP32-accum / P2P tunings. Whole-word (\b) so short markers don't match
+ # workstation parts as substrings: "a100" must not fire on "RTX A1000".
+ _DATACENTER_GPU_RE = re.compile(
+ r"\b(?:a100|a30|h100|h200|h800|gh200|b200|b100|b300|gb200|gb300|"
+ r"l40s?|l4|rtx pro 6000|rtx 6000 ada)\b"
+ )
+
+ @staticmethod
+ def _is_datacenter_gpu(gpu_indices = None) -> bool:
+ """True iff every selected NVIDIA GPU is a datacenter/professional part.
+ NVIDIA-only, fails open to False (consumer GeForce, ROCm, CPU and errors
+ are left untouched); a mixed DC+consumer selection counts as non-DC.
+
+ gpu_indices are PHYSICAL ids (see _get_gpu_free_memory), but
+ get_device_properties wants mask-relative ordinals, so we rebuild the
+ ordinal->physical map from CUDA_VISIBLE_DEVICES and key names by physical
+ id. Otherwise a masked host (CUDA_VISIBLE_DEVICES=4,5,6,7, selection [4,5])
+ would drop the tuning or probe the wrong GPU."""
+ try:
+ import torch
+
+ if getattr(torch.version, "hip", None) is not None:
+ return False # ROCm reuses torch.cuda.*; not a CUDA part
+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
+ return False
+ count = torch.cuda.device_count()
+
+ # Mirror _get_gpu_free_memory: map visible ordinal -> physical id via
+ # CUDA_VISIBLE_DEVICES; unset/unparsable leaves physical id == ordinal.
+ physical_ids: Optional[list[int]] = None
+ cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
+ if cvd is not None:
+ try:
+ physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
+ except ValueError:
+ physical_ids = None
+
+ pattern = LlamaCppBackend._DATACENTER_GPU_RE
+ names_by_id: dict[int, str] = {}
+ for ordinal in range(count):
+ try:
+ name = (torch.cuda.get_device_properties(ordinal).name or "").lower()
+ except Exception:
+ continue
+ pid = (
+ physical_ids[ordinal]
+ if physical_ids is not None and ordinal < len(physical_ids)
+ else ordinal
+ )
+ names_by_id[pid] = name
+
+ indices = list(gpu_indices) if gpu_indices else list(names_by_id)
+ saw = False
+ for _i in indices:
+ name = names_by_id.get(_i)
+ if name is None:
+ continue # not visible -> skip (fail conservative)
+ saw = True
+ if not pattern.search(name):
+ return False
+ return saw
+ except Exception:
+ return False
+
+ @staticmethod
+ def _effective_gpu_count(gpu_indices = None) -> int:
+ """GPUs llama-server will use: len(selection), else the visible CUDA
+ device count (None = every visible GPU). 0 on error so multi-GPU tuning
+ stays off when the count is unknown."""
+ if gpu_indices is not None:
+ return len(gpu_indices)
+ try:
+ import torch
+ if hasattr(torch, "cuda") and torch.cuda.is_available():
+ return torch.cuda.device_count()
+ except Exception:
+ return 0
+ return 0
+
+ @staticmethod
+ def _apply_datacenter_env(env: dict, gpu_indices = None) -> bool:
+ """Inject DC llama.cpp tuning into env in place via setdefault (user
+ values win); return whether the box qualified. Opt out with
+ UNSLOTH_DISABLE_DC_TUNING=1; only datacenter NVIDIA parts qualify
+ (consumer/ROCm/CPU/error are a no-op). Sets GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F
+ for any qualifying GPU (FP32 accum: ~0% cost on B200, real cost on GeForce),
+ plus GGML_CUDA_P2P + CUDA_SCALE_LAUNCH_QUEUES=4x for multi-GPU (+33-51% pp
+ tensor-split, +8-16% pipeline split on B200)."""
+ if os.environ.get("UNSLOTH_DISABLE_DC_TUNING") == "1":
+ return False
+ if not LlamaCppBackend._is_datacenter_gpu(gpu_indices):
+ return False
+ env.setdefault("GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F", "1")
+ if LlamaCppBackend._effective_gpu_count(gpu_indices) > 1:
+ env.setdefault("GGML_CUDA_P2P", "1")
+ env.setdefault("CUDA_SCALE_LAUNCH_QUEUES", "4x")
+ return True
+
@staticmethod
def _get_gpu_free_memory() -> list[tuple[int, int]]:
"""Query free memory per GPU.
@@ -3406,6 +3505,14 @@ class LlamaCppBackend:
env.setdefault("GGML_CUDA_ENABLE_UNIFIED_MEMORY", "1")
logger.info("AMD unified-memory APU: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1")
+ # DC NVIDIA GPUs: FP32 accum (+ P2P / launch queues for multi-GPU).
+ # See _apply_datacenter_env; opt out with UNSLOTH_DISABLE_DC_TUNING=1.
+ if self._apply_datacenter_env(env, gpu_indices):
+ multi_gpu = self._effective_gpu_count(gpu_indices) > 1
+ logger.info(
+ f"Data-center GPU detected: applied DC llama.cpp env tuning (multi_gpu={multi_gpu})"
+ )
+
if sys.platform == "win32":
# Ordering: see _build_windows_path_dirs. #5106.
path_dirs = self._build_windows_path_dirs(
diff --git a/studio/backend/tests/test_datacenter_gpu_tuning.py b/studio/backend/tests/test_datacenter_gpu_tuning.py
new file mode 100644
index 00000000000..fd9b291e8a8
--- /dev/null
+++ b/studio/backend/tests/test_datacenter_gpu_tuning.py
@@ -0,0 +1,278 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Data-center llama.cpp env tuning: FP32 accum (+ P2P / launch queues for
+multi-GPU) must apply only to datacenter NVIDIA parts, never consumer GeForce,
+AMD/ROCm, CPU or macOS. User values win; UNSLOTH_DISABLE_DC_TUNING=1 disables.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+from core.inference.llama_cpp import LlamaCppBackend
+
+
+def _fake_torch(
+ names,
+ *,
+ hip = None,
+ cuda_ok = True,
+):
+ """torch stub: version.hip, cuda.is_available/device_count, get_device_properties(i).name."""
+ t = types.ModuleType("torch")
+ t.version = types.SimpleNamespace(hip = hip)
+ t.cuda = types.SimpleNamespace(
+ is_available = lambda: cuda_ok,
+ device_count = lambda: len(names),
+ get_device_properties = lambda i: types.SimpleNamespace(name = names[i]),
+ )
+ return t
+
+
[email protected](autouse = True)
+def _clear_cuda_visible_devices(monkeypatch):
+ """Detection reads CUDA_VISIBLE_DEVICES, so clear it by default (run unmasked,
+ physical id == ordinal) regardless of host; masked tests set it explicitly."""
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+
+
+# ---------------------------------------------------------------------------
+# _is_datacenter_gpu
+# ---------------------------------------------------------------------------
+
+
+ "names,expected",
+ [
+ # Datacenter / professional parts.
+ (["NVIDIA A100-SXM4-80GB"], True),
+ (["NVIDIA A30"], True),
+ (["NVIDIA H100 80GB HBM3"], True),
+ (["NVIDIA H200"], True),
+ (["NVIDIA H800"], True),
+ (["NVIDIA GH200 480GB"], True),
+ (["NVIDIA B200"], True),
+ (["NVIDIA GB200"], True),
+ (["NVIDIA L40S"], True),
+ (["NVIDIA L4"], True),
+ (["NVIDIA RTX PRO 6000 Blackwell Server Edition"], True),
+ (["NVIDIA RTX 6000 Ada Generation"], True),
+ # Consumer GeForce: never.
+ (["NVIDIA GeForce RTX 4090"], False),
+ (["NVIDIA GeForce RTX 5090"], False),
+ (["NVIDIA GeForce RTX 3090"], False),
+ (["NVIDIA GeForce RTX 2080 Ti"], False),
+ (["NVIDIA GeForce GTX 1080"], False),
+ # Workstation/laptop: short markers must not match as substrings
+ # ("a100" in "A1000", "a30" in "A3000").
+ (["NVIDIA RTX A1000 Laptop GPU"], False),
+ (["NVIDIA RTX A1000 6GB Laptop GPU"], False),
+ (["NVIDIA RTX A3000 Laptop GPU"], False),
+ # Homogeneous multi-DC: all must match.
+ (["NVIDIA B200", "NVIDIA B200"], True),
+ (["NVIDIA H100 80GB HBM3", "NVIDIA H100 80GB HBM3"], True),
+ # Mixed DC + consumer: non-DC, so tuning never lands on the GeForce.
+ (["NVIDIA B200", "NVIDIA GeForce RTX 4090"], False),
+ (["NVIDIA GeForce RTX 4090", "NVIDIA B200"], False),
+ ],
+)
+def test_is_datacenter_gpu(monkeypatch, names, expected):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(names))
+ assert LlamaCppBackend._is_datacenter_gpu() is expected
+
+
+def test_is_datacenter_gpu_respects_selection(monkeypatch):
+ # A mixed box where only the DC GPU is selected -> True; only consumer -> False.
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch(["NVIDIA B200", "NVIDIA GeForce RTX 4090"]),
+ )
+ assert LlamaCppBackend._is_datacenter_gpu([0]) is True
+ assert LlamaCppBackend._is_datacenter_gpu([1]) is False
+ assert LlamaCppBackend._is_datacenter_gpu([0, 1]) is False
+
+
+def test_is_datacenter_gpu_out_of_range_indices_skipped(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"]))
+ # Out-of-range / negative indices are skipped; the one valid DC GPU still wins.
+ assert LlamaCppBackend._is_datacenter_gpu([0, 5, -1]) is True
+ # Only invalid indices -> nothing seen -> False (fail closed for the flag).
+ assert LlamaCppBackend._is_datacenter_gpu([5, 9]) is False
+
+
+def test_is_datacenter_gpu_masked_host_physical_ids(monkeypatch):
+ # Mask 4,5,6,7 -> ordinals 0..3 == physical 4..7. PHYSICAL selection [4,5]
+ # must resolve, not index out of range (the pre-fix bug: 4 >= device_count).
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5,6,7")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))
+ assert LlamaCppBackend._is_datacenter_gpu([4, 5]) is True
+ assert LlamaCppBackend._is_datacenter_gpu([4, 5, 6, 7]) is True
+ assert LlamaCppBackend._is_datacenter_gpu(None) is True
+ assert LlamaCppBackend._is_datacenter_gpu([0, 1]) is False # not visible -> skip
+
+
+def test_is_datacenter_gpu_masked_host_reordered(monkeypatch):
+ # Reordered mask preserves order: ordinal 0 -> physical 7, 1 -> 4, ...
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "7,4,5,6")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA H100 80GB HBM3"] * 4))
+ assert LlamaCppBackend._is_datacenter_gpu([7, 4]) is True
+
+
+def test_is_datacenter_gpu_masked_host_mixed_class(monkeypatch):
+ # Mask 4,5: physical 4 = GeForce, physical 5 = B200. Detection must follow the
+ # selected physical GPU, not a same-numbered ordinal.
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch(["NVIDIA GeForce RTX 4090", "NVIDIA B200"]),
+ )
+ assert LlamaCppBackend._is_datacenter_gpu([4]) is False
+ assert LlamaCppBackend._is_datacenter_gpu([5]) is True
+ assert LlamaCppBackend._is_datacenter_gpu([4, 5]) is False
+
+
+def test_is_datacenter_gpu_unparsable_mask_falls_back(monkeypatch):
+ # Unparsable (UUID) mask falls back to physical id == ordinal (mirrors
+ # _get_gpu_free_memory), so ordinal lookup still classifies the device.
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-abcdef12")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"]))
+ assert LlamaCppBackend._is_datacenter_gpu([0]) is True
+
+
+def test_is_datacenter_gpu_rocm_is_false(monkeypatch):
+ # ROCm reuses torch.cuda.*; an MI300X must not qualify.
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _fake_torch(["AMD Instinct MI300X"], hip = "6.2.0"),
+ )
+ assert LlamaCppBackend._is_datacenter_gpu() is False
+
+
+def test_is_datacenter_gpu_no_cuda_is_false(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch([], cuda_ok = False))
+ assert LlamaCppBackend._is_datacenter_gpu() is False
+
+
+def test_is_datacenter_gpu_missing_torch_is_false(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert LlamaCppBackend._is_datacenter_gpu() is False
+
+
+# ---------------------------------------------------------------------------
+# _effective_gpu_count
+# ---------------------------------------------------------------------------
+
+
+def test_effective_gpu_count_explicit_selection(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))
+ assert LlamaCppBackend._effective_gpu_count([0]) == 1
+ assert LlamaCppBackend._effective_gpu_count([0, 1, 2]) == 3
+
+
+def test_effective_gpu_count_none_uses_visible(monkeypatch):
+ # None -> visible device count.
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))
+ assert LlamaCppBackend._effective_gpu_count(None) == 4
+
+
+def test_effective_gpu_count_no_cuda_is_zero(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch([], cuda_ok = False))
+ assert LlamaCppBackend._effective_gpu_count(None) == 0
+
+
+def test_effective_gpu_count_missing_torch_is_zero(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert LlamaCppBackend._effective_gpu_count(None) == 0
+
+
+# ---------------------------------------------------------------------------
+# _apply_datacenter_env (the env-injection decision)
+# ---------------------------------------------------------------------------
+
+
+def test_apply_env_single_dc_gpu_sets_only_fp32(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"]))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [0]) is True
+ assert env == {"GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F": "1"}
+ assert "GGML_CUDA_P2P" not in env # no multi-GPU flags on one GPU
+ assert "CUDA_SCALE_LAUNCH_QUEUES" not in env
+
+
+def test_apply_env_multi_dc_gpu_sets_all(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [0, 1]) is True
+ assert env["GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F"] == "1"
+ assert env["GGML_CUDA_P2P"] == "1"
+ assert env["CUDA_SCALE_LAUNCH_QUEUES"] == "4x"
+
+
+def test_apply_env_none_indices_uses_visible_count(monkeypatch):
+ # None on a 2x DC box -> multi-GPU flags applied.
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA H100", "NVIDIA H100"]))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, None) is True
+ assert env["GGML_CUDA_P2P"] == "1"
+ assert env["CUDA_SCALE_LAUNCH_QUEUES"] == "4x"
+
+
+def test_apply_env_consumer_gpu_is_noop(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA GeForce RTX 4090"] * 2))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [0, 1]) is False
+ assert env == {}
+
+
+def test_apply_env_user_value_wins(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 2))
+ env = {
+ "GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F": "0", # user explicitly disabled
+ "CUDA_SCALE_LAUNCH_QUEUES": "8x", # user override
+ }
+ assert LlamaCppBackend._apply_datacenter_env(env, [0, 1]) is True
+ # setdefault must not clobber user values; the unset one still defaults.
+ assert env["GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F"] == "0"
+ assert env["CUDA_SCALE_LAUNCH_QUEUES"] == "8x"
+ assert env["GGML_CUDA_P2P"] == "1"
+
+
+def test_apply_env_disable_flag_respected(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DISABLE_DC_TUNING", "1")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 2))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [0, 1]) is False
+ assert env == {}
+
+
+def test_apply_env_fail_open_on_detection_error(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setitem(sys.modules, "torch", None) # detection raises -> False
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [0]) is False
+ assert env == {}
+
+
+def test_apply_env_masked_host_multi_dc(monkeypatch):
+ # End-to-end masked host (mask 4,5,6,7, physical selection [4,5]): pre-fix
+ # applied no tuning; now all three multi-GPU flags must be set.
+ monkeypatch.delenv("UNSLOTH_DISABLE_DC_TUNING", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "4,5,6,7")
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(["NVIDIA B200"] * 4))
+ env: dict = {}
+ assert LlamaCppBackend._apply_datacenter_env(env, [4, 5]) is True
+ assert env["GGML_CUDA_FORCE_CUBLAS_COMPUTE_32F"] == "1"
+ assert env["GGML_CUDA_P2P"] == "1"
+ assert env["CUDA_SCALE_LAUNCH_QUEUES"] == "4x"