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.

Widen the pinned child GPU mask when extra args name a companion device (#11823)

jishnav2046e53e3ddd
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index f07587bc40b..458146b5c02 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -6284,6 +6284,101 @@ def _extra_args_draft_device(extra_args: Optional[Iterable[str]]) -> Optional[st
return _extra_args_device(extra_args, {"--spec-draft-device", "-devd", "--device-draft"})
+_GPU_DEVICE_TOKEN_RE = re.compile(r"(CUDA|ROCm)(\d+)$", re.IGNORECASE)
+# One group per companion: llama.cpp is last-wins within a group, so only its last flag counts.
+_COMPANION_DEVICE_FLAG_GROUPS = (
+ frozenset({"--mmproj-device", "-mmdev"}),
+ frozenset({"--spec-draft-device", "-devd", "--device-draft"}),
+)
+
+
+def _widen_pin_ids_for_companion_devices(
+ cmd: List[str],
+ pin_ids: list[int],
+ inherited_ids: Optional[list[int]],
+ *,
+ may_widen: bool = True,
+) -> tuple[list[int], str]:
+ """Fit a pinned GPU mask to the companion devices the argv names (#11810).
+
+ Companion ``CUDA<n>`` / ``ROCm<n>`` tokens use the unpinned numbering (position in
+ ``inherited_ids``, else the physical index). Cards they name are appended after the
+ pinned ones, the winning flag is renumbered to the child's mask, and a main
+ ``--device`` is added so ``-ngl -1`` does not spread over the extra cards. Tokens
+ the parent cannot see are left alone. ``may_widen`` False (explicit gpu_ids) only
+ renumbers within the pin. Returns the mask and a log note, empty when unchanged.
+ """
+ if not pin_ids:
+ return list(pin_ids), ""
+ main_ids = [int(i) for i in pin_ids]
+ # A main --device past the pinned positions would resolve to a widened companion card.
+ for token in str(_extra_args_main_device(cmd) or "").split(","):
+ match = _GPU_DEVICE_TOKEN_RE.match(token.strip())
+ if match and int(match.group(2)) >= len(main_ids):
+ return list(main_ids), ""
+ # (value index, prefix before "=" or None, [(token, physical id or None)])
+ sites: list[tuple[int, Optional[str], list[tuple[str, Optional[int]]]]] = []
+ prefix_word = None
+ last_of_group: dict[int, int] = {}
+ for i, raw in enumerate(cmd):
+ for group, flags in enumerate(_COMPANION_DEVICE_FLAG_GROUPS):
+ if _flag_name(str(raw)) in flags:
+ last_of_group[group] = i
+ for i in sorted(last_of_group.values()):
+ raw = str(cmd[i])
+ head, eq, inline = raw.partition("=")
+ if eq:
+ at, value, lead = i, inline, head + "="
+ elif i + 1 < len(cmd):
+ at, value, lead = i + 1, str(cmd[i + 1]), None
+ else:
+ continue
+ tokens: list[tuple[str, Optional[int]]] = []
+ for token in value.split(","):
+ match = _GPU_DEVICE_TOKEN_RE.match(token.strip())
+ physical = None
+ if match:
+ prefix_word = prefix_word or match.group(1)
+ n = int(match.group(2))
+ if inherited_ids is None:
+ physical = n
+ elif n < len(inherited_ids):
+ physical = int(inherited_ids[n])
+ if not may_widen and physical not in main_ids:
+ physical = None
+ tokens.append((token, physical))
+ if any(physical is not None for _, physical in tokens):
+ sites.append((at, lead, tokens))
+ if not sites:
+ return list(main_ids), ""
+ widened = list(main_ids)
+ for _, _, tokens in sites:
+ for _, physical in tokens:
+ if physical is not None and physical not in widened:
+ widened.append(physical)
+ changed = False
+ for at, lead, tokens in sites:
+ rewritten = []
+ for token, physical in tokens:
+ if physical is None:
+ rewritten.append(token)
+ continue
+ match = _GPU_DEVICE_TOKEN_RE.match(token.strip())
+ rewritten.append(f"{match.group(1)}{widened.index(physical)}")
+ value = ",".join(rewritten)
+ new = f"{lead}{value}" if lead is not None else value
+ if new != cmd[at]:
+ cmd[at] = new
+ changed = True
+ if len(widened) > len(main_ids) and _extra_args_main_device(cmd) is None:
+ # Pinned cards lead the mask, so the main model's devices are the first positions.
+ cmd.extend(["--device", ",".join(f"{prefix_word}{k}" for k in range(len(main_ids)))])
+ changed = True
+ if not changed and widened == main_ids:
+ return list(main_ids), ""
+ return widened, f"{main_ids} -> {widened}"
+
+
def _extra_args_draft_device_pin(extra_args: Optional[Iterable[str]]) -> Optional[str]:
"""Return a GPU draft-device override; cpu/none do not conflict with a pin."""
last_dev = _extra_args_draft_device(extra_args)
@@ -29124,6 +29219,9 @@ class LlamaCppBackend:
# own devices, the child aborting on a pin it cannot see. The
# draft-device forms count too: parsed with no drafter loaded.
_child_gpu_physical_ids: Optional[tuple[int, ...]] = None
+ # companion flags fitted to the child's mask, refitted by the arch-crash retry
+ _companion_fit_mask: Optional[list[int]] = None
+ _companion_added_device: Optional[list[str]] = None
if not is_vulkan_backend and _gpu_mem:
_child_gpu_physical_ids = self._unmasked_child_gpu_physical_ids()
@@ -29231,6 +29329,31 @@ class LlamaCppBackend:
# Mask on AMD at the ROCr/HSA layer: HIP-only masking still
# enumerates every agent first, which segfaults on a deselected
# unsupported GPU (e.g. gfx1036 iGPU under a gfx103X prebuilt).
+ # Companion flags use the unpinned numbering (#11810). Skipped for a
+ # uuid/MIG mask (CUDA<n> is ambiguous) and an inherited LLAMA_ARG_DEVICE
+ # (the appended --device would override it).
+ _companion_widen = ""
+ if not self._visibility_mask_is_unmappable() and not (
+ _extra_args_main_device(cmd) is None
+ and str(env.get("LLAMA_ARG_DEVICE", "")).strip()
+ ):
+ _had_main_device = _extra_args_main_device(cmd) is not None
+ _pin_ids, _companion_widen = _widen_pin_ids_for_companion_devices(
+ cmd,
+ _pin_ids,
+ self._resolve_visible_physical_ids(),
+ may_widen = not gpu_ids,
+ )
+ if _companion_widen:
+ _companion_fit_mask = list(_pin_ids)
+ if not _had_main_device and _extra_args_main_device(cmd) is not None:
+ _companion_added_device = list(cmd[-2:])
+ if _companion_widen:
+ logger.info(
+ "Companion device flags name GPUs by their unpinned "
+ "numbering; fitted the pinned mask to them: %s",
+ _companion_widen,
+ )
self._emit_child_gpu_visibility(
env,
LlamaCppBackend._child_visibility_for(_pin_ids),
@@ -30470,10 +30593,36 @@ class LlamaCppBackend:
"weights outgrow; set "
"GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 for the respawn."
)
+ _retry_mask = list(_remaining)
+ if _companion_fit_mask is not None:
+ # tokens are positions in the crashed launch's mask
+ if _companion_added_device is not None:
+ for _k in range(len(cmd) - 1, 0, -1):
+ if cmd[_k - 1 : _k + 1] == _companion_added_device:
+ del cmd[_k - 1 : _k + 1]
+ break
+ _had_main_device = _extra_args_main_device(cmd) is not None
+ _retry_mask, _refit = _widen_pin_ids_for_companion_devices(
+ cmd,
+ list(_remaining),
+ list(_companion_fit_mask),
+ may_widen = not gpu_ids,
+ )
+ _companion_added_device = (
+ list(cmd[-2:])
+ if not _had_main_device and _extra_args_main_device(cmd) is not None
+ else None
+ )
+ _companion_fit_mask = list(_retry_mask)
+ if _refit:
+ logger.info(
+ "Refitted companion device flags to the retry's mask: %s",
+ _refit,
+ )
self._emit_child_gpu_visibility(
- env, ",".join(str(i) for i in _remaining), prefer_rocr = True
+ env, ",".join(str(i) for i in _retry_mask), prefer_rocr = True
)
- _child_gpu_physical_ids = tuple(int(i) for i in _remaining)
+ _child_gpu_physical_ids = tuple(int(i) for i in _retry_mask)
# Same for the inherited env twins of the flags dropped
# below: the new mask re-indexes the survivors under them.
self._clear_split_placement_env(env)
diff --git a/studio/backend/tests/test_companion_device_widening.py b/studio/backend/tests/test_companion_device_widening.py
new file mode 100644
index 00000000000..51e554cbaeb
--- /dev/null
+++ b/studio/backend/tests/test_companion_device_widening.py
@@ -0,0 +1,181 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""_widen_pin_ids_for_companion_devices (#11810): --mmproj-device / --spec-draft-device
+naming a card the pin hides was "invalid device"; the mask now widens to cover it."""
+
+import pytest
+
+import core.inference.llama_cpp as llama_cpp
+
+
+def _widen(
+ pin_ids,
+ cmd,
+ inherited = None,
+ may_widen = True,
+):
+ cmd = list(cmd)
+ widened, note = llama_cpp._widen_pin_ids_for_companion_devices(
+ cmd, pin_ids, inherited, may_widen = may_widen
+ )
+ return cmd, widened, note
+
+
+def _value(cmd, flag):
+ return cmd[len(cmd) - 1 - cmd[::-1].index(flag) + 1]
+
+
+def test_a_hidden_companion_device_widens_the_mask():
+ cmd, pin, note = _widen(
+ [0],
+ ["--mmproj-offload", "--mmproj-device", "CUDA1", "--spec-draft-device", "CUDA1"],
+ )
+ assert pin == [0, 1]
+ assert _value(cmd, "--device") == "CUDA0", "the main model keeps GPU 0 after the widening"
+ assert _value(cmd, "--mmproj-device") == "CUDA1"
+ assert note
+
+
+def test_a_companion_on_a_lower_card_is_renumbered_not_left_on_the_main_card():
+ # child mask "1,0": an untouched CUDA0 would stack the projector on the main card
+ cmd, pin, _ = _widen([1], ["--mmproj-device", "CUDA0"])
+ assert pin == [1, 0]
+ assert _value(cmd, "--mmproj-device") == "CUDA1"
+ assert _value(cmd, "--device") == "CUDA0"
+
+
+def test_a_companion_on_the_pinned_card_is_renumbered_to_the_childs_first_device():
+ # Pinned to GPU 1 alone, the child sees one device, CUDA0; the user's CUDA1 is invalid.
+ cmd, pin, note = _widen([1], ["--mmproj-device", "CUDA1"])
+ assert pin == [1]
+ assert _value(cmd, "--mmproj-device") == "CUDA0"
+ assert "--device" not in cmd, "nothing was added to the mask"
+ assert note
+
+
+def test_the_remap_matches_the_visible_order():
+ """With an inherited non-ascending main order, CUDA<n> means n in the WIDENED set."""
+ cmd, pin, note = _widen([1, 0], ["--mmproj-device", "CUDA2"])
+ assert pin == [1, 0, 2]
+ assert _value(cmd, "--device") == "CUDA0,CUDA1"
+ assert _value(cmd, "--mmproj-device") == "CUDA2"
+ assert "2" in note
+
+
+def test_tokens_are_read_through_the_inherited_mask():
+ # A scheduler exposed physical 2 and 3; the user's CUDA0 is physical 2.
+ cmd, pin, _ = _widen([3], ["--mmproj-device", "CUDA0"], inherited = [2, 3])
+ assert pin == [3, 2]
+ assert _value(cmd, "--mmproj-device") == "CUDA1"
+
+
+def test_a_token_past_the_inherited_mask_never_widens_it():
+ cmd, pin, note = _widen([3], ["--mmproj-device", "CUDA5"], inherited = [2, 3])
+ assert pin == [3]
+ assert cmd == ["--mmproj-device", "CUDA5"]
+ assert note == ""
+
+
+def test_no_device_flag_is_emitted_when_the_user_named_one():
+ cmd, pin, note = _widen([0], ["--mmproj-device", "CUDA1", "--device", "CUDA0"])
+ assert pin == [0, 1]
+ assert cmd.count("--device") == 1, "the user's own --device survives untouched"
+ assert note
+
+
+def test_a_main_device_past_the_pin_is_not_moved_onto_a_companion_card():
+ cmd, pin, note = _widen([0], ["--device", "CUDA1", "--mmproj-device", "CUDA2"])
+ assert pin == [0]
+ assert cmd == ["--device", "CUDA1", "--mmproj-device", "CUDA2"]
+ assert note == ""
+
+
+def test_a_flag_already_on_the_childs_numbering_changes_nothing():
+ cmd, pin, note = _widen([0, 1], ["--mmproj-device", "CUDA1"])
+ assert pin == [0, 1]
+ assert cmd == ["--mmproj-device", "CUDA1"]
+ assert note == ""
+
+
+def test_non_gpu_device_tokens_are_ignored():
+ cmd, pin, note = _widen([0], ["--mmproj-device", "CPU", "--spec-draft-device", "none"])
+ assert pin == [0]
+ assert cmd == ["--mmproj-device", "CPU", "--spec-draft-device", "none"]
+ assert note == ""
+
+
+def test_a_stripped_flag_is_not_acted_on():
+ cmd, pin, note = _widen([0], ["--ctx-size", "4096"])
+ assert pin == [0]
+ assert cmd == ["--ctx-size", "4096"]
+ assert note == ""
+
+
[email protected]("prefix", ["CUDA", "ROCm"])
+def test_value_forms_the_parser_reads(prefix):
+ """--flag=value inline spelling and comma lists both reach the helper."""
+ cmd, pin, _ = _widen([0], [f"--mmproj-device={prefix}1"])
+ assert pin == [0, 1]
+ assert f"--mmproj-device={prefix}1" in cmd
+ assert _value(cmd, "--device") == f"{prefix}0"
+
+ cmd, pin, _ = _widen([1], ["--spec-draft-device", f"{prefix}0,{prefix}1"])
+ assert pin == [1, 0]
+ assert _value(cmd, "--spec-draft-device") == f"{prefix}1,{prefix}0"
+
+
+def test_only_the_flag_that_wins_is_acted_on():
+ cmd, pin, _ = _widen([0], ["--mmproj-device", "CUDA7", "-mmdev", "CUDA2"])
+ assert pin == [0, 2], "an overridden flag must not expose another card"
+ assert cmd[:2] == ["--mmproj-device", "CUDA7"]
+ assert _value(cmd, "-mmdev") == "CUDA1"
+ assert cmd.count("--device") == 1
+
+
+def test_load_model_uses_the_argv_and_skips_an_unmappable_mask():
+ import inspect
+
+ src = inspect.getsource(llama_cpp.LlamaCppBackend.load_model)
+ at = src.index("_widen_pin_ids_for_companion_devices(")
+ window = src[at - 400 : at + 200]
+ assert "_visibility_mask_is_unmappable()" in window
+ assert 'env.get("LLAMA_ARG_DEVICE", "")' in window
+ assert "may_widen = not gpu_ids" in src[at : at + 300]
+
+
+def test_an_explicit_gpu_ids_pin_is_never_widened_onto_another_card():
+ cmd, pin, note = _widen([0], ["--mmproj-device", "CUDA1"], may_widen = False)
+ assert pin == [0]
+ assert cmd == ["--mmproj-device", "CUDA1"]
+ assert note == ""
+
+
+def test_an_explicit_pin_still_renumbers_a_companion_on_one_of_its_cards():
+ cmd, pin, _ = _widen([2, 3], ["--mmproj-device", "CUDA3"], may_widen = False)
+ assert pin == [2, 3]
+ assert _value(cmd, "--mmproj-device") == "CUDA1"
+ assert "--device" not in cmd
+
+
+def test_an_arch_crash_retry_refits_the_companion_to_the_new_mask():
+ # [0] widened to [0, 1]; GPU 0 crashes, respawn on 2: projector stays on physical 1
+ cmd, first, _ = _widen([0], ["--mmproj-device", "CUDA1"])
+ assert first == [0, 1] and cmd[-2:] == ["--device", "CUDA0"]
+ del cmd[-2:] # the generated main --device, as the retry drops it
+ retry, note = llama_cpp._widen_pin_ids_for_companion_devices(cmd, [2], first)
+ assert retry == [2, 1]
+ assert _value(cmd, "--mmproj-device") == "CUDA1"
+ assert _value(cmd, "--device") == "CUDA0"
+ assert note
+
+
+def test_the_arch_crash_retry_refits_companions_in_source():
+ import inspect
+
+ src = inspect.getsource(llama_cpp.LlamaCppBackend.load_model)
+ retry = src.index("_arch_crash_retry_gpu_ids(")
+ window = src[retry : retry + 12000]
+ assert "_companion_fit_mask" in window
+ assert "list(_companion_fit_mask)" in window
+ assert '",".join(str(i) for i in _retry_mask)' in window