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.

Serve decision models through llama.cpp in Studio, and export them to GGUF (#12939)

Daniel Han15f715afd695
diff --git a/studio/backend/core/export/decision.py b/studio/backend/core/export/decision.py
new file mode 100644
index 00000000000..0106d52a973
--- /dev/null
+++ b/studio/backend/core/export/decision.py
@@ -0,0 +1,270 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GGUF export of decision models (Clef, Laya) for the Export page.
+
+The server side (``decision_preview``) only reads files: the parent process must not import
+unsloth. The worker side (``run_decision_gguf_export``) calls unsloth.models.decision_gguf,
+whose ``gguf_eligibility`` is the authoritative gate.
+"""
+
+import json
+from pathlib import Path
+from typing import Optional
+
+# Mirrors unsloth.models.decision_gguf.DECISION_GGUF_QUANTIZATIONS (first = default); a test pins it.
+DECISION_GGUF_QUANTIZATIONS = ("q8_0", "f16", "bf16", "q6_k", "q5_k_m", "q4_k_m")
+_CLEF_ARCHITECTURES = ("Qwen3_5ForConditionalGeneration", "Qwen3_5ForCausalLM")
+_CLEF_HEAD_FILES = ("joint_head.safetensors", "joint_head_config.json")
+_LAYA_FILES = ("rl_agent_config.json", "model.safetensors")
+_LAYA_DIRS = ("encoder", "tokenizer")
+
+
+class DecisionExportError(ValueError):
+ """A decision checkpoint that cannot be exported to GGUF; the message is shown to the user."""
+
+
+def _read_json(path: Path) -> Optional[dict]:
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8-sig"))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _local_dir(checkpoint_path) -> Optional[Path]:
+ if not checkpoint_path:
+ return None
+ try:
+ folder = Path(str(checkpoint_path)).expanduser()
+ return folder if folder.is_dir() else None
+ except (OSError, ValueError):
+ return None
+
+
+def decision_kind(checkpoint_path) -> Optional[tuple]:
+ """(layout, adapter_only) for a local decision checkpoint folder, else None. File checks only."""
+ folder = _local_dir(checkpoint_path)
+ if folder is None:
+ return None
+ # Same file rules as unsloth.models.decision.is_decision_checkpoint; merged weights win.
+ if all((folder / name).is_file() for name in _CLEF_HEAD_FILES):
+ if (folder / "config.json").is_file():
+ return "clef", False
+ if (folder / "adapter_config.json").is_file():
+ return "clef", True
+ if all((folder / name).is_file() for name in _LAYA_FILES) and all(
+ (folder / name).is_dir() for name in _LAYA_DIRS
+ ):
+ return "laya", False
+ return None
+
+
+def _cached_base_config(base: str) -> Optional[dict]:
+ local = _local_dir(base)
+ if local is not None:
+ return _read_json(local / "config.json")
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ cached = try_to_load_from_cache(base, "config.json")
+ except Exception:
+ return None
+ return _read_json(Path(cached)) if isinstance(cached, str) else None
+
+
+def _preview_eligibility(folder: Path, layout: str) -> tuple:
+ """(eligible, reason); eligible None when only the worker can tell (base config not on disk)."""
+ if layout == "laya":
+ encoder = _read_json(folder / "encoder" / "config.json") or {}
+ model_type = encoder.get("model_type")
+ if model_type == "modernbert":
+ return True, None
+ return False, (
+ "GGUF export of Laya decision models needs a ModernBERT encoder, and this one is "
+ f"{model_type or 'unknown'}. It still serves through PyTorch in Studio's Decision API."
+ )
+ config = _read_json(folder / "config.json")
+ if config is None:
+ base = (_read_json(folder / "unsloth_decision_config.json") or {}).get("base_model") or (
+ _read_json(folder / "adapter_config.json") or {}
+ ).get("base_model_name_or_path")
+ config = _cached_base_config(str(base)) if base else None
+ if config is None:
+ return None, None
+ architectures = list(config.get("architectures") or [])
+ if any(name in _CLEF_ARCHITECTURES for name in architectures):
+ return True, None
+ return False, (
+ "GGUF export of this decision model is not supported: llama.cpp's decision graph is "
+ f"built for Qwen3.5 backbones only, and this one is {', '.join(architectures) or 'unknown'}. "
+ "It still serves through PyTorch in Studio's Decision API."
+ )
+
+
+def read_existing_export(folder) -> Optional[dict]:
+ try:
+ from core.systemone.gguf_export_contract import read_export
+ except Exception:
+ return None
+ try:
+ return read_export(folder)
+ except Exception:
+ return None
+
+
+def current_export(folder, layout: str) -> Optional[dict]:
+ """export.json when it was made from the folder as it is now, listing only quantizations
+ whose files exist; None for a missing, stale or empty export."""
+ try:
+ from core.systemone.gguf_export_contract import EXPORT_DIR, fingerprint
+ except Exception:
+ return None
+ data = read_existing_export(folder)
+ if data is None or data["layout"] != layout:
+ return None
+ try:
+ if data["source_fingerprint"] != fingerprint(folder, layout):
+ return None
+ except Exception:
+ return None
+ directory = Path(folder) / EXPORT_DIR
+ present = {}
+ for quant in data["quantizations"]:
+ entry = data["files"][quant]
+ names = [entry["model"]] + ([entry["mmproj"]] if entry.get("mmproj") else [])
+ if quant not in present and all((directory / name).is_file() for name in names):
+ present[quant] = entry
+ if not present:
+ return None
+ return {**data, "quantizations": list(present), "files": present}
+
+
+def decision_preview(checkpoint_path) -> Optional[dict]:
+ """The Export page's decision block for a local folder, or None for a non-decision model."""
+ kind = decision_kind(checkpoint_path)
+ if kind is None:
+ return None
+ layout, adapter_only = kind
+ folder = Path(str(checkpoint_path)).expanduser()
+ eligible, reason = _preview_eligibility(folder, layout)
+ return {
+ "is_decision": True,
+ "layout": layout,
+ "adapter_only": adapter_only,
+ "eligible": eligible,
+ "reason": reason,
+ "quantizations": list(DECISION_GGUF_QUANTIZATIONS),
+ "default_quantization": DECISION_GGUF_QUANTIZATIONS[0],
+ "output_dir": str(folder / "gguf"),
+ "existing_export": current_export(folder, layout),
+ }
+
+
+def normalize_decision_quants(quantization_method) -> list:
+ methods = (
+ [quantization_method]
+ if isinstance(quantization_method, str)
+ else list(quantization_method or [])
+ )
+ chosen = []
+ for method in methods:
+ method = str(method).strip().lower()
+ if not method:
+ continue
+ if method not in DECISION_GGUF_QUANTIZATIONS:
+ raise DecisionExportError(
+ f"Decision models export to GGUF as one of "
+ f"{', '.join(q.upper() for q in DECISION_GGUF_QUANTIZATIONS)}, not {method.upper()}."
+ )
+ if method not in chosen:
+ chosen.append(method)
+ return chosen or [DECISION_GGUF_QUANTIZATIONS[0]]
+
+
+def adapter_base(checkpoint_path) -> str:
+ """The base an adapter-only decision folder loads; both configs must name the same one."""
+ folder = Path(str(checkpoint_path)).expanduser()
+ names = []
+ for name, key in (
+ ("unsloth_decision_config.json", "base_model"),
+ ("adapter_config.json", "base_model_name_or_path"),
+ ):
+ try:
+ value = json.loads((folder / name).read_text(encoding = "utf-8")).get(key)
+ except (OSError, ValueError, AttributeError):
+ value = None
+ if value:
+ names.append(str(value))
+ if not names:
+ raise DecisionExportError(f"{folder} has adapters but does not name their base model.")
+ if len(set(names)) > 1:
+ raise DecisionExportError(
+ f"{folder} names two different base models ({names[0]} and {names[1]}); "
+ "re-save it with FastDecisionModel.save_pretrained."
+ )
+ return names[0]
+
+
+def check_decision_eligibility(
+ checkpoint_path,
+ token = None,
+ local_files_only = False,
+) -> dict:
+ """gguf_eligibility from the library; raises DecisionExportError with its reason when ineligible."""
+ from unsloth.models.decision_gguf import gguf_eligibility
+
+ eligibility = gguf_eligibility(
+ str(Path(str(checkpoint_path)).expanduser()), token, local_files_only
+ )
+ if not eligibility.get("eligible"):
+ raise DecisionExportError(
+ eligibility.get("reason") or "This decision model cannot be exported to GGUF."
+ )
+ return eligibility
+
+
+def run_decision_gguf_export(
+ checkpoint_path,
+ quantization_method,
+ local_files_only: bool = False,
+ print_output: bool = False,
+ token = None,
+) -> dict:
+ """Writes <checkpoint_path>/gguf/ and returns its export.json content. ``token`` reaches the
+ base model download of an adapter folder (False = anonymous, None = ambient)."""
+ folder = Path(str(checkpoint_path)).expanduser()
+ quants = normalize_decision_quants(quantization_method)
+ kind = decision_kind(folder)
+ if kind is None:
+ raise DecisionExportError(f"{folder} is not a decision model checkpoint.")
+ check_decision_eligibility(folder, token, local_files_only)
+ _, adapter_only = kind
+ if adapter_only:
+ # Adapters only: FastDecisionModel keeps the head and calibration, save_pretrained_gguf merges.
+ from unsloth import FastDecisionModel
+ model, processor = FastDecisionModel.from_pretrained(
+ str(folder),
+ load_in_4bit = False,
+ use_gradient_checkpointing = False,
+ local_files_only = local_files_only,
+ token = token,
+ )
+ try:
+ return model.save_pretrained_gguf(
+ str(folder),
+ processor,
+ quantization_method = quants,
+ source_folder = str(folder),
+ print_output = print_output,
+ token = token,
+ )
+ finally:
+ del model
+ from unsloth.models.decision_gguf import export_decision_gguf
+
+ return export_decision_gguf(
+ str(folder),
+ quants,
+ source_folder = str(folder),
+ print_output = print_output,
+ )
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index f5fe5099f95..6bacad38e63 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -689,6 +689,9 @@ def _publish_unsloth_model_card(hf_api, repo_id, model, hf_token):
class ExportBackend:
+ # {"layout", "adapter_only"} for a decision checkpoint (GGUF only), else None.
+ decision: Optional[dict] = None
+
def __init__(self):
self.inference_backend = get_inference_backend()
self.current_checkpoint = None
@@ -697,6 +700,7 @@ class ExportBackend:
self.is_vision = False
self.is_peft = False
self._audio_type = None
+ self.decision = None
def cleanup_memory(self):
"""Offload and delete all models from memory"""
@@ -711,6 +715,7 @@ class ExportBackend:
self.current_tokenizer = None
self.current_checkpoint = None
self._audio_type = None
+ self.decision = None
clear_gpu_cache()
@@ -766,6 +771,18 @@ class ExportBackend:
self.cleanup_memory()
+ # Before the base / audio / vision probes: a decision run never reaches the chat loaders.
+ from core.export.decision import decision_kind
+
+ decision = decision_kind(checkpoint_path)
+ if decision is not None:
+ return self._load_decision_checkpoint(
+ str(Path(checkpoint_path).expanduser()),
+ *decision,
+ token = token,
+ base_model = base_model,
+ )
+
checkpoint_path_obj = Path(checkpoint_path)
adapter_config = checkpoint_path_obj / "adapter_config.json"
@@ -977,6 +994,83 @@ class ExportBackend:
_device_map_override = {"device_map": "sequential"},
)
+ def _load_decision_checkpoint(
+ self,
+ checkpoint_path: str,
+ layout: str,
+ adapter_only: bool,
+ token: HfTokenArg = None,
+ base_model: Optional[str] = None,
+ ) -> Tuple[bool, str]:
+ """Records a decision checkpoint; its weights load (adapters) or convert (merged) at export."""
+ from core.export.decision import (
+ DecisionExportError,
+ adapter_base,
+ check_decision_eligibility,
+ )
+
+ if not _export_runtime_available():
+ return False, _export_runtime_message()
+ if adapter_only:
+ # The base FastDecisionModel will load must be the one the route authorized and scanned.
+ try:
+ resolved = adapter_base(checkpoint_path)
+ except DecisionExportError as exc:
+ return False, str(exc)
+ if base_model and resolved != base_model:
+ return False, (
+ f"This adapter loads {resolved}, not the authorized base model {base_model}."
+ )
+ try:
+ check_decision_eligibility(checkpoint_path, token)
+ except DecisionExportError as exc:
+ return False, str(exc)
+ self.decision = {"layout": layout, "adapter_only": adapter_only}
+ # An adapter folder loads its base at export time, under the credential of this load.
+ self._decision_token = token
+ self.is_vision = False
+ self.is_peft = adapter_only
+ self.current_checkpoint = checkpoint_path
+ name = "Clef" if layout == "clef" else "Laya"
+ kind = "LoRA adapters" if adapter_only else "merged"
+ logger.info(f"Decision checkpoint ({name}, {kind}) ready for GGUF export")
+ return True, f"Loaded {name} decision model ({kind}); it exports to GGUF only"
+
+ def _export_decision_gguf(
+ self, quantization_method, push_to_hub: bool, imatrix_file, npu_q4nx: bool
+ ) -> Tuple[bool, str, Optional[str]]:
+ if push_to_hub:
+ return (
+ False,
+ "Decision model GGUF export saves to the run folder only; Hub upload is not supported.",
+ None,
+ )
+ if imatrix_file or npu_q4nx:
+ return (
+ False,
+ "Decision model GGUF export does not support imatrix or Q4NX conversion.",
+ None,
+ )
+ from core.export.decision import DecisionExportError, run_decision_gguf_export
+
+ try:
+ data = run_decision_gguf_export(
+ self.current_checkpoint,
+ quantization_method,
+ local_files_only = _hf_offline(),
+ print_output = True,
+ token = getattr(self, "_decision_token", None),
+ )
+ except (DecisionExportError, ValueError, RuntimeError) as exc:
+ logger.error(f"Decision GGUF export failed: {exc}")
+ return False, str(exc), None
+ output_dir = str(Path(self.current_checkpoint).resolve() / "gguf")
+ quants = ", ".join((data or {}).get("quantizations") or [])
+ return True, f"Decision model exported to GGUF ({quants}) in {output_dir}", output_dir
+
+ def _decision_only_gguf(self) -> Tuple[bool, str, Optional[str]]:
+ return False, "Decision models export to GGUF only.", None
+
def _write_export_metadata(self, save_directory: str):
"""Write export_metadata.json with base model info for Chat page discovery."""
try:
@@ -1017,6 +1111,8 @@ class ExportBackend:
w4a16, mxfp4, mxfp8, nvfp4); it overrides ``format_type`` and is resolved against
unsloth.save COMPRESSED_EXPORT_SCHEMES.
"""
+ if self.decision is not None:
+ return self._decision_only_gguf()
if not _export_runtime_available():
return False, _export_runtime_message(), None
if not self.current_model or not self.current_tokenizer:
@@ -1311,6 +1407,8 @@ class ExportBackend:
private: bool = False,
base_model_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
+ if self.decision is not None:
+ return self._decision_only_gguf()
if not _export_runtime_available():
return False, _export_runtime_message(), None
if not self.current_model or not self.current_tokenizer:
@@ -1446,6 +1544,10 @@ class ExportBackend:
"""
if not _export_runtime_available():
return False, _export_runtime_message(), None
+ if self.decision is not None:
+ return self._export_decision_gguf(
+ quantization_method, push_to_hub, imatrix_file, npu_q4nx
+ )
if not self.current_model or not self.current_tokenizer:
return False, "No model loaded. Please select a checkpoint first.", None
@@ -1977,6 +2079,8 @@ class ExportBackend:
q8_0/f16/bf16/f32. ``adapter_format`` is 'mlx' or 'peft' (MLX servers only offer both);
omitted resolves to the platform's native format.
"""
+ if self.decision is not None:
+ return self._decision_only_gguf()
if not _export_runtime_available():
return False, _export_runtime_message(), None
if not self.current_model or not self.current_tokenizer:
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index bbf3a630d5e..537287a6066 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -58,6 +58,7 @@ class ExportOrchestrator:
self.current_checkpoint: Optional[str] = None
self.is_vision: bool = False
self.is_peft: bool = False
+ self.decision: Optional[Dict[str, Any]] = None
# Thread-safe ring buffer of worker log lines; powers the export logs SSE endpoint.
self._log_buffer: Deque[Dict[str, Any]] = deque(maxlen = _LOG_BUFFER_MAXLEN)
@@ -87,6 +88,7 @@ class ExportOrchestrator:
def _clear_account_result(self):
self.current_checkpoint = None
self.is_vision = self.is_peft = False
+ self.decision = None
self._last_op = None
self.clear_logs()
@@ -559,6 +561,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ self.decision = None
raise
try:
@@ -568,6 +571,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ self.decision = None
op_success, op_message = False, str(exc)
return False, str(exc)
@@ -575,6 +579,7 @@ class ExportOrchestrator:
self.current_checkpoint = resp.get("checkpoint")
self.is_vision = resp.get("is_vision", False)
self.is_peft = resp.get("is_peft", False)
+ self.decision = resp.get("decision")
logger.info("Checkpoint '%s' loaded in subprocess", checkpoint_path)
op_success, op_message = True, resp.get("message", "Loaded successfully")
return True, op_message
@@ -584,6 +589,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ self.decision = None
op_success, op_message = False, error
return False, error
finally:
@@ -753,6 +759,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ self.decision = None
return True
self._active_op_kind = "cleanup"
@@ -775,6 +782,7 @@ class ExportOrchestrator:
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
+ self.decision = None
return success
finally:
self._record_op_finished(success, "", None)
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index 9d5e6408860..e0f1e87be39 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -391,6 +391,7 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:
"checkpoint": checkpoint_path if success else None,
"is_vision": backend.is_vision if success else False,
"is_peft": backend.is_peft if success else False,
+ "decision": getattr(backend, "decision", None) if success else None,
"ts": time.time(),
},
)
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index 99a47f51100..238db506e90 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -21,6 +21,8 @@ logger = get_logger(__name__)
CHAT = "chat"
DIFFUSION = "diffusion"
VIDEO = "video"
+# A Decision API llama.cpp server on the GPU (the PyTorch Clef worker is not arbitrated).
+DECISIONS = "decisions"
_lock = threading.Lock()
_owner: Optional[str] = None
@@ -92,9 +94,19 @@ def _evict_video() -> None:
get_video_backend().unload()
+def _evict_decisions() -> None:
+ from core.systemone.laya_runtime import evict_for_gpu
+ evict_for_gpu()
+
+
# Patchable in tests via monkeypatch.setitem. Ownership is exclusive, so acquire_for's evict-the-current-owner
# generalises to any number of owners.
-_EVICTORS = {CHAT: _evict_chat, DIFFUSION: _evict_diffusion, VIDEO: _evict_video}
+_EVICTORS = {
+ CHAT: _evict_chat,
+ DIFFUSION: _evict_diffusion,
+ VIDEO: _evict_video,
+ DECISIONS: _evict_decisions,
+}
class GpuOwnerBusyError(RuntimeError):
diff --git a/studio/backend/core/systemone/catalog.py b/studio/backend/core/systemone/catalog.py
index cf13a5636d8..3ac1bf333bf 100644
--- a/studio/backend/core/systemone/catalog.py
+++ b/studio/backend/core/systemone/catalog.py
@@ -21,14 +21,27 @@ class Checkpoint:
subfolder: str | None
description: str
download_bytes: int = 0
- # "laya" (rl_agent_config.json + encoder) or "clef" (Qwen3.5 backbone + joint schema head).
+ # "laya" (rl_agent_config.json + encoder), "clef" (Qwen3.5 backbone + joint schema head), or
+ # "gguf" (a GGUF_COMPANIONS entry llama.cpp serves, with no PyTorch form).
layout: str = "laya"
+ # "pytorch", or "llama.cpp" for the GGUF a Clef entry is served from (see laya_runtime._native_target).
+ backend: str = "pytorch"
+ # The served GGUF files of a local export, so a re-export is a different checkpoint to a resident server.
+ revision: str | None = None
+ # Display name where the frontend has none of its own.
+ label: str | None = None
@property
def is_local(self) -> bool:
return Path(self.source).expanduser().is_dir()
+def _gguf(name: str, label: str, repo: str, description: str, download_bytes: int) -> Checkpoint:
+ return Checkpoint(
+ name, repo, None, description, download_bytes, "gguf", "llama.cpp", label = label
+ )
+
+
CHECKPOINTS = {
c.name: c
for c in (
@@ -69,9 +82,177 @@ CHECKPOINTS = {
54_976_000_000,
"clef",
),
+ _gguf(
+ "kev-0.8b",
+ "Kev 0.8B",
+ "ggml-org/Kev-0.8B-GGUF",
+ "Kev 0.8B (Q8_0 GGUF, llama.cpp only): small and fast, text only, runs on CPU.",
+ 812_406_304,
+ ),
+ _gguf(
+ "kev-4b",
+ "Kev 4B",
+ "ggml-org/Kev-4B-GGUF",
+ "Kev 4B (Q8_0 GGUF, llama.cpp only): text only, a GPU is recommended.",
+ 4_483_801_504,
+ ),
+ _gguf(
+ "kev-9b",
+ "Kev 9B",
+ "ggml-org/Kev-9B-GGUF",
+ "Kev 9B (Q8_0 GGUF, llama.cpp only): text only, needs a GPU.",
+ 9_529_735_648,
+ ),
+ _gguf(
+ "lev",
+ "lev",
+ "ggml-org/lev-GGUF",
+ "Interfaze lev on Qwen3.5 4B (Q8_0 GGUF, llama.cpp only): text only, a GPU is recommended.",
+ 4_482_405_280,
+ ),
+ _gguf(
+ "bespoke-nimble-9b-v3",
+ "Bespoke Nimble 9B v3",
+ "ggml-org/Bespoke-Nimble-9B-v3-GGUF",
+ "Bespoke Nimble 9B v3 (Q8_0 GGUF, llama.cpp only): text only, needs a GPU. "
+ "Non-commercial license (CC BY-NC 4.0).",
+ 9_527_503_392,
+ ),
+ _gguf(
+ "openjev",
+ "OpenJev",
+ "ggml-org/OpenJev-GGUF",
+ "OpenJev 27B (Q8_0 GGUF, llama.cpp only): text and images, needs a large GPU. "
+ "Non-commercial license (CC BY-NC 4.0).",
+ 28_595_765_408 + 629_247_232,
+ ),
+ _gguf(
+ "laya-gguf",
+ "Laya GGUF",
+ "ggml-org/Laya-GGUF",
+ "Laya (Q8_0 GGUF, llama.cpp only): small, text only, runs on CPU.",
+ 449_397_600,
+ ),
+ _gguf(
+ "julia-1",
+ "Julia-1",
+ "ggml-org/Julia-1-GGUF",
+ "Supersonic Julia-1 (Q8_0 GGUF, llama.cpp only): the smallest, text only, runs on CPU.",
+ 168_166_496,
+ ),
)
}
+
+@dataclass(frozen = True)
+class GgufCompanion:
+ repo: str
+ revision: str
+ model: str
+ mmproj: str | None
+ download_bytes: int
+ # LFS sha256 of model, mmproj: the Hub cache names blobs by it, so a copy fetched at another revision is found.
+ sha256: tuple[str, ...] = ()
+
+
+# ggml-org GGUFs served by llama.cpp's /v1/systemone (b11443 and newer).
+GGUF_COMPANIONS = {
+ "clef-flash": GgufCompanion(
+ "ggml-org/Clef-Flash-GGUF",
+ "4a192915ef971886004b5b13294f2b4c7a7fc39d",
+ "Clef-Flash-Q8_0.gguf",
+ "mmproj-Clef-Flash-Q8_0.gguf",
+ 9_657_260_192 + 624_229_728,
+ (
+ "d7c352faf1bdd9ea24d0b9347e8eb1eb4bbadeff6c02383bf750215a74f2f1f1",
+ "3fbc646617c56c35ba48e06f0fbe8693a83bde49eb31e2a3bf59ba0a308c9e25",
+ ),
+ ),
+ "clef": GgufCompanion(
+ "ggml-org/Clef-GGUF",
+ "63840a1a68cb7084c88610cffc328509356b04cb",
+ "Clef-Q8_0.gguf",
+ "mmproj-Clef-Q8_0.gguf",
+ 28_732_215_360 + 629_247_424,
+ (
+ "07c6410af7011e0e56873a3b0b3f4ad9e31fb176f0ca80d6fd1525fe6f036548",
+ "0d901ea999ae122ba0afeb4a3f4c4ac9a90baa07f1d120df9c350082db1190a8",
+ ),
+ ),
+ **{
+ name: GgufCompanion(repo, revision, model, mmproj, CHECKPOINTS[name].download_bytes, sha256)
+ for name, repo, revision, model, mmproj, sha256 in (
+ (
+ "kev-0.8b",
+ "ggml-org/Kev-0.8B-GGUF",
+ "e551e319d483ff57e1ff208924b349d397cffc1c",
+ "Kev-0.8B-Q8_0.gguf",
+ None,
+ ("27278f34eb3273bceea4c053dc50dd61a5161da21a718c4aacdf8fd5830771d0",),
+ ),
+ (
+ "kev-4b",
+ "ggml-org/Kev-4B-GGUF",
+ "d924f2e2c3872da8b8aaf3eb4453b4126deceb79",
+ "Kev-4B-Q8_0.gguf",
+ None,
+ ("7c2ebed90560522c2801389db482ac1dc4c36d828f201f6074c1d60e433948da",),
+ ),
+ (
+ "kev-9b",
+ "ggml-org/Kev-9B-GGUF",
+ "ec2bbfe6620218aee2e01cc93bb78dee2a96ed58",
+ "Kev-9B-Q8_0.gguf",
+ None,
+ ("d30b225bfdc985d1856bb04a990be76008d0cf40dccbf78938e3069744bc614c",),
+ ),
+ (
+ "lev",
+ "ggml-org/lev-GGUF",
+ "3e9286a79ae857b4e1de051c92fab6dc574581ce",
+ "lev-Q8_0.gguf",
+ None,
+ ("c6b70833a9ec59c67bda2940f4047c2e1bdc066b4a6f8aec3c36d62b6ea34eef",),
+ ),
+ (
+ "bespoke-nimble-9b-v3",
+ "ggml-org/Bespoke-Nimble-9B-v3-GGUF",
+ "a72bdbadb355ca3014f7f9d2585380917cc59971",
+ "Bespoke-Nimble-9B-v3-Q8_0.gguf",
+ None,
+ ("ad484077ad28c1ba0644509b81e80268f8fd39e9d218415638a988caf3c6e66c",),
+ ),
+ (
+ "openjev",
+ "ggml-org/OpenJev-GGUF",
+ "10840f375658dea7afc5ff4711127bca8218b560",
+ "OpenJev-Q8_0.gguf",
+ "mmproj-OpenJev-Q8_0.gguf",
+ (
+ "5e5574cfeb9145809d3ebe3e854761d62a947033d3f76af4c4b1dd8562409412",
+ "e372cdbf59fdd6bd2504cb64c988b31c7a42ac406a8f711df4b7a7acd9216f1e",
+ ),
+ ),
+ (
+ "laya-gguf",
+ "ggml-org/Laya-GGUF",
+ "22265007700297ba9e128297e82540cf28c5d7d4",
+ "Laya-Q8_0.gguf",
+ None,
+ ("c06528c5746d3bb8baa72a27938be95abbfd0b226f8471e8a9e365ed0bb066d2",),
+ ),
+ (
+ "julia-1",
+ "ggml-org/Julia-1-GGUF",
+ "16fee17949206fbf58da9347daea44d792a81211",
+ "Julia-1-Q8_0.gguf",
+ None,
+ ("1ea6a7e87156eeeda88cb7a36a61265b37ba7b993897b7289b99aea5b5e47069",),
+ ),
+ )
+ },
+}
+
# Names TypeSafe's and OpenJev's SDKs send by default, so an unmodified client reaches the configured model.
DEFAULT_ALIASES = frozenset({"default", "laya", "jev-latest", "jev-preview", "openjev-latest"})
LOCAL_NAME = "laya-local"
diff --git a/studio/backend/core/systemone/gguf_export_contract.py b/studio/backend/core/systemone/gguf_export_contract.py
new file mode 100644
index 00000000000..cfa1a4a8ff5
--- /dev/null
+++ b/studio/backend/core/systemone/gguf_export_contract.py
@@ -0,0 +1,134 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""On-disk contract for a decision fine-tune's GGUF export, shared by the exporter and the Decision API.
+
+An export lives in ``<run folder>/gguf/``: ``model-<QUANT>.gguf``, an optional ``mmproj-<QUANT>.gguf``
+and ``export.json``::
+
+ {"format": "unsloth-decision-gguf", "version": 1, "layout": "clef" | "laya",
+ "quantizations": ["Q8_0", ...],
+ "files": {"Q8_0": {"model": "model-Q8_0.gguf", "mmproj": "mmproj-Q8_0.gguf" | null}},
+ "source_fingerprint": fingerprint(run folder, layout)}
+
+The fingerprint covers what the served probabilities depend on, so retraining or recalibrating the
+folder makes an older export stale.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+EXPORT_DIR = "gguf"
+EXPORT_FILE = "export.json"
+FORMAT = "unsloth-decision-gguf"
+VERSION = 1
+LAYOUTS = ("clef", "laya")
+FINGERPRINT_FILES = {
+ "clef": ("unsloth_decision_config.json", "joint_head_config.json", "joint_head.safetensors"),
+ "laya": ("rl_agent_config.json", "model.safetensors"),
+}
+# Served quantization, best first; any other listed one after these.
+PREFERRED = ("Q8_0", "F16", "BF16")
+_CHUNK = 1 << 20
+_stale_logged: set[tuple[str, str]] = set()
+
+
+@lru_cache(maxsize = 64)
+def _file_digest(path: str, size: int, mtime_ns: int) -> bytes:
+ digest = hashlib.sha256()
+ with open(path, "rb") as source:
+ while chunk := source.read(_CHUNK):
+ digest.update(chunk)
+ return digest.digest()
+
+
+def fingerprint(folder: str | Path, layout: str) -> str:
+ """sha256 over each fingerprint file as name, NUL, then its sha256 (or ``missing``), in order."""
+ if layout not in FINGERPRINT_FILES:
+ raise ValueError(f"Unknown decision layout: {layout!r}")
+ folder = Path(folder)
+ digest = hashlib.sha256()
+ for name in FINGERPRINT_FILES[layout]:
+ digest.update(name.encode() + b"\0")
+ path = folder / name
+ try:
+ stat = path.stat()
+ digest.update(_file_digest(str(path.resolve()), stat.st_size, stat.st_mtime_ns))
+ except OSError:
+ digest.update(b"missing")
+ return digest.hexdigest()
+
+
+def _plain_name(value: Any) -> bool:
+ return (
+ isinstance(value, str)
+ and bool(value)
+ and value == Path(value).name
+ and value not in (".", "..")
+ and "\\" not in value
+ )
+
+
+def read_export(folder: str | Path) -> dict[str, Any] | None:
+ """The folder's ``gguf/export.json`` if it is well formed and names files that exist, else None."""
+ directory = Path(folder) / EXPORT_DIR
+ try:
+ data = json.loads((directory / EXPORT_FILE).read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ if data.get("format") != FORMAT or data.get("version") != VERSION:
+ return None
+ if data.get("layout") not in LAYOUTS or not isinstance(data.get("source_fingerprint"), str):
+ return None
+ files, quantizations = data.get("files"), data.get("quantizations")
+ if not isinstance(files, dict) or not isinstance(quantizations, list):
+ return None
+ for quant in quantizations:
+ entry = files.get(quant) if isinstance(quant, str) else None
+ if not isinstance(entry, dict) or not _plain_name(entry.get("model")):
+ return None
+ mmproj = entry.get("mmproj")
+ if mmproj is not None and not _plain_name(mmproj):
+ return None
+ return data
+
+
+def served_files(folder: str | Path, layout: str) -> tuple[str, Path, Path | None] | None:
+ """(quantization, model path, mmproj path or None) of the folder's current export, else None.
+
+ An export whose fingerprint no longer matches the folder is stale and ignored (logged once).
+ """
+ folder = Path(folder)
+ data = read_export(folder)
+ if data is None or data["layout"] != layout:
+ return None
+ try:
+ current = fingerprint(folder, layout)
+ except OSError:
+ return None
+ if data["source_fingerprint"] != current:
+ key = (str(folder), data["source_fingerprint"])
+ if key not in _stale_logged:
+ _stale_logged.add(key)
+ logger.info("Ignoring the stale GGUF export in %s: the folder changed since", folder)
+ return None
+ listed = [q for q in data["quantizations"] if isinstance(q, str)]
+ order = [q for q in PREFERRED if q in listed] + [q for q in listed if q not in PREFERRED]
+ directory = folder / EXPORT_DIR
+ for quant in order:
+ entry = data["files"][quant]
+ model = directory / entry["model"]
+ mmproj = directory / entry["mmproj"] if entry.get("mmproj") else None
+ if model.is_file() and (mmproj is None or mmproj.is_file()):
+ return quant, model, mmproj
+ return None
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.py
index b08002fe134..fd2e9b6e355 100644
--- a/studio/backend/core/systemone/laya_runtime.py
+++ b/studio/backend/core/systemone/laya_runtime.py
@@ -5,6 +5,7 @@
from __future__ import annotations
+import dataclasses
import gc
import importlib.util
import logging
@@ -14,7 +15,7 @@ import time
from pathlib import Path
from typing import Any
-from .catalog import CHECKPOINTS, LOCAL_NAME, Checkpoint
+from .catalog import CHECKPOINTS, GGUF_COMPANIONS, LOCAL_NAME, Checkpoint
logger = logging.getLogger(__name__)
@@ -35,8 +36,21 @@ _loaded: Checkpoint | None = None
_device_name: str | None = None
_loader: threading.Thread | None = None
_loading: Checkpoint | None = None
+# A llama.cpp load that holds (or is taking) the GPU claim, until its agent is published or dropped.
+_gpu_load = False
_failure: tuple[Checkpoint, str, float] | None = None
_import_lock = threading.Lock()
+# Bumped whenever the resident agent changes, so a stale idle timer never acts on a newer one.
+_generation = 0
+# Bumped by every unload from outside a load, so a load that finishes after one never publishes.
+_unloads = 0
+_last_used = 0.0
+_idle_timer: threading.Timer | None = None
+_fallback_reason: str | None = None
+# A llama.cpp decision server unloads after this long without a request.
+IDLE_UNLOAD_S = 300.0
+# Binaries (path, mtime) whose server answered without a "decisions" output.
+_incapable: set[tuple[str, int]] = set()
class Unavailable(Exception):
@@ -103,6 +117,261 @@ def _wanted(path: str, subfolder: str | None) -> bool:
return rest in _WEIGHT_FILES or rest.startswith(tuple(f"{name}/" for name in _REQUIRED_DIRS))
+LLAMA_CPP = "llama.cpp"
+GGUF = "gguf"
+
+
+def _is_native(checkpoint) -> bool:
+ return getattr(checkpoint, "backend", "pytorch") == LLAMA_CPP
+
+
+def _native_target(checkpoint: Checkpoint) -> Checkpoint | None:
+ """The llama.cpp form of an entry: ggml-org's GGUF for a stock Clef, a current export for a folder, a GGUF entry itself."""
+ if checkpoint.layout == GGUF:
+ return checkpoint
+ if checkpoint.layout != "clef" or _is_native(checkpoint):
+ return None
+ if checkpoint.is_local:
+ from .gguf_export_contract import served_files
+
+ files = served_files(Path(checkpoint.source).expanduser(), "clef")
+ if files is None:
+ return None
+ return dataclasses.replace(
+ checkpoint, backend = LLAMA_CPP, revision = _files_revision(files[1:])
+ )
+ companion = GGUF_COMPANIONS.get(checkpoint.name)
+ if companion is None or CHECKPOINTS.get(checkpoint.name) != checkpoint:
+ return None
+ return dataclasses.replace(
+ checkpoint,
+ source = companion.repo,
+ download_bytes = companion.download_bytes,
+ backend = LLAMA_CPP,
+ )
+
+
+def _files_revision(paths) -> str:
+ parts = []
+ for path in paths:
+ if path is None:
+ continue
+ try:
+ st = path.stat()
+ except OSError:
+ st = None
+ parts.append(f"{path}:{st.st_ino}:{st.st_mtime_ns}:{st.st_size}" if st else str(path))
+ return "|".join(parts)
+
+
+def _native_files(checkpoint: Checkpoint, local_only: bool) -> tuple[Path, Path | None]:
+ if checkpoint.is_local:
+ from .gguf_export_contract import served_files
+
+ files = served_files(Path(checkpoint.source).expanduser(), "clef")
+ if files is None:
+ raise FileNotFoundError(f"No current GGUF export in {checkpoint.source}")
+ return files[1], files[2]
+ from huggingface_hub import hf_hub_download
+
+ from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.utils import hf_env_offline
+
+ companion = GGUF_COMPANIONS[checkpoint.name]
+ cache = active_hf_hub_cache()
+ paths = []
+ for index, name in enumerate(n for n in (companion.model, companion.mmproj) if n):
+ try:
+ path = hf_hub_download(
+ companion.repo,
+ name,
+ revision = companion.revision,
+ cache_dir = cache,
+ local_files_only = local_only or hf_env_offline(),
+ )
+ except Exception:
+ # Settings downloads fetch the repo's main: the same blob there is the pinned file.
+ sha256 = companion.sha256[index] if index < len(companion.sha256) else None
+ if (path := _cached_blob(cache, companion.repo, name, sha256)) is None:
+ raise
+ paths.append(Path(path))
+ return paths[0], (paths[1] if companion.mmproj else None)
+
+
+def _cached_blob(cache, repo: str, name: str, sha256: str | None) -> Path | None:
+ """``name`` in any cached snapshot of ``repo`` whose blob is ``sha256``, else None."""
+ if not sha256:
+ return None
+ if cache is None:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ cache = HF_HUB_CACHE
+ snapshots = Path(cache) / f"models--{repo.replace('/', '--')}" / "snapshots"
+ try:
+ candidates = sorted(snapshots.glob(f"*/{name}"))
+ except OSError:
+ return None
+ for path in candidates:
+ try:
+ if path.resolve(strict = True).name == sha256:
+ return path
+ except (OSError, RuntimeError):
+ continue
+ return None
+
+
+def _binary_key(binary: str) -> tuple[str, int]:
+ try:
+ return binary, Path(binary).stat().st_mtime_ns
+ except OSError:
+ return binary, 0
+
+
+def _native_unavailable(checkpoint: Checkpoint, native: Checkpoint | None) -> str | None:
+ if native is None:
+ if checkpoint.is_local:
+ return "This Clef folder has no current GGUF export."
+ return f"{checkpoint.name} has no GGUF build."
+ from .native_worker import resolve_binary
+
+ binary = resolve_binary()
+ if binary is None:
+ return "llama-server is not installed."
+ if _binary_key(binary) in _incapable:
+ return "This llama.cpp build cannot serve decision models; update llama.cpp in Studio."
+ return None
+
+
+def select(
+ checkpoint: Checkpoint,
+ images = None,
+ questions = None,
+ preference: str | None = None,
+) -> tuple[Checkpoint, str | None]:
+ """(what serves this request, why Auto did not pick llama.cpp); raises for what nothing here can serve.
+
+ Auto takes llama.cpp when the entry has a GGUF and Studio's llama-server serves decisions, else PyTorch.
+ Images are llama.cpp only. Laya is always served by PyTorch, a GGUF entry always by llama.cpp.
+ """
+ from utils.systemone_settings import get_backend
+
+ from .native_worker import request_gap
+
+ if checkpoint.layout == GGUF:
+ return _select_gguf(checkpoint, questions, preference or get_backend()), None
+ if checkpoint.layout != "clef":
+ if images:
+ raise Unavailable(
+ 400, "api_usage_error", "Images need a Clef model; Laya reads text only."
+ )
+ return checkpoint, None
+ preference = preference or get_backend()
+ if preference == "pytorch":
+ if images:
+ raise Unavailable(
+ 400,
+ "api_usage_error",
+ "Images are served only by llama.cpp; set the Decision API runtime to Auto or llama.cpp.",
+ )
+ return checkpoint, None
+ native = _native_target(checkpoint)
+ reason = _native_unavailable(checkpoint, native)
+ if reason is None:
+ reason = request_gap(questions or {})
+ if reason is None:
+ # Auto keeps a resident PyTorch Clef for text rather than reloading the model.
+ resident = _loaded == checkpoint and _agent is not None
+ if preference == "auto" and not images:
+ if resident:
+ return checkpoint, None
+ if (why := _auto_keeps_pytorch(checkpoint, native)) is not None:
+ return checkpoint, why
+ return native, None
+ if preference == LLAMA_CPP or images:
+ raise Unavailable(422, "invalid_request_error", reason)
+ if preference == LLAMA_CPP:
+ status, kind = (
+ (503, "model_unavailable") if native is not None else (400, "api_usage_error")
+ )
+ raise Unavailable(
+ status, kind, f"{reason} Set the Decision API runtime to Auto or PyTorch."
+ )
+ if images:
+ raise Unavailable(400, "api_usage_error", f"Images are served only by llama.cpp: {reason}")
+ return checkpoint, reason
+
+
+def _select_gguf(checkpoint: Checkpoint, questions, preference: str) -> Checkpoint:
+ from .native_worker import request_gap
+
+ if preference == "pytorch":
+ raise Unavailable(
+ 400,
+ "api_usage_error",
+ f"{checkpoint.name} is a GGUF served only by llama.cpp; set the Decision API runtime "
+ "to Auto or llama.cpp.",
+ )
+ if (reason := _native_unavailable(checkpoint, checkpoint)) is not None:
+ raise Unavailable(503, "model_unavailable", f"{checkpoint.name} needs llama.cpp: {reason}")
+ if (reason := request_gap(questions or {})) is not None:
+ raise Unavailable(422, "invalid_request_error", reason)
+ return checkpoint
+
+
+def _auto_keeps_pytorch(checkpoint: Checkpoint, native: Checkpoint) -> str | None:
+ """Why Auto answers text on PyTorch although llama.cpp could: as before llama.cpp existed here."""
+ from core.inference.gpu_arbiter import DECISIONS, current_owner
+
+ from .catalog import clef_unsupported_reason
+
+ if _loaded == native and _agent is not None:
+ return None
+ if clef_unsupported_reason(wait = False) is not None:
+ return None
+ if _native_gpu() and current_owner() not in (None, DECISIONS):
+ return "Another model is using the GPU."
+ if not native.is_local and not is_cached(native) and is_cached(checkpoint):
+ return "The GGUF is not downloaded; the cached PyTorch checkpoint serves."
+ return None
+
+
+def effective_backend(checkpoint) -> tuple[str | None, str | None]:
+ """(backend a text request would use, Auto's reason for PyTorch) for the settings page."""
+ if not isinstance(checkpoint, Checkpoint):
+ return None, None
+ try:
+ target, reason = select(checkpoint)
+ except Unavailable as exc:
+ return None, exc.message
+ return target.backend, reason
+
+
+def native_ready(checkpoint) -> bool:
+ """Whether llama.cpp could serve this Clef or GGUF entry here under the runtime setting."""
+ if not isinstance(checkpoint, Checkpoint) or checkpoint.layout == "laya":
+ return False
+ from utils.systemone_settings import get_backend
+
+ native = _native_target(checkpoint)
+ return get_backend() != "pytorch" and _native_unavailable(checkpoint, native) is None
+
+
+def input_modalities(checkpoint) -> list[str]:
+ """What this entry reads here: images too when llama.cpp serves it with a vision projector."""
+ if not native_ready(checkpoint):
+ return ["text"]
+ native = _native_target(checkpoint)
+ if native.is_local:
+ from .gguf_export_contract import served_files
+ files = served_files(Path(native.source).expanduser(), "clef")
+ return ["text", "image"] if files is not None and files[2] is not None else ["text"]
+ return ["text", "image"] if GGUF_COMPANIONS[native.name].mmproj else ["text"]
+
+
+def _native_gpu() -> bool:
+ from utils.systemone_settings import clef_device
+ return clef_device() == "gpu"
+
+
def _clef_complete(folder: Path) -> bool:
import json
@@ -242,6 +511,12 @@ def _utf8_open(
def is_cached(checkpoint: Checkpoint) -> bool:
+ if _is_native(checkpoint):
+ try:
+ _native_files(checkpoint, local_only = True)
+ except Exception:
+ return False
+ return True
try:
root = _checkpoint_dir(checkpoint, local_only = True)
except Exception:
@@ -252,7 +527,12 @@ def is_cached(checkpoint: Checkpoint) -> bool:
return all((folder / name).is_file() for name in _WEIGHT_FILES)
-def download_plan(checkpoint: Checkpoint) -> dict[str, Any]:
+def download_plan(checkpoint: Checkpoint, preference: str | None = None) -> dict[str, Any]:
+ if checkpoint.layout == "clef" and not _is_native(checkpoint):
+ try:
+ checkpoint = select(checkpoint, preference = preference)[0]
+ except Unavailable:
+ pass
cached = is_cached(checkpoint)
plan = {"repo": None, "files": [], "size_bytes": 0, "cached": cached, "error": None}
if checkpoint.name == LOCAL_NAME or checkpoint.is_local:
@@ -262,6 +542,11 @@ def download_plan(checkpoint: Checkpoint) -> dict[str, Any]:
return plan
plan["repo"] = checkpoint.source
plan["size_bytes"] = checkpoint.download_bytes
+ if _is_native(checkpoint):
+ companion = GGUF_COMPANIONS[checkpoint.name]
+ plan["revision"] = companion.revision
+ plan["files"] = [name for name in (companion.model, companion.mmproj) if name]
+ return plan
if cached:
return plan
try:
@@ -303,16 +588,26 @@ def _release_memory() -> None:
logger.debug("Could not clear the Decision API device cache", exc_info = True)
-def _close(agent) -> None:
+def _close(agent, release_gpu: bool = True) -> None:
# A Clef agent is a worker process; ending it returns its GPU memory.
if agent is not None and hasattr(agent, "close"):
agent.close()
+ if release_gpu and _is_native(agent) and getattr(agent, "gpu", False):
+ from core.inference import gpu_arbiter
+ def unclaimed() -> bool:
+ # A newer server loading or resident while this one closed keeps the claim.
+ with _state_lock:
+ return not _gpu_load and not (_is_native(_loaded) and getattr(_agent, "gpu", False))
+ gpu_arbiter.release_if(gpu_arbiter.DECISIONS, unclaimed)
-def _evict() -> None:
- global _agent, _loaded, _device_name
+
+def _evict(external: bool = False) -> None:
+ global _agent, _loaded, _device_name, _generation, _unloads
with _run_lock:
agent, _agent, _loaded, _device_name = _agent, None, None, None
+ _generation += 1
+ _unloads += external
_close(agent)
_release_memory()
@@ -356,6 +651,8 @@ class _MLXAgent:
def _load_checkpoint(checkpoint: Checkpoint):
from utils.systemone_settings import get_device as preferred_device
+ if _is_native(checkpoint):
+ return _load_native(checkpoint)
root = _checkpoint_dir(checkpoint)
if checkpoint.layout == "clef":
from .clef_runtime import ClefAgent, ClefWorkerError
@@ -397,6 +694,51 @@ def _load_checkpoint(checkpoint: Checkpoint):
return agent, str(agent.device.type)
+def _load_native(checkpoint: Checkpoint):
+ global _gpu_load
+ from core.inference import gpu_arbiter
+ from utils.systemone_settings import get_native_ctx
+
+ from .native_worker import NativeClefAgent, NativeError, NativeIncapable, resolve_binary
+
+ # Fetched (pinned revision) before the eviction, so a failed download leaves the resident model serving.
+ model, mmproj = _native_files(checkpoint, local_only = False)
+ _evict()
+ gpu = _native_gpu()
+ if gpu:
+ with _state_lock:
+ _gpu_load = True
+ try:
+ gpu_arbiter.acquire_for(gpu_arbiter.DECISIONS, allow_evict = False)
+ except gpu_arbiter.GpuOwnerBusyError:
+ raise NativeError(_GPU_BUSY) from None
+ try:
+ agent = NativeClefAgent(
+ model,
+ mmproj,
+ checkpoint.name,
+ gpu = gpu,
+ clef_answers = checkpoint.layout == "clef",
+ ctx = get_native_ctx(),
+ cancelled = (lambda: _training_active()) if gpu else None,
+ )
+ if gpu and _training_active():
+ agent.close()
+ raise NativeError(
+ f"{checkpoint.name} needs the GPU, which a training run took while it loaded."
+ )
+ except BaseException as exc:
+ if isinstance(exc, NativeIncapable) and (binary := resolve_binary()):
+ _incapable.add(_binary_key(binary))
+ if gpu:
+ gpu_arbiter.release(gpu_arbiter.DECISIONS)
+ raise
+ return agent, agent.device
+
+
+_GPU_BUSY = "Unload the resident chat, image or video model before serving a decision model through llama.cpp on the GPU."
+
+
_build_lock = threading.Lock()
@@ -618,8 +960,9 @@ def loading_repo_ids() -> tuple[str, ...]:
def _load(checkpoint: Checkpoint) -> None:
- global _agent, _loaded, _device_name, _loading, _failure
+ global _agent, _loaded, _device_name, _loading, _failure, _generation, _last_used, _gpu_load
started = time.monotonic()
+ unloads = _unloads
try:
agent, device = _load_checkpoint(checkpoint)
except Exception as exc:
@@ -628,10 +971,23 @@ def _load(checkpoint: Checkpoint) -> None:
with _state_lock:
_failure = (checkpoint, message, time.monotonic() + FAILURE_BACKOFF_S)
_loading = None
+ _gpu_load = False
return
with _state_lock:
- _agent, _loaded, _device_name = agent, checkpoint, str(getattr(agent, "device", device))
+ stale = _unloads != unloads
+ if not stale:
+ _agent, _loaded, _device_name = agent, checkpoint, str(getattr(agent, "device", device))
_failure = _loading = None
+ _gpu_load = False
+ _generation += 1
+ _last_used = time.monotonic()
+ generation = _generation
+ if stale:
+ logger.info("System One dropped %s: it was unloaded while it loaded", checkpoint.name)
+ _close(agent)
+ return
+ if _is_native(checkpoint):
+ _schedule_idle_unload(generation)
logger.info(
"System One loaded %s on %s in %.1fs",
checkpoint.name,
@@ -640,6 +996,63 @@ def _load(checkpoint: Checkpoint) -> None:
)
+def _schedule_idle_unload(generation: int, delay: float | None = None) -> None:
+ global _idle_timer
+ timer = threading.Timer(
+ IDLE_UNLOAD_S if delay is None else delay, _idle_unload, args = (generation,)
+ )
+ timer.daemon = True
+ with _state_lock:
+ if _idle_timer is not None:
+ _idle_timer.cancel()
+ _idle_timer = timer
+ timer.start()
+
+
+def _idle_unload(generation: int) -> None:
+ global _agent, _loaded, _device_name, _generation, _unloads
+ if not _run_lock.acquire(blocking = False):
+ # A decision is running; look again once the idle window could have passed.
+ _schedule_idle_unload(generation)
+ return
+ try:
+ if _generation != generation or not _is_native(_loaded):
+ return
+ idle = time.monotonic() - _last_used
+ if idle < IDLE_UNLOAD_S:
+ _schedule_idle_unload(generation, IDLE_UNLOAD_S - idle)
+ return
+ agent, _agent, _loaded, _device_name = _agent, None, None, None
+ _generation += 1
+ _unloads += 1
+ finally:
+ _run_lock.release()
+ logger.info("System One unloaded the idle llama.cpp decision server")
+ _close(agent)
+
+
+def evict_for_gpu() -> None:
+ """GPU arbiter evictor: ends an idle llama.cpp decision server; refuses while it loads or decides."""
+ global _agent, _loaded, _device_name, _generation, _unloads
+ from core.inference.gpu_arbiter import DECISIONS, GpuOwnerBusyError
+
+ with _state_lock:
+ if _is_native(_loading):
+ raise GpuOwnerBusyError(DECISIONS)
+ if not _run_lock.acquire(blocking = False):
+ raise GpuOwnerBusyError(DECISIONS)
+ try:
+ if not _is_native(_loaded):
+ return
+ agent, _agent, _loaded, _device_name = _agent, None, None, None
+ _generation += 1
+ _unloads += 1
+ finally:
+ _run_lock.release()
+ # The arbiter hands ownership on itself, under its own lock.
+ _close(agent, release_gpu = False)
+
+
def _misplaced() -> bool:
# The resident model follows the same rule: off the GPU while training holds it, back on it after.
if getattr(_agent, "_unsloth_for_training", False):
@@ -648,17 +1061,20 @@ def _misplaced() -> bool:
def _clef_blocked_by_training(checkpoint: Checkpoint) -> None:
- if checkpoint.layout != "clef":
+ if checkpoint.layout == "laya":
return
from .catalog import clef_unsupported_reason
- if (reason := clef_unsupported_reason()) is not None:
+ native = _is_native(checkpoint)
+ # llama.cpp also serves Clef on CPU, Metal or Vulkan; the PyTorch worker needs CUDA or ROCm.
+ if not native and (reason := clef_unsupported_reason()) is not None:
raise Unavailable(400, "api_usage_error", reason)
- if not _training_active():
+ if (native and not _native_gpu()) or not _training_active():
return
# Clef has no CPU fallback: it waits for the GPU instead of taking it from the run.
- if _loaded is not None and _loaded.layout == "clef":
- _evict()
+ # Only a resident on the GPU: a llama.cpp server on CPU keeps serving during the run.
+ if _loaded is not None and _loaded.layout != "laya" and _device_name not in (None, "cpu"):
+ _evict(external = True)
raise Unavailable(
503,
"model_unavailable",
@@ -675,6 +1091,10 @@ def _ensure_loading(checkpoint: Checkpoint) -> threading.Thread | None:
with _state_lock:
if _loaded == checkpoint and _agent is not None and not misplaced:
return None
+ if _is_native(checkpoint) and _native_gpu():
+ from core.inference.gpu_arbiter import DECISIONS, current_owner
+ if current_owner() not in (None, DECISIONS):
+ raise Unavailable(409, "gpu_busy", _GPU_BUSY, retry_after = 1)
if _failure and _failure[0] == checkpoint and time.monotonic() < _failure[2]:
raise Unavailable(
503,
@@ -1293,16 +1713,64 @@ def _wire_answer(answer: dict[str, Any]) -> dict[str, Any]:
}
-def decide(checkpoint: Checkpoint, state, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
+def decide(
+ checkpoint: Checkpoint,
+ state,
+ questions: dict[str, dict[str, Any]],
+ images: list[str] | None = None,
+) -> dict[str, Any]:
if not _admission.acquire(blocking = False):
raise Unavailable(529, "overloaded", "System One is busy; retry shortly", retry_after = 1)
try:
- return _decide(checkpoint, state, questions)
+ return _route(checkpoint, state, questions, images or None)
finally:
_admission.release()
-def _decide(checkpoint: Checkpoint, state, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
+def _route(checkpoint: Checkpoint, state, questions, images) -> dict[str, Any]:
+ global _fallback_reason
+ from utils.systemone_settings import get_backend
+
+ from .clef_runtime import MAX_LENGTH
+ from .native_worker import NativeContextOverflow
+
+ target, reason = select(checkpoint, images, questions)
+ if checkpoint.layout != "laya":
+ _fallback_reason = reason
+ try:
+ return _decide(target, state, questions, images)
+ except NativeContextOverflow as exc:
+ # Auto answers on PyTorch only what its longer window can hold; at equal windows it would refuse too.
+ from .catalog import clef_unsupported_reason
+
+ if (
+ get_backend() != "auto"
+ or checkpoint.layout == GGUF
+ or images
+ or exc.limit >= MAX_LENGTH
+ or clef_unsupported_reason() is not None
+ ):
+ raise Unavailable(422, "invalid_request_error", str(exc)) from None
+ _fallback_reason = "The request is longer than the llama.cpp context."
+ return _decide(checkpoint, state, questions, None)
+ except Unavailable:
+ # A llama-server that turned out not to serve decisions: Auto answers this request on PyTorch.
+ if not _is_native(target) or get_backend() != "auto" or images:
+ raise
+ retry, reason = select(checkpoint, images, questions)
+ if retry == target:
+ raise
+ _fallback_reason = reason
+ return _decide(retry, state, questions, None)
+
+
+def _decide(
+ checkpoint: Checkpoint,
+ state,
+ questions: dict[str, dict[str, Any]],
+ images: list[str] | None = None,
+) -> dict[str, Any]:
+ global _last_used
agent = _agent_for(checkpoint, LOAD_WAIT_S)
if not _run_lock.acquire(timeout = RUN_WAIT_S):
raise Unavailable(529, "overloaded", "System One is busy; retry shortly", retry_after = 1)
@@ -1311,6 +1779,10 @@ def _decide(checkpoint: Checkpoint, state, questions: dict[str, dict[str, Any]])
raise Unavailable(
503, "model_loading", f"{checkpoint.name} is reloading", retry_after = 5
)
+ if _is_native(checkpoint):
+ result = _decide_native(checkpoint, agent, state, questions, images)
+ _last_used = time.monotonic()
+ return result
if checkpoint.layout == "clef":
return _decide_clef(checkpoint, agent, state, questions)
laya_questions = {name: _to_laya(q) for name, q in questions.items()}
@@ -1346,13 +1818,36 @@ def _decide_clef(checkpoint: Checkpoint, agent, state, questions) -> dict[str, A
}
+def _decide_native(checkpoint: Checkpoint, agent, state, questions, images) -> dict[str, Any]:
+ from .native_worker import NativeContextOverflow, NativeError
+ try:
+ result = agent.decide(state, questions, images)
+ except NativeContextOverflow:
+ raise
+ except NativeError as exc:
+ if exc.retire:
+ # A crashed or misbehaving server is retired; the next request starts a fresh one.
+ threading.Thread(target = _evict_agent, args = (agent,), daemon = True).start()
+ raise Unavailable(
+ exc.status, exc.error_type, str(exc), retry_after = 5 if exc.retire else None
+ ) from None
+ return {
+ "model": checkpoint.name,
+ "answers": {name: _wire_answer(result["answers"][name]) for name in questions},
+ "usage": {"input_tokens": int(result["input_tokens"]), "output_tokens": 0},
+ "truncated": bool(result["truncated"]),
+ "_backend": LLAMA_CPP,
+ }
+
+
def _evict_agent(agent) -> None:
- global _agent, _loaded, _device_name
+ global _agent, _loaded, _device_name, _generation
# Waits for _decide to release _run_lock.
with _run_lock:
if _agent is not agent:
return
_agent = _loaded = _device_name = None
+ _generation += 1
_close(agent)
@@ -1361,6 +1856,8 @@ def status() -> dict[str, Any]:
failure = _failure if _failure and time.monotonic() < _failure[2] else None
return {
"loaded_model": _loaded.name if _loaded else None,
+ "loaded_backend": _loaded.backend if _loaded else None,
+ "fallback_reason": _fallback_reason,
"device": _device_name,
"loading_model": _loading.name if _loading else None,
# Kept for the settings API: laya is vendored, so there is never an install in flight.
@@ -1378,12 +1875,30 @@ def ensure_can_unload() -> None:
def unload() -> bool:
- global _agent, _loaded, _device_name, _failure
+ global _agent, _loaded, _device_name, _failure, _generation, _unloads
ensure_can_unload()
with _run_lock:
agent, was_loaded = _agent, _agent is not None
_agent = _loaded = _device_name = None
_failure = None
+ _generation += 1
+ _unloads += 1
_close(agent)
_release_memory()
return was_loaded
+
+
+def shutdown() -> None:
+ """Studio shutdown: end a llama.cpp decision server (in-process models go with the process)."""
+ global _agent, _loaded, _device_name, _generation, _unloads
+ with _state_lock:
+ timer = _idle_timer
+ if timer is not None:
+ timer.cancel()
+ with _run_lock:
+ _unloads += 1
+ if not _is_native(_loaded):
+ return
+ agent, _agent, _loaded, _device_name = _agent, None, None, None
+ _generation += 1
+ _close(agent)
diff --git a/studio/backend/core/systemone/native_worker.py b/studio/backend/core/systemone/native_worker.py
new file mode 100644
index 00000000000..77848d368ec
--- /dev/null
+++ b/studio/backend/core/systemone/native_worker.py
@@ -0,0 +1,544 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Decisions from a GGUF on a private loopback llama-server (``POST /v1/systemone``).
+
+Ported from wasimysaid's native worker in #12770. The server is Studio's own llama.cpp. Clef answers
+are rebuilt with the formatter the PyTorch path uses, so the public response does not depend on the
+backend (llama.cpp's own confidence is a normalised formula, PyTorch's the winning probability).
+GGUF-only models (Kev, lev, Nimble, OpenJev, Laya GGUFs) have no Studio reference, so llama.cpp's
+answer is the reference: checked, then passed through.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import math
+import os
+import re
+import secrets
+import subprocess
+import sys
+import threading
+import time
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Any, Callable
+
+import httpx
+
+DEFAULT_CTX = 16384
+LOAD_TIMEOUT_S = 1800.0
+DECIDE_TIMEOUT_S = 300.0
+CLOSE_TIMEOUT_S = 10.0
+_POLL_S = 0.1
+# llama.cpp server-context.cpp wording for inputs over -ub / -c / -b.
+_OVERFLOW = (
+ re.compile(
+ r"input \((\d+) tokens\) is too large to process\. increase the physical batch size "
+ r"\(current batch size: (\d+)\)"
+ ),
+ re.compile(r"input \((\d+) tokens\) is larger than the max context size \((\d+) tokens\)"),
+ re.compile(r"request \((\d+) tokens\) exceeds the available context size \((\d+) tokens\)"),
+ re.compile(
+ r"the question and its options \((\d+) tokens\) are too large to process\. "
+ r"increase the batch size \(current batch size: (\d+)\)"
+ ),
+)
+# server-common.cpp: an image mtmd cannot decode, answered as HTTP 500 by a healthy server.
+_UNDECODABLE_MEDIA = "Failed to load image or audio file"
+_SERVER_LOG_LINES = 40
+
+
+class NativeError(RuntimeError):
+ """The server failed or is unusable: 503, and the server is retired."""
+
+ status = 503
+ error_type = "model_unavailable"
+ retire = True
+
+
+class NativeIncapable(NativeError):
+ """This llama-server build cannot serve decision models."""
+
+
+class NativeInputError(NativeError):
+ """The server refused this request; the server itself is fine."""
+
+ status = 422
+ error_type = "invalid_request_error"
+ retire = False
+
+
+class NativeContextOverflow(NativeInputError):
+ def __init__(self, tokens: int, limit: int):
+ self.tokens, self.limit = tokens, limit
+ super().__init__(
+ f"State and questions are {tokens} tokens; the llama.cpp backend serves at most {limit}. "
+ "Shorten the state or use fewer/shorter criteria."
+ )
+
+
+def resolve_binary() -> str | None:
+ from core.inference.llama_cpp import LlamaCppBackend
+ binary = LlamaCppBackend._find_llama_server_binary()
+ return (LlamaCppBackend._exec_path_for_launch(binary) or binary) if binary else None
+
+
+def request_gap(questions: Mapping[str, Any]) -> str | None:
+ """Why llama.cpp cannot take these questions (its parser wants 2 to 10 score levels), else None."""
+ for name, question in questions.items():
+ if question.get("type") == "score" and len(question.get("criteria") or ()) < 2:
+ return f'llama.cpp needs at least two levels for score "{name}".'
+ return None
+
+
+def _reference_formatter() -> Callable[[dict, dict], dict]:
+ """``systemone_answer`` from the vendored Clef reference, the function the PyTorch path answers with."""
+ if (module := sys.modules.get("_unsloth_clef_reference")) is not None:
+ return module.systemone_answer
+ spec = importlib.util.find_spec("unsloth")
+ roots = [Path(p) for p in (spec.submodule_search_locations or ())] if spec else []
+ roots.append(Path(__file__).resolve().parents[4] / "unsloth")
+ source = next(
+ (
+ path
+ for root in roots
+ if (path := root / "_vendor" / "clef" / "joint_schema_model.py").is_file()
+ ),
+ None,
+ )
+ if source is None:
+ raise NativeError("The vendored Clef reference (unsloth/_vendor/clef) is missing.")
+ # By path: importing the unsloth package would patch transformers in the Studio process.
+ module_spec = importlib.util.spec_from_file_location("_unsloth_clef_reference", source)
+ module = importlib.util.module_from_spec(module_spec)
+ sys.modules["_unsloth_clef_reference"] = module
+ try:
+ module_spec.loader.exec_module(module)
+ except BaseException:
+ sys.modules.pop("_unsloth_clef_reference", None)
+ raise
+ return module.systemone_answer
+
+
+def _probabilities(question: Mapping[str, Any], answer: Any) -> dict[str, float]:
+ if not isinstance(answer, Mapping):
+ raise ValueError("missing answer")
+ kind = question["type"]
+ if kind == "noul":
+ p = answer.get("noul")
+ if isinstance(p, bool) or not isinstance(p, (int, float)):
+ raise ValueError("missing noul probability")
+ values = {"true": float(p), "false": 1.0 - float(p)}
+ else:
+ raw = answer.get("probabilities")
+ keys = (
+ [str(k) for k in question["criteria"]]
+ if kind == "choice"
+ else [str(i) for i in range(len(question["criteria"]))]
+ )
+ if not isinstance(raw, Mapping) or set(raw) != set(keys):
+ raise ValueError("probabilities do not name the question's options")
+ if any(isinstance(v, bool) or not isinstance(v, (int, float)) for v in raw.values()):
+ raise ValueError("non-numeric probabilities")
+ values = {key: float(raw[key]) for key in keys}
+ if not math.isclose(sum(values.values()), 1.0, rel_tol = 1e-4, abs_tol = 1e-4):
+ raise ValueError("probabilities do not sum to one")
+ if any(not math.isfinite(v) or not -1e-6 <= v <= 1 + 1e-6 for v in values.values()):
+ raise ValueError("probabilities out of range")
+ return values
+
+
+def _number(answer: Mapping[str, Any], key: str) -> float:
+ value = answer.get(key)
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
+ raise ValueError(f"missing {key}")
+ return float(value)
+
+
+def _llama_answer(question: Mapping[str, Any], answer: Any) -> dict[str, Any]:
+ """llama.cpp's own answer in Studio's shape, after checking it names the question's options."""
+ probabilities = _probabilities(question, answer)
+ kind = question["type"]
+ if kind == "noul":
+ return {"type": "noul", "noul": probabilities["true"]}
+ if kind == "choice":
+ choice = answer.get("choice")
+ if choice not in probabilities:
+ raise ValueError("choice is not one of the options")
+ return {
+ "type": "choice",
+ "choice": choice,
+ "confidence": _number(answer, "confidence"),
+ "probabilities": probabilities,
+ }
+ return {
+ "type": "score",
+ "score": _number(answer, "score"),
+ "confidence": _number(answer, "confidence"),
+ "legend": {str(i): c for i, c in enumerate(question["criteria"])},
+ "probabilities": probabilities,
+ }
+
+
+def normalise(
+ data: Any,
+ questions: Mapping[str, Mapping[str, Any]],
+ clef_answers: bool = True,
+) -> dict[str, Any]:
+ """Studio's decision result from a llama.cpp /v1/systemone body; Clef answers rebuilt by the PyTorch formatter."""
+ if not isinstance(data, Mapping) or not isinstance(data.get("answers"), Mapping):
+ raise NativeError("llama.cpp returned an invalid decision response.")
+ systemone_answer = _reference_formatter() if clef_answers else None
+ answers = {}
+ for name, question in questions.items():
+ answer = data["answers"].get(name)
+ try:
+ if systemone_answer is None:
+ answers[name] = _llama_answer(question, answer)
+ else:
+ answers[name] = systemone_answer(dict(question), _probabilities(question, answer))
+ except (TypeError, ValueError, KeyError) as exc:
+ raise NativeError(f'llama.cpp returned an invalid answer for "{name}": {exc}') from None
+ usage = data.get("usage") if isinstance(data.get("usage"), Mapping) else {}
+ tokens = usage.get("input_tokens")
+ return {
+ "answers": answers,
+ "input_tokens": int(tokens)
+ if isinstance(tokens, int) and not isinstance(tokens, bool)
+ else 0,
+ # llama.cpp never cuts a state: an input over its batch is refused (NativeContextOverflow).
+ "truncated": False,
+ }
+
+
+def _wire_questions(questions: Mapping[str, Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
+ wire = {}
+ for name, question in questions.items():
+ copied = {k: v for k, v in question.items() if v is not None}
+ # The reference encoder reads a missing or empty instruction as the question id; llama.cpp refuses both.
+ if question.get("instructions") in (None, ""):
+ copied["instructions"] = str(name)
+ wire[name] = copied
+ return wire
+
+
+def _detail(response: httpx.Response) -> str:
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ if isinstance(body, Mapping):
+ value = body.get("error") or body.get("detail") or body.get("message")
+ if isinstance(value, Mapping):
+ value = value.get("message") or value.get("detail")
+ if isinstance(value, str) and value:
+ return value[:1000]
+ return response.text.strip()[:1000] or f"HTTP {response.status_code}"
+
+
+def map_error(status: int, detail: str) -> NativeError:
+ """The Studio error for a non-2xx llama.cpp answer."""
+ if status not in (401, 403):
+ for pattern in _OVERFLOW:
+ if match := pattern.search(detail):
+ return NativeContextOverflow(int(match.group(1)), int(match.group(2)))
+ if 400 <= status < 500 or _UNDECODABLE_MEDIA in detail:
+ return NativeInputError(detail)
+ return NativeError(f"llama.cpp answered HTTP {status}: {detail}")
+
+
+def _pick_device(binary: str, env: dict[str, str]) -> str:
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ devices = LlamaCppBackend._enumerated_gpu_devices(binary, env)
+ if not devices:
+ raise NativeError("llama.cpp sees no usable GPU under this Studio's device visibility.")
+ if len(devices) > 1:
+ try:
+ free = LlamaCppBackend._get_gpu_free_memory(binary, for_llama_server = True)
+ except Exception:
+ free = []
+ # Same order as --list-devices only when both list every visible GPU.
+ if len(free) == len(devices):
+ return devices[max(range(len(free)), key = lambda i: free[i][1])]
+ return devices[0]
+
+
+def _write_key(key: str) -> Path:
+ """The server's API key, readable only by this user, under Studio's auth directory."""
+ from utils.paths.storage_roots import auth_root
+
+ directory = auth_root()
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / f"decision_llama_api_key_{secrets.token_hex(8)}"
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:
+ handle.write(key)
+ return path
+
+
+class NativeClefAgent:
+ """One llama-server serving one decision GGUF; the Decision API keeps it where it keeps a Clef agent."""
+
+ backend = "llama.cpp"
+
+ def __init__(
+ self,
+ model: Path,
+ mmproj: Path | None,
+ alias: str,
+ *,
+ gpu: bool,
+ ctx: int = DEFAULT_CTX,
+ cancelled: Callable[[], bool] | None = None,
+ clef_answers: bool = True,
+ ):
+ from core.inference.llama_cpp import LlamaCppBackend
+ from utils.process_lifetime import (
+ adopt_pid,
+ child_popen_kwargs,
+ is_process_shutting_down,
+ spawn_on_lifetime_thread,
+ )
+ from utils.subprocess_compat import windows_hidden_subprocess_kwargs
+
+ self.alias, self.ctx, self.gpu = alias, int(ctx), gpu
+ self.clef_answers = clef_answers
+ self._lock = threading.Lock()
+ self._process: subprocess.Popen | None = None
+ self._client: httpx.Client | None = None
+ self.input_modalities: tuple[str, ...] = ()
+ binary = resolve_binary()
+ if binary is None:
+ raise NativeError("llama-server is not installed; Studio installs it with llama.cpp.")
+ if not Path(model).is_file():
+ raise NativeError(f"The decision GGUF is missing: {model}")
+ env = LlamaCppBackend._llama_server_env_for_binary(binary)
+ LlamaCppBackend._clear_device_placement_env(env)
+ if gpu:
+ self.device = _pick_device(binary, env)
+ placement = ["-ngl", "-1", "--device", self.device]
+ else:
+ self.device = "cpu"
+ env.update(CUDA_VISIBLE_DEVICES = "", HIP_VISIBLE_DEVICES = "-1", ROCR_VISIBLE_DEVICES = "-1")
+ # The AMX CPU variant aborts loading Clef in graph_reserve unless weights stay unrepacked.
+ placement = ["-ngl", "0", "--device", "none", "--no-repack"]
+ if mmproj is not None:
+ placement.append("--no-mmproj-offload")
+ self.port = LlamaCppBackend._find_free_port()
+ self._key = secrets.token_urlsafe(32)
+ self._key_file: Path | None = None
+ self._log_path: Path | None = None
+ if is_process_shutting_down():
+ raise NativeError("Studio is shutting down; llama.cpp was not started.")
+ self._key_file = _write_key(self._key)
+ self.command = [
+ binary,
+ "-m",
+ str(model),
+ *(["--mmproj", str(mmproj)] if mmproj is not None else []),
+ "--alias",
+ alias,
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(self.port),
+ # Through a file, not argv: a command line is readable by every process of this user.
+ "--api-key-file",
+ str(self._key_file),
+ "--parallel",
+ "1",
+ # A decision reads every token in one ubatch: -ub bounds the longest state served.
+ "-c",
+ str(self.ctx),
+ "-b",
+ str(self.ctx),
+ "-ub",
+ str(self.ctx),
+ *placement,
+ ]
+ try:
+ self._log_path = self._server_log(self.port)
+ log = open(self._log_path, "wb")
+ except BaseException:
+ self._remove_files()
+ raise
+ try:
+ self._process = spawn_on_lifetime_thread(
+ lambda: subprocess.Popen(
+ self.command,
+ stdin = subprocess.DEVNULL,
+ stdout = log,
+ stderr = subprocess.STDOUT,
+ env = env,
+ **windows_hidden_subprocess_kwargs(),
+ **child_popen_kwargs(),
+ )
+ )
+ except BaseException:
+ self._remove_files()
+ raise
+ finally:
+ log.close()
+ adopt_pid(self._process.pid)
+ self._client = httpx.Client(trust_env = False, timeout = DECIDE_TIMEOUT_S)
+ try:
+ self._wait_ready(cancelled)
+ self.input_modalities = self._capabilities()
+ except BaseException:
+ self.close()
+ raise
+
+ @staticmethod
+ def _server_log(port: int) -> Path:
+ import tempfile
+
+ try:
+ from utils.paths.storage_roots import studio_root
+ root = studio_root() / "logs"
+ except Exception:
+ root = Path(tempfile.gettempdir())
+ root.mkdir(parents = True, exist_ok = True)
+ # Per server: a retired one still exiting must not write into its successor's log.
+ return root / f"decision-llama-server-{os.getpid()}-{port}.log"
+
+ def _remove_files(self, keep_log: bool = False) -> None:
+ for path in (self._key_file, None if keep_log else self._log_path):
+ if path is not None:
+ try:
+ path.unlink(missing_ok = True)
+ except OSError:
+ pass
+
+ def _log_tail(self) -> str:
+ if self._log_path is None:
+ return ""
+ try:
+ lines = self._log_path.read_text(encoding = "utf-8", errors = "replace").splitlines()
+ except OSError:
+ return ""
+ return "\n".join(lines[-_SERVER_LOG_LINES:])
+
+ @property
+ def _base(self) -> str:
+ return f"http://127.0.0.1:{self.port}"
+
+ @property
+ def _headers(self) -> dict[str, str]:
+ return {"Authorization": f"Bearer {self._key}"}
+
+ def _wait_ready(self, cancelled: Callable[[], bool] | None) -> None:
+ from utils.process_lifetime import is_process_shutting_down
+
+ deadline = time.monotonic() + LOAD_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if is_process_shutting_down() or (cancelled is not None and cancelled()):
+ raise NativeError("The llama.cpp decision server was stopped while it loaded.")
+ if not self.is_alive():
+ tail = self._log_tail()
+ raise NativeError(
+ f"llama.cpp exited while loading {self.alias} (code {self._process.returncode})"
+ + (f":\n{tail}" if tail else ".")
+ )
+ try:
+ response = self._client.get(f"{self._base}/health", timeout = 2.0)
+ if response.status_code == 200:
+ return
+ except httpx.TransportError:
+ pass
+ time.sleep(_POLL_S)
+ raise NativeError(f"llama.cpp did not load {self.alias} within {LOAD_TIMEOUT_S:.0f}s.")
+
+ def _capabilities(self) -> tuple[str, ...]:
+ try:
+ response = self._client.get(
+ f"{self._base}/v1/models", headers = self._headers, timeout = 10.0
+ )
+ entries = response.json().get("data") if response.status_code == 200 else None
+ except (httpx.HTTPError, ValueError, AttributeError):
+ entries = None
+ for entry in entries if isinstance(entries, list) else ():
+ if not isinstance(entry, Mapping):
+ continue
+ names = {entry.get("id"), *(entry.get("aliases") or ())}
+ arch = (
+ entry.get("architecture") if isinstance(entry.get("architecture"), Mapping) else {}
+ )
+ if self.alias in names and "decisions" in (arch.get("output_modalities") or ()):
+ return tuple(str(m) for m in arch.get("input_modalities") or ("text",))
+ raise NativeIncapable(
+ 'This llama.cpp build does not serve decision models (no "decisions" output in '
+ "/v1/models). Update llama.cpp in Studio."
+ )
+
+ @property
+ def accepts_images(self) -> bool:
+ return "image" in self.input_modalities
+
+ def is_alive(self) -> bool:
+ return self._process is not None and self._process.poll() is None
+
+ def decide(
+ self,
+ state: Any,
+ questions: dict[str, dict[str, Any]],
+ images: list[str] | None = None,
+ ) -> dict[str, Any]:
+ if gap := request_gap(questions):
+ raise NativeInputError(gap)
+ if images and not self.accepts_images:
+ raise NativeInputError(
+ f"{self.alias} has no vision projector, so it cannot read images."
+ )
+ body = {"model": self.alias, "state": state, "questions": _wire_questions(questions)}
+ if images:
+ body["images"] = list(images)
+ with self._lock:
+ client = self._client
+ if client is None or not self.is_alive():
+ raise NativeError("The llama.cpp decision server is not running.")
+ try:
+ response = client.post(
+ f"{self._base}/v1/systemone", json = body, headers = self._headers
+ )
+ except httpx.HTTPError as exc:
+ alive = "" if self.is_alive() else " and exited"
+ raise NativeError(
+ f"The llama.cpp decision server failed{alive}: {type(exc).__name__}"
+ ) from None
+ if not 200 <= response.status_code < 300:
+ raise map_error(response.status_code, _detail(response))
+ try:
+ data = response.json()
+ except ValueError:
+ raise NativeError("llama.cpp returned a decision that is not JSON.") from None
+ return normalise(data, questions, self.clef_answers)
+
+ def close(self) -> None:
+ """Terminate, then kill, then reap; the pid is forgotten only once it is gone."""
+ from utils.process_lifetime import forget_pid
+
+ client, self._client = self._client, None
+ if client is not None:
+ client.close()
+ process = self._process
+ if process is None:
+ self._remove_files()
+ return
+ # A server that exited by itself keeps its log for diagnosis.
+ crashed = process.poll() is not None
+ try:
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout = CLOSE_TIMEOUT_S)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout = CLOSE_TIMEOUT_S)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ if process.poll() is not None:
+ forget_pid(process.pid)
+ self._remove_files(keep_log = crashed)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index a3c18eaae62..fc337bd5667 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1014,6 +1014,10 @@ async def lifespan(app: FastAPI):
await _close_llama_http()
+ from core.systemone.laya_runtime import shutdown as shutdown_decisions
+
+ await asyncio.to_thread(shutdown_decisions)
+
await run_lifespan_shutdown(
terminate_hub_downloads,
lambda: clear_compiled_cache_unless_shared(app),
diff --git a/studio/backend/models/__init__.py b/studio/backend/models/__init__.py
index 42c03255b62..abae5d76b30 100644
--- a/studio/backend/models/__init__.py
+++ b/studio/backend/models/__init__.py
@@ -43,6 +43,8 @@ from .export import (
ConvertQ4NXRequest,
ExportLoRAAdapterRequest,
LlmCompressorExportProbeResponse,
+ DecisionExportInfo,
+ ExportDecisionInfoResponse,
)
from .users import Token
from .inference import (
@@ -102,6 +104,8 @@ __all__ = [
"ConvertQ4NXRequest",
"ExportLoRAAdapterRequest",
"LlmCompressorExportProbeResponse",
+ "DecisionExportInfo",
+ "ExportDecisionInfoResponse",
"Token",
"LoadRequest",
"UnloadRequest",
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 6d42fc0189e..1de309cedf3 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -106,6 +106,40 @@ class ExportStatusResponse(BaseModel):
None,
description = "Error message of the most recently finished op, if it failed",
)
+ decision: Optional[Dict[str, Any]] = Field(
+ None,
+ description = "{layout, adapter_only} when the loaded checkpoint is a decision model",
+ )
+
+
+class DecisionExportInfo(BaseModel):
+ """GGUF export options for a decision model (Clef or Laya) checkpoint."""
+
+ is_decision: bool = Field(True, description = "True for a decision model checkpoint")
+ layout: Literal["clef", "laya"] = Field(..., description = "Decision checkpoint layout")
+ adapter_only: bool = Field(
+ False,
+ description = "True for a Clef folder holding LoRA adapters only (merged at export time)",
+ )
+ eligible: Optional[bool] = Field(
+ None,
+ description = "False when llama.cpp cannot serve this model; None when only the export can tell",
+ )
+ reason: Optional[str] = Field(None, description = "Why the checkpoint is not eligible")
+ quantizations: List[str] = Field(..., description = "Allowed GGUF quantizations, default first")
+ default_quantization: str = Field(..., description = "Default GGUF quantization")
+ output_dir: str = Field(..., description = "Where the GGUF files are written (<run folder>/gguf)")
+ existing_export: Optional[Dict[str, Any]] = Field(
+ None,
+ description = "Content of an earlier gguf/export.json, if valid",
+ )
+
+
+class ExportDecisionInfoResponse(BaseModel):
+ """Decision-model export info for a checkpoint path; decision is None for any other model."""
+
+ checkpoint_path: str
+ decision: Optional[DecisionExportInfo] = None
class ExportOperationResponse(BaseModel):
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 6894ee95ec2..4e713371709 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -52,6 +52,7 @@ from models import (
ExportLoRAAdapterRequest,
ConvertQ4NXRequest,
LlmCompressorExportProbeResponse,
+ ExportDecisionInfoResponse,
)
router = APIRouter()
@@ -238,8 +239,11 @@ async def get_export_status(current_subject: str = Depends(get_current_subject))
# does, so the success banner shows an identical path on either route.
last_op_output_path = None
if last_op and last_op.get("output_path"):
- details = await asyncio.to_thread(_export_details, last_op["output_path"])
- last_op_output_path = (details or {}).get("output_path")
+ if getattr(backend, "decision", None):
+ last_op_output_path = last_op["output_path"]
+ else:
+ details = await asyncio.to_thread(_export_details, last_op["output_path"])
+ last_op_output_path = (details or {}).get("output_path")
return ExportStatusResponse(
current_checkpoint = backend.current_checkpoint,
is_vision = bool(getattr(backend, "is_vision", False)),
@@ -251,6 +255,7 @@ async def get_export_status(current_subject: str = Depends(get_current_subject))
last_op_status = last_op.get("status") if last_op else None,
last_op_output_path = last_op_output_path,
last_op_error = last_op.get("error") if last_op else None,
+ decision = getattr(backend, "decision", None),
)
except Exception as e:
logger.error(f"Error getting export status: {e}", exc_info = True)
@@ -358,6 +363,38 @@ def _export_details(
return {"output_path": output_path}
+def _decision_export_details(output_path: Optional[str]) -> Optional[Dict[str, Any]]:
+ """A decision GGUF lands in the run folder's gguf/; not registered as a chat model folder."""
+ if not output_path:
+ return None
+ from core.export.decision import read_existing_export
+
+ # output_path is <run folder>/gguf; the contract reads from the run folder.
+ export = read_existing_export(Path(output_path).parent)
+ return {
+ "output_path": str(output_path),
+ "decision_export": export,
+ "quantizations": (export or {}).get("quantizations") or [],
+ }
+
+
[email protected]("/decision-info", response_model = ExportDecisionInfoResponse)
+async def get_decision_export_info(
+ checkpoint_path: str = Query(..., description = "Local checkpoint folder"),
+ current_subject: str = Depends(get_current_subject),
+):
+ """GGUF export options for a decision model checkpoint (Clef / Laya); decision is null otherwise."""
+ validate_job_paths({"checkpoint_path": checkpoint_path})
+ from core.export.decision import decision_preview
+
+ try:
+ decision = await asyncio.to_thread(decision_preview, checkpoint_path)
+ except Exception as e:
+ logger.warning(f"Could not inspect {checkpoint_path} for decision export: {e}")
+ decision = None
+ return ExportDecisionInfoResponse(checkpoint_path = checkpoint_path, decision = decision)
+
+
@router.post("/export/merged", response_model = ExportOperationResponse)
async def export_merged_model(
request: ExportMergedModelRequest,
@@ -504,11 +541,11 @@ async def export_gguf(
if not success:
raise HTTPException(status_code = 400, detail = message)
- return ExportOperationResponse(
- success = True,
- message = message,
- details = await asyncio.to_thread(_export_details, output_path, refresh_index = True),
- )
+ if getattr(backend, "decision", None):
+ details = await asyncio.to_thread(_decision_export_details, output_path)
+ else:
+ details = await asyncio.to_thread(_export_details, output_path, refresh_index = True)
+ return ExportOperationResponse(success = True, message = message, details = details)
except HTTPException:
raise
except Exception as e:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 3562d6afd68..ca575bc0756 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -19319,11 +19319,18 @@ async def _load_model_impl(
logger.warning("GGUF runtime missing while loading '%s': %s", model_log_label, e)
raise HTTPException(status_code = 400, detail = str(e))
except Exception as e:
- from core.inference.gpu_arbiter import GpuOwnerBusyError
+ from core.inference.gpu_arbiter import DECISIONS, GpuOwnerBusyError
from utils.transformers_version import SidecarSwapInProgress
if isinstance(e, account_access.GpuBusyForAnotherAccountError):
raise account_access.gpu_busy_error() from e
+ if isinstance(e, GpuOwnerBusyError) and e.owner == DECISIONS:
+ # A llama.cpp decision server loading or deciding refuses eviction until it is idle.
+ raise HTTPException(
+ status_code = 409,
+ detail = "The Decision API is using the GPU; retry shortly.",
+ headers = {"Retry-After": "5"},
+ ) from e
if isinstance(e, GpuOwnerBusyError):
raise
if isinstance(e, SidecarSwapInProgress):
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 02e8842c5fc..ae69d27e95a 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -5785,7 +5785,7 @@ async def list_checkpoints(
outputs_dir = account_access.private_directory(outputs_dir, "outputs")
try:
resolved_outputs_dir = str(resolve_output_dir(outputs_dir))
- raw_models = scan_checkpoints(outputs_dir = resolved_outputs_dir)
+ raw_models = scan_checkpoints(outputs_dir = resolved_outputs_dir, include_decision = True)
models = [
ModelCheckpoints(
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index daf8548f854..7fb94839b2e 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -656,6 +656,8 @@ class SystemOneModelOption(BaseModel):
label: Optional[str] = None
available: bool = True
unavailable_reason: Optional[str] = None
+ # A GGUF with no PyTorch form: the runtime setting matters, and PyTorch cannot serve it.
+ llama_cpp_only: bool = False
class SystemOneConnectionOption(BaseModel):
@@ -680,12 +682,21 @@ class SystemOneSettingsResponse(BaseModel):
installing: bool = False
error: Optional[str] = None
mcp_url: str
+ # Runtime setting, what a text request to the configured model uses now, and why Auto chose PyTorch.
+ backend: str = "auto"
+ native_ctx: int = 16384
+ effective_backend: Optional[str] = None
+ loaded_backend: Optional[str] = None
+ fallback_reason: Optional[str] = None
+ input_modalities: list[str] = ["text"]
class SystemOneSettingsPayload(BaseModel):
enabled: Optional[bool] = None
model: Optional[str] = None
device: Optional[str] = None
+ backend: Optional[str] = None
+ native_ctx: Optional[int] = None
expected_enabled: Optional[bool] = None
expected_model: Optional[str] = None
@@ -1466,8 +1477,20 @@ def update_helper_precache(
def _clef_availability(checkpoint, reason: Optional[str]) -> dict:
+ from core.systemone import laya_runtime
+
+ if getattr(checkpoint, "layout", "laya") == laya_runtime.GGUF:
+ # Selectable under a PyTorch runtime: the runtime row then says to switch it.
+ try:
+ laya_runtime.select(checkpoint, preference = "auto")
+ except laya_runtime.Unavailable as exc:
+ return {"llama_cpp_only": True, "available": False, "unavailable_reason": exc.message}
+ return {"llama_cpp_only": True}
if reason is None or getattr(checkpoint, "layout", "laya") != "clef":
return {}
+ # llama.cpp serves Clef without CUDA or ROCm.
+ if laya_runtime.native_ready(checkpoint):
+ return {}
return {"available": False, "unavailable_reason": reason}
@@ -1495,6 +1518,9 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
if runtime["error_model"] not in (None, model):
error = None
port = getattr(request.app.state, "server_port", None) or request.scope["server"][1]
+ effective, fallback = laya_runtime.effective_backend(configured)
+ if runtime["loaded_model"] == model and runtime["fallback_reason"]:
+ fallback = runtime["fallback_reason"]
return SystemOneSettingsResponse(
enabled = enabled,
enabled_locked = systemone_settings.enabled_locked(),
@@ -1508,6 +1534,7 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
name = c.name,
description = c.description,
download_bytes = c.download_bytes,
+ label = c.label,
**_clef_availability(c, clef_reason),
)
for c in catalog.CHECKPOINTS.values()
@@ -1529,6 +1556,12 @@ def _systemone_response(request: Request) -> SystemOneSettingsResponse:
installing = runtime["installing"],
error = error,
mcp_url = f"http://127.0.0.1:{port}{MCP_PATH}/",
+ backend = systemone_settings.get_backend(),
+ native_ctx = systemone_settings.get_native_ctx(),
+ effective_backend = effective,
+ loaded_backend = runtime["loaded_backend"] if runtime["loaded_model"] else None,
+ fallback_reason = fallback if effective == "pytorch" or effective is None else None,
+ input_modalities = laya_runtime.input_modalities(configured),
)
@@ -1538,7 +1571,10 @@ _SYSTEMONE_SETTINGS_LOCK = threading.Lock()
def _systemone_values(payload: SystemOneSettingsPayload) -> dict[str, Any]:
try:
return systemone_settings.validate(
- **payload.model_dump(include = {"enabled", "model", "device"}, exclude_none = True)
+ **payload.model_dump(
+ include = {"enabled", "model", "device", "backend", "native_ctx"},
+ exclude_none = True,
+ )
)
except ValueError as exc:
raise log_and_http_error(
@@ -1649,7 +1685,9 @@ async def list_systemone_connections(
@_owner_settings_router.get("/systemone/resolve", response_model = SystemOneDownloadPlan)
def resolve_systemone_download(
- model: Optional[str] = None, current_subject: str = Depends(get_current_subject)
+ model: Optional[str] = None,
+ backend: Optional[str] = None,
+ current_subject: str = Depends(get_current_subject),
) -> SystemOneDownloadPlan:
from core.systemone import catalog, laya_runtime
@@ -1662,7 +1700,9 @@ def resolve_systemone_download(
raise HTTPException(status_code = 400, detail = "Unknown Decision API model.")
if isinstance(checkpoint, catalog.Connection):
return SystemOneDownloadPlan(files = [], size_bytes = 0, cached = True)
- return SystemOneDownloadPlan(**laya_runtime.download_plan(checkpoint))
+ if backend is not None and backend not in systemone_settings.BACKENDS:
+ raise HTTPException(status_code = 400, detail = "Unknown Decision API runtime.")
+ return SystemOneDownloadPlan(**laya_runtime.download_plan(checkpoint, preference = backend))
@_owner_settings_router.post("/systemone/unload", response_model = SystemOneSettingsResponse)
diff --git a/studio/backend/routes/systemone.py b/studio/backend/routes/systemone.py
index 7b14b60a3c0..faf0551da5a 100644
--- a/studio/backend/routes/systemone.py
+++ b/studio/backend/routes/systemone.py
@@ -6,6 +6,8 @@
from __future__ import annotations
import asyncio
+import base64
+import binascii
import json
import math
import time
@@ -35,6 +37,11 @@ MAX_CHOICES = 255
MAX_SCORE_LEVELS = 10
MAX_STATE_CHARS = 200_000
MAX_QUESTION_CHARS = 20_000
+MAX_IMAGES = 4
+MAX_IMAGE_BYTES = 4 * 1024 * 1024
+MAX_IMAGES_BYTES = 8 * 1024 * 1024
+# What llama.cpp's mtmd decodes in-process (stb_image); WebP needs an ffmpeg it may not have.
+_IMAGE_TYPES = {"image/png": "PNG", "image/jpeg": "JPEG"}
_TYPES = ("noul", "choice", "score")
MCP_PATH = "/mcp/decisions"
LISTED_MODELS_TTL = 300.0
@@ -60,6 +67,8 @@ class SystemOneRequest(BaseModel):
state: JSONContent
model: str
questions: dict[str, QuestionIn] = Field(min_length = 1)
+ # OpenJev's image extension: base64 data URLs, served by a Clef model through llama.cpp.
+ images: Optional[list[str]] = None
def _error(
@@ -152,8 +161,11 @@ async def system_one(
)
if checkpoint is None:
raise _error(400, "api_usage_error", f"Unknown model: {payload.model}")
- result = await _decide(checkpoint, payload.state, payload.questions)
- return JSONResponse(result, headers = {"x-typesafe-request-id": str(uuid4())})
+ result = await _decide(checkpoint, payload.state, payload.questions, payload.images)
+ headers = {"x-typesafe-request-id": str(uuid4())}
+ if isinstance(checkpoint, catalog.Checkpoint):
+ headers["x-unsloth-decision-backend"] = result.pop("_backend", "pytorch")
+ return JSONResponse(result, headers = headers)
def _require_enabled() -> None:
@@ -165,10 +177,69 @@ def _require_enabled() -> None:
)
+def _validate_images(images: list[str]) -> None:
+ if len(images) > MAX_IMAGES:
+ raise _error(422, "invalid_request_error", f"At most {MAX_IMAGES} images per request")
+ total = 0
+ for index, url in enumerate(images):
+ header, comma, data = url.partition(",")
+ kind = header.removeprefix("data:").removesuffix(";base64")
+ if not comma or kind not in _IMAGE_TYPES or header != f"data:{kind};base64":
+ raise _error(
+ 422,
+ "invalid_request_error",
+ f"images[{index}] must be a PNG or JPEG base64 data URL; remote URLs are not fetched",
+ )
+ if len(data) > 4 * ((MAX_IMAGE_BYTES + 2) // 3):
+ raise _error(422, "invalid_request_error", f"images[{index}] is larger than 4 MiB")
+ try:
+ raw = base64.b64decode(data, validate = True)
+ except (binascii.Error, ValueError):
+ raise _error(
+ 422, "invalid_request_error", f"images[{index}] is not valid base64"
+ ) from None
+ total += len(raw)
+ if not raw or len(raw) > MAX_IMAGE_BYTES or total > MAX_IMAGES_BYTES:
+ raise _error(
+ 422,
+ "invalid_request_error",
+ "Each image must be at most 4 MiB, and all images together at most 8 MiB",
+ )
+ if not _decodes(raw):
+ raise _error(
+ 422,
+ "invalid_request_error",
+ f"images[{index}] is not a readable PNG or JPEG image of at most 4096 x 4096 pixels",
+ )
+
+
+MAX_IMAGE_PIXELS = 4096 * 4096
+
+
+def _decodes(raw: bytes) -> bool:
+ from io import BytesIO
+
+ from PIL import Image
+
+ try:
+ with Image.open(BytesIO(raw)) as image:
+ # By content, as stb_image reads it: a mislabelled JPEG still decodes.
+ if image.format not in _IMAGE_TYPES.values():
+ return False
+ # A few MiB of PNG can decode to gigabytes; stb_image allocates it all.
+ if image.width * image.height > MAX_IMAGE_PIXELS:
+ return False
+ image.verify()
+ except Exception:
+ return False
+ return True
+
+
async def _decide(
checkpoint: catalog.Checkpoint | catalog.Connection,
state: JSONContent,
questions: dict[str, QuestionIn],
+ images: list[str] | None = None,
) -> dict:
if not questions:
raise _error(422, "invalid_request_error", "At least one question is required")
@@ -183,6 +254,12 @@ async def _decide(
raise _error(422, "invalid_request_error", f"At most {MAX_QUESTIONS} questions per request")
for name, question in questions.items():
_validate(name, question)
+ if images:
+ _validate_images(images)
+ if isinstance(checkpoint, catalog.Connection):
+ raise _error(
+ 400, "api_usage_error", "Images are not forwarded to Decision API connections"
+ )
if isinstance(checkpoint, catalog.Connection):
return await _connection_decide(
@@ -196,6 +273,7 @@ async def _decide(
checkpoint,
state,
{name: q.model_dump() for name, q in questions.items()},
+ images or None,
)
except laya_runtime.Unavailable as exc:
raise _error(exc.status, exc.error_type, exc.message, exc.retry_after) from None
@@ -301,17 +379,21 @@ async def refresh_listed_decision_models() -> None:
def decision_model_objects() -> list[dict[str, Any]]:
if not systemone_settings.get_enabled():
return []
+ names = (
+ "default",
+ *(() if systemone_settings.runtime_unavailable_reason() else catalog.CHECKPOINTS),
+ )
return [
{
"id": name,
"object": "model",
"owned_by": "unsloth",
- "architecture": {"input_modalities": ["text"], "output_modalities": ["decisions"]},
+ "architecture": {
+ "input_modalities": laya_runtime.input_modalities(catalog.resolve(name)),
+ "output_modalities": ["decisions"],
+ },
}
- for name in (
- "default",
- *(() if systemone_settings.runtime_unavailable_reason() else catalog.CHECKPOINTS),
- )
+ for name in names
]
@@ -357,7 +439,9 @@ async def decide(state: JSONContent, questions: dict[str, QuestionIn]) -> dict[s
try:
await asyncio.to_thread(_require_enabled)
checkpoint = await asyncio.to_thread(catalog.default_checkpoint)
- return await _decide(checkpoint, state, questions)
+ result = await _decide(checkpoint, state, questions)
+ result.pop("_backend", None)
+ return result
except HTTPException as exc:
raise ToolError(exc.detail["message"]) from None
diff --git a/studio/backend/tests/test_decision_native.py b/studio/backend/tests/test_decision_native.py
new file mode 100644
index 00000000000..3dfaa6f909c
--- /dev/null
+++ b/studio/backend/tests/test_decision_native.py
@@ -0,0 +1,1279 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Clef through llama.cpp: routing, flags, capability, errors and answers, against a stub llama-server."""
+
+import importlib.util
+import json
+import os
+import stat
+import sys
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+from core.inference import gpu_arbiter
+from core.inference.llama_cpp import LlamaCppBackend
+from core.systemone import catalog, gguf_export_contract as contract, laya_runtime, native_worker
+from routes import systemone
+from utils import systemone_settings
+from utils.account_context import OWNER, run_as
+from utils.paths import outputs_root
+
+_REAL_LOAD = laya_runtime._load_checkpoint
+REPO_ROOT = Path(__file__).resolve().parents[3]
+PHYSICAL_BATCH = (
+ "input ({tokens} tokens) is too large to process. increase the physical batch size "
+ "(current batch size: {limit})"
+)
+QUESTIONS = {
+ "route": {
+ "type": "choice",
+ "instructions": "Which team?",
+ "criteria": {"shipping": "parcels", "billing": "charges"},
+ },
+ "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["low", "mid", "high"]},
+ "angry": {"type": "noul", "instructions": None},
+}
+
+# llama-server's /health, /v1/models and /v1/systemone, with llama.cpp's own answer and error shapes.
+STUB = r"""
+import json, os, sys
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+args = sys.argv[1:]
+opt = lambda name: args[args.index(name) + 1] if name in args else None
+mode = os.environ.get("STUB_MODE", "")
+record = os.environ["STUB_RECORD"]
+
+
+def log(kind, **data):
+ with open(record, "a", encoding="utf-8") as f:
+ f.write(json.dumps({"kind": kind, **data}) + "\n")
+
+
+log("start", argv=args, env={k: os.environ.get(k) for k in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES")})
+if mode == "exit":
+ print("stub: failed to load model", flush=True)
+ sys.exit(3)
+key = opt("--api-key") or open(opt("--api-key-file"), encoding="utf-8").read().strip()
+port, alias, ub, mmproj = int(opt("--port")), opt("--alias"), int(opt("-ub")), "--mmproj" in args
+
+
+def answer(q):
+ if q["type"] == "noul":
+ return {"type": "noul", "noul": 0.7}
+ keys = sorted(q["criteria"]) if q["type"] == "choice" else [str(i) for i in range(len(q["criteria"]))]
+ weights = [i + 1 for i in range(len(keys))]
+ probs = {k: w / sum(weights) for k, w in zip(keys, weights)}
+ best = max(probs, key=probs.get)
+ uniform = 1 / len(keys)
+ out = {"type": q["type"], "probabilities": probs, "confidence": (probs[best] - uniform) / (1 - uniform)}
+ if q["type"] == "choice":
+ out["choice"] = best
+ else:
+ out["score"] = sum(i * p for i, p in enumerate(probs.values()))
+ out["legend"] = dict(zip(keys, q["criteria"]))
+ return out
+
+
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def send(self, status, body):
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def error(self, status, message):
+ self.send(status, {"error": {"code": status, "message": message, "type": "x"}})
+
+ def do_GET(self):
+ if self.path == "/health":
+ return self.send(200, {"status": "ok"})
+ if self.headers.get("Authorization") != f"Bearer {key}":
+ return self.error(401, "Invalid API Key")
+ outputs = ["text"] if mode == "nodecisions" else ["decisions"]
+ inputs = ["text", "image", "video"] if mmproj else ["text"]
+ served = "someone-else" if mode == "wrongalias" else alias
+ self.send(200, {"object": "list", "data": [{"id": served, "aliases": [served],
+ "architecture": {"input_modalities": inputs, "output_modalities": outputs}}]})
+
+ def do_POST(self):
+ if self.headers.get("Authorization") != f"Bearer {key}":
+ return self.error(401, "Invalid API Key")
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ log("request", body=body)
+ state = body["state"] if isinstance(body["state"], str) else json.dumps(body["state"])
+ if state == "crash":
+ os._exit(1)
+ if state == "badimage":
+ return self.error(500, "Failed to load image or audio file")
+ if state == "reject":
+ return self.error(400, 'questions.q: "criteria" must be a non-empty object')
+ if state == "context":
+ return self.error(400, "request (9000 tokens) exceeds the available context size (8192 tokens), try increasing it")
+ tokens = len(state.split()) + 10
+ if tokens > ub:
+ return self.error(500, f"input ({tokens} tokens) is too large to process. increase the physical batch size (current batch size: {ub})")
+ answers = {name: answer(q) for name, q in body["questions"].items()}
+ self.send(200, {"model": body["model"], "answers": answers, "usage": {"input_tokens": tokens, "output_tokens": 0}})
+
+
+ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
+"""
+
+
+def _formatter():
+ # The vendored reference, loaded independently of the module under test.
+ path = REPO_ROOT / "unsloth" / "_vendor" / "clef" / "joint_schema_model.py"
+ spec = importlib.util.spec_from_file_location("_test_clef_reference", path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["_test_clef_reference"] = module
+ spec.loader.exec_module(module)
+ return module.systemone_answer
+
+
+def _stub_probabilities(question):
+ if question["type"] == "noul":
+ return {"true": 0.7, "false": 0.3}
+ keys = (
+ sorted(question["criteria"])
+ if question["type"] == "choice"
+ else [str(i) for i in range(len(question["criteria"]))]
+ )
+ weights = [i + 1 for i in range(len(keys))]
+ return {k: w / sum(weights) for k, w in zip(keys, weights)}
+
+
+def stub(tmp_path, monkeypatch):
+ record = tmp_path / "stub_record.jsonl"
+ script = tmp_path / "stub_server.py"
+ script.write_text(STUB, encoding = "utf-8")
+ binary = tmp_path / "llama-server"
+ binary.write_text(f"#!{sys.executable}\nexec(open({str(script)!r}).read())\n", encoding = "utf-8")
+ binary.chmod(binary.stat().st_mode | stat.S_IEXEC)
+ monkeypatch.setenv("STUB_RECORD", str(record))
+ monkeypatch.setattr(native_worker, "resolve_binary", lambda: str(binary))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_llama_server_env_for_binary", staticmethod(lambda _: os.environ.copy())
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_enumerated_gpu_devices", staticmethod(lambda *_: ["CUDA0", "CUDA1"])
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_get_gpu_free_memory",
+ staticmethod(lambda *_, **__: [(0, 1000), (1, 90000)]),
+ )
+
+ def records(kind):
+ if not record.exists():
+ return []
+ rows = [json.loads(line) for line in record.read_text(encoding = "utf-8").splitlines()]
+ return [row for row in rows if row["kind"] == kind]
+
+ yield SimpleNamespace(
+ binary = binary, records = records, set_mode = lambda m: monkeypatch.setenv("STUB_MODE", m)
+ )
+ laya_runtime.shutdown()
+
+
+def home(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ for name in (
+ "UNSLOTH_SYSTEMONE_MODEL",
+ "UNSLOTH_SYSTEMONE_DISABLE",
+ "UNSLOTH_SYSTEMONE_DEVICE",
+ "STUB_MODE",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ for name in (
+ "_agent",
+ "_loaded",
+ "_device_name",
+ "_loader",
+ "_loading",
+ "_failure",
+ "_fallback_reason",
+ ):
+ monkeypatch.setattr(laya_runtime, name, None)
+ monkeypatch.setattr(laya_runtime, "_incapable", set())
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(systemone_settings, "runtime_unavailable_reason", lambda: None)
+ monkeypatch.setattr(systemone_settings, "gpu_available", lambda: False)
+ monkeypatch.setattr(laya_runtime, "_load_checkpoint", _REAL_LOAD)
+ monkeypatch.setattr(laya_runtime, "_training_active", lambda: state.training)
+ # The stock Clef safetensors are never fetched here: the PyTorch worker below is a fake.
+ clef_dir = tmp_path / "clef_safetensors"
+ clef_dir.mkdir()
+ monkeypatch.setattr(laya_runtime, "_clef_dir", lambda checkpoint, local_only: clef_dir)
+ cache = tmp_path / "hub"
+ monkeypatch.setattr("utils.hf_cache_settings.active_hf_hub_cache", lambda: str(cache))
+ state = SimpleNamespace(training = False, torch_agents = [], cache = cache)
+
+ from core.systemone import clef_runtime
+
+ class TorchAgent:
+ device = "cuda"
+
+ def __init__(
+ self,
+ folder,
+ cancelled = None,
+ ):
+ self.closed = False
+ state.torch_agents.append(self)
+
+ def decide(self, state_, questions):
+ systemone_answer = _formatter()
+ answers = {n: systemone_answer(q, _stub_probabilities(q)) for n, q in questions.items()}
+ return {"answers": answers, "input_tokens": 13, "truncated": False}
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr(clef_runtime, "ClefAgent", TorchAgent)
+ from utils.hardware import hardware
+
+ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.CUDA)
+ monkeypatch.setattr(hardware, "DEVICE", hardware.DeviceType.CUDA)
+ outputs = run_as(OWNER, outputs_root)
+ outputs.mkdir(parents = True)
+ state.outputs = outputs
+ yield state
+ if laya_runtime._loader is not None:
+ laya_runtime._loader.join(5)
+ laya_runtime.shutdown()
+
+
+def _cache_gguf(cache: Path, name: str = "clef-flash") -> None:
+ companion = catalog.GGUF_COMPANIONS[name]
+ folder = (
+ cache / f"models--{companion.repo.replace('/', '--')}" / "snapshots" / companion.revision
+ )
+ folder.mkdir(parents = True)
+ for file in (companion.model, companion.mmproj):
+ if file:
+ (folder / file).write_bytes(b"GGUF")
+
+
+def client(home):
+ from routes.settings import router as settings_router
+
+ app = FastAPI()
+ app.include_router(systemone.router, prefix = "/v1")
+ app.include_router(settings_router, prefix = "/api/settings")
+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"
+ return TestClient(app)
+
+
+def _put(client, **settings):
+ response = client.put("/api/settings/systemone", json = settings)
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _post(
+ client,
+ state = "The parcel never arrived.",
+ questions = QUESTIONS,
+ images = None,
+ model = "default",
+):
+ body = {"model": model, "state": state, "questions": questions}
+ if images is not None:
+ body["images"] = images
+ for _ in range(100):
+ response = client.post("/v1/systemone", json = body)
+ if (
+ response.status_code != 503
+ or response.json()["detail"]["error_type"] != "model_loading"
+ ):
+ return response
+ time.sleep(0.1)
+ return response
+
+
+PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+
+
+def _clef_folder(root: Path, name = "clef_run") -> Path:
+ folder = root / name
+ folder.mkdir(parents = True)
+ for file in ("config.json", "joint_head_config.json", "unsloth_decision_config.json"):
+ (folder / file).write_text("{}", encoding = "utf-8")
+ (folder / "joint_head.safetensors").write_bytes(b"head")
+ (folder / "model.safetensors").write_bytes(b"")
+ return folder
+
+
+def _export(
+ folder: Path,
+ quants = ("Q8_0",),
+ mmproj = True,
+ fingerprint = None,
+) -> None:
+ directory = folder / contract.EXPORT_DIR
+ directory.mkdir(exist_ok = True)
+ files = {}
+ for quant in quants:
+ (directory / f"model-{quant}.gguf").write_bytes(b"GGUF")
+ if mmproj:
+ (directory / f"mmproj-{quant}.gguf").write_bytes(b"GGUF")
+ files[quant] = {
+ "model": f"model-{quant}.gguf",
+ "mmproj": f"mmproj-{quant}.gguf" if mmproj else None,
+ }
+ (directory / contract.EXPORT_FILE).write_text(
+ json.dumps(
+ {
+ "format": contract.FORMAT,
+ "version": 1,
+ "layout": "clef",
+ "quantizations": list(quants),
+ "files": files,
+ "source_fingerprint": fingerprint or contract.fingerprint(folder, "clef"),
+ }
+ ),
+ encoding = "utf-8",
+ )
+
+
+def test_fingerprint_follows_the_calibration_and_head_bytes(tmp_path):
+ folder = _clef_folder(tmp_path)
+ first = contract.fingerprint(folder, "clef")
+ assert first == contract.fingerprint(folder, "clef") and len(first) == 64
+ # The backbone weights are not part of it; the head and the calibration are.
+ (folder / "model.safetensors").write_bytes(b"other")
+ assert contract.fingerprint(folder, "clef") == first
+ time.sleep(0.01)
+ (folder / "unsloth_decision_config.json").write_text(
+ '{"temperature": [1, 2, 3]}', encoding = "utf-8"
+ )
+ assert contract.fingerprint(folder, "clef") != first
+ laya = tmp_path / "laya"
+ laya.mkdir()
+ (laya / "rl_agent_config.json").write_text("{}", encoding = "utf-8")
+ assert contract.fingerprint(laya, "laya") != contract.fingerprint(laya, "clef")
+ with pytest.raises(ValueError):
+ contract.fingerprint(laya, "other")
+
+
+def test_the_served_export_prefers_q8_then_f16_and_ignores_stale_ones(tmp_path, caplog):
+ folder = _clef_folder(tmp_path)
+ assert contract.read_export(folder) is None and contract.served_files(folder, "clef") is None
+ _export(folder, quants = ("Q4_K_M", "F16", "Q8_0"))
+ quant, model, mmproj = contract.served_files(folder, "clef")
+ assert (quant, model.name, mmproj.name) == ("Q8_0", "model-Q8_0.gguf", "mmproj-Q8_0.gguf")
+ (folder / "gguf" / "model-Q8_0.gguf").unlink()
+ assert contract.served_files(folder, "clef")[0] == "F16"
+ assert contract.served_files(folder, "laya") is None
+
+ stale = _clef_folder(tmp_path, "stale_run")
+ _export(stale, fingerprint = "0" * 64)
+ with caplog.at_level("INFO"):
+ assert contract.served_files(stale, "clef") is None
+ assert contract.served_files(stale, "clef") is None
+ assert sum("stale GGUF export" in r.message for r in caplog.records) == 1
+
+
+ "edit",
+ [
+ lambda d: d.update(format = "other"),
+ lambda d: d.update(version = 2),
+ lambda d: d.update(layout = "llm"),
+ lambda d: d["files"]["Q8_0"].update(model = "../escape.gguf"),
+ lambda d: d["files"]["Q8_0"].update(mmproj = "sub/mmproj.gguf"),
+ lambda d: d.update(quantizations = ["Q4_0"]),
+ ],
+)
+def test_a_malformed_export_is_not_served(tmp_path, edit):
+ folder = _clef_folder(tmp_path)
+ _export(folder)
+ path = folder / "gguf" / "export.json"
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ edit(data)
+ path.write_text(json.dumps(data), encoding = "utf-8")
+ assert contract.read_export(folder) is None
+
+
+def test_cpu_flags_hide_the_gpu_and_keep_weights_unrepacked(home, stub, tmp_path):
+ model, mmproj = tmp_path / "m.gguf", tmp_path / "mm.gguf"
+ model.write_bytes(b"GGUF")
+ mmproj.write_bytes(b"GGUF")
+ agent = native_worker.NativeClefAgent(model, mmproj, "clef-flash", gpu = False, ctx = 4096)
+ try:
+ start = stub.records("start")[0]
+ argv = start["argv"]
+ value = lambda flag: argv[argv.index(flag) + 1]
+ assert (value("-m"), value("--mmproj"), value("--alias")) == (
+ str(model),
+ str(mmproj),
+ "clef-flash",
+ )
+ assert (value("--host"), value("--parallel")) == ("127.0.0.1", "1")
+ assert value("-c") == value("-b") == value("-ub") == "4096"
+ assert (value("-ngl"), value("--device")) == ("0", "none")
+ assert "--no-repack" in argv and "--no-mmproj-offload" in argv
+ assert start["env"] == {"CUDA_VISIBLE_DEVICES": "", "HIP_VISIBLE_DEVICES": "-1"}
+ assert agent.device == "cpu" and agent.accepts_images
+ finally:
+ agent.close()
+ assert not agent.is_alive()
+
+
+def test_the_key_is_passed_in_a_private_file_and_files_go_with_the_server(home, stub, tmp_path):
+ from utils.paths.storage_roots import auth_root
+
+ model = tmp_path / "m.gguf"
+ model.write_bytes(b"GGUF")
+ agent = native_worker.NativeClefAgent(model, None, "clef-flash", gpu = False)
+ argv = stub.records("start")[0]["argv"]
+ key_file, log_file = Path(argv[argv.index("--api-key-file") + 1]), agent._log_path
+ assert "--api-key" not in argv and agent._key not in " ".join(argv)
+ assert key_file.parent == auth_root() and key_file.read_text(encoding = "utf-8") == agent._key
+ assert len(agent._key) >= 32
+ if os.name != "nt":
+ assert stat.S_IMODE(key_file.stat().st_mode) == 0o600
+ second = native_worker.NativeClefAgent(model, None, "clef-flash", gpu = False)
+ assert second._log_path != log_file and second._key_file != key_file
+ for each in (agent, second):
+ each.close()
+ assert not key_file.exists() and not log_file.exists() and not second._key_file.exists()
+
+
+def test_gpu_flags_offload_to_the_freest_device(home, stub, tmp_path):
+ model = tmp_path / "m.gguf"
+ model.write_bytes(b"GGUF")
+ agent = native_worker.NativeClefAgent(model, None, "clef-ft:run", gpu = True)
+ try:
+ argv = stub.records("start")[0]["argv"]
+ assert argv[argv.index("-ngl") + 1] == "-1" and argv[argv.index("--device") + 1] == "CUDA1"
+ assert argv[argv.index("-ub") + 1] == str(native_worker.DEFAULT_CTX)
+ assert "--mmproj" not in argv and "--no-repack" not in argv
+ # Without a projector the server reads text only.
+ assert agent.device == "CUDA1" and not agent.accepts_images
+ api_key = agent._key
+ finally:
+ agent.close()
+ second = native_worker.NativeClefAgent(model, None, "x", gpu = True)
+ second.close()
+ assert second._key != api_key
+
+
[email protected]("mode", ["nodecisions", "wrongalias"])
+def test_a_server_without_a_decisions_output_is_not_capable(home, stub, tmp_path, mode):
+ model = tmp_path / "m.gguf"
+ model.write_bytes(b"GGUF")
+ stub.set_mode(mode)
+ with pytest.raises(native_worker.NativeIncapable, match = "decisions"):
+ native_worker.NativeClefAgent(model, None, "clef-flash", gpu = False)
+
+
+def test_a_server_that_dies_at_startup_is_a_startup_error(home, stub, tmp_path):
+ model = tmp_path / "m.gguf"
+ model.write_bytes(b"GGUF")
+ stub.set_mode("exit")
+ with pytest.raises(native_worker.NativeError, match = "exited while loading") as failed:
+ native_worker.NativeClefAgent(model, None, "clef-flash", gpu = False)
+ # The server's own output is quoted, and a server that died by itself keeps its log.
+ assert "code 3" in str(failed.value) and "stub: failed to load model" in str(failed.value)
+ from utils.paths.storage_roots import studio_root
+
+ kept = list((studio_root() / "logs").glob("decision-llama-server-*.log"))
+ assert len(kept) == 1 and "stub: failed to load model" in kept[0].read_text(encoding = "utf-8")
+
+
+def test_the_binary_comes_from_studios_resolver(monkeypatch, tmp_path):
+ binary = tmp_path / "llama-server"
+ binary.write_text("#!/bin/sh\n", encoding = "utf-8")
+ binary.chmod(0o755)
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(binary))
+ assert Path(native_worker.resolve_binary()).resolve() == binary.resolve()
+
+
+def test_error_mapping():
+ batch = native_worker.map_error(500, PHYSICAL_BATCH.format(tokens = 20158, limit = 16384))
+ assert isinstance(batch, native_worker.NativeContextOverflow)
+ assert (batch.tokens, batch.limit, batch.status) == (20158, 16384, 422)
+ assert "at most 16384" in str(batch)
+ for status, text in (
+ (
+ 400,
+ "request (9000 tokens) exceeds the available context size (8192 tokens), try increasing it",
+ ),
+ (400, "input (9000 tokens) is larger than the max context size (8192 tokens). skipping"),
+ (
+ 400,
+ "the question and its options (3000 tokens) are too large to process. increase the batch size (current batch size: 2048)",
+ ),
+ ):
+ assert isinstance(
+ native_worker.map_error(status, text), native_worker.NativeContextOverflow
+ )
+ # llama.cpp answers an image mtmd cannot decode with HTTP 500, from a healthy server.
+ undecodable = native_worker.map_error(500, "Failed to load image or audio file")
+ assert type(undecodable) is native_worker.NativeInputError and not undecodable.retire
+ other = native_worker.map_error(400, 'questions.q: "type" must be one of: choice, score, noul')
+ assert (
+ type(other) is native_worker.NativeInputError and other.status == 422 and not other.retire
+ )
+ for status in (401, 403, 500, 502):
+ failure = native_worker.map_error(status, "boom")
+ assert (
+ type(failure) is native_worker.NativeError and failure.status == 503 and failure.retire
+ )
+
+
+def test_answers_are_rebuilt_with_the_pytorch_formatter():
+ # llama.cpp's own confidence for 0.8 / 0.2 is the normalised 0.6; PyTorch answers the winning probability.
+ questions = {
+ "c": {"type": "choice", "instructions": "x", "criteria": {"b": "B", "a": "A"}},
+ "s": {"type": "score", "instructions": "x", "criteria": ["low", "high"]},
+ "n": {"type": "noul", "instructions": "x", "criteria": None},
+ }
+ native = {
+ "answers": {
+ "c": {
+ "type": "choice",
+ "choice": "a",
+ "probabilities": {"a": 0.8, "b": 0.2},
+ "confidence": 0.6,
+ },
+ "s": {
+ "type": "score",
+ "score": 0.75,
+ "probabilities": {"0": 0.25, "1": 0.75},
+ "confidence": 0.5,
+ "legend": {"0": "low", "1": "high"},
+ },
+ "n": {"type": "noul", "noul": 0.123456},
+ },
+ "usage": {"input_tokens": 42, "output_tokens": 0},
+ }
+ result = native_worker.normalise(native, questions)
+ systemone_answer = _formatter()
+ assert result["answers"] == {
+ "c": systemone_answer(questions["c"], {"a": 0.8, "b": 0.2}),
+ "s": systemone_answer(questions["s"], {"0": 0.25, "1": 0.75}),
+ "n": systemone_answer(questions["n"], {"true": 0.123456, "false": 1 - 0.123456}),
+ }
+ assert result["answers"]["c"]["confidence"] == 0.8
+ assert result["answers"]["s"]["confidence"] == 0.75
+ assert result["answers"]["n"] == {"type": "noul", "noul": 0.1235}
+ assert (result["input_tokens"], result["truncated"]) == (42, False)
+ bad = {"answers": {**native["answers"], "c": {"probabilities": {"a": 0.8}}}}
+ with pytest.raises(native_worker.NativeError, match = '"c"'):
+ native_worker.normalise(bad, questions)
+
+
+def test_auto_serves_a_stock_clef_through_llama_cpp(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ settings = client.get("/api/settings/systemone").json()
+ assert (settings["backend"], settings["effective_backend"]) == ("auto", "llama.cpp")
+ assert settings["input_modalities"] == ["text", "image"]
+ response = _post(client)
+ assert response.status_code == 200, response.text
+ assert response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ body = response.json()
+ assert body["model"] == "clef-flash" and body["usage"]["input_tokens"] > 0
+ # GPU by default when there is one; the device is the CPU here (gpu_available is False).
+ argv = stub.records("start")[0]["argv"]
+ companion = catalog.GGUF_COMPANIONS["clef-flash"]
+ assert argv[argv.index("-m") + 1].endswith(f"{companion.revision}/{companion.model}")
+ assert argv[argv.index("--mmproj") + 1].endswith(companion.mmproj)
+ wire = stub.records("request")[0]["body"]
+ assert wire["model"] == "clef-flash"
+ # A missing instruction is the question id, as in Cloudflare's reference encoder.
+ assert wire["questions"]["angry"] == {"type": "noul", "instructions": "angry"}
+ status = client.get("/api/settings/systemone").json()
+ assert (status["loaded_model"], status["loaded_backend"], status["loaded_device"]) == (
+ "clef-flash",
+ "llama.cpp",
+ "cpu",
+ )
+ assert home.torch_agents == []
+
+
+def test_both_backends_answer_the_same_body(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ native = _post(client)
+ _put(client, backend = "pytorch")
+ torch = _post(client)
+ assert torch.headers["x-unsloth-decision-backend"] == "pytorch"
+ assert home.torch_agents and native.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ native_body, torch_body = native.json(), torch.json()
+ native_body["usage"] = torch_body["usage"] = None
+ assert native_body == torch_body
+
+
+def test_auto_without_llama_server_uses_pytorch_and_says_why(home, client, monkeypatch):
+ _cache_gguf(home.cache)
+ monkeypatch.setattr(native_worker, "resolve_binary", lambda: None)
+ _put(client, enabled = True, model = "clef-flash")
+ settings = client.get("/api/settings/systemone").json()
+ assert settings["effective_backend"] == "pytorch"
+ assert settings["fallback_reason"] == "llama-server is not installed."
+ assert settings["input_modalities"] == ["text"]
+ response = _post(client)
+ assert (
+ response.status_code == 200 and response.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ refused = _post(client, images = [PNG])
+ assert refused.status_code == 400
+ assert "Images are served only by llama.cpp" in refused.json()["detail"]["message"]
+
+
+def test_auto_retries_on_pytorch_when_the_build_has_no_decisions(home, client, stub):
+ _cache_gguf(home.cache)
+ stub.set_mode("nodecisions")
+ _put(client, enabled = True, model = "clef-flash")
+ response = _post(client)
+ assert (
+ response.status_code == 200 and response.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ assert len(stub.records("start")) == 1
+ assert _post(client).headers["x-unsloth-decision-backend"] == "pytorch"
+ assert len(stub.records("start")) == 1
+ assert (
+ "cannot serve decision models"
+ in client.get("/api/settings/systemone").json()["fallback_reason"]
+ )
+
+
+def test_forced_backends_give_clear_errors(home, client, stub, monkeypatch):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash", backend = "pytorch")
+ refused = _post(client, images = [PNG])
+ assert refused.status_code == 400 and "Auto or llama.cpp" in refused.json()["detail"]["message"]
+
+ _put(client, backend = "llama.cpp")
+ gap = {"one": {"type": "score", "instructions": "x", "criteria": ["only"]}}
+ refused = _post(client, questions = gap)
+ assert (
+ refused.status_code == 422 and "at least two levels" in refused.json()["detail"]["message"]
+ )
+ monkeypatch.setattr(native_worker, "resolve_binary", lambda: None)
+ refused = _post(client)
+ assert refused.status_code == 503
+ assert refused.json()["detail"]["message"].startswith("llama-server is not installed.")
+ assert home.torch_agents == []
+
+ # A fine-tune without an export has no GGUF at all.
+ folder = _clef_folder(home.outputs, "clef_noexport")
+ _put(client, model = catalog.CLEF_FINE_TUNE_PREFIX + folder.name)
+ refused = _post(client)
+ assert (
+ refused.status_code == 400
+ and "no current GGUF export" in refused.json()["detail"]["message"]
+ )
+
+
+def test_auto_sends_what_llama_cpp_cannot_parse_to_pytorch(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ gap = {"one": {"type": "score", "instructions": "x", "criteria": ["only"]}}
+ response = _post(client, questions = gap)
+ assert (
+ response.status_code == 200 and response.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ assert stub.records("start") == []
+
+
+def test_images_reach_llama_cpp_and_laya_refuses_them(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ response = _post(client, images = [PNG])
+ assert (
+ response.status_code == 200
+ and response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ )
+ assert stub.records("request")[0]["body"]["images"] == [PNG]
+ for bad in (
+ ["https://example.com/a.png"],
+ ["data:image/gif;base64,R0lGOD"],
+ ["data:image/png;base64,%%%"],
+ [PNG] * 5,
+ ):
+ assert _post(client, images = bad).status_code == 422
+ _put(client, model = "laya-multilingual")
+ refused = _post(client, images = [PNG])
+ assert (
+ refused.status_code == 400 and "Laya reads text only" in refused.json()["detail"]["message"]
+ )
+
+
[email protected]("ctx, retried", [(1024, True), (16384, False)])
+def test_auto_retries_an_over_long_state_on_pytorch_only_when_it_is_longer(
+ home, client, stub, ctx, retried
+):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash", native_ctx = ctx)
+ long_state = "word " * (ctx + 50)
+ response = _post(client, state = long_state)
+ if retried:
+ assert (
+ response.status_code == 200
+ and response.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ status = client.get("/api/settings/systemone").json()
+ assert status["loaded_backend"] == "pytorch"
+ assert status["fallback_reason"] == "The request is longer than the llama.cpp context."
+ # The resident PyTorch model keeps serving text under Auto instead of reloading.
+ assert _post(client).headers["x-unsloth-decision-backend"] == "pytorch"
+ assert len(stub.records("start")) == 1
+ else:
+ assert response.status_code == 422
+ assert f"at most {ctx}" in response.json()["detail"]["message"]
+ assert home.torch_agents == []
+
+
+def test_other_native_failures_are_surfaced_not_retried(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ rejected = _post(client, state = "reject")
+ assert rejected.status_code == 422 and "criteria" in rejected.json()["detail"]["message"]
+ assert _post(client).status_code == 200
+ crashed = _post(client, state = "crash")
+ assert (
+ crashed.status_code == 503 and crashed.json()["detail"]["error_type"] == "model_unavailable"
+ )
+ assert home.torch_agents == []
+ # The crashed server was retired; the next request starts a fresh one.
+ deadline = time.monotonic() + 5
+ while laya_runtime._agent is not None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert _post(client).status_code == 200
+ assert len(stub.records("start")) == 2
+ # A context overflow below PyTorch's window is the one failure Auto answers on PyTorch.
+ overflow = _post(client, state = "context")
+ assert (
+ overflow.status_code == 200 and overflow.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ _put(client, backend = "llama.cpp")
+ overflow = _post(client, state = "context")
+ assert overflow.status_code == 422 and "at most 8192" in overflow.json()["detail"]["message"]
+
+
+def test_training_and_the_gpu_arbiter_gate_a_gpu_server(home, client, stub, monkeypatch):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash", device = "gpu")
+ home.training = True
+ busy = _post(client)
+ assert busy.status_code == 503 and "training run" in busy.json()["detail"]["message"]
+ assert stub.records("start") == []
+ home.training = False
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ # Auto answers text on PyTorch beside the chat model, as before llama.cpp served decisions.
+ beside = _post(client)
+ assert beside.status_code == 200 and beside.headers["x-unsloth-decision-backend"] == "pytorch"
+ assert client.get("/api/settings/systemone").json()["fallback_reason"] == (
+ "Another model is using the GPU."
+ )
+ # Only llama.cpp reads images: those still wait for the GPU.
+ busy = _post(client, images = [PNG])
+ assert (
+ busy.status_code == 409 and "Unload the resident chat" in busy.json()["detail"]["message"]
+ )
+ laya_runtime.unload()
+ _put(client, backend = "llama.cpp")
+ busy = _post(client)
+ assert (
+ busy.status_code == 409 and "Unload the resident chat" in busy.json()["detail"]["message"]
+ )
+ assert stub.records("start") == []
+ _put(client, backend = "auto")
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ assert _post(client).headers["x-unsloth-decision-backend"] == "llama.cpp"
+ assert gpu_arbiter.current_owner() == gpu_arbiter.DECISIONS
+ # A chat load evicts the idle server through the arbiter.
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: None)
+ gpu_arbiter.acquire_for(gpu_arbiter.CHAT)
+ assert laya_runtime._agent is None and gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ # Training that starts while it is resident ends it and answers 503.
+ assert _post(client).status_code == 200
+ home.training = True
+ assert _post(client).status_code == 503
+ assert laya_runtime._agent is None and gpu_arbiter.current_owner() is None
+
+
+def test_a_cpu_server_keeps_serving_during_training(home, client, stub):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash", device = "cpu")
+ home.training = True
+ assert _post(client).status_code == 200
+ # A request only PyTorch can answer waits for the GPU, without ending the CPU server.
+ gap = {"one": {"type": "score", "instructions": "x", "criteria": ["only"]}}
+ assert _post(client, questions = gap).status_code == 503
+ assert laya_runtime._agent is not None
+ assert _post(client).status_code == 200
+ assert len(stub.records("start")) == 1
+
+
+def test_a_re_export_replaces_the_resident_server(home, client, stub):
+ folder = _clef_folder(home.outputs, "clef_reexported")
+ _export(folder)
+ _put(client, enabled = True, model = catalog.CLEF_FINE_TUNE_PREFIX + folder.name)
+ assert _post(client).headers["x-unsloth-decision-backend"] == "llama.cpp"
+ time.sleep(0.01)
+ replacement = folder / contract.EXPORT_DIR / "model-Q8_0.gguf.tmp"
+ replacement.write_bytes(b"GGUF re-exported")
+ os.replace(replacement, folder / contract.EXPORT_DIR / "model-Q8_0.gguf")
+ assert _post(client).headers["x-unsloth-decision-backend"] == "llama.cpp"
+ assert len(stub.records("start")) == 2
+
+
+def test_a_fine_tune_serves_its_current_export_and_ignores_a_stale_one(home, client, stub):
+ folder = _clef_folder(home.outputs, "clef_exported")
+ name = catalog.CLEF_FINE_TUNE_PREFIX + folder.name
+ _put(client, enabled = True, model = name)
+ assert _post(client).headers["x-unsloth-decision-backend"] == "pytorch"
+ _export(folder)
+ laya_runtime.unload()
+ response = _post(client)
+ assert response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ argv = stub.records("start")[0]["argv"]
+ assert argv[argv.index("-m") + 1] == str(folder / "gguf" / "model-Q8_0.gguf")
+ assert argv[argv.index("--alias") + 1] == name
+ # Recalibrating the folder makes the export stale: PyTorch again.
+ laya_runtime.unload()
+ time.sleep(0.01)
+ (folder / "unsloth_decision_config.json").write_text(
+ '{"temperature": [2, 2, 2]}', encoding = "utf-8"
+ )
+ assert _post(client).headers["x-unsloth-decision-backend"] == "pytorch"
+
+
+def test_laya_serving_is_unchanged(home, client, stub, monkeypatch):
+ monkeypatch.setattr(
+ laya_runtime, "_load_checkpoint", lambda checkpoint: (SimpleNamespace(), "cpu")
+ )
+ monkeypatch.setattr(
+ laya_runtime,
+ "_predict",
+ lambda agent, state, questions: (
+ {
+ "answers": {n: {"type": "noul", "noul": 0.5, "confidence": 0.5} for n in questions},
+ "usage": {"input_tokens": 1, "output_tokens": 0},
+ },
+ False,
+ ),
+ )
+ _put(client, enabled = True, model = "laya-multilingual", backend = "llama.cpp")
+ response = _post(client, questions = {"q": {"type": "noul", "instructions": "x"}})
+ assert (
+ response.status_code == 200 and response.headers["x-unsloth-decision-backend"] == "pytorch"
+ )
+ assert stub.records("start") == []
+
+
+def test_an_idle_server_unloads_and_a_stale_timer_does_nothing(home, client, stub, monkeypatch):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ monkeypatch.setattr(laya_runtime, "IDLE_UNLOAD_S", 0.3)
+ assert _post(client).status_code == 200
+ agent = laya_runtime._agent
+ generation = laya_runtime._generation
+ deadline = time.monotonic() + 5
+ while laya_runtime._agent is not None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert laya_runtime._agent is None and not agent.is_alive()
+ # A timer from that generation never touches the server loaded after it.
+ assert _post(client).status_code == 200
+ newer = laya_runtime._agent
+ monkeypatch.setattr(laya_runtime, "_last_used", 0.0)
+ laya_runtime._idle_unload(generation)
+ assert laya_runtime._agent is newer and newer.is_alive()
+
+
+def test_a_load_that_loses_its_generation_is_not_published(home, stub, monkeypatch, tmp_path):
+ _cache_gguf(home.cache)
+ target, _ = laya_runtime.select(catalog.CHECKPOINTS["clef-flash"])
+ real = native_worker.NativeClefAgent
+ built = []
+
+ def racing(*args, **kwargs):
+ agent = real(*args, **kwargs)
+ built.append(agent)
+ # Something unloaded the Decision API while this server started.
+ laya_runtime._unloads += 1
+ return agent
+
+ monkeypatch.setattr(native_worker, "NativeClefAgent", racing)
+ laya_runtime._load(target)
+ assert laya_runtime._agent is None and not built[0].is_alive()
+
+
+def test_the_model_list_shows_image_input_only_where_llama_cpp_serves_it(
+ home, client, stub, monkeypatch
+):
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ listed = {
+ m["id"]: m["architecture"]["input_modalities"] for m in systemone.decision_model_objects()
+ }
+ assert listed["clef-flash"] == listed["clef"] == listed["default"] == ["text", "image"]
+ assert listed["laya-multilingual"] == ["text"]
+ _put(client, backend = "pytorch")
+ listed = {
+ m["id"]: m["architecture"]["input_modalities"] for m in systemone.decision_model_objects()
+ }
+ assert listed["clef-flash"] == ["text"]
+
+
+ "owner, status", [(gpu_arbiter.DECISIONS, 409), (gpu_arbiter.DIFFUSION, None)]
+)
+def test_a_chat_load_refused_by_a_busy_decision_server_is_retryable(owner, status):
+ import asyncio
+ from unittest.mock import MagicMock, patch
+
+ from fastapi import HTTPException
+
+ from models.inference import LoadRequest
+ from routes import inference as inference_route
+
+ path = "unsloth/Qwen3-0.6B-GGUF"
+ with (
+ patch.object(
+ inference_route,
+ "_resolve_model_identifier_for_request",
+ return_value = (path, path, False),
+ ),
+ patch.object(
+ inference_route, "resolve_effective_chat_template_override", return_value = None
+ ),
+ patch.object(
+ inference_route, "get_inference_backend", return_value = MagicMock(active_model_name = None)
+ ),
+ patch.object(inference_route, "get_llama_cpp_backend", return_value = MagicMock()),
+ patch.object(
+ inference_route.ModelConfig,
+ "from_identifier",
+ side_effect = gpu_arbiter.GpuOwnerBusyError(owner),
+ ),
+ ):
+ load = inference_route.load_model(LoadRequest(model_path = path), MagicMock(), "unsloth")
+ if status is None:
+ # The preview route maps the image/video refusal itself.
+ with pytest.raises(gpu_arbiter.GpuOwnerBusyError):
+ asyncio.run(load)
+ return
+ with pytest.raises(HTTPException) as refused:
+ asyncio.run(load)
+ assert refused.value.status_code == 409 and refused.value.headers["Retry-After"] == "5"
+ assert refused.value.detail == "The Decision API is using the GPU; retry shortly."
+
+
+def _image_url(kind, data):
+ import base64
+ return f"data:image/{kind};base64," + base64.b64encode(data).decode()
+
+
+def test_an_unreadable_image_is_refused_and_the_server_keeps_serving(home, client, stub):
+ import io
+
+ from PIL import Image
+
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ webp = io.BytesIO()
+ Image.new("RGB", (8, 8), (255, 0, 0)).save(webp, "WEBP")
+ jpeg = io.BytesIO()
+ Image.new("RGB", (8, 8), (255, 0, 0)).save(jpeg, "JPEG")
+ for bad in (
+ _image_url("webp", webp.getvalue()),
+ _image_url("png", b"\x89PNG\r\n\x1a\n" + b"garbage" * 20),
+ _image_url("png", webp.getvalue()),
+ ):
+ refused = _post(client, images = [bad])
+ assert refused.status_code == 422, refused.text
+ assert stub.records("start") == []
+ assert _post(client, images = [_image_url("jpeg", jpeg.getvalue())]).status_code == 200
+ # One the server still cannot decode is the caller's error, not a crash.
+ refused = _post(client, state = "badimage", images = [PNG])
+ assert refused.status_code == 422 and "Failed to load image" in refused.text
+ assert _post(client).status_code == 200
+ assert len(stub.records("start")) == 1
+
+
+def test_a_slow_close_keeps_the_claim_of_a_server_loading_after_it(home, monkeypatch, tmp_path):
+ import threading
+
+ native = laya_runtime._native_target(catalog.CHECKPOINTS["clef-flash"])
+ closing, closed = threading.Event(), threading.Event()
+
+ class Server:
+ backend, gpu, device = "llama.cpp", True, "CUDA0"
+
+ def __init__(self, slow = False):
+ self.slow = slow
+
+ def close(self):
+ if self.slow:
+ closing.set()
+ # llama-server takes its time to exit; the next load starts meanwhile.
+ time.sleep(0.3)
+ closed.set()
+
+ def starting(*args, **kwargs):
+ assert closed.wait(5)
+ return Server()
+
+ monkeypatch.setattr(laya_runtime, "_native_gpu", lambda: True)
+ monkeypatch.setattr(laya_runtime, "_native_files", lambda *a, **k: (tmp_path / "m.gguf", None))
+ monkeypatch.setattr(native_worker, "NativeClefAgent", starting)
+ gpu_arbiter.acquire_for(gpu_arbiter.DECISIONS, allow_evict = False)
+ old = Server(slow = True)
+ monkeypatch.setattr(laya_runtime, "_agent", old)
+ monkeypatch.setattr(laya_runtime, "_loaded", native)
+ retire = threading.Thread(target = laya_runtime._evict_agent, args = (old,))
+ retire.start()
+ assert closing.wait(5)
+ monkeypatch.setattr(laya_runtime, "_loading", native)
+ laya_runtime._load(native)
+ retire.join(5)
+ assert isinstance(laya_runtime._agent, Server) and laya_runtime._agent is not old
+ assert gpu_arbiter.current_owner() == gpu_arbiter.DECISIONS
+ # With nothing loading or resident, a close hands the GPU back.
+ laya_runtime.unload()
+ assert gpu_arbiter.current_owner() is None
+
+
+def test_auto_keeps_pytorch_while_the_gguf_is_not_downloaded(home, client, stub):
+ _put(client, enabled = True, model = "clef-flash")
+ clef = catalog.CHECKPOINTS["clef-flash"]
+ target, reason = laya_runtime.select(clef)
+ assert target == clef and "not downloaded" in reason
+ assert client.get("/api/settings/systemone").json()["effective_backend"] == "pytorch"
+ response = _post(client)
+ assert response.headers["x-unsloth-decision-backend"] == "pytorch"
+ assert stub.records("start") == []
+ # Images and a forced llama.cpp still take the GGUF.
+ assert laya_runtime.select(clef, images = [PNG])[0].backend == "llama.cpp"
+ assert laya_runtime.select(clef, preference = "llama.cpp")[0].backend == "llama.cpp"
+ laya_runtime.unload()
+ _cache_gguf(home.cache)
+ assert laya_runtime.select(clef) == (laya_runtime._native_target(clef), None)
+
+
+def test_an_over_long_state_is_not_retried_where_pytorch_cannot_serve_clef(
+ home, client, stub, monkeypatch
+):
+ from utils.hardware import hardware
+
+ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.MLX)
+ monkeypatch.setattr(hardware, "DEVICE", hardware.DeviceType.MLX)
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash", native_ctx = 1024)
+ response = _post(client, state = "word " * 1100)
+ assert response.status_code == 422 and "at most 1024" in response.json()["detail"]["message"]
+ assert home.torch_agents == []
+
+
+def _cache_blob(
+ cache: Path,
+ name: str,
+ revision: str,
+ sha256s = None,
+) -> None:
+ # The Hub cache layout: snapshot files link to blobs named by their LFS sha256.
+ companion = catalog.GGUF_COMPANIONS[name]
+ repo = cache / f"models--{companion.repo.replace('/', '--')}"
+ (repo / "blobs").mkdir(parents = True, exist_ok = True)
+ (repo / "snapshots" / revision).mkdir(parents = True)
+ files = [f for f in (companion.model, companion.mmproj) if f]
+ for file, sha256 in zip(files, sha256s or companion.sha256):
+ (repo / "blobs" / sha256).write_bytes(b"GGUF")
+ (repo / "snapshots" / revision / file).symlink_to(Path("..", "..", "blobs", sha256))
+
+
+def test_gguf_entries_are_listed_as_llama_cpp_only(home, client, stub):
+ gguf = {n for n, c in catalog.CHECKPOINTS.items() if c.layout == "gguf"}
+ assert gguf == {
+ "kev-0.8b",
+ "kev-4b",
+ "kev-9b",
+ "lev",
+ "bespoke-nimble-9b-v3",
+ "openjev",
+ "laya-gguf",
+ "julia-1",
+ }
+ for name in gguf:
+ checkpoint, companion = catalog.CHECKPOINTS[name], catalog.GGUF_COMPANIONS[name]
+ assert checkpoint.backend == "llama.cpp" and checkpoint.source == companion.repo
+ assert len(companion.sha256) == (2 if companion.mmproj else 1)
+ assert systemone_settings.DEFAULT_MODEL == "laya-multilingual"
+ _put(client, enabled = True)
+ options = {m["name"]: m for m in client.get("/api/settings/systemone").json()["models"]}
+ assert options["kev-0.8b"]["llama_cpp_only"] and options["kev-0.8b"]["label"] == "Kev 0.8B"
+ assert options["kev-0.8b"]["available"] and options["kev-0.8b"]["download_bytes"] == 812_406_304
+ assert not options["clef-flash"]["llama_cpp_only"] and options["clef-flash"]["label"] is None
+ listed = {
+ m["id"]: m["architecture"]["input_modalities"] for m in systemone.decision_model_objects()
+ }
+ assert listed["openjev"] == ["text", "image"] and listed["kev-0.8b"] == ["text"]
+ stub.set_mode("nodecisions")
+ laya_runtime._incapable.add(laya_runtime._binary_key(str(stub.binary)))
+ option = {m["name"]: m for m in client.get("/api/settings/systemone").json()["models"]}["lev"]
+ assert (
+ not option["available"] and "cannot serve decision models" in option["unavailable_reason"]
+ )
+
+
+def test_a_gguf_entry_is_served_only_by_llama_cpp(home, client, stub, monkeypatch):
+ _cache_gguf(home.cache, "kev-0.8b")
+ _put(client, enabled = True, model = "kev-0.8b")
+ settings = client.get("/api/settings/systemone").json()
+ assert (settings["effective_backend"], settings["input_modalities"]) == ("llama.cpp", ["text"])
+ response = _post(client)
+ assert response.status_code == 200, response.text
+ assert response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ argv = stub.records("start")[0]["argv"]
+ companion = catalog.GGUF_COMPANIONS["kev-0.8b"]
+ assert argv[argv.index("-m") + 1].endswith(f"{companion.revision}/{companion.model}")
+ assert "--mmproj" not in argv and argv[argv.index("--alias") + 1] == "kev-0.8b"
+ refused = _post(client, images = [PNG])
+ assert (
+ refused.status_code == 422 and "no vision projector" in refused.json()["detail"]["message"]
+ )
+
+ _put(client, backend = "pytorch")
+ settings = client.get("/api/settings/systemone").json()
+ assert settings["effective_backend"] is None
+ assert "served only by llama.cpp" in settings["fallback_reason"]
+ refused = _post(client)
+ assert refused.status_code == 400
+ assert "Auto or llama.cpp" in refused.json()["detail"]["message"]
+
+ _put(client, backend = "llama.cpp")
+ assert _post(client).status_code == 200
+ monkeypatch.setattr(native_worker, "resolve_binary", lambda: None)
+ _put(client, backend = "auto")
+ refused = _post(client)
+ assert refused.status_code == 503
+ assert refused.json()["detail"]["message"] == (
+ "kev-0.8b needs llama.cpp: llama-server is not installed."
+ )
+ assert home.torch_agents == []
+
+
+def test_a_build_without_decisions_is_a_clear_error_for_a_gguf_entry(home, client, stub):
+ _cache_gguf(home.cache, "julia-1")
+ stub.set_mode("nodecisions")
+ _put(client, enabled = True, model = "julia-1")
+ for _ in range(2):
+ response = _post(client)
+ assert response.status_code == 503
+ assert response.json()["detail"]["message"] == (
+ "julia-1 needs llama.cpp: This llama.cpp build cannot serve decision models; "
+ "update llama.cpp in Studio."
+ )
+ assert len(stub.records("start")) == 1 and home.torch_agents == []
+
+
+def test_a_gguf_entry_passes_llama_cpp_answers_through(home, client, stub):
+ _cache_gguf(home.cache, "laya-gguf")
+ _put(client, enabled = True, model = "laya-gguf")
+ response = _post(client)
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["model"] == "laya-gguf"
+ assert body["usage"] == {"input_tokens": 14, "output_tokens": 0}
+ # llama.cpp's normalised confidence, not the Clef formatter's winning probability.
+ assert body["answers"]["route"] == {
+ "type": "choice",
+ "choice": "shipping",
+ "confidence": pytest.approx((2 / 3 - 1 / 2) / (1 - 1 / 2)),
+ "probabilities": {"billing": pytest.approx(1 / 3), "shipping": pytest.approx(2 / 3)},
+ }
+ assert body["answers"]["urgency"]["legend"] == {"0": "low", "1": "mid", "2": "high"}
+ assert body["answers"]["urgency"]["score"] == pytest.approx(2 / 6 + 2 * 3 / 6)
+ assert body["answers"]["angry"] == {"type": "noul", "noul": 0.7}
+
+ # An over-long state is refused, never retried on PyTorch.
+ _put(client, native_ctx = 1024)
+ response = _post(client, state = "word " * 1100)
+ assert response.status_code == 422 and "at most 1024" in response.json()["detail"]["message"]
+ assert home.torch_agents == []
+
+
+def test_gguf_answers_are_checked_before_they_pass_through():
+ questions = {"c": {"type": "choice", "instructions": "x", "criteria": {"a": "A", "b": "B"}}}
+ good = {
+ "type": "choice",
+ "choice": "a",
+ "probabilities": {"a": 0.8, "b": 0.2},
+ "confidence": 0.6,
+ }
+ result = native_worker.normalise({"answers": {"c": good}}, questions, clef_answers = False)
+ assert result["answers"]["c"] == good
+ for bad in (
+ {**good, "choice": "z"},
+ {**good, "confidence": None},
+ {**good, "probabilities": {"a": 0.8}},
+ ):
+ with pytest.raises(native_worker.NativeError, match = '"c"'):
+ native_worker.normalise({"answers": {"c": bad}}, questions, clef_answers = False)
+
+
+def test_the_download_plan_pins_the_revision_and_main_with_the_same_blob_counts(home, client):
+ companion = catalog.GGUF_COMPANIONS["openjev"]
+ checkpoint = catalog.CHECKPOINTS["openjev"]
+ assert laya_runtime.download_plan(checkpoint, preference = "pytorch")["revision"] == (
+ companion.revision
+ )
+ plan = client.get("/api/settings/systemone/resolve", params = {"model": "openjev"}).json()
+ assert plan == {
+ "repo": "ggml-org/OpenJev-GGUF",
+ "files": ["OpenJev-Q8_0.gguf", "mmproj-OpenJev-Q8_0.gguf"],
+ "size_bytes": 28_595_765_408 + 629_247_232,
+ "cached": False,
+ "error": None,
+ }
+ # The settings download fetches main: another commit holding different bytes is not the model.
+ _cache_blob(home.cache, "openjev", "f" * 40, ("0" * 64, "1" * 64))
+ assert not laya_runtime.is_cached(checkpoint)
+ _cache_blob(home.cache, "openjev", "e" * 40)
+ assert laya_runtime.is_cached(checkpoint)
+ model, mmproj = laya_runtime._native_files(checkpoint, local_only = True)
+ assert model.parent.name == mmproj.parent.name == "e" * 40
+ assert client.get("/api/settings/systemone/resolve", params = {"model": "openjev"}).json()[
+ "cached"
+ ]
+ # The Clef companions resolve the same way.
+ _cache_blob(home.cache, "clef-flash", "e" * 40)
+ assert laya_runtime.is_cached(laya_runtime._native_target(catalog.CHECKPOINTS["clef-flash"]))
+
+
+def test_an_image_that_decodes_to_too_many_pixels_is_refused(home, client, stub):
+ import io
+
+ from PIL import Image
+
+ _cache_gguf(home.cache)
+ _put(client, enabled = True, model = "clef-flash")
+ big = io.BytesIO()
+ Image.new("1", (8192, 8192)).save(big, "PNG")
+ assert len(big.getvalue()) < 4 * 1024 * 1024
+ refused = _post(client, images = [_image_url("png", big.getvalue())])
+ assert refused.status_code == 422 and "4096 x 4096" in refused.text
+ assert stub.records("start") == []
diff --git a/studio/backend/tests/test_decision_native_gpu.py b/studio/backend/tests/test_decision_native_gpu.py
new file mode 100644
index 00000000000..d6ffc76171b
--- /dev/null
+++ b/studio/backend/tests/test_decision_native_gpu.py
@@ -0,0 +1,438 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Stock Clef-Flash Q8_0 through Studio's Decision API on a real llama-server, against FastDecisionModel.
+
+Needs a CUDA GPU, LLAMA_SERVER_PATH (a llama.cpp b11443 or newer build, e.g. Studio's prebuilt) and
+ggml-org/Clef-Flash-GGUF at the pinned revision in UNSLOTH_TEST_CLEF_GGUF_CACHE (a hub cache dir).
+The PyTorch reference (Cloudflare/clef-flash, bf16) runs in its own process: Unsloth patches
+transformers process-wide.
+"""
+
+import base64
+import io
+import json
+import os
+import random
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+sys.path.insert(0, str(REPO_ROOT / "tests" / "_shared"))
+from real_accelerator import has_real_cuda # noqa: E402
+
+pytestmark = [
+ pytest.mark.gpu,
+ pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA GPU"),
+ pytest.mark.skipif(
+ not os.environ.get("LLAMA_SERVER_PATH"),
+ reason = "needs LLAMA_SERVER_PATH (llama.cpp >= b11443)",
+ ),
+ pytest.mark.skipif(
+ not os.environ.get("UNSLOTH_TEST_CLEF_GGUF_CACHE"),
+ reason = "needs UNSLOTH_TEST_CLEF_GGUF_CACHE holding ggml-org/Clef-Flash-GGUF",
+ ),
+]
+
+TEXT = {
+ "support": {
+ "state": "Customer message: I was charged twice for my order last week and nobody has replied.",
+ "questions": {
+ "route": {
+ "type": "choice",
+ "instructions": "Which team should handle this?",
+ "criteria": {
+ "billing": "payments and refunds",
+ "shipping": None,
+ "technical": None,
+ },
+ },
+ "urgency": {
+ "type": "score",
+ "instructions": "How urgent is this?",
+ "criteria": ["can wait", "this week", "today", "right now"],
+ },
+ "angry": {"type": "noul", "instructions": "Is the customer angry?"},
+ },
+ },
+ "review": {
+ "state": "Product review: The headphones arrived quickly and sound great, but the left ear cushion "
+ "started peeling after two days. Still, for the price I'd buy them again.",
+ "questions": {
+ "sentiment": {
+ "type": "choice",
+ "instructions": "Overall sentiment of the review?",
+ "criteria": {"positive": None, "neutral": None, "negative": None},
+ },
+ "stars": {
+ "type": "score",
+ "instructions": "How many stars would this reviewer give?",
+ "criteria": ["1 star", "2 stars", "3 stars", "4 stars", "5 stars"],
+ },
+ "defect": {"type": "noul", "instructions": "Does the review report a product defect?"},
+ },
+ },
+ "moderation": {
+ "state": {
+ "user": "alice",
+ "message": "Can someone tell me how to reset my router password? "
+ "I tried the default one on the sticker and it does not work.",
+ },
+ "questions": {
+ "category": {
+ "type": "choice",
+ "instructions": "What kind of post is this?",
+ "criteria": {
+ "question": "asks for help",
+ "spam": "advertising or scams",
+ "harassment": "attacks another user",
+ "announcement": None,
+ },
+ },
+ "safe": {
+ "type": "noul",
+ "instructions": "Is this post safe to publish?",
+ "criteria": {
+ "true": "allowed by community rules",
+ "false": "breaks community rules",
+ },
+ },
+ },
+ },
+}
+
+
+def _long_state(n_words = 5000, seed = 0):
+ rnd = random.Random(seed)
+ lines = [
+ f"[{i:04d}] agent: order {rnd.randint(10000, 99999)} status checked, "
+ f"carrier scan at hub {rnd.randint(1, 40)} recorded."
+ for i in range(n_words // 14)
+ ]
+ lines.insert(
+ len(lines) // 2, "[note] customer: the package arrived broken and I want a full refund now!"
+ )
+ return "Support log:\n" + "\n".join(lines)
+
+
+TEXT["long_state"] = {
+ "state": _long_state(),
+ "questions": {
+ "issue": {
+ "type": "choice",
+ "instructions": "What does the customer complain about?",
+ "criteria": {
+ "damaged item": None,
+ "late delivery": None,
+ "wrong item": None,
+ "no complaint": None,
+ },
+ },
+ "refund": {"type": "noul", "instructions": "Does the customer ask for a refund?"},
+ },
+}
+
+
+def _red_circle():
+ from PIL import Image, ImageDraw
+
+ image = Image.new("RGB", (256, 256), "white")
+ ImageDraw.Draw(image).ellipse((48, 48, 208, 208), fill = (220, 20, 20))
+ buffer = io.BytesIO()
+ image.save(buffer, format = "PNG")
+ return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
+
+
+IMAGE = {
+ "state": "An image was attached to a support ticket.",
+ "questions": {
+ "color": {
+ "type": "choice",
+ "instructions": "What is the color of the main shape in the image?",
+ "criteria": {"red": None, "green": None, "blue": None, "yellow": None},
+ },
+ "shape": {
+ "type": "choice",
+ "instructions": "What shape is shown in the image?",
+ "criteria": {"circle": None, "square": None, "triangle": None},
+ },
+ "has_text": {"type": "noul", "instructions": "Does the image contain written text?"},
+ },
+}
+
+REFERENCE = r"""
+import json, sys
+import unsloth # noqa: F401 (before transformers)
+from unsloth import FastDecisionModel
+
+requests, out = json.load(open(sys.argv[1])), sys.argv[2]
+model, tokenizer = FastDecisionModel.from_pretrained("Cloudflare/clef-flash", use_gradient_checkpointing=False)
+model.eval()
+answers = {name: FastDecisionModel.predict(model, tokenizer, r["state"], r["questions"]) for name, r in requests.items()}
+json.dump(answers, open(out, "w"), default=str)
+"""
+
+
+def _probabilities(answer):
+ if answer["type"] == "noul":
+ return {"true": float(answer["noul"])}
+ return {k: float(v) for k, v in answer["probabilities"].items()}
+
+
+def _top(answer):
+ if answer["type"] == "noul":
+ return float(answer["noul"]) > 0.5
+ if answer["type"] == "choice":
+ return answer["choice"]
+ # The expected level: an argmax flips on a near tie (0.422 / 0.423) that both backends read the same.
+ return round(float(answer["score"]))
+
+
[email protected](scope = "module")
+def reference(tmp_path_factory):
+ folder = tmp_path_factory.mktemp("clef_reference")
+ (folder / "requests.json").write_text(json.dumps(TEXT), encoding = "utf-8")
+ (folder / "reference.py").write_text(REFERENCE, encoding = "utf-8")
+ env = {**os.environ, "PYTHONPATH": str(REPO_ROOT)}
+ subprocess.run(
+ [
+ sys.executable,
+ str(folder / "reference.py"),
+ str(folder / "requests.json"),
+ str(folder / "out.json"),
+ ],
+ check = True,
+ env = env,
+ cwd = folder,
+ timeout = 3600,
+ )
+ return json.loads((folder / "out.json").read_text(encoding = "utf-8"))
+
+
+def studio(tmp_path, monkeypatch):
+ yield from _studio(tmp_path, monkeypatch, {"model": "clef-flash"})
+
+
+def _studio(tmp_path, monkeypatch, settings):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from core.inference import gpu_arbiter
+ from core.systemone import laya_runtime
+ from routes import systemone
+ from routes.settings import router as settings_router
+ from utils.account_context import OWNER, run_as
+ from utils.paths import outputs_root
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ for name in (
+ "UNSLOTH_SYSTEMONE_MODEL",
+ "UNSLOTH_SYSTEMONE_DISABLE",
+ "UNSLOTH_SYSTEMONE_DEVICE",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache",
+ lambda: os.environ["UNSLOTH_TEST_CLEF_GGUF_CACHE"],
+ )
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ run_as(OWNER, outputs_root).mkdir(parents = True)
+ app = FastAPI()
+ app.include_router(systemone.router, prefix = "/v1")
+ app.include_router(settings_router, prefix = "/api/settings")
+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"
+ client = TestClient(app)
+ response = client.put(
+ "/api/settings/systemone", json = {"enabled": True, "device": "gpu", **settings}
+ )
+ assert response.status_code == 200, response.text
+ yield client
+ laya_runtime.shutdown()
+
+
+def _post(
+ client,
+ request,
+ images = None,
+ model = "clef-flash",
+):
+ body = {"model": model, "state": request["state"], "questions": request["questions"]}
+ if images:
+ body["images"] = images
+ deadline = time.monotonic() + 900
+ while True:
+ response = client.post("/v1/systemone", json = body)
+ loading = (
+ response.status_code == 503
+ and response.json()["detail"]["error_type"] == "model_loading"
+ )
+ if not loading or time.monotonic() > deadline:
+ return response
+ time.sleep(1)
+
+
+def test_clef_flash_on_llama_cpp_matches_pytorch(studio, reference, monkeypatch, record_property):
+ from core.systemone import laya_runtime
+
+ rows, worst = [], 0.0
+ for name, request in TEXT.items():
+ started = time.monotonic()
+ response = _post(studio, request)
+ assert response.status_code == 200, response.text
+ assert response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ native = response.json()
+ for question, answer in native["answers"].items():
+ expected = reference[name][question]
+ ours, theirs = _probabilities(answer), _probabilities(expected)
+ diff = max(abs(ours[k] - theirs[k]) for k in ours)
+ worst = max(worst, diff)
+ rows.append(
+ {
+ "request": name,
+ "question": question,
+ "type": answer["type"],
+ "same_answer": _top(answer) == _top(expected),
+ "max_abs_prob_diff": round(diff, 4),
+ "input_tokens": native["usage"]["input_tokens"],
+ "latency_s": round(time.monotonic() - started, 3),
+ }
+ )
+ print(json.dumps(rows, indent = 1))
+ record_property("parity", rows)
+ assert all(row["same_answer"] for row in rows), rows
+ assert worst <= 0.01, rows
+ assert max(r["input_tokens"] for r in rows) > 10000
+
+ image = _post(studio, IMAGE, images = [_red_circle()])
+ assert image.status_code == 200, image.text
+ answers = image.json()["answers"]
+ print(json.dumps(answers, indent = 1))
+ assert answers["color"]["choice"] == "red" and answers["shape"]["choice"] == "circle"
+ assert answers["has_text"]["noul"] < 0.5
+ status = studio.get("/api/settings/systemone").json()
+ assert (status["loaded_backend"], status["input_modalities"]) == (
+ "llama.cpp",
+ ["text", "image"],
+ )
+ assert status["loaded_device"].startswith("CUDA")
+
+ # A training run takes the GPU: the server is ended and the Decision API answers 503.
+ agent = laya_runtime._agent
+ monkeypatch.setattr(laya_runtime, "_training_active", lambda: True)
+ busy = _post(studio, TEXT["support"])
+ assert busy.status_code == 503 and "training run" in busy.json()["detail"]["message"]
+ assert laya_runtime._agent is None and not agent.is_alive()
+
+
+def _bare_llama_server(model_path, requests, log_path):
+ """llama.cpp's own answers: the GGUF on a plain llama-server with the flags Studio passes."""
+ import socket
+ import urllib.request
+
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ binary = os.environ["LLAMA_SERVER_PATH"]
+ env = {**os.environ, "LD_LIBRARY_PATH": str(Path(binary).parent)}
+ command = [binary, "-m", str(model_path), "--host", "127.0.0.1", "--port", str(port)]
+ command += ["--parallel", "1", "-c", "8192", "-b", "8192", "-ub", "8192", "-ngl", "-1"]
+ with open(log_path, "wb") as log:
+ process = subprocess.Popen(command, stdout = log, stderr = subprocess.STDOUT, env = env)
+ base = f"http://127.0.0.1:{port}"
+ try:
+ deadline = time.monotonic() + 600
+ while True:
+ assert process.poll() is None, Path(log_path).read_text(errors = "replace")[-2000:]
+ try:
+ with urllib.request.urlopen(base + "/health", timeout = 2) as response:
+ if response.status == 200:
+ break
+ except OSError:
+ pass
+ assert time.monotonic() < deadline
+ time.sleep(0.5)
+ answers = {}
+ for name, request in requests.items():
+ data = json.dumps({"model": "x", **request}).encode()
+ post = urllib.request.Request(
+ base + "/v1/systemone", data, {"Content-Type": "application/json"}
+ )
+ with urllib.request.urlopen(post, timeout = 300) as response:
+ answers[name] = json.loads(response.read())
+ return answers
+ finally:
+ process.terminate()
+ process.wait(30)
+
+
+GGUF_ONLY = ["kev-0.8b", "laya-gguf", "julia-1"]
+# The ggml_decision_sweep requests: support, review, moderation (no long state, no images).
+SWEEP = {name: TEXT[name] for name in ("support", "review", "moderation")}
+
+
[email protected]("name", GGUF_ONLY)
+def test_a_gguf_only_model_answers_as_bare_llama_server(
+ name, tmp_path, monkeypatch, record_property
+):
+ from core.inference import llama_cpp
+ from core.systemone import catalog, laya_runtime
+
+ # Studio's own probe gives --list-devices 30 s; a loaded CI host can take longer.
+ binary = os.environ["LLAMA_SERVER_PATH"]
+ listed = subprocess.run(
+ [binary, "--list-devices"],
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ env = llama_cpp.LlamaCppBackend._llama_server_env_for_binary(binary),
+ )
+ devices = llama_cpp._parse_listed_devices(listed.stdout)
+ assert devices, listed.stdout + listed.stderr
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_enumerated_gpu_devices", staticmethod(lambda *_: devices)
+ )
+ client = next(
+ _studio(tmp_path, monkeypatch, {"model": name, "backend": "auto", "native_ctx": 8192})
+ )
+ try:
+ rows = []
+ for request_name, request in SWEEP.items():
+ response = _post(client, request, model = name)
+ assert response.status_code == 200, response.text
+ assert response.headers["x-unsloth-decision-backend"] == "llama.cpp"
+ rows.append((request_name, response.json()))
+ status = client.get("/api/settings/systemone").json()
+ assert (status["loaded_model"], status["loaded_backend"]) == (name, "llama.cpp")
+ assert status["loaded_device"].startswith("CUDA")
+ model_path, _ = laya_runtime._native_files(catalog.CHECKPOINTS[name], local_only = True)
+ assert catalog.GGUF_COMPANIONS[name].revision in str(model_path)
+ finally:
+ laya_runtime.shutdown()
+ bare = _bare_llama_server(model_path, SWEEP, tmp_path / "bare.log")
+ worst = 0.0
+ for request_name, body in rows:
+ assert body["model"] == name
+ expected = bare[request_name]
+ assert body["usage"] == expected["usage"]
+ assert set(body["answers"]) == set(expected["answers"])
+ for question, answer in body["answers"].items():
+ theirs = expected["answers"][question]
+ assert answer.keys() == theirs.keys(), (answer, theirs)
+ for key, value in answer.items():
+ if isinstance(value, float):
+ worst = max(worst, abs(value - theirs[key]))
+ elif key == "probabilities":
+ assert value.keys() == theirs[key].keys()
+ worst = max(worst, *(abs(v - theirs[key][k]) for k, v in value.items()))
+ else:
+ assert value == theirs[key], (question, key)
+ record_property("max_abs_diff", worst)
+ print(json.dumps({"model": name, "max_abs_diff": worst, "studio": dict(rows)}, indent = 1))
+ assert worst <= 1e-9
diff --git a/studio/backend/tests/test_decision_serving.py b/studio/backend/tests/test_decision_serving.py
index 333bdba62cb..e2bcdcb7f28 100644
--- a/studio/backend/tests/test_decision_serving.py
+++ b/studio/backend/tests/test_decision_serving.py
@@ -488,7 +488,11 @@ def test_the_catalog_offers_the_stock_clef_models():
for name, repo in (("clef", "Cloudflare/clef"), ("clef-flash", "Cloudflare/clef-flash")):
checkpoint = catalog.CHECKPOINTS[name]
assert (checkpoint.source, checkpoint.layout, checkpoint.subfolder) == (repo, "clef", None)
- assert all(c.layout == "laya" for n, c in catalog.CHECKPOINTS.items() if n.startswith("laya"))
+ assert all(
+ c.layout == "laya"
+ for n, c in catalog.CHECKPOINTS.items()
+ if n.startswith("laya") and c.backend == "pytorch"
+ )
@pytest.mark.parametrize("kind", ["mlx", "xpu", "cpu"])
@@ -505,7 +509,11 @@ def test_clef_refuses_a_machine_without_an_nvidia_or_amd_gpu(home, client, clef,
for name in (served, "clef", "clef-flash"):
assert models[name]["available"] is False
assert models[name]["unavailable_reason"] == catalog.CLEF_NEEDS_GPU
- assert all(m["available"] for n, m in models.items() if n.startswith("laya"))
+ assert all(
+ m["available"]
+ for n, m in models.items()
+ if n.startswith("laya") and not m["llama_cpp_only"]
+ )
@pytest.mark.parametrize("kind", ["cuda", "rocm"])
@@ -515,7 +523,12 @@ def test_clef_serves_on_nvidia_and_amd_gpus(home, client, clef, monkeypatch, kin
_spoof_device(monkeypatch, kind)
assert _post(client).status_code == 200
models = client.get("/api/settings/systemone").json()["models"]
- assert all(m["available"] and m["unavailable_reason"] is None for m in models)
+ # The GGUF-only entries depend on a llama-server, which this test does not install.
+ assert all(
+ m["available"] and m["unavailable_reason"] is None
+ for m in models
+ if not m["llama_cpp_only"]
+ )
def test_a_failed_device_probe_does_not_refuse_clef(monkeypatch):
diff --git a/studio/backend/tests/test_decision_training.py b/studio/backend/tests/test_decision_training.py
index 4f3e1e10694..40adad31fc2 100644
--- a/studio/backend/tests/test_decision_training.py
+++ b/studio/backend/tests/test_decision_training.py
@@ -520,6 +520,36 @@ def test_llm_output_scans_skip_decision_outputs(studio_home):
assert [name for name, _, _ in scan_checkpoints(str(root))] == ["llama_merged_1"]
+def test_export_checkpoint_list_includes_decision_runs(studio_home):
+ from routes import models as models_routes
+ from utils.models.checkpoints import list_preview_targets
+ from utils.paths import outputs_root
+
+ root = outputs_root()
+ laya = _fake_output(root, "laya_done_1")
+ (laya / "rl_agent_config.json").write_text(
+ json.dumps({"encoder": "answerdotai/ModernBERT-base", "training": {"base": "laya-tiny"}}),
+ encoding = "utf-8",
+ )
+ _fake_output(root, "laya_half_2", complete = False)
+ clef = root / "clef_merged_3"
+ clef.mkdir()
+ for name in ("config.json", "joint_head_config.json", "joint_head.safetensors"):
+ (clef / name).write_text("{}", encoding = "utf-8")
+
+ app = FastAPI()
+ app.include_router(models_routes.router, prefix = "/api/models")
+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"
+ response = TestClient(app).get("/api/models/checkpoints", params = {"outputs_dir": str(root)})
+ assert response.status_code == 200, response.text
+ listed = {m["name"]: m for m in response.json()["models"]}
+ assert sorted(listed) == ["clef_merged_3", "laya_done_1"]
+ assert listed["laya_done_1"]["base_model"] == "laya-tiny"
+ assert listed["laya_done_1"]["checkpoints"][0]["path"] == str(laya)
+ # Chat preview still lists only what chat can load.
+ assert [t["run"] for t in list_preview_targets(str(root))] == ["clef_merged_3"]
+
+
def test_model_config_offers_an_llm_as_a_decision_model(studio_home):
import asyncio
diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.py
index 99c5f737e53..7b46336a275 100644
--- a/studio/backend/tests/test_export_absolute_paths.py
+++ b/studio/backend/tests/test_export_absolute_paths.py
@@ -117,6 +117,9 @@ def _install_lightweight_backend_stubs(monkeypatch):
monkeypatch.setitem(sys.modules, "core.export", core_export)
monkeypatch.setitem(sys.modules, "core.inference", core_inference)
core_export.q4nx = _load_module("core.export.q4nx", "core/export/q4nx.py", monkeypatch)
+ core_export.decision = _load_module(
+ "core.export.decision", "core/export/decision.py", monkeypatch
+ )
_load_module(
"core.inference.model_ids",
"core/inference/model_ids.py",
@@ -213,6 +216,7 @@ def _install_lightweight_backend_stubs(monkeypatch):
"ConvertQ4NXRequest",
"ExportLoRAAdapterRequest",
"LlmCompressorExportProbeResponse",
+ "ExportDecisionInfoResponse",
):
setattr(models_pkg, name, object)
models_pkg.LocalModelInfo = _LocalModelInfo
diff --git a/studio/backend/tests/test_export_decision_backend.py b/studio/backend/tests/test_export_decision_backend.py
new file mode 100644
index 00000000000..5a55ba3facc
--- /dev/null
+++ b/studio/backend/tests/test_export_decision_backend.py
@@ -0,0 +1,407 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Decision checkpoints (Clef, Laya) in the export worker: detected before the chat / vision
+loaders, GGUF only, through unsloth.models.decision_gguf (stubbed here)."""
+
+from __future__ import annotations
+
+import ast
+import json
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = Path(__file__).resolve().parent.parent
+_TESTS_DIR = Path(__file__).resolve().parent
+for _path in (_BACKEND_DIR, _TESTS_DIR):
+ if str(_path) not in sys.path:
+ sys.path.insert(0, str(_path))
+
+from test_export_absolute_paths import ( # noqa: E402
+ _install_export_backend_stubs,
+ _load_module,
+)
+
+_QWEN35 = {"architectures": ["Qwen3_5ForConditionalGeneration"], "model_type": "qwen3_5"}
+
+
+def _write(
+ folder: Path,
+ files: dict,
+ dirs = (),
+) -> Path:
+ folder.mkdir(parents = True, exist_ok = True)
+ for name, content in files.items():
+ data = content if isinstance(content, (bytes, str)) else json.dumps(content)
+ (folder / name).write_bytes(data if isinstance(data, bytes) else data.encode("utf-8"))
+ for name in dirs:
+ (folder / name).mkdir(parents = True, exist_ok = True)
+ return folder
+
+
+def _clef_merged(tmp_path, config = _QWEN35) -> Path:
+ return _write(
+ tmp_path / "clef_run",
+ {
+ "config.json": config,
+ "model.safetensors": b"w",
+ "joint_head.safetensors": b"h",
+ "joint_head_config.json": {},
+ "unsloth_decision_config.json": {},
+ },
+ )
+
+
+def _clef_adapter(tmp_path) -> Path:
+ return _write(
+ tmp_path / "clef_adapter",
+ {
+ "adapter_config.json": {"base_model_name_or_path": "unsloth/Qwen3.5-0.8B"},
+ "adapter_model.safetensors": b"a",
+ "joint_head.safetensors": b"h",
+ "joint_head_config.json": {},
+ },
+ )
+
+
+def _laya(tmp_path) -> Path:
+ folder = _write(
+ tmp_path / "laya_run",
+ {"rl_agent_config.json": {}, "model.safetensors": b"w"},
+ dirs = ("encoder", "tokenizer"),
+ )
+ (folder / "encoder" / "config.json").write_text(
+ json.dumps({"model_type": "modernbert"}), encoding = "utf-8"
+ )
+ return folder
+
+
+class _Recorder:
+ def __init__(self):
+ self.calls = []
+ self.tokens = []
+
+
+class _ForbiddenLoader:
+ calls = []
+
+ @classmethod
+ def from_pretrained(cls, *args, **kwargs):
+ cls.calls.append((args, kwargs))
+ raise AssertionError("chat / vision loader reached for a decision checkpoint")
+
+
+def env(monkeypatch):
+ _install_export_backend_stubs(monkeypatch)
+ lib = _Recorder()
+ lib.eligibility = None
+
+ def gguf_eligibility(folder, *args, **kwargs):
+ lib.calls.append(("eligibility", folder))
+ if lib.eligibility is not None:
+ return lib.eligibility
+ layout = "clef" if (Path(folder) / "joint_head_config.json").is_file() else "laya"
+ return {"eligible": True, "layout": layout, "reason": None}
+
+ def export_decision_gguf(
+ checkpoint_folder,
+ quantization_method,
+ output_dir = None,
+ source_folder = None,
+ print_output = False,
+ ):
+ lib.calls.append(
+ ("export", checkpoint_folder, list(quantization_method), output_dir, source_folder)
+ )
+ return {"quantizations": [q.upper() for q in quantization_method]}
+
+ decision_gguf = types.ModuleType("unsloth.models.decision_gguf")
+ decision_gguf.gguf_eligibility = gguf_eligibility
+ decision_gguf.export_decision_gguf = export_decision_gguf
+ models_pkg = types.ModuleType("unsloth.models")
+ models_pkg.__path__ = []
+ models_pkg.decision_gguf = decision_gguf
+ monkeypatch.setitem(sys.modules, "unsloth.models", models_pkg)
+ monkeypatch.setitem(sys.modules, "unsloth.models.decision_gguf", decision_gguf)
+
+ class _DecisionModel:
+ def save_pretrained_gguf(
+ self,
+ save_directory,
+ tokenizer,
+ quantization_method,
+ source_folder = None,
+ print_output = False,
+ token = None,
+ ):
+ lib.tokens.append(token)
+ lib.calls.append(
+ (
+ "save_pretrained_gguf",
+ save_directory,
+ tokenizer,
+ list(quantization_method),
+ source_folder,
+ )
+ )
+ return {"quantizations": [q.upper() for q in quantization_method]}
+
+ class FastDecisionModel:
+ @staticmethod
+ def from_pretrained(model_name, **kwargs):
+ lib.calls.append(("FastDecisionModel", model_name, kwargs))
+ return _DecisionModel(), "processor"
+
+ sys.modules["unsloth"].FastDecisionModel = FastDecisionModel
+
+ mod = _load_module("test_core_export_backend_decision", "core/export/export.py", monkeypatch)
+ _ForbiddenLoader.calls = []
+ monkeypatch.setattr(mod, "FastLanguageModel", _ForbiddenLoader)
+ monkeypatch.setattr(mod, "FastVisionModel", _ForbiddenLoader)
+ probes = []
+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: probes.append("audio"))
+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: probes.append("vision"))
+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)
+ monkeypatch.setattr(mod.ExportBackend, "cleanup_memory", lambda self: True)
+ monkeypatch.setattr(mod.ExportBackend, "__init__", _bare_init)
+ lib.probes = probes
+ return mod, lib
+
+
+def _bare_init(self):
+ self.current_checkpoint = None
+ self.current_model = None
+ self.current_tokenizer = None
+ self.is_vision = False
+ self.is_peft = False
+ self._audio_type = None
+ self.decision = None
+
+
+def _exports(lib):
+ return [c for c in lib.calls if c[0] in ("export", "save_pretrained_gguf", "FastDecisionModel")]
+
+
+def test_merged_clef_skips_chat_and_vision_loaders_and_exports_in_run_folder(env, tmp_path):
+ mod, lib = env
+ folder = _clef_merged(tmp_path)
+ backend = mod.ExportBackend()
+
+ ok, message = backend.load_checkpoint(str(folder))
+ assert ok, message
+ assert _ForbiddenLoader.calls == [] and lib.probes == []
+ assert backend.decision == {"layout": "clef", "adapter_only": False}
+ assert backend.is_peft is False and backend.is_vision is False
+
+ ok, message, output = backend.export_gguf("ignored_dir", ["Q8_0", "q4_k_m", "q8_0"])
+ assert ok, message
+ assert _exports(lib) == [("export", str(folder), ["q8_0", "q4_k_m"], None, str(folder))]
+ assert output == str(folder.resolve() / "gguf")
+ assert "Q8_0, Q4_K_M" in message
+ assert not (Path.cwd() / "ignored_dir").exists()
+
+
[email protected]("token", ["hf_caller", False])
+def test_adapter_only_clef_loads_and_merges_its_base_with_the_load_credential(env, tmp_path, token):
+ mod, lib = env
+ folder = _clef_adapter(tmp_path)
+ backend = mod.ExportBackend()
+ assert backend.load_checkpoint(str(folder), hf_token = token)[0]
+ assert backend.export_gguf("x", "q8_0")[0]
+ assert _exports(lib)[0][2]["token"] == token
+ assert lib.tokens == [token]
+
+
+def test_adapter_only_clef_merges_through_fast_decision_model(env, tmp_path):
+ mod, lib = env
+ folder = _clef_adapter(tmp_path)
+ backend = mod.ExportBackend()
+
+ ok, message = backend.load_checkpoint(str(folder))
+ assert ok, message
+ assert backend.decision == {"layout": "clef", "adapter_only": True}
+ assert backend.is_peft is True
+
+ ok, message, output = backend.export_gguf("x", "f16")
+ assert ok, message
+ calls = _exports(lib)
+ assert calls[0][0] == "FastDecisionModel" and calls[0][1] == str(folder)
+ assert calls[0][2]["load_in_4bit"] is False
+ assert calls[1] == ("save_pretrained_gguf", str(folder), "processor", ["f16"], str(folder))
+ assert not any(c[0] == "export" for c in calls)
+ assert _ForbiddenLoader.calls == []
+ assert output == str(folder.resolve() / "gguf")
+
+
+def test_laya_exports_through_the_library(env, tmp_path):
+ mod, lib = env
+ folder = _laya(tmp_path)
+ backend = mod.ExportBackend()
+
+ assert backend.load_checkpoint(str(folder))[0]
+ assert backend.decision == {"layout": "laya", "adapter_only": False}
+ ok, _, _ = backend.export_gguf("x", ["bf16"])
+ assert ok
+ assert _exports(lib) == [("export", str(folder), ["bf16"], None, str(folder))]
+ assert _ForbiddenLoader.calls == [] and lib.probes == []
+
+
+def test_a_home_relative_checkpoint_path_is_expanded(env, tmp_path, monkeypatch):
+ mod, lib = env
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ folder = _laya(tmp_path)
+ backend = mod.ExportBackend()
+
+ assert backend.load_checkpoint("~/laya_run")[0]
+ assert backend.export_gguf("x", "q8_0")[0]
+ assert ("eligibility", "~/laya_run") not in lib.calls
+ assert [c for c in lib.calls if c[0] == "eligibility"] == [("eligibility", str(folder))] * 2
+ assert _exports(lib) == [("export", str(folder), ["q8_0"], None, str(folder))]
+
+
+def test_ineligible_clef_fails_the_load_with_the_reason(env, tmp_path):
+ mod, lib = env
+ folder = _clef_merged(tmp_path, config = {"architectures": ["LlamaForCausalLM"]})
+ reason = "llama.cpp's decision graph is built for Qwen3.5 backbones only"
+ lib.eligibility = {"eligible": False, "layout": "clef", "reason": reason}
+ backend = mod.ExportBackend()
+
+ ok, message = backend.load_checkpoint(str(folder))
+ assert ok is False
+ assert message == reason
+ assert backend.decision is None
+ assert _exports(lib) == [] and _ForbiddenLoader.calls == []
+
+
+def test_ineligible_at_export_time_is_an_error_not_a_crash(env, tmp_path):
+ mod, lib = env
+ folder = _clef_merged(tmp_path)
+ backend = mod.ExportBackend()
+ assert backend.load_checkpoint(str(folder))[0]
+ lib.eligibility = {"eligible": False, "layout": "clef", "reason": "not Qwen3.5"}
+
+ assert backend.export_gguf("x", "q8_0") == (False, "not Qwen3.5", None)
+
+
+def test_unknown_quant_is_refused_before_the_library(env, tmp_path):
+ mod, lib = env
+ folder = _clef_merged(tmp_path)
+ backend = mod.ExportBackend()
+ assert backend.load_checkpoint(str(folder))[0]
+
+ ok, message, output = backend.export_gguf("x", ["q2_k_l"])
+ assert ok is False and output is None
+ assert "Q2_K_L" in message
+ assert _exports(lib) == []
+
+
+ "kwargs",
+ [{"push_to_hub": True, "repo_id": "u/r"}, {"imatrix_file": True}, {"npu_q4nx": True}],
+ ids = ["hub", "imatrix", "q4nx"],
+)
+def test_unsupported_gguf_options_are_refused(env, tmp_path, kwargs):
+ mod, lib = env
+ backend = mod.ExportBackend()
+ assert backend.load_checkpoint(str(_clef_merged(tmp_path)))[0]
+
+ ok, _, _ = backend.export_gguf("x", "q8_0", **kwargs)
+ assert ok is False
+ assert _exports(lib) == []
+
+
+def test_other_export_methods_are_gguf_only_for_decision_models(env, tmp_path):
+ mod, _ = env
+ backend = mod.ExportBackend()
+ assert backend.load_checkpoint(str(_clef_adapter(tmp_path)))[0]
+
+ expected = (False, "Decision models export to GGUF only.", None)
+ assert backend.export_merged_model("x") == expected
+ assert backend.export_base_model("x") == expected
+ assert backend.export_lora_adapter("x") == expected
+
+
+def test_non_decision_checkpoint_still_uses_the_text_loader(env, tmp_path, monkeypatch):
+ mod, lib = env
+ folder = _write(tmp_path / "llama_run", {"config.json": {"model_type": "llama"}})
+ loaded = []
+
+ class _TextLoader:
+ @staticmethod
+ def from_pretrained(**kwargs):
+ loaded.append(kwargs["model_name"])
+ return object(), object()
+
+ monkeypatch.setattr(mod, "FastLanguageModel", _TextLoader)
+ monkeypatch.setattr(mod, "_multi_gpu_device_map_kwargs", lambda: {})
+ monkeypatch.setattr(mod, "restore_hf_cache_repo_identity", lambda *a, **k: None)
+ backend = mod.ExportBackend()
+
+ ok, message = backend.load_checkpoint(str(folder))
+ assert ok, message
+ assert loaded == [str(folder)]
+ assert backend.decision is None
+ assert lib.probes == ["audio", "vision"]
+ assert not any(c[0] == "eligibility" for c in lib.calls)
+
+
+def test_studio_quant_list_matches_the_library():
+ from core.export.decision import DECISION_GGUF_QUANTIZATIONS
+
+ source = _BACKEND_DIR.parent.parent / "unsloth" / "models" / "decision_gguf.py"
+ if not source.is_file():
+ pytest.skip("unsloth/models/decision_gguf.py is not in this checkout")
+ tree = ast.parse(source.read_text(encoding = "utf-8"))
+ values = [
+ ast.literal_eval(node.value)
+ for node in tree.body
+ if isinstance(node, ast.Assign)
+ and any(getattr(t, "id", None) == "DECISION_GGUF_QUANTIZATIONS" for t in node.targets)
+ ]
+ assert values == [DECISION_GGUF_QUANTIZATIONS]
+
+
+def test_orchestrator_keeps_the_decision_block_from_the_worker(monkeypatch, tmp_path):
+ from core.export.orchestrator import ExportOrchestrator
+
+ backend = ExportOrchestrator()
+ monkeypatch.setattr(backend, "_ensure_subprocess_alive", lambda: False)
+ monkeypatch.setattr(backend, "_spawn_subprocess", lambda config: None)
+ decision = {"layout": "clef", "adapter_only": False}
+ monkeypatch.setattr(
+ backend,
+ "_wait_response",
+ lambda *a, **k: {
+ "success": True,
+ "message": "ok",
+ "checkpoint": str(tmp_path),
+ "decision": decision,
+ },
+ )
+ assert backend.load_checkpoint(str(tmp_path), load_in_4bit = False)[0]
+ assert backend.decision == decision
+
+ monkeypatch.setattr(
+ backend, "_wait_response", lambda *a, **k: {"success": False, "message": "no"}
+ )
+ assert backend.load_checkpoint(str(tmp_path), load_in_4bit = False) == (False, "no")
+ assert backend.decision is None
+
+
+def test_a_decision_adapter_loads_only_the_authorized_base(env, tmp_path):
+ mod, lib = env
+ folder = _clef_adapter(tmp_path)
+ backend = mod.ExportBackend()
+ ok, message = backend.load_checkpoint(str(folder), base_model = "owner/private-model")
+ assert not ok and "authorized base model owner/private-model" in message
+ (folder / "unsloth_decision_config.json").write_text(
+ json.dumps({"base_model": "owner/private-model"}), encoding = "utf-8"
+ )
+ ok, message = backend.load_checkpoint(str(folder), base_model = "unsloth/Qwen3.5-0.8B")
+ assert not ok and "two different base models" in message
+ assert _exports(lib) == []
diff --git a/studio/backend/tests/test_export_decision_routes.py b/studio/backend/tests/test_export_decision_routes.py
new file mode 100644
index 00000000000..9f5e6e92b0f
--- /dev/null
+++ b/studio/backend/tests/test_export_decision_routes.py
@@ -0,0 +1,216 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Export routes for decision models: /api/export/decision-info and the GGUF result details."""
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import allow_ambient_hf_token, get_current_subject
+from core.systemone.gguf_export_contract import fingerprint
+from routes import export as export_routes
+
+_QWEN35 = {"architectures": ["Qwen3_5ForConditionalGeneration"]}
+
+
+def _write(
+ folder: Path,
+ files: dict,
+ dirs = (),
+) -> Path:
+ folder.mkdir(parents = True, exist_ok = True)
+ for name, content in files.items():
+ (folder / name).write_text(json.dumps(content), encoding = "utf-8")
+ for name in dirs:
+ (folder / name).mkdir(parents = True, exist_ok = True)
+ return folder
+
+
+def _clef(folder: Path, config = _QWEN35) -> Path:
+ return _write(
+ folder,
+ {"config.json": config, "joint_head.safetensors": {}, "joint_head_config.json": {}},
+ )
+
+
+def _client(monkeypatch, backend = None) -> TestClient:
+ async def _supported():
+ pass
+
+ monkeypatch.setattr(export_routes, "_ensure_export_supported", _supported)
+ if backend is not None:
+ monkeypatch.setattr(export_routes, "get_export_backend", lambda: backend)
+ app = FastAPI()
+ app.include_router(export_routes.router, prefix = "/api/export")
+ app.dependency_overrides[get_current_subject] = lambda: "alice"
+ app.dependency_overrides[allow_ambient_hf_token] = lambda: True
+ return TestClient(app)
+
+
+def _info(client, path):
+ response = client.get("/api/export/decision-info", params = {"checkpoint_path": str(path)})
+ assert response.status_code == 200, response.text
+ return response.json()["decision"]
+
+
+def test_decision_info_for_an_eligible_merged_clef(monkeypatch, tmp_path):
+ folder = _clef(tmp_path / "run")
+ info = _info(_client(monkeypatch), folder)
+ assert info["layout"] == "clef" and info["adapter_only"] is False
+ assert info["eligible"] is True and info["reason"] is None
+ assert info["quantizations"][0] == info["default_quantization"] == "q8_0"
+ assert info["output_dir"] == str(folder / "gguf")
+ assert info["existing_export"] is None
+
+
+def test_decision_info_names_why_a_non_qwen35_clef_is_ineligible(monkeypatch, tmp_path):
+ info = _info(
+ _client(monkeypatch), _clef(tmp_path / "run", {"architectures": ["LlamaForCausalLM"]})
+ )
+ assert info["eligible"] is False
+ assert "Qwen3.5" in info["reason"] and "LlamaForCausalLM" in info["reason"]
+
+
+def test_decision_info_for_adapter_only_clef_reads_a_local_base(monkeypatch, tmp_path):
+ base = _write(tmp_path / "base", {"config.json": _QWEN35})
+ folder = _write(
+ tmp_path / "run",
+ {
+ "adapter_config.json": {"base_model_name_or_path": str(base)},
+ "joint_head.safetensors": {},
+ "joint_head_config.json": {},
+ },
+ )
+ info = _info(_client(monkeypatch), folder)
+ assert info["adapter_only"] is True and info["eligible"] is True
+
+
+def test_decision_info_for_laya(monkeypatch, tmp_path):
+ folder = _write(
+ tmp_path / "run",
+ {"rl_agent_config.json": {}, "model.safetensors": {}},
+ dirs = ("encoder", "tokenizer"),
+ )
+ _write(folder / "encoder", {"config.json": {"model_type": "modernbert"}})
+ info = _info(_client(monkeypatch), folder)
+ assert info["layout"] == "laya" and info["eligible"] is True
+
+
+def _export(folder: Path, quants, fingerprint: str) -> dict:
+ export = {
+ "format": "unsloth-decision-gguf",
+ "version": 1,
+ "layout": "clef",
+ "quantizations": list(quants),
+ "files": {q: {"model": f"model-{q}.gguf", "mmproj": f"mmproj-{q}.gguf"} for q in quants},
+ "source_fingerprint": fingerprint,
+ }
+ _write(folder / "gguf", {"export.json": export})
+ return export
+
+
+def test_decision_info_reports_a_current_export_with_only_the_files_on_disk(monkeypatch, tmp_path):
+ folder = _clef(tmp_path / "run")
+ export = _export(folder, ["Q8_0", "Q4_K_M"], fingerprint(folder, "clef"))
+ for name in ("model-Q8_0.gguf", "mmproj-Q8_0.gguf", "model-Q4_K_M.gguf"):
+ (folder / "gguf" / name).write_bytes(b"gguf")
+ client = _client(monkeypatch)
+ assert _info(client, folder)["existing_export"] == {
+ **export,
+ "quantizations": ["Q8_0"],
+ "files": {"Q8_0": export["files"]["Q8_0"]},
+ }
+ (folder / "gguf" / "model-Q8_0.gguf").unlink()
+ assert _info(client, folder)["existing_export"] is None
+
+
+def test_decision_info_ignores_a_stale_export(monkeypatch, tmp_path):
+ folder = _clef(tmp_path / "run")
+ _export(folder, ["Q8_0"], fingerprint(folder, "clef"))
+ for name in ("model-Q8_0.gguf", "mmproj-Q8_0.gguf"):
+ (folder / "gguf" / name).write_bytes(b"gguf")
+ client = _client(monkeypatch)
+ assert _info(client, folder)["existing_export"]["quantizations"] == ["Q8_0"]
+ # Retrained since the export.
+ (folder / "joint_head.safetensors").write_bytes(b"retrained")
+ assert _info(client, folder)["existing_export"] is None
+ _export(folder, ["Q8_0"], "abc")
+ assert _info(client, folder)["existing_export"] is None
+
+
+def test_decision_info_is_null_for_other_models(monkeypatch, tmp_path):
+ client = _client(monkeypatch)
+ assert (
+ _info(client, _write(tmp_path / "llama", {"config.json": {"model_type": "llama"}})) is None
+ )
+ assert _info(client, "unsloth/Llama-3.2-1B") is None
+
+
+def test_ineligible_load_is_a_400_with_the_reason(monkeypatch, tmp_path):
+ backend = MagicMock()
+ backend.load_checkpoint.return_value = (False, "only Qwen3.5 backbones")
+ response = _client(monkeypatch, backend).post(
+ "/api/export/load-checkpoint", json = {"checkpoint_path": str(tmp_path)}
+ )
+ assert response.status_code == 400
+ assert response.json()["detail"] == "only Qwen3.5 backbones"
+
+
+def test_decision_gguf_details_point_at_the_run_folder_without_registering_it(
+ monkeypatch, tmp_path
+):
+ folder = _clef(tmp_path / "run")
+ export = {
+ "format": "unsloth-decision-gguf",
+ "version": 1,
+ "layout": "clef",
+ "quantizations": ["Q8_0", "Q4_K_M"],
+ "files": {
+ "Q8_0": {"model": "model-Q8_0.gguf", "mmproj": None},
+ "Q4_K_M": {"model": "model-Q4_K_M.gguf", "mmproj": None},
+ },
+ "source_fingerprint": "abc",
+ }
+ _write(folder / "gguf", {"export.json": export})
+ backend = MagicMock()
+ backend.decision = {"layout": "clef", "adapter_only": False}
+ backend.export_gguf.return_value = (True, "done", str(folder / "gguf"))
+ registered = []
+ monkeypatch.setattr(
+ export_routes, "_try_register_external_export", lambda *a, **k: registered.append(a)
+ )
+
+ response = _client(monkeypatch, backend).post(
+ "/api/export/export/gguf",
+ json = {"save_directory": "ignored", "quantization_method": ["q8_0", "q4_k_m"]},
+ )
+ assert response.status_code == 200, response.text
+ details = response.json()["details"]
+ assert details["output_path"] == str(folder / "gguf")
+ assert details["quantizations"] == ["Q8_0", "Q4_K_M"]
+ assert details["decision_export"] == export
+ assert registered == []
+ assert backend.export_gguf.call_args.kwargs["quantization_method"] == ["q8_0", "q4_k_m"]
+
+
+def test_non_decision_gguf_details_unchanged(monkeypatch, tmp_path):
+ backend = MagicMock()
+ backend.decision = None
+ backend.export_gguf.return_value = (True, "done", str(tmp_path / "out"))
+ seen = []
+ monkeypatch.setattr(
+ export_routes,
+ "_export_details",
+ lambda path, refresh_index = False: seen.append((path, refresh_index))
+ or {"output_path": "out"},
+ )
+ response = _client(monkeypatch, backend).post(
+ "/api/export/export/gguf", json = {"save_directory": "out", "quantization_method": "Q4_K_M"}
+ )
+ assert response.status_code == 200
+ assert seen == [(str(tmp_path / "out"), True)]
+ assert response.json()["details"] == {"output_path": "out"}
diff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.py
index 56a273a3a34..b36bb021ef0 100644
--- a/studio/backend/tests/test_systemone.py
+++ b/studio/backend/tests/test_systemone.py
@@ -228,7 +228,15 @@ def test_named_checkpoint_swaps_the_resident_model(client, runtime):
422,
"invalid_request_error",
),
- ({"images": ["data:image/png;base64,AAAA"]}, 400, "api_usage_error"),
+ (
+ {
+ "images": [
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+ ]
+ },
+ 400,
+ "api_usage_error",
+ ),
(
{"questions": {f"q{i}": {"type": "noul"} for i in range(65)}},
422,
diff --git a/studio/backend/utils/models/checkpoints.py b/studio/backend/utils/models/checkpoints.py
index 2294c2e2174..2b64be9d8b0 100644
--- a/studio/backend/utils/models/checkpoints.py
+++ b/studio/backend/utils/models/checkpoints.py
@@ -211,7 +211,21 @@ def _has_own_model(path: Path) -> bool:
return False
-def _checkpoint_dirs(run_dir: Path) -> List[Path]:
+# unsloth.models.decision.is_decision_checkpoint's Laya rule; Clef folders carry config.json or adapter_config.json.
+_LAYA_FILES = ("rl_agent_config.json", "model.safetensors")
+_LAYA_DIRS = ("encoder", "tokenizer")
+
+
+def _is_own_laya_run(path: Path) -> bool:
+ try:
+ return all(
+ own_entry(path / name) and (path / name).is_file() for name in _LAYA_FILES
+ ) and all((path / name).is_dir() for name in _LAYA_DIRS)
+ except OSError:
+ return False
+
+
+def _checkpoint_dirs(run_dir: Path, include_decision: bool = False) -> List[Path]:
try:
return sorted(
(
@@ -220,7 +234,7 @@ def _checkpoint_dirs(run_dir: Path) -> List[Path]:
if sub.is_dir()
and sub.name.startswith("checkpoint-")
and within_account(sub)
- and _has_own_model(sub)
+ and (_has_own_model(sub) or (include_decision and _is_own_laya_run(sub)))
),
key = _checkpoint_sort_key,
)
@@ -229,10 +243,12 @@ def _checkpoint_dirs(run_dir: Path) -> List[Path]:
def scan_checkpoints(
- outputs_dir: str | None = None,
+ outputs_dir: str | None = None, include_decision: bool = False
) -> List[Tuple[str, List[Tuple[str, str, Optional[float]]], dict]]:
"""Scan outputs folder for training runs and their checkpoints.
+ ``include_decision`` also lists Laya decision runs (GGUF export only; chat cannot load them).
+
Returns:
[(model_name, [(display_name, checkpoint_path, loss), ...], metadata), ...]
metadata keys (optional): base_model, peft_type, lora_rank.
@@ -257,8 +273,8 @@ def scan_checkpoints(
if not within_account(item):
continue
- has_root_model = _has_own_model(item)
- valid_checkpoints = _checkpoint_dirs(item)
+ has_root_model = _has_own_model(item) or (include_decision and _is_own_laya_run(item))
+ valid_checkpoints = _checkpoint_dirs(item, include_decision)
# A cancelled or crashed run has no final save but can still have checkpoints.
if not has_root_model and not valid_checkpoints:
continue
@@ -266,6 +282,7 @@ def scan_checkpoints(
meta_dir = item if has_root_model else valid_checkpoints[0]
config_file = meta_dir / "config.json"
adapter_config = meta_dir / "adapter_config.json"
+ laya_config = meta_dir / "rl_agent_config.json"
# Training metadata from adapter_config.json / config.json
metadata: dict = {}
@@ -281,6 +298,12 @@ def scan_checkpoints(
elif own_entry(config_file):
cfg = json.loads(config_file.read_text(encoding = "utf-8-sig"))
metadata["base_model"] = cfg.get("_name_or_path")
+ elif include_decision and own_entry(laya_config):
+ laya = json.loads(laya_config.read_text(encoding = "utf-8-sig"))
+ training = (
+ laya.get("training") if isinstance(laya.get("training"), dict) else {}
+ )
+ metadata["base_model"] = training.get("base") or laya.get("encoder")
# Detect BNB quantization from config.json
if own_entry(config_file):
diff --git a/studio/backend/utils/systemone_settings.py b/studio/backend/utils/systemone_settings.py
index 8748c2b73f2..78a59cf6cf3 100644
--- a/studio/backend/utils/systemone_settings.py
+++ b/studio/backend/utils/systemone_settings.py
@@ -12,8 +12,14 @@ from typing import Any
ENABLED_KEY = "systemone_enabled"
MODEL_KEY = "systemone_model"
DEVICE_KEY = "systemone_device"
+BACKEND_KEY = "systemone_backend"
+NATIVE_CTX_KEY = "systemone_native_ctx"
DEFAULT_MODEL = "laya-multilingual"
DEVICES = ("cpu", "gpu")
+BACKENDS = ("auto", "llama.cpp", "pytorch")
+DEFAULT_NATIVE_CTX = 16384
+# -c / -b / -ub of the llama.cpp decision server; compute memory grows with it (~0.24 MiB GPU per token).
+NATIVE_CTX_RANGE = (512, 65536)
ENV_DISABLE = "UNSLOTH_SYSTEMONE_DISABLE"
ENV_MODEL = "UNSLOTH_SYSTEMONE_MODEL"
@@ -89,11 +95,35 @@ def get_device() -> str:
return stored if stored in DEVICES else "cpu"
+def clef_device() -> str:
+ """Where a llama.cpp Clef runs: the chosen device, else the GPU when there is one (CPU needs ~22 GB RAM)."""
+ if device_locked() or _owner_setting(DEVICE_KEY) in DEVICES:
+ return get_device()
+ return "gpu" if gpu_available() else "cpu"
+
+
+def get_backend() -> str:
+ stored = _owner_setting(BACKEND_KEY)
+ return stored if stored in BACKENDS else "auto"
+
+
+def _valid_ctx(value: Any) -> bool:
+ low, high = NATIVE_CTX_RANGE
+ return isinstance(value, int) and not isinstance(value, bool) and low <= value <= high
+
+
+def get_native_ctx() -> int:
+ stored = _owner_setting(NATIVE_CTX_KEY)
+ return stored if _valid_ctx(stored) else DEFAULT_NATIVE_CTX
+
+
def validate(
*,
enabled: bool | None = None,
model: str | None = None,
device: str | None = None,
+ backend: str | None = None,
+ native_ctx: int | None = None,
) -> dict[str, Any]:
from core.systemone.catalog import (
CHECKPOINTS,
@@ -134,6 +164,15 @@ def validate(
if device not in DEVICES:
raise ValueError("Device must be cpu or gpu.")
values[DEVICE_KEY] = device
+ if backend is not None:
+ if backend not in BACKENDS:
+ raise ValueError("Runtime must be auto, llama.cpp or pytorch.")
+ values[BACKEND_KEY] = backend
+ if native_ctx is not None:
+ if not _valid_ctx(native_ctx):
+ low, high = NATIVE_CTX_RANGE
+ raise ValueError(f"The llama.cpp context must be {low} to {high} tokens.")
+ values[NATIVE_CTX_KEY] = native_ctx
serving = enabled if enabled is not None else model is not None and get_enabled()
local = parse_connection(get_model() if model is None else model) is None
if serving and local and (reason := runtime_unavailable_reason()):
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index 8d2a5cd168b..d7af9ac7d9e 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -89,6 +89,38 @@ export interface ExportOperationResponse {
details?: { output_path?: string | null } & Record<string, unknown>;
}
+/** GGUF export options for a decision model (Clef / Laya) checkpoint folder. */
+export interface DecisionExportInfo {
+ is_decision: boolean;
+ layout: "clef" | "laya";
+ /** Clef folder with LoRA adapters only; merged at export time. */
+ adapter_only: boolean;
+ /** false: llama.cpp cannot serve it (see reason); null: only the export can tell. */
+ eligible: boolean | null;
+ reason: string | null;
+ /** Allowed lowercase quantizations, default first. */
+ quantizations: string[];
+ default_quantization: string;
+ /** Where the GGUF files land: <run folder>/gguf. */
+ output_dir: string;
+ existing_export: ({ quantizations?: string[] } & Record<string, unknown>) | null;
+}
+
+/** Decision export info for a local checkpoint folder; null for any other model. */
+export async function fetchDecisionExportInfo(
+ checkpointPath: string,
+ signal?: AbortSignal,
+): Promise<DecisionExportInfo | null> {
+ const response = await authFetch(
+ `/api/export/decision-info?checkpoint_path=${encodeURIComponent(checkpointPath)}`,
+ { signal },
+ );
+ const body = await parseJson<{ decision: DecisionExportInfo | null }>(
+ response,
+ );
+ return body.decision ?? null;
+}
+
export async function fetchCheckpoints(): Promise<CheckpointListResponse> {
const response = await authFetch("/api/models/checkpoints");
return parseJson<CheckpointListResponse>(response);
@@ -256,6 +288,8 @@ export interface ExportStatus {
last_op_status?: "success" | "error" | "cancelled" | null;
last_op_output_path?: string | null;
last_op_error?: string | null;
+ /** {layout, adapter_only} when the loaded checkpoint is a decision model. */
+ decision?: { layout: "clef" | "laya"; adapter_only: boolean } | null;
}
/**
diff --git a/studio/frontend/src/features/export/components/export-run-panel.tsx b/studio/frontend/src/features/export/components/export-run-panel.tsx
index 6c9086dd971..260dfe21552 100644
--- a/studio/frontend/src/features/export/components/export-run-panel.tsx
+++ b/studio/frontend/src/features/export/components/export-run-panel.tsx
@@ -119,6 +119,8 @@ export interface ExportRunPanelProps {
onStart: () => void;
/** Collapse the panel; only offered before a run or after a terminal one. */
onClose: () => void;
+ /** Decision model: output goes to the run folder's gguf/ only; this note replaces the destination picker. */
+ decisionNote?: string;
}
export function ExportRunPanel(props: ExportRunPanelProps) {
@@ -134,6 +136,7 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
defaultSaveDirectory,
saveDirectoryOverridden,
onSaveDirectoryChange,
+ decisionNote,
hfUsername,
onHfUsernameChange,
modelName,
@@ -242,7 +245,12 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
</div>
{/* Destination configuration (only before a run starts) */}
- {showConfig && (
+ {showConfig && decisionNote && (
+ <p className="break-all rounded-lg border p-3 text-xs text-muted-foreground">
+ {decisionNote}
+ </p>
+ )}
+ {showConfig && !decisionNote && (
<>
<div className="flex gap-2">
<Button
@@ -417,7 +425,7 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
: run.result?.outputPath
? [{ label: "", path: run.result.outputPath }]
: [];
- const showLabels = items.length > 1;
+ const showLabels = items.length > 1 || !!decisionNote;
return items.map((o, i) => (
<div
key={`${o.path}-${i}`}
diff --git a/studio/frontend/src/features/export/components/quant-picker.tsx b/studio/frontend/src/features/export/components/quant-picker.tsx
index 3342166075f..9baac419c8d 100644
--- a/studio/frontend/src/features/export/components/quant-picker.tsx
+++ b/studio/frontend/src/features/export/components/quant-picker.tsx
@@ -20,9 +20,16 @@ interface QuantPickerProps {
onChange: (v: string[]) => void;
/** quant value -> "~X GB"; blank/missing when the model size is unknown. */
sizes?: Record<string, string>;
+ /** Choices to offer; defaults to every GGUF quant. */
+ options?: { value: string; label: string; recommended?: boolean }[];
}
-export function QuantPicker({ value, onChange, sizes }: QuantPickerProps) {
+export function QuantPicker({
+ value,
+ onChange,
+ sizes,
+ options = QUANT_OPTIONS,
+}: QuantPickerProps) {
const toggle = (qv: string) => {
onChange(
value.includes(qv) ? value.filter((q) => q !== qv) : [...value, qv],
@@ -66,7 +73,7 @@ export function QuantPicker({ value, onChange, sizes }: QuantPickerProps) {
</span>
</div>
<div className="flex flex-wrap gap-2 py-1 pl-1">
- {QUANT_OPTIONS.map((q) => {
+ {options.map((q) => {
const active = value.includes(q.value);
const sizeLabel = sizes?.[q.value] ?? "";
return (
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index 96e7a0298cf..f43d23051a1 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -50,6 +50,7 @@ import { GuidedTour, useGuidedTourController } from "@/features/tour";
import type { LocalModelInfo } from "@/features/training";
import { useDebouncedValue, useHfTokenValidation } from "@/hooks";
import { useHardwareInfo } from "@/hooks/use-hardware-info";
+import { useT } from "@/i18n";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import {
AlertCircleIcon,
@@ -63,7 +64,11 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { useSearch } from "@tanstack/react-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
-import type { ModelCheckpoints } from "./api/export-api";
+import {
+ type DecisionExportInfo,
+ type ModelCheckpoints,
+ fetchDecisionExportInfo,
+} from "./api/export-api";
import { adapterCompatibilityTip, type AdapterFormat } from "./constants";
import { ExportRunPanel } from "./components/export-run-panel";
import { MethodPicker } from "./components/method-picker";
@@ -168,6 +173,7 @@ function siblingGgufDirectory(sourcePath: string): string | null {
}
export function ExportPage() {
+ const t = useT();
const signalReady = useAppShellReadySignal();
const { hfToken, setHfToken } = useHfTokenStore(
useShallow((s) => ({
@@ -493,6 +499,79 @@ export function ExportPage() {
return map;
}, [exportableLocalModels]);
+ // Decision models (Clef / Laya) are local run folders; the backend says which and what they allow.
+ const decisionProbePath = useMemo(() => {
+ if (sourceMode === "checkpoint") {
+ return (
+ checkpointsForModel.find((c) => c.display_name === checkpoint)?.path ??
+ null
+ );
+ }
+ if (modelSource !== "local" || !selectedSourceModel) {
+ return null;
+ }
+ return localMetaById.get(selectedSourceModel)?.path ?? selectedSourceModel;
+ }, [
+ sourceMode,
+ checkpointsForModel,
+ checkpoint,
+ modelSource,
+ selectedSourceModel,
+ localMetaById,
+ ]);
+ const [decisionState, setDecisionState] = useState<{
+ path: string;
+ info: DecisionExportInfo | null;
+ } | null>(null);
+ useEffect(() => {
+ if (!decisionProbePath) {
+ return;
+ }
+ const controller = new AbortController();
+ fetchDecisionExportInfo(decisionProbePath, controller.signal)
+ .then((info) => {
+ setDecisionState({ path: decisionProbePath, info });
+ if (!info) {
+ return;
+ }
+ // A decision model exports to GGUF only, saved locally in its run folder.
+ const allowed = new Set(info.quantizations);
+ setExportMethod("gguf");
+ setGgufTarget("model");
+ setDestination("local");
+ setQuantLevels((prev) => {
+ const kept = prev.filter((q) => allowed.has(q));
+ if (kept.length === prev.length && kept.length > 0) {
+ return prev;
+ }
+ return kept.length > 0 ? kept : [info.default_quantization];
+ });
+ })
+ .catch(() => {
+ if (!controller.signal.aborted) {
+ setDecisionState({ path: decisionProbePath, info: null });
+ }
+ });
+ return () => controller.abort();
+ }, [decisionProbePath]);
+ const decisionInfo =
+ decisionProbePath && decisionState?.path === decisionProbePath
+ ? decisionState.info
+ : null;
+ const isDecision = decisionInfo != null;
+ const decisionIneligible = decisionInfo?.eligible === false;
+ const decisionQuantOptions = useMemo(
+ () =>
+ (decisionInfo?.quantizations ?? []).map((q) => ({
+ value: q,
+ label: q.toUpperCase(),
+ recommended: q === decisionInfo?.default_quantization,
+ })),
+ [decisionInfo],
+ );
+ const decisionExistingQuants =
+ decisionInfo?.existing_export?.quantizations ?? [];
+
const localResultIds = useMemo(() => {
const ids = exportableLocalModels.map((model) => model.id);
const manual = localModelInput.trim();
@@ -678,7 +757,8 @@ export function ExportPage() {
!exportUnsupported &&
!hubMultiFormat &&
(exportMethod !== "gguf" || ggufAsLora || quantLevels.length > 0) &&
- (exportMethod !== "merged" || selectedFormats.length > 0)
+ (exportMethod !== "merged" || selectedFormats.length > 0) &&
+ (!isDecision || (exportMethod === "gguf" && !decisionIneligible))
);
const applyHfSourceModel = useCallback((value: string) => {
@@ -758,6 +838,9 @@ export function ExportPage() {
if (exportMethod === "merged" && selectedFormats.length === 0) return;
// A Hub merged push writes each format to the repo root; several would collide (mirrors canExport).
if (hubMultiFormat) return;
+ if (isDecision && (exportMethod !== "gguf" || decisionIneligible)) {
+ return;
+ }
const selectedCp =
sourceMode === "checkpoint"
@@ -781,10 +864,12 @@ export function ExportPage() {
// The GGUF method with the LoRA target reuses the LoRA-adapter export path.
const effectiveMethod: ExportMethod = ggufAsLora ? "lora" : exportMethod;
const emitLoraGguf = ggufAsLora || (effectiveMethod === "lora" && loraAsGguf);
- const methodLabel = ggufAsLora
- ? "GGUF LoRA adapter"
- : (EXPORT_METHODS.find((m) => m.value === exportMethod)?.title ??
- exportMethod);
+ const methodLabel = isDecision
+ ? t("exportDecision.methodLabel")
+ : ggufAsLora
+ ? "GGUF LoRA adapter"
+ : (EXPORT_METHODS.find((m) => m.value === exportMethod)?.title ??
+ exportMethod);
const adapterExport = sourceMode === "checkpoint" && isAdapter;
// Consent gate for an HF source's custom (auto_map) code, before handing off to runExport.
@@ -826,9 +911,15 @@ export function ExportPage() {
exportMethod: effectiveMethod,
isAdapter: adapterExport,
quantLevels,
- useImatrix: effectiveImatrix,
- imatrixPath,
- npuQ4nx: effectiveNpuQ4nx,
+ useImatrix: isDecision ? false : effectiveImatrix,
+ imatrixPath: isDecision ? "" : imatrixPath,
+ npuQ4nx: isDecision ? false : effectiveNpuQ4nx,
+ decisionOutputLabel: isDecision
+ ? (quantizations: string[]) =>
+ t("exportDecision.outputLabel", {
+ quantizations: quantizations.join(", "),
+ })
+ : undefined,
mergedSelections: selectedFormats.map((v) => ({
...mergedFormatPayload(v),
label: MERGED_FORMATS.find((f) => f.value === v)?.label ?? v,
@@ -883,6 +974,9 @@ export function ExportPage() {
privateRepo,
modelSource,
runExport,
+ isDecision,
+ decisionIneligible,
+ t,
]);
// Open the inline panel into a fresh config state, clearing any previous terminal run.
@@ -1436,20 +1530,24 @@ export function ExportPage() {
disabledMethods={
exportUnsupported
? ["merged", "lora", "gguf"]
- : !effectiveIsAdapter && effectiveIsQuantized
- ? ["merged", "lora", "gguf"]
- : effectiveIsAdapter
- ? []
- : ["lora"]
+ : isDecision
+ ? ["merged", "lora"]
+ : !effectiveIsAdapter && effectiveIsQuantized
+ ? ["merged", "lora", "gguf"]
+ : effectiveIsAdapter
+ ? []
+ : ["lora"]
}
disabledReason={
exportUnsupported
? exportUnsupportedMessage
- : !effectiveIsAdapter && effectiveIsQuantized
- ? "Pre-quantized (BNB 4-bit) models cannot be exported without LoRA adapters"
- : effectiveIsAdapter
- ? undefined
- : "LoRA-only export needs a LoRA adapter checkpoint"
+ : isDecision
+ ? t("exportDecision.ggufOnly")
+ : !effectiveIsAdapter && effectiveIsQuantized
+ ? "Pre-quantized (BNB 4-bit) models cannot be exported without LoRA adapters"
+ : effectiveIsAdapter
+ ? undefined
+ : "LoRA-only export needs a LoRA adapter checkpoint"
}
/>
@@ -1690,7 +1788,49 @@ export function ExportPage() {
</div>
)}
- {exportMethod === "gguf" && !exportUnsupported && (
+ {exportMethod === "gguf" && !exportUnsupported && decisionInfo && (
+ <div className="space-y-3">
+ {decisionIneligible ? (
+ <Alert variant="destructive">
+ <HugeiconsIcon icon={AlertCircleIcon} className="size-4" />
+ <AlertTitle>{t("exportDecision.notEligibleTitle")}</AlertTitle>
+ <AlertDescription>{decisionInfo.reason}</AlertDescription>
+ </Alert>
+ ) : (
+ <>
+ <div className="space-y-1">
+ <div className="text-sm font-medium">
+ {t("exportDecision.title")}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {t("exportDecision.description", {
+ layout: decisionInfo.layout === "clef" ? "Clef" : "Laya",
+ })}
+ </div>
+ {decisionInfo.adapter_only && (
+ <div className="text-xs text-muted-foreground">
+ {t("exportDecision.adapterNote")}
+ </div>
+ )}
+ </div>
+ <QuantPicker
+ value={quantLevels}
+ onChange={setQuantLevels}
+ options={decisionQuantOptions}
+ />
+ {decisionExistingQuants.length > 0 && (
+ <div className="text-xs text-muted-foreground">
+ {t("exportDecision.existing", {
+ quantizations: decisionExistingQuants.join(", "),
+ })}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )}
+
+ {exportMethod === "gguf" && !exportUnsupported && !decisionInfo && (
<div className="space-y-3">
{effectiveIsAdapter && !isMacHost && (
<div className="space-y-2">
@@ -1862,6 +2002,13 @@ export function ExportPage() {
onPrivateRepoChange={setPrivateRepo}
onStart={handleStart}
onClose={handleClosePanel}
+ decisionNote={
+ decisionInfo
+ ? t("exportDecision.outputNote", {
+ path: decisionInfo.output_dir,
+ })
+ : undefined
+ }
/>
)}
{showPanel && (
diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.ts
index 5fb43052122..e93ff935774 100644
--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts
+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts
@@ -97,6 +97,17 @@ async function recoverViaStatus(
throw new Error("Timed out waiting for the export to finish.");
}
+/** Every quant in the run folder's gguf/export.json, else the ones requested. */
+export function decisionQuantizations(
+ details: ExportOperationResponse["details"] | undefined,
+ requested: string[],
+): string[] {
+ const reported = details?.quantizations;
+ return Array.isArray(reported) && reported.length > 0
+ ? reported.map(String)
+ : requested.map((q) => q.toUpperCase());
+}
+
// Keep the same scrollback depth as the backend ring buffer so the inline
// panel shows the full server-side history.
const MAX_LOG_LINES = 4000;
@@ -162,6 +173,8 @@ export interface RunExportParams {
privateRepo: boolean;
baseModelId?: string | null;
installMissingDependencies?: boolean;
+ /** Decision model (Clef / Laya): labels the run folder's gguf/ output with the quants it holds. */
+ decisionOutputLabel?: (quantizations: string[]) => string;
summary: ExportRunSummary;
}
@@ -407,7 +420,10 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
// failing. Returns the resolved output path (null for load/hub-only).
const runRecoverableOp = async (
post: () => Promise<ExportOperationResponse>,
- ): Promise<{ outputPath: string | null }> => {
+ ): Promise<{
+ outputPath: string | null;
+ details?: ExportOperationResponse["details"];
+ }> => {
let baseline: number | null = null;
try {
baseline = (await getExportStatus()).last_op_seq ?? 0;
@@ -416,7 +432,10 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
}
try {
const resp = await post();
- return { outputPath: resp.details?.output_path ?? null };
+ return {
+ outputPath: resp.details?.output_path ?? null,
+ details: resp.details,
+ };
} catch (err) {
if (!isRecoverableTransportError(err)) throw err;
set({ reconnecting: true });
@@ -492,7 +511,7 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
} else if (params.exportMethod === "gguf") {
// Send the whole quant list in ONE call: the model is merged once and every GGUF comes
// from that single merge (unsloth save_to_gguf loops internally).
- const { outputPath } = await runRecoverableOp(() =>
+ const { outputPath, details } = await runRecoverableOp(() =>
exportGGUF({
save_directory: params.saveDirectory,
quantization_method: params.quantLevels,
@@ -509,7 +528,16 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
npu_q4nx: params.npuQ4nx,
}),
);
- if (outputPath) outputs.push({ label: "GGUF", path: outputPath });
+ if (outputPath) {
+ outputs.push({
+ label: params.decisionOutputLabel
+ ? params.decisionOutputLabel(
+ decisionQuantizations(details, params.quantLevels),
+ )
+ : "GGUF",
+ path: outputPath,
+ });
+ }
if (outputPath && params.npuQ4nx) {
const sep = outputPath.includes("\\") ? "\\" : "/";
outputs.push({ label: "AMD NPU (Q4NX)", path: `${outputPath}${sep}npu-q4nx` });
diff --git a/studio/frontend/src/features/settings/api/systemone.ts b/studio/frontend/src/features/settings/api/systemone.ts
index 672f98bfef5..60a4b414848 100644
--- a/studio/frontend/src/features/settings/api/systemone.ts
+++ b/studio/frontend/src/features/settings/api/systemone.ts
@@ -9,6 +9,7 @@ import {
import type { DecisionResponse } from "../lib/decision-request";
export type SystemOneDevice = "cpu" | "gpu";
+export type SystemOneBackend = "auto" | "llama.cpp" | "pytorch";
export type SystemOneModel = {
name: string;
@@ -18,6 +19,7 @@ export type SystemOneModel = {
label: string | null;
available: boolean;
unavailableReason: string | null;
+ llamaCppOnly: boolean;
};
export type SystemOneSettings = {
@@ -35,6 +37,12 @@ export type SystemOneSettings = {
installing: boolean;
error: string | null;
mcpUrl: string;
+ backend: SystemOneBackend;
+ nativeCtx: number;
+ effectiveBackend: string | null;
+ loadedBackend: string | null;
+ fallbackReason: string | null;
+ inputModalities: string[];
};
export type SystemOneConnection = {
@@ -56,6 +64,8 @@ export type SystemOneSettingsPatch = {
enabled?: boolean;
model?: string;
device?: SystemOneDevice;
+ backend?: SystemOneBackend;
+ nativeCtx?: number;
expectedEnabled?: boolean;
expectedModel?: string;
};
@@ -90,6 +100,8 @@ type ApiSystemOneSettings = {
available?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
unavailable_reason?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ llama_cpp_only?: boolean;
}[];
// biome-ignore lint/style/useNamingConvention: API schema
loaded_model: string | null;
@@ -101,6 +113,17 @@ type ApiSystemOneSettings = {
error: string | null;
// biome-ignore lint/style/useNamingConvention: API schema
mcp_url: string;
+ backend?: SystemOneBackend;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ native_ctx?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ effective_backend?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ loaded_backend?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ fallback_reason?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ input_modalities?: string[];
};
type ApiSystemOneDownloadPlan = {
@@ -134,9 +157,10 @@ function publishSystemOneSettings(settings: SystemOneSettings) {
}
function toApiPatch(patch: SystemOneSettingsPatch) {
- const { expectedEnabled, expectedModel, ...settings } = patch;
+ const { expectedEnabled, expectedModel, nativeCtx, ...settings } = patch;
return {
...settings,
+ ...(nativeCtx !== undefined && { native_ctx: nativeCtx }),
...(expectedEnabled !== undefined && {
expected_enabled: expectedEnabled,
}),
@@ -161,6 +185,7 @@ function fromApi(settings: ApiSystemOneSettings): SystemOneSettings {
label: m.label ?? null,
available: m.available ?? true,
unavailableReason: m.unavailable_reason ?? null,
+ llamaCppOnly: m.llama_cpp_only ?? false,
})),
loadedModel: settings.loaded_model,
loadedDevice: settings.loaded_device,
@@ -168,6 +193,12 @@ function fromApi(settings: ApiSystemOneSettings): SystemOneSettings {
installing: settings.installing,
error: settings.error,
mcpUrl: settings.mcp_url,
+ backend: settings.backend ?? "auto",
+ nativeCtx: settings.native_ctx ?? 16384,
+ effectiveBackend: settings.effective_backend ?? null,
+ loadedBackend: settings.loaded_backend ?? null,
+ fallbackReason: settings.fallback_reason ?? null,
+ inputModalities: settings.input_modalities ?? ["text"],
};
}
@@ -245,8 +276,12 @@ export async function loadSystemOneConnections(): Promise<
export async function resolveSystemOneDownload(
model?: string,
+ backend?: SystemOneBackend,
): Promise<SystemOneDownloadPlan> {
- const query = model ? `?${new URLSearchParams({ model })}` : "";
+ const params = new URLSearchParams();
+ if (model) params.set("model", model);
+ if (backend) params.set("backend", backend);
+ const query = params.size ? `?${params}` : "";
const res = await authFetch(`${SETTINGS_PATH}/resolve${query}`);
if (!res.ok) {
throw new Error(
diff --git a/studio/frontend/src/features/settings/components/decision-api-section.tsx b/studio/frontend/src/features/settings/components/decision-api-section.tsx
index 4eb707d0e9e..ae5ee6a5a5e 100644
--- a/studio/frontend/src/features/settings/components/decision-api-section.tsx
+++ b/studio/frontend/src/features/settings/components/decision-api-section.tsx
@@ -45,6 +45,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { type ReactElement, useEffect, useRef, useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
+ type SystemOneBackend,
type SystemOneConnection,
type SystemOneDevice,
type SystemOneDownloadPlan,
@@ -86,6 +87,7 @@ export function DecisionApiSection(): ReactElement | null {
);
const [planState, setPlanState] = useState<{
model: string;
+ backend: SystemOneBackend;
plan: SystemOneDownloadPlan;
} | null>(null);
const [confirm, setConfirm] = useState<{
@@ -102,7 +104,12 @@ export function DecisionApiSection(): ReactElement | null {
const enabled = settings?.enabled ?? false;
if (tryOpen && !enabled) setTryOpen(false);
const model = settings?.model ?? null;
- const plan = planState && planState.model === model ? planState.plan : null;
+ const backend = settings?.backend ?? "auto";
+ // llama.cpp serves a GGUF, PyTorch the safetensors: the download follows the runtime.
+ const plan =
+ planState?.model === model && planState?.backend === backend
+ ? planState.plan
+ : null;
useEffect(() => {
let live = true;
@@ -160,20 +167,20 @@ export function DecisionApiSection(): ReactElement | null {
useEffect(() => {
if (!enabled || !model) return;
let live = true;
- resolveSystemOneDownload(model).then(
- (next) => live && setPlanState({ model, plan: next }),
+ resolveSystemOneDownload(model, backend).then(
+ (next) => live && setPlanState({ model, backend, plan: next }),
(err) => live && setError(errorMessage(err)),
);
return () => {
live = false;
};
- }, [enabled, model, downloadDone]);
+ }, [enabled, model, backend, downloadDone]);
const modelLabel = (name: string) => {
const connection = connections?.find((c) => c.name === name);
if (connection) return `${connection.provider} · ${connection.model}`;
const option = settings?.models.find((m) => m.name === name);
- if (option?.kind === "fine_tune" && option.label) return option.label;
+ if (option?.label) return option.label;
return DECISION_MODEL_LABELS[name] ? t(DECISION_MODEL_LABELS[name]) : name;
};
@@ -238,6 +245,7 @@ export function DecisionApiSection(): ReactElement | null {
// Offer the download on the switch, not on the first request: a first API call should not sit behind a 700 MB transfer.
const nextEnabled = patch.enabled ?? settings?.enabled;
const nextModel = patch.model ?? settings?.model;
+ const nextBackend = patch.backend ?? backend;
const settingsPatch =
downloadAfter && settings
? {
@@ -246,10 +254,9 @@ export function DecisionApiSection(): ReactElement | null {
expectedModel: settings.model,
}
: patch;
- let resolvedPlan: { model: string; plan: SystemOneDownloadPlan } | null =
- null;
+ let resolvedPlan: typeof planState = null;
if (nextEnabled && nextModel && downloadAfter) {
- const nextPlan = await resolveSystemOneDownload(nextModel);
+ const nextPlan = await resolveSystemOneDownload(nextModel, nextBackend);
if (!nextPlan.cached) {
if (nextPlan.error || !nextPlan.repo || nextPlan.files.length === 0) {
throw new Error(
@@ -264,7 +271,11 @@ export function DecisionApiSection(): ReactElement | null {
});
return;
}
- resolvedPlan = { model: nextModel, plan: nextPlan };
+ resolvedPlan = {
+ model: nextModel,
+ backend: nextBackend,
+ plan: nextPlan,
+ };
}
const next = await updateSystemOneSettings(settingsPatch);
setSettings(next);
@@ -287,7 +298,11 @@ export function DecisionApiSection(): ReactElement | null {
const next = await updateSystemOneSettings(accepted.patch);
setSettings(next);
if (next.model === accepted.model) {
- setPlanState({ model: accepted.model, plan: accepted.plan });
+ setPlanState({
+ model: accepted.model,
+ backend: next.backend,
+ plan: accepted.plan,
+ });
}
} catch (err) {
await resyncSettingsAfterError(
@@ -379,6 +394,9 @@ export function DecisionApiSection(): ReactElement | null {
const remote = connections?.find((c) => c.name === settings.model);
const knownModel = current !== undefined || isRemote;
const longLabel = isRemote || current?.kind === "fine_tune";
+ // Laya is PyTorch only; Clef runs on either runtime, a GGUF-only model on llama.cpp only.
+ const runtimeChoice =
+ isClefDecisionModel(settings.model) || !!current?.llamaCppOnly;
const connectionGroups = [
...new Set(connections?.map((c) => c.providerId)),
].map((id) => connections?.filter((c) => c.providerId === id) ?? []);
@@ -552,7 +570,7 @@ export function DecisionApiSection(): ReactElement | null {
key={option.name}
value={option.name}
disabled={!option.available}
- title={option.unavailableReason ?? undefined}
+ title={option.unavailableReason ?? option.description}
>
<span className="flex items-center gap-2">
{modelLabel(option.name)}
@@ -590,6 +608,55 @@ export function DecisionApiSection(): ReactElement | null {
</div>
</SettingsRow>
+ {runtimeChoice ? (
+ <>
+ <SettingsRow
+ label={t("settings.apiKeys.decisionApi.backend")}
+ description={t("settings.apiKeys.decisionApi.backendDescription")}
+ >
+ <Select
+ value={backend}
+ disabled={busy}
+ onValueChange={(value) =>
+ void apply({ backend: value as SystemOneBackend }, true)
+ }
+ >
+ <SelectTrigger
+ className="w-36"
+ aria-label={t("settings.apiKeys.decisionApi.backend")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="auto">
+ {t("settings.apiKeys.decisionApi.backendAuto")}
+ </SelectItem>
+ <SelectItem value="llama.cpp">llama.cpp</SelectItem>
+ <SelectItem value="pytorch">PyTorch</SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ <p
+ className="pb-3 text-xs text-muted-foreground leading-relaxed"
+ data-decision-backend
+ >
+ {t("settings.apiKeys.decisionApi.backendStatus", {
+ backend:
+ (settings.loadedModel === settings.model
+ ? settings.loadedBackend
+ : settings.effectiveBackend) ??
+ t("settings.apiKeys.decisionApi.backendNone"),
+ })}
+ {settings.fallbackReason ? ` · ${settings.fallbackReason}` : ""}{" "}
+ {t(
+ settings.inputModalities.includes("image")
+ ? "settings.apiKeys.decisionApi.mediaImages"
+ : "settings.apiKeys.decisionApi.mediaText",
+ )}
+ </p>
+ </>
+ ) : null}
+
{isRemote ? null : (
<SettingsRow
label={t("settings.apiKeys.decisionApi.device")}
@@ -667,7 +734,10 @@ export function DecisionApiSection(): ReactElement | null {
</AlertDialogMedia>
<AlertDialogTitle>
{t(
- isClefDecisionModel(confirm?.model ?? settings.model)
+ isClefDecisionModel(confirm?.model ?? settings.model) ||
+ settings.models.find(
+ (m) => m.name === (confirm?.model ?? settings.model),
+ )?.llamaCppOnly
? "settings.apiKeys.decisionApi.downloadConfirmTitleModel"
: "settings.apiKeys.decisionApi.downloadConfirmTitle",
{ model: modelLabel(confirm?.model ?? settings.model) },
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index a1bcca31585..7583e11ecbd 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2801,6 +2801,14 @@ export const ar = {
deviceDescription: "وحدة GPU أسرع في الإجابة، لكنها تحتفظ بذاكرتها محجوزة حتى إعادة التشغيل.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "بيئة التشغيل",
+ backendAuto: "تلقائي",
+ backendDescription:
+ "يشغّل الوضع التلقائي Clef عبر llama.cpp عندما يتوفر للنموذج إصدار GGUF، ويعود إلى PyTorch في غير ذلك. يقرأ llama.cpp الصور أيضًا.",
+ backendStatus: "بيئة التشغيل: {backend}",
+ backendNone: "غير متاحة",
+ mediaImages: "يقرأ النصوص والصور.",
+ mediaText: "يقرأ النصوص فقط.",
checking: "جارٍ التحقق…",
notDownloaded: "غير مُنزَّل · {size}",
downloading: "جارٍ التنزيل…",
@@ -4083,6 +4091,17 @@ export const ar = {
openFileFailed: "تعذّر فتح الملف",
},
},
+ exportDecision: {
+ title: "نموذج القرار",
+ description: "تُصدَّر نماذج القرار {layout} إلى GGUF لخادم القرار في llama.cpp. اختر مستوى تكميم واحدًا أو أكثر.",
+ adapterNote: "تحتوي نقطة الحفظ هذه على محولات LoRA، ويتم دمجها قبل التحويل.",
+ notEligibleTitle: "تصدير GGUF غير متاح",
+ ggufOnly: "تُصدَّر نماذج القرار إلى GGUF فقط",
+ existing: "تم التصدير مسبقًا: {quantizations}",
+ outputNote: "تُحفظ ملفات GGUF في مجلد التشغيل: {path}",
+ methodLabel: "GGUF لنموذج القرار",
+ outputLabel: "GGUF للقرار ({quantizations})",
+ },
decisions: {
title: "جرّب قرارًا",
description: "اطرح على Laya سؤالًا عن أي نص.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 6c7a0ca9310..c3c7b1747c3 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2845,6 +2845,14 @@ export const de = {
deviceDescription: "Die GPU antwortet schneller, hält ihren Speicher aber bis zum Neustart reserviert.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Laufzeit",
+ backendAuto: "Automatisch",
+ backendDescription:
+ "Automatisch stellt Clef über llama.cpp bereit, wenn das Modell einen GGUF-Build hat, und weicht sonst auf PyTorch aus. llama.cpp liest auch Bilder.",
+ backendStatus: "Laufzeit: {backend}",
+ backendNone: "nicht verfügbar",
+ mediaImages: "Liest Text und Bilder.",
+ mediaText: "Liest nur Text.",
checking: "Wird geprüft…",
notDownloaded: "Nicht heruntergeladen · {size}",
downloading: "Wird heruntergeladen…",
@@ -4154,6 +4162,17 @@ export const de = {
openFileFailed: "Die Datei konnte nicht geöffnet werden",
},
},
+ exportDecision: {
+ title: "Entscheidungsmodell",
+ description: "{layout}-Entscheidungsmodelle werden für den Entscheidungsserver von llama.cpp nach GGUF exportiert. Wähle eine oder mehrere Quantisierungen.",
+ adapterNote: "Dieser Checkpoint enthält LoRA-Adapter; sie werden vor der Konvertierung zusammengeführt.",
+ notEligibleTitle: "GGUF-Export nicht verfügbar",
+ ggufOnly: "Entscheidungsmodelle werden nur nach GGUF exportiert",
+ existing: "Bereits exportiert: {quantizations}",
+ outputNote: "GGUF-Dateien werden im Run-Ordner gespeichert: {path}",
+ methodLabel: "GGUF des Entscheidungsmodells",
+ outputLabel: "Entscheidungs-GGUF ({quantizations})",
+ },
decisions: {
title: "Eine Entscheidung testen",
description: "Stelle Laya eine Frage zu einem beliebigen Text.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index bbe9420b60b..cfd2b3bc978 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2836,6 +2836,14 @@ export const en = {
deviceDescription: "GPU answers faster, but keeps its memory reserved until restart.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Runtime",
+ backendAuto: "Auto",
+ backendDescription:
+ "Auto serves Clef through llama.cpp when the model has a GGUF build and falls back to PyTorch otherwise. llama.cpp also reads images.",
+ backendStatus: "Runtime: {backend}",
+ backendNone: "unavailable",
+ mediaImages: "Reads text and images.",
+ mediaText: "Reads text only.",
checking: "Checking…",
notDownloaded: "Not downloaded · {size}",
downloading: "Downloading…",
@@ -4128,6 +4136,17 @@ export const en = {
openFileFailed: "Could not open the file",
},
},
+ exportDecision: {
+ title: "Decision model",
+ description: "{layout} decision models export to GGUF for llama.cpp's decision server. Pick one or more quantizations.",
+ adapterNote: "This checkpoint holds LoRA adapters; they are merged before conversion.",
+ notEligibleTitle: "GGUF export unavailable",
+ ggufOnly: "Decision models export to GGUF only",
+ existing: "Already exported: {quantizations}",
+ outputNote: "GGUF files are saved in the run folder: {path}",
+ methodLabel: "Decision model GGUF",
+ outputLabel: "Decision GGUF ({quantizations})",
+ },
decisions: {
title: "Try a decision",
description: "Ask Laya a question about any text.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index dc4e73fd546..0cb85efa1fc 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2838,6 +2838,14 @@ export const es = {
deviceDescription: "La GPU responde más rápido, pero mantiene su memoria reservada hasta reiniciar.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Entorno de ejecución",
+ backendAuto: "Automático",
+ backendDescription:
+ "Automático sirve Clef mediante llama.cpp cuando el modelo tiene una versión GGUF y recurre a PyTorch en caso contrario. llama.cpp también lee imágenes.",
+ backendStatus: "Entorno de ejecución: {backend}",
+ backendNone: "no disponible",
+ mediaImages: "Lee texto e imágenes.",
+ mediaText: "Solo lee texto.",
checking: "Comprobando…",
notDownloaded: "No descargado · {size}",
downloading: "Descargando…",
@@ -4153,6 +4161,17 @@ export const es = {
openFileFailed: "No se pudo abrir el archivo",
},
},
+ exportDecision: {
+ title: "Modelo de decisión",
+ description: "Los modelos de decisión {layout} se exportan a GGUF para el servidor de decisiones de llama.cpp. Elige una o más cuantizaciones.",
+ adapterNote: "Este checkpoint contiene adaptadores LoRA; se fusionan antes de la conversión.",
+ notEligibleTitle: "Exportación GGUF no disponible",
+ ggufOnly: "Los modelos de decisión solo se exportan a GGUF",
+ existing: "Ya exportado: {quantizations}",
+ outputNote: "Los archivos GGUF se guardan en la carpeta de la ejecución: {path}",
+ methodLabel: "GGUF del modelo de decisión",
+ outputLabel: "GGUF de decisión ({quantizations})",
+ },
decisions: {
title: "Probar una decisión",
description: "Hazle a Laya una pregunta sobre cualquier texto.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index be41a892fba..1809103e212 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2846,6 +2846,14 @@ export const fr = {
deviceDescription: "Le GPU répond plus vite, mais garde sa mémoire réservée jusqu'au redémarrage.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Moteur d'exécution",
+ backendAuto: "Automatique",
+ backendDescription:
+ "Automatique sert Clef via llama.cpp lorsque le modèle a une version GGUF, et se rabat sur PyTorch sinon. llama.cpp lit aussi les images.",
+ backendStatus: "Moteur d'exécution : {backend}",
+ backendNone: "indisponible",
+ mediaImages: "Lit le texte et les images.",
+ mediaText: "Lit uniquement le texte.",
checking: "Vérification…",
notDownloaded: "Non téléchargé · {size}",
downloading: "Téléchargement…",
@@ -4165,6 +4173,17 @@ export const fr = {
openFileFailed: "Impossible d'ouvrir le fichier",
},
},
+ exportDecision: {
+ title: "Modèle de décision",
+ description: "Les modèles de décision {layout} s'exportent en GGUF pour le serveur de décision de llama.cpp. Choisissez une ou plusieurs quantifications.",
+ adapterNote: "Ce checkpoint contient des adaptateurs LoRA ; ils sont fusionnés avant la conversion.",
+ notEligibleTitle: "Export GGUF indisponible",
+ ggufOnly: "Les modèles de décision s'exportent uniquement en GGUF",
+ existing: "Déjà exporté : {quantizations}",
+ outputNote: "Les fichiers GGUF sont enregistrés dans le dossier de l'exécution : {path}",
+ methodLabel: "GGUF du modèle de décision",
+ outputLabel: "GGUF de décision ({quantizations})",
+ },
decisions: {
title: "Essayer une décision",
description: "Posez à Laya une question sur n’importe quel texte.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 88a3f6b9ce5..c15c6eb58cf 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2807,6 +2807,14 @@ export const hi = {
deviceDescription: "GPU तेज़ जवाब देता है, लेकिन रीस्टार्ट होने तक अपनी मेमोरी आरक्षित रखता है।",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "रनटाइम",
+ backendAuto: "ऑटो",
+ backendDescription:
+ "मॉडल का GGUF बिल्ड होने पर ऑटो Clef को llama.cpp से चलाता है, वरना PyTorch पर चला जाता है। llama.cpp इमेज भी पढ़ता है।",
+ backendStatus: "रनटाइम: {backend}",
+ backendNone: "उपलब्ध नहीं",
+ mediaImages: "टेक्स्ट और इमेज पढ़ता है।",
+ mediaText: "सिर्फ़ टेक्स्ट पढ़ता है।",
checking: "जाँच हो रही है…",
notDownloaded: "डाउनलोड नहीं हुआ · {size}",
downloading: "डाउनलोड हो रहा है…",
@@ -4091,6 +4099,17 @@ export const hi = {
openFileFailed: "फ़ाइल खोली नहीं जा सकी",
},
},
+ exportDecision: {
+ title: "निर्णय मॉडल",
+ description: "{layout} निर्णय मॉडल llama.cpp के निर्णय सर्वर के लिए GGUF में एक्सपोर्ट होते हैं। एक या अधिक क्वांटाइज़ेशन चुनें।",
+ adapterNote: "इस चेकपॉइंट में LoRA एडैप्टर हैं; कन्वर्ज़न से पहले उन्हें मर्ज किया जाता है।",
+ notEligibleTitle: "GGUF एक्सपोर्ट उपलब्ध नहीं है",
+ ggufOnly: "निर्णय मॉडल केवल GGUF में एक्सपोर्ट होते हैं",
+ existing: "पहले से एक्सपोर्ट किया गया: {quantizations}",
+ outputNote: "GGUF फ़ाइलें रन फ़ोल्डर में सहेजी जाती हैं: {path}",
+ methodLabel: "निर्णय मॉडल GGUF",
+ outputLabel: "निर्णय GGUF ({quantizations})",
+ },
decisions: {
title: "एक फ़ैसला आज़माएँ",
description: "किसी भी टेक्स्ट के बारे में Laya से सवाल पूछें।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index badc7d73a40..fedf5226cd0 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2804,6 +2804,14 @@ export const it = {
deviceDescription: "La GPU risponde più velocemente, ma tiene la memoria riservata fino al riavvio.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Runtime",
+ backendAuto: "Automatico",
+ backendDescription:
+ "Automatico serve Clef tramite llama.cpp quando il modello ha una build GGUF, altrimenti ripiega su PyTorch. llama.cpp legge anche le immagini.",
+ backendStatus: "Runtime: {backend}",
+ backendNone: "non disponibile",
+ mediaImages: "Legge testo e immagini.",
+ mediaText: "Legge solo testo.",
checking: "Verifica in corso…",
notDownloaded: "Non scaricato · {size}",
downloading: "Download in corso…",
@@ -4155,6 +4163,17 @@ export const it = {
openFileFailed: "Impossibile aprire il file",
},
},
+ exportDecision: {
+ title: "Modello decisionale",
+ description: "I modelli decisionali {layout} si esportano in GGUF per il server decisionale di llama.cpp. Scegli una o più quantizzazioni.",
+ adapterNote: "Questo checkpoint contiene adattatori LoRA; vengono uniti prima della conversione.",
+ notEligibleTitle: "Esportazione GGUF non disponibile",
+ ggufOnly: "I modelli decisionali si esportano solo in GGUF",
+ existing: "Già esportato: {quantizations}",
+ outputNote: "I file GGUF vengono salvati nella cartella dell'esecuzione: {path}",
+ methodLabel: "GGUF del modello decisionale",
+ outputLabel: "GGUF decisionale ({quantizations})",
+ },
decisions: {
title: "Prova una decisione",
description: "Fai a Laya una domanda su qualsiasi testo.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 4f4ecb81b30..2ef80e33f9f 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2771,6 +2771,14 @@ export const ja = {
deviceDescription: "GPU の方が高速ですが、再起動するまでメモリを確保し続けます。",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "ランタイム",
+ backendAuto: "自動",
+ backendDescription:
+ "自動では、モデルに GGUF ビルドがあれば Clef を llama.cpp で提供し、なければ PyTorch に切り替えます。llama.cpp は画像も読み取れます。",
+ backendStatus: "ランタイム: {backend}",
+ backendNone: "利用不可",
+ mediaImages: "テキストと画像を読み取ります。",
+ mediaText: "テキストのみ読み取ります。",
checking: "確認中…",
notDownloaded: "未ダウンロード · {size}",
downloading: "ダウンロード中…",
@@ -4032,6 +4040,17 @@ export const ja = {
openFileFailed: "ファイルを開けませんでした",
},
},
+ exportDecision: {
+ title: "意思決定モデル",
+ description: "{layout} 意思決定モデルは llama.cpp の意思決定サーバー向けに GGUF へエクスポートされます。量子化を 1 つ以上選択してください。",
+ adapterNote: "このチェックポイントには LoRA アダプターが含まれています。変換前にマージされます。",
+ notEligibleTitle: "GGUF エクスポートは利用できません",
+ ggufOnly: "意思決定モデルは GGUF にのみエクスポートできます",
+ existing: "エクスポート済み: {quantizations}",
+ outputNote: "GGUF ファイルは実行フォルダーに保存されます: {path}",
+ methodLabel: "意思決定モデルの GGUF",
+ outputLabel: "意思決定 GGUF ({quantizations})",
+ },
decisions: {
title: "判定を試す",
description: "任意のテキストについて Laya に質問します。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index c602f376a61..f32eb189e3d 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2791,6 +2791,14 @@ export const ko = {
deviceDescription: "GPU가 더 빠르지만 다시 시작할 때까지 메모리를 계속 차지합니다.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "런타임",
+ backendAuto: "자동",
+ backendDescription:
+ "자동은 모델에 GGUF 빌드가 있으면 llama.cpp로 Clef를 제공하고, 없으면 PyTorch로 대체합니다. llama.cpp는 이미지도 읽습니다.",
+ backendStatus: "런타임: {backend}",
+ backendNone: "사용할 수 없음",
+ mediaImages: "텍스트와 이미지를 읽습니다.",
+ mediaText: "텍스트만 읽습니다.",
checking: "확인 중…",
notDownloaded: "다운로드 안 됨 · {size}",
downloading: "다운로드 중…",
@@ -4075,6 +4083,17 @@ export const ko = {
openFileFailed: "파일을 열 수 없습니다",
},
},
+ exportDecision: {
+ title: "의사결정 모델",
+ description: "{layout} 의사결정 모델은 llama.cpp 의사결정 서버용 GGUF로 내보냅니다. 양자화를 하나 이상 선택하세요.",
+ adapterNote: "이 체크포인트에는 LoRA 어댑터가 있으며, 변환 전에 병합됩니다.",
+ notEligibleTitle: "GGUF 내보내기를 사용할 수 없음",
+ ggufOnly: "의사결정 모델은 GGUF로만 내보낼 수 있습니다",
+ existing: "이미 내보냄: {quantizations}",
+ outputNote: "GGUF 파일은 실행 폴더에 저장됩니다: {path}",
+ methodLabel: "의사결정 모델 GGUF",
+ outputLabel: "의사결정 GGUF ({quantizations})",
+ },
decisions: {
title: "판단 사용해 보기",
description: "어떤 텍스트든 Laya에게 질문하세요.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 7564c3ea2f3..4b9527de4fd 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2817,6 +2817,14 @@ export const ptBR = {
deviceDescription: "A GPU responde mais rápido, mas mantém a memória reservada até reiniciar.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Runtime",
+ backendAuto: "Automático",
+ backendDescription:
+ "O automático serve o Clef pelo llama.cpp quando o modelo tem uma versão GGUF e recorre ao PyTorch caso contrário. O llama.cpp também lê imagens.",
+ backendStatus: "Runtime: {backend}",
+ backendNone: "indisponível",
+ mediaImages: "Lê texto e imagens.",
+ mediaText: "Lê apenas texto.",
checking: "Verificando…",
notDownloaded: "Não baixado · {size}",
downloading: "Baixando…",
@@ -4113,6 +4121,17 @@ export const ptBR = {
openFileFailed: "Não foi possível abrir o arquivo",
},
},
+ exportDecision: {
+ title: "Modelo de decisão",
+ description: "Modelos de decisão {layout} são exportados para GGUF para o servidor de decisão do llama.cpp. Escolha uma ou mais quantizações.",
+ adapterNote: "Este checkpoint contém adaptadores LoRA; eles são mesclados antes da conversão.",
+ notEligibleTitle: "Exportação GGUF indisponível",
+ ggufOnly: "Modelos de decisão são exportados apenas para GGUF",
+ existing: "Já exportado: {quantizations}",
+ outputNote: "Os arquivos GGUF são salvos na pasta da execução: {path}",
+ methodLabel: "GGUF do modelo de decisão",
+ outputLabel: "GGUF de decisão ({quantizations})",
+ },
decisions: {
title: "Testar uma decisão",
description: "Faça à Laya uma pergunta sobre qualquer texto.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 51e862addc2..0111b0bf94d 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2812,6 +2812,14 @@ export const ru = {
deviceDescription: "GPU отвечает быстрее, но держит память зарезервированной до перезапуска.",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "Среда выполнения",
+ backendAuto: "Авто",
+ backendDescription:
+ "В режиме «Авто» Clef работает через llama.cpp, если у модели есть сборка GGUF, а иначе через PyTorch. llama.cpp также читает изображения.",
+ backendStatus: "Среда выполнения: {backend}",
+ backendNone: "недоступна",
+ mediaImages: "Читает текст и изображения.",
+ mediaText: "Читает только текст.",
checking: "Проверка…",
notDownloaded: "Не скачана · {size}",
downloading: "Скачивание…",
@@ -4110,6 +4118,17 @@ export const ru = {
openFileFailed: "Не удалось открыть файл",
},
},
+ exportDecision: {
+ title: "Модель принятия решений",
+ description: "Модели принятия решений {layout} экспортируются в GGUF для сервера решений llama.cpp. Выберите одну или несколько квантизаций.",
+ adapterNote: "Этот чекпоинт содержит адаптеры LoRA; они объединяются перед конвертацией.",
+ notEligibleTitle: "Экспорт в GGUF недоступен",
+ ggufOnly: "Модели принятия решений экспортируются только в GGUF",
+ existing: "Уже экспортировано: {quantizations}",
+ outputNote: "Файлы GGUF сохраняются в папке запуска: {path}",
+ methodLabel: "GGUF модели принятия решений",
+ outputLabel: "GGUF решений ({quantizations})",
+ },
decisions: {
title: "Проверить решение",
description: "Задайте Laya вопрос о любом тексте.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 69e6f39f97f..dcf45dce26a 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2750,6 +2750,14 @@ export const zhCN = {
deviceDescription: "GPU 响应更快,但在重启前会一直占用显存。",
deviceCpu: "CPU",
deviceGpu: "GPU",
+ backend: "运行时",
+ backendAuto: "自动",
+ backendDescription:
+ "自动模式下,模型有 GGUF 版本时通过 llama.cpp 提供 Clef,否则回退到 PyTorch。llama.cpp 还能读取图片。",
+ backendStatus: "运行时:{backend}",
+ backendNone: "不可用",
+ mediaImages: "可读取文本和图片。",
+ mediaText: "仅读取文本。",
checking: "正在检查…",
notDownloaded: "未下载 · {size}",
downloading: "正在下载…",
@@ -3989,6 +3997,17 @@ export const zhCN = {
openFileFailed: "无法打开文件",
},
},
+ exportDecision: {
+ title: "决策模型",
+ description: "{layout} 决策模型会导出为 GGUF,供 llama.cpp 决策服务器使用。请选择一个或多个量化级别。",
+ adapterNote: "此检查点包含 LoRA 适配器,转换前会先合并。",
+ notEligibleTitle: "无法导出 GGUF",
+ ggufOnly: "决策模型仅支持导出为 GGUF",
+ existing: "已导出:{quantizations}",
+ outputNote: "GGUF 文件保存在运行文件夹中:{path}",
+ methodLabel: "决策模型 GGUF",
+ outputLabel: "决策 GGUF({quantizations})",
+ },
decisions: {
title: "试一个判断",
description: "就任意文本向 Laya 提一个问题。",
diff --git a/studio/frontend/tests/decision-api-section.test.ts b/studio/frontend/tests/decision-api-section.test.ts
index 2660b16449c..a27342dee85 100644
--- a/studio/frontend/tests/decision-api-section.test.ts
+++ b/studio/frontend/tests/decision-api-section.test.ts
@@ -57,7 +57,7 @@ test("a download waits for confirmation before changing the setting", () => {
);
assert.doesNotMatch(apply, /startDownload\(/);
assert.ok(
- apply.indexOf("resolveSystemOneDownload(nextModel)") <
+ apply.indexOf("resolveSystemOneDownload(nextModel, nextBackend)") <
apply.indexOf("updateSystemOneSettings(settingsPatch)"),
);
assert.match(apply, /expectedEnabled: settings\.enabled/);
@@ -99,7 +99,8 @@ test("the download goes through the manager with the exact files and one scope",
SECTION,
/acceptedState === "running" \|\| acceptedState === "complete"/,
);
- assert.match(SECTION, /resolveSystemOneDownload\(model\)\.then/);
+ assert.match(SECTION, /resolveSystemOneDownload\(model, backend\)\.then/);
+ assert.match(SECTION, /\[enabled, model, backend, downloadDone\]/);
assert.match(SECTION, /await resyncSettingsAfterError/);
});
diff --git a/studio/frontend/tests/export-decision-gguf.test.ts b/studio/frontend/tests/export-decision-gguf.test.ts
new file mode 100644
index 00000000000..6de9646b751
--- /dev/null
+++ b/studio/frontend/tests/export-decision-gguf.test.ts
@@ -0,0 +1,75 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+register("./helpers/export-store-resolver.mjs", import.meta.url);
+
+const stub = await import("./helpers/export-api-stub.mjs");
+const { useExportRuntimeStore } = await import(
+ "../src/features/export/stores/export-runtime-store.ts"
+);
+
+function params(overrides: Record<string, unknown>) {
+ return {
+ sourceMode: "checkpoint",
+ checkpointPath: "/runs/clef",
+ source: "clef",
+ modelSource: "local",
+ trustRemoteCode: true,
+ exportMethod: "gguf",
+ isAdapter: false,
+ quantLevels: ["q8_0", "q4_k_m"],
+ saveDirectory: "clef-gguf",
+ destination: "local",
+ privateRepo: false,
+ summary: {},
+ ...overrides,
+ } as unknown as Parameters<
+ ReturnType<typeof useExportRuntimeStore.getState>["runExport"]
+ >[0];
+}
+
+async function run(overrides: Record<string, unknown>, details: unknown) {
+ stub.resetStub();
+ stub.responses.set("exportGGUF", {
+ success: true,
+ message: "ok",
+ details,
+ });
+ await useExportRuntimeStore.getState().runExport(params(overrides));
+ return useExportRuntimeStore.getState().result;
+}
+
+const label = (quants: string[]) => `Decision GGUF (${quants.join(", ")})`;
+
+test("a decision export lists the quantizations the run folder now holds", async () => {
+ const result = await run(
+ { decisionOutputLabel: label },
+ { output_path: "/runs/clef/gguf", quantizations: ["Q8_0", "Q4_K_M", "F16"] },
+ );
+ assert.deepEqual(result?.outputPaths, [
+ { label: "Decision GGUF (Q8_0, Q4_K_M, F16)", path: "/runs/clef/gguf" },
+ ]);
+ const body = stub.calls.find((c) => c.name === "exportGGUF")?.args[0] as
+ | Record<string, unknown>
+ | undefined;
+ assert.deepEqual(body?.quantization_method, ["q8_0", "q4_k_m"]);
+});
+
+test("a decision export without export.json details falls back to the requested quants", async () => {
+ const result = await run(
+ { decisionOutputLabel: label },
+ { output_path: "/runs/clef/gguf" },
+ );
+ assert.equal(result?.outputPaths[0]?.label, "Decision GGUF (Q8_0, Q4_K_M)");
+});
+
+test("other GGUF exports keep the plain label", async () => {
+ const result = await run({}, { output_path: "exports/model-gguf" });
+ assert.deepEqual(result?.outputPaths, [
+ { label: "GGUF", path: "exports/model-gguf" },
+ ]);
+});
diff --git a/tests/test_decision_gguf.py b/tests/test_decision_gguf.py
new file mode 100644
index 00000000000..13fb7f84b62
--- /dev/null
+++ b/tests/test_decision_gguf.py
@@ -0,0 +1,732 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import json
+import math
+import os
+import random
+import signal
+import subprocess
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from unsloth.models import decision, decision_gguf
+from unsloth.models.decision_gguf import (
+ effective_temperatures,
+ gguf_eligibility,
+ read_decision_temperatures,
+ write_decision_temperatures,
+)
+
+# gguf-py ships with llama.cpp, not on PyPI at the version with the decision keys.
+if os.environ.get("UNSLOTH_TEST_GGUF_PY"):
+ sys.path.insert(0, os.environ["UNSLOTH_TEST_GGUF_PY"])
+try:
+ import gguf
+ import numpy as np
+except ImportError:
+ gguf = None
+needs_gguf = pytest.mark.skipif(gguf is None, reason = "needs gguf-py")
+contract = decision_gguf._contract()
+
+
+def _llama_cpp_temperature(temperatures: dict, qtype: str, n: int) -> float:
+ # server_decision_context::get_temperature for a non-Lev model (server-decision.cpp, b11443).
+ bucket = "2" if n <= 2 else "3_5" if n <= 5 else "6_10" if n <= 10 else "11"
+ for name in (f"{qtype}.{bucket}", qtype):
+ if name in temperatures:
+ return temperatures[name]
+ return 1.0
+
+
+def test_uncalibrated_models_serve_at_one():
+ for layout in ("clef", "laya"):
+ assert effective_temperatures({}, layout) == {"choice": 1.0, "score": 1.0, "noul": 1.0}
+
+
+def test_folded_head_temperature_is_not_applied_twice():
+ config = {"folded_temperature": 1.1728, "temperature": [1.229, 0.681, 0.768]}
+ assert effective_temperatures(config, "clef") == {
+ "choice": 1.229,
+ "score": 0.681,
+ "noul": 0.768,
+ }
+
+
+def test_unfolded_head_temperature_at_the_floor_multiplies_without_a_reclamp():
+ config = {"head_temperature": 0.05, "temperature": [1.0, 0.5, 1.0]}
+ got = effective_temperatures(config, "clef")
+ assert got == pytest.approx({"choice": 0.05, "score": 0.025, "noul": 0.05})
+ # Laya has no head temperature: one left in its config is not what PyTorch applies.
+ assert effective_temperatures(config, "laya") == {"choice": 1.0, "score": 0.5, "noul": 1.0}
+
+
+def test_per_type_and_bucket_values_clamp_as_pytorch_serving_clamps():
+ config = {
+ "head_temperature": 2.0,
+ "temperature": [0.1, 9.0, float("nan")],
+ "temperature_by_options": {
+ "choice:3-5": 0.1006,
+ "noul:2": 0.7,
+ "choice:11+": 2.0,
+ "score:6-10": 50,
+ "bogus:2": 3.0,
+ "choice:7": 3.0,
+ },
+ }
+ assert effective_temperatures(config, "clef") == pytest.approx(
+ {
+ "choice": 1.0,
+ "score": 10.0,
+ "noul": 2.0,
+ "choice.3_5": 1.0,
+ "noul.2": 1.4,
+ "choice.11": 4.0,
+ "score.6_10": 10.0,
+ }
+ )
+
+
+ "config",
+ [
+ {"head_temperature": float("nan")},
+ {"head_temperature": 0.0},
+ {"head_temperature": -1.0},
+ {"head_temperature": float("inf")},
+ {"head_temperature": "warm"},
+ {"temperature": [1.0, 1.0]},
+ {"temperature": 1.0},
+ {"temperature_by_options": [["choice:2", 1.0]]},
+ ],
+)
+def test_invalid_temperatures_are_rejected(config):
+ with pytest.raises(ValueError):
+ effective_temperatures(config, "clef")
+
+
+def test_llama_cpp_lookup_matches_pytorch_serving_on_random_configs():
+ laya = decision._laya()
+ rng = random.Random(0)
+ sizes = list(range(2, 30))
+ for trial in range(300):
+ config = {"temperature": [rng.uniform(0.05, 8.0) for _ in range(3)]}
+ if trial % 2:
+ config["head_temperature"] = rng.choice([0.05, rng.uniform(0.05, 20.0)])
+ config["temperature_by_options"] = {
+ laya.common.temp_bucket(rng.randrange(3), rng.choice(sizes)): rng.uniform(0.01, 9.0)
+ for _ in range(rng.randrange(4))
+ }
+ items = [{"qtype": rng.randrange(3)} for _ in range(20)]
+ logits = [torch.zeros(rng.choice(sizes)) for _ in items]
+ layout = "clef"
+ served = decision._served_temperatures(config, logits, items)
+ written = effective_temperatures(config, layout)
+ for item, z, want in zip(items, logits, served):
+ got = _llama_cpp_temperature(written, decision.QUESTION_TYPES[item["qtype"]], len(z))
+ assert got == pytest.approx(want, rel = 1e-12)
+
+
+def _write_gguf(
+ path: Path,
+ temperatures: dict,
+ max_head_tokens = None,
+) -> None:
+ writer = gguf.GGUFWriter(str(path), arch = "clef")
+ writer.add_string("general.name", "tiny")
+ writer.add_uint32("clef.decision.block_count", 4)
+ if max_head_tokens is not None:
+ writer.add_uint32("clef.decision.max_head_tokens", max_head_tokens)
+ writer.add_array("tokenizer.ggml.tokens", ["a", "b", "c"])
+ writer.add_float32("clef.attention.layer_norm_epsilon", 1e-5)
+ for name, value in temperatures.items():
+ writer.add_float32(f"clef.decision.temperature.{name}", value)
+ rng = np.random.default_rng(0)
+ writer.add_tensor("token_embd.weight", rng.standard_normal((3, 64), dtype = np.float32))
+ weights = rng.standard_normal((4, 64), dtype = np.float32)
+ quantized = gguf.quants.quantize(weights, gguf.GGMLQuantizationType.Q8_0)
+ writer.add_tensor(
+ "blk.0.ffn_up.weight",
+ quantized,
+ raw_shape = quantized.shape,
+ raw_dtype = gguf.GGMLQuantizationType.Q8_0,
+ )
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
+def _snapshot(path: Path) -> tuple:
+ reader = gguf.GGUFReader(str(path), "r")
+ fields = {
+ name: (field.types, field.contents())
+ for name, field in reader.fields.items()
+ if ".decision.temperature." not in name and not name.startswith("GGUF.")
+ }
+ tensors = {
+ t.name: (t.tensor_type, tuple(t.shape), bytes(np.asarray(t.data).tobytes()))
+ for t in reader.tensors
+ }
+ return fields, tensors
+
+
+@needs_gguf
+def test_metadata_writer_replaces_only_the_temperatures_and_is_idempotent(tmp_path):
+ path = tmp_path / "model-Q8_0.gguf"
+ _write_gguf(path, {"choice": 3.0, "choice.2": 0.1})
+ os.chmod(path, 0o644)
+ before = _snapshot(path)
+ wanted = {"choice": 1.229, "score": 0.025, "noul": 0.05, "noul.2": 0.7}
+ assert write_decision_temperatures(path, wanted) is True
+ got = read_decision_temperatures(path)
+ assert set(got) == set(wanted)
+ assert all(np.float32(got[k]) == np.float32(v) for k, v in wanted.items())
+ assert _snapshot(path) == before
+ assert os.name == "nt" or (path.stat().st_mode & 0o777) == 0o644
+ data = path.read_bytes()
+ assert write_decision_temperatures(path, dict(wanted)) is False
+ assert path.read_bytes() == data
+ assert [p.name for p in tmp_path.iterdir()] == [path.name]
+
+
+@needs_gguf
+def test_metadata_writer_leaves_the_file_alone_on_a_bad_value(tmp_path):
+ path = tmp_path / "model.gguf"
+ _write_gguf(path, {"choice": 3.0})
+ data = path.read_bytes()
+ with pytest.raises(ValueError):
+ write_decision_temperatures(path, {"choice": float("nan")})
+ assert path.read_bytes() == data
+ assert [p.name for p in tmp_path.iterdir()] == [path.name]
+
+
+def _clef_folder(
+ folder: Path,
+ architectures = ("Qwen3_5ForConditionalGeneration",),
+ config = None,
+) -> Path:
+ folder.mkdir(parents = True, exist_ok = True)
+ model_config = {"architectures": list(architectures)}
+ if architectures and architectures[0] == "Qwen3_5ForConditionalGeneration":
+ model_config["vision_config"] = {"depth": 1}
+ (folder / "config.json").write_text(json.dumps(model_config))
+ (folder / "joint_head_config.json").write_text(json.dumps({"width": 8}))
+ (folder / "joint_head.safetensors").write_bytes(b"head-weights")
+ (folder / "unsloth_decision_config.json").write_text(
+ json.dumps(
+ config if config is not None else {"head_temperature": 0.05, "temperature": [1, 0.5, 1]}
+ )
+ )
+ return folder
+
+
+def _laya_folder(folder: Path, model_type = "modernbert") -> Path:
+ (folder / "encoder").mkdir(parents = True)
+ (folder / "tokenizer").mkdir()
+ (folder / "encoder" / "config.json").write_text(json.dumps({"model_type": model_type}))
+ (folder / "rl_agent_config.json").write_text(json.dumps({"temperature": [1.2, 0.3, 1.0]}))
+ (folder / "model.safetensors").write_bytes(b"weights")
+ return folder
+
+
+def test_fingerprint_and_export_json(tmp_path):
+ folder = _clef_folder(tmp_path / "run")
+ first = contract.fingerprint(folder, "clef")
+ assert first == contract.fingerprint(folder, "clef")
+ (folder / "config.json").write_text("{}") # not part of what the GGUF decision path reads
+ assert contract.fingerprint(folder, "clef") == first
+ (folder / "joint_head.safetensors").write_bytes(b"other")
+ assert contract.fingerprint(folder, "clef") != first
+ # A stock Clef checkpoint has no Unsloth decision config.
+ second = contract.fingerprint(folder, "clef")
+ (folder / "unsloth_decision_config.json").unlink()
+ assert contract.fingerprint(folder, "clef") not in (first, second)
+ laya = _laya_folder(tmp_path / "laya")
+ laya_print = contract.fingerprint(laya, "laya")
+ (laya / "model.safetensors").write_bytes(b"trained")
+ assert contract.fingerprint(laya, "laya") != laya_print
+
+ out = tmp_path / "run" / contract.EXPORT_DIR
+ out.mkdir()
+ files = {"Q8_0": {"model": "model-Q8_0.gguf", "mmproj": "mmproj-Q8_0.gguf"}}
+ data = decision_gguf._write_export(out, "clef", files, "abc")
+ assert data == {
+ "format": "unsloth-decision-gguf",
+ "version": 1,
+ "layout": "clef",
+ "quantizations": ["Q8_0"],
+ "files": files,
+ "source_fingerprint": "abc",
+ }
+ assert contract.read_export(tmp_path / "run") == data
+ umask = os.umask(0)
+ os.umask(umask)
+ assert os.name == "nt" or ((out / "export.json").stat().st_mode & 0o777) == 0o666 & ~umask
+ assert sorted(p.name for p in out.iterdir()) == ["export.json"]
+
+
+def test_eligibility(tmp_path):
+ assert gguf_eligibility(_clef_folder(tmp_path / "q35"))["eligible"]
+ assert gguf_eligibility(_clef_folder(tmp_path / "q35text", ("Qwen3_5ForCausalLM",)))["eligible"]
+ for name, arch in (
+ ("llama", "LlamaForCausalLM"),
+ ("moe", "Qwen3_5MoeForConditionalGeneration"),
+ ):
+ verdict = gguf_eligibility(_clef_folder(tmp_path / name, (arch,)))
+ assert verdict["eligible"] is False and verdict["layout"] == "clef"
+ assert (
+ "Qwen3.5" in verdict["reason"]
+ and arch in verdict["reason"]
+ and "PyTorch" in verdict["reason"]
+ )
+ # Adapters only: judged by the base they sit on.
+ base = _clef_folder(tmp_path / "base", ("Qwen3ForCausalLM",))
+ adapters = _clef_folder(tmp_path / "adapters", config = {"base_model": str(base)})
+ (adapters / "config.json").unlink()
+ (adapters / "adapter_config.json").write_text(
+ json.dumps({"base_model_name_or_path": str(base)})
+ )
+ assert gguf_eligibility(adapters)["eligible"] is False
+ assert gguf_eligibility(_laya_folder(tmp_path / "laya")) == {
+ "eligible": True,
+ "layout": "laya",
+ "reason": None,
+ }
+ assert gguf_eligibility(_laya_folder(tmp_path / "laya_bert", "bert"))["eligible"] is False
+ assert gguf_eligibility(tmp_path)["eligible"] is False
+
+
+def test_save_refuses_a_non_qwen3_5_clef_before_merging(tmp_path, monkeypatch):
+ model = types.SimpleNamespace(
+ is_clef = True,
+ _backbone = lambda: types.SimpleNamespace(
+ config = types.SimpleNamespace(architectures = ["LlamaForCausalLM"])
+ ),
+ )
+ model.save_pretrained_merged = lambda *a, **k: pytest.fail("merged before refusing")
+ monkeypatch.setattr(
+ decision_gguf, "_converter_dir", lambda *a: pytest.fail("looked for llama.cpp")
+ )
+ with pytest.raises(ValueError, match = "Qwen3.5"):
+ decision_gguf.save_pretrained_gguf(model, tmp_path, quantization_method = "q8_0")
+ with pytest.raises(ValueError, match = "q3_k_m"):
+ decision_gguf.save_pretrained_gguf(model, tmp_path, quantization_method = ["q8_0", "q3_k_m"])
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_converter_without_decision_support_stages_the_pinned_tag(tmp_path, monkeypatch):
+ old = tmp_path / "llama.cpp"
+ old.mkdir()
+ (old / "convert_hf_to_gguf.py").write_text("")
+ good = tmp_path / "staged"
+ (good / "conversion").mkdir(parents = True)
+ (good / "gguf-py" / "gguf").mkdir(parents = True)
+ (good / "convert_hf_to_gguf.py").write_text("")
+ (good / "conversion" / "clef.py").write_text("")
+ (good / "gguf-py" / "gguf" / "constants.py").write_text(
+ 'CLEF = "clef"\nTEMPERATURE = "{arch}.decision.temperature.{name}"\n'
+ )
+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_SCRIPTS_DIR", raising = False)
+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_CONVERTER_TAG", raising = False)
+ monkeypatch.setattr(decision_gguf, "_llama_cpp_folder", lambda: old)
+ import unsloth_zoo.llama_cpp as zoo
+
+ asked = []
+ monkeypatch.setattr(
+ zoo, "_stage_converter_sources", lambda tag, *a, **k: asked.append(tag) or good
+ )
+ assert decision_gguf._converter_dir() == good and asked == ["b11443"]
+ monkeypatch.setattr(zoo, "_stage_converter_sources", lambda tag, *a, **k: None)
+ with pytest.raises(RuntimeError, match = "b11443"):
+ decision_gguf._converter_dir()
+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_SCRIPTS_DIR", str(good))
+ assert decision_gguf._converter_dir() == good
+
+
+def fake_llama_cpp(tmp_path, monkeypatch):
+ calls = []
+
+ def convert(converter, folder, outtype, outfile, mmproj, print_output):
+ calls.append(("convert", outtype, outfile.name, mmproj))
+ if mmproj:
+ outfile.write_bytes(b"mmproj " + outtype.encode())
+ else:
+ # The converter's own temperatures and head length (Laya writes raw, unclamped ones).
+ _write_gguf(outfile, {"choice": 0.1006, "choice.11": 0.1006}, max_head_tokens = 96)
+
+ def quantize(quantizer, source, target, method, print_output):
+ calls.append(("quantize", source.name, target.name))
+ target.write_bytes(source.read_bytes())
+
+ monkeypatch.setattr(decision_gguf, "_converter_dir", lambda *a: tmp_path)
+ monkeypatch.setattr(decision_gguf, "_quantizer", lambda *a: "llama-quantize")
+ monkeypatch.setattr(
+ decision_gguf, "_kquant_quantizer", lambda *a: "llama-quantize", raising = False
+ )
+ monkeypatch.setattr(decision_gguf, "_convert", convert)
+ monkeypatch.setattr(decision_gguf, "_quantize", quantize)
+ return calls
+
+
+@needs_gguf
+def test_export_writes_models_mmproj_temperatures_and_export_json_last(tmp_path, fake_llama_cpp):
+ folder = _clef_folder(tmp_path / "run")
+ data = decision_gguf.export_decision_gguf(folder, ["q8_0", "q4_k_m"])
+ out = folder / "gguf"
+ assert data == contract.read_export(folder)
+ assert data["layout"] == "clef" and data["quantizations"] == ["Q8_0", "Q4_K_M"]
+ assert data["files"] == {
+ "Q8_0": {"model": "model-Q8_0.gguf", "mmproj": "mmproj-Q8_0.gguf"},
+ "Q4_K_M": {"model": "model-Q4_K_M.gguf", "mmproj": "mmproj-Q8_0.gguf"},
+ }
+ assert data["source_fingerprint"] == contract.fingerprint(folder, "clef")
+ # What native serving picks up from the run folder.
+ assert contract.served_files(folder, "clef") == (
+ "Q8_0",
+ out / "model-Q8_0.gguf",
+ out / "mmproj-Q8_0.gguf",
+ )
+ assert sorted(p.name for p in out.iterdir()) == [
+ "export.json",
+ "mmproj-Q8_0.gguf",
+ "model-Q4_K_M.gguf",
+ "model-Q8_0.gguf",
+ ]
+ for name in ("model-Q8_0.gguf", "model-Q4_K_M.gguf"):
+ assert read_decision_temperatures(out / name) == pytest.approx(
+ {"choice": 0.05, "score": 0.025, "noul": 0.05}
+ )
+ # k-quants come from a bf16 intermediate, which is not kept.
+ assert ("quantize", "model-BF16.gguf", "model-Q4_K_M.gguf") in fake_llama_cpp
+ assert not any(p.name.startswith(".unsloth-gguf-") for p in folder.iterdir())
+
+ # Same weights: a later export adds to the earlier one.
+ data = decision_gguf.export_decision_gguf(folder, "f16")
+ assert data["quantizations"] == ["F16", "Q8_0", "Q4_K_M"]
+ # New weights: the old files go.
+ (folder / "joint_head.safetensors").write_bytes(b"retrained")
+ assert contract.served_files(folder, "clef") is None # stale until re-exported
+ data = decision_gguf.export_decision_gguf(folder, "q8_0")
+ assert data["quantizations"] == ["Q8_0"]
+ assert sorted(p.name for p in out.iterdir()) == [
+ "export.json",
+ "mmproj-Q8_0.gguf",
+ "model-Q8_0.gguf",
+ ]
+
+
+@needs_gguf
+def test_laya_export_overwrites_the_converters_raw_temperatures(tmp_path, fake_llama_cpp):
+ folder = _laya_folder(tmp_path / "laya")
+ config = {"temperature": [1.2, 0.3, 1.0], "temperature_by_options": {"choice:11+": 0.1006}}
+ (folder / "rl_agent_config.json").write_text(json.dumps(config))
+ data = decision_gguf.export_decision_gguf(folder, "f16")
+ assert data["files"] == {"F16": {"model": "model-F16.gguf", "mmproj": None}}
+ assert read_decision_temperatures(folder / "gguf" / "model-F16.gguf") == pytest.approx(
+ {"choice": 1.2, "score": 0.5, "noul": 1.0, "choice.11": 0.5}
+ )
+
+
+def test_export_refuses_ineligible_and_adapter_only_folders(tmp_path, fake_llama_cpp):
+ with pytest.raises(ValueError, match = "Qwen3.5"):
+ decision_gguf.export_decision_gguf(
+ _clef_folder(tmp_path / "llama", ("LlamaForCausalLM",)), "q8_0"
+ )
+ base = _clef_folder(tmp_path / "base")
+ adapters = _clef_folder(tmp_path / "adapters", config = {"base_model": str(base)})
+ (adapters / "config.json").unlink()
+ (adapters / "adapter_config.json").write_text("{}")
+ with pytest.raises(ValueError, match = "save_pretrained_gguf"):
+ decision_gguf.export_decision_gguf(adapters, "q8_0")
+ assert fake_llama_cpp == []
+
+
+def _staged(folder: Path) -> list:
+ return sorted(
+ p.name
+ for p in folder.iterdir()
+ if p.name.startswith((".unsloth-merged-", ".unsloth-gguf-"))
+ )
+
+
+def _head_tokens(path: Path) -> int:
+ return int(gguf.GGUFReader(str(path), "r").fields["clef.decision.max_head_tokens"].contents())
+
+
+@needs_gguf
+ "positions, head_max_len, served",
+ [(8192, 96, 256), (300, 96, 150), (None, 400, 400)],
+)
+def test_laya_export_writes_the_head_length_pytorch_serves(
+ tmp_path, fake_llama_cpp, positions, head_max_len, served
+):
+ folder = _laya_folder(tmp_path / "laya")
+ encoder = {"model_type": "modernbert"}
+ if positions is not None:
+ encoder["max_position_embeddings"] = positions
+ (folder / "encoder" / "config.json").write_text(json.dumps(encoder))
+ config = {"temperature": [1.0, 1.0, 1.0], "max_len": 256, "head_max_len": head_max_len}
+ (folder / "rl_agent_config.json").write_text(json.dumps(config))
+ decision_gguf.export_decision_gguf(folder, ["f16", "q4_k_m"])
+ for name in ("model-F16.gguf", "model-Q4_K_M.gguf"):
+ assert _head_tokens(folder / "gguf" / name) == served
+
+
+@needs_gguf
+def test_clef_export_leaves_the_head_length_alone(tmp_path, fake_llama_cpp):
+ folder = _clef_folder(tmp_path / "run")
+ decision_gguf.export_decision_gguf(folder, "q8_0")
+ assert _head_tokens(folder / "gguf" / "model-Q8_0.gguf") == 96
+
+
+@needs_gguf
+def test_metadata_writer_sets_the_head_length_idempotently(tmp_path):
+ path = tmp_path / "model.gguf"
+ _write_gguf(path, {"choice": 1.0}, max_head_tokens = 96)
+ assert write_decision_temperatures(path, {"choice": 1.0}, max_head_tokens = 256) is True
+ assert decision_gguf.read_decision_max_head_tokens(path) == 256
+ assert read_decision_temperatures(path) == {"choice": 1.0}
+ assert write_decision_temperatures(path, {"choice": 1.0}, max_head_tokens = 256) is False
+ with pytest.raises(ValueError):
+ write_decision_temperatures(path, {"choice": 1.0}, max_head_tokens = 0)
+
+
+class _FakeClef:
+ is_clef = True
+
+ def __init__(
+ self,
+ head: bytes,
+ fail = None,
+ ):
+ self.head, self.fail = head, fail
+
+ def _backbone(self):
+ return types.SimpleNamespace(
+ config = types.SimpleNamespace(architectures = ["Qwen3_5ForCausalLM"])
+ )
+
+ def save_pretrained_merged(
+ self,
+ folder,
+ tokenizer = None,
+ **kwargs,
+ ):
+ self.merge_kwargs = kwargs
+ _clef_folder(Path(folder), ("Qwen3_5ForCausalLM",))
+ (Path(folder) / "joint_head.safetensors").write_bytes(self.head)
+ if self.fail is not None:
+ raise self.fail
+
+
+@needs_gguf
+def test_save_adopts_the_folder_only_when_it_holds_the_saved_weights(tmp_path, fake_llama_cpp):
+ folder = _clef_folder(tmp_path / "run", ("Qwen3_5ForCausalLM",))
+ data = decision_gguf.save_pretrained_gguf(_FakeClef(b"head-weights"), folder)
+ assert data["source_fingerprint"] == contract.fingerprint(folder, "clef")
+ assert contract.served_files(folder, "clef") is not None
+
+ # Calibrated or trained in memory since the folder was saved: the folder is stale.
+ data = decision_gguf.save_pretrained_gguf(_FakeClef(b"recalibrated"), folder)
+ assert data["source_fingerprint"] != contract.fingerprint(folder, "clef")
+ assert contract.served_files(folder, "clef") is None
+ assert _staged(folder) == []
+
+
+def _old_llama_cpp(tmp_path: Path) -> Path:
+ old = tmp_path / "old_llama.cpp"
+ old.mkdir()
+ (old / "convert_hf_to_gguf.py").write_text("")
+ return old
+
+
+def _new_llama_cpp(tmp_path: Path) -> Path:
+ good = tmp_path / "new_llama.cpp"
+ (good / "conversion").mkdir(parents = True)
+ (good / "gguf-py" / "gguf").mkdir(parents = True)
+ (good / "convert_hf_to_gguf.py").write_text("")
+ (good / "conversion" / "clef.py").write_text("")
+ (good / "gguf-py" / "gguf" / "constants.py").write_text(
+ 'CLEF = "clef"\nTEMPERATURE = "{arch}.decision.temperature.{name}"\n'
+ )
+ return good
+
+
+def test_kquants_are_refused_before_the_merge_when_llama_cpp_predates_decision(
+ tmp_path, monkeypatch
+):
+ monkeypatch.setattr(decision_gguf, "_converter_dir", lambda *a: tmp_path)
+ monkeypatch.setattr(decision_gguf, "_quantizer", lambda *a: "llama-quantize")
+ old = _old_llama_cpp(tmp_path)
+ monkeypatch.setattr(decision_gguf, "_llama_cpp_folder", lambda: old)
+ model = _FakeClef(b"h")
+ model.save_pretrained_merged = lambda *a, **k: pytest.fail("merged before refusing")
+ out = tmp_path / "out"
+ with pytest.raises(RuntimeError, match = "predates llama.cpp b11443"):
+ decision_gguf.save_pretrained_gguf(model, out, quantization_method = ["q8_0", "q4_k_m"])
+ monkeypatch.setattr(
+ decision_gguf, "_convert", lambda *a: pytest.fail("converted before refusing")
+ )
+ with pytest.raises(RuntimeError, match = "predates llama.cpp b11443"):
+ decision_gguf.export_decision_gguf(_clef_folder(tmp_path / "run"), "q4_k_m")
+
+
+def _fake_quantizer(tmp_path: Path, output: str) -> str:
+ script = tmp_path / "llama-quantize"
+ script.write_text(f"#!{sys.executable}\nprint({output!r}, flush = True)\nraise SystemExit(1)\n")
+ script.chmod(0o755)
+ return str(script)
+
+
[email protected](os.name == "nt", reason = "shebang script")
[email protected]("print_output", [False, True])
+def test_quantize_explains_an_old_quantizer_with_or_without_print_output(
+ tmp_path, monkeypatch, capsys, print_output
+):
+ new = _new_llama_cpp(tmp_path)
+ monkeypatch.setattr(decision_gguf, "_llama_cpp_folder", lambda: new)
+ old = _fake_quantizer(tmp_path, "llama_model_load: error: unknown model architecture: 'clef'")
+ with pytest.raises(RuntimeError, match = "predates llama.cpp b11443"):
+ decision_gguf._quantize(old, tmp_path / "a", tmp_path / "b", "q4_k_m", print_output)
+ assert ("unknown model architecture" in capsys.readouterr().out) == print_output
+ other = _fake_quantizer(tmp_path, "out of disk space")
+ with pytest.raises(RuntimeError, match = "out of disk space") as error:
+ decision_gguf._quantize(other, tmp_path / "a", tmp_path / "b", "q4_k_m", print_output)
+ assert "predates" not in str(error.value)
+
+
+@needs_gguf
+def test_an_interrupted_export_leaves_no_temp_folders(tmp_path, fake_llama_cpp, monkeypatch):
+ folder = _clef_folder(tmp_path / "run", ("Qwen3_5ForCausalLM",))
+
+ def interrupted(*args):
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(decision_gguf, "_convert", interrupted)
+ with pytest.raises(KeyboardInterrupt):
+ decision_gguf.export_decision_gguf(folder, "q8_0")
+ assert _staged(folder) == []
+ with pytest.raises(KeyboardInterrupt):
+ decision_gguf.save_pretrained_gguf(_FakeClef(b"h"), folder)
+ with pytest.raises(KeyboardInterrupt):
+ decision_gguf.save_pretrained_gguf(_FakeClef(b"h", KeyboardInterrupt()), folder)
+ assert _staged(folder) == [] and _staged(folder.parent) == []
+
+
+@needs_gguf
+def test_save_merges_with_the_callers_token(tmp_path, fake_llama_cpp):
+ model = _FakeClef(b"h")
+ decision_gguf.save_pretrained_gguf(model, tmp_path / "a", token = "hf_private")
+ assert model.merge_kwargs == {"token": "hf_private"}
+ decision_gguf.save_pretrained_gguf(model, tmp_path / "b")
+ assert model.merge_kwargs == {}
+
+
+@needs_gguf
+def test_a_failed_publish_keeps_the_export_of_the_same_weights(
+ tmp_path, fake_llama_cpp, monkeypatch
+):
+ folder = _clef_folder(tmp_path / "run")
+ decision_gguf.export_decision_gguf(folder, "q8_0")
+ served = contract.served_files(folder, "clef")
+ replace = os.replace
+
+ def mapped(source, target):
+ # Windows: llama-server has model-Q8_0.gguf mapped, so it cannot be replaced.
+ if Path(target) == folder / "gguf" / "model-Q8_0.gguf":
+ raise PermissionError(13, "The process cannot access the file", str(target))
+ return replace(source, target)
+
+ monkeypatch.setattr(decision_gguf.os, "replace", mapped)
+ with pytest.raises(PermissionError):
+ decision_gguf.export_decision_gguf(folder, ["q8_0", "f16"])
+ monkeypatch.setattr(decision_gguf.os, "replace", replace)
+ assert contract.served_files(folder, "clef") == served
+ assert contract.read_export(folder)["quantizations"] == ["Q8_0"]
+
+ # Other weights: nothing of the old export is current, so nothing is restored.
+ (folder / "joint_head.safetensors").write_bytes(b"retrained")
+ monkeypatch.setattr(decision_gguf.os, "replace", mapped)
+ with pytest.raises(PermissionError):
+ decision_gguf.export_decision_gguf(folder, "q8_0")
+ assert contract.read_export(folder) is None
+
+
+@needs_gguf
+ not hasattr(signal, "SIGKILL") or signal.getsignal(signal.SIGTERM) is not signal.SIG_DFL,
+ reason = "POSIX signals with the default SIGTERM handler",
+)
+def test_sigterm_cleans_up_and_a_killed_export_is_swept_later(
+ tmp_path, fake_llama_cpp, monkeypatch
+):
+ folder = _clef_folder(tmp_path / "run", ("Qwen3_5ForCausalLM",))
+ convert = decision_gguf._convert
+
+ def terminated(*args):
+ decision_gguf._run(
+ [
+ sys.executable,
+ "-c",
+ f"import os, signal, time; os.kill({os.getpid()}, signal.SIGTERM); time.sleep(60)",
+ ],
+ "converting",
+ False,
+ )
+
+ # Studio cancels an export by terminating its worker process.
+ monkeypatch.setattr(decision_gguf, "_convert", terminated)
+ with pytest.raises(SystemExit):
+ decision_gguf.save_pretrained_gguf(_FakeClef(b"h"), folder)
+ assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL
+ assert _staged(folder) == []
+
+ # SIGKILL runs no cleanup: the next export removes what a dead process left.
+ dead = subprocess.Popen([sys.executable, "-c", ""])
+ dead.wait()
+ for prefix in decision_gguf._TEMP_PREFIXES:
+ (folder / f"{prefix}{dead.pid}-x").mkdir()
+ (folder / f"{prefix}{os.getppid()}-alive").mkdir()
+ (folder / f"{prefix}legacy").mkdir()
+ monkeypatch.setattr(decision_gguf, "_convert", convert)
+ decision_gguf.save_pretrained_gguf(_FakeClef(b"h"), folder)
+ assert _staged(folder) == sorted(
+ f"{prefix}{name}"
+ for prefix in decision_gguf._TEMP_PREFIXES
+ for name in (f"{os.getppid()}-alive", "legacy")
+ )
+
+
+def test_eligibility_reads_a_hub_base_with_the_callers_token(tmp_path, monkeypatch):
+ import huggingface_hub
+
+ seen = []
+ config = tmp_path / "config.json"
+ config.write_text(json.dumps({"architectures": ["Qwen3_5ForConditionalGeneration"]}))
+
+ def download(
+ repo,
+ filename,
+ token = None,
+ local_files_only = False,
+ **kwargs,
+ ):
+ seen.append((repo, token, local_files_only))
+ return str(config)
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)
+ adapters = _clef_folder(tmp_path / "adapters", config = {"base_model": "org/private"})
+ (adapters / "config.json").unlink()
+ (adapters / "adapter_config.json").write_text(
+ json.dumps({"base_model_name_or_path": "org/private"})
+ )
+ assert gguf_eligibility(adapters, token = "hf_x", local_files_only = True)["eligible"]
+ assert seen == [("org/private", "hf_x", True)]
diff --git a/tests/test_decision_gguf_real.py b/tests/test_decision_gguf_real.py
new file mode 100644
index 00000000000..b5b52361167
--- /dev/null
+++ b/tests/test_decision_gguf_real.py
@@ -0,0 +1,362 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+# Needs CUDA, llama.cpp >= b11443 at UNSLOTH_LLAMA_CPP_PATH and its llama-server at UNSLOTH_TEST_LLAMA_SERVER.
+
+import json
+import math
+import os
+import random
+import socket
+import subprocess
+import time
+import urllib.request
+from pathlib import Path
+
+import pytest
+from real_accelerator import has_real_cuda
+
+torch = pytest.importorskip("torch")
+
+SERVER = os.environ.get("UNSLOTH_TEST_LLAMA_SERVER", "")
+pytestmark = pytest.mark.skipif(
+ not (has_real_cuda() and SERVER and Path(SERVER).is_file()),
+ reason = "needs CUDA and UNSLOTH_TEST_LLAMA_SERVER",
+)
+REPORT = os.environ.get("UNSLOTH_TEST_GGUF_REPORT")
+TINY_QWEN3_5 = "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration"
+TINY_MODERNBERT = "hf-internal-testing/tiny-random-ModernBertModel"
+QUESTIONS = {
+ "outage": {"type": "noul", "instructions": "Is a service down?"},
+ "team": {
+ "type": "choice",
+ "instructions": "Which team should handle it?",
+ "criteria": {"billing": "payments", "tech": "bugs", "sales": "new orders"},
+ },
+ "mood": {
+ "type": "score",
+ "instructions": "How upset is the customer?",
+ "criteria": ["calm", "annoyed", "angry", "furious"],
+ },
+}
+STATES = (
+ "the server is down again and nothing loads",
+ "my invoice was paid twice please refund",
+ "I want to order ten more licenses",
+ "login page shows an error since this morning",
+)
+GOLD = (("true", "tech", 3), ("false", "billing", 1), ("false", "sales", 0), ("true", "tech", 2))
+
+
+def _rows(
+ n,
+ seed,
+ noise = 0.3,
+):
+ rng = random.Random(seed)
+ rows = []
+ for i in range(n):
+ kind = rng.randrange(len(STATES))
+ outage, team, mood = GOLD[kind]
+ # Label noise, so calibration has something to fit instead of saturating.
+ if rng.random() < noise:
+ outage = rng.choice(["true", "false"])
+ if rng.random() < noise:
+ team = rng.choice(["billing", "tech", "sales"])
+ if rng.random() < noise:
+ mood = rng.randrange(4)
+ rows.append(
+ {
+ "state": f"ticket {i}: {STATES[kind]}",
+ "questions": QUESTIONS,
+ "gold": {"outage": {"label": outage}, "team": {"label": team}, "mood": mood},
+ }
+ )
+ return rows
+
+
+def _free_port():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def _post(url, payload):
+ request = urllib.request.Request(
+ url, data = json.dumps(payload).encode(), headers = {"Content-Type": "application/json"}
+ )
+ with urllib.request.urlopen(request, timeout = 600) as response:
+ return json.loads(response.read())
+
+
+class _Server:
+ def __init__(self, model, mmproj, log):
+ self.port = _free_port()
+ argv = [SERVER, "-m", str(model), "--host", "127.0.0.1", "--port", str(self.port)]
+ argv += ["-c", "16384", "-b", "16384", "-ub", "16384", "-np", "1", "-ngl", "999"]
+ if mmproj:
+ argv += ["--mmproj", str(mmproj)]
+ self.log = Path(log)
+ env = {**os.environ, "LD_LIBRARY_PATH": str(Path(SERVER).resolve().parent)}
+ self.process = subprocess.Popen(
+ argv,
+ stdout = open(self.log, "w"),
+ stderr = subprocess.STDOUT,
+ env = env,
+ start_new_session = True,
+ )
+ deadline = time.time() + 300
+ while time.time() < deadline:
+ if self.process.poll() is not None:
+ raise RuntimeError(f"llama-server exited: {self.log.read_text()[-3000:]}")
+ try:
+ with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/health", timeout = 2) as r:
+ if r.status == 200:
+ return
+ except Exception:
+ time.sleep(0.5)
+ self.close()
+ raise RuntimeError("llama-server did not become ready")
+
+ def decide(self, state, questions):
+ return _post(
+ f"http://127.0.0.1:{self.port}/v1/systemone", {"state": state, "questions": questions}
+ )["answers"]
+
+ def close(self):
+ if self.process.poll() is None:
+ os.killpg(self.process.pid, 15)
+ try:
+ self.process.wait(30)
+ except subprocess.TimeoutExpired:
+ os.killpg(self.process.pid, 9)
+
+
+def _probs(answer):
+ if "noul" in answer and not isinstance(answer["noul"], bool):
+ p = float(answer["noul"])
+ return {"true": p, "false": 1.0 - p}
+ return {str(k): float(v) for k, v in answer["probabilities"].items()}
+
+
+def _gold(row, name):
+ gold = row["gold"][name]
+ return str(gold["label"] if isinstance(gold, dict) else gold)
+
+
+# Ties (near-uniform answers) break by this fixed option order, not by dict order.
+OPTIONS = {
+ name: ["true", "false"]
+ if q["type"] == "noul"
+ else list(q["criteria"])
+ if q["type"] == "choice"
+ else [str(i) for i in range(len(q["criteria"]))]
+ for name, q in QUESTIONS.items()
+}
+
+
+def _top(probs, name):
+ return max(OPTIONS[name], key = probs.get)
+
+
+def _scores(answers, rows):
+ nll, bins = [], [[0, 0.0, 0.0] for _ in range(10)]
+ for answer, row in zip(answers, rows):
+ for name in QUESTIONS:
+ probs = _probs(answer[name])
+ gold = _gold(row, name)
+ nll.append(-math.log(max(probs[gold], 1e-12)))
+ top = _top(probs, name)
+ conf = probs[top]
+ b = bins[min(int(conf * 10), 9)]
+ b[0] += 1
+ b[1] += conf
+ b[2] += float(top == gold)
+ n = sum(b[0] for b in bins)
+ ece = sum(abs(b[1] - b[2]) for b in bins if b[0]) / n
+ return sum(nll) / len(nll), ece
+
+
+def _max_diff(served, reference):
+ worst, same = 0.0, True
+ for got, want in zip(served, reference):
+ for name in QUESTIONS:
+ p, q = _probs(got[name]), _probs(want[name])
+ worst = max(worst, max(abs(p[k] - q[k]) for k in q))
+ # A flip between options PyTorch itself scores within 0.01 is a tie, not a different answer.
+ same &= q[_top(q, name)] - q[_top(p, name)] <= 0.01
+ return worst, same
+
+
+def _serve_and_compare(export_dir, data, reference, rows, label, tmp_path):
+ results = {}
+ for quant in data["quantizations"]:
+ entry = data["files"][quant]
+ mmproj = export_dir / entry["mmproj"] if entry.get("mmproj") else None
+ server = _Server(export_dir / entry["model"], mmproj, tmp_path / f"{label}_{quant}.log")
+ try:
+ served = [server.decide(row["state"], row["questions"]) for row in rows]
+ finally:
+ server.close()
+ worst, same = _max_diff(served, reference)
+ nll, ece = _scores(served, rows)
+ results[quant] = {"max_abs_prob_diff": worst, "same_answers": same, "nll": nll, "ece": ece}
+ nll, ece = _scores(reference, rows)
+ results["pytorch"] = {"nll": nll, "ece": ece}
+ if REPORT:
+ path = Path(REPORT)
+ report = json.loads(path.read_text()) if path.is_file() else {}
+ report[label] = results
+ path.write_text(json.dumps(report, indent = 2))
+ print(label, json.dumps(results, indent = 2))
+ return results
+
+
+def _assert_parity(results, quant, tolerance):
+ # ECE is reported only: it bins by the top answer, so it jumps on near-ties.
+ got = results[quant]
+ assert got["max_abs_prob_diff"] <= tolerance and got["same_answers"], got
+ assert abs(got["nll"] - results["pytorch"]["nll"]) <= tolerance, got
+
+
+def _train(model, tokenizer, rows, tmp_path, steps):
+ from transformers import TrainingArguments
+ from unsloth import DecisionTrainer, FastDecisionModel
+
+ items, _ = FastDecisionModel.build_dataset(rows, tokenizer, model)
+ held = FastDecisionModel.build_dataset(_rows(48, seed = 1), tokenizer, model)[0]
+ DecisionTrainer(
+ model = model,
+ tokenizer = tokenizer,
+ train_dataset = items,
+ head_learning_rate = 5e-3,
+ args = TrainingArguments(
+ output_dir = str(tmp_path / "run"),
+ per_device_train_batch_size = 8,
+ max_steps = steps,
+ learning_rate = 5e-3,
+ report_to = "none",
+ save_strategy = "no",
+ ),
+ ).train()
+ FastDecisionModel.for_inference(model)
+ return FastDecisionModel.calibrate(model, tokenizer, held)
+
+
+def _predict(model, tokenizer, rows):
+ from unsloth import FastDecisionModel
+ return [
+ FastDecisionModel.predict(model, tokenizer, row["state"], row["questions"]) for row in rows
+ ]
+
+
+def test_clef_fine_tune_exports_and_serves_like_pytorch(tmp_path):
+ from transformers import AutoConfig
+ from unsloth import FastDecisionModel
+ from unsloth.models.decision_gguf import read_decision_temperatures, write_decision_temperatures
+
+ hidden = AutoConfig.from_pretrained(TINY_QWEN3_5).text_config.hidden_size
+ head = {
+ "hidden_size": hidden,
+ "width": 64,
+ "routing_layers": 1,
+ "layers": 1,
+ "heads": 4,
+ "feedforward": 128,
+ }
+ model, processor = FastDecisionModel.from_pretrained(
+ TINY_QWEN3_5, decision_head = "clef", head_config = head, max_seq_length = 512
+ )
+ model = FastDecisionModel.get_peft_model(model, r = 8, lora_alpha = 16)
+ calibration = _train(model, processor, _rows(96, seed = 0), tmp_path, steps = 30)
+ rows = _rows(16, seed = 2)
+ config = model.decision_config
+ print("calibration", calibration, config.get("head_temperature"), config.get("temperature"))
+
+ reference = _predict(model, processor, rows)
+ data = model.save_pretrained_gguf(
+ tmp_path / "clef", processor, quantization_method = ["q8_0", "q4_k_m"]
+ )
+ export_dir = tmp_path / "clef" / "gguf"
+ assert data["quantizations"] == ["Q8_0", "Q4_K_M"]
+ assert data["files"]["Q8_0"]["mmproj"] == "mmproj-Q8_0.gguf"
+ results = _serve_and_compare(export_dir, data, reference, rows, "clef_calibrated", tmp_path)
+ # Q8_0 moved a sharply calibrated Clef-Flash fine-tune by 0.045 (BF16: 0.0047).
+ _assert_parity(results, "Q8_0", 0.05)
+
+ # Just under the 0.05 fold floor: the head temperature lives only in the config, so the GGUF must carry it.
+ with torch.no_grad():
+ model.head.joint_logit_scale.fill_(math.log(5.5))
+ config["head_temperature"] = 0.05
+ # 0.05 x 5.0 = 0.25: under laya's 0.5 floor, so re-clamping the product would show.
+ config["temperature"] = [5.0, 5.0, 5.0]
+ reference = _predict(model, processor, rows)
+ data = model.save_pretrained_gguf(
+ tmp_path / "floor", processor, quantization_method = ["bf16", "q8_0"]
+ )
+ export_dir = tmp_path / "floor" / "gguf"
+ floor = {"choice": 0.25, "score": 0.25, "noul": 0.25}
+ assert read_decision_temperatures(export_dir / "model-BF16.gguf") == pytest.approx(floor)
+ results = _serve_and_compare(export_dir, data, reference, rows, "clef_floor", tmp_path)
+ # Temperature 0.25 multiplies logit rounding by 4 (measured 0.0087 and 0.0105); the control drifts > 0.1.
+ _assert_parity(results, "BF16", 0.02)
+
+ # Negative control: the same file without the keys, as the converter alone writes it.
+ write_decision_temperatures(export_dir / "model-BF16.gguf", {})
+ control = {**data, "quantizations": ["BF16"]}
+ results = _serve_and_compare(
+ export_dir, control, reference, rows, "clef_floor_without_keys", tmp_path
+ )
+ assert results["BF16"]["max_abs_prob_diff"] > 0.1
+
+
+def _tiny_laya(folder: Path) -> Path:
+ from huggingface_hub import snapshot_download
+ from safetensors.torch import save_file
+ from transformers import AutoConfig, AutoTokenizer
+ from unsloth.models.decision import _laya
+
+ source = snapshot_download(TINY_MODERNBERT, allow_patterns = ["*.json", "*.txt"])
+ (folder / "encoder").mkdir(parents = True)
+ config = AutoConfig.from_pretrained(source)
+ (folder / "encoder" / "config.json").write_text(config.to_json_string())
+ AutoTokenizer.from_pretrained(source).save_pretrained(str(folder / "tokenizer"))
+ decision_config = {
+ "encoder": TINY_MODERNBERT,
+ "head_layers": 1,
+ "act_costs": {"escalate": 0.5},
+ "max_len": 256,
+ "head_max_len": 96,
+ "temperature": [1.0, 1.0, 1.0],
+ "temperature_by_options": {"choice:3-5": 0.1006, "score:3-5": 0.8},
+ }
+ torch.manual_seed(0)
+ model = _laya().common.build_model(decision_config, encoder_dir = str(folder / "encoder"))
+ save_file(
+ {k: v.half().contiguous() for k, v in model.state_dict().items()},
+ str(folder / "model.safetensors"),
+ )
+ (folder / "rl_agent_config.json").write_text(json.dumps(decision_config))
+ return folder
+
+
+def test_laya_fine_tune_exports_and_serves_like_pytorch(tmp_path):
+ from unsloth import FastDecisionModel
+ from unsloth.models.decision_gguf import read_decision_temperatures
+
+ base = _tiny_laya(tmp_path / "laya_base")
+ model, tokenizer = FastDecisionModel.from_pretrained(str(base), full_finetuning = True)
+ _train(model, tokenizer, _rows(96, seed = 0), tmp_path, steps = 30)
+ # One bucket survives calibration only if its type was not refitted; keep one to test buckets.
+ model.decision_config["temperature_by_options"] = {"choice:3-5": 0.1006}
+ rows = _rows(16, seed = 2)
+ reference = _predict(model, tokenizer, rows)
+ data = model.save_pretrained_gguf(
+ tmp_path / "laya", tokenizer, quantization_method = ["f16", "q8_0"]
+ )
+ export_dir = tmp_path / "laya" / "gguf"
+ temperatures = read_decision_temperatures(export_dir / "model-F16.gguf")
+ assert temperatures["choice.3_5"] == pytest.approx(0.5)
+ results = _serve_and_compare(export_dir, data, reference, rows, "laya", tmp_path)
+ _assert_parity(results, "F16", 0.01)
+ assert results["Q8_0"]["max_abs_prob_diff"] <= 0.02
diff --git a/unsloth/models/decision.py b/unsloth/models/decision.py
index a10ff3d00e4..a5393f9ad06 100644
--- a/unsloth/models/decision.py
+++ b/unsloth/models/decision.py
@@ -1127,6 +1127,7 @@ def _save_clef(
self,
save_directory,
tokenizer,
+ token = None,
exact = False,
) -> None:
import shutil
@@ -1138,7 +1139,12 @@ def _save_clef(
encoder = self.encoder
if hasattr(encoder, "save_pretrained_merged"):
# Unsloth's merge dequantizes a 4-bit base and writes the processor files too.
- encoder.save_pretrained_merged(str(staging), tokenizer, save_method = "merged_16bit")
+ encoder.save_pretrained_merged(
+ str(staging),
+ tokenizer,
+ save_method = "merged_16bit",
+ **({} if token is None else {"token": token}),
+ )
# A merge with local_dir = the save folder leaves huggingface_hub's .cache behind.
shutil.rmtree(staging / ".cache", ignore_errors = True)
else:
@@ -1266,6 +1272,13 @@ def _attach_clef_saving(model) -> None:
model.save_pretrained_merged = types.MethodType(save_pretrained_merged, model)
model.push_to_hub = types.MethodType(push_to_hub_clef, model)
model.push_to_hub_merged = types.MethodType(push_to_hub_merged, model)
+ _attach_gguf_saving(model)
+
+
+def _attach_gguf_saving(model) -> None:
+ from .decision_gguf import push_to_hub_gguf, save_pretrained_gguf
+ model.save_pretrained_gguf = types.MethodType(save_pretrained_gguf, model)
+ model.push_to_hub_gguf = types.MethodType(push_to_hub_gguf, model)
def _clef_mixed_precision(model, args) -> None:
@@ -1689,6 +1702,17 @@ def _calibrate_clef(config: dict, logits, items) -> dict:
return {**_metrics(logits, items, per_item), "fitted_types": sorted(fitted)}
+def _served_lengths(
+ config: dict,
+ positions: int,
+ max_seq_length = None,
+) -> tuple:
+ """(max_len, head_max_len) a Laya checkpoint serves with once loaded."""
+ wanted = max_seq_length or max(int(config.get("max_len", 512)), TRAIN_MAX_LEN)
+ max_len = min(int(positions), int(wanted))
+ return max_len, min(max_len // 2, max(int(config.get("head_max_len", 192)), TRAIN_HEAD_MAX_LEN))
+
+
def save_pretrained_merged(
self,
save_directory,
@@ -1704,7 +1728,7 @@ def save_pretrained_merged(
)
tokenizer = self._saved_temp_tokenizer if tokenizer is None else tokenizer
if getattr(self, "is_clef", False):
- return _save_clef(self, save_directory, tokenizer)
+ return _save_clef(self, save_directory, tokenizer, kwargs.get("token"))
encoder = self.encoder
if hasattr(encoder, "merge_and_unload"):
# Merged on a CPU copy: the model keeps its adapters and the GPU never holds a second encoder.
@@ -1854,10 +1878,8 @@ class FastDecisionModel:
model.encoder.config.reference_compile = False
positions = int(getattr(model.encoder.config, "max_position_embeddings", TRAIN_MAX_LEN))
- wanted = max_seq_length or max(int(config.get("max_len", 512)), TRAIN_MAX_LEN)
- config["max_len"] = min(positions, int(wanted))
- config["head_max_len"] = min(
- config["max_len"] // 2, max(int(config.get("head_max_len", 192)), TRAIN_HEAD_MAX_LEN)
+ config["max_len"], config["head_max_len"] = _served_lengths(
+ config, positions, max_seq_length
)
model.decision_config = config
@@ -1879,6 +1901,7 @@ class FastDecisionModel:
)
model.save_pretrained_merged = types.MethodType(save_pretrained_merged, model)
model.push_to_hub_merged = types.MethodType(push_to_hub_merged, model)
+ _attach_gguf_saving(model)
return model, tokenizer
@staticmethod
diff --git a/unsloth/models/decision_gguf.py b/unsloth/models/decision_gguf.py
new file mode 100644
index 00000000000..3270520f543
--- /dev/null
+++ b/unsloth/models/decision_gguf.py
@@ -0,0 +1,847 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+# Decision model (Clef, Laya) GGUF export for llama.cpp's /v1/systemone: the upstream converter writes
+# the graph, then the temperatures PyTorch serving applies are written, which the Clef converter drops.
+
+__all__ = [
+ "DECISION_GGUF_QUANTIZATIONS",
+ "gguf_eligibility",
+ "effective_temperatures",
+ "read_decision_temperatures",
+ "write_decision_temperatures",
+ "read_decision_max_head_tokens",
+ "export_decision_gguf",
+ "save_pretrained_gguf",
+ "push_to_hub_gguf",
+]
+
+import collections
+import contextlib
+import functools
+import importlib.util
+import json
+import math
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+import uuid
+from pathlib import Path
+from typing import Optional
+
+DECISION_GGUF_QUANTIZATIONS = ("q8_0", "f16", "bf16", "q6_k", "q5_k_m", "q4_k_m")
+# Written by convert_hf_to_gguf.py itself; the rest go through llama-quantize.
+_OUTTYPES = ("q8_0", "f16", "bf16")
+# The first llama.cpp release with the Clef converter, the Decision GGUF keys and /v1/systemone.
+DECISION_LLAMA_CPP_TAG = "b11443"
+# llama.cpp's Clef graph and converter (conversion/clef.py: ClefModel(Qwen3_5TextModel)).
+_CLEF_ARCHITECTURES = ("Qwen3_5ForConditionalGeneration", "Qwen3_5ForCausalLM")
+_QTYPES = ("choice", "score", "noul")
+# laya.common.temp_bucket's sizes, written as the llama.cpp converter names them.
+_BUCKETS = {"2": "2", "3-5": "3_5", "6-10": "6_10", "11+": "11"}
+# Followed by "<pid>-": a later export removes the ones whose process died (SIGKILL, power loss).
+_TEMP_PREFIXES = (".unsloth-merged-", ".unsloth-gguf-")
+_CONTRACT_FILE = (
+ Path(__file__).resolve().parents[2]
+ / "studio"
+ / "backend"
+ / "core"
+ / "systemone"
+ / "gguf_export_contract.py"
+)
+
+
[email protected]_cache(maxsize = None)
+def _contract():
+ # By path: it is standard library only, and importing Studio's package would pull in its server.
+ spec = importlib.util.spec_from_file_location("unsloth._decision_gguf_contract", _CONTRACT_FILE)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _quantizations(quantization_method) -> list:
+ methods = [quantization_method] if isinstance(quantization_method, str) else quantization_method
+ if not methods:
+ raise ValueError("Unsloth: quantization_method is empty.")
+ chosen = []
+ for method in methods:
+ method = str(method).strip().lower()
+ if method not in DECISION_GGUF_QUANTIZATIONS:
+ raise ValueError(
+ f"Unsloth: decision models export to GGUF as one of {list(DECISION_GGUF_QUANTIZATIONS)}, "
+ f"not {method!r}."
+ )
+ if method not in chosen:
+ chosen.append(method)
+ return chosen
+
+
+def _read_json(path: Path) -> dict:
+ return json.loads(path.read_text(encoding = "utf-8"))
+
+
+def _layout(folder: Path) -> Optional[str]:
+ from .decision import is_clef_checkpoint, is_decision_checkpoint
+ if is_clef_checkpoint(folder):
+ return "clef"
+ return "laya" if is_decision_checkpoint(folder) else None
+
+
+def _base_config(
+ base: str,
+ token = None,
+ local_files_only = False,
+) -> Optional[dict]:
+ local = Path(base).expanduser()
+ if (local / "config.json").is_file():
+ return _read_json(local / "config.json")
+ try:
+ from huggingface_hub import hf_hub_download
+ return _read_json(
+ Path(
+ hf_hub_download(base, "config.json", token = token, local_files_only = local_files_only)
+ )
+ )
+ except Exception:
+ return None
+
+
+def _clef_backbone_config(
+ folder: Path,
+ token = None,
+ local_files_only = False,
+) -> Optional[dict]:
+ if (folder / "config.json").is_file():
+ return _read_json(folder / "config.json")
+ # Adapters only: the backbone is the base they were trained on.
+ base = None
+ if (folder / "unsloth_decision_config.json").is_file():
+ base = _read_json(folder / "unsloth_decision_config.json").get("base_model")
+ if not base and (folder / "adapter_config.json").is_file():
+ base = _read_json(folder / "adapter_config.json").get("base_model_name_or_path")
+ return _base_config(str(base), token, local_files_only) if base else None
+
+
+def _clef_reason(architectures) -> Optional[str]:
+ architectures = list(architectures or [])
+ if any(name in _CLEF_ARCHITECTURES for name in architectures):
+ return None
+ return (
+ f"Unsloth: GGUF export of this decision model is not supported: llama.cpp's decision "
+ f"graph is built for Qwen3.5 backbones only, and this one is {', '.join(architectures) or 'unknown'}. "
+ "It still serves through PyTorch (FastDecisionModel.predict, or Studio's Decision API)."
+ )
+
+
+def _laya_reason(model_type) -> str:
+ return (
+ f"Unsloth: GGUF export of Laya decision models needs a ModernBERT encoder "
+ f"(llama.cpp's ModernBertDecisionModel), and this one is {model_type or 'unknown'}. "
+ "It still serves through PyTorch."
+ )
+
+
+def gguf_eligibility(
+ source,
+ token = None,
+ local_files_only = False,
+) -> dict:
+ """{"eligible", "layout", "reason"} for a decision model or an on-disk decision checkpoint."""
+ if not isinstance(source, (str, os.PathLike)):
+ if getattr(source, "is_clef", False):
+ reason = _clef_reason(getattr(source._backbone().config, "architectures", None))
+ return {"eligible": reason is None, "layout": "clef", "reason": reason}
+ model_type = getattr(getattr(source.encoder, "config", None), "model_type", None)
+ reason = None if model_type == "modernbert" else _laya_reason(model_type)
+ return {"eligible": reason is None, "layout": "laya", "reason": reason}
+ folder = Path(source)
+ layout = _layout(folder)
+ if layout is None:
+ return {
+ "eligible": False,
+ "layout": None,
+ "reason": f"Unsloth: {folder} is not a decision model checkpoint.",
+ }
+ if layout == "laya":
+ encoder = folder / "encoder" / "config.json"
+ model_type = _read_json(encoder).get("model_type") if encoder.is_file() else None
+ reason = None if model_type == "modernbert" else _laya_reason(model_type)
+ return {"eligible": reason is None, "layout": "laya", "reason": reason}
+ config = _clef_backbone_config(folder, token, local_files_only)
+ if config is None:
+ return {
+ "eligible": False,
+ "layout": "clef",
+ "reason": f"Unsloth: could not read the backbone config of {folder}, so it cannot be exported to GGUF.",
+ }
+ reason = _clef_reason(config.get("architectures"))
+ return {"eligible": reason is None, "layout": "clef", "reason": reason}
+
+
+def _positive(value, name: str) -> float:
+ try:
+ value = float(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"Unsloth: {name} = {value!r} is not a number.") from None
+ if not math.isfinite(value) or value <= 0.0:
+ raise ValueError(f"Unsloth: {name} = {value!r} is not a finite positive temperature.")
+ return value
+
+
+def effective_temperatures(config: dict, layout: str) -> dict:
+ """The temperature PyTorch serving divides each question type's logits by
+ (decision._served_temperatures), keyed as llama.cpp reads them after
+ "<arch>.decision.temperature.": "<type>" and "<type>.<option-count bucket>"."""
+ from .decision import _laya
+
+ clamp = _laya().common.clamp_temperature
+ # Clef only: a head temperature _fold_temperature could not fold into the weights.
+ head = (
+ _positive(config.get("head_temperature", 1.0), "head_temperature")
+ if layout == "clef"
+ else 1.0
+ )
+ per_type = config.get("temperature", [1.0] * 3)
+ if not isinstance(per_type, (list, tuple)) or len(per_type) != len(_QTYPES):
+ raise ValueError(
+ f"Unsloth: temperature = {per_type!r} must hold one value per question type {_QTYPES}."
+ )
+ out = {name: head * clamp(value) for name, value in zip(_QTYPES, per_type)}
+ buckets = config.get("temperature_by_options") or {}
+ if not isinstance(buckets, dict):
+ raise ValueError(f"Unsloth: temperature_by_options = {buckets!r} is not a mapping.")
+ for key, value in buckets.items():
+ qtype, _, size = str(key).partition(":")
+ if qtype not in _QTYPES or size not in _BUCKETS:
+ # laya.common.temp_bucket never produces it, so PyTorch never applies it either.
+ continue
+ out[f"{qtype}.{_BUCKETS[size]}"] = head * clamp(value)
+ for name, value in out.items():
+ _positive(value, f"temperature {name}")
+ return out
+
+
+def _import_gguf(gguf_py: Optional[Path] = None):
+ if gguf_py is not None and str(gguf_py) not in sys.path:
+ try:
+ import gguf # noqa: F401
+ except ImportError:
+ sys.path.insert(0, str(gguf_py))
+ import gguf
+ from gguf.scripts.gguf_new_metadata import MetadataDetails, copy_with_new_metadata
+
+ return gguf, MetadataDetails, copy_with_new_metadata
+
+
+def _temperature_fields(reader, gguf) -> tuple:
+ arch = reader.fields[gguf.Keys.General.ARCHITECTURE].contents()
+ prefix = f"{arch}.decision.temperature."
+ found = {
+ name[len(prefix) :]: float(field.contents())
+ for name, field in reader.fields.items()
+ if name.startswith(prefix)
+ }
+ return arch, prefix, found
+
+
+def _max_head_tokens(reader, arch) -> Optional[int]:
+ field = reader.fields.get(f"{arch}.decision.max_head_tokens")
+ return None if field is None else int(field.contents())
+
+
+def read_decision_temperatures(gguf_file, gguf_py = None) -> dict:
+ gguf, _, _ = _import_gguf(gguf_py)
+ reader = gguf.GGUFReader(str(gguf_file), "r")
+ try:
+ return _temperature_fields(reader, gguf)[2]
+ finally:
+ del reader
+
+
+def read_decision_max_head_tokens(gguf_file, gguf_py = None) -> Optional[int]:
+ gguf, _, _ = _import_gguf(gguf_py)
+ reader = gguf.GGUFReader(str(gguf_file), "r")
+ try:
+ return _max_head_tokens(reader, _temperature_fields(reader, gguf)[0])
+ finally:
+ del reader
+
+
+def _same(found: dict, wanted: dict) -> bool:
+ import numpy as np
+ return set(found) == set(wanted) and all(
+ np.float32(found[name]) == np.float32(wanted[name]) for name in wanted
+ )
+
+
+def write_decision_temperatures(
+ gguf_file,
+ temperatures: dict,
+ gguf_py = None,
+ max_head_tokens: Optional[int] = None,
+) -> bool:
+ """Replaces every <arch>.decision.temperature.* key with `temperatures` (and
+ <arch>.decision.max_head_tokens when given); everything else is copied unchanged. Atomic
+ (temp file in the same folder, then os.replace). False if the file already held these values."""
+ gguf, MetadataDetails, copy_with_new_metadata = _import_gguf(gguf_py)
+ gguf_file = Path(gguf_file)
+ wanted = {name: _positive(value, f"temperature {name}") for name, value in temperatures.items()}
+ if max_head_tokens is not None and (
+ int(max_head_tokens) != max_head_tokens or max_head_tokens < 1
+ ):
+ raise ValueError(
+ f"Unsloth: max_head_tokens = {max_head_tokens!r} is not a positive integer."
+ )
+ reader = gguf.GGUFReader(str(gguf_file), "r")
+ arch, prefix, found = _temperature_fields(reader, gguf)
+ head_key = f"{arch}.decision.max_head_tokens"
+ if _same(found, wanted) and max_head_tokens in (None, _max_head_tokens(reader, arch)):
+ del reader
+ return False
+ remove = [prefix + name for name in found]
+ new = {
+ prefix + name: MetadataDetails(gguf.GGUFValueType.FLOAT32, value)
+ for name, value in sorted(wanted.items())
+ }
+ if max_head_tokens is not None:
+ new[head_key] = MetadataDetails(gguf.GGUFValueType.UINT32, int(max_head_tokens))
+ tmp = gguf_file.with_name(f".{gguf_file.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp")
+ try:
+ writer = gguf.GGUFWriter(tmp, arch = arch, endianess = reader.endianess)
+ copy_with_new_metadata(reader, writer, new, remove)
+ del reader, writer
+ if not _same(read_decision_temperatures(tmp, gguf_py), wanted) or max_head_tokens not in (
+ None,
+ read_decision_max_head_tokens(tmp, gguf_py),
+ ):
+ raise RuntimeError(
+ f"Unsloth: the decision metadata did not survive rewriting {gguf_file}."
+ )
+ shutil.copymode(gguf_file, tmp)
+ os.replace(tmp, gguf_file)
+ except BaseException:
+ Path(tmp).unlink(missing_ok = True)
+ raise
+ return True
+
+
+def _supports_decision(converter_dir: Path) -> bool:
+ constants = converter_dir / "gguf-py" / "gguf" / "constants.py"
+ if not (
+ (converter_dir / "convert_hf_to_gguf.py").is_file()
+ and (converter_dir / "conversion" / "clef.py").is_file()
+ and constants.is_file()
+ ):
+ return False
+ text = constants.read_text(encoding = "utf-8", errors = "replace")
+ return "{arch}.decision.temperature.{name}" in text and "CLEF" in text
+
+
+def _llama_cpp_folder() -> Path:
+ try:
+ from unsloth_zoo.llama_cpp import LLAMA_CPP_DEFAULT_DIR
+ except ImportError:
+ LLAMA_CPP_DEFAULT_DIR = os.environ.get(
+ "UNSLOTH_LLAMA_CPP_PATH", os.path.join(str(Path.home()), ".unsloth", "llama.cpp")
+ )
+ return Path(LLAMA_CPP_DEFAULT_DIR)
+
+
+def _converter_dir(print_output = False) -> Path:
+ """convert_hf_to_gguf.py + conversion/ + gguf-py/ from one llama.cpp revision with decision models."""
+ pinned = os.environ.get("UNSLOTH_LLAMA_CPP_SCRIPTS_DIR", "").strip()
+ candidates = [Path(pinned)] if pinned else []
+ candidates.append(_llama_cpp_folder())
+ for folder in candidates:
+ if _supports_decision(folder):
+ return folder
+ tag = os.environ.get("UNSLOTH_LLAMA_CPP_CONVERTER_TAG", "").strip() or DECISION_LLAMA_CPP_TAG
+ stage = None
+ try:
+ from unsloth_zoo.llama_cpp import _stage_converter_sources
+ stage = _stage_converter_sources(tag)
+ except Exception as error:
+ if print_output:
+ print(f"Unsloth: could not stage llama.cpp {tag} converter sources: {error}")
+ if stage is not None and _supports_decision(Path(stage)):
+ print(
+ f"Unsloth: the llama.cpp at {candidates[-1]} cannot convert decision models; "
+ f"using the llama.cpp {tag} converter sources staged at {stage}."
+ )
+ return Path(stage)
+ raise RuntimeError(
+ f"Unsloth: decision model GGUF export needs llama.cpp {DECISION_LLAMA_CPP_TAG} or newer "
+ f"(conversion/clef.py and gguf-py's decision keys), and {', '.join(map(str, candidates))} "
+ "does not have them. Delete that folder so Unsloth reinstalls llama.cpp, or point "
+ "UNSLOTH_LLAMA_CPP_SCRIPTS_DIR at a llama.cpp checkout of that tag."
+ )
+
+
+def _quantizer(print_output = False) -> str:
+ from unsloth_zoo.llama_cpp import check_llama_cpp, install_llama_cpp
+ folder = _llama_cpp_folder()
+ try:
+ return check_llama_cpp(llama_cpp_folder = str(folder))[0]
+ except Exception:
+ print("Unsloth: Installing llama.cpp. This might take 3 minutes...")
+ # As save.py: quantizing needs no CUDA build.
+ return install_llama_cpp(
+ llama_cpp_folder = str(folder), gpu_support = False, print_output = print_output
+ )[0]
+
+
+class _RunError(RuntimeError):
+ def __init__(self, message: str, output: str):
+ super().__init__(message)
+ self.output = output
+
+
+def _run(
+ command: list,
+ what: str,
+ print_output: bool,
+ env = None,
+) -> None:
+ if print_output:
+ print("Unsloth: running", " ".join(map(str, command)))
+ # Captured even when echoed, so a failure can be explained from the output.
+ process = subprocess.Popen(
+ [str(part) for part in command],
+ env = env,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ )
+ lines = collections.deque(maxlen = 500)
+ try:
+ for line in process.stdout:
+ if print_output:
+ print(line, end = "", flush = True)
+ lines.append(line.rstrip("\n"))
+ returncode = process.wait()
+ except BaseException:
+ process.kill()
+ process.wait()
+ raise
+ finally:
+ process.stdout.close()
+ if returncode != 0:
+ tail = "\n".join(list(lines)[-30:])
+ raise _RunError(f"Unsloth: {what} failed (exit {returncode}).\n{tail}", "\n".join(lines))
+
+
+def _convert(
+ converter: Path, folder: Path, outtype: str, outfile: Path, mmproj: bool, print_output: bool
+) -> None:
+ env = {k: v for k, v in os.environ.items() if k != "NO_LOCAL_GGUF"}
+ env["PYTHONPATH"] = os.pathsep.join(
+ [str(converter / "gguf-py")] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])
+ )
+ command = [
+ sys.executable,
+ converter / "convert_hf_to_gguf.py",
+ folder,
+ "--outtype",
+ outtype,
+ "--outfile",
+ outfile,
+ ]
+ if mmproj:
+ command.append("--mmproj")
+ _run(command, f"converting {folder} to {outfile.name}", print_output, env)
+ if not outfile.is_file():
+ raise RuntimeError(f"Unsloth: the llama.cpp converter did not write {outfile}.")
+
+
+def _predates(quantizer: str, method: str) -> RuntimeError:
+ return RuntimeError(
+ f"Unsloth: {quantizer} predates llama.cpp {DECISION_LLAMA_CPP_TAG}, so it cannot "
+ f"quantize decision models to {method}. Update llama.cpp (delete {_llama_cpp_folder()} "
+ "so Unsloth reinstalls it), or export as q8_0, f16 or bf16."
+ )
+
+
+def _kquant_quantizer(kquants: list, print_output = False) -> str:
+ """llama-quantize, refused up front when its llama.cpp folder predates decision models."""
+ quantizer = _quantizer(print_output)
+ if not _supports_decision(_llama_cpp_folder()):
+ raise _predates(quantizer, kquants[0])
+ return quantizer
+
+
+def _quantize(quantizer: str, source: Path, target: Path, method: str, print_output: bool) -> None:
+ try:
+ _run(
+ [quantizer, source, target, method.upper()],
+ f"quantizing to {method.upper()}",
+ print_output,
+ )
+ except _RunError as error:
+ if "unknown model architecture" in error.output or not _supports_decision(
+ _llama_cpp_folder()
+ ):
+ raise _predates(quantizer, method) from error
+ raise
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ import psutil
+ except ImportError:
+ # os.kill(pid, 0) terminates the process on Windows.
+ if os.name == "nt":
+ return True
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except OSError:
+ return True
+ return True
+ return psutil.pid_exists(pid)
+
+
+def _remove_abandoned_temp(folder: Path) -> None:
+ try:
+ entries = list(folder.iterdir())
+ except OSError:
+ return
+ for entry in entries:
+ prefix = next((p for p in _TEMP_PREFIXES if entry.name.startswith(p)), None)
+ if prefix is None:
+ continue
+ pid = entry.name[len(prefix) :].partition("-")[0]
+ if not pid.isdigit() or int(pid) == os.getpid() or _pid_alive(int(pid)):
+ continue
+ if entry.is_dir() and not entry.is_symlink():
+ shutil.rmtree(entry, ignore_errors = True)
+
+
+def _temp_prefix(prefix: str) -> str:
+ return f"{prefix}{os.getpid()}-"
+
+
+def _exit_on_sigterm():
+ """SIGTERM (Studio's cancel, `kill`) raises SystemExit, so temp folders and child processes are
+ cleaned up; only where no handler is installed and only on the main thread."""
+ sigterm = getattr(signal, "SIGTERM", None)
+ if (
+ sigterm is None
+ or threading.current_thread() is not threading.main_thread()
+ or signal.getsignal(sigterm) is not signal.SIG_DFL
+ ):
+ yield
+ return
+
+ def _raise(signum, frame):
+ raise SystemExit(128 + signum)
+
+ signal.signal(sigterm, _raise)
+ try:
+ yield
+ finally:
+ signal.signal(sigterm, signal.SIG_DFL)
+
+
+def _has_vision(folder: Path) -> bool:
+ config = folder / "config.json"
+ return config.is_file() and _read_json(config).get("vision_config") is not None
+
+
+def _decision_config(folder: Path, layout: str) -> dict:
+ name = "unsloth_decision_config.json" if layout == "clef" else "rl_agent_config.json"
+ path = folder / name
+ return _read_json(path) if path.is_file() else {}
+
+
+def _write_export(output: Path, layout: str, files: dict, source_fingerprint: str) -> dict:
+ # In the format gguf_export_contract.read_export accepts; written last, atomically.
+ contract = _contract()
+ data = {
+ "format": contract.FORMAT,
+ "version": contract.VERSION,
+ "layout": layout,
+ "quantizations": list(files),
+ "files": {q: {"model": e["model"], "mmproj": e.get("mmproj")} for q, e in files.items()},
+ "source_fingerprint": source_fingerprint,
+ }
+ # open(..., "x") rather than mkstemp: the file gets the umask's mode, not 0600.
+ tmp = output / f".export-{os.getpid()}-{uuid.uuid4().hex[:8]}.json"
+ try:
+ with open(tmp, "x", encoding = "utf-8") as f:
+ json.dump(data, f, indent = 2)
+ os.replace(tmp, output / contract.EXPORT_FILE)
+ except BaseException:
+ tmp.unlink(missing_ok = True)
+ raise
+ return data
+
+
+def _laya_max_head_tokens(folder: Path, config: dict) -> int:
+ # The converter writes the raw head_max_len; PyTorch serves FastDecisionModel's normalised one.
+ from .decision import TRAIN_MAX_LEN, _served_lengths
+
+ encoder = folder / "encoder" / "config.json"
+ positions = _read_json(encoder).get("max_position_embeddings") if encoder.is_file() else None
+ return _served_lengths(config, positions or TRAIN_MAX_LEN)[1]
+
+
+def export_decision_gguf(
+ checkpoint_folder,
+ quantization_method = "q8_0",
+ output_dir = None,
+ source_folder = None,
+ print_output = False,
+) -> dict:
+ """Converts a merged decision checkpoint (Clef or Laya layout) to GGUF in output_dir
+ (default <checkpoint_folder>/gguf): model-<QUANT>.gguf, mmproj-<QUANT>.gguf for a Clef
+ vision tower, and export.json, written last. Returns export.json's content."""
+ with _exit_on_sigterm():
+ return _export_decision_gguf(
+ checkpoint_folder, quantization_method, output_dir, source_folder, print_output
+ )
+
+
+def _export_decision_gguf(
+ checkpoint_folder, quantization_method, output_dir, source_folder, print_output
+) -> dict:
+ contract = _contract()
+ folder = Path(checkpoint_folder)
+ quants = _quantizations(quantization_method)
+ eligibility = gguf_eligibility(folder)
+ if not eligibility["eligible"]:
+ raise ValueError(eligibility["reason"])
+ layout = eligibility["layout"]
+ if layout == "clef" and not (folder / "config.json").is_file():
+ raise ValueError(
+ f"Unsloth: {folder} holds LoRA adapters only; load it with FastDecisionModel and call "
+ "save_pretrained_gguf, which merges them first."
+ )
+ config = _decision_config(folder, layout)
+ temperatures = effective_temperatures(config, layout)
+ max_head_tokens = _laya_max_head_tokens(folder, config) if layout == "laya" else None
+ source = Path(source_folder) if source_folder is not None else folder
+ source_fingerprint = contract.fingerprint(source, layout)
+ converter = _converter_dir(print_output)
+ gguf_py = converter / "gguf-py"
+ kquants = [q for q in quants if q not in _OUTTYPES]
+ quantizer = _kquant_quantizer(kquants, print_output) if kquants else None
+ vision = layout == "clef" and _has_vision(folder)
+ output = Path(output_dir) if output_dir is not None else folder / contract.EXPORT_DIR
+ output.mkdir(parents = True, exist_ok = True)
+
+ def model_name(quant):
+ return f"model-{quant.upper()}.gguf"
+
+ def mmproj_name(quant):
+ # llama-quantize does not quantize vision towers: a k-quant ships the Q8_0 one.
+ return f"mmproj-{(quant if quant in _OUTTYPES else 'q8_0').upper()}.gguf"
+
+ files = {}
+ _remove_abandoned_temp(output.parent)
+ staging = Path(tempfile.mkdtemp(prefix = _temp_prefix(".unsloth-gguf-"), dir = output.parent))
+ try:
+ # Laya weights are float16; Clef's Qwen3.5 backbone is bfloat16.
+ intermediate = "bf16" if layout == "clef" else "f16"
+ outtypes = [q for q in quants if q in _OUTTYPES]
+ if kquants and intermediate not in outtypes:
+ outtypes.append(intermediate)
+ for outtype in outtypes:
+ target = staging / model_name(outtype)
+ print(f"Unsloth: converting the decision model to {outtype.upper()} GGUF...")
+ _convert(converter, folder, outtype, target, False, print_output)
+ write_decision_temperatures(target, temperatures, gguf_py, max_head_tokens)
+ if kquants:
+ print(
+ "Unsloth: k-quants of decision models can move answer probabilities and flip "
+ "close answers; q8_0 stays closest to PyTorch serving."
+ )
+ for quant in kquants:
+ target = staging / model_name(quant)
+ print(f"Unsloth: quantizing the decision model to {quant.upper()}...")
+ _quantize(quantizer, staging / model_name(intermediate), target, quant, print_output)
+ write_decision_temperatures(target, temperatures, gguf_py, max_head_tokens)
+ if vision:
+ for name in sorted({mmproj_name(q) for q in quants}):
+ outtype = name[len("mmproj-") : -len(".gguf")].lower()
+ print(f"Unsloth: converting the vision tower to {name}...")
+ _convert(converter, folder, outtype, staging / name, True, print_output)
+ for quant in quants:
+ found = read_decision_temperatures(staging / model_name(quant), gguf_py)
+ if not _same(found, temperatures):
+ raise RuntimeError(
+ f"Unsloth: {model_name(quant)} lost its decision temperatures ({found} != {temperatures})."
+ )
+ if max_head_tokens is not None:
+ head = read_decision_max_head_tokens(staging / model_name(quant), gguf_py)
+ if head != max_head_tokens:
+ raise RuntimeError(
+ f"Unsloth: {model_name(quant)} has max_head_tokens {head}, not {max_head_tokens}."
+ )
+ files[quant.upper()] = {
+ "model": model_name(quant),
+ "mmproj": mmproj_name(quant) if vision else None,
+ }
+
+ # An earlier export of the same weights keeps its other quantizations.
+ previous = (
+ contract.read_export(output.parent) if output.name == contract.EXPORT_DIR else None
+ )
+ keep = {}
+ if (
+ previous is not None
+ and previous["source_fingerprint"] == source_fingerprint
+ and previous["layout"] == layout
+ ):
+ for quant, entry in previous["files"].items():
+ if quant in files:
+ continue
+ names = [entry["model"]] + ([entry["mmproj"]] if entry.get("mmproj") else [])
+ if all((output / name).is_file() for name in names):
+ keep[quant] = entry
+ merged = {**files, **keep}
+ wanted = {
+ name
+ for entry in merged.values()
+ for name in (entry["model"], entry.get("mmproj"))
+ if name
+ }
+ moved = []
+ try:
+ # Readers see no export while files move, never a half-written one.
+ (output / contract.EXPORT_FILE).unlink(missing_ok = True)
+ if previous is not None:
+ for entry in previous["files"].values():
+ for name in (entry["model"], entry.get("mmproj")):
+ if name and name not in wanted and Path(name).name == name:
+ (output / name).unlink(missing_ok = True)
+ for quant, entry in files.items():
+ for name in (entry["model"], entry["mmproj"]):
+ if name and (staging / name).is_file():
+ os.replace(staging / name, output / name)
+ moved.append(quant)
+ data = _write_export(output, layout, merged, source_fingerprint)
+ except BaseException:
+ # Windows refuses to replace a GGUF llama-server has mapped: keep the same-weights export listed.
+ if (
+ previous is not None
+ and previous["source_fingerprint"] == source_fingerprint
+ and previous["layout"] == layout
+ ):
+ listed = {q: previous["files"][q] for q in previous["quantizations"]}
+ restore = {
+ q: e
+ for q, e in {**listed, **{q: files[q] for q in moved}}.items()
+ if all((output / n).is_file() for n in (e["model"], e.get("mmproj")) if n)
+ }
+ if restore:
+ try:
+ _write_export(output, layout, restore, source_fingerprint)
+ except Exception:
+ pass
+ raise
+ finally:
+ shutil.rmtree(staging, ignore_errors = True)
+ print(f"Unsloth: saved decision model GGUF ({', '.join(files)}) to {output}")
+ return data
+
+
+def save_pretrained_gguf(
+ self,
+ save_directory,
+ tokenizer = None,
+ quantization_method = "q8_0",
+ source_folder = None,
+ print_output = False,
+ **kwargs,
+) -> dict:
+ """GGUF for llama.cpp's decision server in <save_directory>/gguf: merges into a temporary
+ folder, converts, and writes the calibrated temperatures. quantization_method is one of
+ DECISION_GGUF_QUANTIZATIONS or a list of them. token: for the base weights the merge reads."""
+ with _exit_on_sigterm():
+ return _save_pretrained_gguf(
+ self,
+ save_directory,
+ tokenizer,
+ quantization_method,
+ source_folder,
+ print_output,
+ kwargs.get("token"),
+ )
+
+
+def _save_pretrained_gguf(
+ self,
+ save_directory,
+ tokenizer,
+ quantization_method,
+ source_folder,
+ print_output,
+ token = None,
+) -> dict:
+ quants = _quantizations(quantization_method)
+ eligibility = gguf_eligibility(self)
+ if not eligibility["eligible"]:
+ raise ValueError(eligibility["reason"])
+ layout = eligibility["layout"]
+ # Fail before the merge when llama.cpp cannot convert or quantize.
+ _converter_dir(print_output)
+ kquants = [q for q in quants if q not in _OUTTYPES]
+ if kquants:
+ _kquant_quantizer(kquants, print_output)
+ output = Path(save_directory)
+ output.mkdir(parents = True, exist_ok = True)
+ _remove_abandoned_temp(output)
+ with tempfile.TemporaryDirectory(prefix = _temp_prefix(".unsloth-merged-"), dir = output) as merged:
+ self.save_pretrained_merged(
+ merged, tokenizer, **({} if token is None else {"token": token})
+ )
+ if source_folder is None and _layout(output) == layout:
+ # Only a folder holding these weights names the export (not after in-memory calibration).
+ contract = _contract()
+ if contract.fingerprint(output, layout) == contract.fingerprint(merged, layout):
+ source_folder = output
+ if source_folder is not None and _layout(Path(source_folder)) != layout:
+ source_folder = None
+ return export_decision_gguf(
+ merged,
+ quants,
+ output_dir = output / _contract().EXPORT_DIR,
+ source_folder = source_folder,
+ print_output = print_output,
+ )
+
+
+def push_to_hub_gguf(
+ self,
+ repo_id,
+ tokenizer = None,
+ quantization_method = "q8_0",
+ token = None,
+ private = None,
+ print_output = False,
+ **kwargs,
+) -> dict:
+ from huggingface_hub import HfApi
+
+ api = HfApi(token = token)
+ with tempfile.TemporaryDirectory() as folder:
+ data = self.save_pretrained_gguf(
+ folder,
+ tokenizer,
+ quantization_method = quantization_method,
+ print_output = print_output,
+ token = token,
+ )
+ repo_id = api.create_repo(repo_id, private = private, exist_ok = True).repo_id
+ api.upload_folder(folder_path = str(Path(folder) / _contract().EXPORT_DIR), repo_id = repo_id)
+ print(f"Unsloth: Saved the decision model GGUF to https://huggingface.co/{repo_id}")
+ return data