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: promote -ts into tensor_split before manual strip (#11334)

Indrajit swain8a9ad3c92a48
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index 6817bd053c0..6cc80435e68 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -10,7 +10,10 @@ https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"""
from __future__ import annotations
import logging
+import math
import os
+import re
+import struct
import sys
from typing import Any, Callable, Iterable, Mapping, Optional
@@ -346,6 +349,7 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
parse_cache_override(out)
parse_split_mode_override(out)
parse_gpu_layers_override(out)
+ parse_tensor_split_override(out)
parse_reasoning_budget_override(out)
parse_reasoning_budget_message_override(out)
return out
@@ -916,6 +920,100 @@ def parse_gpu_layers_override(args: Optional[Iterable[str]]) -> Optional[int]:
return value
+def _as_emitted(value: float) -> float:
+ """``value`` as the manual launcher will write it, which is ``f"{x:g}"``: six significant
+ digits, so the text the child parses is not always the number validated here."""
+ return float(f"{value:g}")
+
+
+def _as_float32(value: float) -> float:
+ """``value`` as llama.cpp would hold it: overflow becomes inf rather than raising.
+
+ ``struct.pack`` raises OverflowError where the C cast it stands in for saturates, so the
+ caller would have to guard every call site instead of just testing isfinite once.
+ """
+ try:
+ return struct.unpack("=f", struct.pack("=f", value))[0]
+ except OverflowError:
+ return math.copysign(math.inf, value)
+
+
+# Largest share llama.cpp's float array can hold; anything above is out_of_range to std::stof.
+_FLOAT32_MAX = struct.unpack("=f", struct.pack("=f", 3.4028234663852886e38))[0]
+
+# FLT_MIN. libstdc++ throws out_of_range on any SUBNORMAL result too, so the range has a floor as
+# well as a ceiling (measured: stof("1e-38") throws, stof("0") is fine). Rounding decides, not the
+# literal: 1.1754943508222874e-38 rounds UP to FLT_MIN and is accepted.
+_FLOAT32_MIN_NORMAL = struct.unpack("=f", struct.pack("=f", 1.1754943508222875e-38))[0]
+
+
+def parse_tensor_split_override(
+ args: Optional[Iterable[str]], *, reserialized: bool = False
+) -> Optional[list[float]]:
+ """Return the last user-supplied ``-ts`` / ``--tensor-split`` ratios from extras.
+
+ Manual GPU memory with ``gpu_layers >= 0`` strips ``--tensor-split`` because the first-class
+ ``tensor_split`` field owns it. Callers must promote the last-wins extras value into that
+ field first, or an asymmetric MoE split such as ``-ts 2.2,1`` is discarded and llama-server
+ falls back to a near-even layer count (#11330).
+
+ Delimiters match llama.cpp's ``[,/]+`` (``-ts 3/1`` is the same as ``-ts 3,1``). Degenerate
+ values raise so ``validate_extra_args`` can refuse them as a 400 rather than stripping them
+ silently.
+
+ Bounds are llama.cpp's, not Python's: ``std::stof`` (common/arg.cpp) throws
+ ``std::out_of_range`` above FLT_MAX and on any subnormal, and the shares are prefix-summed
+ into a float array (llama-model.cpp), so a value this parser would take as a finite double
+ can still abort the server at startup. Every share is rounded to float32 BEFORE it joins the
+ total, because that is the order llama.cpp adds them in.
+
+ ``reserialized`` is which text the child will parse. Manual mode promotes the ratio into the
+ first-class field and the launcher writes it back out with ``f"{x:g}"``, six significant
+ digits, so there the emitted string is judged. Everywhere else ``-ts`` is pass-through and
+ llama-server reads the user's own text, so judging a rounded version would refuse input that
+ runs: ``-ts 1.1754943508222874e-38,1`` is fine as typed and subnormal once re-serialized.
+ """
+ raw_value = _last_flag_value(args, _TENSOR_SPLIT_FLAGS)
+ if raw_value is None:
+ return None
+ try:
+ parts = [float(p) for p in re.split(r"[,/]+", raw_value) if p.strip()]
+ except ValueError as exc:
+ raise ValueError(
+ "llama-server --tensor-split requires a comma- or slash-separated list of numbers"
+ ) from exc
+ if not parts:
+ raise ValueError(
+ "llama-server --tensor-split requires a comma- or slash-separated list of numbers"
+ )
+ if any((not math.isfinite(v)) or v < 0 for v in parts):
+ raise ValueError("llama-server --tensor-split entries must be finite and non-negative")
+ if sum(parts) <= 0:
+ raise ValueError("llama-server --tensor-split must have a positive total")
+ running = 0.0
+ for part in parts:
+ # The share as the CHILD will hold it: its own text under pass-through, the launcher's
+ # six-digit rendering once manual mode re-serializes it.
+ share = _as_float32(_as_emitted(part) if reserialized else part)
+ if not math.isfinite(share):
+ raise ValueError(
+ "llama-server --tensor-split entries must fit in a 32-bit float "
+ f"(at most {_FLOAT32_MAX:g})"
+ )
+ if part != 0 and share < _FLOAT32_MIN_NORMAL:
+ raise ValueError(
+ "llama-server --tensor-split entries must be 0 or at least "
+ f"{_FLOAT32_MIN_NORMAL:g}: a smaller share is a subnormal float and "
+ "std::stof refuses it"
+ )
+ # llama.cpp prefix-sums the shares it parsed, in float32, so the total is accumulated
+ # the same way rather than in double and compared once.
+ running = _as_float32(running + share)
+ if not math.isfinite(running):
+ raise ValueError("llama-server --tensor-split adds up past the 32-bit float range")
+ return parts
+
+
def check_batch_floor(args: Optional[Iterable[str]], n_parallel: int) -> None:
"""Raise when a pass-through --batch-size would abort llama-server. The launcher raises the
value it emits itself to ``max(slots, 2)``, with the measurements recorded beside that code:
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 9d3ab93ffc9..b48d36a7fa0 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -544,6 +544,17 @@ class ValidateModelRequest(BaseModel):
"for VRAM. -1 (Auto) keeps the previous behaviour for callers that omit it."
),
)
+ tensor_split: Optional[List[float]] = Field(
+ None,
+ description = (
+ "Per-GPU share (--tensor-split) intended for the follow-up load. Manual "
+ "mode promotes an explicit -ts from llama_extra_args into this field "
+ "before stripping the raw flag, so the preflight strips exactly the "
+ "tokens /load strips and judges the command /load will run (#11330). "
+ "No sizing here reads the ratio itself: _guard_chat_load_against_training "
+ "and _estimate_gguf_required_gb budget per device, not per share."
+ ),
+ )
n_parallel: Optional[int] = Field(
None,
ge = PARALLEL_MIN,
@@ -633,6 +644,10 @@ class ValidateModelRequest(BaseModel):
"n_batch", "n_ubatch", "ctx_checkpoints", "reasoning_budget", mode = "before"
)(LoadRequest._no_booleans.__func__)
+ _reject_degenerate_tensor_split = field_validator("tensor_split")(
+ LoadRequest._reject_degenerate_tensor_split.__func__
+ )
+
class TransformersUpgradeInfo(BaseModel):
"""A model architecture no installed transformers ships, but a newer release does."""
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d539a3709d4..f65b5d24dd0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1634,6 +1634,7 @@ try:
parse_reasoning_budget_message_override,
parse_reasoning_budget_override,
parse_split_mode_override,
+ parse_tensor_split_override,
resolve_reasoning_budget,
resolve_reasoning_budget_message,
resolve_tensor_parallel,
@@ -1697,6 +1698,7 @@ except ImportError:
parse_reasoning_budget_message_override,
parse_reasoning_budget_override,
parse_split_mode_override,
+ parse_tensor_split_override,
resolve_reasoning_budget,
resolve_reasoning_budget_message,
resolve_tensor_parallel,
@@ -7222,10 +7224,13 @@ def _should_strip_tensor_split(request: LoadRequest) -> bool:
override it), and with the ratio cleared it wants llama.cpp's default
free-VRAM split. Either way an inherited --tensor-split must go, else the
cleared case silently keeps the stale ratio while status reports None.
- Unlike _should_strip_split_mode this leaves --split-mode untouched, so a
- user's row/none/layer mode survives an Unsloth split-ratio edit. When the
- Tensor Parallelism toggle IS overriding the mode, _should_strip_split_mode
- (called alongside this at every site) strips --split-mode anyway.
+ Explicit extras must be promoted into ``request.tensor_split`` first (same
+ pattern as ``-ngl`` -> ``gpu_layers``) or the strip would discard the only
+ copy of an asymmetric MoE split (#11330). Unlike _should_strip_split_mode
+ this leaves --split-mode untouched, so a user's row/none/layer mode survives
+ an Unsloth split-ratio edit. When the Tensor Parallelism toggle IS overriding
+ the mode, _should_strip_split_mode (called alongside this at every site)
+ strips --split-mode anyway.
"""
return (
getattr(request, "gpu_memory_mode", "auto") == "manual"
@@ -15758,11 +15763,36 @@ async def _load_model_impl(
# stripping the raw flags. This keeps CLI pass-through such as
# ``-ngl 20`` from being silently replaced by the manual default (-1).
# The inherited path already strips offload flags. Manual + per-GPU
- # ratio owns --tensor-split the same way.
+ # ratio owns --tensor-split the same way: promote ``-ts`` into
+ # ``tensor_split`` first, or the strip drops an asymmetric MoE split
+ # and llama-server falls back to a near-even layer count (#11330).
+ # At gpu_layers < 0 the strip does not fire, so the ratio sits in extras
+ # AND in the field; both copies die in load_model's Auto-layers branch,
+ # which test_manual_auto_layers_never_emits_two_tensor_splits pins.
if request.gpu_memory_mode == "manual" and extra_llama_args:
+ _manual_updates: dict[str, Any] = {}
_gpu_layers_override = parse_gpu_layers_override(extra_llama_args)
if _gpu_layers_override is not None:
- request = request.model_copy(update = {"gpu_layers": _gpu_layers_override})
+ _manual_updates["gpu_layers"] = _gpu_layers_override
+ # reserialized only where the launcher REWRITES the ratio, the same predicate
+ # _should_strip_tensor_split uses: manual with the RESOLVED layer count non-negative.
+ # At Auto layers both copies are dropped before argv, so judging a rendering nothing
+ # emits would refuse a flag the child never sees. 400, not the 500 a raise gives.
+ _resolved_layers = (
+ _gpu_layers_override
+ if _gpu_layers_override is not None
+ else getattr(request, "gpu_layers", -1)
+ )
+ try:
+ _tensor_split_override = parse_tensor_split_override(
+ extra_llama_args, reserialized = _resolved_layers >= 0
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc))) from exc
+ if _tensor_split_override is not None:
+ _manual_updates["tensor_split"] = _tensor_split_override
+ if _manual_updates:
+ request = request.model_copy(update = _manual_updates)
_stripped_explicit = strip_shadowing_flags(
extra_llama_args,
strip_context = False,
@@ -17102,15 +17132,34 @@ async def validate_model(
# the GPU; the opposite pairing refused a load that only ever runs on the CPU.
# Same translation, same strip, so the guard below judges the same command.
# After the validation above, so nothing here parses a token the load refuses.
+ # ``-ts`` / ``--tensor-split`` is promoted the same way (#11330).
if getattr(request, "gpu_memory_mode", None) == "manual" and effective_extra_args:
from core.inference.llama_server_args import (
parse_gpu_layers_override,
+ parse_tensor_split_override,
strip_shadowing_flags,
)
+ _validate_manual_updates: dict[str, Any] = {}
_validate_ngl_override = parse_gpu_layers_override(effective_extra_args)
if _validate_ngl_override is not None:
- request = request.model_copy(update = {"gpu_layers": _validate_ngl_override})
+ _validate_manual_updates["gpu_layers"] = _validate_ngl_override
+ # Same reserialized judgement, and the same 400, as the load path above.
+ _validate_resolved_layers = (
+ _validate_ngl_override
+ if _validate_ngl_override is not None
+ else getattr(request, "gpu_layers", -1)
+ )
+ try:
+ _validate_ts_override = parse_tensor_split_override(
+ effective_extra_args, reserialized = _validate_resolved_layers >= 0
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ if _validate_ts_override is not None:
+ _validate_manual_updates["tensor_split"] = _validate_ts_override
+ if _validate_manual_updates:
+ request = request.model_copy(update = _validate_manual_updates)
effective_extra_args = strip_shadowing_flags(
effective_extra_args,
strip_context = False,
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index a9a01f976a8..7a8a0090b2b 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -33,6 +33,12 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
+# The launcher fixtures live beside this file, and the tensor-split cells at the bottom
+# drive the real load_model through them rather than re-deriving a command builder.
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
# Same external-dep stubs as the other llama_cpp unit tests so importing
# the backend doesn't drag in structlog / httpx / loggers.
_loggers_stub = _types.ModuleType("loggers")
@@ -301,15 +307,15 @@ def test_route_normalizes_explicit_extras_before_reload_dedupe():
route_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")
load_impl = route_src[route_src.index("async def _load_model_impl") :]
preserve = load_impl.index("_gpu_layers_override = parse_gpu_layers_override")
- translate = load_impl.index(
- 'request = request.model_copy(update = {"gpu_layers": _gpu_layers_override})'
- )
+ translate = load_impl.index('_manual_updates["gpu_layers"] = _gpu_layers_override')
+ preserve_ts = load_impl.index("_tensor_split_override = parse_tensor_split_override")
+ translate_ts = load_impl.index('_manual_updates["tensor_split"] = _tensor_split_override')
strip = load_impl.index("_stripped_explicit = strip_shadowing_flags")
normalize = load_impl.index(
'request = request.model_copy(update = {"llama_extra_args": extra_llama_args})'
)
dedupe = load_impl.index("_reuse_loaded_gguf(")
- assert preserve < translate < strip < normalize < dedupe
+ assert preserve < translate < preserve_ts < translate_ts < strip < normalize < dedupe
@pytest.mark.parametrize("model_cls", [LoadResponse, InferenceStatusResponse])
@@ -1495,3 +1501,75 @@ def test_zero_vram_chat_load_treats_an_absent_mode_as_auto(not_vulkan):
assert zero("manual", 0, [], False, " ") is False
# Only the canonical spelling still exempts it.
assert zero("manual", 0, [], False, "off") is True
+
+
+def test_manual_auto_layers_never_emits_two_tensor_splits(tmp_path):
+ """Manual + Auto layers is the one cell where the route holds the ratio twice: the
+ strip is False at ``gpu_layers < 0`` while the promotion still fires (#11330).
+ llama.cpp reads the LAST ``--tensor-split``, so a launch path that kept either copy
+ would place by the wrong one; both die here, and that is the launcher's doing rather
+ than the route's, which is why it is pinned.
+ """
+ from test_llama_cpp_placement import _backend, _launch
+
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = False,
+ memory = [(0, 16_000, 16_000), (1, 16_000, 16_000)],
+ )
+ cmd = _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = -1,
+ gpu_ids = [0, 1],
+ n_ctx = 4096,
+ # Exactly the state the /load promotion leaves behind: the field set AND the
+ # raw flag still in extras, because the strip did not fire at gpu_layers < 0.
+ tensor_split = [2.2, 1.0],
+ extra_args = ["-ts", "2.2,1", "-sm", "layer"],
+ )["cmd"]
+ tokens = [tok for tok in cmd if tok in ("--tensor-split", "-ts")]
+ assert len(tokens) <= 1, f"the ratio reached argv twice: {cmd}"
+ # Today both copies are dropped, so /status must not claim a ratio llama-server
+ # never received.
+ assert tokens == []
+ assert backend.tensor_split is None
+
+
+def test_manual_explicit_layers_emits_the_promoted_ratio_once(tmp_path):
+ """The control for the cell above: with layers pinned the strip DOES fire, so the
+ promoted field is the only copy and it is the one that reaches argv (#11330)."""
+ from test_llama_cpp_placement import _backend, _launch
+
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = False,
+ memory = [(0, 16_000, 16_000), (1, 16_000, 16_000)],
+ )
+ cmd = _launch(
+ backend,
+ gguf,
+ gpu_memory_mode = "manual",
+ gpu_layers = 49,
+ gpu_ids = [0, 1],
+ n_ctx = 4096,
+ tensor_split = [2.2, 1.0],
+ # strip_shadowing_flags already removed the raw -ts at this point.
+ extra_args = ["-sm", "layer"],
+ )["cmd"]
+ assert cmd.count("--tensor-split") == 1
+ assert cmd[cmd.index("--tensor-split") + 1] == "2.2,1"
+ assert backend.tensor_split == [2.2, 1.0]
+
+
+def test_manual_auto_layers_does_not_judge_a_rewrite_that_never_happens():
+ """At Auto layers the launcher drops both copies of the ratio, so the route must not refuse
+ a value over the six-digit rendering it will never produce (the strip predicate and the
+ reserialized predicate are the same question)."""
+ route_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")
+ for marker in (
+ "reserialized = _resolved_layers >= 0",
+ "reserialized = _validate_resolved_layers >= 0",
+ ):
+ assert marker in route_src, marker
diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.py
index e072fd34e12..0fb10c51021 100644
--- a/studio/backend/tests/test_llama_server_args.py
+++ b/studio/backend/tests/test_llama_server_args.py
@@ -30,6 +30,7 @@ parse_gpu_layers_override = _lsa.parse_gpu_layers_override
parse_reasoning_budget_message_override = _lsa.parse_reasoning_budget_message_override
parse_reasoning_budget_override = _lsa.parse_reasoning_budget_override
parse_split_mode_override = _lsa.parse_split_mode_override
+parse_tensor_split_override = _lsa.parse_tensor_split_override
resolve_cache_type_kv = _lsa.resolve_cache_type_kv
resolve_reasoning_budget = _lsa.resolve_reasoning_budget
resolve_reasoning_budget_message = _lsa.resolve_reasoning_budget_message
@@ -593,6 +594,151 @@ def test_validate_extra_args_rejects_malformed_gpu_layers_override():
validate_extra_args(["-ngl", "abc"])
+# ── parse_tensor_split_override ──────────────────────────────────────
+
+
+ "args,expected",
+ [
+ (None, None),
+ ([], None),
+ (["--top-k", "20"], None),
+ (["--tensor-split", "2.2,1"], [2.2, 1.0]),
+ (["-ts", "3,1"], [3.0, 1.0]),
+ (["-ts", "3/1"], [3.0, 1.0]),
+ (["--tensor-split=1,1"], [1.0, 1.0]),
+ (["-ts", "1,1", "--tensor-split", "2.2,1"], [2.2, 1.0]),
+ ],
+)
+def test_parse_tensor_split_override(args, expected):
+ assert parse_tensor_split_override(args) == expected
+
+
+ "args",
+ [
+ ["--tensor-split"],
+ ["--tensor-split", "--top-k"],
+ ["--tensor-split", "abc"],
+ ["--tensor-split", "1,-1"],
+ ["--tensor-split", "0,0"],
+ ["--tensor-split", "nan,1"],
+ ["--tensor-split", "inf,1"],
+ ],
+)
+def test_parse_tensor_split_override_rejects_malformed_values(args):
+ with pytest.raises(ValueError, match = "tensor-split"):
+ parse_tensor_split_override(args)
+
+
+ "value,expected",
+ [
+ # PEP 515 grouping is float()'s, so the editor mirror must not refuse it either.
+ ("1_0,1", [10.0, 1.0]),
+ ("1_000.5,1", [1000.5, 1.0]),
+ ("1e1_0,1", [1e10, 1.0]),
+ ("1.,1", [1.0, 1.0]),
+ (".5,1", [0.5, 1.0]),
+ ("+1.5,1", [1.5, 1.0]),
+ ],
+)
+def test_parse_tensor_split_override_reads_python_float_syntax(value, expected):
+ assert parse_tensor_split_override(["-ts", value]) == expected
+
+
[email protected]("value", ["0x10,1", "0b10,1", "0o17,1", "1__0,1", "_1,1", "1_,1", "1e,1"])
+def test_parse_tensor_split_override_rejects_non_float_syntax(value):
+ # JavaScript's Number() reads the 0x/0b/0o forms, so a mirror built on it would call these
+ # loadable and the load would answer 400.
+ with pytest.raises(ValueError, match = "tensor-split"):
+ parse_tensor_split_override(["-ts", value])
+
+
+def test_parse_tensor_split_override_rejects_a_share_float32_cannot_hold():
+ # std::stof throws std::out_of_range above FLT_MAX (measured: stof("1e+39") raises), and the
+ # manual emitter would have written --tensor-split 1e+39,1, so llama-server died at startup
+ # where base had simply discarded the flag.
+ with pytest.raises(ValueError, match = "32-bit float"):
+ parse_tensor_split_override(["-ts", "1e39,1"])
+ assert parse_tensor_split_override(["-ts", "3.4e38,1"]) == [3.4e38, 1.0]
+
+
[email protected]("value", ["1e-50,1", "1e-45,1", "1e-40,1", "1e-38,1"])
+def test_parse_tensor_split_override_rejects_a_share_that_underflows_stof(value):
+ # libstdc++ reports every subnormal result as ERANGE, so std::stof throws out_of_range on the
+ # way DOWN as well: measured here, stof("1e-38") and stof("1e-45") both raise, stof("0") does
+ # not. Rejecting only what rounds to zero would still have let 1e-40 kill the server.
+ with pytest.raises(ValueError, match = "at least"):
+ parse_tensor_split_override(["-ts", value])
+
+
[email protected]("value", ["0,1", "1.2e-38,1", "1e-30,1"])
+def test_parse_tensor_split_override_keeps_what_stof_accepts(value):
+ # An exact zero share is a device the user is deliberately emptying, and everything from
+ # FLT_MIN up survives the emit round trip. 1.1754943508222874e-38 does NOT, even though it
+ # rounds up to FLT_MIN as a float: the six-significant-digit emission loses it, which
+ # test_parse_tensor_split_override_judges_the_share_it_will_emit pins.
+ assert parse_tensor_split_override(["-ts", value]) is not None
+
+
+def test_parse_tensor_split_override_only_rounds_what_gets_reserialized():
+ # Under pass-through llama-server reads the user's OWN text, and std::stof takes
+ # "1.1754943508222874e-38" (measured). Judging the six-digit rendering there would refuse a
+ # split that runs exactly as typed, so the rounding is scoped to the manual promotion that
+ # actually rewrites the ratio.
+ assert parse_tensor_split_override(["-ts", "1.1754943508222874e-38,1"]) is not None
+ with pytest.raises(ValueError, match = "at least"):
+ parse_tensor_split_override(["-ts", "1.1754943508222874e-38,1"], reserialized = True)
+
+
+def test_parse_tensor_split_override_rounds_each_share_before_adding():
+ # llama.cpp does `sum += std::stof(token)`, so each share is a float BEFORE it joins the
+ # total. Compiled and run here, "3.17817e38,1.54601e37,7.00525e36" reaches inf that way while
+ # accumulating the doubles and rounding afterwards lands on FLT_MAX and looked fine.
+ for reserialized in (False, True):
+ with pytest.raises(ValueError, match = "adds up past"):
+ parse_tensor_split_override(
+ ["-ts", "3.17817e38,1.54601e37,7.00525e36"], reserialized = reserialized
+ )
+
+
+def test_parse_tensor_split_override_judges_the_share_it_will_emit():
+ # The manual launcher writes f"{x:g}", six significant digits. 1.1754943508222874e-38 rounds
+ # UP to FLT_MIN as a float and so passed a full-precision check, but it is emitted as
+ # "1.17549e-38" and std::stof refuses THAT as subnormal (measured on this host), so /validate
+ # approved a command the server then died on.
+ with pytest.raises(ValueError, match = "at least"):
+ parse_tensor_split_override(["-ts", "1.1754943508222874e-38,1"], reserialized = True)
+ assert parse_tensor_split_override(["-ts", "1.2e-38,1"], reserialized = True) == [1.2e-38, 1.0]
+
+
+def test_parse_tensor_split_override_totals_the_emitted_shares():
+ # llama.cpp prefix-sums what it PARSED, so the total is accumulated over the emitted values.
+ # Summing the raw doubles instead refused this split, while a real float32 accumulation of
+ # the emitted text ("2.08296e+38,7.17058e+37,6.02804e+37") reaches 3.40282e+38 and fits.
+ assert (
+ parse_tensor_split_override(
+ ["-ts", "2.0829609943909916e38,7.170581961838338e37,6.028042758104631e37"],
+ reserialized = True,
+ )
+ is not None
+ )
+ with pytest.raises(ValueError, match = "adds up past"):
+ parse_tensor_split_override(["-ts", "3e38,3e38"])
+
+
+def test_parse_tensor_split_override_rejects_a_total_float32_cannot_hold():
+ # llama.cpp prefix-sums the shares into the same float array (llama-model.cpp).
+ with pytest.raises(ValueError, match = "adds up past"):
+ parse_tensor_split_override(["-ts", "3e38,3e38"])
+
+
+def test_validate_extra_args_rejects_malformed_tensor_split_override():
+ with pytest.raises(ValueError, match = "tensor-split"):
+ validate_extra_args(["-ts", "abc"])
+
+
# ── reasoning budget first-class shadows ─────────────────────────────
diff --git a/studio/backend/tests/test_validate_diffusion_extra_args.py b/studio/backend/tests/test_validate_diffusion_extra_args.py
index 59185461280..bb21bca8c7f 100644
--- a/studio/backend/tests/test_validate_diffusion_extra_args.py
+++ b/studio/backend/tests/test_validate_diffusion_extra_args.py
@@ -268,6 +268,82 @@ class TestValidateTranslatesManualNgl(unittest.TestCase):
self.assertEqual(seen, [(request.gpu_layers, ["-ngl", "20"])])
+class TestValidateTranslatesManualTensorSplit(unittest.TestCase):
+ """Manual GPU memory strips ``-ts`` / ``--tensor-split`` because the first-class
+ ``tensor_split`` field owns it. /validate must promote the extras value first,
+ the same way it promotes ``-ngl``, or it judges a near-even default while /load
+ would have emitted the asymmetric MoE split (#11330)."""
+
+ def _validate(
+ self,
+ route,
+ *,
+ gpu_layers,
+ extra_args,
+ tensor_split = None,
+ ):
+ seen: list = []
+
+ def _capture(_config, request, **kwargs):
+ seen.append(
+ (
+ request.gpu_layers,
+ request.tensor_split,
+ kwargs.get("llama_extra_args"),
+ )
+ )
+
+ request = ValidateModelRequest(
+ model_path = "someone/moe-gguf",
+ llama_extra_args = extra_args,
+ gpu_memory_mode = "manual",
+ gpu_layers = gpu_layers,
+ tensor_split = tensor_split,
+ )
+ config = SimpleNamespace(
+ identifier = "someone/moe-gguf",
+ display_name = "moe-gguf",
+ is_gguf = True,
+ is_lora = False,
+ is_vision = False,
+ gguf_file = None,
+ )
+ with (
+ patch.object(
+ route,
+ "_resolve_model_identifier_for_request",
+ return_value = ("someone/moe-gguf", "someone/moe-gguf", False),
+ ),
+ patch.object(route.ModelConfig, "from_identifier", return_value = config),
+ patch.object(route, "_resolve_inherited_extra_args", return_value = list(extra_args)),
+ patch.object(route, "_classify_diffusion_gguf", return_value = False),
+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),
+ patch.object(route, "_effective_load_in_4bit", return_value = True),
+ patch.object(route, "_guard_chat_load_against_training", new = _capture),
+ ):
+ asyncio.run(route.validate_model(request, current_subject = "test-user"))
+ return seen
+
+ def test_an_explicit_tensor_split_reaches_the_guard(self):
+ route = _load_route_module("inf_route_manual_ts_1")
+ seen = self._validate(
+ route,
+ gpu_layers = 49,
+ extra_args = ["-ts", "2.2,1", "-sm", "layer"],
+ )
+ self.assertEqual(seen, [(49, [2.2, 1.0], ["-sm", "layer"])])
+
+ def test_extras_override_a_first_class_tensor_split(self):
+ route = _load_route_module("inf_route_manual_ts_2")
+ seen = self._validate(
+ route,
+ gpu_layers = 49,
+ tensor_split = [1, 1],
+ extra_args = ["--tensor-split", "3,1"],
+ )
+ self.assertEqual(seen, [(49, [3.0, 1.0], [])])
+
+
if __name__ == "__main__":
unittest.main()
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 dba4f660c45..83516481539 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
@@ -1766,6 +1766,9 @@ function ExtraArgsRow({
const diagnostics = diagnoseExtraArgs(text, catalog, {
gpuSelectionActive: config.selectedGpuIds != null,
manualGpuMemory: config.gpuMemoryMode === "manual",
+ // Only manual mode with a resolved layer count of 0 or more rewrites --tensor-split; at Auto
+ // layers the launcher drops it, so the value never reaches llama-server.
+ gpuLayers: config.gpuLayers,
// The same floor the batch control shows: with Slots blank the count is the server default
// this page cannot see, so only the hard 2 holds. A build that clamps serves one slot
// whatever is chosen, so an explicit Slots value must not raise the floor.
diff --git a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
index a1b99b3c2ac..2c1d755b2e4 100644
--- a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
+++ b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
@@ -248,6 +248,9 @@ function dropUnusableValues(tokens: readonly string[]): string[] {
const minimum = INTEGER_VALUE_MINIMUM[flag];
const unusable =
missing ||
+ // false: a STORED list, whose mode is unknown, so only what NO mode can run is dropped.
+ (RATIO_VALUE_FLAGS.has(flag) &&
+ ratioValueProblem(flag, value, false) !== null) ||
(INTEGER_VALUE_FLAGS.has(flag) &&
(!INTEGER.test(value.trim()) ||
(minimum !== undefined && Number(value.trim()) < minimum)));
@@ -653,8 +656,120 @@ const VALUE_REQUIRED_FLAGS = new Set([
"--spec-draft-type-v",
"-ctvd",
"--cache-type-v-draft",
+ // read with _last_flag_value, so a bare -ts is a 400, not a flag left to llama-server
+ "--tensor-split",
+ "-ts",
]);
+/** The spellings the GPU Layers control also emits. */
+const GPU_LAYERS_FLAGS = new Set(["--gpu-layers", "--n-gpu-layers", "-ngl"]);
+
+/** The last-wins integer value for `flags` in `tokens`, or null. Mirrors parse_gpu_layers_override
+ * only as far as the one question asked here: is the resolved layer count non-negative. */
+function lastIntegerFlagValue(
+ tokens: readonly string[],
+ flags: ReadonlySet<string>,
+): number | null {
+ let found: number | null = null;
+ for (const [index, token] of tokens.entries()) {
+ const flag = extraArgFlagName(token);
+ if (flag === null || !flags.has(flag)) {
+ continue;
+ }
+ const attached = valueIsAttached(token, flag);
+ const raw = attached ? token.split("=")[1] : tokens[index + 1];
+ if (raw !== undefined && INTEGER.test(raw.trim())) {
+ found = Number(raw.trim());
+ }
+ }
+ return found;
+}
+
+/** Flags whose value the backend reads as a per-GPU ratio, refusing unreadable, negative or
+ * non-finite entries and a zero total with a 400 (parse_tensor_split_override). */
+const RATIO_VALUE_FLAGS = new Set(["--tensor-split", "-ts"]);
+
+/** llama.cpp splits --tensor-split on this exact class, so "3/1" is "3,1". */
+const RATIO_DELIMITER = /[,/]+/;
+
+/** The spellings Python's float() accepts and math.isfinite() then rejects. */
+const NON_FINITE = /^[+-]?(nan|inf(inity)?)$/i;
+
+/** Python's `floatvalue` production (docs: functions#float), which is NOT what Number() takes:
+ * Number() reads 0x/0b/0o literals the backend refuses, and refuses the `1_0` digit grouping
+ * PEP 515 made valid, so a Number()-based mirror disagrees with /validate in both directions. */
+const PY_FLOAT =
+ /^[+-]?(?:(?:\d(?:_?\d)*)?\.\d(?:_?\d)*|\d(?:_?\d)*\.?)(?:[eE][+-]?\d(?:_?\d)*)?$/;
+
+/** Largest per-GPU share llama.cpp's float array holds; std::stof throws out_of_range above it. */
+const FLOAT32_MAX = 3.4028234663852886e38;
+
+/** FLT_MIN. libstdc++ reports every SUBNORMAL result as ERANGE too, so std::stof refuses a share
+ * below this just as it refuses one above FLOAT32_MAX; exactly 0 is fine. */
+const FLOAT32_MIN_NORMAL = 1.1754943508222875e-38;
+
+/** `value` rounded to float32, so the check follows the rounding std::stof does, not the literal. */
+const toFloat32 = (value: number): number => Math.fround(value);
+
+/** `value` as the manual launcher will WRITE it: Python's `f"{x:g}"`, six significant digits.
+ * A share validated at full precision can lose its range in that round trip, so both sides judge
+ * the text the child actually parses. */
+const asEmitted = (value: number): number => Number(value.toPrecision(6));
+
+/** The three ways parse_tensor_split_override refuses a ratio, or null when it would take it. */
+function ratioValueProblem(
+ flag: string,
+ value: string,
+ reserialized: boolean,
+): string | null {
+ const parts = value
+ .split(RATIO_DELIMITER)
+ .filter((part) => part.trim() !== "");
+ if (parts.length === 0) {
+ return `${flag} takes a comma- or slash-separated list of numbers.`;
+ }
+ const trimmed = parts.map((part) => part.trim());
+ // Readability is decided by Python's grammar, never by Number(): "nan"/"inf" are readable and
+ // fail the finite test below, while 0x10 is unreadable to float() even though Number() takes it.
+ if (trimmed.some((part) => !PY_FLOAT.test(part) && !NON_FINITE.test(part))) {
+ return `${flag} takes a comma- or slash-separated list of numbers, and "${value}" is not one.`;
+ }
+ // Underscores are grouping to float() and NaN to Number(), so strip them before converting.
+ const numbers = trimmed.map((part) => Number(part.replace(/_/g, "")));
+ if (numbers.some((entry) => !Number.isFinite(entry) || entry < 0)) {
+ return `${flag} entries must be finite and non-negative.`;
+ }
+ if (numbers.reduce((total, entry) => total + entry, 0) <= 0) {
+ return `${flag} must have a positive total.`;
+ }
+ // Which text llama-server will parse: the user's own under pass-through, the launcher's
+ // six-digit rendering once manual mode promotes and rewrites the ratio. Rounding a
+ // pass-through value here would refuse input that runs exactly as typed.
+ const shares = numbers.map((entry) =>
+ toFloat32(reserialized ? asEmitted(entry) : entry),
+ );
+ if (shares.some((share) => !Number.isFinite(share))) {
+ return `${flag} entries must fit in a 32-bit float (at most ${FLOAT32_MAX.toExponential(4)}).`;
+ }
+ if (
+ shares.some(
+ (share, at) => numbers[at] !== 0 && share < FLOAT32_MIN_NORMAL,
+ )
+ ) {
+ return `${flag} entries must be 0 or at least ${FLOAT32_MIN_NORMAL.toExponential(4)}.`;
+ }
+ // Accumulated the way llama.cpp prefix-sums the shares it parsed, in float32 and step by step.
+ // A single float64 reduction disagrees with that near the top of the range.
+ let running = 0;
+ for (const share of shares) {
+ running = toFloat32(running + share);
+ if (!Number.isFinite(running)) {
+ return `${flag} adds up past the 32-bit float range.`;
+ }
+ }
+ return null;
+}
+
/** The pass-through spellings of the batch size the floor above applies to. */
const BATCH_SIZE_FLAGS = new Set(["--batch-size", "-b"]);
@@ -700,6 +815,9 @@ export type ExtraArgsContext = {
gpuSelectionActive?: boolean;
/** GPU Memory is Manual, which removes the offload flags its controls own. */
manualGpuMemory?: boolean;
+ /** The control's GPU Layers value. Only manual mode with a RESOLVED count of 0 or more rewrites
+ * --tensor-split; at Auto layers the flag is dropped, so it never reaches llama-server. */
+ gpuLayers?: number;
/** Smallest --batch-size this launch can run, max(slots, 2). */
batchFloor?: number;
/** Model Memory keeps the weights resident, which owns the load mode. */
@@ -723,6 +841,11 @@ export function diagnoseExtraArgs(
const noRamReserve = context.noRamReserve ?? false;
const out: ExtraArgsDiagnostic[] = [];
const { tokens, unterminatedQuote, quotedIndices } = parseExtraArgs(input);
+ // Mirrors _should_strip_tensor_split: an -ngl in the extras is promoted first, so the count
+ // that decides is the RESOLVED one, not the control's.
+ const nglOverride = lastIntegerFlagValue(tokens, GPU_LAYERS_FLAGS);
+ const resolvedGpuLayers = nglOverride ?? context.gpuLayers ?? -1;
+ const reserializesSplit = manualGpuMemory && resolvedGpuLayers >= 0;
// Tokens the walk below consumed as somebody's value. A quoted token in value POSITION is a value
// whatever it starts with, since llama.cpp takes the next argv element without looking.
// Position matters as much as the quotes: a user quoting out of habit still wrote a flag.
@@ -883,6 +1006,8 @@ export function diagnoseExtraArgs(
message = numeric
? `${flag} needs a number after it.`
: `${flag} needs a value after it.`;
+ } else if (RATIO_VALUE_FLAGS.has(flag)) {
+ message = ratioValueProblem(flag, value, reserializesSplit);
} else if (!numeric) {
message = null;
} else if (!INTEGER.test(value.trim())) {
diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
index 915258c517e..543134ec17d 100644
--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
@@ -1377,3 +1377,168 @@ test("a managed answer from the previous binary is never published", () => {
/if \(generation === catalogGeneration\) \{ inFlightManaged = null; \}/,
);
});
+
+// validate_extra_args parses -ts in EVERY gpu memory mode, so each case below is a 400 on
+// Load, on /validate and on saving an override; without the mirror the user sees only that
+// server error, with nothing inline first (#11330).
+
+const _tsError = (input: string): string | null =>
+ diagnoseExtraArgs(input, CATALOG).find((d) => d.level === "error")?.message ??
+ null;
+
+test("a tensor split the backend takes raises nothing here", () => {
+ for (const good of [
+ "-ts 2.2,1",
+ "--tensor-split 3,1",
+ // llama.cpp splits on [,/]+, so the slash form is the same instruction.
+ "--tensor-split 3/1",
+ "-ts 0,1",
+ "-ts 0.75,0.25",
+ ]) {
+ assert.equal(_tsError(good), null, good);
+ assert.ok(extraArgsAreLoadable(diagnoseExtraArgs(good, CATALOG)), good);
+ }
+});
+
+test("a bare tensor split is refused rather than left to llama-server", () => {
+ // _last_flag_value raises on a missing value, unlike an ordinary flag whose arity
+ // this side does not know.
+ assert.equal(_tsError("-ts"), "-ts needs a value after it.");
+ assert.equal(_tsError("-ts --top-k 20"), "-ts needs a value after it.");
+});
+
+test("a tensor split that is not a list of numbers is refused", () => {
+ // std::stof throws on this, so llama-server would exit at startup: better a 400,
+ // and better still an inline error.
+ assert.match(_tsError("-ts abc") ?? "", /comma- or slash-separated list of numbers/);
+});
+
+test("a negative or non-finite share is refused", () => {
+ for (const bad of ["-ts 1,-1", "--tensor-split nan,1", "--tensor-split inf,1"]) {
+ assert.equal(
+ _tsError(bad),
+ `${bad.split(" ")[0]} entries must be finite and non-negative.`,
+ bad,
+ );
+ }
+});
+
+test("a split that totals nothing is refused", () => {
+ // llama.cpp normalizes by the total, so an all-zero list divides by zero.
+ assert.match(_tsError("-ts 0,0") ?? "", /must have a positive total/);
+});
+
+test("every tensor split occurrence is judged, not only the last", () => {
+ // Same rule the value check already applies to -ngl: llama.cpp reads the LAST
+ // occurrence, so a bad second one must be caught; this side then errs on the strict
+ // side and reports a bad FIRST one too, rather than modelling last-wins and leaving
+ // a typo invisible.
+ assert.match(_tsError("-ts 3,1 -ts abc") ?? "", /list of numbers/);
+ assert.match(_tsError("-ts abc --tensor-split 3,1") ?? "", /list of numbers/);
+});
+
+test("a stored tensor split the backend now refuses is repaired, not shed", () => {
+ // drop_managed_flags would drop everything from the bad flag to the end of the
+ // list; removing just the option and its value keeps the rest working.
+ assert.deepEqual(
+ sanitizeStoredExtraArgs(["-ts", "abc", "--top-k", "20"], CATALOG.managed),
+ ["--top-k", "20"],
+ );
+ assert.deepEqual(
+ sanitizeStoredExtraArgs(["-ts", "2.2,1", "--top-k", "20"], CATALOG.managed),
+ ["-ts", "2.2,1", "--top-k", "20"],
+ );
+});
+
+test("the ratio mirror reads exactly what Python's float() reads", () => {
+ // Number() takes 0x/0b/0o literals float() refuses, and refuses the digit grouping PEP 515
+ // made valid, so a Number()-based check disagreed with /validate in BOTH directions.
+ for (const bad of ["0x10,1", "0b10,1", "0o17,1", "1__0,1", "_1,1", "1_,1", "1e,1"]) {
+ assert.match(_tsError(`-ts ${bad}`) ?? "", /list of numbers/, bad);
+ }
+ for (const good of ["1_0,1", "1_000.5,1", "1.,1", ".5,1", "1e1_0,1", "+1.5,1"]) {
+ assert.equal(_tsError(`-ts ${good}`), null, good);
+ }
+});
+
+test("a share llama.cpp's float array cannot hold is refused", () => {
+ // std::stof throws std::out_of_range above FLT_MAX (verified: stof("1e+39") -> out_of_range),
+ // so without this the load reaches llama-server and the server dies during startup.
+ assert.match(_tsError("-ts 1e39,1") ?? "", /32-bit float/);
+ assert.equal(_tsError("-ts 3.4e38,1"), null);
+ // The shares are prefix-summed into that same float array.
+ assert.match(_tsError("-ts 3e38,3e38") ?? "", /adds up past/);
+});
+
+test("a share that underflows std::stof is refused too", () => {
+ // libstdc++ throws out_of_range on any subnormal result, not only on a value that rounds to
+ // zero, so the floor is FLT_MIN and not the smallest denormal.
+ for (const bad of ["1e-50,1", "1e-45,1", "1e-40,1", "1e-38,1"]) {
+ assert.match(_tsError(`-ts ${bad}`) ?? "", /0 or at least/, bad);
+ }
+ // 1.1754943508222874e-38 is NOT here: it rounds up to FLT_MIN as a float but is emitted at
+ // six significant digits as a subnormal, which the next test pins.
+ for (const good of ["0,1", "1.2e-38,1", "1e-30,1"]) {
+ assert.equal(_tsError(`-ts ${good}`), null, good);
+ }
+});
+
+test("the mirror judges the share the launcher will write, and totals it in float32", () => {
+ // Both halves of the round-3 review: six-significant-digit emission can move a value out of
+ // range after validation, and a single float64 reduction disagrees with llama.cpp's stepwise
+ // float32 prefix sum near the top of the range.
+ // gpuLayers: 49, because only a manual load with a resolved count of 0 or more rewrites the
+ // ratio, and the rewritten text is what these cases are about.
+ const manual = (input: string) =>
+ diagnoseExtraArgs(input, CATALOG, {
+ manualGpuMemory: true,
+ gpuLayers: 49,
+ }).find((d) => d.level === "error")?.message ?? null;
+ assert.match(manual("-ts 1.1754943508222874e-38,1") ?? "", /0 or at least/);
+ assert.equal(manual("-ts 1.2e-38,1"), null);
+ // Real libstdc++ sums the emitted text to 3.40282e+38, which fits, so this must NOT be refused.
+ assert.equal(
+ manual("-ts 2.0829609943909916e38,7.170581961838338e37,6.028042758104631e37"),
+ null,
+ );
+ assert.match(manual("-ts 3e38,3e38") ?? "", /adds up past/);
+});
+
+test("the ratio rounding follows the mode, and each share rounds before it is added", () => {
+ const err = (input: string, manualGpuMemory: boolean) =>
+ diagnoseExtraArgs(input, CATALOG, { manualGpuMemory, gpuLayers: 49 }).find(
+ (d) => d.level === "error",
+ )?.message ?? null;
+ // Pass-through hands llama-server the user's own text, which std::stof accepts; only the
+ // manual promotion rewrites it at six significant digits.
+ assert.equal(err("-ts 1.1754943508222874e-38,1", false), null);
+ assert.match(err("-ts 1.1754943508222874e-38,1", true) ?? "", /0 or at least/);
+ // Each share is a float before it joins the total, as `sum += std::stof(token)` does.
+ for (const manual of [false, true]) {
+ assert.match(
+ err("-ts 3.17817e38,1.54601e37,7.00525e36", manual) ?? "",
+ /adds up past/,
+ );
+ }
+});
+
+test("only a manual load that will rewrite the split judges the rewritten text", () => {
+ // At Auto layers the launcher drops both copies rather than reserializing either, so the
+ // six-digit rendering is never produced and refusing it would 400 a flag with no effect.
+ const at = (input: string, ctx: object) =>
+ diagnoseExtraArgs(input, CATALOG, ctx).find((d) => d.level === "error")
+ ?.message ?? null;
+ const v = "-ts 1.1754943508222874e-38,1";
+ assert.match(at(v, { manualGpuMemory: true, gpuLayers: 49 }) ?? "", /0 or at least/);
+ assert.equal(at(v, { manualGpuMemory: true, gpuLayers: -1 }), null);
+ assert.equal(at(v, { manualGpuMemory: false, gpuLayers: 49 }), null);
+ // The RESOLVED count decides, so an -ngl in the extras wins over the control either way.
+ assert.equal(
+ at(`-ngl -1 ${v}`, { manualGpuMemory: true, gpuLayers: 49 }),
+ null,
+ );
+ assert.match(
+ at(`-ngl 49 ${v}`, { manualGpuMemory: true, gpuLayers: -1 }) ?? "",
+ /0 or at least/,
+ );
+});