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: expose llama-server batch and micro-batch sizes as first-class load settings (#7973)

Maheswar Kumar968134ab62c6
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 71e8209c19a..2a4e1a7ecb3 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -158,6 +158,9 @@ class GgufLoadIntent:
gpu_ids_are_vulkan_ordinals: Optional[bool] = None
n_threads: Optional[int] = None
n_parallel: int = 1
+ # none follows the llama.cpp defaults (2048 / 512)
+ n_batch: Optional[int] = None
+ n_ubatch: Optional[int] = None
extra_args: Optional[tuple[str, ...]] = None
# The route materialises inherited extras from the live server, so the list alone
# cannot say whether the caller named it. Duplicate-load checks need the difference:
@@ -2653,12 +2656,54 @@ def _extra_args_draft_device_pin(extra_args: Optional[Iterable[str]]) -> Optiona
return last_dev
+def _emitted_n_batch(n_batch: Optional[int], n_parallel: int) -> Optional[int]:
+ """--batch-size the launch actually emits for a requested ``n_batch``.
+
+ llama-server aborts below 2 and below the slot count, so the loader raises the
+ flag to ``max(slots, 2)``. llama.cpp then derives the micro-batch from the
+ raised value (``cparams.n_ubatch = min(cparams.n_batch, n_ubatch or n_batch)``),
+ so every VRAM budget must be sized from it, not from the requested number, or a
+ small batch with many slots is budgeted at a micro-batch the launch never uses.
+ None (llama.cpp defaults) stays None: nothing is emitted, so nothing is raised.
+ """
+ if n_batch is None:
+ return None
+ return max(int(n_batch), max(2, int(n_parallel or 1)))
+
+
+def _repatch_parallel_slots(argv: list[str], n_parallel: int, n_batch: Optional[int]) -> bool:
+ """Point ``--parallel`` at ``n_parallel``, re-raising ``--batch-size`` to match.
+
+ The batch flag is emitted from the slot count as it stood then, so a later
+ restore that hands slots back would leave the batch under the new floor and
+ abort the very fallback the restore exists to make work. Returns whether
+ ``--parallel`` was found (callers rebind their own n_parallel on that).
+ """
+ try:
+ _at = argv.index("--parallel")
+ except ValueError:
+ return False
+ argv[_at + 1] = str(n_parallel)
+ _batch = _emitted_n_batch(n_batch, n_parallel)
+ if _batch is not None and "--batch-size" in argv:
+ argv[argv.index("--batch-size") + 1] = str(_batch)
+ return True
+
+
def _extra_args_n_ubatch(
extra_args: Optional[Iterable[str]],
env: Optional[Mapping[str, str]] = None,
n_ctx: Optional[int] = None,
+ *,
+ n_batch: Optional[int] = None,
+ n_ubatch: Optional[int] = None,
) -> Optional[int]:
- """Effective ubatch after llama.cpp normalizes it, or None at defaults."""
+ """Effective ubatch after llama.cpp normalizes it, or None at defaults.
+
+ Precedence mirrors the launched command line: env, then the first-class
+ n_batch / n_ubatch fields (emitted as flags, so they beat env), then user
+ extra_args (appended last, so they last-wins-override the emitted flags).
+ """
values = {
"batch": _DEFAULT_LLAMA_N_BATCH,
"ubatch": _DEFAULT_LLAMA_N_UBATCH,
@@ -2677,6 +2722,13 @@ def _extra_args_n_ubatch(
except (TypeError, ValueError):
pass
+ if n_batch is not None:
+ values["batch"] = int(n_batch)
+ overridden = True
+ if n_ubatch is not None:
+ values["ubatch"] = int(n_ubatch)
+ overridden = True
+
args = [str(a) for a in extra_args] if extra_args else []
flags = {
"-b": "batch",
@@ -2977,6 +3029,9 @@ class LlamaCppBackend:
self._effective_parallel_slots: int = 1
# --parallel the last load asked for, before any fit-time reduction.
self._requested_n_parallel: int = 1
+ # --batch-size / --ubatch-size the last load asked for; none = defaults or extras / env
+ self._requested_n_batch: Optional[int] = None
+ self._requested_n_ubatch: Optional[int] = None
self._chat_template: Optional[str] = None
self._markup_tokens: list = []
self._markup_profile = None
@@ -3251,6 +3306,16 @@ class LlamaCppBackend:
slots = 1
return max(1, slots)
+ @property
+ def requested_n_batch(self) -> Optional[int]:
+ """--batch-size the last load asked for; None means llama.cpp default."""
+ return self._requested_n_batch
+
+ @property
+ def requested_n_ubatch(self) -> Optional[int]:
+ """--ubatch-size the last load asked for; None means llama.cpp default."""
+ return self._requested_n_ubatch
+
@property
def max_context_length(self) -> Optional[int]:
"""Return the largest context that fits on this hardware at load time.
@@ -3278,6 +3343,8 @@ class LlamaCppBackend:
self._effective_parallel_slots = 1
# Cleared with the effective count so a stale value can't skew the dedupe.
self._requested_n_parallel = 1
+ self._requested_n_batch = None
+ self._requested_n_ubatch = None
@staticmethod
def _read_rss_bytes(pid: int) -> Optional[int]:
@@ -3633,6 +3700,10 @@ class LlamaCppBackend:
return False
if not self._is_diffusion and self._requested_n_parallel != max(1, int(intent.n_parallel)):
return False
+ if not self._is_diffusion and (
+ self._requested_n_batch != intent.n_batch or self._requested_n_ubatch != intent.n_ubatch
+ ):
+ return False
def _norm(value):
if value is None:
@@ -6017,6 +6088,7 @@ class LlamaCppBackend:
kv_unified: bool = True,
flash_attn: bool = True,
split_extra_bytes: int = 0,
+ ubatch_for_slots: Optional[Callable[[int], Optional[int]]] = None,
) -> tuple[Optional[list[int]], bool, int]:
"""Largest serving-slot count in [1, n_parallel) whose fully-on-GPU footprint fits,
so Unsloth keeps the model on GPU (-ngl -1) instead of --fit on, which offloads layers
@@ -6026,10 +6098,16 @@ class LlamaCppBackend:
and KV, then re-selects GPUs like the explicit-context path -- ``split_extra_bytes``
included, so a multi-GPU candidate is re-checked at the split rate. Returns
(gpu_indices, use_fit=False, slots) for the largest fitting count, else (None, True,
- n_parallel). Only ever reduces; unit-testable with synthetic VRAM maps."""
+ n_parallel). Only ever reduces; unit-testable with synthetic VRAM maps.
+ ``ubatch_for_slots`` re-derives the micro-batch per candidate: the emitted
+ --batch-size is raised to max(slots, 2), and llama.cpp caps the micro-batch
+ against it, so a batch below the requested slot count shrinks as the candidates
+ do. Holding it at the requested count made a fitting candidate look too big and
+ dropped the load to --fit offload."""
for slots in range(n_parallel - 1, 0, -1):
+ _ub = ubatch_for_slots(slots) if ubatch_for_slots else n_ubatch
cb = self._estimate_compute_buffer_bytes(
- n_ubatch = n_ubatch, n_parallel = slots, per_device_tensor = False
+ n_ubatch = _ub, n_parallel = slots, per_device_tensor = False
)
if cb <= 0:
cb = self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024
@@ -6042,7 +6120,7 @@ class LlamaCppBackend:
n_parallel = slots,
swa_full = swa_full,
kv_unified = kv_unified,
- n_ubatch = n_ubatch,
+ n_ubatch = _ub,
flash_attn = flash_attn,
)
)
@@ -6873,6 +6951,8 @@ class LlamaCppBackend:
self._swa_full = False
self._kv_cache_unified = False
self._n_ubatch = self._DEFAULT_N_UBATCH
+ self._requested_n_batch = None
+ self._requested_n_ubatch = None
self._flash_attn_enabled = True
self._effective_cache_types = ("f16", "f16")
self._kv_cache_context_total = None
@@ -8429,6 +8509,8 @@ class LlamaCppBackend:
gpu_ids_are_vulkan_ordinals = intent.gpu_ids_are_vulkan_ordinals
n_threads = intent.n_threads
n_parallel = intent.n_parallel
+ n_batch = intent.n_batch
+ n_ubatch = intent.n_ubatch
extra_args = list(intent.extra_args) if intent.extra_args is not None else None
preserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer
# Serialise the whole load so concurrent /load calls never leave two
@@ -8847,10 +8929,21 @@ class LlamaCppBackend:
ctx_override = parse_ctx_override(extra_args)
requested_ctx = resolve_requested_ctx(extra_args, n_ctx)
swa_full = _swa_full_from_args_or_env(extra_args)
- _effective_ubatch = _extra_args_n_ubatch(
- extra_args,
- n_ctx = (requested_ctx if requested_ctx > 0 else self._context_length),
- )
+
+ # The emitted batch, not the requested one: the floor raise below is what
+ # llama.cpp caps the micro-batch against, so the fit, the slot search and
+ # every compute-buffer reserve must be sized from the value that launches.
+ # Slot-dependent, since the floor is max(slots, 2): the slot search below
+ # reduces the count, and each candidate launches at its own batch.
+ def _ubatch_for_slots(slots: int) -> Optional[int]:
+ return _extra_args_n_ubatch(
+ extra_args,
+ n_ctx = (requested_ctx if requested_ctx > 0 else self._context_length),
+ n_batch = _emitted_n_batch(n_batch, slots),
+ n_ubatch = n_ubatch,
+ )
+
+ _effective_ubatch = _ubatch_for_slots(n_parallel)
planned_kv_unified = _kv_unified_from_args(
extra_args,
default = n_parallel > 1 and server_caps.get("supports_kv_unified", False),
@@ -9956,6 +10049,7 @@ class LlamaCppBackend:
kv_unified = planned_kv_unified,
flash_attn = planned_flash_attn,
split_extra_bytes = _cc_split_extra(effective_ctx),
+ ubatch_for_slots = _ubatch_for_slots,
)
if not _uf_slots:
logger.info(
@@ -9966,6 +10060,10 @@ class LlamaCppBackend:
effective_ctx,
)
gpu_indices, use_fit, n_parallel = _gi_slots, False, _slots
+ # Fewer slots means a lower batch floor, so the launch runs a
+ # smaller micro-batch than the one this was sized at. Re-derive
+ # it, or the recorded _n_ubatch describes a graph never built.
+ _effective_ubatch = _ubatch_for_slots(n_parallel)
# MTP reserve at the final context, for the logs below.
_mtp_reserve_bytes = _mtp_bytes(effective_ctx) if _mtp_will_engage else 0
@@ -10103,6 +10201,29 @@ class LlamaCppBackend:
elif not auto_fit:
cmd.extend(["-c", "0"])
+ # emitted before user extras so a pass-through -b / -ub still last-wins-overrides
+ if n_batch is not None:
+ # Two separate aborts, both reachable from the picker since the input
+ # clamps into BATCH_MIN = 1 rather than rejecting:
+ # -b < --parallel -> GGML_ASSERT(n_outputs_max <= cparams.n_outputs_max)
+ # -b 1 (any slots) -> GGML_ASSERT(n_tokens_all <= cparams.n_batch)
+ # Measured: b1/p1 and b1/p2 abort, b2/p1 and b2/p2 load, b4/p8 aborts,
+ # b8/p8 loads. So the floor is max(slots, 2), not slots alone. The
+ # bounds are per-field and cannot express it, so raise here instead of
+ # failing the load.
+ _emit_batch = _emitted_n_batch(n_batch, n_parallel)
+ if _emit_batch != n_batch:
+ logger.warning(
+ "Raising --batch-size from %s to %s: llama-server aborts below "
+ "2 and below the %s parallel slot(s) it serves.",
+ n_batch,
+ _emit_batch,
+ n_parallel,
+ )
+ cmd.extend(["--batch-size", str(_emit_batch)])
+ if n_ubatch is not None:
+ cmd.extend(["--ubatch-size", str(n_ubatch)])
+
server_caps = self.probe_server_capabilities(binary)
# Report a clean public model id (matching GET /v1/models) rather
@@ -10384,8 +10505,7 @@ class LlamaCppBackend:
extra_args, env = _child_spec_env(extra_args)
):
n_parallel = _pv_extras_clamped_slots
- if "--parallel" in cmd:
- cmd[cmd.index("--parallel") + 1] = str(n_parallel)
+ _repatch_parallel_slots(cmd, n_parallel, n_batch)
logger.info(
"Restoring %d parallel slots: the drafter drop left a "
"non-MTP server.",
@@ -10483,18 +10603,19 @@ class LlamaCppBackend:
and not _extra_args_set_spec_type(extra_args)
and _extra_args_requests_mtp(spec_flags, env = _child_spec_env(extra_args))
):
- try:
- _np_at = cmd.index("--parallel")
- except ValueError:
- _np_at = -1
- if _np_at >= 0:
+ if "--parallel" in cmd:
logger.warning(
"%s resolved to MTP speculative decoding, which does not "
"support %d parallel slots; using 1.",
model_identifier,
n_parallel,
)
- cmd[_np_at + 1] = "1"
+ # Through the same helper as the restores: the floor is meant to
+ # be the smallest legal batch, so dropping to one slot must undo
+ # a raise the old count forced. Leaving it launched -b 64 for a
+ # requested -b 1 and made the recorded micro-batch, derived from
+ # the clamped count, describe a graph 32x smaller than the child's.
+ _repatch_parallel_slots(cmd, 1, n_batch)
# _commit_effective_parallel_slots reports what launched, so
# rebind rather than only patching cmd.
_mtp_clamped_slots = n_parallel
@@ -11208,8 +11329,9 @@ class LlamaCppBackend:
# silently serves one chat at a time (and the requested-vs-requested
# dedupe makes that stick). Later retries derive from this argv, so
# rebind n_parallel now.
- if _mtp_clamped_slots > 1 and "--parallel" in fallback_cmd:
- fallback_cmd[fallback_cmd.index("--parallel") + 1] = str(_mtp_clamped_slots)
+ if _mtp_clamped_slots > 1 and _repatch_parallel_slots(
+ fallback_cmd, _mtp_clamped_slots, n_batch
+ ):
n_parallel = _mtp_clamped_slots
healthy = _spawn_and_wait(fallback_cmd, label = "-retry")
if healthy:
@@ -11315,9 +11437,16 @@ class LlamaCppBackend:
self._commit_effective_parallel_slots(n_parallel)
self._swa_full = swa_full
self._kv_cache_unified = kv_cache_unified
+ # Re-derived from the slot count that LAUNCHED, not the one the sizing
+ # pass saw. The drafter drop and the non-MTP retry both hand slots back
+ # after the batch flag is emitted, and this is recorded next to
+ # _commit_effective_parallel_slots: pairing those slots with a micro-batch
+ # derived at the clamped count under-states the cache the slot save
+ # re-estimates from it.
+ _launched_ubatch = _ubatch_for_slots(n_parallel)
self._n_ubatch = max(
0,
- int(self._DEFAULT_N_UBATCH if _effective_ubatch is None else _effective_ubatch),
+ int(self._DEFAULT_N_UBATCH if _launched_ubatch is None else _launched_ubatch),
)
self._flash_attn_enabled = (
_flash_attn_enabled_from_args(_last_spawn_cmd, env = env)
@@ -11369,6 +11498,8 @@ class LlamaCppBackend:
self._requested_n_ctx = int(n_ctx)
# Local n_parallel may have been reduced above; the snapshot has the ask.
self._requested_n_parallel = max(1, int(intent.n_parallel))
+ self._requested_n_batch = intent.n_batch
+ self._requested_n_ubatch = intent.n_ubatch
# Commit the known-good snapshot + whether MTP+tensor is live, then
# watch this load for a mid-generation crash.
self._last_load_intent = intent
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index 5fc313cbfa1..a1894681fac 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -23,6 +23,10 @@ from typing import Iterable, Mapping, Optional
PARALLEL_MIN = 1
PARALLEL_MAX = 64
+# --batch-size / --ubatch-size range, mirrored by N_BATCH_MIN/MAX in per-model-config.ts
+BATCH_MIN = 1
+BATCH_MAX = 65536
+
# Each group = every alias (short + long) of one hard-denied flag.
# Extend the matching group when llama.cpp adds a new alias.
_DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
@@ -209,6 +213,9 @@ _DEVICE_FLAGS: frozenset[str] = frozenset({"--device", "-dev", "--main-gpu", "-m
# opt-in, not default. Layer flags are shared with llama_cpp's override
# detection; the MoE flags are strip-only (manual's --n-cpu-moe slider owns them).
_GPU_LAYER_FLAGS: frozenset[str] = frozenset({"-ngl", "--gpu-layers", "--n-gpu-layers"})
+# inherited copies of these shadow n_batch / n_ubatch, stripped only when the field is set
+_BATCH_FLAGS: frozenset[str] = frozenset({"-b", "--batch-size"})
+_UBATCH_FLAGS: frozenset[str] = frozenset({"-ub", "--ubatch-size"})
_FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})
_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS
_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})
@@ -483,6 +490,8 @@ def strip_shadowing_flags(
strip_tensor_split: bool = False,
strip_offload: bool = False,
strip_device: bool = False,
+ strip_batch: bool = False,
+ strip_ubatch: bool = False,
) -> list[str]:
"""Strip flags that shadow first-class Unsloth settings.
@@ -516,6 +525,10 @@ def strip_shadowing_flags(
shadowing |= _OFFLOAD_SHADOWING_FLAGS
if strip_device:
shadowing |= _DEVICE_FLAGS
+ if strip_batch:
+ shadowing |= _BATCH_FLAGS
+ if strip_ubatch:
+ shadowing |= _UBATCH_FLAGS
tokens = [str(a) for a in (args or [])]
out: list[str] = []
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index c006617371d..576bec318b0 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -18,7 +18,7 @@ from pydantic import (
model_validator,
)
-from core.inference.llama_server_args import PARALLEL_MAX, PARALLEL_MIN
+from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN
from picker.schemas import MAX_CHAT_TEMPLATE_BYTES
@@ -140,6 +140,28 @@ class LoadRequest(BaseModel):
"for non-GGUF models."
),
)
+ n_batch: Optional[int] = Field(
+ None,
+ ge = BATCH_MIN,
+ le = BATCH_MAX,
+ description = (
+ "Logical prompt batch size for llama-server (--batch-size) for "
+ f"this load ({BATCH_MIN}..{BATCH_MAX}). Omit for the llama.cpp "
+ "default (2048). Ignored for non-GGUF models."
+ ),
+ )
+ n_ubatch: Optional[int] = Field(
+ None,
+ ge = BATCH_MIN,
+ le = BATCH_MAX,
+ description = (
+ "Physical prompt micro-batch size for llama-server (--ubatch-size) "
+ f"for this load ({BATCH_MIN}..{BATCH_MAX}). Omit for the llama.cpp "
+ "default (512). llama.cpp caps it at the batch size. Larger values "
+ "speed up prompt processing at the cost of compute-buffer VRAM. "
+ "Ignored for non-GGUF models."
+ ),
+ )
tensor_parallel: bool = Field(
False,
description = (
@@ -193,6 +215,18 @@ class LoadRequest(BaseModel):
),
)
+ @field_validator("n_batch", "n_ubatch", mode = "before")
+ @classmethod
+ def _no_booleans(cls, value: Any) -> Any:
+ # bool subclasses int and pydantic parses non-strictly, so `true` arrives as 1 and
+ # the load launches --batch-size 1, which llama-server aborts on: a 500 rather than
+ # a 422. Mirrors ModelOverrideRequest._no_booleans so /load and /settings agree.
+ # Kept off the annotation: an Annotated BeforeValidator stops the Field constraints
+ # folding into the int core schema, and they leak into OpenAPI as ge/le.
+ if isinstance(value, bool):
+ raise ValueError("Expected a number, got a boolean.")
+ return value
+
@field_validator("tensor_split")
@classmethod
def _reject_degenerate_tensor_split(cls, value: Optional[List[float]]) -> Optional[List[float]]:
@@ -312,6 +346,24 @@ class ValidateModelRequest(BaseModel):
"server-wide --parallel default."
),
)
+ n_batch: Optional[int] = Field(
+ None,
+ ge = BATCH_MIN,
+ le = BATCH_MAX,
+ description = (
+ "Batch size (--batch-size) intended for the follow-up load, so the "
+ "coexistence estimate sizes the compute buffer like /load."
+ ),
+ )
+ n_ubatch: Optional[int] = Field(
+ None,
+ ge = BATCH_MIN,
+ le = BATCH_MAX,
+ description = (
+ "Micro-batch size (--ubatch-size) intended for the follow-up load, "
+ "so the coexistence estimate sizes the compute buffer like /load."
+ ),
+ )
speculative_type: Optional[str] = Field(
None,
description = (
@@ -340,6 +392,10 @@ class ValidateModelRequest(BaseModel):
"guard. Only the leased file's own embedded template is read, never sibling sidecars.",
)
+ _no_booleans = field_validator("n_batch", "n_ubatch", mode = "before")(
+ LoadRequest._no_booleans.__func__
+ )
+
class TransformersUpgradeInfo(BaseModel):
"""A model architecture no installed transformers ships, but a newer release does."""
@@ -665,6 +721,20 @@ class _InferenceRuntimeFields(BaseModel):
"for the diffusion runner, which ignores --parallel."
),
)
+ requested_n_batch: Optional[int] = Field(
+ None,
+ description = (
+ "Batch size (--batch-size) the load was invoked with, or None when "
+ "the load left it at the llama.cpp default (or to extra args / env)."
+ ),
+ )
+ requested_n_ubatch: Optional[int] = Field(
+ None,
+ description = (
+ "Micro-batch size (--ubatch-size) the load was invoked with, or None "
+ "when the load left it at the llama.cpp default (or to extra args / env)."
+ ),
+ )
class LoadResponse(_InferenceRuntimeFields):
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index b00ad1f5616..48b0e6102c4 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -8,10 +8,10 @@ Chat history API routes backed by studio.db.
from typing import Annotated, Any, Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
-from pydantic import BaseModel, ConfigDict, Field, ValidationError
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from auth.authentication import get_current_subject
-from core.inference.llama_server_args import PARALLEL_MAX, PARALLEL_MIN
+from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN
from loggers import get_logger
from utils.utils import safe_curated_detail, log_and_http_error
from storage.studio_db import (
@@ -177,11 +177,25 @@ class ChatPresetLoadConfig(BaseModel):
speculativeType: Optional[str] = None
specDraftNMax: Optional[int] = Field(default = None, ge = 1, le = 16)
nParallel: Optional[int] = Field(default = None, ge = PARALLEL_MIN, le = PARALLEL_MAX)
+ # The normalizer emits both keys on every preset (null included) and this model is
+ # extra="forbid", so without them PUT /api/chat/settings 400s the whole save for any
+ # preset carrying a loadConfig, including one that only pinned nParallel.
+ nBatch: Optional[int] = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
+ nUbatch: Optional[int] = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
tensorParallel: Optional[bool] = None
gpuMemoryMode: Optional[Literal["manual"]] = None
gpuLayers: Optional[int] = None
nCpuMoe: Optional[int] = Field(default = None, ge = 0)
+ @field_validator("nBatch", "nUbatch", mode = "before")
+ @classmethod
+ def _no_booleans(cls, value: Any) -> Any:
+ # Same contract as LoadRequest: bool subclasses int, so lax mode would store
+ # `true` as 1 here while /load 422s it.
+ if isinstance(value, bool):
+ raise ValueError("Expected a number, got a boolean.")
+ return value
+
class ChatPreset(BaseModel):
model_config = ConfigDict(extra = "forbid")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b0c68d40703..cbcf7af8c4d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1069,6 +1069,7 @@ try:
_DEFAULT_FIRST_TOKEN_TIMEOUT_S,
_DEFAULT_MAX_TOKENS_FLOOR,
_DEFAULT_STREAM_STALL_TIMEOUT_S,
+ _emitted_n_batch,
_extra_args_draft_device_pin,
_extra_args_n_ubatch,
_hf_offline_if_unreachable,
@@ -1120,6 +1121,7 @@ except ImportError:
_DEFAULT_FIRST_TOKEN_TIMEOUT_S,
_DEFAULT_MAX_TOKENS_FLOOR,
_DEFAULT_STREAM_STALL_TIMEOUT_S,
+ _emitted_n_batch,
_extra_args_draft_device_pin,
_extra_args_n_ubatch,
_hf_offline_if_unreachable,
@@ -3880,16 +3882,32 @@ def _active_gguf_intent(
native_grant_backed: bool,
) -> GgufLoadIntent:
backend_extra = list(llama_backend.extra_args or ())
- effective_extra = (
- request.llama_extra_args
- if request.llama_extra_args is not None
- else strip_shadowing_flags(
+ request_fields_set = getattr(request, "model_fields_set", set())
+ inherits_extras = request.llama_extra_args is None
+ if inherits_extras:
+ effective_extra = strip_shadowing_flags(
backend_extra,
strip_split_mode = _should_strip_split_mode(request, backend_extra),
strip_tensor_split = _should_strip_tensor_split(request),
strip_offload = request.gpu_memory_mode == "manual",
)
- )
+ # mirror _resolve_inherited_extra_args, or a stale inherited -b / -ub reads as equal
+ batch_stripped_extra = strip_shadowing_flags(
+ effective_extra,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_batch = "n_batch" in request_fields_set,
+ strip_ubatch = "n_ubatch" in request_fields_set,
+ )
+ # a strip that changed the list is an override, so the dedupe compares the stripped one
+ batch_overrides_inherit = batch_stripped_extra != effective_extra
+ effective_extra = batch_stripped_extra
+ else:
+ effective_extra = request.llama_extra_args
+ batch_overrides_inherit = False
source = llama_backend.last_load_intent or GgufLoadIntent(
model_identifier = model_identifier,
gguf_path = None if llama_backend.hf_repo else llama_backend.gguf_path,
@@ -3915,7 +3933,7 @@ def _active_gguf_intent(
mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, native_grant_backed),
dspark_draft_path = _dspark_draft_for_path(llama_backend.gguf_path, native_grant_backed),
compare_mtp_draft = True,
- extra_args_inherited = request.llama_extra_args is None,
+ extra_args_inherited = inherits_extras and not batch_overrides_inherit,
)
@@ -5060,6 +5078,11 @@ def _remote_gguf_companion_bytes(
return 0
+# Upper bound on any current tokenizer, used to rebuild the compute buffer when a
+# truncated header drops the token array. Above Llama 4 / Gemma 3 (256k), the widest shipping.
+_ASSUMED_MAX_VOCAB = 262144
+
+
def _estimate_gguf_kv_gb(
gguf_path: str,
max_seq_length: int,
@@ -5067,10 +5090,18 @@ def _estimate_gguf_kv_gb(
n_parallel: int = 1,
cache_type_kv: Optional[str] = None,
tensor_parallel: bool = False,
+ n_batch: Optional[int] = None,
+ n_ubatch: Optional[int] = None,
+ n_devices: int = 1,
+ is_diffusion: bool = False,
) -> float:
- """KV-cache VRAM (GB) at the larger of max_seq_length and any `--ctx-size`/`-c`
- override, over n_parallel slots, using the effective cache settings and managed
- launcher defaults. 0 if metadata is unreadable."""
+ """KV-cache plus compute-buffer VRAM (GB) at the larger of max_seq_length and
+ any `--ctx-size`/`-c` override, over n_parallel slots at the effective
+ micro-batch, using the effective cache settings and managed launcher
+ defaults. Compute buffers scale with the split the loader budgets: tensor
+ mode reserves them on every device, a multi-GPU layer split replicates the
+ context-linear term; ``is_diffusion`` skips them, since the diffusion
+ runner ignores the llama-server batch flags. 0 if metadata is unreadable."""
try:
from core.inference.llama_server_args import parse_ctx_override
@@ -5110,6 +5141,21 @@ def _estimate_gguf_kv_gb(
planned_cache_types,
key = _kv_bytes_per_elem,
)
+ # the loader raises --batch-size to max(slots, 2) before launch, and llama.cpp
+ # caps the micro-batch against it, so budget from the emitted value. Diffusion
+ # takes neither flag, and SWA metadata prices the KV against the micro-batch,
+ # so consuming them here would charge a diffusion load for a batch it never
+ # runs. Gated like the remote branch already is.
+ effective_ubatch = (
+ None
+ if is_diffusion
+ else _extra_args_n_ubatch(
+ llama_extra_args,
+ n_ctx = ctx,
+ n_batch = _emitted_n_batch(n_batch, slots),
+ n_ubatch = n_ubatch,
+ )
+ )
kv = probe._estimate_kv_cache_bytes(
ctx,
cache_type_for_budget,
@@ -5119,10 +5165,76 @@ def _estimate_gguf_kv_gb(
llama_extra_args,
default = managed_kv_unified,
),
- n_ubatch = _extra_args_n_ubatch(llama_extra_args, n_ctx = ctx),
+ n_ubatch = effective_ubatch,
flash_attn = False,
)
- return kv / (1024**3)
+ # the load reserves ubatch-scaled compute buffers, so they count against training too
+ if is_diffusion:
+ return kv / (1024**3)
+ devices = max(1, int(n_devices))
+
+ def _flat_buffer(per_device_tensor: bool) -> int:
+ """Flat compute buffer, rebuilt when the header is short of a vocab size.
+
+ _estimate_compute_buffer_bytes returns 0 when vocab_size or embedding_length is
+ missing. Only the first is reachable: _vocab_size is set solely from the
+ tokenizer.ggml.tokens array length, which a truncated header drops while keeping
+ the dims. So rebuild from the real formula with a vocab ceiling rather than
+ substituting the loader's flat reserve. The loader can afford that reserve
+ because over-reserving there just shrinks the context; here it denies the load.
+ """
+ flat = probe._estimate_compute_buffer_bytes(
+ n_ubatch = effective_ubatch,
+ n_parallel = slots,
+ per_device_tensor = per_device_tensor,
+ )
+ if flat > 0:
+ return flat
+ # getattr: a bare backend double carries neither dims nor constants.
+ n_embd = getattr(probe, "_embedding_length", None) or 0
+ if n_embd <= 0:
+ return 0 # nothing to rebuild from; the total is floored below instead
+ ub = max(1, int(effective_ubatch or probe._DEFAULT_N_UBATCH))
+ act_scratch = 4 * n_embd * ub * 4
+ out_buffer = _ASSUMED_MAX_VOCAB * ub * 4
+ raw = (
+ 2 * act_scratch + out_buffer * slots
+ if per_device_tensor
+ else act_scratch + out_buffer * max(0, slots - 1)
+ )
+ return int(raw * probe._COMPUTE_BUFFER_SAFETY)
+
+ if tensor_parallel:
+ # mirrors _plan_tensor_parallel: per-device buffer and ctx growth on every device
+ compute = devices * (
+ _flat_buffer(True)
+ + probe._compute_buffer_ctx_bytes(ctx, effective_ubatch, cache_type_for_budget)
+ )
+ else:
+ # mirrors the layer fit: flat buffer once, then per extra device, ctx growth per
+ # device. layer_split follows the loader's own condition: extras that disable
+ # pipeline parallelism (-ot, -ncmoe, --no-kv-offload) leave one KQ-mask copy.
+ from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args
+ pipeline_parallel_off = _pipeline_parallel_disabled_by_args(
+ llama_extra_args, n_layers = getattr(probe, "_n_layers", None)
+ )
+ compute = (
+ _flat_buffer(False)
+ + (devices - 1) * probe._PIPELINE_PER_DEVICE_OVERHEAD_MIB * 1024 * 1024
+ + devices
+ * probe._compute_buffer_ctx_bytes(
+ ctx,
+ effective_ubatch,
+ cache_type_for_budget,
+ layer_split = devices > 1 and not pipeline_parallel_off,
+ )
+ )
+ if compute <= 0:
+ # No embedding_length, so both compute terms are blind while the launch still
+ # reserves buffers. Floor at the loader's flat reserve, charged once: it is an
+ # invented number, and scaling an invention per device has no basis.
+ compute = int(getattr(probe, "_TENSOR_PARALLEL_BUFFER_RESERVE_MIB", 0)) * 1024**2
+ return (kv + compute) / (1024**3)
except Exception as e:
logger.warning(f"Could not size GGUF KV cache for training guard: {e}")
return 0.0
@@ -5137,6 +5249,10 @@ def _estimate_gguf_required_gb(
n_parallel: int = 1,
cache_type_kv: Optional[str] = None,
tensor_parallel: bool = False,
+ n_batch: Optional[int] = None,
+ n_ubatch: Optional[int] = None,
+ n_devices: int = 1,
+ is_diffusion: bool = False,
) -> Optional[float]:
"""Approximate GGUF VRAM (GB): quantized weights + companions, plus the KV
cache for local files (unreadable pre-download for remote). None when nothing
@@ -5204,6 +5320,10 @@ def _estimate_gguf_required_gb(
n_parallel,
cache_type_kv,
tensor_parallel,
+ n_batch,
+ n_ubatch,
+ n_devices,
+ is_diffusion,
)
repo = getattr(config, "gguf_hf_repo", None)
@@ -5228,13 +5348,108 @@ def _estimate_gguf_required_gb(
include_mtp = (not _charge_no_drafter and (_auto_dspark or not dspark_requested)),
include_dspark = (_dspark_capable and (_auto_dspark or dspark_requested)),
)
- return (main_bytes + companions) / (1024**3)
+ total_gb = (main_bytes + companions) / (1024**3)
+ # remote dims are unreadable; only the kq mask, linear in ubatch x ctx, can be sized here
+ from core.inference.llama_server_args import parse_ctx_override
+
+ try:
+ ctx_override = parse_ctx_override(llama_extra_args) or 0
+ except Exception:
+ ctx_override = 0
+ ctx = max(max_seq_length or 0, ctx_override)
+ effective_ubatch = (
+ None
+ if is_diffusion
+ else _extra_args_n_ubatch(
+ llama_extra_args,
+ n_ctx = ctx if ctx > 0 else None,
+ # same floor raise the loader applies at launch
+ n_batch = _emitted_n_batch(n_batch, n_parallel),
+ n_ubatch = n_ubatch,
+ )
+ )
+ if effective_ubatch:
+ # auto context: assume the native one fits at least a full micro-batch
+ budget_ctx = ctx if ctx > 0 else effective_ubatch
+ devices = max(1, int(n_devices))
+ # A multi-device layer split materialises the KQ mask _CTX_COMPUTE_SPLIT_MULT
+ # times, the same step _compute_buffer_ctx_bytes applies locally; charging
+ # the single-copy rate under-reserved 4x. Tensor mode is already correct
+ # (measured at the single-device rate, replicated per device). n_layers is
+ # None here: the header is unread, so -ngl cannot be resolved, but -ot /
+ # -ncmoe / --no-kv-offload / -sm none still register. Without this gate the
+ # same model 409s while remote and loads once cached.
+ from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args
+
+ split_mult = (
+ LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT
+ if devices > 1
+ and not tensor_parallel
+ and not _pipeline_parallel_disabled_by_args(llama_extra_args, n_layers = None)
+ else 1
+ )
+ mask_bytes = (
+ budget_ctx
+ * effective_ubatch
+ * 2
+ * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETY
+ * devices
+ * split_mult
+ )
+ # The mask is only the context-linear half. The flat half needs the dims,
+ # which are unreadable remotely, but its dominant term needs just a vocab
+ # ceiling: llama.cpp reserves n_vocab * ubatch * 4 per slot past the first
+ # (every slot under tensor mode), so n_batch = n_ubatch = 32768 on two
+ # slots is ~32 GiB the mask does not cover. Omitting it let the guard admit
+ # an uncached load that then OOMs the training job it exists to protect.
+ # The activation scratch needs embedding_length and stays uncharged: it is
+ # the small half, and over-reserving here denies the load outright.
+ # Scaled per device only in tensor mode, mirroring the local branch: a
+ # layer split folds the flat buffer in once (_flat_buffer(False)), and
+ # only tensor mode replicates it on every card.
+ _out_slots = n_parallel if tensor_parallel else max(0, n_parallel - 1)
+ out_buffer_bytes = (
+ _ASSUMED_MAX_VOCAB
+ * effective_ubatch
+ * 4
+ * _out_slots
+ * (devices if tensor_parallel else 1)
+ * LlamaCppBackend._COMPUTE_BUFFER_SAFETY
+ )
+ total_gb += (mask_bytes + out_buffer_bytes) / (1024**3)
+ return total_gb
return None
except Exception as e:
logger.warning(f"Could not size GGUF model for training guard: {e}")
return None
+def _guard_device_count(
+ requested_gpu_ids: Optional[list[int]],
+ vulkan_gpu_memory: Optional[list[tuple[int, int, int]]] = None,
+ *,
+ tensor_parallel: bool = False,
+) -> int:
+ """Devices the launch would spread its compute buffers over.
+
+ Tensor mode replicates them on every usable device, so it takes the pool: a pin,
+ else ggml's Vulkan probe (_effective_gpu_count sees CUDA only), else CUDA. A layer
+ split lands on the fewest GPUs that hold the model, so a pin is charged for what it
+ names and automatic placement for one. That last one is an approximation, not an
+ identity: _select_gpus returns [1] only when the model FITS on one card and
+ accumulates otherwise, so a model too big for one is under-charged by the same margin
+ that charging the whole candidate pool would over-charge one that fits. Resolving it
+ needs the free-VRAM map, which only arrives downstream in
+ can_load_chat_during_training; one device is the side that does not 409 a load that
+ launches on one.
+ """
+ if not tensor_parallel:
+ return max(1, len(requested_gpu_ids or ()))
+ if not requested_gpu_ids and vulkan_gpu_memory:
+ return max(1, len(vulkan_gpu_memory))
+ return max(1, LlamaCppBackend._effective_gpu_count(requested_gpu_ids))
+
+
def _gguf_layer_count(config: ModelConfig) -> Optional[int]:
"""Total block count from a local GGUF header, or None (remote / unreadable)."""
try:
@@ -5484,6 +5699,39 @@ async def _prepare_load_placement(
return _LoadPlacement(requested, resolved, is_vulkan, diffusion_kind)
+def _inherited_batch_flags_stripped(request) -> bool:
+ """Whether inheriting the resident extras drops a -b / -ub a set field supersedes.
+
+ _active_gguf_intent computes this inline (``batch_overrides_inherit``). Without it here
+ ``extra_args_inherited`` stays True, so _runtime_matches_intent compares the launched
+ extras (still carrying the stale flag) instead of the stripped override, and an Apply
+ that only raises the batch size reports ``already_loaded``.
+ """
+ if getattr(request, "llama_extra_args", None) is not None:
+ return False
+ fields_set = getattr(request, "model_fields_set", set())
+ strip_batch = "n_batch" in fields_set
+ strip_ubatch = "n_ubatch" in fields_set
+ if not (strip_batch or strip_ubatch):
+ return False
+ stored = list(getattr(get_llama_cpp_backend(), "extra_args", None) or ())
+ if not stored:
+ return False
+ return (
+ strip_shadowing_flags(
+ stored,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_batch = strip_batch,
+ strip_ubatch = strip_ubatch,
+ )
+ != stored
+ )
+
+
def _resolve_gguf_load_intent(
config: ModelConfig,
request: LoadRequest,
@@ -5538,7 +5786,11 @@ def _resolve_gguf_load_intent(
n_parallel = n_parallel,
is_vision = config.is_vision,
gpu_ids_are_vulkan_ordinals = placement.gpu_ids_are_vulkan_ordinals,
- extra_args_inherited = getattr(request, "llama_extra_args", None) is None,
+ extra_args_inherited = (
+ getattr(request, "llama_extra_args", None) is None
+ # a strip that changed the list is an override, so the dedupe compares it
+ and not _inherited_batch_flags_stripped(request)
+ ),
)
@@ -5666,6 +5918,25 @@ def _guard_chat_load_against_training(
and (gpu_ids_are_vulkan_ordinals or (binary and LlamaCppBackend._is_vulkan_backend(binary)))
)
+ # ggml's vulkan pool, probed once: the device count and the free-vram view below both read it
+ vulkan_gpu_memory: Optional[list[tuple[int, int, int]]] = None
+ if is_vulkan_backend and (
+ gpu_ids_are_vulkan_ordinals
+ or diffusion_kind is False
+ or (diffusion_kind is None and not requested_gpu_ids)
+ ):
+ vulkan_gpu_memory = LlamaCppBackend._get_gpu_memory(binary)
+ if not requested_gpu_ids:
+ # automatic placement prefers the discrete cards, like the loader's fit
+ vulkan_gpu_memory = LlamaCppBackend._vulkan_auto_gpu_memory(vulkan_gpu_memory)
+
+ guard_tensor_parallel = _effective_tensor_parallel(
+ llama_extra_args, _guard_tensor_parallel
+ ) and (is_vulkan_backend or LlamaCppBackend._effective_gpu_count(requested_gpu_ids) >= 2)
+ guard_n_devices = _guard_device_count(
+ requested_gpu_ids, vulkan_gpu_memory, tensor_parallel = guard_tensor_parallel
+ )
+
# Size with the count that will actually launch, or a load that fits gets a
# 409: diffusion never receives --parallel, load_model clamps to 1 on an
# llama-server without --kv-unified, and it clamps MTP to 1 as well. An
@@ -5697,13 +5968,14 @@ def _guard_chat_load_against_training(
speculative_type = getattr(request, "speculative_type", None),
n_parallel = n_parallel,
cache_type_kv = request.cache_type_kv,
- tensor_parallel = (
- _effective_tensor_parallel(llama_extra_args, _guard_tensor_parallel)
- and (
- is_vulkan_backend
- or LlamaCppBackend._effective_gpu_count(requested_gpu_ids) >= 2
- )
- ),
+ # getattr: older callers hand this guard a bare request double
+ n_batch = getattr(request, "n_batch", None),
+ n_ubatch = getattr(request, "n_ubatch", None),
+ tensor_parallel = guard_tensor_parallel,
+ # size the compute buffers for the split the loader would budget
+ n_devices = guard_n_devices,
+ # a confirmed diffusion runner ignores the batch flags, so no reserve for it
+ is_diffusion = diffusion_kind is True,
)
if is_gguf
else None
@@ -5724,11 +5996,9 @@ def _guard_chat_load_against_training(
vulkan_free_vram_gb = None
if is_gguf:
if is_vulkan_backend and (gpu_ids_are_vulkan_ordinals or diffusion_kind is False):
- gpu_memory = LlamaCppBackend._get_gpu_memory(binary)
- if not requested_gpu_ids:
- gpu_memory = LlamaCppBackend._vulkan_auto_gpu_memory(gpu_memory)
vulkan_free_vram_gb = {
- index: free_mib / 1024.0 for index, free_mib, _total_mib in gpu_memory
+ index: free_mib / 1024.0
+ for index, free_mib, _total_mib in (vulkan_gpu_memory or [])
}
elif is_vulkan_backend and diffusion_kind is None and requested_gpu_ids:
# Until the header is available, the model may use either the Vulkan
@@ -5849,6 +6119,9 @@ def _resolve_inherited_extra_args(
# must not last-wins-override it. auto leaves a user's inherited -ngl
# alone. getattr: a validate request reuses this resolver, no offload fields.
strip_offload = getattr(request, "gpu_memory_mode", "auto") == "manual",
+ # a set field emits its own flag; an inherited -b / -ub would last-wins-override it
+ strip_batch = "n_batch" in fields_set,
+ strip_ubatch = "n_ubatch" in fields_set,
)
try:
extra_llama_args = validate_extra_args(stripped)
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 5caf4a39700..f20348f1bf9 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -39,6 +39,8 @@ from utils.helper_precache_settings import (
from picker.schemas import MAX_CHAT_TEMPLATE_BYTES, chat_template_byte_length
from utils.coding_agents import CODING_AGENTS, detect_installed_coding_agents
from utils.openai_auto_switch_settings import (
+ BATCH_SIZE_MAX,
+ BATCH_SIZE_MIN,
DEFAULT_AUTO_UNLOAD_KEEP_KV,
DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED,
DEFAULT_OPENAI_AUTO_SWITCH_ENABLED,
@@ -182,6 +184,9 @@ class ModelOverridePayload(BaseModel):
spec_draft_n_max: Optional[int] = Field(default = None, ge = 1, le = 16)
# Parallel decode slots (llama-server --parallel), GGUF-only; None follows the server default.
n_parallel: Optional[int] = Field(default = None, ge = PARALLEL_SLOTS_MIN, le = PARALLEL_SLOTS_MAX)
+ # prompt batch sizes (--batch-size / --ubatch-size), gguf-only; none = llama.cpp defaults
+ n_batch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
+ n_ubatch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
tensor_parallel: bool = False
# Validated in bytes below: pydantic counts characters, so a multi-byte template would pass.
chat_template_override: Optional[str] = None
@@ -215,6 +220,8 @@ class ModelOverridePayload(BaseModel):
"custom_context_length",
"spec_draft_n_max",
"n_parallel",
+ "n_batch",
+ "n_ubatch",
"gpu_layers",
"n_cpu_moe",
"gpu_ids",
@@ -613,6 +620,8 @@ def update_openai_auto_switch_override(
speculative_type = payload.speculative_type,
spec_draft_n_max = payload.spec_draft_n_max,
n_parallel = payload.n_parallel,
+ n_batch = payload.n_batch,
+ n_ubatch = payload.n_ubatch,
tensor_parallel = payload.tensor_parallel,
chat_template_override = payload.chat_template_override,
gpu_memory_mode = payload.gpu_memory_mode,
diff --git a/studio/backend/tests/test_batch_sizes_per_load.py b/studio/backend/tests/test_batch_sizes_per_load.py
new file mode 100644
index 00000000000..366ed79e8f2
--- /dev/null
+++ b/studio/backend/tests/test_batch_sizes_per_load.py
@@ -0,0 +1,720 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""First-class n_batch / n_ubatch load fields (llama-server --batch-size / --ubatch-size).
+
+Compact sibling of test_parallel_slots_per_load.py: pydantic bounds, VRAM-budget
+precedence, reload dedupe, shadow stripping and the stored-override mapping.
+"""
+
+from __future__ import annotations
+
+import sys
+import types as _types
+from dataclasses import replace
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
+sys.modules.setdefault("structlog", _structlog_stub)
+
+import httpx # noqa: F401
+
+from core.inference.llama_cpp import (
+ GgufLoadIntent,
+ LlamaCppBackend,
+ _emitted_n_batch,
+ _extra_args_n_ubatch,
+ _repatch_parallel_slots,
+)
+from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, strip_shadowing_flags
+from models.inference import LoadRequest, ValidateModelRequest
+from utils.openai_auto_switch_settings import (
+ model_override_load_kwargs,
+ normalize_model_override,
+)
+
+
[email protected]("field", ["n_batch", "n_ubatch"])
+def test_load_request_bounds(field):
+ assert getattr(LoadRequest(model_path = "owner/repo"), field) is None
+ assert getattr(LoadRequest(model_path = "owner/repo", **{field: BATCH_MAX}), field) == BATCH_MAX
+ for bad in (BATCH_MIN - 1, BATCH_MAX + 1):
+ with pytest.raises(ValueError):
+ LoadRequest(model_path = "owner/repo", **{field: bad})
+ # /validate sizes like /load, so it carries the same field and bounds
+ assert getattr(ValidateModelRequest(model_path = "owner/repo", **{field: 256}), field) == 256
+
+
[email protected]("field", ["n_batch", "n_ubatch"])
[email protected]("model", [LoadRequest, ValidateModelRequest])
+def test_batch_fields_reject_json_booleans(model, field):
+ # bool is an int subclass, so lax pydantic turns `true` into 1 -> --batch-size 1, which
+ # llama-server refuses to start on: the caller saw a 500 instead of a 422. The override
+ # store already drops booleans, so this keeps /load and /settings in agreement.
+ with pytest.raises(ValueError):
+ model(model_path = "owner/repo", **{field: True})
+ # numeric strings and plain ints still coerce as before
+ assert getattr(model(model_path = "owner/repo", **{field: "4096"}), field) == 4096
+ assert getattr(model(model_path = "owner/repo", **{field: 4096}), field) == 4096
+
+
+def test_effective_ubatch_prefers_first_class_over_env():
+ env = {"LLAMA_ARG_BATCH": "128", "LLAMA_ARG_UBATCH": "128"}
+ assert _extra_args_n_ubatch(None, env = env, n_batch = 4096, n_ubatch = 1024) == 1024
+
+
+def test_effective_ubatch_lets_extras_override_first_class():
+ # extras are appended after the emitted flags, so they last-wins at launch
+ assert _extra_args_n_ubatch(["-ub", "256"], env = {}, n_ubatch = 1024) == 256
+
+
+def test_effective_ubatch_caps_at_batch_and_ctx():
+ assert _extra_args_n_ubatch(None, env = {}, n_batch = 512, n_ubatch = 2048) == 512
+ assert _extra_args_n_ubatch(None, env = {}, n_ubatch = 4096, n_ctx = 1024) == 1024
+ assert _extra_args_n_ubatch(None, env = {}) is None
+
+
+def _loaded_backend() -> LlamaCppBackend:
+ backend = LlamaCppBackend()
+ backend._process = object()
+ backend._healthy = True
+ backend._model_identifier = "owner/repo"
+ backend._hf_variant = "Q4_K_M"
+ backend._requested_n_ctx = 8192
+ backend._requested_spec_mode = "auto"
+ return backend
+
+
+def _intent(**kwargs) -> GgufLoadIntent:
+ return GgufLoadIntent(
+ model_identifier = "owner/repo",
+ hf_variant = "Q4_K_M",
+ n_ctx = 8192,
+ speculative_type = "auto",
+ **kwargs,
+ )
+
+
+def test_dedupe_matches_same_batch_sizes():
+ backend = _loaded_backend()
+ backend._requested_n_batch = 4096
+ matches = backend._runtime_matches_intent(_intent(n_batch = 4096), None)
+ assert matches is True
+
+
+def test_dedupe_reloads_on_batch_change():
+ backend = _loaded_backend()
+ assert backend._runtime_matches_intent(_intent(n_batch = 4096), None) is False
+ backend._requested_n_ubatch = 512
+ assert backend._runtime_matches_intent(_intent(n_ubatch = 1024), None) is False
+
+
+def test_dedupe_ignores_batch_for_diffusion():
+ backend = _loaded_backend()
+ backend._is_diffusion = True
+ backend._diffusion_requested_ngl = None
+ backend._gpu_layers = -1
+ assert backend._runtime_matches_intent(_intent(n_batch = 4096), None) is True
+
+
+def test_strip_shadowing_flags_batch_toggles():
+ args = ["-b", "4096", "--ubatch-size=256", "--top-k", "20"]
+ assert strip_shadowing_flags(args, strip_batch = True) == ["--ubatch-size=256", "--top-k", "20"]
+ assert strip_shadowing_flags(args, strip_ubatch = True) == ["-b", "4096", "--top-k", "20"]
+ assert strip_shadowing_flags(args) == args
+
+
+def test_override_store_round_trip():
+ entry = normalize_model_override({"n_batch": 4096, "n_ubatch": 1024})
+ assert entry == {"n_batch": 4096, "n_ubatch": 1024}
+ # out of range or boolean values drop silently, like the other knobs
+ assert normalize_model_override({"n_batch": 0, "n_ubatch": True}) == {}
+ kwargs = model_override_load_kwargs(entry, is_gguf = True)
+ assert kwargs["n_batch"] == 4096 and kwargs["n_ubatch"] == 1024
+ assert "n_batch" not in model_override_load_kwargs(entry, is_gguf = False)
+
+
+def test_fast_path_intent_strips_inherited_batch_flags_when_field_set():
+ # the already-loaded dedupe must see the same override the slow path launches
+ from routes.inference import _active_gguf_intent
+
+ backend = _loaded_backend()
+ backend._extra_args = ["-b", "512", "--top-k", "20"]
+ backend._extra_args_source = ("owner/repo", "Q4_K_M")
+
+ kwargs = dict(
+ model_identifier = "owner/repo",
+ chat_template_override = None,
+ n_parallel = 1,
+ native_grant_backed = False,
+ )
+ overriding = _active_gguf_intent(
+ LoadRequest(model_path = "owner/repo", n_batch = 4096), backend, **kwargs
+ )
+ assert overriding.extra_args == ("--top-k", "20")
+ assert overriding.extra_args_inherited is False
+
+ inheriting = _active_gguf_intent(LoadRequest(model_path = "owner/repo"), backend, **kwargs)
+ assert inheriting.extra_args == ("-b", "512", "--top-k", "20")
+ assert inheriting.extra_args_inherited is True
+
+
+def test_slow_path_intent_strips_inherited_batch_flags_when_field_set(monkeypatch):
+ # Sibling of the fast-path case above. A bare repo id with no gguf_variant skips
+ # _active_gguf_intent entirely, so without the same bookkeeping here the dedupe
+ # compares the LAUNCHED extras (still carrying -b 512) against themselves and reports
+ # already_loaded -- leaving the server at effective batch 512 for an Apply that asked
+ # for 4096.
+ from types import SimpleNamespace
+
+ from routes import inference as route
+
+ backend = _loaded_backend()
+ backend._extra_args = ["-b", "512", "--top-k", "20"]
+ backend._requested_extra_args = ["-b", "512", "--top-k", "20"]
+ backend._extra_args_source = ("owner/repo", "Q4_K_M")
+ monkeypatch.setattr(route, "get_llama_cpp_backend", lambda: backend)
+
+ config = SimpleNamespace(
+ identifier = "owner/repo",
+ is_gguf = True,
+ gguf_hf_repo = "owner/repo",
+ gguf_variant = "Q4_K_M",
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ is_vision = False,
+ )
+ # n_ctx must match the resident one, or the dedupe short-circuits before the extras.
+ request = LoadRequest(model_path = "owner/repo", n_batch = 4096, max_seq_length = 8192)
+ resolved = route._resolve_inherited_extra_args(request, config, config.identifier, None)
+ assert resolved == ["--top-k", "20"]
+
+ intent = route._resolve_gguf_load_intent(
+ config,
+ request,
+ native_grant_backed = False,
+ chat_template_override = None,
+ extra_args = resolved,
+ placement = SimpleNamespace(
+ resolved_gpu_ids = None, gpu_ids_are_vulkan_ordinals = None, requested_gpu_ids = None
+ ),
+ n_parallel = 1,
+ )
+ assert intent.extra_args_inherited is False
+ # Match the resident batch too, so the stripped inherited -b is the ONLY reason left to
+ # reload. Without this the batch-field comparison alone satisfies the assert and the
+ # extras are never reached.
+ backend._requested_n_batch = 4096
+ assert backend._runtime_matches_intent(intent, ["--top-k", "20"]) is False
+ # Control: with the flag no longer inherited, the same intent dedupes.
+ assert (
+ backend._runtime_matches_intent(
+ replace(intent, extra_args_inherited = True), ["--top-k", "20"]
+ )
+ is True
+ )
+
+ # An Apply that does not name the field still inherits the flag untouched.
+ plain = LoadRequest(model_path = "owner/repo", max_seq_length = 8192)
+ plain_args = route._resolve_inherited_extra_args(plain, config, config.identifier, None)
+ plain_intent = route._resolve_gguf_load_intent(
+ config,
+ plain,
+ native_grant_backed = False,
+ chat_template_override = None,
+ extra_args = plain_args,
+ placement = SimpleNamespace(
+ resolved_gpu_ids = None, gpu_ids_are_vulkan_ordinals = None, requested_gpu_ids = None
+ ),
+ n_parallel = 1,
+ )
+ assert plain_args == ["-b", "512", "--top-k", "20"]
+ assert plain_intent.extra_args_inherited is True
+
+
+def test_remote_gguf_guard_counts_explicit_micro_batch():
+ # a remote gguf has no readable dims, but an explicit ubatch still grows the kq mask
+ from types import SimpleNamespace
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ config = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "owner/repo",
+ gguf_variant = "Q4_K_M",
+ )
+ remote_variant = SimpleNamespace(quant = "Q4_K_M", size_bytes = 1024**3)
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+ base = route._estimate_gguf_required_gb(config, max_seq_length = 32768)
+ big = route._estimate_gguf_required_gb(
+ config, max_seq_length = 32768, n_batch = 65536, n_ubatch = 65536
+ )
+ assert base == pytest.approx(1.0)
+ # ctx-capped ubatch (32768) x ctx x 2 x 1.5 mask safety ~= 3 GiB on top
+ assert big > base + 2.0
+
+ # auto context still reserves: assume the native one fits a full micro-batch
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+ auto_ctx = route._estimate_gguf_required_gb(
+ config, max_seq_length = 0, n_batch = 65536, n_ubatch = 65536
+ )
+ diffusion = route._estimate_gguf_required_gb(
+ config,
+ max_seq_length = 32768,
+ n_batch = 65536,
+ n_ubatch = 65536,
+ is_diffusion = True,
+ )
+ assert auto_ctx > base + 2.0
+ # the diffusion runner ignores the llama-server batch flags, so no reserve
+ assert diffusion == pytest.approx(1.0)
+
+
+def _header_reader(**dims):
+ """Stand in for _read_gguf_metadata, which would otherwise reset the dims we set.
+
+ _estimate_gguf_kv_gb builds its own LlamaCppBackend and reads the file, so patching
+ the instance is not enough; the reader itself has to be replaced.
+ """
+
+ def _reader(self, *args, **kwargs):
+ for key, value in dims.items():
+ setattr(self, f"_{key}", value)
+
+ return _reader
+
+
+_QWEN3_8B = dict(
+ vocab_size = 151936,
+ embedding_length = 4096,
+ n_layers = 36,
+ n_heads = 32,
+ n_kv_heads = 8,
+ head_dim = 128,
+ context_length = 262144,
+ architecture = "qwen3",
+)
+
+
+def test_guard_rebuilds_the_compute_buffer_when_the_header_lost_its_vocab():
+ # _vocab_size comes only from the tokenizer.ggml.tokens array length, so a truncated
+ # header keeps the dims and drops the vocab. Substituting the loader's 5 GiB reserve
+ # here charged ~139x the real allocation and 409'd loads that fit.
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ novocab = dict(_QWEN3_8B, vocab_size = None)
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**_QWEN3_8B)):
+ complete = route._estimate_gguf_kv_gb("/x.gguf", 8192, n_parallel = 1)
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**novocab)):
+ rebuilt = route._estimate_gguf_kv_gb("/x.gguf", 8192, n_parallel = 1)
+ tensor = route._estimate_gguf_kv_gb(
+ "/x.gguf", 8192, n_parallel = 1, n_devices = 4, tensor_parallel = True
+ )
+ # At one slot the vocab-width term drops out entirely, so the rebuild is exact.
+ assert rebuilt == pytest.approx(complete, abs = 0.01)
+ # And the 5 GiB per device the reserve would have cost never appears.
+ assert tensor < complete + 4.0
+
+
+def test_guard_floors_a_header_with_no_dimensions_at_all():
+ # Nothing to rebuild from: both compute terms are blind, so the loader's flat reserve
+ # is the floor. Charged once, not per device, since it is an invented number.
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ blind = dict(_QWEN3_8B, vocab_size = None, embedding_length = None, kv_lora_rank = 512)
+ reserve_gb = LlamaCppBackend._TENSOR_PARALLEL_BUFFER_RESERVE_MIB / 1024
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**blind)):
+ one = route._estimate_gguf_kv_gb("/x.gguf", 8192, n_parallel = 1)
+ four = route._estimate_gguf_kv_gb(
+ "/x.gguf", 8192, n_parallel = 1, n_devices = 4, tensor_parallel = True
+ )
+ assert one > reserve_gb
+ assert four == pytest.approx(one, abs = 0.01)
+
+
+def test_batch_bounds_stay_standard_json_schema():
+ # An Annotated BeforeValidator stops pydantic folding the Field constraints into the
+ # int core schema, so they leak out as non-standard ge/le and generated clients drop
+ # them. Pin the batch fields against an untouched sibling.
+ from models.inference import LoadRequest, ValidateModelRequest
+ for model in (LoadRequest, ValidateModelRequest):
+ props = model.model_json_schema()["properties"]
+ sibling = next(s for s in props["n_parallel"]["anyOf"] if s.get("type") == "integer")
+ for field in ("n_batch", "n_ubatch"):
+ schema = next(s for s in props[field]["anyOf"] if s.get("type") == "integer")
+ assert set(schema) == set(sibling), f"{model.__name__}.{field}: {schema}"
+ assert schema["minimum"] == BATCH_MIN
+ assert schema["maximum"] == BATCH_MAX
+
+
+ "n_batch,n_parallel,expected",
+ [
+ (1, 1, 2), # GGML_ASSERT(n_tokens_all <= cparams.n_batch); a slots-only
+ (1, 2, 2), # floor would emit 1 here and abort
+ (2, 1, 2),
+ (1, 8, 8), # GGML_ASSERT(n_outputs_max <= cparams.n_outputs_max)
+ (4, 8, 8),
+ (7, 8, 8),
+ (8, 8, 8),
+ (32, 64, 64),
+ (64, 64, 64),
+ (64, 1, 64), # already above both floors: untouched
+ (4096, 8, 4096),
+ ],
+)
+def test_emitted_batch_clears_both_llama_server_floors(n_batch, n_parallel, expected):
+ """Measured against the bundled binary: b1/p1 and b1/p2 abort, b2/p1 and b2/p2 load,
+ b4/p8 aborts, b8/p8 loads, b32/p64 aborts, b64/p64 loads. So the floor is
+ max(slots, 2). The per-field bounds cannot express it, so the loader raises instead."""
+ assert _emitted_n_batch(n_batch, n_parallel) == expected
+ # llama.cpp defaults emit no flag, so there is nothing to raise
+ assert _emitted_n_batch(None, n_parallel) is None
+
+
+def test_restoring_slots_re_raises_the_batch_flag():
+ """Two paths hand slots back after --batch-size was emitted: the paravirtual
+ drafter drop, which restores the slots the extras-MTP clamp took, and the
+ non-MTP fallback retry, which restores them in its own argv. Both patched only
+ --parallel, so an explicit small batch emitted at one slot met a restored eight
+ and aborted the very fallback the restore exists to make work."""
+ # emitted at 1 slot, restored to 8: the floor moves with it
+ argv = ["llama-server", "--parallel", "1", "--batch-size", "2", "--ubatch-size", "64"]
+ assert _repatch_parallel_slots(argv, 8, 2) is True
+ assert argv[argv.index("--parallel") + 1] == "8"
+ assert argv[argv.index("--batch-size") + 1] == "8"
+ # the micro-batch is not raised: llama.cpp caps it against the batch itself
+ assert argv[argv.index("--ubatch-size") + 1] == "64"
+
+ # a batch already above the restored floor is left alone
+ argv = ["llama-server", "--parallel", "1", "--batch-size", "4096"]
+ assert _repatch_parallel_slots(argv, 8, 4096) is True
+ assert argv[argv.index("--batch-size") + 1] == "4096"
+
+ # llama.cpp defaults emit no flag, and the restore must not invent one
+ argv = ["llama-server", "--parallel", "1"]
+ assert _repatch_parallel_slots(argv, 8, None) is True
+ assert "--batch-size" not in argv
+
+ # no --parallel to patch: report it so the caller does not rebind n_parallel
+ argv = ["llama-server", "--batch-size", "2"]
+ assert _repatch_parallel_slots(argv, 8, 2) is False
+ assert argv[argv.index("--batch-size") + 1] == "2"
+
+
+def test_budgets_use_the_raised_batch_not_the_requested_one():
+ """llama.cpp caps the micro-batch against the batch it is GIVEN
+ (cparams.n_ubatch = min(cparams.n_batch, n_ubatch or n_batch)), and the loader
+ raises --batch-size to max(slots, 2) before launch. Budgeting from the requested
+ value instead planned n_batch=1 / n_ubatch=64 / 64 slots at a micro-batch of 1
+ and launched it at 64: ~2.2 GB of compute buffer the training guard never
+ charged, and an auto-fit sized for a graph the server does not build."""
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ # what the launch actually runs: the raise is the only difference
+ assert _emitted_n_batch(1, 64) == 64
+ assert _extra_args_n_ubatch(None, env = {}, n_ctx = 32768, n_batch = 1, n_ubatch = 64) == 1
+ assert _extra_args_n_ubatch(None, env = {}, n_ctx = 32768, n_batch = 64, n_ubatch = 64) == 64
+
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**_QWEN3_8B)):
+ raised = route._estimate_gguf_kv_gb("/x.gguf", 32768, n_parallel = 64, n_batch = 1, n_ubatch = 64)
+ # the value the loader emits, asked for directly: the guard must match it
+ explicit = route._estimate_gguf_kv_gb(
+ "/x.gguf", 32768, n_parallel = 64, n_batch = 64, n_ubatch = 64
+ )
+ # and the un-raised micro-batch of 1, which is what a requested-value budget gave
+ unraised = route._estimate_gguf_kv_gb(
+ "/x.gguf", 32768, n_parallel = 64, n_batch = 1, n_ubatch = 1
+ )
+ assert raised == pytest.approx(explicit, abs = 0.01)
+ assert raised > unraised + 2.0
+
+ # the remote branch shares the floor: no dims, but the kq mask still grows
+ from types import SimpleNamespace
+
+ config = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "owner/repo",
+ gguf_variant = "Q4_K_M",
+ )
+ remote_variant = SimpleNamespace(quant = "Q4_K_M", size_bytes = 1024**3)
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+ remote_raised = route._estimate_gguf_required_gb(
+ config, max_seq_length = 262144, n_parallel = 64, n_batch = 1, n_ubatch = 65536
+ )
+ remote_explicit = route._estimate_gguf_required_gb(
+ config, max_seq_length = 262144, n_parallel = 64, n_batch = 64, n_ubatch = 65536
+ )
+ remote_unraised = route._estimate_gguf_required_gb(
+ config, max_seq_length = 262144, n_parallel = 64, n_batch = 1, n_ubatch = 1
+ )
+ assert remote_raised == pytest.approx(remote_explicit, abs = 0.01)
+ # 1 GiB of weights plus a kq mask that is 64x the one a requested-value budget charged
+ assert remote_raised > remote_unraised + 0.04
+
+ # A batch already above both floors is untouched, so the ordinary case is unchanged,
+ # and llama.cpp defaults stay defaults however many slots are asked for: the raise
+ # must not turn an unset field into an emitted one.
+ assert _emitted_n_batch(4096, 8) == 4096
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**_QWEN3_8B)):
+ above_floor = route._estimate_gguf_kv_gb(
+ "/x.gguf", 32768, n_parallel = 8, n_batch = 4096, n_ubatch = 512
+ )
+ defaults = route._estimate_gguf_kv_gb("/x.gguf", 32768, n_parallel = 8)
+ ubatch_only = route._estimate_gguf_kv_gb("/x.gguf", 32768, n_parallel = 8, n_ubatch = 512)
+ # -ub 512 is the llama.cpp default, so pinning it must not move the budget
+ assert above_floor == pytest.approx(ubatch_only, abs = 0.01)
+ assert defaults == pytest.approx(ubatch_only, abs = 0.01)
+
+
+def test_remote_guard_drops_the_split_mask_when_pipelining_is_disabled():
+ # The local rule gates the 4x KQ-mask multiplier on _pipeline_parallel_disabled_by_args.
+ # Without the same gate remotely, -ot / -ncmoe on a 2-GPU pin is charged 4x while the
+ # model is undownloaded and 1x once cached: same model, same flags, two verdicts.
+ from types import SimpleNamespace
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ config = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "owner/repo",
+ gguf_variant = "Q4_K_M",
+ )
+ remote_variant = SimpleNamespace(quant = "Q4_K_M", size_bytes = 1024**3)
+
+ def _required(extra_args):
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+ return route._estimate_gguf_required_gb(
+ config,
+ max_seq_length = 32768,
+ n_ubatch = 2048,
+ n_devices = 2,
+ llama_extra_args = extra_args,
+ )
+
+ split = _required(None)
+ for disabling in (["-ot", r"\.ffn_.*_exps\.=CPU"], ["-ncmoe", "8"], ["--no-kv-offload"]):
+ assert _required(disabling) < split, disabling
+
+
+def test_guard_device_count_follows_the_split_the_loader_would_pick():
+ from unittest.mock import patch
+
+ from routes.inference import _guard_device_count
+
+ pool = [(0, 8192, 8192), (1, 8192, 8192), (2, 8192, 8192)]
+ with patch.object(
+ LlamaCppBackend,
+ "_effective_gpu_count",
+ lambda ids = None: len(ids) if ids else 0,
+ ):
+ # tensor mode replicates on every device; a vulkan host counts the probed pool
+ assert _guard_device_count(None, pool, tensor_parallel = True) == 3
+ assert _guard_device_count([1, 2], pool, tensor_parallel = True) == 2
+ assert _guard_device_count(None, [], tensor_parallel = True) == 1
+ # a layer split lands on the fewest gpus that fit, so auto placement is one
+ assert _guard_device_count(None, pool) == 1
+ assert _guard_device_count([1, 2], pool) == 2
+
+
+def test_override_strips_shadowing_batch_flags():
+ kwargs = model_override_load_kwargs(
+ {"n_batch": 4096, "llama_extra_args": ["-b", "512", "--top-k", "20"]},
+ is_gguf = True,
+ )
+ assert kwargs["llama_extra_args"] == ["--top-k", "20"]
+ # a flag with no first-class field behind it still passes through
+ kwargs = model_override_load_kwargs(
+ {"llama_extra_args": ["-ub", "256"]},
+ is_gguf = True,
+ )
+ assert kwargs["llama_extra_args"] == ["-ub", "256"]
+
+
+def test_the_local_guard_charges_diffusion_nothing_for_the_batch_flags():
+ """The diffusion runner takes neither --batch-size nor --ubatch-size, but SWA metadata
+ prices the KV against the micro-batch (swa_limit = swa * slots + ubatch), so deriving
+ one from the ignored fields charged a diffusion load for a graph it never builds:
+ measured 5.449 GB against 4.658, or 0.79 GB of phantom cache that can 409 a chat
+ coexisting with training. The remote branch was already gated on is_diffusion; this
+ is the local one."""
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ # SWA needs the KV widths as well as the window, or the estimate takes the dense path
+ swa_header = dict(_QWEN3_8B, sliding_window = 1024, kv_key_length = 128, kv_value_length = 128)
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**swa_header)):
+ quiet = route._estimate_gguf_kv_gb("/x.gguf", 131072, n_parallel = 1, is_diffusion = True)
+ loud = route._estimate_gguf_kv_gb(
+ "/x.gguf",
+ 131072,
+ n_parallel = 1,
+ n_batch = 8192,
+ n_ubatch = 8192,
+ is_diffusion = True,
+ )
+ # the same header on a real llama-server load, where the flags DO apply
+ chat_quiet = route._estimate_gguf_kv_gb("/x.gguf", 131072, n_parallel = 1)
+ chat_loud = route._estimate_gguf_kv_gb(
+ "/x.gguf", 131072, n_parallel = 1, n_batch = 8192, n_ubatch = 8192
+ )
+ assert loud == pytest.approx(quiet, abs = 0.001)
+ # and the gate is not vacuous: on the identical header a chat load pays for them
+ assert chat_loud > chat_quiet + 0.7
+
+
+def test_the_recorded_micro_batch_is_derived_from_the_slots_that_launched():
+ """self._n_ubatch is recorded next to _commit_effective_parallel_slots and the two are
+ read together later (the slot save re-estimates the KV from both). Both slot RESTORES
+ (the paravirtual drafter drop and the non-MTP retry) raise the count after the sizing
+ pass ran, so recording the sizing pass's value would pair the launched slots with a
+ micro-batch derived at the clamped count and under-state that cache. Pinned on the
+ source, since reaching the record needs a real spawn."""
+ import ast
+ import inspect
+ import textwrap
+
+ src = textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model))
+ tree = ast.parse(src)
+ calls = [
+ node.lineno
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "_ubatch_for_slots"
+ ]
+ # the sizing pass, the fit-time reduction, and the post-launch record
+ assert len(calls) == 3, f"expected three re-derivations, found {len(calls)}"
+ # the record must not reuse the sizing pass's value
+ compact = "".join(src.split())
+ assert "self._n_ubatch=max(0,int(self._DEFAULT_N_UBATCHif_launched_ubatchisNone" in compact
+ assert "_launched_ubatch=_ubatch_for_slots(n_parallel)" in compact
+ # and it is derived after the last thing that can move the slot count
+ assert compact.index("_launched_ubatch=_ubatch_for_slots") > compact.index(
+ "n_parallel=_mtp_clamped_slots"
+ )
+
+
+def test_the_remote_guard_charges_the_flat_output_buffer():
+ """The KQ mask is only the context-linear half of the compute buffer. llama.cpp also
+ reserves n_vocab * ubatch * 4 per slot past the first, which is context-INdependent and
+ dwarfs the mask at large settings: n_batch = n_ubatch = 32768 on two slots is ~32 GiB
+ the mask never covers. Omitting it remotely let the coexistence guard admit an uncached
+ load that then OOMs the training job it exists to protect."""
+ from types import SimpleNamespace
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ config = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_hf_repo = "owner/repo",
+ gguf_variant = "Q4_K_M",
+ )
+ remote_variant = SimpleNamespace(quant = "Q4_K_M", size_bytes = 1024**3)
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+
+ def _gb(**kwargs):
+ return route._estimate_gguf_required_gb(config, max_seq_length = 32768, **kwargs)
+
+ blank_1 = _gb(n_parallel = 1)
+ blank_4 = _gb(n_parallel = 4)
+ big_1 = _gb(n_parallel = 1, n_batch = 32768, n_ubatch = 32768)
+ big_2 = _gb(n_parallel = 2, n_batch = 32768, n_ubatch = 32768)
+ typical_4 = _gb(n_parallel = 4, n_batch = 2048, n_ubatch = 512)
+
+ # The term is per slot PAST the first, so one slot is unchanged by it and the
+ # llama.cpp defaults (which emit no flag at all) stay exactly at the weights.
+ assert blank_1 == pytest.approx(1.0) and blank_4 == pytest.approx(1.0)
+ # 262144 * 32768 * 4 = 32 GiB for the second slot, which the mask alone missed
+ assert big_2 > big_1 + 30.0
+ # and it stays proportionate where the values are ordinary
+ assert typical_4 < 4.0
+
+ # Scaled per device only in tensor mode. The layer path folds the flat buffer in once
+ # (_flat_buffer(False) is not multiplied), so charging it per device would 409 a
+ # 2-GPU layer split for ~32 GiB it never allocates.
+ with (
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ return_value = ([remote_variant], False),
+ ),
+ patch.object(route, "_remote_gguf_companion_bytes", return_value = 0),
+ ):
+
+ def _split(tensor, devices):
+ return route._estimate_gguf_required_gb(
+ config,
+ max_seq_length = 32768,
+ n_parallel = 2,
+ n_batch = 32768,
+ n_ubatch = 32768,
+ n_devices = devices,
+ tensor_parallel = tensor,
+ )
+
+ layer_1, layer_2 = _split(False, 1), _split(False, 2)
+ tensor_1, tensor_2 = _split(True, 1), _split(True, 2)
+ # the second device adds only the ctx-linear mask, not another 32 GiB of logits
+ assert layer_2 - layer_1 < 30.0
+ # tensor mode replicates the whole buffer on every card, so it does roughly double
+ assert tensor_2 > tensor_1 * 1.8
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 4b85bbc8ba5..26ef2cfbc4b 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -8,10 +8,12 @@ import sys
import pytest
from fastapi import HTTPException
+from pydantic import ValidationError
_backend = os.path.join(os.path.dirname(__file__), "..")
sys.path.insert(0, _backend)
+from core.inference.llama_server_args import BATCH_MAX
from routes import chat_history
@@ -136,6 +138,35 @@ def test_chat_settings_payload_accepts_preset_load_config():
assert dumped["customPresets"][0]["loadConfig"]["kvCacheDtype"] == "q8_0"
+def test_chat_settings_payload_accepts_preset_batch_sizes():
+ from pydantic import ValidationError
+
+ # extra="forbid" 400s the whole settings write, and the normalizer emits both keys on
+ # every preset (null included), so a preset that only pinned nParallel would stop saving.
+ payload = chat_history.ChatSettingsPayload.model_validate(
+ {
+ "customPresets": [
+ {
+ "name": "batch preset",
+ "params": {"temperature": 0.7},
+ "loadConfig": {"nParallel": 4, "nBatch": 4096, "nUbatch": 1024},
+ },
+ ],
+ }
+ )
+ dumped = payload.model_dump(exclude_unset = True)
+ assert dumped["customPresets"][0]["loadConfig"]["nBatch"] == 4096
+ assert dumped["customPresets"][0]["loadConfig"]["nUbatch"] == 1024
+
+ # The unset shape the normalizer sends alongside an untouched knob.
+ chat_history.ChatPresetLoadConfig.model_validate(
+ {"nParallel": 4, "nBatch": None, "nUbatch": None}
+ )
+ for bad in ({"nBatch": 0}, {"nUbatch": BATCH_MAX + 1}, {"nBatch": True}):
+ with pytest.raises(ValidationError):
+ chat_history.ChatPresetLoadConfig.model_validate(bad)
+
+
def test_chat_settings_payload_accepts_mlx_kv_bits():
from pydantic import ValidationError
diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.py
index 11a04aea22b..186a684dc79 100644
--- a/studio/backend/tests/test_chat_load_during_training.py
+++ b/studio/backend/tests/test_chat_load_during_training.py
@@ -1469,6 +1469,29 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):
seen["flash_attn"] = flash_attn
return ctx * n_parallel * (1024**2) # 1 MiB per ctx unit per slot
+ _PIPELINE_PER_DEVICE_OVERHEAD_MIB = 0
+
+ # zeroed: this test pins the kv sizing, not the compute buffers
+ def _estimate_compute_buffer_bytes(
+ self,
+ *,
+ n_ubatch = None,
+ n_parallel = 1,
+ per_device_tensor = False,
+ ):
+ seen["compute_n_ubatch"] = n_ubatch
+ return 0
+
+ def _compute_buffer_ctx_bytes(
+ self,
+ n_ctx,
+ n_ubatch = None,
+ cache_type_kv = None,
+ *,
+ layer_split = False,
+ ):
+ return 0
+
with patch.object(self.route, "LlamaCppBackend", _FakeBackend):
r = self.route
# --ctx-size override above max_seq_length -> override wins
diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.py
index a59358d70f6..c5cb2a325e2 100644
--- a/studio/backend/tests/test_metal_paravirtual_guard.py
+++ b/studio/backend/tests/test_metal_paravirtual_guard.py
@@ -1265,6 +1265,7 @@ def _run_clamp_then_fallback(
spec_flags,
cmd,
asked_for = None,
+ n_batch = None,
):
"""Run the real clamp block, rebuild fallback_cmd the way the MTP retry does, then run
the real restore block. Returns the two argvs and the slot count
@@ -1277,9 +1278,11 @@ def _run_clamp_then_fallback(
"_mtp_clamped_slots": 0,
"model_identifier": "owner/repo",
"logger": llama_cpp.logger,
+ "n_batch": n_batch,
"_extra_args_set_spec_type": llama_cpp._extra_args_set_spec_type,
"_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
"_child_spec_env": llama_cpp._child_spec_env,
+ "_repatch_parallel_slots": llama_cpp._repatch_parallel_slots,
# The pre-fit ask, which the restore must NOT reach for.
"_pending_load_kwargs": {"n_parallel": n_parallel if asked_for is None else asked_for},
}
@@ -1313,6 +1316,46 @@ def test_the_mtp_fallback_gets_the_requested_slots_back():
assert slots == 4
+def test_the_fallback_raises_the_batch_flag_with_the_slots():
+ """--batch-size is emitted from the slot count as it stands then, and llama-server
+ aborts below it, so handing 4 slots back to an argv carrying an explicit -b 2 would
+ abort the very retry the restore exists to make work."""
+ spec = ["--spec-type", "draft-mtp"]
+ cmd = ["llama-server", "-m", "/m.gguf", "--parallel", "4", "--batch-size", "2", *spec]
+ clamped, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 4,
+ extra_args = ["--top-k", "40"],
+ spec_flags = spec,
+ cmd = cmd,
+ n_batch = 2,
+ )
+ assert fallback[fallback.index("--parallel") + 1] == "4"
+ assert fallback[fallback.index("--batch-size") + 1] == "4"
+ assert slots == 4
+ # the clamped argv keeps what it launched with: one slot needs no raise
+ assert clamped[clamped.index("--batch-size") + 1] == "2"
+
+
+def test_the_mtp_backstop_lowers_the_batch_with_the_slots():
+ """The floor is the SMALLEST legal batch, not merely a sufficient one. This clamp runs
+ after --batch-size is emitted, so dropping to one slot has to undo the raise the old
+ count forced: -b 1 with 64 slots emits 64, and leaving it there launched MTP at a
+ 64-token micro-batch for a request of 1 (a much larger compute buffer), while the
+ recorded micro-batch, derived from the clamped count, said 2."""
+ spec = ["--spec-type", "draft-mtp"]
+ cmd = ["llama-server", "-m", "/m.gguf", "--parallel", "64", "--batch-size", "64", *spec]
+ clamped, _fallback, _slots = _run_clamp_then_fallback(
+ n_parallel = 64,
+ extra_args = ["--top-k", "40"],
+ spec_flags = spec,
+ cmd = cmd,
+ n_batch = 1,
+ )
+ assert clamped[clamped.index("--parallel") + 1] == "1"
+ # max(1, max(2, 1)) = 2, which is what _ubatch_for_slots(1) records
+ assert clamped[clamped.index("--batch-size") + 1] == "2"
+
+
def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():
"""A trailing --spec-default cannot override MTP or DSpark that extras or the env
supplied: llama.cpp applies the env first and appends types rather than replacing
@@ -1404,7 +1447,9 @@ def test_the_extras_own_clamp_comes_back_from_the_startup_retry_too():
"_pv_extras_clamped_slots": 4,
"_mtp_clamped_slots": 0,
"_detected_gpus": [], # CPU launch: nothing had to budget the slots
+ "n_batch": None,
"_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
+ "_repatch_parallel_slots": llama_cpp._repatch_parallel_slots,
"strip_shadowing_flags": llama_cpp.strip_shadowing_flags,
"_SPEC_ENV_VARS": llama_cpp._SPEC_ENV_VARS,
"logger": llama_cpp.logger,
diff --git a/studio/backend/tests/test_slot_offload_fit.py b/studio/backend/tests/test_slot_offload_fit.py
index 4441f3afc4d..60900f04195 100644
--- a/studio/backend/tests/test_slot_offload_fit.py
+++ b/studio/backend/tests/test_slot_offload_fit.py
@@ -157,3 +157,40 @@ class TestSlotsThatFitOnGpu:
)
assert calls
assert all(call["swa_full"] is True for call in calls)
+
+ def test_micro_batch_is_re_derived_per_candidate(self):
+ """llama-server raises --batch-size to max(slots, 2) and llama.cpp caps the
+ micro-batch against it, so a batch below the requested slot count shrinks as the
+ candidates do: n_batch=1 launches the 3-slot candidate at -b 3, not the 64 the
+ 4-slot request resolved to. At these dims that is 6.8 MiB of compute buffer
+ against 145.2, so pricing every candidate at the requested count's micro-batch
+ rejects a 3-slot fit that launches comfortably and cuts serving capacity for it."""
+ from core.inference.llama_cpp import _emitted_n_batch, _extra_args_n_ubatch
+
+ def ubatch_for_slots(slots: int):
+ return _extra_args_n_ubatch(
+ None, env = {}, n_ctx = CTX, n_batch = _emitted_n_batch(1, slots), n_ubatch = 64
+ )
+
+ def _fit(**kwargs):
+ calls = []
+ got = _backend(kv_calls = calls)._slots_that_fit_on_gpu(
+ 4,
+ CTX,
+ [(0, 24576)],
+ {0: 24576},
+ 23750 * MIB,
+ "q8_0",
+ FRAC,
+ 0,
+ 1,
+ n_ubatch = 64,
+ **kwargs,
+ )
+ return got, [call["n_ubatch"] for call in calls]
+
+ # priced at the batch each candidate LAUNCHES with: the first one fits, so the
+ # search stops there
+ assert _fit(ubatch_for_slots = ubatch_for_slots) == (([0], False, 3), [3])
+ # held at the requested count's micro-batch, the same card loses a slot
+ assert _fit() == (([0], False, 2), [64, 64])
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index 09c35dd6e94..da38b797fb9 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -287,6 +287,10 @@ VALID_MLX_KV_BITS = frozenset({8, 6, 5, 4, 3, 2})
PARALLEL_SLOTS_MIN = 1
PARALLEL_SLOTS_MAX = 64
+# mirrors BATCH_MIN/MAX in llama_server_args.py, same reason as the slot bounds
+BATCH_SIZE_MIN = 1
+BATCH_SIZE_MAX = 65536
+
MAX_SEQ_LENGTH_CEILING = 1048576
MAX_CHAT_TEMPLATE_OVERRIDE_BYTES = 65_536
# Highest device index a gpu_ids entry may name; also bounds how many ids one entry holds.
@@ -364,6 +368,12 @@ def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:
if n_parallel:
entry["n_parallel"] = n_parallel
+ # blank or out of range means "follow the llama.cpp defaults (2048 / 512)"
+ for key in ("n_batch", "n_ubatch"):
+ parsed = _bounded_int(payload.get(key), minimum = BATCH_SIZE_MIN, maximum = BATCH_SIZE_MAX)
+ if parsed:
+ entry[key] = parsed
+
if _coerce_bool(payload.get("tensor_parallel")):
entry["tensor_parallel"] = True
@@ -460,6 +470,11 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> di
# Slots are a llama-server flag, and the picker sends them for GGUF only.
if override.get("n_parallel") is not None:
kwargs["n_parallel"] = override["n_parallel"]
+ # batch sizes are llama-server flags too (--batch-size / --ubatch-size)
+ if override.get("n_batch") is not None:
+ kwargs["n_batch"] = override["n_batch"]
+ if override.get("n_ubatch") is not None:
+ kwargs["n_ubatch"] = override["n_ubatch"]
if override.get("gpu_memory_mode") is not None:
kwargs["gpu_memory_mode"] = override["gpu_memory_mode"]
if override.get("gpu_layers") is not None:
@@ -493,6 +508,8 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> di
# Sent only when on, so it is always the Tensor Parallelism toggle overriding the
# flag; an override that leaves the toggle off keeps a row/none/layer split mode.
strip_split_mode = bool(kwargs.get("tensor_parallel")),
+ strip_batch = "n_batch" in kwargs,
+ strip_ubatch = "n_ubatch" in kwargs,
)
return kwargs
diff --git a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
index 17173812818..a1d74a2b1cd 100644
--- a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
@@ -34,6 +34,12 @@ function describeOverride(override: ApiModelOverride): string[] {
if (override.n_parallel) {
parts.push(`${override.n_parallel} parallel slots`);
}
+ if (override.n_batch) {
+ parts.push(`batch ${override.n_batch}`);
+ }
+ if (override.n_ubatch) {
+ parts.push(`ubatch ${override.n_ubatch}`);
+ }
if (override.tensor_parallel) {
parts.push("tensor parallel");
}
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 54e0b58025a..f2d245637a6 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1746,6 +1746,10 @@ const VISIBLE_MODEL_RUNTIME_KEYS = [
"loadedKvCacheDtype",
"nParallel",
"loadedNParallel",
+ "nBatch",
+ "loadedNBatch",
+ "nUbatch",
+ "loadedNUbatch",
"tensorParallel",
"loadedTensorParallel",
"gpuMemoryMode",
@@ -2596,6 +2600,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// split (0 especially) must not be refused as a full-GGUF occupant.
gpu_layers: effectiveGpuLayers,
n_parallel: config.nParallel ?? null,
+ // omitted when blank: a null counts as set and strips inherited -b / -ub
+ ...(config.nBatch != null ? { n_batch: config.nBatch } : {}),
+ ...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),
}
: {}),
}))
@@ -2639,6 +2646,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
gpu_ids: effectiveGpuIds ?? undefined,
// Per-model too, or the auto-load reverts a remembered override.
n_parallel: config.nParallel ?? null,
+ ...(config.nBatch != null ? { n_batch: config.nBatch } : {}),
+ ...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),
}
: {}),
}).catch((error: unknown) => {
@@ -2712,6 +2721,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const committedSlots = (loadResp.is_diffusion ?? false)
? null
: (config.nParallel ?? null);
+ // same rule for the batch sizes
+ const committedNBatch = (loadResp.is_diffusion ?? false)
+ ? null
+ : (config.nBatch ?? null);
+ const committedNUbatch = (loadResp.is_diffusion ?? false)
+ ? null
+ : (config.nUbatch ?? null);
useChatRuntimeStore.setState({
ggufContextLength: loadResp.context_length ?? 131072,
ggufMaxContextLength:
@@ -2731,6 +2747,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// Click-time value, not the resolved backend echo (see performLoad).
nParallel: committedSlots,
loadedNParallel: committedSlots,
+ nBatch: committedNBatch,
+ loadedNBatch: committedNBatch,
+ nUbatch: committedNUbatch,
+ loadedNUbatch: committedNUbatch,
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
...loadedGpuMemoryFields(loadResp),
@@ -2763,6 +2783,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// a model that cannot use it.
nParallel: null,
loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
// Non-GGUF response: clears any stale GPU baseline a prior manual-GPU
@@ -3071,6 +3095,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// preset would read as applied and be re-sent by the next Apply.
nParallel: null,
loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
...loadedGpuMemoryFields(loadResp),
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 586c2701b0b..87963f24ca4 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -262,6 +262,9 @@ export async function validateModel(
gpu_layers: payload.gpu_layers,
// Slots scale the KV estimate; keep validate sized like the load.
n_parallel: payload.n_parallel,
+ // batch sizes scale the same estimate; omitted when blank so they never read as set
+ ...(payload.n_batch != null ? { n_batch: payload.n_batch } : {}),
+ ...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {}),
// The estimate charges a drafter whose size differs by kind (a DSpark
// sidecar is ~11 GB), so omitting the mode makes this preflight disagree
// with /load in both directions.
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 84acbe34b48..8361bf78b43 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -517,6 +517,8 @@ export function ChatSettingsPanel({
const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);
const specDraftNMax = useChatRuntimeStore((s) => s.specDraftNMax);
const nParallel = useChatRuntimeStore((s) => s.nParallel);
+ const nBatch = useChatRuntimeStore((s) => s.nBatch);
+ const nUbatch = useChatRuntimeStore((s) => s.nUbatch);
const speculativeType = useChatRuntimeStore((s) => s.speculativeType);
const specFallbackReason = useChatRuntimeStore((s) => s.specFallbackReason);
const specDrafterKind = useChatRuntimeStore((s) => s.specDrafterKind);
@@ -650,6 +652,8 @@ export function ChatSettingsPanel({
speculativeType,
specDraftNMax,
nParallel,
+ nBatch,
+ nUbatch,
params.maxSeqLength,
]);
const activePresetLoadSummary = useMemo(
@@ -670,6 +674,8 @@ export function ChatSettingsPanel({
speculativeType,
specDraftNMax,
nParallel,
+ nBatch,
+ nUbatch,
params.maxSeqLength,
],
);
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 8f921e130b1..c8c2f3007a8 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -783,6 +783,14 @@ export function useChatModelRuntime() {
typeof selection !== "string" && selection.previousConfig
? (selection.previousConfig.nParallel ?? null)
: useChatRuntimeStore.getState().nParallel;
+ const previousNBatch =
+ typeof selection !== "string" && selection.previousConfig
+ ? (selection.previousConfig.nBatch ?? null)
+ : useChatRuntimeStore.getState().nBatch;
+ const previousNUbatch =
+ typeof selection !== "string" && selection.previousConfig
+ ? (selection.previousConfig.nUbatch ?? null)
+ : useChatRuntimeStore.getState().nUbatch;
// Same reason: the rollback echo would overwrite an edit staged against it.
const previousMlxKvBits =
typeof selection !== "string" && selection.previousConfig
@@ -921,6 +929,10 @@ export function useChatModelRuntime() {
pendingLoadConfig?.specDraftNMax ?? stateBeforeUnload.specDraftNMax;
let loadNParallel =
pendingLoadConfig?.nParallel ?? stateBeforeUnload.nParallel;
+ let loadNBatch =
+ pendingLoadConfig?.nBatch ?? stateBeforeUnload.nBatch;
+ let loadNUbatch =
+ pendingLoadConfig?.nUbatch ?? stateBeforeUnload.nUbatch;
try {
// Lightweight pre-flight validation: avoid unloading a working model
// if the new identifier is clearly invalid (e.g. bad HF id / path).
@@ -956,6 +968,12 @@ export function useChatModelRuntime() {
const validateNParallel = resetsPerModelSettings
? (pendingLoadConfig?.nParallel ?? null)
: loadNParallel;
+ const validateNBatch = resetsPerModelSettings
+ ? (pendingLoadConfig?.nBatch ?? null)
+ : loadNBatch;
+ const validateNUbatch = resetsPerModelSettings
+ ? (pendingLoadConfig?.nUbatch ?? null)
+ : loadNUbatch;
const validateMaxSeqLength = resolveFitMaxSeqLength(
isGguf,
loadGpuMemoryMode,
@@ -991,6 +1009,13 @@ export function useChatModelRuntime() {
// split 409s during training even when it fits.
gpu_layers: validateGpuLayers,
n_parallel: validateNParallel,
+ // omitted when blank, like the load payload below
+ ...(validateNBatch != null
+ ? { n_batch: validateNBatch }
+ : {}),
+ ...(validateNUbatch != null
+ ? { n_ubatch: validateNUbatch }
+ : {}),
}
: {}),
});
@@ -1081,6 +1106,10 @@ export function useChatModelRuntime() {
// unless its staged config overrides it.
nParallel: null,
loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
// Per-model GPU knobs must not follow onto a different model
// (gpuMemoryMode is a standing preference and is kept).
selectedGpuIds: null,
@@ -1098,6 +1127,8 @@ export function useChatModelRuntime() {
: persistedSpeculativeType;
loadSpecDraftNMax = pendingLoadConfig?.specDraftNMax ?? null;
loadNParallel = pendingLoadConfig?.nParallel ?? null;
+ loadNBatch = pendingLoadConfig?.nBatch ?? null;
+ loadNUbatch = pendingLoadConfig?.nUbatch ?? null;
// Both payload-only. The store keeps its values: a width is dormant
// preset state off MLX, and a completed load rewrites both anyway.
loadMlxKvBits = pendingLoadConfig?.mlxKvBits ?? null;
@@ -1182,6 +1213,11 @@ export function useChatModelRuntime() {
spec_draft_n_max: loadSpecDraftNMax,
// GGUF-only: slots mean nothing for a transformers load.
n_parallel: isGguf ? loadNParallel : null,
+ // omitted when blank: a null counts as set and strips inherited -b / -ub
+ ...(isGguf && loadNBatch != null ? { n_batch: loadNBatch } : {}),
+ ...(isGguf && loadNUbatch != null
+ ? { n_ubatch: loadNUbatch }
+ : {}),
tensor_parallel: loadTensorParallel,
gpu_memory_mode: loadGpuMemoryMode,
gpu_layers: loadGpuLayers,
@@ -1255,6 +1291,17 @@ export function useChatModelRuntime() {
!(loadResponse.is_diffusion ?? false)
? (loadNParallel ?? null)
: null;
+ // same rule for the batch sizes: gguf-only llama-server flags
+ const committedNBatch =
+ (loadResponse.is_gguf ?? false) &&
+ !(loadResponse.is_diffusion ?? false)
+ ? (loadNBatch ?? null)
+ : null;
+ const committedNUbatch =
+ (loadResponse.is_gguf ?? false) &&
+ !(loadResponse.is_diffusion ?? false)
+ ? (loadNUbatch ?? null)
+ : null;
const nativeCtx = loadResponse.is_gguf
? (loadResponse.context_length ?? 131072)
: null;
@@ -1337,6 +1384,10 @@ export function useChatModelRuntime() {
// adopting it would pin a blank "server default" control.
nParallel: committedSlots,
loadedNParallel: committedSlots,
+ nBatch: committedNBatch,
+ loadedNBatch: committedNBatch,
+ nUbatch: committedNUbatch,
+ loadedNUbatch: committedNUbatch,
customContextLength: keepCustomCtx,
loadedCustomContextLength: keepCustomCtx,
defaultChatTemplate: loadResponse.chat_template ?? null,
@@ -1452,6 +1503,13 @@ export function useChatModelRuntime() {
spec_draft_n_max:
stateBeforeUnload.loadedSpecDraftNMax,
n_parallel: stateBeforeUnload.loadedNParallel,
+ // omit unset fields: a null counts as set and would strip the previous server's extras
+ ...(stateBeforeUnload.loadedNBatch != null
+ ? { n_batch: stateBeforeUnload.loadedNBatch }
+ : {}),
+ ...(stateBeforeUnload.loadedNUbatch != null
+ ? { n_ubatch: stateBeforeUnload.loadedNUbatch }
+ : {}),
// Restore the previous model in the split mode it was running,
// not the default layer split.
tensor_parallel: stateBeforeUnload.loadedTensorParallel ?? false,
@@ -1483,6 +1541,10 @@ export function useChatModelRuntime() {
// Control keeps its intent; only the baseline takes the echo.
nParallel: previousNParallel,
loadedNParallel: stateBeforeUnload.loadedNParallel ?? null,
+ nBatch: previousNBatch,
+ loadedNBatch: stateBeforeUnload.loadedNBatch ?? null,
+ nUbatch: previousNUbatch,
+ loadedNUbatch: stateBeforeUnload.loadedNUbatch ?? null,
loadedSpeculativeType: rollbackSpeculativeType,
loadedSpecDraftNMax:
rollbackResponse.spec_draft_n_max ?? null,
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 2f8e211a43c..ad0b63f64aa 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -28,6 +28,7 @@ import {
} from "../types/api";
import type { ChatModelSummary } from "../types/runtime";
import { sameGpuSelection } from "@/hooks/gpu-selection";
+import { resolveBatchSizeSeed } from "./resolve-batch-size-seed";
import { resolveChatTemplateSeed } from "./resolve-chat-template-seed";
type LocalReasoningEffort = Extract<ReasoningEffort, "low" | "medium" | "high">;
@@ -214,13 +215,39 @@ export function applyActiveModelStatusToStore(
// repo id, and the plain lookup misses that record.
const slotsUnseeded =
prevState.loadedNParallel === null && prevState.nParallel === null;
+ // same rule for the batch-size pair
+ const batchesUnseeded =
+ prevState.loadedNBatch === null &&
+ prevState.nBatch === null &&
+ prevState.loadedNUbatch === null &&
+ prevState.nUbatch === null;
const remembered =
- status.is_gguf && (slotsUnseeded || slotsModelChanged)
+ status.is_gguf && (slotsUnseeded || batchesUnseeded || slotsModelChanged)
? resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)
: null;
const rememberedNParallel = remembered?.remembered
? (remembered.config.nParallel ?? null)
: null;
+ const rememberedNBatch = remembered?.remembered
+ ? (remembered.config.nBatch ?? null)
+ : null;
+ const rememberedNUbatch = remembered?.remembered
+ ? (remembered.config.nUbatch ?? null)
+ : null;
+ const nBatchSeed = resolveBatchSizeSeed({
+ incoming: status.requested_n_batch,
+ isGguf: status.is_gguf ?? true,
+ previous: { value: prevState.nBatch, loaded: prevState.loadedNBatch },
+ seedLoadParams,
+ modelChanged: slotsModelChanged,
+ });
+ const nUbatchSeed = resolveBatchSizeSeed({
+ incoming: status.requested_n_ubatch,
+ isGguf: status.is_gguf ?? true,
+ previous: { value: prevState.nUbatch, loaded: prevState.loadedNUbatch },
+ seedLoadParams,
+ modelChanged: slotsModelChanged,
+ });
// A Manual + Auto-layers load sent its positive context pin as max_seq_length,
// and status only exposes the RESOLVED context; re-seed the pin from the
// requested value (parity with the load paths' keepCustomCtx). Baselines
@@ -424,6 +451,31 @@ export function applyActiveModelStatusToStore(
rememberedNParallel === status.requested_parallel_slots && {
nParallel: rememberedNParallel,
}),
+ // one rule per batch pair, see resolveBatchSizeSeed
+ ...("loaded" in nBatchSeed && { loadedNBatch: nBatchSeed.loaded ?? null }),
+ ...("value" in nBatchSeed && { nBatch: nBatchSeed.value ?? null }),
+ ...("loaded" in nUbatchSeed && {
+ loadedNUbatch: nUbatchSeed.loaded ?? null,
+ }),
+ ...("value" in nUbatchSeed && { nUbatch: nUbatchSeed.value ?? null }),
+ // A swap under this tab resets the controls too, but that clear belongs INSIDE
+ // resolveBatchSizeSeed (modelChanged), not after it: unlike the slot count above,
+ // the batch echo is the REQUESTED size, so a blanket null here would also discard
+ // the value the seed just adopted from the new model's own echo. The control would
+ // then read "default" while the server runs an explicit -b / -ub, and the next
+ // Reload or Apply, which omits a blank field, would silently revert it.
+ ...(seedLoadParams &&
+ (batchesUnseeded || slotsModelChanged) &&
+ rememberedNBatch != null &&
+ rememberedNBatch === status.requested_n_batch && {
+ nBatch: rememberedNBatch,
+ }),
+ ...(seedLoadParams &&
+ (batchesUnseeded || slotsModelChanged) &&
+ rememberedNUbatch != null &&
+ rememberedNUbatch === status.requested_n_ubatch && {
+ nUbatch: rememberedNUbatch,
+ }),
// Re-seed on first hydration, model/variant changes, or a same-model backend
// placement change. gpuStatusFields preserves dirty local edits in the last
// case while advancing their loaded baselines.
diff --git a/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts b/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts
new file mode 100644
index 00000000000..f67a45614f5
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// what a fresh /api/inference/status does to one batch control/baseline pair
+
+export interface BatchSizeSeedState {
+ /** The editable control: what the next load or Apply would send. */
+ value: number | null;
+ /** What the resident server was invoked with, as this tab last saw it. */
+ loaded: number | null;
+}
+
+/** The subset of the pair to write back; empty means leave the store alone. */
+export type BatchSizeSeed = Partial<BatchSizeSeedState>;
+
+export function resolveBatchSizeSeed(options: {
+ /** ``status.requested_n_batch`` / ``_n_ubatch``; undefined on a backend that omits the field. */
+ incoming: number | null | undefined;
+ /** ``status.is_gguf``: a non-GGUF (or diffusion, which echoes null) never has the flag. */
+ isGguf: boolean;
+ previous: BatchSizeSeedState;
+ /** No load of this tab's own is in flight (``!modelLoading``). */
+ seedLoadParams: boolean;
+ /** The model/variant changed underneath this tab. Nothing staged against the
+ * previous model may survive it, so the new model's echo is the whole truth:
+ * the control adopts it even when a pending edit would otherwise hold, and
+ * even when the new model happens to report the count the old one ran. */
+ modelChanged?: boolean;
+}): BatchSizeSeed {
+ const {
+ incoming,
+ isGguf,
+ previous,
+ seedLoadParams,
+ modelChanged = false,
+ } = options;
+ // while a load is in flight performLoad owns the load params
+ if (!seedLoadParams) {
+ return {};
+ }
+ // a non-gguf has no batch flags; an absent field is an older backend saying nothing
+ const effective = isGguf ? incoming : null;
+ if (effective === undefined) {
+ // Nothing to adopt, and nothing staged or recorded against the model that just
+ // left may survive it: the baseline goes with the control, or a later rollback
+ // resends the departed model's batch as if the new server were running it.
+ return modelChanged ? { value: null, loaded: null } : {};
+ }
+ // steady echo: an ordinary poll must not touch anything
+ if (previous.loaded === effective && !modelChanged) {
+ return {};
+ }
+ // the baseline is a fact about the running server; the control follows it only while clean
+ const controlIsClean = modelChanged || previous.value === previous.loaded;
+ return {
+ loaded: effective,
+ ...(controlIsClean ? { value: effective } : {}),
+ };
+}
diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.ts
index 293fd97a00a..7815204ea1b 100644
--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts
+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts
@@ -12,6 +12,8 @@ import {
DEFAULT_MAX_SEQ_LENGTH,
KV_CACHE_DTYPES,
MLX_KV_BITS,
+ N_BATCH_MAX,
+ N_BATCH_MIN,
N_PARALLEL_MAX,
N_PARALLEL_MIN,
normalizeMaxSeqLength,
@@ -37,6 +39,8 @@ export type PresetLoadConfig = Pick<
| "speculativeType"
| "specDraftNMax"
| "nParallel"
+ | "nBatch"
+ | "nUbatch"
| "tensorParallel"
| "gpuMemoryMode"
| "gpuLayers"
@@ -54,6 +58,8 @@ export const EMPTY_PRESET_LOAD_CONFIG: PresetLoadConfig = {
speculativeType: null,
specDraftNMax: null,
nParallel: null,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
};
@@ -129,6 +135,14 @@ export function normalizePresetLoadConfig(
Math.min(N_PARALLEL_MAX, Math.round(partial.nParallel)),
)
: null,
+ nBatch:
+ typeof partial.nBatch === "number" && Number.isFinite(partial.nBatch)
+ ? Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, Math.round(partial.nBatch)))
+ : null,
+ nUbatch:
+ typeof partial.nUbatch === "number" && Number.isFinite(partial.nUbatch)
+ ? Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, Math.round(partial.nUbatch)))
+ : null,
tensorParallel:
typeof partial.tensorParallel === "boolean"
? partial.tensorParallel
@@ -176,6 +190,8 @@ export function capturePresetLoadConfig(): PresetLoadConfig | undefined {
speculativeType: normalizeSpeculativeType(snapshot.speculativeType),
specDraftNMax: snapshot.specDraftNMax ?? null,
nParallel: snapshot.nParallel ?? null,
+ nBatch: snapshot.nBatch ?? null,
+ nUbatch: snapshot.nUbatch ?? null,
tensorParallel: snapshot.tensorParallel ?? false,
...(snapshot.gpuMemoryMode === "manual"
? { gpuMemoryMode: "manual" as const }
@@ -232,6 +248,8 @@ export function applyPresetLoadConfig(
speculativeType: config.speculativeType ?? null,
specDraftNMax: config.specDraftNMax ?? null,
nParallel: config.nParallel ?? null,
+ nBatch: config.nBatch ?? null,
+ nUbatch: config.nUbatch ?? null,
tensorParallel: config.tensorParallel ?? false,
chatTemplateOverride: null,
gpuMemoryMode: config.gpuMemoryMode,
@@ -264,6 +282,12 @@ export function formatPresetLoadConfigSummary(
if (config.nParallel != null) {
parts.push(`${config.nParallel} slots`);
}
+ if (config.nBatch != null) {
+ parts.push(`Batch ${config.nBatch}`);
+ }
+ if (config.nUbatch != null) {
+ parts.push(`uBatch ${config.nUbatch}`);
+ }
if (config.gpuMemoryMode === "manual") {
parts.push("GPU manual");
}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 2fff76adc64..6aef0b8debc 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -1351,6 +1351,13 @@ export function SharedComposer({
gpu_layers: effectiveGpuLayers,
// Slots scale the KV estimate; keep validate sized like the load.
n_parallel: ownConfig.nParallel ?? null,
+ // omitted when blank: a null counts as set and strips inherited -b / -ub
+ ...(ownConfig.nBatch != null
+ ? { n_batch: ownConfig.nBatch }
+ : {}),
+ ...(ownConfig.nUbatch != null
+ ? { n_ubatch: ownConfig.nUbatch }
+ : {}),
}
: {}),
});
@@ -1426,6 +1433,12 @@ export function SharedComposer({
tensor_split: compareLoadKnobs.splitRatio ?? undefined,
gpu_ids: effectiveSelectedGpuIds ?? undefined,
n_parallel: ownConfig.nParallel ?? null,
+ ...(ownConfig.nBatch != null
+ ? { n_batch: ownConfig.nBatch }
+ : {}),
+ ...(ownConfig.nUbatch != null
+ ? { n_ubatch: ownConfig.nUbatch }
+ : {}),
}
: {}),
});
@@ -1463,6 +1476,15 @@ export function SharedComposer({
targetIsGguf && !(resp.is_diffusion ?? false)
? (ownConfig.nParallel ?? null)
: null;
+ // same rule for the batch sizes
+ const committedNBatch =
+ targetIsGguf && !(resp.is_diffusion ?? false)
+ ? (ownConfig.nBatch ?? null)
+ : null;
+ const committedNUbatch =
+ targetIsGguf && !(resp.is_diffusion ?? false)
+ ? (ownConfig.nUbatch ?? null)
+ : null;
useChatRuntimeStore.setState({
supportsReasoning: resp.supports_reasoning ?? false,
reasoningAlwaysOn: resp.reasoning_always_on ?? false,
@@ -1475,6 +1497,10 @@ export function SharedComposer({
// Click-time value, not the resolved echo (see the single-model load).
nParallel: committedSlots,
loadedNParallel: committedSlots,
+ nBatch: committedNBatch,
+ loadedNBatch: committedNBatch,
+ nUbatch: committedNUbatch,
+ loadedNUbatch: committedNUbatch,
tensorParallel: resp.tensor_parallel ?? false,
loadedTensorParallel: resp.tensor_parallel ?? false,
defaultChatTemplate: resp.chat_template ?? null,
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 9abef48f720..9193b98b2b3 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -1065,6 +1065,14 @@ type ChatRuntimeStore = {
/** Slots the last successful load sent (null = default); the rollback
* re-sends it so a failed switch can't lose the override. */
loadedNParallel: number | null;
+ /** user --batch-size override for gguf loads (null = llama.cpp default 2048) */
+ nBatch: number | null;
+ /** batch size the last successful load sent (null = default) */
+ loadedNBatch: number | null;
+ /** user --ubatch-size override for gguf loads (null = llama.cpp default 512) */
+ nUbatch: number | null;
+ /** micro-batch size the last successful load sent (null = default) */
+ loadedNUbatch: number | null;
/** Tensor-parallel split (--split-mode tensor) toggle, GGUF multi-GPU only. */
tensorParallel: boolean;
/** Backend-reported tensor-parallel state; null until first hydrated. */
@@ -1617,6 +1625,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedSpecDraftNMax: null,
nParallel: null,
loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
tensorParallel: false,
loadedTensorParallel: null,
gpuMemoryMode: readPersistedGpuMemoryMode(),
@@ -2074,6 +2086,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedSpecDraftNMax: null,
nParallel: null,
loadedNParallel: null,
+ nBatch: null,
+ loadedNBatch: null,
+ nUbatch: null,
+ loadedNUbatch: null,
tensorParallel: false,
loadedTensorParallel: null,
// Standing preference: survives unload, unlike the per-model knobs above.
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index a12834f640f..94525b0d1ca 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -72,6 +72,10 @@ export interface LoadModelRequest {
* the launch default. The VRAM fitter may launch fewer to stay on GPU.
*/
n_parallel?: number | null;
+ /** prompt batch size (--batch-size), 1..65536; omit/null = llama.cpp default 2048, gguf only */
+ n_batch?: number | null;
+ /** prompt micro-batch size (--ubatch-size), 1..65536; omit/null = llama.cpp default 512, capped at the batch size */
+ n_ubatch?: number | null;
/**
* Split the model across GPUs by tensor (--split-mode tensor) instead
* of by layer for GGUF models. Multi-GPU only; no effect on a single GPU.
@@ -231,6 +235,10 @@ export interface LoadModelResponse {
/** Slots llama-server actually runs, after any fit-time reduction. Null for
* non-GGUF loads. */
parallel_slots?: number | null;
+ /** batch size (--batch-size) the load was invoked with; null = default */
+ requested_n_batch?: number | null;
+ /** micro-batch size (--ubatch-size) the load was invoked with; null = default */
+ requested_n_ubatch?: number | null;
}
export interface UnloadModelRequest {
@@ -310,6 +318,10 @@ export interface InferenceStatusResponse {
/** Slots llama-server actually runs, after any fit-time reduction. Null when
* no GGUF model is loaded. */
parallel_slots?: number | null;
+ /** batch size (--batch-size) the active load was invoked with; null = default */
+ requested_n_batch?: number | null;
+ /** micro-batch size (--ubatch-size) the active load was invoked with; null = default */
+ requested_n_ubatch?: number | null;
n_layers?: number | null;
/** Model's MoE expert-layer count (the n_cpu_moe ceiling); 0 if not MoE. */
n_moe_layers?: number;
diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.ts
index d9320473f2d..18a5fa58b23 100644
--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts
+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts
@@ -34,6 +34,10 @@ export interface ApiModelOverride {
// biome-ignore lint/style/useNamingConvention: API schema
n_parallel?: number;
// biome-ignore lint/style/useNamingConvention: API schema
+ n_batch?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ n_ubatch?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
tensor_parallel?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
chat_template_override?: string;
@@ -107,6 +111,13 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {
if (config.nParallel && config.nParallel > 0) {
payload.n_parallel = config.nParallel;
}
+ // blank follows the llama.cpp defaults (2048 / 512)
+ if (config.nBatch && config.nBatch > 0) {
+ payload.n_batch = config.nBatch;
+ }
+ if (config.nUbatch && config.nUbatch > 0) {
+ payload.n_ubatch = config.nUbatch;
+ }
if (config.tensorParallel) {
payload.tensor_parallel = true;
}
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 08734e70ad6..7ad168062fd 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
@@ -59,6 +59,9 @@ import {
MAX_SEQ_LENGTH_MIN,
MAX_SEQ_LENGTH_STEP,
MLX_KV_BITS,
+ N_BATCH_LLAMA_DEFAULT,
+ N_BATCH_MAX,
+ N_BATCH_MIN,
N_PARALLEL_MAX,
N_PARALLEL_MIN,
type PerModelConfig,
@@ -111,6 +114,8 @@ function hasNonDefaultAdvanced(config: PerModelConfig): boolean {
(config.speculativeType ?? "auto") !== "auto" ||
config.specDraftNMax != null ||
config.nParallel != null ||
+ config.nBatch != null ||
+ config.nUbatch != null ||
config.tensorParallel ||
config.chatTemplateOverride != null ||
(config.gpuMemoryMode ?? "auto") !== "auto" ||
@@ -133,6 +138,8 @@ function withoutUnsupportedDiffusionSettings(
config.gpuLayers == null &&
config.nCpuMoe == null &&
!config.tensorParallel &&
+ config.nBatch == null &&
+ config.nUbatch == null &&
!hasUnsupportedGpuPick
) {
return config;
@@ -143,6 +150,9 @@ function withoutUnsupportedDiffusionSettings(
gpuLayers: undefined,
nCpuMoe: undefined,
tensorParallel: false,
+ // the diffusion runner ignores the llama-server batch flags
+ nBatch: null,
+ nUbatch: null,
...(hasUnsupportedGpuPick
? {
selectedGpuIds: undefined,
@@ -628,6 +638,28 @@ function GgufAdvancedSettings({
gpuLayersInputRef?: Ref<NumericValueInputHandle>;
moeLayersInputRef?: Ref<NumericValueInputHandle>;
}) {
+ const batchAdviceId = useId();
+ const ubatchAdviceId = useId();
+ // llama-server aborts below 2 (GGML_ASSERT(n_tokens_all <= cparams.n_batch)) and below
+ // the slot count (GGML_ASSERT(n_outputs_max <= cparams.n_outputs_max)), so the loader
+ // raises the emitted value to max(slots, 2). Surfaced so the number typed here is not
+ // silently different from the one that runs. With Slots blank the count is the server
+ // default this page cannot see, so only the hard floor of 2 is asserted.
+ const batchFloor = Math.max(2, config.nParallel ?? 2);
+ const batchBelowFloor = config.nBatch != null && config.nBatch < batchFloor;
+ // llama.cpp runs at min(batch, ubatch) and the /status echo is the REQUESTED size, so
+ // the control would otherwise keep showing a value the server never used (batch 8 /
+ // ubatch 4096 measured 8.8x slower). Against the EMITTED batch, or the two advisories
+ // contradict: batch 4 / slots 8 launches at 8, so saying it runs at 4 is wrong. A blank
+ // batch emits no flag and runs llama.cpp's own 2048, which caps the micro-batch just the
+ // same, so it is the default and not "unbounded". Extras or LLAMA_ARG_BATCH can move
+ // that, but this page cannot see them, the same limit the slot floor above carries.
+ const effectiveBatch =
+ config.nBatch != null
+ ? Math.max(config.nBatch, batchFloor)
+ : N_BATCH_LLAMA_DEFAULT;
+ const ubatchExceedsBatch =
+ config.nUbatch != null && config.nUbatch > effectiveBatch;
return (
<>
<div className={ROW_CLASS}>
@@ -778,6 +810,99 @@ function GgufAdvancedSettings({
/>
</div>
+ {!isDiffusion && (
+ <div className="space-y-1">
+ <div className={ROW_CLASS}>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className={LABEL_CLASS}>Batch Size</span>
+ <InfoHint>
+ Logical prompt batch size (--batch-size). Leave blank for the
+ llama.cpp default (2048). Rarely needs changing; the micro-batch
+ below is what usually matters.
+ </InfoHint>
+ </div>
+ <input
+ type="number"
+ min={N_BATCH_MIN}
+ max={N_BATCH_MAX}
+ step={1}
+ value={config.nBatch ?? ""}
+ placeholder="auto"
+ onChange={(event) => {
+ const raw = event.target.value;
+ if (raw === "") {
+ update({ nBatch: null });
+ return;
+ }
+ const parsed = Number.parseInt(raw, 10);
+ if (Number.isFinite(parsed)) {
+ update({
+ nBatch: Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, parsed)),
+ });
+ }
+ }}
+ aria-label="Prompt batch size"
+ aria-describedby={batchBelowFloor ? batchAdviceId : undefined}
+ className={NUMBER_INPUT_CLASS}
+ />
+ </div>
+ {batchBelowFloor && (
+ <p id={batchAdviceId} className="text-ui-12 text-muted-foreground">
+ Too small for llama-server, so the load will raise it to {batchFloor}.
+ {config.nParallel != null && config.nParallel > 2
+ ? " It needs one output slot per parallel slot."
+ : " It cannot run a batch below 2."}
+ </p>
+ )}
+ </div>
+ )}
+
+ {!isDiffusion && (
+ <div className="space-y-1">
+ <div className={ROW_CLASS}>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className={LABEL_CLASS}>Micro-batch Size</span>
+ <InfoHint>
+ Physical prompt micro-batch size (--ubatch-size). Leave blank for
+ the llama.cpp default (512). Larger values speed up prompt
+ processing but use more VRAM for the compute buffer; capped at the
+ batch size.
+ </InfoHint>
+ </div>
+ <input
+ type="number"
+ min={N_BATCH_MIN}
+ max={N_BATCH_MAX}
+ step={1}
+ value={config.nUbatch ?? ""}
+ placeholder="auto"
+ onChange={(event) => {
+ const raw = event.target.value;
+ if (raw === "") {
+ update({ nUbatch: null });
+ return;
+ }
+ const parsed = Number.parseInt(raw, 10);
+ if (Number.isFinite(parsed)) {
+ update({
+ nUbatch: Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, parsed)),
+ });
+ }
+ }}
+ aria-label="Prompt micro-batch size"
+ aria-describedby={ubatchExceedsBatch ? ubatchAdviceId : undefined}
+ className={NUMBER_INPUT_CLASS}
+ />
+ </div>
+ {ubatchExceedsBatch && (
+ <p id={ubatchAdviceId} className="text-ui-12 text-muted-foreground">
+ Micro-batch is larger than the batch size, so llama.cpp will run at{" "}
+ {effectiveBatch}. Raise the batch size to use {config.nUbatch}.
+ </p>
+ )}
+ </div>
+ )}
+
<div className={ROW_CLASS}>
<div className="flex min-w-0 items-center gap-1.5">
<span className={LABEL_CLASS}>Tensor Parallelism</span>
@@ -1026,7 +1151,10 @@ export function ModelConfigPage({
const stagedMetadataPending =
contextFetchKey != null &&
stagedDims == null &&
- (config.gpuMemoryMode === "manual" || config.selectedGpuIds != null);
+ (config.gpuMemoryMode === "manual" ||
+ config.selectedGpuIds != null ||
+ config.nBatch != null ||
+ config.nUbatch != null);
const gpuIndexKind =
pinnableGpuContext(gpuDevices, resolvedIsDiffusion).indexKind ?? null;
const update = (patch: Partial<PerModelConfig>) =>
diff --git a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
index bae0c7a1e16..a05aa33afec 100644
--- a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
+++ b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
@@ -26,6 +26,8 @@ export function useActiveModelConfig(): ActiveModelConfigState {
const speculativeType = useChatRuntimeStore((s) => s.speculativeType);
const specDraftNMax = useChatRuntimeStore((s) => s.specDraftNMax);
const nParallel = useChatRuntimeStore((s) => s.nParallel);
+ const nBatch = useChatRuntimeStore((s) => s.nBatch);
+ const nUbatch = useChatRuntimeStore((s) => s.nUbatch);
const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);
const chatTemplateOverride = useChatRuntimeStore(
(s) => s.chatTemplateOverride,
@@ -61,6 +63,8 @@ export function useActiveModelConfig(): ActiveModelConfigState {
speculativeType: speculativeType ?? "auto",
specDraftNMax: specDraftNMax ?? null,
nParallel: nParallel ?? null,
+ nBatch: nBatch ?? null,
+ nUbatch: nUbatch ?? null,
tensorParallel: tensorParallel ?? false,
chatTemplateOverride: chatTemplateOverride ?? null,
};
@@ -85,6 +89,8 @@ export function useActiveModelConfig(): ActiveModelConfigState {
speculativeType,
specDraftNMax,
nParallel,
+ nBatch,
+ nUbatch,
tensorParallel,
chatTemplateOverride,
gpuMemoryMode,
diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
index 55754e310e3..f527b014e8d 100644
--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
@@ -56,6 +56,9 @@ export function applyPerModelConfigToRuntime(
readPersistedSpeculativeType(),
specDraftNMax: config.specDraftNMax ?? null,
nParallel: config.nParallel ?? null,
+ // the diffusion runner ignores the llama-server batch flags
+ nBatch: options.isDiffusion ? null : (config.nBatch ?? null),
+ nUbatch: options.isDiffusion ? null : (config.nUbatch ?? null),
tensorParallel: options.isDiffusion
? false
: (config.tensorParallel ?? false),
@@ -105,6 +108,8 @@ export function currentRuntimePerModelConfig(
speculativeType: normalizeSpeculativeType(s.speculativeType),
specDraftNMax: s.specDraftNMax ?? null,
nParallel: s.nParallel ?? null,
+ nBatch: s.nBatch ?? null,
+ nUbatch: s.nUbatch ?? null,
tensorParallel: s.tensorParallel ?? false,
chatTemplateOverride: cleanTemplate(s.chatTemplateOverride),
// Snapshot the live GPU knobs too so a failed switch rolls the previous
@@ -132,6 +137,8 @@ export function perModelConfigsEqual(
normalizeSpeculativeType(b.speculativeType) &&
(a.specDraftNMax ?? null) === (b.specDraftNMax ?? null) &&
(a.nParallel ?? null) === (b.nParallel ?? null) &&
+ (a.nBatch ?? null) === (b.nBatch ?? null) &&
+ (a.nUbatch ?? null) === (b.nUbatch ?? null) &&
Boolean(a.tensorParallel) === Boolean(b.tensorParallel) &&
cleanTemplate(a.chatTemplateOverride) ===
cleanTemplate(b.chatTemplateOverride) &&
diff --git a/studio/frontend/src/features/model-picker/model-config/config-signature.ts b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
index 8131f33c72c..8d3d1cf8348 100644
--- a/studio/frontend/src/features/model-picker/model-config/config-signature.ts
+++ b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
@@ -55,6 +55,8 @@ export function loadedConfigSignature(
config.speculativeType ?? "",
config.specDraftNMax ?? "",
config.nParallel ?? "",
+ config.nBatch ?? "",
+ config.nUbatch ?? "",
config.tensorParallel ? "1" : "0",
config.chatTemplateOverride == null
? ""
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index 70220ad04f8..c7165409403 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -21,6 +21,8 @@ export interface PerModelConfig {
speculativeType: string | null;
specDraftNMax: number | null;
nParallel: number | null;
+ nBatch: number | null;
+ nUbatch: number | null;
tensorParallel: boolean;
chatTemplateOverride: string | null;
// GPU Memory controls (per-model, GGUF-only), optional so older blobs still parse. null/absent
@@ -40,6 +42,8 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {
speculativeType: null,
specDraftNMax: null,
nParallel: null,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
chatTemplateOverride: null,
};
@@ -48,6 +52,13 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {
export const N_PARALLEL_MIN = 1;
export const N_PARALLEL_MAX = 64;
+// mirrors llama_server_args.py BATCH_MIN/MAX; null = follow the llama.cpp defaults (2048 / 512)
+export const N_BATCH_MIN = 1;
+export const N_BATCH_MAX = 65536;
+// llama.cpp's own --batch-size default (_DEFAULT_LLAMA_N_BATCH), which a blank control
+// runs at: it still caps the micro-batch, so advisories have to reckon with it.
+export const N_BATCH_LLAMA_DEFAULT = 2048;
+
export const MAX_SEQ_LENGTH_MIN = 128;
export const MAX_SEQ_LENGTH_MAX = 1048576;
export const MAX_SEQ_LENGTH_STEP = 128;
@@ -118,13 +129,15 @@ export {
const STORAGE_KEY = "unsloth_model_configs";
const LEGACY_STORAGE_KEY = "unsloth_load_settings";
const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";
-const STORAGE_SCHEMA_VERSION = 1;
+// v2 added nBatch / nUbatch; a v1 client's normalizer would rewrite them away
+const STORAGE_SCHEMA_VERSION = 2;
+const PRE_BATCH_SCHEMA_VERSION = 1;
const MAX_ENTRIES = 500;
const MAX_PER_MODEL_CONFIG_STORAGE_BYTES = 1024 * 1024;
export const MAX_CHAT_TEMPLATE_BYTES = 65_536;
type StoredPerModelConfig = PerModelConfig & {
- version: typeof STORAGE_SCHEMA_VERSION;
+ version: number;
};
type StoredMap = Record<string, PerModelConfig | StoredPerModelConfig>;
type RawConfig = Partial<PerModelConfig> & { version?: unknown };
@@ -138,6 +151,8 @@ const STORED_CONFIG_FIELDS = new Set([
"speculativeType",
"specDraftNMax",
"nParallel",
+ "nBatch",
+ "nUbatch",
"tensorParallel",
"chatTemplateOverride",
"gpuMemoryMode",
@@ -623,6 +638,14 @@ function normalizeV1(partial: RawConfig): PerModelConfig {
Math.min(N_PARALLEL_MAX, Math.round(partial.nParallel)),
)
: null,
+ nBatch:
+ typeof partial.nBatch === "number" && Number.isFinite(partial.nBatch)
+ ? Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, Math.round(partial.nBatch)))
+ : null,
+ nUbatch:
+ typeof partial.nUbatch === "number" && Number.isFinite(partial.nUbatch)
+ ? Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, Math.round(partial.nUbatch)))
+ : null,
tensorParallel:
typeof partial.tensorParallel === "boolean"
? partial.tensorParallel
@@ -657,9 +680,15 @@ function normalize(raw: unknown): PerModelConfig {
}
function toStoredConfig(config: PerModelConfig): StoredPerModelConfig {
+ const normalized = normalize(config);
+ // records without the v2-only batch fields keep v1 so older clients can still rewrite them
+ const version =
+ normalized.nBatch != null || normalized.nUbatch != null
+ ? STORAGE_SCHEMA_VERSION
+ : PRE_BATCH_SCHEMA_VERSION;
return {
- version: STORAGE_SCHEMA_VERSION,
- ...normalize(config),
+ version,
+ ...normalized,
};
}
@@ -770,6 +799,8 @@ export function isDefaultConfig(config: PerModelConfig): boolean {
config.speculativeType === DEFAULT_PER_MODEL_CONFIG.speculativeType &&
config.specDraftNMax == null &&
config.nParallel == null &&
+ config.nBatch == null &&
+ config.nUbatch == null &&
Boolean(config.tensorParallel) ===
Boolean(DEFAULT_PER_MODEL_CONFIG.tensorParallel) &&
(config.chatTemplateOverride ?? null) === null &&
diff --git a/studio/frontend/tests/adopt-legacy-config-key.test.ts b/studio/frontend/tests/adopt-legacy-config-key.test.ts
index 226b2f61558..16ee3686981 100644
--- a/studio/frontend/tests/adopt-legacy-config-key.test.ts
+++ b/studio/frontend/tests/adopt-legacy-config-key.test.ts
@@ -38,6 +38,8 @@ function config(
speculativeType: null,
specDraftNMax: null,
nParallel: null,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
chatTemplateOverride,
};
diff --git a/studio/frontend/tests/batch-schema-version.test.ts b/studio/frontend/tests/batch-schema-version.test.ts
new file mode 100644
index 00000000000..0c12d7572be
--- /dev/null
+++ b/studio/frontend/tests/batch-schema-version.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const { savePerModelConfig, resolveInitialConfig } = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+
+const MODEL = "unsloth/Repo-GGUF";
+
+function config(nBatch: number | null, nUbatch: number | null = null) {
+ return {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: 4,
+ nBatch,
+ nUbatch,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ };
+}
+
+function storedVersion(): number {
+ const map = JSON.parse(store.get("unsloth_model_configs") ?? "{}");
+ const [entry] = Object.values(map) as { version: number }[];
+ return entry.version;
+}
+
+test("a record with batch fields is stamped v2 so a v1 client cannot rewrite them away", () => {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, "Q4_K_M", config(4096, 1024)));
+ assert.equal(storedVersion(), 2);
+ // and this client still reads its own v2 record back
+ const { config: read, remembered } = resolveInitialConfig(MODEL, "Q4_K_M");
+ assert.ok(remembered);
+ assert.equal(read.nBatch, 4096);
+ assert.equal(read.nUbatch, 1024);
+});
+
+test("a record without batch fields keeps v1 so older clients can still read it", () => {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, "Q4_K_M", config(null)));
+ assert.equal(storedVersion(), 1);
+});
diff --git a/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts b/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts
new file mode 100644
index 00000000000..c4f1ae7604e
--- /dev/null
+++ b/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// S2: no user setting may be lost on any upgrade or downgrade path.
+//
+// The batch fields bumped STORAGE_SCHEMA_VERSION to 2, and a v2 stamp makes the WHOLE
+// record invisible to a v1 client, not just the two new keys. That is safe only because
+// toStoredConfig stamps v2 exclusively on records that actually carry a batch value.
+// These tests pin that, plus the paths where a v1 client meets a v2 record: it must
+// refuse to overwrite, refuse to delete and refuse to evict, never clobber.
+//
+// Hidden is acceptable, lost is not.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const { savePerModelConfig, deletePerModelConfig, resolveInitialConfig } = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+
+const MODEL = "unsloth/Repo-GGUF";
+const VARIANT = "Q4_K_M";
+const KEY = "unsloth_model_configs";
+
+function config(overrides: Record<string, unknown> = {}) {
+ return {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ nBatch: null,
+ nUbatch: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ ...overrides,
+ };
+}
+
+function readMap(): Record<string, Record<string, unknown>> {
+ return JSON.parse(store.get(KEY) ?? "{}");
+}
+
+function writeMap(map: Record<string, unknown>): void {
+ store.set(KEY, JSON.stringify(map));
+}
+
+function onlyEntry(): Record<string, unknown> {
+ const [entry] = Object.values(readMap());
+ return entry;
+}
+
+/** resolveInitialConfig is the public read path; loadPerModelConfig is module-private. */
+function load() {
+ const initial = resolveInitialConfig(MODEL, VARIANT);
+ return initial.remembered ? initial.config : null;
+}
+
+// ---------------------------------------------------------------------------
+// A. A NEW client reading OLD records. Nothing may be dropped.
+// ---------------------------------------------------------------------------
+
+test("a v0 record with no version key at all still loads every field it carried", () => {
+ store.clear();
+ // Pre-versioning shape: the guards read storedConfigVersion() === 0 for this.
+ writeMap({
+ [`${MODEL}::${VARIANT}`]: {
+ customContextLength: 8192,
+ kvCacheDtype: "q8_0",
+ nParallel: 4,
+ tensorParallel: true,
+ },
+ });
+ const loaded = load();
+ assert.ok(loaded, "a v0 record must remain readable");
+ assert.equal(loaded.customContextLength, 8192);
+ assert.equal(loaded.kvCacheDtype, "q8_0");
+ assert.equal(loaded.nParallel, 4);
+ assert.equal(loaded.tensorParallel, true);
+ // The fields that did not exist yet read as unset, not as a bogus default.
+ assert.equal(loaded.nBatch, null);
+ assert.equal(loaded.nUbatch, null);
+});
+
+test("a v1 record loads unchanged and is re-stamped v1, not silently upgraded", () => {
+ store.clear();
+ writeMap({
+ [`${MODEL}::${VARIANT}`]: {
+ version: 1,
+ customContextLength: 4096,
+ nParallel: 2,
+ },
+ });
+ const loaded = load();
+ assert.ok(loaded);
+ assert.equal(loaded.customContextLength, 4096);
+ assert.equal(loaded.nParallel, 2);
+
+ // Re-saving without touching a batch field must NOT poison the record for old clients.
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ customContextLength: 4096, nParallel: 2 })));
+ assert.equal(onlyEntry().version, 1, "a batchless record must stay v1");
+});
+
+// ---------------------------------------------------------------------------
+// B. The property the whole scheme rests on.
+// ---------------------------------------------------------------------------
+
+test("only records that actually carry a batch value are stamped v2", () => {
+ // An all-default config is not persisted at all, so it has no version to check.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config()));
+ assert.deepEqual(readMap(), {}, "a default config must not be written");
+
+ for (const [patch, expected] of [
+ [{ nParallel: 8 }, 1],
+ [{ kvCacheDtype: "q8_0", tensorParallel: true }, 1],
+ [{ nBatch: 4096 }, 2],
+ [{ nUbatch: 512 }, 2],
+ [{ nBatch: 4096, nUbatch: 512 }, 2],
+ ] as const) {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config(patch)));
+ assert.equal(
+ onlyEntry().version,
+ expected,
+ `version for ${JSON.stringify(patch)}`,
+ );
+ }
+});
+
+// ---------------------------------------------------------------------------
+// C. An OLD (v1) client meeting a v2 record. Hidden is fine; destroyed is not.
+// ---------------------------------------------------------------------------
+
+test("a v2 record survives byte-for-byte when an old client refuses it", () => {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ nBatch: 4096, nUbatch: 1024 })));
+
+ // Simulate the old client: stamp the record beyond what this build understands, which
+ // is exactly what a v1 build sees when it reads a v2 record.
+ const map = readMap();
+ const [key] = Object.keys(map);
+ map[key].version = 99;
+ writeMap(map);
+ const poisoned = store.get(KEY);
+
+ // Every entry point must decline rather than clobber.
+ assert.equal(load(), null, "load hides a future record");
+ assert.equal(
+ savePerModelConfig(MODEL, VARIANT, config({ nParallel: 1 })),
+ false,
+ "save must refuse rather than overwrite a future record",
+ );
+ assert.equal(
+ deletePerModelConfig(MODEL, VARIANT),
+ false,
+ "delete must refuse a future record",
+ );
+ assert.equal(store.get(KEY), poisoned, "the stored bytes must be untouched");
+
+ // And once the client understands the schema again, the settings come back.
+ const restored = readMap();
+ restored[Object.keys(restored)[0]].version = 2;
+ writeMap(restored);
+ const loaded = load();
+ assert.ok(loaded, "downgrade then upgrade must round-trip");
+ assert.equal(loaded.nBatch, 4096);
+ assert.equal(loaded.nUbatch, 1024);
+});
+
+test("a future record shows defaults rather than another model's settings", () => {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ nBatch: 4096 })));
+ const map = readMap();
+ map[Object.keys(map)[0]].version = 99;
+ writeMap(map);
+
+ const initial = resolveInitialConfig(MODEL, VARIANT);
+ assert.equal(initial.config.nBatch, null);
+ assert.equal(initial.remembered, false);
+});
+
+// ---------------------------------------------------------------------------
+// D. A new client reading a status payload from an OLDER backend.
+// ---------------------------------------------------------------------------
+
+test("a status payload from a backend that omits the batch echo is a no-op", async () => {
+ const { resolveBatchSizeSeed } = await import(
+ "../src/features/chat/lib/resolve-batch-size-seed.ts"
+ );
+ // An older backend does not send requested_n_batch at all. That is "no information",
+ // and must not be read as "the server is running at the default".
+ const pinned = { value: 4096, loaded: 4096 };
+ assert.deepEqual(
+ resolveBatchSizeSeed({
+ incoming: undefined,
+ isGguf: true,
+ previous: pinned,
+ seedLoadParams: true,
+ }),
+ {},
+ "an absent echo must be a no-op, never a clear",
+ );
+ // A dirty control is likewise left alone.
+ assert.deepEqual(
+ resolveBatchSizeSeed({
+ incoming: undefined,
+ isGguf: true,
+ previous: { value: 2048, loaded: 4096 },
+ seedLoadParams: true,
+ }),
+ {},
+ );
+ // But a backend that genuinely reports "no batch flag" (null) does clear the baseline.
+ assert.deepEqual(
+ resolveBatchSizeSeed({
+ incoming: null,
+ isGguf: true,
+ previous: pinned,
+ seedLoadParams: true,
+ }),
+ { loaded: null, value: null },
+ "an explicit null is information and must be honoured",
+ );
+});
diff --git a/studio/frontend/tests/model-config-instance-key.test.ts b/studio/frontend/tests/model-config-instance-key.test.ts
index d0ac05141e3..eab3613872e 100644
--- a/studio/frontend/tests/model-config-instance-key.test.ts
+++ b/studio/frontend/tests/model-config-instance-key.test.ts
@@ -18,6 +18,8 @@ const LIVE: PerModelConfig = {
speculativeType: "ngram",
specDraftNMax: 6,
nParallel: 4,
+ nBatch: 4096,
+ nUbatch: 1024,
tensorParallel: true,
chatTemplateOverride: null,
gpuMemoryMode: "manual",
@@ -34,6 +36,8 @@ const SAVED: PerModelConfig = {
speculativeType: "auto",
specDraftNMax: null,
nParallel: null,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
chatTemplateOverride: null,
gpuMemoryMode: "auto",
diff --git a/studio/frontend/tests/model-identity.test.ts b/studio/frontend/tests/model-identity.test.ts
index 267da1e04aa..004d332e2ea 100644
--- a/studio/frontend/tests/model-identity.test.ts
+++ b/studio/frontend/tests/model-identity.test.ts
@@ -52,6 +52,8 @@ function config(maxSeqLength: number, kvCacheDtype: string | null = null) {
speculativeType: null,
specDraftNMax: null,
nParallel: null,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
chatTemplateOverride: null,
};
diff --git a/studio/frontend/tests/resident-remembered-config.test.ts b/studio/frontend/tests/resident-remembered-config.test.ts
index e534ef1372f..b88c0e4bb1c 100644
--- a/studio/frontend/tests/resident-remembered-config.test.ts
+++ b/studio/frontend/tests/resident-remembered-config.test.ts
@@ -35,6 +35,8 @@ function config(nParallel: number | null, maxSeqLength: number | null = null) {
speculativeType: null,
specDraftNMax: null,
nParallel,
+ nBatch: null,
+ nUbatch: null,
tensorParallel: false,
chatTemplateOverride: null,
};
diff --git a/studio/frontend/tests/resolve-batch-size-seed.test.ts b/studio/frontend/tests/resolve-batch-size-seed.test.ts
new file mode 100644
index 00000000000..dd9ff1f4ee7
--- /dev/null
+++ b/studio/frontend/tests/resolve-batch-size-seed.test.ts
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { resolveBatchSizeSeed } = await import(
+ "../src/features/chat/lib/resolve-batch-size-seed.ts"
+);
+
+function seed(
+ incoming: number | null | undefined,
+ value: number | null,
+ loaded: number | null,
+ overrides: {
+ isGguf?: boolean;
+ seedLoadParams?: boolean;
+ modelChanged?: boolean;
+ } = {},
+) {
+ return resolveBatchSizeSeed({
+ incoming,
+ isGguf: overrides.isGguf ?? true,
+ previous: { value, loaded },
+ seedLoadParams: overrides.seedLoadParams ?? true,
+ modelChanged: overrides.modelChanged ?? false,
+ });
+}
+
+test("a steady echo never touches the pair", () => {
+ assert.deepEqual(seed(4096, 4096, 4096), {});
+ assert.deepEqual(seed(null, null, null), {});
+});
+
+test("an in-flight load owns the params", () => {
+ assert.deepEqual(seed(4096, null, null, { seedLoadParams: false }), {});
+});
+
+test("an older backend omitting the field says nothing", () => {
+ assert.deepEqual(seed(undefined, 2048, 2048), {});
+});
+
+test("a blank control follows an external move off the defaults", () => {
+ // the echo is the requested size, so leaving it blank would revert it on Apply
+ assert.deepEqual(seed(4096, null, null), { loaded: 4096, value: 4096 });
+});
+
+test("a clean control follows a same-model move", () => {
+ assert.deepEqual(seed(1024, 4096, 4096), { loaded: 1024, value: 1024 });
+});
+
+test("a pending edit keeps the control while the baseline advances", () => {
+ assert.deepEqual(seed(1024, 8192, 4096), { loaded: 1024 });
+ // typed against a server still at the defaults
+ assert.deepEqual(seed(1024, 8192, null), { loaded: 1024 });
+});
+
+test("a null echo clears a clean control along with the baseline", () => {
+ assert.deepEqual(seed(null, 4096, 4096), { loaded: null, value: null });
+ // dirty control keeps its intent
+ assert.deepEqual(seed(null, 8192, 4096), { loaded: null });
+});
+
+test("a non-gguf status clears like a null echo", () => {
+ assert.deepEqual(seed(undefined, 4096, 4096, { isGguf: false }), {
+ loaded: null,
+ value: null,
+ });
+});
+
+test("a swap adopts the new model's reported size instead of blanking the control", () => {
+ // another client loaded a different GGUF with an explicit -b; blanking here would
+ // leave the control reading "default" and revert the server on the next Reload
+ assert.deepEqual(seed(4096, null, null, { modelChanged: true }), {
+ loaded: 4096,
+ value: 4096,
+ });
+ // and it adopts even when the new model happens to report what the old one ran,
+ // which the steady-echo short-circuit would otherwise swallow
+ assert.deepEqual(seed(4096, 4096, 4096, { modelChanged: true }), {
+ loaded: 4096,
+ value: 4096,
+ });
+});
+
+test("a swap drops an edit staged against the model that left", () => {
+ assert.deepEqual(seed(4096, 8192, 2048, { modelChanged: true }), {
+ loaded: 4096,
+ value: 4096,
+ });
+});
+
+test("a swap to a model running the defaults clears both sides", () => {
+ assert.deepEqual(seed(null, 4096, 4096, { modelChanged: true }), {
+ loaded: null,
+ value: null,
+ });
+});
+
+test("a swap to a non-gguf or an older backend still drops the stale control", () => {
+ // non-gguf echoes null, so the baseline goes too
+ assert.deepEqual(
+ seed(undefined, 4096, 4096, { isGguf: false, modelChanged: true }),
+ {
+ loaded: null,
+ value: null,
+ },
+ );
+ // an older backend says nothing, so there is no baseline to adopt -- and the pair
+ // staged against the departed model must not follow onto the new one. Leaving the
+ // baseline behind would have a later failed swap roll back with the old model's
+ // -b, which the backend that reported nothing never ran.
+ assert.deepEqual(seed(undefined, 8192, 2048, { modelChanged: true }), {
+ loaded: null,
+ value: null,
+ });
+});
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index cd203909d68..c54c93ee6d7 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -975,6 +975,9 @@ def test_diffusion_picker_hides_and_clears_unsupported_memory_modes():
assert "resolvedIsDiffusion" in page
assert "stagedMetadataPending ||" in page
assert "config.selectedGpuIds != null" in page
+ pending_gate = page.split("const stagedMetadataPending =", 1)[1].split(";", 1)[0]
+ assert "config.nBatch != null" in pending_gate
+ assert "config.nUbatch != null" in pending_gate
for field in (
'gpuMemoryMode: "auto"',
"gpuLayers: undefined",
@@ -1479,7 +1482,7 @@ def test_hydration_restores_a_remembered_slot_override():
"prevState.nParallel === null;" in status
)
assert (
- "status.is_gguf && (slotsUnseeded || slotsModelChanged)" in status
+ "status.is_gguf && (slotsUnseeded || batchesUnseeded || slotsModelChanged)" in status
), "storage is read on a fresh store or a model change, never on a steady poll"
assert (
"...(seedLoadParams && (slotsUnseeded || slotsModelChanged) &&" in status
@@ -1557,6 +1560,133 @@ def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count(
assert "n_parallel: stateBeforeUnload.loadedNParallel," in runtime
+def test_batch_sizes_setting_wired_end_to_end():
+ """The per-load Batch / Micro-batch knobs (llama-server --batch-size / --ubatch-size)
+ follow the same hops as Parallel Slots; a lost hop silently reverts the model to the
+ llama.cpp defaults (2048 / 512)."""
+ config = _read("features/model-picker/model-config/per-model-config.ts")
+ assert '"nBatch",' in config and '"nUbatch",' in config
+ assert "N_BATCH_MAX, Math.round(partial.nBatch)" in config
+ assert "N_BATCH_MAX, Math.round(partial.nUbatch)" in config
+ assert "config.nBatch == null &&" in config
+ assert "config.nUbatch == null &&" in config
+ page = _read("features/model-picker/components/model-config-page.tsx")
+ assert "Batch Size" in page and "Micro-batch Size" in page
+ assert "config.nBatch != null ||" in page
+ assert 'aria-label="Prompt batch size"' in page
+ assert 'aria-label="Prompt micro-batch size"' in page
+ api_types = _read("features/chat/types/api.ts")
+ assert "n_batch?: number | null;" in api_types
+ assert "n_ubatch?: number | null;" in api_types
+ runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
+ assert "pendingLoadConfig?.nBatch" in runtime
+ # omitted when blank: an explicit null reads as set and strips inherited -b / -ub
+ assert "...(isGguf && loadNBatch != null ? { n_batch: loadNBatch } : {})," in runtime
+ assert "...(isGguf && loadNUbatch != null ? { n_ubatch: loadNUbatch } : {})," in runtime
+ assert "...(validateNBatch != null ? { n_batch: validateNBatch } : {})," in runtime
+ assert "...(validateNUbatch != null ? { n_ubatch: validateNUbatch } : {})," in runtime
+ assert "n_batch: isGguf ? loadNBatch : null," not in runtime
+ runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
+ assert "loadNBatch = pendingLoadConfig?.nBatch ?? null;" in runtime
+ assert "loadNUbatch = pendingLoadConfig?.nUbatch ?? null;" in runtime
+ # rollback re-sends a baseline only when one was asked, for the same reason
+ assert "{ n_batch: stateBeforeUnload.loadedNBatch }" in runtime
+ assert "{ n_ubatch: stateBeforeUnload.loadedNUbatch }" in runtime
+ assert "n_batch: stateBeforeUnload.loadedNBatch," not in runtime
+ chat_api = " ".join(_read("features/chat/api/chat-api.ts").split())
+ assert "...(payload.n_batch != null ? { n_batch: payload.n_batch } : {})," in chat_api
+ assert "...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {})," in chat_api
+ composer = " ".join(_read("features/chat/shared-composer.tsx").split())
+ assert (
+ composer.count("...(ownConfig.nBatch != null ? { n_batch: ownConfig.nBatch } : {}),") == 2
+ )
+ assert (
+ composer.count("...(ownConfig.nUbatch != null ? { n_ubatch: ownConfig.nUbatch } : {}),")
+ == 2
+ )
+ adapter = " ".join(_read("features/chat/api/chat-adapter.ts").split())
+ assert adapter.count("...(config.nBatch != null ? { n_batch: config.nBatch } : {}),") == 2
+ assert adapter.count("...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),") == 2
+ assert "loadedNBatch: committedNBatch," in adapter
+ assert "loadedNUbatch: committedNUbatch," in adapter
+ status = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
+ # both pairs hydrate through the one shared rule
+ assert "incoming: status.requested_n_batch," in status
+ assert "incoming: status.requested_n_ubatch," in status
+ assert '...("loaded" in nBatchSeed && { loadedNBatch: nBatchSeed.loaded ?? null }),' in status
+ assert '...("value" in nBatchSeed && { nBatch: nBatchSeed.value ?? null }),' in status
+ assert (
+ '...("loaded" in nUbatchSeed && { loadedNUbatch: nUbatchSeed.loaded ?? null, }),' in status
+ )
+ assert '...("value" in nUbatchSeed && { nUbatch: nUbatchSeed.value ?? null }),' in status
+ signature = _read("features/model-picker/model-config/config-signature.ts")
+ assert 'config.nBatch ?? "",' in signature
+ assert 'config.nUbatch ?? "",' in signature
+
+
+def test_batch_sizes_reach_an_api_load_through_the_server_mirror():
+ """Same server-mirror hop as the slots: an OpenAI auto-switch load happens without a
+ browser, so the stored override is its only way to carry the batch sizes."""
+ api = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert "n_batch?: number;" in api
+ assert "n_ubatch?: number;" in api
+ assert "if (config.nBatch && config.nBatch > 0) { payload.n_batch = config.nBatch; }" in api
+ assert "if (config.nUbatch && config.nUbatch > 0) { payload.n_ubatch = config.nUbatch; }" in api
+ monitor = " ".join(_read("features/api-monitor/components/saved-model-settings.tsx").split())
+ assert "if (override.n_batch) {" in monitor
+ assert "if (override.n_ubatch) {" in monitor
+
+ route = _read_backend("routes/settings.py")
+ assert "n_batch: Optional[int] = Field(" in route
+ assert "n_batch = payload.n_batch," in route
+ assert "n_ubatch = payload.n_ubatch," in route
+ store = _read_backend("utils/openai_auto_switch_settings.py")
+ assert '("n_batch", "n_ubatch")' in store
+ gguf_block = store.split(" if is_gguf:", 1)[1]
+ assert 'kwargs["n_batch"] = override["n_batch"]' in gguf_block
+ assert 'kwargs["n_ubatch"] = override["n_ubatch"]' in gguf_block
+ # A stored pass-through -b / -ub must not outrank the first-class field.
+ assert 'strip_batch = "n_batch" in kwargs,' in store
+ assert 'strip_ubatch = "n_ubatch" in kwargs,' in store
+
+
+def test_hydration_clears_the_batch_baselines_for_a_batchless_model():
+ """Like the slot baseline: a model whose load never sent the batch sizes must not
+ inherit the previous GGUF's values into the rollback baseline. The null-echo,
+ clean-control-follow and pending-edit rules live in resolveBatchSizeSeed and are
+ behavior-tested in resolve-batch-size-seed.test.ts; here only the wiring is pinned."""
+ seed = " ".join(_read("features/chat/lib/resolve-batch-size-seed.ts").split())
+ # a non-gguf clears; an absent field on a gguf is an older backend saying nothing,
+ # though a swap still has to drop the pair staged against the model that left.
+ # The baseline goes with the control, or a later failed swap rolls back with a
+ # batch the backend that reported nothing never ran.
+ assert "const effective = isGguf ? incoming : null;" in seed
+ assert "if (effective === undefined) {" in seed
+ assert "return modelChanged ? { value: null, loaded: null } : {};" in seed
+ # a blank control is clean too, or an external load to an explicit size reads as dirty
+ assert "const controlIsClean = modelChanged || previous.value === previous.loaded;" in seed
+ assert "...(controlIsClean ? { value: effective } : {})," in seed
+ # a swap must reach the adopt path, not be swallowed by the steady-echo short-circuit
+ assert "if (previous.loaded === effective && !modelChanged) { return {}; }" in seed
+ src = _read("features/chat/lib/apply-inference-status-to-store.ts")
+ status = " ".join(src.split())
+ assert "isGguf: status.is_gguf ?? true," in status
+ # A swap under this tab resets the controls too, but through the seed, not a blanket
+ # null after it: the batch echo is the REQUESTED size, so clearing it here would also
+ # discard the value just adopted from the new model and revert it on the next Reload.
+ assert status.count("modelChanged: slotsModelChanged,") == 2
+ assert "{ nBatch: null, nUbatch: null }" not in status
+ # The remembered override is re-adopted only when the echo proves it.
+ assert (
+ "rememberedNBatch != null && rememberedNBatch === "
+ "status.requested_n_batch && { nBatch: rememberedNBatch, }" in status
+ )
+ assert (
+ "rememberedNUbatch != null && rememberedNUbatch === "
+ "status.requested_n_ubatch && { nUbatch: rememberedNUbatch, }" in status
+ )
+
+
def test_vulkan_inference_devices_are_the_pickable_set():
"""GGUF loads run through llama-server, so on a Vulkan build the picker must offer the
inference inventory (ggml ordinals, the space `--device Vulkan<i>` pins) rather than
@@ -2405,6 +2535,39 @@ def test_the_primary_action_keeps_its_four_labels():
assert primary, "primaryActionLabel is no longer rendered inside the handleRun Button"
+def test_the_micro_batch_advisory_compares_against_the_emitted_batch():
+ """The loader raises --batch-size to max(slots, 2), so the micro-batch advisory has to
+ judge the RAISED value. Against the typed one, batch 4 / slots 8 / ubatch 8 rendered
+ two advisories that contradict each other: "will raise it to 8" beside "llama.cpp will
+ run at 4", when the launch runs at 8. Both the predicate and the number shown come
+ from the emitted batch now."""
+ src = _read("features/model-picker/components/model-config-page.tsx")
+ page = " ".join(src.split())
+ assert "const batchFloor = Math.max(2, config.nParallel ?? 2);" in page
+ assert "Math.max(config.nBatch, batchFloor)" in page
+ assert "config.nUbatch > effectiveBatch" in page
+ # the rendered number too, or the text still names a batch nothing runs at
+ assert 'llama.cpp will run at{" "} {effectiveBatch}.' in page
+ # and the floor must be declared before the comparison that uses it
+ assert page.index("const batchFloor =") < page.index("const effectiveBatch =")
+
+
+def test_a_blank_batch_still_caps_the_micro_batch_at_the_llama_default():
+ """Blank does not mean unbounded: no flag is emitted, so llama.cpp runs its own 2048
+ and caps the micro-batch against THAT. Treating blank as null suppressed the advisory
+ entirely, so a micro-batch of 4096 with the batch left blank looked usable while the
+ server ran 2048. Shared constant rather than a literal, since the backend already
+ names the same number."""
+ src = _read("features/model-picker/components/model-config-page.tsx")
+ page = " ".join(src.split())
+ assert "N_BATCH_LLAMA_DEFAULT," in page # imported, not inlined
+ assert ": N_BATCH_LLAMA_DEFAULT;" in page
+ # effectiveBatch is now never null, so the predicate must not re-check it for null
+ assert "config.nUbatch != null && config.nUbatch > effectiveBatch" in page
+ cfg = _read("features/model-picker/model-config/per-model-config.ts")
+ assert "export const N_BATCH_LLAMA_DEFAULT = 2048;" in cfg
+
+
def test_autoload_sees_every_on_device_inventory_and_fails_closed():
"""#7374: Send downloaded a model over a loadable local one. The cascade read
only the two managed-cache lists, both wrapped in `.catch(() => [])`, so a