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.

fix(studio): auto-enable --embedding for GGUFs missing pooling_type (#9149)

Souravrajvi0785a68dc4d19
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 6d4caa4b2f6..0c3a851f70a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -5824,8 +5824,24 @@ class LlamaCppBackend:
`/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.
+
+ When the header omits pooling_type (common on dedicated encoder arches such as
+ nomic-bert), fall back to architecture and model-name hints so llama-server still
+ launches with --embedding (#9128).
"""
- return getattr(self, "_pooling_type", None) in self._EMBEDDING_POOLING_TYPES
+ pooling = getattr(self, "_pooling_type", None)
+ if pooling is not None:
+ return pooling in self._EMBEDDING_POOLING_TYPES
+ path = getattr(self, "_gguf_path", None)
+ if not path:
+ return False
+ from utils.models.gguf_metadata import is_gguf_embedding_model
+
+ return is_gguf_embedding_model(
+ path,
+ model_identifier = self._model_identifier,
+ architecture = self._architecture,
+ )
@staticmethod
def _resolve_cpu_moe_flag(
@@ -10640,6 +10656,7 @@ class LlamaCppBackend:
self._n_heads = None
self._embedding_length = None
self._pooling_type = None
+ self._gguf_path = gguf_path
self._feed_forward_length = None
self._vocab_size = None
self._kv_key_length = None
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5f6a53b6c14..b76fbe739fa 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -7227,6 +7227,7 @@ def _estimate_gguf_kv_gb(
ctx_checkpoints: Optional[int] = None,
n_devices: int = 1,
is_diffusion: bool = False,
+ model_identifier: Optional[str] = None,
) -> float:
"""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
@@ -7242,6 +7243,7 @@ def _estimate_gguf_kv_gb(
)
probe = LlamaCppBackend()
+ probe._model_identifier = model_identifier
probe._read_gguf_metadata(gguf_path)
if not probe._can_estimate_kv():
return 0.0
@@ -7782,6 +7784,7 @@ def _estimate_gguf_required_gb(
ctx_checkpoints = ctx_checkpoints,
n_devices = n_devices,
is_diffusion = is_diffusion,
+ model_identifier = getattr(config, "identifier", None),
)
repo = getattr(config, "gguf_hf_repo", None)
@@ -7913,15 +7916,17 @@ def _local_gguf_main_path(config: ModelConfig) -> Optional[str]:
def _is_embedding_gguf(config: ModelConfig) -> bool:
"""Whether this GGUF's pooling type makes llama-server launch with --embedding.
- False whenever the header cannot be read, which keeps every caller doing what it
- did before the check existed: this only ever relaxes a refusal, and relaxing one
- on a guess is how a load reaches the abort the refusal exists to prevent.
+ Before an uncached remote GGUF has a readable header, use the same local identifier
+ basename hints as the eventual loader. Generic names remain unclassified, so this
+ only relaxes the batch refusal for models the loader will launch in embedding mode.
"""
try:
main = _local_gguf_main_path(config)
if not main:
return False
probe = LlamaCppBackend()
+ probe._model_identifier = config.identifier
+ probe._gguf_path = main
probe._read_gguf_metadata(main)
return bool(probe.is_embedding_gguf)
except Exception as exc:
diff --git a/studio/backend/tests/test_batch_sizes_per_load.py b/studio/backend/tests/test_batch_sizes_per_load.py
index ceaeeedad20..de13abca9c2 100644
--- a/studio/backend/tests/test_batch_sizes_per_load.py
+++ b/studio/backend/tests/test_batch_sizes_per_load.py
@@ -598,6 +598,37 @@ def test_embedding_guard_prices_the_slots_that_will_launch():
assert clamped == pytest.approx(launched, abs = 0.01)
+def test_embedding_guard_uses_identifier_when_pooling_is_missing():
+ """An embedding name must clamp the admission estimate even when the cached
+ filename and GGUF architecture are generic."""
+ from unittest.mock import patch
+
+ from routes import inference as route
+
+ def _generic_embedding_header(self, path):
+ _header_reader(**_QWEN3_8B)(self)
+ self._gguf_path = path
+
+ with patch.object(LlamaCppBackend, "_read_gguf_metadata", _generic_embedding_header):
+ clamped = route._estimate_gguf_kv_gb(
+ "/x.gguf",
+ 32768,
+ n_parallel = 4,
+ n_batch = 4,
+ n_ubatch = 2,
+ model_identifier = "unsloth/Qwen3-Embedding-4B",
+ )
+ launched = route._estimate_gguf_kv_gb(
+ "/x.gguf",
+ 32768,
+ n_parallel = 2,
+ n_batch = 4,
+ n_ubatch = 2,
+ model_identifier = "unsloth/Qwen3-Embedding-4B",
+ )
+ 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
diff --git a/studio/backend/tests/test_embedding_gguf_launch.py b/studio/backend/tests/test_embedding_gguf_launch.py
index b3016382980..dd16c09ab7b 100644
--- a/studio/backend/tests/test_embedding_gguf_launch.py
+++ b/studio/backend/tests/test_embedding_gguf_launch.py
@@ -110,6 +110,11 @@ class TestIsEmbeddingGguf:
assert backend._pooling_type is None
assert backend.is_embedding_gguf is False
+ def test_false_on_minimal_backend_without_path_state(self):
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._pooling_type = 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))
@@ -140,6 +145,20 @@ class TestIsEmbeddingGguf:
assert backend._pooling_type is None
assert backend.is_embedding_gguf is False
+ def test_true_for_dedicated_embedding_arch_without_pooling_type(self, tmp_path, backend):
+ # nomic-bert and similar encoder GGUFs often omit pooling_type in the header.
+ backend._read_gguf_metadata(_make_gguf(tmp_path, "nomic-bert-moe"))
+ assert backend._pooling_type is None
+ assert backend.is_embedding_gguf is True
+
+ def test_true_for_embedding_name_hint_without_pooling_type(self, tmp_path, backend):
+ backend._model_identifier = "unsloth/Qwen3-Embedding-4B"
+ backend._read_gguf_metadata(
+ _make_gguf(tmp_path, "qwen3", filename = "Qwen3-Embedding-4B-Q4_K_M.gguf")
+ )
+ assert backend._pooling_type is None
+ assert backend.is_embedding_gguf is True
+
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")
diff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.py
index 3092a80e9a7..0aaccf4f9f1 100644
--- a/studio/backend/tests/test_gguf_metadata.py
+++ b/studio/backend/tests/test_gguf_metadata.py
@@ -9,8 +9,11 @@ from __future__ import annotations
import struct
from pathlib import Path
from typing import Iterable, Mapping
+from unittest.mock import patch
from utils.models.gguf_metadata import (
+ is_gguf_embedding_architecture,
+ is_gguf_embedding_model,
is_mmproj_by_metadata,
mmproj_accepts_image,
pairing_score,
@@ -64,12 +67,14 @@ def _write_synthetic_gguf(
path: Path,
general_strings: Mapping[str, str],
*,
+ tensor_names: Iterable[str] | None = None,
extra_uint32: Mapping[str, int] | None = None,
extra_uint64: Mapping[str, int] | None = None,
extra_string_arrays: Mapping[str, Iterable[str]] | None = None,
extra_bools: Mapping[str, bool] | None = None,
) -> Path:
- """Minimal GGUF: header + KV body, no tensors."""
+ """Minimal GGUF header with optional tensor-table entries and no tensor data."""
+ tensor_names = list(tensor_names or ())
extra_uint32 = extra_uint32 or {}
extra_uint64 = extra_uint64 or {}
extra_string_arrays = extra_string_arrays or {}
@@ -92,15 +97,22 @@ def _write_synthetic_gguf(
body += _enc_kv_string_array(k, v)
for k, v in extra_bools.items():
body += _enc_kv_bool(k, v)
+ tensor_info = b""
+ for name in tensor_names:
+ tensor_info += _enc_string(name)
+ tensor_info += struct.pack("<I", 1) # n_dimensions
+ tensor_info += struct.pack("<Q", 1) # dimensions
+ tensor_info += struct.pack("<I", 0) # GGML_TYPE_F32
+ tensor_info += struct.pack("<Q", 0) # data offset
header = struct.pack(
"<IIQQ",
_GGUF_MAGIC,
3, # version
- 0, # tensor_count
+ len(tensor_names),
kv_count,
)
path.parent.mkdir(parents = True, exist_ok = True)
- path.write_bytes(header + body)
+ path.write_bytes(header + body + tensor_info)
return path
@@ -563,3 +575,101 @@ def test_declared_audio_false_is_not_an_audio_claim(tmp_path: Path):
"""A vision projector writing audio=False is still a vision tower."""
p = _projector(tmp_path, **{"clip.has_vision_encoder": True, "clip.has_audio_encoder": False})
assert mmproj_accepts_image(p) is True
+
+
+def test_is_gguf_embedding_architecture_recognises_encoder_arches():
+ assert is_gguf_embedding_architecture("nomic-bert")
+ assert is_gguf_embedding_architecture("NOMIC-BERT-MOE")
+ assert not is_gguf_embedding_architecture("bert")
+ assert not is_gguf_embedding_architecture("llama")
+ assert not is_gguf_embedding_architecture(None)
+
+
+def test_is_gguf_embedding_model_from_architecture(tmp_path: Path):
+ p = _write_synthetic_gguf(
+ tmp_path / "nomic.gguf",
+ {"general.architecture": "nomic-bert"},
+ )
+ assert is_gguf_embedding_model(str(p)) is True
+
+
+def test_is_gguf_embedding_model_from_name_hint(tmp_path: Path):
+ p = _write_synthetic_gguf(
+ tmp_path / "Qwen3-Embedding-4B-Q4_K_M.gguf",
+ {"general.architecture": "qwen3"},
+ )
+ with patch("utils.models.model_config.is_embedding_model") as remote_classifier:
+ assert (
+ is_gguf_embedding_model(str(p), model_identifier = "unsloth/Qwen3-Embedding-4B") is True
+ )
+ remote_classifier.assert_not_called()
+
+
+def test_is_gguf_embedding_model_ignores_owner_name_hint(tmp_path: Path):
+ p = _write_synthetic_gguf(
+ tmp_path / "Llama-3-Q4_K_M.gguf",
+ {"general.architecture": "llama"},
+ )
+ with patch("utils.models.model_config.is_embedding_model") as remote_classifier:
+ assert (
+ is_gguf_embedding_model(str(p), model_identifier = "embedding-lab/Llama-3-GGUF") is False
+ )
+ remote_classifier.assert_not_called()
+
+
+def test_is_gguf_embedding_model_from_intrinsic_name_hints(tmp_path: Path):
+ for index, (key, value) in enumerate(
+ (
+ ("general.name", "Qwen3 Embedding 4B"),
+ ("general.basename", "Qwen3-Embedding"),
+ )
+ ):
+ p = _write_synthetic_gguf(
+ tmp_path / f"model-{index}.gguf",
+ {"general.architecture": "qwen3", key: value},
+ )
+ assert is_gguf_embedding_model(str(p), model_identifier = "local/model") is True
+
+
+def test_is_gguf_embedding_model_excludes_reranker_without_pooling(tmp_path: Path):
+ p = _write_synthetic_gguf(
+ tmp_path / "bge-reranker-v2-m3-Q4_K_M.gguf",
+ {"general.architecture": "bert", "general.name": "Bge M3"},
+ )
+ assert (
+ is_gguf_embedding_model(str(p), model_identifier = "gpustack/bge-reranker-v2-m3-GGUF")
+ is False
+ )
+
+
+def test_is_gguf_embedding_model_rejects_generic_bert_without_pooling(tmp_path: Path):
+ p = _write_synthetic_gguf(
+ tmp_path / "bge-small-en-v1.5.gguf",
+ {"general.architecture": "bert", "general.name": "Bge Small Encoder"},
+ )
+ # No classifier head proves this is not a reranker, but it cannot tell us
+ # whether the missing pooling strategy should be CLS or MEAN.
+ assert is_gguf_embedding_model(str(p), model_identifier = "local/bge-small") is False
+
+
+def test_is_gguf_embedding_model_excludes_unnamed_encoder_classifier_heads(tmp_path: Path):
+ for index, classifier_tensor in enumerate(("cls.weight", "cls.output.weight")):
+ p = _write_synthetic_gguf(
+ tmp_path / f"model-{index}.gguf",
+ {"general.architecture": "modern-bert", "general.name": "MS MARCO Encoder"},
+ tensor_names = (classifier_tensor,),
+ )
+ assert is_gguf_embedding_model(str(p), model_identifier = "local/model") is False
+
+
+def test_is_gguf_embedding_model_checks_every_split_for_classifier_head(tmp_path: Path):
+ first = _write_synthetic_gguf(
+ tmp_path / "model-00001-of-00002.gguf",
+ {"general.architecture": "modern-bert"},
+ )
+ _write_synthetic_gguf(
+ tmp_path / "model-00002-of-00002.gguf",
+ {"general.architecture": "modern-bert"},
+ tensor_names = ("cls.weight",),
+ )
+ assert is_gguf_embedding_model(str(first), model_identifier = "local/model") is False
diff --git a/studio/backend/tests/test_validate_diffusion_extra_args.py b/studio/backend/tests/test_validate_diffusion_extra_args.py
index 3bf37fcac31..59185461280 100644
--- a/studio/backend/tests/test_validate_diffusion_extra_args.py
+++ b/studio/backend/tests/test_validate_diffusion_extra_args.py
@@ -398,6 +398,17 @@ class TestEmbeddingSlotClampInTheBatchFloor(unittest.TestCase):
config = SimpleNamespace(identifier = "someone/gguf", gguf_file = None, gguf_hf_repo = None)
self.assertFalse(route._is_embedding_gguf(config))
+ def test_an_uncached_embedding_identifier_stays_fail_closed(self):
+ route = _load_route_module("inf_route_embed_clamp_6")
+ config = SimpleNamespace(
+ identifier = "Qwen/Qwen3-Embedding-4B-GGUF",
+ gguf_file = None,
+ gguf_hf_repo = "Qwen/Qwen3-Embedding-4B-GGUF",
+ gguf_variant = "Q4_K_M",
+ )
+ with patch.object(route, "_local_gguf_main_path", return_value = None):
+ self.assertFalse(route._is_embedding_gguf(config))
+
class TestValidateAllowsTheEmbeddingClampedBatch(TestValidateRefusesWhatLoadWouldRefuse):
"""The preflight has to allow exactly what the load allows, or the picker refuses a
diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.py
index df6d55e44b3..a2b4f25cfb8 100644
--- a/studio/backend/utils/models/gguf_metadata.py
+++ b/studio/backend/utils/models/gguf_metadata.py
@@ -52,6 +52,10 @@ _BOOL_CACHE: Dict[Tuple[_CacheKey, str], Optional[bool]] = {}
_STRING_CACHE: Dict[Tuple[_CacheKey, str], Optional[str]] = {}
+# Whether the GGUF tensor table contains a sequence-classification head. None
+# means the file could not be read or parsed, so callers can fail closed.
+_CLASSIFIER_HEAD_CACHE: Dict[_CacheKey, Optional[bool]] = {}
+
# GGUF header dims for the staged/deferred-load UI: context_length, layer_count
# (block_count), and moe_layer_count (block_count minus leading dense layers; 0
# if not MoE). One cached pass fills all three so the staged sheet can size every
@@ -345,6 +349,91 @@ def _skip_gguf_value(f, vtype: int) -> bool:
return True
+def _parse_gguf_has_classifier_head(path: str) -> Optional[bool]:
+ """Whether the GGUF tensor table contains llama.cpp's ``cls.*`` head."""
+ try:
+ with open(path, "rb") as f:
+ head = f.read(24)
+ if len(head) < 24:
+ return None
+ magic, _version, tensor_count, kv_count = struct.unpack("<IIQQ", head)
+ if magic != _GGUF_MAGIC or tensor_count > 1 << 20 or kv_count > 1 << 20:
+ return None
+
+ for _ in range(kv_count):
+ klen_bytes = f.read(8)
+ if len(klen_bytes) < 8:
+ return None
+ klen = struct.unpack("<Q", klen_bytes)[0]
+ if klen > 1 << 20 or len(f.read(klen)) < klen:
+ return None
+ vtype_bytes = f.read(4)
+ if len(vtype_bytes) < 4 or not _skip_gguf_value(
+ f, struct.unpack("<I", vtype_bytes)[0]
+ ):
+ return None
+
+ for _ in range(tensor_count):
+ nlen_bytes = f.read(8)
+ if len(nlen_bytes) < 8:
+ return None
+ nlen = struct.unpack("<Q", nlen_bytes)[0]
+ if nlen > 1 << 20:
+ return None
+ name_bytes = f.read(nlen)
+ ndim_bytes = f.read(4)
+ if len(name_bytes) < nlen or len(ndim_bytes) < 4:
+ return None
+ n_dimensions = struct.unpack("<I", ndim_bytes)[0]
+ if n_dimensions > 16:
+ return None
+ # dimensions (u64 each), ggml type (u32), and data offset (u64)
+ trailer_size = n_dimensions * 8 + 4 + 8
+ if len(f.read(trailer_size)) < trailer_size:
+ return None
+ if name_bytes.decode("utf-8", "replace").startswith("cls."):
+ return True
+ except OSError as e:
+ logger.debug(f"_parse_gguf_has_classifier_head: cannot open {path}: {e}")
+ return None
+ except Exception as e:
+ logger.debug(f"_parse_gguf_has_classifier_head: parse failure on {path}: {e}")
+ return None
+ return False
+
+
+def _gguf_shard_has_classifier_head(path: str) -> Optional[bool]:
+ key = _cache_key(path)
+ if key is None:
+ return None
+ with _CACHE_LOCK:
+ if key in _CLASSIFIER_HEAD_CACHE:
+ return _CLASSIFIER_HEAD_CACHE[key]
+ result = _parse_gguf_has_classifier_head(path)
+ with _CACHE_LOCK:
+ while len(_CLASSIFIER_HEAD_CACHE) >= _CACHE_MAX_ENTRIES:
+ try:
+ _CLASSIFIER_HEAD_CACHE.pop(next(iter(_CLASSIFIER_HEAD_CACHE)))
+ except StopIteration:
+ break
+ _CLASSIFIER_HEAD_CACHE[key] = result
+ return result
+
+
+def _gguf_has_classifier_head(path: str) -> Optional[bool]:
+ try:
+ from utils.models.model_config import colocated_split_shards
+ shards, complete = colocated_split_shards(Path(path))
+ except Exception:
+ return None
+ if not complete:
+ return None
+ results = [_gguf_shard_has_classifier_head(str(shard)) for shard in shards]
+ if any(result is True for result in results):
+ return True
+ return False if results and all(result is False for result in results) else None
+
+
def _parse_gguf_bool(path: str, wanted_key: str) -> Optional[bool]:
"""Bool value of ``wanted_key`` (GGUF vtype 7), or ``None`` if absent /
unreadable. Mirrors ``_parse_gguf_header`` for a single bool key."""
@@ -573,6 +662,91 @@ def pairing_score(
return 0
+# GGUF ``general.architecture`` values that intrinsically identify embedding
+# models in llama.cpp. Generic ``bert`` is deliberately absent: without
+# pooling_type its required CLS/MEAN pooling cannot be recovered safely.
+# A ``cls.*`` tensor makes an encoder a sequence-classification/reranker model
+# instead, so architecture matches are gated on the tensor table below.
+GGUF_EMBEDDING_ARCHITECTURES: frozenset[str] = frozenset(
+ {
+ "modern-bert",
+ "nomic-bert",
+ "nomic-bert-moe",
+ "neo-bert",
+ "jina-bert-v2",
+ "jina-bert-v3",
+ "eurobert",
+ "gemma-embedding",
+ "pangu-embedded",
+ "llama-embed",
+ }
+)
+
+# Name hints for model, file and intrinsic GGUF names whose architecture is not yet above.
+_EMBEDDING_NAME_HINTS: tuple[str, ...] = (
+ "nomic-embed",
+ "llama-embed",
+ "embed-text",
+ "embedding",
+ "bge-",
+ "gte-",
+ "e5-",
+ "minilm",
+)
+_RERANKER_NAME_HINTS: tuple[str, ...] = ("reranker", "rerank")
+
+
+def is_gguf_embedding_architecture(architecture: Optional[str]) -> bool:
+ """True when ``architecture`` is a dedicated llama.cpp embedding arch."""
+ return bool(architecture and architecture.strip().lower() in GGUF_EMBEDDING_ARCHITECTURES)
+
+
+def _has_embedding_name_hint(value: Optional[str]) -> bool:
+ return bool(value and any(needle in value.strip().lower() for needle in _EMBEDDING_NAME_HINTS))
+
+
+def _has_reranker_name_hint(value: Optional[str]) -> bool:
+ return bool(value and any(needle in value.strip().lower() for needle in _RERANKER_NAME_HINTS))
+
+
+def is_gguf_embedding_model(
+ gguf_path: str,
+ model_identifier: Optional[str] = None,
+ architecture: Optional[str] = None,
+) -> bool:
+ """Whether a GGUF should be launched with ``--embedding`` for /v1/embeddings."""
+ meta = read_gguf_general_metadata(gguf_path) or {}
+ identifier_basename = None
+ if model_identifier:
+ identifier_basename = model_identifier.strip().replace("\\", "/").rsplit("/", 1)[-1]
+ try:
+ file_basename: Optional[str] = Path(gguf_path).name
+ except Exception:
+ file_basename = None
+ name_candidates = (
+ identifier_basename,
+ file_basename,
+ meta.get("general.name"),
+ meta.get("general.basename"),
+ meta.get("general.base_model.0.name"),
+ )
+ if any(_has_reranker_name_hint(value) for value in name_candidates):
+ return False
+
+ arch = (architecture or meta.get("general.architecture") or "").strip().lower()
+ if arch == "bert":
+ # A classifier head can prove that generic BERT is a reranker, but its
+ # absence cannot recover the missing pooling strategy. llama-server
+ # otherwise defaults to NONE and /v1/embeddings returns HTTP 400.
+ return False
+ if is_gguf_embedding_architecture(arch):
+ # Generic BERT-family architectures also back cross-encoder rerankers.
+ # Their standardized cls.* tensors are intrinsic evidence of that role;
+ # an unreadable tensor table stays unclassified rather than guessing.
+ return _gguf_has_classifier_head(gguf_path) is False
+ return any(_has_embedding_name_hint(value) for value in name_candidates)
+
+
# ── speech / codec architectures ────────────────────────────────────────────
# Not defined here, and deliberately not re-exported either: they live in the leaf module