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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio (Jetson): keep JetPack's CUDA ahead of pip CUDA in llama-server and backend loader paths (#13191)
Daniel Han0512f3a38a4d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 8047d2113e1..8ee38bf42e4 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -16354,13 +16354,15 @@ class LlamaCppBackend:# glob.escape: a prefix with [brackets] is otherwise read as a pattern._site = os.path.join(_glob.escape(sys.prefix), "lib", "python*", "site-packages")+ _pip_dirs = []for _nv_pattern in [os.path.join(_site, "nvidia", _sub, "lib") for _sub in ("cu*", "cudnn", "nvjitlink")] + [os.path.join(_site, "torch", "lib")]:for _nv_dir in _glob.glob(_nv_pattern):if os.path.isdir(_nv_dir):- lib_dirs.append(_nv_dir)+ _pip_dirs.append(_nv_dir)+ _system_dirs = []for cuda_lib in ["/usr/local/cuda/lib64",f"/usr/local/cuda/targets/{_arch}-linux/lib",@@ -16372,7 +16374,15 @@ class LlamaCppBackend:f"/usr/local/cuda-12.8/targets/{_arch}-linux/lib",]:if os.path.isdir(cuda_lib):- lib_dirs.append(cuda_lib)+ _system_dirs.append(cuda_lib)+ from utils.tegra import TEGRA_LIB_DIR, is_tegra++ if is_tegra():+ # Jetson: JetPack's CUDA first; the generic pip builds load but crash on unified memory (#4862).+ _tegra = [TEGRA_LIB_DIR] if os.path.isdir(TEGRA_LIB_DIR) else []+ lib_dirs.extend(_tegra + _system_dirs + _pip_dirs)+ else:+ lib_dirs.extend(_pip_dirs + _system_dirs)# Vendored dirs go last: rescue only, never displace a runtime already found.from utils.llama_cpp_freshness import read_install_markerdiff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex b6853f3ef63..1f42cefc5b0 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -877,19 +877,29 @@ class LlamaServerBackend:lib_dirs = [binary_dir]# glob.escape: a prefix with [brackets] is otherwise read as a pattern.site = os.path.join(glob.escape(sys.prefix), "lib", "python*", "site-packages")+ pip_dirs = []for pattern in (os.path.join(site, "nvidia", "cu*", "lib"),os.path.join(site, "nvidia", "cudnn", "lib"),os.path.join(site, "torch", "lib"),):- lib_dirs.extend(d for d in glob.glob(pattern) if os.path.isdir(d))- for cuda_lib in (- "/usr/local/cuda/lib64",- f"/usr/local/cuda/targets/{arch}-linux/lib",- "/usr/local/cuda-12/lib64",- ):- if os.path.isdir(cuda_lib):- lib_dirs.append(cuda_lib)+ pip_dirs.extend(d for d in glob.glob(pattern) if os.path.isdir(d))+ system_dirs = [+ d+ for d in (+ "/usr/local/cuda/lib64",+ f"/usr/local/cuda/targets/{arch}-linux/lib",+ "/usr/local/cuda-12/lib64",+ )+ if os.path.isdir(d)+ ]+ from utils.tegra import TEGRA_LIB_DIR, is_tegra++ if is_tegra():+ tegra = [TEGRA_LIB_DIR] if os.path.isdir(TEGRA_LIB_DIR) else []+ lib_dirs.extend(tegra + system_dirs + pip_dirs)+ else:+ lib_dirs.extend(pip_dirs + system_dirs)existing = env.get("LD_LIBRARY_PATH", "")joined = ":".join(lib_dirs)env["LD_LIBRARY_PATH"] = f"{joined}:{existing}" if existing else joineddiff --git a/studio/backend/run.py b/studio/backend/run.pyindex 36242d9393c..bdfdeb96403 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -33,6 +33,17 @@ def _normalize_standard_streams():_normalize_standard_streams()+def _is_tegra():+ """utils.tegra.is_tegra, inlined: this runs before the backend is on sys.path."""+ try:+ if os.path.exists("/etc/nv_tegra_release"):+ return True+ with open("/proc/device-tree/compatible", "rb") as fh:+ return b"nvidia,tegra" in fh.read()+ except OSError:+ return False++def _fix_torch_cuda_ld_path():"""Prepend torch's bundled CUDA libs to LD_LIBRARY_PATH, returning True if it was changed. PyTorch wheelsship their own CUDA runtime in ``site-packages/nvidia/*/lib``; on Linux the dynamic linker reads@@ -58,7 +69,8 @@ def _fix_torch_cuda_ld_path():torch_lib = os.path.join(torch_dir, "lib")if os.path.isdir(torch_lib):lib_dirs.append(torch_lib)- if os.path.isdir(nvidia_dir):+ # Jetson: JetPack's CUDA stays first (#4862).+ if os.path.isdir(nvidia_dir) and not _is_tegra():for sub in sorted(os.listdir(nvidia_dir)):lib = os.path.join(nvidia_dir, sub, "lib")if os.path.isdir(lib):diff --git a/studio/backend/tests/test_tegra_cuda_lib_order.py b/studio/backend/tests/test_tegra_cuda_lib_order.pynew file mode 100644index 00000000000..e513ceaca6e--- /dev/null+++ b/studio/backend/tests/test_tegra_cuda_lib_order.py@@ -0,0 +1,148 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""On a Jetson, JetPack's CUDA goes ahead of the generic pip CUDA builds in every loader path a+llama-server child or the backend itself gets (#4862); every other host keeps today's order."""++import os+import sys++import pytest++import run+from core.inference import llama_cpp+from core.rag import embed_llama_server+from utils import tegra++SYSTEM = ("/usr/local/cuda/lib64", "/usr/local/cuda/targets/aarch64-linux/lib", tegra.TEGRA_LIB_DIR)+++def host(monkeypatch, tmp_path):+ """A Linux aarch64 host whose venv carries pip CUDA and torch libs; returns a Tegra switch."""+ site = tmp_path / "lib" / "python3.12" / "site-packages"+ pip_dirs = [+ site / "nvidia" / "cu13" / "lib",+ site / "nvidia" / "cudnn" / "lib",+ site / "torch" / "lib",+ ]+ for d in pip_dirs:+ d.mkdir(parents = True)+ (site / "torch" / "__init__.py").write_text("")+ real_isdir = os.path.isdir+ monkeypatch.setattr(os.path, "isdir", lambda p: str(p) in SYSTEM or real_isdir(p))+ monkeypatch.setattr(sys, "prefix", str(tmp_path))+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr("platform.machine", lambda: "aarch64")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ state = {"tegra": False, "site": site}++ def set_tegra(value):+ state["tegra"] = value+ monkeypatch.setattr(tegra, "is_tegra", lambda: state["tegra"])+ monkeypatch.setattr(run, "_is_tegra", lambda: state["tegra"], raising = False)++ set_tegra(False)+ return set_tegra, state+++def _first_system_and_pip(paths):+ sys_pos = min(i for i, p in enumerate(paths) if p.startswith("/usr/local/cuda"))+ pip_pos = min(i for i, p in enumerate(paths) if "site-packages" in p)+ return sys_pos, pip_pos+++def _llama_paths(monkeypatch, tmp_path):+ binary = tmp_path / "bin" / "llama-server"+ binary.parent.mkdir()+ binary.write_text("")+ monkeypatch.setattr(llama_cpp, "_wsl_system_rocm_lib_dirs", lambda: [])+ monkeypatch.setattr(llama_cpp, "_native_linux_system_rocm_lib_dirs", lambda d: [])+ env = llama_cpp.LlamaCppBackend._llama_server_env_for_binary(str(binary), use_system_rocm = False)+ return env["LD_LIBRARY_PATH"].split(":")+++def _embed_paths(tmp_path):+ env = {}+ embed_llama_server.LlamaServerBackend._add_linux_cuda_libs(env, str(tmp_path / "bin"))+ return env["LD_LIBRARY_PATH"].split(":")+++# LD_LIBRARY_PATH is ":"-joined; a Windows tmp path ("C:\\...") would split apart.+_posix_paths = pytest.mark.skipif(os.name == "nt", reason = "LD_LIBRARY_PATH builders are Linux-only")+++def _run_paths(monkeypatch):+ monkeypatch.setenv("LD_LIBRARY_PATH", "/usr/local/cuda/lib64")+ run._fix_torch_cuda_ld_path()+ return os.environ["LD_LIBRARY_PATH"].split(":")+++def test_jetson_puts_jetpack_cuda_ahead_of_pip_cuda_for_llama_server(host, monkeypatch, tmp_path):+ set_tegra, _ = host+ set_tegra(True)+ sys_pos, pip_pos = _first_system_and_pip(_llama_paths(monkeypatch, tmp_path))+ assert sys_pos < pip_pos+++def test_jetson_puts_jetpack_cuda_ahead_of_pip_cuda_for_the_embedding_server(host, tmp_path):+ set_tegra, _ = host+ set_tegra(True)+ paths = _embed_paths(tmp_path)+ sys_pos, pip_pos = _first_system_and_pip(paths)+ assert sys_pos < pip_pos+ assert paths.index(tegra.TEGRA_LIB_DIR) < sys_pos+++@_posix_paths+def test_jetson_backend_does_not_hoist_pip_cuda_over_jetpack(host, monkeypatch):+ set_tegra, state = host+ monkeypatch.setattr(+ "importlib.util.find_spec",+ lambda name: type("S", (), {"origin": str(state["site"] / "torch" / "__init__.py")})(),+ )+ set_tegra(True)+ paths = _run_paths(monkeypatch)+ assert not any("nvidia" in p for p in paths[: paths.index("/usr/local/cuda/lib64")])++[email protected]("machine", ["aarch64", "x86_64"])+def test_other_hosts_keep_pip_cuda_first(host, monkeypatch, tmp_path, machine):+ monkeypatch.setattr("platform.machine", lambda: machine)+ sys_pos, pip_pos = _first_system_and_pip(_llama_paths(monkeypatch, tmp_path))+ assert pip_pos < sys_pos+ sys_pos, pip_pos = _first_system_and_pip(_embed_paths(tmp_path))+ assert pip_pos < sys_pos+ assert tegra.TEGRA_LIB_DIR not in _embed_paths(tmp_path)+++@_posix_paths+def test_other_hosts_still_hoist_torch_cuda_in_the_backend(host, monkeypatch):+ _, state = host+ monkeypatch.setattr(+ "importlib.util.find_spec",+ lambda name: type("S", (), {"origin": str(state["site"] / "torch" / "__init__.py")})(),+ )+ paths = _run_paths(monkeypatch)+ assert paths.index(str(state["site"] / "nvidia" / "cu13" / "lib")) < paths.index(+ "/usr/local/cuda/lib64"+ )+++def test_is_tegra_reads_the_markers_and_never_raises(monkeypatch, tmp_path):+ release = tmp_path / "nv_tegra_release"+ compatible = tmp_path / "compatible"+ monkeypatch.setattr(tegra, "_TEGRA_RELEASE", str(release))+ monkeypatch.setattr(tegra, "_DEVICE_TREE_COMPATIBLE", str(compatible))+ tegra.is_tegra.cache_clear()+ assert tegra.is_tegra() is False # neither marker present+ compatible.write_bytes(b"nvidia,p3737-0000+p3701-0005\x00nvidia,tegra234\x00")+ tegra.is_tegra.cache_clear()+ assert tegra.is_tegra() is True+ compatible.write_bytes(b"raspberrypi,5-model-b\x00brcm,bcm2712\x00")+ tegra.is_tegra.cache_clear()+ assert tegra.is_tegra() is False+ release.write_text("# R36 (release), REVISION: 4.0\n")+ tegra.is_tegra.cache_clear()+ assert tegra.is_tegra() is True+ tegra.is_tegra.cache_clear()diff --git a/studio/backend/utils/tegra.py b/studio/backend/utils/tegra.pynew file mode 100644index 00000000000..216dd1c0223--- /dev/null+++ b/studio/backend/utils/tegra.py@@ -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++"""NVIDIA Jetson (Tegra) detection, cheap enough for loader-path builders."""++import functools+import os++_TEGRA_RELEASE = "/etc/nv_tegra_release"+_DEVICE_TREE_COMPATIBLE = "/proc/device-tree/compatible"+TEGRA_LIB_DIR = "/usr/lib/aarch64-linux-gnu/tegra"++[email protected]_cache(maxsize = 1)+def is_tegra() -> bool:+ """True on a Jetson: JetPack's release file, or a Tegra SoC in the device tree. Never raises."""+ try:+ if os.path.exists(_TEGRA_RELEASE):+ return True+ with open(_DEVICE_TREE_COMPATIBLE, "rb") as fh:+ return b"nvidia,tegra" in fh.read()+ except OSError:+ return False