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.

launch embedding ggufs with --embedding (#8524)

Maheswar Kumar2c1d09c13277
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ba9dac4e83e..0da3b015fc9 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -3392,6 +3392,8 @@ class LlamaCppBackend:
self._n_kv_heads_by_layer: Optional[list[int]] = None
self._n_heads: Optional[int] = None
self._embedding_length: Optional[int] = None
+ # llama_pooling_type from the GGUF; present and non-zero marks an embedding model.
+ self._pooling_type: Optional[int] = None
# For the compute-graph buffer estimate; vocab from the tokens array len.
self._feed_forward_length: Optional[int] = None
self._vocab_size: Optional[int] = None
@@ -4280,6 +4282,19 @@ class LlamaCppBackend:
return 0
return max(0, self._n_layers - (self._leading_dense_block_count or 0))
+ _EMBEDDING_POOLING_TYPES = frozenset({1, 2, 3}) # llama_pooling_type MEAN, CLS, LAST
+
+ @property
+ def is_embedding_gguf(self) -> bool:
+ """Whether the loaded GGUF is an embedding model, from its pooling type.
+
+ Only MEAN, CLS and LAST pool into the one vector per sequence that
+ `/v1/embeddings` returns. NONE (0) pools nothing, and RANK (4) is a reranker
+ head: llama_context sizes its pooled buffer to n_cls_out while llama-server's
+ send_embedding reads n_embd_out floats out of it.
+ """
+ return getattr(self, "_pooling_type", None) in self._EMBEDDING_POOLING_TYPES
+
@staticmethod
def _resolve_cpu_moe_flag(
n_cpu_moe: int, n_moe_layers: int, leading_dense: int
@@ -6674,9 +6689,11 @@ class LlamaCppBackend:
compute = 2 * act_scratch + out_buffer * par
else:
# Each extra concurrent slot adds one output buffer (chat decode sizes
- # ~one logit row per slot; would under-count embeddings/--logits-all,
- # not run here). Matches measured {1:36,2:492,4:1388,8:3220} MiB.
- compute = act_scratch + out_buffer * max(0, par - 1)
+ # ~one logit row per slot). Embedding mode outputs the whole first
+ # micro-batch too, so it pays for every slot rather than slots past one.
+ # Matches measured chat {1:36,2:492,4:1388,8:3220} MiB.
+ output_slots = par if self.is_embedding_gguf else max(0, par - 1)
+ compute = act_scratch + out_buffer * output_slots
return int(compute * self._COMPUTE_BUFFER_SAFETY)
def _compute_buffer_ctx_bytes(
@@ -7168,6 +7185,7 @@ class LlamaCppBackend:
self._n_kv_heads_by_layer = None
self._n_heads = None
self._embedding_length = None
+ self._pooling_type = None
self._feed_forward_length = None
self._vocab_size = None
self._kv_key_length = None
@@ -7212,6 +7230,7 @@ class LlamaCppBackend:
# Arch-specific keys added dynamically once we know the arch.
arch_keys: dict[str, str] = {} # gguf_key -> attribute name
arch = None
+ pooling_by_arch: dict[str, int] = {}
sliding_window_pattern_period: Optional[int] = None
general: dict[str, str] = {}
@@ -7243,7 +7262,7 @@ class LlamaCppBackend:
break
try:
- if key in WANTED or key in arch_keys:
+ if key in WANTED or key in arch_keys or key.endswith(".pooling_type"):
if vtype == 8: # STRING
slen = struct.unpack("<Q", f.read(8))[0]
val_s = f.read(slen).decode("utf-8")
@@ -7260,6 +7279,7 @@ class LlamaCppBackend:
f"{arch}.attention.head_count_kv": "n_kv_heads",
f"{arch}.attention.head_count": "n_heads",
f"{arch}.embedding_length": "embedding_length",
+ f"{arch}.pooling_type": "pooling_type",
f"{arch}.feed_forward_length": "feed_forward_length",
f"{arch}.attention.key_length": "kv_key_length",
f"{arch}.attention.value_length": "kv_value_length",
@@ -7287,6 +7307,8 @@ class LlamaCppBackend:
)
if key == "diffusion.canvas_length":
canvas_seen = True
+ if key.endswith(".pooling_type"):
+ pooling_by_arch[key] = val_i
attr = arch_keys.get(key)
if attr:
if attr == "sliding_window_pattern":
@@ -7327,6 +7349,11 @@ class LlamaCppBackend:
# what we have.
break
+ # GGUF metadata has no key-order contract. Pooling can precede
+ # general.architecture, so bind the buffered value after the sweep.
+ if arch is not None:
+ self._pooling_type = pooling_by_arch.get(f"{arch}.pooling_type", self._pooling_type)
+
# Decide diffusion routing before the SWA resolver below: it can raise on an arch transformers
# does not know, which would otherwise drop a DiffusionGemma model to plain llama-server.
self._is_diffusion = bool(
@@ -10579,6 +10606,25 @@ class LlamaCppBackend:
)
_effective_ubatch = _ubatch_for_slots(n_parallel)
+ # --embedding forces n_batch = n_ubatch, which aborts a load below the slots.
+ if (
+ self.is_embedding_gguf
+ and _effective_ubatch is not None
+ and _effective_ubatch < n_parallel
+ ):
+ # max(): a degenerate "-b 0" extra resolves to 0, and --parallel 0 is
+ # rejected at arg parse.
+ _embedding_slots = max(1, _effective_ubatch)
+ logger.warning(
+ "Reducing serving slots from %d to %d: llama-server caps the batch "
+ "at the %d-token micro-batch under --embedding and aborts when that "
+ "is below the slot count.",
+ n_parallel,
+ _embedding_slots,
+ _effective_ubatch,
+ )
+ n_parallel = _embedding_slots # allow-slot-clamp: llama-server would abort
+ _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),
@@ -12126,6 +12172,10 @@ class LlamaCppBackend:
elif not auto_fit:
cmd.extend(["-c", "0"])
+ # llama-server 501s on /v1/embeddings without this; pooling stays model-default.
+ if self.is_embedding_gguf:
+ cmd.append("--embedding")
+
# 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
@@ -12787,6 +12837,13 @@ class LlamaCppBackend:
# Library paths so llama-server finds its shared libs and CUDA DLLs.
env = self._llama_server_env_for_binary(binary)
+ # The GGUF header controls pooling; ignore inherited defaults.
+ for _pooling_var in (
+ "LLAMA_ARG_POOLING",
+ "LLAMA_ARG_RERANKING",
+ "LLAMA_ARG_EMBEDDINGS",
+ ):
+ env.pop(_pooling_var, None)
if gpu_memory_mode == "manual":
self._clear_manual_placement_env(env)
# llama.cpp reads LLAMA_ARG_MLOCK / _MMAP / _LOAD_MODE before argv,
@@ -14550,6 +14607,7 @@ class LlamaCppBackend:
self._n_kv_heads_by_layer = None
self._n_heads = None
self._embedding_length = None
+ self._pooling_type = None
self._kv_key_length = None
self._kv_value_length = None
self._sliding_window = None
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index 651c100b4c2..24fa212256d 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -74,10 +74,12 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
frozenset({"--models-preset"}),
frozenset({"--models-max"}),
frozenset({"--models-autoload", "--no-models-autoload"}),
- # Server-mode flips: --embedding / --rerank restrict llama-server to
- # those endpoints, breaking Unsloth's /v1/chat/completions hop.
+ # Server-mode flips: --embedding is set from the GGUF pooling type at load, not by hand.
frozenset({"--embedding", "--embeddings"}),
frozenset({"--rerank", "--reranking"}),
+ # Pooling decides whether the managed embedding launch is safe. A pass-through
+ # override appended after --embedding could switch it to NONE or RANK.
+ frozenset({"--pooling"}),
# llama-server's own built-in tools flag would silently stack on top of
# Unsloth's --enable-tools / --disable-tools policy resolver.
frozenset({"--tools"}),
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d6cbcee4d4b..2545351cb70 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5959,10 +5959,6 @@ def _estimate_gguf_kv_gb(
if ctx <= 0:
return 0.0
slots = max(1, n_parallel or 1)
- managed_kv_unified = bool(
- slots > 1
- and LlamaCppBackend.probe_server_capabilities().get("supports_kv_unified", False)
- )
planned_cache_types = _planned_main_cache_types(
cache_type_kv,
llama_extra_args,
@@ -5998,6 +5994,25 @@ def _estimate_gguf_kv_gb(
n_ubatch = n_ubatch,
)
)
+ # --embedding makes llama-server cap n_batch to n_ubatch. The loader
+ # therefore reduces slots to the same value before fitting; admission
+ # must price the process that will launch, not the original request.
+ if (
+ getattr(probe, "is_embedding_gguf", False)
+ and effective_ubatch is not None
+ and effective_ubatch < slots
+ ):
+ slots = max(1, effective_ubatch)
+ effective_ubatch = _extra_args_n_ubatch(
+ llama_extra_args,
+ n_ctx = ctx,
+ n_batch = _emitted_n_batch(n_batch, slots),
+ n_ubatch = n_ubatch,
+ )
+ managed_kv_unified = bool(
+ slots > 1
+ and LlamaCppBackend.probe_server_capabilities().get("supports_kv_unified", False)
+ )
kv = probe._estimate_kv_cache_bytes(
ctx,
cache_type_for_budget,
@@ -6039,10 +6054,13 @@ def _estimate_gguf_kv_gb(
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
+ output_slots = (
+ slots if getattr(probe, "is_embedding_gguf", False) else max(0, slots - 1)
+ )
raw = (
2 * act_scratch + out_buffer * slots
if per_device_tensor
- else act_scratch + out_buffer * max(0, slots - 1)
+ else act_scratch + out_buffer * output_slots
)
return int(raw * probe._COMPUTE_BUFFER_SAFETY)
@@ -6355,6 +6373,8 @@ def _estimate_gguf_required_gb(
n_ubatch = n_ubatch,
)
)
+ if effective_ubatch is None and not is_diffusion:
+ effective_ubatch = LlamaCppBackend._DEFAULT_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
@@ -6394,7 +6414,8 @@ def _estimate_gguf_required_gb(
# 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)
+ # The remote header is unknown, so reserve as if it enables embeddings.
+ _out_slots = max(1, n_parallel)
out_buffer_bytes = (
_ASSUMED_MAX_VOCAB
* effective_ubatch
@@ -16066,11 +16087,7 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
raise HTTPException(status_code = 400, detail = "'input' must be a string or array.")
if not _embeddings_input_present(_pre):
raise HTTPException(status_code = 400, detail = "'input' is required for embeddings.")
- # Embeddings is a model-bearing inference path too, so honor auto-switch. Unlike
- # vision (cheaply pre-checked via a companion mmproj), GGUF pooling capability has
- # no reliable pre-load probe -- is_embedding_model keys on a sentence-transformers
- # modules.json a bare .gguf never has -- so embeddings auto-switch is best-effort:
- # a non-embedding target switches, then llama-server returns a no-pooling error.
+ # Auto-switch applies here too; the target launches embedding-enabled only if it pools.
body = await _auto_switch_from_request_body(request, current_subject)
if not llama_backend.is_loaded:
_status, _detail = await _no_model_loaded_error(
diff --git a/studio/backend/tests/test_batch_sizes_per_load.py b/studio/backend/tests/test_batch_sizes_per_load.py
index 417cc6a4012..ceaeeedad20 100644
--- a/studio/backend/tests/test_batch_sizes_per_load.py
+++ b/studio/backend/tests/test_batch_sizes_per_load.py
@@ -269,7 +269,7 @@ def test_remote_gguf_guard_counts_explicit_micro_batch():
big = route._estimate_gguf_required_gb(
config, max_seq_length = 32768, n_batch = 65536, n_ubatch = 65536
)
- assert base == pytest.approx(1.0)
+ assert base > 1.5
# ctx-capped ubatch (32768) x ctx x 2 x 1.5 mask safety ~= 3 GiB on top
assert big > base + 2.0
@@ -583,6 +583,21 @@ def test_the_local_guard_charges_diffusion_nothing_for_the_batch_flags():
assert chat_loud > chat_quiet + 0.7
+def test_embedding_guard_prices_the_slots_that_will_launch():
+ """The loader clamps embedding slots to a smaller physical micro-batch.
+ The training coexistence guard must not 409 that reduced process by pricing
+ the original slot request."""
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ embedding = dict(_QWEN3_8B, pooling_type = 2)
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _header_reader(**embedding)):
+ clamped = route._estimate_gguf_kv_gb("/x.gguf", 32768, n_parallel = 4, n_batch = 4, n_ubatch = 2)
+ launched = route._estimate_gguf_kv_gb("/x.gguf", 32768, n_parallel = 2, n_batch = 4, n_ubatch = 2)
+ assert clamped == pytest.approx(launched, abs = 0.01)
+
+
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). The fit-time reduction
@@ -602,8 +617,8 @@ def test_the_recorded_micro_batch_is_derived_from_the_slots_that_launched():
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)}"
+ # sizing pass, embedding slot clamp, fit-time reduction, then the post-launch record
+ assert len(calls) == 4, f"expected four 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
@@ -650,10 +665,12 @@ def test_the_remote_guard_charges_the_flat_output_buffer():
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
+ # Unset fields still launch at llama.cpp's known default 512-token micro-batch.
+ assert blank_1 > 1.5
+ assert blank_4 > blank_1 + 1.5
+ # The remote header may enable embeddings, so the first output buffer is charged.
+ assert big_1 > blank_1 + 30.0
+ # 262144 * 32768 * 4 = 32 GiB for the second slot too.
assert big_2 > big_1 + 30.0
# and it stays proportionate where the values are ordinary
assert typical_4 < 4.0
diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.py
index 3a28061671b..37f65de9e91 100644
--- a/studio/backend/tests/test_compute_buffer.py
+++ b/studio/backend/tests/test_compute_buffer.py
@@ -67,6 +67,7 @@ def _backend(
embd = 5120,
mla = None,
arch = None,
+ pooling_type = None,
):
"""Backend with just the dims the compute-buffer estimate reads."""
b = LlamaCppBackend.__new__(LlamaCppBackend)
@@ -74,6 +75,7 @@ def _backend(
b._embedding_length = embd
b._key_length_mla = mla # non-None -> MLA (compressed attention)
b._architecture = arch # GGUF general.architecture (e.g. 'deepseek4')
+ b._pooling_type = pooling_type
return b
@@ -135,6 +137,13 @@ class TestScaling:
hi = b._estimate_compute_buffer_bytes(n_parallel = 4, n_ubatch = 1024)
assert hi > lo
+ def test_embedding_mode_budgets_the_first_output_buffer(self):
+ chat = _backend()._estimate_compute_buffer_bytes(n_parallel = 1, n_ubatch = 512)
+ embedding = _backend(pooling_type = 2)._estimate_compute_buffer_bytes(
+ n_parallel = 1, n_ubatch = 512
+ )
+ assert embedding > chat
+
class TestFallback:
def test_zero_when_vocab_missing(self):
diff --git a/studio/backend/tests/test_embedding_gguf_launch.py b/studio/backend/tests/test_embedding_gguf_launch.py
new file mode 100644
index 00000000000..b3016382980
--- /dev/null
+++ b/studio/backend/tests/test_embedding_gguf_launch.py
@@ -0,0 +1,235 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Backend contract for serving embedding GGUFs.
+
+llama-server answers ``/v1/embeddings`` with a 501 ("This server does not
+support embeddings. Start it with `--embeddings`") unless it was launched with
+``--embedding``; nothing in llama.cpp turns that on from the model itself. These
+tests pin the header probe that detects an embedding GGUF (``<arch>.pooling_type``,
+the only place the flag can be decided before launch) and the ``load_model``
+emission it gates.
+"""
+
+from __future__ import annotations
+
+import inspect
+import io
+import struct
+import sys
+import types as _types
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+# Same external-dep stubs as the other llama_cpp unit tests so importing
+# the backend doesn't drag in structlog / httpx / loggers.
+_loggers_stub = _types.ModuleType("loggers")
+_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 import llama_cpp as llama_cpp_module
+from core.inference.llama_cpp import LlamaCppBackend
+
+# llama_pooling_type, include/llama.h
+POOLING_NONE = 0
+POOLING_MEAN = 1
+POOLING_CLS = 2
+POOLING_LAST = 3
+POOLING_RANK = 4
+
+_VTYPE_UINT32 = 4
+_VTYPE_STRING = 8
+
+
+def _write_kv(buf: io.BytesIO, key: str, value, vtype: int) -> None:
+ key_bytes = key.encode("utf-8")
+ buf.write(struct.pack("<Q", len(key_bytes)))
+ buf.write(key_bytes)
+ buf.write(struct.pack("<I", vtype))
+ if vtype == _VTYPE_UINT32:
+ buf.write(struct.pack("<I", value))
+ elif vtype == _VTYPE_STRING:
+ val_bytes = value.encode("utf-8")
+ buf.write(struct.pack("<Q", len(val_bytes)))
+ buf.write(val_bytes)
+ else:
+ raise ValueError(f"Unsupported vtype in test helper: {vtype}")
+
+
+def _make_gguf(
+ tmp_path: Path,
+ arch: str,
+ *,
+ pooling_type: int | None = None,
+ pooling_first: bool = False,
+ filename: str = "test.gguf",
+) -> str:
+ """Header-only GGUF v3 carrying the architecture and optional pooling type."""
+ entries: list[tuple[str, object, int]] = []
+ if pooling_type is not None and pooling_first:
+ entries.append((f"{arch}.pooling_type", pooling_type, _VTYPE_UINT32))
+ entries.append(("general.architecture", arch, _VTYPE_STRING))
+ entries.append((f"{arch}.block_count", 12, _VTYPE_UINT32))
+ if pooling_type is not None and not pooling_first:
+ entries.append((f"{arch}.pooling_type", pooling_type, _VTYPE_UINT32))
+
+ buf = io.BytesIO()
+ buf.write(struct.pack("<I", 0x46554747)) # GGUF magic
+ buf.write(struct.pack("<I", 3)) # version 3
+ buf.write(struct.pack("<Q", 0)) # tensor count
+ buf.write(struct.pack("<Q", len(entries)))
+ for key, value, vtype in entries:
+ _write_kv(buf, key, value, vtype)
+
+ path = tmp_path / filename
+ path.write_bytes(buf.getvalue())
+ return str(path)
+
+
+def backend():
+ with patch.object(LlamaCppBackend, "_kill_orphaned_servers"):
+ with patch("atexit.register"):
+ return LlamaCppBackend()
+
+
+class TestIsEmbeddingGguf:
+ def test_false_on_fresh_backend(self, backend):
+ assert backend._pooling_type is None
+ assert backend.is_embedding_gguf is False
+
+ @pytest.mark.parametrize("pooling_type", [POOLING_MEAN, POOLING_CLS, POOLING_LAST])
+ def test_true_for_every_sequence_pooling_mode(self, tmp_path, backend, pooling_type):
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "bert", pooling_type = pooling_type))
+ assert backend._pooling_type == pooling_type
+ assert backend.is_embedding_gguf is True
+
+ def test_pooling_before_architecture_is_detected(self, tmp_path, backend):
+ backend._read_gguf_metadata(
+ _make_gguf(tmp_path, "bert", pooling_type = POOLING_CLS, pooling_first = True)
+ )
+ assert backend._pooling_type == POOLING_CLS
+ assert backend.is_embedding_gguf is True
+
+ def test_false_when_the_header_pools_nothing(self, tmp_path, backend):
+ # Pooling NONE returns per-token vectors, which /v1/embeddings cannot shape.
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "bert", pooling_type = POOLING_NONE))
+ assert backend._pooling_type == POOLING_NONE
+ assert backend.is_embedding_gguf is False
+
+ def test_false_for_a_reranker(self, tmp_path, backend):
+ # send_embedding would read n_embd_out floats from a RANK head's n_cls_out buffer.
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "qwen3", pooling_type = POOLING_RANK))
+ assert backend._pooling_type == POOLING_RANK
+ assert backend.is_embedding_gguf is False
+
+ def test_false_for_a_chat_gguf(self, tmp_path, backend):
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "llama"))
+ assert backend._pooling_type is None
+ assert backend.is_embedding_gguf is False
+
+ def test_resets_between_parses(self, tmp_path, backend):
+ backend._read_gguf_metadata(
+ _make_gguf(tmp_path, "bert", pooling_type = POOLING_CLS, filename = "embed.gguf")
+ )
+ assert backend.is_embedding_gguf is True
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "llama", filename = "chat.gguf"))
+ assert backend.is_embedding_gguf is False
+
+ def test_false_after_unload(self, tmp_path, backend):
+ # A stale pooling type would report an unloaded backend as an embedding server.
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "bert", pooling_type = POOLING_CLS))
+ assert backend.is_embedding_gguf is True
+ backend.unload_model()
+ assert backend._pooling_type is None
+ assert backend.is_embedding_gguf is False
+
+ def test_probe_reads_the_arch_prefixed_key_only(self, tmp_path, backend):
+ # A pooling_type under the wrong arch prefix is another model's key.
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "bert", pooling_type = POOLING_CLS))
+ assert backend.is_embedding_gguf is True
+ buf = io.BytesIO()
+ buf.write(struct.pack("<I", 0x46554747))
+ buf.write(struct.pack("<I", 3))
+ buf.write(struct.pack("<Q", 0))
+ buf.write(struct.pack("<Q", 2))
+ _write_kv(buf, "general.architecture", "llama", _VTYPE_STRING)
+ _write_kv(buf, "bert.pooling_type", POOLING_CLS, _VTYPE_UINT32)
+ mismatched = tmp_path / "mismatched.gguf"
+ mismatched.write_bytes(buf.getvalue())
+ backend._read_gguf_metadata(str(mismatched))
+ assert backend.is_embedding_gguf is False
+
+
+class TestLoadModelEmitsTheFlag:
+ """load_model is too large to drive here, so pin its source, as the
+ GPU-memory-mode and batch-size suites do for the same command block."""
+
+ def test_embedding_flag_is_gated_on_the_header_probe(self):
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ guard = src.find("if self.is_embedding_gguf:")
+ assert guard != -1, "load_model must decide --embedding from the GGUF header"
+ emit = src.find('cmd.append("--embedding")', guard)
+ assert emit != -1 and emit - guard < 120, "--embedding must sit under that guard"
+
+ def test_the_flag_is_never_unconditional(self):
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ base_start = src.find("cmd = [")
+ base_end = src.find("\n ]", base_start)
+ assert '"--embedding"' not in src[base_start:base_end], (
+ "--embedding restricts llama-server to embeddings, so it must never be "
+ "in the base command every chat model launches with"
+ )
+
+ def test_slots_are_clamped_to_the_micro_batch(self):
+ # The slots follow the micro-batch down, or --embedding aborts the load.
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ guard = src.find("_effective_ubatch < n_parallel")
+ assert guard != -1, "load_model must compare the micro-batch against the slot count"
+ block = src[guard : guard + 900]
+ assert "n_parallel = _embedding_slots" in block, "slots must clamp to the micro-batch"
+ assert (
+ "max(1, _effective_ubatch)" in block
+ ), "the clamp must floor at one slot; --parallel 0 is rejected at arg parse"
+ assert "allow-slot-clamp:" in block, "the clamp needs the lint marker and a reason"
+ assert (
+ "_effective_ubatch = _ubatch_for_slots(n_parallel)" in block
+ ), "the micro-batch must be re-derived at the reduced slot count"
+ assert (
+ src.find("self.is_embedding_gguf", guard - 400, guard) != -1
+ ), "the clamp must be gated on the embedding probe"
+ assert guard < src.find("cmd = ["), "the clamp must land before the fit and the launch"
+
+ def test_pooling_is_left_at_the_model_default(self):
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ assert '"--pooling"' not in src, (
+ "the GGUF's own pooling type is correct; pinning one here would "
+ "override rerank (RANK) and mean-pooled models"
+ )
+
+ def test_inherited_pooling_cannot_override_the_header_probe(self):
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ for name in ("LLAMA_ARG_POOLING", "LLAMA_ARG_RERANKING", "LLAMA_ARG_EMBEDDINGS"):
+ assert f'"{name}"' in src
+
+
[email protected]("flag", ["--embedding", "--embeddings", "--pooling"])
+def test_user_extra_args_still_cannot_pass_the_flag(flag):
+ # The denylist keeps a user-supplied --embedding off the chat server; the
+ # header probe is the only thing allowed to turn it on.
+ from core.inference.llama_server_args import is_managed_flag, validate_extra_args
+ assert is_managed_flag(flag) is True
+ with pytest.raises(ValueError, match = "managed by Unsloth Studio"):
+ validate_extra_args([flag])
diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.py
index 0c73eeb4800..0dfe5d3ff97 100644
--- a/studio/backend/tests/test_llama_server_args.py
+++ b/studio/backend/tests/test_llama_server_args.py
@@ -189,6 +189,7 @@ def test_non_flag_token_passes_through():
"--embeddings",
"--rerank",
"--reranking",
+ "--pooling",
# llama-server's own --tools clashes with Unsloth's tool policy.
"--tools",
# Slot-state dir: Studio owns it for KV persistence across idle unload.