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: give a desktop launch the ROCm environment a terminal launch has (#11125)

Daniel Han1d5210d7a9ec
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 16f3c10fbfd..ef471ebf307 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -22,6 +22,26 @@ os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
# spawned workers inherit it. `setdefault` preserves an explicit override, including "0".
os.environ.setdefault("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", "1")
+# The desktop app hands this process a GUI environment, and a GUI environment has
+# no ~/.bashrc in it. `fix_path_env::fix()` in src-tauri/src/main.rs spawns the
+# login shell and then takes PATH out of it and nothing else, so an AMD host's
+# HSA_OVERRIDE_GFX_VERSION / ROCM_PATH / USE_CK are dropped on the desktop path
+# and kept on the `unsloth studio` one. #9926 is that difference: identical model
+# and machine, SIGSEGV from the app and a clean run from a terminal.
+#
+# Here because HSA reads HSA_OVERRIDE_GFX_VERSION and USE_CK when torch first
+# touches the GPU, which is far below this. A no-op unless the desktop app owns
+# this process AND the host has an AMD GPU AND the variable is absent, so a
+# terminal launch and every non-AMD host are unchanged.
+_backend_dir = str(_Path(__file__).parent)
+if _backend_dir not in sys.path:
+ sys.path.insert(0, _backend_dir)
+try:
+ from utils.desktop_shell_env import import_rocm_env_from_login_shell as _import_rocm_env
+ _import_rocm_env()
+except Exception:
+ pass
+
# Windows terminals default to the active system code page. Reconfigure stdout/stderr
# before the startup banner so non-ASCII output cannot crash the backend process.
if sys.platform == "win32":
diff --git a/studio/backend/tests/test_desktop_shell_env_9926.py b/studio/backend/tests/test_desktop_shell_env_9926.py
new file mode 100644
index 00000000000..d0262aeea36
--- /dev/null
+++ b/studio/backend/tests/test_desktop_shell_env_9926.py
@@ -0,0 +1,350 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""unsloth#9926: a desktop launch must end with the ROCm environment a terminal has.
+
+An RX 7600 SIGSEGVs from the desktop app and trains from ``unsloth studio``,
+because ``fix_path_env::fix()`` is ``fix_vars(&["PATH"])`` and keeps only PATH
+out of the login shell. These pin the shape of the fix, not the crash, which
+needs the card.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import sys
+import time
+
+import pytest
+
+from utils import desktop_shell_env as dse
+
+
+def linux(monkeypatch):
+ """The module returns before anything else off Linux, so pin the platform.
+
+ Without this the import tests pass on a Windows or macOS runner by asserting
+ the early return, which is how staging CI caught them asserting nothing.
+ """
+ monkeypatch.setattr(dse.sys, "platform", "linux")
+
+
+def desktop(**extra) -> dict:
+ """An environment as the desktop app hands it over: marked, and ROCm-empty."""
+ return {dse.DESKTOP_MANAGED_ENV: "1", **extra}
+
+
+def test_no_amd_gpu_imports_nothing_and_spawns_no_shell(linux, monkeypatch):
+ monkeypatch.setattr(dse, "host_has_amd_gpu", lambda: False)
+
+ def _explode(*_a, **_k):
+ raise AssertionError("the login shell must not be spawned without an AMD GPU")
+
+ monkeypatch.setattr(dse, "read_login_shell_env", _explode)
+ environ = desktop()
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+ assert environ == desktop()
+
+
+def test_amd_host_imports_the_missing_rocm_vars(linux, monkeypatch):
+ monkeypatch.setattr(dse, "host_has_amd_gpu", lambda: True)
+ monkeypatch.setattr(
+ dse,
+ "read_login_shell_env",
+ lambda *_a, **_k: {
+ "HSA_OVERRIDE_GFX_VERSION": "11.0.0",
+ "ROCM_PATH": "/opt/rocm",
+ "USE_CK": "0",
+ "PATH": "/usr/bin",
+ },
+ )
+ environ = desktop(PATH = "/gui/bin")
+ imported = dse.import_rocm_env_from_login_shell(environ = environ)
+ assert imported == {
+ "HSA_OVERRIDE_GFX_VERSION": "11.0.0",
+ "ROCM_PATH": "/opt/rocm",
+ "USE_CK": "0",
+ }
+ assert environ["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0"
+ # PATH is src-tauri's, deliberately built; taking it here would overwrite it.
+ assert environ["PATH"] == "/gui/bin"
+
+
+def test_a_variable_already_set_is_never_overwritten():
+ shell = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0", "ROCM_PATH": "/opt/rocm"}
+ environ = {"HSA_OVERRIDE_GFX_VERSION": "10.3.0"}
+ assert dse.select_missing_vars(environ, shell) == {"ROCM_PATH": "/opt/rocm"}
+
+
+def test_a_variable_exported_empty_counts_as_set():
+ # Replacing an exported empty would be this module choosing a device.
+ shell = {"HIP_VISIBLE_DEVICES": "0,1"}
+ assert dse.select_missing_vars({"HIP_VISIBLE_DEVICES": ""}, shell) == {}
+
+
+def test_an_empty_mask_in_the_shell_is_imported_as_empty():
+ # An exported empty hides every agent; dropping it hands back the cards.
+ assert dse.select_missing_vars({}, {"ROCR_VISIBLE_DEVICES": ""}) == {"ROCR_VISIBLE_DEVICES": ""}
+
+
+def test_only_allowlisted_names_are_imported():
+ shell = {
+ "HSA_OVERRIDE_GFX_VERSION": "11.0.0",
+ "CUDA_VISIBLE_DEVICES": "3",
+ "AWS_SECRET_ACCESS_KEY": "hunter2",
+ "LD_PRELOAD": "/tmp/evil.so",
+ "PYTHONPATH": "/tmp/whatever",
+ }
+ assert dse.select_missing_vars({}, shell) == {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"}
+
+
+def test_the_allowlist_carries_no_other_vendor():
+ # One of these on the list changes a GUI launch on someone else's stack.
+ forbidden = ("CUDA", "NVIDIA", "NCCL", "ONEAPI", "SYCL", "LEVEL_ZERO", "MLX", "METAL")
+ offenders = [
+ name
+ for name in dse.ROCM_SHELL_ENV_ALLOWLIST
+ if any(token in name.upper() for token in forbidden)
+ ]
+ assert offenders == []
+
+
+def test_importing_twice_is_a_no_op_the_second_time(linux, monkeypatch):
+ monkeypatch.setattr(dse, "host_has_amd_gpu", lambda: True)
+ monkeypatch.setattr(dse, "read_login_shell_env", lambda *_a, **_k: {"ROCM_PATH": "/opt/rocm"})
+ environ = desktop()
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {"ROCM_PATH": "/opt/rocm"}
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+
+
+def test_the_opt_out_short_circuits_before_anything_is_read(monkeypatch):
+ def _explode(*_a, **_k):
+ raise AssertionError("opted out, so nothing should be probed")
+
+ monkeypatch.setattr(dse, "host_has_amd_gpu", _explode)
+ environ = desktop(**{dse.DISABLE_ENV_VAR: "1"})
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+
+
+def test_a_shell_that_fails_yields_nothing(linux, monkeypatch):
+ monkeypatch.setattr(dse, "host_has_amd_gpu", lambda: True)
+
+ def _raise(*_a, **_k):
+ raise OSError("no shell here")
+
+ monkeypatch.setattr(dse.subprocess, "Popen", _raise)
+ environ = desktop()
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+ assert environ == desktop()
+
+
[email protected](sys.platform == "win32", reason = "no POSIX shell on Windows")
+def test_a_real_login_shell_round_trips_a_value(tmp_path, monkeypatch):
+ """``env -0`` is used so a value with a newline cannot split the record."""
+ rc = tmp_path / "rc.sh"
+ rc.write_text(
+ 'echo "banner from an rc file"\n'
+ 'export ROCM_PATH="/opt/rocm"\n'
+ 'export HSA_OVERRIDE_GFX_VERSION="11.0.0"\n'
+ 'export UNSLOTH_TEST_MULTILINE="one\ntwo"\n',
+ encoding = "utf-8",
+ )
+ shim = tmp_path / "shell.sh"
+ # Stands in for a login shell: takes -ilc and sources an rc file first.
+ shim.write_text(
+ "#!/bin/sh\n" f'. "{rc}"\n' "shift 1\n" 'exec /bin/sh -c "$1"\n',
+ encoding = "utf-8",
+ )
+ shim.chmod(0o755)
+
+ env = dse.read_login_shell_env(shell = str(shim))
+ assert env.get("ROCM_PATH") == "/opt/rocm"
+ assert env.get("HSA_OVERRIDE_GFX_VERSION") == "11.0.0"
+ assert env.get("UNSLOTH_TEST_MULTILINE") == "one\ntwo"
+
+
+ not sys.platform.startswith("linux"), reason = "the KFD topology only exists on Linux"
+)
+def test_the_amd_probe_answers_from_the_kernel_without_torch():
+ # No assertion about the answer: this box may or may not have an AMD GPU.
+ assert dse.host_has_amd_gpu() in (True, False)
+
+
+def test_a_launch_the_desktop_app_does_not_own_reads_no_shell(linux, monkeypatch):
+ def _explode(*_a, **_k):
+ raise AssertionError("only a desktop launch lost its environment")
+
+ monkeypatch.setattr(dse, "host_has_amd_gpu", _explode)
+ monkeypatch.setattr(dse, "read_login_shell_env", _explode)
+ # A terminal, a systemd unit, a container: none carry the marker.
+ for environ in ({}, {dse.DESKTOP_MANAGED_ENV: "0"}, {dse.DESKTOP_MANAGED_ENV: ""}):
+ before = dict(environ)
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+ assert environ == before
+
+
+def test_an_amd_kfd_node_is_an_amd_gpu():
+ amd = "cpu_cores_count 0\nsimd_count 32\ngfx_target_version 110200\nvendor_id 4098\n"
+ assert dse._node_is_an_amd_gpu(amd) is True
+
+
+def test_an_nvidia_open_driver_kfd_node_is_not_an_amd_gpu():
+ nvidia = "cpu_cores_count 0\nsimd_count 32\ngfx_target_version 110000\nvendor_id 4318\n"
+ assert dse._node_is_an_amd_gpu(nvidia) is False
+
+
+def test_a_cpu_node_is_not_a_gpu():
+ cpu = "cpu_cores_count 16\nsimd_count 0\ngfx_target_version 0\nvendor_id 4098\n"
+ assert dse._node_is_an_amd_gpu(cpu) is False
+
+
+def _shim(tmp_path, rc_body: str):
+ """A stand-in login shell: sources an rc file, then runs the -c command."""
+ rc = tmp_path / "rc.sh"
+ rc.write_text(rc_body, encoding = "utf-8")
+ shim = tmp_path / "shell.sh"
+ shim.write_text(
+ "#!/bin/sh\n" f'. "{rc}"\n' "shift 1\n" 'exec /bin/sh -c "$1"\n', encoding = "utf-8"
+ )
+ shim.chmod(0o755)
+ return str(shim)
+
+
[email protected](sys.platform == "win32", reason = "no POSIX shell on Windows")
+def test_a_background_job_in_the_rc_neither_stalls_nor_loses_the_environment(tmp_path):
+ """An rc that starts an agent must not cost the whole timeout.
+
+ The child inherits stdout, so a pipe capture waits for it, not for the shell.
+ """
+ shell = _shim(tmp_path, "sleep 45 &\nexport ROCM_PATH=/opt/rocm\n")
+ started = time.monotonic()
+ env = dse.read_login_shell_env(shell = shell, timeout = 15.0)
+ assert time.monotonic() - started < 10.0
+ assert env.get("ROCM_PATH") == "/opt/rocm"
+
+
+def _wait_for_exit(pid: int, seconds: float = 5.0) -> bool:
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ try:
+ os.kill(pid, 0)
+ except OSError:
+ return True
+ time.sleep(0.1)
+ return False
+
+
[email protected](sys.platform == "win32", reason = "no POSIX shell on Windows")
+def test_a_successful_read_still_takes_the_shells_children_with_it(tmp_path):
+ """The shell exits cleanly, so nothing raises: its children still must go."""
+ pidfile = tmp_path / "child.pid"
+ shell = _shim(tmp_path, f"sleep 300 &\necho $! > {pidfile}\nexport ROCM_PATH=/opt/rocm\n")
+ assert dse.read_login_shell_env(shell = shell).get("ROCM_PATH") == "/opt/rocm"
+ child = int(pidfile.read_text().strip())
+ if not _wait_for_exit(child):
+ os.kill(child, signal.SIGKILL)
+ raise AssertionError(f"pid {child} outlived the shell that started it")
+
+
[email protected](sys.platform == "win32", reason = "no POSIX shell on Windows")
+def test_the_timeout_takes_the_shells_children_with_it(tmp_path):
+ """A hung shell must not leave its children running, once per launch."""
+ pidfile = tmp_path / "child.pid"
+ shell = _shim(tmp_path, f"sleep 300 &\necho $! > {pidfile}\nsleep 300\n")
+ assert dse.read_login_shell_env(shell = shell, timeout = 2.0) == {}
+ child = int(pidfile.read_text().strip())
+ if not _wait_for_exit(child):
+ os.kill(child, signal.SIGKILL)
+ raise AssertionError(f"pid {child} outlived the shell that started it")
+
+
[email protected](sys.platform == "win32", reason = "no POSIX shell on Windows")
+def test_a_value_the_filesystem_allows_but_utf8_does_not_round_trips(tmp_path):
+ """A path carrying a non-UTF-8 byte must arrive as those bytes."""
+ shell = _shim(tmp_path, "export ROCM_PATH=\"$(printf '/opt/rocm\\377')\"\n")
+ env = dse.read_login_shell_env(shell = shell)
+ assert os.fsencode(env["ROCM_PATH"]) == b"/opt/rocm\xff"
+
+
+def _shell_with_the_reporters_override(monkeypatch):
+ monkeypatch.setattr(dse, "host_has_amd_gpu", lambda: True)
+ monkeypatch.setattr(
+ dse,
+ "read_login_shell_env",
+ lambda *_a, **_k: {"HSA_OVERRIDE_GFX_VERSION": "11.0.0", "ROCM_PATH": "/opt/rocm"},
+ )
+
+
+def test_an_override_the_install_cannot_serve_is_not_imported(linux, monkeypatch):
+ _shell_with_the_reporters_override(monkeypatch)
+ environ = desktop(**{dse.ROCM_INSTALLED_ARCH_ENV: "gfx1151"})
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {"ROCM_PATH": "/opt/rocm"}
+ assert dse.HSA_OVERRIDE_ENV not in environ
+
+
+def test_an_override_the_install_can_serve_is_imported(linux, monkeypatch):
+ # 11.0.0 is gfx1100, and these wheels carry gfx1100 kernels.
+ _shell_with_the_reporters_override(monkeypatch)
+ environ = desktop(**{dse.ROCM_INSTALLED_ARCH_ENV: "gfx1100"})
+ imported = dse.import_rocm_env_from_login_shell(environ = environ)
+ assert imported["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0"
+
+
+def test_an_install_that_is_not_single_arch_arbitrates_nothing(linux, monkeypatch):
+ """No marker means generic or multi-arch wheels, which contradict no override."""
+ _shell_with_the_reporters_override(monkeypatch)
+ imported = dse.import_rocm_env_from_login_shell(environ = desktop())
+ assert imported["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0"
+
+
+ "value, expected",
+ [
+ ("11.0.0", "gfx1100"),
+ ("11.5.1", "gfx1151"),
+ ("10.3.0", "gfx1030"),
+ ("9.4.2", "gfx942"),
+ # A stepping is a hex nibble, so 10 is "a" and 16 is not a target at all.
+ ("11.0.10", "gfx110a"),
+ ("11.0.16", None),
+ ("11.0", None),
+ ("", None),
+ ("gfx1100", None),
+ (None, None),
+ ],
+)
+def test_the_override_parser_matches_the_cli(value, expected):
+ """One arbiter, two processes: a launch must not depend on which saw it first."""
+ import unsloth_cli.commands.studio as studio_cli
+
+ assert dse.override_gfx_arch(value) == expected
+ assert studio_cli._hsa_override_gfx_arch(value) == expected
+
+
+def test_an_unreadable_override_is_not_ours_to_drop():
+ """The CLI guard leaves a value it cannot parse alone, so this must too."""
+ assert dse.override_contradicts_install("not-a-version", "gfx1151") is False
+
+
+def test_the_cli_and_this_module_name_the_same_marker():
+ """Two files, one contract: a rename on either side must fail here."""
+ import unsloth_cli.commands.studio as studio_cli
+ assert studio_cli.ROCM_INSTALLED_ARCH_ENV == dse.ROCM_INSTALLED_ARCH_ENV
+
+
[email protected]("platform", ["win32", "darwin"])
+def test_no_other_platform_reads_a_shell(platform, monkeypatch):
+ """Windows inherits the user environment already, and macOS has no KFD."""
+
+ def _explode(*_a, **_k):
+ raise AssertionError(f"{platform} must return before anything is read")
+
+ monkeypatch.setattr(dse.sys, "platform", platform)
+ monkeypatch.setattr(dse, "host_has_amd_gpu", _explode)
+ monkeypatch.setattr(dse, "read_login_shell_env", _explode)
+ environ = desktop()
+ assert dse.import_rocm_env_from_login_shell(environ = environ) == {}
+ assert environ == desktop()
diff --git a/studio/backend/utils/desktop_shell_env.py b/studio/backend/utils/desktop_shell_env.py
new file mode 100644
index 00000000000..35f084d0b9e
--- /dev/null
+++ b/studio/backend/utils/desktop_shell_env.py
@@ -0,0 +1,261 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Give the desktop app the ROCm environment a terminal launch already has.
+
+unsloth#9926: ``fix_path_env::fix()`` is ``fix_vars(&["PATH"])``, so src-tauri
+reads the login shell and keeps PATH out of it, dropping every ROCm variable
+beside it. Parity, not policy: only a desktop launch, only an AMD host, only
+allowlisted names that are absent here. Every other launch reads no shell.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import shlex
+import signal
+import subprocess
+import sys
+import tempfile
+
+logger = logging.getLogger(__name__)
+
+DISABLE_ENV_VAR = "UNSLOTH_DISABLE_SHELL_ENV_IMPORT"
+
+# Set by src-tauri on every CLI child it owns (process.rs, DESKTOP_MANAGED_ENV).
+DESKTOP_MANAGED_ENV = "UNSLOTH_DESKTOP_MANAGED"
+
+# From the CLI's #7331 guard, which ran against a GUI environment that never had
+# the override: the arbiter travels, its verdict would say nothing here.
+ROCM_INSTALLED_ARCH_ENV = "UNSLOTH_ROCM_INSTALLED_ARCH"
+HSA_OVERRIDE_ENV = "HSA_OVERRIDE_GFX_VERSION"
+
+# AMD/ROCm only: a wider list would change a GUI launch on someone else's stack.
+ROCM_SHELL_ENV_ALLOWLIST: tuple[str, ...] = (
+ "HSA_OVERRIDE_GFX_VERSION",
+ "PYTORCH_ROCM_ARCH",
+ "AMDGPU_TARGETS",
+ "GPU_TARGETS",
+ "ROCM_PATH",
+ "ROCM_HOME",
+ "HIP_PATH",
+ "HIP_PLATFORM",
+ # CK was being attempted on an arch it was not built for (#9926).
+ "USE_CK",
+ "TORCH_BLAS_PREFER_HIPBLASLT",
+ "MIOPEN_USER_DB_PATH",
+ "MIOPEN_CUSTOM_CACHE_DIR",
+ "MIOPEN_FIND_MODE",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "GPU_DEVICE_ORDINAL",
+ # DXG_DETECTION: main.py sets it for WSL, a host that set it by hand wins.
+ "HSA_ENABLE_SDMA",
+ "HSA_ENABLE_DXG_DETECTION",
+ "HSA_XNACK",
+ "HSA_FORCE_FINE_GRAIN_PCIE",
+ "AMD_SERIALIZE_KERNEL",
+ "GPU_MAX_HW_QUEUES",
+)
+# Not HSA_TOOLS_LIB: HSA dlopens it, which loads a library rather than tuning one.
+
+# NVIDIA's open kernel module registers KFD nodes too (4318), hence the check.
+_AMD_VENDOR_ID = "4098"
+
+
+def host_has_amd_gpu() -> bool:
+ """Whether the amdgpu driver is presenting a GPU here.
+
+ The KFD topology, not torch: this runs before torch is imported.
+ """
+ if not sys.platform.startswith("linux"):
+ return False
+ try:
+ if not os.path.exists("/dev/kfd"):
+ return False
+ nodes = "/sys/class/kfd/kfd/topology/nodes"
+ for entry in sorted(os.listdir(nodes)):
+ path = os.path.join(nodes, entry, "properties")
+ try:
+ with open(path, "r", encoding = "utf-8", errors = "replace") as handle:
+ text = handle.read()
+ except OSError:
+ continue
+ if _node_is_an_amd_gpu(text):
+ return True
+ except Exception:
+ return False
+ return False
+
+
+def _node_is_an_amd_gpu(properties: str) -> bool:
+ """Whether one KFD node's ``properties`` file describes an AMD GPU."""
+ fields = {}
+ for line in properties.splitlines():
+ key, _, value = line.partition(" ")
+ fields[key] = value.strip()
+ try:
+ if int(fields.get("gfx_target_version", "0")) <= 0:
+ return False
+ except ValueError:
+ return False
+ return fields.get("vendor_id") == _AMD_VENDOR_ID
+
+
+def read_login_shell_env(shell: "str | None" = None, timeout: float = 15.0) -> dict:
+ """The environment an interactive login shell would have handed us, or ``{}``.
+
+ ``-i`` runs ``~/.zshrc`` and ``-l`` the profile chain; bash reaches
+ ``~/.bashrc`` only because the stock ``~/.profile`` sources it. ``env -0``
+ into a FILE: a newline in a value corrupts a line parse, and an rc that
+ backgrounds a job leaves that child holding a capture pipe.
+ """
+ shell = shell or os.environ.get("SHELL") or "/bin/sh"
+ with tempfile.TemporaryDirectory(prefix = "unsloth-shell-env-") as work:
+ target = os.path.join(work, "env")
+ try:
+ process = subprocess.Popen(
+ [shell, "-ilc", f"env -0 > {shlex.quote(target)}"],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ # Oh My Zsh's auto-update prompt can block the shell forever.
+ env = {**os.environ, "DISABLE_AUTO_UPDATE": "true"},
+ # Its own group, so the cleanup below takes the whole shell.
+ start_new_session = True,
+ )
+ except Exception as error:
+ logger.debug("login shell environment unavailable: %s", error)
+ return {}
+ # pgid == pid, read before the wait reaps it: getpgid then raises.
+ group = process.pid
+ try:
+ returncode = process.wait(timeout = timeout)
+ except Exception as error:
+ logger.debug("login shell did not finish: %s", error)
+ returncode = None
+ finally:
+ # Every path: a clean exit still leaves an rc's agent running.
+ _terminate_group(group, process)
+ if returncode != 0:
+ logger.debug("login shell exited %s", returncode)
+ return {}
+ try:
+ with open(target, "rb") as handle:
+ raw = handle.read()
+ except OSError as error:
+ logger.debug("login shell wrote no environment: %s", error)
+ return {}
+
+ out: dict = {}
+ # surrogateescape, as os.environ does: `replace` corrupts a path.
+ for record in raw.decode("utf-8", "surrogateescape").split("\0"):
+ name, sep, value = record.partition("=")
+ if sep and name:
+ out[name] = value
+ return out
+
+
+def _terminate_group(group: int, process) -> None:
+ """Kill the shell's session and anything left in it. Never raises."""
+ try:
+ os.killpg(group, signal.SIGKILL)
+ except Exception:
+ pass
+ try:
+ process.wait(timeout = 5)
+ except Exception:
+ pass
+
+
+def select_missing_vars(
+ environ,
+ shell_env,
+ allowlist = ROCM_SHELL_ENV_ALLOWLIST,
+) -> dict:
+ """The allowlisted names the shell has and this process does not.
+
+ Membership on both sides, never truthiness: exported empty is a statement, and
+ ``ROCR_VISIBLE_DEVICES=`` hides every agent.
+ """
+ out: dict = {}
+ for name in allowlist:
+ if name in environ:
+ continue
+ if name in shell_env and isinstance(shell_env[name], str):
+ out[name] = shell_env[name]
+ return out
+
+
+def import_rocm_env_from_login_shell(
+ environ = None,
+ shell = None,
+ timeout: float = 15.0,
+) -> dict:
+ """Fill in the ROCm variables a desktop launch dropped. Returns what it set."""
+ environ = os.environ if environ is None else environ
+ if str(environ.get(DISABLE_ENV_VAR, "")).strip() == "1":
+ return {}
+ # Not a desktop launch: nothing was lost, so nothing is read.
+ if str(environ.get(DESKTOP_MANAGED_ENV, "")).strip() != "1":
+ return {}
+ if not sys.platform.startswith("linux"):
+ return {}
+ if not host_has_amd_gpu():
+ return {}
+ if all(name in environ for name in ROCM_SHELL_ENV_ALLOWLIST):
+ return {}
+
+ imported = select_missing_vars(environ, read_login_shell_env(shell, timeout))
+ if HSA_OVERRIDE_ENV in imported and override_contradicts_install(
+ imported[HSA_OVERRIDE_ENV], environ.get(ROCM_INSTALLED_ARCH_ENV)
+ ):
+ logger.info(
+ "Not importing %s=%s from the login shell: this install carries %s kernels "
+ "only (#7331).",
+ HSA_OVERRIDE_ENV,
+ imported[HSA_OVERRIDE_ENV],
+ environ.get(ROCM_INSTALLED_ARCH_ENV),
+ )
+ del imported[HSA_OVERRIDE_ENV]
+ for name, value in imported.items():
+ environ[name] = value
+ if imported:
+ logger.info(
+ "Imported ROCm environment from the login shell (desktop launches do "
+ "not inherit it): %s",
+ ", ".join(sorted(imported)),
+ )
+ return imported
+
+
+def override_gfx_arch(value):
+ """The gfx arch an ``HSA_OVERRIDE_GFX_VERSION`` value names, or None.
+
+ In step with ``_hsa_override_gfx_arch`` in unsloth_cli/commands/studio.py,
+ install_python_stack.py and install.sh; the parity is tested.
+ """
+ if not isinstance(value, str) or not value:
+ return None
+ # [0-9] rather than str.isdigit()/\d, both of which accept non-ASCII digits.
+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", value.strip()):
+ return None
+ major, minor, step = (int(part) for part in value.strip().split("."))
+ # Steppings are a single hex nibble; anything wider is not a real target.
+ if not (0 <= step <= 15) or major <= 0 or minor > 9:
+ return None
+ return f"gfx{major}{minor}{step:x}"
+
+
+def override_contradicts_install(value, installed_arch) -> bool:
+ """Whether this override names an arch the installed ROCm wheels cannot serve.
+
+ False for a value that does not parse, matching the CLI guard, which leaves an
+ override it cannot read alone.
+ """
+ if not installed_arch:
+ return False
+ named = override_gfx_arch(value)
+ return named is not None and named != installed_arch
diff --git a/tests/studio/test_cli_hsa_spoof_launch_7331.py b/tests/studio/test_cli_hsa_spoof_launch_7331.py
index dce3f43b65d..398d8802911 100644
--- a/tests/studio/test_cli_hsa_spoof_launch_7331.py
+++ b/tests/studio/test_cli_hsa_spoof_launch_7331.py
@@ -343,3 +343,30 @@ def test_a_rocm_metapackage_orphaned_by_a_switch_to_generic_wheels_arbitrates_no
tmp_path / "orphaned", "rocm_sdk_libraries_gfx1151", torch_needs_rocm = False
)
assert _installed_rocm_single_arch(orphaned) is None
+
+
+class TestPublishingTheArbiterForTheDesktopShellImport:
+ """#11125 imports absent ROCm names back out of the login shell on a desktop
+ launch. There the GUI environment never carried the override, so the clear is a
+ no-op and its verdict says nothing: the backend needs the installed arch itself,
+ published whether or not anything was cleared here."""
+
+ def test_the_installed_arch_is_published_even_with_no_override_set(self, tmp_path, monkeypatch):
+ monkeypatch.delenv("HSA_OVERRIDE_GFX_VERSION", raising = False)
+ monkeypatch.delenv(studio_cli.ROCM_INSTALLED_ARCH_ENV, raising = False)
+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")
+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")
+ monkeypatch.setattr(studio_cli, "STUDIO_HOME", venv.parent)
+ monkeypatch.setattr(studio_cli.sys, "prefix", str(venv))
+ assert studio_cli._clear_hsa_override_before_launch(silent = True) is None
+ assert os.environ[studio_cli.ROCM_INSTALLED_ARCH_ENV] == "gfx1151"
+
+ def test_generic_wheels_publish_nothing_to_arbitrate_with(self, tmp_path, monkeypatch):
+ monkeypatch.delenv("HSA_OVERRIDE_GFX_VERSION", raising = False)
+ monkeypatch.delenv(studio_cli.ROCM_INSTALLED_ARCH_ENV, raising = False)
+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")
+ venv = _make_venv(tmp_path, None)
+ monkeypatch.setattr(studio_cli, "STUDIO_HOME", venv.parent)
+ monkeypatch.setattr(studio_cli.sys, "prefix", str(venv))
+ studio_cli._clear_hsa_override_before_launch(silent = True)
+ assert studio_cli.ROCM_INSTALLED_ARCH_ENV not in os.environ
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index f27cde1d68f..706e413df47 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -414,6 +414,14 @@ def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:
return False
+# The single gfx arch this install carries kernels for, published for the backend.
+# Read by studio/backend/utils/desktop_shell_env.py, which imports ROCm variables a
+# desktop launch never received out of the login shell: that profile is where the
+# #7331 override lives, so the backend needs the same arbiter this guard uses, not
+# just the outcome of running it against a GUI environment that never had the value.
+ROCM_INSTALLED_ARCH_ENV = "UNSLOTH_ROCM_INSTALLED_ARCH"
+
+
def _installed_rocm_single_arch(venv_dir: Path) -> Optional[str]:
"""gfx arch the ROCm runtime in *venv_dir* ACTIVELY carries kernels for, or None. Read from the
`rocm` meta-package: globbing for rocm_sdk_libraries_gfx* would read an ORPHAN. None also
@@ -472,9 +480,14 @@ def _clear_hsa_override_contradicting_install(venv_dir: Path) -> Optional[str]:
def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:
"""Run the #7331 spoof clear for whichever entry point is about to launch. Idempotent."""
_venv = STUDIO_HOME / "unsloth_studio"
- _arch = _clear_hsa_override_contradicting_install(
- Path(sys.prefix) if sys.prefix.startswith(str(_venv)) else _venv
- )
+ _root = Path(sys.prefix) if sys.prefix.startswith(str(_venv)) else _venv
+ _arch = _clear_hsa_override_contradicting_install(_root)
+ # Published whether or not anything was cleared here: on a desktop launch the GUI
+ # environment never carried the override, so the clear above is a no-op and the
+ # contradicting value is still sitting in the profile the backend is about to read.
+ _installed = _installed_rocm_single_arch(_root)
+ if _installed and platform.system() != "Windows":
+ os.environ[ROCM_INSTALLED_ARCH_ENV] = _installed
if _arch is not None and not silent:
typer.echo(
f"Cleared HSA_OVERRIDE_GFX_VERSION: this install carries {_arch} kernels "