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.

Reduce comment volume across studio/backend/core (#10502)

Daniel Hana9a3938025ae
diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.py
index 45306e769d8..3a2e33b3e56 100644
--- a/studio/backend/core/data_recipe/jobs/manager.py
+++ b/studio/backend/core/data_recipe/jobs/manager.py
@@ -280,7 +280,6 @@ class JobManager:
return self.get_status(job_id)
def get_current_job_id(self) -> str | None:
- """Return current job_id (or None)."""
with self._lock:
return None if self._job is None else self._job.job_id
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index 61ac0fcb4c5..5b78717be59 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -458,8 +458,6 @@ def _ensure_hub_repo_private(hf_api, repo_id):
class ExportBackend:
- """Handles model export operations"""
-
def __init__(self):
self.inference_backend = get_inference_backend()
self.current_checkpoint = None
@@ -495,11 +493,8 @@ class ExportBackend:
def scan_checkpoints(
self, outputs_dir: str = str(outputs_root())
) -> List[Tuple[str, List[Tuple[str, str]]]]:
- """
- Scan outputs folder for training runs and their checkpoints.
-
- Returns: [(model_name, [(display_name, checkpoint_path), ...]), ...]
- """
+ """Scan the outputs folder for training runs and their checkpoints, as [(model_name,
+ [(display_name, checkpoint_path), ...]), ...]."""
from utils.models.checkpoints import scan_checkpoints
return scan_checkpoints(outputs_dir = outputs_dir)
@@ -512,19 +507,15 @@ class ExportBackend:
hf_token: HfTokenArg = None,
_device_map_override: Optional[dict] = None,
) -> Tuple[bool, str]:
- """
- Load a checkpoint for export.
-
- ``hf_token`` authenticates the actual weight load for gated/private
- checkpoints, matching the token the worker used for the security preflight
- (otherwise a gated repo passes scanning then 401s at from_pretrained).
+ """Load a checkpoint for export.
- ``False`` (denied the ambient token) must travel all the way down: ``None`` reads as
- "go and find a credential" (``if token is None: get_token()`` in ``save.py`` and
- ``hf_login``), and ``get_token()`` reads the operator's stored login off disk.
+ ``hf_token`` authenticates the actual weight load for gated/private checkpoints, matching
+ the token the worker used for the security preflight (otherwise a gated repo passes scanning
+ then 401s at from_pretrained).
- Returns:
- Tuple of (success: bool, message: str)
+ ``False`` (denied the ambient token) must travel all the way down: ``None`` reads as "go and
+ find a credential" (``if token is None: get_token()`` in ``save.py`` and ``hf_login``), and
+ ``get_token()`` reads the operator's stored login off disk.
"""
token = normalize_token(hf_token)
# Loaders only: the probes' cache guards refuse an anonymous read, which offline
@@ -765,22 +756,12 @@ class ExportBackend:
private: bool = False,
compressed_method: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
- """
- Export merged model (for PEFT models).
-
- Args:
- save_directory: Local directory to save model
- format_type: "16-bit (FP16)", "4-bit (FP4)", or a compressed-tensors label
- compressed_method: Optional compressed-tensors scheme alias (e.g. "fp8",
- "fp8_static", "w8a8", "w4a16", "mxfp4", "mxfp8", "nvfp4"). Overrides
- format_type and is resolved against unsloth.save COMPRESSED_EXPORT_SCHEMES.
- push_to_hub: Whether to push to Hugging Face Hub
- repo_id: Hub repository ID (username/model-name)
- hf_token: Hugging Face token
- private: Whether to make the repo private
-
- Returns:
- Tuple of (success: bool, message: str, output_path: Optional[str])
+ """Export a merged model (a no-op merge for non-PEFT base models).
+
+ ``format_type`` is "16-bit (FP16)", "4-bit (FP4)", or a compressed-tensors label.
+ ``compressed_method`` is an optional compressed-tensors scheme alias (fp8, fp8_static, w8a8,
+ w4a16, mxfp4, mxfp8, nvfp4); it overrides ``format_type`` and is resolved against
+ unsloth.save COMPRESSED_EXPORT_SCHEMES.
"""
if not _export_runtime_available():
return False, _export_runtime_message(), None
@@ -1012,12 +993,6 @@ class ExportBackend:
private: bool = False,
base_model_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
- """
- Export base model (for non-PEFT models).
-
- Returns:
- Tuple of (success: bool, message: str, output_path: Optional[str])
- """
if not _export_runtime_available():
return False, _export_runtime_message(), None
if not self.current_model or not self.current_tokenizer:
@@ -1143,23 +1118,12 @@ class ExportBackend:
private: bool = False,
gguf_shard_size: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
- """
- Export model in GGUF format.
-
- Args:
- save_directory: Local directory to save model
- quantization_method: A single GGUF quant method (e.g., "Q4_K_M") or a list of them
- (e.g., ["Q4_K_M", "Q8_0"]). A list produces one GGUF per quant from a single
- model load (unsloth save_to_gguf loops internally).
- push_to_hub: Whether to push to Hugging Face Hub
- repo_id: Hub repository ID
- hf_token: Hugging Face token
- imatrix_file: Optional importance matrix file path or boolean
- private: Whether to make the Hub repository private
- gguf_shard_size: Maximum final full-precision GGUF shard size
-
- Returns:
- Tuple of (success: bool, message: str, output_path: Optional[str])
+ """Export the model in GGUF format.
+
+ ``quantization_method`` is a single GGUF quant method ("Q4_K_M") or a list of them; a list
+ produces one GGUF per quant from a single model load, since unsloth save_to_gguf loops
+ internally. ``imatrix_file`` is an importance matrix path or boolean, and
+ ``gguf_shard_size`` caps the final full-precision GGUF shard size.
"""
if not _export_runtime_available():
return False, _export_runtime_message(), None
@@ -1482,16 +1446,11 @@ class ExportBackend:
gguf: bool = False,
gguf_outtype: str = "q8_0",
) -> Tuple[bool, str, Optional[str]]:
- """
- Export LoRA adapter only (not merged).
-
- Args:
- gguf: If True, also convert the adapter to a GGUF LoRA file (llama.cpp
- convert_lora_to_gguf.py), loadable with `llama-cli --lora ...`.
- gguf_outtype: GGUF LoRA output float type; one of q8_0/f16/bf16/f32.
+ """Export the LoRA adapter only, not merged.
- Returns:
- Tuple of (success: bool, message: str, output_path: Optional[str])
+ ``gguf`` also converts the adapter to a GGUF LoRA file (llama.cpp convert_lora_to_gguf.py),
+ loadable with `llama-cli --lora ...`; ``gguf_outtype`` is its output float type, one of
+ q8_0/f16/bf16/f32.
"""
if not _export_runtime_available():
return False, _export_runtime_message(), None
@@ -1635,7 +1594,6 @@ _export_backend = None
def get_export_backend() -> ExportBackend:
- """Get or create the global export backend instance"""
global _export_backend
if _export_backend is None:
_export_backend = ExportBackend()
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index 7ce9ef409e0..e4f893a921a 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -1,16 +1,10 @@
# 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 orchestrator — subprocess-based.
-
-Same API as ExportBackend, but delegates all ML work to a persistent
-subprocess spawned on first checkpoint load and reused for later exports.
-
-When switching between checkpoints needing different transformers
-versions, the old subprocess is killed and a new one spawned.
-
-Pattern follows core/inference/orchestrator.py.
-"""
+"""Export orchestrator: same API as ExportBackend, but delegates all ML work to a persistent
+subprocess spawned on first checkpoint load and reused for later exports. Switching between
+checkpoints that need different transformers versions kills the old subprocess and spawns a new
+one. Pattern follows core/inference/orchestrator.py."""
import atexit
import structlog
@@ -42,13 +36,8 @@ _CLEANUP_TIMEOUT = 30.0
class ExportOrchestrator:
- """
- Export backend orchestrator — subprocess-based.
-
- Exposes the same API surface as ExportBackend so routes/export.py
- needs minimal changes. All heavy ML work happens in a persistent
- subprocess.
- """
+ """Export backend orchestrator, subprocess-based. Same API surface as ExportBackend so
+ routes/export.py needs minimal changes."""
def __init__(self):
self._proc: Optional[mp.Process] = None
@@ -57,7 +46,6 @@ class ExportOrchestrator:
# Serializes export ops so concurrent HTTP requests can't interleave commands.
self._lock = threading.Lock()
- # Local state mirrors (updated from subprocess responses).
self.current_checkpoint: Optional[str] = None
self.is_vision: bool = False
self.is_peft: bool = False
@@ -85,10 +73,7 @@ class ExportOrchestrator:
atexit.register(self._cleanup)
logger.info("ExportOrchestrator initialized (subprocess mode)")
- # ------------------------------------------------------------------
-
def _append_log(self, entry: Dict[str, Any]) -> None:
- """Append a worker log line to the buffer, stamped with a monotonic seq."""
line = entry.get("line")
if not line:
return
@@ -114,7 +99,6 @@ class ExportOrchestrator:
self._run_start_seq = self._log_seq
def get_logs_since(self, cursor: int) -> Tuple[List[Dict[str, Any]], int]:
- """Return log entries with seq > cursor, plus the new cursor."""
with self._log_lock:
new_entries = [entry for entry in self._log_buffer if entry["seq"] > cursor]
if new_entries:
@@ -122,26 +106,21 @@ class ExportOrchestrator:
return [], cursor
def get_current_log_seq(self) -> int:
- """Return the current seq counter without reading any entries."""
with self._log_lock:
return self._log_seq
def get_run_start_seq(self) -> int:
- """Return the seq captured at the current run's start (SSE default cursor)."""
with self._log_lock:
return self._run_start_seq
def is_export_active(self) -> bool:
- """True while an export / load / cleanup command is running."""
return self._export_active
def is_worker_alive(self) -> bool:
- """True while the persistent export subprocess is running (op or idle)."""
proc = self._proc
return proc is not None and proc.is_alive()
def was_cancelled(self) -> bool:
- """True if the in-flight (or most recent) run was cancelled by the user."""
return self._cancel_requested
def _record_op_finished(self, success: bool, message: str, output_path: Optional[str]) -> None:
@@ -163,12 +142,10 @@ class ExportOrchestrator:
}
def get_last_op(self) -> Optional[Dict[str, Any]]:
- """Return the last finished op record (or None), for status recovery."""
with self._op_lock:
return dict(self._last_op) if self._last_op is not None else None
def get_active_op_kind(self) -> Optional[str]:
- """Return the kind of the currently running op (or None when idle)."""
return self._active_op_kind
def cancel_export(self) -> bool:
@@ -206,10 +183,7 @@ class ExportOrchestrator:
pass
return True
- # ------------------------------------------------------------------
-
def _spawn_subprocess(self, config: dict) -> None:
- """Spawn a new export subprocess."""
# Inside an op a reservation is an install about to abort on is_export_active(), so raising here
# would kill the export for an install that never proceeds.
from utils.transformers_version import sidecar_swap_in_progress
@@ -319,7 +293,6 @@ class ExportOrchestrator:
except Exception:
pass
- # Force kill if still alive.
if self._proc is not None and self._proc.is_alive():
logger.warning("Export subprocess did not exit gracefully, terminating")
try:
@@ -350,17 +323,12 @@ class ExportOrchestrator:
return True
def _cleanup(self):
- """atexit handler."""
self._shutdown_subprocess(timeout = 5.0)
def _ensure_subprocess_alive(self) -> bool:
- """Check if subprocess is alive."""
return self._proc is not None and self._proc.is_alive()
- # ------------------------------------------------------------------
-
def _send_cmd(self, cmd: dict) -> None:
- """Send a command to the subprocess."""
if self._cmd_queue is None:
raise RuntimeError("No export subprocess running")
try:
@@ -369,7 +337,6 @@ class ExportOrchestrator:
raise RuntimeError(f"Failed to send command to subprocess: {exc}")
def _read_resp(self, timeout: float = 1.0) -> Optional[dict]:
- """Read a response from the subprocess (non-blocking with timeout)."""
if self._resp_queue is None:
return None
try:
@@ -421,7 +388,6 @@ class ExportOrchestrator:
raise RuntimeError(f"Subprocess error: {error_msg}")
if rtype == "log":
- # Forwarded stdout/stderr line from the worker.
self._append_log(resp)
deadline = renew()
continue
@@ -442,7 +408,6 @@ class ExportOrchestrator:
deadline = renew()
continue
- # Other response types during wait - skip.
logger.debug(
"Skipping response type '%s' while waiting for '%s'",
rtype,
@@ -458,7 +423,6 @@ class ExportOrchestrator:
)
def _drain_queue(self) -> list:
- """Drain all pending responses."""
events = []
if self._resp_queue is None:
return events
@@ -470,8 +434,6 @@ class ExportOrchestrator:
except (EOFError, OSError, ValueError):
return events
- # ------------------------------------------------------------------
-
def load_checkpoint(
self,
checkpoint_path: str,
@@ -517,7 +479,6 @@ class ExportOrchestrator:
"sidecar; retry when it completes."
)
raise SidecarSwapInProgress(op_message)
- # Always kill any existing subprocess and spawn fresh.
if self._ensure_subprocess_alive():
if self._shutdown_subprocess() is False:
# A survivor still holds GPU memory (a wedged CUDA syscall outliving SIGKILL) and its handle is
@@ -582,7 +543,6 @@ class ExportOrchestrator:
private: bool = False,
compressed_method: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
- """Export merged PEFT model."""
return self._run_export(
"merged",
{
@@ -605,7 +565,6 @@ class ExportOrchestrator:
private: bool = False,
base_model_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
- """Export base model (non-PEFT)."""
return self._run_export(
"base",
{
@@ -724,7 +683,6 @@ class ExportOrchestrator:
self._export_active = False
def cleanup_memory(self) -> bool:
- """Cleanup export-related models from memory."""
with self._lock:
if not self._ensure_subprocess_alive():
self.current_checkpoint = None
@@ -747,7 +705,6 @@ class ExportOrchestrator:
except RuntimeError:
success = False
- # Shut down subprocess after cleanup - no model loaded.
self._shutdown_subprocess()
self.current_checkpoint = None
@@ -765,12 +722,10 @@ class ExportOrchestrator:
return scan_checkpoints(outputs_dir = outputs_dir)
-# ========== GLOBAL INSTANCE ==========
_export_backend = None
def get_export_backend() -> ExportOrchestrator:
- """Get global export backend instance (orchestrator)."""
global _export_backend
if _export_backend is None:
_export_backend = ExportOrchestrator()
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index b46bd2c8a55..d5a27512014 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -83,7 +83,6 @@ def _setup_log_capture(resp_queue: Any) -> None:
os.close(w_out)
os.close(w_err)
- # Replace sys.stdout/sys.stderr with line-buffered writers on fds 1 and 2.
try:
sys.stdout = os.fdopen(1, "w", buffering = 1, encoding = "utf-8", errors = "replace")
sys.stderr = os.fdopen(2, "w", buffering = 1, encoding = "utf-8", errors = "replace")
@@ -229,7 +228,6 @@ def _offline_window_if_unreachable(step = "loading"):
def _send_response(resp_queue: Any, response: dict) -> None:
- """Send a response to the parent process."""
try:
resp_queue.put(response)
except (OSError, ValueError) as exc:
@@ -237,7 +235,6 @@ def _send_response(resp_queue: Any, response: dict) -> None:
def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:
- """Handle a load_checkpoint command."""
from hub.utils.hf_tokens import hf_token_arg
checkpoint_path = cmd["checkpoint_path"]
@@ -405,7 +402,6 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:
def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
- """Handle any export command (merged, base, gguf, lora)."""
export_type = cmd["export_type"] # "merged", "base", "gguf", "lora"
response_type = f"export_{export_type}_done"
@@ -498,7 +494,6 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
def _handle_cleanup(backend, resp_queue: Any) -> None:
- """Handle a cleanup command."""
try:
success = backend.cleanup_memory()
_send_response(
@@ -572,7 +567,6 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
# whoever exports next. The caller's own travels as an argument instead.
apply_token_to_child_env(os.environ, False)
- # ── 1. Activate correct transformers version BEFORE any ML imports ──
with _offline_window_if_unreachable(step = "activating transformers"):
try:
# Plain token: _load_config_json refuses the hub cache for the sentinel, so
@@ -591,20 +585,17 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
)
return
- # ── 1b. Check Triton on Windows (must precede import torch) ──
# Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).
if sys.platform == "win32":
from core._msvc_env import gate_torch_compile_on_windows
gate_torch_compile_on_windows(logger)
- # ── 1c. Stub torchao on Windows ROCm ──
- # See core/_torchao_stub.py: torchao crashes on Windows ROCm (RCCL absent).
- # No-op off Windows ROCm. Must run before importing transformers / unsloth_zoo.
+ # See core/_torchao_stub.py: torchao crashes on Windows ROCm (RCCL absent). No-op off Windows ROCm. Must run
+ # before importing transformers / unsloth_zoo.
from core._torchao_stub import install_torchao_windows_rocm_stub
install_torchao_windows_rocm_stub()
- # ── 2. Import ML libraries (fresh in this clean process) ──
try:
_send_response(
resp_queue,
@@ -642,7 +633,6 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
)
return
- # ── 3. Create export backend and load initial checkpoint ──
try:
backend = ExportBackend()
@@ -663,8 +653,6 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
)
return
- # ── 4. Command loop - process commands until shutdown ──
- # ── 4. Command loop — process commands until shutdown ──
logger.info("Export subprocess ready, entering command loop")
while True:
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.py
index eef2e9bb6c4..9198e8f95e1 100644
--- a/studio/backend/core/inference/_html_to_md.py
+++ b/studio/backend/core/inference/_html_to_md.py
@@ -157,10 +157,9 @@ _IMPLICIT_CLOSERS: dict = {
}
-# a nested container makes an inner item a descendant
# Item tag -> container tags that re-scope it: a nested container makes an inner item a descendant, not an
-# optional-close sibling, so recovery must stop there rather than close (and un-hide) the outer item and leak its nested
-# content.
+# optional-close sibling, so recovery must stop there rather than close (and un-hide) the outer item and leak its
+# nested content.
_CLOSE_BARRIERS: dict = {
"li": frozenset({"ul", "ol", "menu"}),
"dt": frozenset({"dl"}),
@@ -314,9 +313,8 @@ class _MarkdownRenderer(HTMLParser):
self._dropped_chars: int = 0
self._seg_dropped_start: int = 0
self.scope_dropped: list[int] = []
- # role="heading", hgroup and linked h1 render as prose
- # Heading text per segment: role="heading", hgroup and linked h1 render as prose, so ATX reparsing alone cannot
- # keep them out of the gate.
+ # Heading text per segment: role="heading", hgroup and linked h1 render as prose, so ATX reparsing alone
+ # cannot keep them out of the gate.
self._seg_heading_texts: list[str] = []
self.scope_heading_prose: list[int] = []
# Open-tag indices of headings, unwound with _hidden_marks.
@@ -354,7 +352,6 @@ class _MarkdownRenderer(HTMLParser):
# Blockquote state: stack of buffers so nested blockquotes get the right ">" depth.
self._bq_stack: list[list[str]] = []
- # ------------------------------------------------------------------
def _nested_buffer_open(self, frame: _HeaderFrame) -> bool:
"""True when a side buffer opened *inside* *frame* still holds content.
@@ -407,7 +404,6 @@ class _MarkdownRenderer(HTMLParser):
else:
self._out.append(text)
- # ------------------------------------------------------------------
def _seg_heading_prose(self) -> int:
"""Heading characters in this segment that the gate would otherwise read as
body prose. ATX headings carry their own ``#`` here and so score zero."""
@@ -501,10 +497,7 @@ class _MarkdownRenderer(HTMLParser):
# Preserved by hand, so tell the gate too or a title-only card reads as body prose.
self._seg_heading_texts.append(heading_text)
- # ------------------------------------------------------------------ Tag handlers
- # ------------------------------------------------------------------ Structural bookkeeping shared by every start
- # tag (skip/hidden/scope).
- # ------------------------------------------------------------------
+ # Tag handlers. Structural bookkeeping shared by every start tag (skip/hidden/scope).
def _truncate_open_tags(self, index: int) -> None:
"""Drop the open-tag stack above *index*, keeping the closable count."""
for name in self._open_tags[index:]:
@@ -857,7 +850,6 @@ class _MarkdownRenderer(HTMLParser):
self._in_table = False
self._emit("\n")
- # ------------------------------------------------------------------
def _text_suppressed(self) -> bool:
if self._skip_depth or self._hidden_marks:
return True
@@ -899,7 +891,6 @@ class _MarkdownRenderer(HTMLParser):
self._count_header_text(text)
self._emit(text)
- # Flush pending buffers (handles truncated HTML from capped fetches)
def flush_pending(self) -> None:
"""Flush open side-buffers into ``_out`` after close(), recovering truncated HTML."""
# Headers first: a frame finalizes its inner buffers, then emits into the enclosing link or cell, which must
@@ -972,9 +963,8 @@ def _cleanup(text: str) -> str:
return "\n".join(out).strip()
-# known boilerplate stripped from main-content conversions, matched only against short lines
-# Known boilerplate fragments stripped from main-content conversions, matched only against short lines. Sources: GitHub
-# page furniture / client-side error placeholders, skip-links, cookie banners.
+# Known boilerplate fragments stripped from main-content conversions, matched only against short lines. Sources:
+# GitHub page furniture / client-side error placeholders, skip-links, cookie banners.
_BOILERPLATE_FRAGMENTS = (
"skip to content",
"skip to main content",
@@ -993,7 +983,6 @@ _BOILERPLATE_FRAGMENTS = (
"accept all cookies",
"manage cookie preferences",
)
-# only shorter lines are eligible: real content sentences quoting a fragment run longer
# Only shorter lines are eligible for boilerplate dropping; real content sentences quoting a fragment run longer.
_BOILERPLATE_MAX_LINE_CHARS = 300
diff --git a/studio/backend/core/inference/_vulkan_probe.py b/studio/backend/core/inference/_vulkan_probe.py
index 08b3f2ceed1..dfde5a3b344 100644
--- a/studio/backend/core/inference/_vulkan_probe.py
+++ b/studio/backend/core/inference/_vulkan_probe.py
@@ -55,7 +55,6 @@ def _igpu_flags_and_names(base, lib, count: int) -> tuple[list[bool], list[str]]
# crashing the probe.
return flags, names
- # bound outside the try above: a ggml-base without the description symbol must degrade to unnamed
# Bound outside the type-detection try above: a ggml-base without the description symbol (older/custom build) must
# degrade to unnamed devices, not abort before the iGPU flags are read (which would count an iGPU's shared RAM as
# VRAM).
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.py
index 7cc04b4e6c6..eb44107c1fc 100644
--- a/studio/backend/core/inference/anthropic_compat.py
+++ b/studio/backend/core/inference/anthropic_compat.py
@@ -109,7 +109,6 @@ def anthropic_messages_to_openai(
continue
if role == "assistant":
- # text + tool_use (no images in Anthropic's model), plus replayed thinking when preservation is requested
# Assistant content: text + tool_use (no images in Anthropic's model), plus replayed thinking when
# preservation is requested.
text_parts: list[str] = []
@@ -418,7 +417,6 @@ def anthropic_tool_choice_to_openai(tc: Any) -> Any:
def build_anthropic_sse_event(event_type: str, data: dict) -> str:
- """Format a single Anthropic SSE event."""
return f"event: {event_type}\ndata: {json.dumps(data)}\n\n"
@@ -469,7 +467,6 @@ class AnthropicStreamEmitter:
self._open_tool_use_id: Optional[str] = None
self._open_tool_args_sent: bool = False
self._prev_text: str = ""
- # the generator folds reasoning_content into the cumulative text as <think>...</think> markup
# <think> routing: the generator folds reasoning_content into the cumulative text as <think>...</think> markup
# (the UI chat parses it), but Anthropic clients expect typed thinking blocks. Split the markup back out: text
# inside the tags streams as thinking_delta in a "thinking" content block, everything else as ordinary text.
@@ -484,16 +481,14 @@ class AnthropicStreamEmitter:
# <think> is the model quoting the tag and must stay literal.
self._think_consumed: bool = False
self._turn_has_text: bool = False
- # "wrapped" counts the leading <think> tags the generator opened from reasoning_content
# Live provenance from the generator: "wrapped" counts the leading <think> tags IT opened from
# reasoning_content. When provided, a leading tag is only parsed as reasoning if a generator wrap is available
# -- a model answering with literal <think> markup (and no genuine trace) keeps it as text. None falls back to
# the leading-tag heuristic (test doubles / callers without provenance).
self._think_provenance = think_provenance
self._wraps_consumed: int = 0
- # the block spans exactly the wrap's N reasoning chars
- # Active wrap entry ({"len": N} from the generator) while a provenance -backed thinking block streams: the block
- # spans exactly N reasoning chars, so a literal "</think>" INSIDE the trace never ends it early.
+ # Active wrap entry ({"len": N} from the generator) while a provenance-backed thinking block streams: the
+ # block spans exactly N reasoning chars, so a literal "</think>" INSIDE the trace never ends it early.
self._active_wrap: Optional[dict] = None
self._wrap_chars: int = 0
self._close_skip: int = 0
@@ -622,7 +617,6 @@ class AnthropicStreamEmitter:
break
if i:
events.extend(self._emit_text_delta(data[:i]))
- # consumed: the run before the tag has already been delivered
# Consumed: whatever happens to the tag below, the run before it has already been delivered.
# Re-including it in the literal-text branch below sent it to the client twice.
data = data[i:]
@@ -709,12 +703,11 @@ class AnthropicStreamEmitter:
def _emit_thinking_delta(self, text: str) -> list[str]:
if not self._thinking_block_open:
- # a whitespace-only trace is not a thought
# A trace that is only whitespace is not a thought: Qwen3-style templates render "<think>\n\n</think>" on
# every reply when thinking is off, and llama-server parses that into reasoning_content, so an empty
# thinking block would be attached to ordinary answers. The non-streaming reducer already drops those, so
- # hold the leading whitespace run and only open the block once real reasoning arrives; the held run is then
- # emitted with it so the trace stays verbatim.
+ # hold the leading whitespace run and only open the block once real reasoning arrives; the held run is
+ # then emitted with it so the trace stays verbatim.
held = self._thinking_ws_hold + text
if not held.strip():
self._thinking_ws_hold = held
@@ -822,9 +815,8 @@ class AnthropicStreamEmitter:
},
)
)
- # the next content delta opens a fresh block lazily
- # Reset text tracking for the next synthesis turn; the next content delta opens a fresh text (or thinking) block
- # lazily, and the new turn may legitimately open with its own leading <think> block.
+ # Reset text tracking for the next synthesis turn; the next content delta opens a fresh text (or thinking)
+ # block lazily, and the new turn may legitimately open with its own leading <think> block.
self._prev_text = ""
self._tag_buf = ""
self._thinking_ws_hold = ""
@@ -974,12 +966,9 @@ class AnthropicPassthroughEmitter:
delta = choice.get("delta") or {}
finish_reason = choice.get("finish_reason")
- # llama-server splits <think> into reasoning_content whenever it can parse the model's reasoning format (it does
- # so for tool-calling turns, i.e.
- # ── Reasoning ── llama-server splits <think> into reasoning_content whenever it can parse the model's reasoning
- # format (it does so for tool-calling turns, which is every Claude Code turn). Reading only `content` drops the
+ # Reasoning: llama-server splits <think> into reasoning_content whenever it can parse the model's reasoning
+ # format, which it does for tool-calling turns, i.e. every Claude Code turn. Reading only `content` drops the
# entire thinking trace, so the model appears not to think at all.
- # ── Reasoning ──
reasoning = delta.get("reasoning_content")
if reasoning:
if not self._reasoning_as_thinking:
@@ -1001,27 +990,22 @@ class AnthropicPassthroughEmitter:
},
)
)
- # checked unconditionally, not elif: one chunk can carry the final reasoning fragment AND same-chunk content
- # Reconstructed literal block ends where the answer resumes -- checked unconditionally (not elif): one chunk can
- # carry the final reasoning fragment AND same-chunk content/tool output, and the closing tag must land between
- # them.
+ # Reconstructed literal block ends where the answer resumes -- checked unconditionally (not elif): one chunk
+ # can carry the final reasoning fragment AND same-chunk content/tool output, and the closing tag must land
+ # between them.
if self._reasoning_text_open and (
delta.get("content") or delta.get("tool_calls") or finish_reason
):
self._reasoning_text_open = False
events.extend(self._emit_text_delta("</think>"))
- # grammar mode worked: flush anything the healer held (it preceded the call in the model's output) and relay
- # verbatim from here
- # ── Structured tool calls take precedence over healing ── Grammar mode worked: flush anything the healer held
- # (it preceded the call in the model's output) and relay verbatim from here on.
- # ── Structured tool calls take precedence over healing ──
+ # Structured tool calls take precedence over healing. Grammar mode worked: flush anything the healer held (it
+ # preceded the call in the model's output) and relay verbatim from here on.
if delta.get("tool_calls") and self._healer is not None and not self._healer.dormant:
for kind, value in self._healer.structured_tool_call_seen():
if kind == "text" and value:
events.extend(self._emit_text_delta(value))
- # ── Text content ──
content = delta.get("content")
if content and self._healer is not None and not self._healer.dormant:
# Route text through the healer: held/promoted portions become synthetic tool_use blocks, the rest streams
@@ -1034,7 +1018,6 @@ class AnthropicPassthroughEmitter:
elif content:
events.extend(self._emit_text_delta(content))
- # ── Tool calls (streaming deltas) ──
tool_calls = delta.get("tool_calls") or []
for tc in tool_calls:
tc_idx = tc.get("index", 0)
@@ -1092,7 +1075,6 @@ class AnthropicPassthroughEmitter:
)
)
- # ── Finish reason ──
if finish_reason:
self._stop_reason = openai_finish_to_anthropic_stop(finish_reason)
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index d91aeefc435..6a90c1d8f39 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -197,7 +197,6 @@ class ApiMonitorEntry:
progress: Optional[float] = None
# Stamped on the first reply text; snapshot() prefers it over engine timings.
first_token_monotonic: Optional[float] = None
- # a tool card is client output that TTFT should count and the token-rate clock must not
# The same instant, but only for output the model decoded. A tool card is client output that TTFT should count and
# the token-rate clock must not: the tool run between it and the first token is not decoding.
first_decode_monotonic: Optional[float] = None
@@ -207,7 +206,6 @@ class ApiMonitorEntry:
# timings.predicted_ms; set only from engine timings, so its presence marks a rateable row.
decode_ms: Optional[float] = None
stop_reason: Optional[str] = None
- # an n > 1 stream reports each choice in its own chunk
# Every finish reason seen so far. An n > 1 stream reports each choice in its own chunk, so agreement can only be
# judged across the whole request. Not serialized.
stop_reasons_seen: set[str] = field(default_factory = set)
@@ -244,7 +242,6 @@ class ApiMonitorEntry:
if (
tok_per_sec is None
and self.completion_tokens
- # the clock starts at the first token, so one token has no gap to measure and hence no rate
# The clock starts at the first token, so it spans only the gaps that followed it: one token has no gap to
# measure, hence no rate at all.
and self.completion_tokens > 1
@@ -343,8 +340,6 @@ class ApiMonitor:
"""Remove only the terminal callback registration owned by ``lease``."""
with self._callback_condition:
self._terminal_callback_leases.pop(lease, None)
- # let a notification that already captured this callback finish its fast enqueue before the owner
- # drains/stops the writer
# A notification may already have captured this callback. Let its fast enqueue finish before the owner
# drains/stops the writer.
while self._terminal_callbacks_inflight.get(lease, 0):
@@ -495,10 +490,9 @@ class ApiMonitor:
entry.first_token_monotonic = now
if entry.first_decode_monotonic is None:
entry.first_decode_monotonic = now
- # once the "..." marker is present the head is frozen
# Preview is capped: once the "..." marker is present the head is frozen, so skip the per-chunk re-concat
- # (avoids O(n^2) on long generations). A reply that landed exactly on the cap has no marker yet, so let one
- # more append record the truncation before freezing.
+ # (avoids O(n^2) on long generations). A reply that landed exactly on the cap has no marker yet, so let
+ # one more append record the truncation before freezing.
if len(entry.reply) >= _MAX_REPLY_CHARS:
if not entry.reply.endswith("..."):
entry.reply = _trim(entry.reply + text, _MAX_REPLY_CHARS)
@@ -693,7 +687,6 @@ class ApiMonitor:
) -> None:
if not entry_id:
return
- # coerce before locking: a raise here (this runs inside streaming generators) would truncate the user's response
# Coerce before locking: arbitrary payloads, and a raise here (this runs inside streaming generators) would
# truncate the user's response.
tok_per_sec = _finite_float_or_none(tok_per_sec)
diff --git a/studio/backend/core/inference/audio_codecs.py b/studio/backend/core/inference/audio_codecs.py
index bf116b911ea..b6dc11bcc4a 100644
--- a/studio/backend/core/inference/audio_codecs.py
+++ b/studio/backend/core/inference/audio_codecs.py
@@ -151,7 +151,6 @@ class AudioCodecManager:
device: str = "cuda",
model_repo_path: Optional[str] = None,
) -> None:
- """Load the appropriate codec for the given audio type."""
if audio_type == "snac":
self._load_snac(device, model_repo_path)
elif audio_type == "bicodec":
@@ -163,8 +162,6 @@ class AudioCodecManager:
else:
raise ValueError(f"Unknown audio_type: {audio_type}")
- # ── Lazy loaders ─────────────────────────────────────────────
-
def _load_snac(
self,
device: str,
@@ -237,8 +234,6 @@ class AudioCodecManager:
self._codec_devices["dac"] = device
logger.info("Loaded DAC audio codec")
- # ── Decoders ─────────────────────────────────────────────────
-
def decode_snac(self, generated_ids: torch.Tensor, device: str) -> Tuple[bytes, int]:
"""Decode SNAC tokens (Orpheus) into WAV bytes.
@@ -382,8 +377,6 @@ class AudioCodecManager:
return self.decode_dac(text, device)
raise ValueError(f"Cannot decode audio_type: {audio_type}")
- # ── Cleanup ──────────────────────────────────────────────────
-
def unload(self) -> None:
"""Release all codec models from memory."""
if self._snac_model is not None:
diff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.py
index ea857e1ae24..18a6b1206ae 100644
--- a/studio/backend/core/inference/audio_gallery.py
+++ b/studio/backend/core/inference/audio_gallery.py
@@ -60,7 +60,6 @@ def save(wav_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:
return _record(audio_id, meta)
-# /v1/audio/speech persists every call, so bound it here rather than at that route, covering the UI's runaway too
# The OpenAI-compatible /v1/audio/speech route persists every call, so an automated client can grow the gallery until
# the disk fills. Bounded here rather than at that route so the UI's own runaway is covered too. Generous by default:
# this is a convenience gallery, and the clip is returned to the caller either way.
@@ -116,14 +115,11 @@ def _prune_to_cap() -> int:
directory = gallery_dir()
removed = 0
try:
- # select AND delete under one lock: otherwise an archive landing in the window is deleted anyway
# Select AND delete under one lock, as clear() does. Choosing victims from a snapshot and unlinking after it
# leaves a window where an archive lands and is deleted anyway.
with gallery_flags.exclusive(directory, require_file_lock = True):
entries = _list_audio_entries()
- # newest first; the newest is always kept, since dropping what the caller just generated looks like a silent
- # failure
# Newest first, so the index where either budget runs out is the cut point. The newest is always kept:
# dropping what the caller just generated looks like a silent failure.
keep = len(entries) if cap <= 0 else min(cap, len(entries))
@@ -137,7 +133,6 @@ def _prune_to_cap() -> int:
if keep >= len(entries):
return 0
- # re-read TRUSTED before deleting: read() answers "nothing is archived" for a store it cannot parse
# Re-read TRUSTED immediately before deleting: read() answers "nothing is archived" for a store it cannot
# parse, which here would drop the clips the shelf exists to keep. It also covers filesystems where the
# cross-process lock degrades to a no-op.
@@ -210,8 +205,7 @@ def _sidecar_path(audio_id: str) -> Path:
return gallery_dir() / f"{audio_id}.json"
-# key-presence ownership: a hand-dropped wav with a partial sidecar is neither counted as ours nor destroyed
-# key-presence ownership test: a hand-dropped wav with a partial sidecar is never counted as ours nor destroyed
+# Key-presence ownership test: a hand-dropped wav with a partial sidecar is neither counted as ours nor destroyed.
_REQUIRED_META = (
"prompt",
"model",
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
index dfaa3bf0b72..9ca261f12ca 100644
--- a/studio/backend/core/inference/chat_generation_runs.py
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -31,18 +31,16 @@ _SHUTDOWN_GRACE_SECONDS = 10.0
# Second budget, after task.cancel(). Shorter than the grace period: by this point the run is already being abandoned,
# and the only question is whether shutdown returns.
_SHUTDOWN_CANCEL_SECONDS = 5.0
-# the sweeper's work is redundant at shutdown, and Desktop force-kills the backend after five seconds
-# The sweeper's own shutdown budget, far below the producers'. Its work is redundant at shutdown and Desktop force-kills
-# the backend after five seconds.
+# The sweeper's own shutdown budget, far below the producers'. Its work is redundant at shutdown and Desktop
+# force-kills the backend after five seconds.
_SWEEP_SHUTDOWN_SECONDS = 0.5
# A durable run sets cancel_on_disconnect=False, so reaping is keyed on progress rather than on connectedness. The
# default matches llama_cpp._DEFAULT_FIRST_TOKEN_TIMEOUT_S, the request path's own first-token budget: a lease older
# than that cannot be legitimate prefill, and slow decode is safe at any speed. A century: clear of any real lease, far
# below where integer milliseconds overflow.
_MAX_ENV_SECONDS = 100.0 * 365.0 * 24.0 * 60.0 * 60.0
-# a day already means the queue never reports, and tripling it stays inside _MAX_ENV_SECONDS
-# The longest admission keep-alive cadence worth deriving a lease from. A day already means the queue never reports, and
-# tripling it stays far inside _MAX_ENV_SECONDS.
+# The longest admission keep-alive cadence worth deriving a lease from. A day already means the queue never reports,
+# and tripling it stays far inside _MAX_ENV_SECONDS.
_MAX_ADMISSION_INTERVAL_SECONDS = 24.0 * 60.0 * 60.0
_LEASE_TIMEOUT_SECONDS = 1200.0
_LEASE_SWEEP_INTERVAL_SECONDS = 60.0
@@ -225,7 +223,6 @@ class ChatGenerationLeaseSweeper:
self._task: asyncio.Task | None = None
self._stop_event = asyncio.Event()
- # generous: unwinding cleanly beats being cancelled mid-teardown
# Grace for a settled producer to notice the cooperative cancel. Generous: unwinding cleanly beats being cancelled
# mid-teardown, and the run is already declared dead.
_FORCE_CANCEL_GRACE_S = 30.0
@@ -321,11 +318,10 @@ class ChatGenerationLeaseSweeper:
task, self._task = self._task, None
if task is None:
return
- # the boot reconcile settles every active run anyway
# A short wait, not the producer grace. Letting a sweep finish at shutdown buys nothing: the boot reconcile
- # settles every active run anyway, so its work is redundant here, while a sweep parked on the writer lock would
- # otherwise spend Studio Desktop's whole graceful-exit budget before producers are even signalled. asyncio.wait,
- # never wait_for(gather(...)); see ChatGenerationSupervisor.stop.
+ # settles every active run anyway, while a sweep parked on the writer lock would otherwise spend Studio
+ # Desktop's whole graceful-exit budget before producers are even signalled. asyncio.wait, never
+ # wait_for(gather(...)); see ChatGenerationSupervisor.stop.
_done, pending = await asyncio.wait({task}, timeout = _SWEEP_SHUTDOWN_SECONDS)
if not pending:
return
@@ -349,11 +345,9 @@ def start_lease_sweeper(app: Any) -> ChatGenerationLeaseSweeper | None:
return sweeper
-# matched rather than imported to keep this module free of a routes import at module scope
-# The admission stream's own comment, matched rather than imported to keep this module free of a routes import at module
-# scope. Pinned by a test against the constant there.
+# The admission stream's own comment, matched rather than imported to keep this module free of a routes import at
+# module scope. Pinned by a test against the constant there.
_ADMISSION_WAIT_MARKER = ": admission-wait"
-# renewed unconditionally: wait renewals are rate limited and the lease equals the first-token timeout
# Leaving the queue. Renewed unconditionally: wait renewals are rate limited, and the lease equals the first-token
# timeout, so any age carried in is negative margin.
_ADMISSION_DONE_MARKER = ": admission-done"
@@ -454,7 +448,6 @@ class ChatGenerationSupervisor:
return False
cancel_event = self._cancel_events.get(run_id)
if cancel_event is not None:
- # Enrich an early run-only reservation with authoritative identity.
with active_generations.ActiveGeneration(
cancel_event,
run_id = run_id,
@@ -533,9 +526,8 @@ class ChatGenerationSupervisor:
if task is not None and not task.done():
task.cancel()
active_generations.cancel_run(run_id)
- # closes the narrow gap where registration is imminent but this supervisor has not observed it
- # The inference cancel registry closes the narrow gap where registration is imminent but this supervisor has not
- # yet observed it.
+ # The inference cancel registry closes the narrow gap where registration is imminent but this supervisor has
+ # not yet observed it.
from routes.inference import _cancel_by_cancel_id_or_stash
_cancel_by_cancel_id_or_stash(run_id)
@@ -650,7 +642,6 @@ class ChatGenerationSupervisor:
error = "Studio shut down during generation" if shutting_down else None,
)
return
- # spans the lifecycle gate too: a run waiting on the gate is still queued
# Spans the lifecycle gate as well as preparation: a run waiting on the gate is still queued, so its lease
# ages from created_at with nothing renewing it.
async with self._lease_heartbeat(run_id):
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index 8037b6ac51d..828ecad5e91 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -1,11 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Dependency-light wrapper around tokenizer.apply_chat_template with a kwarg
-fallback for templates that reject reasoning/tools args, plus the shared
-native-chat-template fallback used by the transformers and MLX backends.
-"""
+"""Dependency-light wrapper around tokenizer.apply_chat_template with a kwarg fallback for templates
+that reject reasoning/tools args, plus the shared native-chat-template fallback used by the
+transformers and MLX backends."""
import copy
import functools
@@ -34,9 +32,9 @@ _GEMMA_TEMPLATE_OPENERS = (
_GEMMA_THOUGHT_OPEN + _GEMMA_THOUGHT_CLOSE,
)
-# Muse Glimmer's recipient-addressed blocks; see RecipientChannelNormalizer.
-# Both header prefixes occur: generation resumes after the prompt's trailing
-# "<|start|>assistant", so the first header arrives without it and later ones carry it.
+# Muse Glimmer's recipient-addressed blocks; see RecipientChannelNormalizer. Both header prefixes occur: generation
+# resumes after the prompt's trailing "<|start|>assistant", so the first header arrives without it and later ones
+# carry it.
_ATEM_REASONING_RECIPIENT = "self"
_ATEM_REPLY_RECIPIENT = "user"
_ATEM_CLOSE = "<|eom|>"
@@ -46,8 +44,8 @@ _ATEM_BLOCK_ENDS = (_ATEM_CLOSE, _ATEM_END_OF_TURN)
_ATEM_BLOCK_END_MAX_LEN = max(len(marker) for marker in _ATEM_BLOCK_ENDS)
_ATEM_TEMPLATE_OPENER = "<|start|>assistant to=self<|message|>"
_ATEM_HEADER_PREFIXES = ("<|start|>assistant to=", "to=")
-# Bound on a recipient so the holdback below can never be shorter than a real header.
-# Generous rather than a name cap: neither the grammar nor Studio caps a recipient.
+# Bound on a recipient so the holdback below can never be shorter than a real header. Generous rather than a name cap:
+# neither the grammar nor Studio caps a recipient.
_ATEM_RECIPIENT_MAX_LEN = 256
_ATEM_HEADER_RE = re.compile(
r"(?:<\|start\|>assistant )?to=(?P<recipient>[^<\s]{1,%d})<\|message\|>"
@@ -59,9 +57,8 @@ _ATEM_PARTIAL_TAIL_RE = re.compile(
)
# Longest holdback, derived from the same bound so the two cannot drift apart.
_ATEM_HEADER_MAX_LEN = len("<|start|>assistant to=") + _ATEM_RECIPIENT_MAX_LEN + len("<|message|>")
-# Call syntax, taken verbatim from the response_template grammar the checkpoint ships:
-# a call repeats with no enclosing tag, other attributes may precede "name" on the call
-# and sit either side of it on a parameter.
+# Call syntax, taken verbatim from the response_template grammar the checkpoint ships: a call repeats with no
+# enclosing tag, other attributes may precede "name" on the call and sit either side of it on a parameter.
_ATEM_INVOKE_OPEN_RE = re.compile(r'<atem:invoke\b[^>]*?\bname="(?P<name>[^"]+)">')
_ATEM_INVOKE_CLOSE = "</atem:invoke>"
_ATEM_PARAMETER_RE = re.compile(
@@ -71,8 +68,8 @@ _ATEM_PARAMETER_RE = re.compile(
# The template wraps calls in this; the grammar does not model it, so it is framing.
_ATEM_CALLS_ENVELOPE = ("<atem:function_calls>", "</atem:function_calls>")
_ATEM_TAG_START_RE = re.compile(r"</?atem:")
-# Every tag of the call syntax, for recognizing one the token budget cut in half.
-# A tag name ends where these characters stop, matching the grammar's \b.
+# Every tag of the call syntax, for recognizing one the token budget cut in half. A tag name ends where these
+# characters stop, matching the grammar's \b.
_ATEM_NAME_CHARS = frozenset(string.ascii_letters + string.digits + "_-:")
_ATEM_TAGS = (
"<atem:function_calls>",
@@ -83,189 +80,159 @@ _ATEM_TAGS = (
"</atem:parameter>",
)
-# Control markup must not reach the prompt as raw text from a user / system / tool turn:
-# "</think>" ends the reasoning block early, and "<|start|>assistant<|channel|>final
-# <|message|>" in a tool result forges an assistant turn (#7066). One lookahead over the four
-# shapes templates emit (<|name|>/<|name>, <name>/</name>, <name|>, [NAME]/[/NAME]), so one
-# sub() breaks any of them. The name list is closed on purpose, so "<div>", "List<String>",
-# "[1]" and "[inst]" stay as typed, and [THINK] is absent because no template emits it.
-# DeepSeek's fullwidth U+FF5C branch is the one open name class, because it keeps adding
-# spellings; the charset restriction keeps it off real CJK content (\uXXXX escapes keep this
-# file ASCII).
+# Control markup must not reach the prompt as raw text from a user / system / tool turn: "</think>" ends the reasoning
+# block early, and "<|start|>assistant<|channel|>final<|message|>" in a tool result forges an assistant turn (#7066).
+# One lookahead over the four shapes templates emit (<|name|>/<|name>, <name>/</name>, <name|>, [NAME]/[/NAME]), so
+# one sub() breaks any of them. The name list is closed on purpose, so "<div>", "List<String>", "[1]" and "[inst]"
+# stay as typed, and [THINK] is absent because no template emits it. DeepSeek's fullwidth U+FF5C branch is the one
+# open name class, because it keeps adding spellings; the charset restriction keeps it off real CJK content (\uXXXX
+# escapes keep this file ASCII).
_CONTROL_MARKUP = re.compile(
r"<(?="
- # "/?" after the bar: Phi-4 Mini closes with "<|/tool|>" / "<|/tool_call|>"
- # (ollama_template_mappers.py:1023, 1029) rather than a separate closing name, so an
- # MCP description carrying one closed the catalog and rose to system level (#7066).
+ # "/?" after the bar: Phi-4 Mini closes with "<|/tool|>" / "<|/tool_call|>" rather than a separate closing name,
+ # so an MCP description carrying one closed the catalog and rose to system level (#7066).
r"\|/?(?:(?:start|end)_(?:header_id|of_role)|tool(?:_call|_response)?"
- # Kimi K2 / Moonshot wrap history in a section and each call in a begin/end pair
- # (tool_call_parser.py:20, 55-56, 86-89); none is the short "tool_call" spelling,
- # so a paste could fabricate a historical call (#7066).
+ # Kimi K2 / Moonshot wrap history in a section and each call in a begin/end pair (tool_call_parser.py); none is
+ # the short "tool_call" spelling, so a paste could fabricate a historical call (#7066).
r"|tool_calls?(?:_section)?_(?:begin|end)|tool_call_argument_begin"
r"|end(?:_of_(?:turn|text))?"
- # Document boundaries: begin_of_text is Llama-3.1 / Llama-4's BOS, endoftext the
- # GPT-2-lineage EOS Qwen2.5, Qwen3, Phi, gpt-oss and GLM-4.5 all still carry. Reserved
- # vocabulary, same argument as the media placeholders below: the trie splits a pasted
- # copy back out to the real token id, so client text lands mid-conversation as a
- # document break the template never opened (#7066).
+ # Document boundaries: begin_of_text is Llama-3.1 / Llama-4's BOS, endoftext the GPT-2-lineage EOS Qwen2.5, Qwen3,
+ # Phi, gpt-oss and GLM-4.5 all still carry. Reserved vocabulary, same argument as the media placeholders below:
+ # the trie splits a pasted copy back out to the real token id, so client text lands mid-conversation as a document
+ # break the template never opened (#7066).
r"|begin_of_text|endoftext"
- # header_start / header_end / <|eot|> are Llama-4's spelling of Llama-3's
- # start_header_id / end_header_id / eot_id, and im_sep is Phi-4's role separator.
- # im_system / im_middle are Kimi K2's, alongside the ChatML three.
+ # header_start / header_end / <|eot|> are Llama-4's spelling of Llama-3's start_header_id / end_header_id /
+ # eot_id, im_sep is Phi-4's role separator, and im_system / im_middle are Kimi K2's alongside the ChatML three.
r"|header_(?:start|end)|im_(?:start|end|sep|system|middle|user|assistant)"
- # DeepSeek-V4-Flash spells its role boundaries with ASCII bars and a capital, unlike R1's
- # fullwidth ones; this pattern is case-sensitive, so the lowercase names below miss them.
+ # DeepSeek-V4-Flash spells its role boundaries with ASCII bars and a capital, unlike R1's fullwidth ones; this
+ # pattern is case-sensitive, so the lowercase names below miss them.
r"|User|Assistant|System"
r"|assistant|constrain|channel|message|eo[tm](?:_id)?|final"
- # TML Inkling's call envelope, "<|message_model|>NAME<|content_invoke_tool_json|>{...}
- # <|end_message|>". Longer than the "message" / "end" names above, so all three passed
- # through even though the repo parses them as a tool call (tool_call_parser.py:58,
- # tool_healing.py:129-132, 701-707).
+ # TML Inkling's call envelope, "<|message_model|>NAME<|content_invoke_tool_json|>{...}<|end_message|>". Longer
+ # than the "message" / "end" names above, so all three passed through even though the repo parses them as a tool
+ # call.
r"|message_model|content_invoke_tool_json|end_message"
# Command-R / Aya spell every delimiter in caps: <|START_OF_TURN_TOKEN|> etc.
r"|(?:START|END)_OF_TURN_TOKEN|(?:USER|SYSTEM|CHATBOT)_TOKEN"
- # Gemma-4's media placeholders (chat_templates.py:917-921) and Llama-3.1's built-in-tool
- # sentinel (:496). Reserved vocabulary, so a pasted copy is not cosmetic: a processor
- # counts "<|image|>" against the media it was handed, and one extra is a hard ValueError
+ # Gemma-4's media placeholders and Llama-3.1's built-in-tool sentinel. Reserved vocabulary, so a pasted copy is
+ # not cosmetic: a processor counts "<|image|>" against the media it was handed, and one extra is a hard ValueError
# out of MllamaProcessor / Gemma4Processor (#7066).
r"|image|audio|video|python_tag"
- # Qwen 2.5 Coder builds its fill-in-the-middle prompt from these three special
- # tokens (ollama_template_mappers.py:881) while interpolating chat .Content at
- # :908-909, the pipe-token equivalent of Codestral's [PREFIX]/[MIDDLE]/[SUFFIX].
+ # Qwen 2.5 Coder builds its fill-in-the-middle prompt from these three special tokens while interpolating chat
+ # .Content, the pipe-token equivalent of Codestral's [PREFIX]/[MIDDLE]/[SUFFIX].
r"|fim_prefix|fim_suffix|fim_middle"
- # Qwen2-VL / Qwen2.5-VL reserve these for the processor, which expands a pad token
- # per image or video patch (mapper.py:679-697). A pasted one is counted as media
- # with no image behind it, so embeddings bind at the wrong prompt position.
+ # Qwen2-VL / Qwen2.5-VL reserve these for the processor, which expands a pad token per image or video patch. A
+ # pasted one is counted as media with no image behind it, so embeddings bind at the wrong prompt position.
r"|vision_start|vision_end|vision_pad|image_pad|video_pad"
r"|return|system|start|think|turn|user|call|\")\|?>"
- # The parser also recognises the space and backslash-escaped spellings of these openers
- # (tool_call_parser.py:47-53, 62-66), so the class admits both. The name must still start
- # with a letter, keeping "<\uff5c \uff5c>" and other fullwidth-punctuation pairs out.
+ # The parser also recognises the space and backslash-escaped spellings of these openers, so the class admits both.
+ # The name must still start with a letter, keeping "<\uff5c \uff5c>" and other fullwidth-punctuation pairs out.
r"|\uff5c[A-Za-z][A-Za-z\u2581_ \\]{0,39}\uff5c>"
- # The bare-tag families. A "</tools>" in client text closes the real Qwen / Hermes
- # catalog and the rest reads as undeclared tools; Gemma 3 / 3n media placeholders
- # (chat_templates.py:677, 845-847) and Gemma's bare BOS / EOS are the same shape. GLM
- # 4.5-4.7 and Qwen3.5 nest their call protocol inside the outer tag, and tool_call_parser
- # treats every level as structural, so a replayed value can close one and inject another
- # key or call. "<s>" / "</s>" are the Llama-2 / Mistral / Zephyr BOS / EOS: the one
- # addition that collides with a real HTML tag, accepted because a live document boundary
- # beats a space in a rare <s> (#7066).
+ # The bare-tag families. A "</tools>" in client text closes the real Qwen / Hermes catalog and the rest reads as
+ # undeclared tools; Gemma 3 / 3n media placeholders and Gemma's bare BOS / EOS are the same shape. GLM 4.5-4.7 and
+ # Qwen3.5 nest their call protocol inside the outer tag, and tool_call_parser treats every level as structural, so
+ # a replayed value can close one and inject another key or call. "<s>" / "</s>" are the Llama-2 / Mistral / Zephyr
+ # BOS / EOS: the one addition that collides with a real HTML tag, accepted because a live document boundary beats
+ # a space in a rare <s> (#7066).
r"|/?(?:(?:start|end)_of_turn|tool_(?:call|response)|tools|think|eos|bos|s|sop"
r"|start_of_image|image_soft_token|audio_soft_token"
r"|arg_key|arg_value|function|parameter|param)>"
- # The opening halves carry an "=value", so they need their own anchor. The parser accepts
- # both opener spellings (tool_call_parser.py:_TOOL_CLOSED_PATS), so the attribute form
- # needs its own alternative rather than riding on "function=".
+ # The opening halves carry an "=value", so they need their own anchor. The parser accepts both opener spellings,
+ # so the attribute form needs its own alternative rather than riding on "function=".
r"|(?:function|parameter)=|(?:function|param(?:eter)?)\s+name=\""
r"|(?:tool(?:_call|_response)?|channel|turn)\|>"
r")"
- # "[ARGS]", "[CALL_ID]" and "[TOOL_CONTENT]" are absent on purpose: all three are
- # metadata WITHIN a block whose openers are already broken, so none can start or close
- # anything alone, and inbound they are read out of model output (tool_healing.py:36-56).
- # "[ARGS]" also collides with the CLI-synopsis metavariable, and inside a schema "enum"
- # it would become a grammar literal the model must emit. Codestral builds its FIM prompt
- # from [PREFIX]/[MIDDLE]/[SUFFIX] while the chat branch of the same template interpolates
- # .Content between [INST] and [/INST] (ollama_template_mappers.py:266-286) (#7066).
+ # "[ARGS]", "[CALL_ID]" and "[TOOL_CONTENT]" are absent on purpose: all three are metadata WITHIN a block whose
+ # openers are already broken, so none can start or close anything alone, and inbound they are read out of model
+ # output. "[ARGS]" also collides with the CLI-synopsis metavariable, and inside a schema "enum" it would become a
+ # grammar literal the model must emit. Codestral builds its FIM prompt from [PREFIX]/[MIDDLE]/[SUFFIX] while the
+ # chat branch of the same template interpolates .Content between [INST] and [/INST] (#7066).
r"|\[(?=/?(?:INST|SYSTEM_PROMPT|AVAILABLE_TOOLS|TOOL_RESULTS|TOOL_CALLS"
r"|PREFIX|MIDDLE|SUFFIX|gMASK)\])"
- # Llama-2 opens its system block with "<<SYS>>" INSIDE the first [INST], so the doubled
- # angle is the opener, not a single "<". Both meta-llama/Llama-2-*-chat-hf's template and
- # the "llama" entry MODEL_TO_TEMPLATE_MAPPER installs at generate time emit it, and a
- # later user turn carries no system block, so a pasted pair invents one (#7066). Anchored
- # on the second "<", so "<SYS>>", "cout << SYS" and a heredoc "<<-'SYS'" stay as typed.
+ # Llama-2 opens its system block with "<<SYS>>" INSIDE the first [INST], so the doubled angle is the opener, not a
+ # single "<". Both the upstream template and the "llama" entry MODEL_TO_TEMPLATE_MAPPER installs at generate time
+ # emit it, and a later user turn carries no system block, so a pasted pair invents one. Anchored on the second
+ # "<", so "<SYS>>", "cout << SYS" and a heredoc "<<-'SYS'" stay as typed (#7066).
r"|(?<=<)<(?=/?SYS>>)"
)
-# Turn-boundary subset for replayed ASSISTANT content: client-controlled too, so a raw
-# boundary truncates or forges a turn (#7066). Everything else stays byte-identical, because
-# the assistant's own think / channel / tool markup is structure the template re-renders --
-# which is also why DeepSeek's fullwidth TOOL markers stay out while its role markers, the
-# Zephyr / Phi-3 sentinels, Granite, Llama-4, Command-R and Mistral pairs are all in.
+# Turn-boundary subset for replayed ASSISTANT content: client-controlled too, so a raw boundary truncates or forges a
+# turn (#7066). Everything else stays byte-identical, because the assistant's own think / channel / tool markup is
+# structure the template re-renders -- which is also why DeepSeek's fullwidth TOOL markers stay out while its role
+# markers, the Zephyr / Phi-3 sentinels, Granite, Llama-4, Command-R and Mistral pairs are all in.
_TURN_BOUNDARY_MARKUP = re.compile(
r"<(?="
r"\|/?(?:(?:start|end)_(?:header_id|of_role)"
- # Kimi spells a turn "<|im_user|>user<|im_middle|>...<|im_end|>", so the role
- # sentinels are boundaries exactly as im_system and im_middle already are.
+ # Kimi spells a turn "<|im_user|>user<|im_middle|>...<|im_end|>", so the role sentinels are boundaries exactly as
+ # im_system and im_middle already are.
r"|im_(?:start|end|sep|system|middle|user|assistant)"
r"|User|Assistant|System"
r"|end(?:_of_(?:turn|text))?|eo[tm](?:_id)?|header_(?:start|end)"
- # A document boundary is never the assistant's own structure, so unlike think / channel /
- # tool markup these belong in the replay subset too.
+ # A document boundary is never the assistant's own structure, so unlike think / channel / tool markup these belong
+ # in the replay subset too.
r"|begin_of_text|endoftext"
r"|(?:START|END)_OF_TURN_TOKEN|(?:USER|SYSTEM|CHATBOT)_TOKEN"
- # A media placeholder is reserved vocabulary, not reasoning or tool structure: a replayed
- # one is media the processor was handed none of, failing the Gemma / mllama count check.
- # Never legitimate in a replay, unlike think / channel / tool markup.
+ # A media placeholder is reserved vocabulary, not reasoning or tool structure: a replayed one is media the
+ # processor was handed none of, failing the Gemma / mllama count check. Never legitimate in a replay, unlike think
+ # / channel / tool markup.
r"|image|audio|video|python_tag"
- # Qwen 2.5 Coder builds its fill-in-the-middle prompt from these three special
- # tokens (ollama_template_mappers.py:881) while interpolating chat .Content at
- # :908-909, the pipe-token equivalent of Codestral's [PREFIX]/[MIDDLE]/[SUFFIX].
+ # Qwen 2.5 Coder builds its fill-in-the-middle prompt from these three special tokens while interpolating chat
+ # .Content, the pipe-token equivalent of Codestral's [PREFIX]/[MIDDLE]/[SUFFIX].
r"|fim_prefix|fim_suffix|fim_middle"
- # Qwen2-VL / Qwen2.5-VL reserve these for the processor, which expands a pad token
- # per image or video patch (mapper.py:679-697). A pasted one is counted as media
- # with no image behind it, so embeddings bind at the wrong prompt position.
+ # Qwen2-VL / Qwen2.5-VL reserve these for the processor, which expands a pad token per image or video patch. A
+ # pasted one is counted as media with no image behind it, so embeddings bind at the wrong prompt position.
r"|vision_start|vision_end|vision_pad|image_pad|video_pad"
- # A tool RESULT is the tool role's structure and a tool CATALOG is the system's, so a
- # replay carrying either fabricates trusted context. The tool CALL spellings stay out:
- # those the assistant does emit. "tool" alone is Phi-4 Mini's catalog wrapper around
- # .Tools (ollama_template_mappers.py:1022-1029), not its call syntax.
+ # A tool RESULT is the tool role's structure and a tool CATALOG is the system's, so a replay carrying either
+ # fabricates trusted context. The tool CALL spellings stay out: those the assistant does emit. "tool" alone is
+ # Phi-4 Mini's catalog wrapper around .Tools, not its call syntax.
r"|tool_response|tool"
r"|assistant|return|system|start|turn|user|call)\|?>"
r"|\uff5c(?:User|Assistant|(?:begin|end)\u2581of\u2581sentence)\uff5c>"
- # "/?" as in the control pattern: Gemma's delimiters are bare tags, so a replayed
- # "</start_of_turn>" is as much a boundary as "<start_of_turn>".
- # "tools" is the Qwen catalog block around the system turn (chat_templates.py:556-568).
+ # "/?" as in the control pattern: Gemma's delimiters are bare tags, so a replayed "</start_of_turn>" is as much a
+ # boundary as "<start_of_turn>". "tools" is the Qwen catalog block around the system turn.
r"|/?(?:(?:start|end)_of_turn|eos|bos|s|sop|tool_response|tools"
r"|start_of_image|image_soft_token|audio_soft_token)>"
r"|(?:turn|tool_response)\|>"
r")"
- # Same split in the bracket family: Mistral renders assistant .Content verbatim and
- # spells the observation and catalog blocks itself (ollama_template_mappers.py:125-127,
- # 133, 123), so a replay can forge either. "[TOOL_CALLS]" is out, the assistant emits
- # that one (:129); the FIM tokens are stop tokens, so a replay carrying one did not come
- # from the model (:284-286).
+ # Same split in the bracket family: Mistral renders assistant .Content verbatim and spells the observation and
+ # catalog blocks itself, so a replay can forge either. "[TOOL_CALLS]" is out, the assistant emits that one; the
+ # FIM tokens are stop tokens, so a replay carrying one did not come from the model.
r"|\[(?=/?(?:INST|SYSTEM_PROMPT|AVAILABLE_TOOLS|TOOL_RESULTS"
r"|PREFIX|MIDDLE|SUFFIX|gMASK)\])"
- # Llama-2's system section is a boundary for the same reason [SYSTEM_PROMPT] is: the
- # template only emits it in the first user turn, never an assistant one.
+ # Llama-2's system section is a boundary for the same reason [SYSTEM_PROMPT] is: the template only emits it in the
+ # first user turn, never an assistant one.
r"|(?<=<)<(?=/?SYS>>)"
)
-# TTS is not a chat template: the codec prompt is concatenated, so the text sits between
-# codec delimiters (inference.py:1918, 1948-1954, llama_cpp.py:_TTS_PROMPTS) and a pasted
-# closer truncates or garbles the audio. Per codec, and deliberately NOT the chat sweep: this
-# text is meant to be SPOKEN, so "please say <s>hello</s>" must reach the tokenizer as typed
-# (#7066).
+# TTS is not a chat template: the codec prompt is concatenated, so the text sits between codec delimiters and a pasted
+# closer truncates or garbles the audio. Per codec, and deliberately NOT the chat sweep: this text is meant to be
+# SPOKEN, so "please say <s>hello</s>" must reach the tokenizer as typed (#7066).
_MOSS_TTS_MARKUP = re.compile(
r"<(?=/?user_inst>|\|(?:im_(?:start|end)|audio(?:_start|_end|_pad)?"
r"|vision_pad|video_pad)\|>)"
)
_TTS_MARKUP_BY_CODEC = {
- # <custom_token_3>{text}<|eot_id|><custom_token_4>, stop <custom_token_2>. Those three
- # only, not any number: the transformers path spells the same ones as bare ids
- # (inference.py:1886-1888), so "say <custom_token_999>" is ordinary text here.
+ # <custom_token_3>{text}<|eot_id|><custom_token_4>, stop <custom_token_2>. Those three only, not any number: the
+ # transformers path spells the same ones as bare ids, so "say <custom_token_999>" is ordinary text here.
"snac": re.compile(r"<(?=custom_token_[234]>|\|eot_id\|>)"),
- # <|task_tts|><|start_content|>{text}<|end_content|><|start_global_token|>,
- # stop <|im_end|> and </s>.
+ # <|task_tts|><|start_content|>{text}<|end_content|><|start_global_token|>, stop <|im_end|> and </s>.
"bicodec": re.compile(
r"<(?=\|(?:task_tts|(?:start|end)_(?:content|global_token|semantic_token)"
r"|im_end)\|>|/s>)"
),
- # <|im_start|>\n<|text_start|>{text}<|text_end|>\n<|audio_start|>
- # <|global_features_start|>\n, stop <|im_end|> and <|audio_end|>.
+ # <|im_start|>\n<|text_start|>{text}<|text_end|>\n<|audio_start|><|global_features_start|>\n, stop <|im_end|> and
+ # <|audio_end|>.
"dac": re.compile(
r"<(?=\|(?:im_(?:start|end)|text_(?:start|end)|audio_(?:start|end)"
r"|global_features_(?:start|end))\|>)"
),
- # _generate_csm interpolates into "[speaker_id]text" (inference.py:1943-1948) and the
- # processor tokenizes that flat string, so a "[1]" ANYWHERE reads as a second speaker
- # turn, not just a leading one. "<|AUDIO|>" / "<|audio_eos|>" are the codec's own tokens
- # (model_config.py:992-995), and add_special_tokens = True makes the document boundaries
- # forgeable from the text too (#7066).
+ # _generate_csm interpolates into "[speaker_id]text" and the processor tokenizes that flat string, so a "[1]"
+ # ANYWHERE reads as a second speaker turn, not just a leading one. "<|AUDIO|>" / "<|audio_eos|>" are the codec's
+ # own tokens, and add_special_tokens = True makes the document boundaries forgeable from the text too (#7066).
"csm": re.compile(r"\[(?=\d+\])|<(?=\|(?:AUDIO|audio_eos|begin_of_text|end_of_text)\|>)"),
- # Higgs TTS 2 renders scene and chat-role boundaries before opening the audio stream.
- # Both the spoken text and the scene description are inserted verbatim by its template.
+ # Higgs TTS 2 renders scene and chat-role boundaries before opening the audio stream. Both the spoken text and the
+ # scene description are inserted verbatim by its template.
"higgs_tts2": re.compile(
r"<(?=\|(?:begin_of_text|end_of_text|start_header_id|end_header_id"
r"|scene_desc_start|scene_desc_end|eot_id|audio_out_bos|AUDIO_OUT"
@@ -278,55 +245,50 @@ _TTS_MARKUP_BY_CODEC = {
r"<(?=\|(?:im_(?:start|end)|caption_(?:start|end)|lyrics_(?:start|end)"
r"|audio_(?:start|end|cfg))\|>)"
),
- # MOSS Local and Nano wrap client text in a user_inst block inside a ChatML turn.
- # The remaining sentinels are codec placeholders accepted by their processors.
+ # MOSS Local and Nano wrap client text in a user_inst block inside a ChatML turn. The remaining sentinels are
+ # codec placeholders accepted by their processors.
"moss_tts_local": _MOSS_TTS_MARKUP,
"moss_tts_nano": _MOSS_TTS_MARKUP,
}
-# An unrecognised codec gets the union: still far narrower than the chat sweep, but it does
-# not assume a prompt shape this module has not seen.
+# An unrecognised codec gets the union: still far narrower than the chat sweep, but it does not assume a prompt shape
+# this module has not seen.
_TTS_MARKUP_DEFAULT = re.compile(
"|".join(f"(?:{pattern.pattern})" for pattern in _TTS_MARKUP_BY_CODEC.values())
)
-# A delimiter-shaped token: "<...>" or "[...]" with no whitespace inside, which is the
-# only shape any template in this module uses as structure. Ordinary added tokens such as a
-# plain word or a "\u2581" piece are not delimiters and are left alone.
+# A delimiter-shaped token: "<...>" or "[...]" with no whitespace inside, which is the only shape any template in this
+# module uses as structure. Ordinary added tokens such as a plain word or a "\u2581" piece are left alone.
_DELIMITER_SHAPED = re.compile(r"\A(?:<[^\s<>]{1,60}>|\[[^\s\[\]]{1,40}\])\Z")
-# The same shapes, for harvesting literals a template writes out that are not vocab entries.
-# The bracket half excludes quotes and bare digits, so Jinja's own "message['content']" and
-# "messages[0]" indexing stays out of the profile. The attribute arm is the
-# "<function name=\"NAME\">" opener MiniCPM-5 and MiniMax-M2 use: it carries a space and
-# quotes, so the first arm can never see it, and without it a profile kept only the closing
-# "</function>" and left client text free to open a call envelope (#7066).
+# The same shapes, for harvesting literals a template writes out that are not vocab entries. The bracket half excludes
+# quotes and bare digits, so Jinja's own "message['content']" and "messages[0]" indexing stays out of the profile. The
+# attribute arm is the "<function name=\"NAME\">" opener MiniCPM-5 and MiniMax-M2 use: it carries a space and quotes,
+# so the first arm can never see it, and without it a profile kept only the closing "</function>" and left client text
+# free to open a call envelope (#7066).
_TEMPLATE_DELIMITERS = re.compile(
'<[A-Za-z_][A-Za-z0-9_.\\-]{0,38}\\s+[A-Za-z_][A-Za-z0-9_.\\-]{0,38}="[^"<>]{0,60}">'
- # Before the single-angle arm: that would match Llama-2's inner "<SYS>", which the
- # structure gate then drops, leaving the real "<<SYS>>" opener unbroken (#7066).
+ # Before the single-angle arm: that would match Llama-2's inner "<SYS>", which the structure gate then drops,
+ # leaving the real "<<SYS>>" opener unbroken (#7066).
"|<</?[A-Za-z_][A-Za-z0-9_.\\-]{0,38}>>"
"|<[^\\s<>'\"]{1,60}>"
"|\\[/?[A-Za-z_][A-Za-z0-9_.\\-]{0,38}\\]"
)
-# "{# ... #}" never reaches the prompt. The shipped gptoss template mentions "<|final|>"
-# only in a comment (chat_templates.py:1311) while the live protocol emits
-# "<|channel|>final<|message|>", so harvesting comment text rewrote ordinary user and tool
-# text containing "<|final|>" (#7066).
+# "{# ... #}" never reaches the prompt. The shipped gptoss template mentions "<|final|>" only in a comment while the
+# live protocol emits "<|channel|>final<|message|>", so harvesting comment text rewrote ordinary user and tool text
+# containing "<|final|>" (#7066).
_JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.S)
-# Metadata WITHIN a block, never its opener, so with the openers broken none can start or
-# close anything alone. Harvesting them from a Mistral-style template would reintroduce the
-# false rewrite the curated list above documents avoiding (#7066).
+# Metadata WITHIN a block, never its opener, so with the openers broken none can start or close anything alone.
+# Harvesting them from a Mistral-style template would reintroduce the false rewrite the curated list above documents
+# avoiding (#7066).
_BLOCK_METADATA = frozenset({"[ARGS]", "[CALL_ID]", "[TOOL_CONTENT]"})
-# A template that builds its role sentinel by concatenation, "'<|' + message['role'] + '|>'"
-# (Phi-3, chat_templates.py:383), never writes "<|system|>" as a literal, so harvesting
-# literals alone left it out of a profile that any static delimiter elsewhere still made
-# non-empty -- and non-empty is what disables the curated fallback. Both operators: "~" is
-# Jinja's own, and accepting only "+" missed the valid spelling entirely (#7066).
+# A template that builds its role sentinel by concatenation, "'<|' + message['role'] + '|>'" (Phi-3), never writes
+# "<|system|>" as a literal, so harvesting literals alone left it out of a profile that any static delimiter elsewhere
+# still made non-empty -- and non-empty is what disables the curated fallback. Both operators: "~" is Jinja's own, and
+# accepting only "+" missed the valid spelling entirely (#7066).
_DYNAMIC_PIPE_ROLE = re.compile(r"""['"]<\|['"]\s*[+~]|[+~]\s*['"]\|>['"]""")
-# The roles a chat template can interpolate. Closed on purpose: exactly what the
-# construction can emit, rather than re-enabling a match on any "<|word|>".
-# The equals-form opener is built the same way, "{{ '<function=' + call.name + '>' }}", so
-# no complete literal appears; harvesting closers alone left "<function=pay>" byte-exact for
+# The roles a chat template can interpolate. Closed on purpose: exactly what the construction can emit, rather than
+# re-enabling a match on any "<|word|>". The equals-form opener is built the same way, "{{ '<function=' + call.name +
+# '>' }}", so no complete literal appears; harvesting closers alone left "<function=pay>" byte-exact for
# tool_call_parser to read as a live call envelope (#7066).
_CONCATENATED_OPENER = re.compile(r"""['"]<(/?[A-Za-z_][A-Za-z0-9_.\-]{0,30})=['"]\s*[+~]""")
@@ -341,9 +303,8 @@ _ROLE_NAMES = (
"developer",
"human",
)
-# A marker whose name is filled in at render time, so a template only ever shows one
-# example. "<function=pay>" must break on a model whose template spells
-# "<function=example>", which an alternation over literals alone cannot do.
+# A marker whose name is filled in at render time, so a template only ever shows one example. "<function=pay>" must
+# break on a model whose template spells "<function=example>", which an alternation over literals alone cannot do.
_DYNAMIC_OPENER = re.compile(r"\A<(/?[A-Za-z_][A-Za-z0-9_.\-]{0,30})=[^\s<>]*>\Z")
# The attribute spelling of the same thing: the value is the render-time name.
_DYNAMIC_ATTR_OPENER = re.compile(
@@ -351,22 +312,19 @@ _DYNAMIC_ATTR_OPENER = re.compile(
)
-# DeepSeek spells one marker several ways: "<\uff5ctool\u2581calls\u2581begin\uff5c>" in the
-# vocabulary, but tool_call_parser.py:47-53 also accepts the space and backslash-escaped
-# spellings. The curated fullwidth arm matched any name between the bars, so all three broke;
-# an exact literal from the profile breaks only the one the vocabulary happens to hold, and a
-# pasted alias opens a tool-call envelope (#7066).
+# DeepSeek spells one marker several ways: "<\uff5ctool\u2581calls\u2581begin\uff5c>" in the vocabulary, but
+# tool_call_parser also accepts the space and backslash-escaped spellings. The curated fullwidth arm matched any name
+# between the bars, so all three broke; an exact literal from the profile breaks only the one the vocabulary happens
+# to hold, and a pasted alias opens a tool-call envelope (#7066).
_FULLWIDTH_MARKER = re.compile("\\A<\uff5c([A-Za-z][A-Za-z\u2581_ \\\\]{0,39})\uff5c>\\Z")
_ALIAS_SEPARATORS = "(?:\u2581|\\\\?_| )"
@functools.lru_cache(maxsize = 1)
def _deepseek_opener_pattern():
- """The tool-call-parser's own DeepSeek opener alternation, or None if unavailable.
-
- Single source of truth: tool_call_parser keeps the five spellings llama.cpp accepts,
- and a profile that breaks only the one spelling a vocabulary happens to hold leaves the
- other four live (#7066)."""
+ """The tool-call-parser's own DeepSeek opener alternation, or None if unavailable. Single source
+ of truth: tool_call_parser keeps the five spellings llama.cpp accepts, and a profile that
+ breaks only the one spelling a vocabulary happens to hold leaves the other four live (#7066)."""
try:
from core.inference.tool_call_parser import (
_DEEPSEEK_OPEN_RE_SRC,
@@ -374,8 +332,8 @@ def _deepseek_opener_pattern():
)
except Exception: # pragma: no cover - parser unavailable
return None
- # The outer-block alternation plus every fullwidth signal the parser flips on, which is
- # where the per-call "<\uff5ctool\u2581call\u2581begin\uff5c>" lives.
+ # The outer-block alternation plus every fullwidth signal the parser flips on, which is where the per-call
+ # "<\uff5ctool\u2581call\u2581begin\uff5c>" lives.
signals = [
re.escape(signal)
for signal in TOOL_XML_SIGNALS
@@ -388,10 +346,10 @@ def _marker_pattern_source(marker: str) -> str:
"""The regex for one harvested marker: exact, unless its name is dynamic."""
fullwidth = _FULLWIDTH_MARKER.match(marker)
if fullwidth:
- # The parser accepts DeepSeek aliases that are not separator respellings at all,
- # such as the short and singular opener spellings. Reuse its own alternation rather
- # than restating it, so the two cannot drift and a profiled prompt is never handed an
- # envelope the parser honours but the profile never learned to break (#7066).
+ # The parser accepts DeepSeek aliases that are not separator respellings at all, such as the short and
+ # singular opener spellings. Reuse its own alternation rather than restating it, so the two cannot drift and a
+ # profiled prompt is never handed an envelope the parser honours but the profile never learned to break
+ # (#7066).
deepseek = _deepseek_opener_pattern()
if deepseek is not None and re.fullmatch(deepseek, marker):
return deepseek
@@ -405,18 +363,17 @@ def _marker_pattern_source(marker: str) -> str:
return "<" + re.escape(dynamic.group(1)) + "=[^\\s<>]*>"
attr = _DYNAMIC_ATTR_OPENER.match(marker)
if attr:
- # Whitespace stays loose: a template may render one space where a client sends
- # several, and both open the same envelope.
+ # Whitespace stays loose: a template may render one space where a client sends several, and both open the same
+ # envelope.
return "<" + re.escape(attr.group(1)) + "\\s+" + re.escape(attr.group(2)) + '="[^"<>]*">'
return re.escape(marker)
def _template_strings(chat_template) -> list:
- """Every template body a tokenizer exposes, whatever shape it uses.
-
- A tokenizer may carry one string, a dict of named templates, or a list of
- ``{"name", "template"}`` entries (Hermes-3 ships the list form). Profiling only the
- string case would silently drop every literal a named template emits."""
+ """Every template body a tokenizer exposes, whatever shape it uses. A tokenizer may carry one
+ string, a dict of named templates, or a list of ``{"name", "template"}`` entries (Hermes-3
+ ships the list form). Profiling only the string case would silently drop every literal a
+ named template emits."""
out: list = []
if isinstance(chat_template, str):
out.append(chat_template)
@@ -438,14 +395,12 @@ def delimiter_shaped_tokens(tokens) -> list:
class ModelMarkup:
- """The markers one model actually treats as structure, and the patterns for them.
-
- Built from the model's own chat template and token list rather than from the curated
- patterns below, because a vocabulary is authoritative where a hand-written list cannot
- be: it covers a sentinel this module never enumerated, and it leaves alone one that
- belongs to some other family. A Llama-3 checkpoint has no "</think>" in either place,
- so a user pasting a script that contains one keeps their text byte-for-byte (#7066).
- """
+ """The markers one model actually treats as structure, and the patterns for them. Built from the
+ model's own chat template and token list rather than from the curated patterns below, because
+ a vocabulary is authoritative where a hand-written list cannot be: it covers a sentinel this
+ module never enumerated, and it leaves alone one that belongs to some other family. A Llama-3
+ checkpoint has no "</think>" in either place, so a user pasting a script that contains one
+ keeps their text byte-for-byte (#7066)."""
__slots__ = (
"control",
@@ -453,8 +408,8 @@ class ModelMarkup:
"markers",
"rewrite_control",
"rewrite_boundary",
- # Which named template this profile was selected for, so a caller whose catalog
- # emptied during sanitizing can tell its profile is now for the wrong one (#7066).
+ # Which named template this profile was selected for, so a caller whose catalog emptied during sanitizing can
+ # tell its profile is now for the wrong one (#7066).
"selected_with_tools",
)
@@ -466,20 +421,18 @@ class ModelMarkup:
self.markers = markers
self.selected_with_tools = selected_with_tools
self.control = _alternation(markers)
- # Which of the model's own markers open a turn. The curated patterns hold the one
- # thing a vocabulary cannot say: whether the ASSISTANT legitimately emits a marker.
- # A marker this module does not recognise at all is treated as a boundary, since a
- # replayed assistant turn is client text and a forged turn costs more than a spaced
- # one in history it should not have contained.
+ # Which of the model's own markers open a turn. The curated patterns hold the one thing a vocabulary cannot
+ # say: whether the ASSISTANT legitimately emits a marker. A marker this module does not recognise at all is
+ # treated as a boundary, since a replayed assistant turn is client text and a forged turn costs more than a
+ # spaced one in history it should not have contained.
boundary = {
marker
for marker in markers
if _TURN_BOUNDARY_MARKUP.search(marker) or not _CONTROL_MARKUP.search(marker)
}
self.boundary = _alternation(boundary)
- # Bound once per profile, not per call: a fresh partial each time would be a fresh
- # identity, so a sweep cache keyed on the callable would never hit and would grow
- # one entry per message instead.
+ # Bound once per profile, not per call: a fresh partial each time would be a fresh identity, so a sweep cache
+ # keyed on the callable would never hit and would grow one entry per message instead.
self.rewrite_control = functools.partial(neutralize_control_markup, markup = self)
self.rewrite_boundary = functools.partial(neutralize_turn_boundary_markup, markup = self)
@@ -493,9 +446,8 @@ def _alternation(markers: set):
)
-# The special-token variables a chat template may emit instead of writing the literal.
-# Llama-3.1 opens with "{{ bos_token }}", so the concrete spelling is never in the template
-# text and a literal-only scan cannot see it.
+# The special-token variables a chat template may emit instead of writing the literal. Llama-3.1 opens with "{{
+# bos_token }}", so the concrete spelling is never in the template text and a literal-only scan cannot see it.
_SPECIAL_TOKEN_VARIABLES = (
"bos_token",
"eos_token",
@@ -514,33 +466,30 @@ def model_markup(
prefer_tool_use: bool = True,
specials = None,
) -> Optional[ModelMarkup]:
- """Profile one model's structural markers, or None when nothing is known about it.
-
- None means "sweep everything the curated patterns know", which is the safe direction
- for a model whose template and vocabulary could not be read.
- """
+ """Profile one model's structural markers, or None when nothing is known about it. None means
+ "sweep everything the curated patterns know", which is the safe direction for a model whose
+ template and vocabulary could not be read."""
markers: set = set()
for token in tokens or ():
- # A base vocabulary is six figures and almost none of it can be a delimiter, so the
- # cheap first-character test runs before the regex: this is walked once per model.
+ # A base vocabulary is six figures and almost none of it can be a delimiter, so the cheap first-character test
+ # runs before the regex: this is walked once per model.
if not isinstance(token, str) or not token or token[0] not in "<[":
continue
if not _DELIMITER_SHAPED.match(token):
continue
if token in _BLOCK_METADATA:
continue
- # A vocabulary entry proves the string has a token, not that anything treats it as
- # structure: Gemma reserves "<table>" and "<caption>", and harvesting the whole
- # delimiter-shaped vocabulary mangled HTML into "< table>< caption>". The curated
- # pattern is the repo's record of what the renderer and parsers DO treat as
- # structure, so this side is the intersection: granite's "</think>" is kept, its
- # template never emitting it and its vocabulary marking it special=False (#7066).
+ # A vocabulary entry proves the string has a token, not that anything treats it as structure: Gemma reserves
+ # "<table>" and "<caption>", and harvesting the whole delimiter-shaped vocabulary mangled HTML into "< table><
+ # caption>". The curated pattern is the repo's record of what the renderer and parsers DO treat as structure,
+ # so this side is the intersection: granite's "</think>" is kept, its template never emitting it and its
+ # vocabulary marking it special=False (#7066).
if _CONTROL_MARKUP.search(token):
markers.add(token)
known = {token for token in tokens or () if isinstance(token, str)}
- # Only the template this request will render with. A named-template dict carries both
- # "default" and "tool_use", and unioning them made a no-tools turn rewrite "<tools>",
- # which cannot appear in the prompt it is about to send (#7066).
+ # Only the template this request will render with. A named-template dict carries both "default" and "tool_use",
+ # and unioning them made a no-tools turn rewrite "<tools>", which cannot appear in the prompt it is about to send
+ # (#7066).
bodies = _selected_template_strings_from_value(
chat_template, tools, prefer_tool_use = prefer_tool_use
)
@@ -551,40 +500,37 @@ def model_markup(
for match in _TEMPLATE_DELIMITERS.finditer(body):
marker = match.group(0)
if marker.startswith("[") and _within(expressions, match.start()):
- # Real indexing only where Jinja evaluates it: reading the character before
- # the bracket instead took "{{ 'prefix[ZETA]' }}" for an index, and the
- # vocabulary pass rejects unknown families so the marker was lost (#7066).
+ # Real indexing only where Jinja evaluates it: reading the character before the bracket instead took
+ # "{{ 'prefix[ZETA]' }}" for an index, and the vocabulary pass rejects unknown families so the marker
+ # was lost (#7066).
continue
if marker in _BLOCK_METADATA:
continue
- # A literal a template writes out is structure when the tokenizer has a token
- # for it, or when the curated pattern already knows it. Neither holds for the
- # instructional placeholders Qwen prints inside its tool-use prose,
- # "<function-name>" and "<args-json-object>" (chat_templates.py:561, 716):
- # those are words the model reads, and rewriting them mangles ordinary code and
- # tool descriptions that mention them (#7066).
+ # A literal a template writes out is structure when the tokenizer has a token for it, or when the curated
+ # pattern already knows it. Neither holds for the instructional placeholders Qwen prints inside its
+ # tool-use prose, "<function-name>" and "<args-json-object>": those are words the model reads, and
+ # rewriting them mangles ordinary code and tool descriptions that mention them (#7066).
if marker in known or _CONTROL_MARKUP.search(marker):
markers.add(marker)
- # A template that emits "{{ bos_token }}" inserts and tokenizes that value as a
- # document boundary, but its concrete spelling is never in the template text. The
- # vocabulary pass covers it only when the token was harvested, which a partial or
- # stubbed vocabulary does not guarantee, so resolve it from the tokenizer (#7066).
+ # A template that emits "{{ bos_token }}" inserts and tokenizes that value as a document boundary, but its
+ # concrete spelling is never in the template text. The vocabulary pass covers it only when the token was
+ # harvested, which a partial or stubbed vocabulary does not guarantee, so resolve it from the tokenizer
+ # (#7066).
for name, value in (specials or {}).items():
if not isinstance(value, str) or not value:
continue
if not any(name in code for code in _jinja_code(body)):
continue
- # Shape, not the curated pattern: that is only the families this repo has seen,
- # so gating on it would keep exactly what the vocabulary pass already covers and
- # miss the unknown-family boundary this is for. The tokenizer declaring the value
- # AND the template evaluating it is the proof; shape only stops a plain word from
- # becoming a marker that sweeps prose.
+ # Shape, not the curated pattern: that is only the families this repo has seen, so gating on it would keep
+ # exactly what the vocabulary pass already covers and miss the unknown-family boundary this is for. The
+ # tokenizer declaring the value AND the template evaluating it is the proof; shape only stops a plain word
+ # from becoming a marker that sweeps prose.
if value in known or _DELIMITER_SHAPED.match(value):
markers.add(value)
if _DYNAMIC_PIPE_ROLE.search(body):
markers.update(f"<|{role}|>" for role in _ROLE_NAMES)
- # "<function=" built by concatenation: record the example spelling the dynamic rule
- # already knows how to generalize, so any render-time name matches.
+ # "<function=" built by concatenation: record the example spelling the dynamic rule already knows how to
+ # generalize, so any render-time name matches.
for built in _CONCATENATED_OPENER.findall(body):
markers.add(f"<{built}=example>")
return ModelMarkup(markers, bool(tools)) if markers else None
@@ -605,14 +551,12 @@ def _spaced_out_markers(pattern, text: str) -> str:
def neutralize_control_markup(text: str, markup: "ModelMarkup" = None) -> str:
- """Break control markup in free text by spacing out the opener (#7066).
-
- "</think>" -> "< /think>", "[/INST]" -> "[ /INST]": readable, but no longer a
- delimiter to the template, the think extractor or the stop-sequence matcher. A plain
- space, because every tokenizer vocabulary has one; U+2060 can fall back to byte junk.
-
- With a *markup* profile only that model's own markers are broken, so text naming some
- other family's sentinel is left exactly as the caller wrote it."""
+ """Break control markup in free text by spacing out the opener (#7066). "</think>" -> "<
+ /think>", "[/INST]" -> "[ /INST]": readable, but no longer a delimiter to the template, the
+ think extractor or the stop-sequence matcher. A plain space, because every tokenizer
+ vocabulary has one; U+2060 can fall back to byte junk. With a *markup* profile only that
+ model's own markers are broken, so text naming some other family's sentinel is left exactly
+ as the caller wrote it."""
if markup is not None:
return _spaced_out_markers(markup.control, text) if markup.control else text
return _spaced_out(_CONTROL_MARKUP, text)
@@ -626,10 +570,9 @@ def neutralize_turn_boundary_markup(text: str, markup: "ModelMarkup" = None) ->
def neutralize_tts_prompt_text(text: str, audio_type = None) -> str:
- """Break the active codec's own delimiters in a TTS prompt (#7066).
-
- Scoped to *audio_type*: this text is spoken, so anything that is not structure in THIS
- codec's prompt has to survive byte-exact."""
+ """Break the active codec's own delimiters in a TTS prompt (#7066). Scoped to *audio_type*: this
+ text is spoken, so anything that is not structure in THIS codec's prompt has to survive
+ byte-exact."""
return _spaced_out(_TTS_MARKUP_BY_CODEC.get(audio_type, _TTS_MARKUP_DEFAULT), text)
@@ -644,15 +587,16 @@ def _neutralize_leaves(
):
"""Apply *rewrite* to every string leaf, keys included, of a nested structure.
- Iterative, not recursive: the client picks the depth, and a schema ``json.loads``
- accepts must not exhaust the interpreter stack and turn the request into a 500.
- Containers are rebuilt in reverse breadth-first order, so a child is finished before
- its parent and a repeated or self-referencing node is visited once.
+ Iterative, not recursive: the client picks the depth, and a schema ``json.loads`` accepts must
+ not exhaust the interpreter stack and turn the request into a 500. Containers are rebuilt in
+ reverse breadth-first order, so a child is finished before its parent and a repeated or
+ self-referencing node is visited once.
- Rewriting keys is not injective ("a<think>" and "a< think>" both land on "a< think>"),
- so a colliding dict keeps only the last value; *warn_on_key_collision* logs it. The
- merge stands because the alternative, keeping one key raw so both survive, would put
- the markup back in the prompt."""
+ Rewriting keys is not injective ("a<think>" and "a< think>" both land on "a< think>"), so a
+ colliding dict keeps only the last value; *warn_on_key_collision* logs it. The merge stands
+ because the alternative, keeping one key raw so both survive, would put the markup back in the
+ prompt.
+ """
if isinstance(value, str):
return rewrite(value)
if not isinstance(value, (dict, list)):
@@ -690,17 +634,15 @@ def _neutralize_leaves(
return done[id(value)]
-# A media payload stays opaque: a URL or base64 blob the processor resolves, so rewriting one
-# breaks the fetch rather than the prompt. Gated on the part's own type, because "data" and
-# "url" are ordinary content keys elsewhere: a "{'type': 'json', 'data': ...}" part is prompt
-# text Llama-3.1 serializes with tojson, and exempting it put the markup back in the prompt.
-# "input_image" is here because the MLX image counter recognises it (mlx_inference.py:130).
+# A media payload stays opaque: a URL or base64 blob the processor resolves, so rewriting one breaks the fetch rather
+# than the prompt. Gated on the part's own type, because "data" and "url" are ordinary content keys elsewhere: a
+# "{'type': 'json', 'data': ...}" part is prompt text Llama-3.1 serializes with tojson, and exempting it put the
+# markup back in the prompt. "input_image" is here because the MLX image counter recognises it.
_TOOL_RESULT_ROLES = frozenset({"tool", "ipython"})
-# The roles a template actually compares against. A role differing from one of these only by
-# case or padding is canonicalized, so the sweep and the template agree on the turn.
-# Gemma-4 maps "assistant" onto "model" and leaves an incoming "model" alone
-# (gemma-4.jinja:234), so both name the same replayed turn: they take the boundary subset
-# rather than the full sweep, and keep the assistant-only structured fields.
+# The roles a template actually compares against. A role differing from one of these only by case or padding is
+# canonicalized, so the sweep and the template agree on the turn. Gemma-4 maps "assistant" onto "model" and leaves an
+# incoming "model" alone, so both name the same replayed turn: they take the boundary subset rather than the full
+# sweep, and keep the assistant-only structured fields.
_ASSISTANT_ROLES = frozenset({"assistant", "model"})
_SCHEMA_ROLES = frozenset({"system", "user", "assistant", "tool", "ipython", "developer", "model"})
_MEDIA_PART_TYPES = frozenset(
@@ -727,16 +669,13 @@ def _redistribute_swept(
rewrite,
contiguous = None,
):
- """Sweep the joined *texts* and hand each carrier back its own share, or None.
-
- Every carrier keeps its own text in its own position: nothing is moved past a
- neighbour, so a caption still sits on the side of the item it describes.
-
- *contiguous*[i] says whether carrier i+1 directly follows carrier i in the parts list.
- Where it does not -- an image or a JSON part sits between them -- the opener is NOT
- migrated, because moving a character across a media item reorders the text around it
- and a renderer that keeps the media would bind the caption to the wrong side (#7066).
- """
+ """Sweep the joined *texts* and hand each carrier back its own share, or None. Every carrier
+ keeps its own text in its own position: nothing is moved past a neighbour, so a caption still
+ sits on the side of the item it describes. *contiguous*[i] says whether carrier i+1 directly
+ follows carrier i in the parts list; where it does not -- an image or a JSON part sits
+ between them -- the opener is NOT migrated, because moving a character across a media item
+ reorders the text around it and a renderer that keeps the media would bind the caption to the
+ wrong side (#7066)."""
swept = rewrite("".join(texts))
pieces: list = []
inserted: list = []
@@ -757,10 +696,9 @@ def _redistribute_swept(
if position < len(swept):
pieces[-1].extend(swept[position:])
inserted[-1].extend([True] * (len(swept) - position))
- # A break landing at the very start of a carrier is stripped by a renderer that trims
- # each part, which would let the marker re-form. The opener walks forward into the
- # carrier holding the rest of the marker instead, so the break sits inside one carrier.
- # Only the marker's own characters move, and only across the split they already
+ # A break landing at the very start of a carrier is stripped by a renderer that trims each part, which would let
+ # the marker re-form. The opener walks forward into the carrier holding the rest of the marker instead, so the
+ # break sits inside one carrier. Only the marker's own characters move, and only across the split they already
# straddle, so no text passes a neighbour (#7066).
for index in range(len(pieces) - 1):
if contiguous is not None and not contiguous[index]:
@@ -780,20 +718,20 @@ def _neutralize_content_parts(
):
"""Neutralize an OpenAI-style content parts list (#7066).
- Two gaps a per-part rewrite misses. A mapping part without a string "text" was passed
- through whole, yet /generate/stream accepts one and Llama-3.1 serializes the entire
- iterable with tojson. And a marker split across two adjacent text parts survived both
- sweeps, because Gemma-4 concatenates them with no separator (gemma-4.jinja:304) and
- reassembles the opener. Whitespace between them is no fix, since the sibling paths trim
- each part (gemma-4.jinja:339), so a run that only becomes a marker once joined is swept
- as one string and collapses into one part. A clean run keeps its parts."""
+ Two gaps a per-part rewrite misses. A mapping part without a string "text" was passed through
+ whole, yet /generate/stream accepts one and Llama-3.1 serializes the entire iterable with
+ tojson. And a marker split across two adjacent text parts survived both sweeps, because Gemma-4
+ concatenates them with no separator and reassembles the opener. Whitespace between them is no
+ fix, since the sibling paths trim each part, so a run that only becomes a marker once joined is
+ swept as one string and collapses into one part. A clean run keeps its parts.
+ """
parts: list = []
for part in content:
if isinstance(part, str):
parts.append(rewrite(part))
elif isinstance(part, dict):
- # isinstance first: GenerateRequest.messages is an untyped List[dict], so "type"
- # can be unhashable and the set lookup would 500 the request before rendering.
+ # isinstance first: GenerateRequest.messages is an untyped List[dict], so "type" can be unhashable and the
+ # set lookup would 500 the request before rendering.
part_type = part.get("type")
if isinstance(part_type, str) and part_type in _MEDIA_PART_TYPES and media_opaque:
opaque = {k: v for k, v in part.items() if k in _OPAQUE_PART_KEYS}
@@ -802,8 +740,8 @@ def _neutralize_content_parts(
)
parts.append({**swept, **opaque} if opaque else swept)
else:
- # Every field, not just "text": the tojson templates serialize the part
- # whole, so sweeping only "text" left the rest live (#7066).
+ # Every field, not just "text": the tojson templates serialize the part whole, so sweeping only "text"
+ # left the rest live (#7066).
parts.append(_neutralize_leaves(part, rewrite))
else:
parts.append(part)
@@ -815,10 +753,9 @@ def _neutralize_content_parts(
return part["text"]
return None
- # No part reliably separates the text around it: a renderer emits a placeholder only for
- # the media types it knows and silently drops the rest (gemma-4.jinja:334-347 drops
- # video_url, audio_url and input_image), so an apparent separator can render as nothing
- # and leave the fragments adjacent. Every text carrier is therefore one run, which costs
+ # No part reliably separates the text around it: a renderer emits a placeholder only for the media types it knows
+ # and silently drops the rest (gemma-4.jinja drops video_url, audio_url and input_image), so an apparent separator
+ # can render as nothing and leave the fragments adjacent. Every text carrier is therefore one run, which costs
# nothing now that a split marker's opener migrates instead of the run collapsing (#7066).
texts = [_text_of(part) for part in parts]
@@ -833,29 +770,27 @@ def _neutralize_content_parts(
trimmed = "".join(texts[index].strip() for index in carriers)
if rewrite(raw) == raw and rewrite(trimmed) == trimmed:
continue
- # Break the marker inside the carrier holding its opener, so each keeps its own
- # text: Llama-3.1 serializes the list in order with "message.content | tojson"
- # (chat_templates.py:517-523), so moving text between carriers would put a caption
- # on the wrong side of the item it describes (#7066).
+ # Break the marker inside the carrier holding its opener, so each keeps its own text: Llama-3.1 serializes the
+ # list in order with "message.content | tojson", so moving text between carriers would put a caption on the
+ # wrong side of the item it describes (#7066).
run = [texts[index] for index in carriers]
- # First choice: migrate an opener only between carriers that really are adjacent,
- # so nothing crosses an image or a JSON part sitting between them.
+ # First choice: migrate an opener only between carriers that really are adjacent, so nothing crosses an image
+ # or a JSON part sitting between them.
redistributed = _redistribute_swept(
run,
rewrite,
[carriers[i + 1] == carriers[i] + 1 for i in range(len(carriers) - 1)],
)
if redistributed is None:
- # The split straddles a non-text part and a trimming renderer would re-form the
- # marker. Moving the opener across that part is a smaller harm than the collapse
- # below: one marker character changes side, rather than every carrier's text
- # being pulled into the first one (#7066).
+ # The split straddles a non-text part and a trimming renderer would re-form the marker. Moving the opener
+ # across that part is a smaller harm than the collapse below: one marker character changes side, rather
+ # than every carrier's text being pulled into the first one (#7066).
redistributed = _redistribute_swept(run, rewrite)
if redistributed is None:
- # A last resort only: migrating the opener leaves the break inside a carrier for
- # every split of every marker this module knows, so nothing reaches this today.
- # It stays because collapsing is safe when redistribution somehow is not, and a
- # marker that survives a trimming renderer would be worse than reordered text.
+ # A last resort only: migrating the opener leaves the break inside a carrier for every split of every
+ # marker this module knows, so nothing reaches this today. It stays because collapsing is safe when
+ # redistribution somehow is not, and a marker that survives a trimming renderer would be worse than
+ # reordered text.
redistributed = [rewrite(trimmed)] + [""] * (len(carriers) - 1)
for index, text in zip(carriers, redistributed):
part = parts[index]
@@ -866,11 +801,9 @@ def _neutralize_content_parts(
def _differs(new, old) -> bool:
- """True when the rewrite changed *old* into *new*.
-
- The client picks the nesting depth and ``==`` recurses in C, so an overflowing
- comparison must not 500 the request. It counts as changed, keeping the neutralized
- copy: the safe direction (#7066)."""
+ """True when the rewrite changed *old* into *new*. The client picks the nesting depth and ``==``
+ recurses in C, so an overflowing comparison must not 500 the request. It counts as changed,
+ keeping the neutralized copy: the safe direction (#7066)."""
try:
return new != old
except RecursionError:
@@ -884,48 +817,42 @@ def _neutralize_argument_leaves(value, markup = None):
def _neutralized_arguments(arguments, markup = None):
- """Neutralize a replayed call's ``arguments``, or None when already clean.
-
- OpenAI ships ``arguments`` as JSON *text*, and every consumer decodes it back to an
- object AFTER this runs: ``_normalize_tool_call_arguments`` below re-renders through
- ``json.loads`` when a template rejects a string, and llama.cpp does the same in
- ``workaround::func_args_not_string``. So rewriting the raw text lets
- "\\u003ctool_call|\\u003e" through and the decoded marker forges a turn (#7066). Parse
- first, rewrite the decoded leaves, re-serialize; a clean payload stays byte-identical
- so the prefix cache still hits."""
+ """Neutralize a replayed call's ``arguments``, or None when already clean. OpenAI ships
+ ``arguments`` as JSON *text*, and every consumer decodes it back to an object AFTER this runs
+ (``_normalize_tool_call_arguments`` re-renders through ``json.loads`` when a template rejects
+ a string, and llama.cpp does the same in ``workaround::func_args_not_string``), so rewriting
+ the raw text lets "\\u003ctool_call|\\u003e" through and the decoded marker forges a turn
+ (#7066). Parse first, rewrite the decoded leaves, re-serialize; a clean payload stays
+ byte-identical so the prefix cache still hits."""
if isinstance(arguments, str):
decoded = safe = _UNPARSED
try:
decoded = json.loads(arguments)
safe = _neutralize_argument_leaves(decoded, markup)
- # RecursionError as well as a parse error: json.loads and the walk both blow the
- # stack near 1000 levels, so a valid '[' * 1000 + '0' + ']' * 1000 would 500 a
- # request the server used to forward. Fall through to the text rewrite, which cannot
- # recurse; nothing downstream can decode that payload either, so no marker hides.
+ # RecursionError as well as a parse error: json.loads and the walk both blow the stack near 1000 levels, so a
+ # valid '[' * 1000 + '0' + ']' * 1000 would 500 a request the server used to forward. Fall through to the text
+ # rewrite, which cannot recurse; nothing downstream can decode that payload either, so no marker hides.
except (ValueError, TypeError, RecursionError):
decoded = safe = _UNPARSED
if decoded is not _UNPARSED:
- # _differs, not "!=": comparing two distinct deep structures recurses in C, so
- # a payload that decoded fine could still blow the stack on the comparison and
- # 500 a request that used to forward (#7066).
+ # _differs, not "!=": comparing two distinct deep structures recurses in C, so a payload that decoded fine
+ # could still blow the stack on the comparison and 500 a request that used to forward (#7066).
if _differs(safe, decoded):
- # ensure_ascii keeps a decoded lone surrogate ("\ud800") as an escape: raw,
- # it makes the outer request unencodable and raises UnicodeEncodeError on a
- # payload that used to forward fine (#7066).
+ # ensure_ascii keeps a decoded lone surrogate ("\\ud800") as an escape: raw, it makes the outer
+ # request unencodable and raises UnicodeEncodeError on a payload that used to forward fine (#7066).
return json.dumps(safe, ensure_ascii = True)
- # Parsed clean, but the DECODE can hide a marker the template still renders:
- # a duplicate key means json.loads keeps only the last value, so
- # '{"x":"</tool_call><|im_end|>...","x":"safe"}' decodes to {"x": "safe"} while
- # Qwen3 interpolates the raw string verbatim. When the text carries markup the
- # decoded value does not, hand back the canonical re-serialization, which drops
- # the shadowed duplicate exactly as the parser would (#7066).
+ # Parsed clean, but the DECODE can hide a marker the template still renders: a duplicate key means
+ # json.loads keeps only the last value, so '{"x":"</tool_call><|im_end|>...","x":"safe"}' decodes to {"x":
+ # "safe"} while Qwen3 interpolates the raw string verbatim. When the text carries markup the decoded value
+ # does not, hand back the canonical re-serialization, which drops the shadowed duplicate exactly as the
+ # parser would (#7066).
rewrite = neutralize_control_markup if markup is None else markup.rewrite_control
if rewrite(arguments) != arguments:
return json.dumps(safe, ensure_ascii = True)
return None
new_arguments = _neutralize_argument_leaves(arguments, markup)
- # Same guard for arguments that arrived already decoded, which never passed through
- # json.loads and so were never depth-limited by it.
+ # Same guard for arguments that arrived already decoded, which never passed through json.loads and so were never
+ # depth-limited by it.
return new_arguments if _differs(new_arguments, arguments) else None
@@ -944,13 +871,12 @@ def _replayed_ids(msg: dict):
def _injective_id_map(messages: list, markup = None) -> dict:
- """Map each replayed tool-call id to a swept id that is still unique.
-
- The sweep is not injective: "call<|end|>" and "call< |end|>" both break to
- "call< |end|>". Gemma resolves a result by comparing ids and lets the last match win
- (gemma-4.jinja:289-294), so two calls sharing one id would attribute both observations
- to the same call. A collision is therefore given a numeric suffix, which is checked
- against the ids that stay as they are so it cannot land on one of those either."""
+ """Map each replayed tool-call id to a swept id that is still unique. The sweep is not
+ injective: "call<|end|>" and "call< |end|>" both break to "call< |end|>". Gemma resolves a
+ result by comparing ids and lets the last match win, so two calls sharing one id would
+ attribute both observations to the same call. A collision is therefore given a numeric
+ suffix, which is checked against the ids that stay as they are so it cannot land on one of
+ those either."""
originals: list = []
seen: set = set()
for msg in messages:
@@ -961,8 +887,8 @@ def _injective_id_map(messages: list, markup = None) -> dict:
seen.add(value)
originals.append(value)
swept = {original: neutralize_control_markup(original, markup) for original in originals}
- # Reserved first: an id the sweep leaves alone keeps its own spelling, so a rewritten
- # one must never be handed that value.
+ # Reserved first: an id the sweep leaves alone keeps its own spelling, so a rewritten one must never be handed
+ # that value.
taken = {original for original in originals if swept[original] == original}
mapping: dict = {}
for original in originals:
@@ -991,18 +917,18 @@ def _neutralize_replayed_tool_call(
) -> list:
"""Neutralize a replayed tool call's name, arguments and id, in every shape it carries.
- Gemma-4 renders "<|tool_call>call:NAME{key:<|"|>value<|"|>}<tool_call|>", so a name or
+ Gemma-4 renders "<|tool_call>call:NAME{key:<|\"|>value<|\"|>}<tool_call|>", so a name or
argument echoing pasted text can close the call block and open a "<|tool_response>" or
- "<|turn>model" of its own (#7066). The rewrite is the identity on every dispatchable
- name (Unsloth composes ^[a-zA-Z0-9_-]{1,64}$), and a tool result's "name" takes the same
- rewrite, so the two still agree when Gemma-4 pairs them by name.
-
- Both replay shapes are swept, the OpenAI nested one and the flat {"id", "name",
- "arguments"} one, rather than only whichever a particular guard would pick. Harmony /
- gpt-oss, Qwen 2.5 / 3, Granite-4 and Llama-4 select with "{%- if tool_call.function %}"
- (chat_templates.py:771-780), which is a truthiness test, so an empty nested object sends
- them to the flat fields; and a flat-shaped template reads "name" off the call whatever
- the nested object holds. Sweeping both removes the need to guess which one renders."""
+ "<|turn>model" of its own (#7066). The rewrite is the identity on every dispatchable name
+ (Unsloth composes ^[a-zA-Z0-9_-]{1,64}$), and a tool result's "name" takes the same rewrite, so
+ the two still agree when Gemma-4 pairs them by name.
+
+ Both replay shapes are swept, the OpenAI nested one and the flat {"id", "name", "arguments"}
+ one, rather than only whichever a particular guard would pick. Harmony / gpt-oss, Qwen 2.5 / 3,
+ Granite-4 and Llama-4 select with "{%- if tool_call.function %}", a truthiness test, so an empty
+ nested object sends them to the flat fields; and a flat-shaped template reads "name" off the
+ call whatever the nested object holds.
+ """
def _field_updates(source: dict) -> dict:
updates: dict = {}
@@ -1011,9 +937,8 @@ def _neutralize_replayed_tool_call(
new_name = neutralize_control_markup(name, markup)
if new_name != name:
updates["name"] = new_name
- # Harmony concatenates "content_type" straight before "<|message|>"
- # (chat_templates.py:1332-1334), so a replayed "json<|message|><|end|><|start|>"
- # closes the commentary call and opens an assistant channel (#7066).
+ # Harmony concatenates "content_type" straight before "<|message|>", so a replayed
+ # "json<|message|><|end|><|start|>" closes the commentary call and opens an assistant channel (#7066).
content_type = source.get("content_type")
if isinstance(content_type, str) and content_type:
new_content_type = neutralize_control_markup(content_type, markup)
@@ -1034,11 +959,10 @@ def _neutralize_replayed_tool_call(
function = call.get("function")
flat_updates = _field_updates(call)
nested_updates = _field_updates(function) if isinstance(function, dict) else {}
- # Kimi interpolates the id straight between "<|tool_call_begin|>" and
- # "<|tool_call_argument_begin|>", so an id carrying the closer ends the envelope the
- # template opened and injects structure after it, with the name and arguments clean
- # (#7066). Rewritten with the same function as a tool result's "tool_call_id", so a
- # replayed pair still matches on both sides.
+ # Kimi interpolates the id straight between "<|tool_call_begin|>" and "<|tool_call_argument_begin|>", so an id
+ # carrying the closer ends the envelope the template opened and injects structure after it, with the name and
+ # arguments clean (#7066). Rewritten with the same function as a tool result's "tool_call_id", so a replayed
+ # pair still matches on both sides.
id_updates: dict = {}
call_id = call.get("id")
if isinstance(call_id, str) and call_id:
@@ -1059,15 +983,15 @@ def _neutralize_replayed_tool_call(
def sweep_cache() -> dict:
"""A cache for a caller that sweeps the same history more than once.
- The agentic tool loop re-sweeps the whole conversation on every iteration, because a
- tool result lands in it as the loop goes and a forged turn in one would render for
- real. Every earlier turn is then swept again with the identical text, which is pure
- repeated work: the rewrite is a function of the string alone.
+ The agentic tool loop re-sweeps the whole conversation on every iteration, because a tool result
+ lands in it as the loop goes and a forged turn in one would render for real. Every earlier turn
+ is then swept again with identical text, which is pure repeated work: the rewrite is a function
+ of the string alone.
- The cache is handed in by the caller rather than kept here on purpose. It lives as long
- as the request that owns it and is dropped with it, so message text is never retained
- past the call in module state, and it needs no size bound because it can only ever hold
- text the caller is already holding.
+ The cache is handed in by the caller rather than kept here on purpose. It lives as long as the
+ request that owns it and is dropped with it, so message text is never retained past the call in
+ module state, and it needs no size bound because it can only ever hold text the caller is
+ already holding.
"""
return {}
@@ -1093,15 +1017,12 @@ def neutralize_control_markup_in_messages(
cache: dict = None,
markup = None,
) -> list:
- """Neutralize control markup in message content and tool-result names (#7066).
-
- User / system / tool turns lose every marker; assistant turns lose only turn boundaries
- and keep the think / channel / tool markup replayed history legitimately holds. Returns
- the same list object when nothing changed, so the prompt stays byte-for-byte what it
- was.
-
- Pass a ``sweep_cache()`` when sweeping the same growing history repeatedly; results are
- identical either way, since it only memoizes a pure rewrite."""
+ """Neutralize control markup in message content and tool-result names (#7066). User / system /
+ tool turns lose every marker; assistant turns lose only turn boundaries and keep the think /
+ channel / tool markup replayed history legitimately holds. Returns the same list object when
+ nothing changed, so the prompt stays byte-for-byte what it was. Pass a ``sweep_cache()`` when
+ sweeping the same growing history repeatedly; results are identical either way, since it only
+ memoizes a pure rewrite."""
if not messages:
return messages
changed = False
@@ -1111,9 +1032,9 @@ def neutralize_control_markup_in_messages(
if not isinstance(msg, dict):
out.append(msg)
continue
- # isinstance, not truthiness: GenerateRequest.messages is an untyped List[dict], so a
- # role can be an int and ".strip()" on one 500'd the stream before rendering.
- # A non-string is simply not "assistant", so it takes the full rewrite.
+ # isinstance, not truthiness: GenerateRequest.messages is an untyped List[dict], so a role can be an int and
+ # ".strip()" on one 500'd the stream before rendering. A non-string is simply not "assistant", so it takes the
+ # full rewrite.
raw_role_value = msg.get("role")
role = raw_role_value.strip().lower() if isinstance(raw_role_value, str) else ""
assistant = role in _ASSISTANT_ROLES
@@ -1126,26 +1047,22 @@ def neutralize_control_markup_in_messages(
rewrite = _memoized(rewrite, cache)
updates: dict = {}
dropped_keys: set = set()
- # The role is rendered, not just dispatched on: Llama-3.1 concatenates it between
- # "<|start_header_id|>" and "<|end_header_id|>", and /generate/stream takes untyped
- # dicts, so a role of "user<|end_header_id|><|eot_id|>..." forged an assistant turn
- # even with the content swept (#7066). Neutralized rather than rejected, so a client
- # using a role this code does not know still works.
+ # The role is rendered, not just dispatched on: Llama-3.1 concatenates it between "<|start_header_id|>" and
+ # "<|end_header_id|>", and /generate/stream takes untyped dicts, so a role of
+ # "user<|end_header_id|><|eot_id|>..." forged an assistant turn even with the content swept (#7066).
+ # Neutralized rather than rejected, so a client using a role this code does not know still works.
raw_role = msg.get("role")
if isinstance(raw_role, str) and raw_role:
new_role = neutralize_control_markup(raw_role, markup)
- # "Assistant" and " assistant " mean assistant here but not to a template, which
- # compares case-sensitively. That gap let a padded spelling take the lenient
- # assistant treatment while still rendering as one, so a known role is
- # canonicalized and the two agree again (#7066).
+ # "Assistant" and " assistant " mean assistant here but not to a template, which compares
+ # case-sensitively. That gap let a padded spelling take the lenient assistant treatment while still
+ # rendering as one, so a known role is canonicalized and the two agree again (#7066).
if role in _SCHEMA_ROLES and new_role != role:
new_role = role
- # Phi-3 wraps an unrecognised role as "<|" + role + "|>"
- # (chat_templates.py:382-383), so a role of "end" spells that template's own
- # turn terminator while carrying no markup of its own and passing the sweep
- # untouched. A canonical role is MEANT to render that way, so only an unknown
- # one is checked, and it falls back to the least trusted role rather than being
- # padded: a template that trims the role would undo a space (#7066).
+ # Phi-3 wraps an unrecognised role as "<|" + role + "|>", so a role of "end" spells that template's own
+ # turn terminator while carrying no markup of its own and passing the sweep untouched. A canonical role is
+ # MEANT to render that way, so only an unknown one is checked, and it falls back to the least trusted role
+ # rather than being padded: a template that trims the role would undo a space (#7066).
elif role not in _SCHEMA_ROLES:
wrapped = f"<|{new_role}|>"
if neutralize_control_markup(wrapped, markup) != wrapped:
@@ -1157,9 +1074,8 @@ def neutralize_control_markup_in_messages(
new_role = "user"
if new_role != raw_role:
updates["role"] = new_role
- # Gemma-4 falls back to a tool result's "name" when "tool_call_id" matches no
- # call, concatenating it into the "<|tool_response>" block (#7066).
- # Same rewrite as the call's "id" above, so a replayed pair still matches.
+ # Gemma-4 falls back to a tool result's "name" when "tool_call_id" matches no call, concatenating it into the
+ # "<|tool_response>" block (#7066). Same rewrite as the call's "id" above, so a replayed pair still matches.
result_id = msg.get("tool_call_id")
if isinstance(result_id, str) and result_id:
new_result_id = id_map.get(result_id, result_id)
@@ -1170,31 +1086,28 @@ def neutralize_control_markup_in_messages(
new_name = neutralize_control_markup(name, markup)
if new_name != name:
updates["name"] = new_name
- # Concatenated into the header by a recipient-addressed template, so one
- # carrying markup forged a whole system turn (#7066). Never holds delimiters.
+ # Concatenated into the header by a recipient-addressed template, so one carrying markup forged a whole system
+ # turn (#7066). Never holds delimiters.
recipient = msg.get("recipient")
if isinstance(recipient, str) and recipient:
new_recipient = neutralize_control_markup(recipient, markup)
if new_recipient != recipient:
updates["recipient"] = new_recipient
- # A separate reasoning field is the INNER text of a thought block the template wraps
- # itself (Qwen chat_templates.py:759, Gemma-4 gemma-4.jinja:245, Harmony
- # chat_templates.py:1330). None is "content", so it reached the prompt unswept and an
- # embedded closer exited the thought, exposing the rest as answer text. Hence the FULL
- # rewrite: unlike replayed "content", it must never carry its own delimiters (#7066).
+ # A separate reasoning field is the INNER text of a thought block the template wraps itself (Qwen, Gemma-4,
+ # Harmony). None is "content", so it reached the prompt unswept and an embedded closer exited the thought,
+ # exposing the rest as answer text. Hence the FULL rewrite: unlike replayed "content", it must never carry its
+ # own delimiters (#7066).
for field in ("reasoning", "reasoning_content", "thinking"):
value = msg.get(field)
if isinstance(value, str) and value:
new_value = neutralize_control_markup(value, markup)
if new_value != value:
updates[field] = new_value
- # Gemma-4's legacy assistant-level "tool_responses": format_tool_response_block
- # renders the name and every leaf, so markup there closes "<|tool_response>" and
- # opens a model turn. Tool output, so the full rewrite.
+ # Gemma-4's legacy assistant-level "tool_responses": format_tool_response_block renders the name and every
+ # leaf, so markup there closes "<|tool_response>" and opens a model turn. Tool output, so the full rewrite.
tool_responses = msg.get("tool_responses")
- # Gemma-4 reads tool_responses independently of the role (gemma-4.jinja:232-279) and
- # supplies the "<|tool_response>" wrapper itself, so a user or system message
- # carrying one fabricates a trusted observation with no marker for the sweep to
+ # Gemma-4 reads tool_responses independently of the role and supplies the "<|tool_response>" wrapper itself,
+ # so a user or system message carrying one fabricates a trusted observation with no marker for the sweep to
# catch. Assistant-only, exactly like tool_calls (#7066).
if tool_responses is not None and role not in _ASSISTANT_ROLES:
logger.warning(
@@ -1216,25 +1129,21 @@ def neutralize_control_markup_in_messages(
if isinstance(content, str):
new_content = rewrite(content)
elif isinstance(content, dict):
- # Llama-3.1 serializes mapping content with tojson (chat_templates.py:127-128)
- # and /generate/stream takes raw dicts, so object values reach the prompt as
- # live structure too (#7066).
+ # Llama-3.1 serializes mapping content with tojson and /generate/stream takes raw dicts, so object
+ # values reach the prompt as live structure too (#7066).
new_content = _neutralize_leaves(content, rewrite)
elif isinstance(content, list):
- # A media part is only opaque where something RESOLVES it, and nothing does
- # inside a tool result: Unsloth's vision and audio paths build from the last
- # user message, while Llama-3.1's tool branch serializes the whole content
- # iterable with tojson, so an exempt URL there lands in the prompt as live
- # structure. That branch keys on "tool" OR "ipython" (chat_templates.py:517),
- # so both roles count (#7066).
+ # A media part is only opaque where something RESOLVES it, and nothing does inside a tool result:
+ # Unsloth's vision and audio paths build from the last user message, while Llama-3.1's tool branch
+ # serializes the whole content iterable with tojson, so an exempt URL there lands in the prompt as
+ # live structure. That branch keys on "tool" OR "ipython", so both roles count (#7066).
is_tool_result = role in _TOOL_RESULT_ROLES
new_content = _neutralize_content_parts(content, rewrite, not is_tool_result)
if _differs(new_content, content):
updates["content"] = new_content
tool_calls = msg.get("tool_calls")
- # Llama-3.1 branches on "'tool_calls' in message" BEFORE the role
- # (chat_templates.py:487-489) and emits an assistant tool-call turn, so the field on a
- # user or tool message fabricates assistant history however clean its text. It is
+ # Llama-3.1 branches on "'tool_calls' in message" BEFORE the role and emits an assistant tool-call turn, so
+ # the field on a user or tool message fabricates assistant history however clean its text. It is
# assistant-only in the OpenAI schema too, so any other role drops it (#7066).
if tool_calls is not None and role not in _ASSISTANT_ROLES:
logger.warning(
@@ -1265,25 +1174,23 @@ def neutralize_tool_descriptions(
):
"""Neutralize a rendered tool catalog, dropping any tool with an unsafe name.
- Every string in a declaration is prompt text: Gemma-4 interpolates the description into
- its system turn and emits property keys / ``enum`` / ``required`` entries inline, while
- Granite and Mistral-Small-3 render the whole entry with ``tojson``, and ``mcp_client``
- copies a remote ``description`` / ``inputSchema`` verbatim. So markup anywhere in the
- schema closes the system turn and forges a model one (#7066). The rewrite covers the
- whole entry, not just the nested ``function``, because ``ChatCompletionRequest.tools``
- is a bare ``list[dict]``.
-
- ``function.name`` is the dispatch identity: rewriting it silently breaks dispatch,
- leaving it exact forges a turn (Gemma-4 emits ``call:NAME`` unquoted), so a name
- carrying markup drops the tool with a warning instead. The predicate is the rewrite
- itself, not OpenAI's name grammar, so a passthrough client's ``ns.tool`` or
- ``functions.NAME:IDX`` still ships; it is the identity on markup-free strings, so a live
- catalog is returned unchanged."""
- # The agentic loop re-sanitizes the catalog on every iteration, because a one-shot
- # tool can retire between turns, so an unchanged catalog was swept again from scratch.
- # Keyed on the serialized catalog rather than the list itself: a value snapshot cannot
- # go stale if a caller mutates its own list in place, and building one is still five
- # times cheaper than the sweep it skips (#7066).
+ Every string in a declaration is prompt text: Gemma-4 interpolates the description into its
+ system turn and emits property keys / ``enum`` / ``required`` entries inline, while Granite and
+ Mistral-Small-3 render the whole entry with ``tojson``, and ``mcp_client`` copies a remote
+ ``description`` / ``inputSchema`` verbatim. So markup anywhere in the schema closes the system
+ turn and forges a model one (#7066). The rewrite covers the whole entry, not just the nested
+ ``function``, because ``ChatCompletionRequest.tools`` is a bare ``list[dict]``.
+
+ ``function.name`` is the dispatch identity: rewriting it silently breaks dispatch, leaving it
+ exact forges a turn (Gemma-4 emits ``call:NAME`` unquoted), so a name carrying markup drops the
+ tool with a warning instead. The predicate is the rewrite itself, not OpenAI's name grammar, so
+ a passthrough client's ``ns.tool`` or ``functions.NAME:IDX`` still ships; it is the identity on
+ markup-free strings, so a live catalog is returned unchanged.
+ """
+ # The agentic loop re-sanitizes the catalog on every iteration, because a one-shot tool can retire between turns,
+ # so an unchanged catalog was swept again from scratch. Keyed on the serialized catalog rather than the list
+ # itself: a value snapshot cannot go stale if a caller mutates its own list in place, and building one is still
+ # five times cheaper than the sweep it skips (#7066).
key = None
if cache is not None:
try:
@@ -1302,11 +1209,10 @@ def neutralize_tool_descriptions(
continue
function = tool.get("function")
target = function if isinstance(function, dict) and function else tool
- # Both spellings, not just the selected one: an entry may carry an empty
- # "function" mapping alongside a flat "name", and picking the nested level on
- # "isinstance" alone skipped the identity that actually dispatches. The flat name
- # was then rewritten in place, so the model saw a name execute_tool no longer
- # answers to (#7066).
+ # Both spellings, not just the selected one: an entry may carry an empty "function" mapping alongside a flat
+ # "name", and picking the nested level on "isinstance" alone skipped the identity that actually dispatches.
+ # The flat name was then rewritten in place, so the model saw a name execute_tool no longer answers to
+ # (#7066).
name = target.get("name")
unsafe_name = next(
(
@@ -1325,8 +1231,7 @@ def neutralize_tool_descriptions(
)
changed = True
continue
- # Both levels: OpenAI nests the schema under "function", MCP carries
- # "input_schema" on the entry itself.
+ # Both levels: OpenAI nests the schema under "function", MCP carries "input_schema" on the entry itself.
unsafe = _unsafe_schema_identifier(_schema_roots(tool) + _schema_roots(target), markup)
if unsafe is not None:
logger.warning(
@@ -1350,20 +1255,20 @@ def neutralize_tool_descriptions(
return result
-# The machine-valued rather than descriptive positions in a JSON Schema: a property name, an
-# enum or const literal, a required entry are all part of the contract the model must satisfy
-# and the controller forwards verbatim to execute_tool. Rewriting one makes the model emit
-# the rewritten spelling while the MCP server still expects the original, so the tool breaks.
-# function.name is already dropped for this reason; these get the same treatment (#7066).
+# The machine-valued rather than descriptive positions in a JSON Schema: a property name, an enum or const literal, a
+# required entry are all part of the contract the model must satisfy and the controller forwards verbatim to
+# execute_tool. Rewriting one makes the model emit the rewritten spelling while the MCP server still expects the
+# original, so the tool breaks. function.name is already dropped for this reason; these get the same treatment
+# (#7066).
_SCHEMA_KEYED_IDENTIFIERS = frozenset(
{
"properties",
"patternProperties",
"$defs",
"definitions",
- # Both dependent* keywords are keyed BY a property name, and dependentRequired's
- # values are property-name lists too, so it is checked on both sides below.
- # "dependencies" is draft-07's spelling of both, so keyed and list-valued as well.
+ # Both dependent* keywords are keyed BY a property name, and dependentRequired's values are property-name
+ # lists too, so it is checked on both sides below. "dependencies" is draft-07's spelling of both, so keyed and
+ # list-valued as well.
"dependentSchemas",
"dependentRequired",
"dependencies",
@@ -1372,10 +1277,9 @@ _SCHEMA_KEYED_IDENTIFIERS = frozenset(
}
)
_SCHEMA_KEYED_LIST_IDENTIFIERS = frozenset({"dependentRequired", "dependencies"})
-# "pattern" and "default" belong here for the same reason: a grammar built from the schema
-# forces the model to satisfy the rewritten regex or echo the rewritten default, then the MCP
-# server validates the original and rejects the call. The case the "[ARGS]" comment above
-# anticipated.
+# "pattern" and "default" belong here for the same reason: a grammar built from the schema forces the model to satisfy
+# the rewritten regex or echo the rewritten default, then the MCP server validates the original and rejects the call.
+# The case the "[ARGS]" comment above anticipated.
_SCHEMA_VALUED_IDENTIFIERS = frozenset(
{
"enum",
@@ -1383,27 +1287,24 @@ _SCHEMA_VALUED_IDENTIFIERS = frozenset(
"required",
"pattern",
"default",
- # Under format assertion (or a custom validator) this is a constraint the MCP
- # server checks, so a rewrite leaves the model targeting a different contract
- # from the one the server enforces, exactly as for "pattern".
+ # Under format assertion (or a custom validator) this is a constraint the MCP server checks, so a rewrite
+ # leaves the model targeting a different contract from the one the server enforces, exactly as for "pattern".
"format",
- # Same contract argument for the content vocabulary: both are machine-valued
- # strings a validator decodes against. "contentSchema" stays out on purpose, since
- # it holds a subschema whose keyword positions the recursive scan already reads.
+ # Same contract argument for the content vocabulary: both are machine-valued strings a validator decodes
+ # against. "contentSchema" stays out on purpose, since it holds a subschema whose keyword positions the
+ # recursive scan already reads.
"contentEncoding",
"contentMediaType",
- # An OpenAPI discriminator holds only "propertyName" and a "mapping" whose keys and
- # targets are identifiers, with no prose field to protect, so every leaf under it is
- # machine-valued: the server resolves the original while the model sees the rewrite.
+ # An OpenAPI discriminator holds only "propertyName" and a "mapping" whose keys and targets are identifiers,
+ # with no prose field to protect, so every leaf under it is machine-valued: the server resolves the original
+ # while the model sees the rewrite.
"discriminator",
- # Same shape: an OpenAPI xml object is "name" / "namespace" / "prefix" plus two
- # booleans, all serialization identifiers and no prose, so a rewrite would advertise
- # element names the server does not produce.
+ # Same shape: an OpenAPI xml object is "name" / "namespace" / "prefix" plus two booleans, all serialization
+ # identifiers and no prose, so a rewrite would advertise element names the server does not produce.
"xml",
- # A reference is resolved, not read: rewriting "$id", "$anchor" or a "$ref" pointing
- # at them leaves the model and llama-server's grammar on a different schema than the
- # MCP server registered. "$ref" can also name an external URI, which no "$defs" drop
- # would cover.
+ # A reference is resolved, not read: rewriting "$id", "$anchor" or a "$ref" pointing at them leaves the model
+ # and llama-server's grammar on a different schema than the MCP server registered. "$ref" can also name an
+ # external URI, which no "$defs" drop would cover.
"$ref",
"$id",
"$anchor",
@@ -1411,9 +1312,9 @@ _SCHEMA_VALUED_IDENTIFIERS = frozenset(
"$schema",
"$dynamicRef",
"$dynamicAnchor",
- # Draft-2019-09 spells the same recursion "$recursiveRef" / "$recursiveAnchor", and
- # draft-04 spells "$id" as a bare "id", so a schema in an older dialect has the same
- # base URI and resolution targets under different names.
+ # Draft-2019-09 spells the same recursion "$recursiveRef" / "$recursiveAnchor", and draft-04 spells "$id" as a
+ # bare "id", so a schema in an older dialect has the same base URI and resolution targets under different
+ # names.
"$recursiveRef",
"$recursiveAnchor",
"id",
@@ -1445,10 +1346,9 @@ def _first_unsafe_leaf(value, markup = None):
return None
-# Where a real JSON Schema starts in a declaration. The semantic scan anchors here rather
-# than on the whole entry, because a declaration also carries vendor extension fields, and a
-# "default" or "properties" key inside one of those is ordinary prose to neutralize, not a
-# reason to drop the tool.
+# Where a real JSON Schema starts in a declaration. The semantic scan anchors here rather than on the whole entry,
+# because a declaration also carries vendor extension fields, and a "default" or "properties" key inside one of those
+# is ordinary prose to neutralize, not a reason to drop the tool.
_SCHEMA_ROOT_KEYS = (
"parameters",
"input_schema",
@@ -1456,8 +1356,8 @@ _SCHEMA_ROOT_KEYS = (
"outputSchema",
"output_schema",
"returns",
- # Gemma-4 emits a response declaration from "function.response"
- # (gemma-4.jinja:115-124), and a JSON-serializing template exposes the rest of it.
+ # Gemma-4 emits a response declaration from "function.response", and a JSON-serializing template exposes the rest
+ # of it.
"response",
)
@@ -1469,10 +1369,9 @@ def _schema_roots(target):
return [target[key] for key in _SCHEMA_ROOT_KEYS if isinstance(target.get(key), (dict, list))]
-# "examples" carries instance samples, never subschemas, so a sample that happens to hold a
-# key like "required" is ordinary annotation text. Descending into it would read that key as
-# the JSON Schema keyword and drop a usable tool, so the scan stops here and the rewrite
-# neutralizes the sample as descriptive metadata instead.
+# "examples" carries instance samples, never subschemas, so a sample that happens to hold a key like "required" is
+# ordinary annotation text. Descending into it would read that key as the JSON Schema keyword and drop a usable tool,
+# so the scan stops here and the rewrite neutralizes the sample as descriptive metadata instead.
_SCHEMA_INSTANCE_KEYS = frozenset({"examples", "example"})
@@ -1498,19 +1397,17 @@ def _unsafe_schema_identifier(value, markup = None):
and neutralize_control_markup(dependent, markup) != dependent
):
return dependent
- # The keys of this map are names, so only its VALUES are subschemas.
- # Descending into the map itself would read a property literally named
- # "format", "default" or "id" as the keyword of the same name and drop a
- # perfectly ordinary tool.
+ # The keys of this map are names, so only its VALUES are subschemas. Descending into the map
+ # itself would read a property literally named "format", "default" or "id" as the keyword of the
+ # same name and drop a perfectly ordinary tool.
for value in item.values():
if isinstance(value, (dict, list)) and id(value) not in seen:
seen.add(id(value))
stack.append(value)
continue
elif key in _SCHEMA_VALUED_IDENTIFIERS:
- # Every leaf, not just a top-level string: an enum entry or const can be
- # any value, so "enum": [["<s>"]] and "const": {"tag": "</think>"} are
- # literals the model must reproduce exactly.
+ # Every leaf, not just a top-level string: an enum entry or const can be any value, so "enum":
+ # [["<s>"]] and "const": {"tag": "</think>"} are literals the model must reproduce exactly.
unsafe = _first_unsafe_leaf(item, markup)
if unsafe is not None:
return unsafe
@@ -1528,10 +1425,9 @@ def _unsafe_schema_identifier(value, markup = None):
def forced_tool_name(tool_choice):
- """The function name a ``tool_choice`` pins, or None when it pins nothing.
-
- OpenAI: ``{"type": "function", "function": {"name": ...}}``; Anthropic:
- ``{"type": "tool", "name": ...}``. The string forms pin no particular tool."""
+ """The function name a ``tool_choice`` pins, or None when it pins nothing. OpenAI: ``{"type":
+ "function", "function": {"name": ...}}``; Anthropic: ``{"type": "tool", "name": ...}``. The
+ string forms pin no particular tool."""
if not isinstance(tool_choice, dict):
return None
function = tool_choice.get("function")
@@ -1546,10 +1442,9 @@ def catalog_tool_names(tools) -> set:
if not isinstance(tool, dict):
continue
function = tool.get("function")
- # Both spellings: an entry may carry an empty "function" mapping beside the flat
- # name that actually dispatches, and reading only the nested level made a dropped
- # tool look as though it had never been in the caller's catalog -- so a forced
- # tool_choice for it was forwarded unchanged (#7066).
+ # Both spellings: an entry may carry an empty "function" mapping beside the flat name that actually
+ # dispatches, and reading only the nested level made a dropped tool look as though it had never been in the
+ # caller's catalog -- so a forced tool_choice for it was forwarded unchanged (#7066).
nested = function.get("name") if isinstance(function, dict) else None
for name in (nested, tool.get("name")):
if isinstance(name, str):
@@ -1558,13 +1453,11 @@ def catalog_tool_names(tools) -> set:
def _tokenizer_strings(inner) -> Optional[list]:
- """Every string a tokenizer exposes: added tokens AND the base vocabulary.
-
- Neither source alone is enough. A tokenizer can carry unrelated added tokens while its
- chat sentinels stay in the base SentencePiece vocabulary, so short-circuiting on a
- populated added_tokens_decoder left a model's own turn boundaries out of the profile
- and a pasted copy reached the prompt byte-exact (#7066).
- """
+ """Every string a tokenizer exposes: added tokens AND the base vocabulary. Neither source alone
+ is enough: a tokenizer can carry unrelated added tokens while its chat sentinels stay in the
+ base SentencePiece vocabulary, so short-circuiting on a populated added_tokens_decoder left a
+ model's own turn boundaries out of the profile and a pasted copy reached the prompt
+ byte-exact (#7066)."""
out: list = []
added = getattr(inner, "added_tokens_decoder", None)
if isinstance(added, dict):
@@ -1587,16 +1480,16 @@ def _vocabulary_of(tokenizer) -> Optional[list]:
def mapped_chat_template(model_info: dict, active_model_name):
"""The template the generate-time mapper will install, resolved once and cached.
- ``_generate_chat_response_inner`` applies ``get_chat_template`` only when it renders, so
- a profile or an authorization catalog built before that saw the LOAD-time template. A
- tool whose schema carries a delimiter the mapped template introduces was then dropped
- from the prompt but still authorized for healing or execution (#7066).
+ ``_generate_chat_response_inner`` applies ``get_chat_template`` only when it renders, so a
+ profile or an authorization catalog built before that saw the LOAD-time template, and a tool
+ whose schema carries a delimiter the mapped template introduces was dropped from the prompt but
+ still authorized for healing or execution (#7066).
- Resolved on a COPY of the tokenizer: ``get_chat_template`` assigns
- ``tokenizer.chat_template`` (unsloth/chat_templates.py), and this runs before the
- generation lock, so handing it the shared object would let this setup mutate a tokenizer
- another request is rendering with. ``render_native_template`` clones for the same
- reason. Only the resulting template string is kept."""
+ Resolved on a COPY of the tokenizer: ``get_chat_template`` assigns ``tokenizer.chat_template``,
+ and this runs before the generation lock, so handing it the shared object would let this setup
+ mutate a tokenizer another request is rendering with. Only the resulting template string is
+ kept.
+ """
if not isinstance(model_info, dict):
return None
if "mapped_chat_template" in model_info:
@@ -1609,8 +1502,8 @@ def mapped_chat_template(model_info: dict, active_model_name):
name = (active_model_name or "").lower()
if name in MODEL_TO_TEMPLATE_MAPPER:
source = model_info.get("tokenizer")
- # Shallow copy: get_chat_template writes chat_template onto whatever it is
- # given, and a concurrent generation may be rendering with the shared object.
+ # Shallow copy: get_chat_template writes chat_template onto whatever it is given, and a concurrent
+ # generation may be rendering with the shared object.
try:
probe = copy.copy(source)
except Exception:
@@ -1628,7 +1521,6 @@ def mapped_chat_template(model_info: dict, active_model_name):
def _is_processor(obj) -> bool:
"""True for a container processor: it holds a tokenizer AND renders chats itself.
-
``ProcessorMixin.apply_chat_template`` does not switch to "tool_use" implicitly, so a
processor renders "default" unless a template is named. Three call sites need that
distinction and each had grown its own copy of the test."""
@@ -1638,13 +1530,12 @@ def _is_processor(obj) -> bool:
def chat_render_target(processor, tokenizer = None):
- """The object whose chat template a render will actually use.
-
- ``_generate_vlm`` falls back to the nested tokenizer when the processor cannot render
- a chat itself (mlx_inference.py), so anything profiling the prompt ahead of the render
- has to make the same choice. Reproducing the rule at the call site let the two drift:
- a processor without a usable ``chat_template`` was profiled as a processor, selecting
- "default", while the render used the nested tokenizer's tool_use template (#7066)."""
+ """The object whose chat template a render will actually use. ``_generate_vlm`` falls back to
+ the nested tokenizer when the processor cannot render a chat itself, so anything profiling
+ the prompt ahead of the render has to make the same choice. Reproducing the rule at the call
+ site let the two drift: a processor without a usable ``chat_template`` was profiled as a
+ processor, selecting "default", while the render used the nested tokenizer's tool_use
+ template (#7066)."""
if processor is None:
return tokenizer
if (
@@ -1656,35 +1547,33 @@ def chat_render_target(processor, tokenizer = None):
return processor
-# The Jinja variable HF passes the schema in. A template that never reads it cannot put a
-# tool in the prompt, whatever the caller asked for.
+# The Jinja variable HF passes the schema in. A template that never reads it cannot put a tool in the prompt, whatever
+# the caller asked for.
_TOOLS_VARIABLE = re.compile(r"\btools\b")
-# Only what Jinja evaluates counts. A raw word search over the whole body also matched the
-# word in prose the template merely prints, so "{{ 'no tools available' }}" read as a
-# template that renders schemas and the catalog stayed authorized (#7066).
+# Only what Jinja evaluates counts. A raw word search over the whole body also matched the word in prose the template
+# merely prints, so "{{ 'no tools available' }}" read as a template that renders schemas and the catalog stayed
+# authorized (#7066).
_JINJA_CODE = re.compile(r"\{\{(.*?)\}\}|\{%(.*?)%\}", re.S)
-# String literals are data, not a variable read: the same prose moved inside an expression
-# would otherwise pass. Per-quote, so an apostrophe in a double-quoted string cannot swallow
-# the rest of the expression, and escape aware, because a literal ending at the first
-# backslash-quote left the rest of its own prose looking like live code (#7066).
+# String literals are data, not a variable read: the same prose moved inside an expression would otherwise pass.
+# Per-quote, so an apostrophe in a double-quoted string cannot swallow the rest of the expression, and escape aware,
+# because a literal ending at the first backslash-quote left the rest of its own prose looking like live code (#7066).
_JINJA_STRING = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"", re.S)
-# A template that replays assistant tool_calls and tool results takes part in tool calling
-# by design, with the schema supplied by the caller's system prompt rather than by the
-# template: DeepSeek-R1 renders message['tool_calls'] and <|tool outputs|> and never reads
-# the tools variable at all. Unlike the tools read, this one keeps string literals, because
-# the name appears as a mapping key.
+# A template that replays assistant tool_calls and tool results takes part in tool calling by design, with the schema
+# supplied by the caller's system prompt rather than by the template: DeepSeek-R1 renders message['tool_calls'] and
+# <|tool outputs|> and never reads the tools variable at all. Unlike the tools read, this one keeps string literals,
+# because the name appears as a mapping key.
_TOOL_TURN = re.compile(
- # message.tool_calls / message["tool_calls"] / "tool_calls" in message, and the role
- # comparison a template uses to render a tool result. Matching the bare word instead
- # let "{{ 'tool_calls are unsupported' }}" count as taking part in tool calling.
+ # message.tool_calls / message["tool_calls"] / "tool_calls" in message, and the role comparison a template uses to
+ # render a tool result. Matching the bare word instead let "{{ 'tool_calls are unsupported' }}" count as taking
+ # part in tool calling.
r"\.tool_calls\b"
r"|\[\s*['\"]tool_calls['\"]\s*\]"
r"|['\"]tool_calls['\"]\s+in\b"
r"|\btool_calls\s+in\b"
- # "message['role'] == 'tool'" as well as "message.role == 'tool'": the closing quote
- # and bracket sit between the name and the comparison.
+ # "message['role'] == 'tool'" as well as "message.role == 'tool'": the closing quote and bracket sit between the
+ # name and the comparison.
r"|role['\"\]\s]*==\s*['\"]tool['\"]"
r"|['\"]tool['\"]\s*==[\s\['\"]*role"
)
@@ -1697,10 +1586,9 @@ def _jinja_code(body: str):
def _jinja_expression_spans(body: str) -> tuple:
- """The character ranges Jinja evaluates, with string literals taken back out.
-
- A "[" inside one of these is real indexing. Anywhere else, raw template text or inside
- a quoted literal the template prints, it is output the prompt will show."""
+ """The character ranges Jinja evaluates, with string literals taken back out. A "[" inside one
+ of these is real indexing. Anywhere else, raw template text or inside a quoted literal the
+ template prints, it is output the prompt will show."""
spans: list = []
for match in _JINJA_CODE.finditer(body):
group = 1 if match.group(1) is not None else 2
@@ -1724,16 +1612,16 @@ _ENDRAW = re.compile(r"\{%-?\s*endraw\s*-?%\}")
def _evaluated_spans(template: str) -> tuple:
"""The ranges Jinja evaluates, walked quote-aware, with string literals taken out.
- ``_jinja_expression_spans`` ends a block at the first ``}}``, so a template printing
- literal Jinja -- ``{{ "{{ example.0 }}" }}`` -- reads as code. That scanner is shared
- with ``model_markup`` (#7066) and stays as it is; this repair edits the template
- llama-server launches with, so it walks the blocks itself.
+ ``_jinja_expression_spans`` ends a block at the first ``}}``, so a template printing literal
+ Jinja -- ``{{ "{{ example.0 }}" }}`` -- reads as code. That scanner is shared with
+ ``model_markup`` (#7066) and stays as it is; this repair edits the template llama-server
+ launches with, so it walks the blocks itself.
- A comment and a ``{% raw %}`` body are both skipped. Raw is tracked through this same
- walk rather than matched in the source, so tag text that only appears inside a comment
- or a literal cannot make a real expression between two of them look verbatim. Inside a
- raw body nothing is interpreted at all, the way Jinja reads it: the walk runs to the
- terminator, so a comment marker there stays text.
+ A comment and a ``{% raw %}`` body are both skipped. Raw is tracked through this same walk
+ rather than matched in the source, so tag text that only appears inside a comment or a literal
+ cannot make a real expression between two of them look verbatim. Inside a raw body nothing is
+ interpreted at all, the way Jinja reads it: the walk runs to the terminator, so a comment marker
+ there stays text.
"""
spans: list = []
index, end = 0, len(template)
@@ -1794,15 +1682,15 @@ _NUMERIC_MEMBER = re.compile(r"([A-Za-z_]\w*|\)|\])((?:\s*\.\s*\d+)+)")
def repair_numeric_member_access(template) -> Optional[str]:
"""Rewrite ``x.0`` as ``x[0]`` in evaluated code, or None when nothing needs it.
- llama.cpp's Jinja rejects a numeric member property. The throw lands inside its
- capability probe, which swallows it, so ``supports_object_arguments`` stays false and a
- replayed tool call's arguments are never decoded back into an object -- the template's
- own ``arguments.items()`` then dies on the JSON string (GLM-5.3).
+ llama.cpp's Jinja rejects a numeric member property. The throw lands inside its capability
+ probe, which swallows it, so ``supports_object_arguments`` stays false and a replayed tool
+ call's arguments are never decoded back into an object -- the template's own
+ ``arguments.items()`` then dies on the JSON string (GLM-5.3).
- Only the ranges Jinja evaluates are rewritten, never prompt text, a quoted literal, a
- raw block, or Jinja syntax a template prints as an example.
- A chain rewrites whole ("x.0.1" -> "x[0][1]"): leaving the tail behind still throws.
- Jinja lets whitespace sit around each dot, and llama.cpp throws on that spelling too.
+ Only the ranges Jinja evaluates are rewritten, never prompt text, a quoted literal, a raw block,
+ or Jinja syntax a template prints as an example. A chain rewrites whole ("x.0.1" -> "x[0][1]"):
+ leaving the tail behind still throws. Jinja lets whitespace sit around each dot, and llama.cpp
+ throws on that spelling too.
"""
if not isinstance(template, str) or not template:
return None
@@ -1840,19 +1728,20 @@ def _template_reads_tools(
) -> bool:
"""True unless the template selected out of *value* takes no part in tool calling.
- Reading the ``tools`` variable is the direct case. Replaying tool calls counts too:
- such a template round-trips a tool turn it never advertised, so the schema came from
- the caller's own system prompt and the catalog is authorized after all.
+ Reading the ``tools`` variable is the direct case. Replaying tool calls counts too: such a
+ template round-trips a tool turn it never advertised, so the schema came from the caller's own
+ system prompt and the catalog is authorized after all.
- ``require_tools_variable`` drops that second clause, for callers asking whether THIS
- render puts the schema in the prompt: a template that only round-trips renders
- byte-identically with and without a catalog, so the healer would otherwise promote
- calls for tools the model never saw (#7066)."""
+ ``require_tools_variable`` drops that second clause, for callers asking whether THIS render puts
+ the schema in the prompt: a template that only round-trips renders byte-identically with and
+ without a catalog, so the healer would otherwise promote calls for tools the model never saw
+ (#7066).
+ """
bodies = _selected_template_strings_from_value(value, tools, prefer_tool_use = prefer_tool_use)
if not bodies:
- # Unreadable, not proven silent. Emptying the catalog here would disable healing
- # for every model whose template shape this module cannot parse, which is a
- # feature regression rather than the narrow authorization fix (#7066).
+ # Unreadable, not proven silent. Emptying the catalog here would disable healing for every model whose
+ # template shape this module cannot parse, which is a feature regression rather than the narrow authorization
+ # fix (#7066).
return True
if require_tools_variable:
return any(_reads_tools_variable(body) for body in bodies)
@@ -1861,11 +1750,10 @@ def _template_reads_tools(
def _accepts_tools_kwarg(target) -> bool:
"""False only when ``apply_chat_template`` provably rejects ``tools=``.
-
apply_chat_template_for_generation catches that TypeError and succeeds with a no-tools
- attempt, so the prompt carries no schema however often the template body names the
- variable. Signature rather than a probe render: a render needs messages this function
- does not have, and would raise for unrelated reasons on a strict template."""
+ attempt, so the prompt carries no schema however often the template body names the variable.
+ Signature rather than a probe render: a render needs messages this function does not have,
+ and would raise for unrelated reasons on a strict template."""
apply = getattr(target, "apply_chat_template", None)
if apply is None:
return True
@@ -1884,15 +1772,13 @@ def _renders_tool_schema(
tools,
template_is_processor: bool = False,
) -> bool:
- """True unless the template *target* will select provably cannot advertise tools.
-
- A processor is held to the stricter test: its render has no native-template fallback
- behind it (a text model's template cannot place the image), so what the processor's own
- body does with ``tools`` is the whole answer.
-
- ``template_is_processor`` says the *template* is a processor body even though *target*
- is not: under the orchestrator the route has only the body mirrored through worker IPC,
- which would otherwise be judged by the permissive tokenizer rule (#10092)."""
+ """True unless the template *target* will select provably cannot advertise tools. A processor is
+ held to the stricter test: its render has no native-template fallback behind it (a text
+ model's template cannot place the image), so what the processor's own body does with
+ ``tools`` is the whole answer. ``template_is_processor`` says the *template* is a processor
+ body even though *target* is not: under the orchestrator the route has only the body mirrored
+ through worker IPC, which would otherwise be judged by the permissive tokenizer rule
+ (#10092)."""
if tools and not _accepts_tools_kwarg(target):
return False
value = template or getattr(target, "chat_template", None)
@@ -1918,27 +1804,24 @@ def renderable_tool_catalog_for_targets(
):
"""The catalog safe under every object a backend could render this turn with.
- The two backends disagree about which object renders a text turn on a vision model.
- MLX keeps the processor when it has a usable chat template (mlx_inference.py), while
- the transformers path unwraps to the nested tokenizer unconditionally
- (inference.py). Their profiles can differ, so authorizing against one of them lets the
- other's render drop a tool that stays in the healer's catalog (#7066).
-
- Rather than guessing which backend will serve the request, this takes the same
- conservative intersection ``renderable_tool_catalog`` already takes across the active
- and native templates: a tool has to survive every candidate to stay authorized.
-
- Chained rather than intersected by name, so the surviving descriptions carry every
- candidate's sweep too. Sanitizing an already-sanitized catalog is stable, since a
- broken marker no longer matches, so a clean catalog stays byte-identical."""
+ The two backends disagree about which object renders a text turn on a vision model: MLX keeps
+ the processor when it has a usable chat template, while the transformers path unwraps to the
+ nested tokenizer unconditionally. Their profiles can differ, so authorizing against one of them
+ lets the other's render drop a tool that stays in the healer's catalog (#7066).
+
+ Rather than guessing which backend will serve the request, this takes the same conservative
+ intersection ``renderable_tool_catalog`` already takes across the active and native templates: a
+ tool has to survive every candidate to stay authorized. Chained rather than intersected by name,
+ so the surviving descriptions carry every candidate's sweep too. Sanitizing an already-sanitized
+ catalog is stable, since a broken marker no longer matches, so a clean catalog stays
+ byte-identical.
+ """
live = [target for target in targets if target is not None]
if not live:
- # Nothing to profile: the default orchestrator's parent-side mirror carries
- # capability flags, never the tokenizer or processor (orchestrator.py:1278-1292).
- # Skipping the targets returned the caller's list unsanitized while the worker
- # sanitized during the render, so a tool dropped from the prompt stayed authorized
- # for healing. One None target profiles as unprofilable and takes the curated
- # sweep, the safe direction (#7066).
+ # Nothing to profile: the default orchestrator's parent-side mirror carries capability flags, never the
+ # tokenizer or processor. Skipping the targets returned the caller's list unsanitized while the worker
+ # sanitized during the render, so a tool dropped from the prompt stayed authorized for healing. One None
+ # target profiles as unprofilable and takes the curated sweep, the safe direction (#7066).
return renderable_tool_catalog(
tools, None, model_info, cache, active_model_name, template, template_is_processor
)
@@ -1963,21 +1846,20 @@ def renderable_tool_catalog(
):
"""The catalog that survives EVERY template this request could render with.
- A tool-calling turn may render with the active template or, when that template drops
- the schema, with the model's native one, and the two profiles can disagree about which
- tools carry markup. A healer or controller is an authorization boundary, so it has to
- be built from the catalog that is safe either way: promoting a call for a tool the
- prompt never advertised is the failure this guards (#7066).
+ A tool-calling turn may render with the active template or, when that template drops the schema,
+ with the model's native one, and the two profiles can disagree about which tools carry markup. A
+ healer or controller is an authorization boundary, so it has to be built from the catalog that
+ is safe either way: promoting a call for a tool the prompt never advertised is the failure this
+ guards (#7066).
- The cost of the conservative direction is narrow and one-sided. A tool dropped only by
- the template that did NOT get selected stays advertised and directly callable; it just
- is not auto-healed out of text-form output that round.
+ The cost of the conservative direction is narrow and one-sided. A tool dropped only by the
+ template that did NOT get selected stays advertised and directly callable; it just is not
+ auto-healed out of text-form output that round.
"""
- # The mapper installs its template on the TOKENIZER at generate time. A processor
- # render reads the processor's own chat_template and never sees it (_generate_vlm),
- # so resolving it for a processor target profiled a prompt that render cannot
- # produce, and a tool carrying a processor-only delimiter survived the catalog while
- # the actual render dropped it (#7066).
+ # The mapper installs its template on the TOKENIZER at generate time. A processor render reads the processor's own
+ # chat_template and never sees it, so resolving it for a processor target profiled a prompt that render cannot
+ # produce, and a tool carrying a processor-only delimiter survived the catalog while the actual render dropped it
+ # (#7066).
if template is None and not _is_processor(tokenizer):
template = mapped_chat_template(model_info or {}, active_model_name)
safe = neutralize_tool_descriptions(
@@ -1996,32 +1878,29 @@ def renderable_tool_catalog(
active_renders_tools = _renders_tool_schema(
tokenizer, template, tools, template_is_processor = template_is_processor
)
- # A processor stays on "default" and the VLM path renders straight through
- # apply_chat_template_for_generation, with no native-template fallback behind it
- # (mlx_inference.py). When that default body never reads ``tools`` the schema cannot
- # reach the prompt at all, so every tool in the catalog is unadvertised and healing a
- # text-form call would promote one the model was never shown (#7066).
- # Counts here too: the orchestrator passes tokenizer=None, not a processor (#10092).
+ # A processor stays on "default" and the VLM path renders straight through apply_chat_template_for_generation,
+ # with no native-template fallback behind it. When that default body never reads ``tools`` the schema cannot reach
+ # the prompt at all, so every tool in the catalog is unadvertised and healing a text-form call would promote one
+ # the model was never shown (#7066). Counts here too: the orchestrator passes tokenizer=None, not a processor
+ # (#10092).
if (template_is_processor or _is_processor(tokenizer)) and not active_renders_tools:
return _unadvertised()
- # Resolved rather than read: render_native_template fetches it during the render, so on
- # the FIRST request needing the fallback the cache is still empty and this would hand
- # back the active-profile catalog unchanged (#7066).
+ # Resolved rather than read: render_native_template fetches it during the render, so on the FIRST request needing
+ # the fallback the cache is still empty and this would hand back the active-profile catalog unchanged (#7066).
native_tpl = resolve_native_chat_template(
model_info or {}, active_model_name, (model_info or {}).get("hf_token")
)
- # The tokenizer path is normally rescued by that fallback: an active template which
- # drops the schema is re-rendered with the native one. When there is no native template
- # to reach -- unresolvable, private, or a failed fetch -- nothing is left that could
- # advertise, and render_with_native_template_fallback keeps the no-tools prompt. The
- # catalog has to say so, or the healer promotes a call the prompt never showed (#7066).
+ # The tokenizer path is normally rescued by that fallback: an active template which drops the schema is
+ # re-rendered with the native one. When there is no native template to reach -- unresolvable, private, or a failed
+ # fetch -- nothing is left that could advertise, and render_with_native_template_fallback keeps the no-tools
+ # prompt. The catalog has to say so, or the healer promotes a call the prompt never showed (#7066).
if not native_tpl:
return safe if active_renders_tools else _unadvertised()
if not active_renders_tools and not _template_reads_tools(native_tpl, tools):
return _unadvertised()
- # With the special tokens too: the native render profiles through markup_for_tokenizer
- # and so resolves "{{ bos_token }}", and a catalog built without them kept a tool whose
- # schema carries that value while the render dropped it (#7066).
+ # With the special tokens too: the native render profiles through markup_for_tokenizer and so resolves "{{
+ # bos_token }}", and a catalog built without them kept a tool whose schema carries that value while the render
+ # dropped it (#7066).
native = model_markup(
native_tpl,
_vocabulary_of(tokenizer),
@@ -2036,12 +1915,11 @@ def renderable_tool_catalog(
def reconciled_tool_choice(tool_choice, openai_tools, safe_tools):
- """Downgrade a forced ``tool_choice`` to "auto" when WE dropped its tool (#7066).
-
- Only when the neutralizer removed it: the name has to be in the caller's catalog and
- gone from the sanitized one. A client forcing a function it never declared is a
- different, pre-existing case the healing path deliberately reads to decide a streamed
- call must NOT be promoted, so rewriting it there would change unrelated behaviour."""
+ """Downgrade a forced ``tool_choice`` to "auto" when WE dropped its tool (#7066). Only when the
+ neutralizer removed it: the name has to be in the caller's catalog and gone from the
+ sanitized one. A client forcing a function it never declared is a different, pre-existing
+ case the healing path deliberately reads to decide a streamed call must NOT be promoted, so
+ rewriting it there would change unrelated behaviour."""
forced = forced_tool_name(tool_choice)
if forced is None or forced in catalog_tool_names(safe_tools):
return tool_choice
@@ -2073,9 +1951,9 @@ def _selected_template_strings_from_value(
tools = tools or None
if isinstance(template, str):
return (template,)
- # The list form Hermes-3 ships, [{"name": ..., "template": ...}], is the same selection
- # as the dict form; returning nothing for it made every caller fall back to the union,
- # so a no-tools turn inherited the tool_use markers (#7066).
+ # The list form Hermes-3 ships, [{"name": ..., "template": ...}], is the same selection as the dict form;
+ # returning nothing for it made every caller fall back to the union, so a no-tools turn inherited the tool_use
+ # markers (#7066).
if isinstance(template, (list, tuple)):
named = {
entry["name"]: entry["template"]
@@ -2100,7 +1978,6 @@ def _selected_template_strings_from_value(
def _selected_chat_template_strings(tokenizer, tools = None) -> tuple[str, ...]:
- """Return the active chat template selected for this request."""
tools = tools or None
getter = getattr(tokenizer, "get_chat_template", None)
if callable(getter):
@@ -2111,8 +1988,8 @@ def _selected_chat_template_strings(tokenizer, tools = None) -> tuple[str, ...]:
continue
if isinstance(selected, str):
return (selected,)
- # ProcessorMixin.apply_chat_template does not switch to "tool_use" implicitly;
- # it uses "default" unless chat_template= names another template.
+ # ProcessorMixin.apply_chat_template does not switch to "tool_use" implicitly; it uses "default" unless
+ # chat_template= names another template.
return _selected_template_strings_from_value(
getattr(tokenizer, "chat_template", None),
tools,
@@ -2132,13 +2009,10 @@ def _detect_reasoning_channel_markers_from_templates(
def detect_reasoning_channel_markers(tokenizer, tools = None) -> Optional[tuple[str, ...]]:
- """Return the native reasoning-channel markers a tokenizer's template emits.
-
- Detection uses the active chat template rather than model names or vocabulary
- membership. Some models expose Gemma control tokens without using the native
- thought-channel response protocol, and those must keep normal
- ``skip_special_tokens`` streaming.
- """
+ """Return the native reasoning-channel markers a tokenizer's template emits. Detection uses the
+ active chat template rather than model names or vocabulary membership: some models expose
+ Gemma control tokens without using the native thought-channel response protocol, and those
+ must keep normal ``skip_special_tokens`` streaming."""
for obj in _tokenizer_objects(tokenizer):
templates = _selected_chat_template_strings(obj, tools)
if templates:
@@ -2182,10 +2056,9 @@ class ChatTemplateRenderResult:
prompt: str
reasoning_channel_markers: Optional[tuple[str, ...]] = None
- # The tool catalog the SELECTED template actually rendered. The native-template
- # fallback sanitizes with the native model's profile, which can drop a tool the active
- # profile kept, so a healer or controller built from the active catalog could promote a
- # call for a tool the prompt never advertised (#7066).
+ # The tool catalog the SELECTED template actually rendered. The native-template fallback sanitizes with the native
+ # model's profile, which can drop a tool the active profile kept, so a healer or controller built from the active
+ # catalog could promote a call for a tool the prompt never advertised (#7066).
advertised_tools: Optional[list] = None
@@ -2219,8 +2092,8 @@ def _split_partial_marker(text: str, marker: str) -> tuple[str, str]:
def _find_atem_block_end(text: str, start: int = 0) -> tuple[int, int]:
- """Earliest block terminator at or after ``start``. Callers that keep feeding the
- same buffer pass what they have already searched, so a held block costs one scan."""
+ """Earliest block terminator at or after ``start``. Callers that keep feeding the same buffer
+ pass what they have already searched, so a held block costs one scan."""
index, length = -1, 0
for marker in _ATEM_BLOCK_ENDS:
found = text.find(marker, start)
@@ -2230,9 +2103,9 @@ def _find_atem_block_end(text: str, start: int = 0) -> tuple[int, int]:
def _atem_partial_framing_len(text: str) -> int:
- """Length of the trailing fragment that can only be framing the model never finished:
- one opening with "<", or a bare first header that has reached its "<|message|>".
- "...auto=true" is still prose, so it stays."""
+ """Length of the trailing fragment that can only be framing the model never finished: one
+ opening with "<", or a bare first header that has reached its "<|message|>". "...auto=true"
+ is still prose, so it stays."""
for size in range(min(len(text), _ATEM_HEADER_MAX_LEN), 0, -1):
tail = text[-size:]
if not (tail.startswith("<") or (tail.startswith("to=") and "<|" in tail)):
@@ -2245,8 +2118,8 @@ def _atem_partial_framing_len(text: str) -> int:
def _split_partial_atem_boundary(text: str) -> tuple[str, str]:
- """Between blocks either a header or a block terminator may follow, and both are
- consumed there, so a partial of either has to be held for the next chunk."""
+ """Between blocks either a header or a block terminator may follow, and both are consumed there,
+ so a partial of either has to be held for the next chunk."""
stable, held = _split_partial_atem_header(text)
candidate, tail = _split_partial_atem_block_end(text)
return (candidate, tail) if len(tail) > len(held) else (stable, held)
@@ -2262,10 +2135,9 @@ def _split_partial_atem_block_end(text: str) -> tuple[str, str]:
def _atem_parameter_value(raw: str):
- """JSON where it parses, otherwise the text as written (the grammar's
- ``allow_non_json``). Anything that will not re-serialize stays text: json.loads
- accepts NaN and the infinities, which RFC 8259 s6 does not, and 1e400 becomes inf
- without ever being one."""
+ """JSON where it parses, otherwise the text as written (the grammar's ``allow_non_json``).
+ Anything that will not re-serialize stays text: json.loads accepts NaN and the infinities,
+ which RFC 8259 s6 does not, and 1e400 becomes inf without ever being one."""
try:
value = json.loads(raw)
json.dumps(value, allow_nan = False)
@@ -2275,11 +2147,9 @@ def _atem_parameter_value(raw: str):
def _atem_unfinished_tag(text: str) -> int:
- """Offset of the first ATEM tag the model had not finished writing, or -1.
-
- Only the last tag start can be unfinished, and it must match a tag name to a name
- boundary, so "<atem:invoker ..." stays the prose it is.
- """
+ """Offset of the first ATEM tag the model had not finished writing, or -1. Only the last tag
+ start can be unfinished, and it must match a tag name to a name boundary, so "<atem:invoker
+ ..." stays the prose it is."""
starts = [match.start() for match in _ATEM_TAG_START_RE.finditer(text)]
if not starts:
return -1
@@ -2296,11 +2166,9 @@ def _atem_unfinished_tag(text: str) -> int:
def _atem_surrounding_text(segment: str, *, complete: bool = True) -> str:
- """Text around calls, minus the envelope; whitespace alone is framing.
-
- ``complete`` is False for the tail of a block the stream cut short, where a
- trailing fragment of markup the model had not finished writing is framing too.
- """
+ """Text around calls, minus the envelope; whitespace alone is framing. ``complete`` is False for
+ the tail of a block the stream cut short, where a trailing fragment of markup the model had
+ not finished writing is framing too."""
for tag in _ATEM_CALLS_ENVELOPE:
segment = segment.replace(tag, "")
if not complete:
@@ -2311,11 +2179,10 @@ def _atem_surrounding_text(segment: str, *, complete: bool = True) -> str:
def _atem_block_pieces(block: str, *, complete: bool) -> Optional[list[tuple[bool, str]]]:
- """Split a tool-addressed block into ``(is_call, text)`` pieces, or None when it
- holds no call syntax: nothing downstream recognizes the native form, so a block
- passed through is shown as prose instead of executed. Text around the calls keeps
- its place among them. ``complete`` is False for a block the stream cut short.
- """
+ """Split a tool-addressed block into ``(is_call, text)`` pieces, or None when it holds no call
+ syntax: nothing downstream recognizes the native form, so a block passed through is shown as
+ prose instead of executed. Text around the calls keeps its place among them. ``complete`` is
+ False for a block the stream cut short."""
pieces: list[tuple[bool, str]] = []
cursor = 0
saw_call = False
@@ -2330,8 +2197,8 @@ def _atem_block_pieces(block: str, *, complete: bool) -> Optional[list[tuple[boo
body = block[opening.end() : end]
parameters = list(_ATEM_PARAMETER_RE.finditer(body))
if len(parameters) != body.count("<atem:parameter") or "<atem:invoke" in body:
- # An unclosed parameter, or a nested opener stealing this closer: either
- # would run a tool the model did not specify, so keep it as text.
+ # An unclosed parameter, or a nested opener stealing this closer: either would run a tool the model did
+ # not specify, so keep it as text.
pieces.append((False, block[opening.start() : end + len(_ATEM_INVOKE_CLOSE)]))
cursor = end + len(_ATEM_INVOKE_CLOSE)
continue
@@ -2355,13 +2222,10 @@ def _atem_block_pieces(block: str, *, complete: bool) -> Optional[list[tuple[boo
class ReasoningChannelNormalizer:
- """Incrementally convert one native reasoning channel to ``<think>``.
-
- The parser follows mlx-vlm's streaming boundary behavior but emits Unsloth's
- established canonical text contract. Only the configured opening and
- closing markers are consumed; tool-call and other control markers remain
- available to downstream parsers.
- """
+ """Incrementally convert one native reasoning channel to ``<think>``. The parser follows
+ mlx-vlm's streaming boundary behavior but emits Unsloth's canonical text contract. Only the
+ configured opening and closing markers are consumed; tool-call and other control markers
+ remain available to downstream parsers."""
def __init__(
self,
@@ -2375,11 +2239,10 @@ class ReasoningChannelNormalizer:
self._buffer = ""
self._in_reasoning = in_reasoning
self._reasoning_done = False
- # Only a generated opener carries the protocol newline; from the prompt it is
- # already consumed, so a streamed newline is content.
+ # Only a generated opener carries the protocol newline; from the prompt it is already consumed, so a streamed
+ # newline is content.
self._skip_opening_newline = False
- # A prompt-supplied opener never reaches the stream, so <think> is owed to the
- # first delta carrying text.
+ # A prompt-supplied opener never reaches the stream, so <think> is owed to the first delta carrying text.
self._pending_open = in_reasoning
def feed(self, text: str) -> str:
@@ -2422,11 +2285,9 @@ class ReasoningChannelNormalizer:
return "".join(output)
def finish(self) -> str:
- """Flush a stream that ended and close an open think block.
-
- Ended, not merely finished generating: a stop sequence ends a turn as a stop
- token does, and the block it cut inside is still owed its close.
- """
+ """Flush a stream that ended and close an open think block. Ended, not merely finished
+ generating: a stop sequence ends a turn as a stop token does, and the block it cut inside
+ is still owed its close."""
output = self.drain()
if self._in_reasoning:
# Nothing generated: no block at all, rather than a close with no opener.
@@ -2447,14 +2308,12 @@ class ReasoningChannelNormalizer:
class RecipientChannelNormalizer:
"""Convert a recipient-addressed reasoning protocol to ``<think>``.
- Muse Glimmer addresses every assistant block to a recipient: "self" carries
- reasoning, "user" the reply, any other name a tool call. Blocks repeat, so
- this tracks the recipient of each rather than one opener/closer pair.
- Generation resumes after the prompt's trailing ``<|start|>assistant``, so
- the first header arrives without that prefix.
-
- A tool-addressed block is held until it closes and then rewritten as a
- canonical ``<tool_call>``: no downstream parser recognizes the native form.
+ Muse Glimmer addresses every assistant block to a recipient: "self" carries reasoning, "user"
+ the reply, any other name a tool call. Blocks repeat, so this tracks the recipient of each
+ rather than one opener/closer pair. Generation resumes after the prompt's trailing
+ ``<|start|>assistant``, so the first header arrives without that prefix. A tool-addressed block
+ is held until it closes and then rewritten as a canonical ``<tool_call>``: no downstream parser
+ recognizes the native form.
"""
def __init__(
@@ -2471,8 +2330,8 @@ class RecipientChannelNormalizer:
self._passthrough = False
self._skip_opening_newline = False
self._between_blocks = True
- # How much of a held tool block has already been searched for a terminator,
- # so a long argument is scanned once rather than once per delta.
+ # How much of a held tool block has already been searched for a terminator, so a long argument is scanned once
+ # rather than once per delta.
self._tool_scanned = 0
def feed(self, text: str) -> str:
@@ -2500,14 +2359,14 @@ class RecipientChannelNormalizer:
if pieces is not None:
output.append("".join(text for _, text in pieces))
continue
- # No call in it at all: keep the body, but this block is closed and the
- # next header is still ours to read, so do not stop normalizing the turn.
+ # No call in it at all: keep the body, but this block is closed and the next header is still ours to
+ # read, so do not stop normalizing the turn.
output.append(_atem_surrounding_text(block))
continue
if self._in_reply:
- # The reply is content, but the turn can continue after it, so
- # follow it to its close rather than giving up on the rest.
+ # The reply is content, but the turn can continue after it, so follow it to its close rather than
+ # giving up on the rest.
index, length = _find_atem_block_end(self._buffer)
if index < 0:
stable, self._buffer = _split_partial_atem_block_end(self._buffer)
@@ -2542,11 +2401,10 @@ class RecipientChannelNormalizer:
self._between_blocks = True
continue
- # Whitespace separating two blocks is framing, not content. Emitted, it
- # puts a text run between two think blocks, and the UI merges only
- # reasoning that is adjacent, so one reasoning pass renders as two. Gated
- # on having emitted nothing since the last block, so that a space inside
- # off-protocol text survives however the stream happens to be chunked.
+ # Whitespace separating two blocks is framing, not content. Emitted, it puts a text run between two think
+ # blocks, and the UI merges only reasoning that is adjacent, so one reasoning pass renders as two. Gated
+ # on having emitted nothing since the last block, so that a space inside off-protocol text survives
+ # however the stream happens to be chunked.
if self._between_blocks:
stripped = self._buffer.lstrip()
if stripped != self._buffer:
@@ -2557,8 +2415,8 @@ class RecipientChannelNormalizer:
match = _ATEM_HEADER_RE.search(self._buffer)
block_end, end_len = _find_atem_block_end(self._buffer)
if block_end >= 0 and (match is None or block_end < match.start()):
- # A terminator with no block open is framing: the streamer keeps special
- # tokens, and continue_final_message resumes inside a block.
+ # A terminator with no block open is framing: the streamer keeps special tokens, and
+ # continue_final_message resumes inside a block.
output.append(self._buffer[:block_end])
self._buffer = self._buffer[block_end + end_len :]
self._between_blocks = True
@@ -2589,8 +2447,8 @@ class RecipientChannelNormalizer:
return "".join(output)
def finish(self) -> str:
- """Flush a naturally completed stream, closing an open reasoning block and
- keeping any call that closed inside a block the model never terminated."""
+ """Flush a naturally completed stream, closing an open reasoning block and keeping any call
+ that closed inside a block the model never terminated."""
output = self._flush(keep_calls = True)
if self._in_reasoning:
output += _THINK_CLOSE
@@ -2598,17 +2456,17 @@ class RecipientChannelNormalizer:
return output
def drain(self) -> str:
- """Flush buffered text without completing anything the model left open. Text
- held back survives; a call held back does not, so cancelling a turn can never
- be the thing that starts a tool running."""
+ """Flush buffered text without completing anything the model left open. Text held back
+ survives; a call held back does not, so cancelling a turn can never be the thing that
+ starts a tool running."""
return self._flush(keep_calls = False)
def _flush(self, *, keep_calls: bool) -> str:
output = self._buffer
self._buffer = ""
if self._tool_header is not None:
- # No terminator arrived, so unlike feed() there is no complete block to
- # hand on: keep the text the model had written and drop the rest.
+ # No terminator arrived, so unlike feed() there is no complete block to hand on: keep the text the model
+ # had written and drop the rest.
pieces = _atem_block_pieces(output, complete = False)
if pieces is None:
output = _atem_surrounding_text(output, complete = False)
@@ -2616,21 +2474,21 @@ class RecipientChannelNormalizer:
output = "".join(t for is_call, t in pieces if keep_calls or not is_call)
self._tool_header = None
elif output:
- # feed() held this back because it could still become framing. The stream
- # ended before it did, so drop it rather than show the control markup.
+ # feed() held this back because it could still become framing. The stream ended before it did, so drop it
+ # rather than show the control markup.
held = _atem_partial_framing_len(output)
output = output[: len(output) - held] if held else output
if not self._in_reasoning:
- # Flushed between blocks: a later delta must not be re-parsed as a
- # header now that the text before it has already been emitted.
+ # Flushed between blocks: a later delta must not be re-parsed as a header now that the text before it has
+ # already been emitted.
self._passthrough = True
return output
def make_reasoning_normalizer(markers: tuple[str, ...], *, in_reasoning: bool = False):
if markers and markers[0] == _ATEM_REASONING_RECIPIENT:
- # This protocol cannot start mid-block: its generation prompt ends at
- # "<|start|>assistant", so the model always writes its own header.
+ # This protocol cannot start mid-block: its generation prompt ends at "<|start|>assistant", so the model
+ # always writes its own header.
return RecipientChannelNormalizer(*markers)
return ReasoningChannelNormalizer(*markers, in_reasoning = in_reasoning)
@@ -2642,21 +2500,20 @@ def prompt_opens_reasoning_channel(
) -> bool:
"""Whether a rendered prompt *ends* by opening the native reasoning channel.
- Gemma-style templates end a post-tool generation prompt with the opener, so
- generation starts inside reasoning and emits only the closing marker.
-
- Only the tail decides -- the rule ``strip_open_reasoning_prefill`` already uses
- for ``<think>``. Position alone cannot tell a template's own prefill from
- replayed history, which keeps this markup through
- ``neutralize_control_markup_in_messages``, so an opener with content after it
- reads as closed; otherwise history could hide a plain answer in a think block.
- The cost is that a spliced continuation resuming inside a channel also reads as
- closed, leaving its reasoning visible as it was before.
-
- ``continued`` means this render resumed a trailing assistant turn, so the prompt
- ends on client text whose tail proves nothing. It is the render's own state, not
- the request flag, which outlives the continuation: the next tool-loop pass keeps
- the flag but renders an ordinary post-tool prompt that must still be read.
+ Gemma-style templates end a post-tool generation prompt with the opener, so generation starts
+ inside reasoning and emits only the closing marker.
+
+ Only the tail decides -- the rule ``strip_open_reasoning_prefill`` already uses for ``<think>``.
+ Position alone cannot tell a template's own prefill from replayed history, which keeps this
+ markup through ``neutralize_control_markup_in_messages``, so an opener with content after it
+ reads as closed; otherwise history could hide a plain answer in a think block. The cost is that
+ a spliced continuation resuming inside a channel also reads as closed, leaving its reasoning
+ visible as it was before.
+
+ ``continued`` means this render resumed a trailing assistant turn, so the prompt ends on client
+ text whose tail proves nothing. It is the render's own state, not the request flag, which
+ outlives the continuation: the next tool-loop pass keeps the flag but renders an ordinary
+ post-tool prompt that must still be read.
"""
if continued or not prompt or not markers:
return False
@@ -2677,10 +2534,9 @@ def normalize_reasoning_snapshots(
continued: bool = False,
ended = None,
):
- """Normalize a prefix-monotonic cumulative text stream when supported.
-
- ``ended`` is read after the stream: a turn a stop sequence ended still owes
- its open block a close, even if a cancel landed on the same step."""
+ """Normalize a prefix-monotonic cumulative text stream when supported. ``ended`` is read after
+ the stream: a turn a stop sequence ended still owes its open block a close, even if a cancel
+ landed on the same step."""
markers = markers or detect_reasoning_channel_markers(tokenizer, tools = tools)
if markers is None:
yield from stream
@@ -2718,28 +2574,25 @@ def detect_think_prefill(
) -> str:
"""Return the trailing open ``<think>`` prefill of a rendered prompt.
- Reasoning templates (Qwen3.6, DeepSeek-R1-style) end the generation
- prompt with ``<think>\\n`` so the model starts reasoning immediately.
- Because that opening tag is part of the *prompt*, skip_prompt streaming
- never emits it, and the frontend's ``<think>``/``</think>`` parser shows
- the reasoning as plain text instead of a thinking block. (The GGUF path
- is unaffected: llama-server's reasoning parser returns
- ``reasoning_content``, which gets re-wrapped in think tags.)
-
- Returns the exact prompt tail to re-emit at the start of the generated
- stream (e.g. ``"<think>\\n"``), or ``""`` when the prompt does not end
- with an open think block, including the ``enable_thinking=False`` case
+ Reasoning templates (Qwen3.6, DeepSeek-R1-style) end the generation prompt with ``<think>\\n``
+ so the model starts reasoning immediately. Because that opening tag is part of the *prompt*,
+ skip_prompt streaming never emits it, and the frontend's ``<think>``/``</think>`` parser shows
+ the reasoning as plain text instead of a thinking block. (The GGUF path is unaffected:
+ llama-server's reasoning parser returns ``reasoning_content``, which gets re-wrapped in think
+ tags.)
+
+ Returns the exact prompt tail to re-emit at the start of the generated stream, or ``""`` when
+ the prompt does not end with an open think block, including the ``enable_thinking=False`` case
where templates prefill an already-closed ``<think>\\n\\n</think>``.
- ``special_tokens`` is the tokenizer's special-token list. If ``</think>``
- is one, the streamer's skip_special_tokens strips the model's closing tag,
- so re-emitting the open would leave an unclosed block that swallows the
- answer. In that case return ``""`` and fall back to plain text.
+ ``special_tokens`` is the tokenizer's special-token list. If ``</think>`` is one, the streamer's
+ skip_special_tokens strips the model's closing tag, so re-emitting the open would leave an
+ unclosed block that swallows the answer; in that case return ``""`` and fall back to plain text.
``preserves_think_close`` says the stream keeps that closer anyway, as
- ``NativeToolTokenDecoder`` does so the parser can see a call rehearsed inside the
- block. The special-token list then says nothing, and skipping the opener is the same
- bug mirrored: a stray ``</think>``.
+ ``NativeToolTokenDecoder`` does so the parser can see a call rehearsed inside the block. The
+ special-token list then says nothing, and skipping the opener is the same bug mirrored: a stray
+ ``</think>``.
"""
if not prompt:
return ""
@@ -2755,17 +2608,13 @@ def detect_think_prefill(
def _normalize_tool_call_arguments(messages: list) -> list:
- """Coerce each assistant ``tool_calls[].function.arguments`` from a JSON
- string to a dict.
-
- The OpenAI wire format carries ``arguments`` as a JSON string, but some chat
- templates (e.g. the stricter Qwen tool templates shipped with mlx-community
- checkpoints) iterate ``arguments.items()`` and raise
- ``TypeError: Can only get item pairs from a mapping.`` on the string form
- when a prior tool call is re-rendered on the next turn. A dict works on both
- strict and lenient templates, so parse the string; leave non-JSON or non-dict
- values untouched. Returns the original list unchanged when nothing needed
- coercing (no copy)."""
+ """Coerce each assistant ``tool_calls[].function.arguments`` from a JSON string to a dict. The
+ OpenAI wire format carries ``arguments`` as a JSON string, but some chat templates (e.g. the
+ stricter Qwen tool templates shipped with mlx-community checkpoints) iterate
+ ``arguments.items()`` and raise ``TypeError: Can only get item pairs from a mapping.`` on the
+ string form when a prior tool call is re-rendered on the next turn. A dict works on both
+ strict and lenient templates, so parse the string; leave non-JSON or non-dict values
+ untouched. Returns the original list unchanged when nothing needed coercing (no copy)."""
mutated = False
out: list = []
for msg in messages:
@@ -2807,8 +2656,8 @@ def _take_tool_result(pending: list, call_id) -> Optional[dict]:
def _split_parallel_tool_calls(messages: list) -> list:
- """Llama 3.x templates render one call per message, so split parallel calls
- into consecutive single-call messages, each followed by its own result."""
+ """Llama 3.x templates render one call per message, so split parallel calls into consecutive
+ single-call messages, each followed by its own result."""
if not any(isinstance(m, dict) and len(m.get("tool_calls") or ()) > 1 for m in messages):
return messages
@@ -2857,8 +2706,8 @@ def _special_token_strings(tokenizer) -> dict:
try:
value = getattr(tokenizer, name, None)
except Exception:
- # A tokenizer property can raise on a partially loaded model; a missing
- # special is simply one fewer marker, never a failed request.
+ # A tokenizer property can raise on a partially loaded model; a missing special is simply one fewer
+ # marker, never a failed request.
continue
# AddedToken rather than str on some tokenizers, and its str() is the content.
if value is not None and not isinstance(value, str):
@@ -2873,38 +2722,35 @@ def markup_for_tokenizer(
tools = None,
template = None,
) -> Optional[ModelMarkup]:
- """Profile the loaded tokenizer's own structural markers, cached per tokenizer.
-
- Returns None when the template and vocabulary cannot be read, which falls back to the
- curated patterns: an unreadable model stays fully swept rather than unprotected."""
+ """Profile the loaded tokenizer's own structural markers, cached per tokenizer. Returns None
+ when the template and vocabulary cannot be read, which falls back to the curated patterns: an
+ unreadable model stays fully swept rather than unprotected."""
if tokenizer is None:
return None
try:
cached = _MARKUP_BY_TOKENIZER.get(tokenizer)
except TypeError: # not weak-referenceable
cached = None
- # A vision model stores the container processor here: the chat_template lives on the
- # processor while the vocabulary lives on the inner tokenizer, so each is read from
- # whichever actually has it (mirrors chat_eos's template_source unwrap).
+ # A vision model stores the container processor here: the chat_template lives on the processor while the
+ # vocabulary lives on the inner tokenizer, so each is read from whichever actually has it.
inner = getattr(tokenizer, "tokenizer", tokenizer)
- # An explicit *template* is the one this request will actually render with: the
- # generate-time mapper installs its template later, so profiling the load-time one left
- # the authorization catalog a step behind the prompt it was gating (#7066).
+ # An explicit *template* is the one this request will actually render with: the generate-time mapper installs its
+ # template later, so profiling the load-time one left the authorization catalog a step behind the prompt it was
+ # gating (#7066).
if not template:
template = getattr(tokenizer, "chat_template", None)
if not template:
template = getattr(inner, "chat_template", None)
- # Keyed on the template as well as the tokenizer, since get_chat_template() installs a
- # mapped template on the SAME object at generate time and a load-time profile would leave
- # its delimiters unswept (#7066); and on whether tools are present, since a named-template
- # dict emits different literals for "tool_use" and "default". Both selectors share one
- # entry, so a conversation alternating tool and no-tool turns keeps hitting.
+ # Keyed on the template as well as the tokenizer, since get_chat_template() installs a mapped template on the SAME
+ # object at generate time and a load-time profile would leave its delimiters unswept (#7066); and on whether tools
+ # are present, since a named-template dict emits different literals for "tool_use" and "default". Both selectors
+ # share one entry, so a conversation alternating tool and no-tool turns keeps hitting.
is_processor = _is_processor(tokenizer)
- # A processor always renders "default", so its profile does not vary with tools and the
- # cache must not key two identical entries under different selectors.
+ # A processor always renders "default", so its profile does not vary with tools and the cache must not key two
+ # identical entries under different selectors.
selector = bool(tools) and not is_processor
- # A named-template dict is unhashable, so the key is a stable serialization of it;
- # without this the cache write raised TypeError and every call rebuilt the profile.
+ # A named-template dict is unhashable, so the key is a stable serialization of it; without this the cache write
+ # raised TypeError and every call rebuilt the profile.
if not isinstance(template, str):
try:
template_key = json.dumps(template, sort_keys = True, default = str)
@@ -2920,10 +2766,9 @@ def markup_for_tokenizer(
cached = None
tokens = None
tokens = _tokenizer_strings(inner)
- # ProcessorMixin.apply_chat_template does NOT switch to "tool_use" implicitly; it
- # renders "default" unless chat_template= names another. _selected_chat_template_strings
- # already documents this, so profiling with the tokenizer rule left a processor's own
- # default-template boundary unswept while the render emitted it (#7066).
+ # ProcessorMixin.apply_chat_template does NOT switch to "tool_use" implicitly; it renders "default" unless
+ # chat_template= names another. Profiling with the tokenizer rule left a processor's own default-template boundary
+ # unswept while the render emitted it (#7066).
profile = model_markup(
template,
tokens,
@@ -2933,8 +2778,8 @@ def markup_for_tokenizer(
)
try:
entry = cached if isinstance(cached, dict) else {}
- # Two selectors and one template per tokenizer; a template swap adds a key rather
- # than growing without bound, so trim if a tokenizer somehow cycles templates.
+ # Two selectors and one template per tokenizer; a template swap adds a key rather than growing without bound,
+ # so trim if a tokenizer somehow cycles templates.
if len(entry) >= 4:
entry.clear()
entry[(template_key, selector)] = profile
@@ -2945,10 +2790,8 @@ def markup_for_tokenizer(
def trailing_assistant_text(messages: list) -> Optional[str]:
- """Plain text of a trailing assistant turn, else None.
-
- Only plain text resumes: tool calls and image parts have no resume point.
- """
+ """Plain text of a trailing assistant turn, else None. Only plain text resumes: tool calls and
+ image parts have no resume point."""
if not messages:
return None
last = messages[-1]
@@ -2970,12 +2813,10 @@ def trailing_assistant_text(messages: list) -> Optional[str]:
def last_user_text(messages: list) -> str:
- """Text of the newest user turn, with any ``<img>`` markup stripped.
-
- Scans back rather than reading ``messages[-1]``: a continuation ends on the
- assistant partial. Stops at the newest user turn even when it is empty (an
- image-only message), so an older question is never resurrected.
- """
+ """Text of the newest user turn, with any ``<img>`` markup stripped. Scans back rather than
+ reading ``messages[-1]``: a continuation ends on the assistant partial. Stops at the newest
+ user turn even when it is empty (an image-only message), so an older question is never
+ resurrected."""
from core.inference.message_content import content_to_text
for message in reversed(messages or []):
@@ -3032,10 +2873,8 @@ def prompt_serializes_structured_media(prompt, messages) -> bool:
def vlm_prompt_issue(prompt, messages) -> Optional[str]:
- """Name the way a VLM render came back unusable, else None.
-
- Shared by both backends so a defect one of them refuses stays refused by the other.
- """
+ """Name the way a VLM render came back unusable, else None. Shared by both backends so a defect
+ one of them refuses stays refused by the other."""
if not isinstance(prompt, str) or not prompt.strip():
return "an empty prompt"
if prompt_serializes_structured_media(prompt, messages):
@@ -3064,21 +2903,18 @@ def messages_with_attached_image(
) -> list:
"""The conversation to render for a turn that carries an attached image.
- Prepends *system_prompt* as a leading system turn, then injects an ``{"type": "image"}``
- part into the LAST user turn and leaves every other turn -- assistant ``tool_calls``
- and ``role="tool"`` results included -- exactly as the caller sent it. Rebuilding from
- the newest user TEXT instead dropped the folded system instruction and the tool history
- an OpenAI tool loop replays (#10092).
-
- Nothing the caller owns is mutated: callers still read those dicts after generation,
- and a retry re-renders the same list.
-
- *structured_content* wraps content in part lists, as a processor template expects; MLX
- may render through the nested text tokenizer, whose template expects a string.
-
- *fallback_user_text* stands in for a user turn with no text of its own, and opens one
- when there is no user turn at all. Left empty, the conversation is unchanged, so a
- backend that would rather refuse an image nobody asked about keeps refusing it.
+ Prepends *system_prompt* as a leading system turn, then injects an ``{"type": "image"}`` part
+ into the LAST user turn and leaves every other turn -- assistant ``tool_calls`` and
+ ``role="tool"`` results included -- exactly as the caller sent it. Rebuilding from the newest
+ user TEXT instead dropped the folded system instruction and the tool history an OpenAI tool loop
+ replays (#10092). Nothing the caller owns is mutated: callers still read those dicts after
+ generation, and a retry re-renders the same list.
+
+ *structured_content* wraps content in part lists, as a processor template expects; MLX may
+ render through the nested text tokenizer, whose template expects a string. *fallback_user_text*
+ stands in for a user turn with no text of its own, and opens one when there is no user turn at
+ all. Left empty, the conversation is unchanged, so a backend that would rather refuse an image
+ nobody asked about keeps refusing it.
"""
conversation = list(messages or [])
if structured_content:
@@ -3143,15 +2979,12 @@ def messages_with_attached_image(
def render_advertising_tools(render, tools):
"""Render with *tools*, and say whether the prompt actually carries them.
- Returns ``(prompt, advertised)``. *render* takes a catalog and returns a prompt.
-
- Comparing the two renders rather than reading the body: a body that merely names the
- ``tools`` variable can still drop the schema, and a renderer taking ``tools=`` through
- ``**kwargs`` can swallow it without ever raising.
-
- The no-tools probe runs FIRST so the prompt this turn uses is the last thing the
- renderer produced, for anything that caches or observes the render. A probe that raises
- answers "advertised": the render that failed is the throwaway one.
+ Returns ``(prompt, advertised)``; *render* takes a catalog and returns a prompt. Comparing the
+ two renders rather than reading the body: a body that merely names the ``tools`` variable can
+ still drop the schema, and a renderer taking ``tools=`` through ``**kwargs`` can swallow it
+ without ever raising. The no-tools probe runs FIRST so the prompt this turn uses is the last
+ thing the renderer produced, for anything that caches or observes the render. A probe that
+ raises answers "advertised": the render that failed is the throwaway one.
"""
if not tools:
return render(None), False
@@ -3172,15 +3005,14 @@ def append_assistant_turn(
) -> None:
"""Append a generated assistant turn to *conversation*.
- A continuation leaves the resumed partial trailing, and the partial plus what the
- model just added are one turn, so they are merged: appending would instead give two
- consecutive assistant messages and break role alternation. Self-limiting, since
- after a tool result the conversation no longer ends with a plain assistant turn.
+ A continuation leaves the resumed partial trailing, and the partial plus what the model just
+ added are one turn, so they are merged: appending would instead give two consecutive assistant
+ messages and break role alternation. Self-limiting, since after a tool result the conversation
+ no longer ends with a plain assistant turn.
- Merge over the resumed turn rather than replacing it, or every key the partial
- carried but the continuation does not repeat is lost. ``extra_content`` is such a
- key, and Gemini reads the text part's thought signature back from it alone, so a
- resumed turn replayed without it is rejected.
+ Merge over the resumed turn rather than replacing it, or every key the partial carried but the
+ continuation does not repeat is lost. ``extra_content`` is such a key, and Gemini reads the text
+ part's thought signature back from it alone, so a resumed turn replayed without it is rejected.
"""
# Same acceptance rule as the prompt boundary, so a partial sent as text parts merges too.
prev_text = trailing_assistant_text(conversation) if continue_final_message else None
@@ -3194,13 +3026,11 @@ def append_assistant_turn(
def strip_open_reasoning_prefill(prefix: str) -> str:
- """Drop a generation prompt's unclosed ``<think>`` opener.
-
- A splice appends the visible partial to this prefix, so on a template that prefills
- an open block (DeepSeek-R1, QwQ, Qwen3-Thinking) the answer would resume as reasoning.
- Only an opener the prompt itself ends on counts: a bare "<think>" typed into an
- earlier turn is rendered text, and cutting there would eat the transcript.
- """
+ """Drop a generation prompt's unclosed ``<think>`` opener. A splice appends the visible partial
+ to this prefix, so on a template that prefills an open block (DeepSeek-R1, QwQ,
+ Qwen3-Thinking) the answer would resume as reasoning. Only an opener the prompt itself ends
+ on counts: a bare "<think>" typed into an earlier turn is rendered text, and cutting there
+ would eat the transcript."""
open_at = prefix.rfind(_THINK_OPEN)
if open_at == -1 or open_at < prefix.rfind(_THINK_CLOSE):
return prefix
@@ -3215,13 +3045,11 @@ def render_prompt_with_boundary(
continue_final_message: bool = False,
tools: Optional[list] = None,
) -> str:
- """Render *messages* through a renderer's own chat template.
-
- With *continue_final_message* the prompt ends inside the trailing assistant turn, so
- the model resumes it. Processors predating the kwarg get a manual splice, taking the
- partial from *messages* (which the caller already swept) rather than a separate copy:
- a raw partial could close the turn or open another role instead of resuming (#7066).
- """
+ """Render *messages* through a renderer's own chat template. With *continue_final_message* the
+ prompt ends inside the trailing assistant turn, so the model resumes it. Processors predating
+ the kwarg get a manual splice, taking the partial from *messages* (which the caller already
+ swept) rather than a separate copy: a raw partial could close the turn or open another role
+ instead of resuming (#7066)."""
extra = {"tools": tools} if tools else {}
partial = trailing_assistant_text(messages) if continue_final_message else None
if not partial:
@@ -3244,17 +3072,14 @@ def render_prompt_with_boundary(
def neutralize_for_render(tokenizer, messages: list, tools: Optional[list]):
- """Sweep the catalog and the messages for control markup, in the one correct order.
-
- Returns ``(messages, tools, markup)``. One place because the sweep is order dependent:
- a call site that re-derived it swept the messages against a profile the render would
- not select (#7066).
- """
+ """Sweep the catalog and the messages for control markup, in the one correct order. Returns
+ ``(messages, tools, markup)``. One place because the sweep is order dependent: a call site
+ that re-derived it swept the messages against a profile the render would not select (#7066)."""
# Gated on the loaded model's own markers, so another family's sentinel is left alone.
markup = markup_for_tokenizer(tokenizer, tools)
tools = neutralize_tool_descriptions(tools, None, markup)
- # Sanitizing can empty the catalog, which flips the selector, so re-profile first
- # or the messages are swept against a template this request will not use (#7066).
+ # Sanitizing can empty the catalog, which flips the selector, so re-profile first or the messages are swept
+ # against a template this request will not use (#7066).
if bool(tools) != bool(markup and getattr(markup, "selected_with_tools", False)):
markup = markup_for_tokenizer(tokenizer, tools)
return neutralize_control_markup_in_messages(messages, None, markup), tools, markup
@@ -3270,12 +3095,10 @@ def apply_chat_template_for_generation(
preserve_thinking: Optional[bool] = None,
continue_final_message: bool = False,
) -> str:
- """Render the chat prompt. Try richest kwargs first; drop one
- group at a time on TypeError. Jinja / missing-variable errors
- propagate.
-
- With *continue_final_message* the prompt ends inside the trailing assistant
- turn, so the model resumes the partial instead of restarting it."""
+ """Render the chat prompt. Try richest kwargs first; drop one group at a time on TypeError.
+ Jinja / missing-variable errors propagate. With *continue_final_message* the prompt ends
+ inside the trailing assistant turn, so the model resumes the partial instead of restarting
+ it."""
# Shared choke point for the transformers and MLX backends (#7066).
messages, tools, _markup = neutralize_for_render(tokenizer, messages, tools)
reasoning_kwargs: dict = {}
@@ -3295,12 +3118,11 @@ def apply_chat_template_for_generation(
attempts.append(dict(reasoning_kwargs))
attempts.append({})
- # An attempt that drops the tools kwarg selects "default" rather than "tool_use", and
- # the messages above were swept for the profile of the template this request meant to
- # use. A custom or older tokenizer that rejects tools= therefore rendered messages
- # against a template they were not swept for, leaving a default-only boundary
- # byte-exact in client text. Built at most once, and only if such an attempt is
- # reached, so the ordinary path pays nothing (#7066).
+ # An attempt that drops the tools kwarg selects "default" rather than "tool_use", and the messages above were
+ # swept for the profile of the template this request meant to use. A custom or older tokenizer that rejects tools=
+ # therefore rendered messages against a template they were not swept for, leaving a default-only boundary
+ # byte-exact in client text. Built at most once, and only if such an attempt is reached, so the ordinary path pays
+ # nothing (#7066).
_fallback_markup = _UNPARSED
def _swept_for(kwargs: dict, msgs: list) -> list:
@@ -3313,8 +3135,8 @@ def apply_chat_template_for_generation(
_fallback_markup = markup_for_tokenizer(tokenizer, None)
return neutralize_control_markup_in_messages(msgs, None, _fallback_markup)
- # Anything not continuable (an empty partial included, matching the route guard and
- # render_prompt_with_boundary) renders as an ordinary new turn.
+ # Anything not continuable (an empty partial included, matching the route guard and render_prompt_with_boundary)
+ # renders as an ordinary new turn.
_continue_text = trailing_assistant_text(messages) if continue_final_message else None
_continuing = bool(_continue_text)
_boundary_kwargs = (
@@ -3345,11 +3167,9 @@ def apply_chat_template_for_generation(
raise RuntimeError("apply_chat_template_for_generation: no attempt produced a result")
def _render_continuation_manually(msgs: list) -> str:
- """For tokenizers predating ``continue_final_message`` (TypeError above).
-
- Prefix and partial come from the SAME swept copy: an attempt that drops the tools
- kwarg re-sweeps for the default template, whose markup would otherwise survive raw.
- """
+ """For tokenizers predating ``continue_final_message`` (TypeError above). Prefix and partial
+ come from the SAME swept copy: an attempt that drops the tools kwarg re-sweeps for the
+ default template, whose markup would otherwise survive raw."""
for kwargs in attempts:
swept = _swept_for(kwargs, msgs)
try:
@@ -3373,8 +3193,7 @@ def apply_chat_template_for_generation(
try:
return _render_with_fallback(messages)
except Exception:
- # Retry with repairs applied cumulatively. Originals render first, so
- # working templates stay byte-identical.
+ # Retry with repairs applied cumulatively. Originals render first, so working templates stay byte-identical.
candidates: list = []
normalized = _normalize_tool_call_arguments(messages)
if normalized is not messages:
@@ -3395,13 +3214,12 @@ def resolve_native_chat_template(
active_model_name,
hf_token = None,
):
- """The model's native chat template, fetched once and cached on *model_info*.
-
- Returns False when the repo has none and None when the fetch failed, so a failure is
- retried rather than pinned. Shared by the render path and by the authorization catalog,
- which must know the native template on the FIRST request too: it is fetched during
- rendering, so a catalog built before that saw no native profile at all and could
- authorize a tool the native render then left out of the prompt (#7066)."""
+ """The model's native chat template, fetched once and cached on *model_info*. Returns False when
+ the repo has none and None when the fetch failed, so a failure is retried rather than pinned.
+ Shared by the render path and by the authorization catalog, which must know the native
+ template on the FIRST request too: it is fetched during rendering, so a catalog built before
+ that saw no native profile at all and could authorize a tool the native render then left out
+ of the prompt (#7066)."""
native_tpl = model_info.get("native_chat_template")
if native_tpl is not None:
return native_tpl
@@ -3409,8 +3227,8 @@ def resolve_native_chat_template(
template_source = model_info.get("base_model") or active_model_name
if not template_source:
return None
- # Re-use the load-time trust_remote_code so a custom-code tokenizer repo can
- # instantiate its class (the stored flag already covers template_source).
+ # Re-use the load-time trust_remote_code so a custom-code tokenizer repo can instantiate its class (the stored
+ # flag already covers template_source).
trust_remote_code = bool(model_info.get("trust_remote_code", False))
try:
from transformers import AutoTokenizer
@@ -3422,8 +3240,8 @@ def resolve_native_chat_template(
native_tpl = nt.chat_template or False
except Exception as exc:
logger.warning("Could not load native chat template for '%s': %s", template_source, exc)
- # A failed fetch is not "no template": leave the sentinel unset so the next call
- # retries (caching False would pin the tool-dropping override).
+ # A failed fetch is not "no template": leave the sentinel unset so the next call retries (caching False would
+ # pin the tool-dropping override).
return None
model_info["native_chat_template"] = native_tpl
return native_tpl
@@ -3445,28 +3263,25 @@ def render_native_template(
):
"""Render ``messages`` + ``tools`` with the model's NATIVE chat template.
- Some Unsloth override templates (e.g. ``mistral``, ``gemma-4``) do not emit
- the ``tools`` schema, so a tool-calling turn silently stops advertising tools.
- The native template ships in the model repo and carries the family's
- tool-calling syntax. It is loaded straight from the repo (bypassing any
- override on the live tokenizer) and cached on ``model_info``. Returns the
- rendered prompt only if the native template actually emits the tools (render
- differs with vs without tools); otherwise ``None``. With ``return_metadata``,
- returns ``ChatTemplateRenderResult`` so callers can stream with the response
- protocol selected by this request's template.
-
- ``hf_token`` is the token the model was loaded with -- passed to the repo load
- so a gated/private model's native template can still be fetched (otherwise the
- fallback fails silently and keeps the override prompt that dropped tools).
-
- ``trust_remote_code`` is sourced from ``model_info`` (the value the model was
- actually loaded with) rather than a call-site argument, so the native-template
- reload uses exactly the consent already granted at load. A custom-code tokenizer
- repo raises in ``AutoTokenizer.from_pretrained`` unless ``trust_remote_code`` is
- passed, so without this the fallback fails silently and keeps the tool-dropping
- prompt for a model the user already consented to run remote code for. For a LoRA
- adapter the reload targets the base model, whose remote code was gated and loaded
- under the same stored flag, so re-passing it executes no unconsented code.
+ Some Unsloth override templates (e.g. ``mistral``, ``gemma-4``) do not emit the ``tools``
+ schema, so a tool-calling turn silently stops advertising tools. The native template ships in
+ the model repo and carries the family's tool-calling syntax; it is loaded straight from the repo
+ (bypassing any override on the live tokenizer) and cached on ``model_info``. Returns the
+ rendered prompt only if the native template actually emits the tools (render differs with vs
+ without tools); otherwise ``None``. With ``return_metadata``, returns
+ ``ChatTemplateRenderResult`` so callers can stream with the response protocol selected by this
+ request's template.
+
+ ``hf_token`` is the token the model was loaded with, passed to the repo load so a gated/private
+ model's native template can still be fetched (otherwise the fallback fails silently and keeps
+ the override prompt that dropped tools).
+
+ ``trust_remote_code`` is sourced from ``model_info`` (the value the model was actually loaded
+ with) rather than a call-site argument, so the reload uses exactly the consent already granted
+ at load: a custom-code tokenizer repo raises in ``AutoTokenizer.from_pretrained`` without it,
+ and the fallback would fail silently. For a LoRA adapter the reload targets the base model,
+ whose remote code was gated and loaded under the same stored flag, so re-passing it executes no
+ unconsented code.
"""
# ``apply_fn`` lets a backend inject its own render; defaults to the module helper.
if apply_fn is None:
@@ -3479,8 +3294,8 @@ def render_native_template(
if tokenizer is None:
return None
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
- # Render on a shallow copy: mutating the shared tokenizer.chat_template (outside the
- # generation lock) races concurrent requests.
+ # Render on a shallow copy: mutating the shared tokenizer.chat_template (outside the generation lock) races
+ # concurrent requests.
try:
render_tokenizer = copy.copy(tokenizer)
render_tokenizer.chat_template = native_tpl
@@ -3525,12 +3340,11 @@ def render_native_template(
_detect_reasoning_channel_markers_from_templates(
_selected_template_strings_from_value(native_tpl, tools)
),
- # The NATIVE profile decided this render's catalog: it can drop a tool the
- # active profile kept, so callers must gate healing and tool execution on this
- # list rather than on the one they sanitized themselves (#7066).
- # With *tools*, matching the render above: a named native template selects
- # "tool_use" for a tool-calling turn, and profiling it without them read
- # "default" instead, so a tool the render dropped was reported as advertised.
+ # The NATIVE profile decided this render's catalog: it can drop a tool the active profile kept, so callers
+ # must gate healing and tool execution on this list rather than on the one they sanitized themselves. With
+ # *tools*, matching the render above: a named native template selects "tool_use" for a tool-calling turn,
+ # and profiling it without them read "default" instead, so a tool the render dropped was reported as
+ # advertised (#7066).
neutralize_tool_descriptions(
tools, None, markup_for_tokenizer(render_tokenizer, tools)
),
@@ -3554,16 +3368,13 @@ def render_with_native_template_fallback(
hf_token: Optional[str] = None,
return_metadata: bool = False,
):
- """Return ``formatted_prompt``, swapping in a native-template render when an
- override template dropped the ``tools`` schema.
-
- If ``tools`` were requested but the live render is identical with and without
- them (detected by comparison, robust against tool names in the system prompt),
- re-render with the model's native template. Shared by the transformers and MLX
- backends so both advertise tools consistently. ``hf_token`` is forwarded so a
- gated/private model's native template can still be fetched. With
- ``return_metadata``, returns the selected prompt plus reasoning-channel markers
- for the exact template used by this request."""
+ """Return ``formatted_prompt``, swapping in a native-template render when an override template
+ dropped the ``tools`` schema. If ``tools`` were requested but the live render is identical
+ with and without them (detected by comparison, robust against tool names in the system
+ prompt), re-render with the model's native template. Shared by the transformers and MLX
+ backends so both advertise tools consistently. ``hf_token`` is forwarded so a gated/private
+ model's native template can still be fetched. With ``return_metadata``, returns the selected
+ prompt plus reasoning-channel markers for the exact template used by this request."""
live_markers = detect_reasoning_channel_markers(tokenizer, tools = tools)
def _result(
@@ -3574,8 +3385,8 @@ def render_with_native_template_fallback(
if return_metadata:
if advertised is None and tools:
# With *tools*, so the reported catalog is the one the render sanitized:
- # apply_chat_template_for_generation profiles with them, and omitting them
- # here described a "default" template the request never rendered (#7066).
+ # apply_chat_template_for_generation profiles with them, and omitting them here described a "default"
+ # template the request never rendered (#7066).
advertised = neutralize_tool_descriptions(
tools, None, markup_for_tokenizer(tokenizer, tools)
)
@@ -3583,10 +3394,9 @@ def render_with_native_template_fallback(
return prompt
if not tools:
- # Gemma 4 can emit its native reasoning protocol even when a generation-time
- # Unsloth override rendered a marker-free prompt. Preserve the live-verified
- # no-tools thinking behavior without letting cached native metadata describe
- # unrelated tool prompts that kept the active override.
+ # Gemma 4 can emit its native reasoning protocol even when a generation-time Unsloth override rendered a
+ # marker-free prompt. Preserve the live-verified no-tools thinking behavior without letting cached native
+ # metadata describe unrelated tool prompts that kept the active override.
markers = live_markers
if markers is None:
markers = detect_reasoning_channel_markers_from_model_info(
@@ -3595,8 +3405,8 @@ def render_with_native_template_fallback(
return _result(formatted_prompt, markers)
if apply_fn is None:
apply_fn = apply_chat_template_for_generation
- # Probe whether the live template dropped the schema. A tools-requiring template
- # can raise here; on any error keep the valid tools prompt rather than lose it.
+ # Probe whether the live template dropped the schema. A tools-requiring template can raise here; on any error keep
+ # the valid tools prompt rather than lose it.
try:
probe_no_tools = apply_fn(
tokenizer,
diff --git a/studio/backend/core/inference/chat_templates.py b/studio/backend/core/inference/chat_templates.py
index e2490bbf9ab..50d767b46c6 100644
--- a/studio/backend/core/inference/chat_templates.py
+++ b/studio/backend/core/inference/chat_templates.py
@@ -23,16 +23,14 @@ from typing import Optional
# up three parents to <backend> (mirrors utils/inference/inference_config.py).
_ASSETS_DIR = Path(__file__).parent.parent.parent / "assets" / "chat_templates"
-# the -GGUF suffix is retained on ModelConfig.identifier, so this excludes the bf16 repos
# unsloth/gemma-4-<variant>-GGUF (case-insensitive). The "-GGUF" suffix is retained on ModelConfig.identifier for HF
-# GGUF repos, so this matches E2B / E4B / 31B / 26B-A4B and any future unsloth/gemma-4-*-GGUF, while excluding gemma-3,
-# non-Unsloth, and non-GGUF identifiers (e.g. the bf16 "unsloth/gemma-4-E2B-it").
+# GGUF repos, so this matches E2B / E4B / 31B / 26B-A4B and any future unsloth/gemma-4-*-GGUF, while excluding
+# gemma-3, non-Unsloth, and non-GGUF identifiers (e.g. the bf16 "unsloth/gemma-4-E2B-it").
_GEMMA4_GGUF_RE = re.compile(r"^unsloth/gemma-4-.+-gguf$", re.IGNORECASE)
-# E2B/E4B omit the empty thought block on enable_thinking=false
# Google ships two distinct gemma-4 chat templates: E2B/E4B omit the empty "<|channel>thought<channel|>" block on
-# enable_thinking=false, while the 12b/26B-A4B/31B family emits it. Route the two GGUF families to the matching bundled
-# template so each keeps its model's intended behavior.
+# enable_thinking=false, while the 12b/26B-A4B/31B family emits it. Route the two GGUF families to the matching
+# bundled template so each keeps its model's intended behavior.
_GEMMA4_EDGE_GGUF_RE = re.compile(r"^unsloth/gemma-4-e[24]b-it-gguf$", re.IGNORECASE)
_GEMMA4_TEMPLATE_FILE = "gemma-4.jinja"
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.py
index d2afd949298..868a3d18496 100644
--- a/studio/backend/core/inference/checkpoint.py
+++ b/studio/backend/core/inference/checkpoint.py
@@ -40,14 +40,12 @@ from core.inference.context_window import (
)
from core.inference.instruction_pin import is_substantive
-# "rolling" is the pre-existing window, byte for byte
# "checkpoint" resets the epoch; "rolling" is the pre-existing window, byte for byte, and is both the A/B arm and the
# escape hatch for a template family that misbehaves.
CONTEXT_POLICY = os.environ.get("UNSLOTH_CONTEXT_POLICY", "checkpoint").strip().lower()
-# an oversized instruction is excluded whole, never truncated
-# Cap on X. An oversized instruction is excluded whole, never truncated: half an instruction is worse than none, because
-# it reads as complete.
+# Cap on X. An oversized instruction is excluded whole, never truncated: half an instruction is worse than none,
+# because it reads as complete.
MAX_TOKENS = int(os.environ.get("UNSLOTH_CHECKPOINT_MAX_TOKENS", "1024"))
MAX_FRACTION = float(os.environ.get("UNSLOTH_CHECKPOINT_MAX_FRACTION", "0.10"))
# bounded so an epoch that dropped 200 turns cannot yield 40 long-superseded instructions
@@ -120,38 +118,28 @@ def _pick(
) -> list[str]:
"""The selection itself, over positions that are either (text, cost) or not an item.
- Shared by the two paths that select, so the pair rule cannot hold on one and not the
- other: the fresh walk over evicted TURNS (`_select_items`) and the re-cap of a merged
- list of already-rendered STRINGS (`_recap`). It was written against turns only, and
- the merged path then re-capped with a plain newest-first walk that could take the
- opening and drop the successor the fresh walk had paired it with -- the abandoned
- request carried with its correction dropped, reached through the second compaction
- instead of the first.
-
- `reserve_oldest` takes the opening item before the newest-first walk. It is for the
- thread of short prompts, where the FIRST turn is the one that says what is being
- built: newest-first alone would spend all eight slots on the increments nearest the
- end ("add music", "now the score", "fix the pipes") and evict the statement of the
- task itself, which is the loss this pass exists to stop. The walk still runs
- newest-first afterwards, so a later change of direction is kept too, and rendering is
- oldest-first either way.
-
- It reserves the opening item TOGETHER WITH the next one, both or neither, because the
- turn right after the opening is the one that can contradict it without any newer turn
- showing that it did. See `_reserved_order` for why.
+ Shared by the two paths that select, so the pair rule cannot hold on one and not the other: the
+ fresh walk over evicted TURNS (`_select_items`) and the re-cap of a merged list of
+ already-rendered STRINGS (`_recap`). It was written against turns only, and the merged path then
+ re-capped with a plain newest-first walk that could take the opening and drop the successor the
+ fresh walk had paired it with.
+
+ `reserve_oldest` takes the opening item before the newest-first walk. It is for the thread of
+ short prompts, where the FIRST turn is the one that says what is being built: newest-first alone
+ would spend all eight slots on the increments nearest the end and evict the statement of the
+ task itself. The walk still runs newest-first afterwards, and rendering is oldest-first either
+ way. It reserves the opening item TOGETHER WITH the next one, both or neither, because the turn
+ right after the opening is the one that can contradict it without any newer turn showing that it
+ did (see `_reserved_order`).
`reserve_leading` is the same rule for a list whose first N entries arrived as one
- already-rendered block, where WHICH of them is the successor cannot be recovered. The
- block is oldest-first by the position of each item's NEWEST copy, so a successor the
- user restated later renders after the turns that came between: a perfectly valid block
- reads [opening, intervening rule, successor, newest], and reserving its first two
- entries pairs the opening with the intervening rule and lets the walk drop the actual
- correction ("Build Tetris", "Dark theme", "Add music!" carried at a 60-token cap while
- "Actually scrap that and build a Flappy Bird clone instead" was dropped). So the whole
- block is reserved as ONE unit instead of guessing: the successor is somewhere in it,
- whichever entry it is, and an abandoned opening is always the FIRST entry, since an
- opening the user restated is not abandoned and renders at the restatement. Keep the
- unit whole or drop its first entry -- no bullet has to be identified.
+ already-rendered block, where WHICH of them is the successor cannot be recovered: the block is
+ oldest-first by the position of each item's NEWEST copy, so a successor the user restated later
+ renders after the turns that came between, and reserving only its first two entries let the walk
+ drop the actual correction. So the whole block is reserved as ONE unit instead of guessing: the
+ successor is somewhere in it, and an abandoned opening is always the FIRST entry, since an
+ opening the user restated is not abandoned and renders at the restatement. Keep the unit whole
+ or drop its first entry -- no bullet has to be identified.
"""
def _item(index: int) -> Optional[tuple[str, int]]:
@@ -225,36 +213,24 @@ def _pick(
def _reserved_order() -> list[int]:
"""The walk order with the opening PAIR slotted in behind the newest usable turn.
- The opening turn is reserved because it is where the task is stated, but on its
- own that reservation states the task WRONG whenever the user changed direction
- early: the reserved turn was carried and the turn immediately after it was the
- one the slot cap dropped, so "Build Flappy Bird", "Actually build Tetris instead",
- "Add music" carried Flappy Bird and the music at max_items 2, and the same three
- with seven increments carried Flappy Bird and all seven at max_items 8. Both
- blocks tell the model to build the game the user abandoned and then apply every
- later increment to it.
-
- Reserving the opening turn together with its successor is the fix that needs no
- reading of the English: whatever the user said next about the opening request is
- carried alongside it. The pair costs one more slot than the single reservation,
- paid by the oldest turn the newest-first walk would have taken.
-
- It moves the hole rather than closing it, and only the TOKEN cap is really fixed.
- Against the SLOT cap, reserving the opening leaves a contiguous run of n -
- max_items turns dropped whatever the order, so a change of direction inside that
- run is lost either way: the single reservation drops [1, n-k] and the pair drops
- [2, n-k+1]. The pair therefore wins at index 1, which is the case above, and loses
- at index n-k+1. Fuzzed over 40,000 threads it is a net 18% fewer blocks that state
- the abandoned task, fixing about 2.5 for every one it breaks. Closing the class
- outright means not carrying the opening at all once it does not fit, which is the
- loss #9379 landed to stop.
-
- Placed behind the newest turn that CAN BE TAKEN, not merely the newest one that
- qualifies, exactly as the single reservation was. A turn costing more than the
- whole cap is skipped by the walk without spending anything, so reserving behind it
- puts the opening pair ahead of every usable recent turn: "Build Flappy Bird",
- "Actually build Tetris", then an oversized pasted request carried only Flappy Bird
- at a 153-token cap.
+ The opening turn is reserved because it is where the task is stated, but on its own that
+ reservation states the task WRONG whenever the user changed direction early: the reserved
+ turn was carried and the turn immediately after it was the one the slot cap dropped, so
+ "Build Flappy Bird", "Actually build Tetris instead", "Add music" carried Flappy Bird and
+ the music. Reserving the opening turn together with its successor is the fix that needs no
+ reading of the English: whatever the user said next about the opening request is carried
+ alongside it, at the cost of one more slot.
+
+ It moves the hole rather than closing it, and only the TOKEN cap is really fixed. Against
+ the SLOT cap, reserving the opening leaves a contiguous run of n - max_items turns dropped
+ whatever the order: the single reservation drops [1, n-k] and the pair drops [2, n-k+1], so
+ the pair wins at index 1 and loses at index n-k+1. Fuzzed over 40,000 threads it is a net
+ 18% fewer blocks that state the abandoned task. Closing the class outright means not
+ carrying the opening at all once it does not fit, which is the loss #9379 landed to stop.
+
+ Placed behind the newest turn that CAN BE TAKEN, not merely the newest one that qualifies: a
+ turn costing more than the whole cap is skipped by the walk without spending anything, so
+ reserving behind it would put the opening pair ahead of every usable recent turn.
"""
held = set(unit)
rest = [index for index in plain if index not in held]
@@ -278,13 +254,11 @@ def _pick(
# nothing here: it is usually the ONLY turn that fits, so the block would go out empty, which is the failure
# this pass exists to stop (a 43-token instruction then eight 160-token sections under 100 tokens).
return chosen
- # Whole or nothing: half a unit is the bug itself, the abandoned request carried with its correction dropped Whole
- # or nothing: something affordable was left behind and the unit still did not fit, and half a unit is the bug itself
- # -- the abandoned request carried with its correction dropped. So the reservation is abandoned and the newest-first
- # walk decides. The opening is excluded from that walk, or the fallback picks it up again whenever it is the cheaper
- # of the two (a 10-token "Build Tetris", a 30-token correction and a 25-token newest turn under 40 tokens dropped
- # the correction). By position, not by text: a user who RESTATES the opening has not abandoned it, and that newer
- # copy stays selectable. Kept only if it says something, since `chosen` already refused to be empty.
+ # Whole or nothing: something affordable was left behind and the unit still did not fit, and half a unit is the
+ # bug itself -- the abandoned request carried with its correction dropped. So the reservation is abandoned and the
+ # newest-first walk decides. The opening is excluded from that walk, or the fallback picks it up again whenever it
+ # is the cheaper of the two. By position, not by text: a user who RESTATES the opening has not abandoned it, and
+ # that newer copy stays selectable. Kept only if it says something, since `chosen` already refused to be empty.
return _walk([index for index in plain if index != unit[0]]) or chosen
@@ -334,31 +308,23 @@ def carried_forward_items(
) -> list[str]:
"""The user's standing instructions from the evicted turns, oldest first.
- Selected NEWEST-first so the budget is spent on the most recent instructions, then
- reversed for rendering, because reading order decides which of two conflicting
- instructions the model treats as current. Instructions older than the budget are
- silently dropped, which is why `max_items` is small and the header says "lossy".
-
- Repeats collapse to their newest copy, on the same key `_recap` uses.
+ Selected NEWEST-first so the budget is spent on the most recent instructions, then reversed for
+ rendering, because reading order decides which of two conflicting instructions the model treats
+ as current. Instructions older than the budget are silently dropped, which is why `max_items` is
+ small and the header says "lossy". Repeats collapse to their newest copy, on the same key
+ `_recap` uses.
- ONE walk, with no length floor. The floor was 80 characters, and a real chat does not
- clear it: measured on a live session, "Create a Flappy Bird game in HTML" (33), "Add
- music to the game" (21) and "Continue work" (13) all failed it, so three resets each
- carried an EMPTY block and the statement of what the user was building was evicted
- with the rest. The budget was never the constraint there -- 473 tokens free and
- nothing to spend it on.
-
- It was first kept as a fallback, taken only when the floored pass found nothing. That
- was worse than useless in the case that matters most: a long "Build a Flappy Bird
- game ..." followed by a short "Actually make it Tetris" clears the floor on the first
- turn alone, so the fallback never ran and the block carried only the abandoned
- request. The user's latest direction was dropped precisely because an earlier turn
- happened to be wordy.
+ ONE walk, with no length floor. The floor was 80 characters, and a real chat does not clear it:
+ measured on a live session, "Create a Flappy Bird game in HTML", "Add music to the game" and
+ "Continue work" all failed it, so three resets each carried an EMPTY block. Keeping it as a
+ fallback taken only when the floored pass found nothing was worse than useless in the case that
+ matters most: a long opening request followed by a short "Actually make it Tetris" clears the
+ floor on the first turn alone, so the fallback never ran and the block carried only the
+ abandoned request.
`is_substantive` still applies `_CONTINUATIONS`, which is what actually keeps "ok" and
- "continue" out of the system turn; the floor was only ever a second guess at the same
- question, and an empty block is not the safer answer -- it is the one where the model
- is told the conversation was compacted and given nothing of it.
+ "continue" out of the system turn; the floor was only ever a second guess at the same question,
+ and an empty block is not the safer answer.
"""
if not evicted or max_tokens <= 0 or max_items <= 0:
return []
@@ -435,21 +401,16 @@ def _recap(
) -> list[str]:
"""Re-apply the caps to a merged list. Newest-first selection, oldest-first render.
- Repeats collapse to their newest copy: an instruction can be carried, evicted and
- re-selected, and newest wins, which is the order the walk already runs in.
-
- `carried` is how many of the leading entries arrived as one already-rendered block, so
- this walk owes them the same rule the fresh walk owes the opening pair. Without it the
- merge re-created the exact output the pair exists to prevent, one compaction later: a
- block holding "Build Flappy Bird" and its "actually build Tetris" correction, merged
- with the increments evicted since, spends the budget newest-first, skips the long
- correction and then still affords the short opening, so the block tells the model to
- build the game the user cancelled and to apply every later increment to it.
-
- A COUNT rather than a pair, because which two bullets were the pair does not survive
- the render: the block is ordered by each item's newest copy, so the successor of a
- restated correction sits behind the turns that came between. The block is held whole
- or its first bullet is dropped, which needs no bullet to be identified. See `_pick`.
+ Repeats collapse to their newest copy: an instruction can be carried, evicted and re-selected,
+ and newest wins, which is the order the walk already runs in.
+
+ `carried` is how many of the leading entries arrived as one already-rendered block, so this walk
+ owes them the same rule the fresh walk owes the opening pair. Without it the merge re-created
+ the exact output the pair exists to prevent, one compaction later. A COUNT rather than a pair,
+ because which two bullets were the pair does not survive the render: the block is ordered by
+ each item's newest copy, so the successor of a restated correction sits behind the turns that
+ came between. The block is held whole or its first bullet is dropped, which needs no bullet to
+ be identified. See `_pick`.
"""
return _pick(
[(item, estimate_message({"role": "user", "content": item})) for item in items],
@@ -627,7 +588,6 @@ def fit_checkpoint_context(
if dropped == 0 and current_tokens <= prompt_target:
return messages, None
if dropped == 0:
- # nothing evictable and still too big: must fall through to the refusal below
# Nothing evictable and still too big (one huge message, or a system prompt that leaves no room). Must fall
# through to the refusal below, since every consumer reads None as "no truncation happened, carry on".
projected = list(messages)
diff --git a/studio/backend/core/inference/context_refusal.py b/studio/backend/core/inference/context_refusal.py
index ea46fea591c..6d33bfc8a7c 100644
--- a/studio/backend/core/inference/context_refusal.py
+++ b/studio/backend/core/inference/context_refusal.py
@@ -137,10 +137,10 @@ def _blame_latest_turn(context_tokens: int):
# a turn between the two really would have been served and only earns the soft wording. `>=` to match that check.
# Compared without the shared floor, since the hard wording is a claim about the turn's own size.
window = recorded_context or context_tokens
- # Reached only on a counted turn, so this is a claim about a measured size Reached only on a counted turn, per the
- # gate above, so this is a claim about a size that was measured. A turn the template renders as nothing on its own
- # is counted by difference, so every Gemma tool result can earn this wording again rather than being hedged down for
- # being a guess. Not defaulted to "user": `describe_oversize` gives an unnameable role generic advice.
+ # Reached only on a counted turn, per the gate above, so this is a claim about a size that was measured. A turn
+ # the template renders as nothing on its own is counted by difference, so every Gemma tool result can earn this
+ # wording again rather than being hedged down for being a guess. Not defaulted to "user": `describe_oversize`
+ # gives an unnameable role generic advice.
role = str(refusal.get("latest_turn_role") or "")
return role, not (window and latest_turn >= window)
@@ -173,10 +173,9 @@ def _history_cannot_help(context_tokens: int) -> bool:
return irreducible > 0 and window > 0 and irreducible >= window
-# split by role because of the lever: "send it in smaller pieces" is useless for turns the user did not type
# Per role: what to call the turn when it merely dominates, what to call it when it does not fit at all, and the lever
-# worth offering. The lever is why this splits by role -- "send it in smaller pieces" is useless for turns the user did
-# not type.
+# worth offering. The lever is why this splits by role -- "send it in smaller pieces" is useless for turns the user
+# did not type.
_ROLE_ADVICE = {
"user": (
"Most of this prompt is the message just sent",
@@ -196,7 +195,6 @@ _ROLE_ADVICE = {
"The file the model passed to a tool does not fit on its own",
"ask for a smaller file, or raise the Context Length before retrying",
),
- # the same shape with no file in it: "ask for a smaller file" names the wrong thing
# The same shape with no file in it: an oversized program, command, query or MCP payload. "Ask for a smaller file"
# names the wrong thing and cannot be acted on, so this one says what is actually true of every tool.
"assistant_tool_payload": (
@@ -269,7 +267,6 @@ def describe_oversize(request_tokens: int, context_tokens: int) -> str:
) + oversize_advice(context_tokens)
-# anything absent gets the neutral line: an MCP tool's payload is not a file and not a program
# What the user can actually shorten, per tool. Anything absent gets the neutral line: an MCP tool's payload is not a
# file and not a program, and guessing at it is worse than saying the one thing that is true of every tool.
_TOOL_LEVERS = {
diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.py
index 4886c09fbee..840a02a6dc8 100644
--- a/studio/backend/core/inference/context_window.py
+++ b/studio/backend/core/inference/context_window.py
@@ -16,10 +16,8 @@ _UNPRICED_MEDIA_TYPES = frozenset(
("image_url", "input_audio", "audio", "input_image", "input_video")
)
-# How far BELOW the prompt budget a compaction trims, as a fraction of that budget. Trimming to exactly the budget puts
-# the next turn over it again, so the boundary creeps forward every turn: llama-server's prefix cache dies each time and
-# there is no discrete compaction event to report. Taking a chunk out in one go buys a stretch of turns with a fixed
-# head, at the cost of the headroom itself, hence a minority of the budget.
+# Trim BELOW the budget: trimming to exactly it puts the next turn over again, so the boundary creeps every turn and
+# the prefix cache dies.
_COMPACTION_HEADROOM_RATIO = max(
0.0, min(0.9, float(os.environ.get("ROLLING_COMPACTION_HEADROOM_RATIO", "0.25")))
)
@@ -61,19 +59,8 @@ def estimate_messages_tokens(messages: list[dict]) -> int:
def estimate_messages_tokens_dense(messages: list[dict]) -> int:
- """The same estimate, but honest about text that tokenises densely.
-
- Four characters per token is about right for English and badly wrong for CJK and
- emoji, which run closer to one token per character. Measured on an 81-message CJK
- chat: 1295 estimated against 2737 real, a 2.1x undercount, which a caller sizing a
- search budget spends as room it does not have. `_conversation_search_tokens` already
- charges non-ASCII a token each when pricing the result; this is the same rule applied
- to the spend, which is the half that was missing.
-
- Deliberately NOT the default. `truncate_oldest_messages` evicts on the flat estimate,
- and making eviction pessimistic would drop history a request could have kept. Only a
- caller deciding how much room is LEFT wants this, where erring high is the safe side.
- """
+ """Estimate charging non-ASCII a token per character (2.1x undercount measured on CJK). Not the
+ default: eviction must not be pessimistic."""
total = 0
for message in messages:
try:
@@ -86,19 +73,10 @@ def estimate_messages_tokens_dense(messages: list[dict]) -> int:
return total
-# ASCII that runs this far without a break is not prose. Measured with Qwen3 over 16-20k character samples, in
-# characters per token: base64 1.35, hex 1.13, minified JSON 2.75, against English prose at 3.27 and Python source at
-# 4.38. The estimate above charges all of them the English four, so a pasted blob is priced at a third of what it costs,
-# and a caller sizing the room LEFT then hands out room that is already occupied. The rule is per RUN rather than per
-# message, so a blob pasted into a sentence is priced as a blob: a run this long is the thing itself. 64 characters
-# rather than a rounder number because base64 is conventionally wrapped at 76, and at a threshold of 80 a wrapped blob
-# scores as ordinary prose. Measured on the samples above, runs of 64+ non-space characters cover 100% of an unwrapped
-# blob, 98.6% of a wrapped one, 0% of the Python source and 23.5% of a README -- and that 23.5% is its URLs and table
-# rules, which tokenise near this rate themselves rather than at the prose rate.
+# Unbroken ASCII runs are blobs, not prose: base64/hex/minified JSON run 1.1-2.8 chars/token against 3.3 for English.
+# 64 not 80, since base64 wraps at 76.
_DENSE_RUN_CHARS = 64
-# Two characters per token, not one. It stays BELOW the measured cost of every sample, so no turn is priced above what
-# it really costs: over-pricing a turn spends the very room this budget exists to hand out, and a result cut to pay for
-# room that was never occupied is the same waste from the other side.
+# Two characters per token, not one: stays below the measured cost of every sample, so no turn is over-priced.
_DENSE_RUN_CHARS_PER_TOKEN = 2
_DENSE_RUN_RE = re.compile(r"\S{%d,}" % _DENSE_RUN_CHARS)
@@ -106,20 +84,8 @@ _DENSE_RUN_RE = re.compile(r"\S{%d,}" % _DENSE_RUN_CHARS)
def estimate_messages_tokens_conservative(
messages: list[dict], *, dense_ascii: bool = False
) -> int:
- """`estimate_messages_tokens_dense`, with unbroken ASCII runs charged as the blobs
- they are.
-
- For the caller with no tokenizer and no rolling fit behind it: the native loop prices
- what a thread has already spent, and if that number is low the result it then admits
- is what pushes the next prompt past the window, with nothing downstream to recover.
- Non-ASCII keeps its token per character, ordinary ASCII keeps the English four, and
- only the long unbroken runs are charged at `_DENSE_RUN_CHARS_PER_TOKEN`.
-
- ``dense_ascii`` charges ALL of a message's ASCII at that rate, for the messages that
- are dense whether or not they hold an unbroken run: a tool result is `hexdump`, `ls
- -l` or a stack trace as often as it is a blob, and those are space-separated. It
- applies to the ASCII only, so a CJK result is not charged twice for being a result.
- """
+ """As above, but long unbroken ASCII runs are charged as blobs; ``dense_ascii`` charges all
+ ASCII that way."""
total = 0
for message in messages:
try:
@@ -131,8 +97,7 @@ def estimate_messages_tokens_conservative(
if dense_ascii:
total += max(1, wide + (len(text) - wide) // _DENSE_RUN_CHARS_PER_TOKEN)
continue
- # ASCII only: a run of CJK is already charged a token a character above, and charging it here as well would
- # price it twice.
+ # ASCII only: a run of CJK is already charged a token a character above.
runs = sum(
sum(1 for char in match.group(0) if ord(char) <= 127)
for match in _DENSE_RUN_RE.finditer(text)
@@ -143,12 +108,7 @@ def estimate_messages_tokens_conservative(
def group_turns(messages: list[dict]) -> list[list[dict]]:
- """Split messages into the turn groups the rolling window evicts as single units.
-
- Each assistant tool call starts its own group holding its tool results, so long agent
- runs evict old exchanges without orphaning results. Exposed so callers that act on
- evicted turns use the same unit the evictor does.
- """
+ """Split messages into the turn groups the rolling window evicts as single units."""
groups: list[list[dict]] = []
for message in messages:
starts_tool_exchange = message.get("role") == "assistant" and bool(
@@ -169,11 +129,8 @@ def group_turns(messages: list[dict]) -> list[list[dict]]:
def evicted_messages(before: list[dict], after: list[dict]) -> list[dict]:
- """Messages present in ``before`` and absent from ``after``, in their original order.
-
- Identity, not equality: the truncation helpers reuse the same dict objects, and a
- chat can contain two byte-identical turns ("continue" twice) that equality collapses.
- """
+ """Messages in ``before`` and not ``after``. Identity, not equality: two turns can be
+ byte-identical."""
kept = {id(message) for message in after}
return [message for message in before if id(message) not in kept]
@@ -186,11 +143,8 @@ def truncate_oldest_messages(
min_dropped: int = 0,
estimate_message: Callable[[dict], int] = estimate_message_tokens,
) -> tuple[list[dict], int]:
- """Drop complete oldest turns while preserving system messages and the latest turn.
-
- ``min_dropped`` keeps evicting past the point where the prompt fits, so a thread can
- re-apply the boundary it already compacted to instead of one that slides every turn.
- """
+ """Drop oldest turns, keeping system messages and the latest. ``min_dropped`` evicts past the
+ fit, so a boundary can be re-applied."""
if not messages or (keep_ratio >= 1.0 and min_dropped <= 0):
return messages, 0
@@ -258,22 +212,16 @@ def truncate_oldest_messages(
for index, group in enumerate(groups):
if index not in dropped_groups:
if kept and kept[-1].get("role") == "user" and group and group[0].get("role") == "user":
- # Strict chat templates reject adjacent user turns, which an internal tool re-prompt after an evicted
- # exchange would produce.
+ # Strict chat templates reject adjacent user turns, which a re-prompt after an evicted exchange would
+ # produce.
kept.append({"role": "assistant", "content": _OMITTED_TOOL_EXCHANGE})
kept.extend(group)
return kept, dropped
def messages_without_unpriced_media(messages: list[dict]) -> list[dict]:
- """Return the text/template portion that llama-server can count reliably.
-
- ``/apply-template`` does not include tokens added later by the multimodal
- processor. Sending base64 there is therefore both expensive and misleading, but
- skipping the rolling fit entirely also sends an already-overlong text history to
- prefill. Count a media-free shallow copy as a lower bound instead. The original
- messages, including every media part, remain the request that is ultimately sent.
- """
+ """Text-only lower bound: ``/apply-template`` misses tokens the multimodal processor adds later.
+ The request still sends every media part."""
stripped = [_message_without_unpriced_media(message) for message in messages]
return (
messages if all(before is after for before, after in zip(messages, stripped)) else stripped
@@ -281,23 +229,17 @@ def messages_without_unpriced_media(messages: list[dict]) -> list[dict]:
def prompt_budget(context_length: int, max_tokens: Optional[int]) -> int:
- """Tokens available to the PROMPT, once room for the reply is set aside.
-
- Exported so the recall sizing and the client's over-long-request explanation share
- this formula rather than each keeping a copy that drifts from the actual fit.
- """
+ """Tokens available to the PROMPT once reply room is set aside. Exported so recall sizing and
+ the client explanation share one formula."""
if context_length <= 1:
return context_length
requested = max_tokens if max_tokens is not None and max_tokens > 0 else context_length
return context_length - min(requested, max(1, context_length // 4))
-# Cap a tool-loop retrieval without reducing the allowance of smaller results.
_RETRIEVAL_BUDGET_SHARE = 0.5
-# small on purpose: missing the reserve is survivable
-# The least reply room a rescued prompt must leave, as a fraction of the window. Small on purpose: missing the reserve
-# is survivable, so this only rules out the stub-answer end.
+# Small on purpose: missing the reserve is survivable, so this only rules out the stub-answer end.
_RESCUE_REPLY_FLOOR_DIVISOR = 16
@@ -308,13 +250,8 @@ def retrieval_budget(
*,
reply_returns: bool = False,
) -> int:
- """Return the prompt room available to one retrieval.
-
- In a tool loop the retrieved exchange and the reply are protected on the next fit, so
- one retrieval may use at most half the prompt budget; single-shot uses the remainder.
- Kept beside ``prompt_budget`` so every backend sizing ``search_conversation`` shares
- one policy rather than quietly disagreeing.
- """
+ """Prompt room for one retrieval: in a tool loop the exchange and reply are protected next fit,
+ so at most half the budget."""
target = prompt_budget(context_length, max_tokens)
room = max(0, target - int(prompt_tokens or 0))
if reply_returns:
@@ -322,20 +259,12 @@ def retrieval_budget(
return room
-# a result is measured in characters and spent in tokens
-# Headroom against the tokenizer disagreeing with the estimate that sized a result. A result is measured in characters
-# and spent in tokens, so the conversion is the thing that can be wrong; 1% of the budget absorbs that without
-# noticeably shortening output.
+# Headroom for the tokenizer disagreeing with the character-based estimate that sized a result.
_TOOL_RESULT_BUDGET_BUFFER = 0.99
-# What a truncated result costs BESIDES its body: the notice naming the cut, the spill path and the command that resumes
-# it. Measured at 60-85 tokens, held clear of that. Reserved rather than ignored because the body is sized and the
-# notice appended after, so a budget spent entirely on the body overshoots by the notice every time, and at zero room,
-# where the notice IS the message, by the whole of it. Charged by `tools._truncate`, at the point it knows the result
-# really is being cut, and NOT subtracted from the room below. A result that fits carries no notice, so holding this
-# back up front would cut a result that would have fitted whole and then spend more than it saved: 200 tokens of room, a
-# 100-token result, and reserving first leaves 72 for the body and appends ~70 tokens of notice explaining the 28 that
-# were dropped.
+# What a truncated result costs besides its body (notice, spill path, resume command): 60-85 tokens. Charged by
+# `tools._truncate` only when the result really is cut, never up front, or a result that would have fitted whole is
+# cut for nothing.
_RESULT_NOTICE_RESERVE = 128
@@ -346,20 +275,9 @@ def tool_result_budget(
*,
buffer: float = _TOOL_RESULT_BUDGET_BUFFER,
) -> int:
- """Tokens a tool result may add without pushing the next prompt past its budget.
-
- The cap before this was a share of the WINDOW, so it never fell as the conversation
- filled: one result could take half a small context however little was left, and the
- next fit cannot recover because it protects the newest turn, the very result that does
- not fit. This prices the same result against the room actually remaining.
-
- Against ``prompt_budget`` rather than ``context_length``: a result sized to fill the
- physical window leaves the prompt fitting and nothing to answer in. Room for the reply
- is not room for the result. The figure covers the whole tool message, notice included:
- see `_RESULT_NOTICE_RESERVE`, which the truncation charges against this room when it
- turns out to need one. A caller with several tool calls to serve divides what comes
- back between them.
- """
+ """Tokens a tool result may add without pushing the next prompt over. Priced against room
+ remaining, not a share of the window, and against ``prompt_budget`` so the reply still has
+ room. Covers the whole tool message, notice included."""
target = prompt_budget(context_length, max_tokens)
return max(0, int(target * buffer) - int(prompt_tokens or 0))
@@ -371,58 +289,32 @@ def turn_is_servable(
*,
buffer: float = _TOOL_RESULT_BUDGET_BUFFER,
) -> bool:
- """Whether the next prompt fits once this tool returns, given an EMPTY result.
-
- `tool_result_budget` answers how much a result may add and clamps at zero, which the
- truncation reads as "cut hard" -- a number, never a refusal. So a turn whose prompt is
- already over budget before the tool has returned anything is indistinguishable from one
- with a little room left, and the loop runs the tool either way. The side effect lands,
- the result is squeezed to its notice, and the request is rejected regardless.
-
- Zero room is the refusal the budget could not express. Asked with the notice reserve
- charged, because a result cut to nothing still carries the notice saying so, and at
- this end of the scale that IS the whole message.
- """
+ """Whether the next prompt fits given an EMPTY result. `tool_result_budget` clamps at zero,
+ which reads as cut-hard rather than as the refusal it is."""
if context_length <= 1:
return True
return prompt_tokens + _RESULT_NOTICE_RESERVE + _reply_floor(context_length) <= context_length
def _reply_floor(context_length: int) -> int:
- """The least reply room a turn must leave to be worth running.
-
- Deliberately NOT `prompt_budget`, which sets aside the whole of `max_tokens`. That is
- the right reserve for sizing a result, and much too strict for deciding whether a call
- may run at all: at a 4096 window it leaves 3072 for the prompt, so the gate refused
- turns of 3,504 and 3,740 tokens that llama-server would have served without complaint,
- and the model sat retrying smaller and smaller edits against a bar it could not see.
-
- llama-server admits a prompt on size alone (`n_tokens() >= n_ctx`), so that is the line
- this has to draw, minus only enough to answer in. `_RESCUE_REPLY_FLOOR_DIVISOR` already
- encodes that judgement for the compaction rescue -- small on purpose, ruling out the
- stub-answer end rather than promising a full reply.
- """
+ """Least reply room a turn must leave to be worth running. Not `prompt_budget`, which reserves
+ all of `max_tokens` and refused 3,504-token turns at a 4096 window; llama-server admits on
+ size alone (`n_tokens() >= n_ctx`)."""
return max(1, context_length // _RESCUE_REPLY_FLOOR_DIVISOR)
-# How much of a completed call's arguments has to be at stake before replacing them with a receipt is worth the edit.
-# Below this the placeholder is a wash against what it removes, and the model loses sight of its own last action for
-# nothing. Fields naming the call's destination rather than its payload.
+# How much must be at stake before a receipt is worth the edit; below this the placeholder is a wash.
_PATH_KEYS = frozenset({"path", "file_path", "filePath"})
-# Longest path worth repeating inside every elided leaf's receipt.
_RECEIPT_PATH_MAX_CHARS = 120
_ARG_COMPACTION_FLOOR_CHARS = 1024
-# Once the arguments AS A WHOLE are worth reclaiming, the bar each string has to clear drops to this. Not zero: a
-# receipt is about 100 characters, so eliding anything shorter grows the call it is meant to shrink.
+# Not zero: a receipt is about 100 characters, so eliding anything shorter grows the call.
_ARG_COMPACTION_AGGREGATE_LEAF_FLOOR = 256
-# When the total of every string reaches this, the call is worth compacting even though no single string does. Matches
-# the per-leaf floor: the same amount of window either way.
+# Matches the per-leaf floor: the same amount of window either way.
_ARG_COMPACTION_TOTAL_FLOOR_CHARS = 1024
def _largest_leaf(value: Any) -> int:
- """Longest string anywhere in the parsed arguments, at any depth."""
if isinstance(value, str):
return len(value)
if isinstance(value, dict):
@@ -433,7 +325,6 @@ def _largest_leaf(value: Any) -> int:
def _total_leaves(value: Any) -> int:
- """Every string in the parsed arguments added together, at any depth."""
if isinstance(value, str):
return len(value)
if isinstance(value, dict):
@@ -449,62 +340,40 @@ def _compacted_arguments(
phrase: Optional[str] = None,
reply: object = None,
) -> Optional[str]:
- """A receipt standing in for a completed call's arguments, or None to leave them.
-
- The arguments of a call that has ALREADY run are the one part of a tool exchange that
- is pure history: the tool received them in full, the side effect landed, and for the
- file tools the content is on disk and re-readable. Replaying them verbatim buys the
- model nothing it cannot recover, which is what makes them the right thing to spend
- when a turn spills -- unlike the result, which is the only record of what happened.
-
- Structured rather than dropped, and naming the path, so the model can still see which
- file it just wrote and go and read it. A bare "[omitted]" reads as a failed call and
- is answered with a retry of the same oversized write.
- """
- # Resolved here, not as a default: the constant is defined below this function, and a literal default silently kept
- # the OLD wording on this path while the executed and refused paths moved to the new one -- the same receipt the
- # model misread as tool output, still being emitted by the most common caller.
+ """Receipt standing in for a completed call's arguments, or None to leave them. Structured and
+ naming the path, since a bare [omitted] reads as failure and draws a retry of the same
+ oversized write."""
+ # Resolved here, not as a default: the constant is defined below, and a literal default kept the old wording on
+ # this path.
phrase = phrase or _completed_phrase_for(name, reply)
if not isinstance(arguments, str):
return None
- # The general floor exists so a receipt is not bigger than what it replaces, and for ordinary history compaction a
- # call under it is not worth the churn. A REFUSED call is the opposite case: the refusal message itself is about to
- # be added to a prompt that already does not fit, so any reduction at all is the difference between the user reading
- # the refusal and reading llama-server's context error. The size check at the end still guarantees the receipt never
- # grows the prompt.
+ # A refused call ignores the general floor: its refusal is about to enter a prompt that already does not fit. The
+ # size check at the end still stops the receipt growing the prompt.
refused = phrase == _REFUSED_PHRASE
if not refused and len(arguments) < _ARG_COMPACTION_TOTAL_FLOOR_CHARS:
return None
try:
parsed = json.loads(arguments)
except Exception:
- # Unparseable arguments still cost the window, and a call that has already run cannot be re-issued from them, so
- # the size alone is an honest receipt. Worded from `phrase` like every other receipt. Hardcoding "after the call
- # ran" meant a REFUSED call with 1024+ characters of malformed JSON was replayed as having run, next to the tool
- # message saying nothing was written: two contradictory accounts of the same call, one of which invites the
- # model to reason from a side effect that never happened.
+ # Size alone is an honest receipt for unparseable arguments. Worded from `phrase`: hardcoding
+ # after-the-call-ran replayed a REFUSED call as having run.
_unparseable = json.dumps(
{"_unsloth_compacted": f"{len(arguments)} chars {phrase.format(where = '')}"},
ensure_ascii = False,
)
- # Checked here as well as at the end: without the general floor in front of it, a short refused call can have a
- # receipt longer than the arguments it replaces.
+ # Checked here as well as at the end: without the general floor a short refused call can get a receipt longer
+ # than what it replaces.
return _unparseable if len(_unparseable) < len(arguments) else None
if not isinstance(parsed, dict):
return None
path = parsed.get("path") or parsed.get("file_path") or parsed.get("filePath")
elided = 0
- # Per-leaf or aggregate, whichever lets this call be reclaimed. A batched refactor of fifty 800-character edits is
- # forty thousand characters of window with no single string over the floor, so a per-leaf test compacted NOTHING and
- # the call sat in the prompt permanently -- the pre-execution gate then had nothing to reclaim and refused a turn it
- # could have served. The floor exists so a receipt is not bigger than what it replaces, and the final size check
- # below still enforces that. Chosen from the TOTAL, not the largest leaf. Keying on the largest meant one
- # 1100-character edit beside fifty 800-character ones stayed in per-leaf mode and compacted only the first, leaving
- # about 40 KB replayed -- the mixed payload is exactly the shape a batched refactor produces.
+ # Chosen from the TOTAL: fifty 800-character edits clear no per-leaf floor and compacted nothing, and keying on
+ # the largest leaf compacted only the first of a mixed batch.
_leaf_floor = (
- # A refused call takes whatever it can get, floored only at the point where a leaf is longer than the receipt
- # describing it, so eliding cannot lose ground.
+ # A refused call takes what it can get, floored only where a leaf is shorter than its receipt.
_REFUSED_LEAF_FLOOR
if refused
else _ARG_COMPACTION_AGGREGATE_LEAF_FLOOR
@@ -513,35 +382,23 @@ def _compacted_arguments(
)
def _shrink(value: Any, key: str = "") -> Any:
- """Elide every large string, at whatever depth it sits.
-
- Depth is not optional: `edit_file` takes an `edits` ARRAY so several changes cost
- one call instead of one each, which puts the file content at
- `edits[i].new_string`. A top-level-only pass sees nothing there and quietly
- compacts nothing -- the batching and the compaction were written a day apart and
- only the tests noticed they had stopped meeting.
- """
+ """Elide every large string at any depth: `edit_file` takes an `edits` ARRAY, so content
+ sits at `edits[i].new_string`."""
nonlocal elided
- # The destination is never expendable: it is the one field that says WHICH file the call touched, and the
- # receipt promises the content can be found there. A deeply nested path over the aggregate floor was being
- # elided like content, leaving later turns unable to name the file they had just changed.
+ # The destination is never expendable: it names WHICH file the call touched, and the receipt promises the
+ # content is there.
if key in _PATH_KEYS:
return value
if isinstance(value, str) and len(value) >= _leaf_floor:
elided += len(value)
- # Named in the receipt only when repeating it is cheaper than the field it points at. Every elided leaf
- # embeds this, so a 500-character path across four leaves costs more than the content removed and the whole
- # compaction is rejected by the size check below. The `path` field is preserved verbatim either way, so
- # nothing is lost by leaving it out here.
+ # Repeated in each leaf's receipt only when cheaper than the field it points at. `path` is preserved
+ # verbatim either way.
where = (
f" to {path}"
if path and key not in _PATH_KEYS and len(str(path)) <= _RECEIPT_PATH_MAX_CHARS
else ""
)
- # `old_string` names text the edit REMOVED, and the completed phrase says the content is already written
- # `old_string` names text the edit REMOVED. The completed phrase says the content is already written and the
- # file on disk holds it, which of the two halves of a replacement is true only of `new_string`; said of the
- # old text it points the model at content the edit has just taken out.
+ # `old_string` names text the edit REMOVED; the completed phrasing is true only of `new_string`.
leaf_phrase = _COMPLETED_NEUTRAL_PHRASE if key == "old_string" else phrase
return f"<{len(value)} chars {leaf_phrase.format(where = where)}>"
if isinstance(value, dict):
@@ -557,63 +414,37 @@ def _compacted_arguments(
compacted = json.dumps(kept, ensure_ascii = False)
except Exception:
return None
- # Never grow the prompt to describe it: a call whose bulk is spread across many small fields leaves nothing to elide
- # and the receipts cost more than the fields did.
+ # Never grow the prompt to describe it: bulk spread over many small fields leaves nothing worth eliding.
return compacted if len(compacted) < len(arguments) else None
-# A leaf shorter than its own receipt costs room to elide, so this is the break-even point for the refusal wording
-# rather than a judgement about what is worth compacting.
+# A leaf shorter than its own receipt costs room to elide.
_REFUSED_LEAF_FLOOR = 110
_REFUSED_PHRASE = (
"of arguments you sent, elided; this call was refused before it ran and nothing was written"
)
-# Worded so the model cannot mistake it for the tool's OUTPUT. The first version read "<2581 chars written; re-read the
-# file to see it>" and was quoted straight back in the model's reasoning as "the tool result says ... the output was
-# omitted" -- it concluded the sandbox had mangled its file and abandoned a working approach. Says "you sent" so the
-# owner of the text is unambiguous, and says what it is not. The tail once read "read the file back if you need the
-# content", which contradicted every other line this PR added: `edit_file` now says not to read back what you just
-# wrote, and the starved and repeated-result notices both say reading again will not help. Three messages discouraging a
-# re-read and one inviting it is worse than either rule alone, and the re-read is the loop that cost eighteen calls in
-# one turn.
+# Must not read as the tool's OUTPUT: an earlier wording was quoted back as the output was omitted and the model
+# concluded its file was mangled. No invitation to re-read either, which every other notice discourages.
_COMPLETED_PHRASE = "of arguments you sent, already written{where}; elided to save room. Not tool output; the file on disk holds it."
-# The same receipt for a tool that writes no file. `python`, `terminal`, the search tools and every MCP tool are
-# selected by size and by having been answered, exactly like `edit_file`, so a 2000-character `code` argument was handed
-# a receipt saying it was "already written" and that "the file on disk holds it" -- a file the model can then set out to
-# read, or reason from as persisted, when nothing was persisted at all. Neither claim about the filesystem, for every
-# case where the reply does not settle it. Says only what is certainly true: these are the model's own arguments, the
-# call ran, and this is not the tool's output.
+# Same receipt for tools that write no file (`python`, `terminal`, search, MCP): the file wording told the model a
+# `code` argument was on disk.
_COMPLETED_NEUTRAL_PHRASE = (
"of arguments you sent, elided to save room; the call already ran. Not tool output"
)
-# Tools whose completed call really does leave the content in a file.
_FILE_WRITING_TOOLS = frozenset({"edit_file"})
-# A reply that opens like this reports a call that ran and did NOT do what was asked, so the file wording would describe
+# A reply opening like this reports a call that ran and did NOT do what was asked, so the file wording would describe
# a write that never landed.
_FAILED_REPLY_MARKERS = ("error", "failed", "not found", "no such file", "traceback")
-# A reply the WINDOW replaced, not one the tool wrote. Under a near-zero result budget `_fit_result_to_room` swaps the
-# real answer -- including an `Error: ...` -- for a stub saying there was no room for it, and that stub carries none of
-# the markers above. Read as proof of a write, it tells the model an edit landed when the edit may have failed, under
-# exactly the tight context that makes compaction run in the first place. Absence of evidence, so the neutral wording
-# applies.
+# A reply the WINDOW replaced, not one the tool wrote: `_fit_result_to_room` swaps even an `Error: ...` for a stub
+# with none of the markers above.
_INCONCLUSIVE_REPLY_MARKERS = ("no context room left", "chars for the model;")
def _reply_proves_a_write(name: str, content: object) -> bool:
- """Whether this reply settles that the call left its content in a file.
-
- The tool NAME alone is wrong in both directions, and under the tight context that
- triggers compaction the model acts on the answer. An `edit_file` that ran and returned
- "old_string not found" is not a write, and telling it the content is already on disk
- invites it to skip the retry the error was asking for. A `python` or `terminal` call
- whose code created files is not a non-write either, and telling it nothing was written
- invites it to do the same work twice.
-
- So the file wording is earned, not assumed: a file tool AND a reply that does not read
- as a failure. Everything else gets a receipt that claims nothing about the disk.
- """
+ """The tool NAME is wrong both ways: a failed `edit_file` is not a write and a `python` call can
+ be one. File wording needs a file tool AND a non-failure reply."""
if name not in _FILE_WRITING_TOOLS:
return False
if not isinstance(content, str):
@@ -630,55 +461,24 @@ def _completed_phrase_for(name: str, reply: object = None) -> str:
def compact_executed_call_arguments(messages: list[dict], call_id: str) -> list[dict]:
- """Replace ONE just-run call's arguments with a receipt, whatever else is protected.
-
- `compact_completed_tool_arguments` deliberately holds the newest exchange back, which
- is right while a call is still in flight and wrong the instant it returns. Running a
- tool needs no context at all -- only the NEXT prompt does, and by then the arguments
- describe something already on disk.
-
- That distinction is what lets an oversized call be run instead of refused: refusing
- left the arguments in the transcript anyway, the model retried with a fresh oversized
- call, and each round added a receipt and a refusal message while reclaiming less.
- Measured over three rounds of one thread: 50%, then 34%, then 15% of the conversation
- recovered, ending in a one-character reply. Running the call and compacting it costs
- the same tokens once and leaves the file written.
- """
- # None, not the constant: the receipt is chosen per tool, so a completed `python` call is not told its arguments are
- # on disk. `edit_file` still gets the wording this path was built and proven against.
+ """Compact ONE just-run call's arguments even if otherwise protected: only the NEXT prompt needs
+ them. This lets an oversized call run rather than be refused, where each retry reclaimed less
+ (50%, 34%, 15%)."""
+ # None, not the constant: the receipt is per tool, so a completed `python` call is not told its arguments are on
+ # disk.
return _compact_one_call(messages, call_id, None)
def compact_refused_tool_arguments(messages: list[dict], call_id: str) -> list[dict]:
- """Drop the arguments of one call that was declined, naming it as never sent.
-
- Refusing a call does not on its own make the turn servable, and on the template that
- made the refusal necessary it actively does not: an assistant turn's `tool_calls` are
- rendered only once a `tool` message answers them, and the refusal IS such a message.
- So declining costs the prompt the very arguments it was declining to afford, and the
- generation that follows is rejected with nothing written -- an accurate refusal the
- user never gets to act on.
-
- These arguments are the one case with no replay value whatsoever: the call did not
- run, so nothing on disk reflects them and there is nothing to re-read. Their own
- receipt has to say so, because the wording used for a completed call would tell the
- model to go and read a file that was never written.
- """
+ """Drop a declined call's arguments, named as never sent. `tool_calls` render only once a `tool`
+ message answers them, and the refusal is one, so declining costs the prompt what it declined
+ to afford."""
return _compact_one_call(messages, call_id, _REFUSED_PHRASE)
def _last_index_with_call(messages: list[dict], call_id: str) -> int:
- """Where the call this result answers actually is.
-
- Tool-call IDs are NOT unique across a conversation. The textual parsers number from
- `call_0` with an offset that starts at zero on every turn, and the structured
- fallback does the same when the server omits an ID, so a five-round turn holds
- several `call_0`s. Rewriting every match would relabel an earlier successful call as
- refused, or an earlier refused one as already written -- a receipt describing a
- different call's fate, which is worse than not compacting at all.
-
- Both callers act on the call just decided, so the last match is the right one.
- """
+ """Call ids are NOT unique: parsers number from `call_0` each turn, so rewriting every match
+ relabels an earlier call's fate. Callers act on the call just decided, so take the last."""
for index in range(len(messages) - 1, -1, -1):
message = messages[index]
if message.get("role") != "assistant":
@@ -694,7 +494,6 @@ def _last_index_with_call(messages: list[dict], call_id: str) -> int:
def _reply_for_call(messages: list[dict], call_id: str) -> object:
- """The last tool reply answering this id, or None when it has not been answered."""
for message in reversed(messages):
if message.get("role") == "tool" and str(message.get("tool_call_id") or "") == str(call_id):
return message.get("content")
@@ -706,11 +505,8 @@ def _compact_one_call(
call_id: str,
phrase: Optional[str] = None,
) -> list[dict]:
- """Rewrite exactly one call's arguments to a receipt worded by `phrase`.
-
- `None` leaves the wording to the tool, which is what a COMPLETED call wants: only
- the file tools may say the content is on disk.
- """
+ """Rewrite one call's arguments to a receipt worded by `phrase`; `None` lets the tool choose,
+ since only file tools may claim the content is on disk."""
if not call_id:
return messages
target = _last_index_with_call(messages, call_id)
@@ -744,9 +540,7 @@ def _compact_one_call(
return out
-# A `role=tool` reply proves an ANSWER, not an execution. The approval gate answers a declined call with exactly such a
-# message, and an unreadable call is answered without running either. Compacting those to the completed receipt tells
-# the model a file was written that the user refused, which it may then report or reason from.
+# A `role=tool` reply proves an ANSWER, not an execution: the approval gate answers a declined call with one.
_DID_NOT_RUN_MARKERS = (
"the user declined to run this tool call",
"could not be read",
@@ -757,7 +551,6 @@ _DID_NOT_RUN_MARKERS = (
def _reply_shows_execution(content: object) -> bool:
- """Whether this tool reply is the result of a call that actually ran."""
if not isinstance(content, str):
return True
head = content[:200].strip().lower()
@@ -765,18 +558,8 @@ def _reply_shows_execution(content: object) -> bool:
def _executed_call_sites(messages: list[dict]) -> "dict[tuple[int, str], object]":
- """`(message index, call id)` for each call a reply shows actually ran.
-
- Keyed on the SITE, not the id. Generated ids restart at `call_0` on every turn, so a
- conversation-wide set of "answered" ids says an earlier successful `call_0` vouches
- for a later one. Under a tight context that is how a call the user DECLINED came to be
- replayed with the completed receipt: the reply marker correctly skipped the denial,
- and the older success had already put the id in the set. The model is then told a file
- was written that it refused, which it may report or reason from.
-
- Paired the way the transcript reads: a reply answers the most recent announcement of
- that id still waiting for one.
- """
+ """Keyed on the SITE, not the id: generated ids restart at `call_0` each turn, so an earlier
+ success once vouched for a call the user DECLINED."""
pending: dict[str, list[int]] = {}
executed: dict[tuple[int, str], object] = {}
for index, message in enumerate(messages):
@@ -794,9 +577,8 @@ def _executed_call_sites(messages: list[dict]) -> "dict[tuple[int, str], object]
sites = pending.get(str(call_id))
if not sites:
continue
- # NEWEST pending announcement, not the oldest. Textual parsers number from `call_0` every turn, so an
- # interrupted call that never got a result leaves a stale site under the same id; pairing this reply with THAT
- # one marks the stale arguments executed and leaves the call that actually ran uncompactable.
+ # NEWEST pending announcement: an interrupted call leaves a stale site under the same id, and pairing there
+ # leaves the real call uncompactable.
site = sites.pop()
if _reply_shows_execution(message.get("content")):
executed[(site, str(call_id))] = message.get("content")
@@ -806,21 +588,9 @@ def _executed_call_sites(messages: list[dict]) -> "dict[tuple[int, str], object]
def compact_completed_tool_arguments(
messages: list[dict], *, protect_last: int = 0
) -> tuple[list[dict], int]:
- """Replace oversized arguments of already-executed calls with receipts.
-
- Returns the new message list and the number of calls compacted. The input is never
- mutated: this rewrites what is REPLAYED to the model, exactly as
- `strip_result_for_model` already does for results, while the stored thread and the
- arguments the tool actually received stay byte-identical.
-
- Only calls with a `role=tool` reply present are touched. A call still awaiting its
- result is the turn in flight, and rewriting its arguments would tell the model it
- wrote something different from what the tool is at that moment being handed.
-
- Oldest first, so the freshest exchange -- the one the model is mid-way through
- reasoning about -- is the last thing spent. ``protect_last`` holds that many trailing
- messages clear of the pass entirely.
- """
+ """Rewrite only what is REPLAYED; the stored thread and the arguments the tool received stay
+ byte-identical. Only answered calls are touched, oldest first; ``protect_last`` holds
+ trailing messages clear."""
answered = _executed_call_sites(messages)
if not answered:
return messages, 0
@@ -856,23 +626,12 @@ def compact_completed_tool_arguments(
def _blamed_role(message: dict) -> str:
- """The advice key for a turn: its role, except a call the model made itself.
-
- An assistant turn carrying `tool_calls` is reported as `assistant_tool_call` rather
- than `assistant`, because the two have opposite levers. "The reply being continued is
- too long, start a new reply" is the right answer for a resumed generation and the
- wrong one for a turn whose bulk is an 8 KB file the model passed to `edit_file`:
- starting a new reply re-runs the same write. Kept as a role key so the split costs
- the advice table one row and `_blame_latest_turn` nothing.
- """
+ """Advice key: role, except an assistant turn with `tool_calls`, where start-a-new-reply is the
+ wrong lever for an 8 KB payload."""
role = str(message.get("role") or "")
if role == "assistant" and message.get("tool_calls"):
- # Split again by whether a FILE is involved. The file wording reached an oversized `python`, `terminal`, web or
- # MCP call and told the user to ask for a smaller file when the payload was a program, a command or a query --
- # naming the wrong cause and offering an action that cannot shrink it. From the call that accounts for the
- # turn's SIZE, not from whichever call happens to be a file tool. A parallel batch holding a small `edit_file`
- # beside an oversized `python` or MCP payload was diagnosed as a file that is too large, so the advice was to
- # ask for a smaller file -- an action that cannot shrink the payload that caused the refusal.
+ # Split by whether a FILE is involved, from the call that accounts for the turn's SIZE: ask-for-a-smaller-file
+ # cannot shrink a `python` or MCP payload.
_dominant = None
_dominant_size = -1
for call in message.get("tool_calls") or []:
@@ -890,15 +649,8 @@ def _blamed_role(message: dict) -> str:
def _blamed_role_for_turn(messages: list[dict]) -> str:
- """Who to blame for the newest turn, which is not always the newest MESSAGE.
-
- On the strict templates an assistant `tool_calls` block renders only once a `tool`
- message answers it, so the marginal cost of that tool message is the reply PLUS the
- call's arguments, which were invisible until now. Classifying the reply alone reports
- an overflow caused by a large `python`, MCP or `edit_file` payload as a large tool
- result, and the advice -- ask for a smaller slice of the file or page -- cannot shrink
- the thing that actually overflowed.
- """
+ """Blame the newest TURN, not the newest message: a `tool_calls` block renders only once
+ answered, so the reply's marginal cost includes the call's arguments."""
if not messages:
return ""
latest = messages[-1]
@@ -908,8 +660,7 @@ def _blamed_role_for_turn(messages: list[dict]) -> str:
for message in reversed(messages[:-1]):
role = str(message.get("role") or "")
if role != "assistant":
- # Only the call immediately preceding this reply is paired with it; anything else between them means this
- # reply does not belong to a call at all.
+ # Anything between the call and this reply means the reply belongs to no call.
if role == "tool":
continue
break
@@ -920,9 +671,7 @@ def _blamed_role_for_turn(messages: list[dict]) -> str:
for call in message.get("tool_calls") or []
):
break
- # Only when the CALL is the bigger half. A dominant tool result still gets the tool advice, which is right and
- # is what the existing cases assert: the reply is the thing the user can ask for less of. Blaming the call
- # unconditionally reversed that and told them to shrink a payload that was not the problem.
+ # Only when the CALL is the bigger half: a dominant tool result still gets the tool advice.
_call_chars = sum(
len(str((call.get("function") or {}).get("arguments") or ""))
for call in message.get("tool_calls") or []
@@ -938,13 +687,8 @@ def _blamed_role_for_turn(messages: list[dict]) -> str:
def _latest_turn_count(
messages: list[dict], count_tokens: Callable[[list[dict]], int]
) -> tuple[int, bool]:
- """`(tokens, exact)` for the newest message, estimated if the template refuses it.
-
- A tool loop can reach the does-not-fit diagnosis with a tool result last, which strict
- templates reject on its own; letting that raise would abort the fit and tell the user
- nothing. An approximate number beats a diagnosis that never arrives -- but the caller
- has to know which it got, because only the counted one carries the prompt's floor.
- """
+ """Estimated when the template refuses a lone tool result. The caller must know which it got:
+ only the counted one carries the prompt's floor."""
if not messages:
return 0, False
try:
@@ -954,20 +698,9 @@ def _latest_turn_count(
def _shared_prompt_tokens(count_tokens: Callable[[list[dict]], int]) -> int:
- """What a rendered prompt costs before any message at all.
-
- The counter prices a whole PROMPT, not a bag of messages: the template's own wrapper
- and, on a request that advertises tools, the entire tool catalogue rendered into the
- system turn. So that constant sits inside every count the fit takes, including the
- one-message slice above -- on the GGUF tool loop the counters pass `safe_tools` to
- `count_chat_tokens`, which puts the schemas in the prompt it measures, and a couple
- of MCP servers is thousands of tokens of them.
-
- Measured on the empty prompt rather than estimated: this number is subtracted from
- the two counts that decide which part of the prompt gets named, and a subtraction
- that is only roughly right moves the blame instead of removing it. One extra count,
- taken only on the branch that has already decided to refuse the request.
- """
+ """What a rendered prompt costs before any message: the template wrapper plus the whole tool
+ catalogue, so it sits inside every count. Measured, not estimated, since it is subtracted
+ from the counts that decide the blame."""
try:
return max(0, int(count_tokens([])))
except Exception:
@@ -977,19 +710,9 @@ def _shared_prompt_tokens(count_tokens: Callable[[list[dict]], int]) -> int:
def _marginal_turn_count(
fitted: list[dict], count_tokens: Callable[[list[dict]], int], irreducible_tokens: int
) -> Optional[int]:
- """What the newest turn ADDED to the prompt that was actually measured.
-
- The one-message slice is unusable when the template renders the newest message as
- nothing on its own, but the difference against the same prompt WITHOUT it is a real
- tokenizer count of exactly the turn's contribution, with the floor cancelled on both
- sides of the subtraction. So the diagnosis keeps a counted turn where it used to fall
- back to a guess.
-
- `irreducible_tokens` must be the count of `fitted` itself, which is what both callers
- pass. One extra count, on a branch that has already decided to refuse the request,
- next to the one `_shared_prompt_tokens` takes there. None when the counter cannot
- price the prefix, which is the caller's cue to fall back to the estimate.
- """
+ """What the newest turn ADDED, by difference against the same prompt without it, so the floor
+ cancels. `irreducible_tokens` must be the count of `fitted`. None when the prefix cannot be
+ priced."""
try:
return int(irreducible_tokens) - int(count_tokens(list(fitted)[:-1]))
except Exception:
@@ -1003,26 +726,16 @@ def turn_diagnosis(
irreducible_tokens: int,
fitted: Optional[list[dict]] = None,
) -> dict[str, Any]:
- """The fields that say WHICH part of a refused prompt is which.
-
- `shared_prompt_tokens` is the floor both `latest_turn_tokens` and
- `irreducible_tokens` carry, so a consumer comparing the two can take it off both
- sides and compare what the turn actually contributed against what the rest of the
- conversation did. Zero when the turn was estimated rather than counted: that estimate
- prices the message's own JSON and no catalogue, so it has no floor to remove.
-
- `latest_turn_exact` says which of the two `latest_turn_tokens` is. It is False only
- on the fallback below, where nothing could be counted at all, and a consumer must
- then not compare it against `irreducible_tokens`: that number is a tokenizer count of
- the rendered prompt while the estimate is four characters to a token over the
- message's JSON, and the two do not share units. Measured on the bundled gemma-4
- template with a real Gemma tokenizer, 16,400 characters of newlines estimate 8,207
- tokens against 557 rendered, 14.8x, which is enough for the estimate alone to clear
- the dominance ratio against a prompt the turn is 6% of.
-
- `fitted` is the message list `irreducible_tokens` was counted over. Given it, a turn
- the template refuses to render alone is still priced by difference rather than
- guessed.
+ """Which part of a refused prompt is which.
+
+ `shared_prompt_tokens` is the floor both other counts carry; zero when the turn was estimated,
+ since that estimate has no catalogue.
+
+ `latest_turn_exact` False means the two do not share units and must not be compared: 16,400
+ characters of newlines estimate 8,207 tokens against 557 rendered.
+
+ `fitted` is the list `irreducible_tokens` was counted over, so an unrenderable turn is priced by
+ difference.
"""
if not messages:
return {
@@ -1034,47 +747,34 @@ def turn_diagnosis(
latest, exact = _latest_turn_count(messages, count_tokens)
shared = _shared_prompt_tokens(count_tokens) if exact else 0
if exact and latest <= shared:
- # Counted, and yet no bigger than the empty prompt: the template rendered the turn as nothing. Both bundled
- # Gemma-4 templates do exactly that to a `role: tool` message on its own -- `{%- if message['role'] != 'tool'
- # -%}` skips it, and the result is emitted only while scanning forward from the assistant tool call that asked
- # for it, which a one-message slice does not contain. So the number is the floor and nothing else, and
- # subtracting the floor from it would leave the turn contributing ~0 and blame the conversation. Price it by
- # DIFFERENCE against the prompt that was measured instead: the slice is unrenderable, the contribution is not.
- # Reported floor-inclusive, so the consumer's existing subtraction of `shared` leaves exactly the marginal and
- # the ratio still compares two tokenizer counts.
+ # Counted, yet no bigger than the empty prompt: the template rendered the turn as nothing (Gemma-4 skips a
+ # lone `role: tool` message). Price by DIFFERENCE, reported floor-inclusive so the consumer's subtraction
+ # still leaves the marginal.
marginal = _marginal_turn_count(
fitted if fitted is not None else messages, count_tokens, irreducible_tokens
)
if marginal is not None and marginal > 0:
latest = marginal + shared
else:
- # nothing countable left: price the message's own JSON
- # Nothing countable left: same remedy as a template that refuses the slice outright -- price the message's
- # own JSON, and record no floor, because that estimate does not carry one.
+ # Nothing countable left: price the message's own JSON, and record no floor, because that estimate carries
+ # none.
latest = int(estimate_messages_tokens(messages[-1:]))
shared = 0
- # What is REPORTED is now the estimate, and that is what the flag describes. Leaving it True would be the
- # worse half of the bug.
+ # What is REPORTED is now the estimate, and that is what the flag describes.
exact = False
# Never all of either side: a floor at or above them would leave no ratio to compare.
shared = max(0, min(shared, latest - 1, int(irreducible_tokens) - 1))
return {
"latest_turn_tokens": latest,
- # Whose message it is: often a tool result the user cannot shorten.
"latest_turn_role": _blamed_role_for_turn(messages),
"shared_prompt_tokens": shared,
- # Whether the number above is a token count or a four-characters-a-token guess.
"latest_turn_exact": bool(exact),
}
def clamp_compaction_headroom_ratio(value: Any) -> Optional[float]:
- """Return a usable extra-trim ratio, or None when the caller left it unset.
-
- ``ROLLING_COMPACTION_HEADROOM_RATIO`` already clamps the process default to
- ``[0, 0.9]``. Per-request overrides go through the same gate so a UI slider
- cannot ask the fitter to drop the entire prompt or to grow it.
- """
+ """Overrides pass the same ``[0, 0.9]`` clamp as the process default, so a UI slider cannot ask
+ the fitter to drop the whole prompt."""
if value is None:
return None
try:
@@ -1099,24 +799,13 @@ def fit_rolling_context(
headroom_ratio: Optional[float] = None,
estimate_message: Callable[[dict], int] = estimate_message_tokens,
) -> tuple[list[dict], Optional[dict[str, Any]]]:
- """Fit a chat into its real context by dropping oldest complete turns.
-
- The exact tokenizer/template count decides whether trimming is needed; the cheap
- estimator only picks candidate turns. The current turn is never clipped, so an
- irreducibly large request still reaches llama-server's context-length error.
-
- ``reserve_tokens`` leaves room for what the caller adds back after fitting (recalled
- turns). It deliberately does not affect whether to trim at all, so a chat that fits
- today is never evicted just because the reserve would not fit alongside it.
-
- ``sticky_dropped`` is the boundary this thread last compacted to, in messages,
- re-applied before anything else and moved only if what is left still does not fit.
- Without it the fit is stateless (the client re-sends the whole transcript each turn)
- so the boundary slides every reply; with it plus ``_COMPACTION_HEADROOM_RATIO`` of
- slack, compaction is an occasional event the prefix cache can survive.
+ """Fit a chat into its context by dropping oldest complete turns; the current turn is never
+ clipped.
- Acceptance is still checked against the untightened ``prompt_target``: falling short
- of the headroom is not a failure to fit.
+ ``reserve_tokens`` leaves room for what the caller adds back and deliberately does not affect
+ whether to trim at all. ``sticky_dropped`` re-applies the boundary this thread last compacted
+ to, without which the stateless fit slides it every reply. Acceptance uses the untightened
+ ``prompt_target``.
"""
if context_length <= 1:
return messages, None
@@ -1127,9 +816,8 @@ def fit_rolling_context(
current_tokens = initial_tokens
dropped_total = 0
- # Phase one: put the boundary back where this thread already had it, so a compacted thread stops compacting further
- # every turn. Gated on the prompt not already fitting: a saved boundary describes the branch it was measured on, and
- # after a rollback it would evict most of a chat that comfortably fits.
+ # Phase one, gated on the prompt not already fitting: a saved boundary describes the branch it was measured on,
+ # and after a rollback would evict a chat that fits.
if sticky_dropped > 0 and initial_tokens > prompt_target:
candidate, dropped = truncate_oldest_messages(
fitted,
@@ -1143,20 +831,13 @@ def fit_rolling_context(
dropped_total = dropped
current_tokens = count_tokens(fitted)
- # Phase two, only if what is left still does not fit: move the boundary, taking a chunk out rather than skimming to
- # the brim so it can stay put for a while.
+ # Phase two: take a chunk out rather than skimming to the brim, so the boundary can stay put.
trim_target = prompt_target
- # The 5% floor on each eviction bite, given up only by a caller that asked for no extra trim. Keyed on the ratio and
- # not on `headroom`, which `keeps_boundary = False` zeroes for every threadless and incognito request, none of which
- # chose anything.
+ # Keyed on the ratio, not `headroom`, which is zeroed for threadless and incognito requests that chose nothing.
min_bite = True
if current_tokens > prompt_target:
- # Summed, not max()'d: the reserve is spent immediately on recalled passages, so counting it as headroom would
- # hand back room that is already taken. And only for a caller that can put the boundary back next request. The
- # headroom buys quiet turns between compactions by cutting deeper than needed, which is a bargain only if the
- # deeper cut is remembered. An incognito chat, an API request with no persisted thread, or a request whose turns
- # are not saved gets neither the boundary nor a recall of what went, so there it is 25% less history than plain
- # eviction would have kept.
+ # Summed, not max()'d: the reserve is spent at once on recalled passages. Only for callers that can restore
+ # the boundary, since a deeper cut pays only if remembered.
ratio = clamp_compaction_headroom_ratio(headroom_ratio)
if ratio is None:
ratio = _COMPACTION_HEADROOM_RATIO
@@ -1181,10 +862,8 @@ def fit_rolling_context(
current_tokens = count_tokens(fitted)
if current_tokens > prompt_target:
- # Missing the prompt target only loses reserved reply room, so keep the original if it fits the physical window,
- # else an eviction that does. Strictly under on both sides: llama-server refuses at `n_ctx` exactly. But not
- # under by one token, which would lose the history AND answer in one token, worse than the refusal it replaces.
- # Capped by the reserve, so the floor demands no room the target did not.
+ # Strictly under on both sides (llama-server refuses at `n_ctx` exactly), but not under by one token, which
+ # loses the history AND the answer.
reply_floor = min(
max(1, context_length // _RESCUE_REPLY_FLOOR_DIVISOR),
context_length - prompt_target,
@@ -1199,8 +878,8 @@ def fit_rolling_context(
"dropped_messages": dropped_total if rescued else 0,
"prompt_tokens_before": initial_tokens,
"prompt_tokens_after": current_tokens if rescued else initial_tokens,
- # Floor for the conversation, and how much of it is the message just sent: together they say whether the
- # chat or the single message is the problem.
+ # Floor for the conversation and the share of it just sent: together they say whether the chat or the
+ # message is the problem.
"irreducible_tokens": current_tokens,
# `fitted` is what `current_tokens` prices, so the turn can be counted by difference rather than estimated
**turn_diagnosis(
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 43ca1cb6e40..56cebbe2987 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -3,17 +3,16 @@
"""Local diffusion (text-to-image) backend.
-A torch-only singleton that loads one of three "kinds" (see ``resolve_model_kind``):
-a single-file GGUF transformer dequantised on-device via ``GGUFQuantizationConfig``,
-a single-file safetensors transformer (e.g. fp8), or a full diffusers pipeline via
-``from_pretrained`` (which re-applies an embedded quant config such as bnb-4bit). The
-single-file kinds pull the rest of the pipeline (VAE, text encoders, scheduler) from
-the matching base repo; the pipeline kind pulls everything from the repo itself.
-Non-GGUF kinds are gated to the ``unsloth/*`` org (or a local path) for safety.
-
-torch/diffusers are imported lazily so this stays importable in a no-torch runtime.
-``begin_load`` runs on a background thread; poll ``load_progress`` for the download
-bar. GPU-handoff policy lives in the arbiter the routes call, not here.
+A torch-only singleton that loads one of three kinds (see ``resolve_model_kind``): a single-file
+GGUF transformer dequantised on-device via ``GGUFQuantizationConfig``, a single-file safetensors
+transformer (e.g. fp8), or a full diffusers pipeline via ``from_pretrained`` (which re-applies an
+embedded quant config such as bnb-4bit). The single-file kinds pull the rest of the pipeline (VAE,
+text encoders, scheduler) from the matching base repo; the pipeline kind pulls everything from the
+repo itself. Non-GGUF kinds are gated to the ``unsloth/*`` org (or a local path) for safety.
+
+torch/diffusers are imported lazily so this stays importable in a no-torch runtime. ``begin_load``
+runs on a background thread; poll ``load_progress`` for the download bar. GPU-handoff policy lives
+in the arbiter the routes call, not here.
"""
from __future__ import annotations
@@ -191,8 +190,8 @@ from utils.paths.path_utils import (
logger = get_logger(__name__)
-# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent distributed backend:
-# diffusers imports xformers on sight, its quantizers torchao.
+# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent distributed
+# backend: diffusers imports xformers on sight, its quantizers torchao.
install_xformers_windows_rocm_stub()
install_torchao_windows_rocm_stub()
install_torchao_int_mm_patch()
@@ -210,11 +209,10 @@ def _record_revision(out: Optional[dict[str, str]], repo_id: str, info: Any) ->
def hub_cache_dir() -> str:
- """The cache root every loader call must be pinned to.
-
- diffusers resolves an unset cache_dir through huggingface_hub's import-time constant,
- which a mid-session cache-folder change does not update. The prefetch reads the live
- setting, so without this a single load could split across two roots."""
+ """The cache root every loader call must be pinned to. diffusers resolves an unset cache_dir
+ through huggingface_hub's import-time constant, which a mid-session cache-folder change does
+ not update. The prefetch reads the live setting, so without this a single load could split
+ across two roots."""
from utils.hf_cache_settings import active_hf_hub_cache
return active_hf_hub_cache()
@@ -228,23 +226,24 @@ _HUB_REPO_RE = re.compile(
def _gated_in_chain(exc: BaseException) -> Optional[BaseException]:
- """The GatedRepoError in ``exc``'s cause/context chain, or None. Transformers loads re-raise
- the 403 wrapped in an OSError, so the outermost error alone misses the case this exists for.
+ """The GatedRepoError in ``exc``'s cause/context chain, or None. Transformers loads re-raise the
+ 403 wrapped in an OSError, so the outermost error alone misses the case this exists for.
Screened by class name across the MRO, so no hub import."""
seen: set[int] = set()
while exc is not None and id(exc) not in seen:
seen.add(id(exc))
if any(cls.__name__ == "GatedRepoError" for cls in type(exc).__mro__):
return exc
- # `raise ... from None` means the raiser already wrote a better message (the base-repo preflight does), so stop.
+ # `raise ... from None` means the raiser already wrote a better message (the base-repo preflight does), so
+ # stop.
exc = exc.__cause__ or (None if exc.__suppress_context__ else exc.__context__)
return None
def _hf_token_in_play(hf_token: Optional[str]) -> bool:
"""Whether the failing Hub call carried ANY credential, not just Unsloth's own: with token=None
- huggingface_hub still falls back to HF_TOKEN or the cached CLI login, so keying off the request
- token alone loops an already-authenticated user."""
+ huggingface_hub still falls back to HF_TOKEN or the cached CLI login, so keying off the
+ request token alone loops an already-authenticated user."""
if hf_token:
return True
try:
@@ -258,8 +257,8 @@ def _hf_token_in_play(hf_token: Optional[str]) -> bool:
def hub_access_message(exc: BaseException, *, had_token: bool) -> Optional[str]:
"""Rewrite a gated-repo failure into the step that actually unblocks the user, else None so an
- unrelated load error keeps its own text. Only the toast is affected; the raw exception, request
- id and resolve URL still reach the log."""
+ unrelated load error keeps its own text. Only the toast is affected; the raw exception,
+ request id and resolve URL still reach the log."""
gated = _gated_in_chain(exc)
if gated is None:
return None
@@ -279,12 +278,11 @@ def hub_access_message(exc: BaseException, *, had_token: bool) -> Optional[str]:
def resolve_model_kind(gguf_filename: Optional[str], model_kind: Optional[str] = None) -> str:
- """Classify a load request into one of ``_MODEL_KINDS``.
-
- An explicit ``model_kind`` wins (validated). Otherwise the kind is inferred from
- the single-file name: a ``.gguf`` name is ``"gguf"``, any other single-file name is
- ``"single_file"``, and the absence of a name is a full ``"pipeline"`` load. Pure and
- network-free, so the route, validation, and load paths all agree on the kind."""
+ """Classify a load request into one of ``_MODEL_KINDS``. An explicit ``model_kind`` wins
+ (validated). Otherwise the kind is inferred from the single-file name: a ``.gguf`` name is
+ ``"gguf"``, any other single-file name is ``"single_file"``, and the absence of a name is a
+ full ``"pipeline"`` load. Pure and network-free, so the route, validation, and load paths all
+ agree on the kind."""
if model_kind:
kind = model_kind.strip().lower()
if kind not in _MODEL_KINDS:
@@ -302,11 +300,9 @@ def resolve_model_kind(gguf_filename: Optional[str], model_kind: Optional[str] =
def _active_lora_pairs(pipe: Any) -> list:
"""``[(name, weight)]`` for the adapters actually attached to ``pipe``, zero-weight ones
- dropped.
-
- Reads the ``_unsloth_loras`` marker, which the LoRA paths write as ``(name, path, weight)``.
- Shape is tolerated rather than assumed: this runs inside the generate result and an unpacking
- error here would sink a finished generation whose images are already in hand."""
+ dropped. Reads the ``_unsloth_loras`` marker, which the LoRA paths write as ``(name, path,
+ weight)``. Shape is tolerated rather than assumed: this runs inside the generate result and
+ an unpacking error here would sink a finished generation whose images are already in hand."""
pairs = []
for entry in getattr(pipe, "_unsloth_loras", ()) or ():
try:
@@ -329,14 +325,14 @@ def _baked_lora_names(pipe: Any) -> list:
A torchao load attaches its adapters before ``quantize_`` + compile, so they are part of the
BUILD, not of any one generation: peft rewraps each targeted Linear as ``lora.Linear`` and the
- quantiser then converts ``base_layer`` while the ``lora_`` side path stays high precision (see
- ``diffusion_transformer_quant``). Disabling them at generate time sets their scale to 0, which
- is not the same pipeline as one built without them -- so the recipe has to record the bake to
- describe the build that made the image. ``_active_lora_pairs`` deliberately drops the
- zero-weight entries, which is why the applied set cannot carry this.
-
- Shape is tolerated rather than assumed, for the same reason as ``_active_lora_pairs``: this
- runs inside the generate result and must never sink a finished generation."""
+ quantiser then converts ``base_layer`` while the ``lora_`` side path stays high precision.
+ Disabling them at generate time sets their scale to 0, which is not the same pipeline as one
+ built without them, so the recipe has to record the bake. ``_active_lora_pairs`` deliberately
+ drops the zero-weight entries, which is why the applied set cannot carry this.
+
+ Shape is tolerated rather than assumed: this runs inside the generate result and must never sink
+ a finished generation.
+ """
if not getattr(pipe, "_unsloth_loras_baked", False):
return []
names = []
@@ -356,12 +352,12 @@ def resolve_local_single_file(model_path: str) -> Optional[str]:
None.
The On-Device scanner advertises a bare single-file safetensors directory as a text-to-image
- model (it matches a known family by name), but the local picker starts it as a ``pipeline``
- with no filename, so a pipeline load 400s on the missing ``model_index.json`` and the
- advertised model is unusable. The images load route uses this to reinterpret such a pick as a
- ``single_file`` load of the sole checkpoint. A real pipeline dir (has ``model_index.json``) or
- an ambiguous one (0 or more than 1 ``.safetensors``, e.g. a sharded pipeline) returns None and
- loads unchanged. A PEFT LoRA adapter folder is also skipped (see below). Never raises."""
+ model, but the local picker starts it as a ``pipeline`` with no filename, so a pipeline load
+ 400s on the missing ``model_index.json``. The images load route uses this to reinterpret such a
+ pick as a ``single_file`` load of the sole checkpoint. A real pipeline dir, or an ambiguous one
+ (0 or more than 1 ``.safetensors``), returns None and loads unchanged. A PEFT LoRA adapter
+ folder is also skipped. Never raises.
+ """
try:
root = Path(model_path).expanduser()
if not root.is_dir() or (root / "model_index.json").is_file():
@@ -390,11 +386,10 @@ def decode_b64_image(
max_side: int = 4096,
max_pixels: Optional[int] = None,
) -> Any:
- """Decode a base64 (optionally ``data:`` URL) image string to a PIL image.
-
- The image-conditioned workflows (img2img / inpaint / edit) transport the input
- image and mask as base64 in the JSON request, so this is the single decode path.
- A mask is decoded as single-channel ``L``; the source image as ``RGB``."""
+ """Decode a base64 (optionally ``data:`` URL) image string to a PIL image. The image-conditioned
+ workflows (img2img / inpaint / edit) transport the input image and mask as base64 in the JSON
+ request, so this is the single decode path. A mask is decoded as single-channel ``L``; the
+ source image as ``RGB``."""
import base64
import binascii
import io
@@ -454,12 +449,11 @@ def decode_b64_image(
def _snap_to_multiple(img: Any, multiple: int = 16) -> Any:
- """Resize a PIL image so both sides are multiples of ``multiple`` (rounded to nearest,
- minimum one multiple), preserving content with a high-quality resample.
-
- Image-conditioned pipelines (Z-Image / Qwen / FLUX: 8x VAE downsample + 2x patch) reject
- sizes that are not divisible by 16. Rather than error on an odd-sized upload, snap it so
- the workflow just works; rounding to nearest keeps the rescale minimal/accurate."""
+ """Resize a PIL image so both sides are multiples of ``multiple`` (rounded to nearest, minimum
+ one multiple), preserving content with a high-quality resample. Image-conditioned pipelines
+ (Z-Image / Qwen / FLUX: 8x VAE downsample + 2x patch) reject sizes that are not divisible by
+ 16. Rather than error on an odd-sized upload, snap it; rounding to nearest keeps the rescale
+ minimal."""
from PIL import Image
w, h = img.size
@@ -471,14 +465,12 @@ def _snap_to_multiple(img: Any, multiple: int = 16) -> Any:
def _clamp_max_side(img: Any, max_side: int) -> Any:
- """Downscale a PIL image so its longest side is <= ``max_side``, preserving aspect ratio
- (high-quality resample); a no-op when it already fits.
-
- img2img / inpaint take their OUTPUT size from the uploaded image, so without a bound an
- oversized upload (up to the 4096/side decode cap -- 4x the txt2img 2048 ceiling, ~16x the
- area) drives a proportionally larger latent and O(n^2) attention that OOMs the transformer/
- VAE on a normal card, surfacing only as an opaque 500. Clamping the longest side to the same
- 2048 ceiling txt2img enforces (and upscale caps to) keeps these workflows bounded."""
+ """Downscale a PIL image so its longest side is <= ``max_side``, preserving aspect ratio; a
+ no-op when it already fits. img2img / inpaint take their OUTPUT size from the uploaded image,
+ so without a bound an oversized upload drives a proportionally larger latent and O(n^2)
+ attention that OOMs the transformer/VAE on a normal card, surfacing only as an opaque 500.
+ Clamping the longest side to the same 2048 ceiling txt2img enforces keeps these workflows
+ bounded."""
from PIL import Image
w, h = img.size
@@ -492,13 +484,11 @@ def _clamp_max_side(img: Any, max_side: int) -> Any:
def _fit_within(img: Any, max_w: int, max_h: int) -> Any:
- """Downscale a PIL image to fit inside a ``max_w`` x ``max_h`` box, preserving aspect ratio;
- a no-op when it already fits. NEVER enlarges -- growing a source is the Upscale workflow.
-
- img2img takes its output size from the upload, which left the Resolution control inert for
- Transform: a 4000px photo generated at the 2048 clamp and the refusal it raised named a size
- the sliders could not change. Bounding the upload by the requested box makes that control
- mean what it says."""
+ """Downscale a PIL image to fit inside a ``max_w`` x ``max_h`` box, preserving aspect ratio; a
+ no-op when it already fits. NEVER enlarges: growing a source is the Upscale workflow. img2img
+ takes its output size from the upload, which left the Resolution control inert for Transform:
+ a 4000px photo generated at the 2048 clamp and the refusal it raised named a size the sliders
+ could not change."""
from PIL import Image
w, h = img.size
@@ -541,15 +531,12 @@ def _image_variant_hint(
repo_id: Optional[str],
base: Optional[str],
) -> str:
- """The free-text hint ``estimate_image_runtime_mib`` scans for distilled / turbo / edit
- markers, built from every identifier this load carries.
-
- Both ``repo_id`` AND ``base`` go in. Picking one (``repo_id or base``) dropped the base
- whenever a repo id existed, which is every GGUF load, and the base is precisely where the
- marker usually lives: ``unsloth/Z-Image-GGUF`` says nothing while its base
- ``Tongyi-MAI/Z-Image-Turbo`` says turbo, so the 0.85 distilled discount never fired for the
- models most likely to be running on a card that needs it. Deduplicated (a pipeline load passes
- the same id as both) and order-stable, so the hint is a pure function of the load."""
+ """The free-text hint ``estimate_image_runtime_mib`` scans for distilled / turbo / edit markers,
+ built from every identifier this load carries. Both ``repo_id`` AND ``base`` go in: picking
+ one dropped the base whenever a repo id existed, which is every GGUF load, and the base is
+ precisely where the marker usually lives, so the 0.85 distilled discount never fired for the
+ models most likely to be running on a card that needs it. Deduplicated and order-stable, so
+ the hint is a pure function of the load."""
parts: list[str] = []
for part in (family_name, single_file_name, repo_id, base):
text = (part or "").strip()
@@ -559,15 +546,12 @@ def _image_variant_hint(
def _compile_shape_dims(workflow: str, init_pil: Any, width: int, height: int) -> tuple[int, int]:
- """The (width, height) a generation's forward ACTUALLY runs at, for static
- compile-cache shape registration.
-
- txt2img / reference / controlnet generate at the requested slider size, but the
- image-conditioned workflows (img2img / inpaint / upscale / edit) derive the output
- from the (resized/snapped) input image -- registering the slider values there would
- mark a shape covered that was never compiled, so the truly-used shape never
- re-dirties the bundle and warm restarts keep paying its compile. Mirrors the
- width/height kwarg derivation in generate()."""
+ """The (width, height) a generation's forward ACTUALLY runs at, for static compile-cache shape
+ registration. txt2img / reference / controlnet generate at the requested slider size, but the
+ image-conditioned workflows derive the output from the (resized/snapped) input image:
+ registering the slider values there would mark a shape covered that was never compiled, so
+ the truly-used shape never re-dirties the bundle and warm restarts keep paying its compile.
+ Mirrors the width/height kwarg derivation in generate()."""
if workflow in ("txt2img", "reference", "controlnet") or init_pil is None:
return int(width), int(height)
iw, ih = init_pil.size
@@ -589,10 +573,9 @@ _TRUSTED_NON_GGUF_REPOS = frozenset(
# FLUX.2 LoRA training bases (dev gated, klein-4B open); reloaded as a pipeline by "Deploy to Create".
"black-forest-labs/flux.2-dev",
"black-forest-labs/flux.2-klein-4b",
- # The other klein sizes and variants. One family covers both sizes and defaults to 4B, on the understanding that
- # the real base comes from the base_model card tag. Leaving these out made that tag untrusted, so a klein-9B
- # GGUF silently resolved to the 4B config and died in the GGUF quantizer with a bare shape mismatch (24576x4096
- # vs 18432x3072).
+ # The other klein sizes and variants. One family covers both sizes and defaults to 4B, on the understanding
+ # that the real base comes from the base_model card tag. Leaving these out made that tag untrusted, so a
+ # klein-9B GGUF silently resolved to the 4B config and died in the GGUF quantizer with a bare shape mismatch.
"black-forest-labs/flux.2-klein-9b",
"black-forest-labs/flux.2-klein-base-4b",
"black-forest-labs/flux.2-klein-base-9b",
@@ -627,18 +610,16 @@ _TRUSTED_NON_GGUF_REPOS = frozenset(
def _is_trusted_diffusion_repo(repo_id: str) -> bool:
"""Whether a NON-GGUF load is allowed for ``repo_id``.
- Making ``gguf_filename`` optional opens a ``from_pretrained`` / ``from_single_file``
- on an arbitrary repo, which fetches and deserialises third-party weights. So the
- non-GGUF paths are gated to the ``unsloth/*`` org (the curated safetensors models),
- a short allowlist of official safetensors-only base repos (``_TRUSTED_NON_GGUF_REPOS``,
- e.g. the SDXL base), and local paths the user explicitly pointed at (already on their
- disk). The GGUF path is unchanged and stays open to any repo, as before.
-
- A bare ``owner/name`` HF id is never a real filesystem path, and an id with invalid
- characters makes ``Path.exists()`` raise OSError; treat any such failure as "not a
- local path" so the trust decision falls through to the org/allowlist checks (the
- loader's validate_load_request raises the clear FileNotFoundError for a genuinely
- missing local pick)."""
+ Making ``gguf_filename`` optional opens a ``from_pretrained`` / ``from_single_file`` on an
+ arbitrary repo, which fetches and deserialises third-party weights. So the non-GGUF paths are
+ gated to the ``unsloth/*`` org, a short allowlist of official safetensors-only base repos
+ (``_TRUSTED_NON_GGUF_REPOS``), and local paths the user explicitly pointed at. The GGUF path
+ stays open to any repo.
+
+ A bare ``owner/name`` HF id is never a real filesystem path, and an id with invalid characters
+ makes ``Path.exists()`` raise OSError; treat any such failure as not a local path so the trust
+ decision falls through to the org/allowlist checks.
+ """
try:
if Path(repo_id).expanduser().exists():
return True
@@ -652,19 +633,16 @@ def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = Fals
"""A companion ``base_repo`` fed to ``from_pretrained(base)`` (or ``config=base``) must be a
diffusers PIPELINE directory (has ``model_index.json``). ``_is_trusted_diffusion_repo`` accepts
ANY existing local path, so without this a local base that is not a pipeline dir would pass the
- preflight, let the route evict the resident GPU model, then fail deep in the background load --
- the eviction this validation exists to prevent. A non-existent local base is already rejected
- by the trust check (it is neither an existing path nor an unsloth/*/allowlisted repo); a bare
- remote id is left for the loader to resolve. Shared by the image, video, and training preflights
- so their local-base shape check stays in sync. Never evicts; raises ValueError on a bad local
- base.
+ preflight, let the route evict the resident GPU model, then fail deep in the background load:
+ the eviction this validation exists to prevent. A non-existent local base is already rejected by
+ the trust check; a bare remote id is left for the loader to resolve. Shared by the image, video,
+ and training preflights. Never evicts; raises ValueError on a bad local base.
``allow_modular`` accepts ``modular_model_index.json`` as well, for a caller whose loader is
``ModularPipeline.from_pretrained``: that IS the valid on-disk layout for a Modular Diffusers
- pipeline (MiniMax-H3 ships no ``model_index.json`` at all), and the local-model scanners
- already count either index. Off by default -- a conventional ``DiffusionPipeline`` load still
- needs the conventional index, and accepting a modular directory there would only move the
- failure back into the loader."""
+ pipeline (MiniMax-H3 ships no ``model_index.json`` at all). Off by default: a conventional
+ ``DiffusionPipeline`` load still needs the conventional index.
+ """
base = (base_repo or "").strip()
if not base:
return
@@ -686,8 +664,8 @@ def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = Fals
def _repo_access_message(repo: str, *, gated: bool) -> str:
- """The repo id AND its licence page: the worker's 401/403 names neither, and the base comes from a
- card tag, so the user never saw which repo it is."""
+ """The repo id AND its licence page: the worker's 401/403 names neither, and the base comes from
+ a card tag, so the user never saw which repo it is."""
url = f"https://huggingface.co/{repo}"
if gated:
return (
@@ -712,22 +690,19 @@ def _assert_base_repo_accessible(
"""Fail up front, with the licence URL, when a companion base cannot be read.
The Hub gates the BYTE endpoint only, so ``model_info`` answers anonymously for gated repos and
- a plan built from it dies mid-download on a bare token error. Probes ``probe_file`` (fetched by
- the load anyway) only when ``gated`` is set, so an open repo costs one metadata call; the native
- plan passes its own asset name, as a repo it reads only for a VAE has no manifest cached. Fails
- open on any non-access error: offline/transient must not block a load.
+ a plan built from it dies mid-download on a bare token error. Probes ``probe_file`` only when
+ ``gated`` is set, so an open repo costs one metadata call; the native plan passes its own asset
+ name. Fails open on any non-access error: offline/transient must not block a load.
Returns the base's snapshot dir when an ACCESS verdict was excused by a copy living only under
huggingface_hub's import-time root, so the caller can load off disk: ``from_pretrained`` is
- pinned to ``hub_cache_dir()`` and cannot see it, and the failure that earned the escape also
- empties the size estimate. None otherwise.
-
- Under ``local_files_only`` the Hub half stands down and only the cache probe runs. This whole
- function exists to name the repo whose BYTES a download is about to fail on; a load that is
- forbidden to download has no such fetch to pre-empt, so the verdict it would compute is about a
- request that will never be made. The one thing worth keeping is the other-root escape, which is
- a pure cache read, and it is exactly what lets a base staged under huggingface_hub's
- import-time root still load off disk."""
+ pinned to ``hub_cache_dir()`` and cannot see it. None otherwise.
+
+ Under ``local_files_only`` the Hub half stands down and only the cache probe runs: this function
+ exists to name the repo whose BYTES a download is about to fail on, and a load forbidden to
+ download has no such fetch to pre-empt. The other-root escape is a pure cache read and is what
+ lets a base staged under the import-time root still load off disk.
+ """
repo = (base_repo or "").strip()
# Only a remote 'org/name' can be gated; a local base is already on disk.
if not repo or repo.count("/") != 1:
@@ -739,8 +714,8 @@ def _assert_base_repo_accessible(
if Path(repo).expanduser().exists():
return None
# OSError: invalid path characters -> a remote id. RuntimeError: pathlib raises it, not OSError, when expanduser()
- # cannot resolve the home dir ('~other/models', or '~/models' with no HOME). Both carry one slash, so they reach
- # here, and an escape would 500 this fail-open probe.
+ # cannot resolve the home dir. Both carry one slash, so they reach here, and an escape would 500 this fail-open
+ # probe.
except (OSError, RuntimeError, ValueError):
pass
try:
@@ -757,15 +732,14 @@ def _assert_base_repo_accessible(
other_root_snapshot: Optional[str] = None
# A base already on disk needs no Hub access: hf_hub_download catches the gated/401 HEAD and serves the cached
- # pointer (file_download._get_metadata_or_catch_error), which is how a downloaded gated base still loads once the
- # token is cleared or expires. Excuses an ACCESS verdict only, never a 404: a renamed or removed repo cannot be
- # un-renamed by a stale copy.
+ # pointer, which is how a downloaded gated base still loads once the token is cleared or expires. Excuses an
+ # ACCESS verdict only, never a 404: a renamed or removed repo cannot be un-renamed by a stale copy.
def _already_downloaded() -> bool:
"""True when ``probe_file`` is on disk under EITHER root (Unsloth pins its live setting, the
- prefetch writes under huggingface_hub's import-time constant). Never raises. Exact for the
- native plan, which probes an asset it stages; a proxy for the diffusers plan, which probes
- the manifest, so a manifest-cached base with missing shards still dies mid-download on the
- bare token error -- the pre-preflight behaviour, never a blocked load."""
+ prefetch writes under huggingface_hub's import-time constant). Never raises. Exact for
+ the native plan, which probes an asset it stages; a proxy for the diffusers plan, which
+ probes the manifest, so a manifest-cached base with missing shards still dies
+ mid-download on the bare token error."""
nonlocal other_root_snapshot
try:
from huggingface_hub import try_to_load_from_cache
@@ -784,17 +758,17 @@ def _assert_base_repo_accessible(
if local_files_only:
# Cache read only: no model_info, no metadata HEAD. ``_already_downloaded`` is called for its side effect (it
- # sets ``other_root_snapshot``), and its bool is dropped -- a miss here is not a refusal. The loader is the one
- # that raises for a file that is not on disk, with the file's own name in it, which is a better answer than this
- # probe's "add a token" text for a load that was never going to fetch anything.
+ # sets ``other_root_snapshot``), and its bool is dropped: a miss here is not a refusal. The loader is the one
+ # that raises for a file that is not on disk, with the file's own name in it.
_already_downloaded()
return other_root_snapshot
def _is_auth_error(exc: Any) -> bool:
"""A 401/403 that hf_raise_for_status did not classify: an expired token 401s "Invalid
- credentials in Authorization header", which _http.py excludes from its RepoNotFound branch
- by name, and a token missing a permission 403s. Both arrive as plain HfHubHTTPError, so
- catching only the classified errors fails open on the very case this probe exists to catch."""
+ credentials in Authorization header", which _http.py excludes from its RepoNotFound
+ branch by name, and a token missing a permission 403s. Both arrive as plain
+ HfHubHTTPError, so catching only the classified errors fails open on the very case this
+ probe exists to catch."""
status = getattr(getattr(exc, "response", None), "status_code", None)
return status in (401, 403)
@@ -898,8 +872,7 @@ class _LoadState:
# the target and the reported build read gpu_ordinal, so the automatic path still resolves a bare device.
placed_ordinal: Optional[int] = None
# The exact variant hint the memory plan was built from (family + checkpoint name + repo ids). Stored rather than
- # rebuilt so generate()'s activation re-check budgets with the SAME distilled / edit multipliers the load did, and
- # the two can never drift apart.
+ # rebuilt so generate()'s activation re-check budgets with the SAME distilled / edit multipliers the load did.
variant_hint: str = ""
@@ -929,8 +902,8 @@ class _GenState:
def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float) -> Optional[float]:
- """Seconds remaining, from the average step time measured after the first step.
- None until at least one step has elapsed since the first."""
+ """Seconds remaining, from the average step time measured after the first step. None until at
+ least one step has elapsed since the first."""
steps_since_first = step - 1
if not first_step_at or steps_since_first <= 0:
return None
@@ -939,9 +912,9 @@ def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float)
def _resolve_diffusion_compute_dtype(fam: Optional[DiffusionFamily], dtype: Any) -> Any:
- """Promote float16 -> float32 for fp16-incompatible families (e.g. Z-Image),
- whose activations overflow float16's finite range and render a black image.
- Every other dtype/family passes through unchanged."""
+ """Promote float16 -> float32 for fp16-incompatible families (e.g. Z-Image), whose activations
+ overflow float16's finite range and render a black image. Every other dtype/family passes
+ through unchanged."""
if fam is None or not getattr(fam, "fp16_incompatible", False):
return dtype
import torch
@@ -950,19 +923,16 @@ def _resolve_diffusion_compute_dtype(fam: Optional[DiffusionFamily], dtype: Any)
def _install_gguf_prefix_strip(transformer_cls: Any, logger: Any) -> None:
- """Wrap the class's diffusers single-file converter to strip the
- ``model.diffusion_model.`` container prefix that sd.cpp-converted GGUFs
- carry on every tensor.
-
- diffusers (<= 0.39) handles the prefix inconsistently: the FLUX.1 converter
- strips it natively, but the FLUX.2 converter never does and KeyErrors on the
- prefixed keys (``'double_blocks.0.img_attn.norm.key_norm'`` misparse in
- ``convert_flux2_transformer_checkpoint_to_diffusers``), and the Qwen-Image
- mapping fn is an identity, so every prefixed tensor is reported "not used",
- the model stays on meta, and ``.to(cuda)`` dies with "Cannot copy out of
- meta tensor". Stripping the prefix when present is a no-op for already-clean
- checkpoints, so the shim applies to every GGUF transformer class uniformly.
- Idempotent (the wrapper is marked) and best-effort."""
+ """Wrap the class's diffusers single-file converter to strip the ``model.diffusion_model.``
+ container prefix that sd.cpp-converted GGUFs carry on every tensor.
+
+ diffusers (<= 0.39) handles the prefix inconsistently: the FLUX.1 converter strips it natively,
+ but the FLUX.2 converter never does and KeyErrors on the prefixed keys, and the Qwen-Image
+ mapping fn is an identity, so every prefixed tensor is reported not used, the model stays on
+ meta, and ``.to(cuda)`` dies with "Cannot copy out of meta tensor". Stripping the prefix when
+ present is a no-op for already-clean checkpoints, so the shim applies to every GGUF transformer
+ class uniformly. Idempotent (the wrapper is marked) and best-effort.
+ """
try:
from diffusers.loaders import single_file_model as sfm
@@ -991,12 +961,10 @@ def _install_gguf_prefix_strip(transformer_cls: Any, logger: Any) -> None:
@functools.lru_cache(maxsize = None)
def _no_recast_pipeline_class(pipe_cls: Any) -> Any:
- """``pipe_cls`` with the dtype half of ``.to()`` dropped; device moves still work.
-
- Pipelines built by ``from_pipe`` share the resident pipeline's module objects, so a
- dtype cast through one rewrites the loaded model (#9186). Cached because a ControlNet
- swap rebuilds its pipeline: one subclass per class, not a new type per build.
- """
+ """``pipe_cls`` with the dtype half of ``.to()`` dropped; device moves still work. Pipelines
+ built by ``from_pipe`` share the resident pipeline's module objects, so a dtype cast through
+ one rewrites the loaded model (#9186). Cached because a ControlNet swap rebuilds its
+ pipeline: one subclass per class, not a new type per build."""
def to(self, *args: Any, **kwargs: Any) -> Any:
import torch
@@ -1015,12 +983,11 @@ _NO_WEIGHT = object()
def _has_active_lora(loras: Any) -> bool:
- """True when any adapter would actually be baked, for either shape the callers pass.
-
- Weight 0 means disabled, but /images/load passes ``(id, weight)`` tuples while
- /images/download-plan passes ``LoraSpec`` models, whose unpacking yields ``(field, value)``
- pairs -- so ``(_lid, w)`` would bind ``w`` to ``("weight", 0.0)`` and read a disabled adapter
- as active. Reading the attribute first covers both."""
+ """True when any adapter would actually be baked, for either shape the callers pass. Weight 0
+ means disabled, but /images/load passes ``(id, weight)`` tuples while /images/download-plan
+ passes ``LoraSpec`` models, whose unpacking yields ``(field, value)`` pairs, so ``(_lid, w)``
+ would bind ``w`` to ``("weight", 0.0)`` and read a disabled adapter as active. Reading the
+ attribute first covers both."""
for entry in loras or ():
weight = getattr(entry, "weight", _NO_WEIGHT)
if weight is _NO_WEIGHT:
@@ -1046,7 +1013,6 @@ def _uncached_prequant_repo(
) -> Optional[str]:
"""The hosted pre-quant repo an AUTO-derived quant would have to DOWNLOAD for this pick, or None
when it costs no extra bytes (no hosted source, a local override, or already cached).
-
Otherwise an auto GGUF pick fetches the GGUF and then a second multi-GB denoiser it uses
instead. Shared by ``load_pipeline`` and ``_dense_quant_prefetch_needed`` so the load and the
download plan decline together. Cheap (a refs read + stat) and never raises."""
@@ -1077,25 +1043,18 @@ def _dense_transformer_cached(
"""Whether the dense ``transformer/`` shards this load would open are ALREADY on disk, so the
dense-quant fast path costs a GGUF pick no extra bytes.
- Two things have to line up for that to be true, and checking either alone is worse than not
- checking at all, because both failure modes end in the multi-gigabyte download this exists to
- prevent:
-
- * EVERY shard, not merely one. A cancelled pull leaves whatever finished behind, so a byte
- count above zero says a download STARTED, never that it completed.
- * The repo the prefetch will actually FETCH from. A gated base and its ungated mirror are two
- independently addressed caches; ``prefer_ungated_mirror`` picks between them from the full
- file list, so shards resident under the upstream id do not spare a fetch that resolves to
- the mirror.
+ Two things have to line up, and checking either alone is worse than not checking at all, because
+ both failure modes end in the multi-gigabyte download this exists to prevent: EVERY shard, not
+ merely one, since a cancelled pull leaves whatever finished behind; and the repo the prefetch
+ will actually FETCH from, since a gated base and its ungated mirror are two independently
+ addressed caches and ``prefer_ungated_mirror`` picks between them from the full file list.
``companion_files`` is the base-repo listing WITHOUT ``transformer/`` and ``transformer_files``
- is the rest, both from the Hub listing the plan is being built from. The mirror decision is
- taken over BOTH halves, because that is the set ``_predownload_base`` hands
- ``prefer_ungated_mirror``: the upstream only wins when it can satisfy the whole widened fetch,
- so companions cached upstream beside a dense transformer cached under the mirror pick the
- mirror here exactly as the fetch does. Judging on the companions alone kept the upstream and
- then found no shards under it, declining the fast path for weights already on disk. No listing
- means no evidence, and no evidence declines. Never raises."""
+ is the rest. The mirror decision is taken over BOTH halves, because that is the set
+ ``_predownload_base`` hands ``prefer_ungated_mirror``: judging on the companions alone kept the
+ upstream and then found no shards under it, declining the fast path for weights already on disk.
+ No listing means no evidence, and no evidence declines. Never raises.
+ """
base = (base_repo or "").strip()
if not base or not transformer_files:
return False
@@ -1110,12 +1069,11 @@ def _dense_transformer_cached(
def _local_base_transformer_present(base_repo: Optional[str]) -> bool:
"""Whether ``base_repo`` is a local diffusers directory whose ``transformer/`` weights are
- already on disk.
-
- A filesystem base has no Hub listing -- ``model_info`` raises on a path -- so the staged-file
- list comes back empty and every "did the plan stage transformer/?" test reads False. Nothing
- can be downloaded from a directory, so a complete one is staged by definition, and reading the
- empty list as a refusal would decline the fast path for weights the user already has."""
+ already on disk. A filesystem base has no Hub listing (``model_info`` raises on a path) so
+ the staged-file list comes back empty and every did-the-plan-stage-transformer test reads
+ False. Nothing can be downloaded from a directory, so a complete one is staged by definition,
+ and reading the empty list as a refusal would decline the fast path for weights the user
+ already has."""
base = (base_repo or "").strip()
if not base:
return False
@@ -1136,22 +1094,20 @@ def _dense_candidate_is_prequant(
base_repo: Optional[str],
prequant_path: Optional[str],
) -> bool:
- """Whether the dense-quant fast path would open a PRE-QUANT checkpoint rather than the base
- repo's own dense ``transformer/`` shards.
+ """Whether the dense-quant fast path would open a PRE-QUANT checkpoint rather than the base repo's
+ own dense ``transformer/`` shards.
``resolve_dense_quant_candidate`` is the one resolver that picks between the two, and it is the
same call ``_dense_quant_prefetch_needed`` and ``load_pipeline`` re-plan memory against, so
- asking it here keeps the plan and the load on one answer. Only meaningful for an auto quant
- with nothing being baked, which is the only caller: a LoRA bake forces the dense build.
-
- A ``None`` candidate is not by itself a prequant verdict -- it means the resolver had no basis
- (no size entry) and the plan declines to stage ``transformer/`` in that case too. But one of
- its ``None``s is a free-disk gate sized for a DOWNLOAD, and a prequant already on disk
- downloads nothing, so reading that one as "dense" would send a ready checkpoint to the GGUF
- for want of space it does not need. So a ``None`` re-asks the prequant resolver directly. Only
- the caller above reaches here, and it has already sent every UNCACHED prequant to the GGUF, so
- a source that survives that is cached and free. Never raises; an unanswerable probe reads as
- "dense", the conservative side."""
+ asking it here keeps the plan and the load on one answer. Only meaningful for an auto quant with
+ nothing being baked: a LoRA bake forces the dense build.
+
+ A ``None`` candidate is not by itself a prequant verdict: it means the resolver had no basis.
+ But one of its ``None``s is a free-disk gate sized for a DOWNLOAD, and a prequant already on
+ disk downloads nothing, so reading that one as dense would send a ready checkpoint to the GGUF
+ for want of space it does not need. So a ``None`` re-asks the prequant resolver directly. Never
+ raises; an unanswerable probe reads as dense, the conservative side.
+ """
try:
candidate = resolve_dense_quant_candidate(
fam = fam,
@@ -1182,14 +1138,14 @@ def _activation_guard_batch(chunks: Sequence[Sequence[Any]]) -> int:
One image, normally. The OOM backoff halves a failed multi-image forward all the way down to
SINGLETONS, so an oversized batch is already recoverable wherever torch raises; budgeting the
- whole chunk here would refuse batches that complete today (the measured batch-32 fast path).
- A single image that does not fit is the case no backoff can rescue, so that is the floor.
-
- Windows is the exception, and it is the exception this guard was written for. Under WDDM the
- driver satisfies a device overflow out of system RAM instead of raising, so no
- OutOfMemoryError ever reaches the backoff and an overrunning batch simply grows into tens of
- GB of host RAM and pagefile with the desktop unresponsive. Nothing recovers that after the
- fact, so the largest real chunk is budgeted up front there."""
+ whole chunk here would refuse batches that complete today. A single image that does not fit is
+ the case no backoff can rescue, so that is the floor.
+
+ Windows is the exception this guard was written for. Under WDDM the driver satisfies a device
+ overflow out of system RAM instead of raising, so no OutOfMemoryError ever reaches the backoff
+ and an overrunning batch grows into tens of GB of host RAM and pagefile with the desktop
+ unresponsive. Nothing recovers that, so the largest real chunk is budgeted up front there.
+ """
if sys.platform != "win32":
return 1
return max((len(chunk) for chunk in chunks), default = 1)
@@ -1197,11 +1153,9 @@ def _activation_guard_batch(chunks: Sequence[Sequence[Any]]) -> int:
def _memory_request_forces_offload(memory_mode: Optional[str], cpu_offload: bool) -> bool:
"""Whether this memory request offloads the transformer no matter what the weights measure.
-
``balanced`` and ``low_vram`` name their policy outright in ``resolve_offload_policy``, and
the legacy ``cpu_offload`` flag forces whole-module offload when no mode was supplied.
- ``fast`` and ``auto`` are decided from the measured footprint, so they are not knowable here.
- """
+ ``fast`` and ``auto`` are decided from the measured footprint, so they are not knowable here."""
mode = normalize_memory_mode(memory_mode)
if mode in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM):
return True
@@ -1250,8 +1204,8 @@ class DiffusionBackend:
return self._state is not None
def _pick_device_and_dtype(self, ordinal: Optional[int] = None) -> tuple[str, Any]:
- """(device, dtype) for the current host. Thin wrapper over the device
- policy module, kept as a method so tests can still monkeypatch it."""
+ """(device, dtype) for the current host. Thin wrapper over the device policy module, kept as
+ a method so tests can still monkeypatch it."""
if ordinal is None:
target = resolve_diffusion_device_target()
return target.device, target.dtype
@@ -1260,19 +1214,15 @@ class DiffusionBackend:
return target.torch_device, target.dtype
def _reserve_teardown_locked(self) -> None:
- """Fence queued generations off the pipeline this teardown is about to free.
-
- Call only while holding ``_lock``, so the count and the gate move together.
- """
+ """Fence queued generations off the pipeline this teardown is about to free. Call only while
+ holding ``_lock``, so the count and the gate move together."""
self._teardown_waiters += 1
self._teardown_drained.clear()
def _release_teardown_locked(self) -> None:
- """Release one teardown reservation and wake generations when the last one leaves.
-
- Call only while holding ``_lock``. A count is necessary because an unload and a
- superseding load can both be queued behind the active generation.
- """
+ """Release one teardown reservation and wake generations when the last one leaves. Call only
+ while holding ``_lock``. A count is necessary because an unload and a superseding load
+ can both be queued behind the active generation."""
assert self._teardown_waiters > 0, "teardown reservation released without an owner"
self._teardown_waiters -= 1
if self._teardown_waiters == 0:
@@ -1280,12 +1230,10 @@ class DiffusionBackend:
@contextmanager
def _model_transition_slot(self):
- """Hold the generation lock and publish that a model transition owns it.
-
- The teardown fence remains raised until after this context is entered, so queued
- cancellation always observes either that reservation or this owner flag. Releasing
- the flag and lock under the cancellation lock makes the handoff equally atomic.
- """
+ """Hold the generation lock and publish that a model transition owns it. The teardown fence
+ remains raised until after this context is entered, so queued cancellation always
+ observes either that reservation or this owner flag. Releasing the flag and lock under
+ the cancellation lock makes the handoff equally atomic."""
self._generate_lock.acquire()
with self._generation_cancel_lock:
assert not self._transition_owns_slot, "two model transitions own one slot"
@@ -1301,14 +1249,14 @@ class DiffusionBackend:
def _generation_slot(self, cancel: threading.Event):
"""Hold the generation lock, yielding to teardown and remaining cancellable.
- Lock acquisition is not FIFO. If a generation wins the lock after a load or unload
- has raised its fence, it must let that teardown run before reading ``_state``. Once
- the final fence drops, the teardown still owns ``_generate_lock`` until its model
- transition has settled, so the retried acquisition observes the new truthful state.
+ Lock acquisition is not FIFO. If a generation wins the lock after a load or unload has
+ raised its fence, it must let that teardown run before reading ``_state``. Once the final
+ fence drops, the teardown still owns ``_generate_lock`` until its model transition has
+ settled, so the retried acquisition observes the new truthful state.
- The zero-fence check and active-cancel registration share one ``_lock`` section. A
- teardown starting after that check therefore either sees this event and cancels it,
- or reserved before the check and makes this request yield.
+ The zero-fence check and active-cancel registration share one ``_lock`` section. A teardown
+ starting after that check therefore either sees this event and cancels it, or reserved
+ before the check and makes this request yield.
"""
admitted = False
with self._generation_cancel_lock:
@@ -1369,15 +1317,15 @@ class DiffusionBackend:
) -> None:
"""Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.
- Only the host-level impossibilities, which are knowable network-free: the wrong load kind,
- a device with no dense-quant path, and a scheme this GPU or family rules out. Anything
- needing the measured footprint is decided inside ``load_pipeline``. ``auto`` is never
- refused -- delegating the choice is exactly what it means.
+ Only the host-level impossibilities, which are knowable network-free: the wrong load kind, a
+ device with no dense-quant path, and a scheme this GPU or family rules out. Anything needing
+ the measured footprint is decided inside ``load_pipeline``. ``auto`` is never refused.
- Public because the ROUTE has to make this call itself, before it takes the GPU: the copy
- in ``begin_load`` runs inside ``acquire_for``, which evicts chat under the arbiter lock
- before the register callback, and after ``select_and_activate_engine``, which unloads the
- resident model on an engine switch."""
+ Public because the ROUTE has to make this call itself, before it takes the GPU: the copy in
+ ``begin_load`` runs inside ``acquire_for``, which evicts chat under the arbiter lock before
+ the register callback, and after ``select_and_activate_engine``, which unloads the resident
+ model on an engine switch.
+ """
if precision_fallback_allowed():
return
pinned = normalize_transformer_quant(transformer_quant)
@@ -1385,8 +1333,8 @@ class DiffusionBackend:
if pinned is None and te_mode is None:
return
# One probe for both checks, asked of the card THIS load will use: on a mixed box the default device can be a
- # different generation, which would refuse a scheme the selected card supports, or pass one it does not and fail
- # only after eviction. Scoped, because the route calls this on a pooled thread and the probes below use
+ # different generation, which would refuse a scheme the selected card supports, or pass one it does not and
+ # fail only after eviction. Scoped, because the route calls this on a pooled thread and the probes below use
# argument-less CUDA calls.
with diffusion_device_scope(gpu_ordinal):
target = self._target_for_ordinal(fam, gpu_ordinal)
@@ -1420,10 +1368,10 @@ class DiffusionBackend:
f"'{model_kind}' load, which runs the precision its checkpoint carries"
)
elif _memory_request_forces_offload(memory_mode, cpu_offload):
- # Not a measurement: balanced and low_vram name their policy outright, and the legacy flag forces model
- # offload. Offload hooks move modules with Module.to(), which torchao tensors do not survive, so the
- # loader skips the dense build for any of them -- and the strict refusal then landed after the resident
- # model was already gone. The two requests are incompatible on their face; say so here.
+ # Not a measurement: balanced and low_vram name their policy outright, and the legacy flag forces
+ # model offload. Offload hooks move modules with Module.to(), which torchao tensors do not survive, so
+ # the loader skips the dense build for any of them, and the strict refusal then landed after the
+ # resident model was already gone. The two requests are incompatible on their face.
requested_memory = normalize_memory_mode(memory_mode) or "cpu_offload"
reason = (
f"'{requested_memory}' memory places the transformer under CPU offload, and "
@@ -1456,15 +1404,14 @@ class DiffusionBackend:
off_label = "Off to run the checkpoint as-is",
)
)
- # The mode the loader will ACTUALLY attempt, not the raw request: an explicit int8 on a family with no keep-bf16
- # schedule is rewritten to layerwise fp8 before support is consulted, and that path needs no torchao. Refusing
- # on the raw int8 rejected loads the runtime would run and report as fell_back -- Windows ROCm, where the
- # torchao stub kills int8 while fp8 still works.
+ # The mode the loader will ACTUALLY attempt, not the raw request: an explicit int8 on a family with no
+ # keep-bf16 schedule is rewritten to layerwise fp8 before support is consulted, and that path needs no
+ # torchao. Refusing on the raw int8 rejected loads the runtime would run and report as fell_back.
te_effective = effective_te_quant(te_mode, getattr(fam, "name", None))
te_reason = None
if te_quant_needs_resident_weights(te_effective) and not torchao_quantize_importable():
- # The casters import torchao only after the pipeline is downloaded and built, so a broken or absent install
- # failed through load-progress instead of this 409.
+ # The casters import torchao only after the pipeline is downloaded and built, so a broken or absent
+ # install failed through load-progress instead of this 409.
te_reason = (
"torchao is not importable on this install, and these encoder modes are torchao "
"quantisations"
@@ -1478,8 +1425,8 @@ class DiffusionBackend:
memory_mode, cpu_offload
):
# Same fence as the dense transformer above, on the encoder: offload hooks move modules with Module.to(),
- # torchao tensors do not survive it, and the loader reports those modes unsupported once offload is active
- # -- after the resident pipeline is already gone. Layerwise fp8 is a dtype cast and is unaffected.
+ # torchao tensors do not survive it, and the loader reports those modes unsupported once offload is
+ # active, after the resident pipeline is already gone. Layerwise fp8 is a dtype cast and is unaffected.
requested_memory = normalize_memory_mode(memory_mode) or "cpu_offload"
te_reason = (
f"'{requested_memory}' memory places the text encoder under CPU offload, and "
@@ -1502,13 +1449,10 @@ class DiffusionBackend:
*,
ordinal: Optional[int] = None,
) -> DiffusionDeviceTarget:
- """The device target with the family fp16 guard applied.
-
- Routes through _pick_device_and_dtype() (so a monkeypatched override still
- drives the result), then promotes float16 -> float32 for fp16-incompatible
- families (Z-Image), rebuilding the target so dtype + capability flags stay
- consistent with the effective dtype.
- """
+ """The device target with the family fp16 guard applied. Routes through
+ _pick_device_and_dtype() (so a monkeypatched override still drives the result), then
+ promotes float16 -> float32 for fp16-incompatible families (Z-Image), rebuilding the
+ target so dtype + capability flags stay consistent with the effective dtype."""
# Called with no argument on the automatic path so a monkeypatched seam keeps working.
device, dtype = (
self._pick_device_and_dtype()
@@ -1521,9 +1465,9 @@ class DiffusionBackend:
"diffusion.dtype_promoted: family=%s float16 -> float32 (fp16-incompatible)",
getattr(fam, "name", None),
)
- # Builds only. Pinning is the CALLER's decision: a worker thread is dedicated and takes the permanent pin, while
- # a route preflight runs on a pooled executor thread where an unrestored set_device would leak this request's
- # card into the next one.
+ # Builds only. Pinning is the CALLER's decision: a worker thread is dedicated and takes the permanent pin,
+ # while a route preflight runs on a pooled executor thread where an unrestored set_device would leak this
+ # request's card into the next one.
return diffusion_device_target_from_torch_device(device, effective)
def _target_for_ordinal(
@@ -1536,12 +1480,10 @@ class DiffusionBackend:
return self._resolve_device_target(fam, ordinal = ordinal)
def _state_device_target(self, state: _LoadState) -> DiffusionDeviceTarget:
- """The resident pipeline's target, pinned onto the calling thread.
-
- Every worker touching the loaded pipeline goes through this rather than resolving bare:
- the weights are on ``state.gpu_ordinal`` while ``state.device`` is un-indexed, so an
- unpinned thread would resolve to its own default card.
- """
+ """The resident pipeline's target, pinned onto the calling thread. Every worker touching the
+ loaded pipeline goes through this rather than resolving bare: the weights are on
+ ``state.gpu_ordinal`` while ``state.device`` is un-indexed, so an unpinned thread would
+ resolve to its own default card."""
target = self._target_for_ordinal(state.family, state.gpu_ordinal)
apply_diffusion_device_ordinal(target)
# And put an AUTOMATIC load back on its own card. generate() runs on a pooled asyncio.to_thread worker, so a
@@ -1558,13 +1500,12 @@ class DiffusionBackend:
local_files_only: bool = False,
) -> str:
"""The local path of this pick's checkpoint, downloading it when it is not on disk.
-
``local_files_only`` makes both resolutions below cache lookups. The prefetch already
- staged this file under the same flag, so the promise looks kept -- but this call re-resolves
- the revision against the Hub, and a checkpoint republished upstream since the cache was
- filled (or removed between the staging and here) is a multi-GB pull taken under the
- generation lock, after the resident pipeline was evicted, where unload cannot preempt it and
- progress already reads 100%. It is the last unrestricted byte-mover on the image path."""
+ staged this file under the same flag, so the promise looks kept, but this call
+ re-resolves the revision against the Hub, and a checkpoint republished upstream since the
+ cache was filled is a multi-GB pull taken under the generation lock, after the resident
+ pipeline was evicted, where unload cannot preempt it and progress already reads 100%. It
+ is the last unrestricted byte-mover on the image path."""
local_root = Path(repo_id).expanduser()
if local_root.exists():
return str(resolve_local_gguf_child(local_root, gguf_filename))
@@ -1580,9 +1521,9 @@ class DiffusionBackend:
if not isinstance(
try_to_load_from_cache(repo_id, gguf_filename, cache_dir = cache_dir), str
):
- # Same other-root reuse as the pre-quant checkpoint, reached THROUGH that root rather than returned raw,
- # so the ref still resolves and a republished GGUF is picked up; the blob is reused, and offline the
- # cached pointer comes back anyway.
+ # Same other-root reuse as the pre-quant checkpoint, reached THROUGH that root rather than returned
+ # raw, so the ref still resolves and a republished GGUF is picked up; the blob is reused, and offline
+ # the cached pointer comes back anyway.
elsewhere = try_to_load_from_cache(repo_id, gguf_filename, cache_dir = None)
if isinstance(elsewhere, str) and Path(elsewhere).is_file():
try:
@@ -1613,17 +1554,15 @@ class DiffusionBackend:
companion_files: Optional[Sequence[str]] = None,
transformer_files: Optional[Sequence[str]] = None,
) -> bool:
- """True when ``load_pipeline`` may take the dense transformer-quant path, so
- the prefetch should also pull the base repo's ``transformer/`` shards.
-
- Those shards are excluded from the prefetch by default (the GGUF supplies
- the transformer), but ``_load_dense_quant_pipeline`` fetches them with
- ``from_pretrained(subfolder = "transformer")`` under the load lock during
- "finalizing", after the previous pipeline was already evicted, where
- unload/cancellation cannot preempt the download. Mirrors the dense-path
- gates in ``load_pipeline``: quant requested and supported for this device,
- and no pre-quantized checkpoint that would shortcut the dense build. Callers only ask for
- a ``kind == "gguf"`` pick, so the auto-quant decline below applies as written."""
+ """True when ``load_pipeline`` may take the dense transformer-quant path, so the prefetch
+ should also pull the base repo's ``transformer/`` shards. Those shards are excluded from
+ the prefetch by default (the GGUF supplies the transformer), but
+ ``_load_dense_quant_pipeline`` fetches them with ``from_pretrained(subfolder =
+ "transformer")`` under the load lock during finalizing, after the previous pipeline was
+ already evicted, where unload/cancellation cannot preempt the download. Mirrors the
+ dense-path gates in ``load_pipeline``: quant requested and supported for this device, and
+ no pre-quantized checkpoint that would shortcut the dense build. Callers only ask for a
+ ``kind == "gguf"`` pick."""
raw = kwargs.get("transformer_quant")
auto = raw is None or str(raw).strip().lower() in ("", "auto")
if auto:
@@ -1637,7 +1576,8 @@ class DiffusionBackend:
if speed is not None and str(speed).strip().lower() == SPEED_OFF:
return False
try:
- # A definite-offload policy skips the dense build, so widening wastes a multi-GB pull with no GGUF fallback.
+ # A definite-offload policy skips the dense build, so widening wastes a multi-GB pull with no GGUF
+ # fallback.
mm = normalize_memory_mode(kwargs.get("memory_mode"))
if mm in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM):
return False
@@ -1673,12 +1613,10 @@ class DiffusionBackend:
# base transformer/ shards either.
# The same rule, applied to the base repo's own dense shards. The fast path loads transformer/ INSTEAD of the
# GGUF, so on a pick the user made BY QUANT an uncached base means fetching a second, much larger denoiser and
- # never opening the first: Qwen-Image-Edit's Q6_K is 16.9 GB and the base transformer is another 40.9 GB. Cached
- # shards cost nothing, so anyone who already has the dense base keeps the fast path, and an EXPLICIT
- # transformer_quant still opts in as before. This returns the same False a PREQUANT candidate returns below, so
- # a cached pre-quant reaches the load with no transformer/ staged and NOT because a download was refused. That
- # is why the load side re-asks the resolver rather than reading an empty stage as a decline: same verdict here,
- # two different reasons there.
+ # never opening the first. Cached shards cost nothing, so anyone who already has the dense base keeps the fast
+ # path, and an EXPLICIT transformer_quant still opts in. This returns the same False a PREQUANT candidate
+ # returns below, so a cached pre-quant reaches the load with no transformer/ staged and NOT because a download
+ # was refused. That is why the load side re-asks the resolver rather than reading an empty stage as a decline.
if (
auto
and not _has_active_lora(kwargs.get("loras"))
@@ -1743,10 +1681,9 @@ class DiffusionBackend:
path_override: Optional[str],
loras: Any,
) -> Optional[str]:
- """A lower auto rung than ``chosen`` that HAS a usable prequant, or None.
-
- Only when ``auto`` was requested: an explicit scheme is honored or refused, never
- swapped. A baked LoRA takes the dense path regardless, so it gets no retry."""
+ """A lower auto rung than ``chosen`` that HAS a usable prequant, or None. Only when ``auto``
+ was requested: an explicit scheme is honored or refused, never swapped. A baked LoRA
+ takes the dense path regardless, so it gets no retry."""
if normalize_transformer_quant(requested) != TQ_AUTO or _has_active_lora(loras):
return None
try:
@@ -1769,8 +1706,8 @@ class DiffusionBackend:
continue
# Same cached-only rule _uncached_prequant_repo applies to the winner. That guard runs
# select_transformer_quant_scheme, which only ever sees the winner, so a retry that returned an UNCACHED
- # repo would smuggle past it and download a second multi-GB denoiser for a pick that already has its GGUF. A
- # local override is the operator's own file and costs no bytes.
+ # repo would smuggle past it and download a second multi-GB denoiser for a pick that already has its GGUF.
+ # A local override is the operator's own file and costs no bytes.
if source.kind == "repo" and not prequant_checkpoint_cached(
source, cache_dir = hub_cache_dir()
):
@@ -1789,24 +1726,20 @@ class DiffusionBackend:
fetch_base: Optional[str] = None,
local_files_only: bool = False,
) -> Optional[str]:
- """Pre-download the GGUF + the given ``base_files`` into the HF cache,
- WITHOUT the lock and honoring ``cancel_event`` (this load's own event, so a
- replacement load cannot un-cancel this one), so load_pipeline's
- from_single_file / from_pretrained hit the cache and the heavy download can
- be preempted by an unload/eviction. Raises ``RuntimeError("Cancelled")``.
-
- Returns the base repo's local snapshot dir when the prefetched set includes
- the pipeline manifest, so from_pretrained can load from disk instead of
- re-sweeping the hub (its own sweep also pulls files the scoped list skips,
- e.g. the 24 GB packaged root singles in each FLUX.1 repo); None otherwise
- (estimate failure, config-only base, local repo) -> hub id as before.
-
- ``local_files_only`` makes every resolution below a CACHE LOOKUP: the file is returned when
- it is on disk and ``LocalEntryNotFoundError`` is raised when it is not. This is the one call
- in the staging phase that moves multi-GB bytes, so a dropped flag here is the whole
- no-download promise -- a checkpoint that vanished after the switch's locality check, or a
- check that read the cache as more complete than it is, becomes a pull on the user's
- connection that nobody asked for."""
+ """Pre-download the GGUF + the given ``base_files`` into the HF cache, WITHOUT the lock and
+ honoring ``cancel_event`` (this load's own event, so a replacement load cannot un-cancel
+ this one), so load_pipeline's from_single_file / from_pretrained hit the cache and the heavy
+ download can be preempted by an unload/eviction. Raises ``RuntimeError("Cancelled")``.
+
+ Returns the base repo's local snapshot dir when the prefetched set includes the pipeline
+ manifest, so from_pretrained can load from disk instead of re-sweeping the hub (its own
+ sweep also pulls files the scoped list skips); None otherwise (estimate failure, config-only
+ base, local repo) -> hub id as before.
+
+ ``local_files_only`` makes every resolution below a CACHE LOOKUP. This is the one call in
+ the staging phase that moves multi-GB bytes, so a dropped flag here is the whole no-download
+ promise.
+ """
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
# Only the BYTES move; the caller keeps the upstream id. ``fetch_base`` is the load-wide decision when one was
@@ -1814,10 +1747,10 @@ class DiffusionBackend:
base = fetch_base or prefer_ungated_mirror(base, hf_token, files = base_files)
# Callers without a per-load event (tests, direct use) fall back to the current one.
cancel = cancel_event if cancel_event is not None else self._cancel_event
- # A file cached only under huggingface_hub's import-time root resolves through that root: the preflight clears a
- # base found under EITHER root, so without this a cache-folder change turns an already-downloaded gated base
- # into a mid-prefetch Hub token error, and every other moved asset into a needless re-download. GGUF transformer
- # (hub repos only; a local path is already on disk).
+ # A file cached only under huggingface_hub's import-time root resolves through that root: the preflight clears
+ # a base found under EITHER root, so without this a cache-folder change turns an already-downloaded gated base
+ # into a mid-prefetch Hub token error, and every other moved asset into a needless re-download. GGUF
+ # transformer (hub repos only; a local path is already on disk).
if gguf_filename and not Path(repo_id).expanduser().exists():
hf_hub_download_with_xet_fallback(
repo_id,
@@ -1851,8 +1784,8 @@ class DiffusionBackend:
roots.add(root)
if rfilename == "model_index.json":
snapshot_root = root or None
- # Only hand back a snapshot the whole set lives in; otherwise the hub id resolves each file through its own root
- # as before.
+ # Only hand back a snapshot the whole set lives in; otherwise the hub id resolves each file through its own
+ # root as before.
if snapshot_root is not None and roots != {snapshot_root}:
return None
return snapshot_root
@@ -1866,12 +1799,11 @@ class DiffusionBackend:
model_kind: Optional[str] = None,
base_repo: Optional[str] = None,
) -> DiffusionFamily:
- """Cheap, network-free validation shared by the route (before it evicts the
- chat model) and the load paths, so an unloadable pick fails BEFORE the GPU
- handoff. Resolves the load kind (gguf / single_file / pipeline), then raises
- ValueError for a missing single-file name, a non-unsloth non-GGUF repo, or an
- undetectable family, and ValueError/FileNotFoundError for a bad local path.
- Touches no GPU, network, or state."""
+ """Cheap, network-free validation shared by the route (before it evicts the chat model) and
+ the load paths, so an unloadable pick fails BEFORE the GPU handoff. Resolves the load
+ kind (gguf / single_file / pipeline), then raises ValueError for a missing single-file
+ name, a non-unsloth non-GGUF repo, or an undetectable family, and
+ ValueError/FileNotFoundError for a bad local path. Touches no GPU, network, or state."""
kind = resolve_model_kind(gguf_filename, model_kind)
fam = detect_family_for_pick(repo_id, gguf_filename, family_override)
if fam is None:
@@ -1885,9 +1817,9 @@ class DiffusionBackend:
f"pass family_override with that family name. (Video models and image models "
f"whose diffusers transformer has no single-file loader are not supported.)"
)
- # Refuse a too-old diffusers here, not deep in the load, but only when this load builds the diffusers pipeline:
- # a GGUF this host routes to native sd.cpp never instantiates the class. The picker gate reads the same
- # predicate. Imported here, not at module import, because the router imports this module's siblings.
+ # Refuse a too-old diffusers here, not deep in the load, but only when this load builds the diffusers
+ # pipeline: a GGUF this host routes to native sd.cpp never instantiates the class. The picker gate reads the
+ # same predicate. Imported here, not at module import, because the router imports this module's siblings.
from .diffusion_engine_router import family_buildable_here
if not family_buildable_here(fam, model_kind = kind):
@@ -1974,15 +1906,13 @@ class DiffusionBackend:
allow_network: bool = True,
) -> None:
"""The gated/unreadable-base and FLUX.2 size-pairing refusals, run by the route BEFORE it
- takes the GPU.
-
- ``_run_load`` and ``download_plan`` already make them, but ``_run_load`` runs on the load
- thread, after the route evicted chat, and the plan's verdict does not stop the load: the
- images page falls back to /images/load on ANY plan failure. Resolves the base exactly as
- those two do, so all three agree. The one deliberate network step on the pre-eviction path
- (``validate_load_request`` stays network-free): a handful of metadata calls for a remote
- pick, none for a local one, all already made by ``_run_load`` moments later. Fails open on
- offline/transient, so it can refuse a load but never block one that would have worked."""
+ takes the GPU. ``_run_load`` and ``download_plan`` already make them, but ``_run_load``
+ runs on the load thread, after the route evicted chat, and the plan's verdict does not
+ stop the load: the images page falls back to /images/load on ANY plan failure. Resolves
+ the base exactly as those two do, so all three agree. The one deliberate network step on
+ the pre-eviction path (``validate_load_request`` stays network-free): a handful of
+ metadata calls for a remote pick, none for a local one. Fails open on offline/transient,
+ so it can refuse a load but never block one that would have worked."""
kind = resolve_model_kind(gguf_filename, model_kind)
if kind == "pipeline":
base = repo_id # the full pipeline IS the repo
@@ -1992,19 +1922,17 @@ class DiffusionBackend:
# mirror rescues, and the swap is pure, so it decides the same here as on the load thread. Only the raise
# matters; _run_load recomputes the excused snapshot.
_assert_base_repo_accessible(prefer_ungated_mirror(base, hf_token), hf_token)
- # Same reasoning for the FLUX.2 size pairing, and this is the only place it can be caught before a teardown: the
- # loader's own guard opens the downloaded checkpoint, so it fires after ~19 GB of base shards AND after the
- # resident pipeline was freed. Metadata only (one range request for the GGUF's tensor table), and fails open on
- # anything it cannot read. The UPSTREAM base, not the mirror: the size tables key on vendor ids.
+ # Same reasoning for the FLUX.2 size pairing, and this is the only place it can be caught before a teardown:
+ # the loader's own guard opens the downloaded checkpoint, so it fires after ~19 GB of base shards AND after
+ # the resident pipeline was freed. Metadata only, and fails open on anything it cannot read. The UPSTREAM
+ # base, not the mirror: the size tables key on vendor ids.
assert_flux2_pick_compatible(fam, repo_id, gguf_filename, base, hf_token)
- # No media backend decodes a speech GGUF, and detect_family_for_pick answers from the folder name, so a csm file
- # beside a denoiser reaches this loader as one of its own. Cache-only for a load nobody asked for: this probe
- # would otherwise spend a revision HEAD, or a range request and its bound, on the one path that promised to stay
- # off the Hub.
+ # No media backend decodes a speech GGUF, and detect_family_for_pick answers from the folder name, so a csm
+ # file beside a denoiser reaches this loader as one of its own. Cache-only for a load nobody asked for: this
+ # probe would otherwise spend a revision HEAD, or a range request, on the one path that promised to stay off
+ # the Hub.
assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)
- # ── Background load + progress ─────────────────────────────────────────
-
def begin_load(
self,
repo_id: str,
@@ -2032,12 +1960,12 @@ class DiffusionBackend:
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None
- # Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's 400 rather than a load
- # that dies mid-download, and only once so free VRAM cannot re-rank the choice after the weights land. Gated on
- # the resolved backend, since XPU / MPS / CPU ignore physical ids and would otherwise 400 a selection the
- # contract says to drop. Re-ranked only when the caller did not already do it: free VRAM moves between the
- # route's preflight and here (network preflight, engine activation, arbiter eviction), so resolving twice can
- # approve a scheme against one card and place the weights on another.
+ # Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's 400 rather than a
+ # load that dies mid-download, and only once so free VRAM cannot re-rank the choice after the weights land.
+ # Gated on the resolved backend, since XPU / MPS / CPU ignore physical ids and would otherwise 400 a selection
+ # the contract says to drop. Re-ranked only when the caller did not already do it: free VRAM moves between the
+ # route's preflight and here, so resolving twice can approve a scheme against one card and place the weights
+ # on another.
if gpu_ordinal is None:
gpu_ordinal = (
resolve_selected_cuda_ordinal(gpu_ids)
@@ -2051,9 +1979,8 @@ class DiffusionBackend:
model_kind = model_kind,
)
# Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the route answers 409 with
- # the reason instead of evicting the resident model, downloading several GB and only then failing. The declines
- # that need the real footprint (a VRAM misfit, a failed build) can only be found mid-load and surface through
- # load-progress.
+ # the reason instead of evicting the resident model, downloading several GB and only then failing. The
+ # declines that need the real footprint can only be found mid-load and surface through load-progress.
self.assert_precision_available(
fam,
model_kind = resolve_model_kind(gguf_filename, model_kind),
@@ -2068,9 +1995,9 @@ class DiffusionBackend:
raise RuntimeError("A diffusion load is already in progress.")
self._load_token += 1
token = self._load_token
- # A NEW event per load, never a clear() of the shared one: unload() sets the event the running worker holds
- # but also drops _loading, so clearing here would un-cancel that worker. Download preemption is best-effort;
- # the token is the real commit guard.
+ # A NEW event per load, never a clear() of the shared one: unload() sets the event the running worker
+ # holds but also drops _loading, so clearing here would un-cancel that worker. Download preemption is
+ # best-effort; the token is the real commit guard.
cancel_event = threading.Event()
self._cancel_event = cancel_event
# Seed with the family fallback; the worker resolves the real base and updates this.
@@ -2110,10 +2037,9 @@ class DiffusionBackend:
# This load's own event: a later load replaces self._cancel_event rather than clearing it.
cancel_event = kwargs.pop("_cancel_event", None) or self._cancel_event
# An API-initiated load promises to download NOTHING: it may only open what is already cached. Read once here
- # and threaded into the staging phase below, the same way the video path does it -- the flag reached
- # load_pipeline and nothing before it, so the prefetch that moves the bytes ran unrestricted and the promise was
- # carried only by the locality check the flag exists to stop relying on. READ, not popped: load_pipeline takes
- # it too (it is in this thread's kwargs by contract).
+ # and threaded into the staging phase below, the same way the video path does it: the flag reached
+ # load_pipeline and nothing before it, so the prefetch that moves the bytes ran unrestricted. READ, not
+ # popped: load_pipeline takes it too.
local_files_only = bool(kwargs.get("local_files_only"))
try:
# Resolve the base repo and estimate sizes here (both network) so begin_load returns instantly.
@@ -2167,8 +2093,8 @@ class DiffusionBackend:
)
# Only shards this prefetch staged may be materialised by the dense fallback, so read it off the staged
# list: a failed size estimate drops every base file too. A LOCAL base directory has no listing to fail at
- # -- model_info raises on a path -- and its shards are already there, so it counts as staged on the
- # filesystem instead.
+ # (model_info raises on a path) and its shards are already there, so it counts as staged on the filesystem
+ # instead.
kwargs["_transformer_prefetched"] = any(
f.startswith("transformer/") for f in base_files
) or _local_base_transformer_present(base)
@@ -2179,16 +2105,15 @@ class DiffusionBackend:
)
kwargs["_fetch_base"] = fetch_base
# Same preflight the plan runs: catch a gated base here, not 15 GiB into the prefetch. Runs on
- # ``fetch_base``, once it is decided, so it probes the repo the pull will read: refusing the upstream id
- # would reject the gated picks the ungated mirror rescues. Everything above is metadata, so no byte has
- # moved yet. Returns a snapshot dir when it excused the base off a copy only the import-time root holds.
+ # ``fetch_base``, once it is decided, so it probes the repo the pull will read. Everything above is
+ # metadata, so no byte has moved yet. Returns a snapshot dir when it excused the base off a copy only the
+ # import-time root holds.
base_snapshot = _assert_base_repo_accessible(
fetch_base, kwargs.get("hf_token"), local_files_only = local_files_only
)
- # And the same size-pairing preflight the plan and the route run, here because a direct begin_load (a saved
- # config, the deploy path) reaches neither. Still metadata only, so it lands before _prefetch_files stages
- # the base and before load_pipeline unloads the resident pipeline -- the two costs the loader's backstop
- # cannot avoid.
+ # And the same size-pairing preflight the plan and the route run, here because a direct begin_load (a
+ # saved config, the deploy path) reaches neither. Still metadata only, so it lands before _prefetch_files
+ # stages the base and before load_pipeline unloads the resident pipeline.
assert_flux2_pick_compatible(
fam, kwargs["repo_id"], kwargs.get("gguf_filename"), base, kwargs.get("hf_token")
)
@@ -2283,8 +2208,8 @@ class DiffusionBackend:
# else a mirrored companion download reads as zero and the bar sits still.
companion = loading.fetch_repo or loading.base_repo
if loading.base_repo and loading.base_repo == loading.repo_id:
- # Full pipeline: base IS the repo, so count it once. Summing would add the upstream's stale partial blobs --
- # the very thing that selects the mirror -- to the mirror's live bytes, pushing the bar to 100% / finalizing
+ # Full pipeline: base IS the repo, so count it once. Summing would add the upstream's stale partial blobs,
+ # the very thing that selects the mirror, to the mirror's live bytes, pushing the bar to 100% / finalizing
# mid-download.
downloaded = self._cache_bytes(companion or loading.repo_id)
else:
@@ -2301,13 +2226,11 @@ class DiffusionBackend:
return _progress("downloading", downloaded, expected, min(downloaded / expected, 1.0))
def loading_repo_ids(self) -> tuple[str, ...]:
- """Repo ids an in-flight background load is downloading (empty when idle).
-
- The delete-cached guard needs this: during a load ``status()["loaded"]`` is
- still False, but deleting the target repo (or its companion base) would yank
- blobs and snapshot files from under the download/assembly. Includes the mirror
- when one was swapped in: that is where the companion bytes land, so guarding only
- the upstream id would leave the live download deletable."""
+ """Repo ids an in-flight background load is downloading (empty when idle). The delete-cached
+ guard needs this: during a load ``status()["loaded"]`` is still False, but deleting the
+ target repo (or its companion base) would yank blobs and snapshot files from under the
+ download/assembly. Includes the mirror when one was swapped in: that is where the
+ companion bytes land."""
with self._lock:
loading = self._loading
if loading is None or loading.error is not None:
@@ -2324,16 +2247,17 @@ class DiffusionBackend:
local_files_only: bool = False,
base_repo: Optional[str] = None,
) -> dict[str, tuple[str, list[tuple[str, int]]]]:
- """``{component: (repo_id, [(rfilename, size)])}`` for the text encoders this pick will
- take PRE-CAST from a hosted checkpoint instead of the base repo's dense weights.
+ """``{component: (repo_id, [(rfilename, size)])}`` for the text encoders this pick will take
+ PRE-CAST from a hosted checkpoint instead of the base repo's dense weights.
- Empty unless the request asked for a scheme with a hosted artifact AND that artifact
- really resolves, so a plan can never drop a dense encoder the load still wants.
+ Empty unless the request asked for a scheme with a hosted artifact AND that artifact really
+ resolves, so a plan can never drop a dense encoder the load still wants.
Empty under ``local_files_only``: ``te_prequant_hub_files`` is a ``model_info`` per source,
and the only consumer is the size estimate, which has already stood down. Empty is the
- answer an unresolvable pre-cast gives today, and it is the safe one -- it keeps the dense
- shards in the list rather than dropping weights the load may still open."""
+ answer an unresolvable pre-cast gives today, and it keeps the dense shards in the list
+ rather than dropping weights the load may still open.
+ """
if local_files_only:
return {}
try:
@@ -2379,20 +2303,19 @@ class DiffusionBackend:
) -> Optional[tuple[str, str, int]]:
"""The hosted PRE-QUANTIZED transformer this pick loads INSTEAD of the base repo's dense
shards, as ``(repo, filename, declared_size)``, or None when no such artifact is used.
-
- Those shards are already excluded for a GGUF pick, so without this the plan neither counts
- nor stages the multi-GB denoiser the load really keeps on disk: the footprint reads short
- and the file is pulled INLINE during the load, outside the manager's progress, cancel and
- disk preflight. Mirrors the prequant gates in ``_load_dense_quant_pipeline`` so the plan
- and the load agree."""
+ Those shards are already excluded for a GGUF pick, so without this the plan neither
+ counts nor stages the multi-GB denoiser the load really keeps on disk: the footprint
+ reads short and the file is pulled INLINE during the load, outside the manager's
+ progress, cancel and disk preflight. Mirrors the prequant gates in
+ ``_load_dense_quant_pipeline``."""
if kind != "gguf" or fam is None:
return None
try:
raw = kwargs.get("transformer_quant")
auto = raw is None or str(raw).strip().lower() in ("", "auto")
- # An AUTO quant under an explicit Speed="off" is forced to "off" by load_pipeline, which normalizes to None
- # and skips the fast path entirely, so no prequant is ever fetched. An EXPLICIT quant still takes it: that
- # force applies only to the auto tri-state.
+ # An AUTO quant under an explicit Speed="off" is forced to "off" by load_pipeline, which normalizes to
+ # None and skips the fast path entirely, so no prequant is ever fetched. An EXPLICIT quant still takes it:
+ # that force applies only to the auto tri-state.
speed = kwargs.get("speed_mode")
if auto and speed is not None and str(speed).strip().lower() == SPEED_OFF:
return None
@@ -2403,8 +2326,8 @@ class DiffusionBackend:
if _has_active_lora(kwargs.get("loras")):
return None
# A definite-offload policy keeps the GGUF: the fast path needs either a plan with no offload or a
- # quant-sized replan that came back with none, and balanced/low_vram offload BY MODE, so no replan can clear
- # it. Same gate _dense_quant_prefetch_needed applies, for the same reason.
+ # quant-sized replan that came back with none, and balanced/low_vram offload BY MODE, so no replan can
+ # clear it. Same gate _dense_quant_prefetch_needed applies.
mm = normalize_memory_mode(kwargs.get("memory_mode"))
if mm in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM):
return None
@@ -2495,43 +2418,37 @@ class DiffusionBackend:
failures_out: Optional[list] = None,
local_files_only: bool = False,
) -> tuple[int, list[str]]:
- """Total download size for the progress bar, plus the base-repo files to
- fetch (the prefetch reuses this list, so the base is listed only once).
-
- ``sizes_out``, when given, is filled with per-repo byte totals so the download
- plan can size one job per repo off this same single pair of Hub lookups.
- ``resident_file_sizes_out`` receives only the selected pipeline components and default
- weight variant, which is the set that ``from_pretrained`` materialises in memory.
- ``revisions_out`` records the commit each lookup described, so a cache probe can ask
- about the SAME revision the sizes came from instead of whatever ``main`` is locally.
- ``fetch_repos_out`` records the repo that supplied pipeline metadata, so staging reads
- that same pinned file set instead of making a second mirror choice after the estimate.
-
- For a ``pipeline`` load the whole repo IS the pipeline (``base_repo`` is the
- repo itself), so the transformer/ subfolder is INCLUDED -- unlike the GGUF /
- single-file paths, where the transformer is the single file and the base repo
- supplies only the companions. For a ``single_file_is_pipeline`` family (SDXL) the
- single file is the WHOLE pipeline, so the base repo supplies only config/tokenizer
- (no weights) and its weight files are skipped.
+ """Total download size for the progress bar, plus the base-repo files to fetch (the prefetch
+ reuses this list, so the base is listed only once).
+
+ ``sizes_out``, when given, is filled with per-repo byte totals so the download plan can size
+ one job per repo off this same single pair of Hub lookups. ``resident_file_sizes_out``
+ receives only the selected pipeline components and default weight variant, which is the set
+ that ``from_pretrained`` materialises in memory. ``revisions_out`` records the commit each
+ lookup described, so a cache probe can ask about the SAME revision the sizes came from.
+ ``fetch_repos_out`` records the repo that supplied pipeline metadata, so staging reads that
+ same pinned file set instead of making a second mirror choice.
+
+ For a ``pipeline`` load the whole repo IS the pipeline, so the transformer/ subfolder is
+ INCLUDED, unlike the GGUF / single-file paths where the transformer is the single file. For
+ a ``single_file_is_pipeline`` family (SDXL) the base repo supplies only config/tokenizer and
+ its weight files are skipped.
``include_transformer`` may be a CALLABLE ``(companions, transformer_files) -> bool``,
- called once with this repo's actual listing split either side of ``transformer/``. The
+ called once with this repo's actual listing split either side of ``transformer/``: the
widening decision turns on what those two sets say about the cache and about which repo the
- fetch will resolve to, and that listing exists only here -- deciding it before the lookup
- meant guessing at both.
+ fetch will resolve to, and that listing exists only here.
``skip_te_components`` names the text encoders this pick loads PRE-CAST from a hosted
- checkpoint, so their dense weight shards are not counted or fetched: staging the dense
- encoder for a pre-cast load wastes tens of GB (FLUX.2-dev's Mistral-24B is ~48 GB,
- Qwen-Image's Qwen2.5-VL ~16.6 GB) and nothing ever opens them. Everything else in the
- component folder (config, shard index, tokenizer) is kept -- the pre-cast loader
- meta-inits the encoder from the base repo's config.
+ checkpoint, so their dense weight shards are not counted or fetched (staging the dense
+ encoder for a pre-cast load wastes tens of GB and nothing ever opens them). Everything else
+ in the component folder is kept: the pre-cast loader meta-inits the encoder from the base
+ repo's config.
- ``local_files_only`` returns the "metadata unavailable" answer -- ``(0, [])`` -- instead of
+ ``local_files_only`` returns the metadata-unavailable answer, ``(0, [])``, instead of
asking. Every byte this counts belongs to a download that is not permitted, and the empty
- file list is what makes the prefetch below stage nothing: ``from_pretrained`` resolves the
- cached snapshot itself. Callers already handle it, because it is the same pair a failed
- lookup produces."""
+ file list is what makes the prefetch stage nothing.
+ """
if local_files_only:
return 0, []
from huggingface_hub import HfApi
@@ -2668,8 +2585,8 @@ class DiffusionBackend:
except Exception as exc: # noqa: BLE001 - estimate is best-effort
logger.warning("diffusion.size_estimate_failed: %s", exc)
# Recorded so a caller that must not guess (media auto-switch refuses rather than download) can tell a
- # partial file list from a complete one; the estimate itself stays best-effort for the UI, whose fallback is
- # the inline pull.
+ # partial file list from a complete one; the estimate itself stays best-effort for the UI, whose fallback
+ # is the inline pull.
if failures_out is not None:
failures_out.append(exc)
return total, base_files
@@ -2688,26 +2605,23 @@ class DiffusionBackend:
memory_verdict: bool = True,
**load_kwargs: Any,
) -> dict[str, Any]:
- """The repos + exact files this pick needs, so the Hub download manager can fetch
- them with the same file scope the loader would.
+ """The repos + exact files this pick needs, so the Hub download manager can fetch them with the
+ same file scope the loader would.
- A plain snapshot_download would also pull what the loader deliberately skips (the
- packaged root single, transformer/ shards, fp16 twins) -- tens of GB per FLUX repo.
- Resolves family/kind/base exactly as ``_run_load`` does, so the plan and the load
- agree. Local paths are already on disk and yield no entries.
+ A plain snapshot_download would also pull what the loader deliberately skips (the packaged
+ root single, transformer/ shards, fp16 twins), tens of GB per FLUX repo. Resolves
+ family/kind/base exactly as ``_run_load`` does. Local paths are already on disk and yield no
+ entries.
- ``text_encoder_quant`` is read for the same reason as the DiT quant: an fp8 request
- loads a hosted PRE-CAST encoder, so the base repo's dense encoder shards must not be
- staged and the pre-cast checkpoint must be. Without it the manager stages the dense
- encoder (tens of GB the load never opens) and the load then pulls the pre-cast file
- inline, outside the manager's progress and disk preflight.
+ ``text_encoder_quant`` is read for the same reason as the DiT quant: an fp8 request loads a
+ hosted PRE-CAST encoder, so the base repo's dense encoder shards must not be staged and the
+ pre-cast checkpoint must be.
``allow_device_probe=False`` skips device-dependent precision planning and the memory
verdict while training owns the GPU. It is not free: the pre-cast encoder and the DiT
- prequant need a target to resolve, so clearing it also changes WHICH FILES the plan
- counts. ``memory_verdict=False`` suppresses only the oversized-unified-memory refusal,
- so a caller that merely dislikes the verdict does not silently get a different file
- list."""
+ prequant need a target to resolve, so clearing it also changes WHICH FILES the plan counts.
+ ``memory_verdict=False`` suppresses only the oversized-unified-memory refusal.
+ """
fam = detect_family_for_pick(repo_id, gguf_filename, family_override)
kind = resolve_model_kind(gguf_filename, model_kind)
if kind == "pipeline":
@@ -2720,12 +2634,11 @@ class DiffusionBackend:
return {"entries": [], "total_bytes": 0, "required_bytes": 0, "checkpoint_bytes": 0}
else:
base = _resolve_base_repo(repo_id, base_repo, fam, hf_token)
- # Reported, not raised. carried in the envelope instead, the picker can refuse at SELECTION time.
# Reported, not raised. The images page falls back to /images/load on ANY plan failure, so a 400 here would
# start the very download this is meant to prevent; carried in the envelope instead, the picker can refuse at
- # SELECTION time. Metadata only (one range request for the GGUF's tensor table), and None whenever nothing is
- # known to be wrong. The speech verdict belongs here too, not only on the load preflight: the Images page stages
- # and downloads before it calls load, so a later refusal arrives after the bytes.
+ # SELECTION time. Metadata only, and None whenever nothing is known to be wrong. The speech verdict belongs
+ # here too, not only on the load preflight: the Images page stages and downloads before it calls load, so a
+ # later refusal arrives after the bytes.
incompatible = flux2_pick_mismatch(
fam, repo_id, gguf_filename, base, hf_token
) or speech_pick_refusal(repo_id, gguf_filename, hf_token)
@@ -2755,10 +2668,10 @@ class DiffusionBackend:
kind = kind,
pipeline_components = _explicit_pipeline_components(fam),
single_file_is_pipeline = bool(fam and fam.single_file_is_pipeline),
- # The RESOLVED base, as the load passes it: a variant base picks its own pre-quant repo. Deferred exactly as
- # _run_load defers it. Called eagerly this runs before the base listing exists, so the cache gate sees no
- # transformer shards, always declines, and the plan scopes narrower than the load: the registry then reports
- # scope_file_mismatch and the plan cannot adopt the load's own in-flight job.
+ # The RESOLVED base, as the load passes it: a variant base picks its own pre-quant repo. Deferred exactly
+ # as _run_load defers it. Called eagerly this runs before the base listing exists, so the cache gate sees
+ # no transformer shards, always declines, and the plan scopes narrower than the load: the registry then
+ # reports scope_file_mismatch and the plan cannot adopt the load's own in-flight job.
include_transformer = (
(
lambda companions, transformer_files: self._dense_quant_prefetch_needed(
@@ -2820,19 +2733,18 @@ class DiffusionBackend:
) -> None:
"""Add only files the loader cannot already resolve from either cache root.
- The picker knows whether its checkpoint is cached, but not whether companion repos
- are. Keeping this decision in the plan makes a cached GGUF + missing text encoder one
+ The picker knows whether its checkpoint is cached, but not whether companion repos are.
+ Keeping this decision in the plan makes a cached GGUF + missing text encoder one
explicit dependency download, and prevents a cached GGUF from being staged again.
The probe asks about the revision this plan's sizes came from, so a companion that
- republished a file is a MISS here rather than a silent inline fetch during the load.
- One entry per repo: same-repo groups share a scope variant, so a second job for the
- same repo would fight the first over progress, manifest and cancellation.
-
- ``checkpoint`` marks the entry that holds the SELECTED model, so the panel can label
- it without re-deriving the answer from the repo id: only this planner knows a gated
- base was swapped for an ungated mirror, which leaves the entry's repo id different
- from the id the caller picked.
+ republished a file is a MISS here rather than a silent inline fetch during the load. One
+ entry per repo: same-repo groups share a scope variant, so a second job for the same
+ repo would fight the first over progress, manifest and cancellation.
+
+ ``checkpoint`` marks the entry that holds the SELECTED model, so the panel can label it
+ without re-deriving the answer from the repo id: only this planner knows a gated base
+ was swapped for an ungated mirror.
"""
scope = scoped_files.setdefault(repo, [])
@@ -2841,10 +2753,10 @@ class DiffusionBackend:
revision = revisions.get(repo)
live = hub_cache_dir()
- # Preserve main's stable-scope invariant: a running @diffusion job is adopted only when a second claim names
- # the same complete file set. This strict, pinned fast path drops a repo only when one cache root already
- # serves the whole snapshot. The per-file probes below remain necessary for size-corroborated unrelated
- # commits and for accurate remaining-byte accounting.
+ # Preserve main's stable-scope invariant: a running @diffusion job is adopted only when a second claim
+ # names the same complete file set. This strict, pinned fast path drops a repo only when one cache root
+ # already serves the whole snapshot. The per-file probes below remain necessary for size-corroborated
+ # unrelated commits and for accurate remaining-byte accounting.
if self._files_already_cached(repo, files, revision, declared_sizes).issuperset(files):
for entry in entries:
if entry["repo_id"] == repo:
@@ -2859,23 +2771,23 @@ class DiffusionBackend:
return "live"
if not self._hub_file_is_cached(repo, name, revision, size, roots = (None,)):
return None
- # The other root holds a good copy, but reuse_other_cache_root only switches roots when the live lookup
- # finds NOTHING. A stale live copy (right name, wrong bytes) therefore shadows the good one and gets
- # served, or re-fetched inline. Passing no size asks presence alone, which is exactly what that switch
- # tests.
+ # The other root holds a good copy, but reuse_other_cache_root only switches roots when the live
+ # lookup finds NOTHING. A stale live copy (right name, wrong bytes) therefore shadows the good one and
+ # gets served, or re-fetched inline. Passing no size asks presence alone, which is exactly what that
+ # switch tests.
if self._hub_file_is_cached(repo, name, revision, None, roots = (live,)):
return None
return "other"
where = {name: _where(name) for name in files}
# A repo whose files STRADDLE the two roots cannot be handed to from_pretrained as one snapshot:
- # _prefetch_files returns no _base_local_dir in that state and the assembly is pinned to hub_cache_dir(), so
- # the old-root subset is invisible to it. Stage that subset instead, or the load re-pulls it inline past the
- # plan's own progress, cancel and disk preflight, and fails offline after a plan that reported nothing left
- # to do. A repo living entirely in the other root is fine, which is what reuse_other_cache_root is for. A
- # file that is missing everywhere will be downloaded INTO the live root, so it counts as live here: dropping
- # it would read a genuinely-mixed repo as unsplit and stage only the missing part, manufacturing the very
- # split this branch exists to avoid.
+ # _prefetch_files returns no _base_local_dir in that state and the assembly is pinned to hub_cache_dir(),
+ # so the old-root subset is invisible to it. Stage that subset instead, or the load re-pulls it inline
+ # past the plan's own progress, cancel and disk preflight, and fails offline after a plan that reported
+ # nothing left to do. A repo living entirely in the other root is fine. A file that is missing everywhere
+ # will be downloaded INTO the live root, so it counts as live here: dropping it would read a
+ # genuinely-mixed repo as unsplit and stage only the missing part, manufacturing the very split this
+ # branch exists to avoid.
split = {w or "live" for w in where.values()} == {"live", "other"}
missing = [n for n, w in where.items() if w is None or (split and w != "live")]
if not missing:
@@ -2921,9 +2833,9 @@ class DiffusionBackend:
checkpoint = True,
)
if base_files and not Path(base).expanduser().exists():
- # STAGED before the loader runs, so it must name the MIRROR: a gated upstream here 401s an anonymous user at
- # staging and the swap downstream is never reached. status(), the API base repo, saved configs and LoRA tags
- # keep the vendor id; sizes key on it too.
+ # STAGED before the loader runs, so it must name the MIRROR: a gated upstream here 401s an anonymous user
+ # at staging and the swap downstream is never reached. status(), the API base repo, saved configs and LoRA
+ # tags keep the vendor id; sizes key on it too.
if fetch_base != base and fetch_base not in revisions:
mirror_revision = self._current_sha(fetch_base, hf_token)
if mirror_revision:
@@ -2932,16 +2844,16 @@ class DiffusionBackend:
fetch_base,
base_files,
file_sizes.get(base, {}),
- # A pipeline pick has no single file: the base IS the selected model (base = repo_id above). Flagged
- # here rather than by comparing repo ids downstream, because the swap just above leaves this entry named
- # after the MIRROR. Under a GGUF or single-file pick the base is a companion, so it stays unflagged.
+ # A pipeline pick has no single file: the base IS the selected model. Flagged here rather than by
+ # comparing repo ids downstream, because the swap just above leaves this entry named after the MIRROR.
+ # Under a GGUF or single-file pick the base is a companion, so it stays unflagged.
checkpoint = kind == "pipeline",
)
if dit_prequant is not None:
# Staged, not just counted: _load_dense_quant_pipeline fetches this checkpoint during the load, under the
- # load lock and after the previous pipeline was evicted, so leaving it out means a multi-GB inline pull with
- # no progress, no cancel and no disk preflight. A companion of the checkpoint, never the selected model
- # itself.
+ # load lock and after the previous pipeline was evicted, so leaving it out means a multi-GB inline pull
+ # with no progress, no cancel and no disk preflight. A companion of the checkpoint, never the selected
+ # model itself.
prequant_repo, prequant_file, prequant_size = dit_prequant
add_missing_entry(prequant_repo, [prequant_file], {prequant_file: prequant_size})
if incompatible is None and allow_device_probe and memory_verdict:
@@ -2967,8 +2879,8 @@ class DiffusionBackend:
"checkpoint_bytes": checkpoint_bytes,
"incompatible_reason": incompatible,
# Companion discovery failed, so the file list above is partial. The UI stages what it can and the loader
- # pulls the rest inline; a caller that must not download at all has to treat this plan as unverified rather
- # than as nothing missing.
+ # pulls the rest inline; a caller that must not download at all has to treat this plan as unverified
+ # rather than as nothing missing.
"plan_failed": bool(plan_failures),
}
@@ -2979,12 +2891,10 @@ class DiffusionBackend:
revision: Optional[str] = None,
declared_sizes: Optional[dict[str, int]] = None,
) -> set[str]:
- """Return all ``files`` only when one cache root serves the whole pinned snapshot.
-
- A union across roots is not loadable as one snapshot. No revision is no verdict: the
- size-aware per-file probe may still accept an unchanged file after an unrelated repo
- commit, but this strict fast path never trusts a potentially stale local ``main`` ref.
- """
+ """Return all ``files`` only when one cache root serves the whole pinned snapshot. A union
+ across roots is not loadable as one snapshot. No revision is no verdict: the size-aware
+ per-file probe may still accept an unchanged file after an unrelated repo commit, but
+ this strict fast path never trusts a potentially stale local ``main`` ref."""
if not revision or not files:
return set()
try:
@@ -3042,9 +2952,9 @@ class DiffusionBackend:
"""Whether the LOAD will actually resolve a good copy, which is stricter than being cached
somewhere. ``reuse_other_cache_root`` only switches roots when the live lookup finds
nothing, so a stale live copy under the right name shadows a good one in the other root:
- the load reads the stale file, or refetches it inline, after a plan that saw the good copy
- and staged nothing. Presence in the live root is asked separately from validity, because
- presence alone is what that switch tests."""
+ the load reads the stale file, or refetches it inline, after a plan that saw the good
+ copy and staged nothing. Presence in the live root is asked separately from validity,
+ because presence alone is what that switch tests."""
live = hub_cache_dir()
if DiffusionBackend._hub_file_is_cached(
repo_id, filename, revision, expected_size, roots = (live,)
@@ -3066,25 +2976,22 @@ class DiffusionBackend:
expected_size: Optional[int] = None,
roots: Optional[tuple[Optional[str], ...]] = None,
) -> bool:
- """Whether ``filename`` is complete in either cache root the loader reuses.
-
- ``roots`` narrows the search; the default asks both, as the loader's own fetches do.
+ """Whether ``filename`` is complete in either cache root the loader reuses. ``roots`` narrows
+ the search; the default asks both, as the loader's own fetches do.
``try_to_load_from_cache`` is network-free. A pinned miss proves nothing: ``revision`` is
the REPO head, so an unrelated README commit can name a snapshot that a healthy weight was
- never downloaded into. In that case a size-corroborated local ``main`` hit is still valid.
+ never downloaded into, and a size-corroborated local ``main`` hit is still valid.
A pinned HIT is different: it proves the current file exists locally. The loader omits
- ``revision``, so it will open the snapshot selected by the local ``main`` ref. We may omit
- the file from the staged plan only when that unpinned lookup resolves to the SAME snapshot
- path. Otherwise a stale main ref would make the plan bless the current explicit-SHA copy
- while the loader opens an older one (or revalidates inline outside the manager).
-
- Every hit is also corroborated with the size declared by the same Hub lookup. A different
- size means the file was republished or damaged and must be fetched through the manager.
-
- A string alone is not enough on Windows, where a broken snapshot link can survive a
- cancelled download, so the target must still be a real file.
+ ``revision``, so it will open the snapshot selected by the local ``main`` ref, and we may
+ omit the file only when that unpinned lookup resolves to the SAME snapshot path. Otherwise a
+ stale main ref would make the plan bless the current explicit-SHA copy while the loader
+ opens an older one.
+
+ Every hit is also corroborated with the size declared by the same Hub lookup. A string alone
+ is not enough on Windows, where a broken snapshot link can survive a cancelled download, so
+ the target must still be a real file.
"""
try:
from huggingface_hub import try_to_load_from_cache
@@ -3096,10 +3003,10 @@ class DiffusionBackend:
return value if isinstance(value, str) and Path(value).is_file() else None
def sound(hit: str) -> bool:
- """A hit is only proof if it also has the declared bytes. Naming the right commit
- is not enough: a truncated or half-copied file can sit at that path (Windows has
- no symlink to keep the blob out of it), and trusting the ref alone hands the load
- a damaged cache entry it fails on, instead of restaging it through the manager."""
+ """A hit is only proof if it also has the declared bytes. Naming the right commit is
+ not enough: a truncated or half-copied file can sit at that path (Windows has no
+ symlink to keep the blob out of it), and trusting the ref alone hands the load a
+ damaged cache entry it fails on, instead of restaging it through the manager."""
if not expected_size or expected_size <= 0:
return True # nothing declared to check against; trust the ref
try:
@@ -3136,24 +3043,21 @@ class DiffusionBackend:
@staticmethod
def _hub_cache_repo_dir(repo_id: str) -> Path:
- """Local HF hub cache dir for ``repo_id``.
-
- Reads the live setting, not huggingface_hub's import-time constant: changing the
- cache folder does not update the constant, so the old one would count bytes in a
- root the download no longer writes to (progress stuck at 0 for the whole pull)."""
+ """Local HF hub cache dir for ``repo_id``. Reads the live setting, not huggingface_hub's
+ import-time constant: changing the cache folder does not update the constant, so the old
+ one would count bytes in a root the download no longer writes to (progress stuck at 0 for
+ the whole pull)."""
return Path(hub_cache_dir()) / f"models--{repo_id.replace('/', '--')}"
@staticmethod
def _hub_cache_repo_dirs(repo_id: str) -> list[Path]:
"""``repo_id``'s cache dir under EVERY root a load can resolve it through, live root first.
-
- The loader reuses a file cached only under huggingface_hub's import-time root
- (``reuse_other_cache_root``, and the gated preflight excuses a base off it), so after a
- cache-folder change the bytes the load reads are not in the live root at all and sizing that
- root alone reads zero. The constant is read HERE, never bound at import: it is what
+ The loader reuses a file cached only under huggingface_hub's import-time root, so after a
+ cache-folder change the bytes the load reads are not in the live root at all and sizing
+ that root alone reads zero. The constant is read HERE, never bound at import: it is what
``cache_dir = None`` resolves to, and tests move it."""
- # One read of the live root: it is a setting, and load_progress polls this from another thread, so a second read
- # could compare the new root against a `live` built from the old.
+ # One read of the live root: it is a setting, and load_progress polls this from another thread, so a second
+ # read could compare the new root against a `live` built from the old.
live_root = hub_cache_dir()
folder = f"models--{repo_id.replace('/', '--')}"
live = Path(live_root) / folder
@@ -3175,12 +3079,10 @@ class DiffusionBackend:
@staticmethod
def _live_snapshot_dir(repo_dir: Path) -> Optional[Path]:
"""The snapshot ``refs/main`` names: the ONE revision a load reads out of this root.
-
- ``try_to_load_from_cache`` (what the per-file root reuse probes with) defaults to ``main``
- and resolves it through ``refs/main``, so this is exactly the tree the loader will read.
- None when the cache does not say -- no ref file (a revision pinned to a commit hash never
- writes one), unreadable, or the snapshot it names is gone. Callers then read the whole root:
- a cache we cannot scope must still report its bytes, never zero."""
+ ``try_to_load_from_cache`` defaults to ``main`` and resolves it through ``refs/main``, so
+ this is exactly the tree the loader will read. None when the cache does not say (no ref
+ file, unreadable, or the snapshot it names is gone); callers then read the whole root,
+ since a cache we cannot scope must still report its bytes."""
try:
rev = (repo_dir / "refs" / "main").read_text(encoding = "utf-8").strip()
except (OSError, ValueError):
@@ -3198,13 +3100,13 @@ class DiffusionBackend:
Scoped per root to the revision that root serves (``refs/main``), because ``blobs/`` is
append-only: a republished repo keeps the superseded revision's blobs forever under
different etags, so summing the whole dir counts a stale full copy on top of the live
- partial one and ``load_progress`` reports "finalizing" through the rest of a multi-GB pull.
- The in-flight ``blobs/*.incomplete`` still counts: those are this download's own bytes, and
- dropping them would freeze the bar for the length of each shard.
+ partial one and ``load_progress`` reports finalizing through the rest of a multi-GB pull.
+ The in-flight ``blobs/*.incomplete`` still counts: those are this download's own bytes.
Keyed by blob filename, not summed per root: a blob is named after the file's etag, so a
copy present in both roots counts once. Scanning only the live root reports 0 for a load a
- moved cache serves entirely off disk, pinning the progress bar near 0%."""
+ moved cache serves entirely off disk.
+ """
sizes: dict[str, int] = {}
def _add(key: str, path: Path) -> None:
@@ -3242,8 +3144,8 @@ class DiffusionBackend:
@staticmethod
def _local_dir_weight_sizes(path: Path, *, exclude_transformer: bool) -> dict[str, int]:
- """``{relative path: on-disk bytes}`` for the weight files under a diffusers directory.
- Per file, not a total, so callers merging several trees can dedupe by path. See
+ """``{relative path: on-disk bytes}`` for the weight files under a diffusers directory. Per
+ file, not a total, so callers merging several trees can dedupe by path. See
``_local_dir_weight_bytes`` for what the filter is for."""
sizes: dict[str, int] = {}
for f in path.rglob("*"):
@@ -3263,12 +3165,11 @@ class DiffusionBackend:
@staticmethod
def _local_dir_weight_bytes(path: Path, *, exclude_transformer: bool) -> int:
- """Sum the on-disk weight files under a local diffusers directory. The HF blob
- cache is empty for a local path, so this is the only size signal for auto memory
- planning; without it a large local model folds to zero and the planner skips
- offload and OOMs. ``exclude_transformer`` drops the ``transformer/`` subfolder
- for GGUF/single-file loads (their transformer is the single file, not resident
- here); a full pipeline load keeps it (the whole repo is resident)."""
+ """Sum the on-disk weight files under a local diffusers directory. The HF blob cache is
+ empty for a local path, so this is the only size signal for auto memory planning; without
+ it a large local model folds to zero and the planner skips offload and OOMs.
+ ``exclude_transformer`` drops the ``transformer/`` subfolder for GGUF/single-file loads;
+ a full pipeline load keeps it."""
return sum(
DiffusionBackend._local_dir_weight_sizes(
path, exclude_transformer = exclude_transformer
@@ -3285,14 +3186,13 @@ class DiffusionBackend:
read ``base`` from. 0 when nothing is cached.
``fn`` maps a directory to ``{relative path: count}`` so the merge happens per FILE. The
- candidates are every cached snapshot revision under EVERY cache root, plus ``staged_dir``
- (the snapshot the prefetch/preflight handed back). Both roots, because the loader's per-file
- root reuse makes them disjoint PARTS of one repo rather than copies: a text encoder left in
- the old snapshot and a VAE prefetched into the live one both load, and taking the larger
- total would budget only one -- under-counting leaves an auto plan resident and OOMing on
- weights it never counted. Keying on the relative path keeps genuine copies safe too (a file
- mirrored in two roots still counts once, at its largest) and makes the staged dir purely
- additive, so a partial snapshot cannot erase what a root does hold."""
+ candidates are every cached snapshot revision under EVERY cache root, plus ``staged_dir``.
+ Both roots, because the loader's per-file root reuse makes them disjoint PARTS of one repo
+ rather than copies: a text encoder left in the old snapshot and a VAE prefetched into the
+ live one both load, and taking the larger total would budget only one, leaving an auto plan
+ resident and OOMing on weights it never counted. Keying on the relative path keeps genuine
+ copies safe too and makes the staged dir purely additive.
+ """
local = Path(base).expanduser()
if local.is_dir():
return sum(fn(local).values())
@@ -3319,12 +3219,11 @@ class DiffusionBackend:
@staticmethod
def _companion_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:
- """Resident companion (VAE + text-encoder) size for the memory plan.
-
- Excludes ``transformer/`` (supplied by the GGUF/single file, not resident here) --
- otherwise the dense-quant prefetch's cached transformer shards would inflate this
- and wrongly force offload. Walks the snapshot dir, not the flat ``blobs/`` cache,
- since only the snapshot preserves the subfolder split needed to exclude it."""
+ """Resident companion (VAE + text-encoder) size for the memory plan. Excludes
+ ``transformer/`` (supplied by the GGUF/single file, not resident here), otherwise the
+ dense-quant prefetch's cached transformer shards would inflate this and wrongly force
+ offload. Walks the snapshot dir, not the flat ``blobs/`` cache, since only the snapshot
+ preserves the subfolder split needed to exclude it."""
return DiffusionBackend._union_over_cached_revs(
base,
lambda d: DiffusionBackend._local_dir_weight_sizes(d, exclude_transformer = True),
@@ -3335,10 +3234,8 @@ class DiffusionBackend:
def _local_dir_text_encoder_sizes(path: Path) -> dict[str, int]:
"""``{relative path: on-disk bytes}`` for the TEXT-ENCODER weight files under a diffusers
directory: the ``text_encoder*`` subfolders of what ``_local_dir_weight_sizes`` returns.
-
- Derived from that same walk rather than a second one, so the text-encoder term is a strict
- subset of the companion term the planner subtracts it from. Deriving it independently could
- make the subtraction go negative on a tree where one walk saw a file the other did not."""
+ Derived from that same walk rather than a second one, so the text-encoder term is a
+ strict subset of the companion term the planner subtracts it from."""
return {
rel: size
for rel, size in DiffusionBackend._local_dir_weight_sizes(
@@ -3351,10 +3248,9 @@ class DiffusionBackend:
@staticmethod
def _text_encoder_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:
"""Text-encoder size for the memory plan: the share of ``_companion_cache_bytes`` the
- planner can move off the resident floor by streaming the encoders.
-
- Same union-over-cache-roots merge as the companion total, keyed on the same relative
- paths, so a repo split across two roots is counted once in BOTH terms."""
+ planner can move off the resident floor by streaming the encoders. Same
+ union-over-cache-roots merge as the companion total, keyed on the same relative paths, so
+ a repo split across two roots is counted once in BOTH terms."""
return DiffusionBackend._union_over_cached_revs(
base,
DiffusionBackend._local_dir_text_encoder_sizes,
@@ -3363,8 +3259,8 @@ class DiffusionBackend:
@staticmethod
def _safetensors_param_count(path: Path) -> int:
- """Total tensor elements in a safetensors file, read from its JSON header without
- touching the tensor data. 0 on any read/parse failure."""
+ """Total tensor elements in a safetensors file, read from its JSON header without touching
+ the tensor data. 0 on any read/parse failure."""
try:
with open(path, "rb") as fh:
header_len = int.from_bytes(fh.read(8), "little")
@@ -3385,12 +3281,11 @@ class DiffusionBackend:
def _dense_transformer_resident_bytes(base: str, staged_dir: Optional[str] = None) -> int:
"""Resident bf16 size of the base repo's dense ``transformer/`` for the dense-quant
preflight. That fast path loads the transformer at the compute dtype (bf16, 2
- bytes/param) before quantizing, so budget num_params * 2 -- NOT the on-disk bytes,
- which for an F32 base (e.g. Z-Image) are ~2x the resident size. Read from the
- safetensors shard headers. Returns 0 when no ``transformer/*.safetensors`` shards
- are present (an uncached base, or a .bin-only transformer); the caller then gates
- the fast path on the plain plan -- so a base whose shards this misses skips the fit
- check entirely and lets the dense build OOM under a plan sized for the GGUF."""
+ bytes/param) before quantizing, so budget num_params * 2, NOT the on-disk bytes, which
+ for an F32 base are ~2x the resident size. Read from the safetensors shard headers.
+ Returns 0 when no ``transformer/*.safetensors`` shards are present; the caller then gates
+ the fast path on the plain plan, so a base whose shards this misses skips the fit check
+ entirely and lets the dense build OOM under a plan sized for the GGUF."""
def _params(d: Path) -> dict[str, int]:
tdir = d / "transformer"
@@ -3403,8 +3298,6 @@ class DiffusionBackend:
return DiffusionBackend._union_over_cached_revs(base, _params, staged_dir) * 2
- # ── Synchronous load / generate / unload ───────────────────────────────
-
def load_pipeline(
self,
repo_id: str,
@@ -3458,21 +3351,20 @@ class DiffusionBackend:
base = (
repo_id if kind == "pipeline" else _resolve_base_repo(repo_id, base_repo, fam, hf_token)
)
- # ``base`` stays the UPSTREAM id every report and table lookup keys on; ``fetch_base`` is the only id handed to
- # something that downloads. One decision per load (the background path took it before staging), so nothing
- # stages one repo and assembles from the other.
+ # ``base`` stays the UPSTREAM id every report and table lookup keys on; ``fetch_base`` is the only id handed
+ # to something that downloads. One decision per load, so nothing stages one repo and assembles from the other.
fetch_base = _fetch_base or prefer_ungated_mirror(base, hf_token)
target = self._target_for_ordinal(fam, gpu_ordinal)
- # A dedicated worker thread, so the pin is permanent and everything downstream -- the placement, the offload
- # budget, the un-indexed state.device -- lands on the same card.
+ # A dedicated worker thread, so the pin is permanent and everything downstream (the placement, the offload
+ # budget, the un-indexed state.device) lands on the same card.
apply_diffusion_device_ordinal(target)
device, dtype = target.device, target.dtype
import diffusers
- # diffusers hard-codes _tqdm_active = True at import and honours no env var, so setup_logging (which runs long
- # before this lazy import) cannot reach it. Without this, "Loading pipeline components..." is drawn straight
- # onto the log stream and can land mid-record on a structlog JSON line. Idempotent and cheap.
+ # diffusers hard-codes _tqdm_active = True at import and honours no env var, so setup_logging cannot reach it.
+ # Without this, "Loading pipeline components..." is drawn straight onto the log stream and can land mid-record
+ # on a structlog JSON line. Idempotent and cheap.
from loggers.config import quiet_third_party_progress_bars
quiet_third_party_progress_bars()
@@ -3513,8 +3405,8 @@ class DiffusionBackend:
else None
)
# A renamed or hand-picked FLUX.2 GGUF can still land on a different-size base, and no name-based rule
- # catches that. Say so here, naming the file and the repo, rather than letting the GGUF quantizer raise
- # a bare shape mismatch.
+ # catches that. Say so here, naming the file and the repo, rather than letting the GGUF quantizer
+ # raise a bare shape mismatch.
assert_flux2_gguf_matches_base(fam, base, single_file_path)
transformer_cls = getattr(diffusers, fam.transformer_class)
pipeline_cls = getattr(diffusers, fam.pipeline_class)
@@ -3534,13 +3426,12 @@ class DiffusionBackend:
base_local_dir = _base_local_dir,
fetch_base = fetch_base,
)
- # On unified memory the plan above is final -- the quant re-plans below are CUDA-only -- and its 'none'
+ # On unified memory the plan above is final (the quant re-plans below are CUDA-only) and its 'none'
# policy is a placement, not a fit. Refuse here, after the eviction above freed the previous pipeline
- # (so the free reading is the memory this load gets) and before any weight is materialised. A pipeline's
- # weight term is cached SHARD bytes, which is a download size, not a resident one: Z-Image and Lumina
- # ship fp32 shards that halve when loaded as bf16 (the size table records 24.6 GB of Z-Image shards as
- # 12.3 GB resident). Refusing on the download figure would turn away a load that fits, so judge the
- # refusal against the table's resident total whenever it knows this base.
+ # and before any weight is materialised. A pipeline's weight term is cached SHARD bytes, which is a
+ # download size, not a resident one: some families ship fp32 shards that halve when loaded as bf16.
+ # Refusing on the download figure would turn away a load that fits, so judge the refusal against the
+ # table's resident total whenever it knows this base.
raise_on_unified_memory_shortfall(
self._resident_sized_plan(
plan, fam, base, target, kind, text_encoder_quant = text_encoder_quant
@@ -3550,7 +3441,7 @@ class DiffusionBackend:
)
# The caller's RAW request, captured before the tri-state below rewrites it: status has to be able to
- # say "you asked for fp8" long after the loader declined it.
+ # say you asked for fp8 long after the loader declined it.
transformer_quant_requested = transformer_quant
# Dtype tri-state: unset/"auto" -> hardware ladder; "none"/"off" pins GGUF-as-is; an explicit scheme
# pins it.
@@ -3611,14 +3502,13 @@ class DiffusionBackend:
# repo's transformer/ shards, since the fallback would pull them HERE, inside the load lock, after
# eviction, where unload cannot preempt it and progress already reported 100%.
dense_fallback_allowed = bool(_transformer_prefetched)
- # A GGUF pick with the scheme left to us: the hosted pre-quant is free only while already cached, since
- # fetching it means a SECOND multi-GB denoiser and the GGUF never runs. An explicit scheme, a LoRA bake
- # and every non-GGUF kind keep today's behaviour, where the prequant IS the point. An all-zero-weight
- # list is not a bake.
+ # A GGUF pick with the scheme left to us: the hosted pre-quant is free only while already cached,
+ # since fetching it means a SECOND multi-GB denoiser and the GGUF never runs. An explicit scheme, a
+ # LoRA bake and every non-GGUF kind keep today's behaviour. An all-zero-weight list is not a bake.
baking_loras = _has_active_lora(loras)
- # ... and only while a scheme is still ENABLED. An explicit Speed=off rewrites an auto request to "off"
- # above and the plan stages no transformer/ on purpose, so without this the deliberate bit-exact GGUF
- # was reported as a quant declined for want of shards, in the status payload and in the log.
+ # ... and only while a scheme is still ENABLED. An explicit Speed=off rewrites an auto request to
+ # "off" above and the plan stages no transformer/ on purpose, so without this the deliberate bit-exact
+ # GGUF was reported as a quant declined for want of shards.
if (
kind == "gguf"
and transformer_quant_auto
@@ -3649,25 +3539,22 @@ class DiffusionBackend:
"cached, and an auto quant never downloads a second transformer for "
"a GGUF pick"
)
- # The other half of the same rule, and the half the prefetch decides: ``_transformer_prefetched`` is
- # False exactly when the plan left the base repo's transformer/ shards out, so taking the dense path
- # here would pull them from_pretrained() under the load lock, after eviction, where unload cannot
- # preempt it and progress already reported 100%. Declining keeps the GGUF the user picked, which is
- # on disk. Only when the fast path's candidate IS the dense base, though. A CACHED pre-quant stages
- # no transformer/ shards either -- the plan skips them because the small quantised checkpoint
- # replaces them, not because anything would have to be downloaded -- so reading the empty stage as a
- # verdict here would drop a fast path that costs nothing. The branch above already sent every
- # UNCACHED pre-quant to the GGUF, so what reaches here is free. A lower auto rung whose checkpoint
- # is already cached counts as well. Auto's winner having no hosted prequant does not mean there is
- # none to open: fp8 winning while only an int8 checkpoint is published is exactly what the retry
- # below exists for, and declining here would skip past it to the GGUF for a checkpoint that costs
- # nothing. That retry only ever returns a CACHED rung. ... and only on a host where staging those
- # shards could have enabled the quant at all. The unsupported-device checks above run for an
- # EXPLICIT scheme only, so on CPU/MPS, non-bf16 CUDA, a stubbed torchao, or a family this GPU rules
- # out, an AUTO request reached here and was told its shards were not staged -- which is true and
- # irrelevant, since caching them changes nothing. The outcome is the GGUF either way (the re-plan
- # below is gated on dense_transformer_supported), so this is only about not printing a wrong reason
- # on the badge for every Mac and CPU load.
+ # The other half of the same rule, and the half the prefetch decides: ``_transformer_prefetched``
+ # is False exactly when the plan left the base repo's transformer/ shards out, so taking the dense
+ # path here would pull them under the load lock, after eviction. Declining keeps the GGUF the user
+ # picked, which is on disk.
+ # Only when the fast path's candidate IS the dense base, though. A CACHED pre-quant stages no
+ # transformer/ shards either, because the small quantised checkpoint replaces them rather than
+ # because anything would have to be downloaded, so reading the empty stage as a verdict would drop
+ # a fast path that costs nothing. The branch above already sent every UNCACHED pre-quant to the
+ # GGUF. A lower auto rung whose checkpoint is already cached counts as well: fp8 winning while
+ # only an int8 checkpoint is published is exactly what the retry below exists for, and that retry
+ # only ever returns a CACHED rung.
+ # And only on a host where staging those shards could have enabled the quant at all. The
+ # unsupported-device checks above run for an EXPLICIT scheme only, so on CPU/MPS, non-bf16 CUDA, a
+ # stubbed torchao, or a family this GPU rules out, an AUTO request reached here and was told its
+ # shards were not staged, which is true and irrelevant. The outcome is the GGUF either way, so
+ # this is only about not printing a wrong reason on the badge.
elif (
not _transformer_prefetched
and dense_transformer_supported(target)
@@ -3723,12 +3610,10 @@ class DiffusionBackend:
logger = logger,
)
- # Defined OUTSIDE the candidate check: the retry below rebinds ``candidate`` and calls this, and
- # that retry is reached precisely when the first resolve returned None (a free-disk gate
- # skipping the dense download while a lower cached prequant still passes). Nested, the name
- # would be unbound there and the retry would raise UnboundLocalError under the load lock instead
- # of loading the cached rung. Reads ``candidate`` at CALL time, so every call still sizes
- # whichever candidate is current.
+ # Defined OUTSIDE the candidate check: the retry below rebinds ``candidate`` and calls this,
+ # and that retry is reached precisely when the first resolve returned None. Nested, the name
+ # would be unbound there and the retry would raise UnboundLocalError under the load lock.
+ # Reads ``candidate`` at CALL time, so every call still sizes whichever candidate is current.
def _replan_candidate():
return self._plan_memory(
target,
@@ -3746,8 +3631,8 @@ class DiffusionBackend:
# Pass the companion estimate so prefetched base shards aren't double-counted.
companion_override_mib = candidate.companions_mib,
# ... and its text-encoder share, so the planner can still price the streamed-encoder
- # group tier on this path. getattr: a candidate without the split (a duck-typed or older
- # estimate) passes None and keeps the previous decision.
+ # group tier on this path. getattr: a candidate without the split passes None and
+ # keeps the previous decision.
text_encoder_override_mib = getattr(
candidate, "text_encoders_mib", None
),
@@ -3772,8 +3657,8 @@ class DiffusionBackend:
and plan_fits_total_capacity(replanned)
):
# The candidate fits TOTAL capacity but instantaneous free said no, so re-snapshot
- # (settled) and replan once rather than letting a transient foreign allocation force the
- # GGUF fallback.
+ # (settled) and replan once rather than letting a transient foreign allocation force
+ # the GGUF fallback.
replanned = _replan_candidate()
if replanned.offload_policy != OFFLOAD_NONE:
logger.info(
@@ -3795,16 +3680,15 @@ class DiffusionBackend:
)
if replanned.offload_policy == OFFLOAD_NONE:
quant_plan = replanned
- # The GGUF plan declined resident; a prequant-sized replan says nothing about the dense
- # build
+ # The GGUF plan declined resident; a prequant-sized replan says nothing about the
+ # dense build
if candidate.prequant:
dense_fallback_allowed = False
if quant_plan is None:
# Nothing resident for auto's WINNER, either because it has no candidate at all or because
# its replan still offloads. Without this the load leaves quant_plan unset and the gate
# below skips the dense/prequant path entirely, so a lower rung whose checkpoint is CACHED
- # and would fit never gets looked at. Same retry as the resident branch, just reached from
- # the side where the GGUF plan already wanted offload.
+ # and would fit never gets looked at.
retry = self._auto_prequant_retry_scheme(
target,
fam,
@@ -3852,8 +3736,8 @@ class DiffusionBackend:
transformer_quant, # normalized above
family = getattr(fam, "name", None),
)
- # usable_prequant_source (not resolve_): a missing/non-allowlisted local path must not skip the
- # dense-fit re-check
+ # usable_prequant_source (not resolve_): a missing/non-allowlisted local path must not skip
+ # the dense-fit re-check
prequant = (
# A LoRA bake skips the prequant shortcut, so gate the fast path as if no prequant existed
None
@@ -3867,9 +3751,10 @@ class DiffusionBackend:
if scheme is not None
else None
)
- # Reads the cache, so it looks where the prefetch WROTE (the mirror when one was swapped in) and
- # carries the staged snapshot: a base served wholly from the import-time root sizes as 0 on the
- # hub id alone, and a 0 skips this fit check, landing the dense build under a GGUF-sized plan.
+ # Reads the cache, so it looks where the prefetch WROTE (the mirror when one was swapped in)
+ # and carries the staged snapshot: a base served wholly from the import-time root sizes as 0
+ # on the hub id alone, and a 0 skips this fit check, landing the dense build under a
+ # GGUF-sized plan.
dense_mib = int(
self._dense_transformer_resident_bytes(fetch_base, _base_local_dir)
// (1024 * 1024)
@@ -3891,15 +3776,15 @@ class DiffusionBackend:
repo_id = repo_id,
fetch_base = fetch_base,
transformer_resident_override_mib = dense_mib,
- # No companion_override here, so this one reads the cache: point it at the snapshot the
- # load will read, not the live root alone.
+ # No companion_override here, so this one reads the cache: point it at the snapshot
+ # the load will read, not the live root alone.
base_local_dir = _base_local_dir,
)
- # On unified memory the policy cannot express a misfit -- the planner returns 'none' for ANY
- # size there, because offload shuffles bytes within one pool -- so the check above never
+ # On unified memory the policy cannot express a misfit (the planner returns 'none' for ANY
+ # size there, because offload shuffles bytes within one pool) so the check above never
# fires and the dense build proceeds to be OS-killed. Size it explicitly instead, and
- # decline to the packed GGUF (which already passed the load-level refusal) rather than
- # raising: a fallback that fits is better than no load at all.
+ # decline to the packed GGUF rather than raising: a fallback that fits is better than no
+ # load at all.
unified_shortfall = unified_memory_shortfall_message(
dense_plan, family = getattr(fam, "name", None)
)
@@ -3919,11 +3804,11 @@ class DiffusionBackend:
f"'{dense_plan.offload_policy}' offload)"
)
elif not _transformer_prefetched:
- # dense_mib == 0 with nothing staged is not "no information": the prefetch's capacity gate
- # DECLINED the base transformer/ shards, so the dense bf16 build cannot run at all. Reading
- # it as unknown and skipping the retry left the regression alive on the fresh Qwen cache
- # this was written for: fp8 wins, only int8 is published, the load runs fp8 with no prequant
- # and no dense fallback, and drops straight to GGUF.
+ # dense_mib == 0 with nothing staged is not no information: the prefetch's capacity gate
+ # DECLINED the base transformer/ shards, so the dense bf16 build cannot run at all.
+ # Reading it as unknown and skipping the retry left the regression alive: fp8 wins, only
+ # int8 is published, the load runs fp8 with no prequant and no dense fallback, and drops
+ # straight to GGUF.
dense_possible = False
dense_decline_reason = (
"the base transformer this quant is built from was not staged (the "
@@ -3933,10 +3818,9 @@ class DiffusionBackend:
# A hosted prequant never builds dense, so the check above says nothing about what lands. On
# unified memory that gap is a hole: the OFFLOAD_NONE gate below is satisfied for ANY size
# there, and an fp8/int8 artifact can outweigh the packed GGUF that just passed the load-level
- # refusal (0.55x bf16 against a Q4's ~0.3x), so the load would materialise an unsized
- # transformer and be OS-killed. Size the artifact itself and decline to the GGUF when it does
- # not fit. Unified only: off it, the OFFLOAD_NONE test already carries this and the extra
- # resolve is waste.
+ # refusal, so the load would materialise an unsized transformer and be OS-killed. Size the
+ # artifact itself and decline to the GGUF when it does not fit. Unified only: off it, the
+ # OFFLOAD_NONE test already carries this.
if (
prequant is not None
and getattr(plan.device_memory, "memory_kind", None) == "unified_memory"
@@ -3968,8 +3852,8 @@ class DiffusionBackend:
),
# companions_mib is the DENSE encoder plus the VAE, but assembly is handed
# text_encoder_quant and injects the pre-cast encoder when one is configured.
- # Price that share the way the load-level plan does, or a footprint that fits is
- # declined on bytes never materialised.
+ # Price that share the way the load-level plan does, or a footprint that fits
+ # is declined on bytes never materialised.
companion_override_mib = (
self._precast_scaled_companions_mib(
prequant_candidate,
@@ -4002,7 +3886,7 @@ class DiffusionBackend:
# still have picked a DIFFERENT scheme that does have a hosted checkpoint. auto returns one
# winner, and a winner with no published prequant that also cannot build dense would drop the
# whole pick to GGUF even though a lower rung would have loaded. Only for auto: an explicit
- # scheme is never swapped (same contract as select_transformer_quant_scheme).
+ # scheme is never swapped.
if not dense_possible and prequant is None:
retry = self._auto_prequant_retry_scheme(
target,
@@ -4015,8 +3899,8 @@ class DiffusionBackend:
)
# Existence is not fit: an int8 checkpoint can outweigh the Q4 GGUF that planned resident,
# so a host that fits the GGUF need not fit the rung being retried. Size it and replan,
- # exactly as the offload branch does, or the load moves it onto CUDA after eviction under a
- # GGUF-sized budget and OOMs there.
+ # exactly as the offload branch does, or the load moves it onto CUDA after eviction under
+ # a GGUF-sized budget and OOMs there.
retry_candidate = (
resolve_dense_quant_candidate(
fam = fam,
@@ -4059,8 +3943,8 @@ class DiffusionBackend:
if (
retry_plan is not None
and retry_plan.offload_policy == OFFLOAD_NONE
- # Same unified caveat as above: 'none' is not a fit there, so the rung being retried has
- # to be sized explicitly before it is pinned.
+ # Same unified caveat as above: 'none' is not a fit there, so the rung being retried
+ # has to be sized explicitly before it is pinned.
and unified_memory_shortfall_message(
retry_plan, family = getattr(fam, "name", None)
)
@@ -4077,10 +3961,10 @@ class DiffusionBackend:
quant_plan = retry_plan
dense_fallback_allowed = False
else:
- # No prequant source and no retry rung that fits: the fast path is out, so say which of
- # the two halves failed. The reason reaches the caller as the 409 detail on an explicit
- # pin, and as the "Auto: OFF" badge otherwise, so "no hosted checkpoint" alone would
- # leave a user who has one wondering why it was ignored.
+ # No prequant source and no retry rung that fits: the fast path is out, so say which
+ # of the two halves failed. The reason reaches the caller as the 409 detail on an
+ # explicit pin, and as the "Auto: OFF" badge otherwise, so "no hosted checkpoint"
+ # alone would leave a user who has one wondering why it was ignored.
dense_declined = True
transformer_quant_decline = (
f"{dense_decline_reason}, and no hosted pre-quantised "
@@ -4122,14 +4006,15 @@ class DiffusionBackend:
)
pipe = None
transformer_quant_engaged = None
- # Formatted BEFORE the del below, and redacted: this reaches the client both as a status tooltip
- # and (for an explicit ask) as the refusal message.
+ # Formatted BEFORE the del below, and redacted: this reaches the client both as a status
+ # tooltip and (for an explicit ask) as the refusal message.
from utils.native_path_leases import redact_native_paths
transformer_quant_decline = redact_native_paths(
f"the quantised transformer build failed ({exc})"
)
- # Drop the exception before clearing the cache: its traceback pins the dense transformer's VRAM.
+ # Drop the exception before clearing the cache: its traceback pins the dense transformer's
+ # VRAM.
del exc
try:
clear_gpu_cache()
@@ -4145,8 +4030,8 @@ class DiffusionBackend:
and normalize_transformer_quant(transformer_quant) is not None
and _has_active_lora(loras)
):
- # Adapters were requested BAKED but that build failed, and the GGUF fallback cannot carry them; fail
- # loudly.
+ # Adapters were requested BAKED but that build failed, and the GGUF fallback cannot carry them;
+ # fail loudly.
raise RuntimeError(
"The requested LoRA adapters could not be applied: baking adapters "
"requires the quantized (int8/fp8) transformer build, which was "
@@ -4155,10 +4040,10 @@ class DiffusionBackend:
"adapters, free VRAM, or pick a smaller model."
)
- # Fail closed on a declined EXPLICIT precision. Loading the GGUF here produced a perfectly good image at
- # a precision the caller never asked for, and nothing in the response said so, which is why a successful
- # render could not be taken as proof the requested precision ran. `auto` is untouched: falling down the
- # ladder is what it asks for.
+ # Fail closed on a declined EXPLICIT precision. Loading the GGUF here produced a perfectly good image
+ # at a precision the caller never asked for, and nothing in the response said so, which is why a
+ # successful render could not be taken as proof the requested precision ran. `auto` is untouched:
+ # falling down the ladder is what it asks for.
if (
pipe is None
and transformer_quant_pinned is not None
@@ -4177,9 +4062,9 @@ class DiffusionBackend:
if pipe is None:
if kind == "pipeline":
if fam.name == KREA2_FAMILY_NAME:
- # krea ships transformers-5.x configs the 4.x line cannot parse, so assemble per-component;
- # that path never sees pipe_kwargs, so pass the pre-cast TE. Fetches EVERY component from
- # the id given, so it must get the mirror.
+ # krea ships transformers-5.x configs the 4.x line cannot parse, so assemble
+ # per-component; that path never sees pipe_kwargs, so pass the pre-cast TE. Fetches EVERY
+ # component from the id given, so it must get the mirror.
pipe = load_krea2_pipeline(
fetch_base,
dtype,
@@ -4211,7 +4096,8 @@ class DiffusionBackend:
if hf_token:
pipe_kwargs["token"] = hf_token
if fam.name == HIDREAM_FAMILY_NAME:
- # The repo names a Llama text_encoder_4 it does not ship; supply it from the open mirror
+ # The repo names a Llama text_encoder_4 it does not ship; supply it from the open
+ # mirror
pipe_kwargs.update(
hidream_te4_kwargs(
dtype,
@@ -4236,17 +4122,19 @@ class DiffusionBackend:
local_files_only = local_files_only,
)
)
- # The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1 otherwise)
+ # The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1
+ # otherwise)
pipe = pipeline_cls.from_pretrained(
_base_local_dir or fetch_base, **pipe_kwargs
)
elif kind == "single_file" and fam.single_file_is_pipeline:
- # A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline class
- # with ``config`` on the base repo.
+ # A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline
+ # class with ``config`` on the base repo.
sf_pipe_kwargs: dict[str, Any] = {
"local_files_only": local_files_only,
"torch_dtype": dtype,
- # ``config`` is a REPO FETCH ahead of the mirrored load, so a gated id would 401 here first
+ # ``config`` is a REPO FETCH ahead of the mirrored load, so a gated id would 401 here
+ # first
"config": fetch_base,
"cache_dir": hub_cache_dir(),
}
@@ -4261,9 +4149,9 @@ class DiffusionBackend:
"subfolder": "transformer",
"token": hf_token,
"cache_dir": hub_cache_dir(),
- # config is a REPO ID, and diffusers forwards this into the load_config() that resolves it
- # (single_file_model.py), so without the flag this branch reaches the Hub on a load nobody
- # asked for. The pipeline assembly below was already guarded; this call was not.
+ # config is a REPO ID, and diffusers forwards this into the load_config() that resolves
+ # it, so without the flag this branch reaches the Hub on a load nobody asked for. The
+ # pipeline assembly below was already guarded; this call was not.
"local_files_only": local_files_only,
}
if kind == "gguf":
@@ -4286,7 +4174,8 @@ class DiffusionBackend:
hf_token = hf_token,
transformer = transformer,
# Same reason as the full-pipeline branch: the single file supplies only the denoiser,
- # so the encoder, VAE and tokenizer below are still GB this load promised not to fetch.
+ # so the encoder, VAE and tokenizer below are still GB this load promised not to
+ # fetch.
local_files_only = local_files_only,
text_encoder = te_prequant_pipe_kwargs(
fam,
@@ -4367,9 +4256,8 @@ class DiffusionBackend:
logger = logger,
target = target,
)
- # Step caching (First-Block-Cache), also before compile: reuses the transformer tail across steps (~1.4x
- # on Flux, LPIPS ~0.08) and drops compile fullgraph. Tri-state: unset/auto -> FBCACHE_MIN_STEPS policy;
- # off/fbcache pinned.
+ # Step caching (First-Block-Cache), also before compile: reuses the transformer tail across steps and
+ # drops compile fullgraph. Tri-state: unset/auto -> FBCACHE_MIN_STEPS policy; off/fbcache pinned.
cache_request = normalize_transformer_cache(transformer_cache)
cache_auto = transformer_cache is None or cache_request == TC_AUTO
cache_quant_active = transformer_quant_engaged is not None or bool(gguf_filename)
@@ -4407,8 +4295,8 @@ class DiffusionBackend:
else:
cache_reason = "requested"
# Everything to the _LoadState commit mutates PROCESS-WIDE state; the try/finally below restores it on
- # failure. gguf_transformer: the dense fast path still sets gguf_filename, but pipe.transformer is dense
- # (REGIONAL compile).
+ # failure. gguf_transformer: the dense fast path still sets gguf_filename, but pipe.transformer is
+ # dense (REGIONAL compile).
gguf_transformer = kind == "gguf" and transformer_quant_engaged is None
eager_patched = False
@@ -4427,7 +4315,8 @@ class DiffusionBackend:
try:
if effective_speed != SPEED_OFF:
install_compile_safe_patches()
- # Per-arch compile-safe fusions; neutral under compile, tracked by the same eager_patched flag.
+ # Per-arch compile-safe fusions; neutral under compile, tracked by the same eager_patched
+ # flag.
install_arch_patches()
eager_patched = True
else:
@@ -4492,11 +4381,10 @@ class DiffusionBackend:
logger = logger,
)
te_quant = te_outcome.mode
- # Same contract for the other half of "the requested precision": an explicit encoder mode that
- # engaged NOTHING leaves a dense bf16 encoder the caller did not ask for, and a PARTIAL cast leaves
- # a pipeline conditioning off a mixture of quantised and dense encoders. A mode that engaged
- # something ELSE (int8 -> fp8) is reported by the badge instead: the encoder IS quantised on every
- # tower, just not the way asked.
+ # Same contract for the other half of the requested precision: an explicit encoder mode that
+ # engaged NOTHING leaves a dense bf16 encoder the caller did not ask for, and a PARTIAL cast
+ # leaves a pipeline conditioning off a mixture of quantised and dense encoders. A mode that
+ # engaged something ELSE (int8 -> fp8) is reported by the badge instead.
if (
(te_quant is None or te_outcome.partial)
and normalize_te_quant(text_encoder_quant) is not None
@@ -4526,8 +4414,8 @@ class DiffusionBackend:
plan = refined_plan
# Persistent conditioning cache (UNSLOTH_DIFFUSION_COND_CACHE_DIR): repeated prompts skip the
- # text-encoder forward. After the TE quant so the key reflects the encoders that run; ``base`` keys
- # the companion repo.
+ # text-encoder forward. After the TE quant so the key reflects the encoders that run; ``base``
+ # keys the companion repo.
cond_cache.install(
pipe,
family = fam.name,
@@ -4569,9 +4457,9 @@ class DiffusionBackend:
else "requested",
),
"transformer_quant": (
- # The RAW request, not the tri-state rewrite: an "Auto: OFF" badge and a declined "FP8"
- # must not look the same. Captured before the rewrite, so it is also immune to the auto
- # retries pinning a concrete rung: a pick that fell back to a lower rung is still auto.
+ # The RAW request, not the tri-state rewrite: an "Auto: OFF" badge and a declined
+ # "FP8" must not look the same. Captured before the rewrite, so it is also immune to
+ # the auto retries pinning a concrete rung.
transformer_quant_requested,
transformer_quant_engaged or "off",
# A recorded decline wins: it names WHY, where the generic strings below only say the
@@ -4588,8 +4476,8 @@ class DiffusionBackend:
else "re-planned resident for the quantised artifact"
if quant_plan is not None
else "engaged on the dense fast path",
- # Honored when the quant engaged AND when the ask was "off" (a request NOT to quantise,
- # which the GGUF build satisfies)
+ # Honored when the quant engaged AND when the ask was "off" (a request NOT to
+ # quantise, which the GGUF build satisfies)
RESOLVED_APPLIED
if transformer_quant_engaged is not None
or transformer_quant_pinned is None
@@ -4734,26 +4622,21 @@ class DiffusionBackend:
) -> tuple[Any, str]:
"""Build the opt-in fast pipeline and return ``(pipe, engaged_scheme)``.
- Two ways to get the quantized transformer, in order:
+ Two ways to get the quantized transformer, in order: (1) Pre-quantized, when a checkpoint is
+ configured for the chosen scheme (an explicit ``prequant_path`` or the family's hosted
+ repo), loaded onto the meta device and assigned in, so the dense bf16 never lands on the GPU
+ and the load peak is ~half; (2) Dense + quantise (fallback), loading the DENSE bf16
+ transformer from the base repo, placing it, and torchao-quantising it in place.
- 1. Pre-quantized: if a checkpoint is configured for the chosen scheme (an explicit
- ``prequant_path`` or the family's hosted repo), load the already-quantized
- weights onto the meta device and assign them in -- the dense bf16 never lands on
- the GPU, so the load peak is ~half and the download is smaller.
- 2. Dense + quantise (fallback): load the DENSE bf16 transformer from the base repo,
- place it on the device, and torchao-quantise it in place.
+ ``lora_specs`` bakes LoRA adapters into the build: they attach on the DENSE transformer
+ (peft's post-quant torchao dispatch needs quantizer metadata a manual quantize_ never has),
+ then quantize_ converts only the frozen base linears, then the loader compiles. That forces
+ the dense path, so a baked-LoRA load pays the dense peak. Scale 0 reproduces the quantized
+ base exactly.
- ``lora_specs`` bakes LoRA adapters into the build: they attach on the DENSE
- transformer (peft's post-quant torchao dispatch needs quantizer metadata a manual
- quantize_ never has), then quantize_ converts only the frozen base linears (the
- ``lora_`` side path is excluded by name), then the loader compiles. That forces the
- dense path -- the prequant shortcut is skipped -- so a baked-LoRA load pays the dense
- peak. Verified on the Unsloth stack: scale 0 reproduces the quantized base exactly.
-
- Raises if the scheme is unsupported or quantisation fails, so ``load_pipeline``
- catches it and falls back to the GGUF build. Quantisation runs ON the device and
- BEFORE the loader compiles the repeated block, so the order stays quantize ->
- compile -> placement.
+ Raises if the scheme is unsupported or quantisation fails, so ``load_pipeline`` catches it
+ and falls back to the GGUF build. Quantisation runs ON the device and BEFORE the loader
+ compiles the repeated block, so the order stays quantize -> compile -> placement.
``base`` keeps the UPSTREAM id for the prequant table and base_model_id checks; every
download uses ``fetch_base``. A gated base 401s on both the prequant config read and the
@@ -4763,8 +4646,9 @@ class DiffusionBackend:
# 1. Pre-quantized checkpoint, when one is configured for the resolved scheme.
scheme = select_transformer_quant_scheme(target, mode, family = getattr(fam, "name", None))
if scheme is None:
- # Bail BEFORE the multi-GB dense download: an unsupported scheme (fp8 on Ampere, nvfp4 off Blackwell) would
- # materialise the transformer only to fail at quantize, after eviction. load_pipeline falls back to GGUF.
+ # Bail BEFORE the multi-GB dense download: an unsupported scheme (fp8 on Ampere, nvfp4 off Blackwell)
+ # would materialise the transformer only to fail at quantize, after eviction. load_pipeline falls back to
+ # GGUF.
raise RuntimeError("transformer quant unsupported for this device/scheme")
if fam is not None and not _has_active_lora(lora_specs):
# A LoRA bake needs the DENSE transformer (adapters attach before quantize_), so skip prequant. Active
@@ -4820,9 +4704,9 @@ class DiffusionBackend:
"prequant checkpoint unavailable and the dense transformer does not fit resident"
)
# Deliberately the hub id, not base_local_dir: diffusers treats a local directory as terminal (_get_model_file
- # raises rather than falling back to the hub) and a sharded load raises per missing shard, so a partial snapshot
- # would drop a build the hub id completes. Off the hub id a base only the other root holds costs a re-download,
- # or 401s into the GGUF fallback, which is what main does today.
+ # raises rather than falling back to the hub) and a sharded load raises per missing shard, so a partial
+ # snapshot would drop a build the hub id completes. Off the hub id a base only the other root holds costs a
+ # re-download, or 401s into the GGUF fallback.
transformer = transformer_cls.from_pretrained(
fetch_base,
subfolder = "transformer",
@@ -4896,12 +4780,10 @@ class DiffusionBackend:
fetch_base: Optional[str] = None,
local_files_only: bool = False,
) -> Any:
- """Assemble the diffusers pipeline around ``transformer`` and place it on ``device``
- (a no-op for an already-placed pre-quantized transformer; it moves the companions).
-
- Everything below reads the base only to FETCH, so it uses ``fetch_base`` (the load-wide
- decision, re-derived for a direct call). Matters when ``base_local_dir`` is None: nothing
- was staged, so a gated upstream would 401 here."""
+ """Assemble the diffusers pipeline around ``transformer`` and place it on ``device`` (a
+ no-op for an already-placed pre-quantized transformer; it moves the companions).
+ Everything below reads the base only to FETCH, so it uses ``fetch_base``. Matters when
+ ``base_local_dir`` is None: nothing was staged, so a gated upstream would 401 here."""
base = fetch_base or prefer_ungated_mirror(base, hf_token)
if getattr(fam, "name", None) == KREA2_FAMILY_NAME:
# krea ships transformers-5.x configs and no top-level tokenizer files, so assemble per-component.
@@ -4923,8 +4805,8 @@ class DiffusionBackend:
hf_token = hf_token,
transformer = transformer,
text_encoder = krea_te,
- # ``base_local_dir`` is None whenever nothing was staged, and then this is a repo id: the same guard the
- # pipe_kwargs below carry for every other family.
+ # ``base_local_dir`` is None whenever nothing was staged, and then this is a repo id: the same guard
+ # the pipe_kwargs below carry for every other family.
local_files_only = local_files_only,
)
pipe.to(device)
@@ -4973,16 +4855,13 @@ class DiffusionBackend:
target: Any,
text_encoder_quant: Optional[str],
) -> Optional[int]:
- """``candidate.companions_mib`` with the text-encoder share priced at the PRE-CAST size
- when this pick takes its encoder from a hosted fp8 checkpoint.
-
- The estimate is always the DENSE encoder plus the VAE, but assembly is handed
- ``text_encoder_quant`` and injects the pre-cast encoder when one is configured, so the
- unified-memory fit check below would refuse on bytes the load never materialises: for
- FLUX.2-dev's Mistral-24B that is ~17 GB of an encoder the pipeline never builds. Keyed on
- the same ``te_prequant_budget_scale`` the load-level resident plan uses, so a budget cannot
- claim a saving the load does not take. The VAE share is untouched: nothing on this path
- quantises it."""
+ """``candidate.companions_mib`` with the text-encoder share priced at the PRE-CAST size when
+ this pick takes its encoder from a hosted fp8 checkpoint. The estimate is always the
+ DENSE encoder plus the VAE, but assembly is handed ``text_encoder_quant`` and injects the
+ pre-cast encoder when one is configured, so the unified-memory fit check below would
+ refuse on bytes the load never materialises. Keyed on the same
+ ``te_prequant_budget_scale`` the load-level resident plan uses, so a budget cannot claim
+ a saving the load does not take. The VAE share is untouched."""
companions = getattr(candidate, "companions_mib", None)
if companions is None:
return None
@@ -5011,26 +4890,25 @@ class DiffusionBackend:
kind: str,
text_encoder_quant: Optional[str] = None,
) -> Any:
- """``plan`` with its weight term replaced by the family table's bf16-RESIDENT total, for
- the unified-memory refusal only.
+ """``plan`` with its weight term replaced by the family table's bf16-RESIDENT total, for the
+ unified-memory refusal only.
A full-pipeline plan sizes weights from cached shard bytes, which is what the repo stores,
- not what ends up resident: a family shipping fp32 shards (Z-Image, Lumina) halves on the
- bf16 cast, so the refusal would reject a load that comfortably fits. The table is
- documented as post-cast resident sizes, so it is the right number to refuse on. Only ever
- LOWERS the estimate -- a table that reads higher than the shards (a narrow fp8 base that
- upcasts) is already handled in the plan, and taking the max here would double-count it.
+ not what ends up resident: a family shipping fp32 shards halves on the bf16 cast, so the
+ refusal would reject a load that comfortably fits. The table is documented as post-cast
+ resident sizes. Only ever LOWERS the estimate: a table that reads higher than the shards is
+ already handled in the plan.
+
Left alone entirely for single-file/GGUF kinds, whose on-disk size IS their resident size,
- on any target that is not sized in bf16, and for a LOCAL directory: the table is keyed on
- upstream repo ids, so a local checkpoint can only ever reach the coarse family entry, and
- a family covering more than one size (a local FLUX.2-klein 9B against klein's 4B default)
- would be lowered to a number less than half what it loads. On disk is the measured truth
- there; only a hub id the table actually recognises earns the substitution."""
+ on any target not sized in bf16, and for a LOCAL directory: the table is keyed on upstream
+ repo ids, so a local checkpoint can only reach the coarse family entry, and a family
+ covering more than one size would be lowered to a number less than half what it loads.
+ """
try:
- # A whole-pipeline single file (SDXL) carries the U-Net, VAE and text encoders itself, and the base repo is
- # read for config only -- but the plan still adds the base's cached companion weights, so a user who once
- # loaded the full pipeline has those bytes counted twice. Harmless as an offload hint, a rejected load as a
- # hard refusal.
+ # A whole-pipeline single file (SDXL) carries the U-Net, VAE and text encoders itself, and the base repo
+ # is read for config only, but the plan still adds the base's cached companion weights, so a user who once
+ # loaded the full pipeline has those bytes counted twice. Harmless as an offload hint, a rejected load as
+ # a hard refusal.
if kind == "single_file" and getattr(fam, "single_file_is_pipeline", False):
companion = plan.estimates.get("companion_dense_mib")
current = plan.estimates.get("model_dense_mib")
@@ -5050,9 +4928,9 @@ class DiffusionBackend:
if getattr(target, "dtype", None) not in (torch.bfloat16, torch.float16):
return plan
# RECOGNISED bases only. The table is keyed on exact upstream ids, so a fine-tune or a renamed mirror the
- # family detector still matches by name would fall through to the coarse family entry -- and for a family
- # carrying two sizes that entry is the smaller one, so a 9B derivative would be lowered to the 4B number and
- # walk past the refusal. Accept the family's own default base and anything with an explicit override;
+ # family detector still matches by name would fall through to the coarse family entry, and for a family
+ # carrying two sizes that entry is the smaller one, so a 9B derivative would be lowered to the 4B number
+ # and walk past the refusal. Accept the family's own default base and anything with an explicit override;
# anything else keeps its measured size.
canonical = canonical_base(base)
if (
@@ -5064,10 +4942,9 @@ class DiffusionBackend:
if table is None:
return plan
# The table's encoder term is the DENSE one. When this pick takes its encoder pre-cast from a hosted fp8
- # checkpoint the resident encoder is about 0.65x that, and for a heavyweight one (FLUX.2-dev's Mistral-24B,
- # 48 GB) budgeting the dense figure is tens of GB of weights the pipeline never materialises -- enough to
- # refuse a load that fits. Keyed on te_prequant_sources through the shared helper, the same resolver
- # assembly uses, so the budget cannot claim a saving the load does not take.
+ # checkpoint the resident encoder is about 0.65x that, and for a heavyweight one budgeting the dense
+ # figure is tens of GB of weights the pipeline never materialises, enough to refuse a load that fits.
+ # Keyed on te_prequant_sources through the shared helper, the same resolver assembly uses.
from .diffusion_te_prequant import te_prequant_budget_scale
te_scale = te_prequant_budget_scale(
@@ -5104,12 +4981,10 @@ class DiffusionBackend:
memory_mode: Optional[str] = None,
cpu_offload: bool = False,
) -> Optional[str]:
- """Return a pre-download unified-memory refusal for a pipeline, if any.
-
- The estimate comes from Hub metadata because a cold cache has no local size to inspect.
- It uses total capacity so a currently loaded model does not make a valid swap look too
- large. GGUF and single-file loads retain the existing in-load guard.
- """
+ """Return a pre-download unified-memory refusal for a pipeline, if any. The estimate comes
+ from Hub metadata because a cold cache has no local size to inspect. It uses total
+ capacity so a currently loaded model does not make a valid swap look too large. GGUF and
+ single-file loads retain the existing in-load guard."""
if fam is None or kind != "pipeline":
return None
declared_files = list(declared_files or ())
@@ -5171,37 +5046,33 @@ class DiffusionBackend:
base_local_dir: Optional[str] = None,
fetch_base: Optional[str] = None,
):
- """Build the memory plan for this load: snapshot free device memory and
- estimate the model's resident footprint, then let the planner pick an
- offload policy + VAE memory savers. Kept on the backend so the cached base
- repo (companion text-encoder / VAE) feeds the size estimate.
-
- The size estimate is per-kind: diffusers keeps GGUF weights packed (per-matmul
- transient dequant), so a GGUF loads near its on-disk size; a safetensors
- single-file loads near its on-disk size (it carries its dtype), except an fp8
- transformer file that gets upcast to bf16 on load (~2x resident); and a full
- pipeline is one cached download (transformer + companions), already compressed.
- ``transformer_resident_override_mib`` replaces the file-size transformer estimate
- when the loader is planning for a DIFFERENT artifact than the file on disk (the
- dense transformer-quant candidate, whose footprint the auto-policy estimates);
- ``companion_override_mib`` likewise replaces the cached companion total on that
- re-plan, so the base repo's PREFETCHED transformer/ shards -- which land in the
- same blob cache _companion_cache_bytes sums -- are not counted as companions on
- top of transformer_resident_override_mib (a double-count of the transformer);
- ``text_encoder_override_mib`` carries that override's TEXT-ENCODER share, which the
- planner needs to price the streamed-text-encoder group tier. Both come from the same
- family component table, so they cannot disagree about what the companions are.
-
- ``base_local_dir`` is the snapshot the load will actually read, carried into the size lookups
- as an extra source alongside the cache roots. A prefetch split across roots hands back no
- snapshot at all and a preflight-excused one can hold less than the repo, so it is additive
- and never a replacement: under-counting here leaves an auto plan resident and OOMing on
- weights it never budgeted.
+ """Build the memory plan for this load: snapshot free device memory and estimate the model's
+ resident footprint, then let the planner pick an offload policy + VAE memory savers. Kept on
+ the backend so the cached base repo (companion text-encoder / VAE) feeds the size estimate.
+
+ The size estimate is per-kind: diffusers keeps GGUF weights packed (per-matmul transient
+ dequant), so a GGUF loads near its on-disk size; a safetensors single-file loads near its
+ on-disk size, except an fp8 transformer file that gets upcast to bf16 on load (~2x
+ resident); and a full pipeline is one cached download, already compressed.
+
+ ``transformer_resident_override_mib`` replaces the file-size transformer estimate when the
+ loader is planning for a DIFFERENT artifact than the file on disk (the dense
+ transformer-quant candidate); ``companion_override_mib`` likewise replaces the cached
+ companion total on that re-plan, so the base repo's PREFETCHED transformer/ shards are not
+ counted as companions on top of it; ``text_encoder_override_mib`` carries that override's
+ TEXT-ENCODER share, which the planner needs to price the streamed-text-encoder group tier.
+ All come from the same family component table.
+
+ ``base_local_dir`` is the snapshot the load will actually read, carried into the size
+ lookups as an extra source alongside the cache roots: it is additive and never a
+ replacement, since under-counting here leaves an auto plan resident and OOMing on weights it
+ never budgeted.
``fetch_base`` is the repo the bytes were staged from, so every cache scan below reads it:
sizing an upstream id whose cache is empty folds the VAE/text-encoder to zero and wrongly
picks resident placement. ``base`` and ``repo_id`` keep the upstream identity for the
- family/variant checks."""
+ family/variant checks.
+ """
# Settled (max-over-reads) on cuda: a transient foreign allocation would make an empty card look full
device_memory = settled_snapshot_device_memory(target)
if kind == "pipeline":
@@ -5209,12 +5080,12 @@ class DiffusionBackend:
# cached, so sum its on-disk weights.
local_repo = Path(repo_id).expanduser() if repo_id else None
staged_repo = Path(base_local_dir).expanduser() if base_local_dir else None
- # The bytes land under the repo they were STAGED from, so scan the mirror when there is one: an upstream id
- # whose cache is empty folds the whole pipeline to zero.
+ # The bytes land under the repo they were STAGED from, so scan the mirror when there is one: an upstream
+ # id whose cache is empty folds the whole pipeline to zero.
cache_repo = fetch_base or repo_id
- # Largest of every source the load can read this repo from: a staged snapshot can sit under the OTHER root,
- # and a prefetch that split the repo across roots hands back none at all, so the smaller answer would plan a
- # multi-GB pipeline as unknown.
+ # Largest of every source the load can read this repo from: a staged snapshot can sit under the OTHER
+ # root, and a prefetch that split the repo across roots hands back none at all, so the smaller answer
+ # would plan a multi-GB pipeline as unknown.
cached = max(
self._local_dir_weight_bytes(local_repo, exclude_transformer = False)
if local_repo is not None and local_repo.is_dir()
@@ -5242,14 +5113,14 @@ class DiffusionBackend:
table = family_bf16_components_gb(fam, fam.base_repo)
if table is not None:
# Reserve the bf16 footprint from this network-free constant, else model_dense_mib stays None
- # ("unknown -> resident") and the ~54 GB pipeline OOMs
+ # (unknown -> resident) and the ~54 GB pipeline OOMs
table_mib = int(sum(table) * (1000.0**3) / (1024.0 * 1024.0))
model_dense_mib = (
table_mib if model_dense_mib is None else max(model_dense_mib, table_mib)
)
companion_mib = None
- # No companion total on this branch (the whole repo IS the model), so there is no split to hand the planner
- # either. None, not a guess: it reproduces the old decision.
+ # No companion total on this branch (the whole repo IS the model), so there is no split to hand the
+ # planner either. None, not a guess: it reproduces the old decision.
text_encoder_mib = None
else:
if transformer_resident_override_mib is not None:
@@ -5269,8 +5140,8 @@ class DiffusionBackend:
# Companions (VAE + text encoders) load near on-disk size; sum the base-repo cache, or a LOCAL base's
# on-disk weights.
if companion_override_mib is not None:
- # Re-planning the dense candidate: the prefetched transformer/ shards land in the same cache, so use the
- # estimate instead of double-counting.
+ # Re-planning the dense candidate: the prefetched transformer/ shards land in the same cache, so use
+ # the estimate instead of double-counting.
companion_mib = companion_override_mib
# The text-encoder share of that same override, from the same family component table, so the two terms
# cannot disagree. None when the caller has no split.
@@ -5283,7 +5154,7 @@ class DiffusionBackend:
companion_mib = int(companion // (1024 * 1024)) if companion else None
# The text-encoder share of that companion total, from the SAME walk over the same trees, so the
# subtraction the planner does is exact rather than two estimates meeting in the middle. 0 bytes reads
- # as "nothing cached", i.e. no split.
+ # as nothing cached, i.e. no split.
text_encoder = self._text_encoder_cache_bytes(fetch_base or base, base_local_dir)
text_encoder_mib = int(text_encoder // (1024 * 1024)) if text_encoder else None
model_dense_mib = None
@@ -5314,23 +5185,19 @@ class DiffusionBackend:
@staticmethod
def _from_pipe_no_recast(pipe: Any, pipe_cls: Any, **extra: Any) -> Any:
- """``Pipeline.from_pipe``, minus the cast it ends on.
-
- from_pipe casts every component it reuses, to float32 unless the caller named a
- dtype, and on the pinned revision an explicit ``torch_dtype = None`` no longer
- suppresses it. Those components are the resident pipeline's own, so the cast raises
- on a quantized denoiser (#9186) and silently doubles an unquantized one. Catching
- that error is not enough -- components are cast in name order, so earlier ones are
- float32 already when a later one refuses.
- """
+ """``Pipeline.from_pipe``, minus the cast it ends on. from_pipe casts every component it
+ reuses, to float32 unless the caller named a dtype, and on the pinned revision an
+ explicit ``torch_dtype = None`` no longer suppresses it. Those components are the
+ resident pipeline's own, so the cast raises on a quantized denoiser (#9186) and silently
+ doubles an unquantized one. Catching that error is not enough: components are cast in
+ name order, so earlier ones are float32 already when a later one refuses."""
return _no_recast_pipeline_class(pipe_cls).from_pipe(pipe, **extra)
def _workflow_pipe(self, state: _LoadState, class_name: Optional[str], workflow: str) -> Any:
- """The diffusers pipeline for an image-conditioned ``workflow``, built once and
- cached. ``Pipeline.from_pipe`` re-wires the loaded text-to-image pipe's resident
- modules (transformer/VAE/text-encoder, incl. any compiled/quantised state) into
- the workflow pipeline class, so there is no extra VRAM and no reload. Raises a
- clear ValueError when the family does not support the workflow."""
+ """The diffusers pipeline for an image-conditioned ``workflow``, built once and cached.
+ ``Pipeline.from_pipe`` re-wires the loaded text-to-image pipe's resident modules into the
+ workflow pipeline class, so there is no extra VRAM and no reload. Raises a clear
+ ValueError when the family does not support the workflow."""
if not class_name:
raise ValueError(
f"{workflow} is not supported for the '{state.family.name}' model family."
@@ -5341,8 +5208,8 @@ class DiffusionBackend:
import diffusers
pipe = self._from_pipe_no_recast(state.pipe, getattr(diffusers, class_name))
- # Publish to the shared aux cache only if THIS load is still current: from_pipe runs without _lock, so an unload
- # can null _state and caching would hand out stale modules.
+ # Publish to the shared aux cache only if THIS load is still current: from_pipe runs without _lock, so an
+ # unload can null _state and caching would hand out stale modules.
with self._lock:
if self._state is state:
self._aux_pipes[class_name] = pipe
@@ -5425,20 +5292,19 @@ class DiffusionBackend:
@staticmethod
def _align_vae_dtype(pipe: Any, denoiser_attr: str = "transformer") -> None:
- """Cast the VAE to the denoiser's compute dtype before an image-conditioned
- call. The img2img/inpaint pipelines VAE-encode the input image at the text-
- encoder dtype (bf16), but a prior txt2img DECODE may have left the shared VAE
- upcast to fp32 (its ``force_upcast`` path), so the encode would mismatch
- (bf16 image vs fp32 VAE). Re-aligning here is safe: our families run bf16 or
- fp32 only (the fp16 guard promotes fp16), and a later txt2img decode re-upcasts
- as needed. ``denoiser_attr`` is ``pipe.transformer`` for DiT families and
- ``pipe.unet`` for SDXL. Best-effort; a no-op when already aligned."""
+ """Cast the VAE to the denoiser's compute dtype before an image-conditioned call. The
+ img2img/inpaint pipelines VAE-encode the input image at the text-encoder dtype (bf16),
+ but a prior txt2img DECODE may have left the shared VAE upcast to fp32, so the encode
+ would mismatch. Re-aligning here is safe: our families run bf16 or fp32 only, and a later
+ txt2img decode re-upcasts as needed. ``denoiser_attr`` is ``pipe.transformer`` for DiT
+ families and ``pipe.unet`` for SDXL. Best-effort; a no-op when already aligned."""
denoiser = getattr(pipe, denoiser_attr, None)
vae = getattr(pipe, "vae", None)
if denoiser is None or vae is None:
return
try:
- # Read the dtype from the parameters (a compiled nn.Module may hide .dtype), taking the first FLOATING one.
+ # Read the dtype from the parameters (a compiled nn.Module may hide .dtype), taking the first FLOATING
+ # one.
target_dtype = next(
(p.dtype for p in denoiser.parameters() if p.dtype.is_floating_point),
None,
@@ -5452,24 +5318,19 @@ class DiffusionBackend:
@staticmethod
def _make_vae_encode_dtype_safe(pipe: Any) -> None:
- """Cast whatever tensor reaches ``vae.encode`` to the VAE's OWN dtype, so an
- image-conditioned call cannot die on ``Input type (float) and bias type
- (c10::BFloat16) should be the same``.
-
- ``_align_vae_dtype`` pins the VAE to the DENOISER's dtype, but the img2img /
- inpaint pipelines consult neither: they cast the upload to whatever the TEXT
- ENCODER produced (``prompt_embeds[0].dtype`` in ``ZImageImg2ImgPipeline``), a
- third dtype nobody reconciles. When that lands on fp32 against bf16 VAE weights
- the first conv raises, and the user sees only an opaque failure toast.
-
- Wrapping ``encode`` rather than widening ``_align_vae_dtype`` is deliberate: the
- mismatch is between the pipeline's chosen input dtype and the VAE, so the fix has
- to live at that boundary to hold for every family and diffusers version, instead
- of tracking which attribute each pipeline reads this release. Latents come back
- untouched -- ``scale_noise`` and the schedulers upcast to fp32 anyway.
-
- Idempotent (a re-wrap on a warm pipe is a no-op) and best-effort: any failure
- leaves the original ``encode`` in place."""
+ """Cast whatever tensor reaches ``vae.encode`` to the VAE's OWN dtype, so an image-conditioned
+ call cannot die on ``Input type (float) and bias type (c10::BFloat16) should be the same``.
+
+ ``_align_vae_dtype`` pins the VAE to the DENOISER's dtype, but the img2img / inpaint
+ pipelines consult neither: they cast the upload to whatever the TEXT ENCODER produced, a
+ third dtype nobody reconciles. When that lands on fp32 against bf16 VAE weights the first
+ conv raises.
+
+ Wrapping ``encode`` rather than widening ``_align_vae_dtype`` is deliberate: the mismatch is
+ between the pipeline's chosen input dtype and the VAE, so the fix has to live at that
+ boundary to hold for every family and diffusers version. Latents come back untouched:
+ ``scale_noise`` and the schedulers upcast to fp32 anyway. Idempotent and best-effort.
+ """
vae = getattr(pipe, "vae", None)
if vae is None or getattr(vae, "_unsloth_dtype_safe_encode", False):
return
@@ -5505,11 +5366,9 @@ class DiffusionBackend:
hf_token: Optional[str],
cancel: Optional[threading.Event] = None,
) -> tuple[tuple[str, str, float], ...]:
- """Resolve (id, weight) specs to a ``(name, path, weight)`` tuple set for diffusers.
-
- Shared by the generation-time apply path and the quant load-time bake so both produce
- IDENTICAL tuples for the same request (the no-op / weight-only comparisons depend on it).
- """
+ """Resolve (id, weight) specs to a ``(name, path, weight)`` tuple set for diffusers. Shared
+ by the generation-time apply path and the quant load-time bake so both produce IDENTICAL
+ tuples for the same request (the no-op / weight-only comparisons depend on it)."""
from core.inference import diffusion_lora
resolved = diffusion_lora.resolve_specs(
@@ -5541,17 +5400,17 @@ class DiffusionBackend:
def _apply_loras(
self, state: Any, loras: Optional[list[tuple[str, float]]], cancel: threading.Event
) -> None:
- """Load + activate requested LoRA adapters on ``state.pipe`` (non-fused), or clear
- them when none are requested.
+ """Load + activate requested LoRA adapters on ``state.pipe`` (non-fused), or clear them when
+ none are requested.
- The applied set is recorded on the pipe object, so an unchanged selection is a no-op
- and a model swap (a fresh pipe with no marker) resets naturally. Never fuses: fusing
- breaks on quantized (bnb-4bit / torchao) transformers and blocks live weight tweaks.
+ The applied set is recorded on the pipe object, so an unchanged selection is a no-op and a
+ model swap resets naturally. Never fuses: fusing breaks on quantized transformers and blocks
+ live weight tweaks.
- A torchao int8/fp8 pipe carries its adapters from the load-time BAKE (attached before
- quantize_ + compile). Its module topology is frozen: weight-only changes go through
- set_adapters (value-level, compile-guard safe); adding/removing adapters needs a reload
- with the new selection, surfaced as a clean 400 here.
+ A torchao int8/fp8 pipe carries its adapters from the load-time BAKE. Its module topology is
+ frozen: weight-only changes go through set_adapters (value-level, compile-guard safe);
+ adding/removing adapters needs a reload with the new selection, surfaced as a clean 400
+ here.
"""
from core.inference import diffusion_lora
@@ -5632,15 +5491,12 @@ class DiffusionBackend:
quant_baked: bool,
cancel: threading.Event,
) -> None:
- """Generation-time LoRA handling for a torchao-quantized pipe.
-
- The adapters (if any) were baked at load time, before quantize_ + compile, so the
- module topology is immutable here. Allowed without a reload: weight tweaks on the
- baked set and disabling everything (scale 0 reproduces the quantized base exactly;
- set_adapters is value-level, so torch.compile guards absorb it). Anything that would
- change topology (adding adapters to a bake-less load, or a different adapter set)
- raises a clean 400 telling the client to reload with the new selection.
- """
+ """Generation-time LoRA handling for a torchao-quantized pipe. The adapters (if any) were
+ baked at load time, before quantize_ + compile, so the module topology is immutable here.
+ Allowed without a reload: weight tweaks on the baked set and disabling everything (scale
+ 0 reproduces the quantized base exactly; set_adapters is value-level, so torch.compile
+ guards absorb it). Anything that would change topology raises a clean 400 telling the
+ client to reload with the new selection."""
if not quant_baked:
if not specs:
return # no adapters baked, none requested
@@ -5682,17 +5538,15 @@ class DiffusionBackend:
def _reset_step_cache(pipe: Any) -> None:
"""Clear the transformer's stateful step cache (FBCache) before a forward.
- diffusers keys FBCache residuals by cache context ("cond"/"uncond") on the
- long-lived transformer. The context exit does NOT reset them; the end of a
- pipeline ``__call__`` does, via ``maybe_free_model_hooks()`` -- but only when
- the call RETURNS. A call that raised (an OOM this generate() backs off from, a
- cancelled denoise, a failed prior request) leaves its own batch's residual on
- the resident transformer, and the next forward's first step then compares
- against it: a tensor-shape mismatch when the resolution/batch changed, or a
+ diffusers keys FBCache residuals by cache context on the long-lived transformer. The context
+ exit does NOT reset them; the end of a pipeline ``__call__`` does, via
+ ``maybe_free_model_hooks()``, but only when the call RETURNS. A call that raised leaves its
+ own batch's residual on the resident transformer, and the next forward's first step then
+ compares against it: a tensor-shape mismatch when the resolution/batch changed, or a
stale-cache reuse otherwise. The transformer-level reset entry point is
- ``_reset_stateful_cache`` in diffusers 0.39 (``reset_stateful_hooks`` lives only
- on the HookRegistry, so a getattr for it on the transformer is a silent no-op).
- Best-effort: a transformer without the hook (uncached load) is a silent no-op."""
+ ``_reset_stateful_cache`` in diffusers 0.39 (``reset_stateful_hooks`` lives only on the
+ HookRegistry, so a getattr for it on the transformer is a silent no-op). Best-effort.
+ """
transformer = getattr(pipe, "transformer", None)
reset = getattr(transformer, "_reset_stateful_cache", None) or getattr(
transformer, "reset_stateful_hooks", None
@@ -5704,17 +5558,12 @@ class DiffusionBackend:
pass
def _engage_deferred_speed(self, state: _LoadState) -> None:
- """Engage the deferred `default` speed profile at the start of the 3rd
- generation this session.
-
- The load left the pipe fully eager (bit-identical reference); by the 3rd
- image repeated use is established, so pay the one-time compile now: eager
- patches + attention auto upgrade + regional compile -- exactly what an
- unset-speed GGUF load gets at load time. Runs under _generate_lock (the
- caller), so no denoise can race the mutation. The flag is cleared FIRST so
- a failure never retries per generation; unload cleans everything up via the
- same state fields the load-time path uses (backend flags were snapshotted
- at load, before any speed layer could mutate them)."""
+ """Engage the deferred `default` speed profile at the start of the 3rd generation this
+ session. The load left the pipe fully eager (bit-identical reference); by the 3rd image
+ repeated use is established, so pay the one-time compile now: eager patches + attention
+ auto upgrade + regional compile. Runs under _generate_lock, so no denoise can race the
+ mutation. The flag is cleared FIRST so a failure never retries per generation; unload
+ cleans everything up via the same state fields the load-time path uses."""
object.__setattr__(state, "speed_deferred", False)
from .diffusion_eager_patches import install_compile_safe_patches
from .diffusion_arch_patches import install_arch_patches
@@ -5732,8 +5581,7 @@ class DiffusionBackend:
)
object.__setattr__(state, "attention_backend", attention_engaged)
# Keep the badge in step with the state it describes: the top-level field moved, so leaving `resolved` on the
- # load-time value would make the panel report an attention backend that is no longer the one running. Same
- # in-place update as the fields above.
+ # load-time value would make the panel report an attention backend that is no longer the one running.
if isinstance(state.resolved, dict) and "attention_backend" in state.resolved:
entry = dict(state.resolved["attention_backend"])
entry["value"] = attention_engaged or "native"
@@ -5808,8 +5656,8 @@ class DiffusionBackend:
seed: Optional[int] = None,
batch_size: int = 1,
# Batched multi-image generation: ``prompts`` renders one image per prompt (txt2img only), ``seeds`` one per
- # seed, ``batch_size`` alone derives base..base+n-1. Each image gets its OWN Generator, so same-seed repeats are
- # bit-identical.
+ # seed, ``batch_size`` alone derives base..base+n-1. Each image gets its OWN Generator, so same-seed repeats
+ # are bit-identical.
prompts: Optional[list[str]] = None,
seeds: Optional[list[int]] = None,
# Image-conditioned (base64/data-URL): init alone = img2img, init + mask = inpaint. ``strength`` 0 = keep
@@ -5850,7 +5698,7 @@ class DiffusionBackend:
self._state_device_target(state)
# The local `state` ref keeps the pipe alive even if unload() nulls _state. Resolve the per-image
# (prompt, seed) jobs up front: N prompts, one prompt x N seeds, or one prompt deriving
- # base..base+batch_size-1 (as the native engine does).
+ # base..base+batch_size-1.
jobs, seed = resolve_batch_jobs(
prompt = prompt,
prompts = prompts,
@@ -5985,8 +5833,8 @@ class DiffusionBackend:
"diffusers engine (needs a bf16 or bnb-4bit load of a family with a "
"ControlNet pipeline; not GGUF-via-diffusers or torchao fp8/int8)."
)
- # Decode + preprocess the control image FIRST so a bad image 400s before any CN download, at the
- # OUTPUT size.
+ # Decode + preprocess the control image FIRST so a bad image 400s before any CN download, at
+ # the OUTPUT size.
src = decode_b64_image(cn_image_b64, mode = "RGB")
control_pil = diffusion_controlnet.preprocess_control(src, cn_type).resize(
(width, height), Image.LANCZOS
@@ -6013,12 +5861,12 @@ class DiffusionBackend:
# Snap odd-sized inputs (and the mask) to a multiple of 16 where the OUTPUT size comes from the input
# image.
if init_pil is not None and workflow in ("img2img", "inpaint", "edit"):
- # img2img/inpaint take output size from the upload, so bound the longest side to 2048 (a phone photo
- # would OOM).
+ # img2img/inpaint take output size from the upload, so bound the longest side to 2048 (a phone
+ # photo would OOM).
if workflow == "img2img":
# ...and bound Transform by the REQUESTED size too, so the Resolution control caps the output
# instead of being inert. img2img only: an inpaint payload is the canvas the mask was painted
- # against (Extend sends a deliberately ENLARGED one), so shrinking it would break them.
+ # against, so shrinking it would break them.
init_pil = _fit_within(init_pil, min(2048, width), min(2048, height))
elif workflow == "inpaint":
init_pil = _clamp_max_side(init_pil, 2048)
@@ -6037,15 +5885,16 @@ class DiffusionBackend:
call_params = inspect.signature(pipe.__call__).parameters
kwargs: dict[str, Any] = {
- # prompt / generator / num_images_per_prompt are set per chunk below, one torch.Generator PER IMAGE.
+ # prompt / generator / num_images_per_prompt are set per chunk below, one torch.Generator PER
+ # IMAGE.
"num_inference_steps": steps,
# Most pipelines use "guidance_scale"; Qwen-Image uses "true_cfg_scale".
state.family.cfg_kwarg: guidance,
}
if state.family.name == IDEOGRAM4_FAMILY_NAME:
- # Ideogram 4 drives CFG via EITHER a constant guidance_scale OR a per-step guidance_schedule, never
- # both. At the advertised defaults drop the constant so the recommended 48-step taper engages; else
- # null the schedule.
+ # Ideogram 4 drives CFG via EITHER a constant guidance_scale OR a per-step guidance_schedule,
+ # never both. At the advertised defaults drop the constant so the recommended 48-step taper
+ # engages; else null the schedule.
if steps == 48 and abs(float(guidance) - 7.0) < 1e-6:
kwargs.pop(state.family.cfg_kwarg, None)
else:
@@ -6061,8 +5910,8 @@ class DiffusionBackend:
kwargs["mask_image"] = mask_pil
if strength is not None and "strength" in call_params:
kwargs["strength"] = strength
- # width/height: txt2img uses the slider; image-conditioned pipes must use the INPUT IMAGE's size or the
- # latents mismatch, and many drop them, so pass only when accepted.
+ # width/height: txt2img uses the slider; image-conditioned pipes must use the INPUT IMAGE's size or
+ # the latents mismatch, and many drop them, so pass only when accepted.
if workflow in ("txt2img", "reference", "controlnet"):
# These generate at the REQUESTED size (reference/control image resized to match).
kwargs["width"] = width
@@ -6076,8 +5925,8 @@ class DiffusionBackend:
if negative_prompt and "negative_prompt" in call_params:
kwargs["negative_prompt"] = negative_prompt
if workflow == "controlnet" and control_pil is not None:
- # CN pipeline takes the control map + scale; guidance start/end bound its step range. Every kwarg is
- # signature-gated.
+ # CN pipeline takes the control map + scale; guidance start/end bound its step range. Every kwarg
+ # is signature-gated.
if "control_image" in call_params:
kwargs["control_image"] = control_pil
elif "image" in call_params: # some CN pipelines name it "image"
@@ -6092,25 +5941,24 @@ class DiffusionBackend:
if "control_mode" in call_params and cn_mode is not None:
kwargs["control_mode"] = cn_mode
- # Per-forward chunks: the whole job list in ONE forward by default (batch 32 on 4-step models is ~10-22x
- # over serial engines), bounded by an explicit batch_size cap; the OOM backoff below halves a failed
- # chunk.
+ # Per-forward chunks: the whole job list in ONE forward by default, bounded by an explicit batch_size
+ # cap; the OOM backoff below halves a failed chunk.
chunks = chunk_jobs(jobs, batch_size)
try:
- # The dimensions the forward runs at, not the sliders: img2img / inpaint / upscale / edit take their
- # output size from the input image. Same derivation the compile-cache shape registration uses
- # further down.
+ # The dimensions the forward runs at, not the sliders: img2img / inpaint / upscale / edit take
+ # their output size from the input image. Same derivation the compile-cache shape registration
+ # uses further down.
guard_width, guard_height = _compile_shape_dims(
workflow, init_pil, width, height
)
guard_batch = _activation_guard_batch(chunks)
raise_on_image_activation_shortfall(
- # NOT the settled snapshot the load uses: that one calls empty_cache(), which is right once per
- # load but wrong on a per-generation path -- it releases every cached block, so the next forward
- # re-cudaMallocs all of its activations, defeating the caching allocator on every image. This
- # variant credits the same reclaimable bytes back arithmetically instead, so a warm allocator
- # does not read as a full card and nothing is flushed.
+ # NOT the settled snapshot the load uses: that one calls empty_cache(), which is right once
+ # per load but wrong on a per-generation path, since it releases every cached block and the
+ # next forward re-cudaMallocs all of its activations. This variant credits the same
+ # reclaimable bytes back arithmetically instead, so a warm allocator does not read as a full
+ # card.
device_memory = reclaimable_snapshot_device_memory(
self._state_device_target(state)
),
@@ -6236,7 +6084,8 @@ class DiffusionBackend:
cuda_graph.reset_all(state.cuda_graphs)
if len(chunk) < 2 or not oom:
raise
- # OOM backoff: halve the failed chunk and retry; per-image seeds keep every retry reproducible.
+ # OOM backoff: halve the failed chunk and retry; per-image seeds keep every retry
+ # reproducible.
empty_cache = getattr(getattr(torch, "cuda", None), "empty_cache", None)
if callable(empty_cache):
empty_cache()
@@ -6257,8 +6106,8 @@ class DiffusionBackend:
chunk_shapes.append(len(chunk))
steps_done[0] += steps
# Keep progress ACTIVE through the post-denoise work: the route persists the image after this returns,
- # so a mount probe reading idle would refresh the gallery too early. Persist the warm compile bundle; a
- # STATIC compile makes new artifacts per (w,h,batch), so register this shape.
+ # so a mount probe reading idle would refresh the gallery too early. Persist the warm compile bundle;
+ # a STATIC compile makes new artifacts per (w,h,batch), so register this shape.
try:
# Register the dims the forward ACTUALLY compiled with, and every distinct chunk size (a static
# compile makes one artifact per batch size too).
@@ -6276,12 +6125,10 @@ class DiffusionBackend:
except Exception: # noqa: BLE001 - cache persistence is best-effort
pass
# Last word on cancellation, AFTER the post-denoise work: the event stays registered through the
- # compile-cache save (a static compile writes a fresh artifact per shape, so that save is not instant)
- # and the page still shows Stop for as long as progress reads active, so a Stop landing there was
- # answered cancelled = true and then contradicted by the image the route persisted. Check and deregister
- # under the cancellation lock, which cancel_generate takes, so the two cannot interleave: a cancel that
- # saw this event registered ran strictly before the check, and one that arrives after finds nothing to
- # set and answers false. The finally below repeats the clear for every other exit.
+ # compile-cache save and the page still shows Stop for as long as progress reads active, so a Stop
+ # landing there was answered cancelled = true and then contradicted by the image the route persisted.
+ # Check and deregister under the cancellation lock, which cancel_generate takes, so the two cannot
+ # interleave. The finally below repeats the clear for every other exit.
with self._generation_cancel_lock:
if cancel.is_set():
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
@@ -6302,8 +6149,8 @@ class DiffusionBackend:
"model_kind": state.kind,
"gguf_filename": state.gguf_filename,
"transformer_quant": state.transformer_quant,
- # Read off the ENGAGED state, never the request: a recipe that claimed a precision the load declined
- # is the same lie the status badges just fixed.
+ # Read off the ENGAGED state, never the request: a recipe that claimed a precision the load
+ # declined is the same lie the status badges just fixed.
"text_encoder_quant": state.text_encoder_quant,
"memory_mode": state.memory_mode,
"offload_policy": state.offload_policy,
@@ -6345,16 +6192,13 @@ class DiffusionBackend:
}
def cancel_generate(self) -> bool:
- """Signal the in-flight generation to stop at its next step boundary.
-
- The denoise loop already watches this event (``_on_step`` sets diffusers'
- ``_interrupt``, and the per-chunk check discards a partial batch), but until now only
- unload() and a superseding load could set it. Returns False when nothing is running,
- which the route reports so the UI can settle its button back to Generate.
-
- Best effort by construction: the sampler stops at the NEXT step callback, so a cancel
- during the VAE decode or the encode that precedes step 0 lands when that finishes.
- Same contract as the video backend."""
+ """Signal the in-flight generation to stop at its next step boundary. The denoise loop
+ already watches this event (``_on_step`` sets diffusers' ``_interrupt``, and the
+ per-chunk check discards a partial batch), but until now only unload() and a superseding
+ load could set it. Returns False when nothing is running, which the route reports so the
+ UI can settle its button back to Generate. Best effort by construction: the sampler stops
+ at the NEXT step callback, so a cancel during the VAE decode or the encode that precedes
+ step 0 lands when that finishes."""
with self._generation_cancel_lock:
# Stop targets the denoising generation, not a serialized waiter.
active = self._active_generate_cancel
@@ -6396,8 +6240,8 @@ class DiffusionBackend:
self._unload_locked()
finally:
# Released in a finally, exactly like begin_load: _unload_locked ends in clear_gpu_cache(), which
- # raises on a sticky CUDA fault, and an un-drained fence would refuse every later generation for the
- # life of the process.
+ # raises on a sticky CUDA fault, and an un-drained fence would refuse every later generation for
+ # the life of the process.
self._release_teardown_locked()
return self.status()
@@ -6527,23 +6371,20 @@ def _family_workflows(fam: DiffusionFamily) -> list[str]:
def _resolve_base_repo(
repo_id: str, base_repo: Optional[str], fam: DiffusionFamily, hf_token: Optional[str]
) -> str:
- """The companion diffusers repo: caller's base, else the GGUF repo's own
- ``base_model`` tag, else the family fallback. Shared by both load paths so a
- direct ``load_pipeline`` call resolves the variant base the same way.
-
- The base loads via ``from_pretrained``, so it must be trusted -- an explicit
- base_repo is already gated at ``validate_load_request``, but the ``base_model``
- card tag is attacker-controlled metadata on any remote GGUF repo, so a tag that
- is not unsloth/allowlisted/local is dropped in favour of the curated family
- default (never fed to ``from_pretrained``), closing the pickle-deserialisation
- vector the ControlNet path already guards with evaluate_file_security."""
+ """The companion diffusers repo: caller's base, else the GGUF repo's own ``base_model`` tag,
+ else the family fallback. Shared by both load paths so a direct ``load_pipeline`` call
+ resolves the variant base the same way. The base loads via ``from_pretrained``, so it must be
+ trusted: an explicit base_repo is already gated at ``validate_load_request``, but the
+ ``base_model`` card tag is attacker-controlled metadata on any remote GGUF repo, so a tag
+ that is not unsloth/allowlisted/local is dropped in favour of the curated family default,
+ closing the pickle-deserialisation vector."""
base = (base_repo or "").strip()
if not base:
tag = _hf_base_model(repo_id, hf_token)
if tag and _is_trusted_diffusion_repo(tag):
# A card tag can now name a mirror (they are real unsloth/* repos) and clear the trust bar. Map it back:
- # this becomes status()["base_repo"] and a trained adapter's default base_model, both of which must stay the
- # vendor id. An EXPLICIT base_repo is verbatim.
+ # this becomes status()["base_repo"] and a trained adapter's default base_model, both of which must stay
+ # the vendor id. An EXPLICIT base_repo is verbatim.
base = canonical_base(tag)
# Returns the UPSTREAM id; the swap happens at the fetch sites only.
resolved = resolve_base_repo(fam, base)
@@ -6552,12 +6393,10 @@ def _resolve_base_repo(
def _remember_companion_base(repo_id: str, base: str) -> None:
- """Record that *repo_id* takes its companions from *base*, for the delete/cleanup guards.
-
- A card ``base_model`` tag is the one input this resolver has that a later offline scan cannot
- reconstruct -- a GGUF pick caches only the .gguf, never the card -- so the link is written
- where it is decided. Additive and best-effort: a failure here must never fail a load.
- """
+ """Record that *repo_id* takes its companions from *base*, for the delete/cleanup guards. A card
+ ``base_model`` tag is the one input this resolver has that a later offline scan cannot
+ reconstruct (a GGUF pick caches only the .gguf, never the card) so the link is written where
+ it is decided. Additive and best-effort: a failure here must never fail a load."""
try:
from hub.utils.companion_assets import record_companion_link
record_companion_link(repo_id, base)
@@ -6566,11 +6405,9 @@ def _remember_companion_base(repo_id: str, base: str) -> None:
def _hf_base_model(repo_id: str, hf_token: Optional[str]) -> Optional[str]:
- """The diffusers base repo from a GGUF repo's ``base_model`` tag, or None.
-
- Lets one family entry cover every variant (Turbo/full, schnell/dev, the
- 2512 Qwen revision). Skipped for local paths; None on any lookup failure.
- """
+ """The diffusers base repo from a GGUF repo's ``base_model`` tag, or None. Lets one family entry
+ cover every variant (Turbo/full, schnell/dev, the 2512 Qwen revision). Skipped for local
+ paths; None on any lookup failure."""
if Path(repo_id).expanduser().exists():
return None
try:
@@ -6585,12 +6422,10 @@ def _hf_base_model(repo_id: str, hf_token: Optional[str]) -> Optional[str]:
def _offload_controlnet_module(cn_model: Any, device: str, logger: Any) -> bool:
- """Stream a ControlNet module through ``device`` via diffusers group offloading.
-
- Used when the base model was loaded with an offload policy: forcing the ControlNet
- fully resident with ``.to(device)`` would defeat that low-VRAM placement and can OOM.
- Group offloading is applied to this single module (it does not touch the base pipe's
- existing hooks), so it is isolated and reversible. Returns True on success; on any
+ """Stream a ControlNet module through ``device`` via diffusers group offloading. Used when the
+ base model was loaded with an offload policy: forcing the ControlNet fully resident with
+ ``.to(device)`` would defeat that low-VRAM placement and can OOM. Group offloading is applied
+ to this single module, so it is isolated and reversible. Returns True on success; on any
failure the caller falls back to a resident placement, so this never blocks a load."""
try:
import torch
@@ -6613,21 +6448,17 @@ def _offload_controlnet_module(cn_model: Any, device: str, logger: Any) -> bool:
def _base_file_downloaded(rfilename: str, *, include_transformer: bool = False) -> bool:
- """True for base-repo files ``from_pretrained`` actually fetches.
-
- The transformer is supplied by the GGUF, and repo docs (``assets/``, the
- top-level README/PDF/images) are never downloaded — counting them would peg
- the progress estimate above what lands on disk, so the bar would sit short of
- 100% for the whole pipeline-load phase instead of advancing to "finalizing".
- ``include_transformer`` admits the ``transformer/`` shards for loads where the
- dense transformer-quant path will fetch them anyway (see
- ``_dense_quant_prefetch_needed``)."""
+ """True for base-repo files ``from_pretrained`` actually fetches. The transformer is supplied by
+ the GGUF, and repo docs (``assets/``, the top-level README/PDF/images) are never downloaded:
+ counting them would peg the progress estimate above what lands on disk, so the bar would sit
+ short of 100% for the whole pipeline-load phase. ``include_transformer`` admits the
+ ``transformer/`` shards for loads where the dense transformer-quant path will fetch them
+ anyway."""
if rfilename == "transformer/config.json":
- # The one transformer/ file that is ALWAYS needed, shards or not: from_single_file(config = <repo id>, subfolder
- # = "transformer") resolves it through the Hub, so a load that promised to download nothing cannot keep that
- # promise unless this ~1 KB file is already on disk. Excluding it made the locality gate pass and the load fetch
- # it afterwards, AFTER the resident pipeline was evicted. Counting it here is what lets the gate refuse up front
- # (cleanly, before eviction) or clear a pick that really can load offline. Video keeps the same exception at
+ # The one transformer/ file that is ALWAYS needed, shards or not: from_single_file(config = <repo id>,
+ # subfolder = "transformer") resolves it through the Hub, so a load that promised to download nothing cannot
+ # keep that promise unless this ~1 KB file is already on disk. Excluding it made the locality gate pass and
+ # the load fetch it afterwards, AFTER the resident pipeline was evicted. Video keeps the same exception at
# video.py's snapshot filter.
return True
if rfilename.startswith("transformer/"):
@@ -6637,8 +6468,8 @@ def _base_file_downloaded(rfilename: str, *, include_transformer: bool = False)
return not rfilename.startswith("assets/")
-# Weights the base repo need NOT supply when the single file is the whole pipeline (SDXL): from_single_file(config=base)
-# reads only the structure.
+# Weights the base repo need NOT supply when the single file is the whole pipeline (SDXL):
+# from_single_file(config=base) reads only the structure.
_BASE_WEIGHT_EXTS = (
".safetensors",
".bin",
@@ -6655,25 +6486,21 @@ _BASE_WEIGHT_EXTS = (
def _base_config_file_downloaded(rfilename: str) -> bool:
- """True for base-repo files needed to BUILD a pipeline structure around a whole-pipeline
- single file WITHOUT its weights: config / tokenizer / scheduler JSON, but no weight
- tensors (the single file supplies those). Used for ``single_file_is_pipeline`` families."""
+ """True for base-repo files needed to BUILD a pipeline structure around a whole-pipeline single
+ file WITHOUT its weights: config / tokenizer / scheduler JSON, but no weight tensors. Used
+ for ``single_file_is_pipeline`` families."""
if not _base_file_downloaded(rfilename):
return False
return not rfilename.lower().endswith(_BASE_WEIGHT_EXTS)
def _pipeline_file_downloaded(rfilename: str) -> bool:
- """True for files a full-pipeline ``from_pretrained`` fetches.
-
- Like ``_base_file_downloaded`` but for the ``pipeline`` kind, where the repo
- supplies its OWN transformer weights, so the ``transformer/`` subfolder is kept.
- Top-level docs (README/PDF/images) and ``assets/`` are skipped, and so are
- artifacts the torch loader never touches -- ONNX / OpenVINO / Flax exports and
- dtype-variant twins (``*.fp16.safetensors``: the loader requests the default
- variant) -- so an official repo that ships many formats (e.g. SDXL Base) does
- not prefetch tens of GB it will not load.
- """
+ """True for files a full-pipeline ``from_pretrained`` fetches. Like ``_base_file_downloaded``
+ but for the ``pipeline`` kind, where the repo supplies its OWN transformer weights, so the
+ ``transformer/`` subfolder is kept. Top-level docs and ``assets/`` are skipped, and so are
+ artifacts the torch loader never touches (ONNX / OpenVINO / Flax exports and dtype-variant
+ twins), so an official repo that ships many formats does not prefetch tens of GB it will not
+ load."""
if "/" not in rfilename: # top-level: only the pipeline manifest is fetched
return rfilename == "model_index.json"
lower = rfilename.lower()
@@ -6727,11 +6554,9 @@ def _pipeline_components_from_index(
explicit_components: Optional[Sequence[str]] = None,
failures_out: Optional[list] = None,
) -> Optional[tuple[frozenset[str], frozenset[str]]]:
- """Return selected component folders and exact model-index ignores.
-
- The manifest is small but authoritative. If it cannot be read, staging retains the prior
- best-effort listing and resident sizing declines to issue a hard refusal.
- """
+ """Return selected component folders and exact model-index ignores. The manifest is small but
+ authoritative. If it cannot be read, staging retains the prior best-effort listing and
+ resident sizing declines to issue a hard refusal."""
try:
from huggingface_hub import hf_hub_download
diff --git a/studio/backend/core/inference/diffusion_arch_patches.py b/studio/backend/core/inference/diffusion_arch_patches.py
index db6143385ac..987b0a4b9a3 100644
--- a/studio/backend/core/inference/diffusion_arch_patches.py
+++ b/studio/backend/core/inference/diffusion_arch_patches.py
@@ -179,7 +179,6 @@ def _spec_zimage_forward():
return (cls, "forward", _zimage_forward)
-# flux.1: block modulation goes via AdaLayerNormZero
# flux.1: FluxTransformerBlock / FluxSingleTransformerBlock. Block modulation goes via AdaLayerNormZero; here we fuse
# the inline norm2 modulation and the gated residual adds.
def _flux_double_forward(
@@ -307,7 +306,6 @@ def _spec_flux_single():
return (cls, "forward", _flux_single_forward)
-# flux.2-klein: modulation is INLINE, and scale/shift/gate are [B,1,dim], so no [:, None]
# flux.2-klein: Flux2TransformerBlock / Flux2SingleTransformerBlock. Modulation is INLINE, so fuse both;
# scale/shift/gate are [B,1,dim], so no [:, None].
def _flux2_double_forward(
@@ -486,8 +484,7 @@ def _spec_krea2_forward():
return (cls, "forward", _krea2_block_forward)
-# each entry is a zero-arg resolver returning (cls, attr, new_fn) or None; all COMPILE-SAFE
-# registry + lifecycle. Each entry is a zero-arg resolver returning (cls, attr, new_fn) or None. All COMPILE-SAFE.
+# Registry + lifecycle. Each entry is a zero-arg resolver returning (cls, attr, new_fn) or None. All COMPILE-SAFE.
_SPECS: tuple[Callable[[], Optional[tuple]], ...] = (
_spec_qwen_modulate,
_spec_zimage_forward,
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 58350c1bf39..2d7aa36b485 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -106,8 +106,6 @@ def _is_cuda_nvidia(target: Any) -> bool:
try:
import torch
- # torch.version.hip alone misreads AMD wheels that only tag __version__, dropping aiter and pointing
- # cuDNN/xformers at a ROCm card
# Shared with the stub installer: torch.version.hip alone misreads AMD wheels that only tag __version__,
# dropping aiter and pointing cuDNN/xformers (stubbed there) at a ROCm card.
from core._torchao_stub import _module_is_rocm
@@ -116,15 +114,12 @@ def _is_cuda_nvidia(target: Any) -> bool:
return False
-# torch's flash_sdp_enabled() / mem_efficient_sdp_enabled() report the USER TOGGLE (#8225)
-# ── what the native SDPA dispatch can actually run (#8225) ─────────────────── torch's ``flash_sdp_enabled()`` /
-# ``mem_efficient_sdp_enabled()`` report the USER TOGGLE, not whether a kernel exists for this device. On the ROCm build
-# in #8225 (gfx1200, torch 2.11+rocm7) both answer True while every dispatch to them raises "No available kernel.
-# Aborting execution.", so the dispatcher degrades silently to MATH -- and MATH is the one backend that materialises the
-# whole B x heads x N x N score matrix. That is how a 3.4 GB Q4_K_M video model asked a 16 GB card for a single 66.54
-# GiB allocation 70 seconds into a generation. So do not read the flags. Run one tiny attention per backend and record
-# what happens.
-# ── what the native SDPA dispatch can actually run (#8225) ───────────────────
+# What the native SDPA dispatch can actually run (#8225). torch's ``flash_sdp_enabled()`` /
+# ``mem_efficient_sdp_enabled()`` report the USER TOGGLE, not whether a kernel exists for this device. On the ROCm
+# build in #8225 (gfx1200, torch 2.11+rocm7) both answer True while every dispatch to them raises "No available
+# kernel. Aborting execution.", so the dispatcher degrades silently to MATH -- the one backend that materialises the
+# whole B x heads x N x N score matrix, which is how a 3.4 GB Q4_K_M video model asked a 16 GB card for a single 66.54
+# GiB allocation. So do not read the flags: run one tiny attention per backend and record what happens.
SDPA_FLASH = "flash"
SDPA_MEM_EFFICIENT = "mem_efficient"
SDPA_CUDNN = "cudnn"
@@ -134,7 +129,6 @@ SDPA_MATH = "math"
_SDPA_SUBQUADRATIC = (SDPA_FLASH, SDPA_MEM_EFFICIENT, SDPA_CUDNN)
_SDPA_PROBE_LOCK = threading.Lock()
-# a kernel cannot appear or vanish under a running interpreter
# (device type, dtype name) -> the kernels that ran. A kernel cannot appear or vanish under a running interpreter, so
# one probe per device/dtype for the life of the process.
_SDPA_PROBE_CACHE: dict[tuple[str, str], tuple[str, ...]] = {}
@@ -280,7 +274,6 @@ def _cudnn_attention_supported() -> bool:
return have is None or have >= (8, 0)
-# dispatcher name -> (probe module, pip package)
# Optional kernels installable on demand: dispatcher name -> (probe module, pip package). Wheels only
# (--only-binary=:all:), since a source build needs a CUDA toolchain the host may lack.
_INSTALLABLE_BACKENDS: dict[str, tuple[str, str]] = {
@@ -293,12 +286,10 @@ _INSTALLABLE_BACKENDS: dict[str, tuple[str, str]] = {
"xformers": ("xformers", "xformers"),
}
-# on-demand install gate: auto (default) / 1 installs a missing package when a gated backend is requested
-# On-demand install gate (mirrors UNSLOTH_DIFFUSION_SD_CPP_INSTALL): auto (default) / 1 installs a missing package when
-# a gated backend is requested; 0 never installs and falls back to native.
+# On-demand install gate (mirrors UNSLOTH_DIFFUSION_SD_CPP_INSTALL): auto (default) / 1 installs a missing package
+# when a gated backend is requested; 0 never installs and falls back to native.
_ATTENTION_INSTALL_ENV = "UNSLOTH_DIFFUSION_ATTENTION_INSTALL"
-# the loader pre-installs outside its locks
# Packages a pip install was already attempted for in THIS process. The loader pre-installs outside its locks, so a
# recorded attempt stops apply re-running the 600s install under _generate_lock.
_INSTALL_ATTEMPTED: set[str] = set()
@@ -332,21 +323,21 @@ def _redacted_for_log(text: str) -> str:
def _xformers_wheel_target() -> tuple[Optional[str], Optional[str]]:
"""Resolve the xFormers wheel built for the resident torch: (URL, refusal reason).
- xformers' compiled extension is linked against ONE exact (torch, CUDA) pair, and next
- to any other pair ``torch.ops.load_library`` raises -- which xformers/_cpp_lib.py then
- downgrades to a log warning, so the import "succeeds" with memory-efficient attention,
- SwiGLU and the sparse ops silently gone. That is invisible to ``find_spec`` and to pip.
- PyPI publishes only the CUDA-12.8 flavour, so a plain ``pip install xformers`` beside a
- cu130 torch installs the broken combination every time.
-
- So resolve the exact download.pytorch.org wheel instead, and when no wheel matches
- return a reason rather than a URL: installing nothing leaves the caller on torch SDPA,
- which is strictly better than installing an extension that cannot load.
-
- The URL is not HEAD-checked here. This can run under ``_generate_lock`` (the video
- loader has no out-of-lock pre-install hop, unlike the image one), so it must not add
- network round trips to a path that already blocks unload/cancel; a wrong row surfaces
- as a pip failure instead, and the matrix has a live-URL test behind it.
+ xformers' compiled extension is linked against ONE exact (torch, CUDA) pair, and next to any
+ other pair ``torch.ops.load_library`` raises -- which xformers/_cpp_lib.py then downgrades to a
+ log warning, so the import "succeeds" with memory-efficient attention, SwiGLU and the sparse ops
+ silently gone. That is invisible to ``find_spec`` and to pip, and PyPI publishes only the
+ CUDA-12.8 flavour, so a plain ``pip install xformers`` beside a cu130 torch installs the broken
+ combination every time.
+
+ So resolve the exact download.pytorch.org wheel instead, and when no wheel matches return a
+ reason rather than a URL: installing nothing leaves the caller on torch SDPA, which is strictly
+ better than an extension that cannot load.
+
+ The URL is not HEAD-checked here. This can run under ``_generate_lock`` (the video loader has no
+ out-of-lock pre-install hop), so it must not add network round trips to a path that already
+ blocks unload/cancel; a wrong row surfaces as a pip failure instead, and the matrix has a
+ live-URL test behind it.
"""
global _XFORMERS_WHEEL_TARGET
with _XFORMERS_WHEEL_LOCK:
@@ -362,8 +353,8 @@ def _xformers_wheel_target() -> tuple[Optional[str], Optional[str]]:
return (None, f"the xFormers wheel could not be resolved ({exc})")
if env is None:
# Ambiguous: a platform wheel_platform_tag() does not name (macOS, Windows on ARM) which is deterministic,
- # or a probe that timed out on a busy box which is transient. Not cached, so the next request can settle it.
- # Linux aarch64 is NOT here -- it gets a platform_tag and so lands on the branch below.
+ # or a probe that timed out on a busy box which is transient. Not cached, so the next request can settle
+ # it. Linux aarch64 is NOT here: it gets a platform_tag and so lands on the branch below.
return (
None,
"torch could not be probed, or this platform has no xFormers wheel "
@@ -414,20 +405,19 @@ _KERNELS_HUB_FLOOR = (1, 10)
def _kernels_hub_compatible() -> bool:
"""Whether installing the ``kernels`` package is SAFE next to the resident huggingface_hub.
- Current ``kernels`` wheels declare ``huggingface_hub >= 1.10`` and build their dependency
- tables against that API, and with an older hub the breakage is NOT contained to the requested
- backend: ``import kernels`` raises at module scope, and diffusers imports ``kernels`` whenever
- it is installed, so EVERY later pipeline import in every process fails until the package is
+ Current ``kernels`` wheels declare ``huggingface_hub >= 1.10`` and build their dependency tables
+ against that API, and with an older hub the breakage is NOT contained to the requested backend:
+ ``import kernels`` raises at module scope, and diffusers imports ``kernels`` whenever it is
+ installed, so EVERY later pipeline import in every process fails until the package is
uninstalled. Measured with kernels 0.16.0: hub 1.0.0-1.2.4 raise
- ``StrictDataclassFieldValidationError`` on ``import kernels`` (the strict dataclasses only
- learned ``str | None`` unions in hub 1.3.0), and 1.3-1.9 merely happen to work today, below
- the floor kernels supports. The whole 1.x range under 1.10 is therefore refused rather than
- trusted, since the install is unpinned and a future kernels may use any 1.10 API. The
- requested hub backend falls back to native instead. An undeterminable hub version allows the
- install, which keeps the previous behaviour.
-
- A ``--no-deps`` install cannot self-correct here: pip writes the wheel without ever reading
- its ``Requires-Dist``, so this predicate is the only thing enforcing that floor."""
+ ``StrictDataclassFieldValidationError`` on ``import kernels``, and 1.3-1.9 merely happen to work
+ today, below the floor kernels supports. The whole 1.x range under 1.10 is therefore refused
+ rather than trusted, since the install is unpinned. An undeterminable hub version allows the
+ install, keeping the previous behaviour.
+
+ A ``--no-deps`` install cannot self-correct here: pip writes the wheel without ever reading its
+ ``Requires-Dist``, so this predicate is the only thing enforcing that floor.
+ """
try:
import re
from importlib.metadata import version
@@ -443,15 +433,15 @@ def _kernels_hub_compatible() -> bool:
def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Optional[str]:
"""Best-effort wheel-only install of the package ``backend`` needs, when allowed.
- Called after arch gating, so only for a backend that could work here. Failure is swallowed:
- the subsequent set_attention_backend raises on the missing package and falls back to native.
+ Called after arch gating, so only for a backend that could work here. Failure is swallowed: the
+ subsequent set_attention_backend raises on the missing package and falls back to native.
- Returns the reason the install was REFUSED (a policy decision, e.g. no CUDA-matched
- xFormers wheel exists for the resident torch), or None when nothing stood in the way --
- the install ran, was skipped as already present, or merely failed. Every refusal is also
- logged at warning level; the return value is there so a caller that wants to surface the
- reason (rather than silently falling back to native) can, and both current callers
- deliberately ignore it."""
+ Returns the reason the install was REFUSED (a policy decision, e.g. no CUDA-matched xFormers
+ wheel exists for the resident torch), or None when nothing stood in the way -- the install ran,
+ was skipped as already present, or merely failed. Every refusal is also logged at warning level;
+ the return value is there so a caller that wants to surface the reason can, and both current
+ callers deliberately ignore it.
+ """
import importlib.util
import os
@@ -507,10 +497,9 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Opt
)
return refusal
package = wheel_url
- # UNSLOTH_PYTORCH_MIRROR may carry a token for a private index and is baked into the wheel URL
- # What pip gets and what the log gets are not the same string. UNSLOTH_PYTORCH_MIRROR may carry userinfo or a token
- # for a private index, and it is baked into the wheel URL, so logging the URL verbatim writes that secret into the
- # backend log.
+ # What pip gets and what the log gets are not the same string. UNSLOTH_PYTORCH_MIRROR may carry userinfo or a
+ # token for a private index, and it is baked into the wheel URL, so logging the URL verbatim writes that secret
+ # into the backend log.
display = _redacted_for_log(package)
# attempt each install once per process, else the in-lock apply re-runs it under _generate_lock and blocks
# unload/cancel
@@ -526,12 +515,10 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Opt
)
try:
subprocess.run(
- # --no-deps: install ONLY this kernel wheel
# --no-deps: install ONLY this kernel wheel, since xformers/flash-attn pin an exact torch and normal
# resolution would replace the running one. It also means pip never reads the wheel's `Requires-Dist:
- # torch==X`, so nothing here would catch an ABI mismatch -- for xformers, whose mismatch is SILENT (the
- # extension fails to load and _cpp_lib.py logs a warning), the URL was resolved against the running torch
- # above precisely so there is nothing left to catch.
+ # torch==X`, so nothing here would catch an ABI mismatch -- for xformers, whose mismatch is SILENT, the
+ # URL was resolved against the running torch above precisely so there is nothing left to catch.
[
sys.executable,
"-m",
@@ -687,37 +674,25 @@ def _warn(logger: Any, what: str, exc: Exception) -> None:
logger.warning("diffusion.attention: %s unavailable (%s); using default", what, exc)
-# -------------------------------------------------------------------------------------- HunyuanVideo-1.5
-# joint-attention padding trim (accuracy-exact speed win) HunyuanVideo15AttnProcessor2_0 runs a JOINT [video ; text]
-# self-attention and, on EVERY block and step, materialises a dense [B,1,N,N] boolean mask so the video never attends to
-# padded text. But a dense bool attn_mask costs most of what the fused kernels are for. Established by output identity,
-# not by timing, since dispatch overhead makes timings alone ambiguous: FLASH refuses a non-null mask outright, MATH
-# OOMs on the 75.5 GiB [1,16,N,N] score matrix, and the default dispatch is BITWISE-equal to forced cuDNN (296.11 vs
-# 296.00 ms), so cuDNN is what runs -- on a masked path 20x slower than its own unmasked one. On a B200 at the
-# production shape (N~=50k, 121 frames 480p) the SAME attention is 296 ms WITH the dense mask vs 15 ms with
-# attn_mask=None. (An aside worth knowing before optimising here: forced EFFICIENT does the masked attention in 168 ms,
-# so the dispatcher's masked pick is not even the fastest available one.) (torch 2.12;
-# scripts/sdpa_mask_backend_probe.py re-measures it, and also shows MATH OOMing on the 75.5 GiB score matrix and FLASH
-# refusing a dense mask outright). END TO END that is 10.4x: a full 121-frame 832x480 10-step render goes 353.8s ->
-# 33.9s, medians of 3, reproduced across two runs purely to mask padding. And the text is ~99.5% padding: a t2v prompt
-# fills only ~9 of ~1985 slots (image 729 + byt5 256 + mllm 1000, almost all zero-padded). The fix is exact: the model
-# already masks the padded text and DISCARDS its attention output (only the video split feeds proj_out), so removing the
-# padded tokens before attention changes nothing for the video. "Exact" here means no information is discarded, NOT
-# bit-reproducible: swapping masked for fused SDPA perturbs each step at bf16 rounding scale (one DiT forward on
-# identical inputs differs by 6.6e-3 relative, cosine 0.99998) and 10 denoising steps amplify that chaotically, so the
-# finished video is visibly a different sample. That is intrinsic to the kernel change, not to the trim: rendering the
-# SAME dense-mask path under two different exact SDPA kernels diverges MORE (LPIPS 0.303 vs the trim's 0.285, SSIM 0.744
-# vs 0.767, over 13 sampled frames). Whole-video LPIPS cannot judge a kernel change at this step count; the
-# single-forward relative error is the metric that can. Done in an eager forward pre-hook (outside the compiled blocks):
-# drop the all-zero image stream (t2v), trim the mllm/byt5 streams to their globally-valid columns, and -- when nothing
-# partially-padded remains (the common batch-1 / per-branch call) -- flag the DiT so the processor skips the dense mask
-# and runs the fused path. The only numeric change is the SDPA kernel (masked -> fused), on par with the shipped cuDNN
-# backend swap. Mixed-padding batches fall back to the stock dense mask. SHAPE NOTE: the trimmed text length is
-# prompt-dependent, so the compiled blocks see a new shape per prompt. That is free on the default speed tier (compiled
-# with dynamic=True) but not on ``max`` (dynamic=False), where each length is its own graph and a fullgraph region
-# hard-errors once dynamo's recompile limit is reached. The caller therefore only installs the trim on a tier that
-# compiles dynamically; see the call site in video.py.
-# --------------------------------------------------------------------------------------
+# HunyuanVideo-1.5 joint-attention padding trim (accuracy-exact speed win). HunyuanVideo15AttnProcessor2_0 runs a
+# JOINT [video ; text] self-attention and, on every block and step, materialises a dense [B,1,N,N] boolean mask so the
+# video never attends to padded text. A dense bool attn_mask costs most of what the fused kernels are for: at the
+# production shape (N~=50k, 121 frames 480p, B200) the SAME attention is 296 ms with the dense mask against 15 ms with
+# attn_mask=None, and end to end a 121-frame 832x480 10-step render goes 353.8s -> 33.9s. The text is ~99.5% padding
+# (a t2v prompt fills ~9 of ~1985 slots). The fix is exact: the model already masks the padded text and DISCARDS its
+# attention output (only the video split feeds proj_out), so removing the padded tokens before attention changes
+# nothing for the video. "Exact" means no information is discarded, NOT bit-reproducible: swapping masked for fused
+# SDPA perturbs each step at bf16 rounding scale and 10 denoising steps amplify that, so the finished video is a
+# different sample. That is intrinsic to the kernel change, not to the trim, since rendering the SAME dense-mask path
+# under two different exact SDPA kernels diverges more. Whole-video LPIPS cannot judge a kernel change at this step
+# count; the single-forward relative error can. scripts/sdpa_mask_backend_probe.py re-measures all of it. Done in an
+# eager forward pre-hook (outside the compiled blocks): drop the all-zero image stream (t2v), trim the mllm/byt5
+# streams to their globally-valid columns, and, when nothing partially-padded remains, flag the DiT so the processor
+# skips the dense mask and runs the fused path. Mixed-padding batches fall back to the stock dense mask. SHAPE NOTE:
+# the trimmed text length is prompt-dependent, so the compiled blocks see a new shape per prompt. Free on the default
+# speed tier (dynamic=True) but not on ``max`` (dynamic=False), where each length is its own graph and a fullgraph
+# region hard-errors at dynamo's recompile limit. The caller therefore only installs the trim on a tier that compiles
+# dynamically; see the call site in video.py.
_HUNYUAN15_TRANSFORMER_CLS = "HunyuanVideo15Transformer3DModel"
_HUNYUAN15_PROCESSOR_CLS = "HunyuanVideo15AttnProcessor2_0"
_NULL_ATTN_FLAG = "_unsloth_null_attn_mask"
@@ -860,13 +835,15 @@ def _trim_stream(states, mask):
def _hunyuan_trim_pre_hook(module, args, kwargs):
"""Eager forward pre-hook: strip padded text tokens so the joint attention runs fused.
- - Drop the image stream when it is entirely zero (t2v): those ~729 tokens are pure padding.
- This is upstream's own t2v sentinel (``is_t2v = torch.all(image_embeds == 0)``), and
- ``torch.all`` of an empty tensor is vacuously True, so emptying the axis keeps it True.
+ - Drop the image stream when it is entirely zero (t2v): those ~729 tokens are pure padding. This
+ is upstream's own t2v sentinel (``is_t2v = torch.all(image_embeds == 0)``), and ``torch.all`` of
+ an empty tensor is vacuously True, so emptying the axis keeps it True.
+
- Trim the mllm/byt5 text streams to their globally-valid columns.
+
- Flag every block's attention so the null-mask processor skips the dense mask when nothing
- partially-padded remains (the batch-1 / per-guidance-branch case); otherwise leave the
- flag False and the stock dense-mask path handles the residual padding correctly.
+ partially-padded remains; otherwise leave the flag False and the stock dense-mask path handles
+ the residual padding.
This hook is the correctness choke point: the null-mask flag is valid only because the padding
was removed HERE, on the same call. It fires on ``module(...)`` (``__call__``), which the
@@ -876,9 +853,8 @@ def _hunyuan_trim_pre_hook(module, args, kwargs):
The three ``.item()`` reads below are host syncs, but this hook runs eagerly outside the
compiled blocks (~3 syncs against a ~1.3 s forward), so they must stay here and not be folded
- into the graph.
-
- Best-effort: any anomaly leaves the inputs untouched and the flag False."""
+ into the graph. Best-effort: any anomaly leaves the inputs untouched and the flag False.
+ """
import torch
original = dict(kwargs)
@@ -895,10 +871,9 @@ def _hunyuan_trim_pre_hook(module, args, kwargs):
("encoder_hidden_states", "encoder_attention_mask", True),
("encoder_hidden_states_2", "encoder_attention_mask_2", False),
):
- # only touch streams passed by keyword; An absent REQUIRED primary stream drops the fast path
# Only touch streams passed by keyword (the pipeline always does); never write back an absent key (a
- # positional encoder_hidden_states would collide). An absent REQUIRED primary stream drops the fast path; an
- # absent optional byt5 is fine.
+ # positional encoder_hidden_states would collide). An absent REQUIRED primary stream drops the fast path;
+ # an absent optional byt5 is fine.
if skey not in kwargs:
null_ok = null_ok and not required
continue
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.py
index a451c8b303e..81060a9d237 100644
--- a/studio/backend/core/inference/diffusion_auto_policy.py
+++ b/studio/backend/core/inference/diffusion_auto_policy.py
@@ -27,9 +27,9 @@ from typing import Any, Optional
_MIB_PER_GB = 1000.0**3 / (1024.0 * 1024.0) # component sizes below are decimal GB
-# int8/fp8 store one byte per param plus per-row scales (~0.52x with slack for bf16 norms/embeddings);
-# Steady size of a torchao-quantised transformer relative to bf16: int8/fp8 store one byte per param plus per-row scales
-# (~0.52x with slack for bf16 norms/embeddings); nvfp4 packs two per byte plus block scales. Measured on live loads.
+# Steady size of a torchao-quantised transformer relative to bf16: int8/fp8 store one byte per param plus per-row
+# scales (~0.52x with slack for bf16 norms/embeddings); nvfp4 packs two per byte plus block scales. Measured on live
+# loads.
_QUANT_STEADY_FACTOR: dict[str, float] = {
"int8": 0.55,
"fp8": 0.55,
@@ -37,8 +37,6 @@ _QUANT_STEADY_FACTOR: dict[str, float] = {
"nvfp4": 0.33,
}
-# what they occupy on device after the dtype cast, NOT the download size (Z-Image-Turbo ships fp32: 24.6 GB of shards ->
-# 12.3 GB bf16).
# bf16-RESIDENT component sizes in decimal GB: (transformer, text encoders, VAE). What they occupy on device after the
# dtype cast, NOT the download size (Z-Image-Turbo ships fp32: 24.6 GB of shards -> 12.3 GB bf16). From HF sibling
# metadata.
@@ -55,7 +53,6 @@ _FAMILY_BF16_GB: dict[str, tuple[float, float, float]] = {
"lumina-2": (5.2, 5.2, 0.2),
# 17B dual-stream DiT (32.5 GB bf16 on disk) + Qwen2.5-VL 15.5 GB + ByT5 0.8 GB.
"hunyuanimage-2.1": (32.5, 16.3, 0.8),
- # 17B MoE DiT + four text encoders (CLIP-L, CLIP-G, T5-XXL), plus Llama-3.1-8B from the open mirror at load time
# 17B MoE DiT (34.2 GB bf16) + FOUR text encoders: CLIP-L 0.5 + CLIP-G 2.8 + T5-XXL 9.5, plus Llama-3.1-8B (~16 GB
# bf16) from the open mirror at load time.
"hidream-i1": (34.2, 28.8, 0.2),
@@ -64,24 +61,20 @@ _FAMILY_BF16_GB: dict[str, tuple[float, float, float]] = {
"ideogram-4": (37.2, 16.3, 0.2),
}
-# Hub DOWNLOAD bytes relative to the resident sizes above, for families not stored at bf16 Hub DOWNLOAD bytes relative
-# to the bf16-resident sizes above, for families whose published checkpoints are not stored at bf16. The free-disk gate
-# needs what lands in the HF cache, which differs by 2x in either direction here. From HF metadata: z-image Turbo
-# transformer/ 23,479 MiB fp32 -> 11,730 MiB resident (2.00x) lumina-2 transformer/ 9,956 MiB fp32 -> 4,959 MiB resident
-# (2.01x) ideogram-4 transformer/ + unconditional_transformer/ 17,718 MiB fp8 -> 35,477 MiB resident (0.50x) Anything
-# absent ships bf16 and downloads what it occupies (measured 0.99-1.07x).
+# Hub DOWNLOAD bytes relative to the bf16-resident sizes above, for families whose published checkpoints are not
+# stored at bf16. The free-disk gate needs what lands in the HF cache, which differs by 2x in either direction here.
+# From HF metadata: z-image and lumina-2 publish fp32 (2.00x), ideogram-4 publishes fp8 (0.50x). Anything absent ships
+# bf16 and downloads what it occupies (measured 0.99-1.07x).
_FAMILY_HUB_DOWNLOAD_FACTOR: dict[str, float] = {
"z-image": 2.0,
"lumina-2": 2.0,
"ideogram-4": 0.5,
}
-# only Tongyi-MAI/Z-Image needs one: the distilled Turbo publishes fp32 while the undistilled base ships bf16 and
-# downloads exactly what it occupies
-# Per-base overrides of the factor above, for a checkpoint stored at a different precision from its family default. Only
-# Tongyi-MAI/Z-Image needs one: the family key exists because the distilled Turbo publishes fp32 (23,479 MiB), while the
-# undistilled base ships bf16 (11,740 MiB) and so downloads exactly what it occupies. Without it the free-disk gate
-# demands twice the real size.
+# Per-base overrides of the factor above, for a checkpoint stored at a different precision from its family default.
+# Only Tongyi-MAI/Z-Image needs one: the family key exists because the distilled Turbo publishes fp32 (23,479 MiB),
+# while the undistilled base ships bf16 (11,740 MiB) and so downloads exactly what it occupies. Without it the
+# free-disk gate demands twice the real size.
_BASE_REPO_HUB_DOWNLOAD_FACTOR: dict[str, float] = {
"tongyi-mai/z-image": 1.0,
}
@@ -158,12 +151,11 @@ def hub_download_factor(fam: Any, base_repo: Optional[str] = None) -> float:
return _FAMILY_HUB_DOWNLOAD_FACTOR.get(getattr(fam, "name", None), 1.0)
-# flux.2-klein ships FOUR checkpoints under one entry
# Base-repo overrides for families offering multiple sizes under one entry (the table carries the family default).
# flux.2-klein ships FOUR checkpoints under one entry: 4B / base-4B (the family default, Qwen3-4B encoder) and 9B /
# base-9B (18.2 GB transformer, Qwen3-8B encoder). The 9B pair needs an override on BOTH ids: sizing klein-BASE-9B off
-# the family default understates it by 2.3x, and the base variants are the ones the upstream guidance points fine-tuning
-# at, so it is the likelier of the two to be loaded.
+# the family default understates it by 2.3x, and the base variants are the ones upstream guidance points fine-tuning
+# at.
_BASE_REPO_BF16_GB: dict[str, tuple[float, float, float]] = {
"black-forest-labs/flux.2-klein-9b": (18.2, 16.4, 0.2),
"black-forest-labs/flux.2-klein-base-9b": (18.2, 16.4, 0.2),
@@ -210,9 +202,8 @@ class DenseQuantEstimate:
companions_mib: int
prequant: bool
download_transformer_mib: int = 0
- # the memory planner needs the text-encoder share to price the group tier that streams the encoders;
- # The TEXT-ENCODER share of ``companions_mib``. The memory planner needs it to price the group tier that streams the
- # encoders instead of keeping them resident, and this table is the only place the split exists on the
+ # The TEXT-ENCODER share of ``companions_mib``. The memory planner needs it to price the group tier that streams
+ # the encoders instead of keeping them resident, and this table is the only place the split exists on the
# dense-candidate path. Defaulted so any construction that predates it still works (the planner reads a 0 split as
# "no split", i.e. no new tier).
text_encoders_mib: int = 0
@@ -325,7 +316,6 @@ def resolve_dense_quant_candidate(
# no bytes, which is the opposite of what the retry assumes about local paths.
prequant_cached = True
elif src is not None:
- # pin the ACTIVE root, as the retry and loader do
# Pin the ACTIVE root, as the retry and the loader both do. Unpinned, cached_checkpoint_path searches
# only huggingface_hub's import-time constant, so after a cache-folder change the retry proves the
# checkpoint cached in the live root and this would still call it uncached and re-apply the gate.
@@ -374,13 +364,11 @@ def resolve_dense_quant_candidate(
return estimate
-# an `auto` precision is a delegation, so falling back is the feature working
-# ── strict precision (fail closed on a declined EXPLICIT request) ──────────── An `auto` precision is a delegation, so
-# falling back down the ladder is the feature working. An EXPLICIT scheme is a contract: silently loading the GGUF (or a
-# dense bf16 DiT) instead produced a perfectly good image at a precision nobody asked for, which is exactly what made a
-# successful render worthless as proof that the requested precision ran. Escape hatch for anyone who relied on the old
-# behaviour; unset (the default) fails closed.
-# ── strict precision (fail closed on a declined EXPLICIT request) ────────────
+# Strict precision: fail closed on a declined EXPLICIT request. An `auto` precision is a delegation, so falling back
+# down the ladder is the feature working. An EXPLICIT scheme is a contract: silently loading the GGUF (or a dense bf16
+# DiT) instead produced a perfectly good image at a precision nobody asked for, which is what made a successful render
+# worthless as proof that the requested precision ran. Escape hatch for anyone who relied on the old behaviour; unset
+# (the default) fails closed.
_PRECISION_FALLBACK_ENV = "UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK"
@@ -414,11 +402,9 @@ def precision_refusal_message(
return f"{control}='{requested}' could not be used: {reason}. {remedy}"
-# how the engaged value relates to what the caller asked for
-# ── resolved-record (status surface) ───────────────────────────────────────── How the engaged value relates to what
-# the caller asked for. Additive on the status payload: every honored request and every auto decision reports "applied",
-# so a client that ignores the field sees exactly today's behaviour.
-# ── resolved-record (status surface) ─────────────────────────────────────────
+# Resolved-record (status surface). How the engaged value relates to what the caller asked for. Additive on the status
+# payload: every honored request and every auto decision reports "applied", so a client that ignores the field sees
+# exactly today's behaviour.
RESOLVED_APPLIED = "applied" # the ask was honored (or there was no ask)
RESOLVED_FELL_BACK = "fell_back" # an explicit ask was declined and something ELSE engaged
RESOLVED_UNSUPPORTED = "unsupported" # an explicit ask cannot run on this host / model at all
diff --git a/studio/backend/core/inference/diffusion_batched.py b/studio/backend/core/inference/diffusion_batched.py
index b4eda771f77..a1cf1909cb3 100644
--- a/studio/backend/core/inference/diffusion_batched.py
+++ b/studio/backend/core/inference/diffusion_batched.py
@@ -30,9 +30,8 @@ from __future__ import annotations
from typing import Any, Callable, Optional
-# cap on images per call: a longer list is a client error, not an OOM to back off from
-# Upper bound on images per generation call (mirrors the route's cap): a longer prompt/seed list is a client error, not
-# an OOM to back off from.
+# Upper bound on images per generation call (mirrors the route's cap): a longer prompt/seed list is a client error,
+# not an OOM to back off from.
MAX_BATCH_IMAGES = 32
# Seeds stay in JS's safe-integer range so they round-trip through the JSON gallery recipes (a raw 64-bit seed loses
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.py
index b72f5ac78bc..2a26e6fadf8 100644
--- a/studio/backend/core/inference/diffusion_cache.py
+++ b/studio/backend/core/inference/diffusion_cache.py
@@ -27,16 +27,13 @@ TC_AUTO = "auto"
TC_FBCACHE = "fbcache"
TC_MODES = (TC_FBCACHE,)
-# higher skips more steps (faster, lower quality)
# FBCache residual thresholds: higher skips more steps (faster, lower quality). Quantised transformers shift the
# residual distribution, so they need a higher threshold.
DEFAULT_FBCACHE_THRESHOLD = 0.08
QUANT_FBCACHE_THRESHOLD = 0.12
-# FBCache's win scales with step count, so auto engages only at 20+ ("dev" schedules qualify, distilled turbo never
-# does)
-# Auto step-count bar: FBCache's win scales with step count, so auto engages only at 20+ steps ("dev" schedules qualify,
-# distilled turbo never does).
+# Auto step-count bar: FBCache's win scales with step count, so auto engages only at 20+ steps ("dev" schedules
+# qualify, distilled turbo never does).
FBCACHE_MIN_STEPS = 20
@@ -121,7 +118,6 @@ def _compile_hooked_block_inners(transformer: Any, logger: Any = None) -> int:
continue
if getattr(orig, "__self__", None) is None:
continue # not a plain bound method; arming would miss the block
- # fullgraph=False / dynamic=True: a cache's decision graph-breaks
# fullgraph=False / dynamic=True: a cache is active (its decision graph-breaks) and this matches the
# default tier. Dynamo caches per code object, so re-arming after a toggle is ~free.
fn_ref.original_forward = torch.compile(orig, fullgraph = False, dynamic = True)
@@ -205,18 +201,15 @@ def apply_step_cache(
if threshold is not None
else (QUANT_FBCACHE_THRESHOLD if quant_active else DEFAULT_FBCACHE_THRESHOLD)
)
- # native enable_cache only: apply_first_block_cache would also install on a non-CacheMixin transformer whose
- # pipeline opens no cache_context
- # Engage only via the native enable_cache (CacheMixin path): the lower-level apply_first_block_cache hook would also
- # install on a non-CacheMixin transformer whose pipeline opens no cache_context, and crash generation.
+ # Engage only via the native enable_cache (CacheMixin path): the lower-level apply_first_block_cache hook would
+ # also install on a non-CacheMixin transformer whose pipeline opens no cache_context, and crash generation.
enable_cache = getattr(transformer, "enable_cache", None)
if not callable(enable_cache):
_warn(logger, mode, RuntimeError("transformer has no cache_context (not a CacheMixin)"))
return None
- # the hook raises "No context is set" unless the PIPELINE wraps its denoise loop in cache_context();
- # A CacheMixin transformer is necessary but not sufficient: the hook raises "No context is set" unless the PIPELINE
- # wraps its denoise loop in cache_context(...). Flux Kontext / img2img / inpaint / controlnet open none, so run
- # uncached.
+ # A CacheMixin transformer is necessary but not sufficient: the hook raises "No context is set" unless the
+ # PIPELINE wraps its denoise loop in cache_context(...). Flux Kontext / img2img / inpaint / controlnet open none,
+ # so run uncached.
if not _pipeline_opens_cache_context(pipe):
_warn(
logger, mode, RuntimeError("pipeline __call__ opens no cache_context; running uncached")
@@ -233,9 +226,8 @@ def apply_step_cache(
# enable_cache after the pipe ran leaves a stale cached child-registry list, so the new block hooks would never
# receive the cache context. Must follow every enable_cache.
_invalidate_child_registry_cache(transformer)
- # already regionally compiled (toggle path): re-point the fresh hooks at compiled inners
- # If blocks are already regionally compiled (toggle path), re-point the fresh hooks' compute branch at compiled
- # inners; the load path is armed by _compile_repeated_blocks.
+ # If blocks are already regionally compiled (toggle path), re-point the fresh hooks' compute branch at
+ # compiled inners; the load path is armed by _compile_repeated_blocks.
_compile_hooked_block_inners(transformer, logger)
try:
transformer._unsloth_step_cache = f"{mode}@{thr}"
diff --git a/studio/backend/core/inference/diffusion_compat.py b/studio/backend/core/inference/diffusion_compat.py
index 302ed895b1f..582417cd3de 100644
--- a/studio/backend/core/inference/diffusion_compat.py
+++ b/studio/backend/core/inference/diffusion_compat.py
@@ -3,24 +3,23 @@
"""Metadata-only compatibility preflight for a diffusion pick.
-A FLUX.2 GGUF only carries the transformer; its size (``inner_dim``) has to agree with the
-companion diffusers base repo the loader assembles around it. ``assert_flux2_gguf_matches_base``
-already catches a mismatch, but it opens the downloaded checkpoint, so it fires from inside
-``load_pipeline`` -- after the prefetch pulled ~19 GB of base shards and after the resident
-pipeline was torn down to make room. The user paid for both to be told the pick was never valid.
-
-This module answers the same question from metadata alone: one HTTP range request for the first
-few hundred KiB of the GGUF, which is where its tensor table lives. That is cheap enough to run
-at SELECTION time (``/images/download-plan``) and again on the pre-eviction path, so the refusal
-lands before a byte moves and before anything is unloaded.
-
-Fail-open throughout, deliberately: an unreadable or truncated header, a base repo outside the
-size table, an offline host, a server that ignores Range -- all yield "no opinion", and the load
-proceeds exactly as it does today with the loader's own guard as the backstop. A false positive
-here would refuse a pick that works, which is strictly worse than the download this saves.
-
-(A known ungated MIRROR of a base is not an exception to that: it is byte-identical to what it
-copies, ``canonical_base`` maps it back, and it is checked like its upstream.)
+A FLUX.2 GGUF only carries the transformer; its size (``inner_dim``) has to agree with the companion
+diffusers base repo the loader assembles around it. ``assert_flux2_gguf_matches_base`` already
+catches a mismatch, but it opens the downloaded checkpoint, so it fires from inside
+``load_pipeline`` -- after the prefetch pulled ~19 GB of base shards and after the resident pipeline
+was torn down to make room.
+
+This module answers the same question from metadata alone: one HTTP range request for the first few
+hundred KiB of the GGUF, where its tensor table lives. That is cheap enough to run at SELECTION time
+(``/images/download-plan``) and again on the pre-eviction path, so the refusal lands before a byte
+moves and before anything is unloaded.
+
+Fail-open throughout, deliberately: an unreadable or truncated header, a base repo outside the size
+table, an offline host, a server that ignores Range all yield "no opinion", and the load proceeds
+with the loader's own guard as the backstop. A false positive here would refuse a pick that works,
+which is strictly worse than the download this saves. (A known ungated MIRROR of a base is not an
+exception: it is byte-identical to what it copies, ``canonical_base`` maps it back, and it is
+checked like its upstream.)
"""
from __future__ import annotations
@@ -57,19 +56,14 @@ _HEADER_TIMEOUT_SECONDS = 15
# How long to wait for an interrupted read to notice before leaving it to the GC.
_ABANDON_GRACE_SECONDS = 0.5
-# (repo_id, gguf_filename, token fingerprint, local file identity) -> inner_dim or None. Bounded
-# and process-local. It memoises the MISS too -- the three checks on one pick would otherwise
-# re-probe an unreachable Hub three times, and a sticky None is the degradation this module
-# promises anyway. Which is exactly why the last two key parts exist: a sticky None must not
-# outlive its cause.
-#
-# * the TOKEN, fingerprinted rather than stored. Keying on mere presence made every non-empty
-# token one key, so a first probe with an expired credential poisoned the valid one that
-# replaced it for the rest of the process.
-# * the local file's IDENTITY (path, size, mtime). A checkpoint swapped in place keeps its path,
-# so keying on the name alone answers the new file with the old file's dim -- refusing a valid
-# 9B pairing, or handing sd.cpp the 4B text encoders. It also makes the file ARRIVING a new
-# key, so a miss taken before a download finished re-probes off disk for free.
+# (repo_id, gguf_filename, token fingerprint, local file identity) -> inner_dim or None. Bounded and process-local. It
+# memoises the MISS too, since the three checks on one pick would otherwise re-probe an unreachable Hub three times,
+# which is exactly why the last two key parts exist: a sticky None must not outlive its cause. The TOKEN is
+# fingerprinted rather than stored, because keying on mere presence made every non-empty token one key, so a first
+# probe with an expired credential poisoned the valid one that replaced it. The local file's IDENTITY (path, size,
+# mtime) is keyed because a checkpoint swapped in place keeps its path, so keying on the name alone answers the new
+# file with the old file's dim; it also makes the file ARRIVING a new key, so a miss taken before a download finished
+# re-probes off disk for free.
_INNER_DIM_CACHE: dict[tuple[str, str, str, Optional[tuple]], Optional[int]] = {}
_INNER_DIM_CACHE_MAX = 256
_CACHE_LOCK = threading.Lock()
@@ -452,16 +446,11 @@ _SPEECH_ARCH_CACHE_MAX = 256
# variant listing's own freshness window for moved revisions.
_SPEECH_REMOTE_TTL_SECONDS = 60.0
-# (repo_id, gguf_filename, token fingerprint, local file identity) -> the header prefix.
-#
-# The inner-dim probe and the speech probe read the SAME first _GGUF_HEADER_BYTES of the SAME
-# file, and a flux.2 pick that is not a size mismatch runs both: two range requests, each with its
-# own _HEADER_TIMEOUT_SECONDS, so a picker the user waits on could wear twice its documented
-# bound. They share the read now, keyed and aged exactly like the speech memo beside it, so this
-# adds no staleness the module did not already accept.
-#
-# Deliberately NOT consulted by the revalidation paths: their whole job is to re-read a file the
-# Hub has republished, and answering those from a memo would defeat them.
+# (repo_id, gguf_filename, token fingerprint, local file identity) -> the header prefix. The inner-dim probe and the
+# speech probe read the SAME first _GGUF_HEADER_BYTES of the SAME file, and a flux.2 pick that is not a size mismatch
+# runs both: two range requests, each with its own _HEADER_TIMEOUT_SECONDS, so a picker the user waits on could wear
+# twice its documented bound. They share the read now, keyed and aged exactly like the speech memo beside it.
+# Deliberately NOT consulted by the revalidation paths: their whole job is to re-read a file the Hub has republished.
_HEADER_PREFIX_CACHE: dict[tuple[str, str, str, Optional[tuple]], tuple[bytes, float]] = {}
_HEADER_PREFIX_CACHE_MAX = 32
diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.py
index cd2ffb04a3e..b93d92f0ac4 100644
--- a/studio/backend/core/inference/diffusion_compile_cache.py
+++ b/studio/backend/core/inference/diffusion_compile_cache.py
@@ -82,7 +82,6 @@ def cache_root() -> Path:
return Path(root) if root else _DEFAULT_ROOT
-# --------------------------------------------------------------------------- fingerprint
def _triton_version() -> Optional[str]:
try:
import triton # noqa: PLC0415
@@ -120,10 +119,9 @@ def environment_fingerprint() -> dict[str, Any]:
fp["torch"] = str(torch.__version__)
fp["torch_cuda"] = str(torch.version.cuda)
if torch.cuda.is_available():
- # the CURRENT device, not 0: keying by GPU 0 lets two cards share or overwrite each other's
- # architecture-specific artifacts
# The CURRENT device, not 0: a load pinned to another card compiles for that architecture, and keying the
- # bundle by GPU 0 lets two cards share or overwrite each other's supposedly architecture-specific artifacts.
+ # bundle by GPU 0 lets two cards share or overwrite each other's supposedly architecture-specific
+ # artifacts.
index = torch.cuda.current_device()
fp["gpu_name"] = torch.cuda.get_device_name(index)
cap = torch.cuda.get_device_capability(index)
@@ -166,7 +164,6 @@ def cache_key(env_fp: dict[str, Any], model_fp: dict[str, Any]) -> str:
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:32]
-# ----------------------------------------------------------------------------- lifecycle
@dataclasses.dataclass
class CacheContext:
"""Per-load cache state carried between ``begin`` and ``save``/``restore``.
diff --git a/studio/backend/core/inference/diffusion_cond_cache.py b/studio/backend/core/inference/diffusion_cond_cache.py
index 5928100351c..8fa786ab690 100644
--- a/studio/backend/core/inference/diffusion_cond_cache.py
+++ b/studio/backend/core/inference/diffusion_cond_cache.py
@@ -60,7 +60,6 @@ def _json_safe(value: Any) -> bool:
return False
-# layout codes for _flatten/_unflatten: -1 = None, -2 = bare tensor, n >= 0 = list of n tensors
# Per-slot layout codes for _flatten/_unflatten (the leading int64 tensor): -1 = None, -2 = a bare tensor, n >= 0 = a
# LIST of n tensors.
_SLOT_NONE = -1
@@ -134,7 +133,6 @@ def install(
if not callable(encode):
return False
try:
- # lazy: core.training imports core.inference, so a module-level import would be circular
# Lazy: core.training imports parts of core.inference, so a module-level import would be circular.
from core.training.diffusion_train_extras import PersistentConditioningCache
signature = inspect.signature(encode)
@@ -144,10 +142,9 @@ def install(
logger.warning("diffusion.cond_cache: install failed: %s", exc)
return False
- # a GGUF/single-file checkpoint takes its TEXT ENCODERS from the base repo
- # Everything beyond the call arguments that changes the embedding numerics. A GGUF/single-file checkpoint takes its
- # TEXT ENCODERS from the companion base repo, so the base identity keys the cache too; both carry a revision marker,
- # so an advanced commit or an edited dir misses.
+ # Everything beyond the call arguments that changes the embedding numerics. A GGUF/single-file checkpoint takes
+ # its TEXT ENCODERS from the companion base repo, so the base identity keys the cache too; both carry a revision
+ # marker, so an advanced commit or an edited dir misses.
base_ref = base_repo if base_repo else repo_id
load_fp = {
"repo": str(repo_id),
diff --git a/studio/backend/core/inference/diffusion_controlnet.py b/studio/backend/core/inference/diffusion_controlnet.py
index 22637b040d1..d0ac96765a6 100644
--- a/studio/backend/core/inference/diffusion_controlnet.py
+++ b/studio/backend/core/inference/diffusion_controlnet.py
@@ -24,7 +24,6 @@ from typing import Any, Optional
from utils.paths.storage_roots import studio_root
from utils.paths.path_utils import is_appledouble_metadata
-# "passthrough": the supplied image IS the control map; "canny": derive an edge map here
# Control map types. "passthrough": the supplied image IS the control map. "canny": derive an edge map here.
CONTROL_TYPES = ("passthrough", "canny")
diff --git a/studio/backend/core/inference/diffusion_convrot.py b/studio/backend/core/inference/diffusion_convrot.py
index d4b5caedddf..65b34e528bd 100644
--- a/studio/backend/core/inference/diffusion_convrot.py
+++ b/studio/backend/core/inference/diffusion_convrot.py
@@ -55,23 +55,19 @@ from __future__ import annotations
from functools import lru_cache
from typing import Any, Iterable, Optional
-# the rotation KIND; an unimplemented value is refused
-# ── the metadata contract, carried in the prequant checkpoint's own ``metadata`` dict ────────── The rotation KIND. A
-# value this module does not implement is refused, so a future scheme can be added without a released Unsloth silently
-# treating it as this one.
-# ── the metadata contract, carried in the prequant checkpoint's own ``metadata`` dict ──────────
+# The metadata contract, carried in the prequant checkpoint's own ``metadata`` dict. The rotation KIND: a value this
+# module does not implement is refused, so a future scheme can be added without a released Unsloth silently treating
+# it as this one.
CONVROT_KIND = "convrot_hadamard_v1"
-# mirrors the adaLN curve contract next door: a form tag plus the parameters to reproduce the form
# Key naming mirrors the adaLN curve contract next door (``adaln_form`` / ``curve_dim`` / ``curve_grid``): a form tag
# plus the parameters needed to reproduce the form.
ROTATION_KEY = "activation_rotation"
ROTATION_GROUP_KEY = "activation_rotation_group"
ROTATION_FQNS_KEY = "activation_rotation_fqns"
-# 256 beat 64 in weight space on MiniMax-H3 (-19.9% vs -17.3% mean relative quantization error over 200 layers)
-# The group size the denoiser artifact ships at, and the one the hosted conditioner already uses. 256 beat 64 in weight
-# space on MiniMax-H3 (mean relative quantization error -19.9% vs -17.3% over 200 layers) and is the largest power of 4
-# that divides every quantized H3 input axis.
+# The group size the denoiser artifact ships at, and the one the hosted conditioner already uses. 256 beat 64 in
+# weight space on MiniMax-H3 (mean relative quantization error -19.9% vs -17.3% over 200 layers) and is the largest
+# power of 4 that divides every quantized H3 input axis.
DEFAULT_CONVROT_GROUPSIZE = 256
# Marker set on a transformer whose rotation is installed, so a caller can tell a rotated module from an unrotated one
@@ -94,12 +90,8 @@ def is_power_of_four(size: Any) -> bool:
return (n.bit_length() - 1) % 2 == 0
-# mirrors comfy-kitchen's _build_hadamard / _rotate_activation / _rotate_weight, without the wheel dependency
-
-# ── the rotation itself ─────────────────────────────────────────────────────────────────────── Mirrors comfy-kitchen's
-# ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight``, in a few lines of torch rather than a dependency on
-# a wheel Unsloth does not ship.
-# ── the rotation itself ───────────────────────────────────────────────────────────────────────
+# The rotation itself. Mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight``, in a
+# few lines of torch rather than a dependency on a wheel Unsloth does not ship.
_HADAMARD_CACHE: dict = {}
@@ -221,9 +213,6 @@ def _install_rotation(module: Any, group_size: int) -> None:
module.__class__ = convrot_linear_class()
-# ── the metadata contract ─────────────────────────────────────────────────────────────────────
-
-
def declares_rotation(metadata: Any) -> bool:
"""True when ``metadata`` claims its weights were rotated offline.
@@ -274,9 +263,6 @@ def rotation_metadata(group_size: int, fqns: Iterable[str]) -> dict:
}
-# ── the two halves ────────────────────────────────────────────────────────────────────────────
-
-
def rotatable_fqns(
transformer: Any,
filter_fn: Any,
diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.py
index 59c9e56d7d7..685a5a836a3 100644
--- a/studio/backend/core/inference/diffusion_device.py
+++ b/studio/backend/core/inference/diffusion_device.py
@@ -29,7 +29,6 @@ class DiffusionDeviceTarget:
supports_default_torch_compile: bool
supports_pinned_transfer: bool
supports_float64: bool = True
- # kept OUT of `device`: the memory, speed and attention policies compare that string against "cuda"
# Selected CUDA/ROCm physical index, kept OUT of ``device``: the memory, speed and attention policies compare that
# string against "cuda", so a "cuda:1" there disables them silently.
ordinal: Optional[int] = None
@@ -479,11 +478,9 @@ def _mps_or_cpu_target(torch: Any) -> DiffusionDeviceTarget:
# first or the allocator caps at ~1.7x recommendedMaxWorkingSet and can OOM a model that would fit. setdefault
# respects an override.
os.environ.setdefault("PYTORCH_MPS_HIGH_WATERMARK_RATIO", "0.0")
- # NEVER silent float16: modern DiTs produce activations far outside fp16's range (Z-Image MLP peaks near 9e5 ->
- # inf -> NaN -> black image)
- # Prefer bfloat16, else float32, NEVER silent float16: modern DiTs produce activations far outside fp16's range
- # (Z-Image MLP peaks near 9e5 -> inf -> NaN -> black image). bf16 (macOS 14+) shares fp32's exponent range;
- # older macOS uses fp32.
+ # Prefer bfloat16, else float32, NEVER silent float16: modern DiTs produce activations far outside fp16's
+ # range (Z-Image MLP peaks near 9e5 -> inf -> NaN -> black image). bf16 (macOS 14+) shares fp32's exponent
+ # range; older macOS uses fp32.
dtype = torch.bfloat16 if _mps_supports_bfloat16(torch) else torch.float32
return DiffusionDeviceTarget(
device = "mps",
diff --git a/studio/backend/core/inference/diffusion_eager_patches.py b/studio/backend/core/inference/diffusion_eager_patches.py
index b1bf817f6ae..f7474f8003f 100644
--- a/studio/backend/core/inference/diffusion_eager_patches.py
+++ b/studio/backend/core/inference/diffusion_eager_patches.py
@@ -106,10 +106,9 @@ _orig_rmsnorm_forward: Optional[Callable] = None
def _rmsnorm_forward(self, hidden_states):
- # fall back where F.rms_norm is NOT equivalent to diffusers
- # Fall back to the exact original where F.rms_norm is NOT equivalent to diffusers: NPU / bias / fp32-weight, a tuple
- # `dim` (diffusers reduces only the LAST dim), or a dtype mismatch (diffusers computes variance in fp32 from the
- # ORIGINAL tensor).
+ # Fall back to the exact original where F.rms_norm is NOT equivalent to diffusers: NPU / bias / fp32-weight, a
+ # tuple `dim` (diffusers reduces only the LAST dim), or a dtype mismatch (diffusers computes variance in fp32 from
+ # the ORIGINAL tensor).
if _NPU or self.bias is not None or _orig_rmsnorm_forward is None or len(tuple(self.dim)) != 1:
return _orig_rmsnorm_forward(self, hidden_states) # type: ignore[misc]
weight = self.weight
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index bb3091460c8..285ed2d907a 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -49,7 +49,6 @@ logger = get_logger(__name__)
_DISABLE_TOKENS = frozenset({"0", "off", "false", "no"})
_ENABLE_TOKENS = frozenset({"1", "on", "true", "yes"})
-# without this the installer defaults to "cpu" and a forced ROCm/Intel generation silently runs on CPU
# Resolved device backend -> the prebuilt sd-cli accelerator to install, used only for a force-native load on a GPU
# host: without it the installer defaults to "cpu" and a forced ROCm/Intel generation silently runs on CPU. Unknown ->
# "auto".
@@ -97,10 +96,7 @@ def active_engine_name() -> str:
def _activate(name: str, reason: Optional[str]) -> Any:
global _active_engine_name, _fallback_reason
- # without holding _lock across the slow unload()
with _transition_lock:
- # unload the deactivated engine first, else its model stays resident but unreachable (the evictor only targets
- # the active one), leaking 10+ GB
# Switching engines: unload the deactivated one first, else its model stays resident but unreachable (the
# evictor only targets the active engine), leaking 10+ GB. The unload is slow, so resolve under _lock but run
# unload() OUTSIDE it.
@@ -113,18 +109,16 @@ def _activate(name: str, reason: Optional[str]) -> Any:
else:
_fallback_reason = reason if name == ENGINE_DIFFUSERS else None
if engine_to_unload is not None:
- # publish only AFTER the old engine unloads
- # Publish the new engine only AFTER the old one unloads: the evictor unloads get_active_diffusion_engine(),
- # so flipping the name first would let a concurrent acquire_for evict the new (empty) engine while the old
- # model frees VRAM.
+ # Publish the new engine only AFTER the old one unloads: the evictor unloads
+ # get_active_diffusion_engine(), so flipping the name first would let a concurrent acquire_for evict the
+ # new (empty) engine while the old model frees VRAM.
try:
engine_to_unload.unload()
except Exception as exc:
- # do NOT publish after a failed teardown: the old model still holds its memory
- # Do NOT publish the new engine after a failed teardown. The old model (or the resident sd-server) still
- # holds its memory, and flipping the name would hide it from get_active_diffusion_engine(), which the
- # evictor, /images/unload and the next load all resolve through, so the leak would be permanent. Leaving
- # the old engine active keeps it reclaimable and lets the caller retry.
+ # Do NOT publish the new engine after a failed teardown. The old model (or the resident sd-server)
+ # still holds its memory, and flipping the name would hide it from get_active_diffusion_engine(),
+ # which the evictor, /images/unload and the next load all resolve through, so the leak would be
+ # permanent. Leaving the old engine active keeps it reclaimable and lets the caller retry.
logger.error("failed to unload previous engine %s: %s", old_name, exc)
raise RuntimeError(
f"Could not switch the diffusion engine to {name}: unloading the current "
@@ -192,11 +186,9 @@ def select_and_activate_engine(
binary = None
server_binary = None
if policy_eligible and fam_ok:
- # probe the resident sd-server FIRST: a server-only install must route to native without paying an sd-cli
- # download
- # Probe the resident sd-server FIRST (the backend prefers it): a server-only install must still route to native
- # and should not pay an sd-cli download. Install the accelerator-matched build so a forced-native GPU load gets
- # the GPU server.
+ # Probe the resident sd-server FIRST (the backend prefers it): a server-only install must still route to
+ # native and should not pay an sd-cli download. Install the accelerator-matched build so a forced-native GPU
+ # load gets the GPU server.
server_binary = ensure_sd_server_binary(
allow_install = _install_allowed(),
accelerator = _install_accelerator_for(backend),
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 54c32af379c..52311badc05 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -1,16 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Pure helpers for diffusion model identification.
-
-No torch/diffusers imports here: everything in this module is a pure function of
-its string/path arguments so it can be unit-tested without the heavy runtime.
-
-A diffusion checkpoint published as a single-file GGUF only carries the
-transformer weights; the matching VAE / text encoders / scheduler come from a
-companion ``diffusers`` base repo. ``DiffusionFamily`` maps a checkpoint to the
-diffusers classes and base repo needed to assemble the full pipeline.
-"""
+"""Pure helpers for diffusion model identification. No torch/diffusers imports: everything here is a
+pure function of its string/path arguments, so it can be unit-tested without the heavy runtime. A
+diffusion checkpoint published as a single-file GGUF only carries the transformer weights; the
+matching VAE / text encoders / scheduler come from a companion ``diffusers`` base repo, and
+``DiffusionFamily`` maps a checkpoint to the diffusers classes and base repo needed to assemble
+the full pipeline."""
from __future__ import annotations
@@ -25,7 +21,6 @@ from typing import NamedTuple, Optional, Sequence
from utils.paths.path_utils import is_appledouble_metadata
-# runtime->route contract: /images/generate matches these messages EXACTLY for a 409 (vs a 500)
# Runtime->route contract: the /images/generate route matches these messages EXACTLY for a 409 (vs a 500), so both
# engines raise them verbatim.
DIFFUSION_NOT_LOADED_MSG = "No diffusion model is loaded."
@@ -37,13 +32,13 @@ class LoadIdentity:
"""What a caller's derived request parameters depend on, as one comparable value.
``repo_id`` alone is not one: /images/load takes ``base_repo`` and ``family_override``
- independently of the path, so a local checkpoint reloads as a different model while the
- path stays put, and the images route derives steps/guidance from ``base_repo`` and its
- edit-only verdict from the family (#9448). Loads agreeing on all three derive identical
- parameters, which is exactly when accepting one for the other is correct.
+ independently of the path, so a local checkpoint reloads as a different model while the path
+ stays put, and the images route derives steps/guidance from ``base_repo`` and its edit-only
+ verdict from the family (#9448). Loads agreeing on all three derive identical parameters, which
+ is exactly when accepting one for the other is correct.
- A type rather than a tuple, so pinning a bare repo id compares unequal and is refused
- instead of matching some other shape by accident.
+ A type rather than a tuple, so pinning a bare repo id compares unequal and is refused instead of
+ matching some other shape by accident.
"""
repo_id: str
@@ -57,12 +52,10 @@ def load_identity(repo_id, base_repo, family) -> LoadIdentity:
class DiffusionModelReplacedError(RuntimeError):
- """Both engines' ``generate`` refusing a ``LoadIdentity`` that is no longer loaded.
-
- Keeps a caller's per-model steps/guidance and workflow verdict, taken from an earlier
- ``status()`` read, off a model they never validated (#9448). Here rather than in
- ``diffusion`` so the native engine can raise it without importing the torch backend.
- """
+ """Both engines' ``generate`` refusing a ``LoadIdentity`` that is no longer loaded. Keeps a
+ caller's per-model steps/guidance and workflow verdict, taken from an earlier ``status()``
+ read, off a model they never validated (#9448). Here rather than in ``diffusion`` so the
+ native engine can raise it without importing the torch backend."""
def __init__(self, expected: LoadIdentity, actual: LoadIdentity):
super().__init__(
@@ -86,54 +79,50 @@ class DiffusionFamily:
denoiser_attr: str = "transformer"
# True when a single-file ``.safetensors`` is the WHOLE pipeline (SDXL), so the loader calls ``from_single_file``.
single_file_is_pipeline: bool = False
- # True for families needing MULTIPLE denoisers no single file carries (Ideogram 4), so only a full pipeline load is
- # valid.
+ # True for families needing MULTIPLE denoisers no single file carries (Ideogram 4), so only a full pipeline load
+ # is valid.
pipeline_only: bool = False
- # optional pipeline classes for image-conditioned workflows, built via Pipeline.from_pipe
- # Optional diffusers pipeline classes for image-conditioned workflows, built via ``Pipeline.from_pipe`` (no reload).
- # None = unsupported.
+ # Optional diffusers pipeline classes for image-conditioned workflows, built via ``Pipeline.from_pipe`` (no
+ # reload). None = unsupported.
img2img_pipeline_class: Optional[str] = None
inpaint_pipeline_class: Optional[str] = None
- # the ControlNet model loads via from_pretrained, the pipeline via from_pipe
- # ControlNet pipeline + model classes: the model loads via from_pretrained, the pipeline via ``from_pipe``. None on
- # both = no support.
+ # ControlNet pipeline + model classes: the model loads via from_pretrained, the pipeline via ``from_pipe``. None
+ # on both = no support.
controlnet_pipeline_class: Optional[str] = None
controlnet_model_class: Optional[str] = None
# True when the inpaint pipeline keeps the canvas size, so it can also drive outpaint. False for FLUX.2 (it scales
# >1MP inputs to ~1MP).
inpaint_preserves_size: bool = True
- # true for instruction-editing families: the pipeline IS the edit pipeline (image + instruction, no plain
- # text-to-image)
- # True for instruction-editing families (Qwen-Image-Edit / FLUX Kontext): the pipeline IS the edit pipeline (image +
- # instruction, no plain text-to-image). ``base_repo`` supplies the VAE / text-encoder / processor / scheduler.
+ # True for instruction-editing families (Qwen-Image-Edit / FLUX Kontext): the pipeline IS the edit pipeline (image
+ # + instruction, no plain text-to-image). ``base_repo`` supplies the VAE / text-encoder / processor / scheduler.
edit: bool = False
# True for families whose text-to-image pipeline ALSO accepts reference image(s) (FLUX.2 ``image``): no
# ``strength``, size from width/height.
reference: bool = False
# Extra lowercased substrings (besides ``name``) that map a repo id here.
aliases: tuple[str, ...] = field(default_factory = tuple)
- # True for families whose activations overflow float16 (-> black image); the backend promotes a resolved float16 to
- # float32.
+ # True for families whose activations overflow float16 (-> black image); the backend promotes a resolved float16
+ # to float32.
fp16_incompatible: bool = False
# false only for a family whose denoiser block does not compile cleanly with regional torch.compile
supports_torch_compile: bool = True
- # Optional pre-quantized transformer checkpoints as (scheme, repo_id): fetched instead of the dense bf16 (lower load
- # VRAM + download).
+ # Optional pre-quantized transformer checkpoints as (scheme, repo_id): fetched instead of the dense bf16 (lower
+ # load VRAM + download).
prequant_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)
# Hosted checkpoints for NON-DEFAULT bases as (base_repo, scheme, repo_id), base_repo lowercased: one family entry
# covers variants whose weights differ. Resolution prefers an exact variant match, then falls back to
# ``prequant_repos``.
prequant_variant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)
- # Bases (lowercased) with NO hosted checkpoint, which must not inherit ``prequant_repos``: the family fallback names
- # an artifact baked from different weights, and planning acts on it before the load's base_model_id check can refuse
- # it. Only for a base whose weights genuinely differ from the default.
+ # Bases (lowercased) with NO hosted checkpoint, which must not inherit ``prequant_repos``: the family fallback
+ # names an artifact baked from different weights, and planning acts on it before the load's base_model_id check
+ # can refuse it. Only for a base whose weights genuinely differ from the default.
prequant_excluded_bases: tuple[str, ...] = field(default_factory = tuple)
# Preferred checkpoint FILENAME for a scheme, as (scheme, filename), overriding the ``<Model>-<SCHEME>.pt`` name
- # ``prequant_repo_filename`` derives. The derived name stays on as the fallback, so a repo hosting BOTH an old and a
- # new artifact serves the new one to a build that asks for it by name and the old one to every build that does not.
- # That is what lets a rotated (v2) checkpoint ship without regressing an already-installed Unsloth, which would
- # otherwise refuse the v2 tag and fall all the way back to the dense download. A row may also be (scheme, task,
- # filename), which names the artifact for ONE task and beats the task-agnostic row; see
+ # ``prequant_repo_filename`` derives. The derived name stays on as the fallback, so a repo hosting BOTH an old and
+ # a new artifact serves the new one to a build that asks for it by name and the old one to every build that does
+ # not. That is what lets a rotated (v2) checkpoint ship without regressing an already-installed Unsloth, which
+ # would otherwise refuse the v2 tag and fall all the way back to the dense download. A row may also be (scheme,
+ # task, filename), which names the artifact for ONE task and beats the task-agnostic row; see
# ``family_prequant_filename``.
prequant_filenames: tuple[tuple[str, ...], ...] = field(default_factory = tuple)
# Hosted PRE-CAST text-encoder checkpoints as (scheme, component, repo_id). Layerwise-fp8 only: the cast is
@@ -156,12 +145,11 @@ class DiffusionFamily:
# Recommended base repos to train FROM, most-preferred first (e.g. a QLoRA prequant repo, then bf16). Surfaced by
# the Train UI.
train_base_repos: tuple[str, ...] = field(default_factory = tuple)
- # When set, deploying a LoRA trained on this family loads THIS repo instead (Krea: train on Raw, preview on Turbo).
- # Same precision both sides.
+ # When set, deploying a LoRA trained on this family loads THIS repo instead (Krea: train on Raw, preview on
+ # Turbo). Same precision both sides.
deploy_base_repo: Optional[str] = None
- # FLUX.2 Klein trains on an undistilled base and runs the adapter on the matching 4-step checkpoint
- # Variant-specific training-base to inference-base mappings. FLUX.2 Klein trains on an undistilled base and runs the
- # adapter on the matching 4-step checkpoint, so its 4B and 9B variants cannot share the single family-wide
+ # Variant-specific training-base to inference-base mappings. FLUX.2 Klein trains on an undistilled base and runs
+ # the adapter on the matching 4-step checkpoint, so its 4B and 9B variants cannot share the single family-wide
# deploy_base_repo above.
deploy_base_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)
@@ -186,16 +174,16 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
("int8", "unsloth/FLUX.1-schnell-FP8"),
("fp8", "unsloth/FLUX.1-schnell-FP8"),
),
- # Checkpoints baked from the dev / Krea-dev weights (same arch, different weights); without these every int8/fp8
- # load pays the dense download + on-the-fly quantise.
+ # Checkpoints baked from the dev / Krea-dev weights (same arch, different weights); without these every
+ # int8/fp8 load pays the dense download + on-the-fly quantise.
prequant_variant_repos = (
("black-forest-labs/flux.1-dev", "int8", "unsloth/FLUX.1-dev-FP8"),
("black-forest-labs/flux.1-dev", "fp8", "unsloth/FLUX.1-dev-FP8"),
("black-forest-labs/flux.1-krea-dev", "int8", "unsloth/FLUX.1-Krea-dev-FP8"),
("black-forest-labs/flux.1-krea-dev", "fp8", "unsloth/FLUX.1-Krea-dev-FP8"),
),
- # Pre-cast T5-XXL (9.52 -> 5.90 GB; CLIP-L stays dense). One artifact serves schnell/dev/Krea-dev (T5 shards are
- # byte-identical).
+ # Pre-cast T5-XXL (9.52 -> 5.90 GB; CLIP-L stays dense). One artifact serves schnell/dev/Krea-dev (T5 shards
+ # are byte-identical).
te_prequant_repos = (("fp8", "text_encoder_2", "unsloth/FLUX.1-schnell-FP8"),),
aliases = ("flux1", "flux-1"),
# LoRA training targets FLUX.1-dev via the DiT trainer (QLoRA nf4); the dev repo is gated
@@ -257,8 +245,9 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
),
),
),
- # FLUX.2-dev: full (non-distilled) FLUX.2 on the Mistral Flux2Pipeline, so its own entry. Gated base, text-to-image
- # only; sd-cli takes the Mistral encoder from unsloth/FLUX.2-dev-ComfyUI and the VAE from unsloth/FLUX.2-VAE.
+ # FLUX.2-dev: full (non-distilled) FLUX.2 on the Mistral Flux2Pipeline, so its own entry. Gated base,
+ # text-to-image only; sd-cli takes the Mistral encoder from unsloth/FLUX.2-dev-ComfyUI and the VAE from
+ # unsloth/FLUX.2-VAE.
DiffusionFamily(
name = "flux.2-dev",
pipeline_class = "Flux2Pipeline",
@@ -284,7 +273,6 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
),
),
DiffusionFamily(
- # FLUX instruction editing; specific aliases first so detect_family prefers this over "flux.1"
# FLUX instruction editing: FluxKontextPipeline takes an image + instruction. Specific aliases first so
# detect_family prefers this over "flux.1".
name = "flux.1-kontext",
@@ -355,14 +343,14 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
# Both hosted checkpoints are baked from the distilled Turbo transformer, so the undistilled base has none and
# must quantize its own dense weights.
prequant_excluded_bases = ("tongyi-mai/z-image",),
- # Pre-cast Qwen3-4B TE (8.04 -> 4.41 GB), shared with the undistilled base (byte-identical encoder). NOT shared
- # with flux.2-klein-4B: klein TE retrained layer 35 MLP (up/down_proj maxdiff 0.86 vs this checkpoint).
+ # Pre-cast Qwen3-4B TE (8.04 -> 4.41 GB), shared with the undistilled base (byte-identical encoder). NOT
+ # shared with flux.2-klein-4B: klein TE retrained layer 35 MLP (up/down_proj maxdiff 0.86 vs this checkpoint).
te_prequant_repos = (("fp8", "text_encoder", "unsloth/Z-Image-Turbo-FP8"),),
aliases = ("zimage", "z_image"),
# LoRA training via the DiT trainer (bf16); defaults to the prequant nf4 repo for QLoRA
trainable = True,
- # The undistilled base is what the upstream DreamBooth recipe trains on. No deploy pairing: its adapters preview
- # on the base itself at the 20-step / guidance 4 recipe.
+ # The undistilled base is what the upstream DreamBooth recipe trains on. No deploy pairing: its adapters
+ # preview on the base itself at the 20-step / guidance 4 recipe.
train_base_repos = (
"unsloth/Z-Image-Turbo-unsloth-bnb-4bit",
"Tongyi-MAI/Z-Image-Turbo",
@@ -419,10 +407,10 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
fp16_incompatible = True,
),
# HunyuanImage 2.1: a 17B dual-stream DiT with a Qwen2.5-VL encoder, a ByT5 glyph encoder and the 32x HunyuanImage
- # VAE
+ # VAE.
# HiDream-I1: a 17B MoE DiT with FOUR text encoders. The repos ship CLIP-L/CLIP-G/T5-XXL but NOT the Llama-3.1-8B
- # text_encoder_4 their model_index names, so the loader assembles it from the open unsloth mirror. One family covers
- # Full/Dev/Fast.
+ # text_encoder_4 their model_index names, so the loader assembles it from the open unsloth mirror. One family
+ # covers Full/Dev/Fast.
DiffusionFamily(
name = "hunyuanimage-2.1",
# hosted checkpoints, verified bit-identical to on-the-fly quantize (the guider pipeline is not run-to-run
@@ -442,8 +430,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
),
DiffusionFamily(
name = "hidream-i1",
- # Hosted checkpoints: 28/28 per-case gate pairs per scheme (LPIPS 0.291 int8 / 0.278 fp8); int8 bit-identical to
- # on-the-fly quantize.
+ # Hosted checkpoints: 28/28 per-case gate pairs per scheme (LPIPS 0.291 int8 / 0.278 fp8); int8 bit-identical
+ # to on-the-fly quantize.
prequant_repos = (
("int8", "unsloth/HiDream-I1-Full-FP8"),
("fp8", "unsloth/HiDream-I1-Full-FP8"),
@@ -531,8 +519,8 @@ _EDIT_KEYWORDS = ("edit", "kontext", "inpaint", "layered")
def _token_in_needle(token: str, needle: str) -> bool:
"""True when ``token`` appears in ``needle`` as a whole segment (delimited by ``- _ . / \\`` or
- a boundary), not a raw substring, so 'qwen-image-edit' matches '...-2511' but 'kontext' doesn't
- match 'kontextual'."""
+ a boundary), not a raw substring, so 'qwen-image-edit' matches '...-2511' but 'kontext'
+ doesn't match 'kontextual'."""
return re.search(r"(?:^|[-_./\\])" + re.escape(token) + r"(?:$|[-_./\\])", needle) is not None
@@ -548,12 +536,10 @@ def _best_family_match(needle: str) -> Optional[DiffusionFamily]:
def detect_family(repo_id: str, override: Optional[str] = None) -> Optional[DiffusionFamily]:
- """Resolve a ``DiffusionFamily`` from a repo id, or an explicit override.
-
- ``override`` matches a family ``name``/alias exactly; otherwise the most-specific family whose
- name/alias is a substring of the repo id wins. Supported editing families match here;
- unsupported editing/inpaint/layered checkpoints sharing only an arch keyword are rejected (None).
- """
+ """Resolve a ``DiffusionFamily`` from a repo id, or an explicit override. ``override`` matches a
+ family ``name``/alias exactly; otherwise the most-specific family whose name/alias is a
+ substring of the repo id wins. Supported editing families match here; unsupported
+ editing/inpaint/layered checkpoints sharing only an arch keyword are rejected (None)."""
if override:
key = override.strip().lower()
for fam in _FAMILIES:
@@ -592,8 +578,9 @@ def detect_family_by_pipeline_class(class_name: Optional[str]) -> Optional[Diffu
Only the BASE class matches. The loader instantiates ``fam.pipeline_class``
(``diffusion.py:2946``), never the declared class, so tagging an inpaint or img2img checkpoint
would list it and then load it through the wrong pipeline (its UNet input shape differs), which
- is the listing-versus-loader split this exists to close. A variant stays untagged, the answer
- it got before the index was read at all."""
+ is the listing-versus-loader split this exists to close. A variant stays untagged, the answer it
+ got before the index was read at all.
+ """
key = (class_name or "").strip()
if not key:
return None
@@ -613,7 +600,8 @@ def pipeline_class_from_index(path: Optional[str]) -> Optional[str]:
``utf-8-sig`` because PowerShell writes JSON with a BOM and a hand-authored index is ordinary
beside a converted checkpoint; read as ``utf-8`` it raises and the model stays hidden, #8407
again. ``RecursionError`` (a nesting bomb, not a ``ValueError``) is caught too: both callers
- wrap this in a blanket except that reads a raise as detection having succeeded."""
+ wrap this in a blanket except that reads a raise as detection having succeeded.
+ """
root = Path(path or "")
if not str(root):
return None
@@ -633,14 +621,12 @@ def pipeline_class_from_index(path: Optional[str]) -> Optional[str]:
def detect_family_by_pipeline_index(path: Optional[str]) -> Optional[DiffusionFamily]:
- """The family the pipeline saved at ``path`` declares in its ``model_index.json``, or None.
-
- The path-shaped counterpart of ``detect_family_by_pipeline_class``, used by BOTH the listing
- and the loader so the picker and ``validate_load_request`` answer off the same evidence (#8407).
-
- Carries over ``detect_family``'s variant guard: a directory NAMED for a checkpoint the matched
- family cannot run (``...-layered``) is still refused, so the index only adds models whose name
- said nothing, never overrides a name that said no."""
+ """The family the pipeline saved at ``path`` declares in its ``model_index.json``, or None. The
+ path-shaped counterpart of ``detect_family_by_pipeline_class``, used by BOTH the listing and
+ the loader so the picker and ``validate_load_request`` answer off the same evidence (#8407).
+ Carries over ``detect_family``'s variant guard: a directory NAMED for a checkpoint the
+ matched family cannot run (``...-layered``) is still refused, so the index only adds models
+ whose name said nothing, never overrides a name that said no."""
fam = detect_family_by_pipeline_class(pipeline_class_from_index(path))
if fam is None:
return None
@@ -659,21 +645,23 @@ def detect_family_for_pick(
gguf_filename: Optional[str] = None,
override: Optional[str] = None,
) -> Optional[DiffusionFamily]:
- """``detect_family``, falling back to the combined path/filename for a local ``.gguf`` pick
- where the family keyword lives only in the filename, and then to the saved pipeline class of a
- local diffusers pipeline directory. Only fallbacks, so remote picks and overrides behave
- exactly as ``detect_family``. Shared by both engines.
+ """``detect_family``, falling back to the combined path/filename for a local ``.gguf`` pick where
+ the family keyword lives only in the filename, and then to the saved pipeline class of a local
+ diffusers pipeline directory. Only fallbacks, so remote picks and overrides behave exactly as
+ ``detect_family``. Shared by both engines.
The index keeps the listing and the loader on one answer: the listing classifies a moved
pipeline from its ``model_index.json`` (its directory name is a commit hash), and the pick sent
back is that same opaque path with no family_override, so without this the model is shown as
- text-to-image and then refused as an unsupported family (#8407)."""
+ text-to-image and then refused as an unsupported family (#8407).
+ """
fam = None
if not override:
# The checkpoint's own declaration outranks any guess made from its path: a family keyword in ANY ancestor
- # segment otherwise shadows the index (a QwenImagePipeline under `.../flux.1/checkpoint` matched FLUX and never
- # reached it), so the listing, which reads the index, named one family and the loader another for one directory.
- # Remote picks are unaffected: with no local index this is None and the name-based paths below run as before.
+ # segment otherwise shadows the index (a QwenImagePipeline under `.../flux.1/checkpoint` matched FLUX and
+ # never reached it), so the listing, which reads the index, named one family and the loader another for one
+ # directory. Remote picks are unaffected: with no local index this is None and the name-based paths below run
+ # as before.
fam = detect_family_by_pipeline_index(repo_id)
if fam is None:
fam = detect_family(repo_id, override)
@@ -710,10 +698,10 @@ _GATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
# Mirrored to drop the third-party fetch, NOT to route around a gate. Every licence here permits redistribution, and
# each mirror carries the upstream licence text plus the notice that licence prescribes. Qwen-Image-2512 is the one no
-# other redirect could reach: its companions are named by the artifact repo's base_model card tag, not the family table.
-# Kept apart from the gated pairs because the two answer different questions. Both redirect a fetch, but only a GATED
-# upstream justifies overriding a user's existing cache: for these the upstream is reachable without credentials, so a
-# complete local snapshot must keep being used rather than re-pulled from the mirror.
+# other redirect could reach: its companions are named by the artifact repo's base_model card tag, not the family
+# table. Kept apart from the gated pairs because the two answer different questions: both redirect a fetch, but only a
+# GATED upstream justifies overriding a user's existing cache, and for these the upstream is reachable without
+# credentials, so a complete local snapshot must keep being used rather than re-pulled from the mirror.
_UNGATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
("Qwen/Qwen-Image-2512", "unsloth/Qwen-Image-2512"),
("Qwen/Qwen-Image", "unsloth/Qwen-Image"),
@@ -743,20 +731,16 @@ def mirror_repo(repo_id: Optional[str]) -> Optional[str]:
def upstream_is_gated(repo_id: Optional[str]) -> bool:
- """True when ``repo_id`` is a vendor base the Hub refuses without accepted terms.
-
- Distinct from "has a mirror": most of the mirror table is ungated and exists only to keep
- the fetch inside ``unsloth/*``. Only the gated half justifies overriding a user's cache.
- """
+ """True when ``repo_id`` is a vendor base the Hub refuses without accepted terms. Distinct from
+ "has a mirror": most of the mirror table is ungated and exists only to keep the fetch inside
+ ``unsloth/*``. Only the gated half justifies overriding a user's cache."""
return (repo_id or "").strip().lower() in _GATED_UPSTREAMS
def canonical_base(repo_id: Optional[str]) -> str:
- """A mirror id mapped back to the upstream it copies, else ``repo_id`` unchanged.
-
- Base-keyed tables hold UPSTREAM ids, so every lookup normalises here: a mirror reaching
- ``_FLUX2_BASE_INNER_DIM`` misses, and that shape guard fails OPEN, so it goes silent.
- """
+ """A mirror id mapped back to the upstream it copies, else ``repo_id`` unchanged. Base-keyed
+ tables hold UPSTREAM ids, so every lookup normalises here: a mirror reaching
+ ``_FLUX2_BASE_INNER_DIM`` misses, and that shape guard fails OPEN, so it goes silent."""
base = (repo_id or "").strip()
return _MIRROR_UPSTREAM.get(base.lower(), base)
@@ -767,10 +751,8 @@ _WEIGHT_SUFFIXES = frozenset({".safetensors", ".bin", ".pt", ".ckpt", ".gguf"})
def _cached_revisions(root: Path, repo_id: str) -> list[Path]:
"""The snapshot dirs a fetch pinned to ``root`` could resolve for ``repo_id``. Never raises.
-
``refs/main`` alone when it exists, the one commit a branch fetch falls back to on a failed
- HEAD; every snapshot when it does not, since a commit-pinned download leaves no ref.
- """
+ HEAD; every snapshot when it does not, since a commit-pinned download leaves no ref."""
try:
repo = root / f"models--{repo_id.replace('/', '--')}"
ref = repo / "refs" / "main"
@@ -785,12 +767,10 @@ def _cached_revisions(root: Path, repo_id: str) -> list[Path]:
def _root_revision_coverage(root: Path, repo_id: str, wanted: Sequence[str]) -> set[frozenset[str]]:
- """Which subsets of ``wanted`` ONE root can serve, one entry per revision it could resolve.
-
- A fetch that lands in a root lands in a SINGLE revision of it, so a name may not be borrowed
+ """Which subsets of ``wanted`` ONE root can serve, one entry per revision it could resolve. A
+ fetch that lands in a root lands in a SINGLE revision of it, so a name may not be borrowed
from a superseded snapshot to complete a newer one. The empty set is always an option: a root
- is allowed to contribute nothing.
- """
+ is allowed to contribute nothing."""
covers: set[frozenset[str]] = {frozenset()}
for rev in _cached_revisions(root, repo_id):
covers.add(frozenset(name for name in wanted if (rev / name).exists()))
@@ -825,9 +805,9 @@ def _upstream_is_cached(
"""Whether the upstream load is SATISFIABLE from the local cache.
Not "has any blob": one config left by an interrupted or previously-tokened pull would pin every
- later load to the gated upstream and re-raise the 401 the mirror exists to avoid. So the revision
- must hold ``files``, else a real weight file. ``.incomplete`` downloads have no snapshot symlink,
- so they count as absent.
+ later load to the gated upstream and re-raise the 401 the mirror exists to avoid. So the
+ revision must hold ``files``, else a real weight file. ``.incomplete`` downloads have no
+ snapshot symlink, so they count as absent.
Only the revision ``refs/main`` names counts, the one a gated fetch falls back to: on a 401 the
HEAD fails and ``hf_hub_download`` resolves the ref to ONE commit, so a complete but superseded
@@ -841,12 +821,12 @@ def _upstream_is_cached(
``from_pretrained`` is pinned to the live root and cannot see the other one -- counting those
bytes there would send a gated base back to the 401 the mirror exists to avoid.
- With BOTH roots the set is answered per FILE, because that is what those callers then do: a
- pair split across a cache-folder change (one file fetched before it, one after) is held by
- neither root alone, and asking each root for the whole set calls it absent and re-pulls bytes
- the two roots already have between them. Split across ROOTS only: within a root a name still
- has to come from the one revision that root's fetch resolves, so a superseded snapshot cannot
- complete a newer one. Any single root answering the whole set is the case above unchanged.
+ With BOTH roots the set is answered per FILE, because that is what those callers then do: a pair
+ split across a cache-folder change (one file fetched before it, one after) is held by neither
+ root alone, and asking each root for the whole set calls it absent and re-pulls bytes the two
+ roots already have between them. Split across ROOTS only: within a root a name still has to come
+ from the one revision that root's fetch resolves, so a superseded snapshot cannot complete a
+ newer one. Any single root answering the whole set is the case above unchanged.
"""
try:
from utils.hf_cache_settings import active_hf_hub_cache
@@ -862,8 +842,8 @@ def _upstream_is_cached(
roots.append(fallback)
wanted = tuple(files or ())
if wanted and len(roots) > 1:
- # One revision per root, unioned across roots: a name may come from either root, but within a root it has to
- # come from the revision that root's fetch would resolve.
+ # One revision per root, unioned across roots: a name may come from either root, but within a root it has
+ # to come from the revision that root's fetch would resolve.
reachable = {frozenset()}
for root in roots:
covers = _root_revision_coverage(root, repo_id, wanted)
@@ -919,14 +899,14 @@ def legacy_source_repo(repo_id: Optional[str]) -> Optional[str]:
def prefer_cached_legacy_source(repo_id: str, files: Optional[Sequence[str]] = None) -> str:
"""``repo_id``, or the community repack it mirrors when THAT already satisfies ``files``.
- The mirror stays the preferred source for a fresh install; this only spares an existing one
- from re-fetching bytes it already has under the old repo key. Same ``_upstream_is_cached``
- probe the gated swap uses, so an interrupted or partial repack does not win.
+ The mirror stays the preferred source for a fresh install; this only spares an existing one from
+ re-fetching bytes it already has under the old repo key. Same ``_upstream_is_cached`` probe the
+ gated swap uses, so an interrupted or partial repack does not win.
Both cache roots count: the sd.cpp fetch passes ``reuse_other_cache_root``, so a repack left
- behind by a cache-folder change is still reusable, and only the repo id can reach it -- once
- the id has become the mirror those bytes are unreachable and the load re-pulls several GB
- (offline, it fails outright).
+ behind by a cache-folder change is still reusable, and only the repo id can reach it -- once the
+ id has become the mirror those bytes are unreachable and the load re-pulls several GB (offline,
+ it fails outright).
PURE: table lookup + local stat, no network, so the staging plan and the fetch agree.
"""
@@ -937,12 +917,10 @@ def prefer_cached_legacy_source(repo_id: str, files: Optional[Sequence[str]] = N
def _is_local_path(base: str) -> bool:
- """Whether ``base`` exists on disk, i.e. a local dir rather than a Hub id.
-
- A user can clone a base into a relative dir named exactly like the vendor id
- (``black-forest-labs/FLUX.1-dev``), which the loaders deliberately treat as local. OSError from
- an id with invalid path characters just means "not a local path".
- """
+ """Whether ``base`` exists on disk, i.e. a local dir rather than a Hub id. A user can clone a
+ base into a relative dir named exactly like the vendor id (``black-forest-labs/FLUX.1-dev``),
+ which the loaders deliberately treat as local. OSError from an id with invalid path
+ characters just means "not a local path"."""
try:
return Path(base or "").expanduser().exists()
except OSError:
@@ -965,30 +943,31 @@ def prefer_ungated_mirror(
Declines to today's behaviour under ``UNSLOTH_DIFFUSION_NO_MIRROR``, for a local path, or when
the upstream already satisfies the load from cache and switching would re-pull tens of GiB.
- ``files`` sharpens that last test to the names about to be fetched; without it any weight counts.
+ ``files`` sharpens that last test to the names about to be fetched; without it any weight
+ counts.
PURE: table lookup, env read, local stat, NO network. This runs inside pipeline assembly, where
an earlier ``model_info`` probe of the mirror put a Hub round trip on the load path and broke
- four download-plan tests. A missing mirror surfaces as the ordinary download error.
- ``hf_token`` is unused, kept so callers need not care.
+ four download-plan tests. A missing mirror surfaces as the ordinary download error. ``hf_token``
+ is unused, kept so callers need not care.
"""
del hf_token # noqa: F841 -- signature stability only
mirror = mirror_repo(base)
if not mirror or os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip():
return base
- # a local path is never a Hub id: rewriting one sends loads the other sites resolve on disk to the Hub, skipping the
- # copy already downloaded
+ # a local path is never a Hub id: rewriting one sends loads the other sites resolve on disk to the Hub, skipping
+ # the copy already downloaded
if _is_local_path(base):
return base
return base if _upstream_is_cached(base, files) else mirror
-# Default (steps, guidance) per model for callers that cannot pass them. Matched by substring, most specific first; same
-# values as the UI MODEL_DEFAULTS table, keep in sync.
+# Default (steps, guidance) per model for callers that cannot pass them. Matched by substring, most specific first;
+# same values as the UI MODEL_DEFAULTS table, keep in sync.
_GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
("z-image-turbo", 9, 0.0),
- # FLUX.1 Krea dev is a FLUX.1-dev finetune, NOT a Krea-2: 28 steps at guidance 4.5. Must precede the generic "krea"
- # key.
+ # FLUX.1 Krea dev is a FLUX.1-dev finetune, NOT a Krea-2: 28 steps at guidance 4.5. Must precede the generic
+ # "krea" key.
("flux.1-krea", 28, 4.5),
# Krea 2 Raw (undistilled): 52 steps / guidance 3.5. Must precede the generic "krea" key.
("krea-2-raw", 52, 3.5),
@@ -1006,16 +985,15 @@ _GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
("z-image", 20, 4.0),
# Lumina Image 2.0 card: 50 steps, guidance 4 (plus cfg_trunc_ratio 0.25, which the loader passes itself).
("lumina", 50, 4.0),
- # HunyuanImage 2.1 card: guidance feeds distilled_guidance_scale, while real CFG runs inside the guiders
- # HunyuanImage 2.1 card: 50 steps; guidance feeds distilled_guidance_scale, while real CFG runs inside the guiders.
+ # HunyuanImage 2.1 card: 50 steps; guidance feeds distilled_guidance_scale, while real CFG runs inside the
+ # guiders.
("hunyuanimage", 50, 3.25),
# HiDream-I1 upstream: Full 50 steps / guidance 5; the distilled Dev (28) and Fast (16) run guidance-free.
("hidream-i1-dev", 28, 0.0),
("hidream-i1-fast", 16, 0.0),
("hidream", 50, 5.0),
- # Ideogram 4 card: its schedule tapers the last 3 steps
- # Ideogram 4 card: 48 steps, guidance 7 (its schedule tapers the last 3 steps; the loader keeps that taper at these
- # defaults).
+ # Ideogram 4 card: 48 steps, guidance 7 (its schedule tapers the last 3 steps; the loader keeps that taper at
+ # these defaults).
("ideogram", 48, 7.0),
# SDXL: Turbo distilled; base wants ~30 steps + CFG ~7. "sdxl-turbo" precedes "sdxl".
("sdxl-turbo", 3, 0.0),
@@ -1028,8 +1006,8 @@ _GENERATION_DEFAULT_FALLBACK = (9, 0.0)
def default_generation_params(*identifiers: Optional[str]) -> tuple[int, float]:
"""Default ``(steps, guidance)`` for a loaded model. The first identifier naming a known model
- wins (repo id, then resolved base repo), so a local-path load still resolves via its base repo.
- Keys matched as substrings, most specific first."""
+ wins (repo id, then resolved base repo), so a local-path load still resolves via its base
+ repo. Keys matched as substrings, most specific first."""
for identifier in identifiers:
needle = (identifier or "").lower()
for key, steps, guidance in _GENERATION_DEFAULTS:
@@ -1044,13 +1022,12 @@ def family_prequant_repo(
base_repo: Optional[str] = None,
) -> Optional[str]:
"""The hosted pre-quantized transformer repo for ``scheme`` in this family, or None.
-
- ``base_repo`` (when known) selects a variant-specific checkpoint first: a checkpoint is
- baked from ONE base's weights and the loader refuses it for any other base, so a variant
- without its own entry still returns the family default. That is harmless only while the
- default is close enough that planning around it costs nothing, since the base_model_id
- validation refuses the artifact well after the plan was made. A base whose weights really
- differ belongs in ``prequant_excluded_bases``, which returns None here instead."""
+ ``base_repo`` (when known) selects a variant-specific checkpoint first: a checkpoint is baked
+ from ONE base's weights and the loader refuses it for any other base, so a variant without
+ its own entry still returns the family default. That is harmless only while the default is
+ close enough that planning around it costs nothing, since the base_model_id validation
+ refuses the artifact well after the plan was made. A base whose weights really differ belongs
+ in ``prequant_excluded_bases``, which returns None here instead."""
# Both tables are keyed on lowercased upstream ids.
base = canonical_base(base_repo).lower()
if base:
@@ -1077,19 +1054,20 @@ def family_prequant_filename(
"""The preferred checkpoint filename this family declares for ``scheme``, or None.
``None`` means "use the derived ``<Model>-<SCHEME>.pt`` name", which is every family but the
- ones shipping a second artifact under the same repo and scheme. Not variant-keyed: the
- filename says WHICH artifact, the repo says which base.
+ ones shipping a second artifact under the same repo and scheme. Not variant-keyed: the filename
+ says WHICH artifact, the repo says which base.
Rows come in two shapes. ``(scheme, filename)`` is the historical one and is TASK-AGNOSTIC.
- ``(scheme, task, filename)`` names an artifact for one task only and wins over the agnostic
- row when ``task`` matches. That distinction exists because a family can hold several denoiser
- PARTITIONS in one repo (MiniMax-H3: keyframe vs reference), whose checkpoints have identical
- key sets and identical metadata and so cannot be told apart by any later check -- picking the
- wrong one generates from the wrong partition rather than failing.
+ ``(scheme, task, filename)`` names an artifact for one task only and wins over the agnostic row
+ when ``task`` matches. That distinction exists because a family can hold several denoiser
+ PARTITIONS in one repo (MiniMax-H3: keyframe vs reference), whose checkpoints have identical key
+ sets and identical metadata and so cannot be told apart by any later check -- picking the wrong
+ one generates from the wrong partition rather than failing.
``task = None`` therefore sees only the agnostic rows, and a scheme with no row for the task
asked for falls back to the agnostic one, i.e. exactly today's behaviour. Malformed rows are
- skipped rather than raising: this runs on a refusal path where a table typo must not 500."""
+ skipped rather than raising: this runs on a refusal path where a table typo must not 500.
+ """
wanted = (task or "").strip().lower()
agnostic: Optional[str] = None
for entry in getattr(fam, "prequant_filenames", ()) or ():
@@ -1115,8 +1093,8 @@ def family_prequant_filename(
# host can resolve
_DIFFUSERS_DROPPED_PY39 = "0.37.0"
-# First diffusers release exporting each pipeline class, read off ``src/diffusers/__init__.py`` at the upstream tags and
-# cross-checked against each release's requires-python on PyPI. An unlisted class gets a version-free "a newer
+# First diffusers release exporting each pipeline class, read off ``src/diffusers/__init__.py`` at the upstream tags
+# and cross-checked against each release's requires-python on PyPI. An unlisted class gets a version-free "a newer
# diffusers" instead of a number, since the ones left out are older than any release in play -- and
# ``family_pipeline_available`` reads one as available, so every class the listing probes belongs here. This exists so
# the remedy is true: telling a 3.9 host that Z-Image needs Python >= 3.10 sends it to upgrade the interpreter when
@@ -1137,9 +1115,9 @@ _PIPELINE_MIN_DIFFUSERS: dict[str, str] = {
"Flux2KleinInpaintPipeline": "0.38.0",
"Ideogram4Pipeline": "0.39.0",
"Krea2Pipeline": "0.39.0",
- # Older than the 0.35 baseline, but listed anyway: the packaging leaves an UNCONSTRAINED diffusers installable below
- # 3.10, so an already-present ancient one satisfies the pin, and quoting the 0.39 floor at a family that has existed
- # since 0.30 is the same wrong remedy.
+ # Older than the 0.35 baseline, but listed anyway: the packaging leaves an UNCONSTRAINED diffusers installable
+ # below 3.10, so an already-present ancient one satisfies the pin, and quoting the 0.39 floor at a family that has
+ # existed since 0.30 is the same wrong remedy.
"QwenImagePipeline": "0.35.0",
"QwenImageImg2ImgPipeline": "0.35.0",
"QwenImageInpaintPipeline": "0.35.0",
@@ -1167,13 +1145,12 @@ def _version_tuple(v: str) -> tuple[int, ...]:
def pipeline_class_requirement(pipeline_class: str) -> tuple[Optional[str], bool]:
- """``(minimum diffusers version, whether that minimum also needs Python >= 3.10)``.
-
- ``None`` for a class with no entry. That is deliberately not the packaging floor: an unlisted
- class is one old enough that no release in play lacks it (StableDiffusionXLPipeline goes back
- past 0.29), so naming 0.39 would send a supported Python 3.9 host to upgrade its interpreter
- for a class every diffusers it can install already has. Without an entry the refusal says
- "a newer diffusers" and stops there, which is true whatever the class."""
+ """``(minimum diffusers version, whether that minimum also needs Python >= 3.10)``. ``None`` for
+ a class with no entry. That is deliberately not the packaging floor: an unlisted class is one
+ old enough that no release in play lacks it (StableDiffusionXLPipeline goes back past 0.29),
+ so naming 0.39 would send a supported Python 3.9 host to upgrade its interpreter for a class
+ every diffusers it can install already has. Without an entry the refusal says "a newer
+ diffusers" and stops there, which is true whatever the class."""
minimum = _PIPELINE_MIN_DIFFUSERS.get(pipeline_class)
if minimum is None:
return None, False
@@ -1206,14 +1183,15 @@ def _dummy_required_backends(cls: object) -> tuple[str, ...]:
Required, not missing: ``_backends`` is the class's full requirement list, so a placeholder
standing in because transformers is absent still lists torch beside it. Naming them all as
- missing, and prescribing a reinstall, is how you tell someone with a working ROCm or CUDA
- build of torch to replace it.
+ missing, and prescribing a reinstall, is how you tell someone with a working ROCm or CUDA build
+ of torch to replace it.
With a required backend absent (torch, transformers, ...), diffusers still EXPORTS every
- pipeline name, as a ``DummyObject``-metaclassed stand-in from ``diffusers.utils.dummy_*``
- whose ``from_pretrained`` raises ``ImportError`` on the first call. ``hasattr`` therefore
- answers True for a class that cannot be used, which is exactly the "importable" answer the
- strict gate must not accept. Empty tuple for a real class."""
+ pipeline name, as a ``DummyObject``-metaclassed stand-in from ``diffusers.utils.dummy_*`` whose
+ ``from_pretrained`` raises ``ImportError`` on the first call. ``hasattr`` therefore answers True
+ for a class that cannot be used, which is exactly the "importable" answer the strict gate must
+ not accept. Empty tuple for a real class.
+ """
if not str(getattr(cls, "__module__", "")).startswith("diffusers.utils.dummy"):
return ()
backends = getattr(cls, "_backends", None) or ()
@@ -1226,8 +1204,7 @@ def assert_pipeline_class_available(
*,
strict: bool = False,
) -> None:
- """Raise ``ValueError`` before any download when the installed diffusers has no
- ``pipeline_class``.
+ """Raise ``ValueError`` before any download when the installed diffusers has no ``pipeline_class``.
The newer families (Flux2Klein, Z-Image, Krea 2, LTX-2, HunyuanImage) only exist from a
diffusers newer than the 0.35 baseline, and the packaging leaves an older one installable on
@@ -1235,37 +1212,35 @@ def assert_pipeline_class_available(
floor has to be conditional or the whole extra becomes unresolvable. Which release a family
needs differs per class, so the refusal reads it from ``_PIPELINE_MIN_DIFFUSERS`` rather than
quoting the floor at everyone. Without this check the getattr chain died with a bare
- AttributeError deep in the load, after the checkpoint had already been fetched, which is an
- expensive way to learn the environment is too old. Krea 2 already guarded itself this way; this
- is the same check for every family, run from validation.
+ AttributeError deep in the load, after the checkpoint had already been fetched.
- ``strict`` decides what an *unimportable* diffusers means. Inference (the default) stays
- silent: it only answers "is the installed diffusers new enough", and the native sd.cpp engine
- serves GGUF picks on a CPU or Apple host that has no diffusers at all. Training passes
- ``strict = True``, because its child is an ``mp.get_context("spawn")`` process in the SAME
- interpreter -- an import that fails here fails there too, only after the route has reserved the
- training slot and freed the resident GPU models.
+ ``strict`` decides what an *unimportable* diffusers means. Inference (the default) stays silent:
+ it only answers "is the installed diffusers new enough", and the native sd.cpp engine serves
+ GGUF picks on a CPU or Apple host that has no diffusers at all. Training passes ``strict =
+ True``, because its child is an ``mp.get_context("spawn")`` process in the SAME interpreter --
+ an import that fails here fails there too, only after the route has reserved the training slot
+ and freed the resident GPU models.
``ValueError``, like every other unloadable-pick refusal ``validate_load_request`` raises, so
the routes map it to 400 with the message intact. A ``RuntimeError`` instead reached
``/images/load``'s 409 (the code that otherwise means "a load is already in progress") and
escaped ``/images/download-plan``, which catches only (ValueError, FileNotFoundError), as a bare
- 500 with the message lost."""
+ 500 with the message lost.
+ """
try:
import diffusers
present = hasattr(diffusers, pipeline_class)
dummy_backends = _dummy_required_backends(getattr(diffusers, pipeline_class, None))
except Exception as exc: # noqa: BLE001 -- see below: this check must never raise anything but its own ValueError
# Not this check's business under the default: it answers "is the installed diffusers new enough for this
- # family", and with nothing importable there is no version to judge. Refusing would also break the native sd.cpp
- # engine, which serves GGUF picks on a CPU or Apple host without diffusers. A pick that really needs it fails
- # later, in the loader. The one thing that must not happen is a raise of the wrong type: ModuleNotFoundError is
- # not the ValueError the routes map to 400, so it escapes /images/download-plan as a bare 500 with the message
- # lost. The attribute probe is inside the try for the same reason. diffusers' top level is a lazy module, so
- # ``hasattr`` is what actually imports the pipeline's submodule, and when that submodule's own dependencies are
- # unsatisfiable it raises RuntimeError ("Failed to import diffusers.pipelines...") -- which hasattr does NOT
- # swallow, since it only absorbs AttributeError. A partially usable diffusers install therefore escaped this
- # guard exactly the way a missing one used to.
+ # family", and with nothing importable there is no version to judge. Refusing would also break the native
+ # sd.cpp engine, which serves GGUF picks on a CPU or Apple host without diffusers. The one thing that must not
+ # happen is a raise of the wrong type: ModuleNotFoundError is not the ValueError the routes map to 400, so it
+ # escapes /images/download-plan as a bare 500 with the message lost. The attribute probe is inside the try for
+ # the same reason: diffusers' top level is a lazy module, so ``hasattr`` is what actually imports the
+ # pipeline's submodule, and when that submodule's own dependencies are unsatisfiable it raises RuntimeError
+ # ("Failed to import diffusers.pipelines..."), which hasattr does NOT swallow since it only absorbs
+ # AttributeError.
if strict:
raise ValueError(
f"'{family_name}' needs diffusers ({pipeline_class}), which this environment "
@@ -1323,12 +1298,12 @@ def _installed_diffusers_version() -> Optional[str]:
def _installed_at_least(installed: str, minimum: str) -> bool:
- """Whether an INSTALLED version satisfies ``minimum``, judged on its release numbers.
-
- Not ``_version_tuple``, which is for the clean constants in the table above: a vendor build
- carries a PEP 440 local suffix (``0.40.0+dfsg``) that stops the numeric parse mid-version, and
- a git install carries ``.dev0``, which strict PEP 440 sorts below its own release. Both HAVE
- the class, so compare the release they were cut from. An unreadable version answers OPEN."""
+ """Whether an INSTALLED version satisfies ``minimum``, judged on its release numbers. Not
+ ``_version_tuple``, which is for the clean constants in the table above: a vendor build
+ carries a PEP 440 local suffix (``0.40.0+dfsg``) that stops the numeric parse mid-version,
+ and a git install carries ``.dev0``, which strict PEP 440 sorts below its own release. Both
+ HAVE the class, so compare the release they were cut from. An unreadable version answers
+ OPEN."""
try:
from packaging.version import Version
return Version(Version(installed).base_version) >= Version(minimum)
@@ -1338,13 +1313,12 @@ def _installed_at_least(installed: str, minimum: str) -> bool:
def family_probe_class(fam: Any) -> str:
"""The class whose presence in the installed diffusers actually proves ``fam`` is loadable.
-
Normally that is ``fam.pipeline_class``. ``ModularPipeline`` is the exception: it is the
- generic entry point for every Modular Diffusers workflow, not a family, and it has existed for
- several releases, so a diffusers that predates MiniMax-H3's own blocks still answers hasattr
- for it. Probe the family's own transformer class there instead, which is the thing the load
- actually needs. Shared by the listing probe and by both training gates so a family cannot be
- hidden from the picker and simultaneously accepted by /diffusion/start."""
+ generic entry point for every Modular Diffusers workflow, not a family, and it has existed
+ for several releases, so a diffusers that predates MiniMax-H3's own blocks still answers
+ hasattr for it. Probe the family's own transformer class there instead, which is the thing
+ the load actually needs. Shared by the listing probe and by both training gates so a family
+ cannot be hidden from the picker and simultaneously accepted by /diffusion/start."""
name = str(getattr(fam, "pipeline_class", "") or "")
if name == "ModularPipeline":
return str(getattr(fam, "transformer_class", None) or name)
@@ -1355,24 +1329,25 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
"""True when the installed diffusers actually has this family's pipeline class.
The boolean twin of ``assert_pipeline_class_available``, for the listing routes: the newer
- families exist only from diffusers 0.39, and the packaging leaves an older diffusers
- installable on Python 3.9 (diffusers dropped 3.9 in 0.37, so the 0.39 floor has to be
- conditional or the extra becomes unresolvable). Advertising Z-Image or Krea 2 in the picker
- on such an environment offers a pick that can only fail, and no `pip install -U diffusers`
- can fix it without also upgrading Python. Fails OPEN (True) when diffusers cannot be
- imported at all, so a listing never hides a model over an unrelated import problem.
+ families exist only from diffusers 0.39, and the packaging leaves an older diffusers installable
+ on Python 3.9 (diffusers dropped 3.9 in 0.37, so the 0.39 floor has to be conditional or the
+ extra becomes unresolvable). Advertising Z-Image or Krea 2 in the picker on such an environment
+ offers a pick that can only fail, and no `pip install -U diffusers` can fix it without also
+ upgrading Python. Fails OPEN (True) when diffusers cannot be imported at all, so a listing never
+ hides a model over an unrelated import problem.
Uses installed-version metadata because probing diffusers' lazy attributes imports pipeline
- dependencies. The load path remains the final availability check."""
+ dependencies. The load path remains the final availability check.
+ """
if fam is None:
return False
- # A modular family is judged on its own transformer class, not on the generic ``ModularPipeline`` entry point -- see
- # ``family_probe_class``.
+ # A modular family is judged on its own transformer class, not on the generic ``ModularPipeline`` entry point --
+ # see ``family_probe_class``.
name = family_probe_class(fam)
- # No class name to probe means the record is not one this helper can judge, which is the same position as a missing
- # diffusers: answer OPEN. ``family_probe_class`` reads the attribute with a default, so a record without
- # ``pipeline_class`` reaches here as "" rather than raising into the guard below, and ``hasattr(diffusers, "")`` is
- # False -- which would hide the model.
+ # No class name to probe means the record is not one this helper can judge, which is the same position as a
+ # missing diffusers: answer OPEN. ``family_probe_class`` reads the attribute with a default, so a record without
+ # ``pipeline_class`` reaches here as "" rather than raising into the guard below, and ``hasattr(diffusers, "")``
+ # is False -- which would hide the model.
if not name:
return True
if "diffusers" in sys.modules:
@@ -1395,13 +1370,12 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
def family_gguf_loadable(fam: DiffusionFamily) -> bool:
- """True when a GGUF transformer can be assembled for this family.
-
- The two exclusions mirror the ones ``DiffusionBackend.validate_load_request`` raises on (which
- keep their own specific messages): a family whose single file IS the whole pipeline has no
- transformer-only GGUF, and a multi-denoiser family has no single transformer to swap. Exposed
- so the model-listing routes can classify a GGUF the same way the loader would, instead of
- keeping a second hand-maintained list that drifts."""
+ """True when a GGUF transformer can be assembled for this family. The two exclusions mirror the
+ ones ``DiffusionBackend.validate_load_request`` raises on (which keep their own specific
+ messages): a family whose single file IS the whole pipeline has no transformer-only GGUF, and
+ a multi-denoiser family has no single transformer to swap. Exposed so the model-listing
+ routes can classify a GGUF the same way the loader would, instead of keeping a second
+ hand-maintained list that drifts."""
return not fam.single_file_is_pipeline and not fam.pipeline_only
@@ -1434,7 +1408,8 @@ def sd_cpp_companion_only_repo_ids() -> frozenset[str]:
``unsloth/Qwen2.5-VL-7B-Instruct-GGUF``, which is a perfectly good CHAT model that sd.cpp also
borrows as a text encoder. Hiding this set from a chat or GGUF listing would take a real model
away from a user who downloaded it to chat with. Today's only consumer is the non-GGUF
- cached-model listing, which never sees a GGUF-only repo."""
+ cached-model listing, which never sees a GGUF-only repo.
+ """
companions: set[str] = set()
loadable: set[str] = set()
for fam in _FAMILIES:
@@ -1453,14 +1428,12 @@ def sd_cpp_companion_only_repo_ids() -> frozenset[str]:
def sd_cpp_text_encoder_candidates(fam: DiffusionFamily) -> tuple[tuple[str, str, str], ...]:
- """EVERY text-encoder set an sd.cpp load of *fam* could pick, unioned.
-
- For the guard, not for a load. A load reads the GGUF header and picks one; a guard
- reconstructing a checkpoint it cannot open has no header, and for FLUX.2-klein a renamed 9B
- file carries no size token either, so the string fallback answers 4B and the 9B encoder the
- load actually fetched is left unprotected. Naming both costs a delete that is refused and
- saves one that strands an installed model.
- """
+ """EVERY text-encoder set an sd.cpp load of *fam* could pick, unioned. For the guard, not for a
+ load: a load reads the GGUF header and picks one, while a guard reconstructing a checkpoint
+ it cannot open has no header, and for FLUX.2-klein a renamed 9B file carries no size token
+ either, so the string fallback answers 4B and the 9B encoder the load actually fetched is
+ left unprotected. Naming both costs a delete that is refused and saves one that strands an
+ installed model."""
sets = [fam.sd_cpp_text_encoders]
if fam.name == "flux.2-klein":
sets.append(_FLUX2_KLEIN_9B_SD_CPP_TEXT_ENCODERS)
@@ -1473,16 +1446,13 @@ def sd_cpp_text_encoders_for(
gguf_filename: Optional[str] = None,
inner_dim: Optional[int] = None,
) -> tuple[tuple[str, str, str], ...]:
- """The sd.cpp text encoders for a specific load.
-
- FLUX.2-klein picks by variant (9B needs Qwen3-8B, 4B the family default); every other family
- returns its static table.
-
- ``inner_dim`` is the checkpoint's own answer, read from the GGUF header
- (``gguf_flux2_inner_dim``): it decides whenever the caller has it, because a renamed or
- hand-picked file makes the load identity say nothing. The repo id + filename string match is
- the fallback for the callers that have no header to read (the delete guard reconstructs a
- committed load; the plan runs before a byte is fetched)."""
+ """The sd.cpp text encoders for a specific load. FLUX.2-klein picks by variant (9B needs
+ Qwen3-8B, 4B the family default); every other family returns its static table. ``inner_dim``
+ is the checkpoint's own answer, read from the GGUF header (``gguf_flux2_inner_dim``): it
+ decides whenever the caller has it, because a renamed or hand-picked file makes the load
+ identity say nothing. The repo id + filename string match is the fallback for the callers
+ that have no header to read (the delete guard reconstructs a committed load; the plan runs
+ before a byte is fetched)."""
if fam.name == "flux.2-klein":
# A dim this family does not have (a FLUX.2-dev file, a misread) falls through to the strings rather than
# guessing, exactly as the base-size guard fails open on one.
@@ -1500,8 +1470,8 @@ def sd_cpp_text_encoders_for(
# FLUX.2 sizes the adaLN modulation projection as (6 * inner_dim, inner_dim), and inner_dim is the only thing that
# differs between the klein sizes and dev. sd.cpp keys its own FLUX.2 version detection on this same tensor, and GGUF
-# metadata cannot help: our files and leejet's carry no kv pairs at all, and city96/orabazes write general.architecture
-# = "flux" for FLUX.1 and FLUX.2 alike.
+# metadata cannot help: our files and leejet's carry no kv pairs at all, and city96/orabazes write
+# general.architecture = "flux" for FLUX.1 and FLUX.2 alike.
_FLUX2_PROBE_TENSOR = "double_stream_modulation_img.lin.weight"
_FLUX2_INNER_DIMS = {
3072: "FLUX.2-klein-4B / klein-base-4B",
@@ -1528,7 +1498,6 @@ class _HeaderTensor(NamedTuple):
def flux2_base_inner_dim(base_repo: Optional[str]) -> Optional[int]:
"""The ``inner_dim`` a FLUX.2 base config expects, or None when the repo is not one we map.
-
Keyed on UPSTREAM ids, reached through ``canonical_base``: a known ungated mirror is
byte-identical to what it copies, so it maps back and is checked exactly like its upstream.
Anything else -- a local path, a third-party repack, a base we do not ship -- misses, and
@@ -1560,20 +1529,19 @@ def gguf_flux2_inner_dim(path) -> Optional[int]:
def gguf_flux2_inner_dim_from_header(header: bytes) -> Optional[int]:
"""``inner_dim`` read from the leading bytes of a FLUX.2 GGUF, or None.
- Lets the selection-time preflight range-read a few hundred KiB over HTTP instead of pulling
- the whole multi-GB checkpoint: the tensor table it needs sits in the first ~15 KiB. Same
- parser as ``gguf_flux2_inner_dim``, with the two things a PREFIX changes:
-
- * ``_build_tensors`` is skipped. The base class builds a numpy view over every tensor's DATA,
- which a prefix does not carry -- and satisfying those reads would allocate the whole
- declared checkpoint (tens of GiB), which is exactly the cost this avoids. Only the name and
- shape from the table are wanted, and both are already parsed.
- * ``_get`` REFUSES a read past the end instead of returning short or zero-filled data. The
- table is read field by field, so a prefix cutting between a tensor's name and its dims
- would otherwise hand back a zero shape -- a wrong answer, not a missing one, and one that
- would refuse a perfectly valid pick.
-
- None on anything unreadable: too short a prefix, a non-GGUF file, an absent probe tensor."""
+ Lets the selection-time preflight range-read a few hundred KiB over HTTP instead of pulling the
+ whole multi-GB checkpoint: the tensor table it needs sits in the first ~15 KiB. Same parser as
+ ``gguf_flux2_inner_dim``, with the two things a PREFIX changes. ``_build_tensors`` is skipped,
+ because the base class builds a numpy view over every tensor's DATA, which a prefix does not
+ carry, and satisfying those reads would allocate the whole declared checkpoint (tens of GiB);
+ only the name and shape from the table are wanted, and both are already parsed. And ``_get``
+ REFUSES a read past the end instead of returning short or zero-filled data, since the table is
+ read field by field and a prefix cutting between a tensor's name and its dims would otherwise
+ hand back a zero shape, a wrong answer rather than a missing one, which would refuse a perfectly
+ valid pick.
+
+ None on anything unreadable: too short a prefix, a non-GGUF file, an absent probe tensor.
+ """
if not header:
return None
tmp_path = None
@@ -1598,8 +1566,8 @@ def gguf_flux2_inner_dim_from_header(header: bytes) -> Optional[int]:
return super()._get(offset, dtype, count, override_order)
def _build_tensors(self, start_offs, fields):
- # ``field.name`` is the decoded tensor name and parts[3] its dims, both already read from real bytes by
- # ``_get_tensor_info_field``.
+ # ``field.name`` is the decoded tensor name and parts[3] its dims, both already read from real bytes
+ # by ``_get_tensor_info_field``.
self.tensors = [_HeaderTensor(field.name, field.parts[3]) for field in fields]
# GGUFReader memory-maps a path, so the prefix has to land on disk. Bounded by the caller's range request, so
@@ -1608,9 +1576,8 @@ def gguf_flux2_inner_dim_from_header(header: bytes) -> Optional[int]:
with os.fdopen(fd, "wb") as fh:
fh.write(header)
reader = _HeaderOnlyGGUFReader(tmp_path)
- # `data_offset` is where the table ends, so a table that ran past the prefix is not one to read a shape out of;
- # Belt and braces on top of the refusing ``_get``: ``data_offset`` is where the table ends, so a table that ran
- # past the prefix is not one to read a shape out of. The alignment slack is for a header-only file, whose
+ # Belt and braces on top of the refusing ``_get``: ``data_offset`` is where the table ends, so a table that
+ # ran past the prefix is not one to read a shape out of. The alignment slack is for a header-only file, whose
# padding was never written.
if reader.data_offset > len(header) + min(int(reader.alignment), 4096):
return None
@@ -1630,11 +1597,10 @@ def gguf_flux2_inner_dim_from_header(header: bytes) -> Optional[int]:
def flux2_mismatch_reason(
gguf_name: str, base_repo: str, got: Optional[int], want: Optional[int]
) -> Optional[str]:
- """Why this FLUX.2 GGUF cannot load against this base, or None when they agree.
-
- One message for all three checks on the pairing (the plan, the pre-eviction preflight and the
- loader's backstop), so the user reads the same sentence wherever it is caught. ``gguf_name`` is
- a display name the caller has already reduced to a basename. Returns None on any unknown -- an
+ """Why this FLUX.2 GGUF cannot load against this base, or None when they agree. One message for
+ all three checks on the pairing (the plan, the pre-eviction preflight and the loader's
+ backstop), so the user reads the same sentence wherever it is caught. ``gguf_name`` is a
+ display name the caller has already reduced to a basename. Returns None on any unknown -- an
unreadable header, an unmapped base -- so every caller fails open."""
if want is None or got is None or want == got:
return None
@@ -1649,15 +1615,13 @@ def flux2_mismatch_reason(
def assert_flux2_gguf_matches_base(fam, base_repo: str, gguf_path) -> None:
"""Fail early, and legibly, when a FLUX.2 GGUF is paired with a different-size base config.
-
Without this the mismatch surfaces from inside the GGUF quantizer as a bare shape error
("expected torch.Size([18432, 3072]), decodes to (24576, 4096)") that names neither the file
nor the repo. Fail-open by construction: any unreadable file, non-FLUX.2 tensor set, or
- unmapped base leaves the load exactly as it was.
-
- The LAST of three checks on the same pairing, and the only one that opens the downloaded file:
- ``diffusion_compat`` runs the same comparison off a range-read header at plan time and again
- before the resident pipeline is torn down, so a mismatch normally never reaches here."""
+ unmapped base leaves the load exactly as it was. The LAST of three checks on the same
+ pairing, and the only one that opens the downloaded file: ``diffusion_compat`` runs the same
+ comparison off a range-read header at plan time and again before the resident pipeline is
+ torn down, so a mismatch normally never reaches here."""
if gguf_path is None or not str(getattr(fam, "name", "")).startswith("flux.2"):
return
# Short-circuit on the free half: an unmapped base fails open anyway, so a mirror id must not cost a memory-map of
diff --git a/studio/backend/core/inference/diffusion_gguf_compile.py b/studio/backend/core/inference/diffusion_gguf_compile.py
index db50a18187f..893a7e5b360 100644
--- a/studio/backend/core/inference/diffusion_gguf_compile.py
+++ b/studio/backend/core/inference/diffusion_gguf_compile.py
@@ -33,8 +33,6 @@ from typing import Any
from .diffusion_patch_backend import apply_patch, revert_patch
-# --- kill-switch -------------------------------------------------------------------
-
_ENV_COMPILE_DEQUANT = "UNSLOTH_DIFFUSION_GGUF_COMPILE_DEQUANT"
_DISABLED = {"0", "off", "false", "no"}
@@ -99,9 +97,6 @@ def uninstall_compiled_dequant() -> None:
_compiled_dequant_installed = False
-# --- convenience -------------------------------------------------------------------
-
-
def uninstall_all() -> None:
"""Uninstall the GGUF accelerator. Idempotent; safe to call on every unload."""
uninstall_compiled_dequant()
diff --git a/studio/backend/core/inference/diffusion_hidream.py b/studio/backend/core/inference/diffusion_hidream.py
index bf49c90f481..b188d836872 100644
--- a/studio/backend/core/inference/diffusion_hidream.py
+++ b/studio/backend/core/inference/diffusion_hidream.py
@@ -53,9 +53,8 @@ def hidream_te4_kwargs(
import torch # noqa: F401 -- dtype values are torch dtypes; import keeps parity with callers
from transformers import AutoTokenizer, LlamaForCausalLM
- # pin the LIVE hub root: an unpinned lookup uses the import-time root and fails under local_files_only
- # Pinned to the LIVE hub root: ``encoder_repo_complete`` verifies these assets there, so an unpinned lookup after a
- # mid-session cache-folder change searches huggingface_hub's import-time root instead and fails under
+ # Pinned to the LIVE hub root: ``encoder_repo_complete`` verifies these assets there, so an unpinned lookup after
+ # a mid-session cache-folder change searches huggingface_hub's import-time root instead and fails under
# local_files_only for a 16 GB encoder that is present, after the resident image pipeline was evicted.
from utils.hf_cache_settings import active_hf_hub_cache
diff --git a/studio/backend/core/inference/diffusion_ideogram4.py b/studio/backend/core/inference/diffusion_ideogram4.py
index 14e8f46d85d..11569a04188 100644
--- a/studio/backend/core/inference/diffusion_ideogram4.py
+++ b/studio/backend/core/inference/diffusion_ideogram4.py
@@ -71,7 +71,6 @@ def _patch_create_causal_mask() -> None:
_CAUSAL_MASK_PATCHED = True
-# fused qkv (Q/K/V stacked, each hidden_size rows), read from config so a future change cannot mis-split it
# The fp8 attention is a fused ``qkv`` matrix (Q/K/V stacked, each ``hidden_size`` rows), read from config so a future
# change cannot mis-split it.
_QKV_SPLIT = ("to_q", "to_k", "to_v")
@@ -321,7 +320,6 @@ def load_ideogram4_transformer(
config = _read_transformer_config(repo_id, subfolder, token)
shard_paths = _transformer_shard_paths(repo_id, subfolder, token)
- # check every shard header: a dense-first multi-shard fp8 export must still route to dequant
# Detect fp8 from shard HEADERS (keys() reads metadata only), checking all shards so a dense-first multi-shard
# export still routes to the dequant path. Only fp8 materializes tensors; -nf4 goes straight to from_pretrained.
is_fp8 = False
diff --git a/studio/backend/core/inference/diffusion_krea2.py b/studio/backend/core/inference/diffusion_krea2.py
index 821d182a1a5..3b380b93f11 100644
--- a/studio/backend/core/inference/diffusion_krea2.py
+++ b/studio/backend/core/inference/diffusion_krea2.py
@@ -176,7 +176,6 @@ def load_krea2_pipeline(
"""
import diffusers
- # diffusers gained Krea2Pipeline in 0.39; fail here rather than on a bare AttributeError below
# diffusers gained Krea2Pipeline in 0.39; on an older install the getattr chain below dies with a bare
# AttributeError, so fail first with the fix.
if not hasattr(diffusers, "Krea2Pipeline"):
@@ -188,7 +187,6 @@ def load_krea2_pipeline(
token = hf_token or None
cache_dir = _live_cache_dir()
- # read the index before the 26 GB transformer: a corrupt one used to surface only after everything was built
# A few KB, and it configures the components, so it is read before them: read last, a corrupt index only surfaced
# after the encoder, the VAE and the 26 GB transformer were already built.
model_index = _load_model_index(repo_id, hf_token = token, local_files_only = local_files_only)
diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.py
index 8be552369c7..7fd64ca2f6a 100644
--- a/studio/backend/core/inference/diffusion_lora.py
+++ b/studio/backend/core/inference/diffusion_lora.py
@@ -37,8 +37,6 @@ _ALL_EXTS = (".safetensors", ".gguf")
@dataclass(frozen = True)
class LoraCatalogEntry:
- """One discoverable LoRA adapter."""
-
id: str
display_name: str
source: str
@@ -63,9 +61,6 @@ class ResolvedLora:
weight: float
-# curated HF repos with a single-file weight; local discovery and any public HF LoRA repo id also work
-
-
# Curated, family-tagged catalog of known-good diffusion LoRAs (HF repos with a single-file weight). Local discovery and
# any public HF LoRA repo id also work.
def _krea2_lora(style: str, display_name: str) -> LoraCatalogEntry:
@@ -130,7 +125,6 @@ def _scan_local() -> list[LoraCatalogEntry]:
for p in children
if p.is_file() and p.suffix.lower() in _ALL_EXTS and not is_appledouble_metadata(p)
]
- # two files sharing a stem collide on id (== stem)
# Two files sharing a stem but differing in extension collide on id (== stem), so a colliding stem keeps the full
# filename.
stem_counts: dict[str, int] = {}
@@ -291,10 +285,8 @@ def _pick_repo_weight_file(repo_id: str, hf_token: Optional[str]) -> str:
return f
if safes:
return safes[0]
- # gguf fallback only: an imatrix is a .gguf holding no adapter and would be picked here, while a .safetensors never
- # is
- # The gguf fallback only: an imatrix is a .gguf holding no adapter and would be picked here, while a .safetensors is
- # never one, so the candidates above stay untouched.
+ # The gguf fallback only: an imatrix is a .gguf holding no adapter and would be picked here, while a .safetensors
+ # is never one, so the candidates above stay untouched.
ggufs = [
f
for f in files
@@ -426,10 +418,9 @@ _NATIVE_LORA_FAMILY_TOKENS = (
"sd3",
"stable-diffusion",
)
-# LoRA path is the load-time BAKE: adapters attach on the dense transformer BEFORE torchao quantize_ + compile
-# Diffusers quant schemes whose LoRA path is the load-time BAKE: adapters attach on the dense transformer BEFORE torchao
-# quantize_ + compile (peft's TorchaoLoraLinear dispatch needs quantizer metadata a manual quantize_ lacks). Verified on
-# peft 0.18.1 / torchao 0.17 / torch 2.10: scale 0 reproduces the quantized base bit-exactly.
+# Diffusers quant schemes whose LoRA path is the load-time BAKE: adapters attach on the dense transformer BEFORE
+# torchao quantize_ + compile (peft's TorchaoLoraLinear dispatch needs quantizer metadata a manual quantize_ lacks).
+# Verified on peft 0.18.1 / torchao 0.17 / torch 2.10: scale 0 reproduces the quantized base bit-exactly.
_DIFFUSERS_LORA_BAKED_QUANT = ("int8", "fp8")
# Prototype schemes with no validated LoRA path (and no shipped families needing one).
_DIFFUSERS_LORA_BLOCKED_QUANT = ("nvfp4", "mxfp8")
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 123bfcfc5bb..e95b046cad0 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -3,15 +3,15 @@
"""Measured-budget memory policy for the local diffusion backend.
-From the resolved device target, a free-memory snapshot, and a coarse model footprint
-estimate, this picks a CPU-offload policy and VAE slice/tile settings, then applies them to a
-built diffusers pipeline. A model that won't fit resident is kept running by streaming weights
-through the GPU one module at a time, which is lossless (offload / VAE slicing change placement
-and decode chunking, not numerics).
-
-The choice is coarse (sizes the model, not every activation), so ``auto`` is best-effort and
-the explicit ``fast`` / ``balanced`` / ``low_vram`` modes are a hard override. torch / psutil
-imported lazily.
+From the resolved device target, a free-memory snapshot and a coarse model footprint estimate, this
+picks a CPU-offload policy and VAE slice/tile settings, then applies them to a built diffusers
+pipeline. A model that will not fit resident is kept running by streaming weights through the GPU
+one module at a time, which is lossless (offload / VAE slicing change placement and decode chunking,
+not numerics).
+
+The choice is coarse (sizes the model, not every activation), so ``auto`` is best-effort and the
+explicit ``fast`` / ``balanced`` / ``low_vram`` modes are a hard override. torch / psutil imported
+lazily.
"""
from __future__ import annotations
@@ -23,7 +23,6 @@ from dataclasses import dataclass, replace
from typing import Any, Callable, Optional
-# ── memory modes (operator intent) ───────────────────────────────────────────
MEMORY_MODE_AUTO = "auto"
MEMORY_MODE_FAST = "fast"
MEMORY_MODE_BALANCED = "balanced"
@@ -35,11 +34,11 @@ MEMORY_MODES = (
MEMORY_MODE_LOW_VRAM,
)
-# None: all weights resident. model: enable_model_cpu_offload(), one top-level module on the GPU at a time. none -- all
-# weights resident (fastest; fits only with room). model -- enable_model_cpu_offload(): one top-level module on the GPU
-# at a time. group -- apply_group_offloading() on the transformer: stream a few blocks at a time with a prefetch stream.
-# streaming -- group-offload the transformer and leaf-offload text encoders that cannot fit whole. sequential --
-# enable_sequential_cpu_offload(): submodule-level (broken for GGUF through diffusers 0.39, kept as an escape hatch).
+# none -- all weights resident (fastest; fits only with room). model -- enable_model_cpu_offload(): one top-level
+# module on the GPU at a time. group -- apply_group_offloading() on the transformer: stream a few blocks at a time
+# with a prefetch stream. streaming -- group-offload the transformer and leaf-offload text encoders that cannot fit
+# whole. sequential -- enable_sequential_cpu_offload(): submodule-level (broken for GGUF through diffusers 0.39, kept
+# as an escape hatch).
OFFLOAD_NONE = "none"
OFFLOAD_MODEL = "model"
OFFLOAD_GROUP = "group"
@@ -201,10 +200,9 @@ class MemoryPlan:
device_memory: DeviceMemory
estimates: dict[str, Optional[int]]
reasons: tuple[str, ...] = ()
- # defaulted so every existing construction is unchanged
# Under group offload, stream the TEXT ENCODERS alongside the transformer instead of keeping them resident.
- # Defaulted so every existing construction is unchanged; set only where that is what makes group offload fit at all
- # (see plan_diffusion_memory).
+ # Defaulted so every existing construction is unchanged; set only where that is what makes group offload fit at
+ # all (see plan_diffusion_memory).
stream_text_encoders: bool = False
@property
@@ -224,9 +222,6 @@ class MemoryPlan:
}
-# ── hardware snapshot ─────────────────────────────────────────────────────────
-
-
def snapshot_device_memory(target: Any) -> DeviceMemory:
"""Free / total memory for ``target``'s device. Never raises: a probe failure yields None
counts, which the planner treats as "budget unknown" (stay resident)."""
@@ -249,21 +244,18 @@ def snapshot_device_memory(target: Any) -> DeviceMemory:
def reclaimable_snapshot_device_memory(target: Any) -> DeviceMemory:
- """``snapshot_device_memory`` with the caching allocator's RECLAIMABLE bytes credited back
- as free, without flushing it.
+ """``snapshot_device_memory`` with the caching allocator's RECLAIMABLE bytes credited back as free,
+ without flushing it.
``torch.cuda.mem_get_info`` reports driver-level free memory, so every block the caching
- allocator is holding for reuse counts as used even though the next allocation would take it
- straight back. A generation that has already run therefore looks like it is on a much smaller
- card than it is. ``settled_snapshot_device_memory`` fixes that with ``empty_cache()``, which is
- right when it runs ONCE per load, but wrong on a per-generation path: releasing every cached
- block forces the next forward to go back to ``cudaMalloc`` for all of its activations, which is
- the exact cost the caching allocator exists to avoid.
-
- ``memory_reserved() - memory_allocated()`` is that same figure without the flush: bytes this
- process holds and is not using. Adding it back is the honest reading of "how much could this
- generation get". Deliberately an over-estimate at the margin -- fragmentation can stop some of
- it being handed to one large tensor -- because this feeds a REFUSAL, and over-estimating free
+ allocator holds for reuse counts as used even though the next allocation would take it straight
+ back, and a card that has already generated looks much smaller than it is.
+ ``settled_snapshot_device_memory`` fixes that with ``empty_cache()``, right once per load but
+ wrong per generation: releasing every cached block forces the next forward back to
+ ``cudaMalloc`` for all its activations, the exact cost the caching allocator exists to avoid.
+
+ ``memory_reserved() - memory_allocated()`` is that same figure without the flush. Adding it back
+ deliberately over-estimates at the margin, because this feeds a REFUSAL and over-estimating free
memory can only make the guard quieter, never more trigger-happy.
Only the process's own allocator is credited. Host memory pinned by ``enable_model_cpu_offload``
@@ -298,16 +290,14 @@ def reclaimable_snapshot_device_memory(target: Any) -> DeviceMemory:
def _settle_delay(delay_s: float) -> float:
"""How long to wait between the retried reads, honouring ``UNSLOTH_SETTLE_DELAY_S``.
- What the retry loop is for is rejecting a TRANSIENT undercount, and the ``max`` over the
- reads does that whatever the spacing: a real neighbouring tenant caps every read, a
- transient caps only some. The spacing exists to give a real transient time to clear on a
- live card, so production keeps the full second.
+ The retry loop rejects a TRANSIENT undercount, and the ``max`` over the reads does that whatever
+ the spacing; the spacing only gives a real transient time to clear on a live card, so production
+ keeps the full second.
- A test that reaches this through ``_plan_memory`` cannot pass ``delay_s`` and pays the
- wait for nothing -- its snapshots are stubs whose answers do not change with time.
- ``test_diffusion_backend.py`` alone spent 142s of a 328s suite here, most of it in
- tests sitting at exactly 4.00s. Callers that can pass ``delay_s = 0`` already do
- (``test_diffusion_memory.py``); this is for the ones that cannot reach the argument.
+ A test reaching this through ``_plan_memory`` cannot pass ``delay_s`` and pays the wait for
+ nothing, since its snapshots are stubs whose answers do not change with time
+ (``test_diffusion_backend.py`` alone spent 142s of a 328s suite here). Callers that can pass
+ ``delay_s = 0`` already do.
"""
override = os.environ.get("UNSLOTH_SETTLE_DELAY_S")
if override is None:
@@ -387,7 +377,6 @@ def _cuda_memory(backend: str) -> tuple[Optional[int], Optional[int], str]:
free, total = trusted_mem_get_info()
kind = "discrete_vram"
try:
- # query the CURRENT device; hardcoding 0 would inspect the wrong GPU and misclassify it
# Query the CURRENT device (mem_get_info reports it); hardcoding 0 would inspect the wrong GPU and
# misclassify it.
props = torch.cuda.get_device_properties(torch.cuda.current_device())
@@ -429,9 +418,6 @@ def _system_memory_mib() -> tuple[Optional[int], Optional[int]]:
return None, None
-# ── size estimates ────────────────────────────────────────────────────────────
-
-
def file_size_mib(path: Any) -> Optional[int]:
"""On-disk size of ``path`` in MiB, or None if it can't be stat'd."""
try:
@@ -553,29 +539,26 @@ def _unified_oversize_override() -> bool:
def unified_memory_shortfall_message(plan: Any, *, family: Optional[str] = None) -> Optional[str]:
- """On UNIFIED device memory, a user-facing refusal when the WEIGHTS alone cannot fit the
- safe budget (else None).
-
- Unified memory is the one placement where the planner has no fallback left. On discrete
- VRAM an oversized model still loads: it degrades to group / whole-module CPU offload and
- streams from host RAM. On Apple Silicon (and integrated CUDA) the CPU and GPU share one
- pool, so offload moves bytes within that pool and frees nothing -- ``plan_diffusion_memory``
- correctly returns ``none``, and the load then allocates past physical memory. There is no
- torch OOM to catch, because ``_mps_or_cpu_target`` sets PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0
- to disable the MPS allocator's hard limit, so the failure is the OS killing the process
- with no Python exception. Refusing up front is the only way the user learns why.
-
- Weights only (``model_dense_mib`` + the flat base overhead): the per-call runtime headroom
- is the SOFT term -- it is a coarse activation / VAE-decode estimate, and the mps path
- already turns on VAE tiling + slicing, which cuts the decode peak this estimate does not
- model. Counting it would refuse marginal loads that would in fact complete. The weights are
- the hard term: they are unavoidable resident bytes, sized from measured per-family
- component tables or from on-disk checkpoint size, and if they alone do not fit then nothing
- at generation time can rescue the load. Same reasoning as the llama.cpp APU guard, which
- budgets weights and lets KV/context auto-reduce.
-
- Fail-open on anything unknown (no budget, no size), matching the planner's own
- "budget or model size unknown; staying resident"."""
+ """On UNIFIED device memory, a user-facing refusal when the WEIGHTS alone cannot fit the safe
+ budget (else None).
+
+ Unified memory is the one placement with no fallback left. On discrete VRAM an oversized model
+ still loads, degrading to group / whole-module CPU offload and streaming from host RAM. On Apple
+ Silicon (and integrated CUDA) the CPU and GPU share one pool, so offload moves bytes within that
+ pool and frees nothing: ``plan_diffusion_memory`` correctly returns ``none`` and the load then
+ allocates past physical memory. There is no torch OOM to catch, because ``_mps_or_cpu_target``
+ sets PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 to disable the MPS allocator's hard limit, so the
+ failure is the OS killing the process with no Python exception.
+
+ Weights only (``model_dense_mib`` plus the flat base overhead): the per-call runtime headroom is
+ a coarse activation / VAE-decode estimate and the mps path already turns on VAE tiling and
+ slicing, so counting it would refuse marginal loads that would in fact complete. The weights are
+ unavoidable resident bytes, and if they alone do not fit then nothing at generation time can
+ rescue the load. Same reasoning as the llama.cpp APU guard.
+
+ Fail-open on anything unknown (no budget, no size), matching the planner's own "budget or model
+ size unknown; staying resident".
+ """
if _unified_oversize_override():
return None
try:
@@ -646,9 +629,6 @@ def _sum_required(*values: Optional[int]) -> Optional[int]:
return total
-# ── the planner ───────────────────────────────────────────────────────────────
-
-
def plan_diffusion_memory(
*,
target: Any,
@@ -661,23 +641,27 @@ def plan_diffusion_memory(
requested_mode: Optional[str] = None,
explicit_offload: bool = False,
) -> MemoryPlan:
- """Pick an offload policy + VAE memory savers for the current load.
+ """Pick an offload policy plus VAE memory savers for the current load.
``model_dense_mib`` is the resident size of all weights; ``companion_dense_mib`` is just the
companions, which stay resident under group offload while the transformer streams block by
block. ``text_encoder_dense_mib`` is the TEXT-ENCODER share of that companion total, which
- unlocks a second group tier (below); None means "no split available" and reproduces the
- pre-split decision exactly. ``explicit_offload`` is the back-compat ``cpu_offload=True``
- request (forces model offload).
+ unlocks a second group tier; None means "no split available" and reproduces the pre-split
+ decision exactly. ``explicit_offload`` is the back-compat ``cpu_offload=True`` request (forces
+ model offload).
Policies by speed/VRAM tradeoff:
- none - everything resident: fastest, highest VRAM.
- group - stream the transformer, companions resident: near-resident speed, moderate cut.
- group + streamed text encoders - as above, but the encoders stream too: they run ONCE,
- before step 0, so this costs one extra host-to-device pass per call rather than a
- per-step one, and it frees their bytes for every denoising step.
- model - offload every component: lowest VRAM, slow.
- streaming - stream transformer blocks and text-encoder leaves when one component cannot fit.
+
+ none - everything resident: fastest, highest VRAM.
+
+ group - stream the transformer, companions resident: near-resident speed, moderate cut.
+
+ group + streamed text encoders - as above, but the encoders stream too: they run ONCE, before
+ step 0, so this costs one extra host-to-device pass per call rather than a per-step one.
+
+ model - offload every component: lowest VRAM, slow.
+
+ streaming - stream transformer blocks and text-encoder leaves when one component cannot fit.
"""
mode = normalize_memory_mode(requested_mode) or MEMORY_MODE_AUTO
can_offload = bool(getattr(target, "supports_model_cpu_offload", False))
@@ -724,8 +708,6 @@ def plan_diffusion_memory(
and group_floor_streamed_te <= budget
)
- # speed order: plain group (companions resident) beats group with streamed encoders (one extra host-to-device pass
- # per CALL) beats whole-module offload (every component paged per STEP
# The best tier available when the weights do not fit resident, in speed order: plain group (companions resident)
# beats group with streamed encoders (one extra host-to-device pass per CALL) beats whole-module offload (every
# component paged per STEP -- the 48-minute case).
@@ -811,9 +793,6 @@ def plan_diffusion_memory(
)
-# ── apply to a built pipeline ─────────────────────────────────────────────────
-
-
def _streamable_components(pipe: Any, torch: Any) -> dict[str, tuple[Any, str]]:
"""Component name -> (module, group-offload type) for what streaming keeps off the device.
@@ -834,9 +813,9 @@ def _streamable_components(pipe: Any, torch: Any) -> dict[str, tuple[Any, str]]:
def refine_memory_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPlan:
"""Replace whole-module offload when a loaded component cannot fit on the device.
- The coarse planner runs before the pipeline exists. At this point the weights are still on
- CPU, so their actual packed storage is a better signal than family or cache estimates. Keep
- whole-module offload when every component can fit, preserving its faster execution. When one
+ The coarse planner runs before the pipeline exists; at this point the weights are still on CPU,
+ so their actual packed storage is a better signal than family or cache estimates. Keep
+ whole-module offload when every component fits, preserving its faster execution; when one
cannot, use granular streaming so no forward needs to materialise that component in full.
Only a STREAMABLE component justifies the switch, and only if the components streaming cannot
@@ -1118,15 +1097,11 @@ def _apply_group_offload(
return False
-# the load-time plan cannot know the output resolution
-
-# ── generate-time activation guard ──────────────────────────────────────────── The load-time plan cannot know the
-# output resolution: a model is loaded once and then generates at whatever size the sliders say, so ``_plan_memory``
-# budgets the 1024x1024 default. That is the right call for PLACEMENT, but it means a request for a much larger frame is
-# never checked against anything. This is the second half: a per-generation re-check, with the real dimensions.
-# Opt-in escape hatch, mirroring the load-time one: the activation estimate is coarse, so an operator who believes it is
-# wrong keeps a way through.
-# ── generate-time activation guard ────────────────────────────────────────────
+# Generate-time activation guard. The load-time plan cannot know the output resolution: a model is loaded once and
+# then generates at whatever size the sliders say, so ``_plan_memory`` budgets the 1024x1024 default. That is the
+# right call for PLACEMENT, but it means a request for a much larger frame is never checked against anything, so this
+# re-checks per generation with the real dimensions. Opt-in escape hatch, mirroring the load-time one: the activation
+# estimate is coarse, so an operator who believes it is wrong keeps a way through.
OVERSIZED_GENERATE_ENV = "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE"
@@ -1154,41 +1129,36 @@ def image_activation_shortfall_message(
base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,
source_driven: bool = False,
) -> Optional[str]:
- """A user-facing refusal when this generation's ACTIVATIONS plus the flat base overhead
- cannot fit the free device budget, else None.
-
- ``source_driven`` says the refused size comes from an UPLOADED image rather than the
- Resolution control (inpaint / extend / upscale / edit). Telling those callers to "generate at
- a smaller resolution" points them at a control that cannot change the number in the refusal.
- Same verdict either way; only the remedy sentence differs.
-
- Why this is a refusal and not another tuning knob: weights can be offloaded, activations
- cannot. Every offload tier moves WEIGHTS between host and device; the latents, attention
- buffers and VAE intermediates a forward pass allocates have to be on the device while it
- runs. So an activation estimate above the free budget is an overrun at every tier, including
- the lowest one, rather than a hint that a different placement would help. There is nothing
- left to degrade to, which is exactly the situation where refusing beats trying.
-
- Refusing also has to happen HERE rather than being left to torch. On Linux the overrun raises
- ``torch.OutOfMemoryError`` and the job dies cleanly. On Windows WDDM (including ROCm) it does
- not raise at all: the driver satisfies the overflow from system RAM as "non-local" GPU memory,
- so the process quietly grows past the card into tens of GB of host RAM and pagefile, and the
- desktop stops responding with no error anywhere. A ValueError here is a 400 with the reason,
- which is the clean refusal that failure mode never produces on its own.
-
- What it does NOT do is second-guess the load. The flat headroom this estimate is built on is a
- deliberately generous PLANNING figure whose job is to pick an offload tier, and the tier it
- picks already runs the 1024x1024 default on cards whose whole budget is under 8 GB (measured:
- a 8 GB card's safe budget is 5898 MiB against a 6963 MiB default-resolution estimate, and
- those generations complete). Treating that figure as a hard limit at or below the default
- would refuse work that succeeds today. So the refusal needs BOTH conditions: over the free
- budget, and over what the load already budgeted. That confines it to the resolution-driven
- overrun it is for -- the load reserved a 1 MP frame and the request is several times that --
- and leaves every generation at or below the default resolution exactly as it is.
+ """A user-facing refusal when this generation's ACTIVATIONS plus the flat base overhead cannot fit
+ the free device budget, else None.
+
+ ``source_driven`` says the refused size comes from an UPLOADED image rather than the Resolution
+ control (inpaint / extend / upscale / edit); telling those callers to generate at a smaller
+ resolution points them at a control that cannot change the number in the refusal. Same verdict
+ either way, only the remedy sentence differs.
+
+ Why a refusal and not another knob: weights can be offloaded, activations cannot. Every offload
+ tier moves WEIGHTS between host and device, while the latents, attention buffers and VAE
+ intermediates a forward pass allocates have to be on the device while it runs, so an activation
+ estimate above the free budget overruns at every tier including the lowest.
+
+ Refusing has to happen HERE rather than being left to torch. On Linux the overrun raises
+ ``torch.OutOfMemoryError`` and the job dies cleanly; on Windows WDDM (including ROCm) it does
+ not raise at all -- the driver satisfies the overflow from system RAM as "non-local" GPU memory,
+ so the process quietly grows past the card into tens of GB of host RAM and pagefile and the
+ desktop stops responding with no error anywhere.
+
+ It does NOT second-guess the load. The flat headroom this estimate is built on is a deliberately
+ generous PLANNING figure for picking a tier, and that tier already runs the 1024x1024 default on
+ cards whose whole budget is under 8 GB (measured: a 8 GB card's safe budget is 5898 MiB against
+ a 6963 MiB default-resolution estimate, and those generations complete). So the refusal needs
+ BOTH conditions -- over the free budget AND over what the load already budgeted -- which
+ confines it to the resolution-driven overrun it is for.
Fail-open on anything unknown (no free reading, no budget) and on any device class where the
estimate or the offload story means something different, so a broken probe can never block a
- generation that would have worked."""
+ generation that would have worked.
+ """
if _oversized_generate_override():
return None
try:
diff --git a/studio/backend/core/inference/diffusion_patch_backend.py b/studio/backend/core/inference/diffusion_patch_backend.py
index 5c920bae5e1..72f761f5032 100644
--- a/studio/backend/core/inference/diffusion_patch_backend.py
+++ b/studio/backend/core/inference/diffusion_patch_backend.py
@@ -22,7 +22,6 @@ from __future__ import annotations
from typing import Any, Callable, Optional
-# memoised per process (None = unavailable): resolution can import unsloth, far too heavy to repeat
# Resolved ``unsloth_zoo.temporary_patches.utils`` helpers, memoised per process (None = tried and unavailable):
# resolution can import ``unsloth``, far too heavy to repeat per call.
_HELPERS: Optional[dict] = None
diff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.py
index a26b47604eb..c83b02a1218 100644
--- a/studio/backend/core/inference/diffusion_precision.py
+++ b/studio/backend/core/inference/diffusion_precision.py
@@ -365,7 +365,6 @@ def _cast_fp8(encoder: Any, target: Any) -> None:
from diffusers.hooks import apply_layerwise_casting
from diffusers.hooks.layerwise_casting import DEFAULT_SKIP_MODULES_PATTERN
- # idempotent, keyed on the completion marker NOT hook presence
# Idempotent: a pre-cast encoder arrives with the layerwise hooks installed and re-registering a hook name raises,
# which would report an engaged cast as failed. Keyed on the completion marker, NOT hook presence, so a mid-pass
# failure still fails closed.
@@ -398,7 +397,6 @@ def _cast_fp8(encoder: Any, target: Any) -> None:
storage_dtype = torch.float8_e4m3fn,
compute_dtype = target.dtype,
skip_modules_pattern = skip,
- # fp8-ing nn.Embedding would put every prompt token on the coarse fp8 grid
# Keep token-embedding tables full precision: the diffusers default only skips vision pos/patch embeds, and
# fp8-ing nn.Embedding puts every prompt token on the coarse fp8 grid.
skip_modules_classes = (torch.nn.Embedding,),
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index bdb0846095f..2c242ba5b35 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -3,25 +3,23 @@
"""Load a *pre-quantized* transformer instead of quantising a dense one on the GPU.
-The runtime transformer_quant path loads the dense bf16 transformer and ``quantize_``s it
-in place, materialising the full bf16 weights on the GPU first (~2x the GGUF peak, plus the
-full bf16 download). When a transformer was already quantised and saved
-(``scripts/build_prequant_checkpoint.py``), this loads those weights directly: build the
-skeleton on ``meta`` (``init_empty_weights`` + ``from_config``), ``load_state_dict
-(assign=True)`` the quantized state dict (subclass tensors assigned, not copied, so dense
-bf16 never touches the GPU), then move to device.
-
-Measured (B200, Z-Image fp8): GPU load peak 12.9 -> 6.3 GB, download 12 -> 6.28 GB, output
-bit-identical (LPIPS 0.0). The checkpoint carries the same scheme + ``min_features`` as the
+The runtime transformer_quant path loads the dense bf16 transformer and ``quantize_``s it in place,
+materialising the full bf16 weights on the GPU first (~2x the GGUF peak, plus the full bf16
+download). When a transformer was already quantised and saved
+(``scripts/build_prequant_checkpoint.py``), this loads those weights directly: build the skeleton on
+``meta`` (``init_empty_weights`` + ``from_config``), ``load_state_dict(assign=True)`` the quantized
+state dict (subclass tensors assigned, not copied, so dense bf16 never touches the GPU), then move
+to device. Measured (B200, Z-Image fp8): GPU load peak 12.9 -> 6.3 GB, download 12 -> 6.28 GB,
+output bit-identical (LPIPS 0.0). The checkpoint carries the same scheme + ``min_features`` as the
runtime path, so the result matches quantising on the fly.
-torchao's weight subclasses are not safetensors-serializable, so the artifact is a torch.save
-pickle -- read under ``weights_only`` plus the constructor ALLOWLIST below, never as a free one.
-It is a mutable remote file reached by loads that never asked for a scheme (auto resolves an unset
-precision to a hosted checkpoint), so "first-party repo" cannot stand in for that restriction.
+torchao's weight subclasses are not safetensors-serializable, so the artifact is a torch.save pickle
+-- read under ``weights_only`` plus the constructor ALLOWLIST below, never as a free one. It is a
+mutable remote file reached by loads that never asked for a scheme (auto resolves an unset precision
+to a hosted checkpoint), so "first-party repo" cannot stand in for that restriction.
-Best-effort and lazily imported: a missing / mismatched / unreadable checkpoint returns None
-and the caller falls back to dense-quantise (then GGUF). Inert with nothing configured.
+Best-effort and lazily imported: a missing / mismatched / unreadable checkpoint returns None and the
+caller falls back to dense-quantise (then GGUF). Inert with nothing configured.
"""
from __future__ import annotations
@@ -54,17 +52,16 @@ def prequant_format_for(metadata: Any) -> str:
# path is an arbitrary MODEL. Not a code-execution gate -- the load is weights_only either way.
ALLOW_LOCAL_PREQUANT_PATH_ENV = "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH"
-# constructors a pre-quant checkpoint's pickle may name on top of what weights_only permits;
-# The constructors a pre-quant checkpoint's pickle may name, on top of what ``weights_only`` already permits (storages,
-# dtypes, ``_rebuild_*``, ``OrderedDict``, ``torch.device``, ``_get_layout``). Surveyed across every hosted checkpoint
-# Unsloth resolves (image + video, fp8 + int8, rotated and not) this is the complete set, so the load runs
+# The constructors a pre-quant checkpoint's pickle may name, on top of what ``weights_only`` already permits
+# (storages, dtypes, ``_rebuild_*``, ``OrderedDict``, ``torch.device``, ``_get_layout``). Surveyed across every hosted
+# checkpoint Unsloth resolves (image + video, fp8 + int8, rotated and not) this is the complete set, so the load runs
# ``weights_only = True`` and a checkpoint naming anything else is refused before one opcode of it executes, hosted or
-# local. Registered under the name the PICKLE records, which for a re-exported class is not the class's own
+# local. Registered under the name the PICKLE records, which for a re-exported class is not the class's own
# ``__module__`` (``torchao.quantization.Float8Tensor`` really lives in
# ``...quantize_.workflows.float8.float8_tensor``), so both spellings are listed. Names a given torchao lacks are
-# skipped rather than raised: the set spans every release ``install_python_stack`` pins (0.14, 0.16, 0.17) and an absent
-# class could not have produced a loadable checkpoint here anyway. Adding a scheme means adding its constructors here;
-# forgetting warns and falls back to dense-quantise, never a silent unpickle.
+# skipped rather than raised: the set spans every release ``install_python_stack`` pins (0.14, 0.16, 0.17) and an
+# absent class could not have produced a loadable checkpoint here anyway. Adding a scheme means adding its
+# constructors here; forgetting warns and falls back to dense-quantise, never a silent unpickle.
_PREQUANT_SAFE_GLOBALS: tuple[tuple[str, str], ...] = (
# int8: AffineQuantizedTensor + its plain layout, wrapped for dynamic activation quant
("torchao.dtypes.affine_quantized_tensor", "AffineQuantizedTensor"),
@@ -85,9 +82,9 @@ _PREQUANT_SAFE_GLOBALS: tuple[tuple[str, str], ...] = (
("torchao.quantization.granularity", "PerRow"),
("torchao.quantization.granularity", "PerTensor"),
("torchao.float8.inference", "Float8MMConfig"),
- # mxfp8 / nvfp4: no hosted checkpoint uses these, but they are TQ_SCHEMES that scripts/build_prequant_checkpoint.py
- # bakes, so a LOCAL override can be either. torchao only registers them on import of the prototype package, which
- # nothing on this path imports.
+ # mxfp8 / nvfp4: no hosted checkpoint uses these, but they are TQ_SCHEMES that
+ # scripts/build_prequant_checkpoint.py bakes, so a LOCAL override can be either. torchao only registers them on
+ # import of the prototype package, which nothing on this path imports.
("torchao.prototype.mx_formats.mx_tensor", "MXTensor"),
("torchao.prototype.mx_formats.mx_tensor", "QuantizeTensorToMXKwargs"),
("torchao.prototype.mx_formats.config", "ScaleCalculationMode"),
@@ -164,11 +161,10 @@ _SCHEME_REQUIRED_GLOBALS: dict = {
def _tuple_safe_globals_supported() -> bool:
- """Whether this torch's ``add_safe_globals`` understands ``(object, name)`` pairs (2.6+).
-
- Asked by VERSION rather than by trying it: 2.4/2.5 accept the pairs silently and only fail
- later, in ``_get_user_allowed_globals``, which reads ``f.__module__`` off every entry of a
- PROCESS-WIDE list -- so a tuple left there breaks every other weights_only load in Unsloth.
+ """Whether this torch's ``add_safe_globals`` understands ``(object, name)`` pairs (2.6+). Asked
+ by VERSION rather than by trying it: 2.4/2.5 accept the pairs silently and only fail later,
+ in ``_get_user_allowed_globals``, which reads ``f.__module__`` off every entry of a
+ PROCESS-WIDE list, so a tuple left there breaks every other weights_only load in Unsloth.
Nothing is registered unless the answer here is yes."""
try:
import torch
@@ -187,15 +183,16 @@ def _register_prequant_safe_globals() -> bool:
from under the other's ``torch.load``, failing a good checkpoint and dropping it to dense.
Adding once and never removing has no such window.
- The widening this costs is small and bounded: other ``weights_only`` loads in the process
- also accept these torch/torchao tensor constructors, which build tensors and nothing else. A
- pickle naming ANY global is still refused.
+ The widening this costs is small and bounded: other ``weights_only`` loads in the process also
+ accept these torch/torchao tensor constructors, which build tensors and nothing else. A pickle
+ naming ANY global is still refused.
- Registration takes ``(object, name)`` pairs so a re-exported class is registered under the
- name the pickle records, and that form is version-checked BEFORE anything is registered (see
+ Registration takes ``(object, name)`` pairs so a re-exported class is registered under the name
+ the pickle records, and that form is version-checked BEFORE anything is registered (see
``_tuple_safe_globals_supported``). Below 2.6 nothing is registered and
- ``restricted_prequant_load_supported`` tells planning to stop offering pre-quant sources at
- all. Answered once and memoised, including the failure."""
+ ``restricted_prequant_load_supported`` tells planning to stop offering pre-quant sources at all.
+ Answered once and memoised, including the failure.
+ """
global _SAFE_GLOBALS_REGISTERED
if _SAFE_GLOBALS_REGISTERED is not None:
@@ -223,8 +220,8 @@ def _register_prequant_safe_globals() -> bool:
):
add(pairs)
_RESOLVED_SAFE_GLOBALS.update(resolved)
- # The same derivation the unpickler runs, so a form this torch cannot express fails here rather than
- # under a load a plan was already sized on.
+ # The same derivation the unpickler runs, so a form this torch cannot express fails here rather
+ # than under a load a plan was already sized on.
try:
torch._weights_only_unpickler._get_user_allowed_globals()
except AttributeError: # noqa: BLE001 -- private; absence is not a failure
@@ -242,14 +239,15 @@ def restricted_prequant_load_supported(scheme: Optional[str] = None) -> bool:
Without the allowlist there is no safe way to open a pre-quant pickle and the loader refuses.
Planning has to ask the same question BEFORE it sizes the load: a plan that counts on a 6 GB
artifact, drops the dense shards and evicts the resident pipeline has nothing left when the
- refusal arrives. ``usable_prequant_source`` therefore answers None here, hosted and local
- alike, which is the same answer the loader will give.
+ refusal arrives. ``usable_prequant_source`` therefore answers None here, hosted and local alike,
+ which is the same answer the loader will give.
PER SCHEME, because the schemes do not share constructors and torchao does not retire them
- together: ``AffineQuantizedTensor`` and its layout carry every int8 checkpoint and are
- already deprecated upstream (pytorch/ao#2752), so a release that drops them while keeping
- ``Float8Tensor`` leaves fp8 loadable and int8 not. An unknown or unnamed scheme gets the
- floor answer the registration itself already checked."""
+ together: ``AffineQuantizedTensor`` and its layout carry every int8 checkpoint and are already
+ deprecated upstream (pytorch/ao#2752), so a release that drops them while keeping
+ ``Float8Tensor`` leaves fp8 loadable and int8 not. An unknown or unnamed scheme gets the floor
+ answer the registration itself already checked.
+ """
if not _register_prequant_safe_globals():
return False
required = _SCHEME_REQUIRED_GLOBALS.get((scheme or "").strip().lower())
@@ -257,13 +255,12 @@ def restricted_prequant_load_supported(scheme: Optional[str] = None) -> bool:
def _torch_load_prequant(path: str, **kwargs: Any) -> Any:
- """``torch.load`` a pre-quant checkpoint under the allowlist above.
-
- ``weights_only = True`` is the whole point: a pickle that may name any global is remote code
- execution the moment the artifact is not the one that was published. Everything the format
- legitimately needs is allowlisted, so the restriction costs nothing and a mutated artifact
- raises ``UnpicklingError`` into the caller's dense fallback instead of running. A torch that
- cannot express the allowlist is refused outright, never reopened unrestricted."""
+ """``torch.load`` a pre-quant checkpoint under the allowlist above. ``weights_only = True`` is
+ the whole point: a pickle that may name any global is remote code execution the moment the
+ artifact is not the one that was published. Everything the format legitimately needs is
+ allowlisted, so the restriction costs nothing and a mutated artifact raises
+ ``UnpicklingError`` into the caller's dense fallback instead of running. A torch that cannot
+ express the allowlist is refused outright, never reopened unrestricted."""
import torch
if not _register_prequant_safe_globals():
@@ -281,9 +278,8 @@ _PREQUANT_TOGGLE_TOKENS = {"1", "true", "yes", "on", "0", "false", "no", "off"}
def _allowed_prequant_roots() -> list:
"""Operator-allowlisted directories whose pre-quant checkpoints may be unpickled.
-
- ``UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH`` = one or more dirs (``os.pathsep``-separated). A
- bare truthy/falsey toggle is ignored: it must name a directory, so no "allow all" mode."""
+ ``UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH`` = one or more dirs (``os.pathsep``-separated). A bare
+ truthy/falsey toggle is ignored: it must name a directory, so no "allow all" mode."""
import os
raw = (os.environ.get(ALLOW_LOCAL_PREQUANT_PATH_ENV) or "").strip()
@@ -302,8 +298,8 @@ def _allowed_prequant_roots() -> list:
def _local_prequant_path_allowed(path: str) -> bool:
- """True only when ``path`` resolves inside an allowlisted directory. ``realpath`` first
- so a symlink cannot point an allowlisted name at a file outside the allowed roots."""
+ """True only when ``path`` resolves inside an allowlisted directory. ``realpath`` first so a
+ symlink cannot point an allowlisted name at a file outside the allowed roots."""
import os
roots = _allowed_prequant_roots()
@@ -317,11 +313,10 @@ def _local_prequant_path_allowed(path: str) -> bool:
def local_prequant_path_ready(path: str) -> bool:
- """True only when a local pre-quant path would actually load: inside an allowlisted root
- AND the file is present. The auto-policy planner checks this before budgeting the small
- prequant plan, so it never skips the dense shards for a path the loader will refuse
- (which would evict the resident pipeline then rebuild dense under an undersized plan ->
- OOM)."""
+ """True only when a local pre-quant path would actually load: inside an allowlisted root AND the
+ file is present. The auto-policy planner checks this before budgeting the small prequant
+ plan, so it never skips the dense shards for a path the loader will refuse (which would evict
+ the resident pipeline then rebuild dense under an undersized plan -> OOM)."""
import os
if not _local_prequant_path_allowed(path):
@@ -331,9 +326,9 @@ def local_prequant_path_ready(path: str) -> bool:
@dataclass(frozen = True)
class PrequantSource:
- """Where a pre-quantized checkpoint lives. ``kind`` is "path" (a local file) or "repo"
- (Hub repo id in ``location`` + ``filename``; ``fallback_filename`` is tried when the
- primary name is absent, covering repos still on the legacy transformer_<scheme>.pt)."""
+ """Where a pre-quantized checkpoint lives. ``kind`` is "path" (a local file) or "repo" (Hub repo
+ id in ``location`` + ``filename``; ``fallback_filename`` is tried when the primary name is
+ absent, covering repos still on the legacy transformer_<scheme>.pt)."""
kind: str
location: str
@@ -347,8 +342,8 @@ def prequant_filename(scheme: str) -> str:
def prequant_repo_filename(repo_id: str, scheme: str) -> str:
- """The model-name checkpoint filename for ``scheme`` in ``repo_id``: the hosted repos are
- named <Model>-FP8 (or -INT8 / -quantized) and carry <Model>-<SCHEME>.pt files, e.g.
+ """The model-name checkpoint filename for ``scheme`` in ``repo_id``: the hosted repos are named
+ <Model>-FP8 (or -INT8 / -quantized) and carry <Model>-<SCHEME>.pt files, e.g.
unsloth/Z-Image-Turbo-FP8 -> Z-Image-Turbo-INT8.pt / Z-Image-Turbo-FP8.pt."""
model = repo_id.rsplit("/", 1)[-1]
for suffix in ("-fp8", "-int8", "-quantized"):
@@ -368,18 +363,18 @@ def resolve_prequant_source(
) -> Optional[PrequantSource]:
"""Resolve where the checkpoint for ``(fam, scheme)`` comes from.
- Priority: (1) explicit local ``path_override``; (2) the family's hosted repo for
- ``scheme`` (variant-specific when ``base_repo`` names a base with its own baked
- checkpoint); (3) None -> no pre-quant, caller quantises dense. Pure: no IO, no torch.
+ Priority: an explicit local ``path_override``; then the family's hosted repo for ``scheme``
+ (variant-specific when ``base_repo`` names a base with its own baked checkpoint); then None,
+ meaning no pre-quant and the caller quantises dense. Pure: no IO, no torch.
- ``task`` names the workflow / denoiser PARTITION the load is bringing up, for the families
- that host more than one under a single repo and scheme (MiniMax-H3's keyframe and reference
+ ``task`` names the workflow / denoiser PARTITION the load is bringing up, for the families that
+ host more than one under a single repo and scheme (MiniMax-H3's keyframe and reference
denoisers). It only ever selects a more specific filename: unset, or set to a task the family
declares nothing for, resolves exactly what it resolved before.
Both names are repo-ROOT names. Every hosted prequant repo, image and video alike, keeps its
- checkpoints at the root, so there is no directory to prepend; a repo that nested them would
- 404 on the primary AND on the fallback and the load would silently fall back to dense.
+ checkpoints at the root, so there is no directory to prepend; a repo that nested them would 404
+ on the primary AND on the fallback and the load would silently fall back to dense.
"""
override = (path_override or "").strip()
if override:
@@ -391,21 +386,22 @@ def resolve_prequant_source(
repo_id = family_prequant_repo(fam, scheme, base_repo = base_repo)
preferred = family_prequant_filename(fam, scheme, task = task)
- # What the same call would have resolved WITHOUT a task, which is what decides whether a fallback is safe below.
- # Skipped when no task was asked for, since then the two are the same lookup.
+ # What the same call would have resolved WITHOUT a task, which is what decides whether a fallback is safe
+ # below. Skipped when no task was asked for, since then the two are the same lookup.
agnostic = family_prequant_filename(fam, scheme) if task else preferred
except Exception: # noqa: BLE001 - a bad family object must not break the load
repo_id = None
if repo_id:
derived = prequant_repo_filename(repo_id, scheme)
- # A family may name a SECOND artifact for the same repo and scheme (today: MiniMax-H3's rotated INT8 denoiser).
- # It becomes the primary and the derived name becomes the fallback, so a build that knows the new name gets it
- # and every older build keeps resolving the artifact it already understands. Without an override nothing
- # changes: the derived name is primary and the legacy transformer_<scheme>.pt is the fallback. A TASK-SPECIFIC
- # name gets NO fallback. The other artifacts in the repo are the same family, the same scheme and the same base,
- # so every check the loader makes would pass on them -- the fallback would quietly install another partition's
- # denoiser and generate from the wrong weights, which is precisely what naming the artifact per task prevents.
- # Absent is better than wrong here: no artifact means the released bfloat16 denoiser.
+ # A family may name a SECOND artifact for the same repo and scheme (today: MiniMax-H3's rotated INT8
+ # denoiser). It becomes the primary and the derived name becomes the fallback, so a build that knows the new
+ # name gets it and every older build keeps resolving the artifact it already understands. Without an override
+ # nothing changes: the derived name is primary and the legacy transformer_<scheme>.pt is the fallback.
+ # A TASK-SPECIFIC name gets NO fallback. The other artifacts in the repo are the same family, the same scheme
+ # and the same base, so every check the loader makes would pass on them -- the fallback would quietly install
+ # another partition's denoiser and generate from the wrong weights, which is precisely what naming the
+ # artifact per task prevents. Absent is better than wrong here: no artifact means the released bfloat16
+ # denoiser.
task_specific = preferred is not None and preferred != agnostic
return PrequantSource(
kind = "repo",
@@ -425,25 +421,26 @@ def local_prequant_scheme(path: str) -> Optional[str]:
"""The scheme a local pre-quant checkpoint records, or None when it cannot be read.
``resolve_prequant_source`` hands back a ``path`` source for ANY override, whatever scheme was
- asked for: the file is never inspected. That is fine when the caller named the scheme, but
- under ``auto`` the ladder picks one and an override baked for a different scheme then reads as
- an available pre-quant. Planning skips staging the dense transformer, the loader reaches the
- same ``metadata.scheme`` check that runs at load time, refuses the file, and with no dense
- fallback the pick silently drops to GGUF.
+ asked for: the file is never inspected. That is fine when the caller named the scheme, but under
+ ``auto`` the ladder picks one and an override baked for a different scheme then reads as an
+ available pre-quant. Planning skips staging the dense transformer, the loader reaches the same
+ ``metadata.scheme`` check that runs at load time, refuses the file, and with no dense fallback
+ the pick silently drops to GGUF.
Cheap despite the file size: ``mmap`` plus ``map_location = "meta"`` maps the storages instead
of reading them, so only the pickle structure is parsed (~1s on a 34 GB checkpoint). Cached on
- (path, mtime, size) because the auto ladder asks once per candidate scheme. Read under the
- same allowlisted ``weights_only`` load the loader uses, so probing a file that turns out not
- to be a checkpoint cannot execute anything either."""
+ (path, mtime, size) because the auto ladder asks once per candidate scheme. Read under the same
+ allowlisted ``weights_only`` load the loader uses, so probing a file that turns out not to be a
+ checkpoint cannot execute anything either.
+ """
import os
try:
real = os.path.expanduser(path)
st = os.stat(real)
# Nanoseconds, not int(st_mtime): an atomic swap for a same-sized artifact inside the same second would
- # otherwise reuse the previous scheme for the life of the process, and int8 and fp8 checkpoints of one model are
- # exactly that shape.
+ # otherwise reuse the previous scheme for the life of the process, and int8 and fp8 checkpoints of one model
+ # are exactly that shape.
key = (real, st.st_mtime_ns, int(st.st_size))
except Exception: # noqa: BLE001 -- unreadable is "unknown", handled by the caller
return None
@@ -468,21 +465,21 @@ def usable_prequant_source(
path_override: Optional[str] = None,
base_repo: Optional[str] = None,
) -> Optional[PrequantSource]:
- """``resolve_prequant_source``, but a local path counts only when the loader would
- accept it: inside the allowlist AND present on disk AND baked for THIS scheme. Otherwise
- resolves to None so memory planning falls back to dense-fit checks up front, instead of the
- loader refusing the path only after the resident pipeline was evicted and dense bf16
- materialises under a plan that never budgeted for it (evict-then-OOM). Hosted-repo sources are
- unaffected.
-
- The scheme check matters most under ``auto``, which picks a scheme the user never named: an
- int8 override must not read as an available fp8 pre-quant just because the file exists. A
- checkpoint whose scheme cannot be read is treated as not usable, matching every other unknown
- here, since the loader would reject it too.
+ """``resolve_prequant_source``, but a local path counts only when the loader would accept it:
+ inside the allowlist AND present on disk AND baked for THIS scheme. Otherwise resolves to None
+ so memory planning falls back to dense-fit checks up front, instead of the loader refusing the
+ path only after the resident pipeline was evicted and dense bf16 materialises under a plan that
+ never budgeted for it (evict-then-OOM). Hosted-repo sources are unaffected.
+
+ The scheme check matters most under ``auto``, which picks a scheme the user never named: an int8
+ override must not read as an available fp8 pre-quant just because the file exists. A checkpoint
+ whose scheme cannot be read is treated as not usable, matching every other unknown here, since
+ the loader would reject it too.
An install that cannot restrict the load has no usable source AT ALL, hosted included: the
- loader refuses every checkpoint there, and a plan that had already dropped the dense shards
- for one would find that out after the eviction."""
+ loader refuses every checkpoint there, and a plan that had already dropped the dense shards for
+ one would find that out after the eviction.
+ """
if not restricted_prequant_load_supported(scheme):
return None
src = resolve_prequant_source(fam, scheme, path_override = path_override, base_repo = base_repo)
@@ -495,14 +492,12 @@ def usable_prequant_source(
def cached_checkpoint_path(source: Any, *, cache_dir: Optional[str] = None) -> Optional[str]:
- """The path of a hosted (``kind == "repo"``) checkpoint ALREADY in the local Hub cache.
-
- A pure lookup (a refs read plus a stat, no network), so memory planning can ask on every pick.
- Only the PRIMARY ``filename`` counts: a cached ``fallback_filename`` (the legacy artifact) must
+ """The path of a hosted (``kind == "repo"``) checkpoint ALREADY in the local Hub cache. A pure
+ lookup (a refs read plus a stat, no network), so memory planning can ask on every pick. Only
+ the PRIMARY ``filename`` counts: a cached ``fallback_filename`` (the legacy artifact) must
not short-circuit it, or a stale name stays pinned once the repo ships the real one, so a
- fallback-only cache reads as "this would have to download" and the GGUF simply runs.
-
- Both cache roots are searched: Unsloth pins the LIVE cache setting while an unpinned
+ fallback-only cache reads as "this would have to download" and the GGUF simply runs. Both
+ cache roots are searched: Unsloth pins the LIVE cache setting while an unpinned
``hf_hub_download`` falls back to huggingface_hub's import-time constant. Never raises."""
for root in (cache_dir, None) if cache_dir else (None,):
hit = _cached_in_root(source, root)
@@ -545,18 +540,18 @@ def prequant_checkpoint_cached(source: Any, *, cache_dir: Optional[str] = None)
def _pin_kernel_preference(state_dict: Any, logger: Any = None) -> int:
"""Force every loaded fp8 weight onto the plain-torch kernel, matching the local path.
- `_fp8_config` pins `KernelPreference.TORCH` when it BUILDS a config, because AUTO silently
- switches to the MSLK kernel wherever an mslk package is importable (sm90+). A hosted
- checkpoint escapes that pin entirely: the preference is serialized on each Float8Tensor, and
- every published one carries AUTO. Restoring it re-arms the exact kernel the pin exists to
- avoid, and `mslk.f8f8bf16_rowwise` has no fake impl, so the first COMPILED generate dies with
- "Operator does not support running with fake tensors" -- an HTTP 500 on the default speed
- mode, reachable the moment the pre-quant repos are readable.
-
- Safe to rewrite in place: the preference selects a matmul kernel, it is not weight data, so
- the tensors stay bit-identical and the checkpoint's own sha256 still describes them. The
- plain-torch path is also the faster one compiled (an opaque extern call blocks inductor
- quantize fusion), so this costs nothing.
+ ``_fp8_config`` pins ``KernelPreference.TORCH`` when it BUILDS a config, because AUTO silently
+ switches to the MSLK kernel wherever an mslk package is importable (sm90+). A hosted checkpoint
+ escapes that pin entirely: the preference is serialized on each Float8Tensor, and every
+ published one carries AUTO. Restoring it re-arms the exact kernel the pin exists to avoid, and
+ ``mslk.f8f8bf16_rowwise`` has no fake impl, so the first COMPILED generate dies with "Operator
+ does not support running with fake tensors" -- an HTTP 500 on the default speed mode, reachable
+ the moment the pre-quant repos are readable.
+
+ Safe to rewrite in place: the preference selects a matmul kernel, it is not weight data, so the
+ tensors stay bit-identical and the checkpoint's own sha256 still describes them. The plain-torch
+ path is also the faster one compiled (an opaque extern call blocks inductor quantize fusion), so
+ this costs nothing.
"""
try:
from torchao.quantization.quantize_.common.kernel_preference import KernelPreference
@@ -599,29 +594,27 @@ def load_prequantized_transformer(
into a root Unsloth no longer reads.
``config_subfolder`` is where the DENOISER CONFIG lives inside ``base``, defaulting to the
- universal ``transformer``. A family hosting several denoiser partitions in one repo overrides
- it with the one this checkpoint belongs to (MiniMax-H3's ``transformer_ref``): the scoped
- download stages only that partition, so reading the config from the other one would send an
- otherwise fully staged load back to the Hub.
+ universal ``transformer``. A family hosting several denoiser partitions in one repo overrides it
+ with the one this checkpoint belongs to (MiniMax-H3's ``transformer_ref``): the scoped download
+ stages only that partition, so reading the config from the other one would send an otherwise
+ fully staged load back to the Hub.
``prepare_model`` (optional) is called as ``prepare_model(transformer, metadata)`` on the
- freshly built skeleton, AFTER ``from_config`` and BEFORE ``load_state_dict``. That window is
- the only one where a family can reshape the module to match how the checkpoint was baked (a
- swapped submodule, a patched attention class): earlier there is no module, and later
- ``strict=True`` has already rejected the mismatch. It gets the checkpoint's own metadata so it
- can key on what was baked rather than on today's defaults. A raising callback falls out to the
- outer handler below, i.e. a warning and a dense fallback, never a failed load.
+ freshly built skeleton, AFTER ``from_config`` and BEFORE ``load_state_dict``. That window is the
+ only one where a family can reshape the module to match how the checkpoint was baked (a swapped
+ submodule, a patched attention class): earlier there is no module, and later ``strict=True`` has
+ already rejected the mismatch. It gets the checkpoint's own metadata so it can key on what was
+ baked rather than on today's defaults. A raising callback falls out to the outer handler below,
+ i.e. a warning and a dense fallback, never a failed load.
A checkpoint that declares an ACTIVATION ROTATION (``diffusion_convrot``) has the matching
online half installed here, on exactly the fqns it records. That is unconditional and central
- rather than a family opt-in, because the one failure mode worth designing against is the
- silent one: rotated weights met by unrotated activations render wrong pixels and raise
- nothing.
-
- Returns the placed transformer, or None on any problem (missing / mismatched /
- unreadable checkpoint, unsupported meta-init, or a rotation this build cannot apply exactly)
- so the caller falls back to dense-quantise. Best-effort: never raises for an unavailable
- artifact.
+ rather than a family opt-in, because the one failure mode worth designing against is the silent
+ one: rotated weights met by unrotated activations render wrong pixels and raise nothing.
+
+ Returns the placed transformer, or None on any problem (missing / mismatched / unreadable
+ checkpoint, unsupported meta-init, or a rotation this build cannot apply exactly) so the caller
+ falls back to dense-quantise. Best-effort: never raises for an unavailable artifact.
"""
try:
# A request-supplied local path names arbitrary WEIGHTS, a different question from the deserialization one
@@ -656,8 +649,8 @@ def load_prequantized_transformer(
state_dict = ckpt["state_dict"]
_pin_kernel_preference(state_dict, logger)
- # Read from the root that actually supplied the checkpoint: after a mid-session cache change the pinned root may
- # be gone or read-only, and load_config's raise is swallowed below into a None return, silently dropping a
+ # Read from the root that actually supplied the checkpoint: after a mid-session cache change the pinned root
+ # may be gone or read-only, and load_config's raise is swallowed below into a None return, silently dropping a
# prequant whose checkpoint is cached and already loaded.
config = _load_transformer_config(
transformer_cls,
@@ -682,8 +675,8 @@ def load_prequantized_transformer(
transformer = transformer_cls.from_config(config)
# The retry REPLACES the module, so the hook has to run again: skipping it here would load the same state
# dict into a differently shaped model, and this branch is the one families with non-persistent buffers
- # always take -- the mismatch would be the norm, not the corner case, and strict=True would surface it as a
- # bare key error.
+ # always take -- the mismatch would be the norm, not the corner case, and strict=True would surface it as
+ # a bare key error.
if prepare_model is not None:
prepare_model(transformer, metadata)
transformer.load_state_dict(state_dict, strict = True, assign = True)
@@ -693,17 +686,17 @@ def load_prequantized_transformer(
# that were just assigned, and a rotated weight met by an unrotated activation renders plausible garbage with
# nothing to catch. A no-op for every artifact that declares no rotation, and a RAISE (caught below into the
# dense fallback) for one this build cannot honour exactly. After load_state_dict because the meta retry above
- # rebuilds the module; before apply_small_m_padding because padding reparents the Linears and the recorded fqns
- # name the unwrapped tree.
+ # rebuilds the module; before apply_small_m_padding because padding reparents the Linears and the recorded
+ # fqns name the unwrapped tree.
from .diffusion_convrot import apply_activation_rotation
apply_activation_rotation(transformer, metadata, logger = logger)
transformer = transformer.to(device)
- # Same small-M row padding the runtime quantise path applies, and for the same reason: a checkpoint built under
- # the current exclusion set QUANTISES the family's small-M linears, so without the wrappers they would raise
- # inside _int_mm the moment the compiled scope reaches them. After load_state_dict, since wrapping reparents the
- # Linears; after.to() so the granularity probe reads the device tensors the GEMM will see.
+ # Same small-M row padding the runtime quantise path applies, and for the same reason: a checkpoint built
+ # under the current exclusion set QUANTISES the family's small-M linears, so without the wrappers they would
+ # raise inside _int_mm the moment the compiled scope reaches them. After load_state_dict, since wrapping
+ # reparents the Linears; after .to() so the granularity probe reads the device tensors the GEMM will see.
from .diffusion_transformer_quant import apply_small_m_padding
apply_small_m_padding(transformer, scheme, metadata.get("family"), logger = logger)
@@ -731,10 +724,9 @@ def load_prequantized_transformer(
def _entry_not_found_errors() -> tuple:
- """``(EntryNotFoundError, LocalEntryNotFoundError)`` for both huggingface_hub majors.
-
- On 1.x the base splits into a remote 404 and ``LocalEntryNotFoundError`` (no copy in this root,
- no network); on BOTH majors local subclasses the base, so catch it first where they differ.
+ """``(EntryNotFoundError, LocalEntryNotFoundError)`` for both huggingface_hub majors. On 1.x the
+ base splits into a remote 404 and ``LocalEntryNotFoundError`` (no copy in this root, no
+ network); on BOTH majors local subclasses the base, so catch it first where they differ.
Private markers on an unexpected layout are raised by nothing, keeping today's behaviour."""
try:
from huggingface_hub.errors import EntryNotFoundError
@@ -762,15 +754,15 @@ def _download_checkpoint_name(
propagate_missing: bool,
local_files_only: bool = False,
) -> str:
- """Download ONE checkpoint filename, reusing a copy that sits under the other cache root.
-
- Pinned to ``cache_dir``, hf_hub_download would not look there and would re-fetch multiple GB, so
- re-run it THROUGH that root rather than return the raw path: the blob is reused after one HEAD,
- a republished checkpoint is picked up rather than pinned stale, and offline still resolves off
- the cached pointer. ``propagate_missing`` says another filename is still to be tried, so a
- remote 404 for THIS one must reach the caller's fallback branch; swallowing it would return the
- stale other-root copy of a name the repo no longer publishes. A local cache miss is not that
- verdict, and with no name left to try neither is a 404: both keep the copy already found."""
+ """Download ONE checkpoint filename, reusing a copy that sits under the other cache root. Pinned
+ to ``cache_dir``, hf_hub_download would not look there and would re-fetch multiple GB, so
+ re-run it THROUGH that root rather than return the raw path: the blob is reused after one
+ HEAD, a republished checkpoint is picked up rather than pinned stale, and offline still
+ resolves off the cached pointer. ``propagate_missing`` says another filename is still to be
+ tried, so a remote 404 for THIS one must reach the caller's fallback branch; swallowing it
+ would return the stale other-root copy of a name the repo no longer publishes. A local cache
+ miss is not that verdict, and with no name left to try neither is a 404: both keep the copy
+ already found."""
from huggingface_hub import hf_hub_download
EntryNotFoundError, LocalEntryNotFoundError = _entry_not_found_errors()
@@ -811,9 +803,9 @@ def _resolve_checkpoint_path(
local_files_only: bool = False,
) -> Optional[str]:
"""The local file path for ``source``, downloading from the Hub if needed; None if absent.
-
- ``local_files_only`` is the caller's promise that this load may not fetch anything, so a cache
- miss answers None and the build falls back rather than pulling several GB nobody asked for."""
+ ``local_files_only`` is the caller's promise that this load may not fetch anything, so a
+ cache miss answers None and the build falls back rather than pulling several GB nobody asked
+ for."""
if source.kind == "path":
import os
@@ -850,9 +842,8 @@ def _resolve_checkpoint_path(
def _config_cache_roots(checkpoint_path: str, cache_dir: Optional[str]) -> tuple:
"""Cache roots to read the transformer config from, the checkpoint's OWN root first.
-
- ``_resolve_checkpoint_path`` may answer from huggingface_hub's import-time root even when Unsloth
- pins its live one, so pinning the config to the live root alone misses in exactly the
+ ``_resolve_checkpoint_path`` may answer from huggingface_hub's import-time root even when
+ Unsloth pins its live one, so pinning the config to the live root alone misses in exactly the
cache-moved/offline case the checkpoint lookup just accepted, and load_config's raise is
swallowed into a None return. The other root is still tried second."""
if cache_dir is None:
@@ -880,9 +871,8 @@ def _load_transformer_config(
*,
local_files_only: bool = False,
) -> Any:
- """``transformer_cls.load_config`` against the checkpoint's cache root, then the other one.
-
- The config is a few KB, but it is still a Hub fetch, and a load that promised to reach nothing
+ """``transformer_cls.load_config`` against the checkpoint's cache root, then the other one. The
+ config is a few KB, but it is still a Hub fetch, and a load that promised to reach nothing
has to keep that promise for the small files too."""
last: Optional[BaseException] = None
for root in _config_cache_roots(checkpoint_path, cache_dir):
@@ -900,11 +890,10 @@ def _load_transformer_config(
def _fp8_activation_floor_present(state_dict: Any, logger: Any) -> bool:
- """True unless some fp8 tensor was quantised with no activation lower bound.
-
- Only the first quantised tensor is inspected: the builder applies one config to the whole
- module, so the floor is uniform. A state dict with no fp8 tensor at all is left to the other
- checks (an empty or wrong-scheme artifact is their business, not this one)."""
+ """True unless some fp8 tensor was quantised with no activation lower bound. Only the first
+ quantised tensor is inspected: the builder applies one config to the whole module, so the
+ floor is uniform. A state dict with no fp8 tensor at all is left to the other checks (an
+ empty or wrong-scheme artifact is their business, not this one)."""
from .diffusion_transformer_quant import TQ_FP8
try:
@@ -936,17 +925,15 @@ def _validate_activation_rotation(ckpt_format: Any, meta: Any, scheme: str, logg
Three ways an artifact and a loader can disagree about the rotation, and all three end in the
same place -- weights in a rotated basis multiplied by unrotated activations, which is finite,
raises nothing, and renders quietly wrong -- so all three are refused here rather than
- discovered later:
-
- * the artifact declares a rotation and is tagged v1. Only v2 makes an Unsloth too old for this
- code refuse it, so a v1 tag on rotated weights is a hazard to every OTHER build, and the
- builder that produced it is not one to trust about anything else in the file;
- * the artifact is tagged v2 and declares none. Nothing here would rotate, and the tag says
- something was meant to;
- * the rotation is declared but its contract does not parse (an unknown kind, a group that is
- not a power of 4, an absent or malformed fqn list).
-
- Refusing costs a dense fallback: slower and bigger, never wrong."""
+ discovered later. First, the artifact declares a rotation and is tagged v1: only v2 makes an
+ Unsloth too old for this code refuse it, so a v1 tag on rotated weights is a hazard to every
+ OTHER build, and the builder that produced it is not one to trust about anything else in the
+ file. Second, the artifact is tagged v2 and declares none: nothing here would rotate, and the
+ tag says something was meant to. Third, the rotation is declared but its contract does not parse
+ (an unknown kind, a group that is not a power of 4, an absent or malformed fqn list).
+
+ Refusing costs a dense fallback: slower and bigger, never wrong.
+ """
from .diffusion_convrot import declares_rotation, rotation_metadata_error
rotated = declares_rotation(meta)
@@ -978,15 +965,13 @@ def _validate_checkpoint(
min_features: Optional[int] = None,
fast_accum: Optional[bool] = None,
) -> bool:
- """Reject a checkpoint that is the wrong format / scheme / base model / filter.
-
- ``min_features`` (when given) is the runtime Linear-feature threshold: a different
- ``--min-features`` quantises a different set of Linears, so assign=True would silently
- install a mismatched model while status still reports the scheme. Reject it.
-
- ``fast_accum`` (fp8 only): when the caller forces it and the checkpoint baked a different
- value, the loaded kernels would ignore the request, so reject and let the dense path
- honor it. A checkpoint predating a metadata field (absent) is accepted for back-compat."""
+ """Reject a checkpoint that is the wrong format / scheme / base model / filter. ``min_features``
+ (when given) is the runtime Linear-feature threshold: a different ``--min-features``
+ quantises a different set of Linears, so assign=True would silently install a mismatched
+ model while status still reports the scheme. Reject it. ``fast_accum`` (fp8 only): when the
+ caller forces it and the checkpoint baked a different value, the loaded kernels would ignore
+ the request, so reject and let the dense path honor it. A checkpoint predating a metadata
+ field (absent) is accepted for back-compat."""
if not isinstance(ckpt, dict) or ckpt.get("format") not in PREQUANT_FORMATS:
_warn(logger, scheme, ValueError("unrecognised pre-quant checkpoint format"))
return False
@@ -1017,8 +1002,8 @@ def _validate_checkpoint(
# torchao's per-row activation quantiser divides by each row's amax, so a zero row (qwen's text stream emits them)
# gives scale 0 and NaN qdata unless activation_value_lb floors it. That floor is serialised per tensor as
# act_quant_kwargs.hp_value_lb, so an artifact built before the fix stays broken however it is loaded, and it
- # predates any metadata field we could stamp -- and "absent is accepted for back-compat", the convention every check
- # above follows, is exactly wrong here. Reading the tensors is fail-closed and needs no format bump.
+ # predates any metadata field we could stamp -- and "absent is accepted for back-compat", the convention every
+ # check above follows, is exactly wrong here. Reading the tensors is fail-closed and needs no format bump.
if scheme == TQ_FP8 and not _fp8_activation_floor_present(ckpt.get("state_dict"), logger):
return False
ckpt_base = meta.get("base_model_id")
@@ -1095,13 +1080,10 @@ def _validate_checkpoint(
def _same_base_model(a: str, b: str) -> bool:
"""Tolerant base-model id compare: exact, or same final path/repo segment (e.g.
- ``/models/Z-Image-Turbo`` vs ``Tongyi-MAI/Z-Image-Turbo``).
-
- Both sides normalise through ``canonical_base`` first, so a mirror id in a baked
- ``base_model_id`` check cannot refuse the checkpoint and send the load down the multi-GB dense
- download. Today's mirrors keep the repo name, so the tail compare would cover them, but this
- must not depend on that.
- """
+ ``/models/Z-Image-Turbo`` vs ``Tongyi-MAI/Z-Image-Turbo``). Both sides normalise through
+ ``canonical_base`` first, so a mirror id in a baked ``base_model_id`` check cannot refuse the
+ checkpoint and send the load down the multi-GB dense download. Today's mirrors keep the repo
+ name, so the tail compare would cover them, but this must not depend on that."""
from .diffusion_families import canonical_base
a, b = canonical_base(a), canonical_base(b)
@@ -1126,15 +1108,15 @@ def pin_prequantized_module(
one onto the accelerator inside its own ``pre_forward``, i.e. from within the block that is
already executing. A torchao-quantized module does not survive that move: the device change
reaches ``return_and_correct_aliasing``, which tries to alias a CPU storage to an accelerator
- tensor and raises ``Attempted to set the storage of a tensor on device "cuda:0" to a storage
- on different device "cpu"``, and MiniMax-H3's denoise loop dies on its first step. Moving the
- same module at load time, outside any executing block, works -- so the fix is to place it once
- here and take it out of the rotation rather than to move it per forward.
+ tensor and raises ``Attempted to set the storage of a tensor on device "cuda:0" to a storage on
+ different device "cpu"``, and MiniMax-H3's denoise loop dies on its first step. Moving the same
+ module at load time, outside any executing block, works -- so the fix is to place it once here
+ and take it out of the rotation rather than to move it per forward.
That is also what a pre-quantized denoiser is for: the hosted H3 checkpoint is ~20 GB against
- 66.3 GB dense, so keeping it resident is the saving being spent. The other components keep
- their hooks, and the strategy sizes its decisions from live free memory, so the encoder and
- the VAEs still offload around it.
+ 66.3 GB dense, so keeping it resident is the saving being spent. The other components keep their
+ hooks, and the strategy sizes its decisions from live free memory, so the encoder and the VAEs
+ still offload around it.
For a torchao module that placement is REQUIRED, for the reason above. A caller may also pin a
plain dense module, where it is an optimisation instead: a module that moves per forward cannot
diff --git a/studio/backend/core/inference/diffusion_quant_pad.py b/studio/backend/core/inference/diffusion_quant_pad.py
index b969a735652..206f28cddbe 100644
--- a/studio/backend/core/inference/diffusion_quant_pad.py
+++ b/studio/backend/core/inference/diffusion_quant_pad.py
@@ -52,10 +52,9 @@ from torch import nn
# ``_int_mm`` wants strictly more than 16 rows.
INT_MM_MIN_M = 17
-# pad to a warp-friendly 32 rather than exactly INT_MM_MIN_M
-# Pad to a warp-friendly constant rather than to exactly INT_MM_MIN_M. Two reasons: 32 tiles better than 17, and it pins
-# ONE compiled shape for every activation below it, so prompts of differing token counts (H3's seven eval prompts run at
-# M = 10..19) do not each trigger their own inductor recompile.
+# Pad to a warp-friendly constant rather than to exactly INT_MM_MIN_M. Two reasons: 32 tiles better than 17, and it
+# pins ONE compiled shape for every activation below it, so prompts of differing token counts (H3's seven eval prompts
+# run at M = 10..19) do not each trigger their own inductor recompile.
DEFAULT_PAD_TO = 32
@@ -137,7 +136,6 @@ class PadToMinM(nn.Module):
self.pad_to = max(int(pad_to or min_m), self.min_m)
def forward(self, x: torch.Tensor) -> torch.Tensor:
- # deliberately free of call counters: dynamo guards on an nn.Module's integer attributes
# Deliberately free of call counters or any other mutable int attribute: dynamo treats an nn.Module's integer
# attributes as static and guards on their value, so a `+= 1` here would force a recompile on EVERY call until
# the recompile limit is hit, at which point the module silently drops back to eager. Instrumentation belongs
@@ -146,10 +144,9 @@ class PadToMinM(nn.Module):
flat = x.reshape(-1, x.shape[-1])
m = flat.shape[0]
if m == 0:
- # torchao returns a zero-row input UNPROJECTED (a 1472 -> 2048 Linear maps [0, 1472] to [0, 1472])
# No rows to project, and no row 0 to replicate from. torchao returns a zero-row input UNPROJECTED (a
- # quantized 1472 -> 2048 Linear maps [0, 1472] to [0, 1472]), which then breaks a downstream width-sensitive
- # add, so synthesise the empty result at the right width instead of calling through.
+ # quantized 1472 -> 2048 Linear maps [0, 1472] to [0, 1472]), which then breaks a downstream
+ # width-sensitive add, so synthesise the empty result at the right width instead of calling through.
return x.new_empty((*lead, self.inner.out_features))
if m < self.pad_to:
# Everything below pad_to normalises to pad_to, not just what is below min_m. Clearing the floor takes only
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 1543ed3d125..2658925399e 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -209,7 +209,7 @@ def compile_eligible(target: Any, *, is_gguf: bool, family: Any) -> bool:
Only on CUDA (incl. ROCm), for a bf16 transformer, on a compile-friendly family, in a process
that can run inductor. ``is_gguf`` no longer disqualifies (GGUF compiles fine and ~2.3x
faster); the param is kept for compat."""
- del is_gguf # GGUF is compile-eligible now; param kept for call-site compat
+ del is_gguf
if not torch_compile_runtime_available():
return False
if not bool(getattr(target, "supports_default_torch_compile", False)):
@@ -263,7 +263,6 @@ def apply_speed_optims(
"cuda_graph": False,
}
mode = normalize_speed_mode(speed_mode)
- # TF32 (max) and cudnn.benchmark are process-global
# TF32 (max) and cudnn.benchmark (any non-off CUDA load) are process-global; the caller restores them so a later
# `off` load never inherits them.
if mode == SPEED_OFF:
@@ -283,8 +282,7 @@ def apply_speed_optims(
family, logger, dtype = getattr(target, "dtype", None), speed_mode = mode
)
- # default = LIGHT: GGUF compiles ONLY the dequant op chain (cheap, VRAM-free, resolution-invariant)
- # --- the compile lever, per tier --- default = LIGHT: GGUF compiles ONLY the dequant op chain (cheap, VRAM-free,
+ # The compile lever, per tier. default = LIGHT: GGUF compiles ONLY the dequant op chain (cheap, VRAM-free,
# resolution-invariant); dense falls back to the regional block compile. max = FULL: regional max-autotune compile
# of the repeated block. eager = no compile.
if mode == SPEED_DEFAULT:
@@ -452,7 +450,6 @@ def _compile_repeated_blocks(
_warn(logger, "compile_repeated_blocks", exc)
return False
if unet is not None:
- # dynamic is ALWAYS False here, so each new (height, width, batch) pays its own compile
# Whole-module static compile for the U-Net classes above. fullgraph mirrors the regional decision; dynamic is
# ALWAYS False, so each new (height, width, batch) pays its own compile. ``Module.compile`` keeps the module
# identity.
diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.py
index 21b62c06178..2d86e9ab487 100644
--- a/studio/backend/core/inference/diffusion_te_prequant.py
+++ b/studio/backend/core/inference/diffusion_te_prequant.py
@@ -45,21 +45,15 @@ TE_PREQUANT_SCHEMES = ("fp8",)
# diffusion_hidream.py).
TE_PREQUANT_COMPONENTS = ("text_encoder", "text_encoder_2", "text_encoder_3")
-# Fraction of a bf16 text encoder a PRE-CAST fp8 checkpoint occupies, for memory budgeting. fp8 storage is one byte per
-# parameter against bf16's two, so the floor is 0.5, but the cast deliberately keeps modules dense: nn.Embedding tables,
-# the norms in DEFAULT_SKIP_MODULES_PATTERN, the encoder's own _keep_in_fp32_modules (T5's ``wo``) and an lm_head tied
-# to the input embedding. Measured from Hub file metadata over every published artifact (2026-08-07), as hosted
-# checkpoint bytes over the bf16-EQUIVALENT dense bytes of the same component (an fp32-stored encoder is halved first,
-# since the pipeline loads it bf16): FLUX.2-dev text_encoder Mistral-24B 24,683,130,873 / 48,022,800,560 =
-# 0.514 HiDream-I1-Full text_encoder_4 Llama-3.1-8B 8,555,963,320 / 16,060,556,376 = 0.533 Qwen-Image
-# text_encoder Qwen2.5-VL-7B 8,839,210,073 / 16,584,414,544 = 0.533 LTX-2 text_encoder Gemma3-12B
-# 13,205,302,695 / 24,374,720,836 = 0.542 Krea-2-Turbo text_encoder Qwen3-4B 4,831,262,424 /
-# 8,875,715,136 = 0.544 Z-Image-Turbo text_encoder Qwen3-4B 4,411,751,967 / 8,044,982,000 = 0.548
-# Lumina-Image-2.0 text_encoder Gemma2-2B 3,204,501,909 / 5,228,699,608 = 0.613 FLUX.1-schnell
-# text_encoder_2 T5-XXL 5,900,818,800 / 9,524,648,584 = 0.620 The small encoders sit highest: their
-# embedding tables are a large share of the parameters and stay dense. 0.65 is the observed maximum rounded up, so this
-# OVER-states every measured encoder rather than under-stating any. It is a memory budget, and an under-estimate is the
-# expensive direction: it lets an oversized load through to the OS killer.
+# Fraction of a bf16 text encoder a PRE-CAST fp8 checkpoint occupies, for memory budgeting. fp8 storage is one byte
+# per parameter against bf16's two, so the floor is 0.5, but the cast deliberately keeps modules dense: nn.Embedding
+# tables, the norms in DEFAULT_SKIP_MODULES_PATTERN, the encoder's own _keep_in_fp32_modules (T5's ``wo``) and an
+# lm_head tied to the input embedding. Measured from Hub file metadata over every published artifact (2026-08-07) as
+# hosted checkpoint bytes over the bf16-EQUIVALENT dense bytes of the same component, the ratios run 0.514 (FLUX.2-dev
+# Mistral-24B) to 0.620 (FLUX.1-schnell T5-XXL); the small encoders sit highest, because their embedding tables are a
+# large share of the parameters and stay dense. 0.65 is the observed maximum rounded up, so this OVER-states every
+# measured encoder rather than under-stating any: an under-estimate is the expensive direction, since it lets an
+# oversized load through to the OS killer.
TE_PREQUANT_BUDGET_SCALE = 0.65
@@ -91,15 +85,13 @@ def te_prequant_budget_scale(
return TE_PREQUANT_BUDGET_SCALE if sources else 1.0
-# text-encoder weights VERIFIED byte-identical (every shard LFS sha256 compared 2026-07-18)
# Bases whose text-encoder weights are VERIFIED byte-identical (every shard LFS sha256 compared on 2026-07-18), so one
# hosted artifact serves them all. The validator accepts a base_model_id from the same group; anything else keeps the
# strict refusal.
_TE_EQUIVALENT_BASES: tuple[frozenset[str], ...] = (
- # Qwen2.5-VL-7B: 4 shards, identical sha256 set
- # Qwen2.5-VL-7B text encoder: 4 shards, 16,584,414,544 bytes, identical sha256 set. Qwen-Image-2512 republishes the
- # same four shards (re-verified 2026-08-25); refusing it here would pull 16.6 GB of dense encoder the load never
- # opens.
+ # Qwen2.5-VL-7B text encoder: 4 shards, 16,584,414,544 bytes, identical sha256 set. Qwen-Image-2512 republishes
+ # the same four shards (re-verified 2026-08-25); refusing it here would pull 16.6 GB of dense encoder the load
+ # never opens.
frozenset(
{
"qwen/qwen-image",
@@ -122,7 +114,6 @@ _TE_EQUIVALENT_BASES: tuple[frozenset[str], ...] = (
"hidream-ai/hidream-i1-full",
}
),
- # Qwen3-4B: identical sha256 across the distilled Z-Image-Turbo and the undistilled base
# T5-XXL (text_encoder_2): 2 shards, 9,524,648,584 bytes, identical sha256 across every FLUX.1 release; HiDream-I1
# ships the same bytes as text_encoder_3 (cross-component mapping is not wired yet).
frozenset(
@@ -293,10 +284,8 @@ def te_prequant_sources_for_base(
return compatible
-# everything else (config.json, the shard index, tokenizer JSON) is kept when the pre-cast checkpoint replaces the
-# weights
-# Weight files a dense encoder folder holds. Everything else (config.json, the shard index, tokenizer JSON) is kept when
-# the pre-cast checkpoint replaces the weights: the pre-cast loader still meta-inits from the base repo component
+# Weight files a dense encoder folder holds. Everything else (config.json, the shard index, tokenizer JSON) is kept
+# when the pre-cast checkpoint replaces the weights: the pre-cast loader still meta-inits from the base repo component
# config.
_TE_WEIGHT_SUFFIXES = (".safetensors", ".bin", ".pth", ".pt", ".msgpack", ".h5")
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 267fd623d2a..611c0c64031 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -3,22 +3,21 @@
"""Opt-in low-precision quantisation of the diffusion DiT transformer.
-The default GGUF path stores weights 4-bit but DEQUANTISES to bf16 on every matmul, so it
-runs at bf16 tensor-core rate: a memory win that costs speed. This module is the opt-in
-alternative: load the DENSE bf16 transformer and torchao-quantise it with a
-DYNAMIC-ACTIVATION scheme so the matmul runs on low-precision tensor cores. Measured on B200
-(Z-Image-Turbo, 1024px/8 steps) vs GGUF+compile (0.802s, LPIPS 0.083): fp8 0.585s (1.37x),
-int8 0.603s (1.33x), both at LOWER LPIPS than GGUF -- faster and slightly more accurate, at
-a higher-memory dense load. Strictly opt-in; GGUF stays the low-memory default and fallback.
-
-Scheme by architecture (``auto`` picks the best supported, best first):
- nvfp4 / mxfp8 - Blackwell sm_100+ FP4 / MX tensor cores (biggest win; prototype).
- fp8 - Ada / Hopper / Blackwell (sm_89+) fp8 tensor cores.
- int8 - Ampere+ (sm_80+) int8 tensor cores -- the broadest-hardware lever.
-
-Every scheme needs ``torch.compile`` for the speedup (dynamic quant is ~30x slower eager);
-the loader compiles the repeated block after this. torch / torchao imported lazily; every
-probe is best-effort: an unsupported scheme yields None and the caller loads GGUF.
+The default GGUF path stores weights 4-bit but DEQUANTISES to bf16 on every matmul, so it runs at
+bf16 tensor-core rate: a memory win that costs speed. This module is the opt-in alternative: load
+the DENSE bf16 transformer and torchao-quantise it with a DYNAMIC-ACTIVATION scheme so the matmul
+runs on low-precision tensor cores. Measured on B200 (Z-Image-Turbo, 1024px/8 steps) vs GGUF+compile
+(0.802s, LPIPS 0.083): fp8 0.585s (1.37x), int8 0.603s (1.33x), both at LOWER LPIPS than GGUF --
+faster and slightly more accurate, at a higher-memory dense load. Strictly opt-in; GGUF stays the
+low-memory default and fallback.
+
+Scheme by architecture (``auto`` picks the best supported, best first): nvfp4 / mxfp8 for Blackwell
+sm_100+ FP4 / MX tensor cores (biggest win; prototype), fp8 for Ada / Hopper / Blackwell (sm_89+),
+int8 for Ampere+ (sm_80+), the broadest-hardware lever.
+
+Every scheme needs ``torch.compile`` for the speedup (dynamic quant is ~30x slower eager); the
+loader compiles the repeated block after this. torch / torchao imported lazily; every probe is
+best-effort: an unsupported scheme yields None and the caller loads GGUF.
"""
from __future__ import annotations
@@ -49,7 +48,6 @@ TQ_MODES = (TQ_AUTO,) + TQ_SCHEMES
# pass. On torchao 0.17 / B200: fp8 per-row and mxfp8 assert bf16; nvfp4 and int8 handle fp32/fp16.
_REQUIRE_BF16_SCHEMES = (TQ_FP8, TQ_MXFP8)
-# per-ROW is REQUIRED for correctness on outlier-heavy DiTs
# fp8 granularity the runtime uses: per-ROW is REQUIRED for correctness on outlier-heavy DiTs. Stamped into prequant
# metadata, so a stale per-TENSOR checkpoint is rejected and rebuilt.
FP8_GRANULARITY = "per_row"
@@ -57,8 +55,8 @@ FP8_GRANULARITY = "per_row"
# Skip linears below this feature size: a small FLOP share, so leaving them bf16 costs ~nothing.
DEFAULT_MIN_LINEAR_FEATURES = 512
-# int8-ONLY name exclusions: torch._int_mm needs activation rows M above 16, and a DiT's AdaLN modulation and timestep /
-# guidance / pooled-text embedders run once from a [batch, dim] vector (M = 1), so they crash despite large feature
+# int8-ONLY name exclusions: torch._int_mm needs activation rows M above 16, and a DiT's AdaLN modulation and timestep
+# / guidance / pooled-text embedders run once from a [batch, dim] vector (M = 1), so they crash despite large feature
# dims. Negligible FLOPs; scaled_mm has no M limit.
_INT8_EXCLUDE_NAME_TOKENS = (
"norm", # AdaLN modulation .linear
@@ -73,10 +71,9 @@ _INT8_EXCLUDE_NAME_TOKENS = (
)
-# Qwen-Image MMDiT runs every TEXT-stream Linear at M = actual prompt tokens (unpadded, unlike FLUX's 512-token T5)
-# int8 PER-FAMILY exclusions, on top of _INT8_EXCLUDE_NAME_TOKENS. Qwen-Image MMDiT runs every TEXT-stream Linear at M =
-# actual prompt tokens (unpadded, unlike FLUX's 512-token T5), so a short prompt falls under _int_mm's M floor of 16 and
-# the denoise crashes. bf16 there costs ~nothing.
+# int8 PER-FAMILY exclusions, on top of _INT8_EXCLUDE_NAME_TOKENS. Qwen-Image MMDiT runs every TEXT-stream Linear at M
+# = actual prompt tokens (unpadded, unlike FLUX's 512-token T5), so a short prompt falls under _int_mm's M floor of 16
+# and the denoise crashes. bf16 there costs ~nothing.
_QWENIMAGE_INT8_EXCLUDES = (
"txt_in",
"add_q_proj",
@@ -85,15 +82,14 @@ _QWENIMAGE_INT8_EXCLUDES = (
"to_add_out",
"txt_mlp",
)
-# HunyuanVideo-1.5's attention trim shrinks the text / image streams to their VALID token counts
-# HunyuanVideo-1.5's attention trim (this PR) shrinks the text / image streams from their padded lengths to the VALID
-# token counts, so every text-stream Linear runs at a tiny M the int8 dynamic path cannot handle. Both failures measured
-# on B200: - M = 0 (t2v byt5 / image streams trim to zero tokens): torchao returns the input UNPROJECTED (a quantized
-# 1472 -> 2048 Linear maps [1, 0, 1472] to [1, 0, 1472]), so the 2048-wide cond-type add crashes -> context_embedder_2 /
-# image_embedder; - M <= 16 (a short prompt, or the empty negative prompt's ~6 tokens): torch._int_mm requires M > 16
-# and raises -> the TokenRefiner and every block's context-stream projections. These run at M = text tokens (tens)
-# against the video stream's M ~ 32k+, so bf16 here costs nothing measurable and the video-stream linears keep full int8
-# coverage. "context_embedder" also matches "context_embedder_2" (substring check).
+# HunyuanVideo-1.5's attention trim shrinks the text / image streams from their padded lengths to the VALID token
+# counts, so every text-stream Linear runs at a tiny M the int8 dynamic path cannot handle. Both failures measured on
+# B200. M = 0 (t2v byt5 / image streams trim to zero tokens): torchao returns the input UNPROJECTED (a quantized 1472
+# -> 2048 Linear maps [1, 0, 1472] to [1, 0, 1472]), so the 2048-wide cond-type add crashes -- context_embedder_2 /
+# image_embedder. M <= 16 (a short prompt, or the empty negative prompt's ~6 tokens): torch._int_mm requires M > 16
+# and raises -- the TokenRefiner and every block's context-stream projections. These run at M = text tokens (tens)
+# against the video stream's M ~ 32k+, so bf16 here costs nothing measurable and the video-stream linears keep full
+# int8 coverage. "context_embedder" also matches "context_embedder_2" (substring check).
_HUNYUAN15_INT8_EXCLUDES = (
"context_embedder",
"image_embedder",
@@ -103,28 +99,28 @@ _HUNYUAN15_INT8_EXCLUDES = (
"to_add_out",
"ff_context",
)
-# MiniMax-H3 is the same small-M story with one extra trap. Its adaLN projection is named ``adaln_proj``, which no token
-# in _INT8_EXCLUDE_NAME_TOKENS matches: "norm" is the closest and it does not appear in the name. On the DENSE
-# checkpoint that projection is Linear(2688 -> 96768), so it clears min_features = 512 and gets quantized, then runs at
-# M = 1 and raises ``self.size(0) needs to be greater than 16, but got 1`` at the first denoise. Measured: the offline
-# builder happily bakes it, and torch.compile then dies on that module. The pruned-modulation form hides the bug rather
-# than fixing it: there adaln_proj is Linear(8 -> 96768), which falls under min_features and is skipped for free
-# (verified on the fl2va_pruned build: the filter rejects all 51 of them for min_features, in_features = 8). So the
-# exclusion is what makes the DENSE path correct, and is a no-op on the pruned one. H3's OTHER small-M linears --
-# context_embedder and the two token_refiner blocks, 13 in total -- used to be excluded here for the same reason. They
-# are not any more: they are padded instead, see _INT8_FAMILY_PAD_NAME_TOKENS below.
+# MiniMax-H3 is the same small-M story with one extra trap. Its adaLN projection is named ``adaln_proj``, which no
+# token in _INT8_EXCLUDE_NAME_TOKENS matches: "norm" is the closest and it does not appear in the name. On the DENSE
+# checkpoint that projection is Linear(2688 -> 96768), so it clears min_features = 512 and gets quantized, then runs
+# at M = 1 and raises ``self.size(0) needs to be greater than 16, but got 1`` at the first denoise. Measured: the
+# offline builder happily bakes it, and torch.compile then dies on that module. The pruned-modulation form hides the
+# bug rather than fixing it: there adaln_proj is Linear(8 -> 96768), which falls under min_features and is skipped for
+# free (verified on the fl2va_pruned build: the filter rejects all 51 of them for min_features, in_features = 8). So
+# the exclusion is what makes the DENSE path correct, and is a no-op on the pruned one. H3's OTHER small-M linears --
+# context_embedder and the two token_refiner blocks, 13 in total -- used to be excluded here for the same reason; they
+# are padded instead now, see _INT8_FAMILY_PAD_NAME_TOKENS below.
_MINIMAX_H3_INT8_EXCLUDES = ("adaln_proj",)
-# LTX-2 is audiovisual: a video-only run feeds a MINIMAL audio stream (one token for a still) LTX-2 is audiovisual:
-# every block carries an audio-side stream (audio_attn1 / audio_attn2 / audio_ff, fed by audio_proj_in) plus the a2v /
-# v2a cross attentions. A video-only run feeds a MINIMAL audio stream -- one token for a still -- so those linears run
-# at M = 1, under the same _int_mm floor of 16 as the cases above. The audio stream is inert on a video-only run
-# (isolated modalities, out of the loss, out of the LoRA targets), so leaving it in bf16 costs nothing while the
-# video-stream linears keep full int8 coverage. One token covers every audio-side name, including video_to_audio_attn,
-# whose keys/values are that same one-token stream. The audio token alone is not enough. LTX-2 also carries
-# LTX2AdaLayerNormSingle projections whose names say nothing about audio -- av_cross_attn_video_scale_shift /
-# av_cross_attn_video_a2v_gate (the cross-modality modulation, computed unconditionally in forward, isolate_modalities
-# or not) and prompt_adaln / audio_prompt_adaln. Each is a Linear over a BATCH-sized input, so M = batch = 1 for a
-# default training run: the same _int_mm floor, reached whatever the audio stream does.
+# LTX-2 is audiovisual: every block carries an audio-side stream (audio_attn1 / audio_attn2 / audio_ff, fed by
+# audio_proj_in) plus the a2v / v2a cross attentions. A video-only run feeds a MINIMAL audio stream -- one token for a
+# still -- so those linears run at M = 1, under the same _int_mm floor of 16 as the cases above. The audio stream is
+# inert on a video-only run (isolated modalities, out of the loss, out of the LoRA targets), so leaving it in bf16
+# costs nothing while the video-stream linears keep full int8 coverage. One token covers every audio-side name,
+# including video_to_audio_attn, whose keys/values are that same one-token stream.
+# The audio token alone is not enough. LTX-2 also carries LTX2AdaLayerNormSingle projections whose names say nothing
+# about audio -- av_cross_attn_video_scale_shift / av_cross_attn_video_a2v_gate (the cross-modality modulation,
+# computed unconditionally in forward, isolate_modalities or not) and prompt_adaln / audio_prompt_adaln. Each is a
+# Linear over a BATCH-sized input, so M = batch = 1 for a default training run: the same _int_mm floor, reached
+# whatever the audio stream does.
_LTX2_INT8_EXCLUDES = ("audio", "av_cross_attn", "adaln")
_INT8_FAMILY_EXCLUDE_NAME_TOKENS: dict[str, tuple[str, ...]] = {
"qwen-image": _QWENIMAGE_INT8_EXCLUDES,
@@ -138,16 +134,16 @@ _INT8_FAMILY_EXCLUDE_NAME_TOKENS: dict[str, tuple[str, ...]] = {
# Int8 PER-FAMILY row PADDING, the alternative to excluding a small-M Linear. ``_int_mm``'s floor is a GEMM shape
-# constraint, not a numerical one: padding the activation up to 32 rows, running the matmul and slicing the result back
-# returns the caller's rows BITWISE unchanged (torchao's int8 dynamic path scales activations per row, so the pad rows
-# cannot reach them -- see diffusion_quant_pad for why that is asserted rather than assumed). So a Linear that would
-# have been left dense can be quantized after all, and its weights halve. On MiniMax-H3 that is context_embedder plus
-# the two token_refiner blocks: 13 Linears, 798 M parameters, 0.80 GB of bf16 weights, 3.9% of the whole int8
+# constraint, not a numerical one: padding the activation up to 32 rows, running the matmul and slicing the result
+# back returns the caller's rows BITWISE unchanged (torchao's int8 dynamic path scales activations per row, so the pad
+# rows cannot reach them -- see diffusion_quant_pad for why that is asserted rather than assumed). So a Linear that
+# would have been left dense can be quantized after all, and its weights halve. On MiniMax-H3 that is context_embedder
+# plus the two token_refiner blocks: 13 Linears, 798 M parameters, 0.80 GB of bf16 weights, 3.9% of the whole int8
# checkpoint. Measured on B200, 640x384 x 124 frames (see h3_quant/README_int8.md for the paired numbers). Scoped to
-# minimax-h3. qwen-image, qwen-image-edit and hunyuanvideo-1.5 have the same small-M shape and could adopt this, but
-# each has a PUBLISHED int8 prequant checkpoint whose metadata bakes the current exclusion set, and _validate_checkpoint
-# compares that set against exclude_tokens_for_scheme: changing it invalidates those artifacts, so they move only
-# together with a rebuild and republish of each.
+# minimax-h3: qwen-image, qwen-image-edit and hunyuanvideo-1.5 have the same small-M shape and could adopt this, but
+# each has a PUBLISHED int8 prequant checkpoint whose metadata bakes the current exclusion set, and
+# _validate_checkpoint compares that set against exclude_tokens_for_scheme, so changing it invalidates those artifacts
+# and they move only together with a rebuild and republish of each.
_MINIMAX_H3_INT8_PAD_TOKENS = ("context_embedder", "token_refiner")
_INT8_FAMILY_PAD_NAME_TOKENS: dict[str, tuple[str, ...]] = {
"minimax-h3": _MINIMAX_H3_INT8_PAD_TOKENS,
@@ -155,10 +151,10 @@ _INT8_FAMILY_PAD_NAME_TOKENS: dict[str, tuple[str, ...]] = {
def pad_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tuple[str, ...]:
- """Name tokens whose quantized Linears get their activation rows padded to ``_int_mm``'s
- floor rather than being left dense. int8 only (no other scheme has a row floor), and
- per-family. Disjoint from ``exclude_tokens_for_scheme`` by construction: an excluded Linear
- is never quantized, so there is nothing to pad."""
+ """Name tokens whose quantized Linears get their activation rows padded to ``_int_mm``'s floor
+ rather than being left dense. int8 only (no other scheme has a row floor), and per-family.
+ Disjoint from ``exclude_tokens_for_scheme`` by construction: an excluded Linear is never
+ quantized, so there is nothing to pad."""
if scheme != TQ_INT8:
return ()
return _INT8_FAMILY_PAD_NAME_TOKENS.get(str(family or "").strip().lower(), ())
@@ -172,14 +168,12 @@ def apply_small_m_padding(
logger: Any = None,
) -> tuple[str, ...]:
"""Wrap this family's small-M quantized Linears so their GEMM clears ``_int_mm``'s row floor.
-
Call AFTER the weights are quantized and in place -- ``quantize_`` on the runtime path, the
prequant ``load_state_dict`` on the hosted one -- because it reparents the Linears. Returns
- the fqns wrapped, empty for a family with no pad list.
-
- RAISES if a Linear that should be padded cannot be proven safe to pad. A half-padded
- transformer compiles on the modules that were wrapped and crashes on the ones that were not,
- which is worse than either end state, so the caller must treat this as a failed quantise."""
+ the fqns wrapped, empty for a family with no pad list. RAISES if a Linear that should be
+ padded cannot be proven safe to pad: a half-padded transformer compiles on the modules that
+ were wrapped and crashes on the ones that were not, which is worse than either end state, so
+ the caller must treat this as a failed quantise."""
tokens = pad_tokens_for_scheme(scheme, family)
if not tokens:
return ()
@@ -197,8 +191,8 @@ def apply_small_m_padding(
def exclude_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tuple[str, ...]:
- """Name tokens to exclude from quantisation for ``scheme`` (optionally family-specific).
- int8 (M>16) skips the M=1 modulation / conditioning-embedder projections
+ """Name tokens to exclude from quantisation for ``scheme`` (optionally family-specific). int8
+ (M>16) skips the M=1 modulation / conditioning-embedder projections
(_INT8_EXCLUDE_NAME_TOKENS) plus per-family small-M text streams
(_INT8_FAMILY_EXCLUDE_NAME_TOKENS); other schemes (scaled_mm) exclude nothing.
``family=None`` preserves the historical behaviour. Shared by the runtime path and the
@@ -214,10 +208,10 @@ def exclude_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tupl
# Per-arch preference for ``auto``, best first. On Blackwell fp8 leads: on B200 plain fp8 dynamic is faster AND more
# accurate at DiT shapes, while mxfp8 block scaling only adds overhead. nvfp4's FP4 GEMM is real with torch>=2.11 but
# wins only on very large GEMMs (0.81x on Z-Image 1024px, LPIPS 0.166 vs fp8 0.044), so it is kept OUT of the ladder
-# below and stays an explicit opt-in (transformer_quant="nvfp4"): auto must never silently drop to a scheme that is both
-# slower and less accurate. Restore the commented Blackwell tier to re-enable it once the FP4 tensor-core GEMM wins at
-# the DiT's real shapes (hidden ~3072, MLP ~12288, M ~4096) and its accuracy is validated by the prequant gate. Consumer
-# / workstation GPUs move int8 first: they halve fp8/fp16 FP32-accumulate.
+# below and stays an explicit opt-in (transformer_quant="nvfp4"): auto must never silently drop to a scheme that is
+# both slower and less accurate. Restore the commented Blackwell tier to re-enable it once the FP4 tensor-core GEMM
+# wins at the DiT's real shapes (hidden ~3072, MLP ~12288, M ~4096) and its accuracy is validated by the prequant
+# gate. Consumer / workstation GPUs move int8 first: they halve fp8/fp16 FP32-accumulate.
_AUTO_LADDER: tuple[tuple[tuple[int, int], tuple[str, ...]], ...] = (
((10, 0), (TQ_FP8, TQ_MXFP8, TQ_INT8)), # Blackwell sm_100+ (nvfp4 is explicit opt-in only)
# ((10, 0), (TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8)), # restore to re-enable nvfp4 under auto
@@ -226,32 +220,32 @@ _AUTO_LADDER: tuple[tuple[tuple[int, int], tuple[str, ...]], ...] = (
)
# Families whose activation ranges break specific schemes at the MODEL level (the smoke probe only proves the GEMM
-# runs). Measured with the 28-pair prequant accuracy gate on B200: qwen-image + mxfp8 does semantic damage at 1024px, +
-# nvfp4 is unusable (LPIPS 0.51). Neither has a known fix, so both stay denied and auto falls through to int8 (excellent
-# on Qwen). The deny also applies to an EXPLICIT request. fp8 was denied here too, for black frames. That cause is gone:
-# it was torchao's fp8 scale chooser having no eps clamp, so qwen's all-zero text rows gave scale 0 and NaN, and
-# ``_make_quant_config`` now floors it with ``activation_value_lb``. Re-measured on B200 with the floor, and BOTH paths
-# the deny governs clear the 0.10 LPIPS bar, so it is safe to drop rather than just the checkpoint half: prequant
-# checkpoint, full 28-pair gate -> 28/28 PASS (SSIM 0.87-0.99, LPIPS 0.027-0.228, CLIP delta <= 0.019) on-the-fly
-# quantize_, gate's simple_object prompt at its own seeds -> LPIPS 0.048 / 0.033 / 0.027 / 0.063 against pre-floor plain
-# fp8 at LPIPS 0.712 with SSIM 0.016 and mean luma 0. Keeping the deny cost real speed: it pinned qwen to int8 at 1.10x
-# bf16 when compiled fp8 measures 1.21x.
+# runs). Measured with the 28-pair prequant accuracy gate on B200: qwen-image + mxfp8 does semantic damage at 1024px,
+# + nvfp4 is unusable (LPIPS 0.51). Neither has a known fix, so both stay denied and auto falls through to int8
+# (excellent on Qwen). The deny also applies to an EXPLICIT request.
+# fp8 was denied here too, for black frames. That cause is gone: it was torchao's fp8 scale chooser having no eps
+# clamp, so qwen's all-zero text rows gave scale 0 and NaN, and ``_make_quant_config`` now floors it with
+# ``activation_value_lb``. Re-measured on B200 with the floor, and BOTH paths the deny governs clear the 0.10 LPIPS
+# bar: prequant checkpoint, full 28-pair gate -> 28/28 PASS (SSIM 0.87-0.99, LPIPS 0.027-0.228, CLIP delta <= 0.019);
+# on-the-fly quantize_, gate's simple_object prompt at its own seeds -> LPIPS 0.048 / 0.033 / 0.027 / 0.063, against
+# pre-floor plain fp8 at LPIPS 0.712 with SSIM 0.016 and mean luma 0. Keeping the deny cost real speed: it pinned qwen
+# to int8 at 1.10x bf16 when compiled fp8 measures 1.21x.
_FAMILY_SCHEME_DENY: dict[str, frozenset[str]] = {
"qwen-image": frozenset({TQ_MXFP8, TQ_NVFP4}),
"qwen-image-edit": frozenset({TQ_MXFP8, TQ_NVFP4}), # same DiT
}
-# Schemes denied for TRAINING on top of the inference table. Training holds a stricter bar because the evidence above is
-# rendering evidence: it says a frozen fp8 forward reconstructs the bf16 image, not that a LoRA converges when its
+# Schemes denied for TRAINING on top of the inference table. Training holds a stricter bar because the evidence above
+# is rendering evidence: it says a frozen fp8 forward reconstructs the bf16 image, not that a LoRA converges when its
# frozen linears are fp8. Nobody has run that, so qwen fp8 stays out of the Train UI until someone does. Delete the
# entry once a training run is measured.
_FAMILY_TRAIN_SCHEME_DENY: dict[str, frozenset[str]] = {
"qwen-image": frozenset({TQ_FP8}),
"qwen-image-edit": frozenset({TQ_FP8}),
- # MiniMax-H3's packed sequence runs three modalities through one set of linears, so its activation range is not the
- # per-family range the fp8 filter was measured against. The trainer refuses both outright; declaring it here is what
- # keeps /diffusion/info from advertising a start that is guaranteed to 400.
+ # MiniMax-H3's packed sequence runs three modalities through one set of linears, so its activation range is not
+ # the per-family range the fp8 filter was measured against. The trainer refuses both outright; declaring it here
+ # is what keeps /diffusion/info from advertising a start that is guaranteed to 400.
"minimax-h3": frozenset({TQ_FP8, TQ_MXFP8}),
}
@@ -269,20 +263,19 @@ def _family_train_denied(family, scheme: str) -> bool:
def family_denies_scheme(family: Optional[str], scheme: str) -> bool:
"""Whether the measured deny list rules ``scheme`` out for ``family``, regardless of hardware.
-
- Public so the refusal message can tell the two "no" answers apart. ``select_transformer_quant_scheme``
- folds a family deny and a missing kernel into the same ``None``, and an EXPLICIT scheme now fails
- closed, so that single answer is the whole explanation the user gets."""
+ Public so the refusal message can tell the two "no" answers apart:
+ ``select_transformer_quant_scheme`` folds a family deny and a missing kernel into the same
+ ``None``, and an EXPLICIT scheme now fails closed, so that single answer is the whole
+ explanation the user gets."""
return _family_denied(family, scheme)
def explain_unusable_scheme(family: Optional[str], scheme: str) -> str:
- """Why ``select_transformer_quant_scheme`` answered None for an EXPLICIT ``scheme``.
-
- One ``None`` covers three different faults, and the caller turns it into a 409, so the message
+ """Why ``select_transformer_quant_scheme`` answered None for an EXPLICIT ``scheme``. One
+ ``None`` covers three different faults, and the caller turns it into a 409, so the message
has to separate them: a family the scheme is measured to break, a torchao that cannot run at
- all in this install, and a GPU without the kernels. Only the last is a hardware limit, and only
- the last is what the message used to say."""
+ all in this install, and a GPU without the kernels. Only the last is a hardware limit, and
+ only the last is what the message used to say."""
if family_denies_scheme(family, scheme):
return (
f"'{scheme}' is ruled out for family '{family}' by the measured accuracy gate (it "
@@ -303,13 +296,12 @@ _TORCHAO_UNAVAILABLE: Optional[tuple[Optional[str]]] = None
def torchao_unavailable_reason() -> Optional[str]:
"""Why no dense quant scheme can run in this install, or ``None`` when torchao is usable.
-
- ``_smoke_probe`` swallows every failure, so a torchao that does not IMPORT is indistinguishable
- from a GPU that lacks the kernels. That did not matter while a declined explicit scheme fell
- back silently; now it is refused, and the message is all the user has. A torch/torchao version
- skew is the common cause and it is not a hardware fault: telling a Blackwell owner "'fp8' is not
- usable on this GPU" when the real error is ``cannot import name 'ScalingType' from
- torch.nn.functional`` points them at the wrong fix entirely."""
+ ``_smoke_probe`` swallows every failure, so a torchao that does not IMPORT is
+ indistinguishable from a GPU that lacks the kernels. That did not matter while a declined
+ explicit scheme fell back silently; now it is refused, and the message is all the user has. A
+ torch/torchao version skew is the common cause and it is not a hardware fault: telling a
+ Blackwell owner "'fp8' is not usable on this GPU" when the real error is ``cannot import name
+ 'ScalingType' from torch.nn.functional`` points them at the wrong fix entirely."""
global _TORCHAO_UNAVAILABLE
if _TORCHAO_UNAVAILABLE is not None:
return _TORCHAO_UNAVAILABLE[0]
@@ -335,15 +327,15 @@ def torchao_unavailable_reason() -> Optional[str]:
# An absolute POSIX or Windows path, up to the first whitespace / quote / bracket. Deliberately requires a directory
-# separator so dotted module names ("torch.nn.functional") survive intact: those are the actionable half of the message.
+# separator so dotted module names ("torch.nn.functional") survive intact: those are the actionable half of the
+# message.
_ABS_PATH_RE = _re.compile(r"(?:[A-Za-z]:)?[\\/](?:[^\s'\"()<>|]*[\\/])+[^\s'\"()<>|]*")
def _strip_paths(text: str) -> str:
- """``text`` with server filesystem paths replaced by ``<path>``.
-
- Refusal reasons reach an authenticated caller as a 409 body. The reason a load was refused is
- the caller's business; where this machine keeps its site-packages is not."""
+ """``text`` with server filesystem paths replaced by ``<path>``. Refusal reasons reach an
+ authenticated caller as a 409 body: the reason a load was refused is the caller's business,
+ where this machine keeps its site-packages is not."""
return _ABS_PATH_RE.sub("<path>", text)
@@ -402,11 +394,11 @@ _PROFESSIONAL_GPU_MARKERS = ("RTX PRO 6000", "RTX 6000 ADA")
def _is_consumer_gpu(device: Any = None) -> bool:
- """Whether the active GPU is consumer-class (GDDR), where fp8 FP32 accumulate is halved so
- fast (FP16) accumulate is a ~2x win. Data-center HBM and professional parts are not nerfed
- (return False -> precise accumulate, fp8 first). Heuristic on the device name: GeForce /
- TITAN -> consumer; a data-center token or professional marker -> not; anything else defaults
- to consumer (fast accumulate is free on data-center, a win on consumer). True on any failure."""
+ """Whether the active GPU is consumer-class (GDDR), where fp8 FP32 accumulate is halved so fast
+ (FP16) accumulate is a ~2x win. Data-center HBM and professional parts are not nerfed (return
+ False -> precise accumulate, fp8 first). Heuristic on the device name: GeForce / TITAN ->
+ consumer; a data-center token or professional marker -> not; anything else defaults to
+ consumer (fast accumulate is free on data-center, a win on consumer). True on any failure."""
try:
import re
@@ -423,9 +415,8 @@ def _is_consumer_gpu(device: Any = None) -> bool:
def normalize_transformer_quant(value: Optional[str]) -> Optional[str]:
- """Lower/strip a requested transformer quant; None / "" / "none" / "off" -> None.
-
- Raises ValueError for an unsupported value so a bad request is rejected cheaply."""
+ """Lower/strip a requested transformer quant; None / "" / "none" / "off" -> None. Raises
+ ValueError for an unsupported value so a bad request is rejected cheaply."""
if value is None:
return None
normalized = str(value).strip().lower().replace("-", "_")
@@ -439,8 +430,8 @@ def normalize_transformer_quant(value: Optional[str]) -> Optional[str]:
def dense_transformer_supported(target: Any) -> bool:
- """Whether the dense-source quant path is usable for ``target``: a CUDA device with bf16
- dtype (the only config any torchao dynamic scheme accelerates). Cheap loader pre-check."""
+ """Whether the dense-source quant path is usable for ``target``: a CUDA device with bf16 dtype
+ (the only config any torchao dynamic scheme accelerates). Cheap loader pre-check."""
if getattr(target, "device", None) != "cuda":
return False
# The Windows-ROCm torchao stub's quantize_ is a no-op, so the smoke probe passes on a still-dense Linear and the
@@ -480,17 +471,18 @@ def select_transformer_quant_scheme(
) -> Optional[str]:
"""The concrete scheme to apply, or None to fall back to GGUF.
- ``auto`` walks the per-arch ladder and returns the first scheme passing a real
- quantise+matmul smoke test, so an unavailable Blackwell fp4/mx kernel lands on fp8/int8
- with no error. An explicit scheme is honored only if supported (else None), never swapped.
- ``family`` applies the measured deny list (``_FAMILY_SCHEME_DENY``): schemes that produce
- black frames / out-of-bar drift are skipped by ``auto`` and refused when explicit.
+ ``auto`` walks the per-arch ladder and returns the first scheme passing a real quantise+matmul
+ smoke test, so an unavailable Blackwell fp4/mx kernel lands on fp8/int8 with no error. An
+ explicit scheme is honored only if supported (else None), never swapped. ``family`` applies the
+ measured deny list (``_FAMILY_SCHEME_DENY``): schemes that produce black frames / out-of-bar
+ drift are skipped by ``auto`` and refused when explicit.
``unproven_ok`` is for the PRE-EVICTION route gate. The smoke test allocates, so a resident
chat/image/video model can make it fail for want of VRAM rather than for want of a kernel; the
gate runs before the arbiter has evicted that model, so treating "could not tell" as "not
supported" refuses a load the very next moment would have run. It answers "is this scheme
- provably unusable here", and the real selection still happens after the handoff."""
+ provably unusable here", and the real selection still happens after the handoff.
+ """
requested = normalize_transformer_quant(requested)
if requested is None or not dense_transformer_supported(target):
return None
@@ -515,7 +507,6 @@ def select_transformer_quant_scheme(
def auto_scheme_candidates(target: Any, family: Optional[str] = None) -> tuple[str, ...]:
"""Every scheme ``auto`` would accept on this device, best first.
-
``select_transformer_quant_scheme`` returns only the winner, which is all the load needs
until the winner turns out to have no hosted prequant AND not to fit dense. The caller then
needs to know what auto would have picked NEXT, so it can reach a scheme that does have a
@@ -538,9 +529,9 @@ def auto_scheme_candidates(target: Any, family: Optional[str] = None) -> tuple[s
def _prefer_consumer_scheme(schemes: tuple[str, ...], device: Any) -> tuple[str, ...]:
- """Reorder an arch tier's schemes for the GPU class. On consumer / workstation cards move
- int8 first: they halve fp8/fp16 FP32-accumulate while int8 runs full-rate, so int8 is as
- fast or faster (and the only path on pre-Ada consumer). Data-center parts keep fp8 first."""
+ """Reorder an arch tier's schemes for the GPU class. On consumer / workstation cards move int8
+ first: they halve fp8/fp16 FP32-accumulate while int8 runs full-rate, so int8 is as fast or
+ faster (and the only path on pre-Ada consumer). Data-center parts keep fp8 first."""
if TQ_INT8 in schemes and schemes[0] != TQ_INT8 and _is_consumer_gpu(device):
return (TQ_INT8,) + tuple(s for s in schemes if s != TQ_INT8)
return schemes
@@ -571,17 +562,17 @@ def _scheme_supported(
except Exception:
return False
# Resolve the whole table in one throwaway child, falling back in-process. Nothing above allocates: the context
- # arrives on the first ALLOCATION, not on is_available() or get_device_capability() (0 MiB after both, 614 MiB after
- # the first tensor). Worth a child because /images/download-plan calls assert_precision_available while the user is
- # only STAGING, so a plan alone cost the backend ~700 MiB it can never give back. _smoke_probe's card-qualified key,
- # and the child is asked about that same card: a spawn starts on ordinal 0 whatever this thread is pinned to, so a
- # bare "cuda" would file card 0's verdict under the card the load runs on (and a bare key hid child verdicts
- # entirely).
+ # arrives on the first ALLOCATION, not on is_available() or get_device_capability() (0 MiB after both, 614 MiB
+ # after the first tensor). Worth a child because /images/download-plan calls assert_precision_available while the
+ # user is only STAGING, so a plan alone cost the backend ~700 MiB it can never give back. _smoke_probe's key is
+ # card-qualified, and the child is asked about that same card: a spawn starts on ordinal 0 whatever this thread is
+ # pinned to, so a bare "cuda" would file card 0's verdict under the card the load runs on (and a bare key hid
+ # child verdicts entirely).
card = _smoke_cache_device_key(device)
if (scheme, card) not in _SMOKE_CACHE:
with _CHILD_PROBE_LOCK:
- # Re-checked under the lock: the route answers plans concurrently, and a burst of them must not each spawn a
- # child that imports torch.
+ # Re-checked under the lock: the route answers plans concurrently, and a burst of them must not each spawn
+ # a child that imports torch.
if (scheme, card) not in _SMOKE_CACHE:
table = _child_probe_table(card)
if table is not None:
@@ -597,18 +588,18 @@ def _scheme_supported(
return _smoke_probe(scheme, device, unproven_ok = unproven_ok)
-# Long enough for a cold interpreter to import torch and torchao and run every probe (measured 3.9 s on a B200 host, so
-# this is ~45x headroom for a cold page cache); short enough that a child wedged in the driver does not hold the route
-# thread forever. Overrunning it is not a verdict either -- the caller falls back in-process.
+# Long enough for a cold interpreter to import torch and torchao and run every probe (measured 3.9 s on a B200 host,
+# so this is ~45x headroom for a cold page cache); short enough that a child wedged in the driver does not hold the
+# route thread forever. Overrunning it is not a verdict either -- the caller falls back in-process.
_CHILD_PROBE_TIMEOUT = 180.0
-# Set once the spawn machinery has been shown not to work here (frozen build without multiprocessing support, a sandbox
-# that refuses to fork/exec), so the fallback is paid once rather than on every miss.
+# Set once the spawn machinery has been shown not to work here (frozen build without multiprocessing support, a
+# sandbox that refuses to fork/exec), so the fallback is paid once rather than on every miss.
_CHILD_PROBE_UNAVAILABLE = False
-# Consecutive OSErrors out of the spawn before that latch is set anyway. An OSError is resource pressure and clears, so
-# it is retried; a host that raises one every time still stops paying for the attempt after a few misses. Reset by the
-# first spawn that works.
+# Consecutive OSErrors out of the spawn before that latch is set anyway. An OSError is resource pressure and clears,
+# so it is retried; a host that raises one every time still stops paying for the attempt after a few misses. Reset by
+# the first spawn that works.
_CHILD_PROBE_SPAWN_ERROR_LIMIT = 3
_CHILD_PROBE_SPAWN_ERRORS = 0
@@ -618,18 +609,19 @@ _CHILD_PROBE_LOCK = _threading.Lock()
def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
"""Every scheme's verdict from a SHORT-LIVED child process, or None when it could not run.
- The child dies with its CUDA context, which is the whole point: the context is process-wide
- and the driver never returns it, so probing in the backend permanently costs what the probe
- touched. Spawning is not free (3.9 s measured on a B200 host, nearly all of it importing
- torch), so one child answers for every scheme in ``TQ_SCHEMES`` at once rather than one child
- per ladder step: an auto ladder walking three schemes would otherwise pay it three times.
+ The child dies with its CUDA context, which is the whole point: the context is process-wide and
+ the driver never returns it, so probing in the backend permanently costs what the probe touched.
+ Spawning is not free (3.9 s measured on a B200 host, nearly all of it importing torch), so one
+ child answers for every scheme in ``TQ_SCHEMES`` at once rather than one child per ladder step:
+ an auto ladder walking three schemes would otherwise pay it three times.
- Verdicts are the child's ``_run_smoke_probe``, the same function the in-process path calls,
- so the two cannot drift. ``None`` for a scheme is an allocator failure, which the caller
- must not cache. ``None`` for the whole table means no child ran -- a frozen build without
+ Verdicts are the child's ``_run_smoke_probe``, the same function the in-process path calls, so
+ the two cannot drift. ``None`` for a scheme is an allocator failure, which the caller must not
+ cache. ``None`` for the whole table means no child ran -- a frozen build without
multiprocessing, a sandbox that refuses to spawn, a timeout -- and the caller then probes
in-process exactly as before, since refusing a load over a missing subprocess would be worse
- than the VRAM it saves."""
+ than the VRAM it saves.
+ """
global _CHILD_PROBE_UNAVAILABLE, _CHILD_PROBE_SPAWN_ERRORS
if _CHILD_PROBE_UNAVAILABLE:
return None
@@ -650,23 +642,21 @@ def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
# here, which is what the fallback is for.
ctx = mp.get_context("spawn")
with native_path_secret_removed_for_child_start():
- # inside the scrub: the first spawn-context queue starts multiprocessing's resource tracker
# Inside the scrub, as every other orchestrator here builds theirs. The first spawn-context queue starts
# multiprocessing's resource tracker, which is exec'd with this environment and outlives every child, so
# building it above the scrub would strand the lease secret somewhere the child-side scrub cannot reach.
queue = ctx.Queue()
- # The same entrypoint the inference worker is spawned through: it scrubs the lease secret from the child and
- # binds the child to this process's lifetime, so a wedged probe cannot outlive the backend.
+ # The same entrypoint the inference worker is spawned through: it scrubs the lease secret from the child
+ # and binds the child to this process's lifetime, so a wedged probe cannot outlive the backend.
proc = ctx.Process(
target = run_without_native_path_secret,
args = (__name__, "_child_probe_entry", {}, device, TQ_SCHEMES, queue),
daemon = True,
)
proc.start()
- # the bind above is the CHILD arming PDEATHSIG, which is Linux only
# Adopted like every other spawn site: the bind above is the CHILD arming PDEATHSIG, which is Linux only, and
- # the Windows job object can fail to take when Unsloth already runs inside an incompatible host job. This record
- # is what is left in that case.
+ # the Windows job object can fail to take when Unsloth already runs inside an incompatible host job. This
+ # record is what is left in that case.
_adopt_probe_pid(proc.pid)
_CHILD_PROBE_SPAWN_ERRORS = 0
except Exception as exc: # noqa: BLE001 - no child here: probe in-process instead
@@ -674,8 +664,8 @@ def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
# An OSError is momentary pressure on descriptors, process slots or /dev/shm, not a host that cannot spawn;
# latching it would hold the backend on the in-process probe, and its ~800 MiB, until restart. Only a
- # deterministic failure latches on sight, plus a run of OSErrors so a host that always refuses is paid for only
- # briefly.
+ # deterministic failure latches on sight, plus a run of OSErrors so a host that always refuses is paid for
+ # only briefly.
transient = isinstance(exc, OSError)
if transient:
_CHILD_PROBE_SPAWN_ERRORS += 1
@@ -719,17 +709,15 @@ def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
_PROBE_CRASH_SIGNALS = frozenset({4, 6, 7, 8, 11}) # ILL, ABRT, BUS, FPE, SEGV
# Windows has no signal here: multiprocessing returns GetExitCodeProcess verbatim, so a fault is the raw NTSTATUS
-# (access violation 0xC0000005, UCRT abort 0xC0000409), never -SIGSEGV. Only TERMINATE is negative, hence the sign test
-# first; the severity bits then separate a fault from a deliberate sys.exit.
+# (access violation 0xC0000005, UCRT abort 0xC0000409), never -SIGSEGV. Only TERMINATE is negative, hence the sign
+# test first; the severity bits then separate a fault from a deliberate sys.exit.
_NTSTATUS_ERROR_FLOOR = 0xC0000000
def _crashed_child_verdict(proc: Any, device: str) -> Optional[dict[str, Optional[bool]]]:
- """Return an all-false table after a fatal probe crash, otherwise None.
-
- The child may die before identifying the scheme, and every scheme shares ``quantize_``. Disable
- the table rather than repeating a proven-fatal probe in the backend.
- """
+ """Return an all-false table after a fatal probe crash, otherwise None. The child may die before
+ identifying the scheme, and every scheme shares ``quantize_``, so disable the table rather
+ than repeating a proven-fatal probe in the backend."""
try:
exitcode = proc.exitcode if proc is not None else None
except Exception: # noqa: BLE001 -- no handle left: nothing proven, fall back as before
@@ -757,8 +745,8 @@ def _crashed_child_verdict(proc: Any, device: str) -> Optional[dict[str, Optiona
def _adopt_probe_pid(pid: Optional[int]) -> None:
- """Record the probe child against this process's lifetime, so the shutdown sweep and the
- next startup can both reach it. Best-effort: a probe must not fail over its bookkeeping."""
+ """Record the probe child against this process's lifetime, so the shutdown sweep and the next
+ startup can both reach it. Best-effort: a probe must not fail over its bookkeeping."""
try:
from utils.process_lifetime import adopt_pid
adopt_pid(pid)
@@ -775,8 +763,8 @@ def _forget_probe_pid(pid: Optional[int]) -> None:
def _probe_child_alive(proc: Any) -> bool:
- """Whether the child is KNOWN to be running: a missing or never-started handle raises here,
- and that is not a survivor."""
+ """Whether the child is KNOWN to be running: a missing or never-started handle raises here, and
+ that is not a survivor."""
try:
return bool(proc is not None and proc.is_alive())
except Exception: # noqa: BLE001
@@ -784,14 +772,13 @@ def _probe_child_alive(proc: Any) -> bool:
def _close_probe_child(proc: Any, queue: Any) -> bool:
- """Tear the probe child and its queue down; True once the child is confirmed dead.
-
- Terminate then kill, as the chat worker's ``_shutdown_subprocess`` does: this child exists
- to hand a CUDA context back, so a wedged one left alive defeats the whole probe. The
- lifetime record is dropped only on confirmed death -- a child that outlives SIGKILL in an
- uninterruptible driver call keeps its breadcrumb, since that record is the only remaining
- handle on the VRAM it is holding. Best-effort at every step: this runs on the failure path
- too, and a probe that could not answer must not also raise."""
+ """Tear the probe child and its queue down; True once the child is confirmed dead. Terminate
+ then kill, as the chat worker's ``_shutdown_subprocess`` does: this child exists to hand a
+ CUDA context back, so a wedged one left alive defeats the whole probe. The lifetime record is
+ dropped only on confirmed death -- a child that outlives SIGKILL in an uninterruptible driver
+ call keeps its breadcrumb, since that record is the only remaining handle on the VRAM it is
+ holding. Best-effort at every step: this runs on the failure path too, and a probe that could
+ not answer must not also raise."""
try:
pid = proc.pid if proc is not None else None
except Exception: # noqa: BLE001
@@ -827,11 +814,10 @@ def _close_probe_child(proc: Any, queue: Any) -> bool:
def _select_probe_card(device: str) -> None:
- """Make ``device``'s ordinal current in this child, so the probe's argument-less CUDA calls
- -- ``synchronize()``, torchao's own capability lookups -- read the card the tensors are on.
-
- Best-effort: an index this process cannot select still probes, and lands the same failure
- the in-process fallback would."""
+ """Make ``device``'s ordinal current in this child, so the probe's argument-less CUDA calls --
+ ``synchronize()``, torchao's own capability lookups -- read the card the tensors are on.
+ Best-effort: an index this process cannot select still probes, and lands the same failure the
+ in-process fallback would."""
ordinal = device.partition(":")[2]
if not ordinal.isdigit():
return
@@ -844,7 +830,6 @@ def _select_probe_card(device: str) -> None:
def _child_probe_entry(device: str, schemes: tuple[str, ...], out: Any) -> None:
"""Child side of ``_child_probe_table``: probe every scheme and post one table back.
-
Module-level and stdlib-signature so ``spawn`` can reach it by name. Every scheme is
attempted even after one fails, because the verdicts are independent and the whole point is
to pay the CUDA context once."""
@@ -867,27 +852,26 @@ def _smoke_probe(
*,
unproven_ok: bool = False,
) -> bool:
- """True iff a tiny Linear quantised with ``scheme`` runs one M=32 forward and returns
- finite values. Cached per (scheme, device). Makes ``auto`` robust to a build lacking a
- prototype kernel: it fails here and the ladder moves on, rather than crashing at the first
- real denoise step.
-
- Half the input is all-zero rows and the output is checked for finiteness, because a kernel
- that runs is not the same as one that is usable. torchao's ``_choose_scale_float8`` has no
- eps clamp, so a zero row yields scale 0 and NaN qdata; that is the root cause behind
- qwen-image's fp8 black frames (its txt stream emits all-zero token rows through a set of
- ``txt_mlp.net.2`` linears that changes run to run, which is why keeping a fixed subset bf16
- does not fix it). ``_make_quant_config`` floors it with ``activation_value_lb``, but only
- when the installed torchao exposes that kwarg, and without a zero row the probe passed on a
- build lacking it. Zero rows are not exotic: every Wan pipeline pads prompt embeddings with
- ``new_zeros`` out to 226 or 512, so the tail rows reaching the DiT are exactly zero.
- Measured on B200, 4096-wide Linear: 412 of 512 rows non-finite without the floor, 0 of 512
- with it. Failing here costs one ladder step down to int8 instead."""
- # keyed by the CARD, not just "cuda": on a heterogeneous host a pass on one selected GPU would stand in for an
- # untested one
+ """True iff a tiny Linear quantised with ``scheme`` runs one M=32 forward and returns finite
+ values. Cached per (scheme, device). Makes ``auto`` robust to a build lacking a prototype
+ kernel: it fails here and the ladder moves on, rather than crashing at the first real denoise
+ step.
+
+ Half the input is all-zero rows and the output is checked for finiteness, because a kernel that
+ runs is not the same as one that is usable. torchao's ``_choose_scale_float8`` has no eps clamp,
+ so a zero row yields scale 0 and NaN qdata; that is the root cause behind qwen-image's fp8 black
+ frames (its txt stream emits all-zero token rows through a set of ``txt_mlp.net.2`` linears that
+ changes run to run, which is why keeping a fixed subset bf16 does not fix it).
+ ``_make_quant_config`` floors it with ``activation_value_lb``, but only when the installed
+ torchao exposes that kwarg, and without a zero row the probe passed on a build lacking it. Zero
+ rows are not exotic: every Wan pipeline pads prompt embeddings with ``new_zeros`` out to 226 or
+ 512, so the tail rows reaching the DiT are exactly zero. Measured on B200, 4096-wide Linear: 412
+ of 512 rows non-finite without the floor, 0 of 512 with it. Failing here costs one ladder step
+ down to int8 instead.
+ """
# Keyed by the CARD, not just "cuda": the probe runs on whichever device is current, so on a heterogeneous host a
- # pass on one selected GPU would otherwise stand in for an untested one, and a failure on an older card would reject
- # the scheme on a capable one.
+ # pass on one selected GPU would otherwise stand in for an untested one, and a failure on an older card would
+ # reject the scheme on a capable one.
key = (scheme, _smoke_cache_device_key(device))
if key in _SMOKE_CACHE:
return _SMOKE_CACHE[key]
@@ -927,10 +911,9 @@ def _run_smoke_probe(scheme: str, device: str) -> Optional[bool]:
def _is_out_of_memory(exc: BaseException) -> bool:
"""Whether ``exc`` is an allocator failure rather than a verdict on the scheme.
-
- ``torch.OutOfMemoryError`` subclasses ``RuntimeError``, not ``MemoryError``, and moved between
- ``torch.cuda`` and ``torch`` across releases, so both names are tried and the message is the
- backstop (a CUDA OOM surfaced through another wrapper still says "out of memory")."""
+ ``torch.OutOfMemoryError`` subclasses ``RuntimeError``, not ``MemoryError``, and moved
+ between ``torch.cuda`` and ``torch`` across releases, so both names are tried and the message
+ is the backstop (a CUDA OOM surfaced through another wrapper still says "out of memory")."""
try:
import torch
named = tuple(
@@ -949,24 +932,23 @@ def _is_out_of_memory(exc: BaseException) -> bool:
def _resolve_fast_accum(fast_accum: Optional[bool]) -> bool:
- """The fp8 ``use_fast_accum`` to apply. ``None`` (auto) is fast accumulate; an explicit bool
- forces it.
+ """The fp8 ``use_fast_accum`` to apply. ``None`` (auto) is fast accumulate; an explicit bool forces
+ it.
This used to derive from the GPU class, on the theory that only consumer parts pay for FP32
accumulate. The hardware side of that is right -- NVIDIA's professional whitepapers publish
equal FP8 rates for both accumulate modes on RTX 6000 Ada (728.5 TFLOPS either way) and RTX PRO
- 6000 Blackwell, against an exact halving on RTX 4090/5090 -- but the resulting default was
- still wrong on the cards it was written for, because the cost is in the cuBLAS path, not the
- published rate. Measured:
-
- * RTX 6000 Ada (sm_89), Z-Image-Turbo 1024x1024 x9: 6.387 s precise vs ~3.1 s fast --
- precise costs 2.05x and is slower than running the GGUF unquantised. (reported in review)
- * B200 (sm_100): the flag is a no-op -- 4096^3 ``_scaled_mm`` at 3023.8 vs 3041.8 TFLOP/s
- (0.994x) with BITWISE-identical output, and 1.213 s vs 1.230 s end to end.
- * consumer parts already resolved to fast here.
+ 6000 Blackwell, against an exact halving on RTX 4090/5090 -- but the resulting default was still
+ wrong on the cards it was written for, because the cost is in the cuBLAS path, not the published
+ rate. Measured: on RTX 6000 Ada (sm_89), Z-Image-Turbo 1024x1024 x9, 6.387 s precise vs ~3.1 s
+ fast, so precise costs 2.05x and is slower than running the GGUF unquantised (reported in
+ review); on B200 (sm_100) the flag is a no-op, 4096^3 ``_scaled_mm`` at 3023.8 vs 3041.8 TFLOP/s
+ (0.994x) with BITWISE-identical output and 1.213 s vs 1.230 s end to end; and consumer parts
+ already resolved to fast here.
So fast accumulate is a large win where the flag bites and free where it does not. Precise
- accumulate stays one explicit ``transformer_quant_fast_accum: false`` away."""
+ accumulate stays one explicit ``transformer_quant_fast_accum: false`` away.
+ """
return True if fast_accum is None else bool(fast_accum)
@@ -1003,7 +985,6 @@ def _quiet_config(cls: Any, **kwargs: Any) -> Any:
def _make_quant_config(scheme: str, fast_accum: Optional[bool] = None) -> Any:
"""The torchao dynamic-activation config for ``scheme`` (lazy imports per branch).
-
``fast_accum`` applies to fp8 only: None auto-detects by GPU class, True/False force it."""
from torchao.quantization import (
Float8DynamicActivationFloat8WeightConfig,
@@ -1025,9 +1006,10 @@ def _make_quant_config(scheme: str, fast_accum: Optional[bool] = None) -> Any:
config_params = _inspect.signature(Float8DynamicActivationFloat8WeightConfig).parameters
if "activation_value_lb" in config_params:
fp8_kwargs["activation_value_lb"] = 1e-12
- # Pin the plain-torch quantize kernel: the default AUTO switches to the MSLK kernel whenever an mslk package is
- # importable, changing fp8 scale rounding BITWISE and breaking the prequant bit-identity invariant. It is also
- # slower compiled on B200 (an opaque extern call blocks inductor's quantize fusion), so the pin costs nothing.
+ # Pin the plain-torch quantize kernel: the default AUTO switches to the MSLK kernel whenever an mslk package
+ # is importable, changing fp8 scale rounding BITWISE and breaking the prequant bit-identity invariant. It is
+ # also slower compiled on B200 (an opaque extern call blocks inductor's quantize fusion), so the pin costs
+ # nothing.
if "kernel_preference" in config_params:
try:
from torchao.quantization.quantize_.common.kernel_preference import (
@@ -1048,8 +1030,8 @@ def _make_quant_config(scheme: str, fast_accum: Optional[bool] = None) -> Any:
if scheme == TQ_NVFP4:
from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
- # Select the CUTLASS FP4 path, not the default Triton kernel (which needs MSLK): on a Blackwell box with CUTLASS
- # FP4 but no MSLK the default fails the smoke probe and falls back to GGUF.
+ # Select the CUTLASS FP4 path, not the default Triton kernel (which needs MSLK): on a Blackwell box with
+ # CUTLASS FP4 but no MSLK the default fails the smoke probe and falls back to GGUF.
try:
return _quiet_config(NVFP4DynamicActivationNVFP4WeightConfig, use_triton_kernel = False)
except TypeError: # older torchao without the knob
@@ -1077,19 +1059,20 @@ def make_filter_fn(
require_bf16: bool = False,
require_divisible: int = 0,
):
- """A torchao ``quantize_`` filter keeping only FLOP-heavy linears: nn.Linear with in/out
- features >= ``min_features`` AND whose fqn contains no ``exclude_name_tokens`` (int8 uses
- these to skip the M=1 projections that crash ``torch._int_mm``). Hides the callback arity.
-
- ``require_bf16`` also skips any non-bf16 Linear: fp8/mxfp8/nvfp4 assert a bf16 input weight,
- so one non-bf16 Linear (e.g. the fp32 layers Wan/Hunyuan DiTs keep) otherwise raises and
- aborts the ENTIRE pass, leaving the module dense. int8 tolerates non-bf16, so leaves this off.
-
- ``require_divisible`` (0 disables) skips any Linear whose in/out features are not multiples
- of it: the fp8/fp4 scaled_mm hardware GEMM requires 16-aligned dims and the 32-wide MX block
- scaling cannot tile a ragged dim, so one non-conforming Linear would otherwise crash the
- first real matmul AFTER the quantise pass succeeded (the smoke probe only proves an aligned
- GEMM runs). Leaving such a layer bf16 costs ~nothing."""
+ """A torchao ``quantize_`` filter keeping only FLOP-heavy linears: nn.Linear with in/out features
+ >= ``min_features`` AND whose fqn contains no ``exclude_name_tokens`` (int8 uses these to skip
+ the M=1 projections that crash ``torch._int_mm``). Hides the callback arity.
+
+ ``require_bf16`` also skips any non-bf16 Linear: fp8/mxfp8/nvfp4 assert a bf16 input weight, so
+ one non-bf16 Linear (e.g. the fp32 layers Wan/Hunyuan DiTs keep) otherwise raises and aborts the
+ ENTIRE pass, leaving the module dense. int8 tolerates non-bf16, so leaves this off.
+
+ ``require_divisible`` (0 disables) skips any Linear whose in/out features are not multiples of
+ it: the fp8/fp4 scaled_mm hardware GEMM requires 16-aligned dims and the 32-wide MX block
+ scaling cannot tile a ragged dim, so one non-conforming Linear would otherwise crash the first
+ real matmul AFTER the quantise pass succeeded (the smoke probe only proves an aligned GEMM
+ runs). Leaving such a layer bf16 costs ~nothing.
+ """
def filter_fn(module: Any, fqn: str = "") -> bool:
try:
@@ -1133,9 +1116,8 @@ def quantize_transformer(
logger: Any = None,
) -> Optional[str]:
"""Quantise ``pipe.transformer``'s FLOP-heavy linears in place with the arch-chosen scheme.
- Returns the scheme engaged, or None when disabled / unsupported / failed (caller loads
- GGUF). Best-effort: never raises for an unsupported environment (failure leaves it dense).
-
+ Returns the scheme engaged, or None when disabled / unsupported / failed (caller loads GGUF).
+ Best-effort: never raises for an unsupported environment (failure leaves it dense).
``fast_accum`` (fp8 only) overrides the per-GPU-class accumulate choice: None auto-detects,
True/False force it."""
scheme = select_transformer_quant_scheme(target, mode, family = family)
@@ -1147,7 +1129,6 @@ def quantize_transformer(
try:
from torchao.quantization import quantize_
- # int8 skips the M=1 projections; "lora_" keeps a baked adapter's side path high precision.
# int8 skips the M=1 projections; fp8/mxfp8 assert a bf16 weight, so on a mixed-precision DiT they must skip
# non-bf16 ones. "lora_" keeps a baked adapter's side path high precision. Runtime only: NOT part of
# exclude_tokens_for_scheme, whose list is baked into prequant metadata.
@@ -1165,7 +1146,6 @@ def quantize_transformer(
require_divisible = divisible,
),
)
- # not best-effort: a raise here means the transformer is quantized but not safely compilable
# Pad this family's small-M linears now that the weights are quantized and in place. Not best-effort: a raise
# here means the transformer is quantized but not safely compilable, so it falls into the except below and the
# caller loads GGUF.
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 1e377864c26..f99e10bfa97 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -1,12 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Async HTTP client proxying chat completions to external LLM providers.
-
-Most providers use OpenAI-compatible /v1/chat/completions; Anthropic uses
-the native Messages API, translated in this client.
-"""
+"""Async HTTP client proxying chat completions to external LLM providers. Most use OpenAI-compatible
+/v1/chat/completions; Anthropic uses the native Messages API, translated here."""
import asyncio
import base64
@@ -32,32 +28,26 @@ from core.inference.openai_responses_shared import (
)
from core.inference.sse_control_frames import sanitize_provider_sse_line
-# Local servers, not hosted APIs: each applies the model's own chat template on the way
-# in, so a prompt built here is templated just like an in-process one (#7066). "custom" is
-# a user-supplied OpenAI-compatible base_url (routes/providers.py:207-213), i.e. how a
-# self-hosted vLLM or llama.cpp registers without its preset. Unknown endpoint means assume
-# a template applies: sweeping a hosted API costs a space in delimiter-like text, not
-# sweeping a local one costs a forged turn.
+# Local servers, not hosted APIs: each applies the model's own chat template on the way in, so a prompt built here is
+# templated just like an in-process one (#7066). "custom" is a user-supplied OpenAI-compatible base_url, i.e. how a
+# self-hosted vLLM or llama.cpp registers without its preset. Unknown endpoint means assume a template applies:
+# sweeping a hosted API costs a space in delimiter-like text, not sweeping a local one costs a forged turn.
_TEMPLATE_APPLYING_PROVIDERS = frozenset({"vllm", "llama_cpp", "ollama", "custom"})
-# The subset documenting "continue_final_message" + "add_generation_prompt" on
-# /v1/chat/completions.
+# The subset documenting "continue_final_message" + "add_generation_prompt" on /v1/chat/completions.
_CONTINUATION_FLAG_PROVIDERS = frozenset({"vllm", "llama_cpp"})
-# The subset documenting stream_options.include_usage. An OAI-compatible stream omits
-# usage without it, and these providers report no llama.cpp timings either, so the
-# monitor has no token count to derive a speed from. Same caution as the flag above:
-# "custom" is any user-supplied base_url and a strict endpoint 400s on an unknown field.
-# "openai" is absent because it never reaches this body: it routes to /v1/responses,
-# which reports usage on its own.
+# The subset documenting stream_options.include_usage. An OAI-compatible stream omits usage without it, and these
+# providers report no llama.cpp timings either, so the monitor has no token count to derive a speed from. Same caution
+# as the flag above: "custom" is any user-supplied base_url and a strict endpoint 400s on an unknown field. "openai"
+# is absent because it routes to /v1/responses, which reports usage on its own.
_USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi"})
# llama-server reads repeat_penalty, not repetition_penalty (as routes/inference does).
_REPETITION_PENALTY_BODY_KEY = {"llama_cpp": "repeat_penalty"}
-# structlog so INFO diagnostics reach the backend's JSON log stream (the
-# stdlib root logger defaults to WARNING with no handlers). It accepts the
-# existing printf-style positional args.
+# structlog so INFO diagnostics reach the backend's JSON log stream (the stdlib root logger defaults to WARNING with
+# no handlers). It accepts the existing printf-style positional args.
logger = structlog.get_logger(__name__)
_MAX_CONCATENATED_WAV_BYTES = 64 * 1024 * 1024
@@ -146,15 +136,11 @@ def _append_provider_path(base_url: str, endpoint: str) -> str:
def _is_openai_family_cloud(base_url: Optional[str]) -> bool:
- """True iff ``base_url`` points at OpenAI cloud or Azure OpenAI Foundry.
-
- Anchored to the URL host so a path/subdomain like
- ``https://api.openai.com.attacker.com/v1`` can't bypass it (CodeQL
- py/incomplete-url-substring-sanitization). Scopes cloud-only Responses-API
- extensions that 400 on non-cloud OAI-compat servers (ollama/llama.cpp/vLLM).
- Azure Foundry resources live at ``<resource>.openai.azure.com``; the leading
- dot on `endswith` stops `openai.azure.com` apex from matching.
- """
+ """True iff ``base_url`` points at OpenAI cloud or Azure OpenAI Foundry. Anchored to the URL
+ host so a path/subdomain like ``https://api.openai.com.attacker.com/v1`` cannot bypass it
+ (CodeQL py/incomplete-url-substring-sanitization). Scopes cloud-only Responses-API extensions
+ that 400 on non-cloud OAI-compat servers. Azure Foundry resources live at
+ ``<resource>.openai.azure.com``; the leading dot on `endswith` stops the apex from matching."""
if not base_url:
return False
try:
@@ -166,15 +152,11 @@ def _is_openai_family_cloud(base_url: Optional[str]) -> bool:
return host == "api.openai.com" or host.endswith(".openai.azure.com")
-# Claude Opus 4.7 and every Claude 5 family removed temperature/top_p/top_k;
-# Mythos Preview has the same restriction. The API 400s with "<param> is
-# deprecated for this model" on a non-default value. Ref:
-# https://platform.claude.com/docs/en/about-claude/model-deprecations
-# `[a-z]+` family (not `[a-z0-9]+`) so legacy version-first ids like
-# `claude-3-5-sonnet-...` don't parse as major=5. Minor accepts `-` or `.`, and
-# is capped at two digits so the release date in a snapshot id such as
-# `claude-opus-4-20250514` is not read as minor 20250514 (which would sort that
-# Opus 4.0 model above 4.7 and strip the caller's sampling params).
+# Claude Opus 4.7 and every Claude 5 family removed temperature/top_p/top_k, as did Mythos Preview; the API 400s with
+# "<param> is deprecated for this model" on a non-default value. `[a-z]+` family (not `[a-z0-9]+`) so legacy
+# version-first ids like `claude-3-5-sonnet-...` do not parse as major=5. Minor accepts `-` or `.` and is capped at
+# two digits so the release date in a snapshot id such as `claude-opus-4-20250514` is not read as minor 20250514,
+# which would sort that Opus 4.0 model above 4.7 and strip the caller's sampling params.
_ANTHROPIC_MODEL_VERSION = re.compile(
r"^claude-(?P<family>[a-z]+)-(?P<major>\d+)(?:[-.](?P<minor>\d{1,2}))?(?:[-.]|$)",
re.IGNORECASE,
@@ -246,13 +228,10 @@ def _openai_image_replay_requires_reasoning(model: str) -> bool:
def _sanitize_openai_reasoning_replay_item(item: Any) -> Optional[dict[str, Any]]:
- """Return a Responses input-safe reasoning item, if ``item`` is one.
-
- OpenAI image-generation docs allow follow-up edits via the previous
- ``image_generation_call`` id. Reasoning models can also require the
- paired ``reasoning`` output item in manually managed context, so keep
- only the public replay fields and drop everything else.
- """
+ """Return a Responses input-safe reasoning item, if ``item`` is one. OpenAI image-generation
+ docs allow follow-up edits via the previous ``image_generation_call`` id, and reasoning
+ models can also require the paired ``reasoning`` output item in manually managed context, so
+ keep only the public replay fields and drop everything else."""
if not isinstance(item, dict) or item.get("type") != "reasoning":
return None
item_id = item.get("id")
@@ -269,26 +248,21 @@ def _sanitize_openai_reasoning_replay_item(item: Any) -> Optional[dict[str, Any]
text = part.get("text")
if isinstance(text, str):
summary_parts.append({"type": "summary_text", "text": text})
- # `id` and `summary` only: Responses rejects `status` on an input item
- # ("Unknown parameter: 'input[1].status'"), which 400d every replayed edit.
+ # `id` and `summary` only: Responses rejects `status` on an input item ("Unknown parameter: 'input[1].status'"),
+ # which 400d every replayed edit.
replay: dict[str, Any] = {"type": "reasoning", "id": item_id, "summary": summary_parts}
- # A zero-data-retention org has `store=false` forced on it, and OpenAI then
- # attaches `encrypted_content` to every reasoning item because the id alone
- # resolves to nothing server-side on the next turn. Carry it whenever it is
- # present: without it the replay is an id pointing at a response that was
- # never stored.
+ # A zero-data-retention org has `store=false` forced on it, and OpenAI then attaches `encrypted_content` to every
+ # reasoning item because the id alone resolves to nothing server-side on the next turn. Carry it whenever present:
+ # without it the replay is an id pointing at a response that was never stored.
encrypted = item.get("encrypted_content")
if isinstance(encrypted, str) and encrypted:
replay["encrypted_content"] = encrypted
return replay
-# OpenAI Responses inline citation markers: `citeSOURCE_ID[id2...][LOCATOR]`
-# using private-use codepoints (see
-# https://developers.openai.com/api/docs/guides/citation-formatting).
-# Group 1 holds delim-separated tokens; each resolvable token expands to
-# `[[N]](URL)`, unresolved tokens (locators, unknown ids) drop silently so
-# no garbled glyph reaches the renderer.
+# OpenAI Responses inline citation markers: `citeSOURCE_ID[id2...][LOCATOR]` using private-use codepoints
+# (https://developers.openai.com/api/docs/guides/citation-formatting). Group 1 holds delim-separated tokens; each
+# resolvable token expands to `[[N]](URL)`, unresolved tokens drop silently so no garbled glyph reaches the renderer.
_OPENAI_CITE_OPEN = "cite"
_OPENAI_CITE_STOP = ""
_OPENAI_CITE_DELIM = ""
@@ -298,11 +272,9 @@ _OPENAI_CITATION_MARKER = re.compile(
def _build_citation_lookup(url_citations: list[dict[str, Any]]) -> dict[str, tuple[int, str]]:
- """Map every known ``source_id`` alias to ``(citation_index, url)``.
-
- Accepts singular ``source_id`` and plural ``source_ids``. First-seen
- wins on collision so an earlier citation keeps its number.
- """
+ """Map every known ``source_id`` alias to ``(citation_index, url)``. Accepts singular
+ ``source_id`` and plural ``source_ids``. First-seen wins on collision so an earlier citation
+ keeps its number."""
by_source: dict[str, tuple[int, str]] = {}
for idx, cit in enumerate(url_citations, start = 1):
url = cit.get("url")
@@ -321,19 +293,16 @@ def _build_citation_lookup(url_citations: list[dict[str, Any]]) -> dict[str, tup
def _replace_openai_citation_markers(text: str, url_citations: list[dict[str, Any]]) -> str:
- """Rewrite `\\ue200cite\\ue202SOURCE_ID[\\ue202LOCATOR]\\ue201` markers into
- `[[N]](URL)` per resolvable id. Multi-source markers expand to one link
- per id; unresolved tokens drop. Idempotent on text without private-use
- codepoints.
- """
+ """Rewrite `\\ue200cite\\ue202SOURCE_ID[\\ue202LOCATOR]\\ue201` markers into `[[N]](URL)` per
+ resolvable id. Multi-source markers expand to one link per id; unresolved tokens drop.
+ Idempotent on text without private-use codepoints."""
if not text or _OPENAI_CITE_STOP not in text:
return text
by_source = _build_citation_lookup(url_citations)
def _sub(match: re.Match[str]) -> str:
- # Try every delim-split token; unresolved tokens drop. Handles
- # multi-source (all resolve) and source+locator (only id resolves,
- # locator drops). Empty result strips the marker.
+ # Try every delim-split token; unresolved tokens drop. Handles multi-source (all resolve) and source+locator
+ # (only id resolves). Empty result strips the marker.
rendered: list[str] = []
for tok in match.group(1).split(_OPENAI_CITE_DELIM):
if not tok:
@@ -351,14 +320,11 @@ def _replace_openai_citation_markers(text: str, url_citations: list[dict[str, An
def _rewrite_citation_markers_partial(
text: str, url_citations: list[dict[str, Any]]
) -> tuple[str, bool]:
- """Like ``_replace_openai_citation_markers`` but also reports whether
- any marker referenced a source_id not yet in ``url_citations``.
-
- A url_citation's ``annotation.added`` event typically arrives AFTER the
- delta carrying the marker that references it. Callers buffer the segment
- until a later event records the annotation; unresolved markers are left
- verbatim so a follow-up pass still parses cleanly.
- """
+ """Like ``_replace_openai_citation_markers`` but also reports whether any marker referenced a
+ source_id not yet in ``url_citations``. A url_citation's ``annotation.added`` event typically
+ arrives AFTER the delta carrying the marker that references it, so callers buffer the segment
+ until a later event records the annotation; unresolved markers are left verbatim so a
+ follow-up pass still parses cleanly."""
if not text or _OPENAI_CITE_STOP not in text:
return text, False
by_source = _build_citation_lookup(url_citations)
@@ -376,9 +342,8 @@ def _rewrite_citation_markers_partial(
continue
idx, url = hit
rendered.append(f"[[{idx}]]({url})")
- # Leave the whole marker verbatim if any token is unresolved so the
- # caller can re-run once the late annotation lands; partial emission
- # would lose unresolved ids once the source text is dropped.
+ # Leave the whole marker verbatim if any token is unresolved so the caller can re-run once the late annotation
+ # lands; partial emission would lose unresolved ids once the source text is dropped.
if any_unresolved:
has_unresolved = True
return match.group(0)
@@ -388,15 +353,11 @@ def _rewrite_citation_markers_partial(
def _split_pending_citation_tail(text: str) -> tuple[str, str]:
- """Split ``text`` into ``(head, pending_tail)`` for streamed deltas.
-
- A citation marker can straddle two SSE deltas (e.g. delta-1 ends with
- ``\\ue200citetu`` and delta-2 starts with ``rn0view0\\ue201``); the
- unterminated tail is buffered and prepended onto the next delta so the
- rewriter sees a complete marker. ``pending_tail`` is the longest suffix
- starting with ``\\ue200`` and lacking ``\\ue201``; ``head`` is safe to
- emit. Empty tail when ``text`` has no open or a fully closed marker.
- """
+ """Split ``text`` into ``(head, pending_tail)`` for streamed deltas. A citation marker can
+ straddle two SSE deltas, so the unterminated tail is buffered and prepended onto the next
+ delta and the rewriter sees a complete marker. ``pending_tail`` is the longest suffix
+ starting with ``\\ue200`` and lacking ``\\ue201``; ``head`` is safe to emit. Empty tail when
+ ``text`` has no open or a fully closed marker."""
if not text:
return text, ""
last_open = text.rfind("")
@@ -409,21 +370,17 @@ def _split_pending_citation_tail(text: str) -> tuple[str, str]:
def _extract_web_search_action(item: dict[str, Any]) -> dict[str, Any]:
- """Normalize an OpenAI web_search_call action into card arguments.
-
- gpt-5.x agentic search emits three action types, discriminated by
- `action.type`: `search` carries queries, `open_page` a url, `find_in_page` a
- url and a pattern. Reading only `action.query` renders the last two as an
- empty `Searching ""` card. Shapes per WebSearchToolCall in
- https://github.com/openai/openai-openapi (openapi.yaml).
- """
+ """Normalize an OpenAI web_search_call action into card arguments. gpt-5.x agentic search emits
+ three action types discriminated by `action.type`: `search` carries queries, `open_page` a
+ url, `find_in_page` a url and a pattern. Reading only `action.query` renders the last two as
+ an empty `Searching ""` card. Shapes per WebSearchToolCall in
+ https://github.com/openai/openai-openapi."""
if not isinstance(item, dict):
return {}
action = item.get("action") if isinstance(item.get("action"), dict) else {}
action_type = action.get("type") if isinstance(action.get("type"), str) else ""
- # `queries` is the current field and holds every query the call ran; the
- # singular `query` is deprecated in the spec, so it is only the fallback.
- # Neither is required, so a search action can carry no query at all.
+ # `queries` is the current field and holds every query the call ran; the singular `query` is deprecated, so it is
+ # only the fallback. Neither is required, so a search action can carry no query at all.
query = ""
for source in (action.get("queries"), item.get("queries")):
if isinstance(source, list):
@@ -450,11 +407,9 @@ def _extract_web_search_action(item: dict[str, Any]) -> dict[str, Any]:
return arguments
-# Families that accept `prompt_cache_retention: "24h"`. Everything else 400s
-# with "prompt_cache_retention is not supported on this model" and the turn
-# dies (openai/codex#39397), while an unmatched model just falls back to
+# Families that accept `prompt_cache_retention: "24h"`. Everything else 400s with "prompt_cache_retention is not
+# supported on this model" and the turn dies (openai/codex#39397), while an unmatched model just falls back to
# in-memory caching -- so guess narrow.
-# https://developers.openai.com/api/docs/guides/prompt-caching
_OPENAI_EXTENDED_CACHE_FAMILY = re.compile(r"^(?:gpt-5(?:\.\d+)?(?:[-.]|$)|gpt-4\.1$)")
@@ -462,8 +417,8 @@ class _AnthropicThinkingSpec(NamedTuple):
prefixes: tuple[str, ...]
kind: Literal["adaptive", "manual"]
efforts: tuple[str, ...]
- # Claude 5 thinks unless told otherwise, so "Thinking: off" must send an
- # explicit disable. Fable/Mythos 5 400 on it (thinking is always on).
+ # Claude 5 thinks unless told otherwise, so "Thinking: off" must send an explicit disable. Fable/Mythos 5 400 on
+ # it (thinking is always on).
thinking_default_on: bool = False
can_disable: bool = True
@@ -507,12 +462,10 @@ def _anthropic_thinking_spec(model: str) -> Optional[_AnthropicThinkingSpec]:
return None
-# Anthropic ships date-pinned tool versions per model family: the newer
-# `_20260209`/`_20260120` variants only run on recent models (400 "tool not
-# supported" elsewhere), and old versions on a new model miss dynamic
-# filtering and free-with-search pricing. Pick the newest combo the model
-# accepts, else the GA `_20250305`/`_20250910`/`_20250825` defaults. Ref:
-# https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference
+# Anthropic ships date-pinned tool versions per model family: the newer `_20260209`/`_20260120` variants only run on
+# recent models (400 "tool not supported" elsewhere), and old versions on a new model miss dynamic filtering and
+# free-with-search pricing. Pick the newest combo the model accepts, else the GA `_20250305`/`_20250910`/`_20250825`
+# defaults.
_ANTHROPIC_5_PREFIXES = (
"claude-opus-5",
"claude-sonnet-5",
@@ -555,17 +508,14 @@ def _anthropic_code_execution_version(model: str) -> str:
)
-# Anthropic's beta-header flag for code execution does NOT change with the
-# tool version -- both `_20250825` and `_20260120` are unlocked by the same
-# `code-execution-2025-08-25` header per the upstream docs.
+# Anthropic's beta-header flag for code execution does NOT change with the tool version -- both `_20250825` and
+# `_20260120` are unlocked by `code-execution-2025-08-25`.
_ANTHROPIC_CODE_EXECUTION_BETA = "code-execution-2025-08-25"
-# Anthropic server-side context compaction (beta compact-2026-01-12), supported
-# on Claude 5, Opus 4.6/4.7/4.8, Sonnet 4.6 and Mythos Preview. Same beta header
-# for all; the dated `compact_20260112` type lives in body
-# `context_management.edits`. Models outside the prefix list are silently
-# ignored so we don't 400 upstream.
+# Anthropic server-side context compaction (beta compact-2026-01-12), supported on Claude 5, Opus 4.6/4.7/4.8, Sonnet
+# 4.6 and Mythos Preview. Same beta header for all; the dated `compact_20260112` type lives in body
+# `context_management.edits`. Models outside the prefix list are silently ignored so we do not 400 upstream.
_ANTHROPIC_COMPACTION_PREFIXES = _ANTHROPIC_5_PREFIXES + (
"claude-opus-4-7",
"claude-opus-4-6",
@@ -574,17 +524,13 @@ _ANTHROPIC_COMPACTION_PREFIXES = _ANTHROPIC_5_PREFIXES + (
)
_ANTHROPIC_COMPACTION_BETA = "compact-2026-01-12"
_ANTHROPIC_COMPACTION_TYPE = "compact_20260112"
-# The threshold must be >= 50K tokens; lower 400s. Clamp on the way out so
-# a UI slider can't underflow.
+# The threshold must be >= 50K tokens; lower 400s. Clamp on the way out so a UI slider cannot underflow.
_ANTHROPIC_COMPACTION_MIN = 50_000
-# Anthropic fast-mode beta (Opus 5 / Opus 4.8 only, per
-# https://platform.claude.com/docs/en/build-with-claude/fast-mode).
-# Opus 4.7 400s on `speed`; Opus 4.6 accepts it but runs at standard speed and
-# reports `usage.speed: "standard"`, so exposing the toggle there promises a
-# speed-up that never happens. Sonnet 5 never had it.
-# Mutually exclusive with the Priority service tier.
+# Anthropic fast-mode beta, Opus 5 / Opus 4.8 only: Opus 4.7 400s on `speed`; Opus 4.6 accepts it but runs at standard
+# speed and reports `usage.speed: "standard"`, so exposing the toggle there promises a speed-up that never happens.
+# Sonnet 5 never had it. Mutually exclusive with the Priority service tier.
_ANTHROPIC_FAST_MODE_BETA = "fast-mode-2026-02-01"
_ANTHROPIC_FAST_MODE_PREFIXES = (
"claude-opus-5",
@@ -597,29 +543,23 @@ def _anthropic_supports_compaction(model: str) -> bool:
def _anthropic_supports_fast_mode(model: str) -> bool:
- # Require a family boundary ("" or "-") after the prefix so IDs like
- # "claude-opus-4-70" / "claude-opus-4-7b" don't match.
+ # Require a family boundary ("" or "-") after the prefix so IDs like "claude-opus-4-70" / "claude-opus-4-7b" do
+ # not match.
return any(model == p or model.startswith(f"{p}-") for p in _ANTHROPIC_FAST_MODE_PREFIXES)
-# Cap on ``cited_text`` forwarded in document_citations tool_events; bounds
-# SSE bytes on multi-KB cited spans (frontend trims to 240 chars anyway).
+# Cap on ``cited_text`` forwarded in document_citations tool_events; bounds SSE bytes on multi-KB cited spans (the
+# frontend trims to 240 chars anyway).
_CITED_TEXT_MAX_LEN = 512
def _anthropic_citation_key(citation: dict[str, Any]) -> tuple:
- """Stable dedup key for an Anthropic ``citations_delta.citation``.
-
- Anchor fields vary per type (char_location, page_location,
- content_block_location, search_result_location); both start AND
- exclusive end indices are in the key so same-start / different-end pairs
- stay distinct. search_result_location keys on ``search_result_index`` +
- ``source`` instead of document_index so distinct results with the same
- source don't collapse. Unknown shapes fall back to a stringified copy
- (more entries, never collisions). See
- https://platform.claude.com/docs/en/build-with-claude/citations
- and https://platform.claude.com/docs/en/build-with-claude/search-results.
- """
+ """Stable dedup key for an Anthropic ``citations_delta.citation``. Anchor fields vary per type
+ (char_location, page_location, content_block_location, search_result_location); both start
+ AND exclusive end indices are in the key so same-start / different-end pairs stay distinct.
+ search_result_location keys on ``search_result_index`` + ``source`` instead of document_index
+ so distinct results with the same source do not collapse. Unknown shapes fall back to a
+ stringified copy (more entries, never collisions)."""
ctype = citation.get("type")
doc = citation.get("document_index")
title = citation.get("document_title") or ""
@@ -700,24 +640,18 @@ def _apply_mistral_reasoning_controls(
enable_thinking: Optional[bool],
reasoning_effort: Optional[str],
) -> None:
- """
- Translate generic reasoning controls into Mistral's model-specific shape.
-
- Contract:
- - magistral-medium-latest: baseline (no extra field) or
- `prompt_mode="reasoning"` for explicit reasoning mode.
- - mistral-small-latest / mistral-vibe-cli-latest:
- `reasoning_effort` in {"none", "high"}.
- - all other tested Mistral models: no reasoning/thinking params.
- """
+ """Translate generic reasoning controls into Mistral's model-specific shape:
+ magistral-medium-latest takes baseline or `prompt_mode="reasoning"`; mistral-small-latest /
+ mistral-vibe-cli-latest take `reasoning_effort` in {"none", "high"}; all other tested Mistral
+ models take no reasoning params."""
model_for_matching = model.rsplit("/", 1)[-1].strip().lower()
spec = _mistral_thinking_spec(model_for_matching)
body.pop("prompt_mode", None)
body.pop("reasoning_effort", None)
if spec.style == "prompt_mode":
- # Magistral baseline is already reasoning-capable; the explicit
- # prompt_mode path is only for the "high" UI selection.
+ # Magistral baseline is already reasoning-capable; the explicit prompt_mode path is only for the "high" UI
+ # selection.
if enable_thinking is True or reasoning_effort == "high":
body["prompt_mode"] = "reasoning"
return
@@ -743,11 +677,9 @@ _OLLAMA_REASONING_EFFORT_ALIASES = {
def _apply_ollama_reasoning_controls(
body: dict[str, Any], enable_thinking: Optional[bool], reasoning_effort: Optional[str]
) -> None:
- """Map API thinking controls onto Ollama's ``reasoning_effort`` field.
-
- Requests with neither control remain unchanged. An explicit off is
- ``none``; an on without a level is ``medium``. #9649
- """
+ """Map API thinking controls onto Ollama's ``reasoning_effort`` field. Requests with neither
+ control remain unchanged. An explicit off is ``none``; an on without a level is ``medium``.
+ #9649"""
effort = (reasoning_effort or "").strip().lower()
if effort in _OLLAMA_REASONING_EFFORT_ALIASES:
effort = _OLLAMA_REASONING_EFFORT_ALIASES[effort]
@@ -761,12 +693,11 @@ def _apply_ollama_reasoning_controls(
body["reasoning_effort"] = "medium"
-# Shared client reused across all requests for HTTP connection pooling.
-# Auth headers and timeouts are passed per-request, so a single client
-# handles every provider without storing credentials.
+# Shared client reused across all requests for HTTP connection pooling. Auth headers and timeouts are passed
+# per-request, so a single client handles every provider without storing credentials.
def _create_shared_http_client() -> httpx.AsyncClient:
- # Unsupported env proxy schemes (socks:// etc) raise at construction and
- # would crash Unsloth startup (#6090); retry ignoring env proxies instead.
+ # Unsupported env proxy schemes (socks:// etc) raise at construction and would crash Unsloth startup (#6090);
+ # retry ignoring env proxies instead.
try:
return httpx.AsyncClient()
except (ImportError, ValueError) as exc:
@@ -792,18 +723,12 @@ def _safe_fetch_image_for_gemini_sync(
fallback_mime: str,
max_bytes: int = _GEMINI_REMOTE_IMAGE_MAX_BYTES,
) -> Optional[tuple[str, str]]:
- """Synchronous IP-pinned HTTPS image fetch with SSRF guards.
-
- Uses the same pinned-IP + SNI pattern as `tools._fetch_page_text` so DNS
- rebinding between validation and the connection cannot redirect us to a
- private/metadata address. Follows up to 4 hops, re-validating each
- redirect target. Returns (mime, base64) or None.
-
- `max_bytes` is clamped to the per-image cap and also lets the caller pass
- the remaining per-request budget, so an over-budget URL is rejected via
- Content-Length (or read short-circuit) instead of being fully downloaded
- then discarded.
- """
+ """Synchronous IP-pinned HTTPS image fetch with SSRF guards. Uses the same pinned-IP + SNI
+ pattern as `tools._fetch_page_text` so DNS rebinding between validation and the connection
+ cannot redirect us to a private/metadata address. Follows up to 4 hops, re-validating each
+ redirect target. Returns (mime, base64) or None. `max_bytes` is clamped to the per-image cap
+ and also lets the caller pass the remaining per-request budget, so an over-budget URL is
+ rejected via Content-Length instead of being fully downloaded then discarded."""
import urllib.error
import urllib.request
from urllib.parse import urljoin, urlunparse
@@ -823,10 +748,9 @@ def _safe_fetch_image_for_gemini_sync(
)
def _safe_parse_https(raw_url: str) -> Optional[tuple[Any, str, int]]:
- """Validate https + hostname + port. Returns (parsed, host, port) or
- None. Handles malformed-port and malformed-bracketed-IPv6 URLs that
- would else raise ValueError mid-build.
- """
+ """Validate https + hostname + port. Returns (parsed, host, port) or None. Handles
+ malformed-port and malformed-bracketed-IPv6 URLs that would else raise ValueError
+ mid-build."""
try:
parsed_url = urlparse(raw_url)
host_value = parsed_url.hostname
@@ -976,32 +900,26 @@ async def _safe_fetch_image_for_gemini(
fallback_mime: str,
max_bytes: int = _GEMINI_REMOTE_IMAGE_MAX_BYTES,
) -> Optional[tuple[str, str]]:
- """Async wrapper running the IP-pinned fetch on a worker thread.
-
- SSRF guards (https only, pinned IP, per-hop redirect re-check, size cap,
- image/* content-type) live in the sync helper. `max_bytes` carries the
- remaining per-request budget so over-budget URLs are rejected up front.
- """
+ """Async wrapper running the IP-pinned fetch on a worker thread. SSRF guards (https only, pinned
+ IP, per-hop redirect re-check, size cap, image/* content-type) live in the sync helper.
+ `max_bytes` carries the remaining per-request budget so over-budget URLs are rejected up
+ front."""
import asyncio
return await asyncio.to_thread(_safe_fetch_image_for_gemini_sync, url, fallback_mime, max_bytes)
-# Synthetic-tool names stamped onto outbound _toolEvent.arguments so the
-# frontend can tell provider-side cards from real user-declared tools of the
-# same name. Mirrored on the TS side.
+# Synthetic-tool names stamped onto outbound _toolEvent.arguments so the frontend can tell provider-side cards from
+# real user-declared tools of the same name. Mirrored on the TS side.
_SERVER_SIDE_BUILTIN_TOOL_NAMES = frozenset(
{"web_search", "web_fetch", "code_execution", "image_generation"}
)
def _stamp_server_tool_marker(payload: dict[str, Any]) -> None:
- """Tag synthetic provider-side tool events so the frontend can tell them
- from real user-declared / local function tools of the same name. The
- marker rides on `arguments._server_tool` and is only added for known
- server-side builtin names; user-supplied tool calls echoed back through
- these helpers (e.g. Kimi `$web_search`) keep their shape because this
- stays scoped to the canonical builtin names.
- """
+ """Tag synthetic provider-side tool events so the frontend can tell them from real user-declared
+ / local function tools of the same name. The marker rides on `arguments._server_tool` and is
+ only added for known server-side builtin names, so user-supplied tool calls echoed back
+ through these helpers (e.g. Kimi `$web_search`) keep their shape."""
if not isinstance(payload, dict):
return
if payload.get("type") != "tool_start":
@@ -1019,14 +937,10 @@ def _stamp_server_tool_marker(payload: dict[str, Any]) -> None:
def _build_kimi_tool_end(
synthetic_chunk_fn: Any, tool_call_id: str, citations: list[dict[str, str]]
) -> str:
- """Format Kimi web_search citations into the tool_end payload.
-
- Same shape the frontend's parseSourcesFromResult expects for the other
- built-in web_search providers: `Title: ...\\nURL: ...\\n
- Snippet: ...\\n---\\n...`. If no citations were emitted, fall back to a
- generic "(search complete)" string so the UI still transitions the tool
- card to completed.
- """
+ """Format Kimi web_search citations into the tool_end payload, in the shape the frontend's
+ parseSourcesFromResult expects for the other built-in web_search providers. With no
+ citations, fall back to a generic "(search complete)" string so the UI still transitions the
+ tool card to completed."""
blocks: list[str] = []
for cit in citations:
line = f"Title: {cit['title']}\nURL: {cit['url']}"
@@ -1053,16 +967,14 @@ class ExternalProviderClient:
timeout: float = 120.0,
):
self.provider_type = provider_type
- # Single choke point for every outbound provider request (chat, models,
- # responses, messages, containers): the URL is caller-controlled, so it
- # is validated here even when a route already checked it. Routes turn the
+ # Single choke point for every outbound provider request (chat, models, responses, messages, containers): the
+ # URL is caller-controlled, so it is validated here even when a route already checked it. Routes turn the
# ValueError into a 400; reaching it here means a caller bypassed them.
from core.inference.providers import validate_provider_base_url
self.base_url = validate_provider_base_url(base_url)
- # Strip a legacy `/openai` suffix from Google-hosted bases so configs
- # saved before the native switch still route correctly. Custom proxy
- # paths ending in `/openai` are left untouched.
+ # Strip a legacy `/openai` suffix from Google-hosted bases so configs saved before the native switch still
+ # route correctly. Custom proxy paths ending in `/openai` are left untouched.
if self.provider_type == "gemini":
_parsed_base = urlparse(self.base_url)
if (
@@ -1073,8 +985,8 @@ class ExternalProviderClient:
self.base_url = self.base_url[: -len("/openai")]
self.api_key = api_key
self._timeout = httpx.Timeout(timeout, connect = 10.0)
- # Generous per-byte read timeout: reasoning models pause tens of seconds
- # between bytes, but a dead upstream must eventually error, not hang forever.
+ # Generous per-byte read timeout: reasoning models pause tens of seconds between bytes, but a dead upstream
+ # must eventually error, not hang forever.
self._stream_timeout = httpx.Timeout(timeout, connect = 10.0, read = 300.0)
def _auth_headers(self) -> dict[str, str]:
@@ -1085,8 +997,8 @@ class ExternalProviderClient:
auth_header = provider_info.get("auth_header", "Authorization")
auth_prefix = provider_info.get("auth_prefix", "Bearer ")
- # Non-Google Gemini bases (LiteLLM, custom gateways) use OAI-compat
- # Bearer auth, not Google's x-goog-api-key. Override the default.
+ # Non-Google Gemini bases (LiteLLM, custom gateways) use OAI-compat Bearer auth, not Google's x-goog-api-key.
+ # Override the default.
if self.provider_type == "gemini":
_host = (urlparse(self.base_url).hostname or "").lower()
if _host != "generativelanguage.googleapis.com":
@@ -1094,8 +1006,8 @@ class ExternalProviderClient:
auth_prefix = "Bearer "
headers = {"Content-Type": "application/json"}
- # Skip auth header when api_key is empty (optional for local providers);
- # httpx rejects an empty `Bearer ` value as "Illegal header value".
+ # Skip auth header when api_key is empty (optional for local providers); httpx rejects an empty `Bearer `
+ # value as "Illegal header value".
if self.api_key:
headers[auth_header] = f"{auth_prefix}{self.api_key}"
# Merge provider-specific extra headers (anthropic-version, OpenRouter attribution).
@@ -1107,8 +1019,8 @@ class ExternalProviderClient:
from core.inference.providers import get_provider_info
info = get_provider_info(self.provider_type) or {}
- # Google-hosted Gemini uses the native translator; non-Google bases
- # stay on OAI-compat so LiteLLM / custom proxies still work.
+ # Google-hosted Gemini uses the native translator; non-Google bases stay on OAI-compat so LiteLLM / custom
+ # proxies still work.
if self.provider_type == "gemini":
_host = (urlparse(self.base_url).hostname or "").lower()
if _host != "generativelanguage.googleapis.com":
@@ -1141,30 +1053,21 @@ class ExternalProviderClient:
response_format: Optional[dict[str, Any]] = None,
stream: bool = True,
) -> AsyncGenerator[str, None]:
- """
- Yield OpenAI-format SSE lines from the external provider.
-
- OpenAI-compatible providers forward lines verbatim. For Anthropic, the
- native Messages API SSE is translated to OpenAI format.
-
- ``top_k``, ``min_p``, ``repetition_penalty`` and ``presence_penalty``
- are opt-in: forwarded only when supplied, since the frontend's
- capability map already filters them per provider.
-
- ``fast_mode`` only applies to Anthropic Opus 5 / Opus 4.8 (silently
- dropped elsewhere); adds the beta header and ``speed: "fast"``.
- """
- # tool_choice="none" hard-disables hosted/builtin tools across every
- # provider so enabled_tools can't accidentally bill or leak.
+ """Yield OpenAI-format SSE lines from the external provider. OpenAI-compatible providers
+ forward lines verbatim; for Anthropic the native Messages API SSE is translated.
+ ``top_k``, ``min_p``, ``repetition_penalty`` and ``presence_penalty`` are opt-in, forwarded
+ only when supplied, since the frontend's capability map already filters them per provider.
+ ``fast_mode`` only applies to Anthropic Opus 5 / Opus 4.8 (silently dropped elsewhere); it
+ adds the beta header and ``speed: "fast"``."""
+ # tool_choice="none" hard-disables hosted/builtin tools across every provider so enabled_tools cannot
+ # accidentally bill or leak.
tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
if not self._is_openai_compatible():
- # Gemini speaks its own native REST shape (contents/parts);
- # `_stream_gemini` translates request/response into the OpenAI
- # Chat Completions chunk format the rest of Unsloth expects.
- # API ref: https://ai.google.dev/gemini-api/docs
+ # Gemini speaks its own native REST shape (contents/parts); `_stream_gemini` translates request/response
+ # into the OpenAI Chat Completions chunk format the rest of Unsloth expects.
if self.provider_type == "gemini":
async for line in self._stream_gemini(
messages,
@@ -1204,11 +1107,9 @@ class ExternalProviderClient:
yield line
return
- # OpenAI moved flagship models (gpt-5.x) off /v1/chat/completions —
- # those endpoints return 404 "This is not a chat model" for the new
- # families. Route all OpenAI traffic through /v1/responses instead;
- # we translate the Responses SSE back into Chat Completions chunks so
- # the frontend stays endpoint-agnostic.
+ # OpenAI moved flagship models (gpt-5.x) off /v1/chat/completions -- those endpoints return 404 "This is not a
+ # chat model" for the new families. Route all OpenAI traffic through /v1/responses instead and translate the
+ # Responses SSE back into Chat Completions chunks so the frontend stays endpoint-agnostic.
if self.provider_type == "openai":
async for line in self._stream_openai_responses(
messages,
@@ -1229,9 +1130,8 @@ class ExternalProviderClient:
yield line
return
- # Kimi $web_search needs a 2-call round-trip + thinking off; route to
- # a helper. Forced-function tool_choice suppresses it.
- # https://platform.kimi.ai/docs/guide/use-web-search
+ # Kimi $web_search needs a 2-call round-trip + thinking off; route to a helper. Forced-function tool_choice
+ # suppresses it.
_kimi_tool_choice_forced_function = (
isinstance(tool_choice, dict)
and tool_choice.get("type") == "function"
@@ -1253,9 +1153,8 @@ class ExternalProviderClient:
yield line
return
- # A self-hosted server templates client text just like the in-process paths, so the
- # same "</think>" or turn marker forges a turn (#7066). Hosted APIs are left alone:
- # their prompt assembly is not this repo's template and not ours to rewrite.
+ # A self-hosted server templates client text just like the in-process paths, so the same "</think>" or turn
+ # marker forges a turn (#7066). Hosted APIs are left alone: their prompt assembly is not ours to rewrite.
if self.provider_type in _TEMPLATE_APPLYING_PROVIDERS:
from core.inference.chat_template_helpers import (
neutralize_control_markup_in_messages,
@@ -1265,18 +1164,17 @@ class ExternalProviderClient:
messages = neutralize_control_markup_in_messages(messages)
if tools:
safe_tools = neutralize_tool_descriptions(tools)
- # A mixed catalog keeps safe_tools non-empty while dropping the one tool the
- # client forced, so an empty check is not enough: without the passthrough
- # builder's per-name reconciliation the body names an unadvertised function.
+ # A mixed catalog keeps safe_tools non-empty while dropping the one tool the client forced, so an
+ # empty check is not enough: without the passthrough builder's per-name reconciliation the body names
+ # an unadvertised function.
tool_choice = reconciled_tool_choice(tool_choice, tools, safe_tools)
if not safe_tools:
tool_choice = None
tools = safe_tools
- # Both are set because a server rejects continuing while a generation prompt is
- # still asked for. Sent only to the two documenting the pair: "custom" is any
- # user-supplied base_url, and a strict endpoint 400s on an unknown field, so it
- # keeps the trailing assistant turn on its own as before.
+ # Both are set because a server rejects continuing while a generation prompt is still asked for. Sent only to
+ # the two documenting the pair: "custom" is any user-supplied base_url and a strict endpoint 400s on an
+ # unknown field, so it keeps the trailing assistant turn on its own as before.
_continue_body = (
{"continue_final_message": True, "add_generation_prompt": False}
if continue_final_message and self.provider_type in _CONTINUATION_FLAG_PROVIDERS
@@ -1310,18 +1208,16 @@ class ExternalProviderClient:
repetition_penalty
)
- # Drop fields the registry flags as unusable so reasoning-class models
- # with fixed defaults (Kimi k2.6 etc) don't 400 on pydantic defaults
- # the route layer still fills in.
+ # Drop fields the registry flags as unusable so reasoning-class models with fixed defaults (Kimi k2.6 etc) do
+ # not 400 on pydantic defaults the route layer still fills in.
from core.inference.providers import get_provider_info
provider_info = get_provider_info(self.provider_type) or {}
for field in provider_info.get("body_omit", ()):
body.pop(field, None)
- # Kimi thinking is a top-level body field. kimi-k2-thinking is always
- # on (ignore the toggle); kimi-k2.6 defaults on, can be disabled.
- # `keep: all` preserves every chunk for the UI panel.
+ # Kimi thinking is a top-level body field. kimi-k2-thinking is always on (ignore the toggle); kimi-k2.6
+ # defaults on, can be disabled. `keep: all` preserves every chunk for the UI panel.
if self.provider_type == "kimi" and enable_thinking is not None:
if model == "kimi-k2-thinking":
# Always on; ignore client toggle to avoid an API-level reject.
@@ -1342,9 +1238,8 @@ class ExternalProviderClient:
elif self.provider_type == "ollama":
_apply_ollama_reasoning_controls(body, enable_thinking, reasoning_effort)
- # OpenRouter's unified `reasoning` field gates per-model thinking.
- # Some routes (`*_MANDATORY_REASONING_MODELS`) 400 on explicit off.
- # https://openrouter.ai/docs/guides/best-practices/reasoning-tokens
+ # OpenRouter's unified `reasoning` field gates per-model thinking. Some routes
+ # (`*_MANDATORY_REASONING_MODELS`) 400 on explicit off.
if self.provider_type == "openrouter":
normalized_or_model = model.strip().lower()
if reasoning_effort in ("low", "medium", "high"):
@@ -1357,10 +1252,8 @@ class ExternalProviderClient:
else:
body["reasoning"] = {"enabled": False}
- # OpenRouter web plugin works on every model id including
- # meta-routers (unlike `:online`). Forced-function tool_choice
- # suppresses it, matching Gemini/Anthropic.
- # https://openrouter.ai/docs/guides/features/plugins/web-search
+ # OpenRouter web plugin works on every model id including meta-routers (unlike `:online`). Forced-function
+ # tool_choice suppresses it, matching Gemini/Anthropic.
_or_tool_choice_forced_function = (
isinstance(tool_choice, dict)
and tool_choice.get("type") == "function"
@@ -1382,17 +1275,15 @@ class ExternalProviderClient:
body.get("model"),
)
- # Forward OpenAI-style function tools / tool_choice on every OAI-compat
- # route (incl. custom Gemini OpenAI proxies like LiteLLM). Without
- # this, callers wiring user-defined tools silently lose
- # function-calling on non-native providers.
+ # Forward OpenAI-style function tools / tool_choice on every OAI-compat route (incl. custom Gemini OpenAI
+ # proxies like LiteLLM). Without this, callers wiring user-defined tools silently lose function-calling on
+ # non-native providers.
if tools:
body["tools"] = tools
if tool_choice is not None:
body["tool_choice"] = tool_choice
- # JSON mode / guided decoding. Every OpenAI-compatible server accepts
- # this (llama.cpp, vLLM and Ollama all implement it), and dropping it
- # silently turned a caller's structured-output request into free prose.
+ # JSON mode / guided decoding. Every OpenAI-compatible server accepts this (llama.cpp, vLLM and Ollama all
+ # implement it), and dropping it silently turned a caller's structured-output request into free prose.
if response_format is not None:
body["response_format"] = response_format
@@ -1434,17 +1325,15 @@ class ExternalProviderClient:
)
return
- # Manual __anext__ (not `async for`) so we can close the
- # response BEFORE lines_gen, avoiding the httpcore 1.0
- # GeneratorExit -> RuntimeError path on Python 3.13.
+ # Manual __anext__ (not `async for`) so we can close the response BEFORE lines_gen, avoiding the
+ # httpcore 1.0 GeneratorExit -> RuntimeError path on Python 3.13.
lines_gen = response.aiter_lines().__aiter__()
- # Diagnostic counters for the OAI-compat path; surface
- # OpenRouter mid-stream errors otherwise invisible server-side.
+ # Diagnostic counters for the OAI-compat path; surface OpenRouter mid-stream errors otherwise
+ # invisible server-side.
event_counts: dict[str, int] = {}
chosen_model: Optional[str] = None
- # OpenRouter has no web_search_call events — citations arrive
- # as url_citation annotations. Synthesise a tool_start/tool_end
- # pair to match the OpenAI/Anthropic UX.
+ # OpenRouter has no web_search_call events -- citations arrive as url_citation annotations. Synthesise
+ # a tool_start/tool_end pair to match the OpenAI/Anthropic UX.
web_search_active = (
self.provider_type == "openrouter"
and not tool_choice_disabled
@@ -1478,9 +1367,8 @@ class ExternalProviderClient:
return
if payload.get("type") != "url_citation":
return
- # OpenRouter (and OpenAI Chat Completions web_search) nest
- # the citation under url_citation; some variants ship the
- # fields flat on the annotation itself. Accept both.
+ # OpenRouter (and OpenAI Chat Completions web_search) nest the citation under url_citation; some
+ # variants ship the fields flat on the annotation itself. Accept both.
cit = payload.get("url_citation")
if not isinstance(cit, dict):
cit = payload
@@ -1537,10 +1425,8 @@ class ExternalProviderClient:
data_str = line[len("data:") :].strip()
if data_str == "[DONE]":
event_counts["done"] = event_counts.get("done", 0) + 1
- # Emit synthetic tool_end with collected
- # citations BEFORE forwarding [DONE], so the
- # tool-card transitions to "complete" before
- # the stream closes.
+ # Emit synthetic tool_end with collected citations BEFORE forwarding [DONE], so the
+ # tool card transitions to "complete" before the stream closes.
if (
web_search_active
and web_search_tool_started
@@ -1554,9 +1440,8 @@ class ExternalProviderClient:
except Exception:
parsed = None
if isinstance(parsed, dict):
- # Mid-stream provider error event. OpenRouter
- # in particular returns 200 then surfaces the
- # failure as an SSE error event.
+ # Mid-stream provider error event. OpenRouter in particular returns 200 then
+ # surfaces the failure as an SSE error event.
if "error" in parsed:
event_counts["error"] = event_counts.get("error", 0) + 1
logger.warning(
@@ -1566,19 +1451,16 @@ class ExternalProviderClient:
)
else:
event_counts["delta"] = event_counts.get("delta", 0) + 1
- # OpenRouter (and most OAI-compat providers)
- # report the handling model in every chunk's
- # `model` field. Latch the first non-empty
- # value so the router-picked model surfaces
- # in logs and reaches the proxy caller.
+ # OpenRouter (and most OAI-compat providers) report the handling model in every
+ # chunk's `model` field. Latch the first non-empty value so the router-picked
+ # model surfaces in logs and reaches the proxy caller.
if chosen_model is None and isinstance(
parsed.get("model"), str
):
chosen_model = parsed["model"]
- # With web_search on, scan every chunk's
- # delta and message objects for url_citation
- # annotations. Different OpenRouter upstreams
- # place them in different spots.
+ # With web_search on, scan every chunk's delta and message objects for
+ # url_citation annotations. Different OpenRouter upstreams place them in different
+ # spots.
if web_search_active:
choices = parsed.get("choices") or []
if isinstance(choices, list):
@@ -1593,17 +1475,15 @@ class ExternalProviderClient:
continue
for ann in envelope.get("annotations") or []:
_record_or_url_citation(ann)
- # Verbatim relay, minus Unsloth's own UI control protocol:
- # the frames this server writes to paint tool cards ride
- # the same stream, so an endpoint that echoes them forges
- # a card for a tool that never ran.
+ # Verbatim relay, minus Unsloth's own UI control protocol: the frames this server writes to
+ # paint tool cards ride the same stream, so an endpoint that echoes them forges a card for a
+ # tool that never ran.
relayed = sanitize_provider_sse_line(line)
if relayed is None:
continue
yield relayed
- # Stream ended without [DONE] (some upstreams just close
- # the connection). Emit tool_end so the card doesn't stay
- # in "running" forever.
+ # Stream ended without [DONE] (some upstreams just close the connection). Emit tool_end so the
+ # card does not stay in "running" forever.
if web_search_active and web_search_tool_started and not web_search_tool_ended:
yield _build_web_search_tool_end()
web_search_tool_ended = True
@@ -1650,44 +1530,32 @@ class ExternalProviderClient:
async def _stream_kimi_web_search(
self, messages: list[dict[str, Any]], model: str, max_tokens: Optional[int]
) -> AsyncGenerator[str, None]:
- """
- Kimi $web_search round-trip.
-
- Wire flow (per https://platform.kimi.ai/docs/guide/use-web-search):
- 1. POST messages with tools=[{type: "builtin_function",
- function: {name: "$web_search"}}] and thinking=disabled.
- 2. Stream the first response — accumulate function.arguments across
- tool_call deltas until finish_reason="tool_calls". Do NOT forward
- those tool_call chunks to the client (internal protocol step, not
- user-visible output).
- 3. Build a second request: original messages + the assistant message
- carrying the tool_calls + a role=tool message echoing the same
- arguments verbatim (per Kimi docs, the caller "just needs to
- submit tool_call.function.arguments to Kimi as they are" — the
- server actually runs the search).
- 4. Stream the second response — the final answer the user sees, with
- search results already incorporated.
-
- We synthesize tool_start (with the parsed query) when step (2)
- completes, and tool_end (with any url_citation annotations the second
- stream emits) before [DONE], so the chat UI shows the same web-search
- tool card as other providers.
+ """Kimi $web_search round-trip, per https://platform.kimi.ai/docs/guide/use-web-search: POST
+ messages with tools=[{type: "builtin_function", function: {name: "$web_search"}}] and
+ thinking=disabled; stream the first response, accumulating function.arguments across
+ tool_call deltas until finish_reason="tool_calls" and forwarding none of those chunks to the
+ client (internal protocol step, not user-visible output); build a second request of the
+ original messages plus the assistant message carrying the tool_calls plus a role=tool
+ message echoing the same arguments verbatim (the server actually runs the search); stream
+ the second response, which is the final answer with search results incorporated.
+
+ We synthesize tool_start (with the parsed query) when the first call completes, and tool_end
+ (with any url_citation annotations the second stream emits) before [DONE], so the chat UI
+ shows the same web-search tool card as other providers.
"""
url = f"{self.base_url}/chat/completions"
body: dict[str, Any] = {
"model": model,
"messages": messages,
"stream": True,
- # $web_search forbids thinking; sending the toggle would make the
- # server reject the request with 400.
+ # $web_search forbids thinking; sending the toggle would make the server reject the request with 400.
"thinking": {"type": "disabled"},
"tools": [{"type": "builtin_function", "function": {"name": "$web_search"}}],
}
if max_tokens is not None:
body["max_tokens"] = max_tokens
- # Strip body fields the Kimi registry declares unusable
- # (temperature/top_p — see body_omit in providers.py).
+ # Strip body fields the Kimi registry declares unusable (temperature/top_p -- see body_omit in providers.py).
from core.inference.providers import get_provider_info
provider_info = get_provider_info(self.provider_type) or {}
@@ -1713,7 +1581,6 @@ class ExternalProviderClient:
url,
)
- # ---- First call: collect the model's $web_search tool_call ----
tool_calls_acc: dict[int, dict[str, Any]] = {}
try:
async with _http_client.stream(
@@ -1796,9 +1663,8 @@ class ExternalProviderClient:
)
return
- # If the model decided not to search, fall back to a plain streaming
- # call without the builtin tool. Mirrors the UX of every other
- # provider when web_search is on but the model didn't need it.
+ # If the model decided not to search, fall back to a plain streaming call without the builtin tool. Mirrors
+ # the UX of every other provider when web_search is on but the model did not need it.
search_calls = [
tc for tc in tool_calls_acc.values() if tc["function"]["name"] == "$web_search"
]
@@ -1808,8 +1674,8 @@ class ExternalProviderClient:
)
fallback_body = dict(body)
fallback_body.pop("tools", None)
- # This path returns before the common body injection, and Kimi reports no
- # engine timings, so without this the row has neither tokens nor a speed.
+ # This path returns before the common body injection, and Kimi reports no engine timings, so without this
+ # the row has neither tokens nor a speed.
fallback_body["stream_options"] = {"include_usage": True}
try:
async with _http_client.stream(
@@ -1834,9 +1700,8 @@ class ExternalProviderClient:
response.headers.get("Retry-After"),
)
return
- # Manual __anext__ loop instead of `async for` — see the
- # stream_chat_completion comment for the Python 3.13 +
- # httpcore 1.0.x GeneratorExit interaction this avoids.
+ # Manual __anext__ loop instead of `async for` -- see the stream_chat_completion comment for the
+ # Python 3.13 + httpcore 1.0.x GeneratorExit interaction this avoids.
lines_gen = response.aiter_lines().__aiter__()
try:
while True:
@@ -1845,8 +1710,8 @@ class ExternalProviderClient:
except StopAsyncIteration:
break
if line.strip():
- # Same rule as the main relay: never let the
- # endpoint speak Unsloth's control vocabulary.
+ # Same rule as the main relay: never let the endpoint speak Unsloth's control
+ # vocabulary.
relayed = sanitize_provider_sse_line(line)
if relayed is not None:
yield relayed
@@ -1866,15 +1731,15 @@ class ExternalProviderClient:
)
return
- # Synthesize tool_start with the parsed search query so the chat UI's
- # web-search card shows "Searching for: ...".
+ # Synthesize tool_start with the parsed search query so the chat UI's web-search card shows "Searching for:
+ # ...".
first_args_raw = search_calls[0]["function"]["arguments"] or "{}"
try:
first_args = _json.loads(first_args_raw)
except Exception:
first_args = {}
- # Args are an opaque receipt (`{"search_result":..., "usage":{"total_tokens":N}}`),
- # not a query — Kimi runs the search server-side and bakes results into context.
+ # Args are an opaque receipt (`{"search_result":..., "usage":{"total_tokens":N}}`), not a query -- Kimi runs
+ # the search server-side and bakes results into context.
logger.info(
"Kimi $web_search: %d tool_call(s), args[0]=%s",
len(search_calls),
@@ -1895,11 +1760,10 @@ class ExternalProviderClient:
"arguments": first_args if isinstance(first_args, dict) else {},
}
)
- # The search already ran server-side, so emit tool_end now — otherwise the
- # UI card sits in "running" through the whole second-call answer.
+ # The search already ran server-side, so emit tool_end now -- otherwise the UI card sits in "running" through
+ # the whole second-call answer.
yield _build_kimi_tool_end(_synthetic_chunk, tool_call_id, [])
- # ---- Second call: echo the tool_calls back and stream answer ----
assistant_msg = {
"role": "assistant",
"content": "",
@@ -1916,8 +1780,8 @@ class ExternalProviderClient:
]
followup_body = dict(body)
followup_body["messages"] = list(messages) + [assistant_msg] + tool_msgs
- # Request a final `usage` block (OAI-compat streams omit it otherwise) so
- # we can see prompt_tokens jump when search context is injected.
+ # Request a final `usage` block (OAI-compat streams omit it otherwise) so we can see prompt_tokens jump when
+ # search context is injected.
followup_body["stream_options"] = {"include_usage": True}
# Keep the tool on the second call so the model can search again mid-turn.
@@ -1946,8 +1810,7 @@ class ExternalProviderClient:
return
lines_gen = response.aiter_lines().__aiter__()
- # Latch final usage; a big prompt_tokens is evidence the server
- # injected search results into context.
+ # Latch final usage; a big prompt_tokens is evidence the server injected search results into context.
last_usage: Optional[dict[str, Any]] = None
annotation_shapes: set[str] = set()
try:
@@ -1969,9 +1832,8 @@ class ExternalProviderClient:
usage = parsed.get("usage")
if isinstance(usage, dict):
last_usage = usage
- # Scan annotations for diagnostics only; Kimi
- # doesn't emit url_citation today, but a future
- # version's type name would show in the log.
+ # Scan annotations for diagnostics only; Kimi does not emit url_citation today,
+ # but a future version's type name would show in the log.
for choice in parsed.get("choices") or []:
if not isinstance(choice, dict):
continue
@@ -1986,8 +1848,7 @@ class ExternalProviderClient:
annotation_shapes.add(
str(ann.get("type") or "?")
)
- # Same rule as the main relay: never let the endpoint
- # speak Unsloth's control vocabulary.
+ # Same rule as the main relay: never let the endpoint speak Unsloth's control vocabulary.
relayed = sanitize_provider_sse_line(line)
if relayed is None:
continue
@@ -2036,15 +1897,9 @@ class ExternalProviderClient:
*,
fast_mode: Optional[bool] = None,
) -> AsyncGenerator[str, None]:
- """
- Call the Anthropic Messages API and translate its SSE to OpenAI format.
-
- Anthropic SSE event types:
- content_block_delta → OpenAI chunk with delta.content
- message_delta → OpenAI chunk with finish_reason
- message_stop → data: [DONE]
- (all others skipped)
- """
+ """Call the Anthropic Messages API and translate its SSE to OpenAI format:
+ content_block_delta -> chunk with delta.content, message_delta -> chunk with
+ finish_reason, message_stop -> data: [DONE], all others skipped."""
import json as _json
# Extract system prompt; translate image_url parts to Anthropic format
@@ -2061,11 +1916,9 @@ class ExternalProviderClient:
continue
content = msg.get("content")
- # OpenAI role="tool" with list content -> Anthropic native
- # tool_result block on a user message. Translating only in the
- # string-content branch (below) would forward the list-content form
- # as an invalid `role:"tool"` message Anthropic rejects. Handle both
- # upfront.
+ # OpenAI role="tool" with list content -> Anthropic native tool_result block on a user message.
+ # Translating only in the string-content branch below would forward the list-content form as an invalid
+ # `role:"tool"` message Anthropic rejects, so handle both upfront.
if msg.get("role") == "tool":
_tr_id = msg.get("tool_call_id") or ""
if isinstance(content, list):
@@ -2098,20 +1951,16 @@ class ExternalProviderClient:
)
continue
if isinstance(content, list):
- # Translate OpenAI multimodal parts -> Anthropic native shapes.
- # - `image_url` -> `{type:"image", source:...}`
- # - `input_document` -> `{type:"document", source:...}`
- # (Unsloth extension; mirrors Anthropic's document block,
- # which supports PDFs as base64 or URL per
- # https://platform.claude.com/docs/en/build-with-claude/vision)
+ # Translate OpenAI multimodal parts -> Anthropic native shapes: `image_url` -> `{type:"image",
+ # source:...}`, and `input_document` -> `{type:"document", source:...}` (an Unsloth extension
+ # mirroring Anthropic's document block, which supports PDFs as base64 or URL).
anthropic_parts: list[dict[str, Any]] = []
for part in content:
if part.get("type") == "text" and _anthropic_text_is_sendable(part.get("text")):
anthropic_parts.append({"type": "text", "text": part["text"]})
elif part.get("type") == "compaction":
- # Round-trip a prior turn's compaction block back onto this
- # assistant message so Anthropic skips re-compaction. Ref:
- # https://platform.claude.com/docs/en/build-with-claude/compaction
+ # Round-trip a prior turn's compaction block back onto this assistant message so Anthropic
+ # skips re-compaction.
summary = part.get("content") or ""
if isinstance(summary, str) and summary:
anthropic_parts.append({"type": "compaction", "content": summary})
@@ -2133,7 +1982,6 @@ class ExternalProviderClient:
)
else:
# Remote URL -- Anthropic supports the url source type natively.
- # See: https://docs.anthropic.com/en/docs/build-with-claude/vision#url-based-images
anthropic_parts.append(
{
"type": "image",
@@ -2144,13 +1992,13 @@ class ExternalProviderClient:
}
)
elif part.get("type") == "input_document":
- # Unsloth's normalised PDF/doc type (file_data data-URI or
- # file_url) -> Anthropic's native `document` block.
+ # Unsloth's normalised PDF/doc type (file_data data-URI or file_url) -> Anthropic's native
+ # `document` block.
url = part.get("file_url") or ""
data_uri = part.get("file_data") or ""
title = part.get("filename")
- # Treat a "data:" URI with no base64 payload as missing so
- # the file_url branch can take over (matches OpenAI side).
+ # Treat a "data:" URI with no base64 payload as missing so the file_url branch can take over
+ # (matches the OpenAI side).
data_uri_valid = False
b64data = ""
header = ""
@@ -2170,10 +2018,8 @@ class ExternalProviderClient:
"media_type": media_type,
"data": b64data,
},
- # Opt into Anthropic's natural-citation
- # pipeline; without this no citations_delta
- # events fire. See
- # https://platform.claude.com/docs/en/build-with-claude/citations
+ # Opt into Anthropic's natural-citation pipeline; without this no citations_delta
+ # events fire.
"citations": {"enabled": True},
}
if title:
@@ -2191,10 +2037,9 @@ class ExternalProviderClient:
if title:
doc_block["title"] = title
anthropic_parts.append(doc_block)
- # Assistant tool_calls -> Anthropic tool_use blocks appended to
- # the same message. The native Messages API doesn't accept
- # OpenAI's top-level `tool_calls` field; the call lives inside a
- # content block `{type:"tool_use", id, name, input}`.
+ # Assistant tool_calls -> Anthropic tool_use blocks appended to the same message: the native Messages
+ # API does not accept OpenAI's top-level `tool_calls` field, the call lives inside a content block
+ # `{type:"tool_use", id, name, input}`.
if msg.get("role") == "assistant" and isinstance(msg.get("tool_calls"), list):
for _tc in msg["tool_calls"]:
if not isinstance(_tc, dict):
@@ -2217,16 +2062,14 @@ class ExternalProviderClient:
"input": _input,
}
)
- # Skip whole-message append when nothing usable survived. An
- # empty content array (e.g. user dropped only an unparseable
- # `input_document`) would 400 with "messages.N.content: at
- # least one block is required".
+ # Skip whole-message append when nothing usable survived. An empty content array (e.g. user dropped
+ # only an unparseable `input_document`) would 400 with "messages.N.content: at least one block is
+ # required".
if anthropic_parts:
filtered.append({"role": msg["role"], "content": anthropic_parts})
else:
- # role="tool" follow-up -> Anthropic native tool_result block
- # on a `user` message. The OpenAI shape (role=tool,
- # content=string, tool_call_id) is not a valid Anthropic role.
+ # role="tool" follow-up -> Anthropic native tool_result block on a `user` message. The OpenAI shape
+ # (role=tool, content=string, tool_call_id) is not a valid Anthropic role.
if msg.get("role") == "tool":
_tr_id = msg.get("tool_call_id") or ""
_tr_content = msg.get("content")
@@ -2249,10 +2092,9 @@ class ExternalProviderClient:
}
)
continue
- # Assistant turn whose content is a plain string but also
- # carries OpenAI `tool_calls`: convert into a content-array
- # message with a text block + tool_use blocks. Without this,
- # the top-level tool_calls leaks through unchanged.
+ # Assistant turn whose content is a plain string but also carries OpenAI `tool_calls`: convert into a
+ # content-array message with a text block + tool_use blocks, else the top-level tool_calls leaks
+ # through unchanged.
if (
msg.get("role") == "assistant"
and isinstance(msg.get("tool_calls"), list)
@@ -2293,9 +2135,8 @@ class ExternalProviderClient:
continue
filtered.append(msg)
- # Newer Claude models removed temperature/top_p/top_k entirely (400
- # "deprecated for this model"). Reuse the capability wherever those
- # fields are set, including the thinking-mode temperature override.
+ # Newer Claude models removed temperature/top_p/top_k entirely (400 "deprecated for this model"). Reuse the
+ # capability wherever those fields are set, including the thinking-mode temperature override.
sampling_removed = _anthropic_sampling_params_removed(model)
body: dict[str, Any] = {
@@ -2308,11 +2149,11 @@ class ExternalProviderClient:
body["temperature"] = temperature
if top_k is not None and top_k > 0 and not sampling_removed:
body["top_k"] = top_k
- # Anthropic caches a prefix only with a cache_control marker. Treat None
- # as True (frontend default); pass False to opt out.
+ # Anthropic caches a prefix only with a cache_control marker. Treat None as True (frontend default); pass
+ # False to opt out.
prompt_caching_enabled = enable_prompt_caching is not False
- # Optional 1h cache TTL is GA (no beta header). 1h writes cost 2x vs 5m's
- # 1.25x but reads are 0.1x for both, so 1h wins after one extra hit.
+ # Optional 1h cache TTL is GA (no beta header). 1h writes cost 2x vs 5m's 1.25x but reads are 0.1x for both,
+ # so 1h wins after one extra hit.
cache_marker: dict[str, Any] = {"type": "ephemeral"}
if prompt_cache_ttl in ("5m", "1h"):
cache_marker["ttl"] = prompt_cache_ttl
@@ -2331,10 +2172,9 @@ class ExternalProviderClient:
body["system"] = system
if prompt_caching_enabled and filtered:
- # Second breakpoint on the latest message so turn N+1 rehydrates
- # through turn N from cache. Covers the case where the system prompt
- # is below Anthropic's ~1024-token cache floor. (Max 4 breakpoints;
- # we use 2: system + tail.)
+ # Second breakpoint on the latest message so turn N+1 rehydrates through turn N from cache. Covers the
+ # case where the system prompt is below Anthropic's ~1024-token cache floor. (Max 4 breakpoints; we use 2:
+ # system + tail.)
last_msg = filtered[-1]
content = last_msg.get("content")
if isinstance(content, str):
@@ -2346,8 +2186,7 @@ class ExternalProviderClient:
}
]
elif isinstance(content, list) and content:
- # Rebuild the tail (don't mutate the caller's list) with
- # cache_control on the final block.
+ # Rebuild the tail (do not mutate the caller's list) with cache_control on the final block.
head = list(content[:-1])
tail = content[-1]
if isinstance(tail, dict):
@@ -2360,8 +2199,8 @@ class ExternalProviderClient:
thinking_spec.efforts if thinking_spec else ("none", "low", "medium", "high")
)
effort = reasoning_effort if reasoning_effort in allowed_efforts else None
- # Claude 4.6 takes top-tier adaptive effort as "max" only ("xhigh" is
- # 4.7-only), so map "xhigh" -> "max" for 4.6 outbound requests.
+ # Claude 4.6 takes top-tier adaptive effort as "max" only ("xhigh" is 4.7-only), so map "xhigh" -> "max" for
+ # 4.6 outbound requests.
if effort == "xhigh" and model.startswith(("claude-opus-4-6", "claude-sonnet-4-6")):
effort = "max"
if effort is None:
@@ -2369,9 +2208,8 @@ class ExternalProviderClient:
effort = "none"
elif enable_thinking is True:
effort = "medium"
- # Models that think by default need an explicit disable; omitting the
- # field leaves thinking on. Anthropic only accepts it at effort <= high,
- # so send it alone (server default effort is high).
+ # Models that think by default need an explicit disable; omitting the field leaves thinking on. Anthropic only
+ # accepts it at effort <= high, so send it alone (server default effort is high).
if (
effort == "none"
and thinking_spec
@@ -2379,26 +2217,22 @@ class ExternalProviderClient:
and thinking_spec.can_disable
):
body["thinking"] = {"type": "disabled"}
- # Normalize one semantic Thinking control into Anthropic's two model-era
- # APIs: adaptive effort on Claude 4.6+, manual budget_tokens on 4.5.
+ # Normalize one semantic Thinking control into Anthropic's two model-era APIs: adaptive effort on Claude 4.6+,
+ # manual budget_tokens on 4.5.
if effort and effort != "none":
# Anthropic rejects top_k whenever thinking is enabled.
body.pop("top_k", None)
- # 4.5/4.6 require temperature=1 with thinking and forbid top_p in the
- # same request; 4.7 removed temperature entirely (any value 400s), so
- # skip the override there.
+ # 4.5/4.6 require temperature=1 with thinking and forbid top_p in the same request; 4.7 removed
+ # temperature entirely (any value 400s), so skip the override there.
if not sampling_removed:
body["temperature"] = 1
body.pop("top_p", None)
if thinking_spec and thinking_spec.kind == "adaptive":
- # Force display="summarized": it defaults to "omitted" on Opus 4.7,
- # which emits an empty thinking block and leaves the panel blank.
- # Harmless no-op on 4.6.
+ # Force display="summarized": it defaults to "omitted" on Opus 4.7, which emits an empty thinking
+ # block and leaves the panel blank. Harmless no-op on 4.6.
body["thinking"] = {"type": "adaptive", "display": "summarized"}
- # Adaptive effort lives under `output_config.effort`, not top-level
- # (top-level 400s "Extra inputs are not permitted"). Allowed:
- # low|medium|high|xhigh|max. See
- # https://platform.claude.com/docs/en/api/messages
+ # Adaptive effort lives under `output_config.effort`, not top-level (top-level 400s "Extra inputs are
+ # not permitted"). Allowed: low|medium|high|xhigh|max.
body["output_config"] = {"effort": effort}
elif thinking_spec and thinking_spec.kind == "manual":
budget_tokens = {"low": 1024, "medium": 2048, "high": 4096}[effort]
@@ -2406,13 +2240,13 @@ class ExternalProviderClient:
"type": "enabled",
"budget_tokens": budget_tokens,
}
- # Anthropic requires max_tokens to be strictly greater than
- # thinking.budget_tokens on the manual-thinking path.
+ # Anthropic requires max_tokens to be strictly greater than thinking.budget_tokens on the
+ # manual-thinking path.
if body.get("max_tokens", 0) <= budget_tokens:
body["max_tokens"] = budget_tokens + 1024
- # tool_choice="none" or pinned-function suppresses hosted tools so a
- # stale UI toggle can't fire server-side search/code-exec.
+ # tool_choice="none" or pinned-function suppresses hosted tools so a stale UI toggle cannot fire server-side
+ # search/code-exec.
_anthropic_tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
@@ -2427,7 +2261,6 @@ class ExternalProviderClient:
)
# Anthropic web_search (date-pinned per model family).
- # https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool
if _anthropic_hosted_builtins_allowed and enabled_tools and "web_search" in enabled_tools:
anthropic_tools = list(body.get("tools") or [])
anthropic_tools.append(
@@ -2440,7 +2273,6 @@ class ExternalProviderClient:
body["tools"] = anthropic_tools
# Anthropic web_fetch: only URLs already in conversation. Date-pinned.
- # https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool
web_fetch_enabled = bool(
_anthropic_hosted_builtins_allowed and enabled_tools and "web_fetch" in enabled_tools
)
@@ -2455,9 +2287,8 @@ class ExternalProviderClient:
)
body["tools"] = anthropic_tools
- # Anthropic server-side code execution (date-pinned type per model, both
- # unlocked by the same beta header set below). See
- # https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
+ # Anthropic server-side code execution (date-pinned type per model, both unlocked by the same beta header set
+ # below).
code_execution_enabled = bool(
_anthropic_hosted_builtins_allowed
and enabled_tools
@@ -2472,14 +2303,13 @@ class ExternalProviderClient:
}
)
body["tools"] = anthropic_tools
- # Reuse the thread's prior container so filesystem state persists.
- # Stale ids 4xx and clear via container_invalidated.
+ # Reuse the thread's prior container so filesystem state persists. Stale ids 4xx and clear via
+ # container_invalidated.
if anthropic_code_exec_container_id:
body["container"] = anthropic_code_exec_container_id
- # Server-side compaction (beta `compact-2026-01-12`). Clamps below-min
- # thresholds to 50K so the request doesn't 400.
- # https://platform.claude.com/docs/en/build-with-claude/compaction
+ # Server-side compaction (beta `compact-2026-01-12`). Clamps below-min thresholds to 50K so the request does
+ # not 400.
compaction_active = (
compaction_threshold is not None
and compaction_threshold > 0
@@ -2502,9 +2332,8 @@ class ExternalProviderClient:
]
}
- # fast_mode is Opus 5 / 4.8 only; silently drop elsewhere. Incompatible
- # with the Priority service_tier (frontend gate prevents both at once;
- # backend lets Anthropic 400 if combined).
+ # fast_mode is Opus 5 / 4.8 only; silently drop elsewhere. Incompatible with the Priority service_tier (the
+ # frontend gate prevents both at once; the backend lets Anthropic 400 if combined).
fast_mode_active = bool(fast_mode) and _anthropic_supports_fast_mode(model)
if fast_mode_active:
body["speed"] = "fast"
@@ -2512,8 +2341,7 @@ class ExternalProviderClient:
url = f"{self.base_url}/messages"
completion_id = f"chatcmpl-anthropic-{model.replace('/', '-')}"
- # Log outgoing config keys (not messages) to prove which thinking /
- # effort fields reached the wire.
+ # Log outgoing config keys (not messages) to prove which thinking / effort fields reached the wire.
logger.info(
"Anthropic request shape (model=%s, has_thinking=%s, thinking=%s, "
"output_config=%s, temperature=%s, has_top_p=%s, has_top_k=%s, "
@@ -2528,10 +2356,8 @@ class ExternalProviderClient:
body.get("max_tokens"),
)
- # Anthropic stop_reason -> OpenAI finish_reason. `pause_turn` maps to
- # None so the UI doesn't treat a paused server-tool turn as final.
- # `refusal` -> "content_filter" (closest match).
- # https://platform.claude.com/docs/en/api/messages#response-stop-reason
+ # Anthropic stop_reason -> OpenAI finish_reason. `pause_turn` maps to None so the UI does not treat a paused
+ # server-tool turn as final; `refusal` -> "content_filter" (closest match).
_finish_reason_map: dict[str, Optional[str]] = {
"end_turn": "stop",
"max_tokens": "length",
@@ -2575,11 +2401,9 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- # Stale container detection (mirrors the OpenAI path). When
- # we sent a `container` field and the response is 4xx hinting
- # the id is expired / missing, emit container_invalidated so
- # the chat adapter clears the stored id and the next turn
- # falls back to auto-create.
+ # Stale container detection (mirrors the OpenAI path). When we sent a `container` field and the
+ # response is 4xx hinting the id is expired / missing, emit container_invalidated so the chat
+ # adapter clears the stored id and the next turn falls back to auto-create.
if anthropic_code_exec_container_id and 400 <= response.status_code < 500:
lowered = error_text.lower()
if "container" in lowered and (
@@ -2604,59 +2428,47 @@ class ExternalProviderClient:
# NOTE: same manual __anext__ loop as stream_chat_completion — see comment there.
lines_gen = response.aiter_lines().__aiter__()
thinking_open = False
- # Diagnostic counters for "no thinking content" reports —
- # distinguish "Anthropic never sent thinking_delta" from
- # "frontend didn't render the chunks".
+ # Diagnostic counters for "no thinking content" reports -- distinguish "Anthropic never sent
+ # thinking_delta" from "frontend did not render the chunks".
event_counts: dict[str, int] = {}
- # web_search state. Query streams via input_json_delta on a
- # server_tool_use block; results land in a separate
- # web_search_tool_result block. Per-call citations.
+ # web_search state. Query streams via input_json_delta on a server_tool_use block; results land in a
+ # separate web_search_tool_result block. Per-call citations.
current_server_tool_use: Optional[dict[str, Any]] = None
current_result_block: Optional[dict[str, Any]] = None
web_search_calls: dict[str, dict[str, Any]] = {}
- # code_execution state (bash / text_editor sub-tools); kept
- # parallel to web_search so concurrent pills don't collide.
+ # code_execution state (bash / text_editor sub-tools); kept parallel to web_search so concurrent pills
+ # do not collide.
current_code_exec_use: Optional[dict[str, Any]] = None
current_code_exec_result: Optional[dict[str, Any]] = None
code_execution_calls: dict[str, dict[str, Any]] = {}
- # web_fetch state. Same server_tool_use → *_tool_result block
- # shape as web_search but server_tool_use carries
- # name="web_fetch" and the result block is
- # `web_fetch_tool_result` with content.type=`web_fetch_result`
- # (success) or `web_fetch_tool_error` (failure). Kept separate
- # from web_search state so a turn using both doesn't collide.
+ # web_fetch state. Same server_tool_use -> *_tool_result shape as web_search but server_tool_use
+ # carries name="web_fetch" and the result block is `web_fetch_tool_result` with
+ # content.type=`web_fetch_result` (success) or `web_fetch_tool_error` (failure). Kept separate from
+ # web_search state so a turn using both does not collide.
current_web_fetch_use: Optional[dict[str, Any]] = None
current_web_fetch_result: Optional[dict[str, Any]] = None
web_fetch_calls: dict[str, dict[str, Any]] = {}
- # Compaction state. Server-side compaction emits a
- # `{type:"compaction", content:"..."}` content block whenever it
- # runs. The summary text can land on the start event AND/OR via
- # text_delta events on the same block (Anthropic's wire format
- # is permissive). Accumulate in `current_compaction["content"]`
- # and emit on content_block_stop so the chat-adapter can persist
- # it onto the assistant message for next-turn round-tripping.
+ # Compaction state. Server-side compaction emits a `{type:"compaction", content:"..."}` content block
+ # whenever it runs, and the summary text can land on the start event AND/OR via text_delta events on
+ # the same block. Accumulate in `current_compaction["content"]` and emit on content_block_stop so the
+ # chat adapter can persist it onto the assistant message for next-turn round-tripping.
current_compaction: Optional[dict[str, Any]] = None
compaction_blocks_seen = 0
- # Document citations from ``citations_delta`` events. Deduped by
- # type-specific anchor key; inline [N] is injected after each
- # cited run, and the full list is forwarded as a synthetic
- # document_citations tool_event on message_stop for the Sources
- # panel.
+ # Document citations from ``citations_delta`` events. Deduped by type-specific anchor key; inline [N]
+ # is injected after each cited run, and the full list is forwarded as a synthetic document_citations
+ # tool_event on message_stop for the Sources panel.
document_citations: list[dict[str, Any]] = []
- # Surfaced in the final log line. generated_files_count tracks
- # file_id entries on bash_code_execution_result.content that v1
- # drops, to gauge how often the future Files API PR would matter.
+ # Surfaced in the final log line. generated_files_count tracks file_id entries on
+ # bash_code_execution_result.content that v1 drops, to gauge how often the future Files API PR would
+ # matter.
code_execution_generated_files = 0
- # Container id captured from `message_start.message.container.id`
- # when code_execution is enabled. Emit a `container_ready`
- # _toolEvent on first sight so the chat adapter persists it
- # on the thread record. Only emitted when the value differs
- # from the inbound id — no churn on reuse.
+ # Container id captured from `message_start.message.container.id` when code_execution is enabled. Emit
+ # a `container_ready` _toolEvent on first sight so the chat adapter persists it on the thread record,
+ # and only when the value differs from the inbound id, so reuse causes no churn.
latched_container_id: Optional[str] = None
container_id_emitted = False
- # Cache usage from message_start (cache_creation/read_input_tokens)
- # and message_delta (output_tokens), logged on stream complete so
- # caching is verifiable per-request without the dashboard.
+ # Cache usage from message_start (cache_creation/read_input_tokens) and message_delta (output_tokens),
+ # logged on stream complete so caching is verifiable per-request without the dashboard.
last_usage: dict[str, Any] = {}
def _content_chunk(text: str) -> str:
@@ -2704,20 +2516,14 @@ class ExternalProviderClient:
return "\n---\n".join(blocks)
def _format_web_fetch_result(inner: dict[str, Any]) -> str:
- """Render a `web_fetch_tool_result.content` payload as the
- Title / URL / snippet block CodeExecutionToolUI and
- parseSourcesFromResult expect from the web_search path.
-
- Success shape (text):
- {type: web_fetch_result, url, retrieved_at,
- content: {type: document, source: {type: text,
- media_type, data}, title?}}
- Success shape (pdf): source.type=base64 + media_type=
- application/pdf. We don't surface the base64 bytes; the
- title + url is enough for the source pill, and the model
- still sees the document contents.
- Error shape: {type: web_fetch_tool_error, error_code}.
- """
+ """Render a `web_fetch_tool_result.content` payload as the Title / URL / snippet
+ block CodeExecutionToolUI and parseSourcesFromResult expect from the
+ web_search path. Success (text): {type: web_fetch_result, url, retrieved_at,
+ content: {type: document, source: {type: text, media_type, data}, title?}}.
+ Success (pdf): source.type=base64 + media_type=application/pdf, whose base64
+ bytes are not surfaced -- title + url is enough for the source pill and the
+ model still sees the document. Error: {type: web_fetch_tool_error,
+ error_code}."""
inner_type = inner.get("type") or ""
if inner_type == "web_fetch_tool_error":
return f"Error: {inner.get('error_code', 'unknown')}"
@@ -2731,15 +2537,13 @@ class ExternalProviderClient:
if isinstance(source, dict):
media_type = source.get("media_type") or ""
data = source.get("data") or ""
- # Inline a short text preview so the source pill
- # carries usable context; skip for PDFs (body is
- # base64-encoded).
+ # Inline a short text preview so the source pill carries usable context; skip for PDFs
+ # (body is base64-encoded).
if media_type.startswith("text/") and isinstance(data, str) and data:
snippet = data[:240].strip()
- # Frontend parseSourcesFromResult only emits a source pill
- # when both `Title:` and `URL:` are present, so fall back to
- # the URL when Anthropic omits the document title (matches
- # the web_search formatter).
+ # Frontend parseSourcesFromResult only emits a source pill when both `Title:` and `URL:` are
+ # present, so fall back to the URL when Anthropic omits the document title (matches the web_search
+ # formatter).
if not title and url:
title = url
parts: list[str] = []
@@ -2752,12 +2556,9 @@ class ExternalProviderClient:
return "\n".join(parts) if parts else "(fetch complete)"
def _format_code_execution_result(inner: dict[str, Any]) -> str:
- """Render an Anthropic code-execution result block as the
- preformatted text payload the frontend's
- CodeExecutionToolUI displays inside a <pre>. Handles bash,
- text_editor (view/create/str_replace), and the matching
- error variants.
- """
+ """Render an Anthropic code-execution result block as the preformatted text
+ payload the frontend's CodeExecutionToolUI displays inside a <pre>. Handles
+ bash, text_editor (view/create/str_replace), and the matching error variants."""
inner_type = inner.get("type") or ""
if inner_type.endswith("_error"):
return f"Error: {inner.get('error_code', 'unknown')}"
@@ -2774,11 +2575,9 @@ class ExternalProviderClient:
parts.append(f"return_code: {return_code}")
return "\n".join(parts) if parts else "(no output)"
if inner_type == "text_editor_code_execution_result":
- # view: file content; create: is_file_update flag;
- # str_replace: diff `lines` list. The matching
- # server_tool_use carries the command + path, already
- # encoded into tool_start arguments — here we only
- # format the result body.
+ # view: file content; create: is_file_update flag; str_replace: diff `lines` list. The
+ # matching server_tool_use carries the command + path, already encoded into tool_start
+ # arguments -- here we only format the result body.
if "lines" in inner and isinstance(inner.get("lines"), list):
return "\n".join(str(line) for line in inner["lines"])
if "is_file_update" in inner:
@@ -2817,8 +2616,8 @@ class ExternalProviderClient:
key = event_type or "<unknown>"
event_counts[key] = event_counts.get(key, 0) + 1
- # Merge input-side usage from message_start with
- # message_delta's output_tokens into last_usage.
+ # Merge input-side usage from message_start with message_delta's output_tokens into
+ # last_usage.
if event_type == "message_start":
start_usage = (event.get("message") or {}).get("usage")
if isinstance(start_usage, dict):
@@ -2842,10 +2641,8 @@ class ExternalProviderClient:
}
elif block_type == "web_search_tool_result":
tool_use_id = content_block.get("tool_use_id", "")
- # Anthropic sometimes ships the full results list
- # on the start event; sometimes deltas follow.
- # Capture whatever is present and finalize on
- # content_block_stop.
+ # Anthropic sometimes ships the full results list on the start event and sometimes
+ # deltas follow. Capture whatever is present and finalize on content_block_stop.
content = content_block.get("content") or []
current_result_block = {
"tool_use_id": tool_use_id,
@@ -2894,9 +2691,8 @@ class ExternalProviderClient:
"bash_code_execution_tool_result",
"text_editor_code_execution_tool_result",
):
- # Code-exec result content arrives whole on the
- # start event; finalize on content_block_stop to
- # match the web_search ordering.
+ # Code-exec result content arrives whole on the start event; finalize on
+ # content_block_stop to match the web_search ordering.
tool_use_id = content_block.get("tool_use_id", "")
inner = content_block.get("content") or {}
current_code_exec_result = {
@@ -2904,8 +2700,7 @@ class ExternalProviderClient:
"inner": inner if isinstance(inner, dict) else {},
}
elif block_type == "compaction":
- # Summary may arrive on start AND/OR via
- # text_delta. Capture both; emit on stop.
+ # Summary may arrive on start AND/OR via text_delta. Capture both; emit on stop.
seed = content_block.get("content") or ""
current_compaction = {
"content": seed if isinstance(seed, str) else "",
@@ -2924,31 +2719,26 @@ class ExternalProviderClient:
yield _content_chunk(thinking_text)
elif delta_type == "text_delta":
text = delta.get("text", "")
- # text_deltas inside a compaction block carry
- # summary chunks; route them into the compaction
- # buffer and DON'T yield them to the
- # user-visible stream -- the summary is opaque
- # internal state, not assistant prose.
+ # text_deltas inside a compaction block carry summary chunks; route them into the
+ # compaction buffer and do NOT yield them to the user-visible stream -- the summary is
+ # opaque internal state, not assistant prose.
if current_compaction is not None:
if text:
current_compaction["content"] += text
else:
- # First text after a thinking block closes the
- # <think> tag opened above. Anthropic emits a
- # content_block_stop between blocks, but
- # closing on the text_delta transition is more
- # forgiving if events arrive out of order.
+ # First text after a thinking block closes the <think> tag opened above. Anthropic
+ # emits a content_block_stop between blocks, but closing on the text_delta
+ # transition is more forgiving if events arrive out of order.
if thinking_open:
yield _content_chunk("</think>")
thinking_open = False
if text:
yield _content_chunk(text)
- # web_search citations: web_search_tool_result.
- # User-doc citations: citations_delta below.
+ # web_search citations: web_search_tool_result. User-doc citations:
+ # citations_delta below.
elif delta_type == "citations_delta":
- # One citation per event; collapse onto a numbered
- # footnote list and inject [N] inline. See
- # https://platform.claude.com/docs/en/build-with-claude/citations
+ # One citation per event; collapse onto a numbered footnote list and inject [N]
+ # inline.
cit = delta.get("citation")
if isinstance(cit, dict):
key = _anthropic_citation_key(cit)
@@ -2962,9 +2752,8 @@ class ExternalProviderClient:
idx_for_marker = len(document_citations)
yield _content_chunk(f"[{idx_for_marker}]")
elif delta_type == "input_json_delta":
- # partial_json carrying tool inputs (web_search
- # query, code-exec command, etc.); route to
- # whichever buffer is open.
+ # partial_json carrying tool inputs (web_search query, code-exec command, etc.); route
+ # to whichever buffer is open.
partial = delta.get("partial_json", "")
if current_server_tool_use is not None:
current_server_tool_use["buffer"] += partial
@@ -2972,17 +2761,14 @@ class ExternalProviderClient:
current_code_exec_use["buffer"] += partial
elif current_web_fetch_use is not None:
current_web_fetch_use["buffer"] += partial
- # signature_delta and other delta types are skipped
- # — they carry trust / verification metadata, not
- # user-visible content.
+ # signature_delta and other delta types are skipped -- they carry trust / verification
+ # metadata, not user-visible content.
elif event_type == "content_block_stop":
if current_server_tool_use is not None:
- # End of the server_tool_use block — parse the
- # accumulated input_json into a query and emit
- # tool_start. The matching tool_end fires later
- # when the web_search_tool_result block closes
- # with the actual results.
+ # End of the server_tool_use block -- parse the accumulated input_json into a query
+ # and emit tool_start. The matching tool_end fires later when the
+ # web_search_tool_result block closes with the actual results.
buffer = current_server_tool_use["buffer"]
query = ""
if buffer:
@@ -3007,10 +2793,9 @@ class ExternalProviderClient:
)
current_server_tool_use = None
elif current_result_block is not None:
- # End of a web_search_tool_result — emit tool_end
- # carrying the search results as Title:/URL:
- # blocks. The frontend's parseSourcesFromResult
- # lifts these into source pills at message tail.
+ # End of a web_search_tool_result -- emit tool_end carrying the search results as
+ # Title:/URL: blocks. The frontend's parseSourcesFromResult lifts these into source
+ # pills at message tail.
tool_use_id = current_result_block["tool_use_id"]
results = current_result_block["results"]
if tool_use_id in web_search_calls:
@@ -3025,11 +2810,9 @@ class ExternalProviderClient:
)
current_result_block = None
elif current_code_exec_use is not None:
- # End of a code-execution server_tool_use — parse
- # the buffered input_json into a {command, path,
- # ...} dict and emit tool_start. The matching
- # tool_end fires on the result block's
- # content_block_stop.
+ # End of a code-execution server_tool_use -- parse the buffered input_json into a
+ # {command, path, ...} dict and emit tool_start. The matching tool_end fires on the
+ # result block's content_block_stop.
buffer = current_code_exec_use["buffer"]
parsed_args: dict[str, Any] = {}
if buffer:
@@ -3054,9 +2837,8 @@ class ExternalProviderClient:
)
current_code_exec_use = None
elif current_compaction is not None:
- # End of a compaction block: emit a synthetic
- # tool_event so the chat-adapter persists it onto
- # the assistant message for next-turn round-trip.
+ # End of a compaction block: emit a synthetic tool_event so the chat adapter persists
+ # it onto the assistant message for next-turn round-trip.
compaction_blocks_seen += 1
yield _emit_tool_event(
{
@@ -3066,13 +2848,11 @@ class ExternalProviderClient:
)
current_compaction = None
elif current_code_exec_result is not None:
- # End of a code-execution result block — format
- # the inner result into the text payload
- # CodeExecutionToolUI renders.
+ # End of a code-execution result block -- format the inner result into the text
+ # payload CodeExecutionToolUI renders.
tool_use_id = current_code_exec_result["tool_use_id"]
inner = current_code_exec_result["inner"]
- # Track generated-file count for the follow-up
- # Files API PR. v1 drops them.
+ # Track generated-file count for the follow-up Files API PR. v1 drops them.
if isinstance(inner, dict):
file_blocks = inner.get("content")
if isinstance(file_blocks, list):
@@ -3093,11 +2873,9 @@ class ExternalProviderClient:
)
current_code_exec_result = None
elif current_web_fetch_use is not None:
- # End of the web_fetch server_tool_use — parse the
- # buffered input_json into the URL the model asked
- # Anthropic to fetch and emit tool_start. The
- # matching tool_end fires on the result block's
- # content_block_stop just below.
+ # End of the web_fetch server_tool_use -- parse the buffered input_json into the URL
+ # the model asked Anthropic to fetch and emit tool_start. The matching tool_end fires
+ # on the result block's content_block_stop just below.
buffer = current_web_fetch_use["buffer"]
url = ""
if buffer:
@@ -3126,8 +2904,7 @@ class ExternalProviderClient:
)
current_web_fetch_use = None
elif current_web_fetch_result is not None:
- # End of the web_fetch_tool_result — format the
- # source pill and emit tool_end.
+ # End of the web_fetch_tool_result -- format the source pill and emit tool_end.
tool_use_id = current_web_fetch_result["tool_use_id"]
result_text = _format_web_fetch_result(
current_web_fetch_result["inner"]
@@ -3143,10 +2920,8 @@ class ExternalProviderClient:
)
current_web_fetch_result = None
elif thinking_open:
- # Close the <think> tag when the thinking block
- # ends, in case no text_delta follows (e.g.
- # display=omitted on Claude 4.7, or
- # thinking-only turns).
+ # Close the <think> tag when the thinking block ends, in case no text_delta follows
+ # (e.g. display=omitted on Claude 4.7, or thinking-only turns).
yield _content_chunk("</think>")
thinking_open = False
@@ -3154,8 +2929,7 @@ class ExternalProviderClient:
delta_usage = event.get("usage")
if isinstance(delta_usage, dict):
last_usage.update(delta_usage)
- # Compaction iterations aren't in top-level
- # input/output_tokens; fold them into
+ # Compaction iterations are not in top-level input/output_tokens; fold them into
# compaction_{input,output}_tokens for billing.
iterations = delta_usage.get("iterations")
if isinstance(iterations, list):
@@ -3168,10 +2942,9 @@ class ExternalProviderClient:
if c_in or c_out:
last_usage["compaction_input_tokens"] = c_in
last_usage["compaction_output_tokens"] = c_out
- # Container id is on message_delta.delta.container
- # (not message_start; not provisioned yet there).
- # Emit container_ready only when it differs from the
- # inbound id so reuse doesn't re-write it every turn.
+ # Container id is on message_delta.delta.container (not message_start; not provisioned yet
+ # there). Emit container_ready only when it differs from the inbound id so reuse does not
+ # re-write it every turn.
delta_obj = event.get("delta") or {}
container_obj = delta_obj.get("container")
if isinstance(container_obj, dict) and latched_container_id is None:
@@ -3195,10 +2968,8 @@ class ExternalProviderClient:
if thinking_open:
yield _content_chunk("</think>")
thinking_open = False
- # `pause_turn` is in-progress, not terminal: the
- # SSE stream still ends with [DONE] via
- # message_stop but we skip emitting a
- # finish_reason="stop" chunk that would truncate
+ # `pause_turn` is in-progress, not terminal: the SSE stream still ends with [DONE] via
+ # message_stop but we skip emitting a finish_reason="stop" chunk that would truncate
# the rendered message in the UI.
# The `stop` default below reports an unmapped reason as a
# finished answer, hiding a truncating one added upstream.
@@ -3210,19 +2981,16 @@ class ExternalProviderClient:
model,
)
mapped = _finish_reason_map.get(stop_reason, "stop")
- # Streaming refusal: emit a visible notice plus an
- # out-of-band _toolEvent so the frontend can prune
- # the refused turn. The mapped finish_reason is
- # "content_filter" per OpenAI spec.
- # https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
+ # Streaming refusal: emit a visible notice plus an out-of-band _toolEvent so the
+ # frontend can prune the refused turn. The mapped finish_reason is "content_filter"
+ # per OpenAI spec.
if stop_reason == "refusal":
logger.warning(
"Anthropic refusal stop_reason (model=%s)",
model,
)
- # Drop signal rides _toolEvent (not text) so
- # assistant content can't spoof a context
- # reset.
+ # Drop signal rides _toolEvent (not text) so assistant content cannot spoof a
+ # context reset.
yield _content_chunk(
"\n\n_The response was stopped by "
"Anthropic's safety classifier. Edit "
@@ -3254,10 +3022,8 @@ class ExternalProviderClient:
if thinking_open:
yield _content_chunk("</think>")
thinking_open = False
- # Forward document_citations so the Sources panel
- # can render the inline [N] footnotes. ``cited_text``
- # is truncated server-side to keep SSE bytes bounded
- # on long spans.
+ # Forward document_citations so the Sources panel can render the inline [N] footnotes.
+ # ``cited_text`` is truncated server-side to keep SSE bytes bounded on long spans.
if document_citations:
clean_cits = []
for c in document_citations:
@@ -3272,9 +3038,8 @@ class ExternalProviderClient:
"citations": clean_cits,
}
)
- # Final include_usage-style chunk so callers see
- # cache_creation / cache_read without scraping the
- # server log.
+ # Final include_usage-style chunk so callers see cache_creation / cache_read without
+ # scraping the server log.
usage_line = _build_usage_chunk(
completion_id,
"anthropic",
@@ -3297,8 +3062,8 @@ class ExternalProviderClient:
len(sc.get("results") or []) for sc in web_search_calls.values()
)
queries = [sc["query"] for sc in web_search_calls.values() if sc.get("query")]
- # cache_read_input_tokens > 0 proves the cache_control marker
- # works (turn 1 shows cache_creation instead).
+ # cache_read_input_tokens > 0 proves the cache_control marker works (turn 1 shows cache_creation
+ # instead).
code_execution_invocations = len(code_execution_calls)
code_execution_results = sum(
1 for c in code_execution_calls.values() if c.get("result") is not None
@@ -3388,49 +3153,28 @@ class ExternalProviderClient:
tool_choice: Optional[Any] = None,
response_format: Optional[dict[str, Any]] = None,
) -> AsyncGenerator[str, None]:
- """
- Call Google's native Gemini API and translate its streaming
- ``streamGenerateContent`` response into OpenAI Chat Completions chunks.
-
- Gemini does NOT speak the OpenAI Chat Completions contract on its
- primary endpoint. The wire shape is:
-
- POST /v1beta/models/{model}:streamGenerateContent?alt=sse
- {
- "contents": [{"role": "user|model", "parts": [{"text": "..."}]}],
- "systemInstruction": {"parts": [{"text": "..."}]},
- "generationConfig": {"temperature": 0.7, "topP": 0.95, "topK": 40,
- "maxOutputTokens": 1024},
- "tools": [{"googleSearch": {}}, {"codeExecution": {}}],
- "cachedContent": "<cache name>" // optional, see caching docs
- }
-
- Streamed responses are SSE frames carrying partial
- ``GenerateContentResponse`` objects:
-
- {"candidates": [{"content": {"parts": [{"text": "Hello"}]},
- "finishReason": "STOP"}],
- "usageMetadata": {"promptTokenCount": 7, "candidatesTokenCount": 3}}
-
- Image generation uses the same endpoint with model
- ``gemini-2.5-flash-image`` (Nano Banana); the response carries an
- ``inlineData`` part with base64 PNG bytes and a ``mimeType``. We surface
- that through the same ``tool_start`` / ``tool_end`` ``image_b64``
- envelope the OpenAI image_generation path uses, so the chat UI renders
- the image inline with no extra plumbing.
-
- References:
- - https://ai.google.dev/gemini-api/docs/text-generation
- - https://ai.google.dev/gemini-api/docs/function-calling
- - https://ai.google.dev/gemini-api/docs/grounding
- - https://ai.google.dev/gemini-api/docs/caching
- - https://ai.google.dev/gemini-api/docs/image-generation
+ """Call Google's native Gemini API and translate its streaming ``streamGenerateContent``
+ response into OpenAI Chat Completions chunks.
+
+ Gemini does not speak the OpenAI Chat Completions contract on its primary endpoint. The
+ request is POST /v1beta/models/{model}:streamGenerateContent?alt=sse with `contents` (role
+ user|model, `parts`), `systemInstruction`, `generationConfig`
+ (temperature/topP/topK/maxOutputTokens), `tools` (googleSearch, codeExecution) and an
+ optional `cachedContent`. Streamed responses are SSE frames carrying partial
+ ``GenerateContentResponse`` objects: `candidates[].content.parts[]`, `finishReason` and
+ `usageMetadata`.
+
+ Image generation uses the same endpoint with an image model (Nano Banana); the response
+ carries an ``inlineData`` part with base64 bytes and a ``mimeType``, surfaced through the
+ same ``tool_start`` / ``tool_end`` ``image_b64`` envelope the OpenAI image_generation path
+ uses, so the chat UI renders it inline with no extra plumbing. Refs:
+ https://ai.google.dev/gemini-api/docs/text-generation, function-calling, grounding, caching
+ and image-generation.
"""
import json as _json
- # Validate the user-controlled model id first: `../cachedContents/x` is
- # path traversal, and rejecting early avoids attacker-triggered outbound
- # image fetches on a doomed request. Catalog ids match `[A-Za-z0-9._-]+`.
+ # Validate the user-controlled model id first: `../cachedContents/x` is path traversal, and rejecting early
+ # avoids attacker-triggered outbound image fetches on a doomed request. Catalog ids match `[A-Za-z0-9._-]+`.
if not re.fullmatch(r"[A-Za-z0-9._-]+", model):
yield _error_sse_line(
400,
@@ -3439,21 +3183,17 @@ class ExternalProviderClient:
)
return
- # Translate OpenAI messages -> Gemini contents. system role promotes to
- # top-level systemInstruction.
+ # Translate OpenAI messages -> Gemini contents. system role promotes to top-level systemInstruction.
system_text_parts: list[str] = []
contents: list[dict[str, Any]] = []
- # OpenAI may drop `name` from role="tool" follow-ups. Remember prior
- # function names so functionResponse isn't sent name-less (Gemini 400s
- # on empty names).
+ # OpenAI may drop `name` from role="tool" follow-ups. Remember prior function names so functionResponse is not
+ # sent name-less (Gemini 400s on empty names).
tool_call_names: dict[str, str] = {}
- # tool_call_ids whose assistant card was dropped (synthetic builtin) or
- # already replayed as native parts. Their role="tool" follow-up must be
- # skipped to avoid orphan/duplicate responses.
+ # tool_call_ids whose assistant card was dropped (synthetic builtin) or already replayed as native parts.
+ # Their role="tool" follow-up must be skipped to avoid orphan/duplicate responses.
_gemini_skip_tool_result_ids: set[str] = set()
- # Per-request image caps. The byte cap counts DECODED bytes; set to
- # ~14 MB because base64 expansion + prompt overhead must fit Gemini's
- # ~20 MB request limit.
+ # Per-request image caps. The byte cap counts DECODED bytes; set to ~14 MB because base64 expansion + prompt
+ # overhead must fit Gemini's ~20 MB request limit.
_GEMINI_REMOTE_IMAGE_MAX_COUNT = 8
_GEMINI_REMOTE_IMAGE_MAX_TOTAL_BYTES = 14 * 1024 * 1024
_remote_image_count = 0
@@ -3497,17 +3237,16 @@ class ExternalProviderClient:
header.split(";")[0].replace("data:", "").strip().lower()
or "image/jpeg"
)
- # Reject non-image data URLs (e.g. data:text/html);
- # they'd 400 the request as inlineData. Mirrors the
- # remote-fetch path's Content-Type check.
+ # Reject non-image data URLs (e.g. data:text/html); they would 400 the request as
+ # inlineData. Mirrors the remote-fetch path's Content-Type check.
if not media_type.startswith("image/"):
logger.info(
"Gemini inlineData: refusing non-image data URL media_type=%s",
media_type,
)
elif b64data:
- # data: URLs share the same caps as fetched
- # URLs so inline payloads don't bypass them.
+ # data: URLs share the same caps as fetched URLs so inline payloads do not bypass
+ # them.
_data_approx_bytes = (len(b64data) * 3) // 4
if _remote_image_count >= _GEMINI_REMOTE_IMAGE_MAX_COUNT:
logger.info(
@@ -3533,10 +3272,9 @@ class ExternalProviderClient:
}
)
elif url:
- # fileData.fileUri only accepts Files-API URIs and
- # YouTube; everything else is downloaded and inlined.
- # Parse host explicitly so e.g.
- # https://evil.com/youtube.com/x isn't mis-detected.
+ # fileData.fileUri only accepts Files-API URIs and YouTube; everything else is downloaded
+ # and inlined. Parse host explicitly so e.g. https://evil.com/youtube.com/x is not
+ # mis-detected.
try:
_parsed_image_url = urlparse(url)
except (ValueError, UnicodeError):
@@ -3566,8 +3304,7 @@ class ExternalProviderClient:
else "image/jpeg"
)
if _is_youtube:
- # YouTube URIs must use video/mp4; the
- # default image/jpeg yields a 400.
+ # YouTube URIs must use video/mp4; the default image/jpeg yields a 400.
parts.append(
{
"fileData": {
@@ -3591,8 +3328,7 @@ class ExternalProviderClient:
_GEMINI_REMOTE_IMAGE_MAX_COUNT,
)
else:
- # Refuse pre-fetch when the per-request byte
- # budget is spent; pass the remainder so
+ # Refuse pre-fetch when the per-request byte budget is spent; pass the remainder so
# over-budget URLs reject on Content-Length.
_remaining_bytes = (
_GEMINI_REMOTE_IMAGE_MAX_TOTAL_BYTES - _remote_image_total_bytes
@@ -3602,8 +3338,7 @@ class ExternalProviderClient:
"Gemini image fetch: per-request byte cap already reached, dropping image",
)
else:
- # Count attempts before awaiting so slow URLs
- # don't each burn the timeout.
+ # Count attempts before awaiting so slow URLs do not each burn the timeout.
_remote_image_count += 1
_fetched = await _safe_fetch_image_for_gemini(
url,
@@ -3631,10 +3366,9 @@ class ExternalProviderClient:
}
}
)
- # Gemini 3 strict function-calling requires text-part
- # thoughtSignatures to be replayed on history; the frontend stows
- # the latest one as extra_content.google.thought_signature on the
- # assistant message and we pin it onto the last text part here.
+ # Gemini 3 strict function-calling requires text-part thoughtSignatures to be replayed on history; the
+ # frontend stows the latest one as extra_content.google.thought_signature on the assistant message and we
+ # pin it onto the last text part here.
if role == "assistant" and parts:
_msg_extra = msg.get("extra_content") if isinstance(msg, dict) else None
if isinstance(_msg_extra, dict):
@@ -3649,9 +3383,8 @@ class ExternalProviderClient:
"thoughtSignature": _msg_sig,
}
break
- # Translate OpenAI tool_calls into Gemini functionCall parts.
- # code_execution / image_generation replay their native parts
- # (executableCode / codeExecutionResult / inlineData) stowed on
+ # Translate OpenAI tool_calls into Gemini functionCall parts. code_execution / image_generation replay
+ # their native parts (executableCode / codeExecutionResult / inlineData) stowed on
# extra_content.google.native_part.
tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else None
if isinstance(tool_calls, list):
@@ -3676,9 +3409,9 @@ class ExternalProviderClient:
if fn_name and isinstance(tc_id, str) and tc_id:
tool_call_names[tc_id] = fn_name
- # Replay native Gemini code_execution / image_generation
- # parts from extra_content.google.native_part, falling back
- # to args.google.native_part for OAI-compat round-trips.
+ # Replay native Gemini code_execution / image_generation parts from
+ # extra_content.google.native_part, falling back to args.google.native_part for OAI-compat
+ # round-trips.
_extra = tc.get("extra_content")
_native_part = None
_google_extra: dict[str, Any] = {}
@@ -3696,9 +3429,8 @@ class ExternalProviderClient:
if not _google_extra:
_google_extra = _args_google
- # Synthetic builtin cards (web_search/web_fetch) must not
- # become fake functionCalls; drop them. Native
- # code_execution / image_generation replay below.
+ # Synthetic builtin cards (web_search/web_fetch) must not become fake functionCalls; drop them.
+ # Native code_execution / image_generation replay below.
_name_lc = fn_name.lower() if isinstance(fn_name, str) else ""
_is_synthetic_server_builtin = (
_name_lc
@@ -3718,10 +3450,9 @@ class ExternalProviderClient:
_name_lc in ("code_execution", "image_generation")
and isinstance(_native_part, dict)
):
- # No replayable Gemini native part -- skip entirely
- # rather than send a fake functionCall. Also remember
- # this tool_call_id so a matching role="tool" follow-up
- # doesn't become an orphan functionResponse below.
+ # No replayable Gemini native part -- skip entirely rather than send a fake functionCall. Also
+ # remember this tool_call_id so a matching role="tool" follow-up does not become an orphan
+ # functionResponse below.
if isinstance(tc_id, str) and tc_id:
_gemini_skip_tool_result_ids.add(tc_id)
tool_call_names.pop(tc_id, None)
@@ -3729,28 +3460,23 @@ class ExternalProviderClient:
if fn_name in ("code_execution", "image_generation") and isinstance(
_native_part, dict
):
- # code_execution/image_generation history is replayed as
- # native parts; the matching role="tool" must be skipped
- # or Gemini sees a functionResponse with no declared
- # function name and 400s the turn.
+ # code_execution/image_generation history is replayed as native parts; the matching
+ # role="tool" must be skipped or Gemini sees a functionResponse with no declared function name
+ # and 400s the turn.
if isinstance(tc_id, str) and tc_id:
_gemini_skip_tool_result_ids.add(tc_id)
- # New shape: `native_part.parts` is an ordered list of
- # full part wrappers, each carrying its own
- # `thoughtSignature`. Preserves Gemini 3's strict
- # per-part replay requirement when the frontend merged
- # executableCode + codeExecutionResult + inlineData into
- # the same tool-call card.
+ # New shape: `native_part.parts` is an ordered list of full part wrappers, each carrying its
+ # own `thoughtSignature`. Preserves Gemini 3's strict per-part replay requirement when the
+ # frontend merged executableCode + codeExecutionResult + inlineData into the same tool-call
+ # card.
_native_parts_list = _native_part.get("parts")
if isinstance(_native_parts_list, list):
for _entry in _native_parts_list:
if isinstance(_entry, dict):
parts.append(_entry)
continue
- # Legacy single-object native_part: fan the shared
- # thoughtSignature only when one subpart exists; for
- # code+result, prefer executableCode and drop the
- # signature elsewhere.
+ # Legacy single-object native_part: fan the shared thoughtSignature only when one subpart
+ # exists; for code+result, prefer executableCode and drop the signature elsewhere.
_legacy_sig = _native_part.get("thoughtSignature") or _native_part.get(
"thought_signature"
)
@@ -3780,24 +3506,18 @@ class ExternalProviderClient:
parts.append(_replay_part)
continue
- # Forward the OpenAI tool_call id into Gemini's
- # functionCall.id so a follow-up turn issuing multiple calls
- # to the same function (different args, same name) can be
- # disambiguated on the response side. Gemini accepts the
- # field per
- # https://ai.google.dev/gemini-api/docs/function-calling.
+ # Forward the OpenAI tool_call id into Gemini's functionCall.id so a follow-up turn issuing
+ # multiple calls to the same function (different args, same name) can be disambiguated on the
+ # response side.
function_call_part: dict[str, Any] = {
"name": fn_name,
"args": args,
}
if isinstance(tc_id, str) and tc_id:
function_call_part["id"] = tc_id
- # Gemini 3 function-calling requires the prior
- # thoughtSignature echoed back as a sibling of the
- # functionCall part. The translator stows it on the
- # assistant tool_call via
- # `extra_content.google.thought_signature` (see the inbound
- # emit below).
+ # Gemini 3 function-calling requires the prior thoughtSignature echoed back as a sibling of the
+ # functionCall part. The translator stows it on the assistant tool_call via
+ # `extra_content.google.thought_signature` (see the inbound emit below).
fc_part: dict[str, Any] = {"functionCall": function_call_part}
sig = _google_extra.get("thought_signature") or _google_extra.get(
"thoughtSignature"
@@ -3806,20 +3526,17 @@ class ExternalProviderClient:
fc_part["thoughtSignature"] = sig
parts.append(fc_part)
if role == "tool":
- # Drop the follow-up if its assistant-side tool_call was dropped
- # or already replayed as native parts; else it would be an
- # orphan/duplicate functionResponse.
+ # Drop the follow-up if its assistant-side tool_call was dropped or already replayed as native parts;
+ # else it would be an orphan/duplicate functionResponse.
_tc_id_for_skip = msg.get("tool_call_id")
if (
isinstance(_tc_id_for_skip, str)
and _tc_id_for_skip in _gemini_skip_tool_result_ids
):
continue
- # OpenAI's role="tool" follow-up carries the function result.
- # Gemini's matching shape is a role="user" turn with a
- # functionResponse part. When the caller dropped ``name``,
- # recover it from the matching assistant tool_call so Gemini
- # doesn't 400 on an empty name.
+ # OpenAI's role="tool" follow-up carries the function result; Gemini's matching shape is a role="user"
+ # turn with a functionResponse part. When the caller dropped ``name``, recover it from the matching
+ # assistant tool_call so Gemini does not 400 on an empty name.
tool_name = msg.get("name") or msg.get("tool_name") or ""
if not tool_name:
tc_id = msg.get("tool_call_id")
@@ -3827,8 +3544,8 @@ class ExternalProviderClient:
tool_name = tool_call_names[tc_id]
response_payload: Any
if isinstance(content, list):
- # Flatten list-form tool content to text so the
- # functionResponse result matches the string-content path.
+ # Flatten list-form tool content to text so the functionResponse result matches the string-content
+ # path.
_flat_parts: list[str] = []
for _cpart in content:
if (
@@ -3857,17 +3574,16 @@ class ExternalProviderClient:
else {"result": response_payload}
),
}
- # Mirror tool_call_id onto functionResponse.id so Gemini can
- # match the result to the originating functionCall when multiple
- # parallel calls were made.
+ # Mirror tool_call_id onto functionResponse.id so Gemini can match the result to the originating
+ # functionCall when multiple parallel calls were made.
tc_id = msg.get("tool_call_id")
if isinstance(tc_id, str) and tc_id:
function_response_part["id"] = tc_id
parts = [{"functionResponse": function_response_part}]
gemini_role = "user"
if parts:
- # Merge consecutive functionResponse-only user blocks: Gemini
- # wants parallel tool responses grouped into one user turn.
+ # Merge consecutive functionResponse-only user blocks: Gemini wants parallel tool responses grouped
+ # into one user turn.
if (
role == "tool"
and contents
@@ -3885,9 +3601,8 @@ class ExternalProviderClient:
if system_text_parts:
body["systemInstruction"] = {"parts": [{"text": "\n\n".join(system_text_parts)}]}
- # Generation config -- temperature / topP / topK / maxOutputTokens map
- # straight across. The frontend capability matrix restricts the sliders
- # the UI exposes for Gemini to this set.
+ # Generation config -- temperature / topP / topK / maxOutputTokens map straight across. The frontend
+ # capability matrix restricts the sliders the UI exposes for Gemini to this set.
gen_config: dict[str, Any] = {}
if temperature is not None:
gen_config["temperature"] = temperature
@@ -3895,22 +3610,19 @@ class ExternalProviderClient:
gen_config["topP"] = top_p
if top_k is not None and top_k > 0:
gen_config["topK"] = top_k
- # Gemini accepts ``presencePenalty`` on generationConfig with the same
- # sign convention as the OpenAI knob (positive discourages repetition).
- # Forward when the caller sets it.
+ # Gemini accepts ``presencePenalty`` on generationConfig with the same sign convention as the OpenAI knob
+ # (positive discourages repetition). Forward when the caller sets it.
if presence_penalty:
gen_config["presencePenalty"] = presence_penalty
if max_tokens is not None:
gen_config["maxOutputTokens"] = max_tokens
- # Nano Banana image generation: only image-capable models (id contains
- # `-image`/`nano-banana`) accept responseModalities=["TEXT","IMAGE"];
- # text models 400 on it, so a stale image_generation pill is ignored.
- # https://ai.google.dev/gemini-api/docs/image-generation
+ # Nano Banana image generation: only image-capable models (id contains `-image`/`nano-banana`) accept
+ # responseModalities=["TEXT","IMAGE"]; text models 400 on it, so a stale image_generation pill is ignored.
model_lc = model.lower()
is_image_picker_model = "-image" in model_lc or "nano-banana" in model_lc
- # tool_choice="none"/forced-function also suppresses implicit image
- # generation, else an explicit opt-out still bills for image output.
+ # tool_choice="none"/forced-function also suppresses implicit image generation, else an explicit opt-out still
+ # bills for image output.
_tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
@@ -3921,9 +3633,8 @@ class ExternalProviderClient:
and bool(tool_choice["function"].get("name"))
)
_hosted_builtins_allowed = not _tool_choice_disabled and not _tool_choice_forced_function
- # Image-tier models reject text-only tools and thinkingConfig regardless
- # of the pill (model-level constraint); the pill only controls image
- # output. Decouple the two so Images-off + Code/Search-on doesn't 400.
+ # Image-tier models reject text-only tools and thinkingConfig regardless of the pill (model-level constraint);
+ # the pill only controls image output. Decouple the two so Images-off + Code/Search-on does not 400.
image_tool_requested = bool(
_hosted_builtins_allowed and enabled_tools and "image_generation" in enabled_tools
)
@@ -3934,17 +3645,13 @@ class ExternalProviderClient:
if is_image_model:
gen_config["responseModalities"] = ["TEXT", "IMAGE"]
elif is_image_picker_model:
- # Force TEXT-only so an image-capable model with Images OFF doesn't
- # still bill for image output.
+ # Force TEXT-only so an image-capable model with Images OFF does not still bill for image output.
gen_config["responseModalities"] = ["TEXT"]
- # Thinking control. Gemini 3 uses thinkingLevel (str), 2.5 uses
- # thinkingBudget (int). Gemini 3 has no full-off; minimum is
- # "minimal" on Flash, "low" on Pro.
- # https://ai.google.dev/gemini-api/docs/thinking
- # Match the 3.x family by pattern, not by enumerating minors: a new
- # `gemini-3.6-*` would otherwise fall through to the 2.5 branch and get
- # an int budget, which Gemini 3 rejects (400 on thinkingBudget=0).
+ # Thinking control. Gemini 3 uses thinkingLevel (str), 2.5 uses thinkingBudget (int); Gemini 3 has no
+ # full-off, its minimum is "minimal" on Flash and "low" on Pro. Match the 3.x family by pattern, not by
+ # enumerating minors: a new `gemini-3.6-*` would otherwise fall through to the 2.5 branch and get an int
+ # budget, which Gemini 3 rejects (400 on thinkingBudget=0).
_GEMINI3_ALIASES = (
"gemini-pro-latest",
"gemini-flash-latest",
@@ -3962,11 +3669,8 @@ class ExternalProviderClient:
)
effort_lc = (reasoning_effort or "").strip().lower()
if not is_image_model_strict and is_gemini3_thinking:
- # Gemini 3.x thinkingLevel matrix:
- # 3.1+ Pro: low/medium/high
- # 3 Pro: low/high (deprecated 2026-03-09)
- # 3.x Flash*: minimal/low/medium/high
- # Coerce minimal->low on Pro; medium->high on legacy 3-Pro.
+ # Gemini 3.x thinkingLevel matrix: 3.1+ Pro low/medium/high; 3 Pro low/high (deprecated 2026-03-09); 3.x
+ # Flash* minimal/low/medium/high. Coerce minimal->low on Pro, medium->high on legacy 3-Pro.
_G3_LEVELS = {"minimal", "low", "medium", "high"}
level: Optional[str] = None
if effort_lc in ("none", "off"):
@@ -3974,8 +3678,7 @@ class ExternalProviderClient:
elif effort_lc == "max":
level = "high"
elif effort_lc in _G3_LEVELS:
- # Coerce legacy 3-Pro (low/high only) inputs.
- # Undotted `gemini-3-pro` only; any dotted minor is 3.1+.
+ # Coerce legacy 3-Pro (low/high only) inputs. Undotted `gemini-3-pro` only; any dotted minor is 3.1+.
_is_legacy_gemini3_pro = model_lc.startswith("gemini-3-pro")
if is_gemini3_pro and effort_lc == "minimal":
level = "low"
@@ -3990,10 +3693,8 @@ class ExternalProviderClient:
if level is not None:
gen_config["thinkingConfig"] = {"thinkingLevel": level}
elif not is_image_model_strict:
- # Gemini 2.5 / older: thinkingBudget int. Effort -> budget mirrors
- # the OpenAI minimal/low/medium/high ladder so the frontend picker
- # maps cleanly.
- # NOTE: gemini-2.5-flash-lite rejects positive budgets below 512
+ # Gemini 2.5 / older: thinkingBudget int. Effort -> budget mirrors the OpenAI minimal/low/medium/high
+ # ladder so the frontend picker maps cleanly. gemini-2.5-flash-lite rejects positive budgets below 512
# with HTTP 400, so minimal=512 sits at that floor.
_EFFORT_TO_BUDGET: dict[str, int] = {
"minimal": 512,
@@ -4005,8 +3706,8 @@ class ExternalProviderClient:
}
thinking_budget: Optional[int] = None
if effort_lc == "none" or enable_thinking is False:
- # Pro-tier 2.5 rejects budget=0 (400 "only works in thinking
- # mode"), so coerce to a small positive value.
+ # Pro-tier 2.5 rejects budget=0 (400 "only works in thinking mode"), so coerce to a small positive
+ # value.
thinking_budget = 128 if _is_pro_thinking_only else 0
elif effort_lc in _EFFORT_TO_BUDGET:
thinking_budget = _EFFORT_TO_BUDGET[effort_lc]
@@ -4020,11 +3721,8 @@ class ExternalProviderClient:
if gen_config:
body["generationConfig"] = gen_config
- # Hosted tools: googleSearch (grounding) and codeExecution.
- # Image-mode rejects codeExecution; only Gemini 3 image models
- # accept googleSearch.
- # https://ai.google.dev/gemini-api/docs/grounding
- # https://ai.google.dev/gemini-api/docs/code-execution
+ # Hosted tools: googleSearch (grounding) and codeExecution. Image-mode rejects codeExecution; only Gemini 3
+ # image models accept googleSearch.
def _gemini_image_model_allows_google_search(_m: str) -> bool:
return (
_m.startswith("gemini-3-pro-image")
@@ -4038,8 +3736,8 @@ class ExternalProviderClient:
)
code_execution_allowed = not is_image_model_strict
text_tools_allowed = not is_image_model_strict
- # tool_choice="none" / forced-function suppresses hosted builtins too,
- # matching the Anthropic / OpenRouter gates.
+ # tool_choice="none" / forced-function suppresses hosted builtins too, matching the Anthropic / OpenRouter
+ # gates.
tools_array: list[dict[str, Any]] = []
if (
_hosted_builtins_allowed
@@ -4055,12 +3753,9 @@ class ExternalProviderClient:
and code_execution_allowed
):
tools_array.append({"codeExecution": {}})
- # OpenAI function declarations -> Gemini functionDeclarations
- # (https://ai.google.dev/gemini-api/docs/function-calling#step_1). Gemini's
- # Schema accepts only the OpenAPI 3.0 subset; OpenAI strict tools include
- # keys (additionalProperties, $schema, $defs, ...) that 400 as
- # INVALID_ARGUMENT, so strip recursively. Ref:
- # https://ai.google.dev/api/caching#Schema
+ # OpenAI function declarations -> Gemini functionDeclarations. Gemini's Schema accepts only the OpenAPI 3.0
+ # subset; OpenAI strict tools include keys (additionalProperties, $schema, $defs, ...) that 400 as
+ # INVALID_ARGUMENT, so strip recursively. Ref: https://ai.google.dev/api/caching#Schema
_GEMINI_ALLOWED_SCHEMA_KEYS = frozenset(
{
"type",
@@ -4088,9 +3783,8 @@ class ExternalProviderClient:
)
def _resolve_local_schema_ref(root: Optional[dict[str, Any]], ref: str) -> Optional[Any]:
- # Walk a `#/foo/bar` JSON pointer against the schema root. Returns
- # None if the pointer doesn't resolve to a dict, so the caller can
- # fall back to the unresolved node.
+ # Walk a `#/foo/bar` JSON pointer against the schema root. Returns None if the pointer does not resolve to
+ # a dict, so the caller can fall back to the unresolved node.
if not isinstance(root, dict) or not isinstance(ref, str):
return None
if not ref.startswith("#/"):
@@ -4110,16 +3804,15 @@ class ExternalProviderClient:
root: Optional[dict[str, Any]] = None,
_seen_refs: Optional[frozenset[str]] = None,
) -> Any:
- # Recursively filter to Gemini's OpenAPI 3.0 subset (drop non-allowlist
- # keys) and translate JSON Schema `type:[X,"null"]` into
- # `type:X` + `nullable:true`.
+ # Recursively filter to Gemini's OpenAPI 3.0 subset (drop non-allowlist keys) and translate JSON Schema
+ # `type:[X,"null"]` into `type:X` + `nullable:true`.
if root is None and isinstance(node, dict):
root = node
if _seen_refs is None:
_seen_refs = frozenset()
if isinstance(node, dict):
- # Inline `$ref` targets (Gemini's subset has no $ref), with local
- # siblings overriding and a cycle guard.
+ # Inline `$ref` targets (Gemini's subset has no $ref), with local siblings overriding and a cycle
+ # guard.
_ref = node.get("$ref")
if isinstance(_ref, str):
if _ref in _seen_refs:
@@ -4143,9 +3836,8 @@ class ExternalProviderClient:
if len(_non_null) == 1:
_flattened_type = _non_null[0]
elif len(_non_null) > 1:
- # Preserve multi-type unions as anyOf; flattening to the
- # first non-null type silently drops the other branches
- # and changes the tool contract.
+ # Preserve multi-type unions as anyOf; flattening to the first non-null type silently drops
+ # the other branches and changes the tool contract.
_union_any_of = [{"type": _t} for _t in _non_null if isinstance(_t, str)]
for _k, _v in node.items():
if _k == "type" and isinstance(_v, list):
@@ -4161,13 +3853,10 @@ class ExternalProviderClient:
elif _k == "items":
cleaned[_k] = _sanitize_gemini_schema(_v, root, _seen_refs)
elif _k == "anyOf" and isinstance(_v, list):
- # Optional[X] / Union[A, B, None]: Pydantic emits
- # `anyOf: [..., {"type":"null"}]`. Gemini's OpenAPI
- # subset rejects `"type": "null"` inside anyOf, so drop
- # the null variant and surface it via `nullable: true`.
- # If exactly one non-null branch remains, collapse it
- # inline; otherwise keep the slim anyOf and mark the
- # field nullable.
+ # Optional[X] / Union[A, B, None]: Pydantic emits `anyOf: [..., {"type":"null"}]`, and
+ # Gemini's OpenAPI subset rejects `"type": "null"` inside anyOf, so drop the null variant and
+ # surface it via `nullable: true`. If exactly one non-null branch remains, collapse it inline;
+ # otherwise keep the slim anyOf and mark the field nullable.
_saw_null = any(
isinstance(_entry, dict) and _entry.get("type") == "null"
for _entry in _v
@@ -4226,8 +3915,8 @@ class ExternalProviderClient:
tools_array.append({"functionDeclarations": function_declarations})
if tools_array:
body["tools"] = tools_array
- # Tool-choice mapping: OpenAI "auto"/"none"/"required"/{name=...} ->
- # Gemini toolConfig.functionCallingConfig.mode + allowedFunctionNames.
+ # Tool-choice mapping: OpenAI "auto"/"none"/"required"/{name=...} -> Gemini
+ # toolConfig.functionCallingConfig.mode + allowedFunctionNames.
if tool_choice is not None and function_declarations and text_tools_allowed:
_mode: Optional[str] = None
_allowed: Optional[list[str]] = None
@@ -4251,14 +3940,11 @@ class ExternalProviderClient:
_fcc["allowedFunctionNames"] = _allowed
body["toolConfig"] = {"functionCallingConfig": _fcc}
- # Structured output. Gemini carries it on generationConfig as a response
- # MIME type, not the Chat Completions `response_format` this endpoint has
- # never seen, so JSON mode was silently dropped for every native Gemini
- # call (deep research parses its planning hop as JSON). Only on a tool-free
- # turn: Gemini 400s with "Function calling with a response mime type:
- # 'application/json' is unsupported" when both are sent, and the hop that
+ # Structured output. Gemini carries it on generationConfig as a response MIME type, not the Chat Completions
+ # `response_format` this endpoint has never seen, so JSON mode was silently dropped for every native Gemini
+ # call (deep research parses its planning hop as JSON). Only on a tool-free turn: Gemini 400s with "Function
+ # calling with a response mime type: 'application/json' is unsupported" when both are sent, and the hop that
# asks for JSON sends no tools.
- # https://ai.google.dev/gemini-api/docs/structured-output
_rf_type = response_format.get("type") if isinstance(response_format, dict) else None
if _rf_type in ("json_object", "json_schema") and "tools" not in body:
_gen_cfg = body.setdefault("generationConfig", {})
@@ -4266,21 +3952,19 @@ class ExternalProviderClient:
if _rf_type == "json_schema":
_rf_schema = response_format.get("json_schema")
if isinstance(_rf_schema, dict) and isinstance(_rf_schema.get("schema"), dict):
- # responseSchema is the same OpenAPI subset the function
- # declarations use, so it needs the same scrubbing.
+ # responseSchema is the same OpenAPI subset the function declarations use, so it needs the same
+ # scrubbing.
_gen_cfg["responseSchema"] = _sanitize_gemini_schema(_rf_schema["schema"])
- # Prompt caching. The Gemini contract is "create a CachedContent
- # resource, then pass its name on `cachedContent`". The cache is created
- # out of band by the caller via POST /cachedContents; here we forward an
- # explicit cache id when the dispatcher hands us one (a string value on
- # enable_prompt_caching means "use this cache name").
- # https://ai.google.dev/gemini-api/docs/caching
+ # Prompt caching. The Gemini contract is "create a CachedContent resource, then pass its name on
+ # `cachedContent`". The cache is created out of band by the caller via POST /cachedContents; here we forward
+ # an explicit cache id when the dispatcher hands us one (a string value on enable_prompt_caching means "use
+ # this cache name").
if isinstance(enable_prompt_caching, str) and enable_prompt_caching:
body["cachedContent"] = enable_prompt_caching
- # Model id is already validated at the top of _stream_gemini so we never
- # reach a path-traversed URL segment here.
+ # Model id is already validated at the top of _stream_gemini so we never reach a path-traversed URL segment
+ # here.
url = f"{self.base_url}/models/{model}:streamGenerateContent?alt=sse"
completion_id = f"chatcmpl-gemini-{model.replace('/', '-')}"
@@ -4326,17 +4010,15 @@ class ExternalProviderClient:
return f"data: {_json.dumps(chunk)}"
def _gemini_part_extra(part: dict[str, Any]) -> Optional[dict[str, Any]]:
- """Return ``{"google": {"thought_signature": ...}}`` when the Gemini
- stream part carries a `thoughtSignature` we must replay on a
- follow-up turn (Gemini 3 image editing + tool contexts both require
- an exact signature echo)."""
+ """Return ``{"google": {"thought_signature": ...}}`` when the Gemini stream part carries
+ a `thoughtSignature` we must replay on a follow-up turn (Gemini 3 image editing and
+ tool contexts both require an exact signature echo)."""
sig = part.get("thoughtSignature") or part.get("thought_signature")
if isinstance(sig, str) and sig:
return {"google": {"thought_signature": sig}}
return None
- # Gemini finish reasons -> OpenAI vocabulary. Reference:
- # https://ai.google.dev/api/rest/v1beta/Candidate#FinishReason
+ # Gemini finish reasons -> OpenAI vocabulary.
_finish_reason_map: dict[str, Optional[str]] = {
"STOP": "stop",
"MAX_TOKENS": "length",
@@ -4351,26 +4033,23 @@ class ExternalProviderClient:
last_usage: Optional[dict[str, Any]] = None
emitted_function_call_ids: set[str] = set()
- # True once any Gemini functionCall part has been emitted so the final
- # finish_reason swaps STOP -> tool_calls (matches the OpenAI Chat
- # Completions contract; an OAI client that sees a tool_calls delta
- # followed by finish_reason="stop" never executes the tool).
+ # True once any Gemini functionCall part has been emitted so the final finish_reason swaps STOP -> tool_calls
+ # (matching the OpenAI Chat Completions contract; an OAI client that sees a tool_calls delta followed by
+ # finish_reason="stop" never executes the tool).
emitted_any_function_call = False
- # Keyed on whether `googleSearch` was actually forwarded (not caller
- # intent) so image-mode turns don't show a phantom "search complete".
+ # Keyed on whether `googleSearch` was actually forwarded (not caller intent) so image-mode turns do not show a
+ # phantom "search complete".
web_search_active = any("googleSearch" in t for t in tools_array)
web_search_tool_id = "gemini_web_search"
web_search_tool_started = False
web_search_tool_ended = False
web_search_citations: list[dict[str, str]] = []
- # tool_call_id minted on the most recent executableCode part so the
- # matching codeExecutionResult closes out the same envelope. None
- # between rounds.
+ # tool_call_id minted on the most recent executableCode part so the matching codeExecutionResult closes out
+ # the same envelope. None between rounds.
gemini_code_exec_pending_id: Optional[str] = None
- # The most recently emitted code_execution id + result text. Kept *after*
- # the tool_end so a following inline image (matplotlib plot from
- # codeExecution) can attach to the same card via a `__IMAGES__:` marker
- # instead of spawning a separate image_generation event.
+ # The most recently emitted code_execution id + result text. Kept AFTER the tool_end so a following inline
+ # image (matplotlib plot from codeExecution) can attach to the same card via a `__IMAGES__:` marker instead of
+ # spawning a separate image_generation event.
last_code_exec_tool_id: Optional[str] = None
last_code_exec_result_text: str = ""
@@ -4409,9 +4088,8 @@ class ExternalProviderClient:
)
web_search_tool_started = True
- # NOTE: same manual __anext__ loop as the other streaming
- # helpers (see stream_chat_completion for the Python 3.13 +
- # httpcore 1.0.x GeneratorExit ordering).
+ # Same manual __anext__ loop as the other streaming helpers (see stream_chat_completion for the Python
+ # 3.13 + httpcore 1.0.x GeneratorExit ordering).
lines_gen = response.aiter_lines().__aiter__()
final_finish_reason: Optional[str] = None
try:
@@ -4438,21 +4116,18 @@ class ExternalProviderClient:
if not isinstance(event, dict):
continue
- # Latch usageMetadata across deltas -- the final fragment
- # carries the complete totals.
+ # Latch usageMetadata across deltas -- the final fragment carries the complete totals.
usage_meta = event.get("usageMetadata")
if isinstance(usage_meta, dict):
last_usage = usage_meta
- # Prompt-level safety block (zero candidates +
- # promptFeedback.blockReason): surface as an error so the
- # client doesn't see an empty successful response.
+ # Prompt-level safety block (zero candidates + promptFeedback.blockReason): surface as an
+ # error so the client does not see an empty successful response.
prompt_feedback = event.get("promptFeedback")
if isinstance(prompt_feedback, dict) and prompt_feedback.get("blockReason"):
block_reason = str(prompt_feedback.get("blockReason"))
- # Close out the synthetic web_search start so the UI
- # doesn't show a spinner stuck on "searching..."
- # after the error toast lands.
+ # Close out the synthetic web_search start so the UI does not show a spinner stuck on
+ # "searching..." after the error toast lands.
if (
web_search_active
and web_search_tool_started
@@ -4482,10 +4157,8 @@ class ExternalProviderClient:
for cand in candidates:
if not isinstance(cand, dict):
continue
- # Citations / grounding metadata.
- # `groundingMetadata.groundingChunks[].web` carries
- # `uri` + `title`. Collect for the tool_end emission
- # at stream close.
+ # Citations / grounding metadata: `groundingMetadata.groundingChunks[].web` carries `uri`
+ # + `title`. Collect for the tool_end emission at stream close.
gm = cand.get("groundingMetadata")
if isinstance(gm, dict) and web_search_active:
chunks_list = gm.get("groundingChunks") or []
@@ -4517,10 +4190,8 @@ class ExternalProviderClient:
for part in parts:
if not isinstance(part, dict):
continue
- # Text delta. Stow part-level
- # `thoughtSignature` on the delta so Gemini 3
- # turns needing an exact signature echo
- # round-trip cleanly.
+ # Text delta. Stow part-level `thoughtSignature` on the delta so Gemini 3 turns
+ # needing an exact signature echo round-trip cleanly.
text = part.get("text")
_part_extra = _gemini_part_extra(part)
if isinstance(text, str) and text:
@@ -4537,15 +4208,13 @@ class ExternalProviderClient:
"inlineData",
)
):
- # Empty-content part carrying a
- # thoughtSignature: emit an empty delta to
+ # Empty-content part carrying a thoughtSignature: emit an empty delta to
# preserve the signature.
yield _text_chunk(
"",
extra_content = _part_extra,
)
- # functionCall -> OpenAI tool_calls
- # delta envelope.
+ # functionCall -> OpenAI tool_calls delta envelope.
fc = part.get("functionCall")
if isinstance(fc, dict):
fc_name = fc.get("name") or ""
@@ -4554,8 +4223,7 @@ class ExternalProviderClient:
if fc_id in emitted_function_call_ids:
continue
emitted_function_call_ids.add(fc_id)
- # Each functionCall needs its own
- # tool_calls[*].index, else index-based
+ # Each functionCall needs its own tool_calls[*].index, else index-based
# consumers collapse parallel calls.
tc_index = len(emitted_function_call_ids) - 1
tool_call_delta: dict[str, Any] = {
@@ -4567,9 +4235,8 @@ class ExternalProviderClient:
"arguments": _json.dumps(fc_args),
},
}
- # Gemini 3 requires the part-level
- # thoughtSignature echoed next turn; stow
- # it on extra_content.google for replay.
+ # Gemini 3 requires the part-level thoughtSignature echoed next turn; stow it
+ # on extra_content.google for replay.
thought_sig = part.get("thoughtSignature") or part.get(
"thought_signature"
)
@@ -4592,13 +4259,10 @@ class ExternalProviderClient:
],
}
yield f"data: {_json.dumps(tool_chunk)}"
- # executableCode + codeExecutionResult parts
- # surface as the standard code_execution
- # tool_start/tool_end envelope (same shape
- # OpenAI and Anthropic emit) so the chat
- # adapter renders Gemini sandbox output
- # through CodeExecutionToolUI.
- # https://ai.google.dev/gemini-api/docs/code-execution
+ # executableCode + codeExecutionResult parts surface as the standard
+ # code_execution tool_start/tool_end envelope (the same shape OpenAI and Anthropic
+ # emit) so the chat adapter renders Gemini sandbox output through
+ # CodeExecutionToolUI.
exec_code = part.get("executableCode")
if isinstance(exec_code, dict):
code_str = exec_code.get("code") or ""
@@ -4608,17 +4272,14 @@ class ExternalProviderClient:
or f"gemini_code_exec_{time.time_ns()}"
)
gemini_code_exec_pending_id = code_tool_id
- # Stow the raw Gemini part so
- # follow-up turns can replay the
- # native `executableCode` (Gemini
- # rejects a generic functionCall echo
- # for code execution history).
+ # Stow the raw Gemini part so follow-up turns can replay the native
+ # `executableCode` (Gemini rejects a generic functionCall echo for code
+ # execution history).
_exec_thought_sig = part.get(
"thoughtSignature"
) or part.get("thought_signature")
- # Per-part thoughtSignature stays
- # bound to its own part (Gemini 3
- # rejects shared signatures).
+ # Per-part thoughtSignature stays bound to its own part (Gemini 3 rejects
+ # shared signatures).
_exec_part_entry: dict[str, Any] = {
"executableCode": exec_code,
}
@@ -4656,17 +4317,13 @@ class ExternalProviderClient:
if isinstance(exec_result, dict):
outcome = exec_result.get("outcome") or ""
output = exec_result.get("output") or ""
- # Gemini returns OUTCOME_OK /
- # OUTCOME_FAILED /
- # OUTCOME_DEADLINE_EXCEEDED. Treat non-OK
- # outcomes as stderr so the UI surfaces
- # the error.
+ # Gemini returns OUTCOME_OK / OUTCOME_FAILED / OUTCOME_DEADLINE_EXCEEDED.
+ # Treat non-OK outcomes as stderr so the UI surfaces the error.
if outcome and outcome != "OUTCOME_OK":
result_text = f"[{outcome}]\n{output}".rstrip()
else:
result_text = output
- # Pair tool_end with the most recent
- # executableCode tool_start; else
+ # Pair tool_end with the most recent executableCode tool_start; else
# exec_result.id, then a fresh id.
pair_id = (
gemini_code_exec_pending_id
@@ -4714,10 +4371,8 @@ class ExternalProviderClient:
last_code_exec_tool_id = pair_id
last_code_exec_result_text = result_text
gemini_code_exec_pending_id = None
- # inlineData: either a Nano Banana generation
- # (own card) or a sandbox plot attached to
- # the code_execution card via the __IMAGES__:
- # marker.
+ # inlineData: either a Nano Banana generation (own card) or a sandbox plot
+ # attached to the code_execution card via the __IMAGES__: marker.
inline = part.get("inlineData")
if isinstance(inline, dict):
b64 = inline.get("data") or ""
@@ -4736,8 +4391,7 @@ class ExternalProviderClient:
+ "\n__IMAGES__:"
+ _json.dumps([image_uri])
)
- # Stow inlineData so a follow-up
- # turn replays the plot with its
+ # Stow inlineData so a follow-up turn replays the plot with its
# per-part thoughtSignature.
_plot_thought_sig = part.get(
"thoughtSignature"
@@ -4781,9 +4435,8 @@ class ExternalProviderClient:
},
}
)
- # Gemini 3 image edit needs
- # the prior thoughtSignature
- # echoed on the inline image part.
+ # Gemini 3 image edit needs the prior thoughtSignature echoed on the
+ # inline image part.
_img_thought_sig = part.get(
"thoughtSignature"
) or part.get("thought_signature")
@@ -4794,9 +4447,8 @@ class ExternalProviderClient:
"image_b64": b64,
"image_mime": mime,
}
- # Stow inlineData so multi-turn
- # edits replay the original
- # image as native history.
+ # Stow inlineData so multi-turn edits replay the original image as
+ # native history.
_img_part_entry: dict[str, Any] = {
"inlineData": {
"mimeType": mime,
@@ -4831,8 +4483,8 @@ class ExternalProviderClient:
if mapped is not None:
final_finish_reason = mapped
- # End-of-stream order: web_search tool_end -> finish_reason ->
- # usage -> [DONE], matching the Anthropic/OpenAI helpers.
+ # End-of-stream order: web_search tool_end -> finish_reason -> usage -> [DONE], matching the
+ # Anthropic/OpenAI helpers.
if web_search_active and web_search_tool_started and not web_search_tool_ended:
blocks: list[str] = []
for cit in web_search_citations:
@@ -4852,8 +4504,8 @@ class ExternalProviderClient:
web_search_tool_ended = True
if final_finish_reason:
- # Gemini emits "STOP" even for a pure functionCall turn;
- # override to "tool_calls" so OAI clients run the tool.
+ # Gemini emits "STOP" even for a pure functionCall turn; override to "tool_calls" so OAI
+ # clients run the tool.
if emitted_any_function_call and final_finish_reason == "stop":
final_finish_reason = "tool_calls"
finish_chunk = {
@@ -4869,16 +4521,14 @@ class ExternalProviderClient:
}
yield f"data: {_json.dumps(finish_chunk)}"
- # Map Gemini usageMetadata onto OpenAI include_usage.
- # thoughtsTokenCount is billed output too — fold it in so
- # cost calculators don't undercount.
+ # Map Gemini usageMetadata onto OpenAI include_usage. thoughtsTokenCount is billed output too --
+ # fold it in so cost calculators do not undercount.
if isinstance(last_usage, dict):
thought_tokens = last_usage.get("thoughtsTokenCount") or 0
candidate_tokens = last_usage.get("candidatesTokenCount") or 0
prompt_tokens = last_usage.get("promptTokenCount") or 0
- # Gemini bills tool-call prompt slices separately via
- # `toolUsePromptTokenCount`. Fold into input so
- # total_tokens doesn't undercount tool turns.
+ # Gemini bills tool-call prompt slices separately via `toolUsePromptTokenCount`. Fold into
+ # input so total_tokens does not undercount tool turns.
tool_use_prompt_tokens = last_usage.get("toolUsePromptTokenCount") or 0
translated_usage = {
"input_tokens": prompt_tokens + tool_use_prompt_tokens,
@@ -4967,17 +4617,11 @@ class ExternalProviderClient:
tool_choice: Optional[Any] = None,
response_format: Optional[dict[str, Any]] = None,
) -> AsyncGenerator[str, None]:
- """
- Call OpenAI's /v1/responses endpoint and translate its SSE stream back
- into OpenAI Chat Completions chunk format.
-
- The Responses API uses a different request shape (``input`` not
- ``messages``, ``instructions`` for system prompts, ``max_output_tokens``
- for the budget) and emits event-typed SSE frames (e.g.
- ``response.output_text.delta``) rather than chat-completion chunks.
- ``presence_penalty`` / ``top_k`` aren't part of the Responses contract
- and are dropped here.
- """
+ """Call OpenAI's /v1/responses endpoint and translate its SSE stream back into OpenAI Chat
+ Completions chunk format. The Responses API uses a different request shape (``input`` not
+ ``messages``, ``instructions`` for system prompts, ``max_output_tokens`` for the budget)
+ and emits event-typed SSE frames rather than chat-completion chunks. ``presence_penalty``
+ / ``top_k`` are not part of the Responses contract and are dropped here."""
import json as _json
is_openai_cloud = _is_openai_family_cloud(self.base_url)
@@ -4985,13 +4629,12 @@ class ExternalProviderClient:
enabled_tools and "image_generation" in enabled_tools and is_openai_cloud
)
- # Split system messages into a single `instructions` string and
- # translate user/assistant messages into the Responses input shape.
+ # Split system messages into a single `instructions` string and translate user/assistant messages into the
+ # Responses input shape.
instructions_parts: list[str] = []
input_items: list[dict[str, Any]] = []
- # When we drop a server-side builtin `function_call` here, the matching
- # `role="tool"` follow-up must also be dropped -- otherwise the outbound
- # body has an orphan `function_call_output` with no matching
+ # When we drop a server-side builtin `function_call` here, the matching `role="tool"` follow-up must also be
+ # dropped -- otherwise the outbound body has an orphan `function_call_output` with no matching
# `function_call`, which OpenAI Responses can reject or mis-associate.
skipped_server_builtin_call_ids: set[str] = set()
openai_replay_items: list[dict[str, Any]] = []
@@ -5010,14 +4653,12 @@ class ExternalProviderClient:
instructions_parts.append(part["text"])
continue
- # Responses uses item-shape history: each assistant call is a
- # `function_call` item and each role="tool" follow-up a
- # `function_call_output` keyed by call_id (Chat Completions shape 400s).
+ # Responses uses item-shape history: each assistant call is a `function_call` item and each role="tool"
+ # follow-up a `function_call_output` keyed by call_id (the Chat Completions shape 400s).
if role == "tool":
_call_id = msg.get("tool_call_id") or ""
- # If the matching assistant `function_call` was a server-side
- # builtin we already dropped, drop the follow-up too to avoid
- # an orphan `function_call_output`.
+ # If the matching assistant `function_call` was a server-side builtin we already dropped, drop the
+ # follow-up too to avoid an orphan `function_call_output`.
if _call_id and _call_id in skipped_server_builtin_call_ids:
continue
if isinstance(content, list):
@@ -5032,17 +4673,16 @@ class ExternalProviderClient:
input_items.append(responses_function_output(_call_id, _output_text))
continue
- # Translate assistant tool_calls into `function_call` items, skipping
- # server-side builtin cards (builtin name + `_server_tool` marker).
+ # Translate assistant tool_calls into `function_call` items, skipping server-side builtin cards (builtin
+ # name + `_server_tool` marker).
_tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else None
if role == "assistant" and isinstance(_tool_calls, list):
- # Collected rather than appended directly: the turn's reasoning
- # items have to lead it, and whether any of them may be replayed
- # at all is only known once the function_call items survive the
- # server-builtin filter below.
+ # Collected rather than appended directly: the turn's reasoning items have to lead it, and whether any
+ # of them may be replayed at all is only known once the function_call items survive the server-builtin
+ # filter below.
_turn_items: list[dict[str, Any]] = []
- # Emit assistant text before its function_call items to preserve
- # the original response.output ordering.
+ # Emit assistant text before its function_call items to preserve the original response.output
+ # ordering.
if isinstance(content, str) and content:
_turn_items.append({"role": "assistant", "content": content})
elif isinstance(content, list):
@@ -5098,21 +4738,15 @@ class ExternalProviderClient:
_turn_items.append(
responses_function_call(_call_id_out, _fn["name"], _args_raw)
)
- # OpenAI requires the reasoning items that came back alongside a
- # tool call to be replayed with the function_call /
- # function_call_output pair whenever the history is managed by
- # hand, which is exactly what the Unsloth tool loop does: "any
- # reasoning items returned in model responses with tool calls
+ # OpenAI requires the reasoning items that came back alongside a tool call to be replayed with the
+ # function_call / function_call_output pair whenever the history is managed by hand, which is exactly
+ # what the Unsloth tool loop does: "any reasoning items returned in model responses with tool calls
# must also be passed back with tool call outputs"
- # (https://developers.openai.com/api/docs/guides/function-calling).
- # Dropping them loses the model's chain of thought across every
- # local tool hop and misses the prompt cache on the turn after.
- #
- # They lead the turn, matching response.output order, and only
- # when something followed them survived: a trailing reasoning
- # item is a hard 400 ("Item 'rs_...' of type 'reasoning' was
- # provided without its required following item"), so a turn whose
- # calls were all dropped server-side builtins replays none.
+ # (https://developers.openai.com/api/docs/guides/function-calling). Dropping them loses the model's
+ # chain of thought across every local tool hop and misses the prompt cache on the turn after.
+ # They lead the turn, matching response.output order, and only when something following them survived:
+ # a trailing reasoning item is a hard 400 ("Item 'rs_...' of type 'reasoning' was provided without its
+ # required following item"), so a turn whose calls were all dropped server-side builtins replays none.
if _turn_items:
_msg_extra = msg.get("extra_content") if isinstance(msg, dict) else None
_reasoning_replay = (
@@ -5126,8 +4760,8 @@ class ExternalProviderClient:
if _replay:
input_items.append(_replay)
input_items.extend(_turn_items)
- # Assistant text already emitted above (in order) so we don't
- # fall through to the generic content branches.
+ # Assistant text already emitted above (in order) so we do not fall through to the generic content
+ # branches.
continue
if isinstance(content, str):
@@ -5146,8 +4780,8 @@ class ExternalProviderClient:
elif part_type == "image_url":
url = part.get("image_url", {}).get("url", "")
if url:
- # Responses takes image_url as a flat string (both
- # https:// URLs and data: URLs are accepted).
+ # Responses takes image_url as a flat string (both https:// URLs and data: URLs are
+ # accepted).
translated_parts.append({"type": "input_image", "image_url": url})
elif (
part_type == "reasoning"
@@ -5181,12 +4815,11 @@ class ExternalProviderClient:
)
elif part_type == "input_document":
# Map Unsloth's `input_document` onto Responses' `input_file`.
- # https://developers.openai.com/api/docs/guides/images-vision
file_url = part.get("file_url")
file_data = part.get("file_data")
filename = part.get("filename")
- # Treat a "data:" URI with no base64 payload as missing
- # (else file_data="" 400s) and fall back to file_url.
+ # Treat a "data:" URI with no base64 payload as missing (else file_data="" 400s) and fall back
+ # to file_url.
file_data_valid = bool(
isinstance(file_data, str)
and file_data
@@ -5209,11 +4842,10 @@ class ExternalProviderClient:
input_items.append({"role": role, "content": translated_parts})
if previous_response_id:
- # OpenAI's documented multi-turn image generation path can use
- # `previous_response_id` to carry the prior generated image and
- # paired reasoning state. Prefer that over manual item replay when we
- # captured the response id; replay below is a fallback for older
- # stored turns that only have an image_generation_call id.
+ # OpenAI's documented multi-turn image generation path can use `previous_response_id` to carry the prior
+ # generated image and paired reasoning state. Prefer that over manual item replay when we captured the
+ # response id; replay below is a fallback for older stored turns that only have an image_generation_call
+ # id.
openai_replay_items = []
elif (
_openai_image_replay_requires_reasoning(model)
@@ -5258,10 +4890,9 @@ class ExternalProviderClient:
break
input_items[insert_at:insert_at] = openai_replay_items
- # Reasoning families reject temperature/top_p, and the UI hides both
- # sliders for the rest (provider-capabilities.ts), so the only values
- # arriving here are ChatCompletionRequest's 0.6/0.95 defaults, which
- # would override OpenAI's own with a number the user never chose.
+ # Reasoning families reject temperature/top_p, and the UI hides both sliders for the rest
+ # (provider-capabilities.ts), so the only values arriving here are ChatCompletionRequest's 0.6/0.95 defaults,
+ # which would override OpenAI's own with a number the user never chose.
del temperature, top_p # accepted for API symmetry, not forwarded.
body: dict[str, Any] = {
@@ -5271,9 +4902,8 @@ class ExternalProviderClient:
}
if previous_response_id:
body["previous_response_id"] = previous_response_id
- # `summary: "auto"` is what makes /v1/responses emit reasoning summary
- # events; without it the reasoning panel stays blank. Pair it with any
- # explicit effort except "none".
+ # `summary: "auto"` is what makes /v1/responses emit reasoning summary events; without it the reasoning panel
+ # stays blank. Pair it with any explicit effort except "none".
summary_unsupported = bool(
_OPENAI_REASONING_SUMMARY_UNSUPPORTED.match(model.strip().lower())
)
@@ -5299,11 +4929,9 @@ class ExternalProviderClient:
if max_tokens is not None:
body["max_output_tokens"] = max_tokens
- # The Responses API carries structured output on `text.format`; the Chat
- # Completions `response_format` is not part of its contract, so a caller's
- # JSON mode became free prose. The json_schema shape is flattened here:
+ # The Responses API carries structured output on `text.format`; the Chat Completions `response_format` is not
+ # part of its contract, so a caller's JSON mode became free prose. The json_schema shape is flattened here:
# name/schema/strict are siblings of `type`, not nested under json_schema.
- # https://platform.openai.com/docs/guides/structured-outputs
_rf_type = response_format.get("type") if isinstance(response_format, dict) else None
if _rf_type == "json_object":
body["text"] = {"format": {"type": "json_object"}}
@@ -5319,10 +4947,9 @@ class ExternalProviderClient:
}
}
- # Opt into 24h prompt-cache retention (free, vs the default ~5-10 min).
- # Gated on the cloud host because ollama / llama.cpp / "custom" presets
- # reach this path and 400 on the unknown field, and on the model
- # because most cloud families reject the value itself.
+ # Opt into 24h prompt-cache retention (free, vs the default ~5-10 min). Gated on the cloud host because ollama
+ # / llama.cpp / "custom" presets reach this path and 400 on the unknown field, and on the model because most
+ # cloud families reject the value itself.
if (
is_openai_cloud
and enable_prompt_caching is not False
@@ -5331,7 +4958,6 @@ class ExternalProviderClient:
body["prompt_cache_retention"] = "24h"
# Server-side context compaction (OpenAI cloud only).
- # https://developers.openai.com/api/docs/guides/compaction
if is_openai_cloud and compaction_threshold is not None and compaction_threshold > 0:
body["context_management"] = [
{
@@ -5340,9 +4966,7 @@ class ExternalProviderClient:
}
]
- # Map enabled_tools onto Responses-API server tools (cloud only;
- # local OAI-compat backends 400 on these).
- # https://developers.openai.com/api/docs/guides/tools
+ # Map enabled_tools onto Responses-API server tools (cloud only; local OAI-compat backends 400 on these).
code_execution_enabled_openai = bool(
enabled_tools and "code_execution" in enabled_tools and is_openai_cloud
)
@@ -5357,8 +4981,8 @@ class ExternalProviderClient:
tool["action"] = "edit"
return tool
- # Translate Chat-Completions function tools into the Responses
- # function-tool shape (flat name/description/parameters).
+ # Translate Chat-Completions function tools into the Responses function-tool shape (flat
+ # name/description/parameters).
responses_user_function_tools: list[dict[str, Any]] = []
if tools:
for _tool in tools:
@@ -5399,8 +5023,8 @@ class ExternalProviderClient:
responses_tool_choice = {"type": "function", "name": _name}
_responses_tool_choice_none = _responses_tc_string == "none"
- # A pinned user function suppresses hosted builtins (privacy +
- # billing), matching the Gemini / Anthropic / OpenRouter gates.
+ # A pinned user function suppresses hosted builtins (privacy + billing), matching the Gemini / Anthropic /
+ # OpenRouter gates.
_responses_tool_choice_forced_function = (
isinstance(tool_choice, dict)
and tool_choice.get("type") == "function"
@@ -5420,9 +5044,8 @@ class ExternalProviderClient:
):
tools_array.append({"type": "web_search"})
if _responses_hosted_builtins_allowed and code_execution_enabled_openai:
- # Reuse the thread's container so filesystem state persists;
- # auto-create when there isn't one yet. Stale ids 400 and are
- # cleared via container_invalidated.
+ # Reuse the thread's container so filesystem state persists; auto-create when there is not one yet.
+ # Stale ids 400 and are cleared via container_invalidated.
shell_env: dict[str, Any]
if openai_code_exec_container_id:
shell_env = {
@@ -5445,10 +5068,9 @@ class ExternalProviderClient:
logger.info("Proxying OpenAI Responses API to %s (model=%s)", url, model)
def _build_body(container_id_for_this_attempt: Optional[str]) -> dict[str, Any]:
- """Snapshot of the request body. Called once for the initial attempt
- and again with ``None`` for the post-expiry retry. Returns a fresh
- dict so the retry doesn't share state with the first attempt.
- """
+ """Snapshot of the request body. Called once for the initial attempt and again with
+ ``None`` for the post-expiry retry. Returns a fresh dict so the retry does not share
+ state with the first attempt."""
attempt_body = dict(body)
if (enabled_tools or responses_user_function_tools) and not _responses_tool_choice_none:
tools_array_attempt: list[dict[str, Any]] = list(responses_user_function_tools)
@@ -5478,8 +5100,8 @@ class ExternalProviderClient:
return attempt_body
def _is_openai_container_expired_error(error_text: str) -> bool:
- """Substring-match OpenAI's expired/missing code-exec container errors
- (no official error code exists)."""
+ """Substring-match OpenAI's expired/missing code-exec container errors (no official
+ error code exists)."""
lowered = error_text.lower()
if "container" not in lowered:
return False
@@ -5531,46 +5153,41 @@ class ExternalProviderClient:
)
return
- # NOTE: same manual __anext__ loop as stream_chat_completion --
- # see comment there for the GeneratorExit / aclose ordering.
+ # Same manual __anext__ loop as stream_chat_completion -- see there for the GeneratorExit / aclose
+ # ordering.
lines_gen = response.aiter_lines().__aiter__()
done_emitted = False
reasoning_open = False
reasoning_emitted = False
- # Per-call function-tool indexing; distinct slots so
- # parallel calls don't collide on delta.tool_calls[].index.
+ # Per-call function-tool indexing; distinct slots so parallel calls do not collide on
+ # delta.tool_calls[].index.
saw_function_call = False
function_call_index = 0
- # Latched from response.completed/incomplete; surfaces
- # input_tokens_details.cached_tokens to prove cache hits.
+ # Latched from response.completed/incomplete; surfaces input_tokens_details.cached_tokens to prove
+ # cache hits.
last_usage: Optional[dict[str, Any]] = None
- # web_search state. Citations are emitted on text deltas (not
- # per call), so the aggregate list is shared and applied to
- # the LAST web_search tool_end (parseSourcesFromResult
- # flatmaps every call, one non-empty is enough).
+ # web_search state. Citations are emitted on text deltas (not per call), so the aggregate list is
+ # shared and applied to the LAST web_search tool_end (parseSourcesFromResult flatmaps every call,
+ # one non-empty is enough).
web_search_calls: dict[str, dict[str, Any]] = {}
all_url_citations: list[dict[str, Any]] = []
- # shell_calls (code execution): {call_id -> {commands, output}}.
- # shell_call <-> shell_call_output match by call_id; emit
- # tool_start/tool_end like the Anthropic UX.
+ # shell_calls (code execution): {call_id -> {commands, output}}. shell_call and shell_call_output
+ # match by call_id; emit tool_start/tool_end like the Anthropic UX.
shell_calls: dict[str, dict[str, Any]] = {}
- # Container id latched from response.container_id or
- # item.environment.container_id; emit container_ready when it
- # differs from the inbound id.
+ # Container id latched from response.container_id or item.environment.container_id; emit
+ # container_ready when it differs from the inbound id.
latched_container_id: Optional[str] = None
container_id_emitted = False
current_openai_response_id: Optional[str] = None
last_openai_reasoning_replay_item: Optional[dict[str, Any]] = None
openai_reasoning_replay_items: dict[str, dict[str, Any]] = {}
image_generation_calls_started: set[str] = set()
- # Buffer for a citation marker straddling two delta events;
- # prepended onto the next delta. See _split_pending_citation_tail.
+ # Buffer for a citation marker straddling two delta events; prepended onto the next delta. See
+ # _split_pending_citation_tail.
pending_marker_tail: str = ""
- # Segments deferred while their markers reference unseen
- # source_ids; held in arrival order so output never leapfrogs
- # an earlier deferred segment. Flushed on annotation events
- # and force-flushed at end-of-stream with leftover
- # private-use codepoints stripped.
+ # Segments deferred while their markers reference unseen source_ids; held in arrival order so
+ # output never leapfrogs an earlier deferred segment. Flushed on annotation events and
+ # force-flushed at end-of-stream with leftover private-use codepoints stripped.
pending_citation_segments: list[str] = []
def _record_openai_response_id(payload: dict[str, Any]) -> None:
@@ -5586,9 +5203,9 @@ class ExternalProviderClient:
return
def _drain_pending_segments(force: bool) -> str:
- """Re-attempt resolution on buffered segments in order.
- Stops at the first still-unresolved segment unless
- ``force`` (end-of-stream), where lingering markers drop."""
+ """Re-attempt resolution on buffered segments in order. Stops at the first
+ still-unresolved segment unless ``force`` (end-of-stream), where
+ lingering markers drop."""
out: list[str] = []
while pending_citation_segments:
seg = pending_citation_segments[0]
@@ -5610,26 +5227,24 @@ class ExternalProviderClient:
return "".join(out)
def _flush_pending_marker_tail(tail: str) -> str:
- """Render any leftover citation tail at end-of-stream.
-
- Unterminated tails drop (no annotation to bind to). If the
- close byte arrived concatenated, rewrite then scrub any
- residual private-use bytes and any orphan ``cite<sid>``
- literal so the renderer never sees raw markup. url_citations
- are aggregated separately and applied to web_search tool_end.
- """
+ """Render any leftover citation tail at end-of-stream. Unterminated tails
+ drop (no annotation to bind to). If the close byte arrived concatenated,
+ rewrite then scrub any residual private-use bytes and any orphan
+ ``cite<sid>`` literal so the renderer never sees raw markup.
+ url_citations are aggregated separately and applied to web_search
+ tool_end."""
if not tail:
return ""
if _OPENAI_CITE_STOP not in tail:
- # Unterminated: drop the whole tail, else the residual
- # ``cite<sid>`` would leak as plain text.
+ # Unterminated: drop the whole tail, else the residual ``cite<sid>`` would leak as plain
+ # text.
return ""
rendered = _replace_openai_citation_markers(tail, all_url_citations)
# Scrub residual private-use bytes (e.g. a partial opener).
for ch in ("", "", ""):
rendered = rendered.replace(ch, "")
- # Drop any orphan ``cite<sid>`` literal -- meaningless
- # without its closing byte and matching url_citation.
+ # Drop any orphan ``cite<sid>`` literal -- meaningless without its closing byte and matching
+ # url_citation.
rendered = re.sub(r"^cite\S*", "", rendered)
return rendered
@@ -5650,9 +5265,9 @@ class ExternalProviderClient:
return f"data: {_json.dumps(chunk)}"
def _format_shell_output(output: Any) -> str:
- """Render `shell_call_output.output` (stdout/stderr/outcome
- per entry) as the preformatted text CodeExecutionToolUI
- shows; append return_code/(timeout) only when informative."""
+ """Render `shell_call_output.output` (stdout/stderr/outcome per entry) as
+ the preformatted text CodeExecutionToolUI shows; append
+ return_code/(timeout) only when informative."""
if not isinstance(output, list):
return ""
parts: list[str] = []
@@ -5680,10 +5295,9 @@ class ExternalProviderClient:
return "\n--- next command ---\n".join(parts) if parts else "(no output)"
def _record_url_citation(payload: dict[str, Any]) -> None:
- """Append a url_citation, deduped by URL: collect every
- source_id alias onto the entry's ``source_ids`` so the
- rewriter can resolve any alias. The id lives under
- source_id/id/locator across API revisions."""
+ """Append a url_citation, deduped by URL: collect every source_id alias onto
+ the entry's ``source_ids`` so the rewriter can resolve any alias. The id
+ lives under source_id/id/locator across API revisions."""
if payload.get("type") != "url_citation":
return
url = payload.get("url", "")
@@ -5695,9 +5309,8 @@ class ExternalProviderClient:
or payload.get("locator")
or ""
)
- # Single pass: either backfill aliases onto an existing
- # URL entry (and return) or fall through to append a
- # fresh one.
+ # Single pass: either backfill aliases onto an existing URL entry (and return) or fall through
+ # to append a fresh one.
for c in all_url_citations:
if c["url"] != url:
continue
@@ -5790,8 +5403,8 @@ class ExternalProviderClient:
out.append(text)
return "".join(out)
if isinstance(payload, dict):
- # OpenAI responses carry reasoning summaries in
- # different envelope fields across event variants.
+ # OpenAI responses carry reasoning summaries in different envelope fields across event
+ # variants.
for key in ("text", "delta", "content", "summary"):
if key in payload:
text = _extract_reasoning_text(payload.get(key))
@@ -5824,8 +5437,8 @@ class ExternalProviderClient:
except StopAsyncIteration:
break
if not line:
- # A name never carries past the blank line that ends its event,
- # or a stale `response.failed` would fail a later frame.
+ # A name never carries past the blank line that ends its event, or a stale
+ # `response.failed` would fail a later frame.
sse_event_name = ""
continue
if line.startswith("event:"):
@@ -5838,8 +5451,8 @@ class ExternalProviderClient:
if not data_str:
continue
if data_str == "[DONE]":
- # Flush any held-over partial marker; strip
- # private-use bytes so garbled glyphs don't leak.
+ # Flush any held-over partial marker; strip private-use bytes so garbled glyphs do not
+ # leak.
if pending_marker_tail:
flushed = _flush_pending_marker_tail(pending_marker_tail)
pending_marker_tail = ""
@@ -5848,8 +5461,7 @@ class ExternalProviderClient:
yield _chunk_with_text("</think>")
reasoning_open = False
yield _chunk_with_text(flushed)
- # Force-drain any segment still awaiting an
- # annotation; lingering codepoints drop.
+ # Force-drain any segment still awaiting an annotation; lingering codepoints drop.
tail_flushed = _drain_pending_segments(
force = True,
)
@@ -5871,13 +5483,12 @@ class ExternalProviderClient:
try:
event_type = response_event_type(event, sse_event_name)
except ValueError:
- # An OpenAI-compatible endpoint behind this base URL can answer
- # a Responses request with Chat Completions frames, so skipping
- # an unrecognisable frame beats failing the whole completion.
- # The ChatGPT path stays strict, where the shape is guaranteed.
- # An error payload is the exception: the bare {"error": ...} an
- # OpenAI-compatible proxy emits has no type and no event name
- # either, so skipping it returned zero chunks and no error.
+ # An OpenAI-compatible endpoint behind this base URL can answer a Responses request
+ # with Chat Completions frames, so skipping an unrecognisable frame beats failing the
+ # whole completion. The ChatGPT path stays strict, where the shape is guaranteed. An
+ # error payload is the exception: the bare {"error": ...} an OpenAI-compatible proxy
+ # emits has no type and no event name either, so skipping it returned zero chunks and
+ # no error.
if isinstance(event, dict) and isinstance(
event.get("error"), (dict, str)
):
@@ -5892,16 +5503,15 @@ class ExternalProviderClient:
if event_type == "response.output_text.delta":
delta_text = event.get("delta", "")
- # Process inline annotations first so source_ids
- # referenced by same-delta markers are in the
- # lookup before the rewriter runs. Some API
- # versions inline url citations on the delta event.
+ # Process inline annotations first so source_ids referenced by same-delta markers are
+ # in the lookup before the rewriter runs. Some API versions inline url citations on
+ # the delta event.
for ann in event.get("annotations") or []:
if isinstance(ann, dict):
_record_url_citation(ann)
if delta_text or pending_marker_tail:
- # Prepend any held-over tail so a marker
- # straddling two SSE events resolves cleanly.
+ # Prepend any held-over tail so a marker straddling two SSE events resolves
+ # cleanly.
combined = pending_marker_tail + delta_text
head, pending_marker_tail = _split_pending_citation_tail(
combined
@@ -5910,10 +5520,8 @@ class ExternalProviderClient:
if reasoning_open:
yield _chunk_with_text("</think>")
reasoning_open = False
- # Re-attempt earlier deferred segments
- # first so output stays in order; the
- # needed annotation may have arrived
- # inline above.
+ # Re-attempt earlier deferred segments first so output stays in order; the
+ # needed annotation may have arrived inline above.
flushed = _drain_pending_segments(
force = False,
)
@@ -5951,9 +5559,8 @@ class ExternalProviderClient:
item_id,
_extract_web_search_action(item),
)
- # Register shell_call eagerly so out-of-order
- # output links back. Probe env.container_id to
- # emit container_ready before response.completed.
+ # Register shell_call eagerly so out-of-order output links back. Probe
+ # env.container_id to emit container_ready before response.completed.
if isinstance(item, dict) and item.get("type") == "shell_call":
item_id = item.get("id", "") or (f"sc_{len(shell_calls)}")
shell_calls.setdefault(
@@ -6005,13 +5612,11 @@ class ExternalProviderClient:
yield _chunk_with_text(summary_text)
reasoning_emitted = True
elif item.get("type") == "web_search_call":
- # done carries the action; emit tool_start +
- # tool_end here. Citations are aggregated and
- # the last call's result is overwritten at
- # response.completed.
+ # done carries the action; emit tool_start + tool_end here. Citations are
+ # aggregated and the last call's result is overwritten at response.completed.
item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")
- # Overlay, don't replace: a partial done event
- # would drop what the added event carried.
+ # Overlay, do not replace: a partial done event would drop what the added event
+ # carried.
arguments = {
**web_search_calls.get(item_id, {}),
**_extract_web_search_action(item),
@@ -6025,10 +5630,9 @@ class ExternalProviderClient:
"arguments": arguments,
}
)
- # Per-card text; last call gets overwritten
- # with citations at response.completed. The
- # url variants have no query to echo, and the
- # card names the page from `url` instead.
+ # Per-card text; the last call gets overwritten with citations at
+ # response.completed. The url variants have no query to echo, so the card names
+ # the page from `url` instead.
query = arguments.get("query") or ""
per_call_result = f"Searching: {query}" if query else ""
yield _emit_tool_event(
@@ -6039,10 +5643,8 @@ class ExternalProviderClient:
}
)
elif item.get("type") == "shell_call":
- # Join the action.commands array into one
- # newline-separated string (the card renderer,
- # shared with Anthropic bash, wants a single
- # `command`).
+ # Join the action.commands array into one newline-separated string (the card
+ # renderer, shared with Anthropic bash, wants a single `command`).
item_id = item.get("id", "") or (f"sc_{len(shell_calls)}")
action = item.get("action") or {}
commands = (
@@ -6075,8 +5677,7 @@ class ExternalProviderClient:
},
}
)
- # Fallback: output may be bundled on the
- # shell_call done event itself.
+ # Fallback: output may be bundled on the shell_call done event itself.
embedded_output = item.get("output")
if isinstance(embedded_output, list) and embedded_output:
shell_calls[item_id]["output"] = embedded_output
@@ -6089,14 +5690,12 @@ class ExternalProviderClient:
}
)
elif item.get("type") == "shell_call_output":
- # `call_id` links back to the shell_call's
- # `id`, used as the tool_call_id on
- # tool_start. Match on call_id when present so
- # the matching card transitions to complete.
+ # `call_id` links back to the shell_call's `id`, used as the tool_call_id on
+ # tool_start. Match on call_id when present so the matching card transitions to
+ # complete.
call_id = item.get("call_id") or item.get("id") or ""
output = item.get("output") or []
- # Skip if bundled-output path already
- # finalised this card.
+ # Skip if the bundled-output path already finalised this card.
if shell_calls.get(call_id, {}).get("tool_end_emitted"):
continue
if call_id in shell_calls:
@@ -6111,9 +5710,8 @@ class ExternalProviderClient:
}
)
elif item.get("type") == "image_generation_call":
- # Base64 image on `result` (or `b64_json`),
- # `revised_prompt` for the rewritten prompt.
- # ns-resolution id so concurrent gens are unique.
+ # Base64 image on `result` (or `b64_json`), `revised_prompt` for the rewritten
+ # prompt. ns-resolution id so concurrent gens are unique.
raw_item_id = item.get("id")
item_id = raw_item_id or f"img_{time.time_ns()}"
prompt_in = (
@@ -6150,7 +5748,6 @@ class ExternalProviderClient:
)
elif item.get("type") == "function_call":
# Translate to Chat-Completions delta.tool_calls.
- # https://platform.openai.com/docs/guides/function-calling?api-mode=responses
fn_call_id = (
item.get("call_id")
or item.get("id")
@@ -6211,9 +5808,8 @@ class ExternalProviderClient:
completed_usage = (event.get("response") or {}).get("usage")
if isinstance(completed_usage, dict):
last_usage = completed_usage
- # Flush any unterminated citation tail; by now all
- # annotations are recorded, else private-use bytes
- # are stripped.
+ # Flush any unterminated citation tail; by now all annotations are recorded, else
+ # private-use bytes are stripped.
if pending_marker_tail:
flushed = _flush_pending_marker_tail(pending_marker_tail)
pending_marker_tail = ""
@@ -6234,9 +5830,8 @@ class ExternalProviderClient:
if reasoning_open:
yield _chunk_with_text("</think>")
reasoning_open = False
- # Scan response.container_id and response.container.id
- # (docs don't pin the field); emit container_ready
- # only when it differs from the inbound id.
+ # Scan response.container_id and response.container.id (the docs do not pin the
+ # field); emit container_ready only when it differs from the inbound id.
response_obj = event.get("response") or {}
if isinstance(response_obj, dict):
probe_id = response_obj.get("container_id")
@@ -6262,8 +5857,8 @@ class ExternalProviderClient:
}
)
container_id_emitted = True
- # Overwrite the last web_search card with the
- # citation list (the extractor flatMaps cards).
+ # Overwrite the last web_search card with the citation list (the extractor flatMaps
+ # cards).
if web_search_calls and all_url_citations:
last_id = list(web_search_calls.keys())[-1]
blocks: list[str] = []
@@ -6279,8 +5874,7 @@ class ExternalProviderClient:
"result": "\n---\n".join(blocks),
}
)
- # Final flush: finalise any orphan shell_call
- # so the card stops spinning.
+ # Final flush: finalise any orphan shell_call so the card stops spinning.
for sc_id, sc_state in shell_calls.items():
if sc_state.get("tool_end_emitted"):
continue
@@ -6294,15 +5888,10 @@ class ExternalProviderClient:
}
)
sc_state["tool_end_emitted"] = True
- # Hand this turn's reasoning items back so the
- # next request can replay them beside the
- # function_call they belong to; the tool loop
- # latches delta.extra_content onto the assistant
- # message it rebuilds. Only on a turn that
- # actually called a tool: prose needs none, and
- # shipping them would grow every following body
- # for nothing. Mirrors the openai_codex client's
- # openai_codex_reasoning.
+ # Hand this turn's reasoning items back so the next request can replay them beside the
+ # function_call they belong to; the tool loop latches delta.extra_content onto the
+ # assistant message it rebuilds. Only on a turn that actually called a tool: prose
+ # needs none, and shipping them would grow every following body for nothing.
_terminal_delta: dict[str, Any] = {}
if saw_function_call and openai_reasoning_replay_items:
_terminal_delta["extra_content"] = {
@@ -6324,8 +5913,7 @@ class ExternalProviderClient:
],
}
yield f"data: {_json.dumps(chunk)}"
- # Emit include_usage-style chunk after the
- # finish_reason so callers can surface
+ # Emit include_usage-style chunk after the finish_reason so callers can surface
# cached_tokens in their UI.
usage_line = _build_usage_chunk(
completion_id,
@@ -6339,8 +5927,8 @@ class ExternalProviderClient:
incomplete_usage = (event.get("response") or {}).get("usage")
if isinstance(incomplete_usage, dict):
last_usage = incomplete_usage
- # Same flush as response.completed -- truncated
- # streams can leave a half-marker in the buffer.
+ # Same flush as response.completed -- truncated streams can leave a half-marker in the
+ # buffer.
if pending_marker_tail:
flushed = _flush_pending_marker_tail(pending_marker_tail)
pending_marker_tail = ""
@@ -6349,8 +5937,7 @@ class ExternalProviderClient:
yield _chunk_with_text("</think>")
reasoning_open = False
yield _chunk_with_text(flushed)
- # Force-drain any segment still awaiting an
- # annotation; lingering codepoints drop.
+ # Force-drain any segment still awaiting an annotation; lingering codepoints drop.
tail_flushed = _drain_pending_segments(
force = True,
)
@@ -6378,8 +5965,7 @@ class ExternalProviderClient:
"result": "\n---\n".join(blocks),
}
)
- # Mirror the response.completed flush so
- # truncated streams also finalise orphan
+ # Mirror the response.completed flush so truncated streams also finalise orphan
# shell_calls.
for sc_id, sc_state in shell_calls.items():
if sc_state.get("tool_end_emitted"):
@@ -6406,8 +5992,7 @@ class ExternalProviderClient:
],
}
yield f"data: {_json.dumps(chunk)}"
- # Emit include_usage-style chunk after the
- # length-truncated finish_reason too, so
+ # Emit include_usage-style chunk after the length-truncated finish_reason too, so
# incomplete responses still report cached_tokens.
usage_line = _build_usage_chunk(
completion_id,
@@ -6418,8 +6003,8 @@ class ExternalProviderClient:
yield usage_line
elif event_type in ("response.failed", "error"):
- # Surface the failure to the client; the outer
- # route emits [DONE] as part of its cleanup.
+ # Surface the failure to the client; the outer route emits [DONE] as part of its
+ # cleanup.
yield _error_sse_line(
502,
_openai_response_error_message(event),
@@ -6438,8 +6023,7 @@ class ExternalProviderClient:
queries = [
sc["query"] for sc in web_search_calls.values() if sc.get("query")
]
- # On /v1/responses cached tokens live at
- # usage.input_tokens_details.cached_tokens (not
+ # On /v1/responses cached tokens live at usage.input_tokens_details.cached_tokens (not
# prompt_tokens_details, the chat/completions shape).
cached_input_tokens = None
if isinstance(last_usage, dict):
@@ -6511,12 +6095,10 @@ class ExternalProviderClient:
max_tokens: Optional[int] = None,
presence_penalty: float = 0.0,
) -> dict[str, Any]:
- """Non-streaming chat completion. Returns the full response dict.
-
- Only valid for OpenAI-compatible providers. Anthropic requires its own
- Messages API; use stream_chat_completion (with stream=False) if a
- non-streaming Anthropic path is needed later.
- """
+ """Non-streaming chat completion. Returns the full response dict. Only valid for
+ OpenAI-compatible providers: Anthropic requires its own Messages API, so use
+ stream_chat_completion (with stream=False) if a non-streaming Anthropic path is needed
+ later."""
body: dict[str, Any] = {
"model": model,
"messages": messages,
@@ -6629,12 +6211,8 @@ class ExternalProviderClient:
return response.content, media_type
async def list_models(self) -> list[dict[str, Any]]:
- """GET /models to discover available models.
-
- Returns dicts with at least 'id'. All providers expose /models with the
- OpenAI {"data": [...]} shape (Anthropic included:
- https://api.anthropic.com/v1/models).
- """
+ """GET /models to discover available models. Returns dicts with at least 'id'. All providers
+ expose /models with the OpenAI {"data": [...]} shape, Anthropic included."""
try:
response = await _http_client.get(
f"{self.base_url}/models",
@@ -6651,8 +6229,8 @@ class ExternalProviderClient:
models = [model for model in raw_models if isinstance(model, dict)]
if not models and self.provider_type == "ollama":
models = await self._list_ollama_native_models()
- # Gemini's native /v1beta/models uses a different shape; repackage
- # into the OpenAI-compatible one Unsloth expects.
+ # Gemini's native /v1beta/models uses a different shape; repackage into the OpenAI-compatible one Unsloth
+ # expects.
if not models and self.provider_type == "gemini":
models = self._parse_gemini_models(data)
return models
@@ -6662,10 +6240,9 @@ class ExternalProviderClient:
@staticmethod
def _parse_gemini_models(payload: Any) -> list[dict[str, Any]]:
- """Translate Gemini's native /v1beta/models payload to OpenAI shape,
- keeping only entries advertising generateContent / streamGenerateContent
- so embedding-only models don't reach the chat picker.
- """
+ """Translate Gemini's native /v1beta/models payload to OpenAI shape, keeping only entries
+ advertising generateContent / streamGenerateContent so embedding-only models do not reach
+ the chat picker."""
if not isinstance(payload, dict):
return []
entries = payload.get("models") or []
@@ -6684,8 +6261,7 @@ class ExternalProviderClient:
continue
base_id = entry.get("baseModelId")
name = entry.get("name") or ""
- # ``name`` arrives as ``"models/gemini-2.5-flash"``; the chat path
- # uses the bare id.
+ # ``name`` arrives as ``"models/gemini-2.5-flash"``; the chat path uses the bare id.
short_id = (
base_id
if isinstance(base_id, str) and base_id
@@ -6724,12 +6300,9 @@ class ExternalProviderClient:
]
async def verify_models_endpoint_lightweight(self) -> None:
- """
- Confirm GET /models returns 200 without buffering the full response body.
-
- Used for providers with enormous catalogs (e.g. OpenRouter, Hugging Face
- router) where downloading the full JSON would be prohibitive.
- """
+ """Confirm GET /models returns 200 without buffering the full response body. Used for
+ providers with enormous catalogs (e.g. OpenRouter, Hugging Face router) where downloading
+ the full JSON would be prohibitive."""
url = f"{self.base_url}/models"
try:
async with _http_client.stream(
@@ -6751,17 +6324,15 @@ class ExternalProviderClient:
raise
def _container_headers(self) -> dict[str, str]:
- """Auth headers plus the required ``OpenAI-Beta: containers=v1`` opt-in;
- without it DELETE silently no-ops (returns deleted:true but keeps the
- container, verified 2026-05-15)."""
+ """Auth headers plus the required ``OpenAI-Beta: containers=v1`` opt-in; without it DELETE
+ silently no-ops (returns deleted:true but keeps the container, verified 2026-05-15)."""
headers = self._auth_headers()
headers["OpenAI-Beta"] = "containers=v1"
return headers
async def list_openai_containers(self) -> list[dict[str, Any]]:
- """GET /v1/containers; returns raw container records (the route reshapes
- them). Only valid against api.openai.com (caller guards is_openai_cloud).
- """
+ """GET /v1/containers; returns raw container records (the route reshapes them). Only valid
+ against api.openai.com (caller guards is_openai_cloud)."""
response = await _http_client.get(
f"{self.base_url}/containers",
headers = self._container_headers(),
@@ -6779,11 +6350,8 @@ class ExternalProviderClient:
return result
async def create_openai_container(self, name: str, ttl_minutes: int) -> dict[str, Any]:
- """
- POST /v1/containers with ``expires_after.anchor="last_active_at"``.
- ``ttl_minutes`` is the idle timeout — every API call touching the
- container resets the timer.
- """
+ """POST /v1/containers with ``expires_after.anchor="last_active_at"``. ``ttl_minutes`` is
+ the idle timeout -- every API call touching the container resets the timer."""
body = {
"name": name,
"expires_after": {
@@ -6801,12 +6369,10 @@ class ExternalProviderClient:
return response.json()
async def delete_openai_container(self, container_id: str) -> None:
- """DELETE /v1/containers/{id}. 404s surface as HTTPError.
-
- Uses a fresh httpx client (shared-pool DELETEs returned deleted:true but
- left the container alive). Also verifies the body reports deleted:true,
- since OpenAI 2xx-returns that even when silently rejecting the request.
- """
+ """DELETE /v1/containers/{id}. 404s surface as HTTPError. Uses a fresh httpx client
+ (shared-pool DELETEs returned deleted:true but left the container alive), and verifies
+ the body reports deleted:true, since OpenAI 2xx-returns that even when silently rejecting
+ the request."""
url = f"{self.base_url}/containers/{container_id}"
headers = self._container_headers()
logger.info(
@@ -6876,12 +6442,9 @@ def _friendly_provider_error_text(
def _readable_provider_error(status_code: int, message: str, provider_type: str) -> str:
- """Reduce an upstream error body to the sentence it carries.
-
- OpenAI, Anthropic and Gemini all nest the text under `error`, so the raw
- body would otherwise reach the UI as a JSON blob. Non-JSON input (already
- friendly text) passes through unchanged.
- """
+ """Reduce an upstream error body to the sentence it carries. OpenAI, Anthropic and Gemini all
+ nest the text under `error`, so the raw body would otherwise reach the UI as a JSON blob.
+ Non-JSON input (already friendly text) passes through unchanged."""
import json
try:
@@ -6904,8 +6467,8 @@ def _readable_provider_error(status_code: int, message: str, provider_type: str)
None,
)
if not isinstance(text, str) or not text.strip():
- # FastAPI-style bodies (vllm, llama.cpp, custom OpenAI-compat) carry
- # `detail`: a string, or a validation list of `{msg, loc}` entries.
+ # FastAPI-style bodies (vllm, llama.cpp, custom OpenAI-compat) carry `detail`: a string, or a validation
+ # list of `{msg, loc}` entries.
detail = payload.get("detail")
if isinstance(detail, str):
text = detail
@@ -6918,8 +6481,8 @@ def _readable_provider_error(status_code: int, message: str, provider_type: str)
text = "; ".join(msgs) or None
if not isinstance(text, str) or not text.strip():
- # Not JSON means already-friendly text: collapse whitespace and cap so
- # a stray HTML page can't flood the chat.
+ # Not JSON means already-friendly text: collapse whitespace and cap so a stray HTML page cannot flood the
+ # chat.
raw = " ".join(message.split())[:500] if isinstance(message, str) else ""
if isinstance(payload, dict) or not raw:
return f"{provider_type} returned HTTP {status_code} with no error details."
@@ -6935,10 +6498,9 @@ def _error_sse_line(
provider_type: str,
retry_after: str | None = None,
) -> str:
- """Format an error as an SSE data line in OpenAI error format.
-
- ``retry_after`` carries the upstream Retry-After through: this stream is delivered under a
- 200, so a client that backs off has nowhere else to read the delay from."""
+ """Format an error as an SSE data line in OpenAI error format. ``retry_after`` carries the
+ upstream Retry-After through: this stream is delivered under a 200, so a client that backs
+ off has nowhere else to read the delay from."""
import json
error: dict[str, str] = {
@@ -6955,20 +6517,16 @@ def _error_sse_line(
def _build_usage_chunk(
completion_id: str, provider: Literal["anthropic", "openai"], last_usage: Optional[dict]
) -> Optional[str]:
- """Build an OpenAI ``include_usage``-style SSE chunk carrying upstream
- prompt-cache accounting back to the client.
+ """Build an OpenAI ``include_usage``-style SSE chunk carrying upstream prompt-cache accounting back
+ to the client.
Emits the standard chunk shape (``choices: []`` + ``usage`` block) so
- ``stream_options={"include_usage": true}`` clients keep working, plus the
- Anthropic-native counts as extra keys:
- usage.prompt_tokens_details.cached_tokens (both providers)
- usage.cache_creation_input_tokens (Anthropic-only)
- usage.cache_read_input_tokens (Anthropic-only)
-
- Anthropic's ``input_tokens`` excludes the cache buckets, so prompt_tokens
- sums all three (OpenAI Responses already folds cached tokens in).
-
- Returns ``None`` when there are no usage numbers to report.
+ ``stream_options={"include_usage": true}`` clients keep working, plus the Anthropic-native
+ counts as extra keys: usage.prompt_tokens_details.cached_tokens (both providers),
+ usage.cache_creation_input_tokens and usage.cache_read_input_tokens (Anthropic-only).
+ Anthropic's ``input_tokens`` excludes the cache buckets, so prompt_tokens sums all three (OpenAI
+ Responses already folds cached tokens in). Returns ``None`` when there are no usage numbers to
+ report.
"""
if not isinstance(last_usage, dict):
return None
@@ -6990,14 +6548,13 @@ def _build_usage_chunk(
"cache_creation_input_tokens": cache_creation,
"cache_read_input_tokens": cache_read,
}
- # Forward 5m/1h cache-write breakdown so cost calc applies the 2x 1h
- # premium instead of defaulting to 5m on chat-style.
+ # Forward the 5m/1h cache-write breakdown so cost calc applies the 2x 1h premium instead of defaulting to 5m
+ # on chat-style.
cc_breakdown = last_usage.get("cache_creation")
if isinstance(cc_breakdown, dict) and cc_breakdown:
usage_block["cache_creation"] = cc_breakdown
- # Propagate fast-mode `usage.speed` so the cost ledger applies the 6x
- # multiplier without re-derivation (Anthropic falls back to "standard"
- # when fast-mode is unsupported or rate-limited).
+ # Propagate fast-mode `usage.speed` so the cost ledger applies the 6x multiplier without re-derivation
+ # (Anthropic falls back to "standard" when fast-mode is unsupported or rate-limited).
speed = last_usage.get("speed")
if speed in ("fast", "standard"):
usage_block["speed"] = speed
@@ -7015,11 +6572,9 @@ def _build_usage_chunk(
"total_tokens": prompt_tokens + completion_tokens,
"prompt_tokens_details": {"cached_tokens": cached},
}
- # Surface OpenAI Responses / Gemini reasoning-token detail. The caller
- # pre-populates last_usage["output_tokens_details"] with at least
- # {"reasoning_tokens": ...}; mirror it into the OAI
- # `completion_tokens_details` shape so SDKs can render the
- # hidden-thoughts slice.
+ # Surface OpenAI Responses / Gemini reasoning-token detail. The caller pre-populates
+ # last_usage["output_tokens_details"] with at least {"reasoning_tokens": ...}; mirror it into the OAI
+ # `completion_tokens_details` shape so SDKs can render the hidden-thoughts slice.
out_details = last_usage.get("output_tokens_details")
if isinstance(out_details, dict) and out_details:
usage_block["completion_tokens_details"] = {
diff --git a/studio/backend/core/inference/gallery_flags.py b/studio/backend/core/inference/gallery_flags.py
index 7a6b36c6b1e..3a6deedf68f 100644
--- a/studio/backend/core/inference/gallery_flags.py
+++ b/studio/backend/core/inference/gallery_flags.py
@@ -100,7 +100,6 @@ def _load(directory: Path) -> tuple[dict[str, Any], bool]:
try:
with open(_store_path(directory), encoding = "utf-8-sig") as f:
data = json.load(f)
- # validate the shape, not just the version
# Validate the shape, not just the version: a hand-edited ``items`` that is not a dict (e.g. ``[]``) would
# otherwise crash every lookup instead of failing safe.
if (
@@ -111,11 +110,10 @@ def _load(directory: Path) -> tuple[dict[str, Any], bool]:
# Written over an illegible store, so what it does NOT say is not evidence.
if data.get(_TAINT_KEY):
return data, False
- # every ENTRY must be readable too: a malformed value is dropped by the readers
# Every ENTRY has to be readable too, not just the container. A malformed value is dropped by the readers
# below, which reads as "this id is not archived" -- enough for clear() to delete an archived file. So one
- # bad entry costs the store its trust, but the surviving entries are still returned: listing should keep the
- # flags it can read, and only destructive callers need to refuse.
+ # bad entry costs the store its trust, but the surviving entries are still returned: listing should keep
+ # the flags it can read, and only destructive callers need to refuse.
if all(_valid_entry(v) for v in data["items"].values()):
return data, True
logger.warning(
@@ -331,11 +329,10 @@ def set_flags_locked(
write land as one step. Separate for the same per-descriptor lock reason as ``forget_locked``."""
import time
- # a write REPAIRS the store: merging the bad entry back would leave every later clear() refused
- # A write REPAIRS the store rather than preserving what made it untrusted. Merging the bad entry straight back would
- # leave every later clear() refused until someone fixed the file by hand, and refusing here instead would leave the
- # user unable to pin anything at all. Dropping only the unreadable entries keeps the flags that still mean
- # something.
+ # A write REPAIRS the store rather than preserving what made it untrusted. Merging the bad entry straight back
+ # would leave every later clear() refused until someone fixed the file by hand, and refusing here instead would
+ # leave the user unable to pin anything at all. Dropping only the unreadable entries keeps the flags that still
+ # mean something.
data = _carry_taint(*_load(directory))
items: dict[str, Any] = {}
for key, value in data.get("items", {}).items():
@@ -346,10 +343,9 @@ def set_flags_locked(
entry = dict(_entry(items, item_id))
if pinned is not None:
if pinned:
- # strictly ahead of every stored stamp, not just the wall clock
# Strictly ahead of every stamp stored, not just the wall clock: Windows advances time.time() in ~16 ms
- # steps, so two pins a click apart landed on the same value and "most recently pinned leads" stopped holding
- # for exactly the case the client serializes its PATCHes to preserve.
+ # steps, so two pins a click apart landed on the same value and "most recently pinned leads" stopped
+ # holding for exactly the case the client serializes its PATCHes to preserve.
latest = max(
(_pinned_at(v) for v in items.values() if _pinned_at(v) is not None),
default = float("-inf"),
diff --git a/studio/backend/core/inference/generation_timing.py b/studio/backend/core/inference/generation_timing.py
index b525ccd37f2..d65c575e8c8 100644
--- a/studio/backend/core/inference/generation_timing.py
+++ b/studio/backend/core/inference/generation_timing.py
@@ -35,7 +35,6 @@ def _wait_for_device(device):
except TypeError: # torch.mps.synchronize takes no device argument
synchronize()
except Exception:
- # an async device fault belongs to generate(); a timing stamp must not pre-empt it or skip cleanup
# An async device fault surfaces here as a RuntimeError. It belongs to generate(), whose caller reports it; a
# timing stamp must not pre-empt that or skip the cleanup after it.
pass
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index 5f57595debf..03af008af58 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -40,7 +40,6 @@ def _evict_chat() -> None:
from core.inference.llama_cpp import chat_load_active
llama = get_llama_cpp_backend()
- # is_active, not is_loaded: a model still starting holds VRAM
# is_active (process exists), not is_loaded (exists AND healthy): a chat model still starting up holds VRAM but is
# not healthy. chat_load_active too, since an HF load has no process until its GGUF downloaded. unload_model sets
# the cancel event the download loop polls, so it aborts.
@@ -56,7 +55,6 @@ def _evict_chat() -> None:
orchestrator.cancel_load(pending)
# Kill the subprocess too: its base CUDA context holds VRAM diffusion needs.
orchestrator._shutdown_subprocess(timeout = 5.0)
- # the driver reclaims killed VRAM asynchronously, else a warm handoff can transiently OOM
# The driver reclaims the killed VRAM asynchronously, so wait for it to settle before diffusion allocates, else a
# warm handoff can transiently OOM.
llama._wait_for_vram_settle(since_kill = time.monotonic())
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 81fb905542a..52cd44dbb9b 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -70,7 +70,6 @@ def save(image: Any, meta: dict[str, Any]) -> dict[str, Any]:
image_id = uuid.uuid4().hex
directory = gallery_dir()
final_path = directory / f"{image_id}.png"
- # dotted temp (skipped by the *.png glob) then atomic rename
# Write to a dotted temp (skipped by the *.png glob) then atomically rename, so a crash mid-write never leaves a
# truncated {id}.png in the listing.
tmp_path = directory / f".{image_id}.png.tmp"
@@ -121,9 +120,8 @@ def image_b64(image_id: str) -> Optional[str]:
return base64.b64encode(path.read_bytes()).decode("ascii")
-# a PNG missing any is skipped as foreign, so a hand-dropped or older-schema file cannot 500 the listing
-# Required recipe keys (GalleryImage fields minus id/url). A PNG missing any is skipped as foreign, so a hand-dropped or
-# older-schema file cannot 500 the listing.
+# Required recipe keys (GalleryImage fields minus id/url). A PNG missing any is skipped as foreign, so a hand-dropped
+# or older-schema file cannot 500 the listing.
_REQUIRED_META = ("prompt", "width", "height", "steps", "guidance", "seed", "created_at")
@@ -190,13 +188,10 @@ def list_images(
except OSError:
return []
flags = gallery_flags.read(gallery_dir())
- # both run on file stems BEFORE any recipe is read
# Both the shelf split and the pin sort run on file stems, BEFORE any recipe is read, so they cost one dict lookup
# per file and leave the early break below intact.
paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
paths.sort(key = lambda p: (gallery_flags.pin_rank(flags, p.stem), _mtime(p)), reverse = True)
- # page over READABLE records: filtering a foreign PNG out of an already-sliced window would drop valid images and
- # make has_more wrong.
# Page over READABLE records, not raw files: filtering a foreign PNG out of an already-sliced window would drop
# valid images and make has_more wrong. Known limit: this re-reads headers from newest down to `offset+limit` per
# page, so a deep scroll is O(offset) header-opens.
@@ -289,7 +284,6 @@ def clear(include_archived: bool = False) -> int:
cleared.append(path.stem)
except OSError:
continue
- # once every image we own is gone an unreadable store protects nothing
# Nothing left for an unreadable store to protect once every image we own is gone, so this is where the escape
# hatch escapes: replace it, or every later default clear still refuses.
if include_archived and not gallery_flags.is_trusted(directory):
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 11617b8383a..fb0f8d7aab0 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -110,20 +110,15 @@ class HarmonyTextStreamer:
self._is_first_put: bool = True
self._stop: bool = False
- # Stateful channel tracking avoids delta-on-transformed bugs
self._emitted_think_open: bool = False
self._emitted_think_close: bool = False
- self._analysis_emitted: int = 0 # chars of analysis content emitted
- self._final_emitted: int = 0 # chars of final content emitted
-
- # put / end — called from the generation thread
+ self._analysis_emitted: int = 0
+ self._final_emitted: int = 0
def put(self, value):
- """Receive new token IDs from model.generate()."""
import torch
if isinstance(value, torch.Tensor):
- # shape (batch, seq) — take first batch element
ids = value[0].tolist() if value.dim() > 1 else value.tolist()
elif isinstance(value, (list, tuple)):
ids = list(value)
@@ -131,7 +126,6 @@ class HarmonyTextStreamer:
ids = [value]
if self._is_first_put and self.skip_prompt:
- # First call is the full prompt; remember its length.
self._prompt_len = len(ids)
self._token_ids = list(ids)
self._is_first_put = False
@@ -139,28 +133,22 @@ class HarmonyTextStreamer:
self._token_ids.extend(ids)
- # Decode only the generated part (after the prompt).
gen_ids = self._token_ids[self._prompt_len :]
raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)
self._process_incremental(raw)
def end(self):
- """Signal generation is complete."""
- # Final decode to capture remaining content.
gen_ids = self._token_ids[self._prompt_len :]
if gen_ids:
raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)
self._process_incremental(raw)
- # Close any open think tags.
if self._emitted_think_open and not self._emitted_think_close:
self._queue.put("</think>")
self._emitted_think_close = True
self._stop = True
- self._queue.put(None) # sentinel
-
- # Iterator interface — consumed by the streaming loop
+ self._queue.put(None)
def __iter__(self):
return self
@@ -178,16 +166,12 @@ class HarmonyTextStreamer:
raise StopIteration
return val
- # Stateful incremental harmony protocol parsing
-
def _process_incremental(self, raw: str) -> None:
"""Parse harmony channels and emit per-channel deltas (tracked by length, not whole-text diff)."""
- # If raw has <|channel|> but no complete channel+message pair yet, buffer.
has_channel_token = "<|channel|>" in raw
matches = list(self._HARMONY_RE.finditer(raw))
if has_channel_token and not matches:
- # Partial harmony markup still building — wait for more tokens.
return
if not has_channel_token and not matches:
@@ -301,7 +285,7 @@ class InferenceBackend:
self.models = {}
self.active_model_name = None
self.loading_models = set()
- self.loaded_local_models = [] # [(display_name, path), ...]
+ self.loaded_local_models = []
from core.inference.defaults import get_default_models
self.default_models = get_default_models()
@@ -325,21 +309,19 @@ class InferenceBackend:
return 0 if top_k < 0 else top_k
def _resolve_chat_eos(self, model_name: str) -> None:
- """Resolve this chat model's assistant-turn-end stop tokens once at load,
- cache them in model_info, and repair generation_config so every
- ``.generate()`` path stops at the turn boundary.
-
- Some checkpoints (e.g. Qwen3.5 / Qwen3.6 small chat models) end turns with
- ``<|im_end|>`` but ship ``config.eos_token_id = <|endoftext|>`` and no
- ``generation_config.json``, so paths that read ``generation_config`` (the
- vision path, tool loops) run past the turn and loop. Turn-end markers are
- derived from the chat_template (see chat_eos.resolve_chat_turn_end_eos_ids),
- so base/coder models and harmony templates are left untouched.
+ """Resolve this chat model's assistant-turn-end stop tokens once at load, cache them in
+ model_info, and repair generation_config.
+
+ Some checkpoints (Qwen3.5 / Qwen3.6 small chat models) end turns with ``<|im_end|>`` but
+ ship ``config.eos_token_id = <|endoftext|>`` and no ``generation_config.json``, so paths
+ that read ``generation_config`` (the vision path, tool loops) run past the turn and loop.
+ Markers are derived from the chat_template (chat_eos.resolve_chat_turn_end_eos_ids), so
+ base/coder models and harmony templates are left untouched.
"""
info = self.models.get(model_name) or {}
model = info.get("model")
container = info.get("tokenizer")
- tokenizer = getattr(container, "tokenizer", container) # unwrap processors
+ tokenizer = getattr(container, "tokenizer", container)
if model is None or tokenizer is None:
return
# Vision models carry the chat_template on the processor, not the inner
@@ -390,7 +372,6 @@ class InferenceBackend:
try:
model_name = config.identifier
- # Already loaded?
if model_name in self.models and self.models[model_name].get("model"):
logger.info(f"Model {model_name} already loaded")
if hf_token:
@@ -398,7 +379,6 @@ class InferenceBackend:
self.active_model_name = model_name
return True
- # Currently loading?
if model_name in self.loading_models:
logger.info(f"Model {model_name} is already being loaded")
return False
@@ -429,7 +409,6 @@ class InferenceBackend:
"active_adapter": None,
}
- # ── Audio model loading path ──────────────────────────
if config.is_audio:
audio_type = config.audio_type
adapter_info = " (LoRA adapter)" if config.is_lora else ""
@@ -494,7 +473,6 @@ class InferenceBackend:
f"Spark-TTS merged export: LLM from {llm_path}, BiCodec from {abs_repo_path}"
)
else:
- # Base model: download full HF repo, load from /LLM subfolder
abs_repo_path = audio_codec_path or resolve_bicodec_repo_path(
config.path, hf_token = hf_token
)
@@ -504,8 +482,6 @@ class InferenceBackend:
)
if not (config.is_lora and config.base_model):
- # Shared by the merged-export and repo-root branches above: both resolve
- # an llm_path and then load it the same way.
model, tokenizer = FastModel.from_pretrained(
llm_path,
dtype = torch.float32,
@@ -537,7 +513,6 @@ class InferenceBackend:
self.models[model_name]["model"] = model
self.models[model_name]["tokenizer"] = tokenizer
elif audio_type == "whisper":
- # Whisper ASR — uses FastModel with WhisperForConditionalGeneration
from unsloth import FastModel
from transformers import WhisperForConditionalGeneration
@@ -554,7 +529,6 @@ class InferenceBackend:
FastModel.for_inference(model)
model.eval()
- # ASR pipeline (per notebook)
from transformers import pipeline as hf_pipeline
whisper_pipe = hf_pipeline(
@@ -593,7 +567,6 @@ class InferenceBackend:
audio_type, self.device, model_repo_path = model_repo_path
)
- # Reject CPU/disk offload for audio models too
raise_if_offloaded(self.models[model_name]["model"], device_map, "Inference")
self.models[model_name]["context_length"] = runtime_context_length(
self.models[model_name].get("model"),
@@ -611,11 +584,9 @@ class InferenceBackend:
logger.info(f"Loading {model_type} model{adapter_info}: {model_name}")
log_gpu_memory(f"Before loading {model_name}")
- # Same load path for base models and LoRA adapters
if config.is_vision:
- # Vision model (or vision LoRA adapter)
model, processor = FastVisionModel.from_pretrained(
- model_name = config.path, # Can be base model OR LoRA adapter path
+ model_name = config.path,
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
@@ -662,9 +633,8 @@ class InferenceBackend:
self.models[model_name]["processor"] = processor
else:
- # Text model (or text LoRA adapter)
model, tokenizer = FastLanguageModel.from_pretrained(
- model_name = config.path, # Can be base model OR LoRA adapter path
+ model_name = config.path,
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
@@ -698,7 +668,6 @@ class InferenceBackend:
logger.error(f"Failed to load model: {e}")
error_msg = format_error_message(e, config.identifier)
- # Cleanup on failure
if model_name in self.models:
del self.models[model_name]
self.loading_models.discard(model_name)
@@ -709,14 +678,12 @@ class InferenceBackend:
"""Remove a model from the registry and clear GPU memory."""
if model_name in self.models:
try:
- # Clean up codecs for audio models
if self.models[model_name].get("is_audio"):
self._audio_codec_manager.unload()
logger.info(f"Unloading model '{model_name}' from memory.")
del self.models[model_name]
- # Clear the active model if it was the one unloaded
if self.active_model_name == model_name:
self.active_model_name = None
@@ -742,15 +709,14 @@ class InferenceBackend:
return True
def revert_to_base_model(self, base_model_name: str) -> bool:
- """Revert the model to its pristine base state by unloading and
- deleting all adapter configurations."""
+ """Revert the model to its pristine base state by unloading and deleting all adapter
+ configurations."""
if base_model_name not in self.models:
return False
model = self.models[base_model_name].get("model")
try:
- # Unload adapter weights if model is a PeftModel.
if isinstance(model, (PeftModel, PeftModelForCausalLM)):
logger.info(f"Unloading LoRA adapters from '{base_model_name}'...")
unwrapped_base_model = model.unload()
@@ -781,9 +747,7 @@ class InferenceBackend:
hf_token: Optional[str] = None,
gpu_ids: Optional[list[int]] = None,
) -> Tuple[bool, Optional[str], Optional[str]]:
- """Ensure the base model and the given adapter are loaded.
- Idempotent and handles all states correctly.
- """
+ """Ensure the base model and the given adapter are loaded. Idempotent."""
try:
from utils.models import ModelConfig
@@ -793,7 +757,6 @@ class InferenceBackend:
base_model_name = lora_config.base_model
- # 1. Load the base model if not already in memory
if base_model_name not in self.models or not self.models[base_model_name].get("model"):
logger.info(f"Base model '{base_model_name}' not loaded, loading now.")
base_config = ModelConfig.from_ui_selection(base_model_name, None, is_lora = False)
@@ -809,11 +772,9 @@ class InferenceBackend:
self.active_model_name = base_model_name
- # 2. Derive adapter name from the user's selection
adapter_name = lora_path.split("/")[-1].replace(".", "_")
- # 3. Ensure this adapter is loaded (load_adapter only reads from
- # disk if the model doesn't already have it).
+ # load_adapter only reads from disk if the model does not already have this adapter.
adapter_success = self.load_adapter(
base_model_name = base_model_name,
adapter_path = lora_path,
@@ -822,7 +783,6 @@ class InferenceBackend:
if not adapter_success:
return False, base_model_name, None
- # 4. Return the verified adapter name for the UI.
return True, base_model_name, adapter_name
except Exception as e:
@@ -849,7 +809,6 @@ class InferenceBackend:
)
model.load_adapter(adapter_path, adapter_name = adapter_name)
- # Update the registry only after a successful load.
if "loaded_adapters" not in self.models[base_model_name]:
self.models[base_model_name]["loaded_adapters"] = {}
self.models[base_model_name]["loaded_adapters"][adapter_name] = adapter_path
@@ -864,7 +823,6 @@ class InferenceBackend:
return False
def set_active_adapter(self, base_model_name: str, adapter_name: str) -> bool:
- """Set the active adapter for generation."""
model = self.models[base_model_name].get("model")
try:
logger.info(f"Setting active adapter to: '{adapter_name}'")
@@ -872,16 +830,14 @@ class InferenceBackend:
self.models[base_model_name]["active_adapter"] = adapter_name
return True
except Exception as e:
- # Catches "adapter not found" if something goes wrong.
logger.error(f"Failed to set active adapter to '{adapter_name}': {e}")
return False
def _apply_adapter_state(self, use_adapter: Optional[Union[bool, str]]) -> None:
"""Apply adapter state before generation (must hold _generation_lock).
- Toggles PEFT enable/disable_adapter_layers (non-destructive, no reload).
- use_adapter: None = no change, False = base model, True = current adapter,
- str = named adapter.
+ Toggles PEFT enable/disable_adapter_layers, so nothing is reloaded. use_adapter: None = no
+ change, False = base model, True = current adapter, str = named adapter.
"""
if use_adapter is None:
return
@@ -896,7 +852,6 @@ class InferenceBackend:
return
if use_adapter is False:
- # Disable LoRA layers -> base model output.
if isinstance(model, (PeftModel, PeftModelForCausalLM)):
logger.info(
f"Compare mode: disabling adapters on '{base}' for base model generation"
@@ -906,7 +861,6 @@ class InferenceBackend:
logger.info(f"Compare mode: model '{base}' is not a PeftModel, already base")
elif use_adapter is True:
- # Re-enable LoRA layers -> adapter output.
if isinstance(model, (PeftModel, PeftModelForCausalLM)):
logger.info(f"Compare mode: enabling adapters on '{base}' for LoRA generation")
model.base_model.enable_adapter_layers()
@@ -914,7 +868,6 @@ class InferenceBackend:
logger.warning("use_adapter=true but model is not a PeftModel")
elif isinstance(use_adapter, str):
- # Enable adapters and set the named one active.
if isinstance(model, (PeftModel, PeftModelForCausalLM)):
logger.info(f"Compare mode: enabling adapter '{use_adapter}' on '{base}'")
model.base_model.enable_adapter_layers()
@@ -930,9 +883,9 @@ class InferenceBackend:
) -> Generator[str, None, None]:
"""Thread-safe generation with optional adapter toggling.
- Adapter toggle + model.generate() are serialized by _generation_lock in
- the background thread, avoiding the RLock-reentrant race when two async
- SSE handlers share one event-loop thread. use_adapter: see _apply_adapter_state.
+ Adapter toggle and model.generate() are serialized by _generation_lock in the background
+ thread, avoiding the RLock-reentrant race when two async SSE handlers share one event-loop
+ thread. use_adapter: see _apply_adapter_state.
"""
yield from self._generate_chat_response_inner(
cancel_event = cancel_event, _adapter_state = use_adapter, **gen_kwargs
@@ -1086,10 +1039,10 @@ class InferenceBackend:
) -> Generator[str, None, None]:
"""Generate response for text or vision models (lock held by background thread).
- ``tools`` / ``enable_thinking`` / ``reasoning_effort`` / ``preserve_thinking``
- are forwarded into ``apply_chat_template`` so templates that understand them
- (Qwen3, Llama 3.1+, gpt-oss harmony) advertise tool schemas / reasoning controls.
- ``presence_penalty`` matches the GGUF sampling path (0 disables it).
+ ``tools`` / ``enable_thinking`` / ``reasoning_effort`` / ``preserve_thinking`` are forwarded
+ into ``apply_chat_template`` so templates that understand them (Qwen3, Llama 3.1+, gpt-oss
+ harmony) advertise tool schemas and reasoning controls. ``presence_penalty`` matches the
+ GGUF sampling path (0 disables it).
"""
yield from self._generate_chat_response_inner(
messages = messages,
@@ -1132,16 +1085,14 @@ class InferenceBackend:
presence_penalty: float = 0.0,
tool_protocol_active: Optional[bool] = None,
) -> Generator[str, None, None]:
- """Inner generation logic, called by generate_chat_response and
- generate_with_adapter_control.
+ """Inner generation logic.
- tool_protocol_active overrides the bool(tools) default for native tool
- token preservation: the loop's unrestricted mode accepts any tool name
- with an EMPTY tools list, so bool(tools) would strip the very tokens it
- is about to parse.
+ tool_protocol_active overrides the bool(tools) default for native tool token preservation:
+ the loop's unrestricted mode accepts any tool name with an EMPTY tools list, so bool(tools)
+ would strip the very tokens it is about to parse.
- _adapter_state is passed to generate_stream/vision so the background
- thread can toggle adapters under the generation lock.
+ _adapter_state is passed to generate_stream/vision so the background thread can toggle
+ adapters under the generation lock.
"""
if not self.active_model_name:
raise RuntimeError("No active model")
@@ -1149,7 +1100,6 @@ class InferenceBackend:
model_info = self.models[self.active_model_name]
is_vision = model_info.get("is_vision", False)
tokenizer = model_info.get("tokenizer") or model_info.get("processor")
- # Unwrap processor -> raw tokenizer for VLMs on the text path.
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
top_k = self._normalize_top_k(top_k)
@@ -1189,7 +1139,6 @@ class InferenceBackend:
# Text path: messages are already in ChatML format from eval.py.
- # Step 1: apply get_chat_template if model is in mapper.
try:
from utils.datasets import (
MODEL_TO_TEMPLATE_MAPPER,
@@ -1230,7 +1179,6 @@ class InferenceBackend:
except Exception as e:
logger.warning(f"Could not apply get_chat_template: {e}")
- # Step 2: format with tokenizer.apply_chat_template().
if system_prompt:
template_messages = [{"role": "system", "content": system_prompt}] + messages
else:
@@ -1287,14 +1235,12 @@ class InferenceBackend:
logger.debug(f"Formatted prompt: {formatted_prompt[:200]}...")
except Exception as e:
logger.error(f"Error applying chat template: {e}")
- # Fall back to manual formatting
formatted_prompt = self.format_chat_prompt(
messages, system_prompt, continue_final_message = continue_final_message
)
reasoning_channel_markers = None
reasoning_channel_markers_resolved = True
- # Step 3: generate
yield from self.generate_stream(
formatted_prompt,
temperature,
@@ -1361,7 +1307,6 @@ class InferenceBackend:
if not user_message:
user_message = "Describe this image." if image else "Hello"
- # Prepare vision messages
if image:
# Ordinary vision turns keep the historic collapse; full history is unbounded.
has_tool_history = messages_have_tool_history(messages)
@@ -1509,7 +1454,6 @@ class InferenceBackend:
).to(model.device)
prompt_text = input_text
else:
- # Text-only path for a vision model
formatted_prompt = self.format_chat_prompt(
messages, system_prompt, continue_final_message = continue_final_message
)
@@ -1520,7 +1464,6 @@ class InferenceBackend:
).to(model.device)
prompt_text = formatted_prompt
- # Stream with TextIteratorStreamer + background thread
try:
# Re-emit an open <think> prefill swallowed by skip_prompt (see
# generate_stream).
@@ -1723,7 +1666,6 @@ class InferenceBackend:
processor = model_info.get("processor") or model_info.get("tokenizer")
raw_tokenizer = getattr(processor, "tokenizer", processor)
- # Last user text; default matches the notebook prompt
user_text = "Please transcribe this audio."
if messages:
for msg in reversed(messages):
@@ -1731,7 +1673,6 @@ class InferenceBackend:
user_text = content_to_text(msg["content"])
break
- # ASR-specific default system prompt if none set
if not system_prompt:
system_prompt = "You are an assistant that transcribes speech accurately."
@@ -1755,7 +1696,6 @@ class InferenceBackend:
audio_messages, None, markup_for_tokenizer(processor)
)
- # apply_chat_template does audio embedding + tokenization in one step
inputs = processor.apply_chat_template(
audio_messages,
add_generation_prompt = True,
@@ -1876,10 +1816,8 @@ class InferenceBackend:
audio_array,
cancel_event = None,
) -> Generator[str, None, None]:
- """Whisper ASR: takes an audio numpy array, yields transcribed text.
-
- Uses the pre-built transformers pipeline created at model load.
- """
+ """Whisper ASR: takes an audio numpy array, yields transcribed text through the pipeline
+ built at model load."""
# The pipeline reports no token counts, so clear rather than let gen_done
# ship a chat turn's stats as this one's.
self.last_generation_stats = None
@@ -2011,12 +1949,12 @@ class InferenceBackend:
) -> Generator[str, None, None]:
"""Generate a streaming text response (text models only).
- Rendered chat prompts pass add_special_tokens=False; raw prompts keep
- the tokenizer defaults, including BOS insertion for base models.
+ Rendered chat prompts pass add_special_tokens=False; raw prompts keep the tokenizer
+ defaults, including BOS insertion for base models.
- _adapter_state: if not None, the background thread toggles adapters
- before model.generate(), under _generation_lock.
- ``presence_penalty`` matches the GGUF sampling path via a logits processor (0 disables it).
+ _adapter_state: if not None, the background thread toggles adapters before model.generate(),
+ under _generation_lock. ``presence_penalty`` matches the GGUF sampling path via a logits
+ processor (0 disables it).
"""
if not self.active_model_name:
raise RuntimeError("No active model")
@@ -2209,9 +2147,6 @@ class InferenceBackend:
logger.error(f"Error during generation: {e}")
raise
- # ── Audio (TTS) Generation ────────────────────────────────────
-
- # ── Audio (TTS) Generation ────────────────────────────────────
def generate_audio_response(
self,
text: str,
@@ -2227,9 +2162,7 @@ class InferenceBackend:
language: Optional[str] = None,
seed: Optional[int] = None,
) -> Tuple[bytes, int]:
- """Generate audio from text for TTS models.
- Returns (wav_bytes, sample_rate). Blocking — full audio before return.
- """
+ """Generate audio from text for TTS models. Returns (wav_bytes, sample_rate). Blocking."""
# Reserved for native audio architectures; codec-backed TTS models do
# not currently expose scene instructions or deterministic seeding.
del instructions, language, seed
@@ -2473,10 +2406,8 @@ class InferenceBackend:
@classmethod
def _patch_repetition_penalty_processor(cls):
- """Monkey-patch transformers' RepetitionPenaltyLogitsProcessor with a
- 64-token sliding-window variant (from the OuteTTS notebook).
- Applied once per process.
- """
+ """Monkey-patch transformers' RepetitionPenaltyLogitsProcessor with the OuteTTS notebook's
+ 64-token sliding-window variant. Applied once per process."""
if cls._repetition_penalty_patched:
return
cls._repetition_penalty_patched = True
@@ -2527,11 +2458,9 @@ class InferenceBackend:
preserve_thinking: Optional[bool] = None,
continue_final_message: bool = False,
) -> str:
- """Render the chat prompt, peeling kwargs the template doesn't
- understand. Delegates to the dependency-light helper module so the
- fallback chain is unit-testable without pulling unsloth / torch into
- the test sandbox.
- """
+ """Render the chat prompt, peeling kwargs the template does not understand. Delegates to the
+ dependency-light helper module so the fallback chain is unit-testable without pulling
+ unsloth / torch into the test sandbox."""
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
)
@@ -2664,16 +2593,7 @@ class InferenceBackend:
return f"{manual_prompt}{partial}" if partial else manual_prompt
def _format_chat_manual(self, messages: list, template_type: str, special_tokens: dict) -> str:
- """Manual chat-formatting fallback when the tokenizer template fails.
-
- Args:
- messages: List of message dictionaries
- template_type: Detected template type
- special_tokens: Dictionary of special tokens
-
- Returns:
- str: Manually formatted prompt
- """
+ """Manual chat-formatting fallback when the tokenizer template fails."""
if template_type == "llama3":
return self._format_llama3_template(messages, special_tokens)
elif template_type == "mistral":
@@ -2686,7 +2606,6 @@ class InferenceBackend:
return self._format_generic_template(messages, special_tokens)
def _format_llama3_template(self, messages: list, special_tokens: dict) -> str:
- """Format messages using Llama 3 template"""
bos_token = special_tokens.get("bos_token", "<|begin_of_text|>")
formatted = bos_token
@@ -2699,7 +2618,6 @@ class InferenceBackend:
return formatted
def _format_mistral_template(self, messages: list, special_tokens: dict) -> str:
- """Format messages using Mistral template"""
bos_token = special_tokens.get("bos_token", "<s>")
formatted = bos_token
@@ -2734,7 +2652,6 @@ class InferenceBackend:
return formatted
def _format_chatml_template(self, messages: list, special_tokens: dict) -> str:
- """Format messages using ChatML template"""
formatted = ""
for msg in messages:
@@ -2746,7 +2663,6 @@ class InferenceBackend:
return formatted
def _format_alpaca_template(self, messages: list, special_tokens: dict) -> str:
- """Format messages using Alpaca template"""
formatted = ""
system_msg = None
@@ -2766,7 +2682,6 @@ class InferenceBackend:
return formatted
def _format_generic_template(self, messages: list, special_tokens: dict) -> str:
- """Generic fallback formatting"""
formatted = ""
for msg in messages:
@@ -2778,7 +2693,6 @@ class InferenceBackend:
return formatted
def check_vision_model_compatibility(self) -> bool:
- """Whether the current model supports vision."""
current_model = self.get_current_model()
if current_model and current_model in self.models:
return self.models[current_model].get("is_vision", False)
@@ -2794,7 +2708,6 @@ class InferenceBackend:
return
try:
- # Common pattern for Unsloth/Hugging Face models
if hasattr(model, "past_key_values"):
model.past_key_values = None
if hasattr(model, "generation_config"):
@@ -2806,14 +2719,13 @@ class InferenceBackend:
logger.warning(f"Could not fully reset model state for {model_name}: {e}")
def reset_generation_state(self, caller_cancel_event = None):
- """Reset any cached generation state to prevent hanging after errors
+ """Reset any cached generation state to prevent hanging after errors.
- ``caller_cancel_event`` is accepted for signature parity with the
- orchestrator, which uses it to drop a reset from a request that never
- started. Nothing here cancels a live generation, so it is unused.
+ ``caller_cancel_event`` is accepted for signature parity with the orchestrator, which uses
+ it to drop a reset from a request that never started. Nothing here cancels a live
+ generation, so it is unused.
"""
try:
- # Clear cached state for ALL loaded models
for model_name in self.models.keys():
self._reset_model_generation_state(model_name)
@@ -2858,9 +2770,9 @@ class InferenceBackend:
def _generated_token_count(self, model, outputs, prompt_len) -> Optional[int]:
"""New tokens ``generate`` produced, or None when the shape says nothing.
- ``generate`` returns prompt + completion for decoder-only models and
- decoder-start + completion for encoder-decoder ones. Anything else yields
- None, so the caller never reports a count it did not measure.
+ ``generate`` returns prompt + completion for decoder-only models and decoder-start +
+ completion for encoder-decoder ones. Anything else yields None, so the caller never reports
+ a count it did not measure.
"""
sequences = getattr(outputs, "sequences", outputs)
shape = getattr(sequences, "shape", None)
@@ -2874,11 +2786,9 @@ class InferenceBackend:
return total - int(prompt_len)
def _ended_on_stop_token(self, outputs, stop_token_ids) -> bool:
- """Whether the final token is a stop token rather than one cut off by the cap.
-
- A response landing exactly on ``max_new_tokens`` ended naturally; only one
- that did NOT emit a stop token ran out of budget.
- """
+ """Whether the final token is a stop token rather than one cut off by the cap. A response
+ landing exactly on ``max_new_tokens`` ended naturally; only one that did NOT emit a stop
+ token ran out of budget."""
sequences = getattr(outputs, "sequences", outputs)
if isinstance(stop_token_ids, int):
stop_token_ids = (stop_token_ids,)
@@ -2900,11 +2810,10 @@ class InferenceBackend:
) -> None:
"""Latch usage, timings and budget exhaustion for the worker's gen_done stats channel.
- Left at None when the token count is unknown, so a path that cannot count
- reports what it did before. ``truncated`` becomes finish_reason "length";
- a cancelled run stopped by request, not at the cap, so it never sets it.
- ``timer`` carries the prefill/decode split behind the prompt and generation
- speeds; a path that does not measure one reports usage alone.
+ Left at None when the token count is unknown, so a path that cannot count reports what it
+ did before. ``truncated`` becomes finish_reason "length"; a cancelled run stopped by
+ request, not at the cap, so it never sets it. ``timer`` carries the prefill/decode split
+ behind the prompt and generation speeds.
"""
if completion_tokens is None:
return
@@ -3030,8 +2939,6 @@ class InferenceBackend:
try:
from utils.datasets import MODEL_TO_TEMPLATE_MAPPER
-
- # Exact match first
model_name_lower = model_name.lower()
if model_name_lower in MODEL_TO_TEMPLATE_MAPPER:
chat_template_info["template_name"] = MODEL_TO_TEMPLATE_MAPPER[model_name_lower]
@@ -3103,11 +3010,9 @@ class InferenceBackend:
return self.active_model_name
def is_model_loading(self) -> bool:
- """Whether any model is currently loading."""
return len(self.loading_models) > 0
def get_loading_model(self) -> Optional[str]:
- """Name of the currently loading model."""
return next(iter(self.loading_models)) if self.loading_models else None
def load_model_simple(
@@ -3117,18 +3022,8 @@ class InferenceBackend:
max_seq_length: int = 2048,
load_in_4bit: bool = True,
) -> bool:
- """Simple model-loading wrapper for the chat interface. Takes a string
- path and builds the ModelConfig internally.
-
- Args:
- model_path: Model name or path (e.g., "unsloth/llama-3-8b")
- hf_token: HuggingFace token for gated models
- max_seq_length: Maximum sequence length
- load_in_4bit: Whether to use 4-bit quantization
-
- Returns:
- bool: True if successful, False otherwise
- """
+ """Simple model-loading wrapper for the chat interface: takes a string path and builds the
+ ModelConfig internally."""
try:
config = ModelConfig.from_ui_selection(
model_path,
@@ -3139,7 +3034,7 @@ class InferenceBackend:
return self.load_model(
config = config,
max_seq_length = max_seq_length,
- dtype = None, # Auto-detect
+ dtype = None,
load_in_4bit = load_in_4bit,
hf_token = hf_token,
)
@@ -3149,7 +3044,6 @@ class InferenceBackend:
return False
-# Global inference backend instance
inference_backend = InferenceBackend()
diff --git a/studio/backend/core/inference/instruction_pin.py b/studio/backend/core/inference/instruction_pin.py
index 39553b7d859..a9a60f17660 100644
--- a/studio/backend/core/inference/instruction_pin.py
+++ b/studio/backend/core/inference/instruction_pin.py
@@ -83,15 +83,13 @@ _CONTINUATIONS = frozenset(
"then",
}
)
-# keyboards autocorrect "..." to U+2026, so `continue...` matched nothing and recall searched for "continue"
# U+2026 and U+2025 as well as the ASCII spellings: keyboards autocorrect "..." to one ellipsis character, so
# `continue…` matched nothing and recall searched for "continue".
_PUNCTUATION = re.compile(r"[\s\.,!\?;:\-–—\u2025\u2026]+")
-# A closed list, not a word count: words that cannot name a request's subject "Anaphoric" as a closed list rather than a
-# word count: words that cannot name the subject of a request. "what about it" has nothing to search for; "review
-# billing" names its own subject and keeps its retrieval slots. Negation is left out, as in `store._ARCHIVE_STOPWORDS`:
-# a missed anchor is cheaper than a wrong one.
+# "Anaphoric" as a closed list rather than a word count: words that cannot name the subject of a request. "what about
+# it" has nothing to search for; "review billing" names its own subject and keeps its retrieval slots. Negation is
+# left out, as in `store._ARCHIVE_STOPWORDS`: a missed anchor is cheaper than a wrong one.
_FUNCTION_WORDS = frozenset(
"""
a about all also am an and another any anything are as at be been being both but by can
@@ -209,7 +207,6 @@ def _protected_cost(turns: list[list[dict]], index: int) -> int:
small instruction its pin over tokens the pin never keeps -- which is the case the pin
exists for, since an agent run is exactly where the filler follow-up appears.
"""
- # 4 chars per token undercharges CJK and emoji ~2x; over-charging only refuses the pin
# Dense: 4 chars per token undercharges CJK and emoji ~2x, so a 1056-token turn was charged 276 and cleared a 1024
# ceiling. Over-charging only refuses the pin.
return estimate_messages_tokens_dense(turns[index])
@@ -246,9 +243,8 @@ def pinned_instruction_ids(
return set()
turns = group_turns(messages)
- # the newest user group is already window-protected
- # The newest user group is already protected by the window, and the inline recall path replaces that message with a
- # new dict, so its id would go stale anyway.
+ # The newest user group is already protected by the window, and the inline recall path replaces that message with
+ # a new dict, so its id would go stale anyway.
newest_user = next(
(
index
diff --git a/studio/backend/core/inference/key_exchange.py b/studio/backend/core/inference/key_exchange.py
index eb5b90bf7cd..27970fbc47f 100644
--- a/studio/backend/core/inference/key_exchange.py
+++ b/studio/backend/core/inference/key_exchange.py
@@ -76,7 +76,6 @@ def get_public_key_fingerprint() -> str | None:
def get_public_key_pem() -> str:
- """Return the PEM-encoded public key for the frontend."""
if _public_key_pem is None:
raise RuntimeError("Key pair not initialized. Call init_key_pair() first.")
return _public_key_pem
diff --git a/studio/backend/core/inference/llama_admission.py b/studio/backend/core/inference/llama_admission.py
index 1951c64c8cd..35c80dc5880 100644
--- a/studio/backend/core/inference/llama_admission.py
+++ b/studio/backend/core/inference/llama_admission.py
@@ -3,10 +3,9 @@
"""Admission control for local llama-server generation requests.
-The helpers in this module deliberately know nothing about FastAPI, SSE, or the
-OpenAI-compatible route shape. They only coordinate how many upstream generation
-requests may be active for one llama-server backend and provide a cancellable
-FIFO queue for excess requests.
+These helpers deliberately know nothing about FastAPI, SSE or the OpenAI-compatible route shape.
+They only coordinate how many upstream generation requests may be active for one llama-server
+backend and provide a cancellable FIFO queue for excess requests.
"""
from __future__ import annotations
@@ -57,10 +56,9 @@ DEFAULT_ADMISSION_QUEUE_PER_SLOT = 16
# Floor for the scaled line, so a 1-slot backend (plain `unsloth studio`, or any load downshifted to fit VRAM) keeps the
# depth it had before scaling existed rather than dropping to 16 and rejecting callers that used to queue.
DEFAULT_ADMISSION_MIN_QUEUE = 64
-# slot-only admission overcommits a unified KV cache
# Token accounting is on by default. Slot-only admission overcommits a unified KV cache: llama.cpp with --parallel N
-# --kv-unified allocates ONE cache of n_ctx but reports n_ctx_slot = n_ctx to every slot, so N generations are admitted
-# against a cache that may hold one. When they collide, llama.cpp kills every task involved.
+# --kv-unified allocates ONE cache of n_ctx but reports n_ctx_slot = n_ctx to every slot, so N generations are
+# admitted against a cache that may hold one. When they collide, llama.cpp kills every task involved.
DEFAULT_ADMISSION_KV_BUDGET = True
# Ceiling on one round's wait for cache room; generous, since a legitimate wait is bounded by the longest round in
# flight. Bounded at all because a reparker holds the wait line shut for every other caller, so an unbounded wait
@@ -99,7 +97,6 @@ def _max_parked(capacity: int) -> int:
"""
workers = _executor_workers()
spare = workers - _executor_reserve(workers) - max(0, capacity)
- # a quarter of five is one, and one park cannot cover the two simultaneous prompts #7455 exists for
# A quarter of the executor, floored at two while `spare` allows: a quarter of five is one, and one park cannot
# cover the two simultaneous prompts #7455 exists for.
return max(0, min(max(2, workers // 4), spare))
@@ -149,9 +146,8 @@ class LlamaAdmissionConfig:
keepalive_interval_s: float = DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S
max_queue: Optional[int] = DEFAULT_ADMISSION_MAX_QUEUE
queue_per_slot: Optional[int] = DEFAULT_ADMISSION_QUEUE_PER_SLOT
- # the env path clears this floor when the operator sets QUEUE_PER_SLOT
- # Unconditional floor on the scaled line. The env path clears it when the operator sets QUEUE_PER_SLOT, so only the
- # default multiplier is floored.
+ # Unconditional floor on the scaled line. The env path clears it when the operator sets QUEUE_PER_SLOT, so only
+ # the default multiplier is floored.
min_queue: Optional[int] = DEFAULT_ADMISSION_MIN_QUEUE
kv_budget: bool = DEFAULT_ADMISSION_KV_BUDGET
@@ -302,9 +298,8 @@ class _Waiter:
future: asyncio.Future
cancelled: bool = False
granted_lease: Optional["LlamaAdmissionLease"] = None
- # read while the head of the line is considered
- # KV tokens this caller will occupy once admitted. Read while the head of the line is considered, so a large request
- # cannot be overtaken by small ones.
+ # KV tokens this caller will occupy once admitted. Read while the head of the line is considered, so a large
+ # request cannot be overtaken by small ones.
tokens: int = 0
@@ -343,14 +338,13 @@ class LlamaAdmissionLease:
def park(self) -> bool:
"""Hand the slot back while this holder waits on something off the GPU.
- A run stopped on a tool approval prompt is not decoding, so holding its
- slot would let unanswered prompts fill the pool while llama-server idles.
- The lease itself stays valid: releasing it after a park is still correct.
+ A run stopped on a tool approval prompt is not decoding, so holding its slot would let
+ unanswered prompts fill the pool while llama-server idles. The lease itself stays valid:
+ releasing it after a park is still correct.
- False when the park budget is spent and nothing was given back: the
- caller keeps its slot across the prompt, as it did before parking
- existed. Slower for whoever is behind it, but each freed slot admits
- another run that can park too, on the executor the generators run on.
+ False when the park budget is spent and nothing was given back: the caller keeps its slot
+ across the prompt, as it did before parking existed. Slower for whoever is behind it, but
+ each freed slot admits another run that can park too.
"""
queue = self._queue
with self._release_lock:
@@ -462,29 +456,24 @@ class LlamaAdmissionLease:
) -> bool:
"""Re-state this lease's cost, waiting for room rather than running over it.
- ``recost`` declines when the cache is full and the caller carries on at its old
- figure, so the next round sends a bigger prompt than the pool was told about, and
- enough of those is the ``Context size has been exceeded`` that kills every
- decoding slot at once.
-
- Call this only between rounds, and only with ``allow_yield`` true where an idle
- slot's cells actually come back. Being between rounds makes the slot IDLE; what
- makes its cells REUSABLE under ``--kv-unified`` is ``prompt_clear()``, which
- llama-server runs only under ``--cache-idle-slots`` (``server-context.cpp``) --
- force-disabled by ``--cache-ram 0``, and absent on older servers. Studio emits
- ``--cache-ram 0`` on Windows under full GPU offload (#5692, WDDM overhead)
- alongside ``--kv-unified``; there a yielded round's cells stay resident, so
- yielding would hand the same capacity to a second caller. With yielding off this
- degrades to plain ``recost``, which declines rather than overcommits. Where
- clearing IS active the cache changes only the PRICE: reclaiming costs a prefix hit
- if the cells were spilled to host RAM.
-
- False means this lease still holds the figure it came in with: declined,
- cancelled, released, or waited past ``timeout_s``. The timeout is the blast
- radius -- a reparker holds the wait line shut for everyone (see
- ``yield_commitment``), so an endless wait freezes the queue, not one chat. Giving
- up restores the old commitment and the decline-and-continue behaviour that
- predates this.
+ ``recost`` declines when the cache is full and the caller carries on at its old figure, so
+ the next round sends a bigger prompt than the pool was told about, and enough of those is
+ the ``Context size has been exceeded`` that kills every decoding slot at once.
+
+ Call this only between rounds, and only with ``allow_yield`` true where an idle slot's cells
+ actually come back. Being between rounds makes the slot IDLE; what makes its cells REUSABLE
+ under ``--kv-unified`` is ``prompt_clear()``, which llama-server runs only under
+ ``--cache-idle-slots`` (``server-context.cpp``), force-disabled by ``--cache-ram 0`` and
+ absent on older servers. Studio emits ``--cache-ram 0`` on Windows under full GPU offload
+ (#5692) alongside ``--kv-unified``, and there a yielded round's cells stay resident, so
+ yielding would hand the same capacity to a second caller; with yielding off this degrades to
+ plain ``recost``, which declines rather than overcommits. Where clearing IS active the cache
+ changes only the PRICE: reclaiming costs a prefix hit if the cells were spilled to host RAM.
+
+ False means this lease still holds the figure it came in with: declined, cancelled,
+ released, or waited past ``timeout_s``. The timeout is the blast radius, since a reparker
+ holds the wait line shut for everyone (see ``yield_commitment``); giving up restores the old
+ commitment and the decline-and-continue behaviour that predates this.
"""
want = max(0, int(tokens or 0))
# Cheap path first: growth that already fits never touches the wait line.
@@ -527,15 +516,14 @@ class LlamaAdmissionLease:
def _give_up_repark(self, queue, held: int, *, cancelled: bool) -> bool:
"""Stop waiting and go back to holding ``held``.
- Both halves under one queue lock (``abandon_repark(restore = held)``): the wait
- line reopens and the old figure is re-committed together. This lease still
- occupies that much of llama-server's cache, so re-committing it is a correction,
- not a request -- asking through ``try_recost`` let a full cache REFUSE it, after
- which release() subtracted a commitment that was never restored and handed the
- next arrival that much phantom room.
+ Both halves under one queue lock (``abandon_repark(restore = held)``): the wait line reopens
+ and the old figure is re-committed together. This lease still occupies that much of
+ llama-server's cache, so re-committing it is a correction, not a request -- asking through
+ ``try_recost`` let a full cache REFUSE it, after which release() subtracted a commitment
+ that was never restored and handed the next arrival that much phantom room.
- ``_release_lock`` is held across the queue call in release()'s lock order, so the
- commitment cannot be released out from under the restore.
+ ``_release_lock`` is held across the queue call in release()'s lock order, so the commitment
+ cannot be released out from under the restore.
"""
with self._release_lock:
if self._released:
@@ -645,17 +633,16 @@ class LlamaAdmissionReservation:
class LlamaAdmissionQueue:
"""A fixed pool of generation slots for one llama-server, plus a FIFO wait line.
- The pool mirrors llama-server's own ``--parallel`` slots: ``capacity`` slot ids
- are each either free or held by exactly one caller. A caller that finds every
- slot busy waits in arrival order and is handed the next slot to free, so no
- caller is starved. This bounds only the callers that reserve: chat completions
- and messages do, while /v1/completions, Unsloth's own chat endpoint and RAG
- captioning all reach llama-server directly, so it is not a global cap.
- Waiting is unbounded in time by default (``queue_timeout_s``
- None); the wait line itself is bounded, and only how many may line up before
- new arrivals are rejected. By default that is ``16 x slots`` floored at 64,
- not unlimited: an unbounded line takes ``max_queue`` or ``queue_per_slot``
- set to 0. See ``LlamaAdmissionConfig.queue_limit``.
+ The pool mirrors llama-server's own ``--parallel`` slots: ``capacity`` slot ids are each either
+ free or held by exactly one caller, and a caller that finds every slot busy waits in arrival
+ order and is handed the next slot to free, so no caller is starved. This bounds only the callers
+ that reserve: chat completions and messages do, while /v1/completions, Unsloth's own chat
+ endpoint and RAG captioning all reach llama-server directly, so it is not a global cap.
+
+ Waiting is unbounded in time by default (``queue_timeout_s`` None); the wait line itself is
+ bounded, and only in how many may line up before new arrivals are rejected. By default that is
+ ``16 x slots`` floored at 64; an unbounded line takes ``max_queue`` or ``queue_per_slot`` set to
+ 0. See ``LlamaAdmissionConfig.queue_limit``.
"""
__slots__ = (
@@ -709,17 +696,16 @@ class LlamaAdmissionQueue:
def _fits_budget_locked(self, tokens: int) -> bool:
"""Whether ``tokens`` more KV may be committed.
- A caller is always admitted when nothing else holds KV, however large it is.
- Its request may still be refused by llama-server, but that refusal names both
- token counts and the setting to change, whereas refusing here would strand it
- forever.
-
- The escape asks whether anything is COMMITTED, not whether a slot is held.
- ``try_park`` hands a slot back while its holder waits on a tool approval, which
- drops ``_held`` to zero even though llama-server still holds that lease's KV. A
- held-slot test therefore admitted the next caller unconditionally: park a 1500
- token lease against a 2048 token budget, and the next 1500 token one sailed
- through to 3000 committed, which is the collision this accounting exists to stop.
+ A caller is always admitted when nothing else holds KV, however large it is. Its request may
+ still be refused by llama-server, but that refusal names both token counts and the setting
+ to change, whereas refusing here would strand it forever.
+
+ The escape asks whether anything is COMMITTED, not whether a slot is held. ``try_park``
+ hands a slot back while its holder waits on a tool approval, which drops ``_held`` to zero
+ even though llama-server still holds that lease's KV, so a held-slot test admitted the next
+ caller unconditionally: park a 1500 token lease against a 2048 token budget, and the next
+ 1500 token one sailed through to 3000 committed, which is the collision this accounting
+ exists to stop.
"""
if self._budget <= 0 or tokens <= 0:
return True
@@ -841,15 +827,14 @@ class LlamaAdmissionQueue:
def try_recost(self, tokens_from: int, tokens_to: int) -> bool:
"""Move a live commitment to a new size. False leaves it exactly as it was.
- A tool loop's cost is unknown at admission: each round appends its results and
- re-sends the conversation, so a run that opened small can grow into the cache
- while its commitment stays at the opening estimate. #9392 closed that by
- reserving the whole cache for any tool loop, which serialises every tool chat;
- this is the re-costing that PR named as the alternative.
+ A tool loop's cost is unknown at admission: each round appends its results and re-sends the
+ conversation, so a run that opened small can grow into the cache while its commitment stays
+ at the opening estimate. #9392 closed that by reserving the whole cache for any tool loop,
+ which serialises every tool chat; this is the re-costing that PR named as the alternative.
- Never blocks and never overcommits, so it is safe to call from inside a
- generator: growth that does not fit is refused and the caller keeps what it
- holds, rather than waiting on holders that may be waiting on it.
+ Never blocks and never overcommits, so it is safe to call from inside a generator: growth
+ that does not fit is refused and the caller keeps what it holds, rather than waiting on
+ holders that may be waiting on it.
"""
tokens_from = max(0, int(tokens_from or 0))
tokens_to = max(0, int(tokens_to or 0))
@@ -873,13 +858,12 @@ class LlamaAdmissionQueue:
def yield_commitment(self, tokens: int) -> None:
"""Hand a live commitment back before asking for a bigger one.
- Half of ``LlamaAdmissionLease.recost_waiting``. Unconditional by design: a holder
- that blocked while still holding its old commitment would be waiting on holders
- waiting on it -- four runs at a quarter of the cache each, all wanting half, never
- resolve. Letting go first cannot deadlock, since ``_committed`` strictly falls.
-
- The caller counts as reparking until it reclaims, so a new arrival cannot take the
- room it just released: an in-flight conversation beats one that has not started.
+ Half of ``LlamaAdmissionLease.recost_waiting``. Unconditional by design: a holder that
+ blocked while still holding its old commitment would be waiting on holders waiting on it --
+ four runs at a quarter of the cache each, all wanting half, never resolve. Letting go first
+ cannot deadlock, since ``_committed`` strictly falls. The caller counts as reparking until
+ it reclaims, so a new arrival cannot take the room it just released: an in-flight
+ conversation beats one that has not started.
"""
with self._lock:
self._committed = max(0, self._committed - max(0, int(tokens or 0)))
@@ -909,11 +893,11 @@ class LlamaAdmissionQueue:
def abandon_repark(self, restore: int = 0) -> None:
"""Stop counting a reparker that gave up, and re-commit what it takes back.
- One lock for both. ``restore`` is what ``yield_commitment`` handed back and the
- lease still occupies at llama-server, so it is re-committed UNCONDITIONALLY: a
- correction, not a request for room. In two steps the wait line reopened on room
- the lease was about to take back; through ``try_recost`` a full cache could refuse
- it, after which release() subtracted a commitment that was never restored.
+ One lock for both. ``restore`` is what ``yield_commitment`` handed back and the lease still
+ occupies at llama-server, so it is re-committed UNCONDITIONALLY: a correction, not a request
+ for room. In two steps the wait line reopened on room the lease was about to take back;
+ through ``try_recost`` a full cache could refuse it, after which release() subtracted a
+ commitment that was never restored.
"""
with self._lock:
self._reparking = max(0, self._reparking - 1)
diff --git a/studio/backend/core/inference/llama_http.py b/studio/backend/core/inference/llama_http.py
index 930ed786a06..6fdec0bb54f 100644
--- a/studio/backend/core/inference/llama_http.py
+++ b/studio/backend/core/inference/llama_http.py
@@ -25,9 +25,9 @@ def _new_client() -> httpx.AsyncClient:
return httpx.AsyncClient(limits = _LIMITS, trust_env = False)
-# httpx binds its transport to the loop it first ran on
# One client per running event loop: an httpx client binds its transport to the loop it first runs on, so a single
-# global instance breaks across a lifespan restart or a second test loop. Weak keys let a finished loop drop its client.
+# global instance breaks across a lifespan restart or a second test loop. Weak keys let a finished loop drop its
+# client.
_clients: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, httpx.AsyncClient]" = (
weakref.WeakKeyDictionary()
)
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index e3bd02f715c..2c558ae9450 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -34,9 +34,8 @@ _pending = 0
# Subset of _pending that is /p/ preview traffic, so the busy guard can tell a queued Unsloth request from a queued
# preview.
_preview_pending = 0
-# non-preview requests past FastAPI auth: the preview busy guard counts these
# Non-preview requests past FastAPI auth at the local-inference choke point. The preview busy guard counts these, not
-# raw _inflight, so a pre-auth/unauthenticated tracked request that never touches the model can't starve public
+# raw _inflight, so a pre-auth/unauthenticated tracked request that never touches the model cannot starve public
# previews.
_admitted_inference = 0
# Bumped when a preview swap loads a new checkpoint. A non-preview request captures it before the lifecycle gate; if it
@@ -100,22 +99,19 @@ _INFERENCE_SUFFIXES = (
"/video/generate",
)
-# matched WHOLE, not by suffix: a bare "/videos" entry would class an unrouted /v1/anything/videos as inference
# Matched WHOLE, not by suffix. The suffix tuple above is an endswith test, so a bare "/videos" entry would also class
-# an unrouted /v1/anything/videos as inference: that 404s before any auth dependency, and this middleware only excludes
-# 401/403, so each such probe would refresh the chat model's idle timer and keep it resident for free.
+# an unrouted /v1/anything/videos as inference: that 404s before any auth dependency, and this middleware only
+# excludes 401/403, so each such probe would refresh the chat model's idle timer and keep it resident for free.
_INFERENCE_EXACT_PATHS = frozenset({"/v1/videos", "/api/inference/videos"})
-# tracked above (they hold the GPU) but served by the diffusion/video engines, never the llama slot
# Tracked above (they hold the GPU, so the in-flight count must see them) but served by the diffusion/video engines,
-# never the llama slot. A successful one therefore did NOT run against the resident chat model and must not adopt it for
-# Unsloth: clearing the marker on an image or video generation would leave a still-preview-owned checkpoint looking
-# Unsloth-owned, and the next preview for a different checkpoint would 503 on the slot guard.
+# never the llama slot. A successful one therefore did NOT run against the resident chat model and must not adopt it
+# for Unsloth: clearing the marker on an image or video generation would leave a still-preview-owned checkpoint
+# looking Unsloth-owned, and the next preview for a different checkpoint would 503 on the slot guard.
_NON_LLM_SLOT_SUFFIXES = (
"/images/generate",
"/images/generations",
"/video/generate",
- # the OpenAI videos route runs the video backend only, exactly like /video/generate
# The OpenAI videos route (/v1/videos + /api/inference/videos) runs the video backend only, exactly like
# /video/generate. It is tracked as an inference path, so without this it would claim the slot and clear preview
# ownership.
@@ -349,32 +345,27 @@ def _claim_non_preview_slot() -> None:
logger.debug("preview-slot claim on completion failed: %s", exc)
-# set by a route that proved this request will not touch llama.cpp
-# Set on the scope by a route that proved this request won't touch llama.cpp (e.g. it proxied to an external provider),
-# so the keep-warm count excludes it and the middleware skips its end-decrement.
+# Set on the scope by a route that proved this request will not touch llama.cpp (e.g. it proxied to an external
+# provider), so the keep-warm count excludes it and the middleware skips its end-decrement.
_UNTRACKED_SCOPE_KEY = "_unsloth_keepwarm_untracked"
# Set after middleware admission so the preview route can distinguish a real tracked request from direct unit/helper
# calls that have no counters to move.
_TRACKED_SCOPE_KEY = "_unsloth_keepwarm_tracked"
-# while queued on its own serializer a preview must be pending
# A preview route waits on its own serializer after middleware admission. While queued it must be pending, not active:
# an Unsloth swap holds the lifecycle gate while draining active requests, and the queued preview needs that same gate
# after it gets the serializer.
_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY = "_unsloth_keepwarm_preview_serializer_wait"
-# set by the middleware when a preview swap advanced the counter while a non-preview request waited on the gate;
# Set by the middleware on a non-preview scope when a preview swap advanced the counter while it waited on the gate;
# _maybe_auto_switch_model then rejects it rather than serve the swapped-in checkpoint. Deferred to the route (not a
-# middleware 503) so an external- provider request that untracks and returns before that check is never rejected.
+# middleware 503) so an external-provider request that untracks and returns before that check is never rejected.
_PREVIEW_SWAP_REJECT_SCOPE_KEY = "_unsloth_keepwarm_preview_swap_reject"
-# the swap generation at middleware entry, so local-inference admission can also reject a request that passed the gate
-# BEFORE a swap
-# The swap generation snapshot at middleware entry, on the scope so local-inference admission can also reject a request
-# that passed the gate BEFORE a swap (never got the gate-wait reject flag) but is still pre-auth when a preview swaps
-# in.
+# The swap generation snapshot at middleware entry, on the scope so local-inference admission can also reject a
+# request that passed the gate BEFORE a swap (never got the gate-wait reject flag) but is still pre-auth when a
+# preview swaps in.
_SWAP_GEN_AT_ENTRY_KEY = "_unsloth_keepwarm_swap_gen_at_entry"
# Set on the scope by a streaming route that failed after its 200 headers (an SSE error chunk, a passthrough relaying a
@@ -391,8 +382,6 @@ def mark_response_failed(scope) -> None:
scope[_RESPONSE_FAILED_SCOPE_KEY] = True
-# the current request's ASGI scope, so deep streaming error helpers can flag a failure without threading the scope
-# through every yield site
# The current request's ASGI scope, set by the middleware so deep streaming error helpers can flag a failure without
# threading the scope through every yield site. The middleware shares the streaming body's task, so the contextvar
# reaches those generators.
@@ -625,16 +614,15 @@ def _as_bytes(value) -> bytes:
def _carries_bearer_credentials(scope, path: str = "") -> bool:
"""Whether this request carries the credentials its route demands.
- Every tracked media route depends on ``get_current_subject`` (HTTPBearer), so a request
- without one is refused before any handler runs. Counting it anyway would still pin the
- pipeline: the count is taken here, ahead of FastAPI parsing the body, and a client that
- opens the POST and then withholds its body produces no response status either, so the
- 401/403 exclusion below never gets to run. One such connection, replaced as it times
- out, would keep a multi-GB pipeline resident for good. Real clients always send the
- header, so requiring it costs a legitimate generation nothing. Keyless API access is
- the one case where a route demands no bearer at all. Its outer admission middleware
- records that decision before keep-warm runs, so reuse the snapshot instead of
- repeating settings, listener, and DNS work on this loop.
+ Every tracked media route depends on ``get_current_subject`` (HTTPBearer), so a request without
+ one is refused before any handler runs. Counting it anyway would still pin the pipeline: the
+ count is taken here, ahead of FastAPI parsing the body, and a client that opens the POST and
+ then withholds its body produces no response status either, so the 401/403 exclusion below never
+ gets to run -- one such connection, replaced as it times out, would keep a multi-GB pipeline
+ resident for good. Real clients always send the header. Keyless API access is the one case where
+ a route demands no bearer at all; its outer admission middleware records that decision before
+ keep-warm runs, so reuse the snapshot instead of repeating settings, listener and DNS work on
+ this loop.
"""
from utils.keyless_api_access import KEYLESS_ADMISSION_STATE_KEY
@@ -661,9 +649,8 @@ class LlamaKeepWarmMiddleware:
self.app = app
async def __call__(self, scope, receive, send):
- # inference endpoints are all POST, so skipping non-POST avoids counting CORS preflight
- # Inference endpoints are all POST; skipping non-POST avoids counting CORS preflight (OPTIONS). ``or ""`` guards
- # an explicit None path.
+ # Inference endpoints are all POST; skipping non-POST avoids counting CORS preflight (OPTIONS). ``or ""``
+ # guards an explicit None path.
path = scope.get("path") or ""
if scope.get("type") != "http" or scope.get("method") != "POST":
await self.app(scope, receive, send)
@@ -720,11 +707,10 @@ class LlamaKeepWarmMiddleware:
raise
ended = {"done": False}
status = {"code": None}
- # set once the terminal body frame is sent: only a cleanly completed response adopts the model for Unsloth.
- # Set once the terminal body frame (more_body False) is sent: only a response that completed cleanly adopts the
- # model for Unsloth. A client disconnect after the 200 headers raises before that frame (an OSError that
- # _SameTaskStreamingResponse turns into a CancelledError for the body generator, which finishes the monitor and
- # re-raises without flagging the scope), so a cancelled stream never claims the slot.
+ # Set once the terminal body frame (more_body False) is sent: only a response that completed cleanly adopts
+ # the model for Unsloth. A client disconnect after the 200 headers raises before that frame (an OSError that
+ # _SameTaskStreamingResponse turns into a CancelledError for the body generator, which finishes the monitor
+ # and re-raises without flagging the scope), so a cancelled stream never claims the slot.
completed = {"done": False}
def _finish() -> None:
@@ -757,9 +743,8 @@ class LlamaKeepWarmMiddleware:
and not scope.get(_UNTRACKED_SCOPE_KEY)
):
_claim_non_preview_slot()
- # balance note_admitted_inference here (in the finally, so it cannot leak on any exit path), after the claim
- # Balance note_admitted_inference here (runs in the finally, so it can't leak on any exit path), after the
- # claim above and before the untracked / 401 early returns.
+ # Balance note_admitted_inference here (runs in the finally, so it cannot leak on any exit path), after
+ # the claim above and before the untracked / 401 early returns.
if scope.get(_ADMITTED_SCOPE_KEY):
_note_admitted_end()
if scope.get(_UNTRACKED_SCOPE_KEY):
@@ -786,7 +771,6 @@ class LlamaKeepWarmMiddleware:
"more_body", False
)
await send(message)
- # claim only after the terminal frame is delivered
# Claim only after the terminal frame is actually delivered: a client that disconnects on the final write
# makes send() above raise, so completed stays False and the cut-off stream is not mistaken for a clean
# completion.
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index 7a9205b31fd..087f20cf95b 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -1,15 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Boundary validator for user-supplied llama-server pass-through args.
-
-Reject only flags Unsloth manages (model identity, auth, network, parallel
-slots). Everything else (sampling, ``-c``, ``-ngl``, ``--flash-attn``,
-``--cache-type-*``, ``--spec-*``, ``--jinja``, ...) is appended after
-Unsloth's auto-set flags so llama.cpp's last-wins parser lets the user override.
-
-Ref: https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md
-"""
+"""Boundary validator for user-supplied llama-server pass-through args. Reject only flags Unsloth
+manages (model identity, auth, network, parallel slots). Everything else (sampling, ``-c``,
+``-ngl``, ``--flash-attn``, ``--cache-type-*``, ``--spec-*``, ``--jinja``, ...) is appended after
+Unsloth's auto-set flags so llama.cpp's last-wins parser lets the user override. Ref:
+https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md"""
from __future__ import annotations
@@ -20,8 +16,8 @@ from typing import Any, Iterable, Mapping, Optional
logger = logging.getLogger(__name__)
-# Valid llama-server --parallel range, shared with LoadRequest.n_parallel. Mirrored by callers that cannot import this:
-# run.py and unsloth_cli/commands/ studio.py (_PARALLEL_MIN/MAX), per-model-config.ts (N_PARALLEL_MIN/MAX);
+# Valid llama-server --parallel range, shared with LoadRequest.n_parallel. Mirrored by callers that cannot import
+# this: run.py and unsloth_cli/commands/studio.py (_PARALLEL_MIN/MAX), per-model-config.ts (N_PARALLEL_MIN/MAX);
# test_parallel_slots_per_load.py pins them together.
PARALLEL_MIN = 1
PARALLEL_MAX = 64
@@ -30,8 +26,8 @@ PARALLEL_MAX = 64
BATCH_MIN = 1
BATCH_MAX = 65536
-# Sanity bounds, not upstream ones: a stray keystroke fails here rather than in the child. --cache-ram floors at -1 ("no
-# limit"); 0 disables the cache. Mirrored by CTX_CHECKPOINTS_MAX / CACHE_RAM_MAX in per-model-config.ts.
+# Sanity bounds, not upstream ones: a stray keystroke fails here rather than in the child. --cache-ram floors at -1
+# ("no limit"); 0 disables the cache. Mirrored by CTX_CHECKPOINTS_MAX / CACHE_RAM_MAX in per-model-config.ts.
CTX_CHECKPOINTS_MAX = 256
CACHE_RAM_MAX_MIB = 1024 * 1024
@@ -45,11 +41,9 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
# Parallel slots: owned by typer --parallel and LoadRequest.n_parallel; a pass-through would desync the slot
# bookkeeping from llama-server.
_PARALLEL_FLAGS,
- # Model identity: a second -m would load a different model than Unsloth thinks it loaded
- # Model identity: Unsloth resolves it from LoadRequest; a second -m would load a different model than Unsloth thinks
- # it loaded.
+ # Model identity: Unsloth resolves it from LoadRequest; a second -m would load a different model than Unsloth
+ # thinks it loaded.
frozenset({"-m", "--model"}),
- # Unsloth sets a sanitized --alias so the OpenAI API never exposes the local .gguf path;
# Public model id: Unsloth sets a sanitized --alias so the OpenAI API never exposes the local .gguf path. A
# user-supplied alias is appended after Unsloth's and, with llama.cpp's last-wins parsing, would reintroduce the
# path leak this is meant to prevent.
@@ -91,13 +85,12 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
# Pooling decides whether the managed embedding launch is safe. A pass-through override appended after --embedding
# could switch it to NONE or RANK.
frozenset({"--pooling"}),
- # llama-server's own tools flag would silently stack on top of Unsloth's --enable-tools / --disable-tools policy
- # resolver
# llama-server's own built-in tools flag would silently stack on top of Unsloth's --enable-tools / --disable-tools
# policy resolver.
frozenset({"--tools"}),
- # --agent is --tools by another name: upstream documents it as "enable CORS proxy and ALL built-in tools", and that
- # set includes exec_shell_command. Denying --tools while allowing this left the same capability one alias away.
+ # --agent is --tools by another name: upstream documents it as "enable CORS proxy and ALL built-in tools", and
+ # that set includes exec_shell_command. Denying --tools while allowing this left the same capability one alias
+ # away.
frozenset({"-ag", "--agent", "-no-ag", "--no-agent"}),
# Where those tools run: docker:/podman: spins up a container, ssh:<target> runs them on another host entirely.
frozenset({"--tools-runtime"}),
@@ -113,12 +106,13 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
frozenset({"--cors-credentials", "--no-cors-credentials"}),
# Serves local files over the child's HTTP surface.
frozenset({"--media-path"}),
- # Startup output is how _classify_llama_start_failure tells a bad GGUF from an OOM from a rejected flag; redirecting
- # or silencing it makes every failure the same opaque one.
+ # Startup output is how _classify_llama_start_failure tells a bad GGUF from an OOM from a rejected flag;
+ # redirecting or silencing it makes every failure the same opaque one.
frozenset({"--log-file"}),
frozenset({"--log-disable"}),
# Slot-state dir: Unsloth owns it for KV persistence across idle unload. Endpoint exposure (--slots, --props) is
- # deliberately NOT denied alongside it: Unsloth reads GET /props and never /slots, so either is the user's own call.
+ # deliberately NOT denied alongside it: Unsloth reads GET /props and never /slots, so either is the user's own
+ # call.
frozenset({"--slot-save-path"}),
# These print and exit instead of serving, so the load would "succeed" with no server behind it and only time out
# later
@@ -131,11 +125,10 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
_DENYLIST: frozenset[str] = frozenset().union(*_DENYLIST_GROUPS)
-# Flags that take TWO values rather than one. Scanned out of `llama-server --help`: every other option is `--flag VALUE`
-# or a switch, and this list exists so the positional check below does not refuse a legitimate second value.
+# Flags that take TWO values rather than one. Scanned out of `llama-server --help`: every other option is `--flag
+# VALUE` or a switch, and this list exists so the positional check below does not refuse a legitimate second value.
_TWO_VALUE_FLAGS: frozenset[str] = frozenset({"--control-vector-layer-range"})
-# Flags taking a second value on SOME builds (llama.cpp)
# Flags that take a second value on SOME builds. Today's llama.cpp writes the scale into the value ("--lora-scaled
# FNAME:SCALE"), and older ones took it as a separate token ("--lora-scaled FNAME SCALE"); both spellings are already
# handled in _sidecar_weight_files. So the second token is allowed but never required: demanding it would refuse the
@@ -144,31 +137,29 @@ _OPTIONAL_SECOND_VALUE_FLAGS: frozenset[str] = frozenset(
{"--lora-scaled", "--control-vector-scaled"}
)
-# Shape bounds. Not a security boundary -- the denylist is -- but a pasted file or a runaway generator should fail here,
-# naming the limit, rather than at execve or in llama-server's own parser. Generous enough that a grammar or a JSON
-# schema fits.
+# Shape bounds. Not a security boundary -- the denylist is -- but a pasted file or a runaway generator should fail
+# here, naming the limit, rather than at execve or in llama-server's own parser. Generous enough that a grammar or a
+# JSON schema fits.
MAX_EXTRA_ARG_TOKENS = 256
MAX_EXTRA_ARGS_BYTES = 32 * 1024
# Windows passes CreateProcess ONE string for the whole command line, capped at 32767 characters, and the model path,
-# Unsloth's own flags and the quoting subprocess adds all come out of the same budget. So the extras get a smaller share
-# there: accepting the full 32 KiB would pass every check here and then fail inside Popen, after the load had already
-# begun switching models.
+# Unsloth's own flags and the quoting subprocess adds all come out of the same budget. So the extras get a smaller
+# share there: accepting the full 32 KiB would pass every check here and then fail inside Popen, after the load had
+# already begun switching models.
MAX_EXTRA_ARGS_BYTES_WINDOWS = 24 * 1024
-# CreateProcess takes the whole command line as ONE string, capped here. The rest of the command (the binary, the model
-# path, Unsloth's own flags) has to fit too, so the extras are checked against the limit minus this reserve.
+# CreateProcess takes the whole command line as ONE string, capped here. The rest of the command (the binary, the
+# model path, Unsloth's own flags) has to fit too, so the extras are checked against the limit minus this reserve.
WINDOWS_COMMAND_LIMIT = 32767
WINDOWS_COMMAND_RESERVE = 8192
def windows_command_length(args: list) -> int:
- """Characters ``subprocess`` would put on a Windows command line for ``args``.
-
- list2cmdline is the exact serializer Popen uses there, and it is not a sum of
- lengths: a value needing quotes has its backslashes doubled, so an escape-heavy
- grammar can nearly double. Measuring it is the only honest check.
- """
+ """Characters ``subprocess`` would put on a Windows command line for ``args``. list2cmdline is
+ the exact serializer Popen uses there, and it is not a sum of lengths: a value needing quotes
+ has its backslashes doubled, so an escape-heavy grammar can nearly double. Measuring it is
+ the only honest check."""
import subprocess
return len(subprocess.list2cmdline([str(a) for a in args]))
@@ -179,13 +170,10 @@ def max_extra_args_bytes() -> int:
def _flag_name(token: str) -> Optional[str]:
- """Flag name for ``token``, or None if it isn't a flag.
-
- Peels `--key=value` to `--key`, normalises long-option underscores like
- llama.cpp, treats `-1`/`-0.5` as values (shorts always start with a letter),
- and normalises attached `-np8` / `-np-1` / `-np8x` to `-np`. Mirrors the
- CLI's `_expand_attached_np_short`.
- """
+ """Flag name for ``token``, or None if it isn't a flag. Peels `--key=value` to `--key`,
+ normalises long-option underscores like llama.cpp, treats `-1`/`-0.5` as values (shorts
+ always start with a letter), and normalises attached `-np8` / `-np-1` / `-np8x` to `-np`.
+ Mirrors the CLI's `_expand_attached_np_short`."""
token = token.strip()
if not token.startswith("-") or token in {"-", "--"}:
return None
@@ -204,14 +192,11 @@ def _flag_name(token: str) -> Optional[str]:
def _value_is_attached(token: str, flag: str) -> bool:
- """Whether this token carries its own value, rather than expecting the next one.
-
- Not "the name changed": _flag_name also folds llama.cpp's underscore spelling
- (--ctx_size is --ctx-size to it, and the binary takes both), so comparing the
- normalised name against the raw token read "--ctx_size 4096" as attached and then
- refused the 4096 as a bare value. Only "=" and an attached short like -np8 are
- values in the same token.
- """
+ """Whether this token carries its own value, rather than expecting the next one. Not "the name
+ changed": _flag_name also folds llama.cpp's underscore spelling (--ctx_size is --ctx-size to
+ it, and the binary takes both), so comparing the normalised name against the raw token read
+ "--ctx_size 4096" as attached and then refused the 4096 as a bare value. Only "=" and an
+ attached short like -np8 are values in the same token."""
raw = token.strip()
if "=" in raw:
return True
@@ -233,9 +218,9 @@ def _has_control_characters(token: str) -> bool:
def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
- """Validate user-supplied llama-server args. Returns a flat list ready to
- extend the llama-server command; raises ``ValueError`` naming the
- offending flag on the first managed token."""
+ """Validate user-supplied llama-server args. Returns a flat list ready to extend the
+ llama-server command; raises ``ValueError`` naming the offending flag on the first managed
+ token."""
if not args:
return []
out: list[str] = []
@@ -252,10 +237,10 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
raise ValueError(
f"too many extra llama-server args (limit {MAX_EXTRA_ARG_TOKENS} tokens)"
)
- # A grammar or JSON schema is a legitimately long single token, so the cap is on the whole list rather than per
- # token. Strictly, unlike the sizing below: JSON and the browser can both carry an unpaired surrogate, which
- # survives every check here and then makes subprocess.Popen raise while it encodes argv, long after the load has
- # begun switching models. Refused at the boundary, where it is still a 400.
+ # A grammar or JSON schema is a legitimately long single token, so the cap is on the whole list rather than
+ # per token. Strictly, unlike the sizing below: JSON and the browser can both carry an unpaired surrogate,
+ # which survives every check here and then makes subprocess.Popen raise while it encodes argv, long after the
+ # load has begun switching models. Refused at the boundary, where it is still a 400.
try:
encoded = token.encode("utf-8")
except UnicodeEncodeError as error:
@@ -276,18 +261,15 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
f"llama-server flag '{flag}' is managed by Unsloth Studio "
f"and cannot be passed as an extra arg"
)
- # #9510: users reaching for `--parallel 1` hit this refusal with no pointer to the supported knob
# Why (#9510): users reaching for `--parallel 1` to cap concurrent predictions on a local model hit this
# refusal with no pointer to the supported knob; name it.
if flag in _PARALLEL_FLAGS:
message += "; set n_parallel on the load request (parallel decode slots) instead"
raise ValueError(message)
if flag is None:
- # A token belonging to no flag: llama-server answers "invalid argument" and refuses to start (a failed load,
- # not a 400)
- # A token belonging to no flag. Today's llama-server answers "invalid argument" and refuses to start, which
- # is a failed load rather than a 400, and a build that did accept a positional would read it as the model
- # path: that is the one thing the -m / --model denial exists to prevent, and it would sidestep the
+ # A token belonging to no flag. Today's llama-server answers "invalid argument" and refuses to start,
+ # which is a failed load rather than a 400, and a build that did accept a positional would read it as the
+ # model path: that is the one thing the -m / --model denial exists to prevent, and it would sidestep the
# native-path lease as well.
if pending_values <= 0:
raise ValueError(
@@ -304,13 +286,13 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
f"write it as '{flag}'"
)
elif "=" in token:
- # llama.cpp looks the WHOLE token up, folding only the underscore spelling (b10342, b10360)
# llama.cpp looks the WHOLE token up in its option map, folding only the underscore spelling, so
# "--top-k=20" is not "--top-k" with a value: it is an argument it has never heard of. Measured on b10342
# and b10360, where --top-k=20, --ctx-size=4096 and --flash-attn=on each exit with "error: invalid
# argument". Accepting the GNU spelling here meant the switch tore down the resident model and the child
# then refused to start, so it is refused while it is still a 400 with somewhere to go. Splitting it here
- # would be a guess: for a switch the value is not one, and this module cannot know an ordinary flag's arity.
+ # would be a guess: for a switch the value is not one, and this module cannot know an ordinary flag's
+ # arity.
value = token.partition("=")[2]
raise ValueError(
f"llama-server does not read an attached value: write '{flag}' and "
@@ -321,10 +303,8 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
attached = _value_is_attached(token, flag)
if pending_two_value > 0:
raise ValueError(f"llama-server flag '{two_value_flag}' takes two values")
- # An attached value is ONE of the two: "--control-vector-layer-range=1" still owes its END and llama-server
- # exits on the incomplete option
- # An attached value is ONE of the two, not the whole option: "--control-vector-layer-range=1" still owes its
- # END, and llama-server exits on the incomplete option.
+ # An attached value is ONE of the two, not the whole option: "--control-vector-layer-range=1" still owes
+ # its END, and llama-server exits on the incomplete option.
if flag in _TWO_VALUE_FLAGS:
pending_values = 1 if attached else 2
pending_two_value = pending_values
@@ -361,17 +341,16 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[str]]:
"""Split stored args into what still loads and the flag names removed.
- For the paths that CARRY OVER an existing value rather than receive a new one.
- The denylist grows (``--agent`` and the MCP flags were added once a text box
- made them one paste away), so an override saved by an older build can hold a
- name that is refused today. Refusing there punishes a user for a decision made
- later: the load, or the save of an unrelated setting, fails naming a flag they
- may not remember writing. Dropping is the same judgement applied quietly.
-
- A flag takes its value with it, or ``--log-file /var/log/x`` would leave a bare
- ``/var/log/x`` behind, which llama.cpp reads as a positional model path. The
- bounds and the control-character rule are enforced by re-validating what is
- left, so the result is always something ``validate_extra_args`` accepts.
+ For the paths that CARRY OVER an existing value rather than receive a new one. The denylist
+ grows (``--agent`` and the MCP flags were added once a text box made them one paste away), so an
+ override saved by an older build can hold a name that is refused today. Refusing there punishes
+ a user for a decision made later: the load, or the save of an unrelated setting, fails naming a
+ flag they may not remember writing. Dropping is the same judgement applied quietly.
+
+ A flag takes its value with it, or ``--log-file /var/log/x`` would leave a bare ``/var/log/x``
+ behind, which llama.cpp reads as a positional model path. The bounds and the control-character
+ rule are enforced by re-validating what is left, so the result is always something
+ ``validate_extra_args`` accepts.
"""
tokens = [str(raw) for raw in (args or [])]
@@ -381,11 +360,9 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
flag: str,
source: list = None,
) -> bool:
- """True when the token's value is the NEXT token rather than its own.
-
- ``source`` defaults to the input list; the trimming loop passes the list it
- is shortening, where "the next token" means the one just removed.
- """
+ """True when the token's value is the NEXT token rather than its own. ``source`` defaults to
+ the input list; the trimming loop passes the list it is shortening, where "the next
+ token" means the one just removed."""
if _value_is_attached(token, flag):
return False
seq = tokens if source is None else source
@@ -406,7 +383,6 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
dropped.append(flag)
skip_next = _takes_next(index, token, flag)
continue
- # A poisoned VALUE takes its flag with it for the same reason a denied flag takes its value
# A control character never reached the child as anything but noise, and a NUL never reached it at all (execve
# refuses). A poisoned VALUE takes its flag with it for the same reason a denied flag takes its value: a flag
# left expecting one would eat the next token and change what that means.
@@ -416,8 +392,8 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
# would.
dropped.append("<flag>" if flag is not None else "<value>")
if flag is not None:
- # Its value goes too, exactly as a denied flag's does: an orphan left behind is a bare positional, which
- # llama-server reads as the model path.
+ # Its value goes too, exactly as a denied flag's does: an orphan left behind is a bare positional,
+ # which llama-server reads as the model path.
skip_next = _takes_next(index, token, flag)
elif kept:
owner = _flag_name(kept[-1])
@@ -433,8 +409,8 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
dropped.append(flag)
continue
if flag is not None and token != token.strip():
- # Refused for the same reason, and its value goes with it: the padding is part of the token llama.cpp looks
- # up, so the flag never arrives and the value it was written for would be left as a bare positional.
+ # Refused for the same reason, and its value goes with it: the padding is part of the token llama.cpp
+ # looks up, so the flag never arrives and the value it was written for would be left as a bare positional.
dropped.append(flag)
skip_next = _takes_next(index, token, flag)
continue
@@ -453,11 +429,11 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
try:
return validate_extra_args(kept), dropped
except ValueError:
- # Only the bounds can still fail here, and they are about length, so the tail is the right thing to shed. A
- # flag whose value has just gone with it goes too: `['--grammar', <33 KiB>]` trimmed to `['--grammar']` is
- # syntactically valid to this validator, which knows the arity of only a few flags, and llama-server then
- # refuses the launch over a flag with no value. Names, not values: this list goes into a log line, and the
- # token that broke the bound is by definition enormous.
+ # Only the bounds can still fail here, and they are about length, so the tail is the right thing to shed.
+ # A flag whose value has just gone with it goes too: `['--grammar', <33 KiB>]` trimmed to `['--grammar']`
+ # is syntactically valid to this validator, which knows the arity of only a few flags, and llama-server
+ # then refuses the launch over a flag with no value. Names, not values: this list goes into a log line,
+ # and the token that broke the bound is by definition enormous.
dropped.append(_flag_name(kept[-1]) or "<value>")
kept = kept[:-1]
last_flag = _flag_name(kept[-1]) if kept else None
@@ -481,14 +457,14 @@ def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[s
def sorted_managed_flags() -> list[str]:
- """Every denied flag, sorted, for a UI that wants to explain a rejection before
- the request is made. The validator stays the authority; this is only a mirror."""
+ """Every denied flag, sorted, for a UI that wants to explain a rejection before the request is
+ made. The validator stays the authority; this is only a mirror."""
return sorted(_DENYLIST)
def is_managed_flag(flag: str) -> bool:
- """True if ``flag`` is Unsloth-managed. Normalises via ``_flag_name`` so
- `-np8` / `--parallel=8` classify like the canonical tokens."""
+ """True if ``flag`` is Unsloth-managed. Normalises via ``_flag_name`` so `-np8` / `--parallel=8`
+ classify like the canonical tokens."""
normalised = _flag_name(flag)
return normalised is not None and normalised in _DENYLIST
@@ -507,14 +483,13 @@ _SPEC_FLAGS: frozenset[str] = frozenset(
"--spec-ngram-size",
"--draft-min",
"--draft-max",
- # MTP path (llama.cpp #22673). explicit extras for the current load are never stripped. MTP path (llama.cpp
- # #22673). The drafter selectors (local --model-draft and HF --spec-draft-hf aliases) are Unsloth-managed since
- # the separate- drafter support (Gemma 4): an inherited copy must not last-wins-override the auto-detected
- # drafter. Explicit extras for the current load are never stripped. The per-drafter tuning knobs (-ngld,
- # --spec-draft-device) are NOT stripped: the VRAM budget reads them via the same parsers the child honors, so
- # they stay consistent on inherit, and stripping them would silently move a CPU-offloaded drafter back onto the
- # GPU. The draft cache dtype is in that group too, and has its own toggle used only when spec_draft_cache_type
- # is set, the same rule the batch pair follows.
+ # MTP path (llama.cpp #22673). The drafter selectors (local --model-draft and HF --spec-draft-hf aliases) are
+ # Unsloth-managed since the separate-drafter support (Gemma 4): an inherited copy must not last-wins-override
+ # the auto-detected drafter, while explicit extras for the current load are never stripped. The per-drafter
+ # tuning knobs (-ngld, --spec-draft-device) are NOT stripped: the VRAM budget reads them via the same parsers
+ # the child honors, so they stay consistent on inherit, and stripping them would silently move a CPU-offloaded
+ # drafter back onto the GPU. The draft cache dtype is in that group too, with its own toggle used only when
+ # spec_draft_cache_type is set, the same rule the batch pair follows.
"--model-draft",
"-md",
"--spec-draft-model",
@@ -540,20 +515,18 @@ _TEMPLATE_FLAGS: frozenset[str] = frozenset(
"--no-jinja",
}
)
-# Multi-GPU split mode shadows the Tensor Parallelism toggle (--split-mode tensor). Pass-through stays allowed so users
-# keep the row/none/layer modes the toggle doesn't expose, but it's stripped on inherit and reconciled into the
-# round-tripped tensor_parallel state. --tensor-split is coupled to the split mode and is stripped with it: Unsloth owns
-# the tensor-mode split ratios, so an inherited/stale --tensor-split must not last-wins-override Unsloth's computed
-# asymmetric split.
+# Multi-GPU split mode shadows the Tensor Parallelism toggle (--split-mode tensor). Pass-through stays allowed so
+# users keep the row/none/layer modes the toggle doesn't expose, but it's stripped on inherit and reconciled into the
+# round-tripped tensor_parallel state. --tensor-split is coupled to the split mode and is stripped with it: Unsloth
+# owns the tensor-mode split ratios, so an inherited/stale --tensor-split must not last-wins-override Unsloth's
+# computed asymmetric split.
_SPLIT_MODE_FLAGS: frozenset[str] = frozenset({"-sm", "--split-mode"})
_TENSOR_SPLIT_FLAGS: frozenset[str] = frozenset({"-ts", "--tensor-split"})
_SPLIT_SHADOWING_FLAGS: frozenset[str] = _SPLIT_MODE_FLAGS | _TENSOR_SPLIT_FLAGS
-# llama.cpp placement flags (#7188)
-# llama.cpp placement flags. Opt-in (users may pass them under auto-select): stripped only when gpu_ids is set, so they
-# cannot override the selected pool or choose a main GPU outside it (#7188).
+# llama.cpp placement flags. Opt-in (users may pass them under auto-select): stripped only when gpu_ids is set, so
+# they cannot override the selected pool or choose a main GPU outside it (#7188).
_DEVICE_FLAGS: frozenset[str] = frozenset({"--device", "-dev", "--main-gpu", "-mg"})
-# GPU-offload flags. in auto a user's inherited -ngl is respected.
# GPU-offload flags. Stripped only when the GPU Memory mode owns offload (manual emits --fit / --gpu-layers /
# --n-cpu-moe); in auto, a user's inherited -ngl is respected (the offload_overridden path), so this group is opt-in,
# not default. Layer flags are shared with llama_cpp's override detection; the MoE flags are strip-only (manual's
@@ -577,7 +550,6 @@ _SPEC_DRAFT_CACHE_V_FLAGS: frozenset[str] = frozenset(
)
_SPEC_DRAFT_CACHE_FLAGS: frozenset[str] = _SPEC_DRAFT_CACHE_K_FLAGS | _SPEC_DRAFT_CACHE_V_FLAGS
_FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})
-# The fitter's per-device margin.
# The fitter's per-device margin. Never stripped (llama.cpp is last-wins), so a pass-through value is what the child
# really keeps free; see fit_target_margin_in.
_FIT_TARGET_FLAGS: frozenset[str] = frozenset({"-fitt", "--fit-target"})
@@ -585,13 +557,12 @@ _LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS
_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})
_OFFLOAD_SHADOWING_FLAGS: frozenset[str] = _LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGS
-# Host-memory placement flags. Both are full-model RAM reservations (--mlock pins it, --no-mmap mallocs a copy), so the
-# Model Memory settings own them: stripped only when a toggle vetoes them, never unconditionally.
+# Host-memory placement flags. Both are full-model RAM reservations (--mlock pins it, --no-mmap mallocs a copy), so
+# the Model Memory settings own them: stripped only when a toggle vetoes them, never unconditionally.
_MLOCK_FLAGS: frozenset[str] = frozenset({"--mlock", "-mlock"})
# Modern spelling of both, as an enum value. Takes a value, so NOT boolean.
_LOAD_MODE_FLAGS: frozenset[str] = frozenset({"--load-mode", "-lm"})
_NO_MMAP_FLAGS: frozenset[str] = frozenset({"--no-mmap", "-no-mmap"})
-# Deprecated selectors for the same enum. Affirmative dio streams and holds no full copy;
# Deprecated selectors for the same load-mode enum. Measured: ANY of them trailing the managed flag resets the WHOLE
# mode and drops the mlock, in both polarities ("--mmap" and "--no-direct-io" do it too). Affirmative dio streams and
# holds no full copy; the negative spellings are NOT plain mmap, upstream maps them to mode `none` like --no-mmap, so
@@ -602,8 +573,8 @@ _DIO_FLAGS: frozenset[str] = _DIO_ON_FLAGS | _DIO_OFF_FLAGS
_LOAD_MODE_ALIAS_FLAGS: frozenset[str] = _NO_MMAP_FLAGS | frozenset({"--mmap"}) | _DIO_FLAGS
# Every spelling that asks for a full-model host buffer.
_RAM_RESERVING_FLAGS: frozenset[str] = _NO_MMAP_FLAGS | _DIO_OFF_FLAGS
-# llama.cpp reads these before argv, so an inherited value survives stripping the equivalent tokens. Scrubbed whenever a
-# toggle is on, like the spec/placement env groups, so the setting owns memory placement outright.
+# llama.cpp reads these before argv, so an inherited value survives stripping the equivalent tokens. Scrubbed whenever
+# a toggle is on, like the spec/placement env groups, so the setting owns memory placement outright.
MEMORY_ENV_VARS: tuple[str, ...] = (
"LLAMA_ARG_MLOCK",
"LLAMA_ARG_MMAP",
@@ -640,11 +611,8 @@ _BOOLEAN_SHADOWING_FLAGS: frozenset[str] = frozenset(
def parse_ctx_override(args: Optional[Iterable[str]]) -> Optional[int]:
- """Return the last user-supplied ``-c`` / ``--ctx-size`` value.
-
- Mirrors llama.cpp's last-wins parsing for the one numeric knob Unsloth's
- load-time fit logic needs.
- """
+ """Return the last user-supplied ``-c`` / ``--ctx-size`` value. Mirrors llama.cpp's last-wins
+ parsing for the one numeric knob Unsloth's load-time fit logic needs."""
if not args:
return None
@@ -679,13 +647,10 @@ def parse_ctx_override(args: Optional[Iterable[str]]) -> Optional[int]:
def parse_ctx_checkpoints_override(args: Optional[Iterable[str]]) -> Optional[int]:
- """Return the last user-supplied ``--ctx-checkpoints`` value, or None.
-
- The control emits its flag before the extras, so a copy typed for this load
- last-wins at launch. Sizing has to price that value, not the field, or a
- ``--ctx-checkpoints 256`` in the extras allocates 256 per-slot snapshots
- against a fit that budgeted the field's count.
- """
+ """Return the last user-supplied ``--ctx-checkpoints`` value, or None. The control emits its
+ flag before the extras, so a copy typed for this load last-wins at launch. Sizing has to
+ price that value, not the field, or a ``--ctx-checkpoints 256`` in the extras allocates 256
+ per-slot snapshots against a fit that budgeted the field's count."""
value = _last_flag_value(args, _CTX_CHECKPOINTS_FLAGS)
if value is None:
return None
@@ -703,28 +668,26 @@ def resolve_ctx_checkpoints(args: Optional[Iterable[str]], requested: Optional[i
def resolve_requested_ctx(args: Optional[Iterable[str]], fallback_n_ctx: int) -> int:
- """Return the context size load_model should treat as requested.
-
- Single source of truth for load_model's ctx-override conditional so
- tests don't reimplement and assert against their own logic.
- """
+ """Return the context size load_model should treat as requested. Single source of truth for
+ load_model's ctx-override conditional so tests don't reimplement and assert against their own
+ logic."""
override = parse_ctx_override(args)
return override if override is not None else fallback_n_ctx
def matches_explicit_ctx_override(args: Optional[Iterable[str]], n_ctx: Any) -> bool:
- """Whether a pass-through ``-c``/``--ctx-size`` matches the context the caller
- is already sending as a first-class field.
-
- Context is the one first-class field whose load-time value is a VRAM-fit
- TARGET, so a matching flag is not a stale shadow but the user's standing
- decision to run past the estimated threshold. Both strippers ask here rather
- than mirroring the test, so auto-switch and /load inheritance cannot drift.
-
- False for anything unconfirmable, which is the pre-existing strip: no flag, a
- malformed one, or a non-positive/non-int ``n_ctx``. That last case is real --
- override rows are coerced on write but returned verbatim on read, so a row
- from an older build can hold any JSON type and must not raise here.
+ """Whether a pass-through ``-c``/``--ctx-size`` matches the context the caller is already sending
+ as a first-class field.
+
+ Context is the one first-class field whose load-time value is a VRAM-fit TARGET, so a matching
+ flag is not a stale shadow but the user's standing decision to run past the estimated threshold.
+ Both strippers ask here rather than mirroring the test, so auto-switch and /load inheritance
+ cannot drift.
+
+ False for anything unconfirmable, which is the pre-existing strip: no flag, a malformed one, or
+ a non-positive/non-int ``n_ctx``. That last case is real -- override rows are coerced on write
+ but returned verbatim on read, so a row from an older build can hold any JSON type and must not
+ raise here.
"""
if isinstance(n_ctx, bool) or not isinstance(n_ctx, int) or n_ctx <= 0:
return False
@@ -735,12 +698,9 @@ def matches_explicit_ctx_override(args: Optional[Iterable[str]], n_ctx: Any) ->
def _last_flag_value(args: Optional[Iterable[str]], flags: frozenset[str]) -> Optional[str]:
- """Return the last-wins string value among ``flags`` in extras, or None.
-
- Handles both ``--flag=value`` and ``--flag value`` forms and raises if a
- matched flag has no (or an empty) value. Shared by the single-knob
- last-wins parsers (cache type, split mode).
- """
+ """Return the last-wins string value among ``flags`` in extras, or None. Handles both
+ ``--flag=value`` and ``--flag value`` forms and raises if a matched flag has no (or an empty)
+ value. Shared by the single-knob last-wins parsers (cache type, split mode)."""
if not args:
return None
@@ -772,24 +732,18 @@ def _last_flag_value(args: Optional[Iterable[str]], flags: frozenset[str]) -> Op
def parse_cache_override(args: Optional[Iterable[str]]) -> Optional[str]:
- """Return the last-wins cache type if extras pass cache flags.
-
- Mirrors parse_ctx_override but for cache type. Recognises both -ctk
- (key) and -ctv (value). When both flags appear, returns the last-wins
- value, treating key and value cache flags as the same setting because
- Unsloth's KV estimate has a single cache_type_kv knob.
- """
+ """Return the last-wins cache type if extras pass cache flags. Mirrors parse_ctx_override but
+ for cache type. Recognises both -ctk (key) and -ctv (value); when both appear, returns the
+ last-wins value, treating key and value cache flags as the same setting because Unsloth's KV
+ estimate has a single cache_type_kv knob."""
return _last_flag_value(args, _CACHE_FLAGS)
def parse_gpu_layers_override(args: Optional[Iterable[str]]) -> Optional[int]:
- """Return the last user-supplied GPU layer count from extras.
-
- Manual GPU memory mode strips llama.cpp offload flags because the
- first-class load fields own them. Callers use this parser first to preserve
- an explicit ``-ngl`` / ``--gpu-layers`` / ``--n-gpu-layers`` value when
- translating the extras into those fields.
- """
+ """Return the last user-supplied GPU layer count from extras. Manual GPU memory mode strips
+ llama.cpp offload flags because the first-class load fields own them, so callers use this
+ parser first to preserve an explicit ``-ngl`` / ``--gpu-layers`` / ``--n-gpu-layers`` value
+ when translating the extras into those fields."""
raw_value = _last_flag_value(args, _GPU_LAYER_FLAGS)
if raw_value is None:
return None
@@ -803,17 +757,13 @@ def parse_gpu_layers_override(args: Optional[Iterable[str]]) -> Optional[int]:
def check_batch_floor(args: Optional[Iterable[str]], n_parallel: int) -> None:
- """Raise when a pass-through --batch-size would abort llama-server.
-
- The launcher raises the value it emits itself to ``max(slots, 2)``, with the
- measurements recorded beside that code: ``-b 1`` aborts at any slot count, and a
- batch below ``--parallel`` aborts too. Extras are appended AFTER that flag and win
- the last-wins parse, so a small value here is not a smaller batch, it is a server
- that dies during startup, and by then the previous model has been unloaded.
-
- Only the shapes that are certainly wrong: an unreadable value is left to
- llama-server, which names it better than a guess here would.
- """
+ """Raise when a pass-through --batch-size would abort llama-server. The launcher raises the
+ value it emits itself to ``max(slots, 2)``, with the measurements recorded beside that code:
+ ``-b 1`` aborts at any slot count, and a batch below ``--parallel`` aborts too. Extras are
+ appended AFTER that flag and win the last-wins parse, so a small value here is not a smaller
+ batch, it is a server that dies during startup, and by then the previous model has been
+ unloaded. Only the shapes that are certainly wrong: an unreadable value is left to
+ llama-server, which names it better than a guess here would."""
raw_value = _last_flag_value(args, _BATCH_FLAGS)
if raw_value is None:
return
@@ -830,13 +780,10 @@ def check_batch_floor(args: Optional[Iterable[str]], n_parallel: int) -> None:
def fit_is_enabled_in(args: Optional[Iterable[str]]) -> bool:
- """Whether the last ``--fit`` in extras turns the fitter ON.
-
- Only ``--fit on`` hands placement back to llama.cpp; ``--fit off`` disables
- it and so cannot move weights to the CPU. Upstream requires a value and
- rejects anything that is neither truthy nor falsey, so an absent or
- unreadable value is not an enable.
- """
+ """Whether the last ``--fit`` in extras turns the fitter ON. Only ``--fit on`` hands placement
+ back to llama.cpp; ``--fit off`` disables it and so cannot move weights to the CPU. Upstream
+ requires a value and rejects anything that is neither truthy nor falsey, so an absent or
+ unreadable value is not an enable."""
raw_value = _last_flag_value(args, _FIT_FLAGS)
return raw_value is not None and raw_value.strip().lower() in _ENV_TRUE_VALUES
@@ -844,12 +791,10 @@ def fit_is_enabled_in(args: Optional[Iterable[str]]) -> bool:
def fit_is_effectively_on(
args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
) -> bool:
- """Whether the fitter actually runs, over the WHOLE argv and the env twin.
-
- ``fit_is_enabled_in`` answers for the extras alone; this answers for the
- child. llama.cpp defaults the fitter ON and applies the env before argv, so
- only an explicit "off" turns it off, and an unreadable value keeps it on.
- """
+ """Whether the fitter actually runs, over the WHOLE argv and the env twin. ``fit_is_enabled_in``
+ answers for the extras alone; this answers for the child. llama.cpp defaults the fitter ON
+ and applies the env before argv, so only an explicit "off" turns it off, and an unreadable
+ value keeps it on."""
raw_value = _last_flag_value(args, _FIT_FLAGS)
if raw_value is None and env:
raw_value = env.get("LLAMA_ARG_FIT")
@@ -863,18 +808,17 @@ def fit_target_margin_in(
) -> Optional[float]:
"""The per-device margin an effective ``--fit-target`` asks the fitter to keep.
- ``-fitt/--fit-target`` takes a list of MiB values, one per device, and a
- single value is broadcast across all of them (common/arg.cpp; default 1024,
- ``fit_params_target`` in common/common.h). The fitter refuses
- to allocate into that margin and spills the rest to host RAM instead
- (``targets.push_back(dmds_full[id].free - margins[id])``, common/fit.cpp), so
- a load-mode fit that credits VRAM has to price it.
-
- Returns the LARGEST value in the list, because the fit charges one margin to
- every device it credits and understating would claim a fit that is not there.
- ``None`` when nothing readable is set, which leaves the caller on llama.cpp's
- own default rather than on a guess. Last-wins over argv, and the env twin only
- when argv sets nothing, the same precedence ``fit_is_effectively_on`` uses.
+ ``-fitt/--fit-target`` takes a list of MiB values, one per device, and a single value is
+ broadcast across all of them (common/arg.cpp; default 1024, ``fit_params_target`` in
+ common/common.h). The fitter refuses to allocate into that margin and spills the rest to host
+ RAM instead (``targets.push_back(dmds_full[id].free - margins[id])``, common/fit.cpp), so a
+ load-mode fit that credits VRAM has to price it.
+
+ Returns the LARGEST value in the list, because the fit charges one margin to every device it
+ credits and understating would claim a fit that is not there. ``None`` when nothing readable is
+ set, which leaves the caller on llama.cpp's own default rather than on a guess. Last-wins over
+ argv, and the env twin only when argv sets nothing, the same precedence
+ ``fit_is_effectively_on`` uses.
"""
raw_value = _last_flag_value(args, _FIT_TARGET_FLAGS)
if raw_value is None and env:
@@ -903,19 +847,16 @@ def split_policy_starves_devices(
"""True when the effective split leaves fewer devices holding weights than ``n_credited``.
``--split-mode`` and ``--tensor-split`` are pass-through under auto-select
- (``_SPLIT_SHADOWING_FLAGS`` is stripped only when the Tensor Parallelism toggle
- owns the split), so both reach the child appended after Unsloth's own placement
- flags. Either can quietly shrink the pool a pooled VRAM credit was priced for:
-
- * ``--split-mode none`` is ``LLAMA_SPLIT_MODE_NONE`` (common/arg.cpp), which
- puts the whole model on ``--main-gpu`` alone. ``row``/``layer``/``tensor``
- all keep every device, so only ``none`` starves.
- * ``--tensor-split`` is a per-device proportion list, and upstream zero-fills
- every device past the end of the list (common/arg.cpp), so a short list
- starves the tail just as an explicit ``0`` starves its own device.
-
- Value-aware on purpose: a restatement that keeps all devices is not an
- override, and voiding on it would abstain from a fit that is really there.
+ (``_SPLIT_SHADOWING_FLAGS`` is stripped only when the Tensor Parallelism toggle owns the split),
+ so both reach the child appended after Unsloth's own placement flags, and either can quietly
+ shrink the pool a pooled VRAM credit was priced for. ``--split-mode none`` is
+ ``LLAMA_SPLIT_MODE_NONE`` (common/arg.cpp), which puts the whole model on ``--main-gpu`` alone,
+ while ``row``/``layer``/``tensor`` all keep every device. ``--tensor-split`` is a per-device
+ proportion list, and upstream zero-fills every device past the end of the list, so a short list
+ starves the tail just as an explicit ``0`` starves its own device.
+
+ Value-aware on purpose: a restatement that keeps all devices is not an override, and voiding on
+ it would abstain from a fit that is really there.
"""
if n_credited <= 1:
return False
@@ -945,11 +886,9 @@ def split_policy_starves_devices(
def parse_cache_override_per_axis(
args: Optional[Iterable[str]],
) -> tuple[Optional[str], Optional[str]]:
- """Last-wins --cache-type-k / --cache-type-v values kept apart, as (k, v).
-
- parse_cache_override collapses both axes to one last-wins value; this keeps
- them separate so an asymmetric K/V can be budgeted by its heavier axis.
- """
+ """Last-wins --cache-type-k / --cache-type-v values kept apart, as (k, v). parse_cache_override
+ collapses both axes to one last-wins value; this keeps them separate so an asymmetric K/V can
+ be budgeted by its heavier axis."""
return (
_last_flag_value(args, _CACHE_TYPE_K_FLAGS),
_last_flag_value(args, _CACHE_TYPE_V_FLAGS),
@@ -959,32 +898,24 @@ def parse_cache_override_per_axis(
def resolve_cache_type_kv(
args: Optional[Iterable[str]], fallback_cache_type_kv: Optional[str]
) -> Optional[str]:
- """Return the cache type load_model should treat as requested.
-
- Single source of truth for ``load_model``'s cache override conditional.
- """
+ """Return the cache type load_model should treat as requested. Single source of truth for
+ ``load_model``'s cache override conditional."""
override = parse_cache_override(args)
return override if override is not None else fallback_cache_type_kv
def parse_split_mode_override(args: Optional[Iterable[str]]) -> Optional[str]:
- """Return the last-wins ``--split-mode`` / ``-sm`` value from extras.
-
- Mirrors parse_cache_override for the multi-GPU split mode. Returns the
- raw mode string (e.g. ``tensor`` / ``row`` / ``none`` / ``layer``), or
- None when extras don't set it.
- """
+ """Return the last-wins ``--split-mode`` / ``-sm`` value from extras. Mirrors
+ parse_cache_override for the multi-GPU split mode; returns the raw mode string (``tensor`` /
+ ``row`` / ``none`` / ``layer``), or None when extras don't set it."""
return _last_flag_value(args, _SPLIT_MODE_FLAGS)
def resolve_tensor_parallel(args: Optional[Iterable[str]], fallback_tensor_parallel: bool) -> bool:
- """Return the tensor-parallel state load_model should treat as requested.
-
- A user-supplied ``--split-mode`` in extras last-wins-overrides the
- toggle, so reconcile it back into the boolean: any explicit split mode
- means tensor-parallel is on iff that mode is ``tensor``. Falls back to
- the toggle value when extras don't set it.
- """
+ """Return the tensor-parallel state load_model should treat as requested. A user-supplied
+ ``--split-mode`` in extras last-wins-overrides the toggle, so reconcile it back into the
+ boolean: any explicit split mode means tensor-parallel is on iff that mode is ``tensor``.
+ Falls back to the toggle value when extras don't set it."""
override = parse_split_mode_override(args)
if override is None:
return fallback_tensor_parallel
@@ -992,10 +923,10 @@ def resolve_tensor_parallel(args: Optional[Iterable[str]], fallback_tensor_paral
def _env_split_mode_is_tensor(env: Optional[Mapping[str, str]] = None) -> bool:
- """True when the inherited LLAMA_ARG_SPLIT_MODE env selects tensor. Unsloth
- emits --split-mode only on its tensor branch, so a tensor env on the layer
- path would run the child tensor-parallel unbudgeted; this flips the budget
- to tensor. Only tensor is heavier, so other modes are ignored."""
+ """True when the inherited LLAMA_ARG_SPLIT_MODE env selects tensor. Unsloth emits --split-mode
+ only on its tensor branch, so a tensor env on the layer path would run the child
+ tensor-parallel unbudgeted; this flips the budget to tensor. Only tensor is heavier, so other
+ modes are ignored."""
raw = (os.environ if env is None else env).get("LLAMA_ARG_SPLIT_MODE")
return bool(raw) and raw.strip().lower() == "tensor"
@@ -1006,11 +937,9 @@ def _effective_tensor_parallel(
env: Optional[Mapping[str, str]] = None,
) -> bool:
"""Tensor-parallel decision including the inherited LLAMA_ARG_SPLIT_MODE env.
-
- resolve_tensor_parallel (extras + toggle), flipped on when extras set no split
- mode but the child inherits a tensor split env. Shared by load_model (which
- budgets and launches it) and the tensor-fallback wrapper (so an env-only
- tensor crash still retries layer split)."""
+ resolve_tensor_parallel (extras + toggle), flipped on when extras set no split mode but the
+ child inherits a tensor split env. Shared by load_model (which budgets and launches it) and
+ the tensor-fallback wrapper (so an env-only tensor crash still retries layer split)."""
resolved = resolve_tensor_parallel(extra_args, tensor_parallel)
if (
not resolved
@@ -1027,13 +956,11 @@ def _tensor_parallel_matches_loaded(
loaded_tensor_parallel: bool,
env: Optional[Mapping[str, str]] = None,
) -> bool:
- """Whether a duplicate load request matches a loaded server's tensor state.
-
- Env-only tensor mode is a launch hint load_model may downgrade to layer split
- (capacity/buffer), scrubbing the child env. So only let an inherited tensor env
- raise a match against a server that *actually* launched tensor; on a downgraded
- (layer) server the env is ignored, and an identical request would downgrade the
- same way -- avoiding an endless reload of a healthy server."""
+ """Whether a duplicate load request matches a loaded server's tensor state. Env-only tensor mode
+ is a launch hint load_model may downgrade to layer split (capacity/buffer), scrubbing the
+ child env. So only let an inherited tensor env raise a match against a server that *actually*
+ launched tensor; on a downgraded (layer) server the env is ignored, and an identical request
+ would downgrade the same way, avoiding an endless reload of a healthy server."""
requested = resolve_tensor_parallel(extra_args, requested_tensor_parallel)
if (
loaded_tensor_parallel
@@ -1050,11 +977,9 @@ _MMPROJ_ENABLE_FLAGS: frozenset[str] = frozenset({"--mmproj-auto"})
def extra_args_disable_mmproj(args: Optional[Iterable[str]]) -> bool:
- """True when pass-through args opt out of vision mmproj loading.
-
- llama-server parses --mmproj-auto / --no-mmproj / --no-mmproj-auto as one
- boolean with last-wins semantics; mirror that here.
- """
+ """True when pass-through args opt out of vision mmproj loading. llama-server parses
+ --mmproj-auto / --no-mmproj / --no-mmproj-auto as one boolean with last-wins semantics;
+ mirror that here."""
if not args:
return False
disabled = False
@@ -1090,23 +1015,21 @@ def strip_shadowing_flags(
) -> list[str]:
"""Strip flags that shadow first-class Unsloth settings.
- Used when inheriting a previous load's ``llama_extra_args`` so an
- inherited `-c 4096` can't override the current `max_seq_length`
- (same for cache / spec / template / split-mode). Each ``strip_*``
- toggle controls one group; the route only strips groups whose
- first-class field the caller actually supplied.
-
- ``strip_split_mode`` removes both ``--split-mode`` and the coupled
- ``--tensor-split`` (the Tensor Parallelism toggle owns the whole split).
- ``strip_tensor_split`` removes ``--tensor-split`` *alone*, so manual mode can
- replace an inherited per-GPU ratio while leaving the user's ``--split-mode``
- row/none/layer choice intact. ``strip_device`` is enabled when ``gpu_ids``
- owns placement.
-
- ``strip_mlock`` / ``strip_no_mmap`` are enabled by the Model Memory settings
- so a RAM-reservation flag cannot survive a load the user asked to keep
- RAM-free. ``strip_no_mmap`` covers every spelling of mode `none`, so the
- negative DirectIO forms go with it. All boolean: only the token is dropped.
+ Used when inheriting a previous load's ``llama_extra_args`` so an inherited `-c 4096` can't
+ override the current `max_seq_length` (same for cache / spec / template / split-mode). Each
+ ``strip_*`` toggle controls one group; the route only strips groups whose first-class field the
+ caller actually supplied.
+
+ ``strip_split_mode`` removes both ``--split-mode`` and the coupled ``--tensor-split`` (the
+ Tensor Parallelism toggle owns the whole split). ``strip_tensor_split`` removes
+ ``--tensor-split`` *alone*, so manual mode can replace an inherited per-GPU ratio while leaving
+ the user's ``--split-mode`` row/none/layer choice intact. ``strip_device`` is enabled when
+ ``gpu_ids`` owns placement.
+
+ ``strip_mlock`` / ``strip_no_mmap`` are enabled by the Model Memory settings so a
+ RAM-reservation flag cannot survive a load the user asked to keep RAM-free. ``strip_no_mmap``
+ covers every spelling of mode `none`, so the negative DirectIO forms go with it. All boolean:
+ only the token is dropped.
"""
shadowing: set[str] = set()
if strip_context:
@@ -1165,10 +1088,10 @@ def strip_shadowing_flags(
def strip_split_mode_only(args: Optional[Iterable[str]]) -> Optional[list[str]]:
- """Remove the split-mode group (``--split-mode`` / ``-sm`` and the coupled
- ``--tensor-split`` / ``-ts``) from ``args``, keeping every other shadow flag.
- Preserves a None/empty input so the inherit-vs-explicit-empty distinction
- survives. Used where tensor mode is being forced off (downgrade / fallback)."""
+ """Remove the split-mode group (``--split-mode`` / ``-sm`` and the coupled ``--tensor-split`` /
+ ``-ts``) from ``args``, keeping every other shadow flag. Preserves a None/empty input so the
+ inherit-vs-explicit-empty distinction survives. Used where tensor mode is being forced off
+ (downgrade / fallback)."""
if not args:
return args
return strip_shadowing_flags(
@@ -1182,10 +1105,9 @@ def strip_split_mode_only(args: Optional[Iterable[str]]) -> Optional[list[str]]:
def strip_context_only(args: Optional[Iterable[str]]) -> Optional[list[str]]:
- """Remove the context group (``-c`` / ``--ctx-size``) from ``args``, keeping
- every other shadow flag. Preserves a None/empty input so the
- inherit-vs-explicit-empty distinction survives. Used by the Metal
- zero-context floor, where a trailing ``-c 0`` would last-wins override the
+ """Remove the context group (``-c`` / ``--ctx-size``) from ``args``, keeping every other shadow
+ flag. Preserves a None/empty input so the inherit-vs-explicit-empty distinction survives.
+ Used by the Metal zero-context floor, where a trailing ``-c 0`` would last-wins override the
floor and pin the native length again."""
if not args:
return args
@@ -1205,26 +1127,20 @@ def apply_model_memory_policy(
supports_load_mode: bool = False,
weights_in_host_memory: bool = True,
) -> tuple[list[str], list[str]]:
- """Resolve the Model Memory settings into llama-server flags.
-
- Returns ``(managed_flags, extras)``: what Unsloth emits itself, and the
- user's extras with any vetoed flag removed.
-
- "Keep model in GPU memory" page-locks the weights (``--load-mode mmap+mlock``,
- or the deprecated ``--mlock``) but ONLY when ``weights_in_host_memory``.
- mlock pins a whole mapping in host RAM, so for a model fully offloaded to a
- discrete GPU it would hold a second full copy of the weights in system RAM
- without doing anything for VRAM residency; there, residency is carried by
- the idle-unload veto alone. Every other load-mode-bearing flag is stripped
- from the emitted extras, because a trailing one resets the whole mode and
- would drop the mlock.
-
- "Don't reserve system RAM" drops ``--mlock`` / ``--no-mmap``, leaving the
- default mmap path. With both off nothing is stripped, so a hand-typed flag
- still applies.
-
- The per-model Mmap/Mlock control is resolved separately, by
- ``apply_load_mode_policy``, which runs after this and defers to it.
+ """Resolve the Model Memory settings into llama-server flags, returning ``(managed_flags,
+ extras)``: what Unsloth emits itself, and the user's extras with any vetoed flag removed.
+
+ "Keep model in GPU memory" page-locks the weights (``--load-mode mmap+mlock``, or the deprecated
+ ``--mlock``) but ONLY when ``weights_in_host_memory``. mlock pins a whole mapping in host RAM,
+ so for a model fully offloaded to a discrete GPU it would hold a second full copy of the weights
+ in system RAM without doing anything for VRAM residency; there, residency is carried by the
+ idle-unload veto alone. Every other load-mode-bearing flag is stripped from the emitted extras,
+ because a trailing one resets the whole mode and would drop the mlock.
+
+ "Don't reserve system RAM" drops ``--mlock`` / ``--no-mmap``, leaving the default mmap path.
+ With both off nothing is stripped, so a hand-typed flag still applies. The per-model Mmap/Mlock
+ control is resolved separately, by ``apply_load_mode_policy``, which runs after this and defers
+ to it.
"""
try:
from utils.model_memory_settings import get_model_memory_settings
@@ -1232,8 +1148,8 @@ def apply_model_memory_policy(
# Settings unavailable (bare unit-test import): behave as before.
return [], list(extra_args or [])
- # One snapshot for both decisions: read separately, a save landing between them strips for one setting and locks for
- # the other, so a saved --mlock could survive a committed no-reserve.
+ # One snapshot for both decisions: read separately, a save landing between them strips for one setting and locks
+ # for the other, so a saved --mlock could survive a committed no-reserve.
keep_resident, no_ram_reserve = get_model_memory_settings()
tokens = list(extra_args or [])
if no_ram_reserve:
@@ -1275,20 +1191,19 @@ def apply_load_mode_policy(
weights_in_host_memory: bool = True,
requested_load_mode: Optional[str] = None,
) -> tuple[list[str], list[str]]:
- """Resolve the per-model Mmap/Mlock control into llama-server flags.
-
- Returns ``(managed_flags, extras)``, like ``apply_model_memory_policy``, and
- is meant to run straight after it on the extras that call returned.
-
- The Model Memory settings win, which is what the Run settings panel tells the
- user, so changing the order without changing ``loadModeOverrideNotice`` makes
- that note wrong. "Keep model in GPU memory" owns the mode outright while it
- applies; "Don't reserve system RAM" vetoes the values holding a full host copy
- (``none``, ``mlock``, ``mmap+mlock``) and leaves ``mmap`` and ``dio`` alone.
-
- ``auto`` emits nothing: it IS llama.cpp's default, so pinning it would freeze
- what a later build may redefine. An unknown value is dropped rather than passed
- through, since llama-server exits on one.
+ """Resolve the per-model Mmap/Mlock control into llama-server flags, returning ``(managed_flags,
+ extras)`` like ``apply_model_memory_policy``, and meant to run straight after it on the extras
+ that call returned.
+
+ The Model Memory settings win, which is what the Run settings panel tells the user, so changing
+ the order without changing ``loadModeOverrideNotice`` makes that note wrong. "Keep model in GPU
+ memory" owns the mode outright while it applies; "Don't reserve system RAM" vetoes the values
+ holding a full host copy (``none``, ``mlock``, ``mmap+mlock``) and leaves ``mmap`` and ``dio``
+ alone.
+
+ ``auto`` emits nothing: it IS llama.cpp's default, so pinning it would freeze what a later build
+ may redefine. An unknown value is dropped rather than passed through, since llama-server exits
+ on one.
"""
tokens = list(extra_args or [])
mode = _normalize_load_mode_value(requested_load_mode)
@@ -1338,12 +1253,10 @@ def _normalize_load_mode_value(value: Optional[str]) -> str:
def _strip_reserving_load_modes(tokens: list[str]) -> list[str]:
- """Drop only ``--load-mode`` values that lock or reserve host RAM.
-
- No-reserve vetoes the reservation, not the loader. ``mmap`` and ``dio``
- hold no full host copy, so a DirectIO preset survives instead of silently
- falling back to mmap. Unknown values are left alone rather than rewritten.
- """
+ """Drop only ``--load-mode`` values that lock or reserve host RAM. No-reserve vetoes the
+ reservation, not the loader: ``mmap`` and ``dio`` hold no full host copy, so a DirectIO
+ preset survives instead of silently falling back to mmap. Unknown values are left alone
+ rather than rewritten."""
out: list[str] = []
i, n = 0, len(tokens)
while i < n:
@@ -1377,12 +1290,10 @@ def model_memory_owns_placement() -> bool:
def _env_var_locks_or_reserves(name: str, value: str) -> bool:
- """Whether this inherited var, as set, locks or reserves host RAM.
-
- Mirrors the argv rule: the settings own the RESERVATION, not the loader, so
- a DirectIO or mmap choice made through the environment survives the same way
- ``--load-mode dio`` does. An unrecognised value is left alone.
- """
+ """Whether this inherited var, as set, locks or reserves host RAM. Mirrors the argv rule: the
+ settings own the RESERVATION, not the loader, so a DirectIO or mmap choice made through the
+ environment survives the same way ``--load-mode dio`` does. An unrecognised value is left
+ alone."""
normalized = value.strip().lower()
if name == "LLAMA_ARG_MLOCK":
return normalized in _ENV_TRUE_VALUES
@@ -1398,8 +1309,8 @@ def _env_var_locks_or_reserves(name: str, value: str) -> bool:
# The LLAMA_ARG_* twins of flags the denylist refuses. llama.cpp reads these before argv, so a name refused in extra
# args is still reachable through the environment Unsloth's own process inherits. Anyone who can set that environment
-# can already do worse, so this is not the boundary -- it just stops a denied flag arriving by the back door and leaving
-# no trace in the recorded command.
+# can already do worse, so this is not the boundary -- it just stops a denied flag arriving by the back door and
+# leaving no trace in the recorded command.
DENIED_ENV_VARS: tuple[str, ...] = (
"LLAMA_ARG_TOOLS",
"LLAMA_ARG_TOOLS_RUNTIME",
@@ -1411,38 +1322,34 @@ DENIED_ENV_VARS: tuple[str, ...] = (
"LLAMA_ARG_CORS_METHODS",
"LLAMA_ARG_CORS_CREDENTIALS",
"LLAMA_ARG_MEDIA_PATH",
- # Twins of --log-file and --log-disable: Unsloth classifies a failed start by reading llama-server's output
- # The twins of --log-file and --log-disable. Unsloth classifies a failed start by reading llama-server's own output,
- # so an inherited redirect leaves every failure looking like the same opaque one; and unlike the flags, Unsloth
- # emits nothing later that would override these. LLAMA_ARG_LOG_DISABLE has no twin in today's builds, and is listed
- # so it cannot arrive as one.
+ # The twins of --log-file and --log-disable. Unsloth classifies a failed start by reading llama-server's own
+ # output, so an inherited redirect leaves every failure looking like the same opaque one; and unlike the flags,
+ # Unsloth emits nothing later that would override these. LLAMA_ARG_LOG_DISABLE has no twin in today's builds, and
+ # is listed so it cannot arrive as one.
"LLAMA_ARG_LOG_FILE",
"LLAMA_ARG_LOG_DISABLE",
# --api-prefix moves every endpoint, including the /health Unsloth waits on, so an inherited one turns every load
# into a timeout.
"LLAMA_ARG_API_PREFIX",
# --api-key and its file. Unsloth terminates auth itself and sends the child no Authorization header, so an
- # inherited key makes the healthy child refuse every request. The bundled build reads LLAMA_API_KEY for the flag and
- # LLAMA_ARG_API_KEY_FILE for the file; the third spelling is listed because the name has moved between releases and
- # none of them is ours to honour.
+ # inherited key makes the healthy child refuse every request. The bundled build reads LLAMA_API_KEY for the flag
+ # and LLAMA_ARG_API_KEY_FILE for the file; the third spelling is listed because the name has moved between
+ # releases and none of them is ours to honour.
"LLAMA_API_KEY",
"LLAMA_ARG_API_KEY",
"LLAMA_ARG_API_KEY_FILE",
- # Twins of --ssl-key-file / --ssl-cert-file (b10360)
# The twins of --ssl-key-file and --ssl-cert-file. Given both, llama-server listens on https, while Unsloth probes
# /health and proxies over http against the port it launched: the child comes up healthy and every load times out.
# Measured on b10360, where an inherited pair turns "listening on http://127.0.0.1:PORT" into "listening on
# https://...".
"LLAMA_ARG_SSL_KEY_FILE",
"LLAMA_ARG_SSL_CERT_FILE",
- # The rest of the twins --help documents for a denied flag, enumerated from the bundled b10342 help rather than
- # picked one at a time.
- # The rest of the twins its --help documents for a denied flag, enumerated from the bundled b10342 help rather than
- # picked one at a time: every "(env: NAME)" whose option this module refuses. Unsloth emits most of these itself and
- # argv wins over the environment, so removing them changes nothing in the ordinary case; they are here for the paths
- # where it does not, and so a flag denied in the box is not reachable through the environment instead. The mapping
- # below records which flag each one belongs to, since the name does not always say (LLAMA_ARG_STATIC_PATH is
- # --path).
+ # The rest of the twins its --help documents for a denied flag, enumerated from the bundled b10342 help rather
+ # than picked one at a time: every "(env: NAME)" whose option this module refuses. Unsloth emits most of these
+ # itself and argv wins over the environment, so removing them changes nothing in the ordinary case; they are here
+ # for the paths where it does not, and so a flag denied in the box is not reachable through the environment
+ # instead. The mapping below records which flag each one belongs to, since the name does not always say
+ # (LLAMA_ARG_STATIC_PATH is --path).
"LLAMA_ARG_MODEL",
"LLAMA_ARG_MODEL_URL",
"LLAMA_ARG_DOCKER_REPO",
@@ -1456,8 +1363,8 @@ DENIED_ENV_VARS: tuple[str, ...] = (
"LLAMA_ARG_POOLING",
"LLAMA_ARG_EMBEDDINGS",
"LLAMA_ARG_RERANKING",
- # The web UI and its MCP proxy, which upstream marks as not for untrusted environments, and the directory the child
- # serves files from.
+ # The web UI and its MCP proxy, which upstream marks as not for untrusted environments, and the directory the
+ # child serves files from.
"LLAMA_ARG_UI",
"LLAMA_ARG_UI_CONFIG",
"LLAMA_ARG_UI_CONFIG_FILE",
@@ -1466,11 +1373,10 @@ DENIED_ENV_VARS: tuple[str, ...] = (
# Deliberately absent: LLAMA_ARG_MMPROJ and LLAMA_ARG_MMPROJ_URL. --mmproj is refused in the box because Unsloth
# resolves the projector itself, but the environment twin is an INPUT here: _launch_has_mmproj reads both to know
# the launch has a projector at all, which is what keeps the vision and audio state of a model loaded through an
- # inherited one. Only the paravirtual CPU recovery drops them, where an unpinned projector is the corrupt path it is
- # undoing. The pooling twins are absent for the opposite reason: load_model already pops LLAMA_ARG_POOLING /
- # _RERANKING / _EMBEDDINGS itself, next to where it decides what the GGUF header says. The multi-model server mode:
- # a child holding its own model directory, preset and autoload policy is not the single model Unsloth launched and
- # accounts for.
+ # inherited one. Only the paravirtual CPU recovery drops them, where an unpinned projector is the corrupt path it
+ # is undoing. The pooling twins are absent for the opposite reason: load_model already pops LLAMA_ARG_POOLING /
+ # _RERANKING / _EMBEDDINGS itself. The multi-model server mode is absent too: a child holding its own model
+ # directory, preset and autoload policy is not the single model Unsloth launched and accounts for.
"LLAMA_ARG_MODELS_DIR",
"LLAMA_ARG_MODELS_PRESET",
"LLAMA_ARG_MODELS_MAX",
@@ -1503,15 +1409,14 @@ def scrub_denied_env(env: dict) -> list[str]:
def extra_args_select_load_mode(extra_args: Optional[Iterable[str]]) -> bool:
"""Whether the pass-through block already picks a loader mode itself.
- The argv twin of ``memory_env_selects_load_mode``, and it answers for both
- spellings: the ``--load-mode`` enum, and the flags it replaced
- (``--no-mmap`` / ``--mmap`` / the direct-IO pair), which are what this launch
- emits on a build predating the enum (``_LEGACY_LOAD_MODE_FLAGS``) and so are
- what a user's own flag would collide with there.
+ The argv twin of ``memory_env_selects_load_mode``, and it answers for both spellings: the
+ ``--load-mode`` enum, and the flags it replaced (``--no-mmap`` / ``--mmap`` / the direct-IO
+ pair), which are what this launch emits on a build predating the enum
+ (``_LEGACY_LOAD_MODE_FLAGS``) and so are what a user's own flag would collide with there.
- Presence, not value: a fit-derived mode stands aside for any pick the user made
- rather than trying to rank the two. Their tokens are appended after the managed
- block and llama.cpp is last-wins, so theirs governs either way.
+ Presence, not value: a fit-derived mode stands aside for any pick the user made rather than
+ trying to rank the two. Their tokens are appended after the managed block and llama.cpp is
+ last-wins, so theirs governs either way.
"""
for raw in extra_args or ():
if _flag_name(str(raw)) in _LOAD_MODE_FLAGS | _LOAD_MODE_ALIAS_FLAGS:
@@ -1522,18 +1427,18 @@ def extra_args_select_load_mode(extra_args: Optional[Iterable[str]]) -> bool:
def memory_env_selects_load_mode(env: Optional[Mapping[str, str]]) -> bool:
"""Whether the inherited environment already picks a loader mode.
- llama.cpp applies the ``LLAMA_ARG_*`` twins BEFORE argv (common/arg.cpp runs
- its environment loop and only then "handle command line arguments"), and both
- assign the same ``params.load_mode``, so a managed ``--load-mode`` emitted here
- beats an inherited choice without the user typing anything. A mode DERIVED from
- a fit has to stand aside for that choice, the same way it stands aside for the
- per-model pick; a hand-typed flag is argv and still wins by last-arg.
-
- Per variable, matching what upstream really does with each value: a no-value
- option (``--mlock``) runs its handler only for a truthy one (``opt.handler_void
- && is_truthy(value)``), a negative alias (``LLAMA_ARG_NO_MMAP`` /
- ``LLAMA_ARG_NO_DIO``) counts by PRESENCE whatever it says (``get_value_from_env``
- forces "0" when it exists), and the rest assign a mode for any value they parse.
+ llama.cpp applies the ``LLAMA_ARG_*`` twins BEFORE argv (common/arg.cpp runs its environment
+ loop and only then "handle command line arguments"), and both assign the same
+ ``params.load_mode``, so a managed ``--load-mode`` emitted here beats an inherited choice
+ without the user typing anything. A mode DERIVED from a fit has to stand aside for that choice,
+ the same way it stands aside for the per-model pick; a hand-typed flag is argv and still wins by
+ last-arg.
+
+ Per variable, matching what upstream really does with each value: a no-value option
+ (``--mlock``) runs its handler only for a truthy one (``opt.handler_void && is_truthy(value)``),
+ a negative alias (``LLAMA_ARG_NO_MMAP`` / ``LLAMA_ARG_NO_DIO``) counts by PRESENCE whatever it
+ says (``get_value_from_env`` forces "0" when it exists), and the rest assign a mode for any
+ value they parse.
"""
if not env:
return False
@@ -1553,13 +1458,11 @@ def memory_env_selects_load_mode(env: Optional[Mapping[str, str]]) -> bool:
def scrub_memory_env(env: dict) -> list[str]:
- """Drop inherited memory placement the settings override.
-
- Returns the names removed, for logging. A no-op with both toggles off, so an
- existing LLAMA_ARG_MLOCK deployment keeps working untouched. Only the values
- that actually lock or reserve go: an inherited ``LLAMA_ARG_DIO=1`` is a
- loader choice, not a reservation, and no-reserve has no quarrel with it.
- """
+ """Drop inherited memory placement the settings override. Returns the names removed, for
+ logging. A no-op with both toggles off, so an existing LLAMA_ARG_MLOCK deployment keeps
+ working untouched. Only the values that actually lock or reserve go: an inherited
+ ``LLAMA_ARG_DIO=1`` is a loader choice, not a reservation, and no-reserve has no quarrel with
+ it."""
if not model_memory_owns_placement():
return []
removed = [
@@ -1573,8 +1476,8 @@ def scrub_memory_env(env: dict) -> list[str]:
# The pageable twin of each mode that reads the weights into a buffer it allocates. Upstream sets use_mmap for mmap /
-# mmap+mlock / auto only (llama-model-loader.cpp), so `mlock` is a full host copy that is also locked, and `mmap+mlock`
-# is the same lock over a mapping. `none` has no lock to preserve, so it goes back to the default.
+# mmap+mlock / auto only (llama-model-loader.cpp), so `mlock` is a full host copy that is also locked, and
+# `mmap+mlock` is the same lock over a mapping. `none` has no lock to preserve, so it goes back to the default.
_PAGEABLE_LOAD_MODE: dict[str, Optional[str]] = {"none": None, "mlock": "mmap+mlock"}
# Modes that already map, so the rewrite has no unmapped copy of its own to fix and leaves them alone. It reaches them
# only when a LATER reserving selector shadowed the lock (``--load-mode mmap+mlock --no-mmap`` runs unlocked and
@@ -1587,10 +1490,8 @@ _SHADOWED_LOCK_LOAD_MODE = frozenset({"mmap+mlock"})
def _pageable_mode_replacement(
normalized: str, drop_shadowed_mlock: bool
) -> tuple[bool, Optional[str]]:
- """``(rewrite, replacement)`` for one ``--load-mode`` value, argv or env alike.
-
- ``replacement`` None removes the selector, leaving llama.cpp's default mapping.
- """
+ """``(rewrite, replacement)`` for one ``--load-mode`` value, argv or env alike. ``replacement``
+ None removes the selector, leaving llama.cpp's default mapping."""
if normalized in _PAGEABLE_LOAD_MODE:
return True, None if drop_shadowed_mlock else _PAGEABLE_LOAD_MODE[normalized]
if normalized in _SHADOWED_LOCK_LOAD_MODE:
@@ -1605,16 +1506,14 @@ def _pageable_env_value(
) -> tuple[bool, Optional[str]]:
"""``(rewrite, new_value)`` for an inherited var that disables mmap.
- ``rewrite`` False leaves the var alone. ``new_value`` None means remove it; a
- string replaces it, which is how a locked mode keeps its lock. ``LLAMA_ARG_MLOCK``
- is otherwise left alone: on its own it sets the lock bit over the default mapping
- and holds no unmapped copy.
+ ``rewrite`` False leaves the var alone. ``new_value`` None means remove it; a string replaces
+ it, which is how a locked mode keeps its lock. ``LLAMA_ARG_MLOCK`` is otherwise left alone: on
+ its own it sets the lock bit over the default mapping and holds no unmapped copy.
- ``drop_shadowed_mlock`` says the launch is NOT locked before the rewrite, because
- a later selector reset the mlock bit -- llama.cpp resolves these last-wins, so
- ``LLAMA_ARG_MLOCK=1`` beside ``LLAMA_ARG_NO_MMAP`` leaves the child unlocked. There
- is then no lock to carry, so the var goes and a ``mlock`` mode is dropped rather
- than promoted to ``mmap+mlock``.
+ ``drop_shadowed_mlock`` says the launch is NOT locked before the rewrite, because a later
+ selector reset the mlock bit -- llama.cpp resolves these last-wins, so ``LLAMA_ARG_MLOCK=1``
+ beside ``LLAMA_ARG_NO_MMAP`` leaves the child unlocked. There is then no lock to carry, so the
+ var goes and a ``mlock`` mode is dropped rather than promoted to ``mmap+mlock``.
"""
normalized = value.strip().lower()
if name == "LLAMA_ARG_MLOCK":
@@ -1637,30 +1536,29 @@ def force_pageable_load(
) -> tuple[list[str], list[str]]:
"""Rewrite a launch that would hold a full unmapped host copy into a pageable one.
- Returns ``(argv, overridden)``, naming the argv tokens and env vars that were
- dropped or rewritten, for the log line and the warning. Empty means the launch was
- already pageable and ``argv`` comes back unchanged.
-
- Modes ``none`` and ``mlock`` read the weights into a buffer llama.cpp allocates
- (``use_mmap`` is set for ``mmap``/``mmap+mlock``/``auto`` and nothing else), so a
- model larger than free RAM cannot load at all rather than paging in slowly. Both
- sides of llama.cpp's env-then-argv resolution are rewritten, since the environment
- supplies the default the argv only overrides when it names the same option.
-
- A lock that is EFFECTIVE is preserved rather than dropped: ``mlock`` becomes
- ``mmap+mlock`` and ``--no-mmap --mlock`` keeps its lock through the strip, so "keep
- this in RAM" still holds -- over a mapping the kernel can fall back on. ``none`` has
- no lock to keep and needs no replacement flag at all, mmap being the default, so a
- build predating ``--load-mode`` is handed nothing it cannot parse.
-
- A SHADOWED lock is not resurrected. These options resolve last-wins, so
- ``--mlock --no-mmap`` (and the ``LLAMA_ARG_`` twins, where the negative alias is
- read after the affirmative one) runs unlocked and unmapped: the reserving selector
- already cleared the lock bit, which is what ``resolve_effective_memory_state``
- reports. Dropping only the selector and leaving the earlier ``--mlock`` standing
- would hand the child ``mmap+mlock`` and page-lock the whole oversized mapping into
- the RAM this override exists to keep pageable -- worse than the load it fixes. So
- the pre-rewrite state decides, not the tokens that happen to be present.
+ Returns ``(argv, overridden)``, naming the argv tokens and env vars that were dropped or
+ rewritten, for the log line and the warning. Empty means the launch was already pageable and
+ ``argv`` comes back unchanged.
+
+ Modes ``none`` and ``mlock`` read the weights into a buffer llama.cpp allocates (``use_mmap`` is
+ set for ``mmap``/``mmap+mlock``/``auto`` and nothing else), so a model larger than free RAM
+ cannot load at all rather than paging in slowly. Both sides of llama.cpp's env-then-argv
+ resolution are rewritten, since the environment supplies the default the argv only overrides
+ when it names the same option.
+
+ A lock that is EFFECTIVE is preserved rather than dropped: ``mlock`` becomes ``mmap+mlock`` and
+ ``--no-mmap --mlock`` keeps its lock through the strip, so "keep this in RAM" still holds, over
+ a mapping the kernel can fall back on. ``none`` has no lock to keep and needs no replacement
+ flag at all, mmap being the default, so a build predating ``--load-mode`` is handed nothing it
+ cannot parse.
+
+ A SHADOWED lock is not resurrected. These options resolve last-wins, so ``--mlock --no-mmap``
+ (and the ``LLAMA_ARG_`` twins, where the negative alias is read after the affirmative one) runs
+ unlocked and unmapped: the reserving selector already cleared the lock bit, which is what
+ ``resolve_effective_memory_state`` reports. Dropping only the selector and leaving the earlier
+ ``--mlock`` standing would hand the child ``mmap+mlock`` and page-lock the whole oversized
+ mapping into the RAM this override exists to keep pageable, worse than the load it fixes. So the
+ pre-rewrite state decides, not the tokens that happen to be present.
"""
tokens = [str(a) for a in (argv or [])]
# What the child runs TODAY, across env and argv in llama.cpp's own resolution order. Only a launch that reserves
@@ -1680,7 +1578,6 @@ def force_pageable_load(
overridden.append(token)
i += 1
continue
- # A lock a later selector already cleared.
# A lock a later selector already cleared. Valueless like the above, and named in `overridden` so the log line
# describes the whole rewrite.
if drop_shadowed_mlock and flag in _MLOCK_FLAGS:
@@ -1695,9 +1592,9 @@ def force_pageable_load(
else:
value, step = "", 1
normalized = value.strip().lower()
- # `--load-mode mlock --no-mmap` is unlocked by the time the child parses it, so mmap+mlock would ADD a lock;
- # `mmap+mlock --no-mmap` is the same shape one spelling further on, and there the selector itself is the
- # lock.
+ # `--load-mode mlock --no-mmap` is unlocked by the time the child parses it, so mmap+mlock would ADD a
+ # lock; `mmap+mlock --no-mmap` is the same shape one spelling further on, and there the selector itself is
+ # the lock.
rewrite_mode, replacement = _pageable_mode_replacement(normalized, drop_shadowed_mlock)
if rewrite_mode:
overridden.append(" ".join(tokens[i : i + step]))
@@ -1750,12 +1647,10 @@ _LOAD_MODE_RESERVING_VALUES = frozenset({"none", "mlock"})
def resolve_effective_memory_state(
argv: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
) -> tuple[bool, bool]:
- """``(mlock, reserves_ram)`` the child will actually run with.
-
- Mirrors llama.cpp: env supplies defaults, argv overrides last-wins. Used to
- compare a running process against the current settings, so the reload hint
- reflects the launched state rather than only what Unsloth emitted.
- """
+ """``(mlock, reserves_ram)`` the child will actually run with. Mirrors llama.cpp: env supplies
+ defaults, argv overrides last-wins. Used to compare a running process against the current
+ settings, so the reload hint reflects the launched state rather than only what Unsloth
+ emitted."""
env = env or {}
mlock = False
reserves_ram = False
@@ -1765,8 +1660,8 @@ def resolve_effective_memory_state(
# observable and changes no decision.
if str(env.get("LLAMA_ARG_MLOCK", "")).strip().lower() in _ENV_TRUE_VALUES:
mlock = True
- # Every option with a negative form also answers to LLAMA_ARG_NO_<NAME>: upstream rewrites the name and, if that var
- # EXISTS, forces the value falsey whatever it says, before reading the affirmative one. Measured:
+ # Every option with a negative form also answers to LLAMA_ARG_NO_<NAME>: upstream rewrites the name and, if that
+ # var EXISTS, forces the value falsey whatever it says, before reading the affirmative one. Measured:
# LLAMA_ARG_NO_MMAP=0 still disables mmap, and it beats LLAMA_ARG_MMAP=on. --mlock has no negative form, so
# LLAMA_ARG_NO_MLOCK does nothing. LLAMA_ARG_MMAP is whether to mmap, so "off" means mmap disabled ("none").
_mmap_env = "0" if "LLAMA_ARG_NO_MMAP" in env else str(env.get("LLAMA_ARG_MMAP", ""))
@@ -1796,7 +1691,8 @@ def resolve_effective_memory_state(
i += 1
continue
if flag in _MLOCK_FLAGS:
- # Only the mlock bit: which of "mlock" / "mmap+mlock" this maps to is not observable and changes no decision
+ # Only the mlock bit: which of "mlock" / "mmap+mlock" this maps to is not observable and changes no
+ # decision
mlock = True
i += 1
elif flag in _NO_MMAP_FLAGS:
@@ -1812,8 +1708,8 @@ def resolve_effective_memory_state(
reserves_ram = False
i += 1
elif flag in _DIO_OFF_FLAGS:
- # Not "plain mmap": upstream maps these to mode `none`, like --no-mmap, which reads the weights into a full
- # host buffer.
+ # Not "plain mmap": upstream maps these to mode `none`, like --no-mmap, which reads the weights into a
+ # full host buffer.
mlock = False
reserves_ram = True
i += 1
@@ -1845,25 +1741,21 @@ def memory_state_satisfies_settings(
) -> bool:
"""True when a launched ``(mlock, reserves_ram)`` matches the settings.
- Shared by the duplicate-load comparator (so toggling a setting forces a real
- relaunch instead of returning already-loaded) and the settings route (so the
- reload hint agrees with it).
-
- ``state`` is None for a process this policy does not govern, such as the
- diffusion runner, which has no load-mode of its own; nothing about it can
- contradict the settings, so it always matches.
-
- ``policy_active`` says the launch differed from an unmanaged one, because a
- flag was emitted, a requested one suppressed, or an inherited env var
- scrubbed. With both toggles off the policy no longer applies, so any of
- those has to be undone on the next launch, while a launch it never touched
- is left alone.
-
- ``mlock_applicable`` is False when the launch is fully offloaded to a
- discrete GPU, where page-locking host RAM buys nothing and is deliberately
- not emitted. Residency there is the idle-unload veto, which needs no
- relaunch, so demanding mlock would ask for a reload that can never satisfy
- the check.
+ Shared by the duplicate-load comparator (so toggling a setting forces a real relaunch instead of
+ returning already-loaded) and the settings route (so the reload hint agrees with it).
+
+ ``state`` is None for a process this policy does not govern, such as the diffusion runner, which
+ has no load-mode of its own; nothing about it can contradict the settings, so it always matches.
+
+ ``policy_active`` says the launch differed from an unmanaged one, because a flag was emitted, a
+ requested one suppressed, or an inherited env var scrubbed. With both toggles off the policy no
+ longer applies, so any of those has to be undone on the next launch, while a launch it never
+ touched is left alone.
+
+ ``mlock_applicable`` is False when the launch is fully offloaded to a discrete GPU, where
+ page-locking host RAM buys nothing and is deliberately not emitted. Residency there is the
+ idle-unload veto, which needs no relaunch, so demanding mlock would ask for a reload that can
+ never satisfy the check.
"""
if state is None:
return True
diff --git a/studio/backend/core/inference/llama_stats.py b/studio/backend/core/inference/llama_stats.py
index 95241275c9c..74a6be38085 100644
--- a/studio/backend/core/inference/llama_stats.py
+++ b/studio/backend/core/inference/llama_stats.py
@@ -208,11 +208,10 @@ class LlamaServerStatsLogger:
self._log.info("engine_stats", **fields)
-# bounded by threading.TIMEOUT_MAX as well
-# A week already means "never" for a poll interval or a stall timeout. Bounded by threading.TIMEOUT_MAX as well, because
-# the ceiling is platform specific and much lower than it looks: Linux accepts ~9.2e9 seconds, Windows about 49.7 days,
-# since the timeout becomes a DWORD of milliseconds there. Picking a constant by hand got this wrong once already, so
-# let the platform state its own limit.
+# A week already means "never" for a poll interval or a stall timeout. Bounded by threading.TIMEOUT_MAX as well,
+# because the ceiling is platform specific and much lower than it looks: Linux accepts ~9.2e9 seconds, Windows about
+# 49.7 days, since the timeout becomes a DWORD of milliseconds there. Picking a constant by hand got this wrong once
+# already, so let the platform state its own limit.
_MAX_ENV_SECONDS = min(7.0 * 24.0 * 60.0 * 60.0, threading.TIMEOUT_MAX)
@@ -239,10 +238,9 @@ def _env_float(name, default, logger):
)
return default
if value > _MAX_ENV_SECONDS:
- # Event.wait() builds an absolute deadline
# Event.wait() builds an absolute deadline, and one far enough out raises "timestamp out of range for platform
- # time_t" once the wait is entered, killing the poll thread. Measured: a century still waits, 1e10 seconds does
- # not.
+ # time_t" once the wait is entered, killing the poll thread. Measured: a century still waits, 1e10 seconds
+ # does not.
logger.warning(
"engine_stats_env_clamped",
variable = name,
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.py
index 76d32a9a2b9..b14660e0976 100644
--- a/studio/backend/core/inference/local_model_resolver.py
+++ b/studio/backend/core/inference/local_model_resolver.py
@@ -58,16 +58,16 @@ _WARM_DUTY = 10.0
def _is_abs_path_id(value: str) -> bool:
- """True when an id is an absolute filesystem path (the ./models and LM Studio
- scanners use the on-disk path as the id) rather than a repo id like org/name.
-
- Both spellings count on every host. Path() follows the running OS, so a
- Windows backend read "/home/me/x.gguf" as relative and a POSIX one read
- "C:\\models\\x.gguf" the same way, and either then reached /v1/models as a
- published id. Ids outlive the machine that wrote them: settings sync, a WSL
- session and a copied config all carry the other platform's spelling, and the
- model-override identity already folds both. Neither reading can misfire on a
- repo id, which has no leading separator, drive or UNC prefix."""
+ """True when an id is an absolute filesystem path (the ./models and LM Studio scanners use the
+ on-disk path as the id) rather than a repo id like org/name.
+
+ Both spellings count on every host. Path() follows the running OS, so a Windows backend read
+ "/home/me/x.gguf" as relative and a POSIX one read "C:\\models\\x.gguf" the same way, and either
+ then reached /v1/models as a published id. Ids outlive the machine that wrote them: settings
+ sync, a WSL session and a copied config all carry the other platform's spelling, and the
+ model-override identity already folds both. Neither reading can misfire on a repo id, which has
+ no leading separator, drive or UNC prefix.
+ """
from pathlib import PurePosixPath, PureWindowsPath
try:
return PurePosixPath(value).is_absolute() or PureWindowsPath(value).is_absolute()
@@ -203,17 +203,17 @@ def local_gguf_companion_state(roots: tuple[str, ...]) -> tuple:
def _legacy_variant_aliases(variants) -> tuple[tuple[str, str], ...]:
"""``(legacy label, current label)`` for each id this module used to publish and no longer does.
- /v1/models published the loader's label before the swap to the shared lister, and a client
- pins what it was shown. ``DeepSeek-R1-BF16-Q4_K_M.gguf`` was ``BF16``, is ``Q4_K_M``: quant
- shaped, so _resolve_from_index refuses it and the pin 404s. ``Meta-Llama-3-8B.gguf`` was
- ``8B``, is the whole stem: not quant shaped, so it falls through to the Ollama-tag branch and
- quietly serves the preferred quant instead. The quiet one is why quantless labels alias too.
-
- Accept-only, so nothing new can pin a legacy spelling and a bare id never reaches here.
- Dropped rather than guessed: a legacy label equal to a current one, and one naming two files.
- Grouped rows give one file per quant, so ``alpha-Q4_K_M.gguf`` beside
- ``zeta-BF16-Q4_K_M.gguf`` keeps the 404. Never raises: _local_gguf_entry answers None on an
- escape, which would drop the whole repo.
+ /v1/models published the loader's label before the swap to the shared lister, and a client pins
+ what it was shown. ``DeepSeek-R1-BF16-Q4_K_M.gguf`` was ``BF16``, is ``Q4_K_M``: quant shaped,
+ so _resolve_from_index refuses it and the pin 404s. ``Meta-Llama-3-8B.gguf`` was ``8B``, is the
+ whole stem: not quant shaped, so it falls through to the Ollama-tag branch and quietly serves
+ the preferred quant instead. The quiet one is why quantless labels alias too.
+
+ Accept-only, so nothing new can pin a legacy spelling and a bare id never reaches here. Dropped
+ rather than guessed: a legacy label equal to a current one, and one naming two files. Grouped
+ rows give one file per quant, so ``alpha-Q4_K_M.gguf`` beside ``zeta-BF16-Q4_K_M.gguf`` keeps
+ the 404. Never raises: _local_gguf_entry answers None on an escape, which would drop the whole
+ repo.
"""
try:
from utils.models.model_config import _extract_quant_label, _qualified_variant_name
@@ -258,12 +258,11 @@ def _local_gguf_entry(
p = Path(path)
try:
if p.is_file():
- # An mmproj companion is not a servable model on its own A standalone.gguf loads by its own path; no quant
- # sub-selection. An mmproj companion (vision/audio projector) is not a servable model on its own:
- # _scan_models_dir's standalone-file pass does not filter it the way the directory scan does, so reject it
- # here or /v1/models would advertise a projector and a switch could load it instead of the weights, evicting
- # the loaded model. The directory branch below is already mmproj free (list_local_gguf_variants drops mmproj
- # quants).
+ # A standalone .gguf loads by its own path, with no quant sub-selection. An mmproj companion (vision/audio
+ # projector) is not a servable model on its own: _scan_models_dir's standalone-file pass does not filter
+ # it the way the directory scan does, so reject it here or /v1/models would advertise a projector and a
+ # switch could load it instead of the weights, evicting the loaded model. The directory branch below is
+ # already mmproj free (list_local_gguf_variants drops mmproj quants).
if p.suffix.lower() != ".gguf" or detect_gguf_model(str(p)) is None:
return None
return _LocalGgufEntry(loader_id, str(p), ())
@@ -317,10 +316,9 @@ def _local_gguf_entry(
quants = tuple(v.quant for v in variants if getattr(v, "quant", None))
if not quants:
return None
- # that call orders by descending size, and downstream reads [0]
- # That call orders by descending size, so the head is the biggest quant (often F16). Downstream reads [0], and a
- # bare id must mean whichever quant a plain load would take: answering with the largest can evict a model and
- # then OOM.
+ # That call orders by descending size, so the head is the biggest quant (often F16). Downstream reads [0], and
+ # a bare id must mean whichever quant a plain load would take: answering with the largest can evict a model
+ # and then OOM.
from core.inference.openai_auto_download import preferred_quant
# Rank the ROOT checkpoints alone when there are any. A plain local load resolves through non-recursive
@@ -469,9 +467,8 @@ def _weights_are_servable(load_dir) -> bool:
return False
if any((load_dir / name).is_file() for name in _ADAPTER_MARKERS):
return False
- # the same marker is_embedding_model reads for a local path, without its memo
- # Same marker is_embedding_model reads for a local path, without its memo, which would pin a verdict for the process
- # from one scan.
+ # Same marker is_embedding_model reads for a local path, without its memo, which would pin a verdict for the
+ # process from one scan.
return not (load_dir / "modules.json").is_file()
@@ -659,11 +656,10 @@ def _build_index() -> dict[str, _LocalGgufEntry]:
if rp in seen_hf:
return []
seen_hf.add(rp)
- # only the active cache loads by repo id, else an inactive repo is indexed under an id it cannot load by.
- # Only the active cache loads by repo id. Say so, or an inactive repo is indexed under an id it cannot load
- # by, and its snapshot basename (what /v1/models advertises once loaded by path) is never a key at all. No
- # format classification here: nothing on this path reads model_format, and its recursive walk would
- # duplicate the one _local_gguf_entry already does per snapshot, on the request path.
+ # Only the active cache loads by repo id. Say so, or an inactive repo is indexed under an id it cannot
+ # load by, and its snapshot basename (what /v1/models advertises once loaded by path) is never a key at
+ # all. No format classification here: nothing on this path reads model_format, and its recursive walk
+ # would duplicate the one _local_gguf_entry already does per snapshot, on the request path.
return _scan_hf_cache(directory, active_cache = rp == active_root, classify_format = False)
except Exception as exc: # a missing/malformed root must skip, never crash the index
logger.debug("auto-switch: skipping HF cache dir %r: %s", directory, exc)
@@ -763,25 +759,21 @@ def _build_index() -> dict[str, _LocalGgufEntry]:
def _sibling_revision_entries(raw_id: str, loader_id: str):
"""Yield ``(revision_name, entry)`` for the repo's OTHER cached revisions.
- An inactive-cache repo carries its snapshot path as the id, and /v1/models
- advertises only that directory's basename once loaded, so anything durable
- pinned to it (a subagent config) holds one revision hash. Hugging Face writes a
- new snapshot dir on every update, and the scan emits a single entry per repo
- pointed at the newest one, so that pin would otherwise stop resolving and drop
- through to whatever model is loaded.
+ An inactive-cache repo carries its snapshot path as the id, and /v1/models advertises only that
+ directory's basename once loaded, so anything durable pinned to it (a subagent config) holds one
+ revision hash. Hugging Face writes a new snapshot dir on every update and the scan emits a
+ single entry per repo pointed at the newest one, so that pin would otherwise stop resolving and
+ drop through to whatever model is loaded.
- Each revision gets an entry for its OWN directory rather than an alias onto the
- scanned one: aliasing would redirect a pin that names an older complete revision
- onto a newer half-downloaded snapshot and break a request that works today.
- Incomplete revisions are skipped for the same reason.
+ Each revision gets an entry for its OWN directory rather than an alias onto the scanned one:
+ aliasing would redirect a pin that names an older complete revision onto a newer half-downloaded
+ snapshot. Incomplete revisions are skipped for the same reason.
Sibling names are only revisions inside a real cache repo
- (``<root>/models--org--name/snapshots/<rev>``). A scan folder that merely happens
- to be called ``snapshots`` holds unrelated models, and treating those as
- revisions would silently serve one model in place of another.
-
- GGUF only: ``snapshot_variants_all_complete`` reports a revision offering no quants
- as incomplete, so a non-GGUF repo pins to its scanned revision alone.
+ (``<root>/models--org--name/snapshots/<rev>``); a scan folder that merely happens to be called
+ ``snapshots`` holds unrelated models. GGUF only: ``snapshot_variants_all_complete`` reports a
+ revision offering no quants as incomplete, so a non-GGUF repo pins to its scanned revision
+ alone.
"""
from pathlib import Path
from types import SimpleNamespace
@@ -833,7 +825,6 @@ def _snapshot_is_trusted(timestamp: float, now: float) -> bool:
return False
-# a cache built on top of this index can key on it and be dropped by the same call that drops the index
# Bumped by every invalidate_index() call. A cache built on top of this index can key on it and be dropped by the same
# call that drops the index, rather than each new invalidation site having to remember one more cache to clear.
_generation = 0
@@ -880,8 +871,6 @@ def _index() -> dict[str, _LocalGgufEntry]:
if ts > 0.0 and now - ts < _CACHE_TTL_S:
return cached
fresh = _build_index()
- # stamp AFTER the scan: a multi-root scan on an install with many local models can itself exceed the TTL,
- # storing the cache already expired
# Stamp AFTER the scan, not with the pre-scan ``now``: a multi-root scan on an install with many local models
# can itself exceed the TTL, which would store the cache already expired and make every request rebuild the
# index.
@@ -980,19 +969,18 @@ def resolve_local_gguf(
) -> Optional[tuple]:
"""Return ``(load_path, gguf_variant, loader_id)`` for a local match, else None.
- ``load_path`` is the concrete on-disk path to hand /load (so it never fetches
- a remote), ``loader_id`` is the advertised id used as the launch-override key.
- ``gguf_variant`` is None for a non-GGUF checkpoint, which has no quant to pin.
- ``requested`` is ``repo`` or ``repo:VARIANT``. An exact id match wins first
- (so ids containing a colon still resolve); else the last ``:VARIANT`` is split
- off and resolves only when that quant is on disk, unless it names no quant at
- all (an Ollama-style ":latest"), which means the repo.
-
- ``allow_scan=False`` answers from the last built index and never rebuilds. It is
- a raw snapshot read for callers that separately decide whether the snapshot is
- trustworthy; use :func:`resolve_trusted_cached_local_gguf` for model switching.
- With ``include_companion_scope=True``, append whether sibling snapshots belong
- to this repo-level resolution and may be searched for compatible companions.
+ ``load_path`` is the concrete on-disk path to hand /load (so it never fetches a remote),
+ ``loader_id`` is the advertised id used as the launch-override key, and ``gguf_variant`` is None
+ for a non-GGUF checkpoint, which has no quant to pin. ``requested`` is ``repo`` or
+ ``repo:VARIANT``: an exact id match wins first (so ids containing a colon still resolve), else
+ the last ``:VARIANT`` is split off and resolves only when that quant is on disk, unless it names
+ no quant at all (an Ollama-style ":latest"), which means the repo.
+
+ ``allow_scan=False`` answers from the last built index and never rebuilds. It is a raw snapshot
+ read for callers that separately decide whether the snapshot is trustworthy; use
+ :func:`resolve_trusted_cached_local_gguf` for model switching. With
+ ``include_companion_scope=True``, append whether sibling snapshots belong to this repo-level
+ resolution and may be searched for compatible companions.
"""
if not isinstance(requested, str) or not requested.strip():
return None
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index edf0bcc7561..86ac674f9c6 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -32,11 +32,9 @@ MCP_TOOL_PREFIX = "mcp__"
_WINDOWS_BATCH_ALWAYS_UNSAFE_ARGUMENT_CHARS = frozenset('%!"\r\n')
_WINDOWS_BATCH_UNQUOTED_UNSAFE_ARGUMENT_CHARS = frozenset("&|<>^()")
-# A failed probe isn't cached (a recovered server must come back), but it's
-# recorded so a down server isn't re-probed -- and the chat send re-hung for
-# the full timeout -- on every message. Cool off for this long after a failure;
-# much longer for OAuth, whose probe can hang up to _OAUTH_PROBE_TIMEOUT,
-# so that hang doesn't recur every minute.
+# A failed probe isn't cached (a recovered server must come back), but it's recorded so a down server isn't re-probed
+# -- and the chat send re-hung for the full timeout -- on every message. Cool off for this long after a failure; much
+# longer for OAuth, whose probe can hang up to _OAUTH_PROBE_TIMEOUT, so that hang doesn't recur every minute.
FAILED_PROBE_COOLOFF_SECONDS = 60.0
OAUTH_FAILED_PROBE_COOLOFF_SECONDS = 300.0
@@ -44,15 +42,15 @@ _oauth_token_store = None
def is_stdio(address: str) -> bool:
- """A non-HTTP address is a local stdio command, e.g.
- 'npx -y @modelcontextprotocol/server-filesystem /path'."""
+ """A non-HTTP address is a local stdio command, e.g. 'npx -y
+ @modelcontextprotocol/server-filesystem /path'."""
return not address.strip().lower().startswith(("http://", "https://"))
def _split_windows_command_line(address: str) -> list[str]:
"""Parse a Windows command line using the same backslash/quote rules that
- subprocess.list2cmdline() writes. This keeps trailing backslashes before a
- closing quote from being doubled in the resulting argv."""
+ subprocess.list2cmdline() writes. This keeps trailing backslashes before a closing quote from
+ being doubled in the resulting argv."""
parts: list[str] = []
current: list[str] = []
in_quotes = False
@@ -76,9 +74,8 @@ def _split_windows_command_line(address: str) -> list[str]:
backslashes = 0
i += 1
continue
- # subprocess.list2cmdline() implements the MS C runtime grammar: only
- # space and tab delimit arguments. Other Unicode/control whitespace is
- # ordinary argument data and must not be split here.
+ # subprocess.list2cmdline() implements the MS C runtime grammar: only space and tab delimit arguments. Other
+ # Unicode/control whitespace is ordinary argument data and must not be split here.
if ch in (" ", "\t") and not in_quotes:
if backslashes:
current.extend("\\" * backslashes)
@@ -111,8 +108,8 @@ def _split_windows_command_line(address: str) -> list[str]:
def parse_stdio_command(address: str) -> list[str]:
- """Split a stdio command line into argv. Shared by route validation and the
- transport so both agree on quoting (notably Windows backslash paths)."""
+ """Split a stdio command line into argv. Shared by route validation and the transport so both
+ agree on quoting (notably Windows backslash paths)."""
posix = sys.platform != "win32"
if posix:
return shlex.split(address, posix = posix)
@@ -122,11 +119,11 @@ def parse_stdio_command(address: str) -> list[str]:
def join_stdio_command(parts: list[str]) -> str:
- """Inverse of parse_stdio_command: join argv into a single command string
- that parse_stdio_command() splits back into ``parts`` on this platform.
- Config files (issue #5936) carry structured command + args; storage holds
- one string in the url field. Windows uses list2cmdline so spaced/backslash
- paths round-trip through the posix=False quote-strip; posix uses shlex."""
+ """Inverse of parse_stdio_command: join argv into a single command string that
+ parse_stdio_command() splits back into ``parts`` on this platform. Config files (issue #5936)
+ carry structured command + args; storage holds one string in the url field. Windows uses
+ list2cmdline so spaced/backslash paths round-trip through the posix=False quote-strip; posix
+ uses shlex."""
if sys.platform == "win32":
return subprocess.list2cmdline(parts)
return shlex.join(parts)
@@ -143,10 +140,9 @@ def _windows_batch_argument_is_unsafe(argument: str) -> bool:
def _session_log_id(url: str) -> str:
- """A non-secret label for logs. stdio commands can embed credentials in argv
- (e.g. ``npx server --token sk-...``) and HTTP URLs in their query string, so
- never log the raw address; use the executable basename (or the host) plus a
- short digest of the full address instead."""
+ """A non-secret label for logs. stdio commands can embed credentials in argv (e.g. ``npx server
+ --token sk-...``) and HTTP URLs in their query string, so never log the raw address; use the
+ executable basename (or the host) plus a short digest of the full address instead."""
digest = hashlib.sha256(url.encode()).hexdigest()[:12]
if not is_stdio(url):
try:
@@ -163,18 +159,18 @@ def _session_log_id(url: str) -> str:
def stdio_mcp_enabled() -> bool:
- """stdio MCP servers spawn local processes as the backend user (bypassing the
- sandbox), so allowed only when the host is the user's own machine. On startup
- a loopback bind defaults UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 (see
- utils.host_policy.apply_stdio_mcp_loopback_default, called from run.py); the
- Tauri app does the same. Off for Colab and any network (0.0.0.0) bind unless
+ """stdio MCP servers spawn local processes as the backend user (bypassing the sandbox), so allowed
+ only when the host is the user's own machine. On startup a loopback bind defaults
+ UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 (see utils.host_policy.apply_stdio_mcp_loopback_default, called
+ from run.py); the Tauri app does the same. Off for Colab and any network (0.0.0.0) bind unless
an operator sets the var out-of-band; set it to 0 to force-disable.
- When stdio is on only because of that loopback auto-default, an explicit
- `unsloth studio run --disable-tools` turns it back off (a local stdio command
- is server-side code execution). An explicit operator opt-in via the env var
- still wins -- including the documented `=1` network opt-in, where the process
- tool policy is False merely by the external-host default, not by choice."""
+ When stdio is on only because of that loopback auto-default, an explicit `unsloth studio run
+ --disable-tools` turns it back off (a local stdio command is server-side code execution). An
+ explicit operator opt-in via the env var still wins, including the documented `=1` network
+ opt-in, where the process tool policy is False merely by the external-host default, not by
+ choice.
+ """
if os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") != "1":
return False
from state.tool_policy import get_tool_policy
@@ -186,11 +182,10 @@ def stdio_mcp_enabled() -> bool:
def stdio_mcp_disabled_reason() -> str:
- """User-facing reason local commands are off, mirroring stdio_mcp_enabled().
-
- Telling a user whose gate is suspended by an active tunnel to set
- UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 would re-enable local command execution on
- a published API, so the suspended cases must name their actual cause."""
+ """User-facing reason local commands are off, mirroring stdio_mcp_enabled(). Telling a user
+ whose gate is suspended by an active tunnel to set UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 would
+ re-enable local command execution on a published API, so the suspended cases must name their
+ actual cause."""
from state.tool_policy import get_tool_policy
from utils.host_policy import loopback_default_active, remote_connector_active
@@ -214,9 +209,8 @@ def stdio_mcp_disabled_reason() -> str:
)
-# Probe timeouts for discovering a server's tool list. OAuth needs minutes for
-# first-connect/expired-token browser sign-in; stdio allows for first-run
-# package download (e.g. `npx -y ...`); HTTP fails fast.
+# Probe timeouts for discovering a server's tool list. OAuth needs minutes for first-connect/expired-token browser
+# sign-in; stdio allows for first-run package download (e.g. `npx -y ...`); HTTP fails fast.
_HTTP_PROBE_TIMEOUT = 8.0
_OAUTH_PROBE_TIMEOUT = 305.0
_STDIO_PROBE_TIMEOUT = 60.0
@@ -229,8 +223,8 @@ def probe_timeout(address: str, use_oauth: bool) -> float:
def parse_server_headers(server: dict) -> Optional[dict]:
- """Parsed headers_json. For stdio servers this dict is the process env
- instead of HTTP headers (see _client)."""
+ """Parsed headers_json. For stdio servers this dict is the process env instead of HTTP headers
+ (see _client)."""
raw = server.get("headers_json")
if not raw:
return None
@@ -248,8 +242,8 @@ def _oauth_store():
from key_value.aio.stores.filetree import FileTreeStore
from utils.paths.storage_roots import ensure_dir, studio_root
- # Hash keys/collections — fastmcp uses raw URLs as keys, and FileTreeStore
- # would treat the "://" as nested directories.
+ # Hash keys/collections: fastmcp uses raw URLs as keys, and FileTreeStore would treat the "://" as nested
+ # directories.
_oauth_token_store = FileTreeStore(
data_directory = ensure_dir(studio_root() / "mcp-oauth-tokens"),
key_sanitization_strategy = AlwaysHashStrategy(),
@@ -259,9 +253,9 @@ def _oauth_store():
def _strip_client_id_under_basic_auth(auth) -> None:
- """The SDK leaves client_id in the body under Basic auth; strict servers (Notion) read
- that as two auth methods -- RFC 6749 2.3 -- and 401. Safe to drop: 3.2.1 makes client_id
- a MAY once authenticated, and an unauthenticated client sends no header, so it keeps it."""
+ """The SDK leaves client_id in the body under Basic auth; strict servers (Notion) read that as
+ two auth methods -- RFC 6749 2.3 -- and 401. Safe to drop: 3.2.1 makes client_id a MAY once
+ authenticated, and an unauthenticated client sends no header, so it keeps it."""
context = getattr(auth, "context", None)
prepare = getattr(context, "prepare_token_auth", None)
if prepare is None:
@@ -290,10 +284,10 @@ def _oauth(url: str):
async def clear_oauth_tokens_async(url: str) -> None:
- """Drop any persisted OAuth tokens for ``url``. fastmcp keys tokens by MCP
- URL, so on server delete / URL change / OAuth disable we must clear them, else
- re-registering the same URL reuses the old account's token. Best-effort: store
- / OAuth failures must not 500 the delete / update route."""
+ """Drop any persisted OAuth tokens for ``url``. fastmcp keys tokens by MCP URL, so on server
+ delete / URL change / OAuth disable we must clear them, else re-registering the same URL
+ reuses the old account's token. Best-effort: store / OAuth failures must not 500 the delete /
+ update route."""
try:
await _oauth(url).token_storage_adapter.clear()
except Exception as exc: # noqa: BLE001
@@ -315,27 +309,27 @@ def _launcher_name(command: str) -> str:
def _is_node_command(command: str) -> bool:
- """Whether argv[0] is a Node launcher. Only those need the managed runtime, so a
- Python or other stdio server keeps the toolchain its own env pinned."""
+ """Whether argv[0] is a Node launcher. Only those need the managed runtime, so a Python or other
+ stdio server keeps the toolchain its own env pinned."""
return _launcher_name(command) in _NODE_COMMANDS
def _command_selects_runtime(command: Optional[str]) -> bool:
- """A path to a ``node`` launcher picks the runtime explicitly and runs regardless of
- PATH, so handing its children a different Node would only split the two."""
+ """A path to a ``node`` launcher picks the runtime explicitly and runs regardless of PATH, so
+ handing its children a different Node would only split the two."""
return (
command is not None and bool(os.path.dirname(command)) and _launcher_name(command) == "node"
)
def _runtime_requirements(command: Optional[str]) -> tuple[bool, bool]:
- """``(needs npm, needs npx)`` for argv[0]. Each launcher asks only for what it runs,
- so an unrelated missing launcher cannot shadow a good runtime: node needs neither, npm
- needs npm, and npx needs npx alone -- npx never shells out to an ``npm`` executable,
- its npx-cli.js delegates in-process to the npm library it ships with, so a PATH
- exposing node and npx without a separate npm runs it fine and must be left alone.
- A pathed npm/npx is already located and only needs a node for its shebang, so it
- does not require a second copy of itself on PATH either."""
+ """``(needs npm, needs npx)`` for argv[0]. Each launcher asks only for what it runs, so an
+ unrelated missing launcher cannot shadow a good runtime: node needs neither, npm needs npm,
+ and npx needs npx alone -- npx never shells out to an ``npm`` executable, its npx-cli.js
+ delegates in-process to the npm library it ships with, so a PATH exposing node and npx
+ without a separate npm runs it fine and must be left alone. A pathed npm/npx is already
+ located and only needs a node for its shebang, so it does not require a second copy of itself
+ on PATH either."""
name = _launcher_name(command) if command is not None else None
if name == "node":
return False, False
@@ -349,8 +343,8 @@ def _runtime_requirements(command: Optional[str]) -> tuple[bool, bool]:
def _path_key(env: dict) -> str:
- """The key holding PATH. Windows env names are case-insensitive, so a config may
- spell it ``Path``; on POSIX only the exact name counts."""
+ """The key holding PATH. Windows env names are case-insensitive, so a config may spell it
+ ``Path``; on POSIX only the exact name counts."""
if _IS_WINDOWS:
for key in env:
if key.upper() == "PATH":
@@ -359,8 +353,8 @@ def _path_key(env: dict) -> str:
def _stdio_env(headers: Optional[dict], command: Optional[str] = None) -> Optional[dict]:
- """Process env for a stdio server: its own vars, plus the managed Node bin dir
- on PATH so ``npx ...`` servers spawn on hosts with no usable system Node."""
+ """Process env for a stdio server: its own vars, plus the managed Node bin dir on PATH so ``npx
+ ...`` servers spawn on hosts with no usable system Node."""
env = dict(headers or {})
for key, value in env.items():
if not isinstance(key, str) or not isinstance(value, str):
@@ -392,9 +386,9 @@ def _stdio_env(headers: Optional[dict], command: Optional[str] = None) -> Option
def _stdio_argv(parts: list, env: Optional[dict]) -> list:
- """argv with argv[0] resolved against the child's PATH. Windows resolves the
- command against the parent environment before ``env`` applies, so a managed-only
- ``npx`` has to be handed over as a full path."""
+ """argv with argv[0] resolved against the child's PATH. Windows resolves the command against the
+ parent environment before ``env`` applies, so a managed-only ``npx`` has to be handed over as
+ a full path."""
path_key = _path_key(env or {})
explicit_path = env is not None and path_key in env
path = (env or {}).get(path_key)
@@ -461,8 +455,8 @@ def _client(
parts = parse_stdio_command(url)
if not parts:
raise ValueError(f"Empty stdio command: {url!r}")
- # env vars ride the headers field (merged over the SDK default env).
- # keep_alive=False tears the subprocess down so a one-shot call leaves no orphan.
+ # env vars ride the headers field (merged over the SDK default env). keep_alive=False tears the subprocess
+ # down so a one-shot call leaves no orphan.
env = _stdio_env(headers, parts[0])
argv = _stdio_argv(parts, env)
return Client(
@@ -492,18 +486,16 @@ _SESSION_CLOSE_TIMEOUT = 10.0
_SESSION_WEDGE_MARGIN = 15.0
_SESSION_LIVENESS_TIMEOUT = 5.0
_CANCEL_UNWIND_TIMEOUT = 2.0
-# An HTTP session idle this long is re-proved with tools/list before the next
-# dispatch: the server may have expired it (MCP says a server MAY terminate a
-# session at any time), and no HTTP transport exposes a liveness probe we can
-# ask instead -- see _transport_dead.
+# An HTTP session idle this long is re-proved with tools/list before the next dispatch: the server may have expired it
+# (MCP says a server MAY terminate a session at any time), and no HTTP transport exposes a liveness probe we can ask
+# instead -- see _transport_dead.
_HTTP_IDLE_RECHECK = 30.0
_DEFAULT_MAX_SESSIONS = 32
def _max_sessions_from_env() -> int:
- # The cap covers stdio and HTTP sessions alike now, so the stdio-specific
- # name is wrong; keep honouring it so deployments that already set it do not
- # silently jump back to the default.
+ # The cap covers stdio and HTTP sessions alike now, so the stdio-specific name is wrong; keep honouring it so
+ # deployments that already set it do not silently jump back to the default.
raw = os.environ.get("UNSLOTH_STUDIO_MAX_MCP_SESSIONS")
if raw is None:
raw = os.environ.get("UNSLOTH_STUDIO_MAX_STDIO_MCP_SESSIONS")
@@ -519,21 +511,18 @@ _MAX_SESSIONS = _max_sessions_from_env()
def _connect_window(url: str, timeout: Optional[float]) -> Optional[float]:
- """How long connecting may take, out of the caller's remaining budget.
-
- stdio keeps the cold-start cap: a first run may download a package before the
- server says anything. HTTP has no such phase, and capping it would reject
- connections the caller explicitly allowed time for -- which is what the
- one-shot path it replaced always did."""
+ """How long connecting may take, out of the caller's remaining budget. stdio keeps the
+ cold-start cap: a first run may download a package before the server says anything. HTTP has
+ no such phase, and capping it would reject connections the caller explicitly allowed time
+ for, which is what the one-shot path it replaced always did."""
if timeout is None or not is_stdio(url):
return timeout
return min(timeout, _STDIO_CONNECT_TIMEOUT)
class _ConnectTimeout(asyncio.TimeoutError):
- """Ran out of time before the transport was up. Carries the window that
- actually expired, which is not the caller's timeout when stdio's cold-start
- cap is the tighter bound."""
+ """Ran out of time before the transport was up. Carries the window that actually expired, which
+ is not the caller's timeout when stdio's cold-start cap is the tighter bound."""
def __init__(self, window: Optional[float]):
super().__init__()
@@ -541,9 +530,9 @@ class _ConnectTimeout(asyncio.TimeoutError):
def _is_tool_error(exc: BaseException) -> bool:
- """A tool-level failure (the tool ran and errored) leaves the transport alive,
- so the session is kept; fastmcp raises ToolError for these. Anything else from
- call_tool is transport-level. Version-safe (fastmcp 3.0.2 has no dead probe)."""
+ """A tool-level failure (the tool ran and errored) leaves the transport alive, so the session is
+ kept; fastmcp raises ToolError for these. Anything else from call_tool is transport-level.
+ Version-safe (fastmcp 3.0.2 has no dead probe)."""
try:
from fastmcp.exceptions import ToolError
except Exception: # noqa: BLE001
@@ -552,15 +541,13 @@ def _is_tool_error(exc: BaseException) -> bool:
def _is_protocol_error(exc: BaseException) -> bool:
- """A JSON-RPC error response, as opposed to a broken connection.
-
- A FastMCP server answers an unknown tool or bad arguments with a result
- carrying is_error, but the MCP spec also lets a server report those as a
- protocol error, and plenty of non-FastMCP servers do. fastmcp surfaces that
- as MCPError (McpError before the rename) carrying the ErrorData the server
- sent. Receiving it proves the connection is working, so retiring the session
- over it would throw away the chat's server-side state for a mistyped tool
- name. The caller still marks the session for a probe before reuse."""
+ """A JSON-RPC error response, as opposed to a broken connection. A FastMCP server answers an
+ unknown tool or bad arguments with a result carrying is_error, but the MCP spec also lets a
+ server report those as a protocol error, and plenty of non-FastMCP servers do. fastmcp
+ surfaces that as MCPError (McpError before the rename) carrying the ErrorData the server
+ sent. Receiving it proves the connection is working, so retiring the session over it would
+ throw away the chat's server-side state for a mistyped tool name. The caller still marks the
+ session for a probe before reuse."""
for module, name in (
("mcp.shared.exceptions", "MCPError"),
("mcp.shared.exceptions", "McpError"),
@@ -570,24 +557,21 @@ def _is_protocol_error(exc: BaseException) -> bool:
except Exception: # noqa: BLE001
continue
if cls is not None and isinstance(exc, cls):
- # Only when the server actually sent an error object; a synthetic
- # MCPError with nothing behind it stays transport-level.
+ # Only when the server actually sent an error object; a synthetic MCPError with nothing behind it stays
+ # transport-level.
return getattr(exc, "error", None) is not None
return False
def _transport_dead(session) -> bool:
- """Best-effort, version-adaptive liveness probe for a cached client.
- ``Client.is_connected()`` only checks a session object exists, not that the
- subprocess (or the server's HTTP session) is alive, so it is never used here.
- Returns True only when the transport is positively gone; unknown returns
- False (the call surfaces it).
-
- Only the stdio transport answers: ``_is_session_dead``/``_connect_task`` are
- ``StdioTransport`` internals, and neither ``StreamableHttpTransport`` nor
- ``SSETransport`` has ever carried them (checked on fastmcp 3.0.2 and 4.0.0).
- For HTTP this returns "unknown" every time, which is why an idle HTTP session
- is re-proved with tools/list instead -- see _needs_idle_recheck."""
+ """Best-effort, version-adaptive liveness probe for a cached client. ``Client.is_connected()``
+ only checks a session object exists, not that the subprocess (or the server's HTTP session)
+ is alive, so it is never used here. Returns True only when the transport is positively gone;
+ unknown returns False (the call surfaces it). Only the stdio transport answers:
+ ``_is_session_dead``/``_connect_task`` are ``StdioTransport`` internals, and neither
+ ``StreamableHttpTransport`` nor ``SSETransport`` has ever carried them (checked on fastmcp
+ 3.0.2 and 4.0.0). For HTTP this returns "unknown" every time, which is why an idle HTTP
+ session is re-proved with tools/list instead -- see _needs_idle_recheck."""
client = getattr(session, "client", None)
if client is None:
return True
@@ -610,21 +594,16 @@ def _transport_dead(session) -> bool:
def _needs_idle_recheck(session, idle_for: float, remaining: Optional[float]) -> bool:
- """Whether an idle HTTP session must prove itself before the next dispatch.
-
- A server MAY drop an HTTP session whenever it likes, and the client only
- learns on the next request -- which would surface as a failed tool call the
- user has to retry by hand. stdio is exempt: _transport_dead answers there, and
- a live subprocess does not expire on its own.
-
- Skipped when the caller cannot afford it. The probe exists to save someone a
- failed call, so spending their whole budget on it (tool_call_timeout goes down
- to 1s) would cause the very failure it is meant to avoid; dispatching straight
- away is the better bet with that little time left."""
+ """Whether an idle HTTP session must prove itself before the next dispatch. A server MAY drop an
+ HTTP session whenever it likes, and the client only learns on the next request, which would
+ surface as a failed tool call the user has to retry by hand. stdio is exempt: _transport_dead
+ answers there, and a live subprocess does not expire on its own. Skipped when the caller
+ cannot afford it: the probe exists to save someone a failed call, so spending their whole
+ budget on it (tool_call_timeout goes down to 1s) would cause the very failure it is meant to
+ avoid."""
if is_stdio(session.url):
return False
- # Negative means this borrower connected the session itself, so the handshake
- # it just completed is proof enough.
+ # Negative means this borrower connected the session itself, so the handshake it just completed is proof enough.
if idle_for < 0.0 or idle_for < _HTTP_IDLE_RECHECK:
return False
return remaining is None or remaining > _SESSION_LIVENESS_TIMEOUT * 2
@@ -636,18 +615,17 @@ def _session_responsive(
cancel_event = None,
timeout_is_fatal: bool = True,
) -> bool:
- """Whether a session left dirty by an abandoned call can be reused: the
- server must answer inside ``budget`` (the caller's remaining deadline).
- Proves the server is alive, not that the abandoned call finished -- MCP
- requests are concurrent. Probes with a raw single-page tools/list: ping
- answers "Method not found" on a modern-era connection, and list_tools()
- auto-paginates up to 250 pages.
-
- ``timeout_is_fatal`` separates the two callers. A dirty session is under
- suspicion, so silence within the window condemns it. An idle one is only
- being spot-checked: a slow answer says nothing about whether the transport
- is gone, and retiring it there would throw away the very state this cache
- exists to keep. Only a definite failure retires that one."""
+ """Whether a session left dirty by an abandoned call can be reused: the server must answer inside
+ ``budget`` (the caller's remaining deadline). Proves the server is alive, not that the abandoned
+ call finished -- MCP requests are concurrent. Probes with a raw single-page tools/list: ping
+ answers "Method not found" on a modern-era connection, and list_tools() auto-paginates up to 250
+ pages.
+
+ ``timeout_is_fatal`` separates the two callers. A dirty session is under suspicion, so silence
+ within the window condemns it. An idle one is only being spot-checked: a slow answer says
+ nothing about whether the transport is gone, and retiring it there would throw away the very
+ state this cache exists to keep. Only a definite failure retires that one.
+ """
client = session.client
if client is None:
return False
@@ -664,10 +642,9 @@ def _session_responsive(
except (asyncio.TimeoutError, _SessionWedged):
return not timeout_is_fatal
except Exception as exc: # noqa: BLE001
- # A JSON-RPC error (a rate limit, a permission rule on tools/list) is the
- # server answering on this very session, exactly as it is for call_tool.
- # Reconnecting would throw away the chat's state over a reply that proves
- # the transport works.
+ # A JSON-RPC error (a rate limit, a permission rule on tools/list) is the server answering on this very
+ # session, exactly as it is for call_tool. Reconnecting would throw away the chat's state over a reply that
+ # proves the transport works.
if not _is_protocol_error(exc):
return False
session.dirty = False
@@ -699,9 +676,8 @@ class _McpSession:
headers: Optional[dict],
use_oauth: bool = False,
):
- # A cached session is built by _client(url, headers) with no auth, so an
- # OAuth server must never reach here. call_tool_sync already routes it to
- # the one-shot path; this makes a future routing slip fail loudly rather
+ # A cached session is built by _client(url, headers) with no auth, so an OAuth server must never reach here.
+ # call_tool_sync already routes it to the one-shot path; this makes a future routing slip fail loudly rather
# than quietly talk to an OAuth server unauthenticated.
if use_oauth and not is_stdio(url):
raise ValueError("OAuth MCP servers cannot use a shared session")
@@ -713,22 +689,18 @@ class _McpSession:
self.dirty = False # a call was abandoned on it; ping before reuse
self._close_lock = threading.Lock()
self.call_lock = threading.Lock()
- # One stdio subprocess is one ordered byte stream, so overlapping calls
- # must not interleave on it. HTTP has no such constraint: every JSON-RPC
- # message is its own POST and the spec lets a client keep several streams
- # open at once, so serializing it would only undo the parallelism the
- # one-shot path had.
+ # One stdio subprocess is one ordered byte stream, so overlapping calls must not interleave on it. HTTP has no
+ # such constraint: every JSON-RPC message is its own POST and the spec lets a client keep several streams open
+ # at once, so serializing it would only undo the parallelism the one-shot path had.
self.serialize_calls = is_stdio(url)
self.last_used = time.monotonic()
- # When the transport was last shown to be alive, as opposed to merely
- # borrowed. Checkout refreshes last_used immediately, so the idle gap the
- # recheck needs has to be measured from here or a second borrower arriving
+ # When the transport was last shown to be alive, as opposed to merely borrowed. Checkout refreshes last_used
+ # immediately, so the idle gap the recheck needs has to be measured from here or a second borrower arriving
# during the first one's probe would see no gap at all.
self.proved_at = self.last_used
self.in_flight = 0 # guarded by _mcp_sessions_lock
- # On Windows a bare new_event_loop() can be a SelectorEventLoop (if any
- # component set that policy), which cannot spawn subprocesses natively;
- # force a ProactorEventLoop so the stdio transport always works.
+ # On Windows a bare new_event_loop() can be a SelectorEventLoop (if any component set that policy), which
+ # cannot spawn subprocesses natively; force a ProactorEventLoop so the stdio transport always works.
if sys.platform == "win32":
self.loop = asyncio.ProactorEventLoop()
else:
@@ -747,16 +719,14 @@ class _McpSession:
async def _open():
client = _client(self.url, self.headers)
await client.__aenter__()
- # Publish on the loop thread with no await in between: if an abort
- # races a just-completed connect, close() still sees the client and
- # __aexit__s it instead of orphaning the subprocess.
+ # Publish on the loop thread with no await in between: if an abort races a just-completed connect, close()
+ # still sees the client and __aexit__s it instead of orphaning the subprocess.
self.client = client
return client
future = asyncio.run_coroutine_threadsafe(_open(), self.loop)
- # timeout=None means unlimited (no connect deadline); a finite caller
- # timeout bounds connect by _connect_window(), which caps stdio at its
- # cold-start limit and hands HTTP the whole remaining budget.
+ # timeout=None means unlimited (no connect deadline); a finite caller timeout bounds connect by
+ # _connect_window(), which caps stdio at its cold-start limit and hands HTTP the whole remaining budget.
window = _connect_window(self.url, timeout)
deadline = None if window is None else time.monotonic() + window
while True:
@@ -791,11 +761,10 @@ class _McpSession:
):
self.last_used = time.monotonic()
future = asyncio.run_coroutine_threadsafe(coro, self.loop)
- # The coroutine enforces the tool timeout; the margin only catches a
- # wedged loop. No deadline at all when the caller set none -- but poll
- # so a session closed under us (server update/delete) can't hang the
- # request thread forever on a stopped loop. Callers whose whole budget is
- # the timeout (the liveness probe) pass margin=0.
+ # The coroutine enforces the tool timeout; the margin only catches a wedged loop. No deadline at all when the
+ # caller set none -- but poll so a session closed under us (server update/delete) can't hang the request
+ # thread forever on a stopped loop. Callers whose whole budget is the timeout (the liveness probe) pass
+ # margin=0.
deadline = None if timeout is None else time.monotonic() + timeout + margin
try:
while True:
@@ -827,13 +796,13 @@ class _McpSession:
if loop_alive:
async def _shutdown() -> None:
- # Runs on the loop thread, so it serializes with an aborted
- # connect() that finished anyway and just published its client.
+ # Runs on the loop thread, so it serializes with an aborted connect() that finished anyway and just
+ # published its client.
client, self.client = self.client, None
if client is not None:
await client.__aexit__(None, None, None)
- # Cancel in-flight calls so they unwind before loop.stop
- # (their run() waiters have already been released via `closed`).
+ # Cancel in-flight calls so they unwind before loop.stop (their run() waiters have already been
+ # released via `closed`).
for task in asyncio.all_tasks():
if task is not asyncio.current_task():
task.cancel()
@@ -860,8 +829,7 @@ class _McpSession:
_mcp_sessions: dict[tuple, _McpSession] = {}
-# Per-key locks so a slow connect/close never blocks unrelated servers; the
-# global lock only guards the dicts.
+# Per-key locks so a slow connect/close never blocks unrelated servers; the global lock only guards the dicts.
class _McpKeyLock:
"""A per-key lock that can be removed once nobody references it."""
@@ -873,20 +841,17 @@ class _McpKeyLock:
_mcp_key_locks: dict[tuple, _McpKeyLock] = {}
_mcp_sessions_lock = threading.Lock()
_mcp_reaper_started = False
-# Sessions discarded while somebody else was mid-call, closed by one worker off
-# the request path. See _close_detached.
+# Sessions discarded while somebody else was mid-call, closed by one worker off the request path. See _close_detached.
_mcp_cleanup_lock = threading.Lock()
_mcp_cleanup_queue: list = []
-# Depth past which an evicting caller closes the overflow itself. See
-# _close_detached.
+# Depth past which an evicting caller closes the overflow itself. See _close_detached.
_MAX_PENDING_CLOSES = 8
# How wide close_mcp_sessions fans out. See _close_all.
_MAX_CLOSE_THREADS = 16
_mcp_cleanup_worker: Optional[threading.Thread] = None
-# close_mcp_sessions() can only close sessions already published in _mcp_sessions;
-# one still inside connect() would be missed and then cached already
-# stale. Bump a generation on every close so that connect discards its
-# session instead of publishing it. Guarded by _mcp_sessions_lock.
+# close_mcp_sessions() can only close sessions already published in _mcp_sessions; one still inside connect() would be
+# missed and then cached already stale. Bump a generation on every close so that connect discards its session instead
+# of publishing it. Guarded by _mcp_sessions_lock.
_mcp_close_all_gen = 0
_mcp_url_close_gen: dict[str, int] = {}
_mcp_cfg_close_gen: dict[tuple, int] = {}
@@ -900,9 +865,8 @@ def _headers_key(headers: Optional[dict]) -> tuple:
def _url_close_key(url: str) -> str:
- # Commands/URLs (token args, embedded credentials) and env values can hold
- # secrets and these maps are never pruned; key by digest so closed/edited
- # configs don't retain them in memory forever.
+ # Commands/URLs (token args, embedded credentials) and env values can hold secrets and these maps are never
+ # pruned; key by digest so closed/edited configs don't retain them in memory forever.
return hashlib.sha256(url.encode()).hexdigest()
@@ -923,13 +887,10 @@ def _session_key(url: str, headers: Optional[dict], scope: Optional[str]) -> tup
def _checkout_session(key: tuple) -> tuple[Optional[_McpSession], float]:
- """Returns the session and how long it had been unused, measured before
- last_used is refreshed.
-
- The idle gap is returned rather than stored on the session because HTTP
- borrowers run concurrently: a second checkout would otherwise overwrite the
- first one's gap with a near-zero value and talk it out of proving a session
- that really had gone stale."""
+ """Returns the session and how long it had been unused, measured before last_used is refreshed.
+ The idle gap is returned rather than stored on the session because HTTP borrowers run
+ concurrently: a second checkout would otherwise overwrite the first one's gap with a
+ near-zero value and talk it out of proving a session that really had gone stale."""
session = _mcp_sessions.get(key)
if session is not None and session.is_connected():
now = time.monotonic()
@@ -981,12 +942,10 @@ def _get_session(
config_check,
use_oauth: bool = False,
) -> tuple[_McpSession, float]:
- """``deadline`` is the caller's absolute monotonic budget (None = no limit):
- the key-lock wait and the connect share it, so a slow startup can't stack
- full timeout windows (see _call_session_tool).
-
- Returns the session and this borrower's idle gap (negative when we connected
- it ourselves), which only the borrower may act on -- see _checkout_session."""
+ """``deadline`` is the caller's absolute monotonic budget (None = no limit): the key-lock wait
+ and the connect share it, so a slow startup can't stack full timeout windows (see
+ _call_session_tool). Returns the session and this borrower's idle gap (negative when we
+ connected it ourselves), which only the borrower may act on -- see _checkout_session."""
global _mcp_reaper_started
key = _session_key(url, headers, scope)
with _mcp_sessions_lock:
@@ -995,13 +954,11 @@ def _get_session(
return session, idle_for
key_lock = _borrow_key_lock(key)
try:
- # Poll the acquire with connect()'s deadline/cancel semantics: a second
- # same-scope call must not block uncancellably behind another caller's
- # slow startup (e.g. a first-run npx download).
+ # Poll the acquire with connect()'s deadline/cancel semantics: a second same-scope call must not block
+ # uncancellably behind another caller's slow startup (e.g. a first-run npx download).
remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
- # timeout=None means no key-lock deadline (only cancel unblocks it). The
- # wait is bounded exactly like the connect it is queueing behind, so an
- # HTTP caller is not cut off at stdio's cold-start cap here either.
+ # timeout=None means no key-lock deadline (only cancel unblocks it). The wait is bounded exactly like the
+ # connect it is queueing behind, so an HTTP caller is not cut off at stdio's cold-start cap here either.
window = _connect_window(url, remaining)
lock_deadline = None if window is None else time.monotonic() + window
while not key_lock.lock.acquire(timeout = 0.05):
@@ -1053,10 +1010,9 @@ def _get_session(
for victim in evicted:
logger.info("Evicting LRU idle MCP session: %s", _session_log_id(victim.url))
if evicted:
- # Detached: these belong to other scopes and nobody is waiting
- # on them, but an unresponsive transport costs
- # _SESSION_CLOSE_TIMEOUT each. Charging that to this caller
- # would spend the deadline meant for their tool call.
+ # Detached: these belong to other scopes and nobody is waiting on them, but an unresponsive
+ # transport costs _SESSION_CLOSE_TIMEOUT each. Charging that to this caller would spend the
+ # deadline meant for their tool call.
_close_detached(evicted)
if closed_while_connecting:
session.close()
@@ -1074,9 +1030,8 @@ def _release_session(session: _McpSession, defer_close: bool = False) -> None:
session.in_flight = max(0, session.in_flight - 1)
session.last_used = time.monotonic()
close_now = session.defunct and session.in_flight == 0
- # Re-enforce the cap once a burst's sessions go idle. Insert-time eviction
- # only trims idle sessions, so it can overshoot while every cached session
- # is busy; reclaim that overshoot here instead of waiting for the idle
+ # Re-enforce the cap once a burst's sessions go idle. Insert-time eviction only trims idle sessions, so it can
+ # overshoot while every cached session is busy; reclaim that overshoot here instead of waiting for the idle
# reaper. Never evict the session we just used (its last_used is newest).
while len(_mcp_sessions) > _MAX_SESSIONS:
idle = [
@@ -1090,14 +1045,11 @@ def _release_session(session: _McpSession, defer_close: bool = False) -> None:
victims.append(_mcp_sessions.pop(oldest))
_discard_key_lock(oldest)
if close_now and defer_close:
- # This borrower was the last one on a session that has been discarded,
- # either by its own failure or by a sibling's. Either way the caller is
- # mid-request -- it may still have a reconnect and retry to do on the
- # same deadline -- and a transport that is being discarded because it
- # stopped answering is exactly the one whose close runs long. Only the
- # unscoped one-shot path closes inline (defer_close is False there),
- # because there the teardown is the call's own work and the caller
- # expects the subprocess gone by the time it returns.
+ # This borrower was the last one on a session that has been discarded, either by its own failure or by a
+ # sibling's. Either way the caller is mid-request -- it may still have a reconnect and retry to do on the same
+ # deadline -- and a transport that is being discarded because it stopped answering is exactly the one whose
+ # close runs long. Only the unscoped one-shot path closes inline (defer_close is False there), because there
+ # the teardown is the call's own work and the caller expects the subprocess gone by the time it returns.
victims.append(session)
elif close_now:
session.close()
@@ -1106,10 +1058,9 @@ def _release_session(session: _McpSession, defer_close: bool = False) -> None:
def _retire_session(session: _McpSession) -> None:
- """Close a discarded session, but only once no other borrower is mid-call
- on it -- overlapping same-scope calls share one client, and one call's
- timeout must not kill another's in-flight request. The last borrower's
- _release_session() performs the deferred close."""
+ """Close a discarded session, but only once no other borrower is mid-call on it: overlapping
+ same-scope calls share one client, and one call's timeout must not kill another's in-flight
+ request. The last borrower's _release_session() performs the deferred close."""
with _mcp_sessions_lock:
session.defunct = True
busy = session.in_flight > 0
@@ -1126,10 +1077,9 @@ def _drop_session(key: tuple, session: _McpSession) -> None:
def _evict_lru_locked() -> list:
- """Caller holds _mcp_sessions_lock. Evict least-recently-used *idle*
- sessions until the cache is under the cap. Returns the evicted sessions so
- the caller can close them OUTSIDE the lock. If every session is busy the
- cache may transiently overshoot rather than kill an in-flight call."""
+ """Caller holds _mcp_sessions_lock. Evict least-recently-used *idle* sessions until the cache is
+ under the cap. Returns the evicted sessions so the caller can close them OUTSIDE the lock. If
+ every session is busy the cache may transiently overshoot rather than kill an in-flight call."""
victims: list = []
while len(_mcp_sessions) >= _MAX_SESSIONS:
idle = [(s.last_used, k) for k, s in _mcp_sessions.items() if s.in_flight == 0]
@@ -1163,26 +1113,25 @@ def close_mcp_sessions(url: Optional[str] = None, headers = _ANY_HEADERS) -> Non
pending, worker = _drain_cleanup_queue()
_close_all(sessions + pending)
if worker is not None and worker is not threading.current_thread():
- # Draining the queue does not recall the session the worker had already
- # popped, and this function promises its caller (a server edit, or
- # atexit) that the teardown has happened. The worker stops as soon as the
- # queue is empty, so this waits for that one close and no longer.
+ # Draining the queue does not recall the session the worker had already popped, and this function promises its
+ # caller (a server edit, or atexit) that the teardown has happened. The worker stops as soon as the queue is
+ # empty, so this waits for that one close and no longer.
worker.join(_SESSION_CLOSE_TIMEOUT + 5.0)
def _close_all(sessions: list) -> None:
"""Close sessions in parallel.
- Serially, each unresponsive transport can burn _SESSION_CLOSE_TIMEOUT plus
- the thread join before the next one starts. This runs on the request thread
- when a server is edited or deleted, and a popular HTTP server now holds a
- session per chat rather than one overall, so a serial close could stall that
- route for minutes.
+ Serially, each unresponsive transport can burn _SESSION_CLOSE_TIMEOUT plus the thread join
+ before the next one starts. This runs on the request thread when a server is edited or deleted,
+ and a popular HTTP server now holds a session per chat rather than one overall, so a serial
+ close could stall that route for minutes.
- Fanned out _MAX_CLOSE_THREADS wide rather than one thread per session. The
- cache is allowed to overshoot _MAX_SESSIONS while every session in it is
- busy, so the list handed here has no fixed length, and a shutdown is the
- worst moment to ask the process for an unbounded number of threads."""
+ Fanned out _MAX_CLOSE_THREADS wide rather than one thread per session. The cache is allowed to
+ overshoot _MAX_SESSIONS while every session in it is busy, so the list handed here has no fixed
+ length, and a shutdown is the worst moment to ask the process for an unbounded number of
+ threads.
+ """
if not sessions:
return
if len(sessions) == 1:
@@ -1200,16 +1149,15 @@ def _close_all(sessions: list) -> None:
session = pending.pop()
_close_quietly(session)
- # Bare threads, not a ThreadPoolExecutor: this also runs as the atexit
- # handler, and Python shuts the executor machinery down before normal atexit
- # callbacks, so submitting there raises ("can't register atexit after
+ # Bare threads, not a ThreadPoolExecutor: this also runs as the atexit handler, and Python shuts the executor
+ # machinery down before normal atexit callbacks, so submitting there raises ("can't register atexit after
# shutdown") and the whole cleanup aborts with stdio subprocesses still up.
width = min(len(pending), _MAX_CLOSE_THREADS)
threads = [threading.Thread(target = _drain, name = "mcp-close", daemon = True) for _ in range(width)]
for thread in threads:
thread.start()
- # Each worker may take several sessions in turn, so the wait scales with the
- # rounds it has to make rather than with a single close.
+ # Each worker may take several sessions in turn, so the wait scales with the rounds it has to make rather than
+ # with a single close.
rounds = -(-len(sessions) // width)
for thread in threads:
thread.join(rounds * (_SESSION_CLOSE_TIMEOUT + 5.0))
@@ -1218,24 +1166,23 @@ def _close_all(sessions: list) -> None:
def _close_detached(sessions: list) -> None:
"""Hand sessions nobody is waiting on to the cleanup worker.
- Used for LRU victims and for the deferred close of a retired session: those
- belong to another scope or to a call that has already ended, while the thread
- holding them is in the middle of serving a tool call on its own deadline and
- an unresponsive transport costs _SESSION_CLOSE_TIMEOUT to shut down.
-
- One worker rather than a thread per session: nobody is waiting on these, so
- closing them one at a time is fine, and a run of new chat scopes against a
- server that hangs on shutdown then cannot spawn threads without bound.
- close_mcp_sessions stays synchronous and drains this queue, because its caller
- (a server edit, or atexit) does need the teardown to have happened.
-
- Past _MAX_PENDING_CLOSES the overflow is closed on the caller instead. A queue
- that keeps growing means the server is shutting down slower than chats are
- opening, and every waiting session still holds its own loop thread and
- connection, so the queue has to be bounded as well as the cache. Making the
- caller wait is the backpressure that stops it: unpleasant, but the same thing
- that happened before any of this was deferred, and only once the deferral has
- already failed to keep up."""
+ Used for LRU victims and for the deferred close of a retired session: those belong to another
+ scope or to a call that has already ended, while the thread holding them is in the middle of
+ serving a tool call on its own deadline and an unresponsive transport costs
+ _SESSION_CLOSE_TIMEOUT to shut down.
+
+ One worker rather than a thread per session: nobody is waiting on these, so closing them one at
+ a time is fine, and a run of new chat scopes against a server that hangs on shutdown then cannot
+ spawn threads without bound. close_mcp_sessions stays synchronous and drains this queue, because
+ its caller (a server edit, or atexit) does need the teardown to have happened.
+
+ Past _MAX_PENDING_CLOSES the overflow is closed on the caller instead. A queue that keeps
+ growing means the server is shutting down slower than chats are opening, and every waiting
+ session still holds its own loop thread and connection, so the queue has to be bounded as well
+ as the cache. Making the caller wait is the backpressure that stops it: unpleasant, but the same
+ thing that happened before any of this was deferred, and only once the deferral has already
+ failed to keep up.
+ """
global _mcp_cleanup_worker
if not sessions:
return
@@ -1263,8 +1210,8 @@ def _cleanup_worker() -> None:
def _drain_cleanup_queue() -> tuple[list, Optional[threading.Thread]]:
- """Take back whatever the worker has not started on yet, plus the worker
- itself so the caller can wait out the one close already under way."""
+ """Take back whatever the worker has not started on yet, plus the worker itself so the caller
+ can wait out the one close already under way."""
with _mcp_cleanup_lock:
pending = list(_mcp_cleanup_queue)
_mcp_cleanup_queue.clear()
@@ -1278,30 +1225,27 @@ def _close_quietly(session) -> None:
logger.exception("Closing a discarded MCP session failed")
-# The cache stopped being stdio-only, but an in-place upgrade can leave a caller
-# holding the old name; it costs two lines to keep it working.
+# The cache stopped being stdio-only, but an in-place upgrade can leave a caller holding the old name; it costs two
+# lines to keep it working.
close_stdio_sessions = close_mcp_sessions
def _reset_after_fork() -> None:
- """Drop everything the child inherited from the parent's cache.
-
- Only the forking thread survives a fork, so every session's loop thread is
- gone while its client still reports connected. A child that checked one out
- would wait on a loop that will never run, and _transport_dead cannot see it
- for HTTP. Nothing here is closed: those objects belong to the parent, which
- is still using them."""
+ """Drop everything the child inherited from the parent's cache. Only the forking thread survives
+ a fork, so every session's loop thread is gone while its client still reports connected. A
+ child that checked one out would wait on a loop that will never run, and _transport_dead
+ cannot see it for HTTP. Nothing here is closed: those objects belong to the parent, which is
+ still using them."""
global _mcp_reaper_started, _mcp_connects_in_flight, _mcp_sessions_lock
global _mcp_cleanup_lock, _mcp_cleanup_worker
- # Replaced, not just cleared: a lock the fork caught held belongs to a thread
- # that no longer exists here, so the child would block on it forever.
+ # Replaced, not just cleared: a lock the fork caught held belongs to a thread that no longer exists here, so the
+ # child would block on it forever.
_mcp_sessions_lock = threading.Lock()
_mcp_sessions.clear()
_mcp_key_locks.clear()
_mcp_connects_in_flight = 0
_mcp_reaper_started = False
- # The cleanup worker did not survive the fork either, and its queue holds the
- # parent's sessions.
+ # The cleanup worker did not survive the fork either, and its queue holds the parent's sessions.
_mcp_cleanup_lock = threading.Lock()
_mcp_cleanup_queue.clear()
_mcp_cleanup_worker = None
@@ -1350,15 +1294,13 @@ async def list_tools_async(
return await asyncio.wait_for(_fetch(), timeout = timeout)
-# Discovered-tool cache, keyed by MCP server id. get_enabled_mcp_tools() probes a server only
-# on a cache miss, keeping MCP discovery off the chat send's critical path -- tool schemas are
-# stable within a session. The /refresh route warms it; a URL/header/OAuth change or a delete
-# evicts it. Successful probes are cached indefinitely.
+# Discovered-tool cache, keyed by MCP server id. get_enabled_mcp_tools() probes a server only on a cache miss, keeping
+# MCP discovery off the chat send's critical path -- tool schemas are stable within a session. The /refresh route
+# warms it; a URL/header/OAuth change or a delete evicts it. Successful probes are cached indefinitely.
_tool_cache: dict[str, list[dict]] = {}
-# server_id -> monotonic time before which a failed server must not be
-# re-probed (see record_probe_failure). Cleared on a successful probe or
-# eviction.
+# server_id -> monotonic time before which a failed server must not be re-probed (see record_probe_failure). Cleared
+# on a successful probe or eviction.
_probe_cooloff_until: dict[str, float] = {}
# Coordinate off-loop token-count snapshots with row and schema-cache mutations.
@@ -1383,9 +1325,8 @@ def serialize_mcp_server_mutation(handler):
return _serialized
-# MCP server fields whose change invalidates a server's discovered tools: the
-# endpoint/auth used to probe it (url, headers, oauth) or whether it's used at
-# all (is_enabled). A rename does not. The update route's eviction and
+# MCP server fields whose change invalidates a server's discovered tools: the endpoint/auth used to probe it (url,
+# headers, oauth) or whether it's used at all (is_enabled). A rename does not. The update route's eviction and
# get_enabled_mcp_tools' mid-probe guard both key off this so they can't drift.
TOOL_CACHE_INVALIDATING_FIELDS = frozenset({"url", "headers_json", "use_oauth", "is_enabled"})
@@ -1460,19 +1401,17 @@ _IMAGE_SUBTYPES = {
}
-# What tool-fallback.tsx may interpolate into data:<type>;base64,... : an RFC 9110
-# 8.3.1 token subtype, minus "*", which names a range and never a payload.
+# What tool-fallback.tsx may interpolate into data:<type>;base64,... : an RFC 9110 8.3.1 token subtype, minus "*",
+# which names a range and never a payload.
_MEDIA_TYPE = re.compile(r"^image/[a-z0-9][a-z0-9!#$%&'^_`|~.+-]*$")
def _uri_mime(uri: Any) -> Optional[str]:
- """Guess a media type from the part of a URI that names the resource.
-
- mimetypes only stopped reading the query and fragment in 3.11.9 / 3.12.3 / 3.13
- (CPython gh-117217), and on older supported interpreters 'gen.png?download=1'
- guessed nothing while 'download?name=gen.png' guessed image/png. Dropping both
- keeps every interpreter in agreement. The scheme stays so a data: URI still
- resolves; a bare host goes, since a host name is not a file name."""
+ """Guess a media type from the part of a URI that names the resource. mimetypes only stopped
+ reading the query and fragment in 3.11.9 / 3.12.3 / 3.13 (CPython gh-117217), and on older
+ supported interpreters 'gen.png?download=1' guessed nothing while 'download?name=gen.png'
+ guessed image/png. Dropping both keeps every interpreter in agreement. The scheme stays so a
+ data: URI still resolves; a bare host goes, since a host name is not a file name."""
split = urlsplit(str(uri))
cleaned = urlunsplit((split.scheme, split.netloc if split.path else "", split.path, "", ""))
return mimetypes.guess_type(cleaned, strict = False)[0]
@@ -1488,8 +1427,8 @@ def _image_mime(mime: Any) -> Optional[str]:
else:
subtype = essence[len("application/") :] if essence.startswith("application/") else ""
resolved = _IMAGE_SUBTYPES.get(subtype) or _uri_mime(f"file:///image.{subtype}")
- # one gate for every branch. Lowercased again because a registry answer carries the
- # host's spelling: Windows returns image/JXL for .jxl, Linux and macOS image/jxl.
+ # one gate for every branch. Lowercased again because a registry answer carries the host's spelling: Windows
+ # returns image/JXL for .jxl, Linux and macOS image/jxl.
resolved = resolved.lower() if resolved else ""
return resolved if _MEDIA_TYPE.match(resolved) else None
@@ -1567,8 +1506,8 @@ def _flatten_result(result: Any) -> str:
def _unwind_budget(unwind_timeout: float, timeout: Optional[float], elapsed: float) -> float:
- """How long a cancelled call may take to unwind: whatever is left of the
- caller's window, so the wait is never charged on top of an expired deadline."""
+ """How long a cancelled call may take to unwind: whatever is left of the caller's window, so the
+ wait is never charged on top of an expired deadline."""
if not unwind_timeout:
return 0.0
if timeout is None:
@@ -1582,10 +1521,10 @@ async def _race_tool_call(
cancel_event,
unwind_timeout: float = 0.0,
) -> Any:
- """Await ``call_coro`` under ``timeout``, polling ``cancel_event`` so a
- /cancel POST interrupts even mid-network-read. ``unwind_timeout`` waits up to
- that long for a cancelled call to finish unwinding; only callers that hand the
- client back to a cache need it (one-shot clients are discarded anyway)."""
+ """Await ``call_coro`` under ``timeout``, polling ``cancel_event`` so a /cancel POST interrupts
+ even mid-network-read. ``unwind_timeout`` waits up to that long for a cancelled call to
+ finish unwinding; only callers that hand the client back to a cache need it (one-shot clients
+ are discarded anyway)."""
async def _watch_cancel() -> None:
while cancel_event is not None and not cancel_event.is_set():
@@ -1609,8 +1548,8 @@ async def _race_tool_call(
for t in (call_task, watch_task):
if not t.done():
t.cancel()
- # Let a cancelled call unwind before its session is reused, out of the
- # caller's remaining budget. Outlasting it just leaves the session dirty.
+ # Let a cancelled call unwind before its session is reused, out of the caller's remaining budget. Outlasting
+ # it just leaves the session dirty.
left = _unwind_budget(unwind_timeout, timeout, time.monotonic() - started)
if left:
await asyncio.wait({call_task, watch_task}, timeout = left)
@@ -1634,18 +1573,16 @@ def _call_session_tool(
) -> Any:
if cancel_event is not None and cancel_event.is_set():
raise _MCPCancelled
- # One deadline covers the key-lock wait, connect, call-lock wait, and the
- # call itself, matching the one-shot path where the caller's timeout wrapped
- # connect plus call in a single window.
+ # One deadline covers the key-lock wait, connect, call-lock wait, and the call itself, matching the one-shot path
+ # where the caller's timeout wrapped connect plus call in a single window.
deadline = None if timeout is None else time.monotonic() + timeout
def _remaining() -> Optional[float]:
return None if deadline is None else max(0.0, deadline - time.monotonic())
- # Callers without an Unsloth session id must retain the former one-shot
- # behavior: no browser/cookie/tool state can leak into another request.
- # Use an ephemeral key (and close it below) rather than the shared empty
- # scope that the persistent-session cache used previously.
+ # Callers without an Unsloth session id must retain the former one-shot behavior: no browser/cookie/tool state can
+ # leak into another request. Use an ephemeral key (and close it below) rather than the shared empty scope that the
+ # persistent-session cache used previously.
def _config_ok() -> bool:
if config_check is None:
return True
@@ -1658,18 +1595,17 @@ def _call_session_tool(
if ephemeral:
scope = f"request-{uuid.uuid4().hex}"
key = _session_key(url, headers, scope)
- # attempt 0 may find the cached session stale/dead *before* dispatch and
- # reconnect once (safe); attempt 1 is a freshly connected session.
+ # attempt 0 may find the cached session stale/dead *before* dispatch and reconnect once (safe); attempt 1 is a
+ # freshly connected session.
for attempt in (0, 1):
session, idle_for = _get_session(
url, headers, scope, deadline, cancel_event, config_check, use_oauth
)
locked = False
try:
- # Serialize calls per session where the transport demands it:
- # overlapping same-scope calls must not interleave operations on one
- # stateful stdio server (browser, REPL). HTTP multiplexes by request
- # id, so its calls run in parallel as they did one-shot.
+ # Serialize calls per session where the transport demands it: overlapping same-scope calls must not
+ # interleave operations on one stateful stdio server (browser, REPL). HTTP multiplexes by request id, so
+ # its calls run in parallel as they did one-shot.
if session.serialize_calls:
while not session.call_lock.acquire(timeout = 0.05):
if cancel_event is not None and cancel_event.is_set():
@@ -1687,16 +1623,16 @@ def _call_session_tool(
discard_session = ephemeral
retry = False
try:
- # We may have waited on the call lock while another caller's timeout retired this
- # session, a server update/delete invalidated it, or a reused subprocess died. Re-check
- # all three before dispatch so we never run on a retired/dead client or a stale config.
+ # We may have waited on the call lock while another caller's timeout retired this session, a server
+ # update/delete invalidated it, or a reused subprocess died. Re-check all three before dispatch so we
+ # never run on a retired/dead client or a stale config.
if session.closed.is_set():
# Intentional close (server update/delete/shutdown): don't retry on stale config.
discard_session = True
raise RuntimeError("MCP server was updated or removed during the call")
elif session.defunct:
- # A concurrent same-scope caller's timeout retired this session;
- # move to a fresh one instead of reusing the retired client.
+ # A concurrent same-scope caller's timeout retired this session; move to a fresh one instead of
+ # reusing the retired client.
discard_session = True
if attempt == 0:
retry = True
@@ -1717,9 +1653,8 @@ def _call_session_tool(
) and not _session_responsive(
session, _remaining(), cancel_event, timeout_is_fatal = session.dirty
):
- # Dirty: still stuck on the abandoned call. Idle HTTP: the server
- # may have expired the session while nothing was using it, and no
- # HTTP transport lets us ask. Either way it failed to answer, so
+ # Dirty: still stuck on the abandoned call. Idle HTTP: the server may have expired the session while
+ # nothing was using it, and no HTTP transport lets us ask. Either way it failed to answer, so
# reconnect BEFORE dispatch rather than losing the user's call.
discard_session = True
if attempt == 0:
@@ -1737,51 +1672,46 @@ def _call_session_tool(
0.0 if ephemeral else _CANCEL_UNWIND_TIMEOUT,
)
out = session.run(coro, rem)
- # A completed round trip proves the transport better than any
- # probe could, so it resets the idle clock the recheck reads.
+ # A completed round trip proves the transport better than any probe could, so it resets the idle clock
+ # the recheck reads.
session.proved_at = time.monotonic()
return out
except (_MCPCancelled, asyncio.TimeoutError):
- # Keep the session so a Stop doesn't destroy the server's state; the
- # SDK drops the abandoned reply, and reuse is gated on a live probe.
+ # Keep the session so a Stop doesn't destroy the server's state; the SDK drops the abandoned reply, and
+ # reuse is gated on a live probe.
session.dirty = True
raise
except _SessionWedged:
discard_session = True
raise asyncio.TimeoutError
except _SessionClosed:
- # close_mcp_sessions() shut this session mid-call (server
- # update/delete/shutdown); don't retry on the stale config.
+ # close_mcp_sessions() shut this session mid-call (server update/delete/shutdown); don't retry on the
+ # stale config.
discard_session = True
raise RuntimeError("MCP server was updated or removed during the call")
except Exception as exc:
if session.closed.is_set():
- # An intentional close (server update/delete) can surface as a plain transport
- # error or AttributeError instead of _SessionClosed; don't mistake it for a crash.
+ # An intentional close (server update/delete) can surface as a plain transport error or AttributeError
+ # instead of _SessionClosed; don't mistake it for a crash.
discard_session = True
raise RuntimeError("MCP server was updated or removed during the call")
- # A ToolError or a JSON-RPC error response means the server answered,
- # so the transport is alive -> keep the session and its state.
- # Anything else is transport-level (dead subprocess, broken pipe,
- # dropped HTTP stream): evict so it can't poison the scope, but DO
- # NOT replay (the tool may already have run); the next call opens a
- # fresh session.
+ # A ToolError or a JSON-RPC error response means the server answered, so the transport is alive: keep the
+ # session and its state. Anything else is transport-level (dead subprocess, broken pipe, dropped HTTP
+ # stream): evict so it can't poison the scope, but DO NOT replay (the tool may already have run); the next
+ # call opens a fresh session.
if _is_protocol_error(exc):
- # The server replied, so the transport is fine and the session's
- # state is worth keeping. Probe it before the next call anyway,
- # in case the error was the server telling us the session is no
- # longer one it recognises.
+ # The server replied, so the transport is fine and the session's state is worth keeping. Probe it
+ # before the next call anyway, in case the error was the server telling us the session is no longer
+ # one it recognises.
session.dirty = True
elif not _is_tool_error(exc):
discard_session = True
raise
finally:
- # Remove from the cache and mark defunct BEFORE giving up the borrow,
- # so no other caller can check this session out after it failed. The
- # order matters more now that HTTP callers do not queue on call_lock:
- # released first, a concurrent same-scope call could check out the
- # broken transport while it was still cached, and _release_session can
- # sit closing LRU victims for seconds first. in_flight is still held
+ # Remove from the cache and mark defunct BEFORE giving up the borrow, so no other caller can check this
+ # session out after it failed. The order matters more now that HTTP callers do not queue on call_lock:
+ # released first, a concurrent same-scope call could check out the broken transport while it was still
+ # cached, and _release_session can sit closing LRU victims for seconds first. in_flight is still held
# here, so the close defers to the release below.
if discard_session:
_drop_session(key, session)
@@ -1804,31 +1734,27 @@ def call_tool_sync(
scope: Optional[str] = None,
config_check = None,
) -> str:
- """Call one MCP tool and return its flattened text/image result.
-
- Never raises: every failure comes back as an "Error: ..." string for the model.
-
- Which transport path runs depends on ``scope`` (an opaque per-chat key) and
- ``use_oauth``:
-
- * stdio always goes through the session machinery. Without a scope it still
- gets a private ephemeral session that is closed afterwards, so no browser
- or cookie state leaks between requests.
- * HTTP reuses a cached session only when it has a scope AND OAuth is off, so
- a server that keeps state between calls keeps it for the whole chat.
- * OAuth HTTP, and HTTP without a scope, connect once and disconnect, exactly
- as before sessions were shared. Refreshing a token on a long-lived shared
- connection is not something this code can do safely yet.
-
- ``timeout`` is one budget covering connect and call together. ``cancel_event``
- aborts an in-flight call. ``config_check`` re-reads the server row so a call
- that raced an edit or delete cannot dispatch on the stale configuration."""
+ """Call one MCP tool and return its flattened text/image result. Never raises: every failure comes
+ back as an "Error: ..." string for the model.
+
+ Which transport path runs depends on ``scope`` (an opaque per-chat key) and ``use_oauth``. stdio
+ always goes through the session machinery, and without a scope it still gets a private ephemeral
+ session that is closed afterwards, so no browser or cookie state leaks between requests. HTTP
+ reuses a cached session only when it has a scope AND OAuth is off, so a server that keeps state
+ between calls keeps it for the whole chat. OAuth HTTP, and HTTP without a scope, connect once
+ and disconnect, exactly as before sessions were shared: refreshing a token on a long-lived
+ shared connection is not something this code can do safely yet.
+
+ ``timeout`` is one budget covering connect and call together. ``cancel_event`` aborts an
+ in-flight call. ``config_check`` re-reads the server row so a call that raced an edit or delete
+ cannot dispatch on the stale configuration.
+ """
async def _one_shot() -> Any:
async with _client(url, headers, use_oauth) as client:
- # raise_on_error=False lets an is_error result (which may still carry
- # image content) reach _flatten_result instead of FastMCP raising ToolError
- # and dropping the images. Transport failures still raise (handled below).
+ # raise_on_error=False lets an is_error result (which may still carry image content) reach _flatten_result
+ # instead of FastMCP raising ToolError and dropping the images. Transport failures still raise (handled
+ # below).
return await client.call_tool(name, args, raise_on_error = False)
try:
@@ -1841,8 +1767,8 @@ def call_tool_sync(
except _MCPCancelled:
return f"Error: MCP tool '{name}' cancelled"
except _ConnectTimeout as exc:
- # Report the window that actually expired: for stdio that is the
- # cold-start cap, not the (larger) caller timeout.
+ # Report the window that actually expired: for stdio that is the cold-start cap, not the (larger) caller
+ # timeout.
suffix = f" after {round(exc.window, 1):g}s" if exc.window is not None else ""
return f"Error: MCP tool '{name}' timed out connecting{suffix}"
except asyncio.TimeoutError:
diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.py
index 49b9aeee31d..ff84f967903 100644
--- a/studio/backend/core/inference/media_auto_switch.py
+++ b/studio/backend/core/inference/media_auto_switch.py
@@ -345,8 +345,7 @@ async def _gated_start_load(
openai_errors = openai_errors,
hf_token = hf_token,
)
- # capped, in its own task: a first-run native install runs for minutes before begin_load
- # given its own task and waited on with a cap: a first-run native install runs for minutes before
+ # Given its own task and waited on with a cap: a first-run native install runs for minutes before
# begin_load, and holding both media gates and chat's that long blocks every unrelated request. On expiry
# the load keeps going without them.
setup = asyncio.ensure_future(_start_load(owner, pick, current_subject, hf_token))
diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.py
index 965007d7085..c6db9ae1038 100644
--- a/studio/backend/core/inference/media_keepwarm.py
+++ b/studio/backend/core/inference/media_keepwarm.py
@@ -48,11 +48,9 @@ class _Tracker:
self._last_active = time.monotonic()
# The model identity the last tick saw, so a fresh load counts as activity.
self.seen: Any = None
- # so the tick that sees work end can start the TTL there rather than at the last busy poll
# Whether the last tick found work in flight, so the tick that sees it end can start the TTL there rather than
# at the last busy poll.
self.was_busy = False
- # terminal record of the last finished job
# The terminal record of the last finished background job this tracker has seen, so a job no poll ever sampled
# as busy still dates the TTL from its completion.
self.completed: Any = None
@@ -226,9 +224,8 @@ async def admission_gate(owner: str):
@contextlib.asynccontextmanager
async def _gate(tracker: _Tracker):
- # polled non-blocking acquire, like llama_keepwarm's
- # Polled non-blocking acquire, exactly like llama_keepwarm's: it keeps the wait off this loop AND cancellation-safe,
- # since a cancel lands during the sleep with the gate free.
+ # Polled non-blocking acquire, exactly like llama_keepwarm's: it keeps the wait off this loop AND
+ # cancellation-safe, since a cancel lands during the sleep with the gate free.
while not tracker.gate.acquire(blocking = False):
await asyncio.sleep(0.02)
try:
@@ -314,11 +311,10 @@ def _probe(backend: Any) -> tuple[bool, Optional[tuple[Any, ...]]]:
return loading or bool(progress.get("active")), _completed_token(progress)
-# the repo id is not enough: MiniMax-H3 stages a different denoiser per h3_task and quants are picked per load.
# What makes one resident build different from another. The repo id is not enough: MiniMax-H3 stages a different
# denoiser per h3_task, so a cached fl2va -> ref2va reload is a new build under the same id, and the quants are picked
-# per load too. Only fields fixed at load time, so nothing that moves under a resident model (a Speed=Auto compile flips
-# speed_optims mid-life) can be mistaken for a reload and keep it warm forever.
+# per load too. Only fields fixed at load time, so nothing that moves under a resident model (a Speed=Auto compile
+# flips speed_optims mid-life) can be mistaken for a reload and keep it warm forever.
_IDENTITY_FIELDS = (
"repo_id",
"base_repo",
@@ -357,11 +353,9 @@ async def _tick(tracker: _Tracker, ttl: float) -> None:
tracker.was_busy = True
return
if tracker.was_busy or finished:
- # a video generation outlives its POST, so dating the TTL from the last busy poll would spend up to one poll
- # interval of the user's keep-warm window before the model was even free
# The work ended between two ticks. A video generation outlives its POST, so the only activity it stamps
- # after that is the busy polls, and dating the TTL from the last of those spends up to one poll interval of
- # the keep-warm window the user configured before the model was even free. Start it here instead.
+ # after that is the busy polls, and dating the TTL from the last of those spends up to one poll interval
+ # of the keep-warm window the user configured before the model was even free. Start it here instead.
tracker.was_busy = False
tracker.seen = identity
tracker.note_activity()
diff --git a/studio/backend/core/inference/media_locality.py b/studio/backend/core/inference/media_locality.py
index 0529178b0b4..3c32b493d9f 100644
--- a/studio/backend/core/inference/media_locality.py
+++ b/studio/backend/core/inference/media_locality.py
@@ -299,7 +299,6 @@ def _pipeline_components_present(root: Path) -> bool:
# [null, null] marks a component this pipeline deliberately ships without.
if len(entry) not in (2, 3) or not entry[1]:
continue
- # a modular entry is [library, class, spec]
# a modular entry is [library, class, spec], and its spec can name another repo, which this directory is
# never expected to hold but the load still pulls
hosted = _hosted_source(entry[2]) if len(entry) == 3 else None
@@ -344,9 +343,8 @@ def _cached_snapshot_root(repo_id: str, revision: str = "") -> Optional[Path]:
repo_dir = Path(hub_cache_dir()) / f"models--{repo_id.replace('/', '--')}"
snapshots = repo_dir / "snapshots"
- # a pinned revision is the only candidate: falling back to main is how the default snapshot approves a pin
- # a pinned revision is a commit sha, or a branch or tag the cache records under refs/, and it is the only candidate:
- # falling back to main is how the default snapshot approves a pin
+ # a pinned revision is a commit sha, or a branch or tag the cache records under refs/, and it is the only
+ # candidate: falling back to main is how the default snapshot approves a pin
for candidate in [revision] if revision else ["main"]:
pinned = snapshots / candidate
if pinned.is_dir():
@@ -383,7 +381,6 @@ def _hosted_component_cached(source: str, subfolder: str, revision: str, variant
snapshot = _cached_snapshot_root(source, revision)
if snapshot is None:
return False
- # _upstream_is_cached's no-manifest branch is satisfied by a single weight file
# the same component rules either way: _upstream_is_cached's no-manifest branch is satisfied by a single weight
# file, which an interrupted sharded pull leaves behind
return _component_present(snapshot / subfolder if subfolder else snapshot, variant)
@@ -426,9 +423,8 @@ def _component_present(component: Path, variant: str = "") -> bool:
# *_config.json instead and ship no weights at all
if (component / "config.json").is_file():
return any(entry.suffix.lower() in _WEIGHT_SUFFIXES for entry in files)
- # a tokenizer ships no weights but is useless without its vocabulary
- # a tokenizer ships no weights but is still useless without its vocabulary, and which file that is varies by class,
- # so any one of the known spellings answers for all of them
+ # a tokenizer ships no weights but is still useless without its vocabulary, and which file that is varies by
+ # class, so any one of the known spellings answers for all of them
if (component / "tokenizer_config.json").is_file():
return any((component / name).is_file() for name in _TOKENIZER_ASSETS)
# a metadata-only component is its config: a scheduler or processor directory holding anything else at all (a stray
@@ -508,7 +504,6 @@ def missing_download_bytes(
model_kind = target.model_kind,
gpu_ordinal = ordinal,
hf_token = hf_token,
- # only the verdict, not the probe: this must count the SAME files the load will fetch
# Only the verdict, not the probe: this asks whether the pick is already on disk, so it must count the
# SAME files the load will fetch. Clearing the probe drops the pre-cast encoder and the GGUF
# dense-transformer widening, which is how a "fully downloaded" answer goes wrong.
diff --git a/studio/backend/core/inference/media_model_index.py b/studio/backend/core/inference/media_model_index.py
index 090d2fdc633..d8ce2631c6d 100644
--- a/studio/backend/core/inference/media_model_index.py
+++ b/studio/backend/core/inference/media_model_index.py
@@ -53,9 +53,6 @@ class MediaModelPick:
_AMBIGUOUS = MediaModelPick("", "")
-# ── resolving a name to a downloaded model ──────────────────────────
-
-
def _resolve_load_dir(p: Path) -> Path:
"""The directory holding the weights, unwrapping an HF cache repo to its snapshot.
@@ -368,9 +365,6 @@ def available_media_model_ids(task: str) -> list[str]:
)
-# ── recognising the resident model ──────────────────────────────────
-
-
def published_token(pick: MediaModelPick) -> str:
"""The ``gguf_variant`` the backend will publish once *pick* is loaded, lowercased."""
from hub.utils.gguf import extract_quant_token
diff --git a/studio/backend/core/inference/message_content.py b/studio/backend/core/inference/message_content.py
index cfd989702fe..f9bd61fd810 100644
--- a/studio/backend/core/inference/message_content.py
+++ b/studio/backend/core/inference/message_content.py
@@ -12,7 +12,6 @@ from __future__ import annotations
from typing import Any
-# a paste-only turn carries no `content` text: the composer wraps long pastes in this tag
# The composer sends a long paste as a text attachment wrapped in this tag, so a paste-only turn carries no `content`
# text at all.
_PASTED_TEXT_OPEN = "<pasted_text name="
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 72dad6c5b67..71b029a35e5 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -1,9 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
-"""MLX inference backend for Apple Silicon.
-
-Drop-in replacement for InferenceBackend — same interface, uses mlx-lm/mlx-vlm
-instead of torch/transformers for model loading and generation.
-"""
+"""MLX inference backend for Apple Silicon. Drop-in replacement for InferenceBackend, same
+interface, using mlx-lm/mlx-vlm instead of torch/transformers for model loading and generation."""
import copy
import hashlib
@@ -47,10 +44,10 @@ from loggers import get_logger
logger = get_logger(__name__)
-# Prefix reuse for mlx-vlm generation, owned by Studio. A forward is not shape-invariant,
-# so a reused turn answers as an unreused one only when both chunk the same rows: every
-# request prefills on one grid and snapshots where a chunk of it ends, counting forwards.
-# Driven through public kwargs only: prompt_cache, prompt_cache_state, prefill_step_size.
+# Prefix reuse for mlx-vlm generation, owned by Studio. A forward is not shape-invariant, so a reused turn answers as
+# an unreused one only when both chunk the same rows: every request prefills on one grid and snapshots where a chunk
+# of it ends, counting forwards. Driven through public kwargs only: prompt_cache, prompt_cache_state,
+# prefill_step_size.
# The grid the boundary sits on: a prompt shorter than the step has no boundary at all.
VLM_PROMPT_CACHE_PREFILL_STEP = 256
@@ -72,10 +69,10 @@ def _is_cache(value):
def _is_opaque_cache(value):
- """A cache whose fields this cannot reach: it carries ``state`` but keeps its
- attributes somewhere ``vars`` does not see, as a ``__slots__`` layout does. Every
- class mlx-vlm ships today is an ordinary one; a future one that is not must stop
- the copy rather than be handed back as itself, which would share it."""
+ """A cache whose fields this cannot reach: it carries ``state`` but keeps its attributes
+ somewhere ``vars`` does not see, as a ``__slots__`` layout does. Every class mlx-vlm ships
+ today is an ordinary one; a future one that is not must stop the copy rather than be handed
+ back as itself, which would share it."""
return not hasattr(value, "__dict__") and hasattr(type(value), "state")
@@ -186,9 +183,9 @@ def _chunk_rows(args, kwargs):
def _place_per_layer_inputs(kwargs, rows, start):
- """Slice ``per_layer_inputs`` to this forward's own rows: mlx-vlm computes it for
- the whole uncached prompt and the model slices it at an offset a resume shifts. A
- single-token forward gets none and computes its own, as the reference model does."""
+ """Slice ``per_layer_inputs`` to this forward's own rows: mlx-vlm computes it for the whole
+ uncached prompt and the model slices it at an offset a resume shifts. A single-token forward
+ gets none and computes its own, as the reference model does."""
inputs = kwargs.get("per_layer_inputs")
shape = getattr(inputs, "shape", None)
if not shape:
@@ -214,9 +211,9 @@ _RECORDING_CLASSES = {}
def _prompt_wide_position_ids(args, kwargs):
- """Whether ``position_ids`` spans more than the chunk being fed: mlx-vlm primes
- mRoPE prompt-wide and not every family slices the kwarg (glm4v feeds it through
- as is), so a prompt-wide one is withheld for the model's own primed state."""
+ """Whether ``position_ids`` spans more than the chunk being fed: mlx-vlm primes mRoPE
+ prompt-wide and not every family slices the kwarg (glm4v feeds it through as is), so a
+ prompt-wide one is withheld for the model's own primed state."""
shape = getattr(kwargs.get("position_ids"), "shape", None)
if not shape:
return False
@@ -248,8 +245,8 @@ def _recording_class(base):
_place_per_layer_inputs(
kwargs, _chunk_rows(args, kwargs), (offset or 0) - record.resume_offset
)
- # As the next forward begins, not as the boundary one returns: generate_step
- # converts the cache between the two (KV quantization).
+ # As the next forward begins, not as the boundary one returns: generate_step converts the cache between the
+ # two (KV quantization).
if (
record is not None
and record.capture_at
@@ -271,8 +268,8 @@ def _recording_class(base):
def _offset_aware_policy(host):
- """``chunked_prefill_policy`` of ``host`` fed only the token types past the
- cache: with the vision block already there, the suffix is text and may chunk."""
+ """``chunked_prefill_policy`` of ``host`` fed only the token types past the cache: with the
+ vision block already there, the suffix is text and may chunk."""
base_policy = type(host).chunked_prefill_policy
def policy(
@@ -384,12 +381,12 @@ class VLMPromptSnapshotStore:
class VLMPromptCacheSession:
- """The ``prompt_cache_state`` one generation hands to mlx-vlm: ``find_prefix_length``
- picks the snapshot to resume from, swaps ``cache`` to it and arms the capture, and
- ``finish`` stores it. ``releases_unserved`` frees the rest, the headroom a media pass
- needs. A ``media_block`` prefills the rows through the last vision token for models
- that cannot chunk them, becoming the grid's origin, and ``policy_hosts`` are the
- models whose ``chunked_prefill_policy`` would then refuse to chunk the suffix."""
+ """The ``prompt_cache_state`` one generation hands to mlx-vlm: ``find_prefix_length`` picks the
+ snapshot to resume from, swaps ``cache`` to it and arms the capture, and ``finish`` stores
+ it. ``releases_unserved`` frees the rest, the headroom a media pass needs. A ``media_block``
+ prefills the rows through the last vision token for models that cannot chunk them, becoming
+ the grid's origin, and ``policy_hosts`` are the models whose ``chunked_prefill_policy`` would
+ then refuse to chunk the suffix."""
def __init__(
self,
@@ -430,8 +427,8 @@ class VLMPromptCacheSession:
def __exit__(self, *exc):
try:
for host in self._patched_hosts:
- # policy_hosts is (model, language_model), which name one object twice when
- # the wrapper exposes none, so unpatch idempotently rather than del twice.
+ # policy_hosts is (model, language_model), which name one object twice when the wrapper exposes none,
+ # so unpatch idempotently rather than del twice.
host.__dict__.pop("chunked_prefill_policy", None)
finally:
# The class goes back regardless: one left wrapped serves every later request.
@@ -501,8 +498,8 @@ class VLMPromptCacheSession:
self._store.store(self._key, prefix_ids, copy)
def update(self, _token_ids, _cache):
- """mlx-vlm's after-generation hook; ``finish`` stores, as it also runs on a
- consumer that stops reading early."""
+ """mlx-vlm's after-generation hook; ``finish`` stores, as it also runs on a consumer that
+ stops reading early."""
def finish(self):
snapshot = self._forward.record.snapshot
@@ -581,8 +578,8 @@ def _temporary_mlx_adapter_state(model, use_adapter):
def _mlx_vlm_model_config(model):
- """Return the loaded MLX model config and its type, preferring whichever of
- config / _config actually carries a model_type."""
+ """Return the loaded MLX model config and its type, preferring whichever of config / _config
+ actually carries a model_type."""
def _model_type(cfg):
return cfg.get("model_type") if isinstance(cfg, dict) else getattr(cfg, "model_type", None)
@@ -599,8 +596,8 @@ def _mlx_vlm_model_config(model):
return (configs[0] if configs else None), None
-# Matched on the context-bearing term, not a field list: mlx-lm alone spells it four ways.
-# max_length is a generation default and n_sequences a batch count, so neither qualifies.
+# Matched on the context-bearing term, not a field list: mlx-lm alone spells it four ways. max_length is a generation
+# default and n_sequences a batch count, so neither qualifies.
_MLX_CONTEXT_KEY = re.compile(
r"(?:position(?:s|_embeddings)|(?:^|_)ctx|context_len(?:gth)?"
r"|seq(?:uence)?_len(?:gth)?|model_max_length)$"
@@ -647,12 +644,10 @@ def _positive_int(value):
def mlx_native_context_length(model):
- """The window the model was trained for, or None when it isn't readable.
-
- The widest plausible length across every config wins, so a stub text config the
- blocks were never built from cannot shorten the window the weights support --
- mlx-vlm's Phi-3-V carries a 4096 text config beside the 131072 its attention uses.
- """
+ """The window the model was trained for, or None when it isn't readable. The widest plausible
+ length across every config wins, so a stub text config the blocks were never built from
+ cannot shorten the window the weights support -- mlx-vlm's Phi-3-V carries a 4096 text config
+ beside the 131072 its attention uses."""
lengths = []
for cfg in _mlx_config_candidates(model):
try:
@@ -671,8 +666,8 @@ def mlx_native_context_length(model):
def _ascii_registry_key(value):
- """An mlx-vlm registry key lowered within ASCII, else None. Not `casefold`:
- it folds non-ASCII onto ASCII, so "ſmolvlm" would reach `smolvlm`."""
+ """An mlx-vlm registry key lowered within ASCII, else None. Not `casefold`: it folds non-ASCII
+ onto ASCII, so "ſmolvlm" would reach `smolvlm`."""
if not isinstance(value, str) or not value.isascii():
return None
return value.lower()
@@ -686,13 +681,11 @@ def _render_registered_vlm_prompt(
num_audios = 0,
continue_final_message = False,
):
- """Render through mlx-vlm when it declares a formatter for this model.
-
- With *continue_final_message* the trailing assistant turn is dropped from the render
- and appended as text, resuming the partial rather than opening a fresh turn. That text
- comes from the SWEPT messages: a raw partial could close the turn or open another
- role instead of resuming (#7066).
- """
+ """Render through mlx-vlm when it declares a formatter for this model. With
+ *continue_final_message* the trailing assistant turn is dropped from the render and appended
+ as text, resuming the partial rather than opening a fresh turn. That text comes from the
+ SWEPT messages: a raw partial could close the turn or open another role instead of resuming
+ (#7066)."""
from mlx_vlm import prompt_utils
config, model_type = _mlx_vlm_model_config(model)
@@ -700,8 +693,8 @@ def _render_registered_vlm_prompt(
return None
model_config = getattr(prompt_utils, "MODEL_CONFIG", {})
if model_type not in model_config:
- # Registry keys are ASCII, so fold in ASCII: casefold would route
- # "ſmolvlm" into the unrelated `smolvlm` renderer.
+ # Registry keys are ASCII, so fold in ASCII: casefold would route "ſmolvlm" into the unrelated `smolvlm`
+ # renderer.
folded = _ascii_registry_key(model_type)
matches = (
[
@@ -716,9 +709,8 @@ def _render_registered_vlm_prompt(
if len(matches) != 1:
return None
canonical = matches[0]
- # Preserve the checkpoint's config object. The prompt helper only needs
- # its own canonical routing key, and mutating the loaded model would make
- # later capability and export logic observe a value it never published.
+ # Preserve the checkpoint's config object. The prompt helper only needs its own canonical routing key, and
+ # mutating the loaded model would make later capability and export logic observe a value it never published.
config = dict(config) if isinstance(config, dict) else dict(config.__dict__)
config["model_type"] = canonical
@@ -755,32 +747,24 @@ def _classify_mlx_audio_type(
is_vision,
config_audio_type = None,
):
- """audio_type for the model entry: "audio_vlm" (omni audio input; is_audio
- stays False — it means TTS and redirects in the chat route) or None.
-
- The checkpoint's own capability comes from unsloth_zoo, which answers it by
- observing whether audio content changes what the processor returns. Two
- things stay here because they are this backend's, not the checkpoint's: the
- waveform arrives at the rate the chat route decodes to, and the prompt is
- rendered through mlx-vlm's registry, where some families accept an audio
- count and silently drop it. The rendered prompt is what the capability call
- probes with, so a family whose marker only its own template emits is judged
- on the real thing.
-
- This probe speaks for "audio_vlm" and nothing else, so `config_audio_type`
- (the pre-load answer from detect_audio_type) is carried through untouched
- whenever the probe has no standing:
-
- * a non-vision checkpoint is never asked, so a TTS codec ("snac", "dac",
- "bicodec", "csm") or Whisper keeps the classification it arrived with —
- the worker mirrors this entry over the pre-load config, so returning a
- bare None here would silently strip the chat route's TTS redirect;
- * a probe that could not run (absent or older unsloth_zoo, a raising or
- unrecognised capability result) leaves the pre-load answer standing
- rather than downgrading a model on the strength of a missing
- dependency.
-
- Only a probe that actually ran and answered may retract "audio_vlm".
+ """audio_type for the model entry: "audio_vlm" (omni audio input; is_audio stays False, since it
+ means TTS and redirects in the chat route) or None.
+
+ The checkpoint's own capability comes from unsloth_zoo, which answers it by observing whether
+ audio content changes what the processor returns. Two things stay here because they are this
+ backend's, not the checkpoint's: the waveform arrives at the rate the chat route decodes to, and
+ the prompt is rendered through mlx-vlm's registry, where some families accept an audio count and
+ silently drop it. The rendered prompt is what the capability call probes with, so a family whose
+ marker only its own template emits is judged on the real thing.
+
+ This probe speaks for "audio_vlm" and nothing else, so ``config_audio_type`` (the pre-load
+ answer from detect_audio_type) is carried through untouched whenever the probe has no standing:
+ a non-vision checkpoint is never asked, so a TTS codec ("snac", "dac", "bicodec", "csm") or
+ Whisper keeps the classification it arrived with (the worker mirrors this entry over the
+ pre-load config, so returning a bare None would silently strip the chat route's TTS redirect);
+ and a probe that could not run (absent or older unsloth_zoo, a raising or unrecognised
+ capability result) leaves the pre-load answer standing rather than downgrading a model over a
+ missing dependency. Only a probe that actually ran and answered may retract "audio_vlm".
"""
def _probe_says_no():
@@ -789,8 +773,8 @@ def _classify_mlx_audio_type(
if not is_vision or processor is None:
return config_audio_type
- # All of it inside the guard: a model load must never fail on a probe.
- # BaseException because any escape here aborts the load.
+ # All of it inside the guard: a model load must never fail on a probe. BaseException because any escape here
+ # aborts the load.
try:
from unsloth_zoo.mlx.utils import (
audio_extractor_sampling_rate,
@@ -829,12 +813,10 @@ def _classify_mlx_audio_type(
def _mlx_config_field(model, name):
- """Read a config field in either shape a loaded MLX model exposes it in.
-
- A checkpoint's config is a dict on some models and an object on others, under
- ``config`` or ``_config`` -- the same spread ``_mlx_vlm_model_config`` walks to
- find a model_type. A getattr-only read silently misses the dict half.
- """
+ """Read a config field in either shape a loaded MLX model exposes it in. A checkpoint's config
+ is a dict on some models and an object on others, under ``config`` or ``_config`` -- the same
+ spread ``_mlx_vlm_model_config`` walks to find a model_type. A getattr-only read silently
+ misses the dict half."""
for cfg in (getattr(model, "config", None), getattr(model, "_config", None)):
value = cfg.get(name) if isinstance(cfg, dict) else getattr(cfg, name, None)
if value is not None:
@@ -843,14 +825,10 @@ def _mlx_config_field(model, name):
def _mlx_stop_token_ids(tokenizer, model = None):
- """Ids the runtime actually stops on, as a tuple.
-
- Prefer the stopping criteria mlx_vlm consults, then the model config that
- seeds them, before the tokenizer attribute: they disagree on some repos
- (Kimi-VL lists two config ids and a different tokenizer id), and picking the
- wrong source misreads a real stop as truncation. Each source may be a bare
- int or a collection.
- """
+ """Ids the runtime actually stops on, as a tuple. Prefer the stopping criteria mlx_vlm consults,
+ then the model config that seeds them, before the tokenizer attribute: they disagree on some
+ repos (Kimi-VL lists two config ids and a different tokenizer id), and picking the wrong
+ source misreads a real stop as truncation. Each source may be a bare int or a collection."""
for source in (
getattr(getattr(tokenizer, "stopping_criteria", None), "eos_token_ids", None),
_mlx_config_field(model, "eos_token_id"),
@@ -860,9 +838,8 @@ def _mlx_stop_token_ids(tokenizer, model = None):
if source is None:
continue
if isinstance(source, (list, tuple, set, frozenset)):
- # An empty collection falls through too: a source present but unset is
- # not an answer, and stopping on nothing misreads a real stop as
- # truncation. A bare id is kept as-is, since 0 is a valid token.
+ # An empty collection falls through too: a source present but unset is not an answer, and stopping on
+ # nothing misreads a real stop as truncation. A bare id is kept as-is, since 0 is a valid token.
if not source:
continue
return tuple(source)
@@ -872,28 +849,21 @@ def _mlx_stop_token_ids(tokenizer, model = None):
def _mlx_stop_sequences(stop):
- """The sequences a request asked to stop on, as a list.
-
- An empty one is dropped rather than matched: it is found at position 0 of
- every reply and would end each turn before its first token.
- """
+ """The sequences a request asked to stop on, as a list. An empty one is dropped rather than
+ matched: it is found at position 0 of every reply and would end each turn before its first
+ token."""
return [x for x in ([stop] if isinstance(stop, str) else stop or []) if x]
def _mlx_stop_cut(text: str, stops) -> tuple[int, bool]:
- """How much of a cumulative reply may be shown, and whether a stop ended it.
-
- Text that could still grow into a sequence is held back, as llama-server holds
- it: a client cannot unsee a fragment the next token completes. A trailing
- replacement character is never matched either, since a decode prints the same
- character for one the model wrote and for bytes that never finished arriving
- and neither runtime tells them apart; it is delivered regardless.
-
- A caller whose decode rewrites as readily as it extends must withhold until the
- turn ends and apply this cut once.
- """
- # An unresolved character is not a character yet, and dropping it can uncover
- # the start of a sequence.
+ """How much of a cumulative reply may be shown, and whether a stop ended it. Text that could
+ still grow into a sequence is held back, as llama-server holds it: a client cannot unsee a
+ fragment the next token completes. A trailing replacement character is never matched either,
+ since a decode prints the same character for one the model wrote and for bytes that never
+ finished arriving and neither runtime tells them apart; it is delivered regardless. A caller
+ whose decode rewrites as readily as it extends must withhold until the turn ends and apply
+ this cut once."""
+ # An unresolved character is not a character yet, and dropping it can uncover the start of a sequence.
resolved = text.rstrip("\ufffd")
cut = len(resolved)
for sequence in stops:
@@ -912,13 +882,10 @@ def _mlx_stop_cut(text: str, stops) -> tuple[int, bool]:
def _mlx_finish_reason(response, stop_ids, generated_n, max_tokens):
- """Why generation stopped: "length" only when the limit was reached.
-
- mlx_lm reports it directly. mlx_vlm's result carries no reason, and a count
- at the limit is ambiguous -- a stop token sampled as the final allowed token
- looks identical to ordinary exhaustion -- so fall back to the last token's
- identity, which separates them.
- """
+ """Why generation stopped: "length" only when the limit was reached. mlx_lm reports it directly.
+ mlx_vlm's result carries no reason, and a count at the limit is ambiguous -- a stop token
+ sampled as the final allowed token looks identical to ordinary exhaustion -- so fall back to
+ the last token's identity, which separates them."""
reason = getattr(response, "finish_reason", None)
if reason in ("stop", "length"):
return reason
@@ -936,8 +903,8 @@ def _build_generation_stats(
cached_n = 0,
finish_reason = None,
):
- """Map mlx stream stats onto the usage/timings shape llama-server emits,
- plus the reason generation ended."""
+ """Map mlx stream stats onto the usage/timings shape llama-server emits, plus the reason
+ generation ended."""
prompt_n = int(prompt_n or 0)
gen_n = int(gen_n or 0)
cached_n = int(cached_n or 0)
@@ -951,9 +918,8 @@ def _build_generation_stats(
"prompt_tokens": total_prompt_n,
"completion_tokens": gen_n,
"total_tokens": total_prompt_n + gen_n,
- # The reused prefix is inside prompt_tokens, so name it here as
- # llama-server does. Reporting it only under timings.cache_n leaves a
- # caller reading the OpenAI field a cached_tokens of 0 on every hit.
+ # The reused prefix is inside prompt_tokens, so name it here as llama-server does. Reporting it only under
+ # timings.cache_n leaves a caller reading the OpenAI field a cached_tokens of 0 on every hit.
"prompt_tokens_details": {"cached_tokens": cached_n},
},
"timings": {
@@ -967,8 +933,8 @@ def _build_generation_stats(
"predicted_per_second": gen_tps,
"cache_n": cached_n,
},
- # Latched where generation exits, so a cancel arriving afterwards
- # cannot rewrite the reason the completion actually ended for.
+ # Latched where generation exits, so a cancel arriving afterwards cannot rewrite the reason the completion
+ # actually ended for.
"finish_reason": finish_reason,
}
@@ -987,8 +953,8 @@ MLX_KV_QUANT_NO_REUSE = (
MLX_KV_QUANT_VLM_CACHE_NOTE = (
"On vision models, quantization starts once the cache reaches {start} tokens."
)
-# RotatingKVCache.to_quantized raises and mlx-lm converts from the first token, so the
-# two are resolved here rather than failing generation on its first step.
+# RotatingKVCache.to_quantized raises and mlx-lm converts from the first token, so the two are resolved here rather
+# than failing generation on its first step.
MLX_KV_QUANT_PINNED_CONTEXT = (
"Context Length is set for this model, which limits the KV cache, and the installed "
"mlx-lm cannot quantize a limited cache. Reset it to quantize instead."
@@ -996,14 +962,11 @@ MLX_KV_QUANT_PINNED_CONTEXT = (
def _kv_entry_nbytes(entry):
- """Bytes held by one cache entry, or None when it cannot be measured.
-
- Read straight off the property, because that is what decides admission:
- upstream's LRUPromptCache.insert_cache sums ``c.nbytes`` itself, so an
- entry whose property raises (mlx-lm 0.31.2's QuantizedKVCache, a missing
- tree_reduce import) cannot enter the cache however else it could be sized.
- Measuring it another way here would only promise reuse that never happens.
- """
+ """Bytes held by one cache entry, or None when it cannot be measured. Read straight off the
+ property, because that is what decides admission: upstream's LRUPromptCache.insert_cache sums
+ ``c.nbytes`` itself, so an entry whose property raises (mlx-lm 0.31.2's QuantizedKVCache, a
+ missing tree_reduce import) cannot enter the cache however else it could be sized. Measuring
+ it another way here would only promise reuse that never happens."""
try:
return int(entry.nbytes)
except Exception:
@@ -1030,12 +993,10 @@ def _normalize_mlx_kv_bits(value):
def _mlx_rng_key_words():
- """The MLX PRNG key as its two 32-bit words, or None if it cannot be read.
-
- Deciding it here is what lets the rewind below stay unconditional. A key
- that reads but is not two words is not the same as an unreadable one: the
- rewind no longer works on the installed mlx, so say so before declining.
- """
+ """The MLX PRNG key as its two 32-bit words, or None if it cannot be read. Deciding it here is
+ what lets the rewind below stay unconditional. A key that reads but is not two words is not
+ the same as an unreadable one: the rewind no longer works on the installed mlx, so say so
+ before declining."""
import mlx.core as mx
try:
@@ -1056,18 +1017,16 @@ def _mlx_rng_key_words():
def _as_uint32_pair(high, low):
"""Both words as uint32, or None if either is not a 32-bit word at all.
- mx.random.seed takes a uint64 and raises outside [0, 2**64); that raise would
- land in the probe's finally and replace the probe's own outcome. So the words
- are range-checked here rather than passed through, which is what lets the
- rewind below stay unguarded.
-
- Range-checked and not simply masked, though. A negative reads as the two's
- complement of the uint32 mlx stores, so reinterpreting it loses nothing. A
- value at or above 2**32 is not a 32-bit word under any reading, and masking
- it would turn a key we cannot represent into a plausible wrong one: (2**32, 0)
- would restore as (0, 0), the probe would report success, and sampling would
- silently diverge from an unprobed run. Decline instead, which is the outcome
- the caller already handles.
+ mx.random.seed takes a uint64 and raises outside [0, 2**64); that raise would land in the
+ probe's finally and replace the probe's own outcome. So the words are range-checked here rather
+ than passed through, which is what lets the rewind below stay unguarded.
+
+ Range-checked and not simply masked, though. A negative reads as the two's complement of the
+ uint32 mlx stores, so reinterpreting it loses nothing. A value at or above 2**32 is not a 32-bit
+ word under any reading, and masking it would turn a key we cannot represent into a plausible
+ wrong one: (2**32, 0) would restore as (0, 0), the probe would report success, and sampling
+ would silently diverge from an unprobed run. Decline instead, which is the outcome the caller
+ already handles.
"""
converted = []
for word in (high, low):
@@ -1084,16 +1043,12 @@ def _as_uint32_pair(high, low):
def _restore_mlx_rng_key(words):
- """Rewind the MLX PRNG to a key captured by ``_mlx_rng_key_words``.
-
- mlx 0.32.1 made mx.random.state a sentinel that refuses item assignment.
- mx.random.key packs a seed as its two 32-bit halves, so reseeding with a
- key's own words restores it exactly, over the whole unsigned 64-bit range.
-
- Unguarded on purpose: the range check in _as_uint32_pair removes the only way
- this can raise, so there is no failure to swallow, and a blanket except here
- would be a failure indistinguishable from an intentional no-op.
- """
+ """Rewind the MLX PRNG to a key captured by ``_mlx_rng_key_words``. mlx 0.32.1 made
+ mx.random.state a sentinel that refuses item assignment; mx.random.key packs a seed as its
+ two 32-bit halves, so reseeding with a key's own words restores it exactly, over the whole
+ unsigned 64-bit range. Unguarded on purpose: the range check in _as_uint32_pair removes the
+ only way this can raise, so there is no failure to swallow, and a blanket except here would
+ be a failure indistinguishable from an intentional no-op."""
import mlx.core as mx
if words is None:
@@ -1105,17 +1060,12 @@ def _restore_mlx_rng_key(words):
def _kv_quant_probe(language_model, entries, bits):
- """Attempt the conversion the runtime will perform, on a real cache.
-
- Static proxies proved wrong in both directions: a model can declare a
- head_dim it does not use for the cache, and a window can be spelled
- differently from entry to entry. So populate one token and try the
- conversion that generation would do.
-
- Returns ``(converted, skipped, failure, retainable)``. ``retainable`` is
- False when a converted entry's size cannot be read, because the prompt
- cache budgets by size and upstream recomputes it internally.
- """
+ """Attempt the conversion the runtime will perform, on a real cache. Static proxies proved wrong
+ in both directions: a model can declare a head_dim it does not use for the cache, and a
+ window can be spelled differently from entry to entry. So populate one token and try the
+ conversion that generation would do. Returns ``(converted, skipped, failure, retainable)``,
+ where ``retainable`` is False when a converted entry's size cannot be read, because the
+ prompt cache budgets by size and upstream recomputes it internally."""
import mlx.core as mx
convertible = [entry for entry in entries if getattr(entry, "to_quantized", None) is not None]
@@ -1127,8 +1077,8 @@ def _kv_quant_probe(language_model, entries, bits):
for entry in convertible
for name in ("max_size", "window_size")
):
- # A bounded ring cannot be probed unwrapped, and wrapped its conversion
- # keeps an absolute offset past its storage. Refuse before the forward pass.
+ # A bounded ring cannot be probed unwrapped, and wrapped its conversion keeps an absolute offset past its
+ # storage. Refuse before the forward pass.
return 0, 0, "it uses a bounded sliding window", True
# The forward pass below draws random numbers, so keep sampled output stable.
@@ -1161,8 +1111,8 @@ def _kv_quant_probe(language_model, entries, bits):
_restore_mlx_rng_key(rng_key)
-# A no-argument mx.synchronize() waits on the default stream, which generation does not
-# use. mlx-vlm moves the symbol between layouts, and speculative decoding owns its own.
+# A no-argument mx.synchronize() waits on the default stream, which generation does not use. mlx-vlm moves the symbol
+# between layouts, and speculative decoding owns its own.
_GENERATION_STREAM_MODULES = (
"mlx_lm.generate",
"mlx_vlm.generate",
@@ -1173,13 +1123,10 @@ _GENERATION_STREAM_MODULES = (
def _drain_generation_streams(mx):
- """Best effort: every caller is a cleanup path whose old body could not fail.
-
- At the mlx-vlm pin floor generation_stream is a plain mx.new_stream, which raises
- when synchronized off its creating thread (mlx made command encoders thread local
- in 0.31.2). Draining is a margin on top of the clear, never a precondition, so a
- drain we cannot perform is skipped.
- """
+ """Best effort: every caller is a cleanup path whose old body could not fail. At the mlx-vlm pin
+ floor generation_stream is a plain mx.new_stream, which raises when synchronized off its
+ creating thread (mlx made command encoders thread local in 0.31.2). Draining is a margin on
+ top of the clear, never a precondition, so a drain we cannot perform is skipped."""
synchronize = getattr(mx, "synchronize", None)
if not callable(synchronize):
@@ -1206,13 +1153,10 @@ def _kv_quant_eligibility(
is_vlm,
bits = MLX_KV_BITS_CHOICES[0],
):
- """Whether KV quantization can apply to this model, before generating.
-
- Returns ``(verdict, reason, retainable)``, verdict in
- full/partial/none/refused. Eligibility only: what the runtime converts stays
- its own decision. Refusing here is what stops an ineligible model raising
- mid-generation, once the leading entries are already converted.
- """
+ """Whether KV quantization can apply to this model, before generating. Returns ``(verdict,
+ reason, retainable)``, verdict in full/partial/none/refused. Eligibility only: what the
+ runtime converts stays its own decision. Refusing here is what stops an ineligible model
+ raising mid-generation, once the leading entries are already converted."""
language_model = getattr(model, "language_model", model) if is_vlm else model
try:
if is_vlm:
@@ -1229,8 +1173,7 @@ def _kv_quant_eligibility(
return "none", "this model builds no KV cache to quantize", True
converted, skipped, failure, retainable = _kv_quant_probe(language_model, entries, bits)
- # Released only here, once the probe's own locals are gone, or the pages stay
- # in the allocator.
+ # Released only here, once the probe's own locals are gone, or the pages stay in the allocator.
import mlx.core as mx
entries.clear()
@@ -1255,9 +1198,8 @@ def _vlm_quantized_kv_start():
return 5000
-# An override replaces an existing template, never creates one: both render
-# selectors pick their target by whether a template is present, so creating one
-# would silently move the render to a different object.
+# An override replaces an existing template, never creates one: both render selectors pick their target by whether a
+# template is present, so creating one would silently move the render to a different object.
_TEMPLATE_NOT_CAPTURED = object()
MLX_TEMPLATE_NO_TARGET = (
"this model builds its prompt without a chat template, and supplying one "
@@ -1282,11 +1224,9 @@ MLX_TEMPLATE_DROPS_AUDIO = (
def _template_install_targets(tokenizer, processor):
- """Objects whose chat_template would be read at render time.
-
- The processor and the tokenizer can be the same object when a processor
- exposes no nested tokenizer, so the result is de-duplicated by identity.
- """
+ """Objects whose chat_template would be read at render time. The processor and the tokenizer can
+ be the same object when a processor exposes no nested tokenizer, so the result is
+ de-duplicated by identity."""
seen, targets = [], []
for candidate in (processor, tokenizer):
if candidate is None:
@@ -1299,12 +1239,9 @@ def _template_install_targets(tokenizer, processor):
def _template_render_targets(tokenizer, processor):
- """Objects a render selector would actually read the template from.
-
- Deferred to chat_render_target rather than restated (#7066): it also
- requires the processor to be able to render, and mlx-vlm's
- get_chat_template applies the same rule for audio.
- """
+ """Objects a render selector would actually read the template from. Deferred to
+ chat_render_target rather than restated (#7066): it also requires the processor to be able to
+ render, and mlx-vlm's get_chat_template applies the same rule for audio."""
from core.inference.chat_template_helpers import chat_render_target
target = chat_render_target(processor, tokenizer)
@@ -1317,13 +1254,10 @@ def _usable_template(value):
def _native_template_source(tokenizer, processor):
- """The object whose chat_template is this model's default.
-
- The render target, so the editor's "model default" is the text generation
- really uses. Falls back to the tokenizer when that target holds no usable
- string, keeping the nested template reported for a processor carrying a
- named set rather than reporting none at all.
- """
+ """The object whose chat_template is this model's default. The render target, so the editor's
+ "model default" is the text generation really uses. Falls back to the tokenizer when that
+ target holds no usable string, keeping the nested template reported for a processor carrying
+ a named set rather than reporting none at all."""
for target in _template_render_targets(tokenizer, processor):
if _usable_template(getattr(target, "chat_template", None)):
return target
@@ -1331,11 +1265,9 @@ def _native_template_source(tokenizer, processor):
def _template_override_status(override, tokenizer, processor):
- """Resolve a requested override against this model, without applying it.
-
- Returns the targets to install onto and a status dict; an empty target list
- with a reason means the override cannot be honored.
- """
+ """Resolve a requested override against this model, without applying it. Returns the targets to
+ install onto and a status dict; an empty target list with a reason means the override cannot
+ be honored."""
status = {
"requested": override,
"applied": None,
@@ -1352,27 +1284,24 @@ def _template_override_status(override, tokenizer, processor):
except Exception as exc:
status["reason"] = MLX_TEMPLATE_NOT_SETTABLE.format(error = exc)
return [], status
- # Judge only the objects that render: an unreplaceable template on an object
- # nothing reads would reject a working override.
+ # Judge only the objects that render: an unreplaceable template on an object nothing reads would reject a working
+ # override.
blocked = [(c, getattr(c, "chat_template", None)) for c in rendering]
if any(getattr(c, "_chat_template", None) is not None for c in rendering):
- # apply_chat_template prefers a callable template over the attribute, so
- # an assignment would be inert.
+ # apply_chat_template prefers a callable template over the attribute, so an assignment would be inert.
status["reason"] = MLX_TEMPLATE_CALLABLE
return [], status
if any(isinstance(value, (dict, list)) for _, value in blocked):
status["reason"] = MLX_TEMPLATE_NAMED_SET
return [], status
if not any(_usable_template(value) for _, value in blocked):
- # Nothing to replace. Honorable on a text model, which cannot chat without
- # one. Not with a processor: creating one takes the render away from
- # mlx-vlm's fallback, which is what places the markers.
+ # Nothing to replace. Honorable on a text model, which cannot chat without one. Not with a processor: creating
+ # one takes the render away from mlx-vlm's fallback, which is what places the markers.
if processor is not None or not blocked:
status["reason"] = MLX_TEMPLATE_NO_TARGET
return [], status
return [c for c, _ in blocked], status
- # Install on every object holding a replaceable string, so both selectors keep
- # choosing what they chose before.
+ # Install on every object holding a replaceable string, so both selectors keep choosing what they chose before.
return [c for c, value in existing if _usable_template(value)], status
@@ -1403,14 +1332,11 @@ def _image_marker_survives(
processor,
placeholder = None,
):
- """Whether the installed template still marks where an image goes.
-
- Rendered through the target generation uses, so this sees what a real image
- request would. Three ways to fail: rendering an image the same as no image,
- emitting the structured content object instead of a marker, and dropping
- the placeholder the model names. A bare difference is not enough on its
- own, since a template can render the image as ordinary prose.
- """
+ """Whether the installed template still marks where an image goes. Rendered through the target
+ generation uses, so this sees what a real image request would. Three ways to fail: rendering
+ an image the same as no image, emitting the structured content object instead of a marker,
+ and dropping the placeholder the model names. A bare difference is not enough on its own,
+ since a template can render the image as ordinary prose."""
from core.inference.chat_template_helpers import apply_chat_template_for_generation
targets = _template_render_targets(tokenizer, processor)
@@ -1430,12 +1356,9 @@ def _image_marker_survives(
def _revoke_override_dropping(status, survives, reason):
- """Undo an installed override that stopped marking where media goes.
-
- Capability was classified against the native template, so an override that
- no longer renders the marker would leave the model advertising an input it
- can no longer place.
- """
+ """Undo an installed override that stopped marking where media goes. Capability was classified
+ against the native template, so an override that no longer renders the marker would leave the
+ model advertising an input it can no longer place."""
if not status["applied"] or survives():
return status
_restore_templates(status["restore"])
@@ -1473,17 +1396,14 @@ def _restore_templates(installed):
def _install_template_override(override, tokenizer, processor, probe):
- """Install a chat template override, or report why it was not honored.
-
- ``probe`` renders a short conversation with whatever is installed; a
- template that cannot render would otherwise raise on every generation
- instead of once here, which is how a hand-edited template usually fails.
- """
+ """Install a chat template override, or report why it was not honored. ``probe`` renders a short
+ conversation with whatever is installed; a template that cannot render would otherwise raise
+ on every generation instead of once here, which is how a hand-edited template usually fails."""
targets, status = _template_override_status(override, tokenizer, processor)
if not targets:
return status
- # Restore only what was actually assigned: a target that refused the assignment
- # would refuse the restore too, masking the real error.
+ # Restore only what was actually assigned: a target that refused the assignment would refuse the restore too,
+ # masking the real error.
installed = []
template = MLX_TEMPLATE_RENDER_FAILED
try:
@@ -1504,26 +1424,22 @@ def _install_template_override(override, tokenizer, processor, probe):
def _kv_entry_is_bounded(entry, window):
- """Whether this cache entry declares a cap that holds it at or below *window*.
-
- Only a declared cap counts, and only up to the requested size. mlx-vlm's Florence2
- hands back a class that concatenates forever and declares nothing; a model that
- declares a cap wider than the request is bounded, but not at what was asked for.
- """
+ """Whether this cache entry declares a cap that holds it at or below *window*. Only a declared
+ cap counts, and only up to the requested size. mlx-vlm's Florence2 hands back a class that
+ concatenates forever and declares nothing; a model that declares a cap wider than the request
+ is bounded, but not at what was asked for."""
cap = getattr(entry, "max_size", None) or getattr(entry, "chunk_size", None)
if not cap or cap > window:
return False
- # Retaining as much as it holds means it never rotates: the write index resets past
- # the buffer end and updates stop landing.
+ # Retaining as much as it holds means it never rotates: the write index resets past the buffer end and updates
+ # stop landing.
return cap > getattr(entry, "keep", 0)
def _kv_window_enforced(model, is_vlm, window):
- """Whether a cache built for this model at *window* is bounded in every layer.
-
- Both runtimes defer to a model's own make_cache when it has one and ignore
- max_kv_size there. Returns None when no cache could be built to judge.
- """
+ """Whether a cache built for this model at *window* is bounded in every layer. Both runtimes
+ defer to a model's own make_cache when it has one and ignore max_kv_size there. Returns None
+ when no cache could be built to judge."""
language_model = getattr(model, "language_model", model) if is_vlm else model
try:
if is_vlm:
@@ -1532,8 +1448,8 @@ def _kv_window_enforced(model, is_vlm, window):
else:
from mlx_lm.models import cache as lm_cache
entries = lm_cache.make_prompt_cache(language_model, max_kv_size = window)
- # Inside the guard with the build: an unjudgeable shape must read as unknown,
- # since load_model calls this unguarded and a raise would fail the load.
+ # Inside the guard with the build: an unjudgeable shape must read as unknown, since load_model calls this
+ # unguarded and a raise would fail the load.
flattened = list(_flatten_kv_entries(entries))
return bool(flattened) and all(_kv_entry_is_bounded(entry, window) for entry in flattened)
except Exception as exc:
@@ -1617,12 +1533,10 @@ def _flatten_kv_entries(cache):
def _kv_prefix_coverage(cache):
- """Tokens the whole cache holds, or None when no entry can attest to it.
-
- A recurrent entry has no offset: it holds fixed-size state, not a token
- sequence. An attention sibling attests for it, since unrewindable state only
- ever serves the prefix it was built from. Nothing attesting keeps mamba out.
- """
+ """Tokens the whole cache holds, or None when no entry can attest to it. A recurrent entry has
+ no offset: it holds fixed-size state, not a token sequence. An attention sibling attests for
+ it, since unrewindable state only ever serves the prefix it was built from. Nothing attesting
+ keeps mamba out."""
covered = None
for entry in _flatten_kv_entries(cache):
offset = getattr(entry, "offset", None)
@@ -1711,7 +1625,6 @@ class _MLXPromptCacheHistory:
def _mlx_distributed_rank_size(group = None):
- """Return ``(rank, world_size)`` for an optional MLX distributed group."""
if group is None:
return 0, 1
rank = int(group.rank())
@@ -1753,13 +1666,10 @@ def _init_mlx_distributed():
def _normalize_mlx_seed(seed):
- """Map any request seed onto ``mx.random.key``'s unsigned domain.
-
- The seed field is shared with backends that accept values this one cannot:
- llama-server forwards ``-1`` unchanged, while ``mx.random.key`` raises for
- negatives and for anything >= 2**64. Reducing modulo 2**64 is total over
- every Python int, so no schema-valid seed can fail mid-generation.
- """
+ """Map any request seed onto ``mx.random.key``'s unsigned domain. The seed field is shared with
+ backends that accept values this one cannot: llama-server forwards ``-1`` unchanged, while
+ ``mx.random.key`` raises for negatives and for anything >= 2**64. Reducing modulo 2**64 is
+ total over every Python int, so no schema-valid seed can fail mid-generation."""
return int(seed) % (2**64)
@@ -1773,16 +1683,12 @@ def _make_seeded_mlx_sampler(
min_tokens_to_keep = 1,
):
"""mlx_lm.make_sampler's chain with a request-scoped key instead of global RNG.
-
- ``mx.random.seed`` mutates thread-local state that later requests inherit, so
- an unseeded request following a seeded one would silently become reproducible.
- A per-request key keeps determinism inside the request that asked for it.
-
- The filtering stages are mlx_lm's own ``apply_*`` functions rather than
- reimplementations: supplying a custom sampler suppresses the chain mlx_lm and
- mlx_vlm would otherwise build, so anything not reused here would be silently
- dropped from seeded requests only.
- """
+ ``mx.random.seed`` mutates thread-local state that later requests inherit, so an unseeded
+ request following a seeded one would silently become reproducible; a per-request key keeps
+ determinism inside the request that asked for it. The filtering stages are mlx_lm's own
+ ``apply_*`` functions rather than reimplementations: supplying a custom sampler suppresses
+ the chain mlx_lm and mlx_vlm would otherwise build, so anything not reused here would be
+ silently dropped from seeded requests only."""
import mlx.core as mx
from mlx_lm.sample_utils import apply_top_p, apply_min_p, apply_top_k
@@ -1811,11 +1717,8 @@ def _make_seeded_mlx_sampler(
def _make_mlx_presence_penalty_processor(penalty: float):
"""Presence penalty as an mlx_lm/mlx_vlm logits processor, matching the safetensors path.
-
- generate_step calls processors as ``fn(tokens, logits)`` with ``tokens`` the
- full running sequence; the first call is prompt-only, so latch that length
- and penalize only after it.
- """
+ generate_step calls processors as ``fn(tokens, logits)`` with ``tokens`` the full running
+ sequence; the first call is prompt-only, so latch that length and penalize only after it."""
state = {"prompt_len": None}
def _processor(tokens, logits):
@@ -1829,17 +1732,14 @@ def _make_mlx_presence_penalty_processor(penalty: float):
import mlx.core as mx
vocab = logits.shape[-1]
- # Bound ids to [0, vocab) before indexing logits: MLX does no bounds
- # checking and out-of-bounds indexing is undefined behavior (crash /
- # corruption), unlike torch's harmless negative wrap. MLX also lacks
- # boolean-mask filtering, so out-of-range/negative ids route to a
- # scratch slot at index vocab (dropped before the subtract) that never
- # collides with a real token: real ids (including 0) are penalized
- # once, strays ignored.
+ # Bound ids to [0, vocab) before indexing logits: MLX does no bounds checking and out-of-bounds indexing is
+ # undefined behavior (crash / corruption), unlike torch's harmless negative wrap. MLX also lacks boolean-mask
+ # filtering, so out-of-range/negative ids route to a scratch slot at index vocab (dropped before the subtract)
+ # that never collides with a real token: real ids (including 0) are penalized once, strays ignored.
valid = (generated >= 0) & (generated < vocab)
safe = mx.where(valid, generated, vocab).astype(mx.int32)
- # Scatter penalty into a (vocab + 1)-wide mask: duplicate ids are
- # idempotent (presence applies once per token); scratch column dropped.
+ # Scatter penalty into a (vocab + 1)-wide mask: duplicate ids are idempotent (presence applies once per
+ # token); scratch column dropped.
mask = mx.zeros((vocab + 1,), dtype = logits.dtype)
mask[safe] = penalty
logits = logits - mask[:vocab]
@@ -1849,14 +1749,11 @@ def _make_mlx_presence_penalty_processor(penalty: float):
def _make_mlx_frequency_penalty_processor(penalty: float):
- """Frequency penalty as an mlx_lm/mlx_vlm logits processor.
-
- Identical to the presence processor except the scatter *accumulates*, so a
- token repeated N times in the completion is charged N × penalty. It counts
- occurrences and scales once, in float32: accumulating the penalty itself in
- a float16 logits dtype rounds on every repeat, which drifts by tens of
- logits over a long run (1000 repeats at 0.3 lands on -274.25, not -300).
- """
+ """Frequency penalty as an mlx_lm/mlx_vlm logits processor. Identical to the presence processor
+ except the scatter *accumulates*, so a token repeated N times in the completion is charged N
+ x penalty. It counts occurrences and scales once, in float32: accumulating the penalty itself
+ in a float16 logits dtype rounds on every repeat, which drifts by tens of logits over a long
+ run (1000 repeats at 0.3 lands on -274.25, not -300)."""
state = {"prompt_len": None}
def _processor(tokens, logits):
@@ -1878,13 +1775,10 @@ def _make_mlx_frequency_penalty_processor(penalty: float):
def _make_mlx_logit_bias_processor(logit_bias: dict):
- """Additive logit bias as an mlx_lm/mlx_vlm logits processor.
-
- mlx_lm's own ``logit_bias`` processor indexes logits with the raw client
- ids; MLX does no bounds checking, so a bias on an id past the model's logit
- width is undefined behavior. Route strays to the same discarded scratch
- slot the penalty processors use.
- """
+ """Additive logit bias as an mlx_lm/mlx_vlm logits processor. mlx_lm's own ``logit_bias``
+ processor indexes logits with the raw client ids; MLX does no bounds checking, so a bias on
+ an id past the model's logit width is undefined behavior. Route strays to the same discarded
+ scratch slot the penalty processors use."""
state = {"safe": None, "values": None, "vocab": None}
def _processor(tokens, logits):
@@ -1911,15 +1805,11 @@ def _mlx_sampling_processors(
frequency_penalty: float = 0.0,
logit_bias = None,
):
- """Logits processors for the sampling knobs, or ``None`` when all are inert.
-
- Bias runs before the penalties, matching llama-server's sampler order.
- mlx_lm supplies only the repetition penalty here: its presence and
- frequency processors window the last 20 tokens *including the prompt*,
- while the penalties below score the whole completion and exclude it, so
- using them would make the same request sample differently depending on the
- backend.
- """
+ """Logits processors for the sampling knobs, or ``None`` when all are inert. Bias runs before
+ the penalties, matching llama-server's sampler order. mlx_lm supplies only the repetition
+ penalty here: its presence and frequency processors window the last 20 tokens *including the
+ prompt*, while the penalties below score the whole completion and exclude it, so using them
+ would make the same request sample differently depending on the backend."""
processors = []
if logit_bias:
processors.append(_make_mlx_logit_bias_processor(logit_bias))
@@ -1933,10 +1823,9 @@ def _mlx_sampling_processors(
return processors or None
-# Families that mlx_vlm inlined before should_add_special_tokens existed: their template
-# already emits the markers, so tokenization must not add them again. Deliberately not the
-# current helper's list, which carries laguna -- only 0.6.9 stopped tokenizing laguna with
-# the markers, and 0.6.0-0.6.8 are what this stands in for.
+# Families that mlx_vlm inlined before should_add_special_tokens existed: their template already emits the markers, so
+# tokenization must not add them again. Deliberately not the current helper's list, which carries laguna -- only 0.6.9
+# stopped tokenizing laguna with the markers, and 0.6.0-0.6.8 are what this stands in for.
_VLM_INLINE_SPECIAL_TOKEN_FAMILIES = ("gemma3", "gemma3n", "gemma4", "gemma4_unified")
# First mlx-vlm whose gemma-4 mask overlay skips a resumed suffix's non-square mask (#1445).
_VLM_MEDIA_BLOCK_MIN_VERSION = "0.6.4"
@@ -1956,9 +1845,9 @@ def _vlm_add_special_tokens(model_type, processor):
class _VLMMediaBlock:
- """A prompt's rows through its last vision token, prefilled by Studio: models whose
- vision tokens attend to each other prefill in one forward that lands off the grid,
- and this is that forward cut where the grid can continue."""
+ """A prompt's rows through its last vision token, prefilled by Studio: models whose vision
+ tokens attend to each other prefill in one forward that lands off the grid, and this is that
+ forward cut where the grid can continue."""
def __init__(self, model, processor, prompt, images, make_cache):
from mlx_vlm.utils import prepare_inputs
@@ -2029,8 +1918,7 @@ class MLXInferenceBackend:
self.loaded_local_models = []
self.device = "mlx"
self._generation_lock = threading.Lock()
- # usage, timings and terminal reason of the latest generation,
- # shipped on gen_done.
+ # usage, timings and terminal reason of the latest generation, shipped on gen_done.
self.last_generation_stats = None
self._model = None
@@ -2045,9 +1933,8 @@ class MLXInferenceBackend:
# Recorded for unload to release pinned memory back to the OS.
self._memory_limits_applied = {}
- # Load-time runtime knobs; every generation path reads them from here rather
- # than from per-request kwargs. Bound now so a load that fails before
- # installing leaves readers a dict rather than raising.
+ # Load-time runtime knobs; every generation path reads them from here rather than from per-request kwargs.
+ # Bound now so a load that fails before installing leaves readers a dict rather than raising.
self._kv_quant = _kv_quant_status(None, None, False)
self._kv_cache_window = None
self._template_override = _template_override_status(None, None, None)[1]
@@ -2103,8 +1990,8 @@ class MLXInferenceBackend:
self._vlm_snapshot_store_unavailable = True
logger.info("MLX VLM prompt cache disabled by budget")
return None
- # Needs a dispatcher that primes mRoPE state, reports reuse and routes diffusion
- # itself: all three arrived with cached_tokens.
+ # Needs a dispatcher that primes mRoPE state, reports reuse and routes diffusion itself: all three arrived
+ # with cached_tokens.
try:
from mlx_vlm.generate import GenerationResult
from mlx_vlm.generate.diffusion import is_diffusion_model
@@ -2224,29 +2111,23 @@ class MLXInferenceBackend:
return rest, cache, key, tokens, len(tokens) - len(rest)
def _kv_quant_generate_kwargs(self):
- """Load-time runtime knobs for a generate call, empty when unset.
-
- quantized_kv_start is deliberately not passed: mlx-lm and mlx-vlm ship
- different defaults (0 and 5000) and each runtime keeps its own.
- """
+ """Load-time runtime knobs for a generate call, empty when unset. quantized_kv_start is
+ deliberately not passed: mlx-lm and mlx-vlm ship different defaults (0 and 5000) and each
+ runtime keeps its own."""
kv_bits = (getattr(self, "_kv_quant", None) or {}).get("kv_bits")
return {} if kv_bits is None else {"kv_bits": kv_bits}
def _kv_window_generate_kwargs(self):
- """The cache bound for a generation that builds its own cache, empty when unset.
-
- Both runtimes read it only when no prompt_cache is passed, so this covers the
- request that reaches generation without one rather than duplicating the bound.
- """
+ """The cache bound for a generation that builds its own cache, empty when unset. Both
+ runtimes read it only when no prompt_cache is passed, so this covers the request that
+ reaches generation without one rather than duplicating the bound."""
window = getattr(self, "_kv_cache_window", None)
return {} if window is None else {"max_kv_size": window}
def _encode_prompt(self, prompt):
- """The tokens a generation sends for this prompt.
-
- A template that already emitted the BOS would otherwise get a second one, shifting
- every cached-prefix comparison and overstating a counted prompt by one.
- """
+ """The tokens a generation sends for this prompt. A template that already emitted the BOS
+ would otherwise get a second one, shifting every cached-prefix comparison and overstating
+ a counted prompt by one."""
bos = getattr(self._tokenizer, "bos_token", None)
return list(
self._tokenizer.encode(
@@ -2255,12 +2136,9 @@ class MLXInferenceBackend:
)
def _configure_memory_limits(self):
- """Apply Metal memory caps before loading a model.
-
- memory_limit = 85% of recommended working-set;
- wired_limit = min(recommended, memory_limit). Recorded so unload can
- lower wired_limit back to release pinned RAM.
- """
+ """Apply Metal memory caps before loading a model. memory_limit = 85% of recommended
+ working-set; wired_limit = min(recommended, memory_limit). Recorded so unload can lower
+ wired_limit back to release pinned RAM."""
import mlx.core as mx
if not mx.metal.is_available():
@@ -2288,15 +2166,15 @@ class MLXInferenceBackend:
def _resolve_context_lengths(self, model, max_seq_length):
"""Resolve (served, native, ceiling) for a freshly loaded model.
- Mirrors the GGUF resolution order: whatever the load attached or was asked for is
- honored verbatim, while asking for nothing takes the trained window. The served
- length is what bounds the KV cache, where the architecture allows it.
+ Mirrors the GGUF resolution order: whatever the load attached or was asked for is honored
+ verbatim, while asking for nothing takes the trained window. The served length is what
+ bounds the KV cache, where the architecture allows it.
- The served value is held to the same ceiling a request is (LoadRequest bounds
- max_seq_length at MAX_REQUESTABLE_CONTEXT), because it drives the cache and the
- usage bar's denominator. Llama-4 Scout declares 10,485,760, ten times that: served
- unclamped would make the bar meaningless and name a length no control can ask for.
- The native window is reported as read, since it is metadata about the model.
+ The served value is held to the same ceiling a request is (LoadRequest bounds max_seq_length
+ at MAX_REQUESTABLE_CONTEXT), because it drives the cache and the usage bar's denominator.
+ Llama-4 Scout declares 10,485,760, ten times that: served unclamped would make the bar
+ meaningless and name a length no control can ask for. The native window is reported as read,
+ since it is metadata about the model.
"""
native = mlx_native_context_length(model)
served = runtime_context_length(model, max_seq_length) or native
@@ -2306,11 +2184,9 @@ class MLXInferenceBackend:
return served, native, native
def _kv_cache_window_enforceable(self, served):
- """Whether a cache built for this model would really cap at *served*.
-
- A probe that could not run counts as not enforceable: claiming a bound nobody
- confirmed is what makes the setting look like it works.
- """
+ """Whether a cache built for this model would really cap at *served*. A probe that could not
+ run counts as not enforceable: claiming a bound nobody confirmed is what makes the
+ setting look like it works."""
if not served or served <= 0:
return False
enforced = _kv_window_enforced(self._model, self._is_vlm, int(served))
@@ -2331,18 +2207,18 @@ class MLXInferenceBackend:
def _resolve_kv_policy(self, is_vlm, kv_bits, max_seq_length, served):
"""The quantization status and cache window this load will run with.
- Rotation is what keeps a long conversation inside the window, so nothing here can
- refuse a request; the model simply stops attending to the oldest tokens.
+ Rotation is what keeps a long conversation inside the window, so nothing here can refuse a
+ request; the model simply stops attending to the oldest tokens.
- Quantization cannot coexist with a bound -- a rotating cache has no conversion,
- and mlx-lm converts from the first token -- so an enforceable pin, an explicit
- instruction about memory, outranks it. A window the backend chose for itself
- yields to an explicitly requested quantization, and so does a pin that cannot be
- enforced, which would otherwise spend the quantization and bound nothing.
+ Quantization cannot coexist with a bound -- a rotating cache has no conversion, and mlx-lm
+ converts from the first token -- so an enforceable pin, an explicit instruction about
+ memory, outranks it. A window the backend chose for itself yields to an explicitly requested
+ quantization, and so does a pin that cannot be enforced, which would otherwise spend the
+ quantization and bound nothing.
"""
pinned = _positive_int(max_seq_length) is not None
- # Tri-state: True bounded, False confirmed unbounded, None unjudgeable. Only True
- # installs a bound; the other two stay apart so a client can tell them apart.
+ # Tri-state: True bounded, False confirmed unbounded, None unjudgeable. Only True installs a bound; the other
+ # two stay apart so a client can tell them apart.
confirmed = self._kv_cache_window_enforceable(served)
enforceable = confirmed is True
quant = _kv_quant_status(
@@ -2352,8 +2228,8 @@ class MLXInferenceBackend:
pinned and enforceable,
)
if not enforceable or (quant["kv_bits"] is not None and not pinned):
- # No bound installed, so False wherever the probe answered at all; None only
- # where nothing could be built to judge.
+ # No bound installed, so False wherever the probe answered at all; None only where nothing could be built
+ # to judge.
return quant, None, None if confirmed is None else False
logger.info("MLX KV cache limited to %d tokens", int(served))
return quant, int(served), True
@@ -2374,8 +2250,7 @@ class MLXInferenceBackend:
) -> bool:
import mlx.core as mx
- # Keep the token so the native-template fallback can fetch a gated
- # model's repo template during generation.
+ # Keep the token so the native-template fallback can fetch a gated model's repo template during generation.
self._hf_token = hf_token
model_name = config.identifier if hasattr(config, "identifier") else str(config)
is_vision = getattr(config, "is_vision", False)
@@ -2385,10 +2260,9 @@ class MLXInferenceBackend:
self._distributed_rank = distributed_rank
self._distributed_world_size = distributed_size
- # GGUF guard: GGUF is served by llama-server in the parent process,
- # not mlx-lm. Reaching here with is_gguf=True means the route's
- # detection flaked but the subprocess re-detected GGUF; raise loudly
- # instead of a cryptic mlx_lm error.
+ # GGUF guard: GGUF is served by llama-server in the parent process, not mlx-lm. Reaching here with
+ # is_gguf=True means the route's detection flaked but the subprocess re-detected GGUF; raise loudly instead of
+ # a cryptic mlx_lm error.
if getattr(config, "is_gguf", False):
raise RuntimeError(
f"MLXInferenceBackend cannot load GGUF model '{model_name}': "
@@ -2479,9 +2353,8 @@ class MLXInferenceBackend:
_served_ctx, _native_ctx, _max_ctx = self._resolve_context_lengths(
self._model, max_seq_length
)
- # Classify before the first generation: an ineligible cache would otherwise
- # raise inside maybe_quantize_kv_cache mid-stream, after converting the
- # leading entries.
+ # Classify before the first generation: an ineligible cache would otherwise raise inside
+ # maybe_quantize_kv_cache mid-stream, after converting the leading entries.
self._kv_quant, self._kv_cache_window, _ctx_enforced = self._resolve_kv_policy(
is_vision, kv_bits, max_seq_length, _served_ctx
)
@@ -2492,10 +2365,9 @@ class MLXInferenceBackend:
self._kv_quant["eligibility"],
)
- # Captured before installing, so chat_template_info keeps reporting what the
- # model shipped with. From the render target, not the nested tokenizer: on a
- # processor owning its own template those differ, and saving the wrong
- # default back would install the tokenizer's template over the processor.
+ # Captured before installing, so chat_template_info keeps reporting what the model shipped with. From the
+ # render target, not the nested tokenizer: on a processor owning its own template those differ, and saving the
+ # wrong default back would install the tokenizer's template over the processor.
native_source = _native_template_source(self._tokenizer, self._processor)
native_template = getattr(native_source, "chat_template", None)
native_marks_audio = bool(
@@ -2512,16 +2384,15 @@ class MLXInferenceBackend:
)
if native_marks_audio:
_revoke_override_that_drops_audio(self._template_override, self._processor, self._model)
- # Unconditional for vision, unlike audio: a native template that marks
- # nothing still renders images through _generate_vlm's recovery, but an
- # override rendering plain text drops the image in silence, so gating on
- # the native template would skip exactly the models needing the check.
+ # Unconditional for vision, unlike audio: a native template that marks nothing still renders images through
+ # _generate_vlm's recovery, but an override rendering plain text drops the image in silence, so gating on the
+ # native template would skip exactly the models needing the check.
if is_vision:
_revoke_override_that_drops_image(
self._template_override, self._tokenizer, self._processor, image_placeholder
)
- # Released once the media checks are done: the pairs reference the tokenizer
- # and processor, so keeping them would outlive the unload that nulls both.
+ # Released once the media checks are done: the pairs reference the tokenizer and processor, so keeping them
+ # would outlive the unload that nulls both.
self._template_override["restore"] = []
if self._template_override["reason"]:
logger.info(
@@ -2549,15 +2420,15 @@ class MLXInferenceBackend:
"audio_type": _audio_type,
"has_audio_input": is_audio_input_type(_audio_type),
"context_length": _served_ctx,
- # Parity with llama.cpp's requested_n_ctx: the served window cannot say
- # whether anything was asked for, and that decides reuse and "pinned".
+ # Parity with llama.cpp's requested_n_ctx: the served window cannot say whether anything was asked for,
+ # and that decides reuse and "pinned".
"requested_context_length": _positive_int(max_seq_length) or 0,
# Nothing measures the machine, so window and ceiling coincide.
"native_context_length": _native_ctx,
"max_context_length": _max_ctx,
- # Whether the served window actually bounds the cache: True confirmed on a
- # real cache, False confirmed unbounded, None nothing could be built to judge.
- # Without it the API reports a limit a client cannot tell from an enforced one.
+ # Whether the served window actually bounds the cache: True confirmed on a real cache, False confirmed
+ # unbounded, None nothing could be built to judge. Without it the API reports a limit a client cannot tell
+ # from an enforced one.
"context_length_enforced": _ctx_enforced,
"mlx_kv_bits": self._kv_quant["kv_bits"],
"mlx_kv_bits_requested": self._kv_quant["requested_kv_bits"],
@@ -2574,12 +2445,10 @@ class MLXInferenceBackend:
return True
def _render_template_probe(self, is_vision: bool) -> str:
- """Render a short conversation through the path generation will use.
-
- Must use the same target the real request does. The recovery renderer
- returns None instead of raising for a model outside mlx-vlm's family
- list, so probing it would pass a template that cannot render at all.
- """
+ """Render a short conversation through the path generation will use. Must use the same
+ target the real request does: the recovery renderer returns None instead of raising for a
+ model outside mlx-vlm's family list, so probing it would pass a template that cannot
+ render at all."""
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
chat_render_target,
@@ -2601,13 +2470,10 @@ class MLXInferenceBackend:
model_name: str,
native_template = _TEMPLATE_NOT_CAPTURED,
) -> None:
- """Mirror InferenceBackend._load_chat_template_info for MLX.
-
- Stores ``chat_template_info`` on ``self.models[model_name]``. The
- template recorded is the one the model shipped with, not an override:
- the capability classification and the editor's notion of "default"
- both read it, so an override installed on the tokenizer must not
- show up here."""
+ """Mirror InferenceBackend._load_chat_template_info for MLX. Stores ``chat_template_info``
+ on ``self.models[model_name]``. The template recorded is the one the model shipped with,
+ not an override: the capability classification and the editor's notion of "default" both
+ read it, so an override installed on the tokenizer must not show up here."""
entry = self.models.get(model_name)
if not entry:
return
@@ -2704,10 +2570,8 @@ class MLXInferenceBackend:
preserve_thinking = None,
continue_final_message = False,
):
- """Render the prompt a text generation sends, with its template metadata.
-
- Shared with counting, so a count cannot price a prompt the model never sees.
- """
+ """Render the prompt a text generation sends, with its template metadata. Shared with
+ counting, so a count cannot price a prompt the model never sees."""
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
render_with_native_template_fallback,
@@ -2725,10 +2589,9 @@ class MLXInferenceBackend:
if prompt is None:
raise RuntimeError("apply_chat_template returned None — tokenizer may be incompatible")
- # Parity with the transformers backend: if the template dropped the requested
- # tools, fall back to the native template so MLX text models keep advertising
- # them. self._tokenizer is this entry's tokenizer, so probe and native render
- # share a renderer. (VLM renders via the processor for image tokens.)
+ # Parity with the transformers backend: if the template dropped the requested tools, fall back to the native
+ # template so MLX text models keep advertising them. self._tokenizer is this entry's tokenizer, so probe and
+ # native render share a renderer. (VLM renders via the processor for image tokens.)
model_info = self.models.get(self.active_model_name, {})
return render_with_native_template_fallback(
formatted_prompt = prompt,
@@ -2747,11 +2610,8 @@ class MLXInferenceBackend:
@staticmethod
def _with_system_prompt(messages, system_prompt):
- """The conversation a request carrying this system prompt turns into.
-
- Shared with generation, which takes the system prompt beside the messages rather
- than inside them.
- """
+ """The conversation a request carrying this system prompt turns into. Shared with
+ generation, which takes the system prompt beside the messages rather than inside them."""
full_messages = []
if system_prompt:
full_messages.append({"role": "system", "content": system_prompt})
@@ -2768,19 +2628,16 @@ class MLXInferenceBackend:
reasoning_effort = None,
preserve_thinking = None,
) -> int:
- """Prompt tokens this model would receive for these messages.
-
- Renders and tokenizes exactly as generation does.
- """
+ """Prompt tokens this model would receive for these messages. Renders and tokenizes exactly
+ as generation does."""
if self._model is None:
raise RuntimeError("No model loaded")
full_messages = self._with_system_prompt(messages, system_prompt)
if self._is_vlm:
- # Through the processor, which is what a vision generation renders with; the
- # text renderer would not recover the template failures it recovers from.
- # images=None: an image anywhere in the conversation makes the structured-item
- # check raise, and the caller declines rather than pricing a prompt without it.
+ # Through the processor, which is what a vision generation renders with; the text renderer would not
+ # recover the template failures it recovers from. images=None: an image anywhere in the conversation makes
+ # the structured-item check raise, and the caller declines rather than pricing a prompt without it.
prompt, _ = self._render_vlm_prompt(
full_messages,
None,
@@ -2789,9 +2646,9 @@ class MLXInferenceBackend:
reasoning_effort = reasoning_effort,
preserve_thinking = preserve_thinking,
)
- # Whether the markers belong to the template or to tokenization is a per-model
- # answer mlx_vlm makes for every generation; ask it rather than guess, or the
- # count is off by whatever the generation's own choice would have added.
+ # Whether the markers belong to the template or to tokenization is a per-model answer mlx_vlm makes for
+ # every generation; ask it rather than guess, or the count is off by whatever the generation's own choice
+ # would have added.
_model_type = getattr(getattr(self._model, "config", None), "model_type", None)
add_special = _vlm_add_special_tokens(_model_type, self._processor)
return len(self._tokenizer.encode(prompt, add_special_tokens = add_special))
@@ -2950,12 +2807,11 @@ class MLXInferenceBackend:
)
prompt = render_result.prompt
reasoning_channel_markers = render_result.reasoning_channel_markers
- # Not the request flag: a later tool-loop pass keeps it but renders an
- # ordinary post-tool prompt.
+ # Not the request flag: a later tool-loop pass keeps it but renders an ordinary post-tool prompt.
_resumed_partial = bool(continue_final_message and trailing_assistant_text(messages))
- # An open <think> prefilled by the template lives in the prompt, not
- # the generated tokens; re-emit it so the frontend renders the block.
+ # An open <think> prefilled by the template lives in the prompt, not the generated tokens; re-emit it so the
+ # frontend renders the block.
think_prefix = detect_think_prefill(
prompt,
getattr(self._tokenizer, "all_special_tokens", None),
@@ -3017,16 +2873,15 @@ class MLXInferenceBackend:
if reasoning_channel_markers is not None
else None
)
- # Sequences match the sampled text, ahead of the prefill this path restores
- # and the <think> rewriting below: matching delivered text would end turns on
- # markup the model never wrote, and never find a native marker asked for.
+ # Sequences match the sampled text, ahead of the prefill this path restores and the <think> rewriting below:
+ # matching delivered text would end turns on markup the model never wrote, and never find a native marker
+ # asked for.
sequences = _mlx_stop_sequences(stop)
stopped = False
sampled = ""
released = 0
- # MLX consumers diff cumulative snapshots. Keep a prompt-prefilled
- # <think> prefix on every native-protocol snapshot just as the normal
- # decoding path does below.
+ # MLX consumers diff cumulative snapshots. Keep a prompt-prefilled <think> prefix on every native-protocol
+ # snapshot just as the normal decoding path does below.
normalized_output = think_prefix
with self._generation_lock, _temporary_mlx_adapter_state(self._model, _adapter_state):
(
@@ -3084,17 +2939,16 @@ class MLXInferenceBackend:
cut, stopped = _mlx_stop_cut(sampled, sequences)
else:
cut = len(sampled)
- # Cut before normalizing: the markers the normalizer writes are
- # this layer's own, unmatched for the same reason the prefill is.
+ # Cut before normalizing: the markers the normalizer writes are this layer's own, unmatched
+ # for the same reason the prefill is.
delta = normalizer.feed(sampled[released:cut])
released = cut
if delta:
normalized_output += delta
yield normalized_output
else:
- # Re-decoding every id rebuilds rather than extends, so an
- # invalid byte sequence can revise characters already shown.
- # Predates stop handling and affects plain replies too.
+ # Re-decoding every id rebuilds rather than extends, so an invalid byte sequence can revise
+ # characters already shown. Predates stop handling and affects plain replies too.
if native_token_decoder is not None:
# Some runtimes stop on an allowlisted control (TML Inkling's
# <|end_message|>). Drop only the TRAILING stop id, so the marker
@@ -3121,11 +2975,10 @@ class MLXInferenceBackend:
if not sequences:
yield think_prefix + sampled
else:
- # Matched every step, delivered once at the end: this
- # decode revises earlier snapshots, and consumers diff
- # them by length, so a revised one splices two renderings
- # into text that can spell the sequence itself. A stream
- # cannot unsend, so nothing goes out until it settles.
+ # Matched every step, delivered once at the end: this decode revises earlier snapshots,
+ # and consumers diff them by length, so a revised one splices two renderings into text
+ # that can spell the sequence itself. A stream cannot unsend, so nothing goes out until it
+ # settles.
cut, stopped = _mlx_stop_cut(sampled, sequences)
if stopped:
break
@@ -3144,8 +2997,8 @@ class MLXInferenceBackend:
logger.error("stream_generate failed:\n%s", traceback.format_exc())
raise
finally:
- # Latch final stats here, so a cancel arriving later cannot
- # rewrite the reason the generation actually ended for.
+ # Latch final stats here, so a cancel arriving later cannot rewrite the reason the generation actually
+ # ended for.
if final_response is not None:
self.last_generation_stats = _build_generation_stats(
getattr(final_response, "prompt_tokens", 0),
@@ -3160,16 +3013,16 @@ class MLXInferenceBackend:
max_new_tokens,
),
)
- # The turn's settled text: delivered once for the plain path, as the tail for
- # the native-channel one. Every snapshot was matched as it arrived, so a turn
- # no sequence ended owes all of its text, held-back partial included.
+ # The turn's settled text: delivered once for the plain path, as the tail for the native-channel one. Every
+ # snapshot was matched as it arrived, so a turn no sequence ended owes all of its text, held-back partial
+ # included.
if sequences:
if not stopped:
cut = len(sampled)
if normalizer is None:
settled = think_prefix + sampled[:cut]
- # The prefill already went out, so a turn whose settled text is just
- # the prefill owes no second snapshot saying the same thing.
+ # The prefill already went out, so a turn whose settled text is just the prefill owes no second
+ # snapshot saying the same thing.
if settled != think_prefix:
yield settled
else:
@@ -3178,8 +3031,8 @@ class MLXInferenceBackend:
normalized_output += delta
yield normalized_output
if normalizer is not None:
- # A sequence ends the turn as a stop token would, so a reasoning block it
- # cut inside is closed. Only a cancelled turn drains: more was coming.
+ # A sequence ends the turn as a stop token would, so a reasoning block it cut inside is closed. Only a
+ # cancelled turn drains: more was coming.
cancelled = not stopped and cancel_event is not None and cancel_event.is_set()
tail = normalizer.drain() if cancelled else normalizer.finish()
if tail:
@@ -3199,20 +3052,17 @@ class MLXInferenceBackend:
preserve_thinking = None,
continue_final_message = False,
):
- """Render the prompt a vision generation sends, and the target that rendered it.
-
- Shared with counting, as _render_text_prompt is for text models, so a count cannot
- price a prompt the model never sees. A text-only conversation passes images=None.
- """
+ """Render the prompt a vision generation sends, and the target that rendered it. Shared with
+ counting, as _render_text_prompt is for text models, so a count cannot price a prompt the
+ model never sees. A text-only conversation passes images=None."""
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
chat_render_target,
)
- # Pick the chat-template-aware caller: processors with their own
- # apply_chat_template + chat_template (e.g. Qwen2.5-VL), else the nested tokenizer.
- # Shared with the healing catalog the route builds ahead of this render, which has
- # to authorize against the same template this line selects (#7066).
+ # Pick the chat-template-aware caller: processors with their own apply_chat_template + chat_template (e.g.
+ # Qwen2.5-VL), else the nested tokenizer. Shared with the healing catalog the route builds ahead of this
+ # render, which has to authorize against the same template this line selects (#7066).
chat_target = chat_render_target(self._processor)
attached_images = 0 if images is None else len(images)
@@ -3362,9 +3212,9 @@ class MLXInferenceBackend:
len(prompt),
image is not None,
)
- # stream_generate forwards **kwargs into generate_step (builds the
- # sampler + logits_processors internally). GOTCHA: generate_step expects
- # temperature= (long form); temp= is silently ignored, stuck at greedy 0.0.
+ # stream_generate forwards **kwargs into generate_step (which builds the sampler + logits_processors
+ # internally). GOTCHA: generate_step expects temperature= (long form); temp= is silently ignored, stuck at
+ # greedy 0.0.
vlm_kwargs = dict(
max_tokens = max_new_tokens,
temperature = temperature,
@@ -3375,9 +3225,8 @@ class MLXInferenceBackend:
vlm_kwargs.update(self._kv_quant_generate_kwargs())
vlm_kwargs.update(self._kv_window_generate_kwargs())
if seed is not None:
- # generate_step builds its temperature/top_p/min_p/top_k sampler only
- # when sampler is None, so a seeded request must supply the whole
- # chain -- otherwise seeding would silently disable those controls.
+ # generate_step builds its temperature/top_p/min_p/top_k sampler only when sampler is None, so a seeded
+ # request must supply the whole chain -- otherwise seeding would silently disable those controls.
vlm_kwargs["sampler"] = _make_seeded_mlx_sampler(
seed,
temp = temperature,
@@ -3390,8 +3239,8 @@ class MLXInferenceBackend:
1.0,
)
if presence_penalty or frequency_penalty or logit_bias:
- # These need custom processors: pass the full list (repetition +
- # the rest) instead of the repetition_penalty shortcut so all apply.
+ # These need custom processors: pass the full list (repetition + the rest) instead of the
+ # repetition_penalty shortcut so all apply.
vlm_kwargs["logits_processors"] = _mlx_sampling_processors(
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
@@ -3440,9 +3289,8 @@ class MLXInferenceBackend:
nonlocal stopped
sampled = ""
released = 0
- # Hold the generation lock AND the request-scoped adapter state for the
- # whole stream so Base-vs-LoRA compare mode honors use_adapter and the
- # wrapper tree is restored on completion, cancellation, or close.
+ # Hold the generation lock AND the request-scoped adapter state for the whole stream so Base-vs-LoRA
+ # compare mode honors use_adapter and the wrapper tree is restored on completion, cancellation, or close.
with (
self._generation_lock,
_temporary_mlx_adapter_state(self._model, _adapter_state),
@@ -3453,10 +3301,9 @@ class MLXInferenceBackend:
self._release_vlm_snapshots()
final_response = None
try:
- # Emit any prefilled <think> block before the first token so the
- # UI renders it during prefill, matching _generate_text. Done
- # inside the adapter context so an unsupported request raises
- # before any output escapes.
+ # Emit any prefilled <think> block before the first token so the UI renders it during prefill,
+ # matching _generate_text. Done inside the adapter context so an unsupported request raises before
+ # any output escapes.
if prefill:
yield prefill
for response in vlm_stream(
@@ -3484,8 +3331,7 @@ class MLXInferenceBackend:
yield prefill + sampled
else:
cut, stopped = _mlx_stop_cut(sampled, sequences)
- # These deltas only append, so the cut never moves back
- # over text already released.
+ # These deltas only append, so the cut never moves back over text already released.
if cut > released:
released = cut
yield prefill + sampled[:cut]
@@ -3509,13 +3355,12 @@ class MLXInferenceBackend:
cached_n = int(getattr(final_response, "cached_tokens", 0) or 0)
produced_n, produced_s = session.produced_tokens, session.produced_seconds
cached_n = max(cached_n - produced_n, 0)
- # mlx_vlm exposes the same stats fields as mlx_lm, minus a
- # finish reason, so that one is derived.
+ # mlx_vlm exposes the same stats fields as mlx_lm, minus a finish reason, so that one is derived.
if final_response is not None:
tokenizer = getattr(self._processor, "tokenizer", self._processor)
stop_ids = _mlx_stop_token_ids(tokenizer, self._model)
- # mlx-vlm rates the whole prompt against the prefill it ran, which
- # leaves out the rows the session produced first.
+ # mlx-vlm rates the whole prompt against the prefill it ran, which leaves out the rows the
+ # session produced first.
prompt_n = int(getattr(final_response, "prompt_tokens", 0) or 0)
prefilled_n = max(prompt_n - cached_n, 0)
prompt_tps = float(getattr(final_response, "prompt_tps", 0.0) or 0.0)
@@ -3559,9 +3404,9 @@ class MLXInferenceBackend:
stop = None,
**_sampler,
):
- """Audio-input chat (omni models): waveform in, incremental text deltas
- out (the audio route forwards deltas, unlike the snapshot-diffing
- text/vision paths). Greedy, so the worker's sampler kwargs go unused."""
+ """Audio-input chat (omni models): waveform in, incremental text deltas out (the audio route
+ forwards deltas, unlike the snapshot-diffing text/vision paths). Greedy, so the worker's
+ sampler kwargs go unused."""
entry = self.models.get(self.active_model_name) or {}
if entry.get("audio_type") != "audio_vlm":
raise RuntimeError(
@@ -3607,8 +3452,8 @@ class MLXInferenceBackend:
sampled = ""
released = 0
stopped = False
- # Hold the adapter state for the whole stream, as text and vision do,
- # so Base-vs-LoRA compare doesn't run the adapter on both sides.
+ # Hold the adapter state for the whole stream, as text and vision do, so Base-vs-LoRA compare doesn't run the
+ # adapter on both sides.
with self._generation_lock, _temporary_mlx_adapter_state(self._model, use_adapter):
# As on the image path: the tower gets the headroom, under the lock.
self._release_vlm_snapshots()
@@ -3631,8 +3476,8 @@ class MLXInferenceBackend:
cut, stopped = _mlx_stop_cut(sampled, sequences)
else:
cut = len(sampled)
- # Cut before normalizing: the markers the normalizer writes are
- # this layer's own, unmatched for the same reason the prefill is.
+ # Cut before normalizing: the markers the normalizer writes are this layer's own, unmatched for
+ # the same reason the prefill is.
delta = sampled[released:cut]
released = cut
if normalizer is not None:
@@ -3644,8 +3489,8 @@ class MLXInferenceBackend:
if cancel_event and cancel_event.is_set():
break
finally:
- # Derived as the vision path derives it: this backend reports no
- # finish reason, and unset reads as a natural end.
+ # Derived as the vision path derives it: this backend reports no finish reason, and unset reads as a
+ # natural end.
if final_response is not None:
tokenizer = getattr(self._processor, "tokenizer", self._processor)
self.last_generation_stats = _build_generation_stats(
diff --git a/studio/backend/core/inference/offload_cost_model.py b/studio/backend/core/inference/offload_cost_model.py
index 29973fba7cb..08de0b28f93 100644
--- a/studio/backend/core/inference/offload_cost_model.py
+++ b/studio/backend/core/inference/offload_cost_model.py
@@ -55,17 +55,14 @@ REFERENCE_HOST_THREADS = 192
_THREAD_PARALLEL_MS_PER_GIB = 138.4
_THREAD_SERIAL_MS_PER_GIB = 5.57
-# across DIFFERENT machines the slope is steeper (12 cloud vCPUs are ~6 physical cores on one memory controller)
# The fit above varies threads on ONE machine; across DIFFERENT machines the slope is steeper (12 cloud vCPUs are ~6
# physical cores on one memory controller). Least squares over dense Q4 on 12 and 48 vCPU hosts (24.21 and 6.82 ms per
-# GiB) gives a = 278.2, b = 1.03. Neither fit dominates -- at 192 threads cross-machine predicts 2.48 vs 5.498 measured,
-# at 12 one-machine predicts 17.1 vs 24.21 -- so take whichever is MORE expensive: optimism quotes a spill that runs
-# several times slower than promised.
+# GiB) gives a = 278.2, b = 1.03. Neither fit dominates -- at 192 threads cross-machine predicts 2.48 vs 5.498
+# measured, at 12 one-machine predicts 17.1 vs 24.21 -- so take whichever is MORE expensive: optimism quotes a spill
+# that runs several times slower than promised.
_CROSS_HOST_PARALLEL_MS_PER_GIB = 278.2
_CROSS_HOST_SERIAL_MS_PER_GIB = 1.03
-# residual model/measured over 70 runs (T4, L4, A100, RTX PRO 6000 at 2-48 vCPU)
-
# Residual model/measured over 70 runs on T4, L4, A100 and RTX PRO 6000 (2, 8, 12, 48 vCPU), Qwen3.8-27B and
# Qwen3.6-35B-A3B at Q2_K_XL / Q4_K_XL / Q8_K_XL: medians 1.09 (48 cpu), 0.59 (12), 0.24 (8), 0.24 (2). One case stays
@@ -78,9 +75,7 @@ class Access(str, Enum):
# : Dense FFN: large contiguous matmuls, best case for the CPU backend.
CONTIGUOUS = "contiguous"
- # : lm_head: one tall matvec; parallelises worse than 64 independent FFN blocks and dequantises more bytes per
- # output element.
- # : lm_head: one tall matvec, usually higher-bit. Parallelises worse than 64 : independent FFN blocks and
+ # : lm_head: one tall matvec, usually higher-bit. Parallelises worse than 64 independent FFN blocks and
# dequantises more bytes per output element.
SINGLE_MATVEC = "single_matvec"
# : MoE experts: 8-of-256 scattered small matmuls per layer per token.
@@ -99,9 +94,8 @@ _RATE_RATIOS: dict[Access, float] = {
Access.KV_CACHE: 20.1,
}
-# bracketed by the two measurements (dense 49.4, MoE 66.9)
-# Prefill streaming bandwidth, GiB/s. Bracketed by the two measurements (dense 49.4, MoE 66.9); that spread is why this
-# is a coarse constant, not a curve.
+# Prefill streaming bandwidth, GiB/s. Bracketed by the two measurements (dense 49.4, MoE 66.9); that spread is why
+# this is a coarse constant, not a curve.
PREFILL_STREAM_GIB_S = 55.0
# Spilling several groups costs MORE than the sum of each alone -- contention, not amortisation. Measured 6% for the
diff --git a/studio/backend/core/inference/offload_layout.py b/studio/backend/core/inference/offload_layout.py
index bf1779a3984..1b98122c948 100644
--- a/studio/backend/core/inference/offload_layout.py
+++ b/studio/backend/core/inference/offload_layout.py
@@ -64,9 +64,8 @@ class ModelLayout:
recurrent_bytes: int = 0
n_ctx_train: int = 0
is_moe: bool = False
- # offloaded experts move only expert_used/expert_count per token, a dense FFN all of it
- # Sparse-MoE routing: experts read per token is expert_used/expert_count. Offloaded experts move only that fraction
- # per token, a dense FFN all of it.
+ # Sparse-MoE routing: experts read per token is expert_used/expert_count. Offloaded experts move only that
+ # fraction per token, a dense FFN all of it.
n_expert: int = 0
n_expert_used: int = 0
# ``blocks`` drops the trailing nextn/MTP blk.<N> tensors: block_count counts them (llama-model.cpp reads it into
@@ -82,11 +81,10 @@ class ModelLayout:
# from n_layer_all (llama-model.cpp:1449) puts those blocks on a GPU FIRST. llama.cpp's own fitter widens its
# offloadable-layer count the same way (common/fit.cpp:139-142). Zero when nothing was dropped.
excluded_block_bytes: int = 0
- # sliding-window attention interleaves window-sized and full-context caches per layer
# Sliding-window attention: some layers keep a window-sized cache, some the full context
- # (llama-kv-cache-iswa.cpp:69-104 builds two caches and filters each by hparams.is_swa(il)), interleaved per layer.
- # Every layer is still an attention layer, so n_attention_layers does NOT reveal this. A multi-device split has to
- # know WHERE the big caches land, so the planner abstains.
+ # (llama-kv-cache-iswa.cpp:69-104 builds two caches and filters each by hparams.is_swa(il)), interleaved per
+ # layer. Every layer is still an attention layer, so n_attention_layers does NOT reveal this. A multi-device split
+ # has to know WHERE the big caches land, so the planner abstains.
has_swa: bool = False
# False when a needed quantity could not be read. The planner abstains.
complete: bool = False
@@ -217,7 +215,6 @@ def _layout_from_readers(readers) -> ModelLayout:
kv_per_token = int(n_attention) * int(n_kv_head) * (int(key_len) + int(val_len)) * 2
- # charging every layer the full context is the safe direction for the TOTAL
# Charging every layer the full context above is the safe direction for the TOTAL; what it cannot say is which
# layers hold the big caches.
has_swa = bool(_field(reader, f"{arch}.attention.sliding_window") or 0)
@@ -282,11 +279,10 @@ def _layout_from_readers(readers) -> ModelLayout:
if not lm_head and token_embd:
other_resident += token_embd
- # trailing nextn/MTP blocks are not loaded unless a draft is engaged
- # Trailing nextn/MTP blocks are NOT part of the target model and are not loaded unless a draft is engaged, so an -ot
- # naming them moves nothing: measured, spilling only blk.<nextn> leaves the host buffer at exactly token_embd and
- # the device buffer unchanged. Counting them spillable would credit bytes that can never be freed. Unsloth prices
- # the drafter separately anyway.
+ # Trailing nextn/MTP blocks are NOT part of the target model and are not loaded unless a draft is engaged, so an
+ # -ot naming them moves nothing: measured, spilling only blk.<nextn> leaves the host buffer at exactly token_embd
+ # and the device buffer unchanged. Counting them spillable would credit bytes that can never be freed. Unsloth
+ # prices the drafter separately anyway.
all_block_indices = set(spill) | set(resident)
block_indices = sorted(i for i in all_block_indices if i < n_layers)
has_excluded = any(i >= n_layers for i in all_block_indices)
diff --git a/studio/backend/core/inference/offload_planner.py b/studio/backend/core/inference/offload_planner.py
index ac23c7a1c2a..8a3237680eb 100644
--- a/studio/backend/core/inference/offload_planner.py
+++ b/studio/backend/core/inference/offload_planner.py
@@ -70,7 +70,6 @@ class SpillOrder(Enum):
split), which would favour FRONT/BACK over LARGEST. Hence configurable.
"""
- # best-fit-decreasing: overshoot is real bandwidth, a 209 MiB block for a 50 MiB deficit wastes 159 MiB per token
# Best-fit-decreasing: fewest blocks AND least overshoot. Overshoot is real bandwidth -- a 209 MiB block for a 50
# MiB deficit wastes 159 MiB per token.
LARGEST_FIRST = "largest_first"
@@ -80,16 +79,14 @@ class SpillOrder(Enum):
@dataclass(frozen = True)
class PlanOptions:
- # Compute buffer + CUDA context + scratch, charged on every device. 1 GiB was too thin and failed CONSISTENTLY: the
- # planner fills to ``budget - overhead_bytes_per_device``, leaving exactly this much free whatever the budget is, so
- # the dense 27B at depth 32768 died identically at 6, 7, 8 and 10 GiB with
- # ggml_backend_cuda_buffer_type_alloc_buffer: allocating 594.16 MiB on device 0: cudaMalloc failed: out of memory
+ # Compute buffer + CUDA context + scratch, charged on every device. 1 GiB was too thin and failed CONSISTENTLY:
+ # the planner fills to ``budget - overhead_bytes_per_device``, leaving exactly this much free whatever the budget
+ # is, so the dense 27B at depth 32768 died identically at 6, 7, 8 and 10 GiB allocating 594.16 MiB on device 0.
# The child needs the PREFILL compute buffer (594 MiB measured) plus its own CUDA primary context, which took the
# rest of the old 1 GiB. Not benchmark fragmentation: 16, 64 and 1024 MiB hog blocks all reproduced the identical
- # 594.16 MiB failure. 1.5 GiB covers the measured 1.07 GiB with margin -- a measured floor, not a fitted curve,
- # since the steady-state compute buffer is flat in context (493 to 509 MiB from depth 4096 to 32768) but the prefill
- # graph's reservation is not. Erring high costs some spill (linear at 5.544 ms/GiB), erring low costs the whole
- # load.
+ # failure. 1.5 GiB covers the measured 1.07 GiB with margin -- a measured floor, not a fitted curve, since the
+ # steady-state compute buffer is flat in context (493 to 509 MiB from depth 4096 to 32768) but the prefill graph's
+ # reservation is not. Erring high costs some spill (linear at 5.544 ms/GiB), erring low costs the whole load.
overhead_bytes_per_device: int = (3 * GIB) // 2
# GPU-resident bytes NOT in the layout (a vision projector, an MTP draft reserve), charged once against the pooled
# budget: the layout only knows the target GGUF's tensor table. Subtracting from the budget also reaches
@@ -108,21 +105,19 @@ class PlanOptions:
min_ctx: int = 4096
spill_order: SpillOrder = SpillOrder.LARGEST_FIRST
allow_lm_head_spill: bool = True
- # spilled generation runs on the CPU backend (ggml only moves an op to the GPU at batch >= 32 and decode is batch 1)
- # What the host brings to bear on spilled weights. Spilled generation runs on the CPU backend -- ggml only moves an
- # op to the GPU at batch >= 32 (ggml-cuda.cu, op_offload_min_batch_size) and decode is batch 1 -- so the penalty
- # scales with core count: 2.42 / 5.83 / 11.82 / 14.94 t/s at 4 / 16 / 64 / 192 threads.
+ # What the host brings to bear on spilled weights. Spilled generation runs on the CPU backend -- ggml only moves
+ # an op to the GPU at batch >= 32 (ggml-cuda.cu, op_offload_min_batch_size) and decode is batch 1 -- so the
+ # penalty scales with core count: 2.42 / 5.83 / 11.82 / 14.94 t/s at 4 / 16 / 64 / 192 threads.
host: HostProfile = field(default_factory = HostProfile)
# q8_0 measured 35% slower generation, and without GGML_CUDA_FA_ALL_QUANTS only four MATCHED K/V combinations are
# compiled (a mismatched pair falls to CPU and stalls). Off by default; matched pairs only when enabled.
allow_kv_quant: bool = False
kv_quant_type: str = "q8_0"
- # with -nkvo llama.cpp puts the WHOLE cache on the host (offload is one scalar and the buffer type falls back to CPU
- # for every layer)
- # The caller passed -nkvo (or a false LLAMA_ARG_KV_OFFLOAD), so llama.cpp puts the WHOLE cache on the host: offload
- # is one scalar and the buffer type falls back to the CPU one for every layer (llama-kv-cache.cpp:210-219), same
- # branch in the recurrent and DSV4 caches. The cache and the recurrent state move out of the VRAM footprint and into
- # the host one; charging them to VRAM anyway would spill FFN blocks for a deficit the child never has.
+ # The caller passed -nkvo (or a false LLAMA_ARG_KV_OFFLOAD), so llama.cpp puts the WHOLE cache on the host:
+ # offload is one scalar and the buffer type falls back to the CPU one for every layer
+ # (llama-kv-cache.cpp:210-219), same branch in the recurrent and DSV4 caches. The cache and the recurrent state
+ # move out of the VRAM footprint and into the host one; charging them to VRAM anyway would spill FFN blocks for a
+ # deficit the child never has.
kv_on_host: bool = False
@@ -140,8 +135,6 @@ class Plan:
cache_type_v: Optional[str] = None
spilled_blocks: tuple[int, ...] = field(default_factory = tuple)
spilled_lm_head: bool = False
- # no rung fits; mmap has to stay, since it is the only thing that makes an over-commit pageable rather than
- # OOM-killed
# No rung fits. mmap has to stay, because it is the only thing that makes an over-commit pageable rather than
# OOM-killed.
insufficient: bool = False
@@ -533,10 +526,9 @@ def _per_device_usage(
) -> tuple[Optional[str], list[int], list[list[int]]]:
if len(vram_bytes_per_device) <= 1:
return None, [], []
- # recurrent hybrid, n_attention_layers short of n_layers
- # These three shapes -- recurrent hybrid, n_attention_layers short of n_layers, sliding window -- are only a problem
- # when the cache has to be spread evenly for want of anything better. A vector removes that guess; without one they
- # still abstain.
+ # These three shapes -- recurrent hybrid, n_attention_layers short of n_layers, sliding window -- are only a
+ # problem when the cache has to be spread evenly for want of anything better. A vector removes that guess; without
+ # one they still abstain.
uneven_cache = (
layout.recurrent_bytes > 0 or layout.n_attention_layers != layout.n_layers or layout.has_swa
)
@@ -898,10 +890,10 @@ def _finish(
patterns: list[str] = []
indices = sorted(b.index for b in chosen)
if indices:
- # One global pattern when every spillable block is going -- shorter, and the form the benchmarks used. NOT when
- # the GGUF carries blocks the layout dropped: the unbounded \d+ would also match the trailing nextn/MTP blocks,
- # whose ffn_*_exps load the moment a draft is engaged. That moves bytes neither host_bytes nor the deficit
- # counted (so the mmap decision is made on an undercount) and drags the draft FFN onto the CPU backend.
+ # One global pattern when every spillable block is going -- shorter, and the form the benchmarks used. NOT
+ # when the GGUF carries blocks the layout dropped: the unbounded \d+ would also match the trailing nextn/MTP
+ # blocks, whose ffn_*_exps load the moment a draft is engaged, moving bytes neither host_bytes nor the deficit
+ # counted (so the mmap decision is made on an undercount) and dragging the draft FFN onto the CPU backend.
spillable = [b.index for b in layout.blocks if b.spillable_bytes > 0]
all_of_them = set(indices) == set(spillable) and not layout.has_excluded_blocks
patterns.append(spill_pattern_for(layout, None if all_of_them else indices))
@@ -914,7 +906,6 @@ def _finish(
# token_embd is host-resident on every launch, so it is host RAM this plan must pay for even when nothing is spilled
host_bytes = layout.token_embd_bytes + spilled_bytes
if opts.kv_on_host:
- # -nkvo moved the cache and recurrent state out of VRAM
# -nkvo moved the cache and the recurrent state out of VRAM, not out of existence: they are host RAM now, and
# the mmap decision below has to see them or it answers against a footprint short by the whole cache.
host_bytes += (
@@ -946,8 +937,8 @@ def _finish(
n_ctx = n_ctx,
ot_patterns = tuple(patterns),
load_mode_none = load_mode_none,
- # matched pairs only: an unmatched K/V combination is not compiled without GGML_CUDA_FA_ALL_QUANTS and silently
- # falls back to CPU
+ # Matched pairs only: an unmatched K/V combination is not compiled without GGML_CUDA_FA_ALL_QUANTS and
+ # silently falls back to CPU.
cache_type_k = cache_type,
cache_type_v = cache_type,
spilled_blocks = tuple(indices),
diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.py
index 00579ea05c0..1c0e17a8b82 100644
--- a/studio/backend/core/inference/openai_auto_download.py
+++ b/studio/backend/core/inference/openai_auto_download.py
@@ -78,7 +78,6 @@ class _Active:
expected_bytes: int = 0
monitor_id: Optional[str] = None
started_at: float = 0.0
- # held until a retry surfaces it: Retry-After is far longer than the watcher poll
# Set when the worker failed. Held until a retry surfaces it: Retry-After is far longer than the watcher poll, so
# the client would restart the same failing download.
error: Optional[str] = None
@@ -430,8 +429,6 @@ async def _watch(active: _Active, hf_token: Optional[str]) -> None:
state, error = await _job_state(active.repo_id, active.variant)
if state in ("running", "cancelling", "unknown"):
if timed_out:
- # a running worker still owns the slot, and releasing on the clock alone would admit a second
- # multi-GB download beside it
# A running worker still owns the slot: releasing on the clock alone would admit a second multi-GB
# download beside it. "unknown" cannot confirm it is alive, so release then, or a broken probe
# wedges us.
@@ -876,7 +873,6 @@ def _bare_quant_alias(wanted: str, lowered: dict[str, str]) -> Optional[str]:
target = (wanted or "").strip().lower()
if not target:
return None
- # PATH-qualified keys only: an H3 root stem's bare quant names both partitions
# PATH-qualified keys only, not is_qualified_gguf_variant_key: an H3 root stem's bare quant names both partitions,
# so it must miss rather than serve one of them.
matches = [
@@ -967,10 +963,9 @@ async def _dispatch(
return busy
monitor_id = api_monitor.record_lifecycle(
- # only /v1 reaches auto-download, but that is not API-key traffic
# Reason "api" since only /v1 reaches auto-download, but that is not API-key traffic: Unsloth's chat calls /v1
- # on a JWT, and marking its download would pop the overlay mid-chat. So attribution comes from the request, plus
- # its caller, since the row is shared.
+ # on a JWT, and marking its download would pop the overlay mid-chat. So attribution comes from the request,
+ # plus its caller, since the row is shared.
event = "download",
model = label,
reason = "api",
diff --git a/studio/backend/core/inference/openai_codex_auth.py b/studio/backend/core/inference/openai_codex_auth.py
index a023fc46947..383add48da0 100644
--- a/studio/backend/core/inference/openai_codex_auth.py
+++ b/studio/backend/core/inference/openai_codex_auth.py
@@ -896,9 +896,8 @@ async def resolve_access(
raise CodexAuthError("ChatGPT connection was disconnected during refresh.")
if current.get("refresh_token") != previous_refresh_token:
return current["access_token"], current["account_id"]
- # a refresh rotates credentials without rebinding the connection
- # A refresh rotates credentials, it does not rebind the connection, so the record of which account the saved
- # models were proven for carries over. _validate_token_payload only knows about the token fields.
+ # A refresh rotates credentials, it does not rebind the connection, so the record of which account the
+ # saved models were proven for carries over. _validate_token_payload only knows about the token fields.
proof = current.get("catalog_account_id")
if proof is not None and refreshed.get("account_id") == current.get("account_id"):
refreshed["catalog_account_id"] = proof
diff --git a/studio/backend/core/inference/openai_codex_client.py b/studio/backend/core/inference/openai_codex_client.py
index f05d1b43220..0d15901f47a 100644
--- a/studio/backend/core/inference/openai_codex_client.py
+++ b/studio/backend/core/inference/openai_codex_client.py
@@ -232,9 +232,8 @@ _MODELS_CACHE_MAX_ENTRIES = 32
_models_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
# Outlives the cache TTL: a slug listed for this plan stays saveable afterwards.
_offered_models: dict[str, dict[str, dict[str, Any]]] = {}
-# a reauthorization can rebind a connection to a different account whose plan lists different slugs
-# Which ChatGPT account each cached catalog belongs to; a reauthorization can rebind a connection to a different account
-# whose plan lists different slugs.
+# Which ChatGPT account each cached catalog belongs to; a reauthorization can rebind a connection to a different
+# account whose plan lists different slugs.
_catalog_accounts: dict[str, str] = {}
@@ -247,11 +246,9 @@ def _normalize_subscription_model(item: Any) -> dict[str, Any] | None:
display_name = item.get("display_name")
context_window = item.get("context_window")
modalities = item.get("input_modalities")
- # `or []` only covers a falsy value, so a scalar raised TypeError out of the whole call and cost the catalog every
- # other entry too
- # Every other field here tolerates whatever upstream sends, and this one has to as well: `or []` only covers a falsy
- # value, so a scalar raised TypeError out of the whole call and cost the catalog every other entry too, not just
- # this one.
+ # Every other field here tolerates whatever upstream sends, and this one has to as well: `or []` only covers a
+ # falsy value, so a scalar raised TypeError out of the whole call and cost the catalog every other entry too, not
+ # just this one.
levels = item.get("supported_reasoning_levels")
efforts = [
level["effort"]
@@ -270,10 +267,9 @@ def _normalize_subscription_model(item: Any) -> dict[str, Any] | None:
),
"vision": "image" in modalities if isinstance(modalities, list) else None,
"reasoning_efforts": efforts,
- # "hide" is a presentation flag, not a revocation
# "hide" marks a slug no picker should offer (codex-auto-review, and models that age out of the list). It is a
- # presentation flag, not a revocation: the account can still call one it already saved, so the entry is kept and
- # marked instead of dropped, which is what lets callers tell "not offered" from "not on this plan".
+ # presentation flag, not a revocation: the account can still call one it already saved, so the entry is kept
+ # and marked instead of dropped, which is what lets callers tell "not offered" from "not on this plan".
"listed": item.get("visibility") == "list",
}
@@ -299,21 +295,18 @@ def offered_subscription_model_ids(provider_id: str) -> set[str]:
}
-# the absence is deliberate, so it must not read as "nothing fetched yet" and license the previous account's saved slugs
# Connections whose catalog was dropped because the account behind them changed. The absence is deliberate, so it must
# not read as "nothing fetched yet" and license the previous account's saved slugs.
_stale_catalogs: set[str] = set()
-# the ticket the newest catalog read holds
# The ticket the newest catalog read for each connection is holding, so a read that was overtaken (by a rebind, a
# disconnect, or a newer read) cannot commit its result over the one that replaced it.
_catalog_requests: dict[str, int] = {}
-# one shared counter, not per connection: nothing reads the number, only whether it still matches
# Tickets are drawn from one counter shared by every connection rather than counting up per connection. Nothing reads
# the number itself, only whether it still matches, and a value that is never reissued is what lets
-# forget_subscription_models drop the entry instead of leaving a larger one behind: a read still in flight then finds no
-# ticket at all, and the next read draws a number no earlier read can be holding.
+# forget_subscription_models drop the entry instead of leaving a larger one behind: a read still in flight then finds
+# no ticket at all, and the next read draws a number no earlier read can be holding.
_catalog_request_serial = 0
@@ -435,10 +428,9 @@ async def list_subscription_models(
status = 401,
) from exc
except Exception as exc:
- # the refresh got no answer, which is retryable
# The refresh did not get an answer, which is retryable. Calling it a reauthorization would send the
- # user to reconnect a connection whose credentials are probably fine, and the responses transport treats
- # the same failure as transient.
+ # user to reconnect a connection whose credentials are probably fine, and the responses transport
+ # treats the same failure as transient.
raise CodexTransportError("Could not refresh ChatGPT authorization.") from exc
response = await client.get(
url,
@@ -860,10 +852,8 @@ class OpenAICodexClient:
"schema": schema["schema"],
"strict": bool(schema.get("strict", True)),
}
- # ChatGPT's Codex Responses endpoint rejects max_output_tokens even though the public Responses API accepts it;
- # Pi intentionally does not forward a token cap here. ChatGPT's Codex Responses endpoint rejects
- # max_output_tokens even though the public Responses API accepts it; the subscription service applies its own
- # cap.
+ # ChatGPT's Codex Responses endpoint rejects max_output_tokens even though the public Responses API accepts
+ # it; the subscription service applies its own cap, and Pi intentionally does not forward a token cap here.
if reasoning_effort:
body["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
if tools:
diff --git a/studio/backend/core/inference/openai_codex_tool_loop.py b/studio/backend/core/inference/openai_codex_tool_loop.py
index e67e4baa820..03e39d2f848 100644
--- a/studio/backend/core/inference/openai_codex_tool_loop.py
+++ b/studio/backend/core/inference/openai_codex_tool_loop.py
@@ -100,7 +100,6 @@ def stream_codex_with_studio_tools(
messages = run.messages,
session_id = run.session_id,
thread_id = run.thread_id,
- # keep the Codex model id: the shared loop sums usage into one chunk
# Before this loop was shared, Codex relayed the provider's own usage chunks and they carried the Codex
# model id. The shared loop sums them into one synthetic chunk instead, so dropping the model here would
# relabel that accounting "external" and move behaviour the Codex path is meant to keep.
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index e040be03f2a..af1565fd66a 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -1,18 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Inference orchestrator — subprocess-based.
-
-Same API as InferenceBackend, but delegates all ML work to a persistent
-subprocess spawned on first model load and reused for later requests.
-
-When switching between models needing different transformers versions
-(e.g. GLM-4.7-Flash needs 5.x, Qwen needs 4.57.x), the old subprocess is
-killed and a new one spawned with the correct version.
-
-Pattern follows core/training/training.py.
-"""
+"""Inference orchestrator, subprocess-based. Same API as InferenceBackend, but delegates all ML work
+to a persistent subprocess spawned on first model load and reused for later requests. When
+switching between models needing different transformers versions (e.g. GLM-4.7-Flash needs 5.x,
+Qwen needs 4.57.x), the old subprocess is killed and a new one spawned with the correct version.
+Pattern follows core/training/training.py."""
import atexit
import base64
@@ -37,7 +30,6 @@ from core.inference.audio_errors import (
from utils.hardware import get_device, prepare_gpu_selection
from utils.utils import hf_env_offline
-# Re-exported via PEP 562, not a module-level import
# Re-exported from the shared helper so GGUF, training and inference share one type. Via PEP 562, not a module-level
# import: resolving the name imports unsloth_zoo, hence torch, and routes/inference.py imports this module at startup
# only for GenStream*.
@@ -67,10 +59,10 @@ _DISPATCH_STOP_TIMEOUT = 5.0
_DISPATCH_IDLE_TIMEOUT = 30.0
_DISPATCH_DRAIN_TIMEOUT = 5.0
-# Only bounds the Transformers subprocess path; llama.cpp TTS never reaches here. 120s was tuned against GGUF speeds and
-# killed real work: a safetensors LoRA on a mid-range GPU needs minutes for the same clip a GGUF returns in seconds. A
-# dead worker is already caught every second by _ensure_subprocess_alive, so this only has to bound one that is alive
-# and wedged, and a generous value costs nothing.
+# Only bounds the Transformers subprocess path; llama.cpp TTS never reaches here. 120s was tuned against GGUF speeds
+# and killed real work: a safetensors LoRA on a mid-range GPU needs minutes for the same clip a GGUF returns in
+# seconds. A dead worker is already caught every second by _ensure_subprocess_alive, so this only has to bound one
+# that is alive and wedged, and a generous value costs nothing.
_AUDIO_GENERATION_TIMEOUT = 900.0
_AUDIO_GENERATION_BASE_TOKENS = 2048
AUDIO_GENERATION_MAX_TOKENS = 8192
@@ -82,8 +74,8 @@ _AUDIO_CANCEL_DRAIN_TIMEOUT = 5.0
# model the user just loaded.
_AUDIO_CANCEL_TEARDOWN_TIMEOUT = 30.0
-# Max wait for a cancelled generation to release _gen_lock before unload_model tears the subprocess down. Only bounds a
-# wedged worker.
+# Max wait for a cancelled generation to release _gen_lock before unload_model tears the subprocess down. Only bounds
+# a wedged worker.
_UNLOAD_GEN_LOCK_TIMEOUT = 15.0
@@ -92,16 +84,12 @@ def _audio_generation_timeout(
base: Optional[float] = None,
max_tokens: Optional[int] = None,
) -> float:
- """Scale a floor by the requested token count.
-
- ``base`` differs per backend by an order of magnitude: the Transformers subprocess
- needs minutes for a clip llama.cpp returns in seconds, so llama_cpp.py passes its
- own. Sharing one base silently gave every GGUF read the Transformers budget, which
- holds other_inference_request_count() up and blocks idle auto-unload for that long.
-
- Resolved at call time, not bound as a default: a default is evaluated once at import,
- so reassigning the module constant afterwards had no effect.
- """
+ """Scale a floor by the requested token count. ``base`` differs per backend by an order of
+ magnitude: the Transformers subprocess needs minutes for a clip llama.cpp returns in seconds,
+ so llama_cpp.py passes its own; sharing one base silently gave every GGUF read the
+ Transformers budget, which holds other_inference_request_count() up and blocks idle
+ auto-unload for that long. Resolved at call time, not bound as a default: a default is
+ evaluated once at import, so reassigning the module constant afterwards had no effect."""
if base is None:
base = _AUDIO_GENERATION_TIMEOUT
if max_tokens is None:
@@ -123,22 +111,17 @@ _MLX_RUNTIME_MIRROR_FIELDS = (
def _mlx_runtime_mirror_fields(model_info: dict) -> dict:
- """MLX runtime state the parent mirrors, omitting what was not reported.
-
- Only the MLX backend sends these. Creating the keys for every backend would
- make the reload comparison see a None the backend never stored, and reload
- on every identical request.
- """
+ """MLX runtime state the parent mirrors, omitting what was not reported. Only the MLX backend
+ sends these. Creating the keys for every backend would make the reload comparison see a None
+ the backend never stored, and reload on every identical request."""
return {key: model_info[key] for key in _MLX_RUNTIME_MIRROR_FIELDS if key in model_info}
class GenStreamError(str):
- """A stream chunk carrying a real backend/generation error, not model text.
-
- Subclasses str so existing display/logging consumers are unaffected, while
- callers can distinguish a real error from model output whose visible text
- starts with "Error:" by checking isinstance(chunk, GenStreamError).
- """
+ """A stream chunk carrying a real backend/generation error, not model text. Subclasses str so
+ existing display/logging consumers are unaffected, while callers can distinguish a real error
+ from model output whose visible text starts with "Error:" by checking isinstance(chunk,
+ GenStreamError)."""
__slots__ = ("public",)
@@ -169,13 +152,11 @@ class GenStreamErrorRaised(RuntimeError):
def _summed_tool_loop_stats(total, turn):
- """Fold one tool-loop turn's report into the loop's running total.
-
- Every turn spends its tokens on the same request, so the reply reports their
- sum, as the llama.cpp tool loop does; reporting only the last turn hides the
- tokens that produced the tool call. The prompt count is the last turn's to
- report one, which already contains the tool results the earlier turns produced.
- """
+ """Fold one tool-loop turn's report into the loop's running total. Every turn spends its tokens
+ on the same request, so the reply reports their sum, as the llama.cpp tool loop does;
+ reporting only the last turn hides the tokens that produced the tool call. The prompt count
+ is the last turn's to report one, which already contains the tool results the earlier turns
+ produced."""
if not isinstance(turn, dict):
return total
if not isinstance(total, dict):
@@ -184,8 +165,8 @@ def _summed_tool_loop_stats(total, turn):
usage = dict(turn.get("usage") or {})
completion = (usage.get("completion_tokens") or 0) + (prior_usage.get("completion_tokens") or 0)
usage["completion_tokens"] = completion
- # The prompt is the loop's, not one turn's, so a turn that ended before reporting keeps the last count that arrived.
- # Its details describe that same count and move with it, or cached tokens could outnumber prompt tokens.
+ # The prompt is the loop's, not one turn's, so a turn that ended before reporting keeps the last count that
+ # arrived. Its details describe that same count and move with it, or cached tokens could outnumber prompt tokens.
if not usage.get("prompt_tokens"):
usage["prompt_tokens"] = prior_usage.get("prompt_tokens") or 0
usage.pop("prompt_tokens_details", None)
@@ -202,13 +183,13 @@ def _summed_tool_loop_stats(total, turn):
summed["usage"] = usage
timings = dict(turn.get("timings") or {})
prior = total.get("timings") or {}
- # Seeded from the turn but folded unconditionally, as the llama.cpp loop does: a turn reporting no timings must not
- # take the loop's totals with it.
+ # Seeded from the turn but folded unconditionally, as the llama.cpp loop does: a turn reporting no timings must
+ # not take the loop's totals with it.
if timings or prior:
for field in ("predicted_ms", "predicted_n"):
timings[field] = (timings.get(field) or 0) + (prior.get(field) or 0)
- # Rates describe the totals above, not the turn they arrived with: leaving the last turn's would report a speed
- # the summed counts contradict.
+ # Rates describe the totals above, not the turn they arrived with: leaving the last turn's would report a
+ # speed the summed counts contradict.
predicted_ms = timings.get("predicted_ms") or 0
predicted_n = timings.get("predicted_n") or 0
timings["predicted_per_token_ms"] = (predicted_ms / predicted_n) if predicted_n else 0.0
@@ -220,12 +201,9 @@ def _summed_tool_loop_stats(total, turn):
def _mirrored_model_entry(model_info: dict, model_name: str) -> dict:
- """The parent's view of a model the worker holds.
-
- Measured or classified in the subprocess and unrecoverable once the model lives
- there, so a field the worker sends and this does not copy is one the API can never
- report.
- """
+ """The parent's view of a model the worker holds. Measured or classified in the subprocess and
+ unrecoverable once the model lives there, so a field the worker sends and this does not copy
+ is one the API can never report."""
return {
"is_vision": model_info.get("is_vision", False),
"is_lora": model_info.get("is_lora", False),
@@ -243,12 +221,9 @@ def _mirrored_model_entry(model_info: dict, model_name: str) -> dict:
class InferenceOrchestrator:
- """
- Inference backend orchestrator — subprocess-based.
-
- Same API surface as InferenceBackend (so routes/inference.py needs
- minimal changes); all heavy ML work happens in a persistent subprocess.
- """
+ """Inference backend orchestrator, subprocess-based. Same API surface as InferenceBackend (so
+ routes/inference.py needs minimal changes); all heavy ML work happens in a persistent
+ subprocess."""
def __init__(self):
self._proc: Optional[mp.Process] = None
@@ -272,17 +247,17 @@ class InferenceOrchestrator:
# model
self._unload_pending = False
# Blocking TTS has no token response that can safely establish worker ownership while it is queued behind
- # compare-mode work. Reserve the dispatcher admission lane for the whole TTS request so its shared cancel event
- # cannot hit a sibling. Mutated under _dispatcher_lifecycle_lock while holding _gen_lock.
+ # compare-mode work. Reserve the dispatcher admission lane for the whole TTS request so its shared cancel
+ # event cannot hit a sibling. Mutated under _dispatcher_lifecycle_lock while holding _gen_lock.
self._exclusive_tts_pending = False
self._exclusive_vram_probe_pending = False
- # Dispatcher state for compare mode: bypass _gen_lock
# Dispatcher state for compare mode (adapter-controlled requests): bypass _gen_lock, send commands directly,
# read from per-request mailboxes routed by a dispatcher thread on request_id.
self._mailboxes: dict[str, queue.Queue] = {}
# request_id -> cancel event, so the dispatcher can move worker ownership as it routes. Consumers read their
- # mailbox whenever they get to it, so only the dispatcher sees responses in the order the worker produced them.
+ # mailbox whenever they get to it, so only the dispatcher sees responses in the order the worker produced
+ # them.
self._request_cancel_events: dict[str, object] = {}
# Mailboxes for the _gen_lock generations. Kept apart from _mailboxes because that map means "compare requests
# are in flight" to the unload and distributed paths.
@@ -290,12 +265,10 @@ class InferenceOrchestrator:
self._mailbox_lock = threading.Lock()
self._dispatcher_thread: Optional[threading.Thread] = None
self._dispatcher_stop = threading.Event()
- # Serializes dispatcher start/stop. the orphan later steals the "unloaded" reply off resp_queue and hangs
- # unload_model
# Serializes dispatcher start/stop. _generate_dispatched (compare mode) bypasses _gen_lock, so two concurrent
- # compare requests can both reach _start_dispatcher; without this lock both could observe no live dispatcher and
- # each spawn one, orphaning the extra thread (self._dispatcher_thread tracks only the last). The orphan later
- # steals the "unloaded" reply off resp_queue and hangs unload_model.
+ # compare requests can both reach _start_dispatcher; without this lock both could observe no live dispatcher
+ # and each spawn one, orphaning the extra thread (self._dispatcher_thread tracks only the last). The orphan
+ # later steals the "unloaded" reply off resp_queue and hangs unload_model.
self._dispatcher_lifecycle_lock = threading.Lock()
# Local state mirrors (updated from subprocess responses)
@@ -325,8 +298,6 @@ class InferenceOrchestrator:
# would call huggingface.co on every boot. First reader starts it.
self._top_models_started = False
- # ------------------------------------------------------------------ Default models (top GGUFs fetched dynamically
- # from HF) ------------------------------------------------------------------
def _refresh_static_models_if_stale(self) -> None:
"""Recompute the curated defaults if hardware was re-detected since."""
import utils.hardware.hardware as _hw_mod
@@ -350,17 +321,15 @@ class InferenceOrchestrator:
logger.info("hardware was re-detected; curated default models refreshed")
def _start_top_models_fetch(self) -> None:
- """Kick the remote ranking fetch once, on first read of the model list.
-
- Guarded by the construction lock, so two concurrent first-readers cannot each put up
- a thread. Skipped when the host asked for no outbound calls: the fetch is a raw
- httpx.get, so HF_HUB_OFFLINE does not reach it on its own. Via hf_env_offline(), not
- a literal "1" test, since HF_HUB_OFFLINE=true/on and TRANSFORMERS_OFFLINE count too.
- """
+ """Kick the remote ranking fetch once, on first read of the model list. Guarded by the
+ construction lock, so two concurrent first-readers cannot each put up a thread. Skipped
+ when the host asked for no outbound calls: the fetch is a raw httpx.get, so
+ HF_HUB_OFFLINE does not reach it on its own. Via hf_env_offline(), not a literal "1"
+ test, since HF_HUB_OFFLINE=true/on and TRANSFORMERS_OFFLINE count too."""
if self._top_models_started:
return
- # Checked before the latch: claiming it while offline would retire the fetch for the process, so an offline boot
- # or a temporary force_hf_offline() could never recover.
+ # Checked before the latch: claiming it while offline would retire the fetch for the process, so an offline
+ # boot or a temporary force_hf_offline() could never recover.
if hf_env_offline():
logger.info("offline mode requested; skipping the remote top-models ranking")
return
@@ -410,8 +379,8 @@ class InferenceOrchestrator:
hub_ids = [
m["id"] for m in models if not m.get("id", "").upper().endswith("-GGUF")
][:40]
- # Counts at info, ids at debug: two lists of 40 repo names cost ~1.5 KB of every boot to say the catalog
- # fetch worked
+ # Counts at info, ids at debug: two lists of 40 repo names cost ~1.5 KB of every boot to say the
+ # catalog fetch worked
if gguf_ids:
self._top_gguf_cache = gguf_ids
logger.info("Fetched %d top GGUF models", len(gguf_ids))
@@ -430,7 +399,6 @@ class InferenceOrchestrator:
config: dict,
cache_environment: Optional[Mapping[str, str]] = None,
) -> None:
- """Spawn a new inference subprocess."""
from utils.transformers_version import (
SidecarSwapInProgress,
sidecar_swap_kind,
@@ -538,22 +506,19 @@ class InferenceOrchestrator:
self._cancel_event.set()
def is_worker_alive(self) -> bool:
- """True while the inference subprocess is running, even with no model
- active (a failed load can leave a live worker holding sidecar modules)."""
+ """True while the inference subprocess is running, even with no model active (a failed load
+ can leave a live worker holding sidecar modules)."""
proc = self._proc
return proc is not None and proc.is_alive()
def post_handoff_gpu_availability_gb(
self,
) -> Optional[tuple[dict[int, float], dict[int, float], dict[int, float]]]:
- """Atomically snapshot live free, total and disposable-worker VRAM.
-
- The worker is queried only while idle. This avoids retaining a load-time
- allocator value after reset_generation_state() releases cache, and it keeps
- compare-mode's queue reader from consuming the probe response. The send
- lock spans the system and worker reads, so a reset cannot make the same
- cache bytes appear in both values.
- """
+ """Atomically snapshot live free, total and disposable-worker VRAM. The worker is queried
+ only while idle, which avoids retaining a load-time allocator value after
+ reset_generation_state() releases cache and keeps compare-mode's queue reader from
+ consuming the probe response. The send lock spans the system and worker reads, so a reset
+ cannot make the same cache bytes appear in both values."""
proc = self._proc
active = self.active_model_name
if proc is None or not proc.is_alive() or not active:
@@ -624,12 +589,10 @@ class InferenceOrchestrator:
return self._shutdown_subprocess_locked(timeout)
def _shutdown_subprocess_locked(self, timeout: float) -> bool:
- """Gracefully shut down the inference subprocess.
-
- Returns True only once the worker is confirmed dead. If it survives
- terminate/kill (e.g. wedged in an uninterruptible CUDA syscall that outlives
- SIGKILL) the live handle is KEPT, not nulled, so is_worker_alive() and the
- pre-swap liveness guard can still observe the survivor instead of a cleared
+ """Gracefully shut down the inference subprocess. Returns True only once the worker is
+ confirmed dead. If it survives terminate/kill (e.g. wedged in an uninterruptible CUDA
+ syscall that outlives SIGKILL) the live handle is KEPT, not nulled, so is_worker_alive()
+ and the pre-swap liveness guard can still observe the survivor instead of a cleared
handle and refuse the destructive sidecar swap."""
self._stop_dispatcher() # before killing subprocess
if self._proc is None or not self._proc.is_alive():
@@ -759,22 +722,19 @@ class InferenceOrchestrator:
< max(tolerance_mib, int(max(current[index], previous[index]) * 0.02))
for index in current
)
- # Two unchanged low samples can precede delayed driver reclaim. Stability is meaningful only after an upward
- # release was observed; otherwise consume the full bounded window.
+ # Two unchanged low samples can precede delayed driver reclaim. Stability is meaningful only after an
+ # upward release was observed; otherwise consume the full bounded window.
if stable and observed_reclaim and not expected_mib:
return True
previous = current
return not expected_free_gb
def _reset_worker_scoped_state(self) -> None:
- """Drop bookkeeping that only means anything for the worker that just died.
-
- Ownership is scoped by cancel-event identity alone, so a consumer still blocked
- on its mailbox when the process was replaced stayed recorded as the executor. A
- generation on the fresh worker then failed _owns_worker and could not be stopped.
- Mailboxes go too: nothing will ever route to them, and a stale one reads as
- compare activity to the unload path.
- """
+ """Drop bookkeeping that only means anything for the worker that just died. Ownership is
+ scoped by cancel-event identity alone, so a consumer still blocked on its mailbox when
+ the process was replaced stayed recorded as the executor, and a generation on the fresh
+ worker then failed _owns_worker and could not be stopped. Mailboxes go too: nothing will
+ ever route to them, and a stale one reads as compare activity to the unload path."""
with self._active_cancel_lock:
self._active_cancel_events.clear()
self._executing_cancel_events.clear()
@@ -784,11 +744,9 @@ class InferenceOrchestrator:
self._request_cancel_events.clear()
def _cleanup(self):
- """atexit handler."""
self._shutdown_subprocess(timeout = 5.0)
def _ensure_subprocess_alive(self) -> bool:
- """True if the subprocess is alive."""
return self._proc is not None and self._proc.is_alive()
def _subprocess_crash_message(self, context: str) -> str:
@@ -827,7 +785,6 @@ class InferenceOrchestrator:
return f"{message} Details: pid={pid}, exitcode={exitcode}."
def _send_cmd(self, cmd: dict) -> None:
- """Send a command to the subprocess."""
if self._cmd_queue is None:
raise RuntimeError("No inference subprocess running")
try:
@@ -853,17 +810,13 @@ class InferenceOrchestrator:
expected_request_id: Optional[str] = None,
cancel_event: Optional[threading.Event] = None,
) -> dict:
- """Block until a response of the expected type arrives.
-
- Also handles 'status' and 'error' events during the wait. Returns the
- matching response dict; raises RuntimeError on timeout or crash.
-
- *timeout* is an **inactivity** timeout: it resets on each status
- message, so long-running operations (large downloads, slow loads)
- survive as long as the subprocess keeps reporting progress.
- """
- # Local: resolving this name runs the shim's lazy unsloth_zoo load, which pulls torch. The shim caches its pick,
- # so this site and load_model()'s `except` see one class.
+ """Block until a response of the expected type arrives. Also handles 'status' and 'error'
+ events during the wait. Returns the matching response dict; raises RuntimeError on
+ timeout or crash. *timeout* is an **inactivity** timeout: it resets on each status
+ message, so long-running operations (large downloads, slow loads) survive as long as the
+ subprocess keeps reporting progress."""
+ # Local: resolving this name runs the shim's lazy unsloth_zoo load, which pulls torch. The shim caches its
+ # pick, so this site and load_model()'s `except` see one class.
from utils.hf_xet_fallback import DownloadStallError
deadline = time.monotonic() + timeout
@@ -912,7 +865,6 @@ class InferenceOrchestrator:
)
def _drain_queue(self) -> list:
- """Drain all pending responses."""
events = []
if self._resp_queue is None:
return events
@@ -927,12 +879,11 @@ class InferenceOrchestrator:
def _direct_reader(self, request_id: str):
"""Response reader for a _gen_lock generation, safe once compare exists.
- The dispatcher and this reader would otherwise both consume _resp_queue. A
- dispatcher started mid-stream took our responses and dropped them as
- unaddressed (truncating or hanging the chat), and this reader, already blocked
- on the queue, could take a compare request's response before that dispatcher
- saw it. Registering a mailbox fixes the first; handing foreign responses to
- their own mailbox fixes the second.
+ The dispatcher and this reader would otherwise both consume _resp_queue. A dispatcher
+ started mid-stream took our responses and dropped them as unaddressed (truncating or hanging
+ the chat), and this reader, already blocked on the queue, could take a compare request's
+ response before that dispatcher saw it. Registering a mailbox fixes the first; handing
+ foreign responses to their own mailbox fixes the second.
Returns (read_one, drain, release).
"""
@@ -995,11 +946,8 @@ class InferenceOrchestrator:
return read_one, drain, release
def _drain_until_gen_done(self, timeout: float = 5.0) -> None:
- """Consume resp_queue events until gen_done/gen_error, discarding them.
-
- Called after cancel so stale tokens from the cancelled generation
- don't leak into the next request.
- """
+ """Consume resp_queue events until gen_done/gen_error, discarding them. Called after cancel
+ so stale tokens from the cancelled generation don't leak into the next request."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
resp = self._read_resp(timeout = min(0.5, deadline - time.monotonic()))
@@ -1012,8 +960,6 @@ class InferenceOrchestrator:
return
logger.warning("Timed out waiting for gen_done after cancel")
- # ------------------------------------------------------------------ Generation command + token-stream helpers
- # (shared by all paths) ------------------------------------------------------------------
def _build_generate_cmd(
self,
request_id: str,
@@ -1088,15 +1034,11 @@ class InferenceOrchestrator:
read_timeout: float = 30.0,
mark_started: bool = True,
) -> Generator[str, None, None]:
- """Yield tokens from a response stream until gen_done/gen_error.
-
- ``read_one(timeout)`` returns the next response (or None on timeout) and
- owns the queue choice — the shared resp_queue under _gen_lock, or a
- per-request mailbox on the dispatcher path — so this loop stays agnostic
- of which queue is read. On cancel, ``drain_on_cancel()`` consumes the
- cancel ack from that same source so stale events don't leak into the
- next request.
- """
+ """Yield tokens from a response stream until gen_done/gen_error. ``read_one(timeout)``
+ returns the next response (or None on timeout) and owns the queue choice -- the shared
+ resp_queue under _gen_lock, or a per-request mailbox on the dispatcher path -- so this
+ loop stays agnostic of which queue is read. On cancel, ``drain_on_cancel()`` consumes the
+ cancel ack from that same source so stale events don't leak into the next request."""
# Latch this stream's subprocess/queue: if a wedged worker is torn down and a later load spawns a fresh one,
# bail rather than re-block on the new queue under _gen_lock (deadlock).
initial_proc = self._proc
@@ -1121,9 +1063,9 @@ class InferenceOrchestrator:
rtype = resp.get("type", "")
if rtype == "status":
continue
- # The worker is answering THIS request, so it is the one executing: only now may its cancel event speak for
- # the shared worker one. The dispatched path opts out: its dispatcher already did this in worker order,
- # which a mailbox read can lag behind.
+ # The worker is answering THIS request, so it is the one executing: only now may its cancel event speak
+ # for the shared worker one. The dispatched path opts out: its dispatcher already did this in worker
+ # order, which a mailbox read can lag behind.
if mark_started:
self._mark_worker_started(cancel_event)
# Subprocess-level error (no request_id); request-scoped failures arrive as gen_error below
@@ -1133,8 +1075,8 @@ class InferenceOrchestrator:
if rtype == "token":
if cancel_event is not None and cancel_event.is_set():
- # Same rule as reset_generation_state: the shared worker event may only be set by the generation the
- # worker is running. A dispatched request can still be draining stale mailbox tokens after the
+ # Same rule as reset_generation_state: the shared worker event may only be set by the generation
+ # the worker is running. A dispatched request can still be draining stale mailbox tokens after the
# dispatcher retired it, and signalling from here would end the next one instead. Tearing this
# stream down is always safe, so the local drain happens either way.
if self._owns_worker(cancel_event):
@@ -1150,26 +1092,20 @@ class InferenceOrchestrator:
yield GenStreamError(f"Error: {resp.get('error', 'Unknown error')}")
return
- # ------------------------------------------------------------------ Dispatcher - per-request mailbox routing for
- # compare mode ------------------------------------------------------------------
def _start_dispatcher(self) -> bool:
- """Start the dispatcher thread if not already running.
-
- The dispatcher reads the shared resp_queue and routes responses to
- per-request mailbox queues, letting multiple adapter-controlled
- (compare) requests be in-flight without holding _gen_lock.
-
- The whole check-then-spawn runs under _dispatcher_lifecycle_lock so
- concurrent compare requests (which bypass _gen_lock) can't both observe
- no live dispatcher and each spawn one. Returns True only for the caller
- that actually started a new thread; False if one was already alive.
- """
+ """Start the dispatcher thread if not already running. The dispatcher reads the shared
+ resp_queue and routes responses to per-request mailbox queues, letting multiple
+ adapter-controlled (compare) requests be in-flight without holding _gen_lock. The whole
+ check-then-spawn runs under _dispatcher_lifecycle_lock so concurrent compare requests
+ (which bypass _gen_lock) can't both observe no live dispatcher and each spawn one.
+ Returns True only for the caller that actually started a new thread; False if one was
+ already alive."""
with self._dispatcher_lifecycle_lock:
# Refuse to start while an unload is in progress. unload_model sets _unload_pending under this same lock
# before it stops the idle dispatcher, so a start queued behind that stop observes the unload here and
- # bails. Without this a fresh dispatcher would be spawned after the stop, become the resp_queue reader, and
- # consume the worker's "unloaded" reply (unroutable, so dropped) before unload_model's _wait_response sees
- # it -- hanging the unload 300s.
+ # bails. Without this a fresh dispatcher would be spawned after the stop, become the resp_queue reader,
+ # and consume the worker's "unloaded" reply (unroutable, so dropped) before unload_model's _wait_response
+ # sees it -- hanging the unload 300s.
if (
self._unload_pending
or self._exclusive_tts_pending
@@ -1190,13 +1126,10 @@ class InferenceOrchestrator:
return True
def _stop_dispatcher(self) -> None:
- """Signal the dispatcher to stop and wait for it.
-
- Runs under _dispatcher_lifecycle_lock (paired with _start_dispatcher) so
- a stop can't interleave with a concurrent start. Callers must NOT hold
- _mailbox_lock here: this joins the dispatcher, and the dispatcher loop
- takes _mailbox_lock, so holding it would deadlock the join.
- """
+ """Signal the dispatcher to stop and wait for it. Runs under _dispatcher_lifecycle_lock
+ (paired with _start_dispatcher) so a stop can't interleave with a concurrent start.
+ Callers must NOT hold _mailbox_lock here: this joins the dispatcher, and the dispatcher
+ loop takes _mailbox_lock, so holding it would deadlock the join."""
with self._dispatcher_lifecycle_lock:
if self._dispatcher_thread is None:
return
@@ -1206,7 +1139,7 @@ class InferenceOrchestrator:
logger.debug("Dispatcher thread stopped")
def _dispatcher_loop(self) -> None:
- """Background loop: read resp_queue → route to mailboxes by request_id."""
+ """Background loop: read resp_queue and route to mailboxes by request_id."""
while not self._dispatcher_stop.is_set():
if self._resp_queue is None:
break
@@ -1280,12 +1213,10 @@ class InferenceOrchestrator:
logit_bias: Optional[dict] = None,
stop: Optional[list] = None,
) -> Generator[str, None, None]:
- """Dispatched generation — sends command without holding _gen_lock.
-
- Uses a per-request mailbox for tokens so two compare-mode requests can
- be queued at once. The subprocess still runs commands sequentially, so
- GPU work stays serialized; this only avoids orchestrator lock contention.
- """
+ """Dispatched generation, sending the command without holding _gen_lock. Uses a per-request
+ mailbox for tokens so two compare-mode requests can be queued at once. The subprocess
+ still runs commands sequentially, so GPU work stays serialized; this only avoids
+ orchestrator lock contention."""
if not self._ensure_subprocess_alive():
yield GenStreamError("Error: Inference subprocess is not running", public = True)
return
@@ -1306,12 +1237,11 @@ class InferenceOrchestrator:
yield GenStreamError("Error: audio generation is in progress", public = True)
return
- # _start_dispatcher serializes concurrent starters and returns True only for the caller that spawned the thread.
- # Ensure the dispatcher runs. _start_dispatcher serializes concurrent starters under _dispatcher_lifecycle_lock
- # and returns True only for the caller that spawned the thread, so at most one dispatcher ever exists even when
- # two compare requests race here. Derive dispatcher_preexisting from that atomic result (not a separate unlocked
- # is_alive() read): if THIS call started the dispatcher and then bails on a racing unload, it must stop it again
- # (see the unloading bail below).
+ # Ensure the dispatcher runs. _start_dispatcher serializes concurrent starters under
+ # _dispatcher_lifecycle_lock and returns True only for the caller that spawned the thread, so at most one
+ # dispatcher ever exists even when two compare requests race here. Derive dispatcher_preexisting from that
+ # atomic result (not a separate unlocked is_alive() read): if THIS call started the dispatcher and then bails
+ # on a racing unload, it must stop it again (see the unloading bail below).
started = self._start_dispatcher()
dispatcher_preexisting = not started
@@ -1374,8 +1304,8 @@ class InferenceOrchestrator:
# A racing unload can pass its _wait_dispatcher_idle() while the dispatcher was stopped, then set
# _unload_pending. The one we just started would otherwise linger with no mailboxes, race unload_model's
# _wait_response for the "unloaded" reply off resp_queue, and drop it as unroutable -- hanging the unload
- # 300s. Stop it here so the unload stays the sole resp_queue reader. Outside _mailbox_lock: _stop_dispatcher
- # joins the dispatcher, which itself takes that lock.
+ # 300s. Stop it here so the unload stays the sole resp_queue reader. Outside _mailbox_lock:
+ # _stop_dispatcher joins the dispatcher, which itself takes that lock.
if orphaned_dispatcher:
self._stop_dispatcher()
detail = (
@@ -1421,8 +1351,8 @@ class InferenceOrchestrator:
mark_started = False,
)
finally:
- # Normally already retired by the dispatcher at gen_done; this covers streams that end without one (cancel,
- # disconnect, a dead subprocess).
+ # Normally already retired by the dispatcher at gen_done; this covers streams that end without one
+ # (cancel, disconnect, a dead subprocess).
self._release_worker(cancel_event)
with self._mailbox_lock:
self._mailboxes.pop(request_id, None)
@@ -1448,15 +1378,11 @@ class InferenceOrchestrator:
logger.warning("Timed out draining mailbox after cancel")
def _wait_dispatcher_idle(self, cancel_event = None) -> bool:
- """Wait for all dispatched requests to complete, then stop dispatcher.
-
- Returns True if the dispatcher was stopped (all mailboxes drained, or no
- dispatcher was running), and False if it was left running because compare
- requests were still active after _DISPATCH_IDLE_TIMEOUT.
-
- Callers must reserve admission before using this as an exclusive handoff;
- TTS does so under _gen_lock, while older direct paths call it before the lock.
- """
+ """Wait for all dispatched requests to complete, then stop dispatcher. Returns True if the
+ dispatcher was stopped (all mailboxes drained, or no dispatcher was running), and False
+ if it was left running because compare requests were still active after
+ _DISPATCH_IDLE_TIMEOUT. Callers must reserve admission before using this as an exclusive
+ handoff; TTS does so under _gen_lock, while older direct paths call it before the lock."""
if self._dispatcher_thread is None or not self._dispatcher_thread.is_alive():
return True
@@ -1539,8 +1465,6 @@ class InferenceOrchestrator:
raise RuntimeError("Timeout waiting for distributed object share")
- # Monotonic count of PUBLISHED loads, so the install route can detect a load (including a same-model reload) that
- # completed
# Monotonic count of PUBLISHED loads; lets the install route detect a load (including a same-model reload) that
# completed while it waited on the gate. Bumped when the load result is published, not at load start: a start-time
# bump is already visible when the installer snapshots mid-load, so the completed reload would look unchanged and
@@ -1570,11 +1494,8 @@ class InferenceOrchestrator:
anonymous_hf_access: bool = False,
audio_codec_path: Optional[str] = None,
) -> bool:
- """Load a model for inference.
-
- Always spawns a fresh subprocess per load for a clean interpreter (no
- stale unsloth patches, torch.compile caches, or getsource failures).
- """
+ """Load a model for inference. Always spawns a fresh subprocess per load for a clean
+ interpreter (no stale unsloth patches, torch.compile caches, or getsource failures)."""
from utils.transformers_version import needs_transformers_5
from utils.hf_xet_fallback import DownloadStallError
@@ -1614,9 +1535,8 @@ class InferenceOrchestrator:
if audio_codec_path is not None:
sub_config["audio_codec_path"] = audio_codec_path
if audio_device_forces_cpu(audio_device) and is_native_audio_model(model_name):
- # Choosing a card for a load that takes none harms it twice: several
- # GPUs are rejected as unsupported sharding, and required_gb becomes
- # expected_free_gb, so the settle wait raises on a busy card.
+ # Choosing a card for a load that takes none harms it twice: several GPUs are rejected as unsupported
+ # sharding, and required_gb becomes expected_free_gb, so the settle wait raises on a busy card.
resolved_gpu_ids, gpu_selection = None, {"selection_mode": "cpu_audio"}
else:
resolved_gpu_ids, gpu_selection = prepare_gpu_selection(
@@ -1637,7 +1557,8 @@ class InferenceOrchestrator:
# Recheck the sidecar reservation BEFORE tearing the old worker down, for REPAIRS only: an install holds
# this same lifecycle gate, so it cannot swap while this load runs, and its queued-load snapshot aborts it
- # after this load publishes -- the load wins cleanly. Raising here (repair) keeps the current model loaded.
+ # after this load publishes -- the load wins cleanly. Raising here (repair) keeps the current model
+ # loaded.
from utils.transformers_version import (
SidecarSwapInProgress,
sidecar_swap_kind,
@@ -1657,9 +1578,9 @@ class InferenceOrchestrator:
self._cancel_generation()
time.sleep(0.3)
if self._shutdown_subprocess() is False:
- # The worker survived terminate/kill (e.g. a wedged CUDA syscall that outlives SIGKILL). Its handle
- # is kept, so is_worker_alive() and the pre-swap guard still see it; do not spawn a second worker
- # over one still holding GPU memory. Fail so the load can retry once it exits.
+ # The worker survived terminate/kill (e.g. a wedged CUDA syscall that outlives SIGKILL). Its
+ # handle is kept, so is_worker_alive() and the pre-swap guard still see it; do not spawn a second
+ # worker over one still holding GPU memory. Fail so the load can retry once it exits.
raise RuntimeError(
"The current inference worker did not exit and still holds GPU "
"memory; not starting a new model over it. Retry shortly."
@@ -1726,9 +1647,9 @@ class InferenceOrchestrator:
# A cancel can land after the pre-spawn recheck but while _spawn_subprocess is still creating the
# queues/process. cancel_load runs off the lifecycle gate, so its _shutdown_subprocess can see _proc
- # still None and no-op, orphaning this fresh worker; the load would then wait for "loaded" and publish a
- # model /unload reported unloaded, over a live subprocess nothing reaps. Recheck now the child exists
- # and tear it down before publishing.
+ # still None and no-op, orphaning this fresh worker; the load would then wait for "loaded" and publish
+ # a model /unload reported unloaded, over a live subprocess nothing reaps. Recheck now the child
+ # exists and tear it down before publishing.
if model_name not in self.loading_models or (
load_cancel_event is not None and load_cancel_event.is_set()
):
@@ -1851,8 +1772,8 @@ class InferenceOrchestrator:
raise
self.active_model_name = None
self.models.clear()
- # Reap workers after any failed load, including inactivity timeouts that leave installs and GPU memory alive
- # (#9398)
+ # Reap workers after any failed load, including inactivity timeouts that leave installs and GPU memory
+ # alive (#9398)
try:
self._shutdown_subprocess(timeout = 5)
except Exception as teardown_exc:
@@ -1860,16 +1781,13 @@ class InferenceOrchestrator:
raise
def cancel_load(self, model_name: str) -> bool:
- """Abort an in-flight load by terminating its subprocess.
-
- Returns True if a load for ``model_name`` (matched case-insensitively) was
- cancelled, False if nothing was loading under that name. This only tears the
- loading subprocess down -- it sends no command to a worker -- so, unlike the
- rest of ``unload_model``, it is safe to run WITHOUT the inference lifecycle
- gate. ``/unload`` calls it off-gate so the "stop loading" button can interrupt
- a safetensors load that holds the gate for its whole (multi-minute) duration;
- a gated cancel could never preempt that load.
- """
+ """Abort an in-flight load by terminating its subprocess. Returns True if a load for
+ ``model_name`` (matched case-insensitively) was cancelled, False if nothing was loading
+ under that name. This only tears the loading subprocess down -- it sends no command to a
+ worker -- so, unlike the rest of ``unload_model``, it is safe to run WITHOUT the
+ inference lifecycle gate. ``/unload`` calls it off-gate so the "stop loading" button can
+ interrupt a safetensors load that holds the gate for its whole (multi-minute) duration; a
+ gated cancel could never preempt that load."""
target = model_name
if target not in self.loading_models:
target = next(
@@ -1882,7 +1800,6 @@ class InferenceOrchestrator:
"Cancelling in-flight load for model '%s' by terminating subprocess",
target,
)
- # Discard the loading marker BEFORE the teardown
# Discard the loading marker (and clear local state) BEFORE the teardown, not after. cancel_load runs off the
# lifecycle gate, alongside a load_model that rechecks this marker before each spawn. But _shutdown_subprocess
# can block (~1s tearing a live child down and joining the dispatcher), so clearing only after leaves a window
@@ -1893,8 +1810,8 @@ class InferenceOrchestrator:
self.models.clear()
self._shutdown_subprocess(timeout = 0.5)
# Clear the local mirrors again AFTER the teardown. A racing off-gate load_model may still be parked in
- # _wait_response("loaded"): its worker already queued a "loaded" reply, so during the shutdown window above (the
- # 0.5s settle before the response queue is drained and nulled) that thread can consume it and repopulate
+ # _wait_response("loaded"): its worker already queued a "loaded" reply, so during the shutdown window above
+ # (the 0.5s settle before the response queue is drained and nulled) that thread can consume it and repopulate
# active_model_name/models, undoing the pre-teardown clear. _shutdown_subprocess nulls the queue but not the
# mirrors, so without this second clear /unload reports success while the backend still advertises a killed
# model. The nulled queue lets no further "loaded" through, so re-clearing here wipes any repopulation.
@@ -1902,11 +1819,9 @@ class InferenceOrchestrator:
self.models.clear()
return True
- # --- Dictation models ------------------------------------------------- These run in the STT sidecars
- # (whisper-server, llama-server, and the Transformers spawn child), not the chat worker. Their lifecycle goes
- # through here all the same, so one object knows everything that is resident and Voice settings and Model Hub cannot
- # report different things about one model.
- # --- Dictation models -------------------------------------------------
+ # Dictation models run in the STT sidecars (whisper-server, llama-server, and the Transformers spawn child), not
+ # the chat worker. Their lifecycle goes through here all the same, so one object knows everything that is resident
+ # and Voice settings and Model Hub cannot report different things about one model.
def load_stt_model(
self,
model: Optional[str],
@@ -1914,10 +1829,8 @@ class InferenceOrchestrator:
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
) -> None:
- """Make a dictation model resident on its sidecar.
-
- ``device`` is the user's audio device preference (``auto``/``cpu``/``gpu``).
- """
+ """Make a dictation model resident on its sidecar. ``device`` is the user's audio device
+ preference (``auto``/``cpu``/``gpu``)."""
from core.inference import stt_registry
stt_registry.load(model, engine, request_cancel_event, device = device)
@@ -1927,12 +1840,10 @@ class InferenceOrchestrator:
expected_model: Optional[str] = None,
wait: bool = True,
) -> list:
- """Release dictation models (all engines by default); returns refusals.
-
- ``expected_model`` scopes the release to a sidecar still holding that model.
- ``wait=False`` leaves a sidecar that is mid-request alone, for a caller
- freeing memory opportunistically rather than to reclaim it now.
- """
+ """Release dictation models (all engines by default); returns refusals. ``expected_model``
+ scopes the release to a sidecar still holding that model. ``wait=False`` leaves a sidecar
+ that is mid-request alone, for a caller freeing memory opportunistically rather than to
+ reclaim it now."""
from core.inference import stt_registry
return stt_registry.unload(engines, wait = wait, expected_model = expected_model)
@@ -1942,10 +1853,9 @@ class InferenceOrchestrator:
return stt_registry.resident()
def unload_model(self, model_name: str) -> bool:
- """Unload a model from the subprocess."""
- # active_model_name can differ in case from the client's raw /unload name (the load path canonicalizes casing).
- # Match case-insensitively and use the canonical spelling so the guard, unload command, and cleanup below hit
- # the loaded model.
+ # active_model_name can differ in case from the client's raw /unload name (the load path canonicalizes
+ # casing). Match case-insensitively and use the canonical spelling so the guard, unload command, and cleanup
+ # below hit the loaded model.
if (
self.active_model_name is not None
and model_name != self.active_model_name
@@ -1962,25 +1872,24 @@ class InferenceOrchestrator:
self.active_model_name = None
return True
- # Nothing loaded under this name: the worker falls back to unloading its *active* model when the name is absent
# Nothing loaded under this name: don't unload a stale model. The worker falls back to unloading its *active*
# model when the name is absent, so a stale unload (lost a race to a concurrent load) would hit the wrong one.
if model_name != self.active_model_name and model_name not in self.models:
self.models.pop(model_name, None)
return True
- # The subprocess runs commands sequentially, so a bare unload queues behind a running generate (a 2-3 min hang).
- # Cancel first (via the mp.Event the worker polls each token), then take _gen_lock as sole resp_queue reader
- # (like GGUF). Set _unload_pending under _dispatcher_lifecycle_lock so it is ordered ahead of the dispatcher
- # stop that _wait_dispatcher_idle runs under the same lock: a compare request's _start_dispatcher queued behind
- # that stop then observes the unload and refuses to spawn a fresh dispatcher that would eat the "unloaded" reply
- # off resp_queue. This is a standalone acquisition (no _gen_lock held yet), so it keeps the _gen_lock ->
- # _dispatcher_lifecycle_lock order and can't deadlock.
+ # The subprocess runs commands sequentially, so a bare unload queues behind a running generate (a 2-3 min
+ # hang). Cancel first (via the mp.Event the worker polls each token), then take _gen_lock as sole resp_queue
+ # reader (like GGUF). Set _unload_pending under _dispatcher_lifecycle_lock so it is ordered ahead of the
+ # dispatcher stop that _wait_dispatcher_idle runs under the same lock: a compare request's _start_dispatcher
+ # queued behind that stop then observes the unload and refuses to spawn a fresh dispatcher that would eat the
+ # "unloaded" reply off resp_queue. This is a standalone acquisition (no _gen_lock held yet), so it keeps the
+ # _gen_lock -> _dispatcher_lifecycle_lock order and can't deadlock.
with self._dispatcher_lifecycle_lock:
self._unload_pending = True
- # Cancelling only the running generation isn't enough: the worker clears cancel_event at each generate start, so
- # a queued one would clear it and run the outgoing model to completion. drain_event, never cleared, makes any
- # generate dequeued during the unload skip.
+ # Cancelling only the running generation isn't enough: the worker clears cancel_event at each generate start,
+ # so a queued one would clear it and run the outgoing model to completion. drain_event, never cleared, makes
+ # any generate dequeued during the unload skip.
if self._drain_event is not None:
self._drain_event.set()
try:
@@ -1999,8 +1908,8 @@ class InferenceOrchestrator:
return True
try:
- # Stop the compare-mode dispatcher so it can't consume the "unloaded" reply off resp_queue before we do.
- # A dispatched generation bypasses _gen_lock, so a wedged one slips past the acquire above; if the
+ # Stop the compare-mode dispatcher so it can't consume the "unloaded" reply off resp_queue before we
+ # do. A dispatched generation bypasses _gen_lock, so a wedged one slips past the acquire above; if the
# dispatcher is still active it owns resp_queue and the queued unload hangs _wait_response behind the
# stuck generate.
if not self._wait_dispatcher_idle():
@@ -2027,9 +1936,9 @@ class InferenceOrchestrator:
self.active_model_name = None
logger.info("Model '%s' unloaded from subprocess", model_name)
- # empty_cache in the child cannot return the accelerator context, so an idle worker keeps its high-water
- # mark -- VRAM the GGUF backend cannot see and gpu_arbiter never evicts (both are chat-owned). Nothing
- # left to serve, so drop it; load_model respawns a fresh worker regardless.
+ # empty_cache in the child cannot return the accelerator context, so an idle worker keeps its
+ # high-water mark -- VRAM the GGUF backend cannot see and gpu_arbiter never evicts (both are
+ # chat-owned). Nothing left to serve, so drop it; load_model respawns a fresh worker regardless.
if not self.models and not self.loading_models:
logger.info("No models left resident; shutting the inference subprocess down")
try:
@@ -2062,12 +1971,10 @@ class InferenceOrchestrator:
preserve_thinking: Optional[bool] = None,
timeout: float = 30.0,
) -> tuple[int, Optional[str]]:
- """Prompt tokens the loaded model would receive, and whose tokenizer counted them.
-
- Reads through an addressed mailbox, as generations do: compare mode bypasses the
- generation lock and leaves a dispatcher owning the response queue, which would
- route this reply nowhere.
- """
+ """Prompt tokens the loaded model would receive, and whose tokenizer counted them. Reads
+ through an addressed mailbox, as generations do: compare mode bypasses the generation
+ lock and leaves a dispatcher owning the response queue, which would route this reply
+ nowhere."""
if not self._gen_lock.acquire(blocking = False):
raise RuntimeError("Cannot count tokens while a generation is in progress")
request_id = str(uuid.uuid4())
@@ -2135,18 +2042,12 @@ class InferenceOrchestrator:
logit_bias: Optional[dict] = None,
stop: Optional[list] = None,
) -> Generator[str, None, None]:
- """Generate response, streaming tokens from subprocess.
-
- ``tools`` / ``enable_thinking`` / ``reasoning_effort`` /
- ``preserve_thinking`` are forwarded so the template can render tool
- schemas and reasoning controls.
-
- ``stats_holder``: caller-owned dict; on gen_done its "stats" key gets
- the worker's usage, timings and terminal reason. Request-scoped to avoid
- cross-stream reads.
-
- ``presence_penalty`` matches the GGUF sampling path (0 disables it).
- """
+ """Generate response, streaming tokens from subprocess. ``tools`` / ``enable_thinking`` /
+ ``reasoning_effort`` / ``preserve_thinking`` are forwarded so the template can render
+ tool schemas and reasoning controls. ``stats_holder`` is a caller-owned dict whose
+ "stats" key gets the worker's usage, timings and terminal reason on gen_done;
+ request-scoped to avoid cross-stream reads. ``presence_penalty`` matches the GGUF
+ sampling path (0 disables it)."""
yield from self._generate_inner(
messages = messages,
system_prompt = system_prompt,
@@ -2209,21 +2110,17 @@ class InferenceOrchestrator:
seed: Optional[int] = None,
**_unused,
):
- """Run the safetensors agentic tool loop in the parent process,
- calling the worker for each turn.
-
- Yields the same event dicts as the GGUF tool loop so the route layer
- can stream both backends through one helper.
- """
+ """Run the safetensors agentic tool loop in the parent process, calling the worker for each
+ turn. Yields the same event dicts as the GGUF tool loop so the route layer can stream
+ both backends through one helper."""
from core.inference.safetensors_agentic import run_safetensors_tool_loop
from core.inference.tools import execute_tool
max_new_tokens = max_tokens if max_tokens and max_tokens > 0 else 2048
- # The worker's usage for the LATEST turn only. Hoisted out of the turn so the
- # loop can size a conversation search against a real prompt count, and cleared
- # on the way in rather than on each way out, so a turn that failed or was
- # cancelled leaves it empty instead of handing the loop an earlier turn's number.
+ # The worker's usage for the LATEST turn only. Hoisted out of the turn so the loop can size a conversation
+ # search against a real prompt count, and cleared on the way in rather than on each way out, so a turn that
+ # failed or was cancelled leaves it empty instead of handing the loop an earlier turn's number.
turn_stats: dict = {}
def _single_turn(
@@ -2232,8 +2129,8 @@ class InferenceOrchestrator:
active_tools: Optional[list[dict]] = None,
tool_protocol_active: Optional[bool] = None,
):
- # ``conv`` already carries any system message. ``active_tools`` lets run_safetensors_tool_loop drop one-shot
- # tools (e.g. render_html) from later same-response prompts.
+ # ``conv`` already carries any system message. ``active_tools`` lets run_safetensors_tool_loop drop
+ # one-shot tools (e.g. render_html) from later same-response prompts.
turn_tools = active_tools if active_tools is not None else tools
turn_stats.clear()
common_kwargs = dict(
@@ -2285,7 +2182,8 @@ class InferenceOrchestrator:
close()
except Exception:
logger.debug("failed to close errored generation stream", exc_info = True)
- # A turn that never reported (one a cancel interrupted) folds in as nothing, leaving the turns that did
+ # A turn that never reported (one a cancel interrupted) folds in as nothing, leaving the turns that
+ # did
if stats_holder is not None:
stats_holder["stats"] = _summed_tool_loop_stats(
stats_holder.get("stats"), turn_stats.get("stats")
@@ -2347,13 +2245,10 @@ class InferenceOrchestrator:
stats_holder: Optional[dict] = None,
**gen_kwargs,
) -> Generator[str, None, None]:
- """Generate with adapter control, streaming tokens from subprocess.
-
- Uses the dispatcher path (no _gen_lock) so compare-mode requests
- don't block each other; the subprocess serializes them via its
- sequential command loop. Backend failures raise instead of becoming
- assistant text.
- """
+ """Generate with adapter control, streaming tokens from subprocess. Uses the dispatcher path
+ (no _gen_lock) so compare-mode requests don't block each other; the subprocess serializes
+ them via its sequential command loop. Backend failures raise instead of becoming
+ assistant text."""
stream = self._generate_dispatched(
use_adapter = use_adapter,
cancel_event = cancel_event,
@@ -2398,11 +2293,9 @@ class InferenceOrchestrator:
logit_bias: Optional[dict] = None,
stop: Optional[list] = None,
) -> Generator[str, None, None]:
- """Inner generation logic — sends command to subprocess, yields tokens.
-
- Serialized by _gen_lock (one generation at a time) so concurrent
- readers don't consume each other's tokens off the shared resp_queue.
- """
+ """Inner generation logic: sends the command to the subprocess and yields tokens. Serialized
+ by _gen_lock (one generation at a time) so concurrent readers don't consume each other's
+ tokens off the shared resp_queue."""
if not self._ensure_subprocess_alive():
yield GenStreamError("Error: Inference subprocess is not running", public = True)
return
@@ -2475,23 +2368,18 @@ class InferenceOrchestrator:
release_mailbox()
def _claim_worker(self, cancel_event) -> None:
- """Record this request as one the worker will run.
-
- Admission only. The subprocess executes generations one at a time, so a
- dispatched request sitting behind another in the command queue is claimed
- but not executing, and must not be able to signal the shared cancel event
- (that would end whichever request IS executing). _mark_worker_started
- promotes it once the worker answers it.
- """
+ """Record this request as one the worker will run. Admission only: the subprocess executes
+ generations one at a time, so a dispatched request sitting behind another in the command
+ queue is claimed but not executing, and must not be able to signal the shared cancel
+ event (that would end whichever request IS executing). _mark_worker_started promotes it
+ once the worker answers it."""
with self._active_cancel_lock:
self._active_cancel_events.append(cancel_event)
def _mark_worker_started(self, cancel_event) -> None:
- """Promote a claimed request to executing, on its first worker response.
-
- Sole executor: the subprocess runs one generation at a time, so answering
- this one means it has left the previous one behind.
- """
+ """Promote a claimed request to executing, on its first worker response. Sole executor: the
+ subprocess runs one generation at a time, so answering this one means it has left the
+ previous one behind."""
if cancel_event is None:
return
with self._active_cancel_lock:
@@ -2507,34 +2395,27 @@ class InferenceOrchestrator:
pass
def _owns_worker(self, cancel_event) -> bool:
- """Whether a reset from this request may signal the shared cancel event.
-
- True when it is one of the EXECUTING generations, and when nothing is in
- flight at all: an error path that resets before anything started has no
- one else to interrupt, so it must not become a silent no-op. Claimed but
- queued does not count, or a Stop on a queued request would end the
- running one, including during the prefill before any response arrives.
- """
+ """Whether a reset from this request may signal the shared cancel event. True when it is one
+ of the EXECUTING generations, and when nothing is in flight at all: an error path that
+ resets before anything started has no one else to interrupt, so it must not become a
+ silent no-op. Claimed but queued does not count, or a Stop on a queued request would end
+ the running one, including during the prefill before any response arrives."""
with self._active_cancel_lock:
if not self._active_cancel_events:
return True
if self._executing_cancel_events:
return any(ev is cancel_event for ev in self._executing_cancel_events)
- # Claimed but nothing has answered yet.
- # Claimed but nothing has answered yet (A is in prefill). The worker takes commands in order, so the oldest
- # claim is the executor; anyone else here is queued behind it.
+ # Claimed but nothing has answered yet (A is in prefill). The worker takes commands in order, so the
+ # oldest claim is the executor; anyone else here is queued behind it.
return self._active_cancel_events[0] is cancel_event
def reset_generation_state(self, caller_cancel_event = None):
- """Cancel any ongoing generation and reset state.
-
- ``caller_cancel_event`` scopes the reset to one request. The worker has a
- single cancel event and generation is serialized on _gen_lock, so a chat
- that is still queued has no generation of its own to reset: calling this
- from its Stop handler would kill whichever chat currently holds the lock.
- Pass the request's own event and the reset is dropped unless that request
- is the one running. Omit it for genuinely global resets (unload, switch).
- """
+ """Cancel any ongoing generation and reset state. ``caller_cancel_event`` scopes the reset
+ to one request. The worker has a single cancel event and generation is serialized on
+ _gen_lock, so a chat that is still queued has no generation of its own to reset: calling
+ this from its Stop handler would kill whichever chat currently holds the lock. Pass the
+ request's own event and the reset is dropped unless that request is the one running. Omit
+ it for genuinely global resets (unload, switch)."""
if caller_cancel_event is not None and not self._owns_worker(caller_cancel_event):
return
self._cancel_generation()
@@ -2546,9 +2427,6 @@ class InferenceOrchestrator:
except RuntimeError:
pass
- # ------------------------------------------------------------------ Audio generation - TTS, ASR, audio input
- # ------------------------------------------------------------------
-
def generate_audio_response(
self,
text: str,
@@ -2564,10 +2442,8 @@ class InferenceOrchestrator:
language: Optional[str] = None,
seed: Optional[int] = None,
) -> Tuple[bytes, int]:
- """Generate TTS audio. Returns (wav_bytes, sample_rate).
-
- Blocking — sends command and waits for the full audio response.
- """
+ """Generate TTS audio. Returns (wav_bytes, sample_rate). Blocking: sends the command and
+ waits for the full audio response."""
if not self._ensure_subprocess_alive():
raise RuntimeError("Inference subprocess is not running")
if not self.active_model_name:
@@ -2640,8 +2516,8 @@ class InferenceOrchestrator:
# Same shared-queue hazard as _generate_inner: see _direct_reader.
read_one, _drain, release_mailbox = self._direct_reader(request_id)
try:
- # Claim before enqueueing so request-scoped reset ownership follows the same discipline as text and
- # audio-input generation
+ # Claim before enqueueing so request-scoped reset ownership follows the same discipline as text
+ # and audio-input generation
with self._send_order_lock:
self._claim_worker(cancel_event)
self._send_cmd(cmd)
@@ -2669,8 +2545,8 @@ class InferenceOrchestrator:
# erased or hit an earlier request.
self._cancel_generation()
cancel_signalled = True
- # The cancel is delivered now, so hold the worker to the drain window from here rather than
- # from when the caller asked
+ # The cancel is delivered now, so hold the worker to the drain window from here rather
+ # than from when the caller asked
cancel_deadline = time.monotonic() + _AUDIO_CANCEL_DRAIN_TIMEOUT
deadline = min(deadline, cancel_deadline)
remaining = max(0.1, deadline - time.monotonic())
@@ -2717,9 +2593,9 @@ class InferenceOrchestrator:
if rtype == "status":
continue
- # A caller cancellation already spent the drain window polling this request's mailbox. Tear down an
- # unresponsive worker now instead of waiting out the much longer generation watchdog or draining
- # twice.
+ # A caller cancellation already spent the drain window polling this request's mailbox. Tear down
+ # an unresponsive worker now instead of waiting out the much longer generation watchdog or
+ # draining twice.
if cancel_deadline is not None:
if self._shutdown_subprocess(timeout = _AUDIO_CANCEL_DRAIN_TIMEOUT):
self.active_model_name = None
@@ -2750,7 +2626,7 @@ class InferenceOrchestrator:
cancel_event = None,
stats_holder: Optional[dict] = None,
) -> Generator[str, None, None]:
- """Whisper ASR — sends audio to subprocess, yields text."""
+ """Whisper ASR: sends audio to the subprocess and yields text."""
yield from self._generate_audio_input_inner(
audio_array = audio_array,
audio_type = "whisper",
@@ -2776,7 +2652,7 @@ class InferenceOrchestrator:
stats_holder: Optional[dict] = None,
stop = None,
) -> Generator[str, None, None]:
- """Audio input generation (e.g. Gemma 3n) — streams text tokens."""
+ """Audio input generation (e.g. Gemma 3n): streams text tokens."""
yield from self._generate_audio_input_inner(
audio_array = audio_array,
audio_type = None, # worker uses generate_audio_input_response
@@ -2811,11 +2687,9 @@ class InferenceOrchestrator:
stats_holder: Optional[dict] = None,
stop = None,
) -> Generator[str, None, None]:
- """Shared inner logic for audio input generation (Whisper + ASR).
-
- ``stats_holder``: as in generate_chat_response — caller-owned, filled on
- gen_done with the worker's usage / budget report.
- """
+ """Shared inner logic for audio input generation (Whisper + ASR). ``stats_holder``: as in
+ generate_chat_response, caller-owned and filled on gen_done with the worker's usage /
+ budget report."""
if not self._ensure_subprocess_alive():
yield GenStreamError("Error: Inference subprocess is not running", public = True)
return
@@ -2825,8 +2699,8 @@ class InferenceOrchestrator:
expected_model = self.active_model_name
with self._gen_lock:
- # Recheck under the lock (see _generate_inner): a raced unload/switch may have cleared or swapped the model
- # while we waited.
+ # Recheck under the lock (see _generate_inner): a raced unload/switch may have cleared or swapped the
+ # model while we waited.
if self._unload_pending or self.active_model_name != expected_model:
yield GenStreamError("Error: model is being unloaded", public = True)
return
@@ -2881,9 +2755,6 @@ class InferenceOrchestrator:
self._release_worker(cancel_event)
release_mailbox()
- # ------------------------------------------------------------------ Local helpers (no subprocess needed)
- # ------------------------------------------------------------------
-
def resize_image(
self,
img,
@@ -2912,11 +2783,9 @@ class InferenceOrchestrator:
return self.active_model_name
def is_model_loading(self) -> bool:
- """True if any model is loading."""
return len(self.loading_models) > 0
def get_loading_model(self) -> Optional[str]:
- """Name of the currently loading model."""
return next(iter(self.loading_models)) if self.loading_models else None
def check_vision_model_compatibility(self) -> bool:
@@ -2931,20 +2800,17 @@ class InferenceOrchestrator:
return is_gpt_oss_model_name(model_name or self.active_model_name or "")
-# ========== GLOBAL INSTANCE ==========
_inference_backend = None
-# Guards the lazy construction below. The first build runs hardware detection, seconds cold, and first-paint routes call
-# this getter from executor threads. Unlocked, several would see None and each build an orchestrator, orphaning all but
-# the last plus any load on them.
+# Guards the lazy construction below. The first build runs hardware detection, seconds cold, and first-paint routes
+# call this getter from executor threads. Unlocked, several would see None and each build an orchestrator, orphaning
+# all but the last plus any load on them.
_inference_backend_lock = threading.Lock()
def peek_inference_backend() -> Optional["InferenceOrchestrator"]:
- """The orchestrator if one exists, else None. Never constructs one.
-
- For callers that only describe what is already loaded: constructing reaches
- get_default_models() -> get_device(), which blocks on the torch import during the warm.
- """
+ """The orchestrator if one exists, else None. Never constructs one. For callers that only
+ describe what is already loaded: constructing reaches get_default_models() -> get_device(),
+ which blocks on the torch import during the warm."""
return _inference_backend
diff --git a/studio/backend/core/inference/passthrough_healing.py b/studio/backend/core/inference/passthrough_healing.py
index 2b0e64242a7..20c6275b4bc 100644
--- a/studio/backend/core/inference/passthrough_healing.py
+++ b/studio/backend/core/inference/passthrough_healing.py
@@ -35,7 +35,6 @@ from core.inference.tool_loop_controller import (
)
from core.tool_healing import parse_tool_calls_from_text
-# narrower than the loops' TOOL_XML_SIGNALS
# Only the formats this healer's parser can promote -- narrower than the loops' broader TOOL_XML_SIGNALS. A loop-only
# marker (Llama <|python_tag|>, bare [ARGS]) would buffer a streamed call as prose without promoting it, so keep a
# healer-aligned list. Mistral's [TOOL_CALLS] IS promotable, so it stays in.
@@ -65,9 +64,8 @@ def nudge_enabled(request_flag: Optional[bool]) -> bool:
_MAX_SIGNAL_LEN = max(len(s) for s in _HEAL_SIGNALS)
-# a suspected-but-unclosed block larger than this is a false alarm, bounding memory on XML-lookalike prose
-# A suspected-but-unclosed tool block larger than this is declared a false alarm and flushed, bounding memory on a model
-# rambling XML-lookalike text.
+# A suspected-but-unclosed tool block larger than this is declared a false alarm and flushed, bounding memory on a
+# model rambling XML-lookalike text.
_MAX_HOLD_CHARS = 64 * 1024
@@ -329,14 +327,11 @@ class StreamToolCallHealer:
self._buffer = ""
self._holding = False
self._id_offset = 0
- # promotion is destructive, so a caller DISCARDING a promoted call (a turn truncated at finish_reason "length")
- # has no other way to give the model's words back
- # Markup span each promoted call was cut from, keyed by its call id. Promotion is destructive -- the span never
- # reaches the client -- so a caller that ends up DISCARDING a promoted call (a turn truncated at finish_reason
- # "length" cannot be executed) has no other way to give the model's own words back. Bounded by _MAX_HOLD_CHARS
- # per span.
+ # Markup span each promoted call was cut from, keyed by its call id. Promotion is destructive -- the span
+ # never reaches the client -- so a caller that ends up DISCARDING a promoted call (a turn truncated at
+ # finish_reason "length" cannot be executed) has no other way to give the model's own words back. Bounded by
+ # _MAX_HOLD_CHARS per span.
self._promoted_spans: dict[str, str] = {}
- # structured delta.tool_calls upstream means grammar mode worked, so healing goes dormant
# Structured delta.tool_calls seen upstream: grammar mode already worked, so healing goes dormant and text
# relays verbatim.
self.dormant = False
diff --git a/studio/backend/core/inference/presence_penalty.py b/studio/backend/core/inference/presence_penalty.py
index 4b855d4c710..c112c432c17 100644
--- a/studio/backend/core/inference/presence_penalty.py
+++ b/studio/backend/core/inference/presence_penalty.py
@@ -24,11 +24,10 @@ def apply_presence_penalty(input_ids, scores, penalty: float, prompt_len: int):
if generated.numel() == 0:
continue
seen = torch.unique(generated)
- # drop out-of-range/negative ids before indexing: a negative id would wrap to the wrong row
- # Bound generated ids to the valid range [0, vocab_size). Real completion tokens are always in range, so this is
- # a zero-regression safety net that drops any stray out-of-range or negative id before indexing (mirrors the MLX
- # path's bound). Filtering both ends avoids indexing scores with a negative id (which would silently wrap to the
- # wrong row).
+ # Bound generated ids to the valid range [0, vocab_size). Real completion tokens are always in range, so this
+ # is a zero-regression safety net that drops any stray out-of-range or negative id before indexing (mirrors
+ # the MLX path's bound). Filtering both ends avoids indexing scores with a negative id, which would silently
+ # wrap to the wrong row.
seen = seen[(seen >= 0) & (seen < vocab_size)]
if seen.numel():
scores[b, seen] = scores[b, seen] - penalty
diff --git a/studio/backend/core/inference/pricing.py b/studio/backend/core/inference/pricing.py
index add4bbafecb..f6d43c02053 100644
--- a/studio/backend/core/inference/pricing.py
+++ b/studio/backend/core/inference/pricing.py
@@ -110,7 +110,6 @@ OPENAI_WEB_SEARCH_USD_PER_1K = 10.0
OPENAI_CONTAINER_USD_PER_HOUR = 0.09 # 1g default tier
-# Sonnet 5 launched at $2/$10 per MTok through 2026-08-31 while ANTHROPIC_PRICING carries the standard $3/$15
# Claude Sonnet 5 launched on introductory pricing of $2/$10 per MTok, in force through 2026-08-31; ANTHROPIC_PRICING
# carries the standard $3/$15 that takes over on 2026-09-01. Billing the standard rate early overstates every Sonnet 5
# turn by 50%, so overlay the launch rate while it lasts. The entry expires on its own and can be deleted after the
@@ -190,9 +189,8 @@ def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str
"cache_read_input_tokens" in usage and usage.get("cache_read_input_tokens") is not None
)
cache_read = max(0, int(usage.get("cache_read_input_tokens") or 0))
- # an explicit native cache_read_input_tokens of 0 is authoritative
- # Fall back to mirrored prompt_tokens_details only when native cache_read_input_tokens is absent; an explicit native
- # 0 is authoritative, so a stale proxy mirror can't inflate cache_read.
+ # Fall back to mirrored prompt_tokens_details only when native cache_read_input_tokens is absent; an explicit
+ # native 0 is authoritative, so a stale proxy mirror can't inflate cache_read.
if not cache_read_native_present:
details = usage.get("prompt_tokens_details") or {}
if isinstance(details, dict):
diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.py
index 432ed4999d5..3f53814f8fe 100644
--- a/studio/backend/core/inference/providers.py
+++ b/studio/backend/core/inference/providers.py
@@ -1,12 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Static registry of supported external LLM providers.
-
-All providers expose OpenAI-compatible /v1/chat/completions endpoints
-with Bearer token auth and SSE streaming.
-"""
+"""Static registry of supported external LLM providers. All expose OpenAI-compatible
+/v1/chat/completions endpoints with Bearer token auth and SSE streaming."""
import ipaddress
import os
@@ -447,12 +443,10 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
def get_provider_info(provider_type: str) -> dict[str, Any] | None:
- """Return the registry entry for a provider type, or None if unknown."""
return PROVIDER_REGISTRY.get(provider_type)
def get_base_url(provider_type: str) -> str | None:
- """Return the default base URL for a provider type."""
info = PROVIDER_REGISTRY.get(provider_type)
return info["base_url"] if info else None
@@ -460,18 +454,16 @@ def get_base_url(provider_type: str) -> str | None:
def provider_runs_local_tools(provider_type: str | None) -> bool:
"""Whether Unsloth may run its own tool loop against this provider type.
- Unsloth's tools (web_search, python, terminal, MCP, knowledge-base search)
- execute on the Unsloth host, so any provider whose wire format can carry a
- tool schema out and a tool result back can use them. That is the whole
- OpenAI-compatible family plus Gemini, whose native shape is translated to
- and from OpenAI chunks in ``external_provider.py``.
-
- Anthropic is deliberately absent: ``_stream_anthropic`` only appends
- Anthropic's own hosted builtins and never forwards a caller's function-tool
- schemas, so the loop would advertise a catalog the model never sees.
- Enabling it needs OpenAI -> Anthropic schema translation plus tool_use /
- tool_result message replay, which is separate work. Anthropic keeps its
- hosted web_search, web_fetch and code_execution meanwhile.
+ Unsloth's tools (web_search, python, terminal, MCP, knowledge-base search) execute on the
+ Unsloth host, so any provider whose wire format can carry a tool schema out and a tool result
+ back can use them: the whole OpenAI-compatible family plus Gemini, whose native shape is
+ translated to and from OpenAI chunks in ``external_provider.py``.
+
+ Anthropic is deliberately absent: ``_stream_anthropic`` only appends Anthropic's own hosted
+ builtins and never forwards a caller's function-tool schemas, so the loop would advertise a
+ catalog the model never sees. Enabling it needs OpenAI -> Anthropic schema translation plus
+ tool_use / tool_result message replay, which is separate work. Anthropic keeps its hosted
+ web_search, web_fetch and code_execution meanwhile.
"""
# isinstance, not a truthiness check: the value reaches here straight from a
# request body, and a list or dict key raises TypeError inside dict.get, which
@@ -657,24 +649,16 @@ def _metadata_host(hostname: str) -> bool:
return ip in _METADATA_IPS or (ip.version == 4 and ip in _METADATA_NETWORK)
-# The block above only reads the hostname text, so a caller-controlled name
-# (metadata-alias.attacker.test IN A 169.254.169.254) dials the very service it
-# exists to refuse. Names are resolved on the default path too, but only far
-# enough to answer "is this metadata"; refusing other private addresses stays
-# opt-in. Three things keep that lookup off the endpoints people configure:
-# * registry hosts and IP literals skip it, so a real provider or
-# http://127.0.0.1:11434 touches no resolver;
-# * a name that does not resolve is allowed -- http://my_ollama:11434 may only
-# resolve in the client's network namespace, not in this one;
-# * it is bounded and cached, so a dead resolver cannot stall each request.
-# A client is built per request and the route validates the same URL again,
-# so the cache is what keeps a request to one lookup.
-# Short on purpose. This validator is sync and called from async handlers, so
-# the wait is the event loop's wait, and every millisecond of it is shared by
-# every concurrent request. A provider hostname that a resolver can answer at
-# all is answered well inside this; past it the answer is treated as unknown,
-# which the default path allows and the opt-in path re-asks for without a bound.
-# So a longer deadline buys accuracy for nobody and costs latency for everyone.
+# The block above only reads the hostname text, so a caller-controlled name (metadata-alias.attacker.test IN A
+# 169.254.169.254) dials the very service it exists to refuse. Names are resolved on the default path too, but only
+# far enough to answer "is this metadata"; refusing other private addresses stays opt-in. Three things keep that
+# lookup off the endpoints people configure: registry hosts and IP literals skip it, so a real provider or
+# http://127.0.0.1:11434 touches no resolver; a name that does not resolve is allowed, since http://my_ollama:11434
+# may only resolve in the client's network namespace; and it is bounded and cached, so a dead resolver cannot stall
+# each request. The deadline is short on purpose: this validator is sync and called from async handlers, so the wait
+# is the event loop's wait, shared by every concurrent request. A provider hostname a resolver can answer at all is
+# answered well inside it; past it the answer is treated as unknown, which the default path allows and the opt-in path
+# re-asks for without a bound.
_DNS_TIMEOUT_SECONDS = 0.5
_DNS_CACHE_TTL_SECONDS = 300.0
_DNS_CACHE_MAX_ENTRIES = 512
@@ -682,19 +666,13 @@ _DNS_CACHE_MAX_ENTRIES = 512
# timeout are both cheap to repeat and wrong to remember.
_dns_cache: dict[str, tuple[float, tuple[str, ...]]] = {}
_dns_cache_lock = threading.Lock()
-# A lookup that times out is abandoned, not cancelled, so its thread lives until
-# the platform resolver gives up. Rotating hostnames defeat the cache and would
-# otherwise pile those up one per request, so the number in flight is capped and
-# a caller waits its turn up to the same deadline rather than being waved
-# through the moment the pool is busy.
-#
-# Saturating the pool still ends in "no answer", which the default path allows.
-# That is the same decision this file makes for a lookup that times out, and it
-# is deliberate: refusing instead would mean any resolver trouble, or any caller
-# willing to stall a few lookups, could stop the operator configuring a provider
-# at all. The check is a bound on what a caller-supplied URL may resolve to, not
-# a guarantee about what the socket will later connect to -- see the transport
-# note on _resolve_host.
+# A lookup that times out is abandoned, not cancelled, so its thread lives until the platform resolver gives up.
+# Rotating hostnames defeat the cache and would otherwise pile those up one per request, so the number in flight is
+# capped and a caller waits its turn up to the same deadline rather than being waved through the moment the pool is
+# busy. Saturating the pool still ends in "no answer", which the default path allows: refusing instead would mean any
+# resolver trouble, or any caller willing to stall a few lookups, could stop the operator configuring a provider at
+# all. The check is a bound on what a caller-supplied URL may resolve to, not a guarantee about what the socket will
+# later connect to; see the transport note on _resolve_host.
_DNS_MAX_IN_FLIGHT = 32
_dns_in_flight = threading.BoundedSemaphore(_DNS_MAX_IN_FLIGHT)
@@ -941,15 +919,14 @@ def list_available_providers(include_hidden: bool = False) -> list[dict[str, Any
"""Return registered providers (for the /registry endpoint).
Hidden entries exist only for backend lookups and are surfaced by the UI via
- ``CUSTOM_PROVIDER_PRESETS`` instead of the dropdown, so they stay filtered
- out by default. That default is load-bearing for upgrades: a browser holding
- a cached bundle from before this capability existed has no idea to filter on
- ``hidden``, and would render the self-hosted presets as duplicate dropdown
- entries.
-
- ``include_hidden`` is how a client that does know says so. The self-hosted
- presets are exactly the ones that run Unsloth's tools, so their capability
- has to reach a frontend that asks for it, and asking is opt-in.
+ ``CUSTOM_PROVIDER_PRESETS`` instead of the dropdown, so they stay filtered out by default. That
+ default is load-bearing for upgrades: a browser holding a cached bundle from before this
+ capability existed has no idea to filter on ``hidden``, and would render the self-hosted presets
+ as duplicate dropdown entries.
+
+ ``include_hidden`` is how a client that does know says so. The self-hosted presets are exactly
+ the ones that run Unsloth's tools, so their capability has to reach a frontend that asks for it,
+ and asking is opt-in.
"""
result = []
for provider_type, info in PROVIDER_REGISTRY.items():
diff --git a/studio/backend/core/inference/repetition_guard.py b/studio/backend/core/inference/repetition_guard.py
index 6f6a30bcd45..8452966abf8 100644
--- a/studio/backend/core/inference/repetition_guard.py
+++ b/studio/backend/core/inference/repetition_guard.py
@@ -34,9 +34,9 @@ _MIN_REPEAT_COUNT = 5
# The share of the fragment repeated windows must cover before it counts as dominated.
_DOMINANCE_RATIO = 0.5
-# ceiling so the scan cannot grow with an arbitrarily long input
-# Ceiling on distinct windows held while scanning. Every fragment a context window can actually produce stays well under
-# this, so the judgement is unchanged in practice; it exists so the scan cannot grow with an arbitrarily long input.
+# Ceiling on distinct windows held while scanning. Every fragment a context window can actually produce stays well
+# under this, so the judgement is unchanged in practice; it exists so the scan cannot grow with an arbitrarily long
+# input.
_MAX_TRACKED_WINDOWS = 100_000
@@ -56,13 +56,10 @@ def is_repetition_dominated(text: str) -> bool:
return True
# Sliding exact-repeat windows, for echoes that do not align to line boundaries.
needed = max(_MIN_REPEAT_COUNT, math.ceil(length * _DOMINANCE_RATIO / _REPEAT_WINDOW))
- # keyed by HASH: retaining the 60-char slices held ~180 MB for an 800,000-character fragment
- # Keyed by HASH, not by the window itself. Retaining the 60-character slices meant one entry per starting offset, so
- # an 800,000-character fragment held roughly 180 MB of substrings alive purely to decide whether to send one more
- # continuation.
+ # Keyed by HASH, not by the window itself. Retaining the 60-character slices meant one entry per starting offset,
+ # so an 800,000-character fragment held roughly 180 MB of substrings alive purely to decide whether to send one
+ # more continuation.
counts: dict[int, int] = {}
- # occurrences must not overlap, else one repeated character counts as many (a 64-char rule tripped the threshold at
- # 16% coverage)
# Occurrences must not overlap, or a single run of one character counts as many. A 64-character rule inside a
# 400-character answer yields five overlapping 60-character windows and tripped the threshold at 16 percent
# coverage, abandoning a valid answer.
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index ae309324cec..e0c069c54d3 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -1,17 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Safetensors/transformers agentic tool loop.
+"""Safetensors/transformers agentic tool loop.
-Wraps a single-turn cumulative-text generator with the same tool-calling,
-thinking-block, status, and metadata event protocol the GGUF path uses, so
-the front-end SSE shape is identical across backends.
+Wraps a single-turn cumulative-text generator with the same tool-calling, thinking-block, status and
+metadata event protocol the GGUF path uses, so the front-end SSE shape is identical across backends.
-Unlike the GGUF path (``llama_cpp.py``), which uses llama-server's structured
-``delta.tool_calls``, native transformers has no such channel, so this loop
-parses tool calls from the cumulative text and dispatches via
-``core.inference.tools``.
+Unlike the GGUF path (``llama_cpp.py``), which uses llama-server's structured ``delta.tool_calls``,
+native transformers has no such channel, so this loop parses tool calls from the cumulative text and
+dispatches via ``core.inference.tools``.
"""
import bisect
@@ -232,7 +229,6 @@ def _earliest_tool_signal(
candidate, p, active_tools, unrestricted = unrestricted
)
if name_start < p:
- # Genuine ``NAME[ARGS]``: the boundary is the start of NAME.
if name_start >= floor and (best < 0 or name_start < best):
best = name_start
break
@@ -421,7 +417,6 @@ def _first_detected_tool_name(content: str) -> Optional[str]:
return i >= 0 and think_spans[i][0] <= pos < think_spans[i][1]
def _first_outside(start: int, finder) -> int:
- # First occurrence at/after ``start`` that is not inside a think span.
pos = finder(start)
while pos >= 0 and _in_think(pos):
pos = finder(pos + 1)
@@ -554,23 +549,20 @@ def _spent_prompt_tokens(
) -> int:
"""Tokens the next prompt already owes, from the count the last turn reported.
- The backend tokenises the turn's prompt to run it and ships that count on gen_done,
- tool catalogue included, so the only part left to estimate is what the loop appended
- afterwards: this turn's assistant text and the results of any tool already run in the
- same batch. Estimating that tail alone is what stops a long English preamble being
- charged several times what it costs.
-
- An exact recount here is not available. This loop runs in the PARENT process and
- `InferenceOrchestrator.models` mirrors the worker's model_info, which carries no
- tokenizer, so counting the conversation again would mean a round trip into the worker
- between every tool call.
-
- Without a report the estimate covers the whole thread, as it did before. Dense
- because four characters per token undercounts CJK and emoji by about half: measured
- on an 81-message CJK chat, 1295 estimated against 2737 real, reporting 1777 tokens of
- room where 335 remained. Never floored to zero, which reaches the tool as "there is
- no room left in this context to search earlier conversation" and switches recall off
- on exactly the tight windows that need it.
+ The backend tokenises the turn's prompt to run it and ships that count on gen_done, tool
+ catalogue included, so the only part left to estimate is what the loop appended afterwards: this
+ turn's assistant text and the results of any tool already run in the same batch. Estimating that
+ tail alone is what stops a long English preamble being charged several times what it costs.
+
+ An exact recount is not available: this loop runs in the PARENT process and
+ `InferenceOrchestrator.models` mirrors the worker's model_info, which carries no tokenizer, so
+ counting again would mean a round trip into the worker between every tool call.
+
+ Without a report the estimate covers the whole thread, as it did before. Dense because four
+ characters per token undercounts CJK and emoji by about half (measured on an 81-message CJK
+ chat: 1295 estimated against 2737 real, reporting 1777 tokens of room where 335 remained). Never
+ floored to zero, which reaches the tool as "there is no room left to search earlier
+ conversation" and switches recall off on exactly the tight windows that need it.
"""
stats = (generation_stats_holder or {}).get("stats")
usage = stats.get("usage") if isinstance(stats, dict) else None
@@ -608,24 +600,22 @@ def run_safetensors_tool_loop(
) -> Generator[dict, None, None]:
"""Drive an agentic tool loop on top of a cumulative-text generator.
- ``single_turn(messages)`` must yield cumulative assistant text (each
- yield is a snapshot of all tokens so far). The loop:
-
- * Buffers each turn's leading chars to decide whether a tool call is
- coming. Plain content streams once the buffer rules it out.
- * On ``<tool_call>`` or ``<function=`` in the cumulative text, drains
- the rest of the turn silently and parses tool calls from the content.
- * Executes each tool via ``execute_tool``, appends the assistant
- tool-call message and tool result, and re-enters ``single_turn``.
- * After ``max_tool_iterations`` turns without a final answer, asks once
- more for a final answer with no tools.
+ ``single_turn(messages)`` must yield cumulative assistant text (each yield is a snapshot of all
+ tokens so far). The loop buffers each turn's leading chars to decide whether a tool call is
+ coming, drains the rest of the turn silently once a call marker appears, executes each tool via
+ ``execute_tool``, appends the assistant tool-call message and tool result, and re-enters
+ ``single_turn``. After ``max_tool_iterations`` turns without a final answer it asks once more
+ with no tools.
Yields event dicts matching the GGUF path:
* ``{"type": "status", "text": ...}`` -- empty string clears the badge.
- * ``{"type": "content", "text": ...}`` -- cumulative cleaned text for
- the current turn (consumer diffs against its own ``prev_text`` cursor).
+
+ * ``{"type": "content", "text": ...}`` -- cumulative cleaned text for the current turn (consumer
+ diffs against its own ``prev_text`` cursor).
+
* ``{"type": "tool_start", "tool_name", "tool_call_id", "arguments"}``
+
* ``{"type": "tool_end", "tool_name", "tool_call_id", "result"}``
"""
conversation = list(messages)
@@ -792,14 +782,11 @@ def run_safetensors_tool_loop(
# Live-args offset for the provisional render_html card: the drained call
# text streams as tool_args so the canvas shows the HTML being written.
_live_args_streamed_upto = -1
- # When a human confirmation gate is active the real tool_start is keyed
- # by an approval id and carries awaiting_confirmation, so an early
- # provisional card (keyed by tool_call_id, no approval) would show the
- # tool as "running" before the user has approved it. Suppress the early
- # card in that case and let the gated tool_start be the first signal.
- # In auto mode render_html is always safe and never prompts, so keep its
- # early canvas card (the frontend sends confirm_tool_calls=true alongside
- # auto); mirrors the GGUF path's _confirm_gated exemption.
+ # When a human confirmation gate is active the real tool_start is keyed by an approval id and carries
+ # awaiting_confirmation, so an early provisional card (keyed by tool_call_id, no approval) would show the tool
+ # as "running" before the user has approved it. Suppress the early card in that case. In auto mode render_html
+ # is always safe and never prompts, so keep its early canvas card; mirrors the GGUF path's _confirm_gated
+ # exemption.
from core.inference.tools import is_always_safe_tool
_provisional_confirm_gated = (
@@ -809,16 +796,12 @@ def run_safetensors_tool_loop(
)
def _should_start_provisional_render_html(content: str) -> bool:
- # Every part of this is re-resolved per chunk, exactly as before. The gates
- # are a dict lookup and a scan of a handful of tools, so hoisting them saves
- # nothing measurable and would bake in an invariant nothing enforces:
- # active_tools is handed to the injectable single_turn callback, which is
- # free to append to it while generating.
- #
- # The name lookup is likewise not cached. The first call's name is not final
- # until its marker completes: a truncated ``<function=rende`` ahead of a
- # finished ``<function=get_weather>`` reads as get_weather until it closes,
- # then as render_html, so caching the first answer would drop the panel.
+ # Every part of this is re-resolved per chunk. The gates are a dict lookup and a scan of a handful of
+ # tools, so hoisting them saves nothing measurable and would bake in an invariant nothing enforces:
+ # active_tools is handed to the injectable single_turn callback, which is free to append to it while
+ # generating. The name lookup is likewise not cached, because the first call's name is not final until its
+ # marker completes: a truncated ``<function=rende`` ahead of a finished ``<function=get_weather>`` reads
+ # as get_weather until it closes, then as render_html, so caching the first answer would drop the panel.
if (
_tool_succeeded("render_html")
or _provisional_confirm_gated
@@ -887,7 +870,6 @@ def run_safetensors_tool_loop(
"arguments": {},
"provenance": _tool_event_provenance(provisional = True),
}
- # Backlog first: everything drained so far.
yield {
"type": "tool_args",
"tool_call_id": provisional_render_html_id,
@@ -966,7 +948,6 @@ def run_safetensors_tool_loop(
yield {"type": "content", "text": emit}
continue
- # BUFFERING: hold until we know it is not a tool call.
content_buffer += delta
stripped = content_buffer.lstrip()
if not stripped:
@@ -1034,7 +1015,6 @@ def run_safetensors_tool_loop(
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
):
- # Closed object that parses as a bare-JSON call -- drain silently.
detect_state = _state_draining
continue
elif blocked_bare_json_chain_may_continue(content_buffer, _enabled_tool_names):
@@ -1044,7 +1024,6 @@ def run_safetensors_tool_loop(
# content a later peer could make executable.
detect_state = _state_draining
continue
- # Closed non-call object (or oversized non-call) -- stream as text.
# Gemma wrapper-less ``call:NAME{...}`` has no tool_xml_signals entry:
# buffer it here or it streams raw until the end-of-turn safety net.
@@ -1141,7 +1120,6 @@ def run_safetensors_tool_loop(
last_emitted = emit
yield {"type": "content", "text": emit}
- # Stream finished -- resolve what we collected.
if cancel_event is not None and cancel_event.is_set():
emit = _cancelled_buffer_text()
if emit:
@@ -1319,7 +1297,6 @@ def run_safetensors_tool_loop(
content_text = strip_leading_bare_json_call(content_text, _enabled_tool_names)
if final_attempt_done:
- # Final-answer turn re-called a tool -- stop the loop.
if content_text:
yield {"type": "content", "text": content_text}
yield {"type": "status", "text": ""}
@@ -1440,7 +1417,6 @@ def run_safetensors_tool_loop(
else None
)
if _decision is not None and _decision != "deny":
- # Approved: now it really is running.
yield {"type": "status", "text": decision.status_text}
if _decision == "deny":
decision_slot = None
@@ -1499,15 +1475,11 @@ def run_safetensors_tool_loop(
):
from core.inference.context_window import retrieval_budget
- # From the tokenizer count the last turn reported rather than
- # from characters alone: `conversation` already carries this
- # turn's assistant preamble and its tool call, and pricing the
- # whole thread by characters is what hands a retrieval room the
- # next prompt does not have.
- #
- # `reply_returns`, as the GGUF loop does: result and reply are
- # both protected on the next fit, so one retrieval cannot spend
- # the budget they share.
+ # From the tokenizer count the last turn reported rather than from characters alone:
+ # `conversation` already carries this turn's assistant preamble and its tool call, and pricing
+ # the whole thread by characters is what hands a retrieval room the next prompt does not have.
+ # `reply_returns`, as the GGUF loop does: result and reply are both protected on the next fit,
+ # so one retrieval cannot spend the budget they share.
spent = _spent_prompt_tokens(
conversation,
tools,
@@ -1538,22 +1510,18 @@ def run_safetensors_tool_loop(
# against falls back to the window-independent constant.
if _accepts_kwarg(execute_tool, "context_tokens"):
kwargs["context_tokens"] = int(context_length)
- # Tool results are counted TWICE, which charges them two
- # characters per token instead of four. The estimator's rate is an
- # English one, and this budget exists because the results these
- # tools return are base64, minified JSON, hashes and command
- # output, which run nearer two. Under-pricing what is already in
- # the conversation hands the next call room that is occupied, and
- # this loop has no exact count and no rolling fit to catch it.
+ # Tool results are counted TWICE, which charges them two characters per token instead of four.
+ # The estimator's rate is an English one, and this budget exists because the results these
+ # tools return are base64, minified JSON, hashes and command output, which run nearer two.
+ # Under-pricing what is already in the conversation hands the next call room that is occupied,
+ # and this loop has no exact count and no rolling fit to catch it.
results = [
message for message in conversation if message.get("role") == "tool"
]
- # Removed from the thread below rather than added on top of it:
- # the conservative estimate already prices every message it is
- # given, so leaving the results in and adding them again charges
- # them twice, and a CJK result twice over at a token per character
- # each time. A thread with one sizable earlier result would then
- # report no room while it still had plenty.
+ # Removed from the thread below rather than added on top of it: the conservative estimate
+ # already prices every message it is given, so leaving the results in and adding them again
+ # charges them twice, and a CJK result twice over. A thread with one sizable earlier result
+ # would then report no room while it still had plenty.
rest = [
message for message in conversation if message.get("role") != "tool"
]
@@ -1570,12 +1538,10 @@ def run_safetensors_tool_loop(
kwargs["result_budget_tokens"] = tool_result_budget(
int(context_length),
max_tokens,
- # Conservative for the thread as a whole, not only for the
- # tool turns doubled below: a user or assistant turn can hold
- # a pasted blob or a block of minified JSON, and priced at the
- # English rate it reports a third of what it costs. Nothing
- # here can measure exactly, and the room this produces is what
- # the next result is admitted against.
+ # Conservative for the thread as a whole, not only for the tool turns doubled below: a
+ # user or assistant turn can hold a pasted blob or a block of minified JSON, and priced at
+ # the English rate it reports a third of what it costs. Nothing here can measure exactly,
+ # and the room this produces is what the next result is admitted against.
_spent_tokens(rest)
+ _spent_tokens(tools or [])
# Every ASCII character of a result at two per token, not only
@@ -1608,14 +1574,12 @@ def run_safetensors_tool_loop(
completion = tool_controller.record_result(decision, result)
if provisional_match:
provisional_resolved = True
- # A tool ran this turn, so it counts against the caller's budget.
_turn_executed_real_tool = True
yield completion.tool_end_event()
conversation.append(completion.tool_message())
append_deferred_nudges(conversation, deferred_noop_msgs)
- # Clear the status badge before the next turn.
yield {"type": "status", "text": ""}
if tool_controller.force_final_answer:
@@ -1629,7 +1593,6 @@ def run_safetensors_tool_loop(
if _turn_executed_real_tool:
_executed_tool_iters += 1
if _executed_tool_iters >= max_tool_iterations and not final_attempt_done:
- # Budget exhausted; nudge a final plain answer.
final_attempt_done = True
conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})
diff --git a/studio/backend/core/inference/sandbox_site/sitecustomize.py b/studio/backend/core/inference/sandbox_site/sitecustomize.py
index e5aaba4be8b..51c4b831ea3 100644
--- a/studio/backend/core/inference/sandbox_site/sitecustomize.py
+++ b/studio/backend/core/inference/sandbox_site/sitecustomize.py
@@ -33,7 +33,6 @@ import json
import os
import sys
-# remapping is gated on the prefix being ABSENT (see _remap) so a genuine host mount is never shadowed
# Code-interpreter convention prefixes. Remapping is gated on the prefix being ABSENT (see _remap) so a genuine host
# mount / user dir is never shadowed.
_PREFIXES = ("/mnt/data", "/mnt/outputs", "/home/sandbox", "/workspace")
@@ -43,7 +42,6 @@ _notified = False
# Invented absolute write path -> healed CWD target, so re-writing the same artifact re-serves it instead of tripping
# the anti-clobber guard.
_remapped_writes: dict = {}
-# each tool call is a fresh subprocess, so an on-disk sidecar carries the map across runs;
# Each tool call is a fresh subprocess (in-process map starts empty), so this on-disk sidecar carries the map across
# runs. It records only sources the fallback healed, so an unrelated same-basename file is never adopted.
_REMAP_SIDECAR = ".unsloth_sandbox_remap.json"
@@ -186,9 +184,8 @@ def _remap_open(file, mode):
if text == cwd or text.startswith(cwd + os.sep):
return file
parent = os.path.dirname(text)
- # an existing external directory is a deliberate target and stays truthful (os.path.exists follows symlinks)
- # Redirect only when the parent is missing; an existing external directory is a deliberate target and stays truthful
- # (os.path.exists follows symlinks).
+ # Redirect only when the parent is missing; an existing external directory is a deliberate target and stays
+ # truthful (os.path.exists follows symlinks).
if parent and os.path.exists(parent):
return file
base = os.path.basename(text)
@@ -271,7 +268,6 @@ def _install():
*,
dir_fd = None,
):
- # only O_CREAT can create; O_TRUNC / O_APPEND without it still require the file to exist
# Path.touch() etc. go through os.open, not builtins.open. Only O_CREAT can create, so only it maps to
# "creating" mode; O_TRUNC / O_APPEND without O_CREAT still require the file to exist, so behave as a read.
logical_mode = "w" if (flags & os.O_CREAT) else "r"
@@ -281,7 +277,6 @@ def _install():
return original_os_open(mapped, flags, mode, dir_fd = dir_fd)
def _path_mkdir(self, *args, **kwargs):
- # pathlib probes the unpatched Path.is_dir()/os.stat on FileExistsError
# pathlib probes Path.is_dir()/os.stat (unpatched) on FileExistsError, so a bare os.mkdir remap would still
# raise when the target exists. Remap the receiver up front so parents/exist_ok stays idempotent.
mapped = _remap(self)
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.py
index 7e598c1add3..678c3cf2fed 100644
--- a/studio/backend/core/inference/sd_cpp_args.py
+++ b/studio/backend/core/inference/sd_cpp_args.py
@@ -24,7 +24,6 @@ from core.inference.diffusion_memory import (
OFFLOAD_SEQUENTIAL,
)
-# in supply order, keyed by DiffusionFamily.name so the family registry need not import sd.cpp specifics
# Per-family text-encoder flags, in supply order. Keyed by ``DiffusionFamily.name`` so the family registry need not
# import sd.cpp specifics.
_TE_FLAGS_BY_FAMILY: dict[str, tuple[str, ...]] = {
@@ -157,7 +156,6 @@ def metal_text_encoder_flags() -> list[str]:
ggml's Metal backend gates RMS_NORM on contiguous rows and calls ``GGML_ABORT`` when that does
not hold, with no per-op CPU fallback, so an LLM text encoder (Qwen3 for FLUX.2 / Z-Image, T5
for FLUX.1) takes the whole sd-server process down mid-generation:
-
ggml_metal_op_encode_impl: error: unsupported op 'RMS_NORM' -> ggml_abort
LLMEmbedder::encode_prompt -> LLMRunner::compute -> GGMLRunner::compute
@@ -175,14 +173,11 @@ def metal_text_encoder_flags() -> list[str]:
return ["--clip-on-cpu"]
-# sd.cpp prefers GPU -> iGPU -> CPU and only --backend changes which backend EXECUTES the graph (--offload-to-cpu moves
-# parameters)
-# Everything on the CPU backend. sd.cpp prefers GPU -> integrated GPU -> CPU and only `--backend` changes which backend
-# EXECUTES the graph (`--offload-to-cpu` moves parameters, not compute), so this is the one flag that removes ggml-metal
-# entirely.
+# Everything on the CPU backend. sd.cpp prefers GPU -> integrated GPU -> CPU and only `--backend` changes which
+# backend EXECUTES the graph (`--offload-to-cpu` moves parameters, not compute), so this is the one flag that removes
+# ggml-metal entirely.
CPU_BACKEND_FLAGS: tuple[str, ...] = ("--backend", "cpu")
-# a negative --max-vram auto-detects free VRAM per device
# Graph-cut segmented execution; a negative --max-vram auto-detects free VRAM per device, sparing that many GiB. It
# segments on its own, so it stands alone.
GRAPH_CUT_VRAM_FLAGS: tuple[str, ...] = ("--max-vram", "-1")
@@ -242,7 +237,6 @@ def without_device_backend_flags(flags: Sequence[str]) -> list[str]:
return out
-# ggml-metal calls GGML_ABORT when ggml_metal_device_supports_op() is false
# The ggml signature for "this graph cannot run on this backend at all": ggml-metal calls GGML_ABORT when
# ggml_metal_device_supports_op() returns false, since a single-backend graph has nowhere else to put the node. The
# SIGABRT takes sd-server down mid-generation.
@@ -355,7 +349,6 @@ def build_sd_cpp_command(
cmd += ["--lora-model-dir", params.lora_dir]
if params.lora_apply_mode:
cmd += ["--lora-apply-mode", params.lora_apply_mode]
- # leaving them unset lets sd.cpp derive the size from an input image
# Emit explicit dims when given. An image-conditioned run leaving them unset omits the flags so sd.cpp derives the
# size from the input; a plain txt2img keeps the 1024 default.
if params.width is not None or params.height is not None:
@@ -643,8 +636,6 @@ def build_img_gen_request(
req["seed"] = int(seed)
if sample_params:
req["sample_params"] = sample_params
- # the API resolves each `path` against the server's --lora-model-dir (prompt-embedded <lora:> tags are unsupported
- # server-side)
# Structured LoRA list: the API resolves each ``path`` against the server's ``--lora-model-dir`` (prompt-embedded
# ``<lora:>`` tags are unsupported server-side), so LoRAs are staged here.
if lora:
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 5874b320f6e..e2ee1994671 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -3,23 +3,17 @@
"""Native stable-diffusion.cpp diffusion backend (the no-GPU tier).
-``SdCppDiffusionBackend`` presents the SAME public surface the image routes use on
-the diffusers ``DiffusionBackend`` (``begin_load`` / ``load_progress`` / ``generate``
-/ ``generate_progress`` / ``unload`` / ``status``), but is backed by the ``sd-cli``
-subprocess (``SdCppEngine``) instead of an in-process diffusers pipeline. The engine
-router (``diffusion_engine_router.py``) selects this backend only when no usable
-CUDA/ROCm/XPU GPU is present, where it is measurably faster and far lighter on RAM
-than diffusers (see outputs/sdcpp_cpu).
-
-It reuses the transformer GGUF the diffusers path already downloads and additionally
-fetches the per-family single-file VAE + text encoders declared in
-``diffusion_families`` (sd-cli cannot read the sharded diffusers components). The
-binary is installed lazily on first use; if it is unavailable or the family has no
-native mapping, the router falls back to diffusers, so this backend is only ever
-asked to run requests it can serve.
-
-Import-light on purpose: no torch / diffusers here, so selecting it on a CPU box
-does not drag the heavy GPU stack into the process.
+``SdCppDiffusionBackend`` presents the SAME public surface the image routes use on the diffusers
+``DiffusionBackend``, but is backed by the ``sd-cli`` subprocess (``SdCppEngine``) instead of an
+in-process diffusers pipeline. The engine router selects it only when no usable CUDA/ROCm/XPU GPU is
+present, where it is measurably faster and far lighter on RAM than diffusers.
+
+It reuses the transformer GGUF the diffusers path already downloads and additionally fetches the
+per-family single-file VAE + text encoders declared in ``diffusion_families`` (sd-cli cannot read
+the sharded diffusers components). The binary is installed lazily on first use; if it is unavailable
+or the family has no native mapping, the router falls back to diffusers, so this backend is only
+ever asked to run requests it can serve. Import-light on purpose: no torch / diffusers here, so
+selecting it on a CPU box does not drag the heavy GPU stack into the process.
"""
from __future__ import annotations
@@ -102,22 +96,23 @@ _install_lock = threading.Lock()
# Admission control over the managed tree, because "is anything running in there?" and "start replacing it" have to be
# ONE decision. _managed_tree_in_use() alone is a point-in-time sample, and an install spends seconds to minutes
# downloading before it extracts: a one-shot generation admitted inside that window launches the very sd-cli the
-# extraction then overwrites. Installs are the writers, one-shot sd-cli runs are the readers. Held only across the state
-# change, never across a download or a generation, and the readers never take _install_lock, so there is no cycle.
+# extraction then overwrites. Installs are the writers, one-shot sd-cli runs are the readers. Held only across the
+# state change, never across a download or a generation, and the readers never take _install_lock, so there is no
+# cycle.
_tree_state = threading.Condition()
_tree_readers = 0
_tree_installing = False
# A download can legitimately take minutes; wait rather than run a binary that is being replaced
_TREE_WAIT_TIMEOUT_S = 900.0
-# How often the wait re-checks for cancellation. Nothing notifies the condition when a request is cancelled, so a single
-# long wait would hold the generate lock past an unload.
+# How often the wait re-checks for cancellation. Nothing notifies the condition when a request is cancelled, so a
+# single long wait would hold the generate lock past an unload.
_TREE_WAIT_TICK_S = 0.5
@contextlib.contextmanager
def _tree_claimed_for_install():
- """Claim the managed tree for an install. Yields False when something is running in it, in
- which case the caller keeps what is on disk and retries on a later load."""
+ """Claim the managed tree for an install. Yields False when something is running in it, in which
+ case the caller keeps what is on disk and retries on a later load."""
global _tree_installing
with _tree_state:
if _tree_readers or _tree_installing or _managed_tree_in_use():
@@ -142,15 +137,15 @@ def _tree_reader(
Only a MANAGED copy needs this. An sd-cli from ``SD_CLI_PATH`` / ``UNSLOTH_SD_CPP_PATH``, an
in-tree build or ``PATH`` is one the installer never touches, so claiming for it would block
- that generation behind an unrelated bundle download for nothing (and, on a timeout, fail it).
-
- A timeout is NOT admission: the install still holds the tree, and starting the binary it is
+ that generation behind an unrelated bundle download for nothing (and, on a timeout, fail it). A
+ timeout is NOT admission: the install still holds the tree, and starting the binary it is
replacing is the exact race this exists to prevent.
The wait is cancellable. The caller already holds the generate lock here, so an unload or a
cancel that could not get out of this would read as a hung Unsloth for up to the whole timeout
while nothing has even started. Nothing notifies the condition on cancel, so the wait is
- re-checked on a short tick rather than once."""
+ re-checked on a short tick rather than once.
+ """
global _tree_readers
if not is_managed_binary(binary):
yield
@@ -187,25 +182,22 @@ _MAX_SERVER_BATCH = 8
def _default_threads() -> int:
- """Physical-core thread count for the sd.cpp CPU backend.
-
- ``threads = None`` lets sd.cpp pick its own default, which is the logical-core
- count (all hyperthreads). For the compute-bound GGML matmuls the diffusion CPU
- path runs, oversubscribing the hyperthreads adds scheduling contention without
- extra throughput, so pin to physical cores (``cpu_count // 2``) instead. Falls
- back to 8 when the count is unknown, and clamps to at least 1."""
+ """Physical-core thread count for the sd.cpp CPU backend. ``threads = None`` lets sd.cpp pick
+ its own default, which is the logical-core count (all hyperthreads). For the compute-bound
+ GGML matmuls the diffusion CPU path runs, oversubscribing the hyperthreads adds scheduling
+ contention without extra throughput, so pin to physical cores instead. Falls back to 8 when
+ the count is unknown, and clamps to at least 1."""
cpu = os.cpu_count()
return max(1, cpu // 2 if cpu else 8)
def _server_binary_runnable(binary: str) -> bool:
- """Best-effort probe that ``binary`` can actually execute (not just exist).
-
- Runs ``<binary> --help`` with the same runtime env the server will use, so a present
- but unrunnable build (wrong arch, missing shared libs, no execute bit) is caught before
- a multi-GB asset download. Conservative: only a clear "cannot launch" signal (OSError,
- or the dynamic-loader exit codes 126/127) returns False; anything else is treated as
- runnable so a quirky ``--help`` exit code never blocks a working binary."""
+ """Best-effort probe that ``binary`` can actually execute (not just exist). Runs ``<binary>
+ --help`` with the same runtime env the server will use, so a present but unrunnable build
+ (wrong arch, missing shared libs, no execute bit) is caught before a multi-GB asset download.
+ Conservative: only a clear "cannot launch" signal (OSError, or the dynamic-loader exit codes
+ 126/127) returns False; anything else is treated as runnable so a quirky ``--help`` exit code
+ never blocks a working binary."""
import subprocess
try:
@@ -231,15 +223,15 @@ def _usable_or_discard_managed(binary: str) -> bool:
``find_sd_*_binary`` only checks that the path is a file, so an interrupted extraction (or a
prebuilt for the wrong CPU) left a present-but-unrunnable binary that the installer then never
retried: every load probed it, rejected it, and fell back to diffusers, so native inference
- stayed off until the user deleted the directory by hand. Probing here closes that loop.
+ stayed off until the user deleted the directory by hand.
Only a copy the installer may replace is removed, i.e. one under the installer-owned root that
- carries its ownership marker (``is_managed_binary``). SD_CLI_PATH, UNSLOTH_SD_CPP_PATH, an
- in-tree build, anything on PATH and an unmarked directory at the default path (a user's own
- stable-diffusion.cpp checkout looks exactly like that) are the user's, so an unrunnable one of
- those is reported as-is (the router still rejects it) rather than deleted or reinstalled over.
- Deleting one would also be unrepairable: install() refuses an unmarked non-empty target, so the
- binary would be gone AND the reinstall refused."""
+ carries its ownership marker. SD_CLI_PATH, UNSLOTH_SD_CPP_PATH, an in-tree build, anything on
+ PATH and an unmarked directory at the default path (a user's own stable-diffusion.cpp checkout
+ looks exactly like that) are the user's, so an unrunnable one of those is reported as-is rather
+ than deleted or reinstalled over. Deleting one would also be unrepairable: install() refuses an
+ unmarked non-empty target, so the binary would be gone AND the reinstall refused.
+ """
if _server_binary_runnable(binary):
return True
if not is_managed_binary(binary):
@@ -259,12 +251,11 @@ def _usable_or_discard_managed(binary: str) -> bool:
def _sd_cpp_probe_output(binary: str, *args: str) -> Optional[str]:
- """Combined stdout+stderr of ``binary <args>``, or None when it could not be read.
-
- ``sd-cli`` prints ``--help`` on stdout and exits 0, and logs errors on stderr, so both
- streams are folded together. None means "could not tell" -- cannot exec, timed out, or a
- non-zero exit (which is how an older build rejects a flag it does not know) -- and is never
- evidence that a feature is absent, so every caller has to stay conservative on it."""
+ """Combined stdout+stderr of ``binary <args>``, or None when it could not be read. ``sd-cli``
+ prints ``--help`` on stdout and exits 0, and logs errors on stderr, so both streams are
+ folded together. None means "could not tell" -- cannot exec, timed out, or a non-zero exit
+ (which is how an older build rejects a flag it does not know) -- and is never evidence that a
+ feature is absent, so every caller has to stay conservative on it."""
import subprocess
try:
@@ -287,16 +278,14 @@ def _sd_cpp_probe_output(binary: str, *args: str) -> Optional[str]:
# The ``--help`` token that marks a build carrying MiniMax-H3 support. Upstream added the mode's own options
# (``--ref-video`` / ``--ref-audio``, and the "MiniMax-H3 Ref2VA" wording on ``--ref-image``) in the very commit that
-# added H3 upstream, released as master-812-ea7f0c8, so their presence is exactly the capability signal. ``--version``
-# cannot stand in for it: the release prebuilts are built without a.git dir and answer "stable-diffusion.cpp version
-# unknown, commit unknown", so there is no tag to compare.
+# added H3, so their presence is exactly the capability signal. ``--version`` cannot stand in for it: the release
+# prebuilts are built without a .git dir and answer "version unknown, commit unknown".
_H3_HELP_MARKER = "--ref-video"
def sd_cpp_supports_minimax_h3(binary: str) -> bool:
- """True unless ``binary``'s ``--help`` demonstrably predates MiniMax-H3 support.
-
- Conservative by design: an unreadable ``--help`` returns True, because the load's existing
+ """True unless ``binary``'s ``--help`` demonstrably predates MiniMax-H3 support. Conservative by
+ design: an unreadable ``--help`` returns True, because the load's existing
``SdCppEngine.version()`` gate already refuses a binary that cannot run, and guessing "no H3"
from a probe failure would take native video away from a working build."""
text = _sd_cpp_probe_output(binary, "--help")
@@ -311,16 +300,13 @@ def help_text_supports_minimax_h3(help_text: str) -> bool:
def sd_cpp_binary_vets_for_h3(binary: str) -> bool:
- """Both of ``ensure_h3_sd_cpp_binary``'s questions against a live binary, on ONE ``--help``.
-
- The capability marker cannot stand alone here. ``--ref-video`` is a plain option name that
+ """Both of ``ensure_h3_sd_cpp_binary``'s questions against a live binary, on ONE ``--help``. The
+ capability marker cannot stand alone here: ``--ref-video`` is a plain option name that
unrelated reference-video tools expose too, so a caller re-checking only capability would
- accept a program the gate itself would have refused on identity -- the difference between
- "an sd.cpp build too old for H3" and "not sd.cpp at all" (#8507).
-
- Same conservative default as ``sd_cpp_supports_minimax_h3``: an unreadable ``--help`` is
- "could not tell", and the caller's own ``version()`` gate already refuses a binary that will
- not run."""
+ accept a program the gate itself would have refused on identity -- the difference between "an
+ sd.cpp build too old for H3" and "not sd.cpp at all" (#8507). Same conservative default as
+ ``sd_cpp_supports_minimax_h3``: an unreadable ``--help`` is "could not tell", and the
+ caller's own ``version()`` gate already refuses a binary that will not run."""
text = _sd_cpp_probe_output(binary, "--help")
if text is None:
return True
@@ -333,13 +319,11 @@ _GRAPH_CUT_HELP_MARKERS: tuple[str, ...] = ("--max-vram", "--stream-layers")
def sd_cpp_supports_graph_cut(binary: Optional[str]) -> bool:
- """True only when ``binary``'s ``--help`` advertises the graph-cut executor.
-
- The opposite default to ``sd_cpp_supports_minimax_h3``, and for the same reason each is safe:
- that gate refuses a build, so "cannot tell" has to keep it, while this one ADDS flags, and
- sd-cli exits non-zero on an option it does not know. Guessing yes from an unreadable ``--help``
- would therefore break every generation on an older build instead of merely leaving it as slow
- as it is today."""
+ """True only when ``binary``'s ``--help`` advertises the graph-cut executor. The opposite
+ default to ``sd_cpp_supports_minimax_h3``, and for the same reason each is safe: that gate
+ refuses a build, so "cannot tell" has to keep it, while this one ADDS flags, and sd-cli exits
+ non-zero on an option it does not know. Guessing yes from an unreadable ``--help`` would
+ break every generation on an older build instead of merely leaving it as slow as it is today."""
if not binary:
return False
text = _sd_cpp_probe_output(binary, "--help")
@@ -352,14 +336,15 @@ def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:
"""True unless ``binary`` demonstrably enumerates the CPU ggml device and nothing else.
``sd-cli --list-devices`` prints one ``name<TAB>description`` line per available ggml backend
- device and exits 0, a format its own help text documents, so a CPU-only prebuilt answers
- ``CPU\t<cpu model>`` while a CUDA / ROCm / Vulkan / Metal build adds its own device. That is the
- only way to tell the two apart after the fact: ``find_sd_cpp_binary`` returns whatever is
- installed regardless of which accelerator it was asked for.
+ device and exits 0, so a CPU-only prebuilt answers ``CPU\t<cpu model>`` while a CUDA / ROCm /
+ Vulkan / Metal build adds its own device. That is the only way to tell the two apart after the
+ fact: ``find_sd_cpp_binary`` returns whatever is installed regardless of which accelerator it
+ was asked for.
Conservative everywhere else -- unreadable output, or an older build that rejects the flag --
- because neither is evidence that the accelerator is missing. A missing binary is False: there
- is nothing to run on the GPU at all."""
+ because neither is evidence that the accelerator is missing. A missing binary is False: there is
+ nothing to run on the GPU at all.
+ """
if not binary:
return False
verdict = sd_cpp_accelerator_device_verdict(binary)
@@ -368,11 +353,10 @@ def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:
def sd_cpp_accelerator_device_verdict(binary: str) -> Optional[bool]:
"""``sd_cpp_lists_accelerator_device`` without the conservative default: None means the probe
- said nothing usable, rather than being folded into "assume it has one".
-
- A caller COMPARING two readings needs that apart. Against a recorded decision, the collapsed
- True is indistinguishable from a real accelerator, so an unreadable re-probe would read as a
- build that changed underneath the load and refuse it."""
+ said nothing usable, rather than being folded into "assume it has one". A caller COMPARING
+ two readings needs that apart: against a recorded decision, the collapsed True is
+ indistinguishable from a real accelerator, so an unreadable re-probe would read as a build
+ that changed underneath the load and refuse it."""
text = _sd_cpp_probe_output(binary, "--list-devices")
if text is None:
return None
@@ -388,12 +372,10 @@ _PHYSICAL_INDEX_DEVICE_PREFIXES: tuple[str, ...] = ("CUDA", "ROCM")
def sd_cpp_device_name_for_ordinal(binary: Optional[str], ordinal: Optional[int]) -> Optional[str]:
- """The ``--list-devices`` name for CUDA/ROCm physical index ``ordinal``, or None.
-
- None whenever the answer is not certain -- no selection, an unreadable probe, a build whose
- devices are in another namespace, an index it does not list -- since the fallback is sd.cpp's
- own device choice, i.e. today's behaviour.
- """
+ """The ``--list-devices`` name for CUDA/ROCm physical index ``ordinal``, or None. None whenever
+ the answer is not certain -- no selection, an unreadable probe, a build whose devices are in
+ another namespace, an index it does not list -- since the fallback is sd.cpp's own device
+ choice, i.e. today's behaviour."""
if not binary or ordinal is None:
return None
text = _sd_cpp_probe_output(binary, "--list-devices")
@@ -406,9 +388,9 @@ def sd_cpp_device_name_for_ordinal(binary: Optional[str], ordinal: Optional[int]
if name[len(head) :] == str(ordinal):
return name
# Said out loud rather than dropped in silence: the load still runs, on whichever device this build picks for
- # itself, which is what happens today for every native load. Refusing instead would take the GPU selection from "not
- # honoured here" to "cannot load at all" on any build older than the one that added --list-devices, including a
- # user's own SD_CLI_PATH copy, since sd.cpp treats an unknown argument as fatal.
+ # itself, which is what happens today for every native load. Refusing instead would take the GPU selection from
+ # "not honoured here" to "cannot load at all" on any build older than the one that added --list-devices, including
+ # a user's own SD_CLI_PATH copy, since sd.cpp treats an unknown argument as fatal.
logger.warning(
"sd_cpp.device_pin_unresolved: this build does not report a CUDA/ROCm device %s "
"(--list-devices %s), so the graph runs on its own default device",
@@ -423,18 +405,16 @@ def _h3_replacement_hint(binary: str) -> str:
Only a binary in a layout the installer writes to can be recovered by clearing that layout:
``install()`` refuses a non-empty unmarked target, so an empty one is what lets the next load
- put the pinned prebuilt there. Anything PATH or an env var named is elsewhere entirely. The
- refusal used to end with "or remove that directory" whatever the binary was, which for the
- ``/usr/bin/sd`` PATH discovery picks up read as "remove /usr/bin".
+ put the pinned prebuilt there. Anything PATH or an env var named is elsewhere entirely; the
+ refusal used to end with "or remove that directory" whatever the binary was, which for a
+ ``/usr/bin/sd`` PATH discovery read as "remove /usr/bin".
MOVE, never remove. Only the caller's unowned branch reaches this, so a root that matches here
necessarily carries no ownership marker -- it is the user's own build sitting at the path the
- installer would use, which ``is_managed_binary`` documents as a supported thing to do, and
- which a ``git clone`` of leejet's repo produces verbatim. Moving it aside frees the path
- without destroying anything, and the user can put it back.
-
- ``in_tree_install_root`` is not consulted at all: the installer never writes to
- ``<repo_root>/stable-diffusion.cpp``, so clearing it would buy nothing."""
+ installer would use, which a ``git clone`` of leejet's repo produces verbatim. Moving it aside
+ frees the path without destroying anything. ``in_tree_install_root`` is not consulted at all:
+ the installer never writes there.
+ """
roots = [managed_install_root(), legacy_sibling_install_root()]
for root in roots:
if root is None:
@@ -454,35 +434,33 @@ def ensure_h3_sd_cpp_binary(
ADVERTISE H3 support.
``ensure_sd_cpp_binary`` hands back whatever ``find_sd_cpp_binary`` locates and only probes
- runnability, so an install that predates H3 (an upgraded Unsloth still carrying an older managed
- sd-cli) is returned unchanged, the H3 load reports ready on it, and the first generation fails.
- Only this path is stricter: image generation must keep working on any user-supplied build. Its
- caller runs it BEFORE resolving the H3 assets, so a refusal costs no download.
+ runnability, so an install that predates H3 is returned unchanged, the H3 load reports ready on
+ it, and the first generation fails. Only this path is stricter: image generation must keep
+ working on any user-supplied build. Its caller runs it BEFORE resolving the H3 assets, so a
+ refusal costs no download.
A stale copy we own is deleted so the installer puts the pinned prebuilt back; a user's own
build is left alone and the load fails with a message naming it, the same ownership split
- ``_usable_or_discard_managed`` makes. Returns None when no H3-capable binary can be produced.
-
- A user-supplied binary that is not stable-diffusion.cpp AT ALL gets its own message: "no H3
+ ``_usable_or_discard_managed`` makes. Returns None when no H3-capable binary can be produced. A
+ user-supplied binary that is not stable-diffusion.cpp AT ALL gets its own message: "no H3
options" is true of every unrelated program, and reporting it as an outdated build is what sent
#8507 looking for a newer stable-diffusion.cpp that was never installed.
"""
binary = ensure_sd_cpp_binary(allow_install = allow_install, accelerator = accelerator)
if not binary:
return binary
- # ONE --help, two questions: is this stable-diffusion.cpp, and does this build carry H3. A second spawn would double
- # the cost of the refusal path and could read a different build than the one just judged. None is "could not tell",
- # which stays conservative on both counts. Conservative HERE means keeping the binary, the opposite of the engine's
- # identity probe, which rejects on an unreadable one. Not an inconsistency to iron out: this decides whether to
- # refuse a binary the user chose, where a probe failure must not take native video away from a working build, while
- # the engine decides whether to ADOPT an ambiguously named PATH candidate on no evidence at all. Opposite questions,
- # so opposite safe defaults.
+ # ONE --help, two questions: is this stable-diffusion.cpp, and does this build carry H3. A second spawn would
+ # double the cost of the refusal path and could read a different build than the one just judged. None is "could
+ # not tell", which stays conservative on both counts. Conservative HERE means keeping the binary, the opposite of
+ # the engine's identity probe, which rejects on an unreadable one: this decides whether to refuse a binary the
+ # user chose, where a probe failure must not take native video away from a working build, while the engine decides
+ # whether to ADOPT an ambiguously named PATH candidate on no evidence at all.
help_text = _sd_cpp_probe_output(binary, "--help")
if help_text is None:
return binary
# Identity BEFORE capability, never the marker alone. --ref-video is a plain option name that unrelated
# reference-video tools also expose, so returning early on it would readmit exactly the class of program #8507 was
- # about -- through SD_CLI_PATH instead of PATH. Upstream added H3 eight months after print_usage started with the
+ # about, through SD_CLI_PATH instead of PATH. Upstream added H3 eight months after print_usage started with the
# project banner, so a genuine H3 build always answers both.
identified = help_text_identifies_sd_cpp(help_text)
if identified and help_text_supports_minimax_h3(help_text):
@@ -495,8 +473,8 @@ def ensure_h3_sd_cpp_binary(
# that is not stable-diffusion.cpp, so reporting the capability verdict here sent users hunting for a newer
# build of something they never installed (#8507, where the binary was Debian/Ubuntu's `sd` find-and-replace
# tool). Discovery already skips an unrelated PATH `sd`, so what reaches this line came from somewhere the
- # identity gate does not cover -- an SD_CLI_PATH / UNSLOTH_SD_CPP_PATH override, an in-tree developer build, or
- # a PATH `sd-cli`. None of them is ours to overwrite, so all four say so and stop.
+ # identity gate does not cover -- an SD_CLI_PATH / UNSLOTH_SD_CPP_PATH override, an in-tree developer build,
+ # or a PATH `sd-cli`. None of them is ours to overwrite, so all four say so and stop.
if not identified:
raise RuntimeError(
f"The executable at {binary} is not stable-diffusion.cpp: its --help output does "
@@ -515,10 +493,10 @@ def ensure_h3_sd_cpp_binary(
# Ours, but replacing it is exactly what auto-install is switched off for.
logger.warning("managed sd.cpp binary %s %s", binary, fault)
return None
- # Deleting it is a WRITE to the managed tree, so it takes the same admission an install does. An image one-shot may
- # be executing this very file: on Linux the running child survives the unlink but the next image in the batch can no
- # longer resolve it, and on Windows the unlink fails outright and the H3 load is refused. Held only across the
- # unlink -- ensure_sd_cpp_binary below claims the tree itself, and the claim is not reentrant.
+ # Deleting it is a WRITE to the managed tree, so it takes the same admission an install does. An image one-shot
+ # may be executing this very file: on Linux the running child survives the unlink but the next image in the batch
+ # can no longer resolve it, and on Windows the unlink fails outright and the H3 load is refused. Held only across
+ # the unlink -- ensure_sd_cpp_binary below claims the tree itself, and the claim is not reentrant.
with _tree_claimed_for_install() as claimed:
if not claimed:
logger.warning(
@@ -556,9 +534,9 @@ def _installer_module():
return install_sd_cpp_prebuilt
-# Accelerators whose upgrade install already failed this process. Without this, a host that asks for a GPU build it has
-# no asset for would re-resolve (and re-download) on every single load, because the wrong-accelerator binary it keeps
-# still does not match the request.
+# Accelerators whose upgrade install already failed this process. Without this, a host that asks for a GPU build it
+# has no asset for would re-resolve (and re-download) on every single load, because the wrong-accelerator binary it
+# keeps still does not match the request.
_failed_accelerator_upgrades: set[str] = set()
@@ -571,12 +549,11 @@ def _note_failed_upgrade(accelerator: str) -> None:
def _incomplete_tree_replacement(exc: BaseException) -> bool:
- """True when an install failed PART WAY through replacing the managed tree.
-
- That leaves a mixture of two bundles, and the installer withholds the record precisely so the
- next load retries the sweep. Memoising it as a failed upgrade would do the opposite: the
- mismatch is then suppressed for the rest of the process and the mixed tree is served as if it
- were the accelerator that was asked for."""
+ """True when an install failed PART WAY through replacing the managed tree. That leaves a
+ mixture of two bundles, and the installer withholds the record precisely so the next load
+ retries the sweep. Memoising it as a failed upgrade would do the opposite: the mismatch is
+ then suppressed for the rest of the process and the mixed tree is served as if it were the
+ accelerator that was asked for."""
try:
return isinstance(exc, _installer_module().SupersededBinaryError)
except Exception: # noqa: BLE001 -- cannot tell -> an ordinary failure
@@ -585,12 +562,10 @@ def _incomplete_tree_replacement(exc: BaseException) -> bool:
def _tree_in_use(backend: Any) -> bool:
"""True while ``backend`` may still have a native process executing out of the managed tree.
-
Three windows, and all three are live processes running the files an install would replace:
the resident sd-server; a server that has been spawned but has not committed to ``_state``
- yet (``_pending_server``, which is exactly the ``SdCppServer.start()`` span -- minutes on a
- large checkpoint, and the load that owns it has published nothing else to look at); and a
- generation that has been signalled to cancel but has not finished."""
+ yet (``_pending_server``, exactly the ``SdCppServer.start()`` span, minutes on a large
+ checkpoint); and a generation that has been signalled to cancel but has not finished."""
if backend is None:
return False
state = getattr(backend, "_state", None)
@@ -609,34 +584,33 @@ def _managed_tree_in_use() -> bool:
An accelerator upgrade REPLACES the binaries in that tree, and Linux refuses to open a running
executable for writing (ETXTBSY) while Windows locks it, so an install attempted now fails and
can leave the tree half-written. The load path knows when it is safe and retries after its own
- teardown, but it is not the only entry point: the engine router calls ``ensure_sd_server_binary``
- / ``ensure_sd_cpp_binary`` directly, BEFORE ``begin_load`` stops anything. Answering here, at
- the one place that decides an install is needed, covers every caller instead of one.
+ teardown, but it is not the only entry point: the engine router calls
+ ``ensure_sd_server_binary`` / ``ensure_sd_cpp_binary`` directly, BEFORE ``begin_load`` stops
+ anything. Answering here covers every caller instead of one.
Reads the singleton without a lock on purpose: a stale answer either defers an upgrade to the
- next load (harmless) or lets one through in a window the load path guards anyway."""
+ next load (harmless) or lets one through in a window the load path guards anyway.
+ """
return _tree_in_use(_sd_cpp_backend)
def _accelerator_changed(binary: str, accelerator: str) -> bool:
- """True when ``binary`` is a managed install built for a DIFFERENT accelerator than the one
- now asked for, so reusing it would silently run the wrong build.
-
- The case that matters: a host that installed the CPU bundle (the default when the device
- target resolves to CPU) later forces the native engine on a CUDA/ROCm/Vulkan GPU. Both
- ``ensure_*`` return any runnable binary they find, so without this the CPU sd-server is
- reused forever and generation stays on the CPU even though a matching GPU build now exists.
-
- The reverse matters too: a host with a recorded GPU install whose device target later
- resolves to CPU keeps running on the GPU, because nothing in the sd-server/sd-cli command
- line asks for a CPU backend -- the build itself is the choice. So a recorded accelerator
- that is not the one now wanted is a change in either direction.
-
- Deliberately conservative -- only a copy the installer owns is ever replaced (the user's own
- build or an in-tree checkout is left alone), and an install with NO record is left alone when
- the CPU build is wanted: unrecorded is unknown (GPU assets shipped before the record did), and
- reinstalling every legacy install on a CPU target would redownload the bundle for the common
- case, where the install almost certainly is the CPU one already."""
+ """True when ``binary`` is a managed install built for a DIFFERENT accelerator than the one now
+ asked for, so reusing it would silently run the wrong build.
+
+ The case that matters: a host that installed the CPU bundle later forces the native engine on a
+ CUDA/ROCm/Vulkan GPU. Both ``ensure_*`` return any runnable binary they find, so without this
+ the CPU sd-server is reused forever and generation stays on the CPU even though a matching GPU
+ build now exists. The reverse matters too: a host with a recorded GPU install whose device
+ target later resolves to CPU keeps running on the GPU, because nothing in the command line asks
+ for a CPU backend -- the build itself is the choice.
+
+ Deliberately conservative: only a copy the installer owns is ever replaced, and an install with
+ NO record is left alone when the CPU build is wanted, since unrecorded is unknown (GPU assets
+ shipped before the record did) and reinstalling every legacy install on a CPU target would
+ redownload the bundle for the common case, where the install almost certainly is the CPU one
+ already.
+ """
root = owning_managed_root(binary)
if root is None:
return False
@@ -662,20 +636,21 @@ def _record_mismatch(mod, root: Path, want: str) -> bool:
def _superseded_legacy_server(binary: Optional[str], accelerator: str) -> bool:
- """True when ``binary`` is a MISMATCHED sd-server out of the tree an older build left beside
- the Unsloth home, while the CURRENT managed root holds a completed install for ``accelerator``
- whose bundle shipped no sd-server.
+ """True when ``binary`` is a MISMATCHED sd-server out of the tree an older build left beside the
+ Unsloth home, while the CURRENT managed root holds a completed install for ``accelerator`` whose
+ bundle shipped no sd-server.
- That install is the authoritative one, and the recorded fact that its bundle is serverless
- makes "no server" the answer rather than "install again": otherwise the finder keeps handing
- the legacy server back, ``_accelerator_changed`` keeps rejecting it as the wrong build, and
- every single load reinstalls the bundle that is already on disk.
+ That install is the authoritative one, and the recorded fact that its bundle is serverless makes
+ "no server" the answer rather than "install again": otherwise the finder keeps handing the
+ legacy server back, ``_accelerator_changed`` keeps rejecting it as the wrong build, and every
+ single load reinstalls the bundle that is already on disk.
Both halves are required. A legacy server that MATCHES the wanted accelerator is a working
server and is still preferred over the one-shot CLI. And an install whose record does not say
``ships_server: false`` -- an older record without the field, or a bundle that did ship one
- whose binary was later deleted or removed by the runnability repair -- is NOT evidence of a
- serverless bundle, so it must keep reinstalling, which is what repairs the missing server."""
+ whose binary was later deleted -- is NOT evidence of a serverless bundle, so it must keep
+ reinstalling, which is what repairs the missing server.
+ """
root = owning_managed_root(binary)
if root is None:
return False
@@ -698,15 +673,16 @@ def _superseded_legacy_server(binary: Optional[str], accelerator: str) -> bool:
def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:
"""The accelerator class recorded for the managed install ``binary`` belongs to.
- None for a binary the installer does not own (SD_CLI_PATH, UNSLOTH_SD_CPP_PATH, an in-tree
- build, PATH) and for a record that cannot be read: neither is an answer, and the only caller
- uses this to notice that the answer CHANGED, never to decide what to install.
+ None for a binary the installer does not own and for a record that cannot be read: neither is an
+ answer, and the only caller uses this to notice that the answer CHANGED, never to decide what to
+ install.
Deliberately not ``_accelerator_changed``: that one answers "should an install run", so it
stands down while the tree is in use and while an upgrade for this accelerator has already
- failed, and a load that keeps a usable wrong-accelerator build on purpose would be refused by
- it on every single load. What the load needs is narrower -- did the tree it resolved this
- binary out of get replaced underneath it."""
+ failed, and a load that keeps a usable wrong-accelerator build on purpose would be refused by it
+ on every load. What the load needs is narrower -- did the tree it resolved this binary out of
+ get replaced underneath it.
+ """
# From the root the binary is actually IN, not the current default. The finder also serves a tree an older build
# left beside the Unsloth home, and reading the current root for a binary out of that one reports "unrecorded" on
# both sides of the comparison, so a swap underneath this load reads as no change at all.
@@ -720,12 +696,10 @@ def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:
def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu") -> Optional[str]:
- """Path to a usable ``sd-cli`` binary, installing the prebuilt once if needed.
-
- Returns the binary path, or None when it is absent and cannot be installed
- (install disabled, no network, unsupported platform). Never raises -- a None
- return is the router's signal to fall back to diffusers.
- """
+ """Path to a usable ``sd-cli`` binary, installing the prebuilt once if needed. Returns the
+ binary path, or None when it is absent and cannot be installed (install disabled, no network,
+ unsupported platform). Never raises -- a None return is the router's signal to fall back to
+ diffusers."""
found = find_sd_cpp_binary()
usable = bool(found) and _usable_or_discard_managed(found)
if usable and not _accelerator_changed(found, accelerator):
@@ -757,13 +731,13 @@ def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu"
except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back
logger.warning("sd-cli auto-install failed: %s", exc)
if _incomplete_tree_replacement(exc):
- # The sweep got part way, and it takes sd-cli before sd-server, so the fallback resolved before the
- # install may be one of the copies it already removed. Re-find, so this returns a file that exists
- # -- often the one the new bundle just extracted -- or None, never a path that is gone. Through the
- # usability gate, not raw: the raise came BEFORE install()'s _make_executable, so on POSIX a freshly
- # extracted copy has no execute bit and find_sd_cpp_binary only checks that the path is a file. The
- # gate probes it and, being ours, removes it if it cannot run, so the next load reinstalls rather
- # than being handed a binary that fails to launch.
+ # The sweep got part way, and it takes sd-cli before sd-server, so the fallback resolved before
+ # the install may be one of the copies it already removed. Re-find, so this returns a file that
+ # exists -- often the one the new bundle just extracted -- or None, never a path that is gone.
+ # Through the usability gate, not raw: the raise came BEFORE install()'s _make_executable, so on
+ # POSIX a freshly extracted copy has no execute bit and find_sd_cpp_binary only checks that the
+ # path is a file. The gate probes it and, being ours, removes it if it cannot run, so the next
+ # load reinstalls rather than being handed a binary that fails to launch.
refound = find_sd_cpp_binary()
return refound if refound and _usable_or_discard_managed(refound) else None
if fallback is not None:
@@ -774,20 +748,17 @@ def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu"
def ensure_sd_server_binary(
*, allow_install: bool = True, accelerator: str = "cpu"
) -> Optional[str]:
- """Path to a usable ``sd-server`` binary, installing the prebuilt once if needed.
-
- Unlike ``ensure_sd_cpp_binary``, this installs when *sd-server specifically* is
- missing -- even if an ``sd-cli`` from an older install is already present -- so an
- existing one-shot install is upgraded to the persistent server (the prebuilt archive
- ships both). Returns None when it is absent and cannot be installed; the backend then
- uses the one-shot fallback. Never raises.
- """
+ """Path to a usable ``sd-server`` binary, installing the prebuilt once if needed. Unlike
+ ``ensure_sd_cpp_binary``, this installs when *sd-server specifically* is missing -- even if
+ an ``sd-cli`` from an older install is already present -- so an existing one-shot install is
+ upgraded to the persistent server (the prebuilt archive ships both). Returns None when it is
+ absent and cannot be installed; the backend then uses the one-shot fallback. Never raises."""
found = find_sd_server_binary()
usable = bool(found) and _usable_or_discard_managed(found)
# Ahead of _accelerator_changed, which reports "unchanged" while the managed tree is in use (an install would
- # overwrite a running binary) and would hand the mismatched legacy server to a load that has the matching serverless
- # build right here. None IS the answer: the one-shot sd-cli of the right build runs, and the bundle is not
- # downloaded again on every later load.
+ # overwrite a running binary) and would hand the mismatched legacy server to a load that has the matching
+ # serverless build right here. None IS the answer: the one-shot sd-cli of the right build runs, and the bundle is
+ # not downloaded again on every later load.
if usable and _superseded_legacy_server(found, accelerator):
return None
if usable and not _accelerator_changed(found, accelerator):
@@ -827,11 +798,11 @@ def ensure_sd_server_binary(
_note_failed_upgrade(accelerator)
return fallback
installed = find_sd_server_binary()
- # The finder also probes the tree an older build left beside the Unsloth home, so when the bundle just installed
- # ships no sd-server the hit here can be that legacy server, built for a different accelerator. None, not the
- # fallback: an install just completed, so the router's next step resolves the sd-cli it landed, and a one-shot
- # run on the right build beats a resident server on the wrong one. The fallback stays for the failure path
- # above, where no matching binary was fetched at all.
+ # The finder also probes the tree an older build left beside the Unsloth home, so when the bundle just
+ # installed ships no sd-server the hit here can be that legacy server, built for a different accelerator.
+ # None, not the fallback: an install just completed, so the router's next step resolves the sd-cli it landed,
+ # and a one-shot run on the right build beats a resident server on the wrong one. The fallback stays for the
+ # failure path above, where no matching binary was fetched at all.
if installed and _accelerator_changed(installed, accelerator):
return None
return installed or fallback
@@ -839,11 +810,9 @@ def ensure_sd_server_binary(
@dataclass(frozen = True)
class _SdState:
- """The loaded native checkpoint: resolved asset paths + run settings.
-
- ``server`` is the resident ``sd-server`` process (the model is loaded once, inside
- it) when ``mode == "server"``; in the ``"oneshot"`` fallback it is ``None`` and each
- generation re-runs ``sd-cli``."""
+ """The loaded native checkpoint: resolved asset paths + run settings. ``server`` is the resident
+ ``sd-server`` process (the model is loaded once, inside it) when ``mode == "server"``; in the
+ ``"oneshot"`` fallback it is ``None`` and each generation re-runs ``sd-cli``."""
repo_id: str
base_repo: str
@@ -866,13 +835,13 @@ class _SdState:
# The FLUX.2 inner_dim this load read out of the checkpoint's own header, when it could. Kept so the delete guard
# reconstructs the SAME encoder pick without re-probing under the lock.
flux2_inner_dim: Optional[int] = None
- # The managed tree's recorded accelerator when this load chose its binary. The one-shot path re-resolves sd-cli per
- # image, so without this it would silently adopt an install that landed between images even when that install is for
- # a DIFFERENT accelerator, while ``device`` and ``offload_flags`` still describe the build the load committed to.
- # None on the server path, which asks the same question at start time against its own local copy.
+ # The managed tree's recorded accelerator when this load chose its binary. The one-shot path re-resolves sd-cli
+ # per image, so without this it would silently adopt an install that landed between images even when that install
+ # is for a DIFFERENT accelerator, while ``device`` and ``offload_flags`` still describe the build the load
+ # committed to. None on the server path, which asks the same question at start time against its own local copy.
sd_accelerator: Optional[str] = None
- # Physical card behind the server's single resolved CUDA/ROCm backend. None for CPU/Metal/Vulkan, an unresolved pin,
- # automatic multi-GPU, and one-shot mode; those shapes cannot safely consume the startup VRAM floor.
+ # Physical card behind the server's single resolved CUDA/ROCm backend. None for CPU/Metal/Vulkan, an unresolved
+ # pin, automatic multi-GPU, and one-shot mode; those shapes cannot safely consume the startup VRAM floor.
physical_gpu_id: Optional[int] = None
@@ -922,8 +891,8 @@ def _resolved_server_physical_gpu_id(
def _memory_policy(memory_mode: Optional[str], cpu_offload: bool) -> str:
- """Map the diffusers memory knobs onto an sd-cli offload policy. Only meaningful
- off-CPU (forced sd_cpp / MPS); on CPU everything is resident in RAM anyway."""
+ """Map the diffusers memory knobs onto an sd-cli offload policy. Only meaningful off-CPU (forced
+ sd_cpp / MPS); on CPU everything is resident in RAM anyway."""
mode = (memory_mode or "").strip().lower()
if mode == "low_vram":
return OFFLOAD_SEQUENTIAL
@@ -973,12 +942,9 @@ def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float)
def _map_guidance(
fam: DiffusionFamily, guidance: Optional[float]
) -> tuple[Optional[float], Optional[float]]:
- """(cfg_scale, guidance) for sd-cli from the single diffusers ``guidance`` value.
-
- FLUX families take a distilled embedded ``--guidance``; everyone else uses real
- classifier-free ``--cfg-scale``. A distilled 0/1 means CFG off (sd-cli's 1.0); a
- value > 1 is real CFG. Mirrors the engine mapping validated in the CPU benchmark.
- """
+ """(cfg_scale, guidance) for sd-cli from the single diffusers ``guidance`` value. FLUX families
+ take a distilled embedded ``--guidance``; everyone else uses real classifier-free
+ ``--cfg-scale``. A distilled 0/1 means CFG off (sd-cli's 1.0); a value > 1 is real CFG."""
if fam.name in ("flux.1", "flux.2-klein", "flux.2-dev"):
return None, (float(guidance) if guidance is not None else None)
cfg = float(guidance) if (guidance is not None and guidance > 1.0) else 1.0
@@ -987,14 +953,11 @@ def _map_guidance(
def _fetch_repo_map(assets: list[tuple[str, str, str]], hf_token: Optional[str]) -> dict[str, str]:
"""upstream asset repo -> the repo to actually fetch from (its ungated mirror, or itself).
-
Decided per REPO over its whole file list, the same input ``download_plan`` uses, so staging
- and the load agree even when a repo carries several assets.
-
- Two swaps, in order: a GATED vendor base goes to its ungated mirror, then a mirror whose
- community repack is already cached goes back to the repack. The second only ever spares an
- existing install a re-download of bytes it already holds under the old repo key; a fresh one
- still pulls the mirror."""
+ and the load agree even when a repo carries several assets. Two swaps, in order: a GATED
+ vendor base goes to its ungated mirror, then a mirror whose community repack is already
+ cached goes back to the repack. The second only ever spares an existing install a re-download
+ of bytes it already holds under the old repo key; a fresh one still pulls the mirror."""
by_repo: dict[str, list[str]] = {}
for repo, filename, _kind in assets:
by_repo.setdefault(repo, []).append(filename)
@@ -1010,7 +973,6 @@ class _NeverRaised(Exception):
def _local_entry_not_found_error() -> type[BaseException]:
"""huggingface_hub's "not cached and downloads are disabled" error, or an unraisable stand-in.
-
Resolved lazily and defensively for the same reason the rest of this module imports
``huggingface_hub`` inside functions: an unexpected hub layout must degrade to today's error,
never break the import or swallow an unrelated exception. The stand-in matches nothing, so a
@@ -1024,10 +986,8 @@ def _local_entry_not_found_error() -> type[BaseException]:
def _with_mirrors(repo_ids) -> tuple[str, ...]:
"""``repo_ids`` plus the ungated mirror and the community repack of each, de-duplicated, order
- preserved.
-
- The delete-cached guard must protect whichever of the set the bytes landed in, and that
- decision is re-taken per load; naming all of them is cheap and cannot under-protect."""
+ preserved. The delete-cached guard must protect whichever of the set the bytes landed in, and
+ that decision is re-taken per load; naming all of them is cheap and cannot under-protect."""
out: list[str] = []
for rid in repo_ids:
if not rid:
@@ -1073,12 +1033,12 @@ class SdCppDiffusionBackend:
# mid-startup.
self._pending_server: Optional[SdCppServer] = None
self._gen: Optional[_SdGen] = None
- # Set by _resolve_backend when it had to skip an accelerator install because the managed tree was still in use;
- # the load retries it once the tree is free.
+ # Set by _resolve_backend when it had to skip an accelerator install because the managed tree was still in
+ # use; the load retries it once the tree is free.
self._deferred_accelerator_install = False
# Servers taken out of _state/_pending_server whose stop() has not returned yet. unload() deliberately stops
- # outside the lock (terminate can take seconds), so between the clear and the stop the fields say idle while the
- # process is still running its own executable.
+ # outside the lock (terminate can take seconds), so between the clear and the stop the fields say idle while
+ # the process is still running its own executable.
self._stopping_servers = 0
# Set once this load's graph proved unrunnable on the GPU backend (a ggml unsupported-op abort), so the CPU
# restart happens once per load. Cleared by each load.
@@ -1095,8 +1055,8 @@ class SdCppDiffusionBackend:
self._stopping_servers += count
def _stop_reserved(self, server: Any) -> None:
- """Stop a server whose pending stop was already reserved by ``_reserve_stop``. Never
- raises: a teardown may not fail a load or an unload."""
+ """Stop a server whose pending stop was already reserved by ``_reserve_stop``. Never raises:
+ a teardown may not fail a load or an unload."""
try:
server.stop()
except Exception as exc: # noqa: BLE001 -- a stop that fails must not fail the caller
@@ -1124,8 +1084,8 @@ class SdCppDiffusionBackend:
"""The SdCppEngine, installing the binary on first use. Raises if unusable."""
if self._engine is not None and self._engine.is_available():
return self._engine
- # The accelerator this host resolves to, never the "cpu" default: this is also the one-shot FALLBACK path (a GPU
- # sd-server that would not start lands here), and asking for the CPU build there would reinstall the plain
+ # The accelerator this host resolves to, never the "cpu" default: this is also the one-shot FALLBACK path (a
+ # GPU sd-server that would not start lands here), and asking for the CPU build there would reinstall the plain
# bundle over the working GPU one and run the whole generation on the CPU.
binary = ensure_sd_cpp_binary(
allow_install = _install_allowed() and not _tree_in_use(self),
@@ -1138,25 +1098,21 @@ class SdCppDiffusionBackend:
def _resolve_backend(self) -> tuple[str, Optional[str], Optional[SdCppEngine]]:
"""Pick the native execution mode: ("server", binary, None) or ("oneshot", None, engine).
-
- The persistent ``sd-server`` is preferred (load once, serve many). The one-shot
- ``sd-cli`` is the fallback for older / custom builds that lack the server target.
- An explicitly injected engine forces one-shot (the unit-test seam and an escape
- hatch), so a test never spawns a real server or triggers an install. A lazily
- cached fallback engine does NOT force one-shot: once a resident server becomes
- available (installed, or a per-model start that previously failed now works), the
- next load can use it, instead of being pinned to one-shot for the whole session.
- """
+ The persistent ``sd-server`` is preferred (load once, serve many); the one-shot
+ ``sd-cli`` is the fallback for older / custom builds that lack the server target. An
+ explicitly injected engine forces one-shot (the unit-test seam and an escape hatch), so a
+ test never spawns a real server or triggers an install. A lazily cached fallback engine
+ does NOT force one-shot: once a resident server becomes available, the next load can use
+ it instead of being pinned to one-shot for the whole session."""
if self._engine_injected and self._engine is not None:
return "oneshot", None, self._resolve_engine()
accelerator = self._resolved_accelerator()
# An accelerator upgrade REPLACES the binaries in the managed tree, and this runs before the load stops the
- # resident server (which is executing its own file) or waits out an in-flight one-shot sd-cli. Linux refuses to
- # open a running executable for writing (ETXTBSY) and Windows locks it, so an install here fails and can leave
- # the tree half-written. _accelerator_changed refuses the upgrade while the tree is in use, whoever asks; record
- # that it did, so this load retries it after its own teardown, when the tree is the only thing that has changed.
- # _managed_tree_in_use covers the singleton for callers that never see this instance (the engine router); this
- # load's own state is the authority for this load.
+ # resident server or waits out an in-flight one-shot sd-cli. Linux refuses to open a running executable for
+ # writing (ETXTBSY) and Windows locks it, so an install here fails and can leave the tree half-written.
+ # _accelerator_changed refuses the upgrade while the tree is in use, whoever asks; record that it did, so this
+ # load retries it after its own teardown. _managed_tree_in_use covers the singleton for callers that never see
+ # this instance (the engine router); this load's own state is the authority for this load.
upgrade_pending = _tree_in_use(self) or _managed_tree_in_use()
self._deferred_accelerator_install = upgrade_pending
server_binary = ensure_sd_server_binary(
@@ -1170,14 +1126,13 @@ class SdCppDiffusionBackend:
return "oneshot", None, self._resolve_engine()
def _upgrade_server_after_teardown(self, server_binary: Optional[str]) -> Optional[str]:
- """Land the install this load deferred, now the managed tree is free.
-
- Called under both locks with the old server stopped and the previous generation finished,
- which is the only moment nothing is executing out of the tree. ``server_binary`` is None on
- a serverless install (one-shot sd-cli only): the install still has to run, since the same
- archive carries the sd-cli this load is about to generate with -- skipping it there is what
- left a CUDA request committing the old CPU CLI. Returns the upgraded path, the one passed
- in when nothing changed or the install could not deliver, or None when there was no server
+ """Land the install this load deferred, now the managed tree is free. Called under both
+ locks with the old server stopped and the previous generation finished, which is the only
+ moment nothing is executing out of the tree. ``server_binary`` is None on a serverless
+ install (one-shot sd-cli only): the install still has to run, since the same archive
+ carries the sd-cli this load is about to generate with -- skipping it there is what left
+ a CUDA request committing the old CPU CLI. Returns the upgraded path, the one passed in
+ when nothing changed or the install could not deliver, or None when there was no server
and the archive has none: never worse than what the load already had."""
if not _install_allowed():
return server_binary
@@ -1197,19 +1152,16 @@ class SdCppDiffusionBackend:
logger.warning("sd.cpp accelerator upgrade failed: %s", exc)
return server_binary
- # ── Background load + progress ─────────────────────────────────────────
-
def begin_load(
self,
repo_id: str,
*,
- # Same name, position and default as DiffusionBackend.begin_load: the route calls whichever engine was activated
- # through ONE call site and passes this unconditionally, so an engine that does not declare it TypeErrors every
- # load on the hosts that select it (CPU-only, opted-in MPS, UNSLOTH_DIFFUSION_ENGINE=sd_cpp) -- including the
- # ordinary user-initiated ones, which pass False. Covers the MODEL ASSETS only: the GGUF, the VAE and the text
- # encoders this pick fetches from the Hub. It deliberately says nothing about the sd-cli/sd-server BINARY, which
- # is a separate managed tree with its own install policy (_install_allowed / ensure_sd_*_binary); a background
- # load may still install one, exactly as it does today.
+ # Same name, position and default as DiffusionBackend.begin_load: the route calls whichever engine was
+ # activated through ONE call site and passes this unconditionally, so an engine that does not declare it
+ # TypeErrors every load on the hosts that select it. Covers the MODEL ASSETS only: the GGUF, the VAE and the
+ # text encoders this pick fetches from the Hub. It deliberately says nothing about the sd-cli/sd-server
+ # BINARY, which is a separate managed tree with its own install policy; a background load may still install
+ # one, exactly as it does today.
local_files_only: bool = False,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
@@ -1218,8 +1170,8 @@ class SdCppDiffusionBackend:
cpu_offload: bool = False,
memory_mode: Optional[str] = None,
speed_mode: Optional[str] = None,
- # diffusers-only knobs accepted for a uniform call and ignored (sd.cpp has no torchao quant / SDPA dispatcher /
- # fbcache)
+ # diffusers-only knobs accepted for a uniform call and ignored (sd.cpp has no torchao quant / SDPA dispatcher
+ # / fbcache)
text_encoder_quant: Optional[str] = None,
transformer_quant: Optional[str] = None,
transformer_quant_fast_accum: Optional[bool] = None,
@@ -1229,8 +1181,8 @@ class SdCppDiffusionBackend:
transformer_cache_threshold: Optional[float] = None,
# Accepted for interface parity; native is GGUF-only (router forces diffusers otherwise).
model_kind: Optional[str] = None,
- # Parity with the diffusers load-time LoRA bake; native applies LoRA per generation, so a load-time selection is
- # ignored.
+ # Parity with the diffusers load-time LoRA bake; native applies LoRA per generation, so a load-time selection
+ # is ignored.
loras: Optional[list[tuple[str, float]]] = None,
gpu_ids: Optional[list[int]] = None,
# The ordinal the ROUTE already ranked, so the preflight and the load agree on one card
@@ -1239,10 +1191,10 @@ class SdCppDiffusionBackend:
"""Validate, then fetch assets on a daemon thread. Returns at once."""
# Empty/whitespace token = "no token"; "" verbatim breaks the anonymous fallback.
hf_token = hf_token.strip() if hf_token and hf_token.strip() else None
- # Same fallback the diffusers and video backends take: the route ranks the selection and passes the winner, but
- # a direct caller (an MCP client, a test, a plugin) hands over gpu_ids alone, and without this the native engine
- # is the one engine that would drop the pick silently. Re-ranked only when nobody has, so a route-resolved
- # winner is never second-guessed against free VRAM that has moved since.
+ # Same fallback the diffusers and video backends take: the route ranks the selection and passes the winner,
+ # but a direct caller (an MCP client, a test, a plugin) hands over gpu_ids alone, and without this the native
+ # engine is the one engine that would drop the pick silently. Re-ranked only when nobody has, so a
+ # route-resolved winner is never second-guessed against free VRAM that has moved since.
if gpu_ordinal is None:
gpu_ordinal = (
resolve_selected_cuda_ordinal(gpu_ids)
@@ -1295,8 +1247,8 @@ class SdCppDiffusionBackend:
self._active_generate_cancel.set()
self._load_token += 1
token = self._load_token
- # A NEW event per load, never a clear() of the shared one: unload() sets the event the running worker holds
- # but also drops _loading, so a clear() here would un-cancel its still-running multi-gigabyte pull.
+ # A NEW event per load, never a clear() of the shared one: unload() sets the event the running worker
+ # holds but also drops _loading, so a clear() here would un-cancel its still-running multi-gigabyte pull.
cancel_event = threading.Event()
self._cancel_event = cancel_event
self._loading = _SdLoading(
@@ -1352,17 +1304,16 @@ class SdCppDiffusionBackend:
# This load's own event: a later load replaces self._cancel_event rather than clearing it.
cancel_event = _cancel_event if _cancel_event is not None else self._cancel_event
# The server this load publishes to _pending_server, out here so the backstop below can always unpublish it. A
- # leaked _pending_server reads as "the managed tree is busy" for the rest of the process and blocks every later
- # install.
+ # leaked _pending_server reads as "the managed tree is busy" for the rest of the process and blocks every
+ # later install.
started: Optional[SdCppServer] = None
try:
- # Resolve mode + binary up front so an install failure surfaces before the multi-GB pull
- # Resolve mode (server preferred, one-shot fallback) + binary up front so an install failure surfaces before
- # the multi-GB pull.
+ # Resolve mode (server preferred, one-shot fallback) + binary up front so an install failure surfaces
+ # before the multi-GB pull.
mode, server_binary, engine = self._resolve_backend()
if mode == "server":
- # Probe the server binary before the pull: a present-but-unrunnable build would download everything then
- # fail
+ # Probe the server binary before the pull: a present-but-unrunnable build would download everything
+ # then fail
assert server_binary is not None
if not _server_binary_runnable(server_binary):
logger.warning(
@@ -1386,10 +1337,10 @@ class SdCppDiffusionBackend:
# build. "It exists and it runs" is therefore not evidence that it is the build this load resolved its
# device and offload policy for, so the answer is re-asked under the reader claim.
server_accelerator = _installed_accelerator_of(server_binary)
- # The same pin for the one-shot CLI, and for the same reason. Sampling it only at state construction, after
- # the download, would record whatever an install left in the tree in that window and the first generation --
- # which re-reads the tree and compares -- would then agree with the replacement, so the check that exists to
- # notice a swap could never fire for one that landed during the download.
+ # The same pin for the one-shot CLI, and for the same reason. Sampling it only at state construction,
+ # after the download, would record whatever an install left in the tree in that window, and the first
+ # generation -- which re-reads the tree and compares -- would then agree with the replacement, so the
+ # check that exists to notice a swap could never fire for one that landed during the download.
engine_accelerator = _installed_accelerator_of(getattr(engine, "binary", None))
if mode == "oneshot":
# version() is None when a present binary can't run; fail now, not on the first generation
@@ -1397,13 +1348,13 @@ class SdCppDiffusionBackend:
if engine.version() is None:
raise RuntimeError("sd-cli binary is present but not runnable.")
- # Swap ONCE so the size probe and the download agree: sizes come from paths-info, which -- unlike model_info
- # -- 401s anonymously on a gated repo, so probing the upstream drops the VAE from the progress total the
- # mirror then pulls. The probe is a RANGE READ off the Hub when the checkpoint is not on disk, so an offline
- # load asks it the way begin_load does: memo or local header or nothing. A None here only falls back to the
- # filename heuristic for the encoder pick, and a cache-only load can fetch nothing the heuristic did not
- # already have. The speech verdict lands here rather than in begin_load, which is offline-only by contract;
- # before _asset_specs, so the refusal precedes any fetch.
+ # Swap ONCE so the size probe and the download agree: sizes come from paths-info, which -- unlike
+ # model_info -- 401s anonymously on a gated repo, so probing the upstream drops the VAE from the progress
+ # total the mirror then pulls. The probe is a RANGE READ off the Hub when the checkpoint is not on disk,
+ # so an offline load asks it the way begin_load does: memo or local header or nothing. A None here only
+ # falls back to the filename heuristic for the encoder pick, and a cache-only load can fetch nothing the
+ # heuristic did not already have. The speech verdict lands here rather than in begin_load, which is
+ # offline-only by contract; before _asset_specs, so the refusal precedes any fetch.
_assert_pick_is_not_speech(
repo_id, gguf_filename, hf_token, allow_network = not local_files_only
)
@@ -1419,10 +1370,10 @@ class SdCppDiffusionBackend:
dict.fromkeys(r for r, _f, kind in specs if kind != "diffusion_model")
)
# And record them, from the SAME post-probe specs. begin_load records what it can, but it resolves the
- # header offline, so a remote or renamed FLUX.2-klein 9B checkpoint with no cached probe records the default
- # 4B encoder while this load fetches the 9B one. Whatever that leaves unrecorded is a companion the delete
- # guard would let go while its GGUF is still installed. Recorded on the FETCH ids too, since a gated mirror
- # or a cached community repack is where the bytes land.
+ # header offline, so a remote or renamed FLUX.2-klein 9B checkpoint with no cached probe records the
+ # default 4B encoder while this load fetches the 9B one. Whatever that leaves unrecorded is a companion
+ # the delete guard would let go while its GGUF is still installed. Recorded on the FETCH ids too, since a
+ # gated mirror or a cached community repack is where the bytes land.
try:
from hub.utils.companion_assets import record_companion_link
for asset_repo in dict.fromkeys(
@@ -1443,10 +1394,10 @@ class SdCppDiffusionBackend:
hf_token,
local_files_only = local_files_only,
)
- # Skipped outright offline: the size probe is get_paths_info, a Hub round trip, and its only product is the
- # progress bar's denominator. A cache-only load resolves every asset from disk in milliseconds, so 0 (the
- # value this method already reports for any size the Hub will not answer) costs nothing and asking would be
- # the one network call left on the path.
+ # Skipped outright offline: the size probe is get_paths_info, a Hub round trip, and its only product is
+ # the progress bar's denominator. A cache-only load resolves every asset from disk in milliseconds, so 0
+ # (the value this method already reports for any size the Hub will not answer) costs nothing and asking
+ # would be the one network call left on the path.
if not local_files_only:
self._set_expected_bytes(assets, hf_token)
paths = self._fetch_assets(
@@ -1470,10 +1421,10 @@ class SdCppDiffusionBackend:
offload: tuple[str, ...] = ()
if device != "cpu":
offload = tuple(offload_flags(_memory_policy(memory_mode, cpu_offload)))
- # The device pin is NOT folded in here: the binary can still change below, through the deferred accelerator
- # install, the post-download re-resolve, or a server start that falls back to one-shot, and the ggml device
- # names come from whichever build ends up running. It is added at each point the flags are handed to a
- # binary instead.
+ # The device pin is NOT folded in here: the binary can still change below, through the deferred
+ # accelerator install, the post-download re-resolve, or a server start that falls back to one-shot, and
+ # the ggml device names come from whichever build ends up running. It is added at each point the flags are
+ # handed to a binary instead.
gpu_ordinal = gpu_ordinal if device == "cuda" else None
native_speed = _native_speed_for(speed_mode)
@@ -1495,35 +1446,34 @@ class SdCppDiffusionBackend:
self._reserve_stop()
if old_state is not None and old_state.server is not None:
self._stop_reserved(old_state.server)
- # The tree is free now, so an install deferred in _resolve_backend can land: this runs under both locks,
- # the old server is stopped, the previous generation has finished and no new one can start. Not gated on
- # the resolved mode: a serverless install resolves to one-shot precisely BECAUSE the deferral suppressed
- # the install, and its sd-cli comes out of the same archive.
+ # The tree is free now, so an install deferred in _resolve_backend can land: this runs under both
+ # locks, the old server is stopped, the previous generation has finished and no new one can start. Not
+ # gated on the resolved mode: a serverless install resolves to one-shot precisely BECAUSE the deferral
+ # suppressed the install, and its sd-cli comes out of the same archive.
if self._deferred_accelerator_install:
self._deferred_accelerator_install = False
upgraded = self._upgrade_server_after_teardown(server_binary)
if mode == "server":
server_binary = upgraded
- # This load's own install just rewrote the tree, under the install claim, so what it left behind IS
- # the decision here -- comparing against the answer from before it would fail the load on the
+ # This load's own install just rewrote the tree, under the install claim, so what it left behind
+ # IS the decision here -- comparing against the answer from before it would fail the load on the
# upgrade it asked for. Both pins move: a serverless upgrade lands the sd-cli out of the same
# archive.
server_accelerator = _installed_accelerator_of(server_binary)
engine_accelerator = _installed_accelerator_of(getattr(engine, "binary", None))
- # A new checkpoint earns a fresh attempt on the GPU backend: the previous abort says nothing about this
- # graph.
+ # A new checkpoint earns a fresh attempt on the GPU backend: the previous abort says nothing about
+ # this graph.
self._cpu_backend_forced = False
server: Optional[SdCppServer] = None
if mode == "server":
assert server_binary is not None
# _fetch_assets above runs for minutes with no claim on the tree (there is nothing executing in it
# yet to claim for), so an install can have swept this path between layouts since _resolve_backend
- # picked it. Re-resolve before starting: the stale path would drop the load to one-shot for nothing,
- # or start a build this load did not select. Under the READER, and held until _pending_server is
- # published. Re-resolving alone does not close the race: allow_install=False only declines to
- # install, it does not wait for or claim the tree, so an installer that has already passed its
- # in-use check can sweep this executable between the re-read and the start. Once _pending_server is
- # published, _tree_in_use covers it and the claim is no longer what is holding the installer off.
+ # picked it. Re-resolve before starting: the stale path would drop the load to one-shot for
+ # nothing, or start a build this load did not select. Under the READER, and held until
+ # _pending_server is published. Re-resolving alone does not close the race: allow_install=False
+ # only declines to install, it does not wait for or claim the tree, so an installer that has
+ # already passed its in-use check can sweep this executable between the re-read and the start.
with _tree_reader(server_binary, cancel_event):
refreshed = ensure_sd_server_binary(
allow_install = False, accelerator = self._resolved_accelerator()
@@ -1542,9 +1492,9 @@ class SdCppDiffusionBackend:
)
mode, server_binary, engine = "oneshot", None, self._resolve_engine()
# And pin off THIS engine. The one-shot pin above was taken while the mode was still
- # "server", i.e. off an engine of None, so leaving it would compare the sd-cli just resolved
- # against None and refuse the documented fallback on every load that reaches it. Resolved
- # here, inside the claim, so it is vetted at the moment it is pinned.
+ # "server", i.e. off an engine of None, so leaving it would compare the sd-cli just
+ # resolved against None and refuse the documented fallback on every load that reaches it.
+ # Resolved here, inside the claim, so it is vetted at the moment it is pinned.
engine_accelerator = _installed_accelerator_of(
getattr(engine, "binary", None)
)
@@ -1558,12 +1508,11 @@ class SdCppDiffusionBackend:
server = SdCppServer(server_binary)
# Published INSIDE the claim: _tree_in_use reads _pending_server, so this is the handover
# from "a reader holds the tree" to "a starting server does", with no gap between them.
- # Cancellation is re-read in the SAME block. The revalidation above can sit for 20s in
- # _server_binary_runnable, and an unload arriving in that window finds no _pending_server to
- # stop, so without this the load would go on to spawn the process anyway and hold the device
- # for the whole start() timeout before the commit below noticed. Asked under the lock that
- # publishes, so an unload either stops this server or is seen here; it cannot fall between
- # the two.
+ # Cancellation is re-read in the SAME block: the revalidation above can sit for 20s in
+ # _server_binary_runnable, and an unload arriving in that window finds no _pending_server
+ # to stop, so without this the load would spawn the process anyway and hold the device for
+ # the whole start() timeout. Asked under the lock that publishes, so an unload either
+ # stops this server or is seen here.
with self._lock:
if self._load_token != _load_token or cancel_event.is_set():
server = None
@@ -1575,14 +1524,13 @@ class SdCppDiffusionBackend:
if mode == "server":
assert server_binary is not None
assert server is not None
- # ``started`` is the object to clear below ``started`` (set with _pending_server above) is the
- # object to clear below. ``server`` itself is set to None when start() fails and the load falls back
- # to one-shot, and comparing THAT against _pending_server left the stopped server published forever,
- # which reads as "the managed tree is busy" for the rest of the process. A server that DID start
- # stays published until _state takes it over, under the same lock. Clearing it here would leave a
- # window in which the tree reads as idle -- no reader, no pending, no state -- while the process is
- # up and running out of it, and an ensure_* landing in that window admits an install that later
- # overwrites the executable underneath the live server.
+ # ``started`` (set with _pending_server above) is the object to clear below. ``server`` itself is
+ # set to None when start() fails and the load falls back to one-shot, and comparing THAT against
+ # _pending_server left the stopped server published forever, which reads as "the managed tree is
+ # busy" for the rest of the process. A server that DID start stays published until _state takes it
+ # over, under the same lock: clearing it here would leave a window in which the tree reads as idle
+ # while the process is up and running out of it, and an ensure_* landing in that window admits an
+ # install that later overwrites the executable underneath the live server.
started_ok = False
try:
server.start(
@@ -1605,8 +1553,8 @@ class SdCppDiffusionBackend:
)
server.stop()
# Unpublish BEFORE resolving the one-shot engine: _pending_server means "a process is running
- # out of the tree", and leaving this stopped one there would block the very sd-cli install this
- # fallback needs.
+ # out of the tree", and leaving this stopped one there would block the very sd-cli install
+ # this fallback needs.
with self._lock:
if self._pending_server is server:
self._pending_server = None
@@ -1661,8 +1609,8 @@ class SdCppDiffusionBackend:
files = files,
vae_format = fam.sd_cpp_vae_format,
native_speed = native_speed,
- # Pinned against the binary this load COMMITTED to, which a deferred install or a one-shot fallback
- # may have changed since the policy was built.
+ # Pinned against the binary this load COMMITTED to, which a deferred install or a one-shot
+ # fallback may have changed since the policy was built.
offload_flags = committed_offload_flags,
threads = _default_threads(),
sampling_method = fam.sd_cpp_sampling_method,
@@ -1690,9 +1638,9 @@ class SdCppDiffusionBackend:
orphan: Optional[SdCppServer] = None
with self._lock:
if self._load_token != _load_token:
- # Superseded / unloaded while loading: discard the started server so it doesn't leak. Reserved
- # in the SAME block that unpublishes it, so the tree never reads as idle while the process is
- # still coming down.
+ # Superseded / unloaded while loading: discard the started server so it does not leak.
+ # Reserved in the SAME block that unpublishes it, so the tree never reads as idle while the
+ # process is still coming down.
superseded = True
if server is not None:
self._reserve_stop()
@@ -1700,8 +1648,8 @@ class SdCppDiffusionBackend:
else:
self._state = state
self._loading = None
- # The exchange the started server stayed published for: it is _state's now, or reserved for the stop
- # below, and either way _tree_in_use still sees it.
+ # The exchange the started server stayed published for: it is _state's now, or reserved for the
+ # stop below, and either way _tree_in_use still sees it.
if self._pending_server is started:
self._pending_server = None
if orphan is not None:
@@ -1740,18 +1688,17 @@ class SdCppDiffusionBackend:
hf_token: Optional[str] = None,
**_load_kwargs: Any,
) -> dict[str, Any]:
- """The repos + exact files a NATIVE load of this pick needs, in the same envelope the
- diffusers backend returns, so the Hub download manager stages what sd-cli will actually
- open.
+ """The repos + exact files a NATIVE load of this pick needs, in the same envelope the diffusers
+ backend returns, so the Hub download manager stages what sd-cli will actually open.
The two engines want different files: diffusers builds a pipeline around the base repo's
sharded components, while sd-cli reads the single-file VAE + text encoders declared in
``diffusion_families``. Planning with the wrong engine stages tens of GB the load never
opens and then pulls the native assets inline, outside the manager's progress and disk
- preflight -- so the route asks whichever engine it predicts the load will select.
-
- The diffusers-only kwargs (quant / memory / LoRA) are accepted and ignored, exactly as
- ``begin_load`` accepts them: nothing sd-cli fetches depends on them."""
+ preflight -- so the route asks whichever engine it predicts the load will select. The
+ diffusers-only kwargs (quant / memory / LoRA) are accepted and ignored, exactly as
+ ``begin_load`` accepts them.
+ """
if not gguf_filename:
raise ValueError(
"gguf_filename is required: the native engine loads single-file GGUF checkpoints only."
@@ -1775,9 +1722,9 @@ class SdCppDiffusionBackend:
# are gated (the FLUX.1 VAE lives in black-forest-labs/FLUX.1-schnell) and an anonymous user would 401 at
# staging, never reaching the swap. Same per-repo file list on both sides, so both take the same decision.
fetch_repo = _fetch_repo_map(specs, hf_token)
- # MERGED, not reassigned: two upstream repos can share one fetch repo (the FLUX.2 VAE and the dev encoders both
- # come from Comfy-Org/flux2-dev once that repack is cached), and a plain comprehension would drop whichever
- # landed first, leaving its files out of both the staged entry and the footprint.
+ # MERGED, not reassigned: two upstream repos can share one fetch repo (the FLUX.2 VAE and the dev encoders
+ # both come from Comfy-Org/flux2-dev once that repack is cached), and a plain comprehension would drop
+ # whichever landed first, leaving its files out of both the staged entry and the footprint.
merged: dict[str, list[str]] = {}
for repo, names in by_repo.items():
into = merged.setdefault(fetch_repo[repo], [])
@@ -1789,8 +1736,8 @@ class SdCppDiffusionBackend:
sizes = self._plan_file_sizes(by_repo, hf_token)
entries: list[dict[str, Any]] = []
total = 0
- # Imported here, not at module scope: diffusion.py is the heavier module and the routes already load this one on
- # its own
+ # Imported here, not at module scope: diffusion.py is the heavier module and the routes already load this one
+ # on its own
from core.inference.diffusion import DiffusionBackend
for repo, names in by_repo.items():
@@ -1798,9 +1745,9 @@ class SdCppDiffusionBackend:
# Same missing-file filter the diffusers planner applies: _fetch_assets already reads both cache roots, so
# staging an asset it can resolve re-downloads it for nothing and fails offline. required_bytes keeps the
# UNFILTERED sum -- it is the disk footprint. Sized, so a republished asset under the same name is a miss
- # rather than a silent inline fetch during the load. Without it the probe trusts the local ref alone.
- # Loadable, not merely cached: a stale live-root copy shadows a good one in the other root, because the
- # fetch only switches roots when the live lookup finds nothing.
+ # rather than a silent inline fetch during the load. Loadable, not merely cached: a stale live-root copy
+ # shadows a good one in the other root, because the fetch only switches roots when the live lookup finds
+ # nothing.
missing = [
n
for n in names
@@ -1817,12 +1764,10 @@ class SdCppDiffusionBackend:
# Only the transformer entry carries the GGUF filename; the VAE / encoder entries are plain single
# files.
"gguf_filename": gguf_filename if repo == fetch_repo_id else None,
- # Compared against the POST-swap id, because a gated pick staged from its ungated mirror no longer
- # matches the id the caller asked for.
- # Same entry, said plainly for the panel's label: the transformer IS the pick, the VAE / encoders
- # are required assets. Compared against the POST-swap id, because a gated pick staged from its
- # ungated mirror no longer matches the id the caller asked for. Native picks are always single-file,
- # so there is no pipeline case.
+ # Said plainly for the panel's label: the transformer IS the pick, the VAE / encoders are required
+ # assets. Compared against the POST-swap id, because a gated pick staged from its ungated mirror
+ # no longer matches the id the caller asked for. Native picks are always single-file, so there is
+ # no pipeline case.
"checkpoint": repo == fetch_repo_id and gguf_filename in missing,
}
)
@@ -1867,13 +1812,12 @@ class SdCppDiffusionBackend:
error this replaces. Run from BOTH the plan and ``_run_load``, as the diffusers backend
does, because the UI falls back to /images/load when the plan call fails.
- ``local_files_only`` skips it entirely. The probe is a ``model_info`` call plus, for a
- gated repo, a metadata HEAD -- pure network, whose whole purpose is to turn a 401 that
- would otherwise arrive mid-download into a licence URL up front. A cache-only load never
- starts that download: it either resolves the companion from disk (in which case the probe
- would only have excused it anyway, via ``_already_downloaded``) or fails on the local
- miss, which is the clearer error of the two. Skipping is therefore strictly what the
- offline contract asks for and never hides a refusal a network load would have made."""
+ ``local_files_only`` skips it entirely. The probe is a ``model_info`` call plus, for a gated
+ repo, a metadata HEAD -- pure network, whose whole purpose is to turn a 401 that would
+ otherwise arrive mid-download into a licence URL up front. A cache-only load never starts
+ that download: it either resolves the companion from disk or fails on the local miss, which
+ is the clearer error of the two.
+ """
if local_files_only:
return
from core.inference.diffusion import _assert_base_repo_accessible
@@ -1896,11 +1840,11 @@ class SdCppDiffusionBackend:
hf_token: Optional[str] = None,
allow_network: bool = True, # noqa: ARG002 -- signature parity; no speech probe here
) -> None:
- """The companion refusal ``_run_load`` makes, run by the route BEFORE it takes the GPU.
-
- Same signature and reason as the diffusers backend's: ``_run_load`` runs on the load thread,
- after a forced-native load on a GPU host already evicted chat, so a pick refused only there
- unloads the resident model first. Nothing to check without a family or checkpoint name."""
+ """The companion refusal ``_run_load`` makes, run by the route BEFORE it takes the GPU. Same
+ signature and reason as the diffusers backend's: ``_run_load`` runs on the load thread,
+ after a forced-native load on a GPU host already evicted chat, so a pick refused only
+ there unloads the resident model first. Nothing to check without a family or checkpoint
+ name."""
if fam is None or not gguf_filename:
return
# Post-swap, as the plan and the load are: the swap is pure, so all three decide alike
@@ -1921,8 +1865,7 @@ class SdCppDiffusionBackend:
def _plan_file_sizes(
by_repo: dict[str, list[str]], hf_token: Optional[str]
) -> dict[tuple[str, str], int]:
- """(repo, filename) -> size in bytes, best-effort (0 for anything the Hub won't answer).
-
+ """(repo, filename) -> size in bytes, best-effort (0 for anything the Hub will not answer).
A missing size only understates the manager's progress total; it must not fail the plan,
which is the cheap pre-flight for a load that would otherwise download inline."""
out: dict[tuple[str, str], int] = {}
@@ -1964,13 +1907,13 @@ class SdCppDiffusionBackend:
fam: DiffusionFamily,
inner_dim: Optional[int] = None,
) -> list[tuple[str, str, str]]:
- """(repo, filename, kind) for every file sd-cli needs. ``kind`` is the
- SdCppModelFiles field; the transformer reuses the diffusers GGUF."""
+ """(repo, filename, kind) for every file sd-cli needs. ``kind`` is the SdCppModelFiles
+ field; the transformer reuses the diffusers GGUF."""
specs: list[tuple[str, str, str]] = [(repo_id, gguf_filename, "diffusion_model")]
if fam.sd_cpp_vae:
specs.append((fam.sd_cpp_vae[0], fam.sd_cpp_vae[1], "vae"))
- # Pick the encoder per variant so a 9B GGUF fetches the right one: from the header when the caller read it, else
- # from the load identity, which a renamed file makes silent.
+ # Pick the encoder per variant so a 9B GGUF fetches the right one: from the header when the caller read it,
+ # else from the load identity, which a renamed file makes silent.
for terepo, tefile, kind in sd_cpp_text_encoders_for(
fam, repo_id, gguf_filename, inner_dim = inner_dim
):
@@ -2008,13 +1951,12 @@ class SdCppDiffusionBackend:
cancel_event: Optional[threading.Event] = None,
local_files_only: bool = False,
) -> dict[str, str]:
- """Download every asset (cancellable via this load's own ``cancel_event``, so
- a replacement load cannot un-cancel this pull), returning kind -> local path.
-
- ``local_files_only`` resolves each asset from the HF cache and never from the network; an
- asset that is not there fails HERE, with the repo and filename named, rather than being
- quietly pulled. This is the last and only network call left on an offline load's path, so
- it is the one that has to honour the flag rather than merely accept it."""
+ """Download every asset (cancellable via this load's own ``cancel_event``, so a replacement
+ load cannot un-cancel this pull), returning kind -> local path. ``local_files_only``
+ resolves each asset from the HF cache and never from the network; an asset that is not
+ there fails HERE, with the repo and filename named, rather than being quietly pulled.
+ This is the last and only network call left on an offline load's path, so it is the one
+ that has to honour the flag rather than merely accept it."""
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
# Callers without a per-load event (tests, direct use) fall back to the current one.
@@ -2033,8 +1975,8 @@ class SdCppDiffusionBackend:
path = str(resolve_local_gguf_child(local_root, fn))
else:
# Resolve an asset cached only under huggingface_hub's import-time root through that root, as the
- # preflight does. Pinned to the live root, a cache-folder change re-downloads every moved asset and 401s
- # on an already-downloaded gated base.
+ # preflight does. Pinned to the live root, a cache-folder change re-downloads every moved asset and
+ # 401s on an already-downloaded gated base.
try:
path = hf_hub_download_with_xet_fallback(
repo,
@@ -2079,11 +2021,10 @@ class SdCppDiffusionBackend:
return _progress("downloading", downloaded, expected, fraction)
def loading_repo_ids(self) -> tuple[str, ...]:
- """Repo ids an in-flight background load is downloading (empty when idle).
- Mirrors the diffusers backend so the delete-cached guard can query whichever
- engine is active without caring which one it got. Includes the companion
- VAE / text-encoder repos: deleting one of those mid-load would remove files
- the committed SdCppModelFiles paths need, and the mirror of each, where those bytes
+ """Repo ids an in-flight background load is downloading (empty when idle). Mirrors the
+ diffusers backend so the delete-cached guard can query whichever engine is active.
+ Includes the companion VAE / text-encoder repos, since deleting one mid-load would remove
+ files the committed SdCppModelFiles paths need, and the mirror of each, where those bytes
land once a gated asset repo is swapped out."""
with self._lock:
loading = self._loading
@@ -2093,14 +2034,12 @@ class SdCppDiffusionBackend:
return _with_mirrors(ids)
def loaded_repo_ids(self) -> tuple[str, ...]:
- """Repo ids the COMMITTED native model reads from disk (empty when unloaded).
-
- The one-shot sd-cli re-reads the companion VAE / text-encoder files from the HF
- cache on every generation (server mode keeps them in the resident process, but the
- extra ids are harmless there), so the delete-cached guard must refuse those
- companion repos while the model is loaded -- status().repo_id covers only the main
- GGUF. Reconstructed from the committed family, mirroring loading_repo_ids(), and
- carrying the mirrors too: one-shot sd-cli re-reads whichever of the pair was fetched."""
+ """Repo ids the COMMITTED native model reads from disk (empty when unloaded). The one-shot
+ sd-cli re-reads the companion VAE / text-encoder files from the HF cache on every
+ generation (server mode keeps them in the resident process, but the extra ids are
+ harmless there), so the delete-cached guard must refuse those companion repos while the
+ model is loaded -- status().repo_id covers only the main GGUF. Reconstructed from the
+ committed family, mirroring loading_repo_ids(), and carrying the mirrors too."""
with self._lock:
state = self._state
if state is None:
@@ -2110,8 +2049,8 @@ class SdCppDiffusionBackend:
if fam.sd_cpp_vae:
repos.append(fam.sd_cpp_vae[0])
# Same per-variant selection as _asset_specs (the header dim this load committed, else repo id AND GGUF
- # filename) so the delete guard protects the encoder repo this load actually downloaded. Read off the state,
- # never re-probed: this runs under _lock.
+ # filename) so the delete guard protects the encoder repo this load actually downloaded. Read off the
+ # state, never re-probed: this runs under _lock.
repos.extend(
terepo
for terepo, _f, _k in sd_cpp_text_encoders_for(
@@ -2123,8 +2062,6 @@ class SdCppDiffusionBackend:
)
return _with_mirrors(repos)
- # ── Generate ───────────────────────────────────────────────────────────
-
def generate(
self,
*,
@@ -2136,8 +2073,8 @@ class SdCppDiffusionBackend:
guidance: float = 0.0,
seed: Optional[int] = None,
batch_size: int = 1,
- # Batched prompt/seed lists are diffusers-engine features; accepted for parity and rejected below, since sd-cli
- # would render them serially.
+ # Batched prompt/seed lists are diffusers-engine features; accepted for parity and rejected below, since
+ # sd-cli would render them serially.
prompts: Optional[list[str]] = None,
seeds: Optional[list[int]] = None,
# Accepted for interface parity; native is text-to-image only, so image-conditioned requests are rejected below.
@@ -2146,8 +2083,8 @@ class SdCppDiffusionBackend:
strength: Optional[float] = None,
upscale: Optional[float] = None, # needs an init image; rejected by the guard below
reference_images: Optional[list[str]] = None, # GPU/diffusers-only (FLUX.2)
- # LoRA (id, weight) pairs; resolved up front then applied per path: prompt tags for one-shot sd-cli, structured
- # `lora` for sd-server.
+ # LoRA (id, weight) pairs; resolved up front then applied per path: prompt tags for one-shot sd-cli,
+ # structured `lora` for sd-server.
loras: Optional[list[tuple[str, float]]] = None,
# ControlNet is diffusers-only; rejected by the guard below (accepted for parity).
controlnet: Optional[tuple[str, str, str, float, float, float]] = None,
@@ -2266,8 +2203,8 @@ class SdCppDiffusionBackend:
cancel = cancel,
)
# Check and deregister under _lock, the lock cancel_generate takes, so the two cannot interleave: a
- # cancel that saw this event registered ran strictly before the check and the run unwinds as cancelled,
- # and one arriving after finds nothing to set and answers false. Same critical section as
+ # cancel that saw this event registered ran strictly before the check and the run unwinds as
+ # cancelled, and one arriving after finds nothing to set and answers false. Same critical section as
# DiffusionBackend.generate; /images/generate/cancel resolves through the engine router, so a native
# host has to give the same answer. The finally repeats the clear for every other exit.
with self._lock:
@@ -2286,8 +2223,8 @@ class SdCppDiffusionBackend:
"gguf_filename": state.gguf_filename,
# The rest of the build the recipe records. The native engine has no dense quant path and no
# memory-mode planner, so those two are honestly null -- but the offload it ran under is real
- # (sd-cli flags) and status() already derives it the same way. Omitting them here persisted null for
- # every native image and left the recipe unable to say how the picture was produced.
+ # (sd-cli flags) and status() already derives it the same way. Omitting them here persisted null
+ # for every native image and left the recipe unable to say how the picture was produced.
"transformer_quant": None,
"text_encoder_quant": None,
"memory_mode": None,
@@ -2323,18 +2260,18 @@ class SdCppDiffusionBackend:
) -> tuple[list, list[int]]:
"""Generate via the resident sd-server (no model reload).
- A batch larger than the server's per-job limit is split into chunks: the server
- rejects a batch_count above _MAX_SERVER_BATCH, and the one-shot path served large
- batches image-by-image, so preserve that. The base seed is masked to sd.cpp's
- signed-int64 range (the request model / diffusers accept larger seeds), and each
- chunk is submitted at base+offset so the per-image seeds stay reproducible. Each
- chunk gets a timeout proportional to its image count so a slow CPU batch is not
- cancelled partway through on one fixed deadline.
-
- LoRA on the server goes through the structured ``lora`` request field, NOT prompt
- tags (the sdcpp API intentionally ignores ``<lora:>`` in the prompt). Selected
- adapters are staged into the server's ``--lora-model-dir`` scratch dir, which the
- server rescans per request, and referenced by their staged filename."""
+ A batch larger than the server's per-job limit is split into chunks: the server rejects a
+ batch_count above _MAX_SERVER_BATCH, and the one-shot path served large batches
+ image-by-image. The base seed is masked to sd.cpp's signed-int64 range (the request model /
+ diffusers accept larger seeds), and each chunk is submitted at base+offset so the per-image
+ seeds stay reproducible. Each chunk gets a timeout proportional to its image count so a slow
+ CPU batch is not cancelled partway through on one fixed deadline.
+
+ LoRA on the server goes through the structured ``lora`` request field, NOT prompt tags (the
+ sdcpp API intentionally ignores ``<lora:>`` in the prompt). Selected adapters are staged
+ into the server's ``--lora-model-dir`` scratch dir, which the server rescans per request,
+ and referenced by their staged filename.
+ """
import io
import os
import shutil
@@ -2349,8 +2286,8 @@ class SdCppDiffusionBackend:
base_seed = int(seed) & ((1 << 63) - 1)
images: list = []
seeds: list[int] = []
- # Stage LoRAs into a per-request subdir of the server lora-model-dir (so a prior request's adapters cannot leak
- # in); removed after.
+ # Stage LoRAs into a per-request subdir of the server lora-model-dir (so a prior request's adapters cannot
+ # leak in); removed after.
lora_payload: Optional[list[dict]] = None
lora_stage: Optional[Path] = None
if lora_resolved:
@@ -2397,8 +2334,8 @@ class SdCppDiffusionBackend:
total_timeout = max(deadline - time.monotonic(), 1.0),
)
except RuntimeError as exc:
- # A ggml unsupported-op abort killed the server: this graph cannot run on the GPU backend at all, so
- # restart the model on the CPU backend once and retry this chunk. Any other death propagates.
+ # A ggml unsupported-op abort killed the server: this graph cannot run on the GPU backend at all,
+ # so restart the model on the CPU backend once and retry this chunk. Any other death propagates.
server = self._restart_server_on_cpu_backend(state, str(exc), cancel)
if server is None:
raise
@@ -2434,17 +2371,15 @@ class SdCppDiffusionBackend:
``GGML_ABORT`` when one is not implemented for that device, because a single-backend graph
has nowhere else to put the node -- there is no per-op CPU fallback. The whole sd-server
dies with SIGABRT mid-generation, so the user sees "the native image renderer stopped
- unexpectedly" with no way forward. Observed on macos-14 arm64 with FLUX.2-klein-4B Q2_K:
- the encoder is already pinned to CPU (see metal_text_encoder_flags), and the abort then
- moves into the denoise loop:
-
- ggml_metal_op_encode_impl: error: unsupported op 'MUL_MAT' -> ggml_abort
- StableDiffusionGGML::sample -> sample_k_diffusion
+ unexpectedly" with no way forward. Observed on macos-14 arm64 with FLUX.2-klein-4B Q2_K: the
+ encoder is already pinned to CPU and the abort then moves into the denoise loop
+ (`unsupported op 'MUL_MAT' -> ggml_abort` under `sample_k_diffusion`).
``--backend cpu`` is the only flag that changes which backend EXECUTES the graph
(``--offload-to-cpu`` moves parameters, not compute), so the restart runs the same
- checkpoint slower rather than not at all. Done once per load: the second abort, or any
- other cause of death, is surfaced to the caller."""
+ checkpoint slower rather than not at all. Done once per load: the second abort, or any other
+ cause of death, is surfaced to the caller.
+ """
if not is_ggml_unsupported_op_abort(error_text):
return None
if self._cpu_backend_forced or state.device == "cpu":
@@ -2469,9 +2404,9 @@ class SdCppDiffusionBackend:
server.start(
state.files,
vae_format = state.vae_format,
- # WITHOUT the device pin. sd.cpp joins repeated --backend values into one spec instead of replacing, and
- # an explicit diffusion=CUDA0 outranks the bare `cpu` default, so leaving the pin on would restart the
- # server onto the very backend that just aborted.
+ # WITHOUT the device pin. sd.cpp joins repeated --backend values into one spec instead of replacing,
+ # and an explicit diffusion=CUDA0 outranks the bare `cpu` default, so leaving the pin on would restart
+ # the server onto the very backend that just aborted.
offload = without_device_backend_flags(state.offload_flags),
native_speed = state.native_speed,
threads = state.threads,
@@ -2502,12 +2437,11 @@ class SdCppDiffusionBackend:
lora_resolved: list,
cancel: threading.Event,
) -> tuple[list, list[int]]:
- """Fallback path: re-run one-shot sd-cli per image (reloads the model each time).
-
- LoRA on the one-shot path uses sd-cli's own mechanism: materialize the selected
- adapters into a ``--lora-model-dir`` and inject matching ``<lora:ALIAS:w>`` tags
- into the prompt (sd-cli parses and strips them). supports_lora already gated the
- family upstream, so a non-empty ``lora_resolved`` is safe to apply here."""
+ """Fallback path: re-run one-shot sd-cli per image (reloads the model each time). LoRA on
+ the one-shot path uses sd-cli's own mechanism: materialize the selected adapters into a
+ ``--lora-model-dir`` and inject matching ``<lora:ALIAS:w>`` tags into the prompt (sd-cli
+ parses and strips them). supports_lora already gated the family upstream, so a non-empty
+ ``lora_resolved`` is safe to apply here."""
import tempfile
from PIL import Image
@@ -2554,20 +2488,20 @@ class SdCppDiffusionBackend:
lora_dir = lora_dir,
lora_apply_mode = "auto" if lora_dir else None,
)
- # Each sd-cli run executes out of the managed tree, so hold installs off for its duration (and wait here
- # if one is already extracting). getattr: an INJECTED engine is the unit-test seam / escape hatch and
- # need not name a file at all, and nothing without a path is a binary an install replaces.
+ # Each sd-cli run executes out of the managed tree, so hold installs off for its duration (and wait
+ # here if one is already extracting). getattr: an INJECTED engine is the unit-test seam / escape hatch
+ # and need not name a file at all, and nothing without a path is a binary an install replaces.
with _tree_reader(getattr(engine, "binary", None), cancel):
# Re-resolve INSIDE the claim. An install that finished while this image was waiting can have put
# its sd-cli somewhere else and swept the copy resolved above, so the cached path would launch a
- # file that is no longer there. Also covers a batch, which releases the claim between images. Cheap
- # when nothing moved: _resolve_engine returns the cached engine whose binary still exists.
+ # file that is no longer there. Also covers a batch, which releases the claim between images.
+ # Cheap when nothing moved.
engine = self._resolve_engine()
# Existence is not identity here either. The install that moved the CLI may have been for a
# different accelerator (an H3 load putting the CPU fallback in, say), and this state's device and
- # offload policy were chosen for the other one, so running it would either spend unaccounted VRAM or
- # drop the whole generation onto the CPU while the arbiter's accounting says otherwise. The server
- # path refuses exactly this mismatch before it starts; refusing here costs a reload, which
+ # offload policy were chosen for the other one, so running it would either spend unaccounted VRAM
+ # or drop the whole generation onto the CPU while the arbiter's accounting says otherwise. The
+ # server path refuses exactly this mismatch before it starts; refusing here costs a reload, which
# re-resolves device, accelerator and install together.
if (
_installed_accelerator_of(getattr(engine, "binary", None))
@@ -2625,11 +2559,10 @@ class SdCppDiffusionBackend:
}
def cancel_generate(self) -> bool:
- """Signal the in-flight generation to stop, matching DiffusionBackend.cancel_generate.
-
- The native engine is stricter than best-effort: the runner polls this event and kills
- the sd-cli process tree, so the stop lands within the poll interval rather than at the
- next step boundary. Returns False when nothing is running."""
+ """Signal the in-flight generation to stop, matching DiffusionBackend.cancel_generate. The
+ native engine is stricter than best-effort: the runner polls this event and kills the
+ sd-cli process tree, so the stop lands within the poll interval rather than at the next
+ step boundary. Returns False when nothing is running."""
with self._lock:
cancel = self._active_generate_cancel
if cancel is None:
@@ -2637,12 +2570,10 @@ class SdCppDiffusionBackend:
cancel.set()
return True
- # ── Unload / status ──────────────────────────────────────────────────────
-
def unload(self) -> dict[str, Any]:
with self._lock:
- # Under the lock: begin_load rebinds this attribute, so an unlocked read could set an event the current load
- # no longer watches.
+ # Under the lock: begin_load rebinds this attribute, so an unlocked read could set an event the current
+ # load no longer watches.
self._cancel_event.set()
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()
@@ -2653,8 +2584,8 @@ class SdCppDiffusionBackend:
# Grab a mid-start() uncommitted server too so we can stop it (startup is abortable).
pending = self._pending_server
self._pending_server = None
- # Reserved HERE, not at the stop below: the fields are already empty by then, and a router probe landing in
- # that gap would read an idle tree and reinstall over a process that is still running.
+ # Reserved HERE, not at the stop below: the fields are already empty by then, and a router probe landing
+ # in that gap would read an idle tree and reinstall over a process that is still running.
to_stop = [
srv
for srv in (state.server if state is not None else None, pending)
@@ -2663,20 +2594,20 @@ class SdCppDiffusionBackend:
if pending is not None and state is not None and pending is state.server:
to_stop = to_stop[:1]
self._reserve_stop(len(to_stop))
- # Stop the resident server outside the lock (terminate can take seconds); a mid-flight generation unwinds as the
- # process goes away.
+ # Stop the resident server outside the lock (terminate can take seconds); a mid-flight generation unwinds as
+ # the process goes away.
for srv in to_stop:
self._stop_reserved(srv)
- # Barrier: wait for a signalled one-shot generation to exit before reporting unloaded, since callers treat this
- # return as "device is free".
+ # Barrier: wait for a signalled one-shot generation to exit before reporting unloaded, since callers treat
+ # this return as "device is free".
with self._generate_lock:
pass
return self.status()
def status(self) -> dict[str, Any]:
state = self._state
- # A resident sd-server can exit after load (OOM/crash while idle); drop stale state so clients reload instead of
- # 500ing per generation.
+ # A resident sd-server can exit after load (OOM/crash while idle); drop stale state so clients reload instead
+ # of 500ing per generation.
if (
state is not None
and state.mode == "server"
diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.py
index 15dbdbf3055..b18ab6cb1a8 100644
--- a/studio/backend/core/inference/sd_cpp_engine.py
+++ b/studio/backend/core/inference/sd_cpp_engine.py
@@ -61,11 +61,10 @@ _SERVER_STEM = "sd-server"
# before they delete a tree
OWNER_MARKER = ".unsloth-studio-owned"
-# the native engine exists FOR slow CPU hosts
-# Ceiling for one native run. The native engine exists FOR slow CPU hosts: on GPU-less CI runners a 512x512 4-step Q2_K
-# generation took 900 s on Linux and 1465 s on Windows, so a 30-minute cap killed jobs that were still progressing. It
-# matches the Images page's own SETTLE_MAX_MS (6 h), so it only stops a WEDGED process from holding the lock forever;
-# cancel_event is the user-facing abort.
+# Ceiling for one native run. The native engine exists FOR slow CPU hosts: on GPU-less CI runners a 512x512 4-step
+# Q2_K generation took 900 s on Linux and 1465 s on Windows, so a 30-minute cap killed jobs that were still
+# progressing. It matches the Images page's own SETTLE_MAX_MS (6 h), so it only stops a WEDGED process from holding
+# the lock forever; cancel_event is the user-facing abort.
NATIVE_GENERATION_TIMEOUT_S = 6 * 60 * 60.0
_PRIVATE_TEXT_OPTIONS = frozenset({"--prompt", "--negative-prompt", "-p", "-n"})
@@ -155,7 +154,6 @@ def _sd_cpp_command_summary(cmd: list[str], *, default_mode: str = "img_gen") ->
# <speed>\033[K", with a trailing newline only on the final step of a phase. So the carriage return LEADS the record and
# the erase-to-end-of-line CLOSES it.
_ANSI_ERASE = "\x1b[K"
-# stripped before a record reaches on_log / the error tail: an escape mid-line corrupts both
# Any CSI escape (the erase above, plus colour runs some builds emit), stripped before a record reaches on_log / the
# error tail: an escape in the middle of a line corrupts both.
_ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
@@ -324,21 +322,19 @@ def _first_file(paths: list[Path]) -> Optional[str]:
return None
-# keyed by the file itself rather than the path alone
-# Identity verdicts, keyed by the file itself rather than by the path alone, so replacing a binary in place re-probes it
-# while a rebuild elsewhere on PATH is unaffected. Bounded: an Unsloth session sees a handful of candidates, and a
-# runaway key set would only ever come from a path being rewritten under us, which is exactly the case that must not be
+# Identity verdicts, keyed by the file itself rather than by the path alone, so replacing a binary in place re-probes
+# it while a rebuild elsewhere on PATH is unaffected. Bounded: an Unsloth session sees a handful of candidates, and a
+# runaway key set would only come from a path being rewritten under us, which is exactly the case that must not be
# served from here.
_IDENTITY_MEMO: dict[tuple[str, int, int, int], tuple[bool, float]] = {}
_IDENTITY_MEMO_LOCK = threading.Lock()
_IDENTITY_MEMO_MAX = 32
-# no stat tuple is a content hash: on Windows `st_ctime` is the CREATION time
# How long a verdict may answer for. The key catches the replacements it can SEE, but no stat tuple is a content hash:
# on Windows ``st_ctime`` is the CREATION time, which an in-place overwrite preserves, so a same-sized write that also
-# restores mtime is invisible to it. Hashing the file on every lookup would trade the exec this memo exists to avoid for
-# a read of the whole binary, on a path walked for every load. A short life is the cheaper guarantee and it is not
-# platform-specific: whatever the key misses, and whatever nobody has thought of, expires within a minute. Long enough
-# for its actual job, which is the several resolutions inside one load sequence.
+# restores mtime is invisible to it. Hashing the file on every lookup would trade the exec this memo exists to avoid
+# for a read of the whole binary, on a path walked for every load. A short life is the cheaper guarantee and it is not
+# platform-specific: whatever the key misses expires within a minute, which is long enough for the several resolutions
+# inside one load sequence.
_IDENTITY_MEMO_TTL_S = 60.0
@@ -381,21 +377,16 @@ def sd_cpp_binary_identifies(binary: str) -> bool:
"""``help_text_identifies_sd_cpp`` against a live ``binary``.
Fails CLOSED: every caller is deciding whether to trust an ambiguously named executable, and a
- probe that cannot be read is no evidence that it is the one we want. Memoized per file
- revision -- discovery runs on every load and ``ensure_sd_cpp_binary`` alone resolves twice, so
- without this a candidate that hangs costs its full timeout again on each one.
+ probe that cannot be read is no evidence that it is the one we want. Memoized per file revision,
+ since discovery runs on every load and ``ensure_sd_cpp_binary`` alone resolves twice.
- Only a DECISIVE verdict is memoized, because the key cannot see the difference. A timeout, a
+ Only a DECISIVE verdict is memoized, because the key cannot see the difference: a timeout, a
failed spawn, or a non-zero exit with nothing identifying in the output are all "could not
- tell", and none of them touches the file, so its key is unchanged -- caching that "no" would
- blacklist a genuine build for the life of the process over one slow ``--help`` under memory
- pressure, or over a missing shared library the user then installs. Same rule as
- ``utils.node_runtime``, which memoizes only an adequate result so a runtime installed after the
- first probe is still picked up.
-
- A clean exit that simply is not stable-diffusion.cpp IS decisive, which is the case that
- matters: Debian/Ubuntu's ``sd`` answers ``--help`` with rc 0, so the candidate this exists to
- stop re-executing is still probed exactly once.
+ tell", and none of them touches the file, so caching that "no" would blacklist a genuine build
+ for the life of the process over one slow ``--help`` or a missing shared library the user then
+ installs. Same rule as ``utils.node_runtime``. A clean exit that simply is not
+ stable-diffusion.cpp IS decisive, which is the case that matters: Debian/Ubuntu's ``sd`` answers
+ ``--help`` with rc 0.
"""
key = _identity_key(binary)
if key is not None:
@@ -492,22 +483,19 @@ def _studio_component_root(name: str) -> Path:
def legacy_sibling_install_root() -> Optional[Path]:
"""The pre-fix managed root, ``<studio home>/../stable-diffusion.cpp``, or None.
- Older builds derived the sd.cpp root from the *parent* of the Unsloth home, which put the tree
+ Older builds derived the sd.cpp root from the PARENT of the Unsloth home, which put the tree
outside the Unsloth home entirely. Two problems: a relative ``UNSLOTH_STUDIO_HOME`` collapsed
that parent to the working directory, so an unrelated ``stable-diffusion.cpp`` checkout sitting
- there became "the managed install" and the installer refused to run; and it disagreed with
- every other component, which install under the home.
-
- Kept only so a tree an older build really did install still resolves. Returned solely when it
- carries the ownership marker, so a checkout that merely happens to sit next to the Unsloth home
- is never adopted.
-
- The LEXICAL parent first, because that is the one the old code took: ``Path(home).parent`` does
- not resolve symlinks, so for a home under a symlinked directory the tree an older build really
- created sits next to the link, not next to its target. Resolving first looked in the wrong
- place, re-downloaded the bundle and left the old install orphaned from uninstall as well. The
- resolved parent is still tried after it, for a home reached through a link the other way
- around."""
+ there became "the managed install" and the installer refused to run; and it disagreed with every
+ other component, which install under the home.
+
+ Kept only so a tree an older build really did install still resolves, and returned solely when
+ it carries the ownership marker. The LEXICAL parent first, because that is the one the old code
+ took: ``Path(home).parent`` does not resolve symlinks, so for a home under a symlinked directory
+ the tree an older build created sits next to the link, not next to its target, and resolving
+ first looked in the wrong place and re-downloaded the bundle. The resolved parent is still tried
+ after it.
+ """
home = (os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()
if not home:
return None
@@ -607,7 +595,6 @@ def _find_binary(
if hit:
return hit
- # default install root honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the installer
# 3. Default install root: <studio home>/stable-diffusion.cpp (honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the
# installer so side-by-side Unsloth instances stay isolated), else ~/.unsloth/....
default_root = managed_install_root()
@@ -615,7 +602,6 @@ def _find_binary(
if hit:
return hit
- # a tree an older build installed beside the Unsloth home
# 3b. A tree an older build installed beside the Unsloth home. Marker-gated (see legacy_sibling_install_root), so
# only a real previous install is picked up here.
legacy_root = legacy_sibling_install_root()
@@ -804,8 +790,6 @@ class SdCppEngine:
cancel_event = cancel_event,
)
- # ── internals ─────────────────────────────────────────────────────────────
-
def _require_binary(self) -> str:
if not self.is_available():
raise RuntimeError(
@@ -944,8 +928,6 @@ class SdCppEngine:
return out
-# ── engine routing ──────────────────────────────────────────────────────────
-
ENGINE_DIFFUSERS = "diffusers"
ENGINE_SD_CPP = "sd_cpp"
diff --git a/studio/backend/core/inference/sd_cpp_server.py b/studio/backend/core/inference/sd_cpp_server.py
index 7c1f34dd671..b32623f3d80 100644
--- a/studio/backend/core/inference/sd_cpp_server.py
+++ b/studio/backend/core/inference/sd_cpp_server.py
@@ -74,7 +74,6 @@ _TRANSPORT_ERRORS = (
httpx.WriteError,
)
-# the port binds only after the model loads, so any 200 means ready
# Readiness probe: the port binds only after the model loads, so any 200 means ready. Use trivial /v1/models, not the
# capabilities endpoint (which can block).
_READY_PATH = "/v1/models"
@@ -514,8 +513,6 @@ class SdCppServer:
self._stdout_thread.join(timeout = 2)
self._stdout_thread = None
- # ── generation ───────────────────────────────────────────────────────────
-
def img_gen(
self,
payload: dict[str, Any],
diff --git a/studio/backend/core/inference/search_images.py b/studio/backend/core/inference/search_images.py
index 242baae2948..a8030881469 100644
--- a/studio/backend/core/inference/search_images.py
+++ b/studio/backend/core/inference/search_images.py
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-# a registry keyed by opaque ids plus a thumbnail proxy
# web_search image results: a registry keyed by opaque ids plus a thumbnail proxy, so neither the model nor the browser
# sees an image URL.
@@ -41,25 +40,22 @@ _MAX_CONCURRENT_FETCHES = 4
_registry: dict[str, dict[str, Any]] = {}
_registry_lock = threading.Lock()
-# a fetch that started before a clear must not publish its thumbnail after it
# Bumped by clear_cache. A fetch that started before the clear must not publish its thumbnail after it: the write is
# done under _registry_lock and skipped if this moved.
_cache_generation = 0
-# The generation of the last CLEAR-EVERYTHING, plus the generation each individually reaped id was taken at. The
-# generation at which a CLEAR-EVERYTHING last ran, and the generation at which each individually reaped id was taken. A
-# selective clear must not abort an in-flight fetch for an id it spared: thumbnail_bytes would answer None, the endpoint
-# 404s, and SearchImageThumb renders nothing and never retries -- its effect depends only on (id, nearViewport), so
-# "re-fetches on the next request" is not true, there is no next request. Bounded; on overflow the per-id record is
-# dropped and the full-clear generation is moved instead, which over-aborts rather than republishing a thumbnail a clear
-# removed.
+# The generation at which a CLEAR-EVERYTHING last ran, plus the generation at which each individually reaped id was
+# taken. A selective clear must not abort an in-flight fetch for an id it spared: thumbnail_bytes would answer None,
+# the endpoint 404s, and SearchImageThumb renders nothing and never retries -- its effect depends only on (id,
+# nearViewport), so "re-fetches on the next request" is not true, there is no next request. Bounded; on overflow the
+# per-id record is dropped and the full-clear generation is moved instead, which over-aborts rather than republishing
+# a thumbnail a clear removed.
_full_clear_generation = 0
_reaped_at: dict[str, int] = {}
_REAPED_AT_MAX = 4096
-# a fetch started at or after this is still answered exactly
-# The newest generation whose per-id records have been dropped to stay under that cap. A fetch that started at or after
-# this is still answered exactly, because nothing covering it was dropped; only one older than every record we still
-# hold has to be given up on. Fetches are bounded by THUMBNAIL_FETCH_TIMEOUT_S, so outliving 4096 reaped images is not a
-# real case.
+# The newest generation whose per-id records have been dropped to stay under that cap. A fetch that started at or
+# after this is still answered exactly, because nothing covering it was dropped; only one older than every record we
+# still hold has to be given up on. Fetches are bounded by THUMBNAIL_FETCH_TIMEOUT_S, so outliving 4096 reaped images
+# is not a real case.
_reaped_floor_generation = 0
# Ids whose files a clear could not unlink -- on Windows another process holding the JPEG open is enough. The
# cache-first read and the sidecar read both go around the registry, so without this they would go on serving a picture
@@ -157,7 +153,6 @@ def register_images(
"thumbnail": thumbnail,
"source": source,
"created": now,
- # the proxy fetch happens on a later request
# Kept with the entry: the proxy fetch happens on a later request, and without it every redirect hop
# would be re-checked against no policy.
"policy": website_policy,
diff --git a/studio/backend/core/inference/stream_errors.py b/studio/backend/core/inference/stream_errors.py
index b8a662dad88..efa55b0a046 100644
--- a/studio/backend/core/inference/stream_errors.py
+++ b/studio/backend/core/inference/stream_errors.py
@@ -26,17 +26,16 @@ the problem.
from typing import Any, Optional
-# Starvation: concurrent generations drew on the same unified cache Two different failures share the word "context" and
-# need different advice. Starvation: the decode could not find KV space because concurrent generations drew on the same
-# unified cache. Nothing about this request was too big, so telling the user to shorten it is wrong. Matched on a
-# substring because the server appends punctuation and, on some paths, batch details.
+# Two different failures share the word "context" and need different advice. Starvation: the decode could not find KV
+# space because concurrent generations drew on the same unified cache. Nothing about this request was too big, so
+# telling the user to shorten it is wrong. Matched on a substring because the server appends punctuation and, on some
+# paths, batch details.
_STARVATION_MARKERS = (
"context size has been exceeded",
"failed to find free space in the kv cache",
"failed to find a memory slot",
)
-# oversize: the server's precise text (both token counts) is kept verbatim, only the remedy is added
# Oversize: the request alone did not fit, and the server says so precisely, including both token counts. That text is
# kept verbatim; only the remedy is added.
_OVERSIZE_MARKERS = (
@@ -88,9 +87,9 @@ class LlamaStreamError(RuntimeError):
kv_starvation: bool = False,
context_oversize: bool = False,
):
- # keep the server's own text so _friendly_error's token-count regex still rewrites an oversize refusal
- # str(exc) stays the server's own text where there is one, so the existing token-count regex in _friendly_error
- # still matches an oversize refusal and rewrites it into the established "Message too long" wording.
+ # str(exc) stays the server's own text where there is one, so the existing token-count regex in
+ # _friendly_error still matches an oversize refusal and rewrites it into the established "Message too long"
+ # wording.
super().__init__(server_message or friendly)
self.friendly = friendly
self.server_message = server_message
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index 5f84dcb4de5..9432d9de395 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -80,8 +80,6 @@ from utils.process_lifetime import (
logger = get_logger(__name__)
-# one repo per model; keys match the Transformers sidecar's ids so the frontend reuses one picker, values are the single
-# file inside each repo
# Curated GGML checkpoints, one repo per model. Keys match the Transformers sidecar's ids so the frontend reuses one
# picker; values are the single file inside each repo.
GGML_STT_REPOS: dict[str, str] = {
@@ -151,14 +149,9 @@ def _managed_whisper_cpp_dir() -> Path:
def find_whisper_server_binary() -> Optional[str]:
- """Locate the whisper-server binary.
-
- Search order:
- 1. WHISPER_SERVER_PATH environment variable (direct path to binary)
- 2. UNSLOTH_WHISPER_CPP_PATH env var (custom whisper.cpp install dir)
- 3. managed dir: <STUDIO_HOME or ~/.unsloth>/whisper.cpp/{,build/bin/}whisper-server
- 4. whisper-server on PATH
- """
+ """Locate the whisper-server binary, in order: WHISPER_SERVER_PATH (direct path),
+ UNSLOTH_WHISPER_CPP_PATH (custom install dir), the managed dir <STUDIO_HOME or
+ ~/.unsloth>/whisper.cpp/{,build/bin/}whisper-server, then whisper-server on PATH."""
binary_name = "whisper-server.exe" if sys.platform == "win32" else "whisper-server"
def _layout_candidates(d: Path) -> list[Path]:
@@ -278,7 +271,6 @@ def slim_runtime_intact(binary: str) -> bool:
return intact
-# a runtime that starts, answers GET /, then dies on the first inference
# A runtime that starts, answers GET /, and then dies on the first actual inference. Reported on Windows with ROCm on
# gfx1200, where rocBLAS is missing its TensileLibrary: the marker and the linked libraries are all present, so
# slim_runtime_intact() is happy and is_available() said yes, which meant _resolve_serving_stt_engine never fell back
@@ -342,18 +334,13 @@ def ensure_engine_available() -> str:
return binary
-# build the whisper-server env: prepend the binary dir (co-located libs win, and a backstop where the loader ignores the
-# rpath)
-
-# --------------------------------------------------------------------------- whisper-server child-process environment
-# --------------------------------------------------------------------------- Build the whisper-server env: prepend the
-# binary dir (co-located libs win, and a backstop where the loader ignores the rpath) and scrub secret-bearing vars the
-# binary never needs. On WSL2 ROCm the system HIP libs go first, since a bundle's bare-metal HIP cannot drive /dev/dxg.
-# A CUDA bundle ships libggml-cuda.so but not libcudart/libcublas (paired with the user's PyTorch), so add the
-# CUDA-from-PyTorch runtime dirs the selection gated on, else the backend cannot resolve a runtime that lives only in
-# wheels. Mirrors llama's binary_env(); the scrub/WSL/dedupe helpers live in utils.prebuilt.
-# Module-level aliases keep the historical patch points for tests and callers.
-# ---------------------------------------------------------------------------
+# whisper-server child-process environment. Build the env by prepending the binary dir (co-located libs win, and a
+# backstop where the loader ignores the rpath) and scrubbing secret-bearing vars the binary never needs. On WSL2 ROCm
+# the system HIP libs go first, since a bundle's bare-metal HIP cannot drive /dev/dxg. A CUDA bundle ships
+# libggml-cuda.so but not libcudart/libcublas (paired with the user's PyTorch), so add the CUDA-from-PyTorch runtime
+# dirs the selection gated on, else the backend cannot resolve a runtime that lives only in wheels. Mirrors llama's
+# binary_env(); the scrub/WSL/dedupe helpers live in utils.prebuilt, and the module-level aliases keep the historical
+# patch points for tests and callers.
_wsl_system_rocm_lib_dirs = wsl_system_rocm_lib_dirs
_dedupe_existing_dirs = dedupe_existing_dirs
@@ -397,9 +384,7 @@ def _whisper_server_child_env(binary: str) -> dict[str, str]:
return env
-# --------------------------------------------------------------------------- Model file download (single files;
-# deliberately outside the Model Hub flow) ---------------------------------------------------------------------------
-# ---------------------------------------------------------------------------
+# Model file download: single files, deliberately outside the Model Hub flow.
def _cached_model_path(
@@ -469,7 +454,6 @@ class _GgmlDownloadState:
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
- # "model" goes None once the worker thread stops
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
# cancellation was indistinguishable from an unrelated one and a deferred load restarted the whole
# download.
@@ -691,9 +675,6 @@ def cancel_model_download() -> bool:
return _download_state.cancel()
-# ---------------------------------------------------------------------------
-
-
def _pcm_to_wav_bytes(decoded_audio) -> bytes:
"""Wrap decoded float32 mono 16 kHz PCM into an in-memory 16-bit WAV."""
import numpy as np
@@ -709,9 +690,6 @@ def _pcm_to_wav_bytes(decoded_audio) -> bytes:
return buf.getvalue()
-# ---------------------------------------------------------------------------
-
-
class GgmlSttSidecar:
"""Owns one whisper-server subprocess and proxies dictation to it."""
@@ -740,9 +718,8 @@ class GgmlSttSidecar:
@property
def loaded_model(self) -> Optional[str]:
- # lock-free status read: transcribe() holds self._lock for the whole inference call
- # Lock-free status read (like stt_sidecar.py): transcribe() holds self._lock for the whole inference call (up to
- # _TRANSCRIBE_TIMEOUT_SECONDS), and status polls plus training admission must not block behind it.
+ # Lock-free status read (like stt_sidecar.py): transcribe() holds self._lock for the whole inference call (up
+ # to _TRANSCRIBE_TIMEOUT_SECONDS), and status polls plus training admission must not block behind it.
# _process_alive() snapshots self._process before poll(), which subprocess guards with _waitpid_lock, so a
# concurrent unload is safe.
return self._model_id if self._process_alive() else None
@@ -765,8 +742,6 @@ class GgmlSttSidecar:
process = self._process
return process is not None and process.poll() is None
- # -- idle unload ------------------------------------------------------
-
def _cancel_idle_unload_locked(self) -> None:
self._idle_generation += 1
if self._idle_timer is not None:
@@ -790,8 +765,6 @@ class GgmlSttSidecar:
logger.info("Unloading idle GGUF STT model %s", self._model_id)
self._release_locked()
- # -- process lifecycle -------------------------------------------------
-
def _release_locked(self) -> None:
self._cancel_idle_unload_locked()
process = self._process
@@ -1103,8 +1076,6 @@ class GgmlSttSidecar:
return False
return b"whisper" in body.lower()
- # -- transcription ------------------------------------------------------
-
def transcribe(
self,
audio: bytes,
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 78e98091035..7b98c4645ec 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -99,10 +99,9 @@ MTMD_STT_MODELS: dict[str, MtmdSttModel] = {
# complies. Parakeet and Nemotron ASR are too: llama.cpp has the audio graphs but not the text architectures.
_TRANSCRIBE_PROMPT = "Transcribe the audio."
-# Speech runs about 3 tokens a second in English and more in scripts with no word boundaries Output cap per second of
-# audio. Speech runs about 3 tokens a second in English and more in scripts with no word boundaries, so this is
-# generous: generation stops at EOS long before it, and the cap only exists so a looping model cannot run to the request
-# timeout.
+# Output cap per second of audio. Speech runs about 3 tokens a second in English and more in scripts with no word
+# boundaries, so this is generous: generation stops at EOS long before it, and the cap only exists so a looping model
+# cannot run to the request timeout.
_TRANSCRIPT_TOKENS_PER_SECOND = 30
_MIN_TRANSCRIPT_TOKENS = 512
# Well under any of these models' trained context, which also has to hold the audio. llama-server is left on its default
@@ -334,7 +333,6 @@ class _MtmdDownloadState:
"model": model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
- # "model" goes None once the worker thread stops
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
# cancellation was indistinguishable from an unrelated one and a deferred load restarted the whole
# download.
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index 39618cb005c..e3559ab8717 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -60,11 +60,10 @@ def load(
"""
others = [name for name in STT_ENGINES if name != engine]
with _load_lock:
- # release other engines only once the checkpoint is on disk
- # Release the other engines BEFORE allocating, but only once the checkpoint is known to be on disk. Holding two
- # engines across the load is what makes a switch OOM on a device that fits either alone; releasing blind would
- # let a 409 for a model that was never downloaded cost the user the engine they were already using. When the
- # answer is not certain, keep the old order and accept the peak.
+ # Release the other engines BEFORE allocating, but only once the checkpoint is known to be on disk. Holding
+ # two engines across the load is what makes a switch OOM on a device that fits either alone; releasing blind
+ # would let a 409 for a model that was never downloaded cost the user the engine they were already using. When
+ # the answer is not certain, keep the old order and accept the peak.
if _model_is_downloaded(engine, model):
unload(others, wait = False)
sidecar_for(engine).load(
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index 53930dfff4c..e3acfbfa17f 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -1,20 +1,17 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Standalone speech-to-text (STT) sidecar for dictation.
-
-Loads a Whisper model (via Transformers) in a spawn child of its own, separate
-from the chat model's inference subprocess, so dictation works with any chat
-model without evicting it. Curated defaults plus any Transformers-compatible
-Whisper repo; weights come through Unsloth's Model Hub and stay warm briefly
-between dictations. CUDA runs float16; MPS and CPU run float32.
-
-Everything except the model itself stays here: device choice, the Hub cache,
-audio decoding, windowing and the idle timer. Only the load and the generate
-happen in core/inference/stt_transformers_worker.py, because an accelerator
-context is never returned while the process holding it lives and the backend
-must not be the process that takes one.
+"""Standalone speech-to-text (STT) sidecar for dictation.
+
+Loads a Whisper model (via Transformers) in a spawn child of its own, separate from the chat model's
+inference subprocess, so dictation works with any chat model without evicting it. Curated defaults
+plus any Transformers-compatible Whisper repo; weights come through Unsloth's Model Hub and stay
+warm briefly between dictations. CUDA runs float16; MPS and CPU run float32.
+
+Everything except the model itself stays here: device choice, the Hub cache, audio decoding,
+windowing and the idle timer. Only the load and the generate happen in
+core/inference/stt_transformers_worker.py, because an accelerator context is never returned while
+the process holding it lives and the backend must not be the process that takes one.
"""
from __future__ import annotations
@@ -40,9 +37,8 @@ from loggers import get_logger
logger = get_logger(__name__)
-# stable API/UI id -> Hub repository; a request may instead pass a validated `owner/model` id
-# Multilingual Whisper defaults: stable API/UI id -> Hub repository. A request may instead pass a validated Hugging Face
-# `owner/model` id.
+# Multilingual Whisper defaults: stable API/UI id -> Hub repository. A request may instead pass a validated Hugging
+# Face `owner/model` id.
STT_MODELS: dict[str, str] = {
"tiny": "unsloth/whisper-tiny",
"base": "unsloth/whisper-base",
@@ -255,7 +251,6 @@ _WHISPER_LANGUAGE_ALIASES = {
def normalize_whisper_language(language: Optional[str]) -> Optional[str]:
- """Convert a BCP-47 locale into the short code Whisper expects."""
if not language:
return None
normalized = language.strip().replace("_", "-").lower()
@@ -275,7 +270,6 @@ def _known_whisper_languages() -> Optional[frozenset[str]]:
def ensure_stt_available() -> None:
- """Raise when the complete local Whisper backend cannot be imported."""
try:
import av # noqa: F401
import torch # noqa: F401
@@ -288,7 +282,6 @@ def ensure_stt_available() -> None:
def is_available() -> bool:
- """True when the complete local Whisper backend can be imported."""
try:
ensure_stt_available()
except SttUnavailableError:
@@ -312,7 +305,6 @@ def resolve_model_id(model: Optional[str]) -> str:
def resolve_model_repo(model_id: str) -> str:
- """Return the Hub repository for a curated or custom model id."""
resolved = resolve_model_id(model_id)
return STT_MODELS.get(resolved, resolved)
@@ -545,10 +537,9 @@ def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
shards = set(weight_map.values())
if not all(isinstance(shard, str) and shard in siblings for shard in shards):
raise SttModelCompatibilityError(f"Checkpoint index '{index_name}' has missing shards.")
- # The index JSON is attacker-controlled and a safetensors index can name.bin shards The index JSON is
- # attacker-controlled: a safetensors index can name pytorch_model-*.bin shards, which Transformers still loads
- # through torch.load (pickle) since it dispatches per shard by file extension. Require every shard to be
- # safetensors so no pickle file is selected.
+ # The index JSON is attacker-controlled: a safetensors index can name pytorch_model-*.bin shards, which
+ # Transformers still loads through torch.load (pickle) since it dispatches per shard by file extension.
+ # Require every shard to be safetensors so no pickle file is selected.
if not all(shard.endswith(".safetensors") for shard in shards):
raise SttModelCompatibilityError(
f"Checkpoint index '{index_name}' references non-safetensors shards."
@@ -588,8 +579,6 @@ def validate_remote_model(model: Optional[str], hf_token: Optional[str] = None)
raise SttModelCompatibilityError(
f"Could not resolve an immutable revision for STT model '{model_id}'."
)
- # the download pins to the validated commit so the repo cannot be swapped between validation and snapshot_download
- # (TOCTOU)
# The commit that was validated; the download pins to it so the repo cannot be swapped between validation and
# snapshot_download (TOCTOU).
return {"model": model_id, "repo": repo, "revision": revision}
@@ -623,7 +612,6 @@ def _snapshot_is_complete(snapshot: Path) -> bool:
# repo shipping only pickle weights re-resolves and fails closed in _select_snapshot_files).
index = snapshot / _STT_SAFETENSORS_INDEX
if index.is_file():
- # every shard must exist and be safetensors, since a safe index naming .bin shards would still pickle-load them
# Sharded safetensors checkpoint: every shard must exist and be safetensors (a safe index naming .bin shards
# would still pickle-load them, matching the _select_snapshot_files guard).
weight_map = _read_json_object(index).get("weight_map")
@@ -635,7 +623,6 @@ def _snapshot_is_complete(snapshot: Path) -> bool:
has_weights = all((snapshot / shard).is_file() for shard in shards)
else:
has_weights = (snapshot / _STT_SAFETENSORS_WEIGHTS).is_file()
- # WhisperProcessor needs either the fast tokenizer.json or the slow vocab.json + merges.txt pair
# WhisperProcessor needs the tokenizer: either the fast tokenizer.json or the slow vocab.json + merges.txt pair.
has_tokenizer = (snapshot / "tokenizer.json").is_file() or (
(snapshot / "vocab.json").is_file() and (snapshot / "merges.txt").is_file()
@@ -649,7 +636,6 @@ def _snapshot_is_complete(snapshot: Path) -> bool:
def is_model_downloaded(model: Optional[str]) -> bool:
- """True when a usable Whisper snapshot exists in the local HF cache."""
try:
return _find_complete_cached_snapshot(model) is not None
except Exception:
@@ -686,7 +672,6 @@ class _SnapshotDownloadState:
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
- # "model" goes None once the worker thread stops
# Which model the cancel applies to. "model" goes None once the worker thread stops, so a settled
# cancellation was indistinguishable from an unrelated one and a deferred load restarted the whole
# download.
@@ -1044,17 +1029,15 @@ def _engine_survived_kill(engine) -> bool:
def _close_engine(engine) -> bool:
"""End the worker behind an engine handle, if it has one.
- Ending the worker is what returns its accelerator context; dropping the
- handle and emptying the cache cannot. A plain object (tests, or a future
- in-process engine) has no close and needs none.
-
- False when the engine says so itself, which WhisperWorker does for a child
- that outlived terminate and kill and is therefore still holding the memory
- this call was made to release, and False when close() raises out of a
- process operation: nothing was confirmed dead, so the handle has to be kept
- rather than the memory advertised as free. A close that raised over a child
- already gone still counts as released, so bookkeeping that failed after the
- death cannot wedge every later load.
+ Ending the worker is what returns its accelerator context; dropping the handle and emptying the
+ cache cannot. A plain object (tests, or a future in-process engine) has no close and needs none.
+
+ False when the engine says so itself, which WhisperWorker does for a child that outlived
+ terminate and kill and is therefore still holding the memory this call was made to release, and
+ False when close() raises out of a process operation: nothing was confirmed dead, so the handle
+ has to be kept rather than the memory advertised as free. A close that raised over a child
+ already gone still counts as released, so bookkeeping that failed after the death cannot wedge
+ every later load.
"""
close = getattr(engine, "close", None)
if close is None:
@@ -1180,7 +1163,6 @@ class WhisperSttSidecar:
@property
def device(self) -> Optional[str]:
- # torch's ROCm build keeps the "cuda" device name for HIP
# Reported, so name the backend a user recognises. Torch's ROCm build keeps the "cuda" device name for HIP,
# which made an AMD box report "Transformers - cuda".
return _reported_device(self._device)
@@ -1272,20 +1254,16 @@ class WhisperSttSidecar:
def _release_engine_locked(self) -> bool:
"""Release the resident engine. False if its child outlived the kill.
- Such a child still holds its accelerator memory, so forgetting it here
- would report the model unloaded and let training be admitted against
- memory that is not free. Keep it resident instead and rearm the idle
- timer, so the release is tried again rather than stranded.
-
- The fields are cleared only once the worker is confirmed dead. close()
- can take the full shutdown wait, and loaded_model reads the fields
- without this lock, so clearing them first would report nothing resident
- for that whole window.
+ Such a child still holds its accelerator memory, so forgetting it here would report the
+ model unloaded and let training be admitted against memory that is not free. Keep it
+ resident instead and rearm the idle timer, so the release is tried again rather than
+ stranded.
- A worker kept this way is flagged a survivor: it was asked to shut down,
- terminated and killed, so it is held for its memory and not for its
- answers, and a later dictation must load one of its own rather than be
- handed this one and wait out the command timeout on it.
+ The fields are cleared only once the worker is confirmed dead: close() can take the full
+ shutdown wait and loaded_model reads the fields without this lock, so clearing them first
+ would report nothing resident for that whole window. A worker kept this way is flagged a
+ survivor, held for its memory and not for its answers, so a later dictation loads one of its
+ own rather than waiting out the command timeout on it.
"""
self._cancel_idle_unload_locked()
engine = self._engine
@@ -1313,15 +1291,12 @@ class WhisperSttSidecar:
) -> None:
"""Hold an engine whose child outlived its close, so it stays accounted.
- Its device is the one the child reports, which after a CPU retry is not
- the one this load started on; a child that never finished its load
- reports none, so the device the attempt was made on stands in. The idle
- timer is rearmed, so the release is tried again rather than the survivor
- being stranded here.
-
- Held for its memory, not for its answers: it is flagged so a later
- dictation loads a worker of its own instead of being handed one that is
- wedged, which would cost the caller the whole command timeout.
+ Its device is the one the child reports, which after a CPU retry is not the one this load
+ started on; a child that never finished its load reports none, so the device the attempt was
+ made on stands in. The idle timer is rearmed so the release is tried again. Held for its
+ memory, not its answers: it is flagged so a later dictation loads a worker of its own
+ instead of being handed one that is wedged, which would cost the caller the whole command
+ timeout.
"""
self._engine = engine
self._model_id = model_id
@@ -1337,12 +1312,11 @@ class WhisperSttSidecar:
def _is_survivor_locked(self) -> bool:
"""Whether the resident engine is held for its memory, not its answers.
- Folds in the flag the handle raised on itself: a command that was
- cancelled or timed out closes the worker from inside the handle, so
- close()'s False never reaches the sidecar and this is the only way it
- learns the child outlived both signals. Handing such a worker to the
- next dictation would spend the whole command timeout on it under the
- model lock; refusing lets the idle timer retry the kill instead.
+ Folds in the flag the handle raised on itself: a command that was cancelled or timed out
+ closes the worker from inside the handle, so close()'s False never reaches the sidecar and
+ this is the only way it learns the child outlived both signals. Handing such a worker to the
+ next dictation would spend the whole command timeout on it under the model lock; refusing
+ lets the idle timer retry the kill instead.
"""
if self._survivor:
return True
@@ -1360,22 +1334,18 @@ class WhisperSttSidecar:
def _build_model(self, snapshot_path: str, device: str, dtype, cancel_event: threading.Event):
"""Start a worker process holding this model and return its handle.
- Out of process because an accelerator context is never given back while
- the process holding it lives, so an in-process load made the backend
- permanently heavier even after unload.
-
- A host that cannot create a child at all (a sandbox, or a frozen POSIX
- build) falls back to loading here instead, on the CPU: this move may
- take work out of the backend, never take dictation away from someone
- who had it. The fallback waits for the CPU attempt, so a spawn failure
- on an accelerator still goes through the caller's own CPU retry rather
- than downgrading the user here.
-
- A child that outlived start()'s own kill is left in ``_start_survivor``
- for the caller. start() ends its child on every failure, so a handle
- still reporting a live process is one holding memory that nothing else
- knows about: dropping it here is what would let this failed load read as
- nothing resident.
+ Out of process because an accelerator context is never given back while the process holding
+ it lives, so an in-process load made the backend permanently heavier even after unload.
+
+ A host that cannot create a child at all (a sandbox, or a frozen POSIX build) falls back to
+ loading here instead, on the CPU: this move may take work out of the backend, never take
+ dictation away from someone who had it. The fallback waits for the CPU attempt, so a spawn
+ failure on an accelerator still goes through the caller's own CPU retry.
+
+ A child that outlived start()'s own kill is left in ``_start_survivor`` for the caller.
+ start() ends its child on every failure, so a handle still reporting a live process is one
+ holding memory that nothing else knows about: dropping it here is what would let this failed
+ load read as nothing resident.
"""
from core.inference.stt_transformers_worker import (
InProcessWhisperEngine,
@@ -1409,21 +1379,18 @@ class WhisperSttSidecar:
model_id: str,
use_resident: bool = True,
) -> _CachedSttSnapshot:
- """Validate the local snapshot before decode or model replacement.
-
- Returns the checkpoint's multilingual flag when local metadata provides
- it. Curated defaults are known multilingual.
-
- ``use_resident = False`` skips the resident-model shortcut and resolves the
- path on disk. The shortcut answers from the loaded model and returns no
- path, which is right when that model is about to be reused and wrong when
- the caller is replacing it with one on another device: the same model id is
- resident, but the load still needs somewhere to read the weights from.
-
- A survivor is held for its memory alone, so it does not answer for the
- model the way a resident one does: the snapshot is looked up on disk, or
- the load it precedes would be turned away as a checkpoint that is not
- downloaded.
+ """Validate the local snapshot before decode or model replacement. Returns the checkpoint's
+ multilingual flag when local metadata provides it; curated defaults are known multilingual.
+
+ ``use_resident = False`` skips the resident-model shortcut and resolves the path on disk.
+ The shortcut answers from the loaded model and returns no path, which is right when that
+ model is about to be reused and wrong when the caller is replacing it with one on another
+ device: the same model id is resident, but the load still needs somewhere to read the
+ weights from.
+
+ A survivor is held for its memory alone, so it does not answer for the model the way a
+ resident one does: the snapshot is looked up on disk, or the load it precedes would be
+ turned away as a checkpoint that is not downloaded.
"""
model_id = resolve_model_id(model_id)
with self._lock:
diff --git a/studio/backend/core/inference/stt_transformers_worker.py b/studio/backend/core/inference/stt_transformers_worker.py
index 4eb23b2fb2d..0af7e340241 100644
--- a/studio/backend/core/inference/stt_transformers_worker.py
+++ b/studio/backend/core/inference/stt_transformers_worker.py
@@ -40,7 +40,6 @@ _BACKEND_PATH = str(Path(__file__).resolve().parent.parent.parent)
# both bounds only break a hang: a cold-disk large-v3 load and a 30 minute transcription are legitimately slow
_LOAD_TIMEOUT_SECONDS = 600.0
_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
-# generation stops within a token, but a load inside from_pretrained never sees the cancel
# How long a cancelled command gets before the child is killed. Generation stops within a token, but a load inside
# from_pretrained never sees the cancel, and training is waiting for that memory.
_CANCEL_GRACE_SECONDS = 10.0
@@ -70,9 +69,6 @@ class SttWorkerSpawnError(SttWorkerError):
"""
-# ---------------------------------------------------------------------------
-
-
def _ensure_backend_on_path() -> None:
if _BACKEND_PATH not in sys.path:
sys.path.insert(0, _BACKEND_PATH)
@@ -286,9 +282,6 @@ def run_stt_worker(
return
-# ---------------------------------------------------------------------------
-
-
def _raise_worker_error(response: dict) -> None:
from core.inference import stt_sidecar
@@ -316,7 +309,6 @@ class WhisperWorker:
# that failed at something
self._ready_event = None
self._answered = False
- # a child that answered neither terminate nor kill answers no later command either
# Set once close() found a child that outlived terminate and kill. The handle is kept so its memory stays
# accounted, but a child that answered neither signal answers no later command either, and its terminate left
# the queues liable to corruption, so it must never be handed to a later dictation.
@@ -430,7 +422,6 @@ class WhisperWorker:
generate_kwargs: dict,
cancel_event: Optional[threading.Event] = None,
) -> str:
- """Transcribe one decoded window and return its text."""
if self._cancel_event is not None:
self._cancel_event.clear()
self._send(
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 68aecb9d12d..2cb50e7ffa2 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -3,44 +3,35 @@
"""Unsloth-owned tool execution loop, shared by every external provider transport.
-The loop owns the parts that do not depend on how bytes reach the provider:
-turn cycling, the tool budget, the approval handshake, local execution through
-``execute_tool``, and the conversation replay that carries results back. A
-``ToolLoopTransport`` supplies the one thing that does differ -- an async
-iterator of OpenAI-shaped SSE lines for one turn.
-
-Two transports exist: ``CodexTransport`` (the ChatGPT subscription, which speaks
-its own app-server protocol) and ``OAICompatTransport`` (everything routed
-through ``ExternalProviderClient``, which already normalises Anthropic, Gemini
+The loop owns the parts that do not depend on how bytes reach the provider: turn cycling, the tool
+budget, the approval handshake, local execution through ``execute_tool``, and the conversation
+replay that carries results back. A ``ToolLoopTransport`` supplies the one thing that does differ,
+an async iterator of OpenAI-shaped SSE lines for one turn. Two transports exist: ``CodexTransport``
+(the ChatGPT subscription, which speaks its own app-server protocol) and ``OAICompatTransport``
+(everything routed through ``ExternalProviderClient``, which already normalises Anthropic, Gemini
and the Responses API into OpenAI chunk shape).
-Self-hosted models frequently write tool calls as text rather than emitting
-structured ``delta.tool_calls``. A transport that sets ``heals_text_tool_calls``
-gets the content stream routed through ``StreamToolCallHealer``, the same
-bounded buffer the client-tool passthrough uses: only a trailing partial-signal
-window or a suspected tool block is ever withheld, and a block that cannot
-become a declared call flushes verbatim. Nothing here invents a cap on how much
-model output may be held.
-
-Origins. This file is assembled out of four contributor PRs rather than written
-from scratch, and the squash merge of #8665 did not carry their authorship, so
-it is recorded here:
-
-* #8626 (khalidejaz) -- the registry capability and the hidden-entry exposure,
- including the ``provider_runs_local_tools()`` name ``providers.py`` still
- uses.
-* #8630 (mahiatlinux) -- most of the loop internals below: the user-turn append,
- the tool-stream advance and drain, usage merging, the approval flush delay,
- the budget-exhausted nudge, and the streamed tool-name rule that llama-server
- forced. Also the browser testing against a control worktree that caught a
- truncated turn discarding a healed call along with the text describing it.
-* #7805 (Etherll) -- the hosted-provider reach.
-* #7330 (Souravrajvi0) -- the original OpenAI-compatible framing.
-
-Two ideas from those PRs were deliberately not taken, which is worth knowing
-before anyone re-derives them: the per-connection opt-in from #8630 and the
-``studio_tool_execution`` column from #7805. #8665 shipped a static disclosure
-instead, while widening the capability from four self-hosted types to thirteen.
+Self-hosted models frequently write tool calls as text rather than emitting structured
+``delta.tool_calls``. A transport that sets ``heals_text_tool_calls`` gets the content stream routed
+through ``StreamToolCallHealer``, the same bounded buffer the client-tool passthrough uses: only a
+trailing partial-signal window or a suspected tool block is ever withheld, and a block that cannot
+become a declared call flushes verbatim. Nothing here invents a cap on how much model output may be
+held.
+
+Origins. This file is assembled out of four contributor PRs rather than written from scratch, and
+the squash merge of #8665 did not carry their authorship, so it is recorded here. #8626 (khalidejaz)
+contributed the registry capability and the hidden-entry exposure, including the
+``provider_runs_local_tools()`` name ``providers.py`` still uses. #8630 (mahiatlinux) contributed
+most of the loop internals below: the user-turn append, the tool-stream advance and drain, usage
+merging, the approval flush delay, the budget-exhausted nudge, and the streamed tool-name rule that
+llama-server forced, plus the browser testing against a control worktree that caught a truncated
+turn discarding a healed call along with the text describing it. #7805 (Etherll) contributed the
+hosted-provider reach, and #7330 (Souravrajvi0) the original OpenAI-compatible framing.
+
+Two ideas from those PRs were deliberately not taken, which is worth knowing before anyone
+re-derives them: the per-connection opt-in from #8630 and the ``studio_tool_execution`` column from
+#7805. #8665 shipped a static disclosure instead, while widening the capability from four
+self-hosted types to thirteen.
"""
from __future__ import annotations
@@ -147,11 +138,9 @@ def _truncate_for_model(
*,
joiner: str = "\n",
) -> str:
- """Hold a hosted result to the same cap a local result gets.
-
- Read off ``tools`` rather than copied, so an install that lowers
- ``UNSLOTH_TOOL_RESULT_MAX_CHARS`` gets the lower cap here too.
- """
+ """Hold a hosted result to the same cap a local result gets. Read off ``tools`` rather than
+ copied, so an install that lowers ``UNSLOTH_TOOL_RESULT_MAX_CHARS`` gets the lower cap here
+ too."""
if limit is None:
limit = tools_module._MAX_OUTPUT_CHARS
if len(text) <= limit:
@@ -159,7 +148,6 @@ def _truncate_for_model(
return text[:limit] + f"{joiner}... [truncated, {len(text) - limit} more characters]"
-# Cap on a call's label.
# Cap on a call's label. Small next to the result cap: this is the query or the code, not the output.
_HOSTED_ARGUMENT_MAX_CHARS = 2000
@@ -171,12 +159,10 @@ _HOSTED_ARGUMENT_PLUMBING_KEYS = frozenset({"google", "_server_tool"})
def _carries_image_sentinel(result: str) -> bool:
- """Whether a hosted result ends in the ``__IMAGES__`` envelope itself.
-
- Validated rather than matched on sight, the way the local strippers
- validate theirs: a fetched page that merely writes the marker is prose, and
- reading it as a picture would report an image the turn never made.
- """
+ """Whether a hosted result ends in the ``__IMAGES__`` envelope itself. Validated rather than
+ matched on sight, the way the local strippers validate theirs: a fetched page that merely
+ writes the marker is prose, and reading it as a picture would report an image the turn never
+ made."""
_, sep, payload = result.rpartition("\n__IMAGES__:")
if not sep:
return False
@@ -226,12 +212,9 @@ def _chunk_payload(line: str) -> dict[str, Any] | None:
def _mint_streamed_card_id(taken: set[str], index: Any) -> str:
- """The id the client painted an id-less call's card under.
-
- ``tool_call_<delta index>``, else the lowest free ``tool_call_<n>``: the
- client's rule, reproduced so tool_start and tool_end reach the card the
- stream drew. A card id only; the replayed id stays ``call_<round>_<pos>``.
- """
+ """The id the client painted an id-less call's card under. ``tool_call_<delta index>``, else the
+ lowest free ``tool_call_<n>``: the client's rule, reproduced so tool_start and tool_end reach
+ the card the stream drew. A card id only; the replayed id stays ``call_<round>_<pos>``."""
preferred = (
f"tool_call_{index}" if isinstance(index, int) and not isinstance(index, bool) else ""
)
@@ -282,12 +265,10 @@ def _normalized_call(call: dict[str, Any], fallback_id: str = "") -> dict[str, A
def _argument_fragment(value: Any) -> Any:
- """A decoded-object ``arguments`` delta as the text it would have streamed as.
-
- llama-server has shipped a decoded object where a string fragment belongs
- (ggml-org/llama.cpp#20198). Everything else passes through untouched, so ``None`` still means
- "announced, no arguments field". Mirrors ``streamedToolCallArguments`` in ``tool-call-arguments.ts``.
- """
+ """A decoded-object ``arguments`` delta as the text it would have streamed as. llama-server has
+ shipped a decoded object where a string fragment belongs (ggml-org/llama.cpp#20198).
+ Everything else passes through untouched, so ``None`` still means "announced, no arguments
+ field". Mirrors ``streamedToolCallArguments`` in ``tool-call-arguments.ts``."""
if isinstance(value, (dict, list)):
try:
return json.dumps(value, ensure_ascii = False, separators = (",", ":"))
@@ -297,12 +278,10 @@ def _argument_fragment(value: Any) -> Any:
def _delta_text(content: Any) -> str:
- """Text of a content delta, whether it is a plain string or content parts.
-
- Structured content blocks reach the client fine either way, but only the
- text of them belongs in the assistant message replayed upstream, and
- dropping it there loses the turn's prose on the follow-up call.
- """
+ """Text of a content delta, whether it is a plain string or content parts. Structured content
+ blocks reach the client fine either way, but only the text of them belongs in the assistant
+ message replayed upstream, and dropping it there loses the turn's prose on the follow-up
+ call."""
if isinstance(content, str):
return content
if isinstance(content, list):
@@ -334,9 +313,10 @@ class ToolLoopTransport(Protocol):
# does; a self-hosted GGUF often does.
heals_text_tool_calls: bool
- # Whether the transport already stripped Unsloth's control vocabulary from every raw upstream line. A transport that
- # has not is sanitized here; one that has must not be sanitized twice, because by this point its own synthesized
- # frames (a provider-hosted image result, say) are indis- tinguishable from a forged one and would be thrown away.
+ # Whether the transport already stripped Unsloth's control vocabulary from every raw upstream line. A transport
+ # that has not is sanitized here; one that has must not be sanitized twice, because by this point its own
+ # synthesized frames (a provider-hosted image result, say) are indistinguishable from a forged one and would be
+ # thrown away.
sanitizes_provider_frames: bool
def stream(
@@ -374,8 +354,8 @@ class ToolLoopPolicy:
auto_heal: bool | None = None
# None follows UNSLOTH_TOOL_CALL_NUDGE; explicit booleans win.
nudge_tool_calls: bool | None = None
- # Called before relaying the chunk that ends a turn a text-form call was healed out of. Headerless relay only, to arm
- # its ServerToolCallStripper for a call that never reached the wire as a tool_calls key.
+ # Called before relaying the chunk that ends a turn a text-form call was healed out of. Headerless relay only, to
+ # arm its ServerToolCallStripper for a call that never reached the wire as a tool_calls key.
on_withheld_tool_call: Callable[[], None] | None = None
# Called when a provider turn ends, however it ended. Headerless only: clears the stripper's withheld-call flag,
# which the wire cannot always close because a turn may end on [DONE] alone.
@@ -388,13 +368,10 @@ def _reject_json_constant(name: str) -> Any:
def _split_top_level_json_objects(text: str) -> tuple[list[str], str]:
- """The top-level JSON objects in ``text``, and any object still unfinished.
-
- A second top-level ``{`` means one slot took a second parallel call. Text
- that is not a run of whole objects comes back whole, so a stream this was
- never meant for is left alone. Must agree with
- ``splitTopLevelJsonObjects`` in ``chat/tool-call-arguments.ts``.
- """
+ """The top-level JSON objects in ``text``, and any object still unfinished. A second top-level
+ ``{`` means one slot took a second parallel call. Text that is not a run of whole objects
+ comes back whole, so a stream this was never meant for is left alone. Must agree with
+ ``splitTopLevelJsonObjects`` in ``chat/tool-call-arguments.ts``."""
unsplit: tuple[list[str], str] = ([], text)
complete: list[str] = []
depth = 0
@@ -448,12 +425,9 @@ def _split_top_level_json_objects(text: str) -> tuple[list[str], str]:
@dataclass
class _BoundaryScan:
- """``_split_top_level_json_objects`` over a string that only ever grows.
-
- Rescanning per fragment is O(N^2); resuming is one pass. ``feed`` takes the
- same string extended, never a rewritten one, so ``_Turn`` drops the scan
- for any key a fork rewrites.
- """
+ """``_split_top_level_json_objects`` over a string that only ever grows. Rescanning per fragment
+ is O(N^2); resuming is one pass. ``feed`` takes the same string extended, never a rewritten
+ one, so ``_Turn`` drops the scan for any key a fork rewrites."""
depth: int = 0
start: int = -1
@@ -531,8 +505,8 @@ class _Turn:
key_by_call_id: dict[str, Any] = field(default_factory = dict)
# Resumable boundary scan per call, keyed the same as ``by_index``.
scan_by_key: dict[Any, _BoundaryScan] = field(default_factory = dict)
- # Forks whose object never closed: reported only once it does, or a stream cut short after '{"a":1}{' runs the tool
- # on half an argument.
+ # Forks whose object never closed: reported only once it does, or a stream cut short after '{"a":1}{' runs the
+ # tool on half an argument.
open_tail_keys: set[Any] = field(default_factory = set)
# Metadata from a delta repeating the slot's name. That name is either the call's, resent, or the next call to the
# same tool announcing itself, and only the object that follows tells them apart.
@@ -547,17 +521,13 @@ class _Turn:
hosted_results: dict[str, dict[str, Any]] = field(default_factory = dict)
def note_hosted_tool_event(self, event: Any) -> None:
- """Record a provider-side tool call carried on ``_toolEvent``.
-
- These reach the client as their own frames but are not part of the
- assistant message this loop replays, so the follow-up request would lose
- whatever the provider just produced. Unsloth's own events carry a
- top-level ``type``, so ``_toolEvent`` is unambiguously the provider's.
-
- Both halves matter: ``tool_end`` generally omits ``tool_name``, and for
- Gemini code execution the code that ran is only in the ``tool_start``
- arguments, so a result recorded alone is unlabelled.
- """
+ """Record a provider-side tool call carried on ``_toolEvent``. These reach the client as
+ their own frames but are not part of the assistant message this loop replays, so the
+ follow-up request would lose whatever the provider just produced; Unsloth's own events
+ carry a top-level ``type``, so ``_toolEvent`` is unambiguously the provider's. Both
+ halves matter: ``tool_end`` generally omits ``tool_name``, and for Gemini code execution
+ the code that ran is only in the ``tool_start`` arguments, so a result recorded alone is
+ unlabelled."""
if not isinstance(event, dict):
return
call_id = event.get("tool_call_id")
@@ -596,12 +566,13 @@ class _Turn:
entry["ended"] = True
if isinstance(result, str) and result.strip():
if _carries_image_sentinel(result):
- # A Gemini plot with no stdout is nothing BUT the sentinel, so stripping leaves an empty string and the
- # entry looks empty.
+ # A Gemini plot with no stdout is nothing BUT the sentinel, so stripping leaves an empty string and
+ # the entry looks empty.
entry["produced_image"] = True
# Same normalisation local results get: the frontend sentinels carry a full data URI, and replaying one
# sends megabytes of base64. The tool's name goes with it, as the local path passes it: only the sandbox
- # tools emit __FILES__, so a fetched page ending in a well formed one keeps that line as the content it is.
+ # tools emit __FILES__, so a fetched page ending in a well formed one keeps that line as the content it
+ # is.
stripped = strip_result_for_model(result, entry.get("name"))
if stripped.strip():
entry["result"] = _truncate_for_model(stripped)
@@ -623,8 +594,8 @@ class _Turn:
arguments = entry.get("arguments")
if arguments:
header = f"[{name} {arguments}]"
- # A call that ended with nothing to show still has to appear, as the same "(no output)" local tools report,
- # so the model can tell the code ran from it never having run at all.
+ # A call that ended with nothing to show still has to appear, as the same "(no output)" local tools
+ # report, so the model can tell the code ran from it never having run at all.
body = result or ("(produced an image)" if produced_image else "(no output)")
if result and produced_image:
body = f"{result}\n(produced an image)"
@@ -642,9 +613,8 @@ class _Turn:
# call that is already open instead.
index = self.last_index if self.last_index is not None else len(self.order)
call_id = raw_call.get("id")
- # index restarts at 0 for every tool round
- # continue whichever call owns this index now: index restarts at 0 for every tool round, so after a fork the
- # bare argument fragments belong to the newer call.
+ # continue whichever call owns this index now: index restarts at 0 for every tool round, so after a fork
+ # the bare argument fragments belong to the newer call.
key: Any = self.open_key_by_index.get(index, index)
if isinstance(call_id, str) and call_id:
# An id beats the latest-index mapping: a fragment repeating one returns to its own call wherever that
@@ -653,14 +623,12 @@ class _Turn:
if owner is not None:
key = owner
elif self.by_index.get(key, {}).get("id"):
- # Two distinct calls at the same index: merging concatenates their argument JSON into one
- # unparseable blob and loses an intent
- # Two distinct calls reported at the same index. Merging them concatenates their argument JSON into
- # one unparseable blob and loses an intent, so key the second on its own id.
+ # Two distinct calls reported at the same index. Merging them concatenates their argument JSON
+ # into one unparseable blob and loses an intent, so key the second on its own id.
key = (index, call_id)
- # A closed object takes no more content, so the next arguments to reach the slot belong to the next parallel
- # call. Forking on the accumulated text alone catches this only once they glue on, and a delta carrying an
- # id would claim the finished call and append to it (issue #9807).
+ # A closed object takes no more content, so the next arguments to reach the slot belong to the next
+ # parallel call. Forking on the accumulated text alone catches this only once they glue on, and a delta
+ # carrying an id would claim the finished call and append to it (issue #9807).
held = self.by_index.get(key)
new_function = raw_call.get("function")
new_arguments = _argument_fragment(
@@ -668,10 +636,10 @@ class _Turn:
)
new_name = new_function.get("name") if isinstance(new_function, dict) else None
# A next call opens with the "{" of its own arguments object, so a fragment starting with anything else is
- # not one: whitespace after a closing brace belongs to the object just closed, and forking on a stray scalar
- # suffix would run the tool twice. An id names a call outright, so one naming a DIFFERENT call opens the
- # next even before its arguments arrive. Alone, or repeating the slot's name, it is that call's id stamped
- # late.
+ # not one: whitespace after a closing brace belongs to the object just closed, and forking on a stray
+ # scalar suffix would run the tool twice. An id names a call outright, so one naming a DIFFERENT call
+ # opens the next even before its arguments arrive. Alone, or repeating the slot's name, it is that call's
+ # id stamped late.
held_name_now = held["function"]["name"] if held is not None else ""
id_names_another_call = bool(
isinstance(call_id, str)
@@ -683,8 +651,8 @@ class _Turn:
# same call.
and new_name != held_name_now
)
- # A snapshot provider repeats the finished call verbatim once it has an id. Exact repeats only, so a second
- # call still opens.
+ # A snapshot provider repeats the finished call verbatim once it has an id. Exact repeats only, so a
+ # second call still opens.
resends_this_call = bool(
held is not None
and isinstance(call_id, str)
@@ -722,8 +690,8 @@ class _Turn:
and isinstance(new_arguments, str)
and new_arguments.strip().startswith("{")
)
- # A fragment repeating the id this slot holds continues it however complete the arguments look, or two calls
- # end up with one id.
+ # A fragment repeating the id this slot holds continues it however complete the arguments look, or two
+ # calls end up with one id.
names_this_call = (
held is not None
and isinstance(call_id, str)
@@ -736,8 +704,8 @@ class _Turn:
slot_is_closed = bool(closed) and not unfinished
extra = raw_call.get("extra_content")
# A name repeating a closed slot's says nothing new about that call, so metadata riding it belongs to
- # whichever call the next object opens. Merged here it overwrites that call's signature and leaves the next
- # unsigned.
+ # whichever call the next object opens. Merged here it overwrites that call's signature and leaves the
+ # next unsigned.
extra_is_ambiguous = bool(
slot_is_closed
and isinstance(new_name, str)
@@ -766,8 +734,8 @@ class _Turn:
"id": "",
"type": "function",
"function": {"name": opening_name, "arguments": ""},
- # A name with no `arguments` field is an announcement; a zero-parameter tool sends "" rather than no
- # field.
+ # A name with no `arguments` field is an announcement; a zero-parameter tool sends "" rather than
+ # no field.
"announced_only": new_arguments is None and bool(opening_name),
# A fork's guess, or a slot the provider opened itself. Only the provider's own announcement runs
# unfilled.
@@ -804,11 +772,11 @@ class _Turn:
current["extra_content"] = {**current.get("extra_content", {}), **extra}
function = raw_call.get("function")
if isinstance(function, dict):
- # Two provider dialects, and picking either one alone breaks the other. llama-server re-sends the whole
- # name as it grows ("web" then "web_search"), so appending yields "webweb_search". OpenAI streams it in
- # fragments ("web" then "_search"), so assigning yields "_search". Both then fail the enabled-name check
- # and the call silently never runs. A fragment that already starts with what we have is the whole name
- # resent; anything else continues it.
+ # Two provider dialects, and picking either one alone breaks the other. llama-server re-sends the
+ # whole name as it grows ("web" then "web_search"), so appending yields "webweb_search"; OpenAI
+ # streams it in fragments ("web" then "_search"), so assigning yields "_search". Both then fail the
+ # enabled-name check and the call silently never runs. A fragment that already starts with what we
+ # have is the whole name resent; anything else continues it.
fragment = function.get("name")
name_before = current["function"]["name"]
# Never once the object has closed AND a name is set: that puts one tool's arguments under another's
@@ -821,8 +789,8 @@ class _Turn:
if isinstance(new_arguments, str) and not resends_this_call:
current["function"]["arguments"] += new_arguments
if not (isinstance(call_id, str) and call_id):
- # The id fork cannot see this: an id-less stream has no ids to differ on, so appending glued two
- # calls into one blob (issue #9807).
+ # The id fork cannot see this: an id-less stream has no ids to differ on, so appending glued
+ # two calls into one blob (issue #9807).
self._fork_glued_arguments(
index,
key,
@@ -834,11 +802,9 @@ class _Turn:
)
def _scan(self, key: Any, text: str) -> tuple[list[str], str]:
- """``_split_top_level_json_objects(text)``, resuming the scan for ``key``.
-
- The same answer as scanning from byte zero, at the cost of the bytes
- this call added rather than of the whole accumulation.
- """
+ """``_split_top_level_json_objects(text)``, resuming the scan for ``key``. The same answer
+ as scanning from byte zero, at the cost of the bytes this call added rather than of the
+ whole accumulation."""
scan = self.scan_by_key.get(key)
if scan is None:
scan = _BoundaryScan()
@@ -860,8 +826,8 @@ class _Turn:
segments = complete + ([tail] if tail else [])
if len(segments) < 2:
return
- # Below rewrites this slot's arguments rather than extending them, so the resumable scan no longer describes the
- # string it was reading.
+ # Below rewrites this slot's arguments rather than extending them, so the resumable scan no longer describes
+ # the string it was reading.
self.scan_by_key.pop(key, None)
# The slot keeps its first object, name and id. Nothing per-call rides along: two calls claiming one
# thoughtSignature is a rejected turn.
@@ -897,13 +863,10 @@ class _Turn:
self.open_key_by_index[index] = open_key
def _call_is_finished(self, key: Any) -> bool:
- """Whether a call forked off an unfinished object has since closed it.
-
- Only ``length`` and ``content_filter`` mark a turn truncated, so a
- stream that stops after ``{"a":1}{`` looks complete; running the tool a
- second time on that lone brace is worse than dropping a call the model
- never finished writing.
- """
+ """Whether a call forked off an unfinished object has since closed it. Only ``length`` and
+ ``content_filter`` mark a turn truncated, so a stream that stops after ``{"a":1}{`` looks
+ complete; running the tool a second time on that lone brace is worse than dropping a call
+ the model never finished writing."""
if key not in self.open_tail_keys:
return True
closed, unfinished = _split_top_level_json_objects(
@@ -920,18 +883,13 @@ class _Turn:
taken: set[str] | None = None,
cards: set[str] | None = None,
) -> list[dict[str, Any]]:
- """Every call this turn produced, with ids unique across the whole run.
-
- ``taken`` carries the ids already used by earlier turns. A provider that
- restarts its numbering each turn, and the healer (which always mints
- call_0 first), would otherwise put two different results under one id in
- the conversation replayed upstream.
-
- ``cards`` carries the card ids already handed out. The client keeps one
- list of cards for the whole response, so a second round has to keep
- counting rather than start again at ``tool_call_0`` and reopen the first
- round's cards.
- """
+ """Every call this turn produced, with ids unique across the whole run. ``taken`` carries
+ the ids already used by earlier turns: a provider that restarts its numbering each turn,
+ and the healer (which always mints call_0 first), would otherwise put two different
+ results under one id in the conversation replayed upstream. ``cards`` carries the card
+ ids already handed out, because the client keeps one list of cards for the whole
+ response, so a second round has to keep counting rather than start again at
+ ``tool_call_0`` and reopen the first round's cards."""
seen: set[str] = taken if taken is not None else set()
painted: set[str] = cards if cards is not None else set()
out: list[dict[str, Any]] = []
@@ -949,9 +907,10 @@ class _Turn:
ordered = [
(index, call) for _, index, call in sorted(numbered, key = lambda triple: triple[0])
]
- # An announcement another call took over, and a name that only looked like the closed call's resent, were never
- # calls. A lone announcement the provider opened is kept (a zero-parameter tool looks like that). Its metadata
- # goes to the call it was mistaken for: Gemini stows a thought signature there and rejects a replay without one.
+ # An announcement another call took over, and a name that only looked like the closed call's resent, were
+ # never calls. A lone announcement the provider opened is kept (a zero-parameter tool looks like that). Its
+ # metadata goes to the call it was mistaken for: Gemini stows a thought signature there and rejects a replay
+ # without one.
for key, waiting in self.pending_extra.items():
# No object ever came, so the repeated name was that call's after all and so is the metadata that rode it.
held = self.by_index.get(key)
@@ -973,9 +932,9 @@ class _Turn:
continue
kept.append((index, call))
ordered = kept
- # Provider ids reserved first, so a minted card id never collides. Only the ones _normalized_call keeps: a call
- # it rejects draws no card, the client releases the id it had minted for it, and an id held here that the client
- # has given back puts the two out of step from the next round.
+ # Provider ids reserved first, so a minted card id never collides. Only the ones _normalized_call keeps: a
+ # call it rejects draws no card, the client releases the id it had minted for it, and an id held here that the
+ # client has given back puts the two out of step from the next round.
painted.update(
call["id"]
for _, call in ordered
@@ -993,9 +952,9 @@ class _Turn:
painted.add(card_id)
normalized["card_id"] = card_id
if normalized["id"] in seen:
- # The client keyed the card it painted on the id the provider streamed, so keep that one for the events
- # aimed at the card. Never replayed upstream: the conversation carries the de-duplicated id, which is
- # the whole point of the rename.
+ # The client keyed the card it painted on the id the provider streamed, so keep that one for the
+ # events aimed at the card. Never replayed upstream: the conversation carries the de-duplicated id,
+ # which is the whole point of the rename.
normalized["stream_id"] = normalized["id"]
# The renamed id is itself stored and replayed, so a single-shot rename collides again on the next
# request. Counting up over a finite ledger terminates and leaves the first attempt as is.
@@ -1025,13 +984,11 @@ def _rewrite_content(payload: dict[str, Any], choice: dict[str, Any], text: str)
def _split_turn_end(
payload: dict[str, Any], choice: dict[str, Any], delta: dict[str, Any]
) -> tuple[str | None, str]:
- """Separate a turn-ending chunk into what can be sent now and the reason to hold.
-
- Only the finish_reason has to wait for the healer to resolve; the content on that same
- chunk does not, and holding it too would let residue flushed by ``finalize`` overtake
- it and reverse the text on the wire. So the content goes out in place and a bare
- finish-only chunk is what gets parked.
- """
+ """Separate a turn-ending chunk into what can be sent now and the reason to hold. Only the
+ finish_reason has to wait for the healer to resolve; the content on that same chunk does not,
+ and holding it too would let residue flushed by ``finalize`` overtake it and reverse the text
+ on the wire. So the content goes out in place and a bare finish-only chunk is what gets
+ parked."""
now_choice = {key: value for key, value in choice.items() if key != "finish_reason"}
now_choice["delta"] = delta
now_payload = {key: value for key, value in payload.items() if key != "choices"}
@@ -1050,8 +1007,8 @@ def _split_turn_end(
def _unrun_provenance(tool_name: str, round_id: int) -> dict[str, Any]:
- """Provenance for a hand-built unrun card; carries the MCP display name so a
- budget-exhausted or truncated MCP call never shows the internal server id."""
+ """Provenance for a hand-built unrun card; carries the MCP display name so a budget-exhausted or
+ truncated MCP call never shows the internal server id."""
provenance: dict[str, Any] = {"source": "local", "round_id": round_id}
mcp = mcp_display_parts(tool_name)
if mcp:
@@ -1062,16 +1019,13 @@ def _unrun_provenance(tool_name: str, round_id: int) -> dict[str, Any]:
def _unrun_call_card(
*, tool_name: str, tool_call_id: str, arguments: Any, result: str, provenance: dict[str, Any]
) -> list[str]:
- """The open/close pair for a call this loop announces but never runs.
-
- The close on its own is not enough. A call the provider streamed as a
- tool_calls delta already has a card, and the client reconciles both events
- onto it by id -- but a call the healer promoted out of TEXT was never
- streamed as a delta, so a lone tool_end names a card that does not exist and
- the adapter drops it: the user is told nothing at all. Opening the card
- first makes both cases end the same way, and keeps the invariant the loop is
- tested on, that every tool_end closes a tool_start.
- """
+ """The open/close pair for a call this loop announces but never runs. The close on its own is
+ not enough: a call the provider streamed as a tool_calls delta already has a card, and the
+ client reconciles both events onto it by id, but a call the healer promoted out of TEXT was
+ never streamed as a delta, so a lone tool_end names a card that does not exist and the
+ adapter drops it, leaving the user told nothing at all. Opening the card first makes both
+ cases end the same way, and keeps the invariant the loop is tested on, that every tool_end
+ closes a tool_start."""
shown = arguments if isinstance(arguments, dict) else {}
return [
_sse(
@@ -1102,14 +1056,11 @@ def _status_sse(text: str) -> str:
def _merge_usage(totals: dict[str, Any], usage: Any) -> None:
- """Sum one turn's usage into the running total.
-
- Per-turn usage is withheld while the loop runs and one summed chunk is sent
- at the end, so a multi-turn answer reports the same shape a single-turn one
- does instead of a burst of partial counts the client would have to add up.
- Detail sub-objects are summed too: reporting less than the same provider's
- plain stream would understate cost and cache hits.
- """
+ """Sum one turn's usage into the running total. Per-turn usage is withheld while the loop runs
+ and one summed chunk is sent at the end, so a multi-turn answer reports the same shape a
+ single-turn one does instead of a burst of partial counts the client would have to add up.
+ Detail sub-objects are summed too: reporting less than the same provider's plain stream would
+ understate cost and cache hits."""
if not isinstance(usage, dict):
return
for field, value in usage.items():
@@ -1148,13 +1099,10 @@ def _is_usage_only(payload: dict[str, Any]) -> bool:
def _replayed_call_ids(conversation: list[dict[str, Any]]) -> set[str]:
- """Every tool-call id already in the history this run starts from.
-
- The healer restarts its counter every request, so a freshly minted call_0
- collides with a stripped call_0 replayed from history inside one upstream
- body. Seeding the ledger makes calls() rename the new one as it does any
- repeat within a run.
- """
+ """Every tool-call id already in the history this run starts from. The healer restarts its
+ counter every request, so a freshly minted call_0 collides with a stripped call_0 replayed
+ from history inside one upstream body. Seeding the ledger makes calls() rename the new one as
+ it does any repeat within a run."""
taken: set[str] = set()
for message in conversation:
if not isinstance(message, dict):
@@ -1169,12 +1117,10 @@ def _replayed_call_ids(conversation: list[dict[str, Any]]) -> set[str]:
def _append_user_turn(conversation: list[dict[str, Any]], content: str) -> None:
- """Append a user turn, merging into a trailing one so roles keep alternating.
-
- A turn whose only calls were no-ops appends no assistant message, so a bare
- append would leave two user turns in a row. Unlike the in-process loops this
- conversation is rendered by the provider, and a strict server rejects that.
- """
+ """Append a user turn, merging into a trailing one so roles keep alternating. A turn whose only
+ calls were no-ops appends no assistant message, so a bare append would leave two user turns
+ in a row. Unlike the in-process loops this conversation is rendered by the provider, and a
+ strict server rejects that."""
if not content:
return
last = conversation[-1] if conversation else None
@@ -1197,13 +1143,10 @@ def _advance_tool_stream(generator: Any, outcome: dict[str, Any]) -> Any:
async def _drain_step_task(task: Any, cancel_event: threading.Event) -> None:
- """Join a pending ``next(gen)`` worker before its generator is closed.
-
- Cancelling the awaiting task does not stop the worker thread, and calling
- close() while next() is still running raises "generator already executing"
- and skips the generator's own cleanup. Setting the cancel flag lets a
- cancel-observing tool return, then the task is shielded until it finishes.
- """
+ """Join a pending ``next(gen)`` worker before its generator is closed. Cancelling the awaiting
+ task does not stop the worker thread, and calling close() while next() is still running
+ raises "generator already executing" and skips the generator's own cleanup. Setting the
+ cancel flag lets a cancel-observing tool return, then the task is shielded until it finishes."""
if task is None:
return
if task.done():
@@ -1287,16 +1230,15 @@ async def stream_with_studio_tools(
last_reprompt_text = ""
provider_turns = 0
used_call_ids: set[str] = _replayed_call_ids(conversation)
- # Card ids handed out this response.
# Card ids handed out this response. The client keeps one list across all rounds, so the numbering carries rather
# than reopening an earlier card.
painted_card_ids: set[str] = set()
spent_budget_passes = 0
fruitless_turns = 0
# One provider call per possible execution, plus headroom for the no-op, nudge and final-answer passes that
- # legitimately execute nothing. The unlimited sentinel keeps its own budget rather than dropping to a smaller fixed
- # number: both local loops run "Max" for as many turns as the model asks for, and fruitless_turns already ends a run
- # that executes nothing, so a lower bound here only cuts a productive run short with no final answer.
+ # legitimately execute nothing. The unlimited sentinel keeps its own budget rather than dropping to a smaller
+ # fixed number: both local loops run "Max" for as many turns as the model asks for, and fruitless_turns already
+ # ends a run that executes nothing, so a lower bound here only cuts a productive run short with no final answer.
max_provider_turns = max(1, remaining) + 2 * MAX_ACT_REPROMPTS + 4
while not cancel_event.is_set():
@@ -1323,8 +1265,8 @@ async def stream_with_studio_tools(
# enabled_tools), so there are no provider-hosted builtins left for "none" to revoke, and saying it explicitly
# stops a model from calling a tool it was just denied.
turn_tool_choice = tool_choice if tools_available else "none"
- # A forced choice applies until the model actually calls something; the result follow-up must be free to answer
- # in prose.
+ # A forced choice applies until the model actually calls something; the result follow-up must be free to
+ # answer in prose.
if executed_any and turn_tool_choice not in ("auto", "none"):
turn_tool_choice = "auto"
@@ -1338,12 +1280,12 @@ async def stream_with_studio_tools(
async for line in generator:
if _is_done_sentinel(line):
continue
- # This loop writes its tool cards, badges and the approval handshake onto the same stream the provider's
- # chunks are relayed on, and the client tells them apart only by shape. A provider's copy of that
- # vocabulary would therefore paint a card for a tool that never ran, so strip it before anything below
- # can relay it. Skipped for a transport that already did it at the point the raw bytes arrived:
- # everything reaching here from one of those is this server's own frame, and stripping it drops a
- # retained hosted tool's result after the provider billed it.
+ # This loop writes its tool cards, badges and the approval handshake onto the same stream the
+ # provider's chunks are relayed on, and the client tells them apart only by shape. A provider's copy
+ # of that vocabulary would therefore paint a card for a tool that never ran, so strip it before
+ # anything below can relay it. Skipped for a transport that already did it at the point the raw bytes
+ # arrived: everything reaching here from one of those is this server's own frame, and stripping it
+ # drops a retained hosted tool's result after the provider billed it.
if not transport_sanitizes:
sanitized = sanitize_provider_sse_line(line)
if sanitized is None:
@@ -1353,17 +1295,17 @@ async def stream_with_studio_tools(
if payload is None:
yield line
continue
- # OpenRouter and friends resolve a routing alias to a concrete model and name it on every chunk. That id
- # is more specific than the one the request asked for, so let it win for the summed usage chunk this
- # loop emits once the answer ends.
+ # OpenRouter and friends resolve a routing alias to a concrete model and name it on every chunk. That
+ # id is more specific than the one the request asked for, so let it win for the summed usage chunk
+ # this loop emits once the answer ends.
upstream_model = payload.get("model")
if isinstance(upstream_model, str) and upstream_model:
model_name = upstream_model
if "usage" in payload:
_merge_usage(usage_totals, payload.get("usage"))
if _is_usage_only(payload):
- # Withheld: one summed chunk is sent once the loop ends, so a multi-turn answer does not report
- # a burst of partial counts.
+ # Withheld: one summed chunk is sent once the loop ends, so a multi-turn answer does not
+ # report a burst of partial counts.
continue
# Some providers hang usage off a chunk that also carries a choice, which cannot be withheld
# wholesale without losing the content. Drop just the usage: it is already in the totals, and
@@ -1461,11 +1403,10 @@ async def stream_with_studio_tools(
# The turn ended in a call this loop is about to run, so the provider's reason is not the end of the
# response. Arming blanks it for headerless callers and records the debt, so owed_terminal_chunk() still
- # mints a terminal if the loop stops before a later turn supplies one. A truncated turn is the exception: it
- # refuses to run the call, so its reason really is final.
- #
- # Deliberately not conditioned on held_final: a provider that closes on [DONE] alone while a healed call is
- # promoted would leave the debt unarmed, ending the stream with no finish_reason, which openai-node rejects.
+ # mints a terminal if the loop stops before a later turn supplies one. A truncated turn is the exception:
+ # it refuses to run the call, so its reason really is final. Deliberately not conditioned on held_final: a
+ # provider that closes on [DONE] alone while a healed call is promoted would leave the debt unarmed,
+ # ending the stream with no finish_reason, which openai-node rejects.
if (
turn.healed
and turn.finish_reason not in ("length", "content_filter")
@@ -1491,22 +1432,22 @@ async def stream_with_studio_tools(
if policy.on_provider_turn_end is not None:
policy.on_provider_turn_end()
- # Both mean the turn ended before the model finished Both of these mean the turn ended before the model finished
- # saying what it wanted: "length" hit the token ceiling, "content_filter" had the output cut by the provider's
- # own filter. Either way a call collected so far may be half-written, so it is described rather than run. "stop"
- # is not in this set: llama.cpp and vLLM routinely finish a perfectly good tool call with it, and refusing those
- # would disable tool calling on exactly the self-hosted servers this path exists for.
+ # Both of these mean the turn ended before the model finished saying what it wanted: "length" hit the token
+ # ceiling, "content_filter" had the output cut by the provider's own filter. Either way a call collected so
+ # far may be half-written, so it is described rather than run. "stop" is not in this set: llama.cpp and vLLM
+ # routinely finish a perfectly good tool call with it, and refusing those would disable tool calling on
+ # exactly the self-hosted servers this path exists for.
truncated = turn.finish_reason in ("length", "content_filter")
if truncated and healer is not None and turn.healed:
# A call cut off at the token limit must not run: its arguments can be half-written and the model never
- # finished saying what it wanted. But promotion is destructive -- the healer already removed the markup span
- # from the text relayed above -- so discarding the call on its own would take the sentence that introduced
- # it with it, and the user would be left with a stub answer, no card, and no way to tell that anything was
- # attempted. Give the exact removed span back instead. It is the same verbatim flush the healer performs for
- # a block that turns out not to be a declared call, and only the healer can supply it: nothing else in the
- # loop keeps the raw bytes, and re-encoding the parsed call would print something the model never wrote.
- # Released at the end of the turn rather than in document order because "length" is only known once the turn
- # has ended.
+ # finished saying what it wanted. But promotion is destructive -- the healer already removed the markup
+ # span from the text relayed above -- so discarding the call on its own would take the sentence that
+ # introduced it with it, and the user would be left with a stub answer, no card, and no way to tell that
+ # anything was attempted. Give the exact removed span back instead. It is the same verbatim flush the
+ # healer performs for a block that turns out not to be a declared call, and only the healer can supply it:
+ # nothing else in the loop keeps the raw bytes, and re-encoding the parsed call would print something the
+ # model never wrote. Released at the end of the turn rather than in document order because "length" is
+ # only known once the turn has ended.
for healed_call in turn.healed:
span = healer.promoted_source(healed_call.get("id", ""))
if not span:
@@ -1514,15 +1455,14 @@ async def stream_with_studio_tools(
turn.text.append(span)
yield _sse({"choices": [{"index": 0, "delta": {"content": span}}]})
if truncated:
- # The other half: a call the provider streamed as a tool_calls delta was relayed as it arrived
# The other half of the same problem. A call the provider streamed as a tool_calls delta was relayed as it
# arrived, so the client already has a card for it, and refusing to run it leaves that card open for the
# rest of the response. Close it the way every other unrun call is closed. Structured only: a healed call
# was never streamed, and the span released just above is what tells the user about that one. Through
# `calls`, which never executes anything: it is what mints the card id for a call the provider gave none,
- # and the client drew its card under that same spelling. Reading the slots directly left every id-less call
- # out, so the card the deltas painted spun for the rest of the response. Calls it drops -- nameless, or a
- # fork whose object never closed -- have no card of ours to close either.
+ # and the client drew its card under that same spelling. Reading the slots directly left every id-less
+ # call out, so the card the deltas painted spun for the rest of the response. Calls it drops -- nameless,
+ # or a fork whose object never closed -- have no card of ours to close either.
for raw_call in turn.calls(used_call_ids, painted_card_ids):
truncated_id = (
raw_call.get("card_id") or raw_call.get("stream_id") or raw_call["id"]
@@ -1531,17 +1471,17 @@ async def stream_with_studio_tools(
for card_line in _unrun_call_card(
tool_name = name,
tool_call_id = truncated_id,
- # The arguments are cut off mid-write, so there is nothing well formed to show; the result says what
- # happened.
+ # The arguments are cut off mid-write, so there is nothing well formed to show; the result says
+ # what happened.
arguments = {},
result = _TOOL_TRUNCATED,
provenance = _unrun_provenance(name, round_id + 1),
):
yield card_line
# tool_choice "none" is an instruction, and a provider that emits a call anyway has not been authorized to run
- # one. Withdrawing the catalog on the way out is not enough on its own: Deep Research sets "none" exactly so the
- # scraped web text in its prompts cannot reach python or terminal, so a naive or compromised endpoint echoing a
- # call back must not be able to execute it here.
+ # one. Withdrawing the catalog on the way out is not enough on its own: Deep Research sets "none" exactly so
+ # the scraped web text in its prompts cannot reach python or terminal, so a naive or compromised endpoint
+ # echoing a call back must not be able to execute it here.
calls = (
[]
if (truncated or tool_choice == "none")
@@ -1549,13 +1489,12 @@ async def stream_with_studio_tools(
)
if not calls:
# The badge clears between iterations, and this turn is over too. Without it a turn whose only call was
- # refused never reaches the empty status below, so the client keeps the card it drew for that call open and
- # a reprompted call merges into it: an upstream ending on [DONE] sends no finish_reason either, so there is
- # no other boundary on this path. Only when a call was streamed: a turn that said nothing at all left the
- # client nothing to close, and a provider that sends no lines still ends the response silently.
+ # refused never reaches the empty status below, so the client keeps the card it drew for that call open
+ # and a reprompted call merges into it: an upstream ending on [DONE] sends no finish_reason either, so
+ # there is no other boundary on this path. Only when a call was streamed: a turn that said nothing at all
+ # left the client nothing to close, and a provider that sends no lines still ends the response silently.
if turn.by_index:
yield _status_sse("")
- # No tool this turn.
# No tool this turn. A model that only said what it was about to do gets one nudge to actually do it, the
# same recovery the local loops give a stalled small model, then the answer stands as written.
visible_answer = "".join(turn.text)
@@ -1571,9 +1510,9 @@ async def stream_with_studio_tools(
last_reprompt_text = visible_answer
stalled_hosted = turn.hosted_replay_text()
if stalled_hosted:
- # A hosted tool did run, the model just did not go on to ask for a local one. The replay below never
- # happens on this path, so the reprompted request would be told to continue from output it can no
- # longer see.
+ # A hosted tool did run, the model just did not go on to ask for a local one. The replay below
+ # never happens on this path, so the reprompted request would be told to continue from output it
+ # can no longer see.
stalled_message: dict[str, Any] = {
"role": "assistant",
"content": (
@@ -1589,8 +1528,8 @@ async def stream_with_studio_tools(
append_assistant_turn(
conversation,
stalled_message,
- # A resumed partial is the same turn as what the model just added, so merge rather than append:
- # appending puts a turn boundary mid-sentence.
+ # A resumed partial is the same turn as what the model just added, so merge rather than
+ # append: appending puts a turn boundary mid-sentence.
continue_final_message = run.continue_final_message,
)
_append_user_turn(conversation, reprompt_to_act_message(tool_hint))
@@ -1622,7 +1561,8 @@ async def stream_with_studio_tools(
exhausted_call: dict[str, Any] = {
"id": call["id"],
"type": "function",
- # Copied: the normalized call also carries a parsed arguments dict that must not reach the provider
+ # Copied: the normalized call also carries a parsed arguments dict that must not reach the
+ # provider
"function": dict(call["function"]),
}
exhausted_extra = call.get("extra_content")
@@ -1645,14 +1585,13 @@ async def stream_with_studio_tools(
if not decision.should_execute:
completion = controller.record_noop(decision)
noop_messages.append(completion.model_message())
- # The provider's tool_calls delta was relayed while it streamed and the client painted a card from it;
# The provider's own tool_calls delta for this call was relayed verbatim while it streamed and the
- # client painted a card from it. Nothing else closes that card, so without a terminal event it spins for
- # the rest of the answer and then reads as a tool that ran and returned nothing. Keyed on the streamed
- # id, since a repeated call is exactly the one this loop renames above. Only for a tool the user DID
- # enable. A call for something outside the catalog is not a tool of Unsloth's that declined to run, it
- # is a name this install never offered, and giving it a card would advertise a tool the user switched
- # off. That one is answered in the conversation only.
+ # client painted a card from it. Nothing else closes that card, so without a terminal event it spins
+ # for the rest of the answer and then reads as a tool that ran and returned nothing. Keyed on the
+ # streamed id, since a repeated call is exactly the one this loop renames above. Only for a tool the
+ # user DID enable: a call for something outside the catalog is not a tool of Unsloth's that declined
+ # to run, it is a name this install never offered, and giving it a card would advertise a tool the
+ # user switched off. That one is answered in the conversation only.
if decision.action == "disabled":
continue
for card_line in _unrun_call_card(
@@ -1762,16 +1701,16 @@ async def stream_with_studio_tools(
"rag_scope": rag_scope,
"disable_sandbox": bypass_permissions,
}
- # Provider loops share the local catalogue selector, so search_conversation is advertised here too once
- # a thread has an archive and needs the same branch: the stored rows are the whole DAG, and Retry leaves
- # the replaced response in them.
+ # Provider loops share the local catalogue selector, so search_conversation is advertised here too
+ # once a thread has an archive and needs the same branch: the stored rows are the whole DAG, and Retry
+ # leaves the replaced response in them.
if accepts_kwarg(execute_tool, "conversation_branch"):
kwargs["conversation_branch"] = request_branch
# And a budget, so the tool's clamp is not skipped. Unsloth cannot measure an external model's window,
# and a custom OpenAI-compatible endpoint can be a small local server, so a model-chosen 8 chunks is
# roughly 4K tokens replayed on every later call. Unmeasurable means one recall's worth. Explicitly
- # unknowable, not absent: this request is served by an external provider, so the resident GGUF's window
- # says nothing about what it can hold. 0 keeps the default page cap instead of inheriting it.
+ # unknowable, not absent: this request is served by an external provider, so the resident GGUF's
+ # window says nothing about what it can hold. 0 keeps the default page cap instead of inheriting it.
if accepts_kwarg(execute_tool, "context_tokens"):
kwargs["context_tokens"] = 0
if accepts_kwarg(execute_tool, "conversation_budget_tokens"):
@@ -1821,9 +1760,9 @@ async def stream_with_studio_tools(
if "result" in outcome:
result = outcome["result"]
elif cancel_event.is_set():
- # Stopped before the tool returned. Defaulting to "" here would record a successful empty result and
- # paint a normal tool_end, so the transcript would claim a tool ran and produced nothing, when in
- # truth it was abandoned partway and its side effects may already have happened.
+ # Stopped before the tool returned. Defaulting to "" here would record a successful empty result
+ # and paint a normal tool_end, so the transcript would claim a tool ran and produced nothing, when
+ # in truth it was abandoned partway and its side effects may already have happened.
result = _TOOL_CANCELLED
else:
result = ""
@@ -1836,9 +1775,9 @@ async def stream_with_studio_tools(
tool_stream.close()
completion = controller.record_result(decision, result)
- # Counted whether or not the tool succeeded: a failing call has already done its work (and possibly its side
- # effects), so letting it run for free would put the budget past max_calls. Counted per call rather than per
- # turn, so parallel calls each spend one.
+ # Counted whether or not the tool succeeded: a failing call has already done its work (and possibly its
+ # side effects), so letting it run for free would put the budget past max_calls. Counted per call rather
+ # than per turn, so parallel calls each spend one.
if not unlimited:
remaining -= 1
turn_executed_real_tool = True
@@ -1860,8 +1799,8 @@ async def stream_with_studio_tools(
if hosted_text:
# A tool the provider ran itself this turn. Its output went to the client as its own frame but is not
# otherwise part of this message, so the follow-up would answer from the local results alone. Replayed as
- # text, not native items: the shape differs per provider (Gemini codeExecutionResult, an OpenAI image call),
- # while every provider can read its own prior turn's prose.
+ # text, not native items: the shape differs per provider (Gemini codeExecutionResult, an OpenAI image
+ # call), while every provider can read its own prior turn's prose.
assistant_message["content"] = (
f"{assistant_message['content']}\n\n{hosted_text}"
if assistant_message["content"]
@@ -1892,8 +1831,8 @@ async def stream_with_studio_tools(
else:
fruitless_turns += 1
if fruitless_turns >= _MAX_FRUITLESS_TURNS:
- # It asked for tools twice running and none could run. One more pass would only repeat the exchange, so
- # stop asking.
+ # It asked for tools twice running and none could run. One more pass would only repeat the exchange,
+ # so stop asking.
break
if remaining <= 0 and not unlimited and not controller.force_final_answer:
if spent_budget_passes:
diff --git a/studio/backend/core/inference/tensor_fallback.py b/studio/backend/core/inference/tensor_fallback.py
index b60fdf848a9..61299445cc2 100644
--- a/studio/backend/core/inference/tensor_fallback.py
+++ b/studio/backend/core/inference/tensor_fallback.py
@@ -69,7 +69,6 @@ async def load_with_tensor_fallback(
"(this model may not support tensor parallelism)",
label,
)
- # explicit --split-mode layer: leftover extras or an inherited LLAMA_ARG_SPLIT_MODE=tensor would re-crash the retry
# Force --split-mode layer (CLI wins over env) so neither leftover extras nor an inherited
# LLAMA_ARG_SPLIT_MODE=tensor can re-engage tensor and re-crash the retry; load_model and the child both honor the
# explicit layer override.
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index 39aa7a86260..e9acb94b78d 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -1,26 +1,17 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Backend-neutral tool-call parser shared by GGUF, safetensors, and MLX, so the
-safetensors + MLX agentic loop sees the same call shape llama-server gives GGUF:
-
- - ``<tool_call>{json}</tool_call>`` (Qwen / Hermes)
- - ``<function=name><parameter=k>v</parameter></function>`` (Qwen3.5 xml)
- - ``<|python_tag|>NAME.call(k="v", ...)`` (Llama-3 built-in tools)
- - ``<|python_tag|>{"name":..., "parameters":...}`` (Llama-3 custom)
- - ``{"name":..., "parameters":...}`` (Llama-3.2 bare JSON)
- - ``[TOOL_CALLS] [{...}, ...]`` (Mistral v0.3 / Nemo / Small)
- - ``[TOOL_CALLS]name{json}`` (Mistral v11+ / Magistral)
- - ``[TOOL_CALLS]name[ARGS]{json}`` (Ministral / Mistral Large 3)
- - ``<|tool_call>call:NAME{k:<|"|>v<|"|>}<tool_call|>`` (Gemma 4)
- - ``<|tool▁calls▁begin|>...function<|tool▁sep|>NAME\\n``\\`\\`\\`json\\n{...}\\n\\`\\`\\`...`` (DeepSeek R1)
- - ``<|tool▁calls▁begin|>...<|tool▁call▁begin|>NAME<|tool▁sep|>{json}<|tool▁call▁end|>...`` (DeepSeek V3 / V3.1)
- - ``<tool_call>NAME\\n<arg_key>k</arg_key>\\n<arg_value>v</arg_value>...</tool_call>`` (GLM 4.5 / 4.6 / 4.7)
- - ``<|tool_calls_section_begin|>...<|tool_call_begin|>functions.NAME:IDX<|tool_call_argument_begin|>{json}<|tool_call_end|>...`` (Kimi K2)
-
-Missing closing tags / brackets are tolerated: models often truncate mid-stream.
-"""
+"""Backend-neutral tool-call parser shared by GGUF, safetensors, and MLX, so the safetensors + MLX
+agentic loop sees the same call shape llama-server gives GGUF. Formats:
+``<tool_call>{json}</tool_call>`` (Qwen / Hermes);
+``<function=name><parameter=k>v</parameter></function>`` (Qwen3.5 xml);
+``<|python_tag|>NAME.call(k="v", ...)`` and ``<|python_tag|>{"name":..., "parameters":...}``
+(Llama-3); bare ``{"name":..., "parameters":...}`` (Llama-3.2); ``[TOOL_CALLS]`` array /
+``name{json}`` / ``name[ARGS]{json}`` (Mistral v0.3 through Large 3);
+``<|tool_call>call:NAME{k:<|"|>v<|"|>}<tool_call|>`` (Gemma 4); the fullwidth-pipe envelopes of
+DeepSeek R1 / V3 / V3.1; ``<tool_call>NAME<arg_key>..<arg_value>..</tool_call>`` (GLM 4.5-4.7);
+and the ``<|tool_calls_section_begin|>`` form (Kimi K2). Missing closing tags / brackets are
+tolerated: models often truncate mid-stream."""
# Lazy annotations keep the standalone python 3.9 import working.
from __future__ import annotations
@@ -48,8 +39,8 @@ TOOL_XML_SIGNALS = (
"<|python_tag|>",
"[TOOL_CALLS]",
"<|tool_call>",
- # Bare reasoning-rehearsal marker (``name[ARGS]{...}``, no leading [TOOL_CALLS]); keeps a rehearsed call held in the
- # stream so it is promoted, not leaked as prose.
+ # Bare reasoning-rehearsal marker (``name[ARGS]{...}``, no leading [TOOL_CALLS]); keeps a rehearsed call held in
+ # the stream so it is promoted, not leaked as prose.
"[ARGS]",
# DeepSeek R1 / V3 / V3.1 -- 5 opener variants llama.cpp keeps.
"<|tool▁calls▁begin|>",
@@ -163,8 +154,8 @@ BUDGET_EXHAUSTED_NUDGE = (
# The exact-args dup guard misses paraphrased re-searches, so also cap KB searches per turn
RAG_MAX_SEARCHES_PER_TURN = 3
# Both retrieval tools share that cap. Their top-K passages land in the current exchange, which the rolling window
-# protects and cannot evict, so an uncapped search only ends the turn in a context-length error. Here so both tool loops
-# agree on it.
+# protects and cannot evict, so an uncapped search only ends the turn in a context-length error. Here so both tool
+# loops agree on it.
RAG_SEARCH_TOOLS = frozenset({"search_knowledge_base", "search_conversation"})
RAG_SEARCH_CAP_NUDGE = (
"You have already searched the knowledge base several times this turn. "
@@ -173,19 +164,17 @@ RAG_SEARCH_CAP_NUDGE = (
)
-# Verbs naming work this turn.
-# ── Plan-without-action re-prompt (shared by the GGUF and safetensors loops) ── Verbs naming work this turn. Narrow on
+# Plan-without-action re-prompt (shared by the GGUF and safetensors loops). Verbs naming work this turn. Narrow on
# purpose: "install"/"add"/"open" belong to advice for the user, which must not be re-prompted.
-# ── Plan-without-action re-prompt (shared by the GGUF and safetensors loops) ──
_ACTION_VERB = (
r"(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e"
r"|review|inspect|read|gather|examine|retrieve|browse|consult|verify"
r"|confirm|compute|calculate|determine|identify|render)"
)
-# Offering to help hands control back exactly like "let me know": measured on real turns, "I'll do my best to help" and
-# "allow me to assist" close a clarification request and never precede a tool call. "help you" keeps its plan reading
-# when an action follows it ("I'll help you search the web"). name no work of their own, so they only ever sign off a
-# question to the user (#8907)
+# Offering to help hands control back exactly like "let me know": measured on real turns, "I'll do my best to help"
+# and "allow me to assist" close a clarification request and never precede a tool call. "help you" keeps its plan
+# reading when an action follows it ("I'll help you search the web"). These name no work of their own, so they only
+# ever sign off a question to the user (#8907)
_SIGN_OFF = r"(?:dig\s+in|help\s+analy[sz]e)\b(?=[^\w]*\Z)" # \Z not $: a later line is still work
_HELP_OFFER = (
r"(?:do(?:ing)?\s+my\s+best|try\s+my\s+best|be\s+(?:able|happy|glad)\s+to\b"
@@ -204,9 +193,8 @@ INTENT_SIGNAL = re.compile(
# bare "assist" still names work here ("let me assist by searching"), so only the sign-offs skip the "to"
r"(?!\s+" + _SIGN_OFF + r")(?!\s+to\s+" + _HELP_OFFER + r")"
r"|"
- # "first" must open a sentence and be followed by a plan (pronoun, "my/our plan", or an action verb);
# Step/plan framing. "first" must open a sentence and be followed by a plan (pronoun, "my/our plan", or an action
- # verb); otherwise it is prose ("The first line is blank.", "First place went to Alice") or advice to the user.
+ # verb); otherwise it is prose ("The first line is blank.") or advice to the user.
r"(?:^|[.!?]\s+)\s*(?:the\s+)?first\s+step\b"
r"|(?:^|[.!?]\s+)\s*first\s*[,:–—-]?\s+(?:my|our)\s+(?:plan|approach|step)\b"
r"|(?:^|[.!?]\s+)\s*first\s*[,:–—-]?\s+(?:i|we|let['’]?s|let us)\b"
@@ -247,16 +235,17 @@ def _normalize_for_repeat(text: str) -> str:
return " ".join(words)
-# A nudge that just gets the same answer back has not worked, so stop there. Exact after normalisation. Every relaxation
-# tried here lost a real correction: a similarity ratio is length dependent (one changed token in a 50-word plan still
-# scored 0.98), a set ignores order ("cats not dogs"), and ignoring filler words eats the target itself ("The Who", "OK
-# Go"). A missed repeat costs one nudge out of MAX_ACT_REPROMPTS; a false one strands the plan unexecuted.
+# A nudge that just gets the same answer back has not worked, so stop there. Exact after normalisation: every
+# relaxation tried here lost a real correction -- a similarity ratio is length dependent (one changed token in a
+# 50-word plan still scored 0.98), a set ignores order ("cats not dogs"), and ignoring filler words eats the target
+# itself ("The Who", "OK Go"). A missed repeat costs one nudge out of MAX_ACT_REPROMPTS; a false one strands the plan
+# unexecuted.
def is_reprompt_repeat(text: str, previous: str) -> bool:
return is_reprompt_restatement(text, previous)
-# Same comparison, different decision: this one discards the turn. An appended answer must not match, and deletions flip
-# meaning ("is not supported" -> "is supported").
+# Same comparison, different decision: this one discards the turn. An appended answer must not match, and deletions
+# flip meaning ("is not supported" -> "is supported").
def is_reprompt_restatement(text: str, previous: str) -> bool:
if not previous:
return False
@@ -274,9 +263,9 @@ def reprompt_to_act_message(tool_hint: str) -> str:
)
-# How much of the unfinished thought is carried into the continuation. The point is to resume, not to replay: the whole
-# thought is what filled the window, so putting it back reproduces the same ending. The tail is the part still being
-# worked on.
+# How much of the unfinished thought is carried into the continuation. The point is to resume, not to replay: the
+# whole thought is what filled the window, so putting it back reproduces the same ending. The tail is the part still
+# being worked on.
_LENGTH_PROGRESS_TAIL_CHARS = 600
@@ -287,12 +276,10 @@ def unfinished_thought_progress(reasoning: str) -> str:
def starved_result_message(tool_name: str, result: str) -> str:
- """Appended when the window priced this call's result at nothing before it ran.
-
- Said on the FIRST such call rather than after a run of identical ones: the pricing is
- known before the tool executes, so waiting for the repeat guard to notice costs several
- calls to learn something already computed.
- """
+ """Appended when the window priced this call's result at nothing before it ran. Said on the
+ FIRST such call rather than after a run of identical ones: the pricing is known before the
+ tool executes, so waiting for the repeat guard to notice costs several calls to learn
+ something already computed."""
return (
f"{result}\n\n"
f"[No room in the window for this result, so {tool_name} returned nothing usable. "
@@ -302,11 +289,9 @@ def starved_result_message(tool_name: str, result: str) -> str:
def repeated_result_message(tool_name: str, times: int, last_result: str) -> str:
- """Appended to a result the tool has now returned unchanged several times.
-
- The last result is kept rather than replaced: it may be the truncation notice that
- caused the repeats, and dropping it would leave the model with less than it had.
- """
+ """Appended to a result the tool has now returned unchanged several times. The last result is
+ kept rather than replaced: it may be the truncation notice that caused the repeats, and
+ dropping it would leave the model with less than it had."""
return (
f"{last_result}\n\n"
f"[{tool_name} returned exactly this {times} times; it will not change. Continue "
@@ -315,15 +300,12 @@ def repeated_result_message(tool_name: str, times: int, last_result: str) -> str
def thinking_exhausted_message(context_length: Optional[int] = None) -> str:
- """Shown when even a thinking-off retry produced nothing visible.
-
- Names the lever the user actually has. Hermes surfaces the same advice
- (NousResearch/hermes-agent, `_thinking_exhausted`) and Codex's guidance for the
- identical symptom is likewise to lower reasoning effort, because no amount of
- retrying fits a thought that did not fit the first time.
- """
- # Built by substitution rather than `.format` on a pre-spaced fragment, which produced "spent its whole reply of the
- # 4096-token window on reasoning".
+ """Shown when even a thinking-off retry produced nothing visible. Names the lever the user
+ actually has. Hermes surfaces the same advice and Codex's guidance for the identical symptom
+ is likewise to lower reasoning effort, because no amount of retrying fits a thought that did
+ not fit the first time."""
+ # Built by substitution rather than `.format` on a pre-spaced fragment, which produced "spent its whole reply of
+ # the 4096-token window on reasoning".
window = f"{context_length}-token " if context_length else ""
return (
f"The model spent the whole of its {window}window on reasoning and had none "
@@ -336,14 +318,12 @@ def thinking_exhausted_message(context_length: Optional[int] = None) -> str:
def reasoning_cap_spent_message(max_tokens: Optional[int] = None) -> str:
- """Shown when a reasoning-only turn was stopped by the CALLER's own Max Tokens.
-
- A different wall from the one `thinking_exhausted_message` describes, and the levers
- are opposite: the window has room, the allowance does not, and only one attempt ran.
- Blaming the context window there sends the user to raise the one setting that was
- never the constraint, and this text reaches the client as ordinary content, so the
- frontend's cap-aware error cannot correct it afterwards.
- """
+ """Shown when a reasoning-only turn was stopped by the CALLER's own Max Tokens. A different wall
+ from the one `thinking_exhausted_message` describes, and the levers are opposite: the window
+ has room, the allowance does not, and only one attempt ran. Blaming the context window there
+ sends the user to raise the one setting that was never the constraint, and this text reaches
+ the client as ordinary content, so the frontend's cap-aware error cannot correct it
+ afterwards."""
allowance = f" of {max_tokens} tokens" if max_tokens else ""
return (
f"The model used its whole output allowance{allowance} on reasoning and had none "
@@ -356,12 +336,10 @@ def reasoning_cap_spent_message(max_tokens: Optional[int] = None) -> str:
def continue_after_length_message() -> str:
- """The user message appended when a turn ended inside its own reasoning.
-
- The instruction is to ACT, not to think more carefully: the previous turn ended with
- nothing to show because thinking consumed the whole window, so asking for more
- deliberation is asking for the same ending a second time.
- """
+ """The user message appended when a turn ended inside its own reasoning. The instruction is to
+ ACT, not to think more carefully: the previous turn ended with nothing to show because
+ thinking consumed the whole window, so asking for more deliberation is asking for the same
+ ending a second time."""
return (
"You ran out of room while thinking, so nothing was produced. Stop thinking and "
"act: call a tool or answer now. If it will not all fit, deliver the first part "
@@ -399,9 +377,8 @@ _LLAMA3_CALL_CHAIN_RE = re.compile(r"\s*;\s*([\w\.\-]+)\s*\.\s*call\s*\(")
# retries every offset of a long run (ReDoS).
_LLAMA3_KEY_RE = re.compile(r"\w+")
_LLAMA3_WS_RE = re.compile(r"\s*")
-# ints, decimals (1.5, 1., .5) and sci notation
-# ints, decimals (1.5, 1., .5) and sci notation; trailing ``(?![\w.])`` stops a token like ``1.2.3`` being truncated to
-# ``1.2`` (which would mis-parse the remainder).
+# ints, decimals (1.5, 1., .5) and sci notation; trailing ``(?![\w.])`` stops a token like ``1.2.3`` being truncated
+# to ``1.2`` (which would mis-parse the remainder).
_LLAMA3_NUM_RE = re.compile(r"-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?![\w.])")
_LLAMA3_LIT_RE = re.compile(r"true|false|null")
@@ -410,7 +387,7 @@ _LLAMA3_LIT_RE = re.compile(r"true|false|null")
_MISTRAL_TRIGGER = "[TOOL_CALLS]"
_MISTRAL_ARGS_MARKER = "[ARGS]"
# Mistral Small 3.2 emits ``name[CALL_ID]<id>[ARGS]{json}`` (absent on Ministral / Magistral); llama.cpp distinguishes
-# the two on ``[CALL_ID]`` (common/chat.cpp).
+# the two on ``[CALL_ID]``.
_MISTRAL_CALL_ID_MARKER = "[CALL_ID]"
# Magistral wraps reasoning in ``[THINK]...[/THINK]``; a ``[TOOL_CALLS]`` inside that block is chain-of-thought, not a
# real call.
@@ -430,8 +407,6 @@ _DEEPSEEK_R1_FUNC_MARKER = "function" + _DEEPSEEK_SEP
_DEEPSEEK_R1_FENCE = "\n```json\n"
_DEEPSEEK_R1_CLOSE_RE = re.compile(r"```[\s\r\n]*" + re.escape(_DEEPSEEK_CALL_END))
-# GLM 4.5-4.7: the lookahead also allows a direct ``<arg_key>``/``</tool_call>`` (4.7 drops the newline, zero-arg calls
-# close at once).
# GLM 4.5-4.7: ``<tool_call>NAME[\n]<arg_key>K</arg_key>...``; the lookahead also allows a direct
# ``<arg_key>``/``</tool_call>`` (4.7 drops the newline, zero-arg calls close at once). Name class ``[\w.\-]+`` keeps
# prose like ``<tool_call>not a call</tool_call>`` unparsed; ``{`` stays with the Qwen JSON parser.
@@ -441,11 +416,10 @@ _GLM_ARG_KEY_OPEN = "<arg_key>"
_GLM_ARG_KEY_CLOSE = "</arg_key>"
_GLM_ARG_VAL_OPEN = "<arg_value>"
_GLM_ARG_VAL_CLOSE = "</arg_value>"
-# Strings arrive raw, non-strings via tojson; only unambiguous JSON literals decode (bare ``42``/``true``/``null`` stay
-# strings).
+# Strings arrive raw, non-strings via tojson; only unambiguous JSON literals decode (bare ``42``/``true``/``null``
+# stay strings).
_GLM_JSON_NUMERIC_RE = re.compile(r"-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?")
-# Kimi K2 / Moonshot (ASCII pipes).
# Kimi K2 / Moonshot (ASCII pipes). Id ``functions.NAME:IDX`` -- strip ``functions.``/``:N`` for the name.
_KIMI_SECTION_BEGIN = "<|tool_calls_section_begin|>"
_KIMI_SECTION_END = "<|tool_calls_section_end|>"
@@ -460,8 +434,8 @@ _GEMMA_STR_BEGIN = '<|"|>'
_GEMMA_STR_END = '<|"|>'
_GEMMA_TC_END = "<tool_call|>"
-# skip_special_tokens strips the wrapper and ``<|"|>`` markers, so streamed Gemma calls arrive as bare ``call:NAME{k:v,
-# ...}``
+# skip_special_tokens strips the wrapper and ``<|"|>`` markers, so streamed Gemma calls arrive as bare
+# ``call:NAME{k:v, ...}``
_GEMMA_BARE_TC_RE = re.compile(r"(?<!\w)call\s*:\s*([\w\.\-]+)\s*\{")
# Partial leading prefix (``call``, ``call :``, ``call : name``) so the streaming buffer holds it instead of leaking
# visible text
@@ -505,8 +479,8 @@ def _skip_mistral_call_id(text: str, pos: int) -> int:
def _strip_mistral_reasoning(content: str) -> str:
- """Drop a leading Magistral ``[THINK]...[/THINK]`` so a ``[TOOL_CALLS]`` inside
- reasoning is not taken as a real call; an unclosed ``[THINK]`` drops from it on."""
+ """Drop a leading Magistral ``[THINK]...[/THINK]`` so a ``[TOOL_CALLS]`` inside reasoning is not
+ taken as a real call; an unclosed ``[THINK]`` drops from it on."""
i = 0
n = len(content)
while i < n and content[i] in " \t\n\r":
@@ -520,10 +494,9 @@ def _strip_mistral_reasoning(content: str) -> str:
def _strip_mistral_closed_calls(text: str) -> str:
- """Strip cleanly-closed ``[TOOL_CALLS]`` blocks (array, ``name{json}``,
- ``name[ARGS]{json}``) via balanced scanning -- a non-greedy ``\\{.*?\\}`` would
- truncate at the first ``}`` and lose nested JSON. Unclosed runs are left for
- ``final=True`` cleanup."""
+ """Strip cleanly-closed ``[TOOL_CALLS]`` blocks (array, ``name{json}``, ``name[ARGS]{json}``)
+ via balanced scanning -- a non-greedy ``\\{.*?\\}`` would truncate at the first ``}`` and
+ lose nested JSON. Unclosed runs are left for ``final=True`` cleanup."""
n = len(text)
out = []
cursor = 0
@@ -579,7 +552,7 @@ def _strip_mistral_closed_calls(text: str) -> str:
break
cursor = end + 1
# Consume the optional EOS marker too, mirroring the array shape, so a ``[TOOL_CALLS]name{json}</s>`` tail
- # doesn't leave ``</s>`` as content.
+ # does not leave ``</s>`` as content.
if text.startswith("</s>", cursor):
cursor += len("</s>")
return "".join(out)
@@ -591,12 +564,11 @@ _GEMMA_ANCHOR_CLOSERS = ("</think>", "[/THINK]", "</thinking>")
def _gemma_call_is_anchored(text: str, start: int, floor: int) -> bool:
- """Whether a markerless ``call:NAME{...}`` at ``start`` OWNS its position: only
- horizontal whitespace between it and ``floor`` (the scan origin), the start of its
- line, or a reasoning close. Anywhere else it reads as a sentence documenting the
- syntax, so the DISPLAY strip keeps it. The parser is deliberately NOT gated this
- way, so a call it promotes mid-prose stays visible instead of the answer being
- deleted around it."""
+ """Whether a markerless ``call:NAME{...}`` at ``start`` OWNS its position: only horizontal
+ whitespace between it and ``floor`` (the scan origin), the start of its line, or a reasoning
+ close. Anywhere else it reads as a sentence documenting the syntax, so the DISPLAY strip
+ keeps it. The parser is deliberately NOT gated this way, so a call it promotes mid-prose
+ stays visible instead of the answer being deleted around it."""
i = start - 1
while i >= floor and text[i] in " \t\r":
i -= 1
@@ -1280,10 +1252,10 @@ def _unmask_blocked_bodies(text: str, bodies: list) -> Optional[str]:
def _strip_gemma_wrapperless_calls(text: str, enabled_tool_names: Optional[set] = None) -> str:
- """Strip closed wrapper-less Gemma ``call:NAME{...}`` calls with balanced brace
- scanning (nested arguments are removed whole). Gated like the parser: a name that is
- not markerless-promotable stays visible, as does an unanchored mid-sentence call.
- ``None`` strips every anchored closed non-execution call."""
+ """Strip closed wrapper-less Gemma ``call:NAME{...}`` calls with balanced brace scanning (nested
+ arguments are removed whole). Gated like the parser: a name that is not markerless-promotable
+ stays visible, as does an unanchored mid-sentence call. ``None`` strips every anchored closed
+ non-execution call."""
if _whole_content_is_json_value(text):
return text
n = len(text)
@@ -1333,7 +1305,9 @@ _FUNC_CLOSE_TAG_RE = re.compile(r"</function>")
def _strip_function_xml_calls(text: str, *, final: bool) -> str:
- """Strip ``<function=...>`` calls by mirroring the parser: an opener inside an open ``<parameter>`` is data and each call closes at its first ``</function>`` that is not parameter data; ``final`` drops a trailing unclosed call."""
+ """Strip ``<function=...>`` calls by mirroring the parser: an opener inside an open
+ ``<parameter>`` is data and each call closes at its first ``</function>`` that is not
+ parameter data; ``final`` drops a trailing unclosed call."""
starts = [
m for m in _TC_FUNC_START_RE.finditer(text) if not _inside_open_parameter(text, m.start())
]
@@ -1369,15 +1343,14 @@ def _glm_value_close(
*,
strict: bool = False,
) -> int:
- """Index of the ``</arg_value>`` that really ends the GLM value at ``vs``: the
- first one whose next non-space token is ``<arg_key>``, ``</tool_call>`` or
- end-of-text AND that sits at balanced quote state (an embedded literal pair
- like ``print("</arg_value></tool_call>")`` lives inside a still-open string).
- Quote openers are contextual (single quote only after punctuation, so
- apostrophes are prose; double quote also at word start), mirroring the Gemma
- scanners. If no candidate balances, the first token-valid one wins -- except
- in ``strict`` mode (Auto-Heal off), which refuses the in-quote fallback rather
- than execute truncated arguments. Returns -1 if unclosed."""
+ """Index of the ``</arg_value>`` that really ends the GLM value at ``vs``: the first one whose
+ next non-space token is ``<arg_key>``, ``</tool_call>`` or end-of-text AND that sits at
+ balanced quote state (an embedded literal pair like ``print("</arg_value></tool_call>")``
+ lives inside a still-open string). Quote openers are contextual (single quote only after
+ punctuation, so apostrophes are prose; double quote also at word start), mirroring the Gemma
+ scanners. If no candidate balances, the first token-valid one wins -- except in ``strict``
+ mode (Auto-Heal off), which refuses the in-quote fallback rather than execute truncated
+ arguments. Returns -1 if unclosed."""
n = len(text)
search = vs
first_candidate = -1
@@ -1415,11 +1388,10 @@ def _glm_value_close(
def _strip_glm_calls(text: str, *, final: bool) -> str:
- """Strip GLM 4.x calls by scanning to each call's REAL ``</tool_call>`` (the one
- after the last consumed ``<arg_value>``, mirroring ``_parse_glm_tool_calls``), so
- a literal ``</tool_call>`` inside a value is data. Qwen ``<tool_call>{json}`` has
- no NAME token and is left to the regex arms. ``final`` drops a truncated call to
- EOS; otherwise it stays buffered."""
+ """Strip GLM 4.x calls by scanning to each call's REAL ``</tool_call>`` (the one after the last
+ consumed ``<arg_value>``, mirroring ``_parse_glm_tool_calls``), so a literal ``</tool_call>``
+ inside a value is data. Qwen ``<tool_call>{json}`` has no NAME token and is left to the regex
+ arms. ``final`` drops a truncated call to EOS; otherwise it stays buffered."""
out: list[str] = []
cursor = 0
n = len(text)
@@ -1469,13 +1441,11 @@ def strip_segment(
seg_final: bool,
enabled_tool_names: Optional[set] = None,
) -> str:
- """Strip tool-call markup from one non-``<think>`` segment.
-
- The single definition of the scan order, shared by the GGUF and safetensors paths.
- ``routes/inference.py`` keeps a deliberately different order for the passthrough
- path, pinned by ``tests/test_route_strip_drift.py``. ``seg_final`` enables the
- end-of-turn arms (markerless Gemma, open tails, trailing partial rehearsal).
- """
+ """Strip tool-call markup from one non-``<think>`` segment. The single definition of the scan
+ order, shared by the GGUF and safetensors paths. ``routes/inference.py`` keeps a deliberately
+ different order for the passthrough path, pinned by ``tests/test_route_strip_drift.py``.
+ ``seg_final`` enables the end-of-turn arms (markerless Gemma, open tails, trailing partial
+ rehearsal)."""
seg = _strip_mistral_closed_calls(segment)
# Bare rehearsal ``name[ARGS]{json}`` and the Mistral name form, through the shared balanced scan. Name-gated: an
# inactive ``foo[ARGS]{..}`` is prose and is kept.
@@ -1485,8 +1455,8 @@ def strip_segment(
seg = _strip_gemma_wrapperless_calls(seg, enabled_tool_names)
# Scan, not regex, so a literal ``<function=...>`` inside a value stays data.
seg = _strip_function_xml_calls(seg, final = seg_final)
- # GLM 4.x: scan to the call's real </tool_call>, so a literal one inside a value is data. Qwen <tool_call>{json} is
- # left to the regex arms.
+ # GLM 4.x: scan to the call's real </tool_call>, so a literal one inside a value is data. Qwen <tool_call>{json}
+ # is left to the regex arms.
seg = _strip_glm_calls(seg, final = seg_final)
pats = _TOOL_ALL_PATS if seg_final else _TOOL_CLOSED_PATS
required_pairs = (
@@ -1510,8 +1480,8 @@ def strip_segment(
continue
scan_end = last_close + len(token)
if pat_idx == 3:
- # The Mistral array arm keeps consuming an optional ``\s*</s>`` PAST the ``]`` the bound is taken from;
- # without this the EOS survives
+ # The Mistral array arm keeps consuming an optional ``\s*</s>`` PAST the ``]`` the bound is taken
+ # from; without this the EOS survives
eos = scan_end
while eos < len(seg) and seg[eos].isspace():
eos += 1
@@ -1539,13 +1509,11 @@ def strip_tool_markup(
final: bool = False,
enabled_tool_names: Optional[set] = None,
) -> str:
- """Strip tool-call markup. ``final=False`` keeps in-progress markup buffered;
- ``final=True`` also drops trailing unclosed runs and trims.
-
- ``enabled_tool_names`` gates the name-conditioned forms so a disabled/example name in
- prose is kept (mirrors the parser gate): the bare reasoning-rehearsal ``name[ARGS]{...}``
- and the markerless Gemma ``call:NAME{...}`` strip. ``None`` strips every closed call.
- """
+ """Strip tool-call markup. ``final=False`` keeps in-progress markup buffered; ``final=True``
+ also drops trailing unclosed runs and trims. ``enabled_tool_names`` gates the
+ name-conditioned forms so a disabled/example name in prose is kept (mirrors the parser gate):
+ the bare reasoning-rehearsal ``name[ARGS]{...}`` and the markerless Gemma ``call:NAME{...}``
+ strip. ``None`` strips every closed call."""
if final:
# Drop a leading Magistral ``[THINK]...[/THINK]`` at end-of-turn; its bracket form is not the ``<think>`` the
# reasoning channel renders.
@@ -1558,9 +1526,9 @@ def strip_tool_markup(
enabled_tool_names = enabled_tool_names,
)
- # ``<think>`` / ``[THINK]`` reasoning is preserved verbatim (a rehearsed call inside it is not executed, so it must
- # not be stripped from display either); a literal think marker inside a real call's arguments is that call's data
- # and is stripped with the call.
+ # ``<think>`` / ``[THINK]`` reasoning is preserved verbatim (a rehearsed call inside it is not executed, so it
+ # must not be stripped from display either); a literal think marker inside a real call's arguments is that call's
+ # data and is stripped with the call.
# A blocked call's body is quoted prose: hide it from the passes, then put it back.
masked, bodies = _mask_blocked_bodies(text, enabled_tool_names)
result = _tool_healing.strip_outside_think(masked, _strip_segment)
@@ -1621,16 +1589,14 @@ def _first_sentinel(
start: int,
enabled_tool_names = None,
) -> int:
- """Lowest index >= ``start`` at which any strip sentinel occurs, or -1.
-
- ``call`` is the one sentinel that is also an ordinary English word, and treating every
- "I will call the tool" as markup would put the full strip back on the per-token path for
- plain prose. It is therefore confirmed against the arm it stands for: the whole
- ``call:NAME{`` anchor with a name the strip would remove, or a partial the next token could
- complete (``_GEMMA_BARE_TC_PREFIX_RE``; the name is incomplete, so it cannot be gated yet).
- Every append is checked, so a call arriving a character at a time is caught while partial.
- A complete non-promotable call is prose; counting it would re-strip every token of a long
- quoted one."""
+ """Lowest index >= ``start`` at which any strip sentinel occurs, or -1. ``call`` is the one
+ sentinel that is also an ordinary English word, and treating every "I will call the tool" as
+ markup would put the full strip back on the per-token path for plain prose. It is therefore
+ confirmed against the arm it stands for: the whole ``call:NAME{`` anchor with a name the strip
+ would remove, or a partial the next token could complete (``_GEMMA_BARE_TC_PREFIX_RE``; the name
+ is incomplete, so it cannot be gated yet). Every append is checked, so a call arriving a
+ character at a time is caught while partial. A complete non-promotable call is prose; counting
+ it would re-strip every token of a long quoted one."""
best = -1
for sentinel in _STRIP_SENTINELS:
if sentinel == _GEMMA_BARE_SENTINEL:
@@ -1653,22 +1619,17 @@ def _first_sentinel(
def _is_provisional_call(text: str, found: int) -> bool:
"""True when ``found`` is a ``call`` that only qualifies while it ends the buffer.
-
- ``_first_sentinel`` accepts such a hit because the next token may complete it, but
- the acceptance has to expire: the word ``call`` at a token boundary would otherwise
- pin the scan and put the full strip back on every later token.
- """
+ ``_first_sentinel`` accepts such a hit because the next token may complete it, but the
+ acceptance has to expire: the word ``call`` at a token boundary would otherwise pin the scan
+ and put the full strip back on every later token."""
return text.startswith(_GEMMA_BARE_SENTINEL, found) and not _GEMMA_BARE_TC_RE.match(text, found)
def _unmatched_think_closer(text: str, start: int = 0) -> int:
- """Lowest index >= ``start`` of a reasoning closer with no opener ahead of it, or -1.
-
- A stray closer is what a prefilled reasoning turn looks like, and
- ``strip_outside_think`` handles it by synthesising a span that begins at offset 0 of
- the segment. Anything that changes where offset 0 sits therefore has to leave such a
- segment alone.
- """
+ """Lowest index >= ``start`` of a reasoning closer with no opener ahead of it, or -1. A stray
+ closer is what a prefilled reasoning turn looks like, and ``strip_outside_think`` handles it
+ by synthesising a span that begins at offset 0 of the segment, so anything that changes where
+ offset 0 sits has to leave such a segment alone."""
best = -1
for opener, closer in (("<think>", "</think>"), ("[THINK]", "[/THINK]")):
close_at = text.find(closer, start)
@@ -1685,24 +1646,17 @@ def _unmatched_think_closer(text: str, start: int = 0) -> int:
def _safe_cut(text: str, first: int) -> int:
"""Largest index <= ``first`` that no strip decision can depend on text before.
- Every arm anchors on a sentinel, so a match cannot begin before the first sentinel --
- with two exceptions, both of which reach backwards:
-
- * the rehearsal form is ``NAME[ARGS]{...}``, whose match starts at the name, before
- its ``[ARGS]`` sentinel. A name contains no whitespace, so backing up to the start
- of the preceding run covers it. (``[TOOL_CALLS] NAME[ARGS]`` needs no wider window:
- ``[TOOL_CALLS]`` is itself a sentinel, so it would be the first one found.)
- * the ``[TOOL_CALLS]`` and ``[ARGS]`` arms are gated on markdown code spans, and an
- opening fence can sit arbitrarily far back. If any backtick or tilde precedes the
- cut, no cut is safe.
-
- (The markerless Gemma arm reaches back to the start of the segment as well, but is
- handled by its caller rather than here: see ``StreamingMarkupStripper.strip``.)
-
- The result is then snapped back to a line start. The code-fence pattern is anchored
- with ``^``, so cutting mid-line can turn a fence that was mid-line into one that opens
- a block -- which flips the in-code gate and changes the output. Snapping to a newline
- keeps ``^`` meaning the same thing on the slice as on the whole buffer.
+ Every arm anchors on a sentinel, so a match cannot begin before the first sentinel, with two
+ exceptions that reach backwards. The rehearsal form is ``NAME[ARGS]{...}``, whose match starts
+ at the name, before its ``[ARGS]`` sentinel; a name contains no whitespace, so backing up to the
+ start of the preceding run covers it. And the ``[TOOL_CALLS]`` / ``[ARGS]`` arms are gated on
+ markdown code spans, where an opening fence can sit arbitrarily far back, so if any backtick or
+ tilde precedes the cut, no cut is safe. (The markerless Gemma arm reaches back to the start of
+ the segment too, but is handled by ``StreamingMarkupStripper.strip``.)
+
+ The result is then snapped back to a line start: the code-fence pattern is anchored with ``^``,
+ so cutting mid-line can turn a fence that was mid-line into one that opens a block, flipping the
+ in-code gate.
"""
if first <= 0:
return 0
@@ -1721,9 +1675,9 @@ def _safe_cut(text: str, first: int) -> int:
close_at = _unmatched_think_closer(text)
if 0 <= close_at and first < close_at:
return 0
- # ``_strip_function_xml_calls`` treats a ``<function>`` opener inside an unclosed ``<parameter>`` as a literal in an
- # argument value, and decides that from the text before it. Cutting there loses the context and the nested markup
- # leaks into the display. The literal test keeps the common case off the scan.
+ # ``_strip_function_xml_calls`` treats a ``<function>`` opener inside an unclosed ``<parameter>`` as a literal in
+ # an argument value, and decides that from the text before it. Cutting there loses the context and the nested
+ # markup leaks into the display. The literal test keeps the common case off the scan.
if "<param" in head and _inside_open_parameter(text, cut):
return 0
return cut
@@ -1732,26 +1686,22 @@ def _safe_cut(text: str, first: int) -> int:
class StreamingMarkupStripper:
"""Strip tool markup from an append-only buffer without rescanning it every token.
- The streaming display path used to call the full strip on the entire accumulated
- response once per content token, which is a linear scan with ~10 regex passes per
- token and therefore quadratic in the response length. Two properties make that
- avoidable, both asserted by ``test_refactor_guard.py``:
-
- * text containing no sentinel from ``_STRIP_SENTINELS`` is returned unchanged, so a
- prose-only response does no regex work at all; and
- * no arm can match before the first sentinel, so
- ``strip(text) == text[:first] + strip(text[first:])``.
-
- The scan for that first sentinel resumes where the previous call stopped (overlapping
- by ``_SENTINEL_MAX_LEN - 1`` so a sentinel split across two appends is still seen),
- which makes the pre-markup phase amortized constant per token rather than linear.
-
- The instance assumes append-only growth: one instance per buffer, appended to, with
- ``reset()`` before a new buffer. A shorter buffer, or one whose sampled head, middle
- or previous tail no longer matches, re-derives the state, so an ordinary rewind is
- handled. That check samples rather than compares in full, because comparing in full
- would be linear in the buffer and reintroduce the cost this class removes, so it is a
- guard against misuse rather than a guarantee for arbitrary call sequences.
+ The streaming display path used to call the full strip on the entire accumulated response once
+ per content token, which is a linear scan with ~10 regex passes per token and therefore
+ quadratic in the response length. Two properties make that avoidable, both asserted by
+ ``test_refactor_guard.py``: text containing no sentinel from ``_STRIP_SENTINELS`` is returned
+ unchanged, so a prose-only response does no regex work at all; and no arm can match before the
+ first sentinel, so ``strip(text) == text[:first] + strip(text[first:])``. The scan for that
+ first sentinel resumes where the previous call stopped (overlapping by ``_SENTINEL_MAX_LEN - 1``
+ so a sentinel split across two appends is still seen), which makes the pre-markup phase
+ amortized constant per token rather than linear.
+
+ The instance assumes append-only growth: one instance per buffer, appended to, with ``reset()``
+ before a new buffer. A shorter buffer, or one whose sampled head, middle or previous tail no
+ longer matches, re-derives the state, so an ordinary rewind is handled. That check samples
+ rather than compares in full, because comparing in full would be linear in the buffer and
+ reintroduce the cost this class removes, so it is a guard against misuse rather than a guarantee
+ for arbitrary call sequences.
"""
__slots__ = (
@@ -1779,8 +1729,8 @@ class StreamingMarkupStripper:
):
self._enabled_tool_names = enabled_tool_names
# Whether the last segment gets the end-of-turn arms. The tool-generation loop wants them (partial markup must
- # never render); the final-answer loop strips with ``final = False`` and does not. The incremental machinery is
- # the same either way: fewer arms on the same sentinels, and ``_safe_cut``'s guards stay a superset.
+ # never render); the final-answer loop strips with ``final = False`` and does not. The incremental machinery
+ # is the same either way: fewer arms on the same sentinels, and ``_safe_cut``'s guards stay a superset.
self._seg_final = seg_final
self._reset()
@@ -1808,20 +1758,17 @@ class StreamingMarkupStripper:
def _think_block(self, text: str, first: int) -> str:
"""Classify the reasoning block opening at absolute offset ``first``.
- Returns ``"settled"`` when a complete, unambiguous block was folded into the
- settled prefix, ``"open"`` when a clean block is still streaming (its content is
- preserved verbatim, so the whole buffer is currently unchanged), or ``""`` when
- the shape is anything else and the full strip has to run.
-
- ``strip_outside_think`` already processes each segment in isolation, so a segment
- boundary is a point nothing downstream can reach back across -- unlike a cut inside
- a segment, which is why this needs neither the line-start snap nor the backtick
- check that ``_safe_cut`` does.
-
- Deliberately conservative: it only fires on a block whose opener is the first
- sentinel in the remaining text and whose body carries no other markup. A
- ``</think>`` sitting inside a call's arguments is that call's data, not a closer,
- and this refuses to guess about it.
+ Returns ``"settled"`` when a complete, unambiguous block was folded into the settled prefix,
+ ``"open"`` when a clean block is still streaming (its content is preserved verbatim, so the
+ whole buffer is currently unchanged), or ``""`` when the shape is anything else and the full
+ strip has to run.
+
+ ``strip_outside_think`` already processes each segment in isolation, so a segment boundary
+ is a point nothing downstream can reach back across -- unlike a cut inside a segment, which
+ is why this needs neither the line-start snap nor the backtick check that ``_safe_cut``
+ does. Deliberately conservative: it only fires on a block whose opener is the first sentinel
+ in the remaining text and whose body carries no other markup, since a ``</think>`` sitting
+ inside a call's arguments is that call's data.
"""
for opener, closer in (("<think>", "</think>"), ("[THINK]", "[/THINK]")):
if text.startswith(opener, first):
@@ -1867,18 +1814,14 @@ class StreamingMarkupStripper:
def _needs_whole_buffer(self, text: str) -> bool:
"""True when no split of ``text`` is safe and the strip has to see all of it.
- Two shapes reach back to the start of a segment rather than to their own anchor:
-
- * the markerless Gemma arm keeps a whole-JSON or leading-JSON answer's
- ``call:NAME{...}`` examples visible as data, and earlier arms can leave behind
- a trimmed segment that is whole JSON when the untrimmed one was not; and
- * a reasoning closer with no opener, which makes offset 0 of the segment the
- thing ``_think_spans_outside_tool_markup`` decides from.
-
- Either way a split can delete text out of the user's answer, so the buffer is
- stripped whole instead. That is the pre-change cost, paid only by a buffer that
- actually holds one of these -- and only once markup is present, since this runs
- after the sentinel scan rather than in front of it.
+ Two shapes reach back to the start of a segment rather than to their own anchor: the
+ markerless Gemma arm, which keeps a whole-JSON or leading-JSON answer's ``call:NAME{...}``
+ examples visible as data (and earlier arms can leave behind a trimmed segment that is whole
+ JSON when the untrimmed one was not); and a reasoning closer with no opener, which makes
+ offset 0 of the segment the thing ``_think_spans_outside_tool_markup`` decides from. Either
+ way a split can delete text out of the user's answer, so the buffer is stripped whole
+ instead. That is the pre-change cost, paid only by a buffer that actually holds one of
+ these, and only once markup is present.
"""
return _promotable_gemma_call_pos(text, self._floor, self._enabled_tool_names) >= 0 or (
self._floor > 0 and _unmatched_think_closer(text, self._floor) >= 0
@@ -1905,28 +1848,21 @@ class StreamingMarkupStripper:
return restored if restored is not None else _tool_healing.strip_outside_think(text, _seg)
def reset(self):
- """Drop every cached prefix, for a caller starting a new buffer.
-
- The streaming caller keeps one instance for the whole request but begins a fresh
- ``cumulative_display`` in each tool iteration. ``_is_extension`` samples the ends
- rather than comparing, deliberately, so it cannot be relied on to notice: two
- buffers agreeing on a length and 64 bytes at each end are accepted, and the scan
- then resumes at an offset belonging to the previous iteration and never looks
- below it again. Saying so explicitly costs nothing and makes the sampled check
- exact for that caller, since within an iteration every mutation is an append.
- """
+ """Drop every cached prefix, for a caller starting a new buffer. The streaming caller keeps
+ one instance for the whole request but begins a fresh ``cumulative_display`` in each tool
+ iteration, and ``_is_extension`` samples the ends rather than comparing, so it cannot be
+ relied on to notice: two buffers agreeing on a length and 64 bytes at each end are
+ accepted, and the scan then resumes at an offset belonging to the previous iteration and
+ never looks below it again."""
self._reset()
def _note(self, text: str):
- """Record what this call saw, as measurements rather than as the buffer.
-
- Holding a reference to the caller's string is what makes this expensive: the
- streaming loop grows it with ``cumulative_display += token``, and CPython can
- only resize a string in place while nothing else refers to it. One extra
- reference turns every append into a full copy, so the concatenation goes
- quadratic even though the scanning here does not. Measured over an append-only
- loop at 64k tokens: 1.14s holding the buffer, 0.003s holding these three.
- """
+ """Record what this call saw, as measurements rather than as the buffer. Holding a reference
+ to the caller's string is what makes this expensive: the streaming loop grows it with
+ ``cumulative_display += token``, and CPython can only resize a string in place while
+ nothing else refers to it, so one extra reference turns every append into a full copy and
+ the concatenation goes quadratic even though the scanning here does not. Measured over an
+ append-only loop at 64k tokens: 1.14s holding the buffer, 0.003s holding these three."""
self._seen_len = len(text)
# A buffer at or under the sample size aliases itself here. Harmless: the copy that forces is bounded by the
# sample size.
@@ -1938,16 +1874,15 @@ class StreamingMarkupStripper:
def _is_extension(self, text: str) -> bool:
"""Cheap check that ``text`` continues the previous call's buffer.
- A full ``startswith`` would be linear in the buffer and so reintroduce the
- quadratic cost this class exists to remove, so this samples three fixed windows
- instead: the head, the middle, and the previous buffer's last bytes. All three
- are O(1) and all three must still match.
+ A full ``startswith`` would be linear in the buffer and so reintroduce the quadratic cost
+ this class exists to remove, so this samples three fixed windows instead: the head, the
+ middle, and the previous buffer's last bytes. All three are O(1) and all three must still
+ match.
- This is a guard against obvious misuse, not a proof. Two different buffers that
- agree on all three windows and on length would still be taken for a continuation;
- the middle window exists because head and tail alone missed the case where only
- the middle changed. The contract remains: one instance per buffer, appended to,
- and ``reset()`` before a new one. Both callers in this repo do exactly that.
+ This is a guard against obvious misuse, not a proof. Two different buffers that agree on all
+ three windows and on length would still be taken for a continuation; the middle window
+ exists because head and tail alone missed the case where only the middle changed. The
+ contract remains: one instance per buffer, appended to, and ``reset()`` before a new one.
"""
end = self._seen_len
if end < 0:
@@ -2012,8 +1947,8 @@ class StreamingMarkupStripper:
# streaming, so re-deriving keeps the cut exact.
cut = _safe_cut(tail, self._first)
# After the cut, not before: with nothing settled and nothing to trim, the whole-buffer strip below already is
- # the split one, so these two scans would decide nothing and an answer with markup near its front would pay them
- # per token.
+ # the split one, so these two scans would decide nothing and an answer with markup near its front would pay
+ # them per token.
if (cut or self._floor) and self._needs_whole_buffer(text):
out = self._full_strip(text)
self._note(text)
@@ -2026,9 +1961,9 @@ class StreamingMarkupStripper:
def _unchanged(self, text: str) -> str:
"""Result when nothing after the settled prefix needs stripping."""
self._note(text)
- # With nothing removed the answer is the caller's own string, so hand it straight back rather than rebuilding it
- # a token at a time. Returned, not kept: holding a reference is exactly what would stop the caller growing it in
- # place.
+ # With nothing removed the answer is the caller's own string, so hand it straight back rather than rebuilding
+ # it a token at a time. Returned, not kept: holding a reference is exactly what would stop the caller growing
+ # it in place.
return text if self._floor_identity else self._floor_out + text[self._floor :]
@@ -2043,7 +1978,7 @@ _EMBEDDED_MARKER_RE = re.compile(
)
# Covers ``<function=NAME>`` and the attribute form. ``<|python_tag|>`` is Llama-3's envelope too (built-in
# ``NAME.call(`` and custom ``{json}``), so a quoted DeepSeek/Kimi example is data; the call-shaped lookahead mirrors
-# the ``_TOOL_ALL_PATS`` python_tag arm so a bare prose ``<|python_tag|>`` mention isn't treated as one.
+# the ``_TOOL_ALL_PATS`` python_tag arm so a bare prose ``<|python_tag|>`` mention is not treated as one.
_OUTER_ENVELOPE_OPEN_RE = re.compile(
r'<tool_call>|<function(?:=|\s+name=")|<\|tool_call>'
r"|<\|python_tag\|>(?=\s*(?:\{|[A-Za-z_][\w.]*\())"
@@ -2076,7 +2011,7 @@ def _marker_inside_leading_envelope(content: str, enabled_tool_names: Optional[s
# example (same rule as the XML envelopes below).
return True
if name is not None and first_marker.start() <= end:
- # A disabled-name leading object is prose (can't own the turn), but a marker inside its own strings
+ # A disabled-name leading object is prose (cannot own the turn), but a marker inside its own strings
# stays data. A marker AFTER it falls through to the pre-pass.
return True
elif content.startswith(_MISTRAL_TRIGGER, i):
@@ -2116,8 +2051,8 @@ def _marker_inside_leading_envelope(content: str, enabled_tool_names: Optional[s
marker = _EMBEDDED_MARKER_RE.search(residue)
if marker is None:
return True
- # A marker still stands; any opener left in the residue is UNCLOSED. One before the marker is a truncated outer call
- # holding the marker as data: skip the pre-pass.
+ # A marker still stands; any opener left in the residue is UNCLOSED. One before the marker is a truncated outer
+ # call holding the marker as data: skip the pre-pass.
opener = _OUTER_ENVELOPE_OPEN_RE.search(residue)
return opener is not None and opener.start() < marker.start()
@@ -2128,9 +2063,9 @@ def _mistral_region_end(
*,
open_envelope_runs_to_eof: bool = False,
) -> int | None:
- """Exclusive end of the balanced ``[TOOL_CALLS]`` call starting at ``idx``,
- or ``None`` when truncated/unrecognised (same shapes as the strip scan:
- array, single-object, and named ``name [CALL_ID]? [ARGS]? {json}``).
+ """Exclusive end of the balanced ``[TOOL_CALLS]`` call starting at ``idx``, or ``None`` when
+ truncated/unrecognised (same shapes as the strip scan: array, single-object, and named ``name
+ [CALL_ID]? [ARGS]? {json}``).
``open_envelope_runs_to_eof`` treats a still-streaming ``[``/``{`` envelope as reaching EOF.
``_parse_mistral_tool_calls`` accepts that form under allow_incomplete, so refusing it here
@@ -2167,7 +2102,9 @@ def _mistral_region_end(
def _xml_signal_inside_leading_mistral(content: str) -> bool:
- """True when a parseable Mistral call is the first tool emission in document order: it owns the turn, so later XML (quoted in its arguments or in trailing prose) is not promoted over it. A signal BEFORE the trigger keeps normal order."""
+ """True when a parseable Mistral call is the first tool emission in document order: it owns the
+ turn, so later XML (quoted in its arguments or in trailing prose) is not promoted over it. A
+ signal BEFORE the trigger keeps normal order."""
trig = content.find(_MISTRAL_TRIGGER)
if trig < 0:
return False
@@ -2219,8 +2156,8 @@ _ATTR_FUNC_OPEN_RE = re.compile(r'<function\s+name="')
def _first_foreign_tool_signal(content: str) -> int | None:
- """Offset of the first tool signal a non-envelope parser would fire on
- (XML forms plus ``<|python_tag|>``, which also runs before the Mistral parser)."""
+ """Offset of the first tool signal a non-envelope parser would fire on (XML forms plus
+ ``<|python_tag|>``, which also runs before the Mistral parser)."""
first = None
for sig in ("<tool_call>", "<|tool_call>", "<function=", "<|python_tag|>"):
p = content.find(sig)
@@ -2229,8 +2166,9 @@ def _first_foreign_tool_signal(content: str) -> int | None:
attr = _ATTR_FUNC_OPEN_RE.search(content)
if attr is not None and (first is None or attr.start() < first):
first = attr.start()
- # DeepSeek/Kimi markers are foreign to a JSON envelope too: a marker inside a leading object routes through the same
- # guard (and, if disabled, the drop-and-parse-the-tail recursion, so a real call after the object is still reached).
+ # DeepSeek/Kimi markers are foreign to a JSON envelope too: a marker inside a leading object routes through the
+ # same guard (and, if disabled, the drop-and-parse-the-tail recursion, so a real call after the object is still
+ # reached).
marker = _EMBEDDED_MARKER_RE.search(content)
if marker is not None and (first is None or marker.start() < first):
first = marker.start()
@@ -2238,9 +2176,9 @@ def _first_foreign_tool_signal(content: str) -> int | None:
def _xml_signal_inside_leading_bare_json(content: str) -> bool:
- """True when the first foreign tool signal is a quoted literal inside a
- LEADING bare-JSON call object or JSON answer -- data, not a real call
- (sibling of ``_xml_signal_inside_leading_mistral``)."""
+ """True when the first foreign tool signal is a quoted literal inside a LEADING bare-JSON call
+ object or JSON answer -- data, not a real call (sibling of
+ ``_xml_signal_inside_leading_mistral``)."""
i = 0
n = len(content)
while i < n and content[i] in " \t\n\r":
@@ -2283,10 +2221,10 @@ def _xml_signal_inside_leading_bare_json(content: str) -> bool:
def _signal_inside_leading_wrapperless_gemma(
content: str, enabled_tool_names: Optional[set]
) -> bool:
- """True when the first foreign tool signal is a quoted literal inside (or after) a
- LEADING promotable wrapper-less Gemma call (sibling of the Mistral/bare-JSON leading
- guards). Markerless form, so a non-promotable name is skipped as prose; ``None`` keeps
- the name-agnostic behaviour for non-execution names."""
+ """True when the first foreign tool signal is a quoted literal inside (or after) a LEADING
+ promotable wrapper-less Gemma call (sibling of the Mistral/bare-JSON leading guards). Markerless
+ form, so a non-promotable name is skipped as prose; ``None`` keeps the name-agnostic behaviour
+ for non-execution names."""
first = _first_foreign_tool_signal(content)
trig = content.find(_MISTRAL_TRIGGER)
if trig >= 0 and (first is None or trig < first):
@@ -2342,10 +2280,10 @@ def _inside_leading_markerless_body(
def _disabled_gemma_call_end_containing_signal(
content: str, enabled_tool_names: Optional[set]
) -> int | None:
- """End offset (exclusive) of the earliest PROSE (non-promotable) wrapper-less Gemma
- call whose balanced body holds the first foreign signal, else None. A prose name makes
- the quoted literal data, so the caller drops the span and recurses on the tail; a
- promotable call defers to the enabled-call guard."""
+ """End offset (exclusive) of the earliest PROSE (non-promotable) wrapper-less Gemma call whose
+ balanced body holds the first foreign signal, else None. A prose name makes the quoted literal
+ data, so the caller drops the span and recurses on the tail; a promotable call defers to the
+ enabled-call guard."""
first = _first_foreign_tool_signal(content)
trig = content.find(_MISTRAL_TRIGGER)
if trig >= 0 and (first is None or trig < first):
@@ -2376,14 +2314,12 @@ def parse_tool_calls_from_text(
enabled_tool_names: Optional[set] = None,
) -> list[dict]:
"""Return OpenAI-format tool calls, first-match wins so calls are never double-counted.
-
- ``allow_incomplete=True`` (default) heals truncated calls (missing close tag /
- unclosed parameter); ``False`` accepts only well-formed closed calls (trailing
- prose tolerated), matching llama-server's strict path when Auto-Heal is off.
-
- ``enabled_tool_names`` gates only the markerless Llama-3.2 bare-JSON form (the
- marker-based forms carry an explicit signal, so a disabled-tool name there is a
- real call attempt). ``None`` keeps the name-agnostic behaviour."""
+ ``allow_incomplete=True`` (default) heals truncated calls (missing close tag / unclosed
+ parameter); ``False`` accepts only well-formed closed calls (trailing prose tolerated),
+ matching llama-server's strict path when Auto-Heal is off. ``enabled_tool_names`` gates only
+ the markerless Llama-3.2 bare-JSON form (the marker-based forms carry an explicit signal, so
+ a disabled-tool name there is a real call attempt); ``None`` keeps the name-agnostic
+ behaviour."""
# Drop Magistral [THINK]...[/THINK] BEFORE dispatch: a rehearsed call inside it must never be promoted, and the
# parse path must agree with the display strip.
content = _strip_mistral_reasoning(content)
@@ -2392,9 +2328,9 @@ def parse_tool_calls_from_text(
# call's arguments are quoted prose, and a wrapped call nested there was promoted.
content, _blocked_bodies = _mask_blocked_bodies(content, enabled_tool_names, think = True)
- # A leading bare-JSON value is decided FIRST: a string argument quoting tool markup (XML or a Mistral trigger) must
- # stay data, so the bare-JSON parser takes the outer call before any other pass. Precedes the Mistral guard, whose
- # preamble tolerance would otherwise claim a trigger quoted inside the leading object.
+ # A leading bare-JSON value is decided FIRST: a string argument quoting tool markup (XML or a Mistral trigger)
+ # must stay data, so the bare-JSON parser takes the outer call before any other pass. Precedes the Mistral guard,
+ # whose preamble tolerance would otherwise claim a trigger quoted inside the leading object.
if _xml_signal_inside_leading_bare_json(content):
calls = _parse_llama3_bare_json(
content, id_offset = id_offset, enabled_tool_names = enabled_tool_names
@@ -2444,8 +2380,8 @@ def parse_tool_calls_from_text(
)
if calls:
# A bare rehearsal ``name[ARGS]{..}`` after the Mistral call is a peer tool call, not foreign XML the
- # owns-the-turn guard protects against: promote it too so a Mistral call and a rehearsal in one message both
- # parse.
+ # owns-the-turn guard protects against: promote it too so a Mistral call and a rehearsal in one message
+ # both parse.
calls.extend(
_parse_bare_rehearsals(
content,
@@ -2458,7 +2394,7 @@ def parse_tool_calls_from_text(
# DeepSeek/Kimi markers are unique, so try them first -- unless an outer envelope opens before the first marker
# (then the marker is argument data).
if not _marker_inside_leading_envelope(content, enabled_tool_names):
- # Dispatch by earliest opener so a quoted DS example inside a Kimi call (or vice versa) can't hijack the turn
+ # Dispatch by earliest opener so a quoted DS example inside a Kimi call (or vice versa) cannot hijack the turn
# via fixed parser order
_ds = _DEEPSEEK_BEGIN_RE.search(content)
_ds_pos = _ds.start() if _ds else len(content)
@@ -2475,9 +2411,9 @@ def parse_tool_calls_from_text(
if calls:
return calls
- # A leading MiniCPM/MiniMax attribute-form call owns the turn: tool_healing doesn't know the <function name="...">
- # wrapper, so a <tool_call> quoted in its parameter would beat the outer call. Any earlier signal keeps normal
- # order.
+ # A leading MiniCPM/MiniMax attribute-form call owns the turn: tool_healing does not know the <function
+ # name="..."> wrapper, so a <tool_call> quoted in its parameter would beat the outer call. Any earlier signal
+ # keeps normal order.
attr = _ATTR_FUNC_OPEN_RE.search(content)
if attr is not None:
first_other = None
@@ -2531,10 +2467,10 @@ def parse_tool_calls_from_text(
if calls:
return calls
- # Qwen/Hermes, Qwen3.5 XML, Gemma 4, plus Mistral [TOOL_CALLS] / bare rehearsal ``name[ARGS]{json}`` use the shared
- # tool_healing parser (strict/Auto-Heal contract + nested-marker, trailing-prose, and ``<|"|>`` quoted-string
- # handling the GGUF path relies on). ``enabled_tool_names`` gates the ambiguous bare-rehearsal form so an inactive
- # ``foo[ARGS]{..}`` stays prose.
+ # Qwen/Hermes, Qwen3.5 XML, Gemma 4, plus Mistral [TOOL_CALLS] / bare rehearsal ``name[ARGS]{json}`` use the
+ # shared tool_healing parser (strict/Auto-Heal contract + nested-marker, trailing-prose, and ``<|"|>``
+ # quoted-string handling the GGUF path relies on). ``enabled_tool_names`` gates the ambiguous bare-rehearsal form
+ # so an inactive ``foo[ARGS]{..}`` stays prose.
calls = _tool_healing.parse_tool_calls_from_text(
content,
id_offset = id_offset,
@@ -2545,9 +2481,9 @@ def parse_tool_calls_from_text(
return calls
# Formats tool_healing does not cover; these run only after it finds nothing, so a strict-rejected call is never
- # re-healed here. Blank any JSON/Gemma marker coverage first: markup inside a marker's span (even one that failed to
- # parse) is that call's data, not a sibling, so a nested ``<function=...>`` / ``<|python_tag|>`` / ``[TOOL_CALLS]``
- # must not be promoted.
+ # re-healed here. Blank any JSON/Gemma marker coverage first: markup inside a marker's span (even one that failed
+ # to parse) is that call's data, not a sibling, so a nested ``<function=...>`` / ``<|python_tag|>`` /
+ # ``[TOOL_CALLS]`` must not be promoted.
fallback_content = content
coverage = _tool_healing.marker_coverage(content)
if coverage:
@@ -2566,8 +2502,8 @@ def parse_tool_calls_from_text(
if calls:
return calls
- # Llama-3.2 bare ``{"name":..., "parameters":...}`` (strict shape). Only a LEADING call object matches and owns the
- # turn, so an enabled ``call:NAME{...}`` in its arguments stays data (Gemma never starts ``{``).
+ # Llama-3.2 bare ``{"name":..., "parameters":...}`` (strict shape). Only a LEADING call object matches and owns
+ # the turn, so an enabled ``call:NAME{...}`` in its arguments stays data (Gemma never starts ``{``).
calls = _parse_llama3_bare_json(
fallback_content, id_offset = id_offset, enabled_tool_names = enabled_tool_names
)
@@ -2630,12 +2566,11 @@ _trim_param_value = _tool_healing._trim_param_value
def _inside_open_parameter(text: str, pos: int) -> bool:
- """True if ``pos`` sits inside an unclosed ``<parameter>``/``<param>`` block --
- i.e. a ``<function>`` / ``<parameter>`` opener at ``pos`` is a literal inside an
- argument value (e.g. code that prints tool-call XML), not a real nested call.
-
- The healer's algorithm over a wider vocabulary (``<param name="...">`` openers,
- ``</tool_call>`` closers for GLM 4.x / Kimi K2); only that is passed in."""
+ """True if ``pos`` sits inside an unclosed ``<parameter>``/``<param>`` block -- i.e. a
+ ``<function>`` / ``<parameter>`` opener at ``pos`` is a literal inside an argument value
+ (e.g. code that prints tool-call XML), not a real nested call. The healer's algorithm over a
+ wider vocabulary (``<param name="...">`` openers, ``</tool_call>`` closers for GLM 4.x / Kimi
+ K2); only that is passed in."""
return _tool_healing._inside_open_parameter(
text,
pos,
@@ -2665,7 +2600,7 @@ def _parse_function_xml(
body_start = fm.end()
next_func = func_starts[idx + 1].start() if idx + 1 < len(func_starts) else len(content)
# The call ends at the FIRST </function> / </tool_call> not inside an open parameter: a literal close in a
- # code/search argument is skipped as data, and prose after the real close isn't folded into the last argument
+ # code/search argument is skipped as data, and prose after the real close is not folded into the last argument
# (mirrors _strip_function_xml_calls and tool_healing._func_close_index).
close_match = None
for cm in _TC_END_TAG_RE.finditer(content, body_start, next_func):
@@ -2728,8 +2663,8 @@ def _parse_function_xml(
def _llama3_kv_value(body: str, p: int, n: int) -> tuple[Any, int | None]:
- """One ``.call`` value (string/number/true/false/null) at ``body[p:]``.
- Returns ``(value, consumed_len)`` or ``(None, None)`` if none matches."""
+ """One ``.call`` value (string/number/true/false/null) at ``body[p:]``. Returns ``(value,
+ consumed_len)`` or ``(None, None)`` if none matches."""
if p >= n:
return None, None
if body[p] == '"':
@@ -2755,8 +2690,8 @@ def _llama3_kv_value(body: str, p: int, n: int) -> tuple[Any, int | None]:
nm = _LLAMA3_NUM_RE.match(body, p)
if nm:
v = nm.group(0)
- # Scientific notation (1e-3, -2E+4, 0.5e2) and decimals decode as float; a bare integer stays int. ``"." in v``
- # alone missed the exponent forms (1e-3 -> 1).
+ # Scientific notation (1e-3, -2E+4, 0.5e2) and decimals decode as float; a bare integer stays int. ``"." in
+ # v`` alone missed the exponent forms (1e-3 -> 1).
return (float(v) if any(c in v for c in ".eE") else int(v)), nm.end() - p
lm = _LLAMA3_LIT_RE.match(body, p)
if lm:
@@ -2765,8 +2700,8 @@ def _llama3_kv_value(body: str, p: int, n: int) -> tuple[Any, int | None]:
def _parse_llama3_kv_args(body: str) -> dict[str, Any]:
- """``k=v, ...`` kwargs from a ``.call(...)`` body, left to right (later keys win).
- Linear hand-scan replacing the quadratic ``_LLAMA3_KV_RE.finditer`` walk."""
+ """``k=v, ...`` kwargs from a ``.call(...)`` body, left to right (later keys win). Linear
+ hand-scan replacing the quadratic ``_LLAMA3_KV_RE.finditer`` walk."""
args: dict[str, Any] = {}
n = len(body)
i = 0
@@ -2796,16 +2731,15 @@ def _parse_llama3_python_tag(
allow_incomplete: bool = True,
) -> list[dict]:
"""Parse the Llama-3 emissions: ``<|python_tag|>NAME.call(...)`` (built-in),
- ``<|python_tag|>{"name":..., "parameters":...}`` (custom), multi-call via
- ``; ``, ``parameters`` or ``arguments`` key."""
+ ``<|python_tag|>{"name":..., "parameters":...}`` (custom), multi-call via ``; ``,
+ ``parameters`` or ``arguments`` key."""
out: list[dict] = []
if _LLAMA3_PYTHON_TAG not in content:
return out
- # ``NAME.call(...)`` built-in form, anchored to ``<|python_tag|>`` and optionally ``
# 1. ``NAME.call(...)`` built-in form, anchored to ``<|python_tag|>`` and optionally ``; ``-chained within one
- # emission. Anchoring to the tag boundary (not a free scan) keeps a literal ``<|python_tag|>x.call(...)`` quoted in
- # a custom-form JSON argument from being mistaken for a real built-in call.
+ # emission. Anchoring to the tag boundary (not a free scan) keeps a literal ``<|python_tag|>x.call(...)`` quoted
+ # in a custom-form JSON argument from being mistaken for a real built-in call.
pos = content.find(_LLAMA3_PYTHON_TAG)
truncated = False
while pos >= 0 and not truncated:
@@ -2839,7 +2773,6 @@ def _parse_llama3_python_tag(
if depth == 0:
break
i += 1
- # Truncated ``.call(...)`` with no closing paren
# Truncated ``.call(...)`` with no closing paren: reject in strict mode instead of executing a partial.
if not allow_incomplete and depth > 0:
truncated = True
@@ -2864,7 +2797,6 @@ def _parse_llama3_python_tag(
# Past the consumed region: a second ``<|python_tag|>`` may carry more calls.
pos = content.find(_LLAMA3_PYTHON_TAG, i + 1)
- # ``<|python_tag|>{"name":..., "parameters":...}``
# 2. ``<|python_tag|>{"name":..., "parameters":...}``. ``raw_decode`` peels multiple ``; ``-separated objects from
# one emission.
if not out:
@@ -2925,9 +2857,9 @@ _LLAMA3_HEADER_ROLES = ("assistant", "user", "system", "tool", "ipython")
def strip_llama3_leading_sentinels(content: str) -> str:
"""Strip leading Llama-3 special-token sentinels (and the role label after
- ``<|start_header_id|>``) that can leak from a prior turn before a bare-JSON tool
- call. Shared by the parser and the streaming buffering guards so a
- sentinel-prefixed ``{"name":...}`` is recognised the same everywhere."""
+ ``<|start_header_id|>``) that can leak from a prior turn before a bare-JSON tool call. Shared
+ by the parser and the streaming buffering guards so a sentinel-prefixed ``{"name":...}`` is
+ recognised the same everywhere."""
stripped = content.lstrip()
while True:
stripped = stripped.lstrip()
@@ -2954,8 +2886,8 @@ def _parse_llama3_bare_json(
enabled_tool_names: Optional[set] = None,
) -> list[dict]:
"""Llama-3.2 ``custom_tools`` bare ``{"name":.., "parameters":{..}}`` (no ``<|python_tag|>``),
- strict so prose/echoes don't fire. ``enabled_tool_names`` gates on the parsed name so an
- ordinary JSON answer isn't misread as a call to a disabled tool; ``None`` is name-agnostic."""
+ strict so prose/echoes do not fire. ``enabled_tool_names`` gates on the parsed name so an
+ ordinary JSON answer is not misread as a call to a disabled tool; ``None`` is name-agnostic."""
out: list[dict] = []
stripped = strip_llama3_leading_sentinels(content)
if not stripped.startswith("{"):
@@ -3029,8 +2961,8 @@ def _parse_mistral_tool_calls(
id_offset: int,
allow_incomplete: bool = True,
) -> list[dict]:
- """Parse all Mistral emissions: pre-v11 ``[TOOL_CALLS][...]`` / ``[TOOL_CALLS]{...}``
- and v11+ ``[TOOL_CALLS]name{json}`` / ``[TOOL_CALLS]name[ARGS]{json}``."""
+ """Parse all Mistral emissions: pre-v11 ``[TOOL_CALLS][...]`` / ``[TOOL_CALLS]{...}`` and v11+
+ ``[TOOL_CALLS]name{json}`` / ``[TOOL_CALLS]name[ARGS]{json}``."""
out: list[dict] = []
content = _strip_mistral_reasoning(content)
idx = content.find(_MISTRAL_TRIGGER)
@@ -3195,10 +3127,10 @@ def _consume_mistral_call(obj_text: str, out: list[dict], id_offset: int) -> Non
def _whole_content_is_json_value(text: str) -> bool:
- """True when the entire content is one valid JSON value (a structured
- answer, e.g. a response_format turn). Markerless scans must treat text
- inside it as data: an answer documenting an enabled tool's syntax must
- not execute that tool or have the example stripped from display."""
+ """True when the entire content is one valid JSON value (a structured answer, e.g. a
+ response_format turn). Markerless scans must treat text inside it as data: an answer
+ documenting an enabled tool's syntax must not execute that tool or have the example stripped
+ from display."""
t = text.strip()
if t[:1] not in "{[":
return False
@@ -3210,10 +3142,10 @@ def _whole_content_is_json_value(text: str) -> bool:
def _leading_json_value_end(text: str) -> int | None:
- """End index (exclusive) of a balanced LEADING JSON value that parses as
- JSON: a structured answer possibly followed by prose. Markerless scans treat
- its contents as data (extends ``_whole_content_is_json_value``); leading-keyed,
- so a JSON blob mid-prose is not an answer span."""
+ """End index (exclusive) of a balanced LEADING JSON value that parses as JSON: a structured
+ answer possibly followed by prose. Markerless scans treat its contents as data (extends
+ ``_whole_content_is_json_value``); leading-keyed, so a JSON blob mid-prose is not an answer
+ span."""
i = 0
n = len(text)
while i < n and text[i].isspace():
@@ -3238,14 +3170,12 @@ def _parse_gemma_tool_calls(
enabled_tool_names: Optional[set] = None,
) -> list[dict]:
"""Gemma 4: ``<|tool_call>call:NAME{k:<|"|>v<|"|>, ...}<tool_call|>``, plus the
- ``skip_special_tokens`` stream where the wrapper and string markers were
- stripped (bare ``call:NAME{k:v, ...}``).
-
- ``enabled_tool_names`` gates on the parsed name: the wrapper-less shape is indistinguishable
- from prose documenting the syntax, so a disabled/example name must not be stolen as a call
- (``None`` keeps the name-agnostic behaviour). Execution-class and MCP names are never
- promoted here whatever the gate, since a bare call may be attacker-quoted prose; they must
- carry the ``<|tool_call>`` wrapper."""
+ ``skip_special_tokens`` stream where the wrapper and string markers were stripped (bare
+ ``call:NAME{k:v, ...}``). ``enabled_tool_names`` gates on the parsed name: the wrapper-less
+ shape is indistinguishable from prose documenting the syntax, so a disabled/example name must
+ not be stolen as a call (``None`` keeps the name-agnostic behaviour). Execution-class and MCP
+ names are never promoted here whatever the gate, since a bare call may be attacker-quoted prose;
+ they must carry the ``<|tool_call>`` wrapper."""
out: list[dict] = []
# The WRAPPED form (strict + nested-marker handling) is tool_healing's, which runs first: defer content with a
# wrapped opener. A marker literal alone is not enough -- a wrapper-less call mentioning ``<|tool_call>`` would be
@@ -3323,13 +3253,11 @@ _balanced_brace_end = _tool_healing._balanced_brace_end
def _gemma_body_brace_end(text: str, brace_pos: int) -> int | None:
- """Index of the ``}`` closing the wrapper-less Gemma body at ``brace_pos``.
-
- Values are raw after ``skip_special_tokens``, so quoted strings (single or
- double) hide braces; the quote rules mirror ``_gemma_parse_stripped_body`` so
- the boundary always agrees with the body parser. Contextual openers: a single
- quote opens only at value-start context (after ``:{[(,=`` -- apostrophes in
- ``what's the weather`` are prose), a double quote also at word start (so
+ """Index of the ``}`` closing the wrapper-less Gemma body at ``brace_pos``. Values are raw after
+ ``skip_special_tokens``, so quoted strings (single or double) hide braces; the quote rules
+ mirror ``_gemma_parse_stripped_body`` so the boundary always agrees with the body parser.
+ Contextual openers: a single quote opens only at value-start context (after ``:{[(,=``, so
+ apostrophes in ``what's the weather`` are prose), a double quote also at word start (so
``query:find "a, b"`` hides its delimiters)."""
if brace_pos >= len(text) or text[brace_pos] != "{":
return None
@@ -3367,10 +3295,9 @@ _BARE_JSON_NAME_RE = re.compile(r'"name"\s*:\s*"([^"]+)"')
def _top_level_bare_json_name(probe: str) -> Optional[str]:
"""TOP-LEVEL ``"name"`` (or ``"function"`` alias, name wins) of a bare-JSON object, else None.
-
- Skips nested objects/arrays so a nested ``"name"`` isn't mistaken for the call name. A
- truncated tail yields the name found SO FAR (None if none), so the caller keeps text that
- never named a call while a held fragment is still recognised as one."""
+ Skips nested objects/arrays so a nested ``"name"`` is not mistaken for the call name. A
+ truncated tail yields the name found SO FAR (None if none), so the caller keeps text that never
+ named a call while a held fragment is still recognised as one."""
if not probe.startswith("{"):
return None
decoder = json.JSONDecoder()
@@ -3481,12 +3408,11 @@ def _next_top_level_comma(text: str, start: int, end: int) -> "int | None":
def strip_leading_bare_json_call(text: str, enabled_tool_names: Optional[set] = None) -> str:
- """Remove leading Llama-3.2 bare-JSON calls (including a ``;``-chained run)
- that ``strip_tool_markup`` misses; non-call text is unchanged and
- ``enabled_tool_names`` gates like the parser. Consuming the whole chain
- matters because the loops keep this text as next-turn assistant history: a
- leftover executed call would be replayed alongside the structured
- ``tool_calls``."""
+ """Remove leading Llama-3.2 bare-JSON calls (including a ``;``-chained run) that
+ ``strip_tool_markup`` misses; non-call text is unchanged and ``enabled_tool_names`` gates
+ like the parser. Consuming the whole chain matters because the loops keep this text as
+ next-turn assistant history: a leftover executed call would be replayed alongside the
+ structured ``tool_calls``."""
remainder = text
stripped_any = False
# The blocked call-shaped objects the parser skipped, in order, so parse and strip agree.
@@ -3767,11 +3693,11 @@ def _gemma_parse_value(
*,
in_mapping: bool = False,
):
- """Parse one Gemma arg value at ``i`` in a single O(n) forward pass; returns
- ``(value, next_index, closed)``. ``closed`` is False when a string/object/array
- runs off the end without its terminator, so the caller can fall back to raw.
- ``in_mapping`` applies the top-level rule that a comma only ends the value
- when a ``key:`` follows (array elements split on every top-level comma)."""
+ """Parse one Gemma arg value at ``i`` in a single O(n) forward pass; returns ``(value,
+ next_index, closed)``. ``closed`` is False when a string/object/array runs off the end
+ without its terminator, so the caller can fall back to raw. ``in_mapping`` applies the
+ top-level rule that a comma only ends the value when a ``key:`` follows (array elements split
+ on every top-level comma)."""
if text.startswith(_GEMMA_STR_BEGIN, i):
close = text.find(_GEMMA_STR_END, i + len(_GEMMA_STR_BEGIN))
if close < 0:
@@ -3849,8 +3775,8 @@ def _gemma_parse_value(
def _gemma_parse_array(text: str, start: int):
- """Parse a Gemma ``[...]`` array at ``text[start] == '['`` in one forward
- pass; returns ``(list, next_index, closed)``."""
+ """Parse a Gemma ``[...]`` array at ``text[start] == '['`` in one forward pass; returns ``(list,
+ next_index, closed)``."""
items: list[Any] = []
i, n = start + 1, len(text)
while i < n:
@@ -3866,8 +3792,8 @@ def _gemma_parse_array(text: str, start: int):
def _gemma_coerce_scalar(raw: str) -> Any:
- """Coerce an unquoted Gemma value to bool/int/float/None, else keep str
- (quotes stripped first so quoted/unquoted variants compare identical)."""
+ """Coerce an unquoted Gemma value to bool/int/float/None, else keep str (quotes stripped first
+ so quoted/unquoted variants compare identical)."""
raw = raw.strip()
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":
return raw[1:-1]
@@ -3889,8 +3815,8 @@ def _gemma_coerce_scalar(raw: str) -> Any:
def _gemma_strip_quoted_leaves(value: Any) -> Any:
- """Recursively unquote quoted string leaves of a nested stripped-stream value,
- so nested ``city:"New York"`` matches the top-level coercion (no stray quotes)."""
+ """Recursively unquote quoted string leaves of a nested stripped-stream value, so nested
+ ``city:"New York"`` matches the top-level coercion (no stray quotes)."""
if isinstance(value, str):
v = value.strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'":
@@ -3904,10 +3830,10 @@ def _gemma_strip_quoted_leaves(value: Any) -> Any:
def _gemma_parse_stripped_body(body: str) -> dict[str, Any]:
- """Parse a quote-less Gemma arg body ``key:value, key2:value2`` (the
- ``skip_special_tokens`` stream with ``<|"|>`` markers removed). Each value runs
- to the next top-level ``, key:`` boundary, tracking ``{}``/``[]``/``()`` depth so
- commas/braces inside a ``code`` / ``command`` value aren't truncated."""
+ """Parse a quote-less Gemma arg body ``key:value, key2:value2`` (the ``skip_special_tokens``
+ stream with ``<|"|>`` markers removed). Each value runs to the next top-level ``, key:``
+ boundary, tracking ``{}``/``[]``/``()`` depth so commas/braces inside a ``code`` /
+ ``command`` value are not truncated."""
out: dict[str, Any] = {}
i, n = 0, len(body)
while i < n:
@@ -3944,8 +3870,8 @@ def _gemma_parse_stripped_body(body: str) -> dict[str, Any]:
i += 1
raw_val = body[vstart:i].strip()
if raw_val[:1] in "{[":
- # Nested object/array: accept only a fully consumed, closed parse; a truncated/malformed value falls back to
- # the raw string.
+ # Nested object/array: accept only a fully consumed, closed parse; a truncated/malformed value falls back
+ # to the raw string.
parsed, end, closed = _gemma_parse_value(raw_val, 0)
out[key] = (
_gemma_strip_quoted_leaves(parsed)
@@ -3960,9 +3886,8 @@ def _gemma_parse_stripped_body(body: str) -> dict[str, Any]:
def _gemma_parse_mapping(text: str, start: int):
- """Parse a Gemma ``{key:value, ...}`` mapping at ``text[start] == '{'`` in one
- forward pass; returns ``(dict, next_index, closed)`` (``closed`` True iff the
- matching ``}`` was reached)."""
+ """Parse a Gemma ``{key:value, ...}`` mapping at ``text[start] == '{'`` in one forward pass;
+ returns ``(dict, next_index, closed)`` (``closed`` True iff the matching ``}`` was reached)."""
out: dict[str, Any] = {}
i, n = start + 1, len(text)
while i < n:
@@ -4000,12 +3925,9 @@ def _gemma_parse_mapping(text: str, start: int):
return out, i, False
-# ── DeepSeek R1 / V3 / V3.1 ─────────────────────────────────────────
-
-
def _find_outside_json_strings(text: str, needle: str, start: int) -> int:
- """Index of ``needle`` at/after ``start`` OUTSIDE any JSON string, or -1: a
- marker inside an argument string must not be taken as the structural terminator."""
+ """Index of ``needle`` at/after ``start`` OUTSIDE any JSON string, or -1: a marker inside an
+ argument string must not be taken as the structural terminator."""
i = start
n = len(text)
in_string = False
@@ -4037,14 +3959,10 @@ def _parse_deepseek_tool_calls(
id_offset: int,
allow_incomplete: bool = True,
) -> list[dict]:
- """DeepSeek R1 / V3 / V3.1.
-
- R1: ``<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>NAME\\n``\\`\\`\\`json\\n{...}\\n\\`\\`\\`<|tool▁call▁end|>...``
- V3.x: ``<|tool▁calls▁begin|><|tool▁call▁begin|>NAME<|tool▁sep|>{json}<|tool▁call▁end|>...``
-
- Mirrors llama.cpp's pre-autoparser ``common_chat_parse_deepseek_r1`` /
- ``_v3_1`` handling; tolerates the 5 opener variants llama.cpp keeps.
- """
+ """DeepSeek R1 / V3 / V3.1. R1 wraps the arguments in a ```json fence after
+ ``function<|tool_sep|>NAME``; V3.x puts ``NAME<|tool_sep|>{json}`` directly. Mirrors
+ llama.cpp's pre-autoparser ``common_chat_parse_deepseek_r1`` / ``_v3_1`` handling and
+ tolerates the 5 opener variants llama.cpp keeps."""
out: list[dict] = []
begin = _DEEPSEEK_BEGIN_RE.search(content)
if not begin:
@@ -4087,9 +4005,9 @@ def _parse_deepseek_tool_calls(
if not isinstance(args, dict):
pos = brace_end + 1
continue
- # The closing fence + <|tool▁call▁end|> must IMMEDIATELY follow the JSON, else an unbounded search lands on a
- # LATER call's terminator. Absent close: heal past the JSON (strict rejects); later well-formed calls are still
- # kept.
+ # The closing fence + tool-call-end marker must IMMEDIATELY follow the JSON, else an unbounded search lands on
+ # a LATER call's terminator. Absent close: heal past the JSON (strict rejects); later well-formed calls are
+ # still kept.
after = brace_end + 1
while after < len(body) and body[after] in " \t\r\n":
after += 1
@@ -4117,8 +4035,8 @@ def _parse_deepseek_tool_calls(
sep_pos = body.find(_DEEPSEEK_SEP, pos)
if sep_pos < 0:
break
- # Walk left from sep_pos to the name start; stop at ``\n`` (turn boundary), ``<`` (tag start), or ``>`` (end of
- # an optional ``<|tool▁call▁begin|>``).
+ # Walk left from sep_pos to the name start; stop at ``\n`` (turn boundary), ``<`` (tag start), or ``>`` (end
+ # of an optional call-begin marker).
name_start = sep_pos
while name_start > pos and body[name_start - 1] not in "\n<>":
name_start -= 1
@@ -4158,28 +4076,23 @@ def _parse_deepseek_tool_calls(
},
}
)
- # Advance just past the JSON; seeking the optional <|tool▁call▁end|> could land on a LATER call's end marker and
+ # Advance just past the JSON; seeking the optional call-end marker could land on a LATER call's end marker and
# skip the call between
pos = brace_end + 1
return out
-# ── GLM 4.5 / 4.6 / 4.7 ─────────────────────────────────────────────
-
-
def _parse_glm_tool_calls(
content: str,
*,
id_offset: int,
allow_incomplete: bool = True,
) -> list[dict]:
- """GLM 4.5 / 4.6 / 4.7.
-
- ``<tool_call>NAME[\\n]<arg_key>K</arg_key>[\\n]<arg_value>V</arg_value>
- ...</tool_call>``. Multi-call is back-to-back blocks, no envelope.
- Mirrors llama.cpp's GLM 4.x tool-call handling (``common_chat_params_init_glm_4_5``
- plus its generalized XML-style parser, llama.cpp PRs #15904 / #16932).
- """
+ """GLM 4.5 / 4.6 / 4.7:
+ ``<tool_call>NAME[\\n]<arg_key>K</arg_key>[\\n]<arg_value>V</arg_value>...</tool_call>``.
+ Multi-call is back-to-back blocks, no envelope. Mirrors llama.cpp's GLM 4.x tool-call
+ handling (``common_chat_params_init_glm_4_5`` plus its generalized XML-style parser, PRs
+ #15904 / #16932)."""
out: list[dict] = []
pos = 0
while pos < len(content):
@@ -4192,8 +4105,8 @@ def _parse_glm_tool_calls(
args: dict[str, Any] = {}
valid = True
close = -1
- # Walk arg pairs directly against ``content``: a value may contain a literal </tool_call>, so the real close is
- # the </tool_call> before the next <arg_key>. ``str.find`` keeps this linear.
+ # Walk arg pairs directly against ``content``: a value may contain a literal </tool_call>, so the real close
+ # is the </tool_call> before the next <arg_key>. ``str.find`` keeps this linear.
while True:
ks = content.find(_GLM_ARG_KEY_OPEN, apos)
tc = content.find(_GLM_TC_CLOSE, apos)
@@ -4225,7 +4138,7 @@ def _parse_glm_tool_calls(
valid = False
break
# Bound the healed value at the next structural tag, not EOF, so a value missing only its </arg_value>
- # can't swallow the markup after it.
+ # cannot swallow the markup after it.
nk = content.find(_GLM_ARG_KEY_OPEN, vs)
tc = content.find(_GLM_TC_CLOSE, vs)
bounds = [b for b in (nk, tc) if b >= 0]
@@ -4238,8 +4151,6 @@ def _parse_glm_tool_calls(
continue
raw_val = content[vs:ve]
apos = ve + len(_GLM_ARG_VAL_CLOSE)
- # Decode only unambiguous JSON literals; ``"`` is left out of the probe: a verbatim string's quotes are
- # meaningful
# Decode only unambiguous JSON literals; else keep the value RAW so whitespace in string args survives
# (matches vLLM glm4_moe). ``"`` is left out of the probe: a verbatim string's quotes are meaningful.
probe = raw_val.strip()
@@ -4274,24 +4185,17 @@ def _parse_glm_tool_calls(
return out
-# ── Kimi K2 / Moonshot ──────────────────────────────────────────────
-
-
def _parse_kimi_tool_calls(
content: str,
*,
id_offset: int,
allow_incomplete: bool = True,
) -> list[dict]:
- """Kimi K2.
-
- ``<|tool_calls_section_begin|><|tool_call_begin|>functions.NAME:IDX
- <|tool_call_argument_begin|>{json}<|tool_call_end|>...
- <|tool_calls_section_end|>``. Full id is preserved on ``tool_calls
- [i].id`` for round-trip through the chat template. Outer loop walks
- every section in the stream (vLLM / SGLang parity); mirrors llama.cpp's
- Kimi K2 handling via its generalized XML-style parser (llama.cpp PR #16932).
- """
+ """Kimi K2:
+ ``<|tool_calls_section_begin|><|tool_call_begin|>functions.NAME:IDX<|tool_call_argument_begin|>{json}<|tool_call_end|>...<|tool_calls_section_end|>``.
+ The full id is preserved on ``tool_calls[i].id`` for round-trip through the chat template.
+ The outer loop walks every section in the stream (vLLM / SGLang parity); mirrors llama.cpp's
+ Kimi K2 handling via its generalized XML-style parser (PR #16932)."""
out: list[dict] = []
outer_pos = 0
while True:
@@ -4299,13 +4203,13 @@ def _parse_kimi_tool_calls(
if section_start < 0:
break
scan_start = section_start + len(_KIMI_SECTION_BEGIN)
- # Section end OUTSIDE JSON strings: an argument may contain the literal end token, and a raw find would drop the
- # later valid call.
+ # Section end OUTSIDE JSON strings: an argument may contain the literal end token, and a raw find would drop
+ # the later valid call.
section_end = _find_outside_json_strings(content, _KIMI_SECTION_END, scan_start)
scan_end = section_end if section_end >= 0 else len(content)
body = content[scan_start:scan_end]
- # Truncated tail: parse what we have, then exit. In strict mode a section with no <|tool_calls_section_end|> is
- # truncated; reject it instead.
+ # Truncated tail: parse what we have, then exit. In strict mode a section with no <|tool_calls_section_end|>
+ # is truncated; reject it instead.
if section_end < 0:
if allow_incomplete:
out.extend(
@@ -4356,9 +4260,8 @@ def _parse_kimi_section_body(
else:
base = full_id.split(":")[0]
name = base[len("functions.") :] if base.startswith("functions.") else base
- # Drop bare-counter ids (``3``, ``42``) -- matches vLLM
# Drop bare-counter ids (``3``, ``42``) -- matches vLLM; SGLang infers the name from the tool schema, which we
- # don't have here.
+ # do not have here.
if name.isdigit():
json_start = arg_begin + len(_KIMI_ARG_BEGIN)
brace_end = (
@@ -4379,8 +4282,8 @@ def _parse_kimi_section_body(
continue
brace_end = _balanced_brace_end(body, json_start)
if brace_end is None:
- # Malformed / truncated JSON: skip this call but keep parsing later ones instead of dropping the rest of the
- # section (vLLM recovers them)
+ # Malformed / truncated JSON: skip this call but keep parsing later ones instead of dropping the rest of
+ # the section (vLLM recovers them)
nxt = body.find(_KIMI_CALL_BEGIN, json_start)
if nxt < 0:
break
@@ -4395,8 +4298,8 @@ def _parse_kimi_section_body(
pos = brace_end + 1
continue
if not allow_incomplete:
- # Strict mode: this call must close with <|tool_call_end|> before the next <|tool_call_begin|>; otherwise it
- # is truncated, so reject it.
+ # Strict mode: this call must close with <|tool_call_end|> before the next <|tool_call_begin|>; otherwise
+ # it is truncated, so reject it.
end_marker = body.find(_KIMI_CALL_END, brace_end + 1)
next_call = body.find(_KIMI_CALL_BEGIN, brace_end + 1)
if end_marker < 0 or (next_call >= 0 and end_marker > next_call):
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index e34cf90cefa..38ad1d76f61 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -69,7 +69,6 @@ def _looks_like_broken_json(raw: str) -> bool:
# json at all` healable.
if error.msg.startswith("Expecting property name"):
return False
- # excluded for the opposite reason: `{"a": 1} trailing` decodes fully and then finds junk
# Excluded for the opposite reason: a COMPLETE document with something after it. `{"a": 1} trailing` decodes
# fully and then finds junk, so nothing was lost.
if error.msg.startswith("Extra data"):
@@ -152,7 +151,6 @@ def _heal_arg_key(tool_name: str, tool_schemas = None) -> "str | None":
key = _HEAL_ARG_CACHE.get(tool_name)
if key is not None or not tool_schemas:
return key
- # not cached: caching by name would let one chat's MCP server decide another chat's healing
# Not cached: the request's tools belong to the request, and caching them by name would let one chat's MCP server
# decide another chat's healing.
return _healable_keys_from(tool_schemas).get(tool_name)
@@ -197,7 +195,6 @@ class ToolCallDecision:
tool_name: str
arguments: dict[str, Any]
tool_call_id: str = ""
- # for an id-less call this is the spelling the client minted
# The id the card carries on screen. For an id-less call that is the spelling the client minted, not the id the
# conversation replays; otherwise the two are the same.
card_call_id: str = ""
@@ -240,7 +237,6 @@ class ToolCallDecision:
return None
def tool_start_payload(self) -> dict[str, Any]:
- """Build the payload fields for a real tool_start event."""
fragment = self.unparsed_fragment
# `raw` is the shape this module already uses for arguments it could not read into a schema, so the card shows
# the model's own text under a name that means something rather than an internal sentinel.
@@ -255,7 +251,6 @@ class ToolCallDecision:
}
def tool_start_event(self) -> dict[str, Any]:
- """Build the existing backend event shape for a real execution."""
return {"type": "tool_start", **self.tool_start_payload()}
def as_assistant_tool_call(self) -> dict[str, Any]:
@@ -290,7 +285,6 @@ class ToolCallCompletion:
executed: bool = False
def tool_end_payload(self) -> dict[str, Any]:
- """Build the payload fields for a real tool_end event."""
return {
"tool_name": self.decision.tool_name,
"tool_call_id": self.decision.card_id,
@@ -299,7 +293,6 @@ class ToolCallCompletion:
}
def tool_end_event(self) -> dict[str, Any]:
- """Build the existing backend event shape for a real execution result."""
return {"type": "tool_end", **self.tool_end_payload()}
def tool_message(self) -> dict[str, Any]:
@@ -364,10 +357,9 @@ _DECODE_ERRORS = (ValueError, RecursionError)
_LITERAL_ERRORS = (*_DECODE_ERRORS, SyntaxError, MemoryError)
-# group 1 is the closing quote, which `endswith` cannot stand in for because an open string can end on an escaped one;
# A JSON string, open or closed; group 1 is the closing quote, which `endswith` cannot stand in for because an open
-# string can end on an escaped one. The `\?$` tail stops a started match from ever failing, which would send `finditer`
-# back over every later quote.
+# string can end on an escaped one. The `\?$` tail stops a started match from ever failing, which would send
+# `finditer` back over every later quote.
_JSON_STRING_RE = re.compile(r'"(?:[^"\\]|\\.)*(?:(")|\\?$)', re.S)
_JSON_CLOSER = {"[": "]", "{": "}"}
diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.py
index bd9c135508c..11e77d72e75 100644
--- a/studio/backend/core/inference/tool_stream_exec.py
+++ b/studio/backend/core/inference/tool_stream_exec.py
@@ -150,11 +150,10 @@ def stream_tool_execution(
done_sentinel = object()
outcome: dict[str, Any] = {}
- # bound at the PRODUCER boundary: the consumer-side cap alone would not stop a fast worker enqueuing unboundedly
- # Bound accepted output at the PRODUCER boundary: the consumer-side cap alone wouldn't stop a fast worker enqueuing
- # unboundedly while a slow SSE client backpressures. Accept at most one char past the cap (so the consumer still
- # emits the capped notice) and drop the rest. The final result is captured independently, so this never changes the
- # byte-identical result.
+ # Bound accepted output at the PRODUCER boundary: the consumer-side cap alone wouldn't stop a fast worker
+ # enqueuing unboundedly while a slow SSE client backpressures. Accept at most one char past the cap (so the
+ # consumer still emits the capped notice) and drop the rest. The final result is captured independently, so this
+ # never changes the byte-identical result.
accepted_output_chars = 0
accepted_output_lock = threading.Lock()
@@ -187,7 +186,6 @@ def stream_tool_execution(
)
worker.start()
- # paced by counting idle polls, not a wall clock: tests patch `time.monotonic` globally
# Heartbeats are paced by counting idle queue polls rather than a wall clock (tests patch ``time.monotonic``
# globally, so the wrapper must not read it).
idle_polls_per_heartbeat = max(1, int(round(heartbeat_interval_s / poll_interval_s)))
@@ -293,7 +291,6 @@ def stream_tool_execution(
error = outcome.get("error")
if error is not None:
raise error
- # returned verbatim, so the final tool result is byte-identical to a direct execute_tool call
# Returned verbatim (the loop's record_result handles non-str), so the final tool result is byte-identical to a
# direct execute_tool call.
return outcome.get("result")
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index cc12d109d25..5825d7a4459 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -1,8 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Tool definitions and executors for LLM tool calling: web search
-(DuckDuckGo), Python code execution, and terminal commands."""
+"""Tool definitions and executors for LLM tool calling: web search (DuckDuckGo), Python code
+execution, and terminal commands."""
import ast
import codecs
@@ -33,26 +33,20 @@ import contextlib
import threading
from contextvars import ContextVar
-# What a truncated result costs besides its body, charged where the cut is decided rather
-# than held back from the room in advance. See its definition for why that matters.
+# What a truncated result costs besides its body, charged where the cut is decided rather than held back in advance.
from .context_window import _RESULT_NOTICE_RESERVE
-# The window of the model THIS request is served by, set by execute_tool for the call's
-# duration. Left unset, the budget falls back to the process-global probe, which is right
-# for the local loops and wrong for anything else: an external-provider request runs
-# Unsloth's tool loop without touching a resident GGUF, so inheriting that GGUF's window
-# let a small resident model truncate pages for a large cloud model, and a large resident
-# model hand the full 16,000 characters to a small OpenAI-compatible endpoint.
+# The window of the model THIS request is served by, set by execute_tool for the call's duration. Left unset it falls
+# back to the process-global probe, which is wrong for an external-provider request: that runs Unsloth's tool loop
+# without touching a resident GGUF, so a small resident model truncated pages for a large cloud model.
_UNSET_CONTEXT_TOKENS = object()
_REQUEST_CONTEXT_TOKENS: ContextVar = ContextVar(
"unsloth_request_context_tokens",
default = _UNSET_CONTEXT_TOKENS,
)
-# What the CONVERSATION has left, as opposed to how big the window is. The window alone
-# cannot size a result: it does not fall as the thread fills, so the last result before an
-# overflow is allowed exactly as much room as the first. None means the caller could not
-# say, and every cap then behaves exactly as it did before this existed.
+# What the CONVERSATION has left, as opposed to how big the window is: the window does not fall as the thread fills,
+# so the last result before an overflow would get as much room as the first. None means the caller could not say.
_REQUEST_RESULT_BUDGET: ContextVar = ContextVar(
"unsloth_request_result_budget_tokens",
default = None,
@@ -92,8 +86,8 @@ _DISABLE_DNS_PINNING_ENV = "UNSLOTH_STUDIO_DISABLE_DNS_PINNING"
# Splits the UI source-map from the result; loops strip it (like __IMAGES__).
RAG_SOURCES_SENTINEL = "\n__RAG_SOURCES__:"
-# A search that ran but produced nothing usable. Not a tool error, so callers that judge a step
-# by its evidence (deep research) have to test for these explicitly.
+# A search that ran but produced nothing usable. Not a tool error, so callers that judge a step by its evidence must
+# test for these explicitly.
EMPTY_SEARCH_RESULTS = (
"No results found.",
"No results found within the website access limits.",
@@ -101,8 +95,8 @@ EMPTY_SEARCH_RESULTS = (
# ddgs signals an empty sweep by raising rather than returning [].
_DDGS_EMPTY_SWEEP = "No results found"
-# Import these at module level so the preexec_fn closure triggers no imports in
-# the forked child (which can deadlock multi-threaded servers).
+# Import at module level so the preexec_fn closure triggers no imports in the forked child (which can deadlock
+# multi-threaded servers).
_libc = None
if sys.platform == "linux":
try:
@@ -122,10 +116,9 @@ if sys.platform != "win32":
except ImportError:
pass
-# Raster-image allowlist for sandbox file serving; what a tool call reports inline (`__IMAGES__`)
-# and what the route serves inline (_SANDBOX_MEDIA_TYPES in routes/inference.py) are one set, pinned
-# equal by test_sandbox_files_and_storage_roots -- drift means a model's photo previews on one path only.
-# No .svg (XSS via embedded scripts), no .html, no .pdf.
+# Raster-image allowlist for sandbox file serving, pinned equal to _SANDBOX_MEDIA_TYPES by
+# test_sandbox_files_and_storage_roots; drift means a model's photo previews on one path only. No .svg (XSS via
+# embedded scripts), no .html, no .pdf.
_IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".avif"})
@@ -138,9 +131,8 @@ def _env_int(name: str, default: int) -> int:
return value if value > 0 else default
-# Model-visible cap on python/terminal tool results (protects the context
-# window). The live UI stream is capped separately and higher, so _truncate's
-# notice stays mode-neutral (see tool_stream_exec.TOOL_OUTPUT_STREAM_MAX_CHARS).
+# Model-visible cap on python/terminal tool results. The live UI stream is capped separately and higher, so
+# _truncate's notice stays mode-neutral (tool_stream_exec.TOOL_OUTPUT_STREAM_MAX_CHARS).
_MAX_OUTPUT_CHARS = _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000)
_BLOCKED_COMMANDS_COMMON = frozenset(
{
@@ -177,9 +169,8 @@ _BLOCKED_COMMANDS_COMMON = frozenset(
"rsync",
"eval",
"source",
- # `.` is the POSIX synonym for `source`: `. ./script.sh` runs the file's
- # contents in the current shell, past a classifier that never sees them.
- # Matched at command position only, so `find . -type f` / `cd .` are fine.
+ # `.` is the POSIX synonym for `source`, so `. ./script.sh` runs the file's contents past a classifier that
+ # never sees them. Matched at command position only.
".",
}
)
@@ -201,9 +192,8 @@ _BLOCKED_COMMANDS = (
_SHELL_SEPARATORS = frozenset({";", "&&", "||", "|", "&", "\n", "(", ")", "`", "{", "}"})
-# Bash keywords starting a new command position (then $cmd, do $cmd, etc.).
-# `if`/`while`/`until` are followed by a CONDITION the shell executes, so a
-# command right after them is at command position (if rm -rf x; then :; fi).
+# Bash keywords starting a new command position. `if`/`while`/`until` are followed by a CONDITION the shell executes,
+# so a command right after them is at command position.
_SHELL_KEYWORDS_AS_SEP = frozenset({"then", "do", "else", "elif", "if", "while", "until", "!"})
# Wrappers whose next non-flag argument is the command Bash will exec.
_COMMAND_PREFIXES = frozenset(
@@ -227,9 +217,8 @@ _COMMAND_PREFIXES = frozenset(
"xargs",
}
)
-# Wrapper options whose VALUE is a separate token (env -u NAME, nice -n 5).
-# Unconsumed, the value is mistaken for the wrapped command: `env -u FOO rm -rf x`
-# reads as command `FOO`. Shared by the auto gate and the blocklist walk.
+# Wrapper options whose VALUE is a separate token (env -u NAME, nice -n 5). Unconsumed, `env -u FOO rm -rf x` reads as
+# command `FOO`.
_WRAPPER_VALUE_FLAGS_BY_CMD = {
# env -i/--ignore-environment is VALUELESS; only -u/--unset takes a name.
"env": frozenset({"-u", "--unset"}),
@@ -264,9 +253,8 @@ _WRAPPER_VALUE_FLAGS_BY_CMD = {
"nohup": frozenset(),
}
_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
-# Env-assignment prefixes that change command lookup or code loading, so
-# `LD_PRELOAD=x ls` / `PATH=. ls` run attacker code before the read-only
-# utility. LD_*/DYLD_* and any *PATH are covered by the prefix/suffix check.
+# Env-assignment prefixes that change command lookup or code loading, so `LD_PRELOAD=x ls` / `PATH=. ls` run attacker
+# code before the read-only utility.
_AUTO_UNSAFE_ENV_ASSIGN = frozenset(
{
"IFS",
@@ -291,9 +279,8 @@ _AUTO_UNSAFE_ENV_ASSIGN = frozenset(
)
-# A search-path entry that can shadow a real binary or module: absolute, home or
-# a parent escape. A relative entry (`PYTHONPATH=src`) points inside the session
-# workdir, the agent's own directory, and is the common spelling in ordinary work.
+# A search-path entry that can shadow a real binary or module: absolute, home or a parent escape. A relative entry
+# points inside the session workdir and is the common spelling in ordinary work.
_PATH_ENTRY_ESCAPES_RE = re.compile(r"(?:^|:)\s*(?:/|~|\$|[A-Za-z]:[\\/]|\.\.)")
@@ -302,17 +289,16 @@ def _env_assignment_is_unsafe(name: str, value: str = "") -> bool:
if name in _AUTO_UNSAFE_ENV_ASSIGN or name.startswith(("LD_", "DYLD_")):
return True
if name == "PATH":
- # Every value counts: PATH picks the BINARY, and a relative entry is the
- # sharpest form of that (`PATH=. ls` runs ./ls).
+ # Every value counts: PATH picks the BINARY, and a relative entry is the sharpest form of that (`PATH=. ls`
+ # runs ./ls).
return True
- # The other search paths (PYTHONPATH, NODE_PATH, ...) only shadow a real
- # module when the entry escapes the workdir.
+ # The other search paths (PYTHONPATH, NODE_PATH, ...) only shadow a real module when the entry escapes the
+ # workdir.
return name.endswith("PATH") and bool(_PATH_ENTRY_ESCAPES_RE.search(value))
-# Container CLIs start or reach into a container (docker run -v /:/host), but
-# their read subcommands are ordinary inspection and must not interrupt. An
-# unrecognised subcommand still asks, so the list can only be too small.
+# Container CLIs start or reach into a container (docker run -v /:/host), but their read subcommands must not
+# interrupt. An unrecognised subcommand still asks, so the list can only be too small.
_CONTAINER_CLIS = frozenset({"docker", "podman", "nerdctl", "ctr", "crictl", "lxc", "kubectl"})
_CONTAINER_READ_SUBCOMMANDS = frozenset(
{
@@ -340,112 +326,93 @@ _CONTAINER_READ_SUBCOMMANDS = frozenset(
"api-versions",
}
)
-# Windows `if exist FILE cmd` / `if defined VAR cmd` put an operand between the
-# keyword and the command, so the command word is two tokens along.
-# awk runs its program text, which can shell out through the system() builtin
-# or by piping to a shell ("cmd" | "sh"). Screening the program keeps ordinary
-# field work (awk '{print $1}') running while the escape hatches ask.
+# Windows `if exist FILE cmd` / `if defined VAR cmd` put an operand between the keyword and the command. awk runs its
+# program text, which can shell out via system() or by piping to a shell, so the program is screened while ordinary
+# field work runs.
_AWK_COMMANDS = frozenset({"awk", "gawk", "mawk", "nawk", "busybox-awk"})
_AWK_SHELL_ESCAPE_RE = re.compile(
r"\bsystem\s*\(|\|\s*&?\s*[\"']\s*(?:/\S*/)?(?:sh|bash|zsh|ksh|dash|cmd)\b|"
r"\bENVIRON\s*\[|\bprintf\s*\|"
)
-# sed shells out like awk: GNU's `e` runs the rest of its line through popen and
-# the `s///e` flag runs the pattern space, hiding a command inside a text-editing
-# argument. Screened so ordinary editing (sed 's/a/b/g') stays unprompted.
+# sed shells out like awk: GNU's `e` runs the rest of its line through popen and the `s///e` flag runs the pattern
+# space, hiding a command inside a text-editing argument.
_SED_COMMANDS = frozenset({"sed", "gsed", "ssed"})
-# `s///` flags that may precede `e`. `w` is absent: it takes the rest of the
-# line as a filename, so the e in `s/a/b/w report.txt` is part of that name.
+# `s///` flags that may precede `e`. `w` is absent: it takes the rest of the line as a filename, so the e in `s/a/b/w
+# report.txt` is part of that name.
_SED_SUBST_FLAGS = frozenset("0123456789gpiImMe")
-# sed short options that consume text, so no later letter in the cluster is a
-# flag: -e/-f take a script and -l a length (attached or next token), while -i's
-# backup suffix is ATTACHED ONLY (`-ifoo` otherwise reads as an attached `-f oo`).
+# sed short options that consume text, so no later letter in the cluster is a flag: -e/-f take a script and -l a
+# length, while -i's backup suffix is ATTACHED ONLY (`-ifoo` otherwise reads as an attached `-f oo`).
_SED_VALUE_FLAGS = "efl"
_SED_ATTACHED_VALUE_FLAGS = "i"
-# A backslash in a sed text argument escapes the next character, newline
-# included, so it is stripped before the payload is read as a shell command.
+# A backslash in a sed text argument escapes the next character, newline included, so it is stripped before the
+# payload is read as a shell command.
_SED_TEXT_ESCAPE_RE = re.compile(r"\\([\s\S])")
-# A plain parameter reference in a sed program (`sed "$p" f`). Bare `$NAME` /
-# `${NAME}` only: anything with an operator is a transformation this scan does
-# not model, so the program is judged UNREAD (see _sed_program_unresolved).
+# A plain parameter reference in a sed program. Bare `$NAME` / `${NAME}` only: anything with an operator is a
+# transformation this scan does not model, so the program is judged UNREAD.
_PROGRAM_VAR_RE = re.compile(r"\$\{(\w+)\}|\$(\w+)")
-# An unbraced expansion bash performs: a name (`$p`), a positional (`$1`) or a
-# special parameter ($@ $* $# $? $- $$ $!). Any other `$` is literal (verified:
-# `printf '%s' "$ d"` prints `$ d`), which keeps sed's `$` address out of scope.
+# An unbraced expansion bash performs: a name, a positional or a special parameter. Any other `$` is literal, which
+# keeps sed's `$` address out of scope.
_UNBRACED_PARAM_RE = re.compile(r"\$(?:[A-Za-z_]\w*|[0-9]+|[@*#?$!-])")
-# Arithmetic evaluates to an INTEGER, so it spells no sed command. A digit in its
-# place keeps `sed -n "1,$((n + 1))p" f` silent while still exposing the `e` in
-# `sed "$((c+1))e rm -f victim"`, which runs rm.
+# Arithmetic evaluates to an INTEGER, so it spells no sed command. A digit in its place keeps `sed -n "1,$((n + 1))p"
+# f` silent while still exposing the `e` in `sed "$((c+1))e rm -f victim"`.
_ARITHMETIC_VALUE = "0"
-# The FLOOR every invocation gets for its argument walk, which keeps a line
-# padded with `-exec sed` words linear. A flat cap is padding an attacker
-# controls: `sed -n ...x128 '1e rm -f victim'` pushed the script past 128.
+# The FLOOR every invocation gets for its argument walk, which keeps a line padded with `-exec sed` words linear. A
+# flat cap is padding an attacker controls.
_MAX_SED_ARG_SCAN = 128
-# Argument tokens the sed screen may walk across ONE command line, split over the
-# sed words on it, so a lone sed reads its whole list and the work stays linear.
+# Argument tokens the sed screen may walk across ONE command line, split over the sed words on it, so a lone sed reads
+# its whole list and the work stays linear.
_SED_SCAN_BUDGET = 200_000
-# Wrappers may sit between `find -exec` and the command it runs; bounded so a
-# line padded with `-exec env -exec env ...` cannot make the scan quadratic.
+# Wrappers may sit between `find -exec` and the command it runs; bounded so a line padded with `-exec env -exec env
+# ...` cannot make the scan quadratic.
_MAX_EXEC_PREFIX_SCAN = 32
-# First window tried when balancing a `$(...)`, quadrupled until the span closes
-# (_substitution_span), so a line of many short substitutions stays linear.
+# First window tried when balancing a `$(...)`, quadrupled until the span closes, so a line of many short
+# substitutions stays linear.
_SUBSTITUTION_SPAN_STEP = 64
-# Quote state (_shell_quote_states) of a backslash and the character behind it.
-# Distinct from the surrounding quoting because bash expands neither: the `$(` in
-# `sed "s/\$(CC)/gcc/" Makefile` opens no command substitution.
+# Quote state of a backslash and the character behind it. Distinct from the surrounding quoting because bash expands
+# neither: the `$(` in `sed "s/\$(CC)/gcc/" Makefile` opens no command substitution.
_ESCAPED_CHAR_STATE = "\\"
_WIN_CONDITIONAL_KEYWORDS = frozenset({"exist", "defined", "errorlevel", "not"})
_FIND_EXEC_FLAGS = frozenset({"-exec", "-execdir", "-ok", "-okdir"})
-# A find action is COMPLETE at its terminator: words after it are find's next
-# predicate, not CMD's. Reading past it took a following `-exec grep -e safe {} +`
-# for sed's script. `\;` is listed too, for the non-posix lexer.
+# A find action is COMPLETE at its terminator: words after it are find's next predicate, not CMD's. Reading past it
+# took a following `-exec grep -e safe {} +` for sed's script.
_FIND_EXEC_TERMINATORS = frozenset({"+", ";", "\\;"})
-# The `;` spellings END the action wherever they stand: a quoted `';'` and an
-# escaped `\;` reach find as the same word. `+` is absent because find reads it
-# as the batched terminator only directly after a `{}` (see _exec_scan_layout).
+# The `;` spellings END the action wherever they stand: a quoted `';'` and an escaped `\;` reach find as the same
+# word. `+` is absent because find reads it as the batched terminator only directly after a `{}`.
_FIND_EXEC_SEMICOLONS = frozenset({";", "\\;"})
-# ...but ONLY inside such an action. shlex strips quoting, so a sed FILE operand
-# spelled `';'` or `'+'` arrives as the same token as a real separator, and
-# ending the scan there dropped the `-e` script behind it: verified that
-# `sed -n ';' -e '1e rm -f victim' input` really runs rm. Outside an action only
-# an UNQUOTED `;` ends the invocation.
-
-# The characters a separator token can be built from, masked while the command
-# is lexed a second time so a quoted one is told apart from a real one.
+# ...but ONLY inside such an action. shlex strips quoting, so a sed FILE operand spelled `';'` arrives as the same
+# token as a real separator, and ending the scan there dropped the `-e` script behind it (verified: it really runs
+# rm). Outside an action only an UNQUOTED `;` ends the invocation.
+
+# The characters a separator token can be built from, masked while the command is lexed a second time so a quoted one
+# is told apart from a real one.
_SEPARATOR_CHARS = frozenset("".join(_SHELL_SEPARATORS))
-# Placeholder for a quoted separator character during that second lex. Any
-# non-whitespace, non-quote, non-punctuation_chars character serves, so the
-# masked text splits into the same words and the token lists line up.
+# Placeholder for a quoted separator character during that second lex. Any non-whitespace, non-quote,
+# non-punctuation_chars character serves, so the masked text splits into the same words.
_QUOTED_SEPARATOR_MARK = "\x00"
-# The characters bash expands a word against the filesystem for, and the
-# placeholder standing in for a QUOTED one during the same second lex.
+# The characters bash expands a word against the filesystem for, and the placeholder standing in for a QUOTED one
+# during the same second lex.
_GLOB_CHARS = frozenset("*?[")
_QUOTED_GLOB_MARK = "\x01"
-# The characters a redirection is built from, and the placeholder standing in
-# for a QUOTED one. A redirection is something the shell PERFORMS, so a quoted
-# spelling is an ordinary word the command receives instead.
+# The characters a redirection is built from, and the placeholder for a QUOTED one. A redirection is something the
+# shell PERFORMS, so a quoted spelling is an ordinary word the command receives.
_REDIRECT_CHARS = frozenset("<>")
_QUOTED_REDIRECT_MARK = "\x02"
-# The characters that open an expansion, and the placeholder for one the quoting
-# made literal. Double quoting is NOT literal here (`sed "$p" f` expands), so
-# only single-quoted and escaped states count (see _unquoted_expansion_indexes).
+# The characters that open an expansion, and the placeholder for one the quoting made literal. Double quoting is NOT
+# literal here (`sed "$p" f` expands), so only single-quoted and escaped states count.
_EXPANSION_CHARS = frozenset("$`")
_QUOTED_EXPANSION_MARK = "\x04"
-# The characters punctuation_chars glues into one token. A run like `|&` matches
-# no _SHELL_SEPARATORS entry, so the sed screen read past the end of the command
-# (`sed '1e rm -f victim' input |& grep -e safe` runs rm). `{`/`}` are absent so
-# find's `{}` stays an ordinary word.
+# The characters punctuation_chars glues into one token. A run like `|&` matches no _SHELL_SEPARATORS entry, so the
+# sed screen read past the end of the command. `{`/`}` are absent so find's `{}` stays an ordinary word.
_OPERATOR_TOKEN_CHARS = frozenset(";&|()`")
-# One shell redirection, as the lexer hands it over. The target may be glued on
-# (`2>/dev/null`) or be the next token (`> out.txt`); `&` splits off under
-# punctuation_chars, so `2>&1` arrives as three.
+# One shell redirection as the lexer hands it over. The target may be glued on (`2>/dev/null`) or be the next token;
+# `&` splits off under punctuation_chars, so `2>&1` arrives as three.
_REDIRECTION_RE = re.compile(r"^(?:\d+|&)?(?:<<<|<<-|<<|<>|>>|>\||<&|>&|<|>)")
def _looks_like_separator(token: str) -> bool:
- """Whether a lexed token is a shell operator rather than a word a command
- receives. A known separator, or a RUN of punctuation_chars characters, which
- is how bash builds `|&`, `;;` and `;&`."""
+ """Whether a lexed token is a shell operator rather than a word a command receives: a known
+ separator, or a RUN of punctuation_chars characters, which is how bash builds `|&`, `;;` and
+ `;&`."""
if token in _SHELL_SEPARATORS:
return True
return bool(token) and not (set(token) - _OPERATOR_TOKEN_CHARS)
@@ -457,23 +424,18 @@ def _redirection_span(
quoted: "frozenset[int]" = frozenset(),
quoted_redirects: "frozenset[int]" = frozenset(),
) -> "tuple[int, ...]":
- """The token indexes one shell redirection at ``index`` occupies, or ``()``.
-
- The shell REMOVES a redirection before the command sees its arguments, so
- leaving the words in place made it the command's first operand: verified that
- `sed </dev/null '1e rm -f victim' input` and `> out.txt rm -rf victim` both
- run for real. A detached target is claimed only when it is an ordinary word.
- """
+ """The token indexes one shell redirection at ``index`` occupies, or ``()``. The shell REMOVES a
+ redirection before the command sees its arguments, so leaving the words in place made it the
+ command's first operand (verified: `sed </dev/null '1e rm -f victim' input` runs). A detached
+ target is claimed only when it is an ordinary word."""
if tokens[index] == "&" and index + 1 < len(tokens) and tokens[index + 1][:1] in "<>":
- # `&>out.txt` splits in two, and reading the `&` as a background
- # operator ended the command early. Only a redirection may follow, so
- # `echo hi & rm -rf victim` keeps its separator.
+ # `&>out.txt` splits in two, and reading the `&` as a background operator ended the command early. Only a
+ # redirection may follow, so `echo hi & rm -rf victim` keeps its separator.
tail = _redirection_span(tokens, index + 1, quoted, quoted_redirects)
return (index, *tail) if tail else ()
if index in quoted_redirects:
- # The quoting makes it a WORD the command receives: `sed -f '>prog' -e
- # '1e rm -f victim' input` takes `>prog` as the script FILE and really
- # runs the payload, while removing it as a redirection left -e unread.
+ # The quoting makes it a WORD the command receives: `sed -f '>prog' -e '1e rm -f victim' input` takes `>prog`
+ # as the script FILE and really runs the payload, while removing it as a redirection left -e unread.
return ()
match = _REDIRECTION_RE.match(tokens[index])
if not match:
@@ -485,14 +447,13 @@ def _redirection_span(
if nxt >= len(tokens):
return tuple(span)
if tokens[nxt] in {"&", "|"}:
- # `2>&1` and `>|out.txt` each arrive as three tokens, and the middle one
- # was read as the end of the command (verified: both run the payload).
+ # `2>&1` and `>|out.txt` each arrive as three tokens, and the middle one was read as the end of the command
+ # (verified: both run the payload).
span.append(nxt)
nxt += 1
if nxt < len(tokens) and not (_looks_like_separator(tokens[nxt]) and nxt not in quoted):
- # The shell hands the target to open(), not to sed: `sed > --sandbox
- # '1e touch MARKER' input` and its `> ';'` twin both really run it. Only
- # a BARE operator is refused, since that line is malformed anyway.
+ # The shell hands the target to open(), not to sed, so `sed > --sandbox '1e touch MARKER' input` really runs
+ # it. Only a BARE operator is refused, since that line is malformed anyway.
span.append(nxt)
return tuple(span)
@@ -502,9 +463,8 @@ _TEST_BUILTINS = frozenset({"[", "[[", "]", "]]"})
def _is_unresolved_command_glob(base: str) -> bool:
- """Whether a command word is a glob bash expands to some other name
- (`/bin/r[m]` runs rm). A pattern with no literal character (a bare `*`) is
- not one, and the test builtins are not patterns."""
+ """Whether a command word is a glob bash expands to some other name (`/bin/r[m]` runs rm). A
+ pattern with no literal character is not one, and the test builtins are not patterns."""
if base in _TEST_BUILTINS or not any(ch in base for ch in "*?["):
return False
return any(ch.isalnum() for ch in base)
@@ -518,10 +478,8 @@ def _blocked_matching_glob(base: str) -> "set[str]":
def _is_sed_command(base: str) -> bool:
- """Whether a command word runs sed: an exact name, or a command-position GLOB
- that could expand to one, since bash resolves `/usr/bin/s[e]d` to sed after
- this scan. Fail closed: a non-sed program holds no `e` and yields no
- payload."""
+ """Whether a command word runs sed: an exact name, or a command-position GLOB that could expand
+ to one, since bash resolves `/usr/bin/s[e]d` to sed after this scan. Fail closed."""
if base in _SED_COMMANDS:
return True
return _is_unresolved_command_glob(base) and any(
@@ -530,10 +488,9 @@ def _is_sed_command(base: str) -> bool:
def _sed_short_flag(token: str) -> "tuple[str, str] | None":
- """The first value-taking short option in a sed flag cluster, as
- ``(letter, text glued after it)``, or ``None``. The scan stops there because
- the rest of the token is that option's value: `-ifoo` is -i with backup
- suffix "foo", not an attached -f."""
+ """The first value-taking short option in a sed flag cluster, as ``(letter, text glued after
+ it)``, or ``None``. The scan stops there because the rest of the token is that option's
+ value: `-ifoo` is -i with suffix "foo", not an attached -f."""
if not token.startswith("-") or token.startswith("--"):
return None
for index, ch in enumerate(token[1:]):
@@ -543,10 +500,9 @@ def _sed_short_flag(token: str) -> "tuple[str, str] | None":
def _sed_long_flag(name: str) -> str:
- """Which value-taking sed long option ``--name`` is: "e" for --expression,
- "f" for --file, "l" for --line-length, "" otherwise. getopt allows unambiguous
- abbreviations, so --e/--ex are --expression and --fi upwards is --file (--f is
- ambiguous with --follow-symlinks). --in-place's suffix is always attached."""
+ """Which value-taking sed long option ``--name`` is: "e", "f", "l" or "". getopt allows
+ unambiguous abbreviations, so --e/--ex are --expression and --fi upwards is --file (--f is
+ ambiguous with --follow-symlinks)."""
if len(name) <= 2:
return ""
if "--expression".startswith(name):
@@ -559,54 +515,44 @@ def _sed_long_flag(name: str) -> str:
def _sed_disables_exec(name: str) -> bool:
- """Whether the long option ``name`` puts sed in a mode that REFUSES to shell
- out. --sandbox disables e/r/w and --posix drops the GNU extensions `e` belongs
- to, so a script COMPILED under either aborts the run (exit 1) and its payload
- is inert. WHICH scripts that covers depends on where the flag sits: see
- _sed_invocation. Only unambiguous abbreviations count (`--s` is ambiguous and
- sed exits on it), and an `=` spelling is rejected by sed too.
- """
+ """Whether the long option ``name`` puts sed in a mode that REFUSES to shell out. --sandbox
+ disables e/r/w and --posix drops the GNU extensions `e` belongs to, so a script COMPILED
+ under either aborts the run and its payload is inert; which scripts that covers depends on
+ where the flag sits (see _sed_invocation). Only unambiguous abbreviations count."""
if len(name) >= 4 and "--sandbox".startswith(name):
return True
return len(name) >= 3 and "--posix".startswith(name)
def _sed_scan_limit(sed_words: int) -> int:
- """How many argument tokens ONE sed invocation may walk looking for its
- script. A lone sed gets the whole budget, so padding cannot push the script
- out of view; a line packed with sed words falls back to the floor, which
- keeps the walk linear (`-exec sed ` repeated to 16KB: 39s against 3s)."""
+ """How many argument tokens ONE sed invocation may walk looking for its script. A lone sed gets
+ the whole budget, so padding cannot push the script out of view; a line packed with sed words
+ falls back to the floor, which keeps the walk linear (39s against 3s)."""
if sed_words <= 1:
return _SED_SCAN_BUDGET
return max(_MAX_SED_ARG_SCAN, _SED_SCAN_BUDGET // sed_words)
-# An -f operand naming a STREAM rather than a file on disk, so the script arrives
-# on stdin and "no program found" is ignorance rather than safety:
-# `sed -f - input <<EOF ... 1e touch MARKER ... EOF` really runs the payload.
+# An -f operand naming a STREAM rather than a file on disk, so the script arrives on stdin and "no program found" is
+# ignorance rather than safety.
_SED_STREAM_PROGRAM_SOURCES = frozenset({"-", "/dev/stdin", "/dev/fd/0"})
def _sed_program_source_is_stream(value: str) -> bool:
- """Whether an `-f` operand reads the script from a stream this scan cannot
- follow. A named file (`sed -f prog.sed input`) stays out: it is documented
- residue rather than something to fail on. A process substitution counts, since
- `sed -f <(printf 'e rm -f victim') input` really runs rm; the lexer splits
- that operand at the `(`, which is why the bare `<`/`>` are here too."""
+ """Whether an `-f` operand reads the script from a stream this scan cannot follow. A named file
+ stays out: it is documented residue rather than something to fail on. A process substitution
+ counts, since `sed -f <(printf 'e rm -f victim') input` really runs rm, and the lexer splits
+ that operand at the `(`."""
if value in _SED_STREAM_PROGRAM_SOURCES or value.startswith("/dev/fd/"):
return True
return value[:1] in "<>"
def _end_program_source(programs: "list[str]", exec_disabled: bool) -> None:
- """Close the script source the pieces collected so far belong to, by appending
- the blank line the join needs.
-
- A source BOUNDARY ends any line continuation open across it, so a trailing
- `a\\` appends a blank line instead of swallowing the next source's first line.
- Verified on GNU sed 4.9: `sed -e '1a\\' -f /dev/null -e 'e touch MARKER' input`
- creates the file while the same line without the -f does not.
- """
+ """Close the script source the pieces collected so far belong to, by appending the blank line
+ the join needs. A source BOUNDARY ends any line continuation open across it, so a trailing
+ `a\\` appends a blank line instead of swallowing the next source's first line (verified on GNU
+ sed 4.9)."""
if programs and programs[-1] and not exec_disabled:
programs.append("")
@@ -620,44 +566,37 @@ def _sed_invocation(
globs: "frozenset[int]" = frozenset(),
expandable: "frozenset[int]" = frozenset(),
) -> "tuple[list[str], bool, bool]":
- """The sed invocation whose command word sits at ``start``, as
- ``(program alternatives, unread, live_program)``.
-
- sed joins its -e values with newlines, so `sed -e '1a\\' -e 'e rm -rf x'`
- appends a line instead of executing it and the pieces are judged together.
- With no -e or -f the first positional is the script.
-
- --sandbox / --posix abort at COMPILE time, and sed compiles each -e as it is
- parsed while the positional waits for the whole option list, so the flag
- suppresses exactly the scripts written after it (verified on GNU sed 4.9:
- `sed -e '1e touch MARKER' --sandbox input` still runs). One written after the
- POSITIONAL suppresses only while getopt permutes, and POSIXLY_CORRECT turns
- that off from outside the command text, so it is not read as suppressing.
- `--` is honoured: a `--sandbox` behind it is an input FILENAME.
-
- ``unread`` says the program is at best a PREFIX of the real one, so an empty
- result proves nothing and callers fail closed on it.
-
- ``stops`` and ``skips`` are token INDEXES, not text: where the invocation
- ends (a separator the shell performs, or the `+` / `;` closing this sed's
- find action) and which words are a redirection the shell removes before sed
- runs. Both distinctions need the original quoting, which the text has lost.
- A skip yields to a pending -e/-f/-l value, since that word is sed's.
+ """The sed invocation whose command word sits at ``start``, as ``(program alternatives, unread,
+ live_program)``.
+
+ sed joins its -e values with newlines, so `sed -e '1a\' -e 'e rm -rf x'` appends a line instead
+ of executing it and the pieces are judged together. With no -e or -f the first positional is the
+ script.
+
+ --sandbox / --posix abort at COMPILE time, and sed compiles each -e as it is parsed while the
+ positional waits for the whole option list, so the flag suppresses exactly the scripts written
+ after it (verified on GNU sed 4.9). One written after the POSITIONAL suppresses only while
+ getopt permutes, and POSIXLY_CORRECT turns that off from outside the command text, so it is not
+ read as suppressing. `--` is honoured.
+
+ ``unread`` says the program is at best a PREFIX of the real one, so an empty result proves
+ nothing and callers fail closed on it.
+
+ ``stops`` and ``skips`` are token INDEXES, not text: where the invocation ends and which words
+ are a redirection the shell removes. Both distinctions need the original quoting, which the text
+ has lost. A skip yields to a pending -e/-f/-l value, since that word is sed's.
"""
programs: "list[str]" = []
first_positional = ""
positional_disabled = False # a mode flag preceded the positional script
positional_globbed = False # ...and bash rewrites it before sed is started
positional_live = False # ...and it holds an expansion the shell performs
- # A program flag AHEAD of the positional word makes that word an input FILE.
- # One BEHIND it does so only while getopt permutes, and POSIXLY_CORRECT turns
- # permutation off from outside the command text, so the positional is still
- # read as a script then (verified on GNU sed 4.9 that
- # `POSIXLY_CORRECT=1 sed '1e touch MARKER' input -f /dev/null` creates it).
+ # A program flag AHEAD of the positional word makes that word an input FILE. One BEHIND it does so only while
+ # getopt permutes, and POSIXLY_CORRECT turns permutation off from outside the command text, so the positional is
+ # still read as a script then (verified on GNU sed 4.9).
program_flag_before_positional = False
- # A mode flag has been seen, so every script COMPILED after it is inert.
- # Monotone by construction, so the live pieces are always a PREFIX rather
- # than a hole in the middle of one `-e '1a\' -e 'e rm -rf x'` program.
+ # A mode flag has been seen, so every script COMPILED after it is inert. Monotone by construction, so the live
+ # pieces are always a PREFIX rather than a hole in the middle of one program.
exec_disabled = False
end_of_options = False # `--` seen: no later word is an option
value_pending = "" # "e", "f" or "l": the next token is that flag's value
@@ -671,14 +610,11 @@ def _sed_invocation(
hit_separator = True
break
if start + 1 + offset in skips:
- # A redirection: the shell removed it before sed ran. Checked AHEAD
- # of the pending value, because one standing where that value goes is
- # removed too and the value is the word BEHIND it (`sed -n -e >out
- # '1e touch MARKER' input` really runs the payload).
+ # A redirection: the shell removed it before sed ran. Checked AHEAD of the pending value, because one
+ # standing where that value goes is removed too and the value is the word BEHIND it.
continue
if value_pending:
- # The value is consumed either way; only a script sed still compiles
- # goes into the program.
+ # The value is consumed either way; only a script sed still compiles goes into the program.
if value_pending == "e" and not exec_disabled:
programs.append(token)
glob_program = glob_program or start + 1 + offset in globs
@@ -720,8 +656,8 @@ def _sed_invocation(
continue
letter, attached = found
if letter in _SED_ATTACHED_VALUE_FLAGS:
- # -i's suffix is the rest of the token; it never takes the next
- # one, so the script is still the positional ahead.
+ # -i's suffix is the rest of the token; it never takes the next one, so the script is still the
+ # positional ahead.
continue
if letter in "ef" and not first_positional:
program_flag_before_positional = True
@@ -749,40 +685,34 @@ def _sed_invocation(
if not programs:
joined = [first_positional]
else:
- # A program option stands BEHIND the positional, so which of the two
- # sed compiles depends on permutation. They are ALTERNATIVES, not one
- # program: joining them let an unterminated command in one swallow
- # the other, and `POSIXLY_CORRECT=1 sed '1e touch MARKER' input -e
- # safe` read as safe although it really runs the payload.
+ # A program option stands BEHIND the positional, so which of the two sed compiles depends on permutation.
+ # They are ALTERNATIVES, not one program: joining them let an unterminated command in one swallow the
+ # other.
joined.append(first_positional)
- # Complete when a separator closed the invocation, or when the window
- # already covered every remaining argument.
+ # Complete when a separator closed the invocation, or when the window already covered every remaining argument.
scan_overflowed = not hit_separator and len(tokens) > start + 1 + limit
- # A still-pending -f value means the invocation ended before its operand was
- # read at all -- a process substitution ends it at the `(` -- so the program
- # is unknown rather than absent.
+ # A still-pending -f value means the invocation ended before its operand was read at all (a process substitution
+ # ends it at the `(`), so the program is unknown rather than absent.
joined = [piece.replace(_ANSI_C_NEWLINE_MARK, "\n") for piece in joined]
unread = scan_overflowed or stream_program or glob_program or value_pending == "f"
return joined, unread, live_program
def _sed_text(text: str) -> str:
- """Unescape one sed text argument the way read_text does: every backslash
- drops away and the character behind it stays, so `e touch MARK\\ER` runs
- MARKER."""
+ """Unescape one sed text argument the way read_text does: every backslash drops away and the
+ character behind it stays, so `e touch MARK\\ER` runs MARKER."""
return _SED_TEXT_ESCAPE_RE.sub(r"\1", text).strip()
def _sed_exec_payloads(program: str) -> "list[str]":
"""Shell payloads a sed program executes, in order.
- `e COMMAND` runs COMMAND. A bare `e` and the `s///e` flag run the pattern
- space, which only exists at run time, so they yield an EMPTY payload:
- executes, but nothing to screen. An empty list means it only edits text.
+ `e COMMAND` runs COMMAND. A bare `e` and the `s///e` flag run the pattern space, which only
+ exists at run time, so they yield an EMPTY payload: executes, but nothing to screen. An empty
+ list means it only edits text.
- The walk skips every region where an `e` is data (regexes, replacements,
- a/i/c text, r/w filenames, b/t labels, comments), keeping `:e;N;$!be;...`,
- `sed 's/e/E/g'` and `sed 's/a/b/w report.txt'` out of the results.
+ The walk skips every region where an `e` is data (regexes, replacements, a/i/c text, r/w
+ filenames, b/t labels, comments).
"""
payloads: "list[str]" = []
n = len(program)
@@ -792,16 +722,15 @@ def _sed_exec_payloads(program: str) -> "list[str]":
return n if end < 0 else end
def _end_of_text(pos: int) -> int:
- # read_text, which collects `e`/`a`/`i`/`c` text: a backslash escapes
- # the next character, so a line ending in one carries the text onto the
- # NEXT line instead of stopping there.
+ # read_text, which collects `e`/`a`/`i`/`c` text: a backslash escapes the next character, so a line ending in
+ # one carries the text onto the NEXT line.
while pos < n and program[pos] != "\n":
pos += 2 if program[pos] == "\\" else 1
return min(pos, n)
def _skip_bracket(pos: int) -> int:
- # A bracket expression, where the delimiter is data (`s/[/]/x/` really
- # substitutes a slash). A leading `]` is literal; [:class:] nests.
+ # A bracket expression, where the delimiter is data (`s/[/]/x/` really substitutes a slash). A leading `]` is
+ # literal; [:class:] nests.
pos += 1
if pos < n and program[pos] == "^":
pos += 1
@@ -816,8 +745,8 @@ def _sed_exec_payloads(program: str) -> "list[str]":
return pos + 1
def _skip_section(pos: int, delim: str, brackets: bool) -> int:
- # One delimited section of a regex / s/// / y///, through its closing
- # delimiter. Brackets apply to regex halves only; elsewhere `[` is data.
+ # One delimited section of a regex / s/// / y///, through its closing delimiter. Brackets apply to regex
+ # halves only; elsewhere `[` is data.
while pos < n and program[pos] != delim:
if program[pos] == "\\":
pos += 2
@@ -828,8 +757,7 @@ def _sed_exec_payloads(program: str) -> "list[str]":
return pos + 1
def _skip_address(pos: int) -> int:
- # A line number (GNU's first~step included), `$`, /regex/ or \%regex%,
- # each allowing I/M modifiers.
+ # A line number (GNU's first~step included), `$`, /regex/ or \%regex%, each allowing I/M modifiers.
if pos < n and program[pos] == "$":
return pos + 1
if pos < n and program[pos].isdigit():
@@ -874,9 +802,8 @@ def _sed_exec_payloads(program: str) -> "list[str]":
break
cmd, i = program[i], i + 1
if cmd == "e":
- # The payload ends at an UNESCAPED newline, so a `;` inside it is
- # shell text and `e\` + newline hands the next line to the same
- # shell (`1e\` / `rm -f victim` really runs rm).
+ # The payload ends at an UNESCAPED newline, so a `;` inside it is shell text and `e\` + newline hands the
+ # next line to the same shell.
end = _end_of_text(i)
payloads.append(_sed_text(program[i:end]))
i = end
@@ -908,24 +835,21 @@ def _sed_exec_payloads(program: str) -> "list[str]":
def _assignment_bindings(
tokens: "list[str]", quoted: "frozenset[int]" = frozenset()
) -> "list[tuple[int, str, str | None]]":
- """Every `NAME=value` word as ``(token index, name, value)``, in the order
- the shell performs the assignments.
-
- An ordered LIST, not a map, because bash uses the binding performed most
- recently BEFORE the reference: first-wins let
- `p='1,3p'; p='1e rm -f victim'; sed "$p" input` read as `1,3p` while rm
- really runs. The index rides along so _bindings_before can drop the
- assignments that only happen after the sed.
-
- A non-literal value is recorded as ``None``, which CLEARS the name rather
- than leaving a stale earlier one standing, since resolving to that would
- invent a program rather than read one.
-
- Only a word that really changes SHELL state counts. An assignment-shaped
- ARGUMENT (`echo p='1,3p'`), one in a subshell and one used as a command's
- environment prefix all leave `$p` alone, and recording them overwrote a
- payload with a value bash never assigned; all three run rm for real. A
- conditional one after `&&` may or may not run, so it is UNRESOLVED instead.
+ """Every `NAME=value` word as ``(token index, name, value)``, in the order the shell performs the
+ assignments.
+
+ An ordered LIST, not a map, because bash uses the binding performed most recently BEFORE the
+ reference: first-wins let `p='1,3p'; p='1e rm -f victim'; sed "$p" input` read as `1,3p` while
+ rm really runs. The index rides along so _bindings_before can drop assignments that only happen
+ after the sed.
+
+ A non-literal value is recorded as ``None``, which CLEARS the name rather than leaving a stale
+ earlier one standing.
+
+ Only a word that really changes SHELL state counts: an assignment-shaped ARGUMENT, one in a
+ subshell and one used as a command's environment prefix all leave `$p` alone, and recording them
+ overwrote a payload with a value bash never assigned. A conditional one after `&&` may or may
+ not run, so it is UNRESOLVED instead.
"""
bindings: "list[tuple[int, str, str | None]]" = []
pending: "list[tuple[int, str, str | None]]" = [] # the run at this position
@@ -953,9 +877,8 @@ def _assignment_bindings(
at_command = True
continue
if function_body and _ASSIGNMENT_RE.match(token):
- # A body bash has not run yet, and may never run: `p='1e rm -f
- # victim'; f() { p='1,3p'; }; sed "$p" input` really runs rm.
- # Clearing the name is right whether or not f is ever called.
+ # A body bash has not run yet, and may never run. Clearing the name is right whether or not f is ever
+ # called.
name = token.partition("=")[0]
pending.append((index, name, None))
continue
@@ -966,8 +889,8 @@ def _assignment_bindings(
pending.append((index, name, None if conditional else literal))
continue
if at_command:
- # A command word: the run in front of it is that command's
- # ENVIRONMENT, which bash hands the CHILD and not itself.
+ # A command word: the run in front of it is that command's ENVIRONMENT, which bash hands the CHILD and not
+ # itself.
pending = []
at_command = False
bindings.extend(pending)
@@ -977,11 +900,10 @@ def _assignment_bindings(
def _bindings_before(
bindings: "list[tuple[int, str, str | None]]", cursor: int, limit: int, env: "dict[str, str]"
) -> int:
- """Fold into ``env`` every binding at a token index below ``limit``, starting
- at ``cursor``, and return the cursor to pass in next time. Later bindings
- overwrite earlier ones, so ``env`` holds what the shell would have in scope
- at token ``limit``. Seds are visited left to right, so the cursor only moves
- forward and the whole line costs ONE walk of the binding list."""
+ """Fold into ``env`` every binding at a token index below ``limit``, starting at ``cursor``, and
+ return the cursor to pass in next time. Later bindings overwrite earlier ones. Seds are
+ visited left to right, so the cursor only moves forward and the whole line costs ONE walk of
+ the binding list."""
while cursor < len(bindings) and bindings[cursor][0] < limit:
_index, name, value = bindings[cursor]
if value is None:
@@ -993,21 +915,16 @@ def _bindings_before(
def _resolve_program_vars(program: str, env: "dict[str, str]") -> str:
- """``program`` with each `$NAME` / `${NAME}` replaced by its assigned value.
-
- A sed script held in a variable (`p='# note<newline>e CMD'; sed "$p" f`) is
- only a program once the reference is resolved, and only in a pass that KEEPS
- the quoted newline: the blanket newline pass turns the value into one long
- sed comment. An unassigned name is left as written, so nothing is invented.
- """
+ """``program`` with each `$NAME` / `${NAME}` replaced by its assigned value. A sed script held
+ in a variable is only a program once the reference is resolved, and only in a pass that KEEPS
+ the quoted newline: the blanket newline pass turns the value into one long sed comment. An
+ unassigned name is left as written."""
return _PROGRAM_VAR_RE.sub(lambda m: env.get(m.group(1) or m.group(2), m.group(0)), program)
def _sed_program_variants(program: str, env: "dict[str, str]") -> "list[str]":
- """The sed program as written, plus the variable-resolved and
- arithmetic-collapsed forms. All are screened, because any spelling can be the
- one holding the `e`: the raw text in `sed "e $file"`, the resolved one in
- `sed "$p"`, the collapsed one in `sed "$((c+1))e rm -f victim"`."""
+ """The sed program as written, plus the variable-resolved and arithmetic-collapsed forms. All
+ are screened, because any spelling can be the one holding the `e`."""
if "$" not in program:
return [program]
variants = [program]
@@ -1022,33 +939,28 @@ def _sed_program_variants(program: str, env: "dict[str, str]") -> "list[str]":
def _expansion_key(text: str) -> str:
- """One expansion, keyed so the raw-command spelling and the post-lex one
- compare equal. Only the escaping differs between them, so it is dropped."""
+ """One expansion, keyed so the raw-command spelling and the post-lex one compare equal. Only the
+ escaping differs between them, so it is dropped."""
return text.replace("\\", "")
def _sed_program_unresolved(variants: "list[str]", live: "set[str]") -> bool:
- """Whether NO spelling of the sed program is one this scan actually READ,
- because every one still holds an expansion bash would rewrite.
-
- The program is knowable only when each expansion reduces to text:
- `p='1,3p'; sed "$p" f` does, `sed "${p#x }" f` does not. The parameter
- transformations (`${p%y}`, `${p/a/b}`, `${p:-z}`, `${p^^}`, `${!p}`, ...) are
- not modelled one at a time; an unread program is UNKNOWN and the auto gate
- asks, which makes every unmodelled form safe by default rather than a way
- past (`p='x e rm -f victim'; sed "${p#x }" input` really runs rm).
-
- Only expansions the shell RUNS count, and only where they land in the
- PROGRAM, so one the program merely quotes (`sed 's/$(x)/y/' f`), an escaped
- one (`sed "s/\\$(CC)/gcc/" Makefile`) and one in a FILE operand
- (`sed -n '1,3p' $(ls)`) are all left running.
+ """Whether NO spelling of the sed program is one this scan actually READ, because every one still
+ holds an expansion bash would rewrite.
+
+ The program is knowable only when each expansion reduces to text. The parameter transformations
+ (`${p%y}`, `${p/a/b}`, `${p:-z}`, ...) are not modelled one at a time; an unread program is
+ UNKNOWN and the auto gate asks, which makes every unmodelled form safe by default rather than a
+ way past.
+
+ Only expansions the shell RUNS count, and only where they land in the PROGRAM, so one the
+ program merely quotes, an escaped one and one in a FILE operand are all left running.
"""
if not live:
return False
- # shlex removes the escaping as it splits, so the SAME expansion is spelled
- # one way in the raw command and another in the token, and an exact
- # comparison read a generated program as one already read. Keying both sides
- # without backslashes can only make a spelling MATCH, so it fails closed.
+ # shlex removes the escaping as it splits, so the SAME expansion is spelled one way in the raw command and another
+ # in the token, and an exact comparison read a generated program as one already read. Keying both sides without
+ # backslashes can only make a spelling MATCH, so it fails closed.
keys = {_expansion_key(found) for found in live}
return not any(
all(_expansion_key(found) not in keys for found in _shell_expansions(variant, quoted = False))
@@ -1057,18 +969,16 @@ def _sed_program_unresolved(variants: "list[str]", live: "set[str]") -> bool:
def _quoted_separator_indexes(text: str, tokens: "list[str]", punctuation: str) -> "frozenset[int]":
- """Indexes of ``tokens`` that only LOOK like a shell separator because the
- quoting has been stripped off them.
-
- shlex hands back the identical token `;` for a real separator and for a
- quoted `';'` a command receives as data, so `sed -n ';' -e '1e rm -f victim'
- input` looked like a sed that had already ended and the `-e` script behind
- the `;` was never read (verified on GNU sed 4.9: it runs rm).
-
- Told apart by masking every separator character the shell QUOTES and lexing
- a second time. Only those characters change, and each inside the word it
- already belonged to, so the two token lists line up; the alignment is
- asserted by the length check, and anything unexpected reports nothing.
+ """Indexes of ``tokens`` that only LOOK like a shell separator because the quoting has been
+ stripped off them.
+
+ shlex hands back the identical token `;` for a real separator and for a quoted `';'` a command
+ receives as data, so `sed -n ';' -e '1e rm -f victim' input` looked like a sed that had already
+ ended (verified on GNU sed 4.9: it runs rm).
+
+ Told apart by masking every separator character the shell QUOTES and lexing a second time. Only
+ those characters change, and each inside the word it already belonged to, so the two token lists
+ line up; the alignment is asserted by the length check.
"""
if not any(_looks_like_separator(token) for token in tokens):
# Nothing to tell apart: skip the quote walk and the second lex.
@@ -1100,11 +1010,10 @@ def _quoted_separator_indexes(text: str, tokens: "list[str]", punctuation: str)
def _masked_tokens(
text: str, tokens: "list[str]", punctuation: str, chars: "frozenset[str]", mark: str
) -> "list[str] | None":
- """``tokens`` re-lexed with every one of ``chars`` the QUOTING made literal
- replaced by ``mark``, or ``None`` when the two lexes do not line up and
- nothing can be said. Each replacement stays inside the word it already
- belonged to, so the second lex yields the same words; the alignment is
- asserted by the length check rather than assumed."""
+ """``tokens`` re-lexed with every one of ``chars`` the QUOTING made literal replaced by
+ ``mark``, or ``None`` when the two lexes do not line up. Each replacement stays inside the
+ word it already belonged to, so the second lex yields the same words; the alignment is
+ asserted by the length check."""
if not any(char in chars for char in text) or mark in text:
return None
states = _shell_quote_states(text)
@@ -1123,14 +1032,10 @@ def _masked_tokens(
def _quoted_redirection_indexes(
text: str, tokens: "list[str]", punctuation: str
) -> "frozenset[int]":
- """Indexes of ``tokens`` that only LOOK like a redirection because the
- quoting has been stripped off them.
-
- A QUOTED redirection is a word the shell hands the command: `sed -f '>prog'
- -e '1e rm -f victim' input` takes `>prog` as the script FILE and really runs
- the payload. Decided on the operator the token OPENS with, so `2>'/dev/null'`
- keeps its bare `2>` and stays a redirection while `'>prog'` does not.
- """
+ """Indexes of ``tokens`` that only LOOK like a redirection because the quoting has been stripped
+ off them. A QUOTED redirection is a word the shell hands the command: `sed -f '>prog' -e '1e
+ rm -f victim' input` takes `>prog` as the script FILE and really runs the payload. Decided on
+ the operator the token OPENS with, so `2>'/dev/null'` stays a redirection."""
marked = _masked_tokens(text, tokens, punctuation, _REDIRECT_CHARS, _QUOTED_REDIRECT_MARK)
if marked is None:
return frozenset()
@@ -1144,17 +1049,11 @@ def _quoted_redirection_indexes(
def _unquoted_expansion_indexes(
text: str, tokens: "list[str]", punctuation: str
) -> "frozenset[int]":
- """Indexes of ``tokens`` holding an expansion the shell really PERFORMS.
-
- Live expansions are collected over the whole command, so matching a sed
- program against them by text alone attributed another command's expansion to
- a program that merely spells the same thing, and the read-only
- `echo "$p"; sed 's/$p/x/' f` asked. This supplies the missing occurrence.
-
- Double quoting is deliberately not literal: `sed "$p" f` expands and must
- stay in. Only single, ANSI-C and backslash quoting make these characters
- data.
- """
+ """Indexes of ``tokens`` holding an expansion the shell really PERFORMS. Live expansions are
+ collected over the whole command, so matching a sed program against them by text alone
+ attributed another command's expansion to a program that merely spells the same thing; this
+ supplies the missing occurrence. Double quoting is deliberately not literal: `sed "$p" f`
+ expands and must stay in."""
if not any(char in _EXPANSION_CHARS for char in text) or _QUOTED_EXPANSION_MARK in text:
return frozenset()
states = _shell_quote_states(text)
@@ -1180,16 +1079,11 @@ def _unquoted_expansion_indexes(
def _unquoted_glob_indexes(text: str, tokens: "list[str]", punctuation: str) -> "frozenset[int]":
- """Indexes of ``tokens`` holding a pathname-expansion metacharacter the shell
- will EXPAND, rather than one the quoting made literal.
-
- bash expands after this scan, so a word it rewrites is not the word the
- command receives: in a directory holding a file named `1e rm -f victim`,
- `sed *` hands sed that filename as its script and really runs rm. The quoted
- spellings a sed program uses must stay readable (`sed 's/a*/b/' f` expands
- nothing). Told apart by masking and re-lexing, as in
- _quoted_separator_indexes.
- """
+ """Indexes of ``tokens`` holding a pathname-expansion metacharacter the shell will EXPAND,
+ rather than one the quoting made literal. bash expands after this scan, so in a directory
+ holding a file named `1e rm -f victim`, `sed *` hands sed that filename as its script and
+ really runs rm. The quoted spellings a sed program uses must stay readable. Told apart by
+ masking and re-lexing."""
if not any(char in _GLOB_CHARS for char in text) or _QUOTED_GLOB_MARK in text:
return frozenset()
states = _shell_quote_states(text)
@@ -1211,10 +1105,9 @@ def _unquoted_glob_indexes(text: str, tokens: "list[str]", punctuation: str) ->
def _xargs_replacement(tokens: "list[str]", start: int, end: int) -> str:
- """The placeholder the xargs word at ``start`` substitutes into the command
- words behind it, or "" when it replaces nothing. GNU xargs takes it attached
- (`-I{}`), as the next word (`-I {}`) or after an `=` (`--replace={}`); `-i`
- and a bare `--replace` default to `{}`."""
+ """The placeholder the xargs word at ``start`` substitutes into the command words behind it, or
+ "" when it replaces nothing. GNU xargs takes it attached (`-I{}`), as the next word or after
+ an `=`; `-i` and a bare `--replace` default to `{}`."""
index = start + 1
while index < end:
token = tokens[index]
@@ -1232,19 +1125,11 @@ def _xargs_replacement(tokens: "list[str]", start: int, end: int) -> str:
def _xargs_hides_sed_program(tokens: "list[str]", xargs: int, sed: int, program: str) -> bool:
- """Whether an xargs is the one deciding what program its sed runs.
-
- xargs appends the words it reads on stdin, and with -I substitutes them into
- the words already there, so the program need not be in the command TEXT at
- all. Both of these run rm for real, one holding no program and the other only
- the placeholder, so the sed fails closed:
- printf '1e rm -f victim\\0input\\0' | xargs -0 sed
- printf '1e rm -f victim\\n' | xargs -I{} sed '{}' input
- The ordinary idioms are untouched, since their program is right there and the
- placeholder stands where the FILE goes:
- find . -name '*.py' | xargs sed -i 's/a/b/g'
- find . -name '*.py' | xargs -I{} sed -i 's/a/b/' {}
- """
+ """Whether an xargs is the one deciding what program its sed runs. xargs appends the words it
+ reads on stdin, and with -I substitutes them into the words already there, so the program
+ need not be in the command TEXT at all (`printf '1e rm -f victim\0input\0' | xargs -0 sed`
+ runs rm), and the sed fails closed. The ordinary idioms are untouched, since their program is
+ right there and the placeholder stands where the FILE goes."""
if not program.strip():
return True
placeholder = _xargs_replacement(tokens, xargs, sed)
@@ -1252,20 +1137,16 @@ def _xargs_hides_sed_program(tokens: "list[str]", xargs: int, sed: int, program:
def _sed_program_is_a_placeholder(program: str) -> bool:
- """Whether the whole sed program is a token another tool REWRITES before sed
- starts. find replaces `{}` with the pathname it found, so with a file named
- `1e rm -f victim` the line
- `printf 'input' | find '1e rm -f victim' -exec xargs sed {} +` really runs rm
- while `{}` read as an already-known program. A `{}` among the FILE operands
- (`find . -exec sed -i 's/a/b/' {} +`) is not the program and is untouched."""
+ """Whether the whole sed program is a token another tool REWRITES before sed starts. find
+ replaces `{}` with the pathname it found, so with a file named `1e rm -f victim` a `find ...
+ -exec xargs sed {} +` really runs rm while `{}` read as an already-known program. A `{}`
+ among the FILE operands is not the program and is untouched."""
return program.strip() == "{}"
def _forwards_exec_flags(base: str) -> bool:
- """Whether a command word runs a tool whose `-exec` / `-x` options hand the
- words behind them to a child command. Exact names, plus any command-position
- GLOB that could expand to one, so `/usr/bin/fin[d] . -exec rm {} \\;` is not
- read as an ordinary word."""
+ """Whether a command word runs a tool whose `-exec` / `-x` options hand the words behind them to
+ a child command. Exact names, plus any command-position GLOB that could expand to one."""
if base in _EXEC_FLAG_FORWARDING_COMMANDS:
return True
return _is_unresolved_command_glob(base) and any(
@@ -1278,23 +1159,19 @@ def _exec_scan_layout(
quoted: "frozenset[int]",
quoted_redirects: "frozenset[int]" = frozenset(),
) -> "tuple[frozenset[int], frozenset[int], frozenset[int]]":
- """``(exec-flag indexes, invocation-stop indexes, redirection indexes)`` for
- one token list, in a single left-to-right pass.
-
- An exec-flag index is a `find`/`fd` option whose following words are a
- COMMAND that tool runs. Recognised only while a find/fd word the shell
- really RUNS is in scope: those letters belong to too many other tools, so
- `grep -x rm file` and the grep `-x` in `find . -exec grep -x rm {} \\;` must
- not have rm hard-blocked.
-
- A stop index ends a sed invocation: a separator the shell PERFORMS, or the
- `;` / `{} +` closing an open exec action. Outside an action those are
- ordinary operands, which keeps `sed -n ';' -e '1e rm -f victim' input`
- readable while a real terminator still stops the scan.
-
- A redirection index is a word the shell consumes and never hands to the
- command. Taken FIRST, so the `&` in `sed 2>&1 '1e rm -f victim' input` reads
- as part of that redirection rather than as the end of the invocation.
+ """``(exec-flag indexes, invocation-stop indexes, redirection indexes)`` for one token list, in a
+ single left-to-right pass.
+
+ An exec-flag index is a `find`/`fd` option whose following words are a COMMAND that tool runs.
+ Recognised only while a find/fd word the shell really RUNS is in scope: those letters belong to
+ too many other tools, so `grep -x rm file` must not have rm hard-blocked.
+
+ A stop index ends a sed invocation: a separator the shell PERFORMS, or the `;` / `{} +` closing
+ an open exec action. Outside an action those are ordinary operands.
+
+ A redirection index is a word the shell consumes and never hands to the command. Taken FIRST, so
+ the `&` in `sed 2>&1 '1e rm -f victim' input` reads as part of that redirection rather than as
+ the end of the invocation.
"""
exec_flags: "set[int]" = set()
stops: "set[int]" = set()
@@ -1324,17 +1201,14 @@ def _exec_scan_layout(
if in_action and (
token in _FIND_EXEC_SEMICOLONS or (token == "+" and here and tokens[here - 1] == "{}")
):
- # find ends the batched form at `{} +` only: a `+` anywhere else is
- # an ordinary argument it hands the child, so
- # `find . -exec sed -n '+' -e '1e touch MARKER' {} +` really runs the
- # payload. The `;` forms need no such test: a quoted `';'` and an
- # escaped `\\;` reach find as the same word and both terminate.
+ # find ends the batched form at `{} +` only: a `+` anywhere else is an ordinary argument it hands the
+ # child, so `find . -exec sed -n '+' -e '1e touch MARKER' {} +` really runs the payload. The `;` forms
+ # need no such test.
stops.add(here)
in_action = False
continue
if forwarding and token == "--" and not in_action:
- # Nothing behind fd's `--` is an option: `fd -- -x rm` merely lists
- # `rm/-x` and was being refused.
+ # Nothing behind fd's `--` is an option: `fd -- -x rm` merely lists `rm/-x` and was being refused.
forwarding = False
at_command = False
continue
@@ -1346,8 +1220,8 @@ def _exec_scan_layout(
in_action = True
continue
if forwarding and not in_action and token[:2] in {"-x", "-X"} and len(token) > 2:
- # fd takes the command attached to the short option too:
- # `fd '^victim$' . -xrm` deletes the match for real (fdfind 9.0.0).
+ # fd takes the command attached to the short option too: `fd '^victim$' . -xrm` deletes the match for real
+ # (fdfind 9.0.0).
exec_flags.add(here)
in_action = True
continue
@@ -1357,9 +1231,8 @@ def _exec_scan_layout(
skip_operand = False # a wrapper option's value (env -u NAME)
continue
if token.startswith("-") or _ASSIGNMENT_RE.match(token):
- # A wrapper option whose value is a SEPARATE token precedes that
- # value and not the wrapped command, so `env -u FOO find ...` keeps
- # looking for find rather than stopping at FOO.
+ # A wrapper option whose value is a SEPARATE token precedes that value and not the wrapped command, so
+ # `env -u FOO find ...` keeps looking for find.
skip_operand = token in _WRAPPER_VALUE_FLAGS_BY_CMD.get(wrapper, frozenset())
continue
if wrapper and token.lstrip("-").isdigit():
@@ -1369,9 +1242,8 @@ def _exec_scan_layout(
wrapper = base
continue
if at_command and _forwards_exec_flags(base):
- # Only a find/fd the shell really RUNS forwards its exec flags. Any
- # token spelled `fd`/`find` used to turn one on, so `echo fd -x rm`
- # and `grep fd -x rm file` came back with rm and were refused.
+ # Only a find/fd the shell really RUNS forwards its exec flags. Any token spelled `fd`/`find` used to turn
+ # one on, so `echo fd -x rm` came back with rm and was refused.
forwarding = True
at_command = False
wrapper = ""
@@ -1383,17 +1255,16 @@ def _win_switch(token: str) -> str:
return token[1:] if token.startswith("//") else token
-# `start` launches its argument as a program, so that argument is a command
-# position. These switches precede it; the value-taking ones eat a token.
+# `start` launches its argument as a program, so that argument is a command position. These switches precede it; the
+# value-taking ones eat a token.
_START_SWITCHES_WITH_VALUE = {"/d", "/node", "/affinity", "/machine"}
-# A slash, one letter, optional `:value` (/s, /v:on, /t:0a). Matched in full so
-# a program spelled as a path (/bin/bash) is never skipped as a switch.
+# A slash, one letter, optional `:value` (/s, /v:on, /t:0a). Matched in full so a program spelled as a path
+# (/bin/bash) is never skipped as a switch.
_CMD_SWITCH_RE = re.compile(r"/[a-zA-Z](?::[\w.]+)?")
-# START's documented switches. Matched by name rather than by a leading slash,
-# because MSYS rewrites a POSIX path argument and hands cmd back something like
-# /c/Windows/.../powershell.exe, which is a program and not a switch.
+# START's documented switches. Matched by name rather than by a leading slash, because MSYS rewrites a POSIX path
+# argument and hands cmd back something like /c/Windows/.../powershell.exe, which is a program and not a switch.
_START_SWITCHES = frozenset(
{
"/min",
@@ -1418,14 +1289,11 @@ _START_SWITCHES = frozenset(
def _is_start_title(token: str) -> bool:
- """True when START would read ``token`` as its window title, not the program.
-
- The cmd lexer keeps the quote marks, so a title still arrives quoted. The
- posix lexer has stripped them, leaving two spellings a bare program name
- cannot have: the empty ``start ""`` idiom, and a title containing
- whitespace. A single-word posix title (``start "job" prog``) is
- indistinguishable from a program name and is deliberately not guessed.
- """
+ """True when START would read ``token`` as its window title, not the program. The cmd lexer
+ keeps the quote marks, so a title still arrives quoted; the posix lexer leaves two spellings
+ a bare program name cannot have, the empty ``start ""`` idiom and a title containing
+ whitespace. A single-word posix title is indistinguishable from a program name and is
+ deliberately not guessed."""
return (
token == ""
or any(char.isspace() for char in token)
@@ -1436,25 +1304,20 @@ def _is_start_title(token: str) -> bool:
def _find_blocked_commands(command: str) -> set[str]:
"""Detect blocked commands at shell command position only.
- A token is at command position if it is the first token, or follows a
- shell separator / brace-group opener / new-command keyword (`then`, `do`,
- etc.), or a command-prefix wrapper like `env` / `time` / `xargs` (next
- token is the real command). Tokens in argument position (`grep -r curl .`,
- `echo source the data`, `ls /usr/bin/curl`) pass through. Also scans
- `find ... -exec CMD` and recurses into bash -c / cmd /c.
+ A token is at command position if it is the first token, or follows a shell separator /
+ brace-group opener / new-command keyword, or a command-prefix wrapper like `env` / `time` /
+ `xargs`. Tokens in argument position pass through. Also scans `find ... -exec CMD` and recurses
+ into bash -c / cmd /c.
"""
blocked: set[str] = set()
- # Decode ANSI-C quoting first ($'ssh' -> ssh) so a blocked name hidden behind
- # it is still detected at command position.
+ # Decode ANSI-C quoting first ($'ssh' -> ssh) so a blocked name hidden behind it is still detected at command
+ # position.
command = _decode_ansi_c(command, keep_one_word = True)
- # punctuation_chars splits separators into their own tokens, so command
- # position is detected even in `echo done; rm -rf x` (no whitespace).
- # Keyed to the shell that will actually run this, not to the OS: on a
- # Windows host with bash the non-posix lexer never split on `;`, so the
- # command after a control-flow keyword stayed unread and
- # `if true; then rm -rf x; fi` came back with nothing blocked.
+ # punctuation_chars splits separators into their own tokens, so command position is detected even in `echo done;
+ # rm -rf x`. Keyed to the shell that will actually run this, not to the OS: on a Windows host with bash the
+ # non-posix lexer never split on `;`, so `if true; then rm -rf x; fi` came back with nothing blocked.
lexed_posix = _shell_is_posix()
try:
if not lexed_posix:
@@ -1466,11 +1329,9 @@ def _find_blocked_commands(command: str) -> set[str]:
except ValueError:
tokens = command.split()
lexed_posix = False
- # Which separator tokens the shell only produced because the quoting was
- # stripped. The non-posix (cmd) lexer KEEPS the quote marks, so a quoted
- # `';'` never looks like a separator there and nothing has to be recovered;
- # the split() fallback has no quoting model at all, so it reports nothing
- # either and both shells reach the same verdict.
+ # Which separator tokens the shell only produced because the quoting was stripped. The non-posix (cmd) lexer KEEPS
+ # the quote marks and the split() fallback has no quoting model, so both report nothing and reach the same
+ # verdict.
quoted_separators = (
_quoted_separator_indexes(command, tokens, ";&|()`") if lexed_posix else frozenset()
)
@@ -1493,20 +1354,17 @@ def _find_blocked_commands(command: str) -> set[str]:
return base
def _exec_child_index(start: int) -> "tuple[int, bool]":
- """The command a `find -exec` actually runs, as ``(index, overflowed)``;
- the index is -1 when the action holds no command word at all.
-
- Command prefixes forward to their target, so `-exec env sed ...` runs
- sed. Wrapper flags, assignment prefixes and duration operands are
- stepped over as the walk above does, and a wrapper option taking a
- SEPARATE value consumes it too, else that value reads as the command
- (`-exec env -u FOO sed ...` came back with `FOO`). The hop is bounded so
+ """The command a `find -exec` actually runs, as ``(index, overflowed)``; the index is -1 when
+ the action holds no command word at all.
+
+ Command prefixes forward to their target, so `-exec env sed ...` runs sed. Wrapper flags,
+ assignment prefixes and duration operands are stepped over, and a wrapper option taking a
+ SEPARATE value consumes it too, else that value reads as the command. The hop is bounded so
`-exec env -exec env ...` cannot make this quadratic.
- ``overflowed`` says the bound ran out with words still ahead. That is
- NOT the same as finding nothing, and reporting both as "no child" let a
- long enough chain read as safe: `-exec` + 33 `env` + `rm -f victim ;`
- really deletes. The caller fails closed on it.
+ ``overflowed`` says the bound ran out with words still ahead. That is NOT the same as
+ finding nothing, and reporting both as "no child" let a long enough chain read as safe:
+ `-exec` + 33 `env` + `rm -f victim ;` really deletes.
"""
i, steps, wrapper = start, 0, ""
while i < len(tokens) and steps < _MAX_EXEC_PREFIX_SCAN:
@@ -1515,11 +1373,9 @@ def _find_blocked_commands(command: str) -> set[str]:
return -1, False
steps += 1
if wrapper and token in _WRAPPER_VALUE_FLAGS_BY_CMD.get(wrapper, frozenset()):
- # `env -u NAME`, `stdbuf -o L`: the option and its operand, both
- # consumed in ONE step -- the budget bounds the work done per
- # -exec, and stepping over two tokens costs no more than one.
- # An attached spelling (-uNAME, --unset=NAME) carries its own
- # value and is skipped by the plain-option branch below.
+ # `env -u NAME`, `stdbuf -o L`: the option and its operand, both consumed in ONE step, since the
+ # budget bounds the work done per -exec. An attached spelling carries its own value and is skipped by
+ # the plain-option branch below.
i += 2
continue
if wrapper and (
@@ -1534,8 +1390,8 @@ def _find_blocked_commands(command: str) -> set[str]:
i += 1
continue
return i, False
- # Walking off the end means the action really held nothing; stopping on
- # the bound with words still ahead means the child is merely UNREAD.
+ # Walking off the end means the action really held nothing; stopping on the bound with words still ahead means
+ # the child is merely UNREAD.
return -1, steps >= _MAX_EXEC_PREFIX_SCAN and i < len(tokens)
expect_command = True # start of string is a command position
@@ -1547,8 +1403,8 @@ def _find_blocked_commands(command: str) -> set[str]:
xargs_index = -1 # an xargs awaiting the command it wraps
for token_index, token in enumerate(tokens):
if skip_operand:
- # `exec -a NAME cmd` and `if exist FILE cmd` both put an operand
- # where the command word would otherwise be.
+ # `exec -a NAME cmd` and `if exist FILE cmd` both put an operand where the command word would otherwise
+ # be.
skip_operand = False
continue
if expect_command and token.lower() in _WIN_CONDITIONAL_KEYWORDS:
@@ -1558,16 +1414,12 @@ def _find_blocked_commands(command: str) -> set[str]:
skip_operand = True
continue
if token_index in redirect_indexes:
- # The shell performs the redirection and hands the command neither
- # word, so command position is unchanged by it: `> out.txt rm -rf
- # victim` and `2>&1 rm -rf victim` both really delete, while reading
- # `out.txt` (and the `1`) as the command word left the `rm` behind
- # it in argument position and the blocklist came back empty.
+ # The shell performs the redirection and hands the command neither word, so command position is unchanged
+ # by it: reading `out.txt` as the command word left the `rm` behind it in argument position and the
+ # blocklist came back empty, while `> out.txt rm -rf victim` really deletes.
continue
- # A keyword only separates where a COMMAND may start (see below).
- # A quoted operator is DATA the command receives, not a separator, so it
- # leaves command position alone: `printf '%s' '|&' rm` and
- # `grep '|&' rm file` run nothing and must not be refused.
+ # A keyword only separates where a COMMAND may start. A quoted operator is DATA the command receives, not a
+ # separator, so it leaves command position alone: `grep '|&' rm file` runs nothing and must not be refused.
if (_looks_like_separator(token) and token_index not in quoted_separators) or (
token in _SHELL_KEYWORDS_AS_SEP and expect_command
):
@@ -1577,19 +1429,16 @@ def _find_blocked_commands(command: str) -> set[str]:
xargs_index = -1
continue
if token.startswith("-"):
- # A wrapper option whose value is a SEPARATE token precedes that
- # value, not the wrapped command. Without consuming it the value is
- # read as the command word and the real command behind it is never
- # reached: `env -u PATH rm -rf x` and `xargs -I {} rm -rf build`
- # both came back empty. An attached spelling (-uPATH, --unset=PATH)
- # carries its own value and falls through to the plain-flag case.
+ # A wrapper option whose value is a SEPARATE token precedes that value, not the wrapped command. Without
+ # consuming it the value is read as the command word and the real command behind it is never reached (`env
+ # -u PATH rm -rf x` came back empty). An attached spelling falls through to the plain-flag case.
if prefix_pending and token in _WRAPPER_VALUE_FLAGS_BY_CMD.get(
prefix_command, frozenset()
):
skip_operand = True
continue
- # Flags belong to the active command, but keep expect_command while a
- # wrapper prefix awaits its command (`stdbuf -oL cmd`, `xargs -- cmd`).
+ # Flags belong to the active command, but keep expect_command while a wrapper prefix awaits its command
+ # (`stdbuf -oL cmd`, `xargs -- cmd`).
if not prefix_pending:
expect_command = False
continue
@@ -1613,8 +1462,8 @@ def _find_blocked_commands(command: str) -> set[str]:
blocked.add(base)
else:
blocked |= _blocked_matching_glob(base)
- # Wrappers (env/time/xargs/sudo) consume one command; the next non-flag,
- # non-numeric token is the real command. sudo is also in _BLOCKED_COMMANDS.
+ # Wrappers (env/time/xargs/sudo) consume one command; the next non-flag, non-numeric token is the real
+ # command. sudo is also in _BLOCKED_COMMANDS.
if base in _COMMAND_PREFIXES:
if base == "xargs" and xargs_index < 0:
xargs_index = token_index
@@ -1626,8 +1475,8 @@ def _find_blocked_commands(command: str) -> set[str]:
prefix_command = ""
xargs_index = -1
- # `alias zap='rm -rf'` stores a command bash runs when the alias is invoked,
- # so the body is scanned as a command in its own right.
+ # `alias zap='rm -rf'` stores a command bash runs when the alias is invoked, so the body is scanned as a command
+ # in its own right.
for i, tok in enumerate(tokens):
if _token_basename(tok) != "alias":
continue
@@ -1638,63 +1487,53 @@ def _find_blocked_commands(command: str) -> set[str]:
if _sep and _value:
blocked |= _find_blocked_commands(_value)
- # `find ... -exec CMD ... ;`, `-execdir CMD ... ;` and fd's `-x` / `-X` /
- # `--exec` / `--exec-batch` all invoke CMD directly (_exec_scan_layout picks
- # which spellings count where). Reading only find's own flags left every fd
- # form unscanned, so `fd -x rm -rf x` and `fd -x sed '1e rm -f victim' {}`
- # -- both verified to run -- reached the hard blocklist as nothing at all.
+ # find's `-exec`/`-execdir` and fd's `-x` / `-X` / `--exec` / `--exec-batch` all invoke CMD directly. Reading only
+ # find's own flags left every fd form unscanned, so `fd -x rm -rf x` reached the hard blocklist as nothing at all.
for i, tok in enumerate(tokens):
- # The long flags also carry the command attached (fd --exec=rm), where
- # the value is command position rather than a discarded option argument.
+ # The long flags also carry the command attached (fd --exec=rm), where the value is command position rather
+ # than a discarded option argument.
attached = ""
if tok[:2] in {"-x", "-X"} and len(tok) > 2 and i in exec_flag_indexes:
- # fd takes the command attached to the short option (`fd ... -xrm`),
- # where the value is command position rather than an option argument.
+ # fd takes the command attached to the short option (`fd ... -xrm`), where the value is command position
+ # rather than an option argument.
attached = tok[2:].strip("\"'")
elif "=" in tok and tok.split("=", 1)[0] in _ATTACHED_EXEC_FLAGS:
attached = tok.split("=", 1)[1].strip("\"'")
if attached:
attached_base = _token_basename(attached.split()[0])
if _is_sed_command(attached_base):
- # The words after the flag are that sed's arguments, so its
- # program is screened from the FLAG. fd 9 actually takes them
- # as search paths and runs nothing, so this only ever blocks
- # a command that could not have worked anyway; a spelling
- # that does forward them would otherwise be a free pass.
+ # The words after the flag are that sed's arguments, so its program is screened from the FLAG. fd 9
+ # actually takes them as search paths and runs nothing, so this only blocks a command that could not
+ # have worked anyway; a spelling that does forward them would otherwise be a free pass.
sed_indexes.append(i)
if attached_base in _BLOCKED_COMMANDS:
blocked.add(attached_base)
else:
blocked |= _blocked_matching_glob(attached_base)
if i in exec_flag_indexes and i + 1 < len(tokens):
- # The word right after the flag AND the command it forwards to: a
- # wrapper is a command in its own right (`-exec sudo ls`) as well as
- # a step on the way to another one (`-exec env rm -rf x`), so
- # dropping either half loses a real detection.
+ # The word right after the flag AND the command it forwards to: a wrapper is a command in its own right
+ # (`-exec sudo ls`) as well as a step on the way to another one, so dropping either half loses a real
+ # detection.
child, prefix_overflowed = _exec_child_index(i + 1)
if prefix_overflowed:
- # The wrapper chain outran the hop budget, so the command that
- # finally runs was never reached: block the chain itself rather
- # than let `-exec env ...x33 rm -f victim ;` ride in behind it.
+ # The wrapper chain outran the hop budget, so the command that finally runs was never reached: block
+ # the chain itself rather than let `-exec env ...x33 rm -f victim ;` ride in behind it.
blocked.add(_token_basename(tokens[i + 1]))
continue
exec_words = [i + 1] if child in (-1, i + 1) else [i + 1, child]
for word in exec_words:
base = _token_basename(tokens[word])
if _is_sed_command(base):
- # find runs its -exec child directly, but the walk above only
- # reaches `find`, so a sed there never got its program
- # screened (`find . -exec sed '1e rm -f victim' {} +`, and
- # behind a wrapper `find . -exec env sed '1e ...' {} +`).
+ # find runs its -exec child directly, but the walk above only reaches `find`, so a sed there never
+ # got its program screened.
sed_indexes.append(word)
if base in _BLOCKED_COMMANDS:
blocked.add(base)
else:
blocked |= _blocked_matching_glob(base)
- # Regex catches blocked words at command boundaries shlex misses: inside
- # $(rm -rf), <(rm), backtick chains, or "foo;rm". Anchored to command-position
- # delimiters, so it doesn't match in argument position.
+ # Regex catches blocked words at command boundaries shlex misses: inside $(rm -rf), <(rm), backtick chains, or
+ # "foo;rm". Anchored to command-position delimiters, so it doesn't match in argument position.
lowered = command.lower()
if _BLOCKED_COMMANDS:
words_alt = "|".join(re.escape(w) for w in sorted(_BLOCKED_COMMANDS))
@@ -1705,8 +1544,7 @@ def _find_blocked_commands(command: str) -> set[str]:
)
blocked.update(re.findall(pattern, lowered))
- # Nested shell invocations (bash -c '...', bash -lc '...', cmd /c '...'):
- # on a -c/-/c flag, look back for a shell name (skipping flags) and
+ # Nested shell invocations (bash -c, cmd /c): on a -c/-/c flag, look back for a shell name (skipping flags) and
# recursively scan the nested command string.
_SHELLS = {"bash", "sh", "zsh", "dash", "ksh", "csh", "tcsh", "fish"}
_SHELLS_WIN = {"cmd", "cmd.exe"}
@@ -1716,36 +1554,35 @@ def _find_blocked_commands(command: str) -> set[str]:
is_unix_c = tok_lower == "-c" or (
tok_lower.startswith("-") and tok_lower.endswith("c") and not tok_lower.startswith("--")
)
- # Git Bash mangles a lone /c into a path, so models write //c and MSYS
- # hands cmd back a single slash; /k runs the payload the same way.
+ # Git Bash mangles a lone /c into a path, so models write //c and MSYS hands cmd back a single slash; /k runs
+ # the payload the same way.
is_win_c = _win_switch(tok_lower) in ("/c", "/k")
if not (is_unix_c or is_win_c) or i < 1 or i + 1 >= len(tokens):
continue
- # Look back past flags for the shell binary. Windows flags and absolute
- # paths both start with /, so only skip things shaped like a whole
- # switch (/s, /v:on) and never a program spelled as a path (/bin/bash).
+ # Look back past flags for the shell binary. Windows flags and absolute paths both start with /, so only skip
+ # things shaped like a whole switch (/s, /v:on) and never a program spelled as a path (/bin/bash).
for j in range(i - 1, -1, -1):
prev = tokens[j]
if prev.startswith("-"):
continue # skip Unix flags like --login, -l
- # Git Bash doubles the slash on these switches too, so normalise
- # them like the trigger: else `cmd //v:on //c powershell` stops here.
+ # Git Bash doubles the slash on these switches too, so normalise them like the trigger: else `cmd //v:on
+ # //c powershell` stops here.
if is_win_c and _CMD_SWITCH_RE.fullmatch(_win_switch(prev)):
continue # skip Windows switches like /s, /q, /v:on
prev_base = os.path.basename(prev).lower()
if is_unix_c and prev_base in _SHELLS:
blocked |= _find_blocked_commands(tokens[i + 1])
elif is_win_c and prev_base in _SHELLS_WIN:
- # The cmd lexer keeps the marks, so `cmd /c "powershell ls"`
- # would recurse on a first word of `"powershell` and match nothing.
+ # The cmd lexer keeps the marks, so `cmd /c "powershell ls"` would recurse on a first word of
+ # `"powershell` and match nothing.
payload = tokens[i + 1]
if len(payload) > 1 and payload[0] == '"' and payload[-1] == '"':
payload = payload[1:-1]
blocked |= _find_blocked_commands(payload)
break # stop at first non-flag token
- # `cmd /c start "" prog` puts prog in a command position the scan above
- # sees only as an argument, so screen what start actually launches.
+ # `cmd /c start "" prog` puts prog in a command position the scan above sees only as an argument, so screen what
+ # start actually launches.
for i, token in enumerate(tokens):
if os.path.basename(token).lower() not in ("start", "start.exe"):
continue
@@ -1753,12 +1590,10 @@ def _find_blocked_commands(command: str) -> set[str]:
while j < len(tokens) and _win_switch(tokens[j].lower()) in _START_SWITCHES:
# /d C:\dir and friends carry their value in the next token.
j += 2 if _win_switch(tokens[j].lower()) in _START_SWITCHES_WITH_VALUE else 1
- # cmd reads a quoted first argument as the window title, putting the
- # program one token further on. Reading that second token only when the
- # first is recognisably a title keeps `echo start notepad powershell`
- # runnable; deciding whether `start` itself is executed is deliberately
- # not attempted, since every local approximation of it under-approximated
- # and let a real launch through.
+ # cmd reads a quoted first argument as the window title, putting the program one token further on. Reading
+ # that second token only when the first is recognisably a title keeps `echo start notepad powershell`
+ # runnable; deciding whether `start` itself is executed is deliberately not attempted, since every local
+ # approximation under-approximated.
if j < len(tokens):
blocked |= _find_blocked_commands(tokens[j])
if j + 1 < len(tokens) and _is_start_title(tokens[j]):
@@ -1769,19 +1604,19 @@ def _find_blocked_commands(command: str) -> set[str]:
if k < len(tokens):
blocked |= _find_blocked_commands(tokens[k])
- # sed's `e COMMAND` hands COMMAND to the shell, a real command position the
- # scan above sees only as a text argument, so screen it like `bash -c`. The
- # pattern-space forms yield an empty payload; the auto gate prompts on those.
+ # sed's `e COMMAND` hands COMMAND to the shell, a real command position the scan above sees only as a text
+ # argument, so screen it like `bash -c`. The pattern-space forms yield an empty payload; the auto gate prompts on
+ # those.
sed_limit = _sed_scan_limit(len(sed_indexes))
- # Built at most once per call, and only when some program actually names a
- # variable, so a line packed with sed words stays linear.
+ # Built at most once per call, and only when some program actually names a variable, so a line packed with sed
+ # words stays linear.
sed_vars: "dict[str, str] | None" = None
sed_bindings: "list[tuple[int, str, str | None]] | None" = None
sed_cursor = 0
# Visited left to right so the binding cursor below only moves forward.
for i in sorted(set(sed_indexes)):
- # A script --sandbox / --posix stops sed compiling is already left out of
- # the program (_sed_invocation), so a name inside one is never blocked.
+ # A script --sandbox / --posix stops sed compiling is already left out of the program, so a name inside one is
+ # never blocked.
if glob_indexes is None:
glob_indexes = (
_unquoted_glob_indexes(command, tokens, ";&|()`") if lexed_posix else frozenset()
@@ -1791,28 +1626,22 @@ def _find_blocked_commands(command: str) -> set[str]:
)
program = "\n".join(alternatives)
if scan_overflowed:
- # The script sits past the scan window, so an empty program here is
- # only ignorance: block the sed itself rather than let an
- # `e rm -rf ~` ride in behind enough padding options.
+ # The script sits past the scan window, so an empty program here is only ignorance: block the sed itself
+ # rather than let an `e rm -rf ~` ride in behind enough padding options.
blocked.add(_token_basename(tokens[i]))
continue
if _sed_program_is_a_placeholder(program):
- # find rewrites `{}` before the child starts, so this is not a
- # program that was read (see _sed_program_is_a_placeholder).
+ # find rewrites `{}` before the child starts, so this is not a program that was read.
blocked.add(_token_basename(tokens[i]))
continue
if i in sed_xargs and _xargs_hides_sed_program(tokens, sed_xargs[i], i, program):
- # The program comes off stdin or out of an -I placeholder, so it is
- # not in the text to read at all (see _xargs_hides_sed_program).
+ # The program comes off stdin or out of an -I placeholder, so it is not in the text to read at all.
blocked.add(_token_basename(tokens[i]))
continue
if "$" in program:
- # A program held in a variable (p='...e rm -f victim'; sed "$p" f)
- # only shows its `e` once the reference is resolved. shlex kept the
- # quoted value whole, newlines and all, so the binding is exact.
- # Only the assignments AHEAD of this sed are in scope, and the last
- # of them wins, which is the pair that `p='1,3p';
- # p='1e rm -f victim'; sed "$p" input` turns on.
+ # A program held in a variable only shows its `e` once the reference is resolved; shlex kept the quoted
+ # value whole, newlines and all, so the binding is exact. Only the assignments AHEAD of this sed are in
+ # scope, and the last of them wins.
if sed_bindings is None:
sed_bindings = _assignment_bindings(tokens, quoted_separators)
sed_vars = {}
@@ -1826,29 +1655,27 @@ def _find_blocked_commands(command: str) -> set[str]:
return blocked
-# Directory holding the sandbox ``sitecustomize.py`` shim (code-interpreter
-# path remap); placed on the sandboxed child's PYTHONPATH in _build_safe_env.
+# Directory holding the sandbox ``sitecustomize.py`` shim (code-interpreter path remap); placed on the sandboxed
+# child's PYTHONPATH in _build_safe_env.
_SANDBOX_SITE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_site")
-# ── "Approve for me" (permission_mode="auto") safety detection ──────────────
-# Auto mode pauses only calls classified here as potentially unsafe. The sandbox
-# and hard blocks (blocklist, rlimits) still apply at run time; this gate only
-# decides prompting, and fails closed: anything not provably read-only asks.
+# "Approve for me" (permission_mode="auto") safety detection. Auto mode pauses only calls classified here as
+# potentially unsafe. The sandbox and hard blocks still apply at run time; this gate only decides prompting, and fails
+# closed: anything not provably read-only asks.
# Read-only commands allowed to run without confirmation in auto mode.
-# ── "Approve for me" (permission_mode="auto") safety detection ──────────────
_AUTO_SAFE_TERMINAL_COMMANDS = frozenset(
{
"ls",
"dir",
"pwd",
- # cd absent: `cd /; cat etc/passwd` escapes the workdir for a later
- # relative read the path scan cannot see, so cd always asks.
+ # cd absent: `cd /; cat etc/passwd` escapes the workdir for a later relative read the path scan cannot see, so
+ # cd always asks.
"cat",
"head",
"tail",
- # less/more absent: their pager escapes (+cmd, !shell, -o, LESSOPEN) can
- # run a command or write a file, so they always ask.
+ # less/more absent: their pager escapes (+cmd, !shell, -o, LESSOPEN) can run a command or write a file, so
+ # they always ask.
"grep",
"egrep",
"fgrep",
@@ -1866,8 +1693,8 @@ _AUTO_SAFE_TERMINAL_COMMANDS = frozenset(
"stat",
"du",
"df",
- # ps absent: BSD env flags (ps auxe, ps eww) dump a parent's unscrubbed
- # env and can't be flag-parsed reliably, so ps always asks.
+ # ps absent: BSD env flags (ps auxe, ps eww) dump a parent's unscrubbed env and can't be flag-parsed reliably,
+ # so ps always asks.
"date",
"cal",
"whoami",
@@ -1919,43 +1746,37 @@ _AUTO_SAFE_TERMINAL_COMMANDS = frozenset(
"jq",
}
)
-# Flags that turn an otherwise read-only command into a writer or executor
-# (sort -o FILE, tree -o FILE, xxd -r IN OUT, find -exec/-delete/...).
+# Flags that turn an otherwise read-only command into a writer or executor (sort -o FILE, tree -o FILE, xxd -r IN OUT,
+# find -exec/-delete).
_AUTO_UNSAFE_COMMAND_FLAGS = {
- # --files0-from=F makes sort read the NUL-separated list of input files
- # named in F, so a crafted list reads arbitrary host files indirectly.
+ # --files0-from=F makes sort read the NUL-separated list of input files named in F, so a crafted list reads
+ # arbitrary host files indirectly.
"sort": frozenset(
{"-o", "--output", "--compress-program", "-T", "--temporary-directory", "--files0-from"}
),
"tree": frozenset({"-o"}),
"xxd": frozenset({"-r"}),
- # -c/--check makes a checksum tool read a manifest file and then read every
- # path it names, so a manifest listing /etc/passwd turns `sha256sum -c list`
- # into an indirect host-file read; the digest form (sha256sum file) only reads
- # the named files.
+ # -c/--check makes a checksum tool read a manifest and then every path it names, so a manifest listing /etc/passwd
+ # turns `sha256sum -c list` into an indirect host-file read; the digest form only reads the named files.
"md5sum": frozenset({"-c", "--check"}),
"sha1sum": frozenset({"-c", "--check"}),
"sha256sum": frozenset({"-c", "--check"}),
"shasum": frozenset({"-c", "--check"}),
"cksum": frozenset({"-c", "--check"}),
- # GNU time -o/--output/-a/--append FILE writes timing output; time is a
- # wrapper, so the flag is checked before the wrapped command like env -C.
+ # GNU time -o/--output/-a/--append FILE writes timing output; time is a wrapper, so the flag is checked before the
+ # wrapped command like env -C.
"time": frozenset({"-o", "--output", "-a", "--append"}),
# rg runs an arbitrary program per file with --pre/--hostname-bin.
"rg": frozenset({"--pre", "--hostname-bin"}),
# env -C/--chdir escapes the workdir; -S/--split-string builds a command.
"env": frozenset({"-C", "--chdir", "-S", "--split-string"}),
- # ionice -p/-P/-u change the I/O priority of an already running process /
- # group / user instead of forwarding to a wrapped read-only command, so a
- # bare `ionice -c 3 -p <pid>` mutates another process. ionice stays a safe
- # wrapper for `ionice -c 3 <cmd>`; only the process-target flags ask.
+ # ionice -p/-P/-u change the I/O priority of an already running process instead of forwarding to a wrapped
+ # read-only command, so a bare `ionice -c 3 -p <pid>` mutates another process. Only the process-target flags ask.
"ionice": frozenset({"-p", "-P", "-u"}),
- # printf -v NAME assigns to a shell var, so `printf -v PATH %s .; ls` runs
- # ./ls from the workdir.
+ # printf -v NAME assigns to a shell var, so `printf -v PATH %s .; ls` runs ./ls from the workdir.
"printf": frozenset({"-v"}),
- # wc/du/find --files0-from=F read the NUL-separated list of input paths named
- # in F, so a crafted list reads arbitrary host files past the literal path /
- # root checks, like sort --files0-from. find spells it -files0-from (a primary).
+ # wc/du/find --files0-from=F read the NUL-separated list of input paths named in F, so a crafted list reads
+ # arbitrary host files past the literal path / root checks. find spells it -files0-from (a primary).
"wc": frozenset({"--files0-from"}),
"du": frozenset({"--files0-from"}),
"find": frozenset(
@@ -1972,8 +1793,8 @@ _AUTO_UNSAFE_COMMAND_FLAGS = {
"-files0-from",
}
),
- # fd -x/--exec/-X/--exec-batch run a command per result;
- # --base-directory/--search-path move the search root outside the workdir.
+ # fd -x/--exec/-X/--exec-batch run a command per result; --base-directory/--search-path move the search root
+ # outside the workdir.
"fd": frozenset({"-x", "--exec", "-X", "--exec-batch", "--base-directory", "--search-path"}),
# date -s/--set writes the clock; display forms (+FORMAT, -d/-u/-R/-r) read.
"date": frozenset({"-s", "--set"}),
@@ -1982,44 +1803,35 @@ _AUTO_UNSAFE_COMMAND_FLAGS = {
# hostname -F/--file, -b/--boot set the hostname; display flags only read.
"hostname": frozenset({"-F", "--file", "-b", "--boot"}),
}
-# Commands safe only without a mutating positional: `hostname NAME` sets the
-# hostname, `date MMDDhhmm...` sets the clock (a +FORMAT token or a display
-# flag's value stays read-only), so any other positional asks.
+# Commands safe only without a mutating positional: `hostname NAME` sets the hostname and `date MMDDhhmm...` sets the
+# clock, so any other positional asks.
_AUTO_ARG_SENSITIVE_COMMANDS = frozenset({"hostname", "date"})
-# date display flags taking a value token (-d STRING, -r FILE, -f FILE); the
-# value is not a clock-setting positional, so it is skipped.
+# date display flags taking a value token (-d STRING, -r FILE, -f FILE); the value is not a clock-setting positional,
+# so it is skipped.
_DATE_DISPLAY_VALUE_FLAGS = frozenset({"-d", "--date", "-r", "--reference", "-f", "--file"})
-# Commands that write their 2nd positional (uniq [INPUT [OUTPUT]], xxd [infile
-# [outfile]]): the 1st file reads to stdout, but a second file positional
-# overwrites it, like `sort -o`.
+# Commands that write their 2nd positional (uniq [INPUT [OUTPUT]], xxd [infile [outfile]]): the 1st file reads to
+# stdout, but a second overwrites it.
_AUTO_SECOND_POSITIONAL_WRITES = frozenset({"uniq", "xxd"})
-# Value-taking option flags for those commands whose argument is a separate token
-# (uniq -f 2, xxd -c 16). The value must be consumed so a numeric option value is
-# not miscounted as the output-file positional, and, conversely, a file that is
-# literally named with digits (uniq 123 out) is still counted.
+# Value-taking option flags for those commands whose argument is a separate token (uniq -f 2, xxd -c 16). The value
+# must be consumed so a numeric option value is not miscounted as the output-file positional, and a file literally
+# named with digits is still counted.
_SECOND_POSITIONAL_VALUE_FLAGS = {
"uniq": frozenset({"-f", "--skip-fields", "-s", "--skip-chars", "-w", "--check-chars"}),
"xxd": frozenset(
{"-c", "--cols", "-s", "--seek", "-l", "--len", "-g", "--groupsize", "-o", "--offset"}
),
}
-# find/fd group with (...) which resets command context, so scan every token for
-# these once find/fd appears anywhere.
+# find/fd group with (...) which resets command context, so scan every token for these once find/fd appears anywhere.
_AUTO_UNSAFE_FIND_LIKE_FLAGS = _AUTO_UNSAFE_COMMAND_FLAGS["find"] | _AUTO_UNSAFE_COMMAND_FLAGS["fd"]
-# Recursive readers with an absolute-path target escape the workdir onto host
-# files (grep -R TOKEN /home, rg TOKEN /), so they ask.
+# Recursive readers with an absolute-path target escape the workdir onto host files (grep -R TOKEN /home, rg TOKEN /),
+# so they ask.
_AUTO_RECURSIVE_SEARCH = frozenset({"grep", "egrep", "fgrep", "rg", "ug", "find", "fd"})
-# Directory walkers that always recurse (tree /home, du /) read the whole host
-# subtree under an absolute/tilde root, like a recursive search. ls only recurses
-# with -R/--recursive, so it is gated separately when that flag is present.
+# Directory walkers that always recurse (tree /home, du /) read the whole host subtree under an absolute/tilde root.
+# ls only recurses with -R, so it is gated separately.
_AUTO_RECURSIVE_LISTERS = frozenset({"tree", "du"})
-# Benign wrappers: safe AND forward command position to their target (checked in
-# turn). sudo/su/chroot/etc. are absent, so they classify as unsafe. xargs is
-# absent too: it appends arguments read from stdin that this scan never sees, so
-# `echo -o out /etc/passwd | xargs sort` forwards to `sort -o out /etc/passwd`
-# (a write + sensitive read) while only the allow-listed literals are visible.
-# setsid/exec/builtin forward to a child command just like env/nohup, so
-# classification continues at the child rather than stopping at the wrapper.
+# Benign wrappers: safe AND forward command position to their target. sudo/su/chroot are absent, so they classify as
+# unsafe. xargs is absent too: it appends arguments read from stdin that this scan never sees, so `echo -o out
+# /etc/passwd | xargs sort` forwards a write plus a sensitive read while only the allow-listed literals are visible.
_AUTO_SAFE_WRAPPERS = frozenset(
{
"env",
@@ -2054,8 +1866,7 @@ _AUTO_SAFE_MCP_TOOL_RE = re.compile(
r"retrieve|count|status|info|help|check)(?:[_\-].*)?$",
re.IGNORECASE,
)
-# A mutating verb anywhere in the name overrides a read-only prefix, so a
-# compound name like get_or_create_issue or read_and_delete_file still asks.
+# A mutating verb anywhere in the name overrides a read-only prefix, so get_or_create_issue still asks.
_AUTO_UNSAFE_MCP_VERB_RE = re.compile(
r"(?:^|[_\-])(?:create|update|delete|remove|write|set|add|send|post|put|"
r"patch|insert|drop|kill|exec|execute|run|deploy|publish|move|rename|edit|"
@@ -2068,11 +1879,9 @@ _AUTO_UNSAFE_MCP_VERB_RE = re.compile(
r"upsert|assign|mark|subscribe|unsubscribe|reply|notify)(?:[_\-]|$)",
re.IGNORECASE,
)
-# A read-named MCP tool that returns a secret is still a sensitive read, so a
-# credential noun anywhere in the name (read_secret, list_tokens,
-# get_credentials, fetch_api_key) asks even without a mutating verb or a path/SQL
-# argument. Scoped nouns (api/access/private/... _key) avoid flagging benign
-# keys like a primary_key or keyboard lookup.
+# A read-named MCP tool that returns a secret is still a sensitive read, so a credential noun anywhere in the name
+# asks even without a mutating verb or a path/SQL argument. Scoped nouns avoid flagging a benign primary_key or
+# keyboard lookup.
_AUTO_SENSITIVE_MCP_NOUN_RE = re.compile(
r"(?:^|[_\-])(?:"
r"secret|token|credential|password|passwd|passphrase|apikey|"
@@ -2080,20 +1889,19 @@ _AUTO_SENSITIVE_MCP_NOUN_RE = re.compile(
r")s?(?:[_\-]|$)",
re.IGNORECASE,
)
-# Split a camelCase boundary with an underscore (runCommand -> run_Command) so
-# the term-boundary MCP regexes match camelCase tool names too.
+# Split a camelCase boundary with an underscore (runCommand -> run_Command) so the term-boundary MCP regexes match
+# camelCase tool names too.
_CAMEL_CASE_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
-# A name that reads (get_release, search_code, list_invoices) names its SUBJECT,
-# not the action, so the impact and runtime-noun patterns below must not fire on
-# it, or the everyday read tools of every server would prompt.
+# A name that reads (get_release, search_code) names its SUBJECT, not the action, so the impact and runtime-noun
+# patterns below must not fire on it, or the everyday read tools of every server would prompt.
_AUTO_READ_MCP_VERB_RE = re.compile(
r"(?:^|[_\-])(?:get|list|read|search|find|fetch|query|describe|show|view|"
r"inspect|status|info|count|exists|lookup|browse|preview|download|export|"
r"history|log|logs|diff|compare|summarize|summarise)(?:[_\-]|$)",
re.IGNORECASE,
)
-# The runtime nouns alone (python, code, script, notebook) name a subject as
-# often as an action, so they only count when nothing reads.
+# The runtime nouns alone (python, code, script, notebook) name a subject as often as an action, so they only count
+# when nothing reads.
_AUTO_EXEC_MCP_VERB_ONLY_RE = re.compile(
r"(?:^|[_\-])(?:exec|execute|run|eval|spawn|invoke|launch|shell|bash|zsh|"
r"powershell|pwsh|terminal|subprocess|interpreter)(?:[_\-]|$)",
@@ -2104,26 +1912,21 @@ _AUTO_EXEC_MCP_RUNTIME_NOUN_RE = re.compile(
r"script|repl|sandbox|notebook)(?:[_\-]|$)",
re.IGNORECASE,
)
-# An MCP tool that runs arbitrary commands/code (run_command, eval_code, bash)
-# is as unsafe as a terminal call and runs on the server, outside the terminal
-# sandbox, so auto gates it. Whole name segments only, so get_command and
-# list_shells stay read.
+# An MCP tool that runs arbitrary commands/code is as unsafe as a terminal call and runs on the server, outside the
+# terminal sandbox. Whole name segments only, so get_command and list_shells stay read.
_AUTO_EXEC_MCP_TOOL_RE = re.compile(
r"(?:^|[_\-])(?:"
r"exec|execute|run|eval|spawn|invoke|launch|"
r"shell|bash|zsh|powershell|pwsh|terminal|subprocess|interpreter|"
- # A bare runtime name (mcp__srv__python, __node, __code) is an execution
- # tool even without a verb: its payload runs on the MCP server.
+ # A bare runtime name (mcp__srv__python, __node, __code) is an execution tool even without a verb: its payload
+ # runs on the MCP server.
r"python[0-9.]*|node|nodejs|deno|bun|ruby|perl|php|code|script|repl|sandbox|notebook"
r")(?:[_\-]|$)",
re.IGNORECASE,
)
-# A destructive verb as a whole name segment: an honestly-named MCP tool
-# (delete_file, delete_repo, drop_table, purge_index) runs outside the terminal
-# sandbox and causes data loss, so auto prompts on it even when the arguments
-# carry no SQL/HTTP mutation marker. Non-destructive mutations (create/update/
-# add/set/insert/patch) still run; a read that merely contains one of these as
-# a substring (undelete, list_removed) does not match on the segment boundary.
+# A destructive verb as a whole name segment runs outside the terminal sandbox and causes data loss, so auto prompts
+# even when the arguments carry no SQL/HTTP mutation marker. Non-destructive mutations still run, and a read that
+# merely contains one as a substring (undelete) does not match on the segment boundary.
_AUTO_DESTRUCTIVE_MCP_VERB_RE = re.compile(
r"(?:^|[_\-])(?:"
r"delete|destroy|drop|purge|wipe|truncate|erase|remove|unlink|"
@@ -2131,8 +1934,8 @@ _AUTO_DESTRUCTIVE_MCP_VERB_RE = re.compile(
r")(?:[_\-]|$)",
re.IGNORECASE,
)
-# A name without separators (mcp__srv__runcommand, __shellexec) never reaches the
-# segment boundaries above, so match the verb+object compounds directly.
+# A name without separators (mcp__srv__runcommand) never reaches the segment boundaries above, so match the
+# verb+object compounds directly.
_MCP_EXEC_VERBS = r"execute|exec|run|eval|spawn|invoke|launch|start"
_MCP_EXEC_OBJECTS = r"command|cmd|shell|script|code|process|program|bash|terminal|proc|task|job"
_AUTO_EXEC_MCP_COMPOUND_RE = re.compile(
@@ -2142,9 +1945,8 @@ _AUTO_EXEC_MCP_COMPOUND_RE = re.compile(
r")(?:[_\-]|$)",
re.IGNORECASE,
)
-# The verbs an MCP tool name may carry and still run without a prompt: reads, and
-# ordinary writes that create or edit a record. Destructive, privilege and
-# money-moving verbs are caught by the patterns above before this is consulted.
+# The verbs an MCP tool name may carry and still run without a prompt: reads, and ordinary writes that create or edit
+# a record. Destructive, privilege and money-moving verbs are caught above.
_AUTO_KNOWN_MCP_VERBS = frozenset(
{
# read / inspect
@@ -2333,9 +2135,8 @@ _AUTO_KNOWN_MCP_VERBS = frozenset(
)
-# Verbs the patterns above already gate. A name carrying one is still screenable
-# even though reaching this point means it did not match: `undelete` is the
-# reverse of a verb this classifier knows.
+# Verbs the patterns above already gate. A name carrying one is still screenable even though reaching this point means
+# it did not match: `undelete` is the reverse of a verb this classifier knows.
_AUTO_GATED_MCP_VERBS = frozenset(
{
"delete",
@@ -2376,32 +2177,30 @@ _AUTO_MCP_VERB_VOCAB = _AUTO_KNOWN_MCP_VERBS | _AUTO_GATED_MCP_VERBS
def _mcp_verb_is_known(tool_name: str) -> bool:
- """Whether any term of an MCP tool name is a verb this classifier knows.
- A name with none of them cannot be screened, so the caller fails closed."""
+ """Whether any term of an MCP tool name is a verb this classifier knows. A name with none of
+ them cannot be screened, so the caller fails closed."""
for part in re.split(r"[_\-]+", tool_name.lower()):
if not part:
continue
if part in _AUTO_KNOWN_MCP_VERBS:
return True
- # The reverse or the repeat of a recognised verb (undelete, reopen,
- # resend) is just as screenable as the verb itself.
+ # The reverse or the repeat of a recognised verb (undelete, reopen, resend) is just as screenable as the verb
+ # itself.
for prefix in ("un", "re"):
if part.startswith(prefix) and part[len(prefix) :] in _AUTO_MCP_VERB_VOCAB:
return True
return False
-# Privilege escalation over MCP: granting a role/permission/policy hands out
-# access the operator never approved. An unambiguous privilege verb matches on
-# its own; the soft verbs below (assign/add/set/attach/bind) only count next to a
-# privilege noun, so assign_issue / add_label keep running.
+# Privilege escalation over MCP: granting a role/permission/policy hands out access the operator never approved. An
+# unambiguous privilege verb matches on its own; the soft verbs (assign/add/set) only count next to a privilege noun,
+# so assign_issue keeps running.
_AUTO_PRIVILEGE_MCP_VERB_RE = re.compile(
r"(?:^|[_\-])(?:grant|authorize|authorise|elevate|escalate|impersonate|sudo|promote)(?:[_\-]|$)",
re.IGNORECASE,
)
-# Money movement and other irreversible external side effects: an MCP call
-# that pays, refunds, wires or transfers funds cannot be undone by the
-# operator, so it asks even though it is not "destructive" in the fs sense.
+# Money movement and other irreversible external side effects cannot be undone by the operator, so they ask even
+# though they are not "destructive" in the fs sense.
_AUTO_HIGH_IMPACT_MCP_RE = re.compile(
r"(?:^|[_\-])(?:transfer|payout|payment|pay|charge|refund|wire|remit|"
r"withdraw|deposit|invoice|subscription|subscriptions|billing|"
@@ -2419,8 +2218,8 @@ _AUTO_PRIVILEGE_MCP_SOFT_VERB_RE = re.compile(
re.IGNORECASE,
)
-# Python: modules whose import alone signals side effects auto mode should ask
-# about (process spawning, network, bulk file ops, low-level memory).
+# Python: modules whose import alone signals side effects auto mode should ask about (process spawning, network, bulk
+# file ops, low-level memory).
_AUTO_UNSAFE_PY_MODULES = frozenset(
{
"subprocess",
@@ -2436,8 +2235,8 @@ _AUTO_UNSAFE_PY_MODULES = frozenset(
"http",
"httpx",
"aiohttp",
- # huggingface_hub.hf_hub_download / snapshot_download fetch remote repo
- # files over the network and write them to an on-disk cache.
+ # huggingface_hub.hf_hub_download / snapshot_download fetch remote repo files over the network and write them
+ # to an on-disk cache.
"huggingface_hub",
# websockets opens a network connection; socketserver binds a listener.
"websockets",
@@ -2446,8 +2245,8 @@ _AUTO_UNSAFE_PY_MODULES = frozenset(
"smtplib",
"telnetlib",
"paramiko",
- # mail/news/rpc/browser stdlib clients open outbound connections
- # (imaplib, poplib, xmlrpc.client, webbrowser.open).
+ # mail/news/rpc/browser stdlib clients open outbound connections (imaplib, poplib, xmlrpc.client,
+ # webbrowser.open).
"imaplib",
"poplib",
"nntplib",
@@ -2461,19 +2260,19 @@ _AUTO_UNSAFE_PY_MODULES = frozenset(
"dill",
# dbm.open(file, "c"/"n") creates files; treat the family as writers.
"dbm",
- # sqlite3.connect(path) creates/mutates a database file (and runs DDL/DML
- # without an open()/writer attribute), like dbm.
+ # sqlite3.connect(path) creates/mutates a database file (and runs DDL/DML without an open()/writer attribute),
+ # like dbm.
"sqlite3",
# runpy runs a script/module as code.
"runpy",
- # ensurepip.bootstrap installs pip and venv.create builds an environment;
- # both write to disk and can fetch/install packages.
+ # ensurepip.bootstrap installs pip and venv.create builds an environment; both write to disk and can
+ # fetch/install packages.
"ensurepip",
"venv",
}
)
-# Attribute calls that mutate the filesystem / spawn processes (os.remove,
-# Path.write_text, sock.connect, ...) regardless of how the module was bound.
+# Attribute calls that mutate the filesystem / spawn processes (os.remove, Path.write_text, sock.connect) regardless
+# of how the module was bound.
_AUTO_UNSAFE_PY_ATTRS = frozenset(
{
"remove",
@@ -2529,9 +2328,8 @@ _AUTO_UNSAFE_PY_ATTRS = frozenset(
"setxattr",
"removexattr",
"import_module",
- # loader.exec_module runs a module's code like import_module; archive
- # extractall/extract write arbitrary files (zip-slip): extract takes a
- # single member but an attacker-controlled member path still escapes.
+ # loader.exec_module runs a module's code like import_module; archive extractall/extract write arbitrary files
+ # (zip-slip): extract takes a single member but an attacker-controlled member path still escapes.
"exec_module",
"extractall",
"extract",
@@ -2541,8 +2339,7 @@ _AUTO_UNSAFE_PY_ATTRS = frozenset(
"create_subprocess_shell",
"subprocess_exec",
"subprocess_shell",
- # asyncio outbound connections / listeners (open_connection,
- # create_connection/server and unix variants), like socket.connect.
+ # asyncio outbound connections / listeners, like socket.connect.
"open_connection",
"create_connection",
"create_server",
@@ -2559,25 +2356,23 @@ _AUTO_UNSAFE_PY_ATTRS = frozenset(
"fchdir",
"run_path",
"run_module",
- # types.FunctionType wraps a compiled code object into a callable, a
- # dynamic-execution vector; pandas read_pickle deserializes (runs code).
+ # types.FunctionType wraps a compiled code object into a callable, a dynamic-execution vector; pandas
+ # read_pickle deserializes (runs code).
"FunctionType",
"read_pickle",
}
)
-# Loaders that can execute code embedded in the data they deserialize; gated by
-# receiver module (torch.load, yaml.load) since bare `load` is too common.
+# Loaders that can execute code embedded in the data they deserialize; gated by receiver module (torch.load,
+# yaml.load) since bare `load` is too common.
_AUTO_UNSAFE_PY_LOAD_MODULES = frozenset({"torch", "joblib", "cloudpickle", "yaml"})
-# The load entry points on those modules. yaml.load runs whatever its Loader=
-# builds, and !!python/object/apply in the data is a call, so it asks like the
-# pickle-backed ones do. yaml.safe_load is untouched.
+# The load entry points on those modules. yaml.load runs whatever its Loader= builds, and !!python/object/apply in the
+# data is a call, so it asks like the pickle-backed ones. yaml.safe_load is untouched.
_AUTO_UNSAFE_PY_LOAD_ATTRS = frozenset({"load", "load_all"})
-# Loader classes: the same deserialize one level down (yaml.Loader(s).get_data())
-# and what a custom loader subclasses. Ordinary words, so matched by receiver.
+# Loader classes: the same deserialize one level down (yaml.Loader(s).get_data()) and what a custom loader subclasses.
+# Ordinary words, so matched by receiver.
_AUTO_UNSAFE_PY_LOAD_CLASSES = frozenset({"Loader", "Constructor"})
-# Names no other library uses, so they are matched wherever they appear rather
-# than by receiver: an alias, a subclass, a loop, a helper or a factory all name
-# one of these somewhere, and following the value through every binding form is
+# Names no other library uses, so they are matched wherever they appear rather than by receiver: an alias, a subclass,
+# a loop, a helper or a factory all name one of these somewhere, and following the value through every binding form is
# a game without an end.
_AUTO_UNSAFE_YAML_LOADERS = frozenset(
{
@@ -2594,9 +2389,8 @@ _AUTO_UNSAFE_YAML_LOADERS = frozenset(
"FullConstructor",
}
)
-# Writer methods that persist to disk without going through open() (numpy.save,
-# Image.save, plt.savefig, DataFrame.to_csv, json.dump). Gated as method calls
-# only, so a bare attribute reference is not mistaken for a write.
+# Writer methods that persist to disk without going through open() (numpy.save, Image.save, plt.savefig,
+# DataFrame.to_csv, json.dump). Gated as method calls only, so a bare attribute reference is not mistaken for a write.
_AUTO_UNSAFE_PY_WRITE_METHODS = frozenset(
{
"save",
@@ -2616,9 +2410,8 @@ _AUTO_UNSAFE_PY_WRITE_METHODS = frozenset(
"to_stata",
"to_sql",
"to_xml",
- # pandas text exporters that write when given a path/buffer (to_html /
- # to_markdown / to_latex mirror to_csv); to_clipboard / to_gbq persist
- # off-process. to_string is omitted: it is overwhelmingly display-only.
+ # pandas text exporters that write when given a path/buffer; to_clipboard / to_gbq persist off-process.
+ # to_string is omitted: it is overwhelmingly display-only.
"to_html",
"to_markdown",
"to_latex",
@@ -2628,22 +2421,21 @@ _AUTO_UNSAFE_PY_WRITE_METHODS = frozenset(
"imsave",
"write_image",
"write_html",
- # ML persistence helpers (transformers/peft/safetensors/keras) that
- # export adapters or weights to disk without an open()/writer attribute.
+ # ML persistence helpers (transformers/peft/safetensors/keras) that export adapters or weights to disk without
+ # an open()/writer attribute.
"save_pretrained",
"save_file",
"save_model",
"save_weights",
"save_lora",
"save_checkpoint",
- # logging file handlers open a log file for write on construction (even
- # default mode "a" creates); matched as attribute call and bare import.
+ # logging file handlers open a log file for write on construction (even default mode "a" creates); matched as
+ # attribute call and bare import.
"FileHandler",
"WatchedFileHandler",
"RotatingFileHandler",
"TimedRotatingFileHandler",
- # numpy.memmap(..., mode="w+") and pandas writers create/truncate a file
- # on construction, like open(..., "w").
+ # numpy.memmap(..., mode="w+") and pandas writers create/truncate a file on construction, like open(..., "w").
"memmap",
"open_memmap",
"ExcelWriter",
@@ -2652,9 +2444,8 @@ _AUTO_UNSAFE_PY_WRITE_METHODS = frozenset(
"writedoc",
}
)
-# Archive / compressed-file constructors taking the mode as their 2nd arg like
-# open: ZipFile(name, "w") / gzip.GzipFile(name, "w") write, so gated only in
-# write mode (reading a .gz is fine, so the modules are not blanket-unsafe).
+# Archive / compressed-file constructors taking the mode as their 2nd arg like open, so gated only in write mode
+# (reading a .gz is fine, so the modules are not blanket-unsafe).
_ARCHIVE_CTOR_NAMES = frozenset({"ZipFile", "TarFile", "GzipFile", "BZ2File", "LZMAFile"})
# The stdlib module each archive constructor is imported from.
_ARCHIVE_CTOR_MODULES = {
@@ -2664,29 +2455,25 @@ _ARCHIVE_CTOR_MODULES = {
"bz2": "BZ2File",
"lzma": "LZMAFile",
}
-# Modules whose top-level open() takes the mode as its 2nd arg like builtin open,
-# so `from gzip import open as gopen` binds an open alias gated on write mode.
+# Modules whose top-level open() takes the mode as its 2nd arg like builtin open, so `from gzip import open as gopen`
+# binds an open alias gated on write mode.
_OPEN_ALIAS_MODULES = frozenset({"gzip", "bz2", "lzma"})
-# Builtins/itertools helpers that call their first argument once per item, so a
-# writer/open alias handed to one runs without a direct call(...) site
-# (list(map(open, names, modes)), starmap(np.save, ...)). filter's predicate is
-# also invoked, so a writer smuggled there runs too.
+# Builtins/itertools helpers that call their first argument once per item, so a writer/open alias handed to one runs
+# without a direct call(...) site. filter's predicate is also invoked, so a writer smuggled there runs too.
_HIGHER_ORDER_INVOKERS = frozenset({"map", "filter", "starmap", "reduce"})
_PY_WRITE_MODE_RE = re.compile(r"[wax+]")
-# A file-mode literal ("w", "rb", "a+"): letters/flags only, no path chars.
-# Used to tell a Path.open("w") mode from a ZipFile.open("name.txt") filename.
+# A file-mode literal ("w", "rb", "a+"): letters/flags only, no path chars. Tells a Path.open("w") mode from a
+# ZipFile.open("name.txt") filename.
_PY_MODE_LITERAL_RE = re.compile(r"^[rwxa][btru+]*$")
-# Destructive filesystem calls in the python tool pair with the terminal `rm`
-# gate, so auto prompts. `rmtree`/`unlink`/`rmdir`/`removedirs` name only fs
-# deletion, so any receiver counts; `remove` is gated on the `os` module alone so
-# a benign list.remove() stays out. A bare import binding is caught separately.
+# Destructive filesystem calls in the python tool pair with the terminal `rm` gate.
+# `rmtree`/`unlink`/`rmdir`/`removedirs` name only fs deletion, so any receiver counts; `remove` is gated on the `os`
+# module alone so a benign list.remove() stays out.
_PY_DESTRUCTIVE_FS_ATTRS = frozenset({"unlink", "rmtree", "rmdir", "removedirs"})
# psutil ends a process exactly as os.kill does, which is already gated.
_PY_PROCESS_KILL_ATTRS = frozenset({"kill", "terminate", "send_signal", "suspend"})
_PY_PROCESS_MODULES = frozenset({"psutil"})
-# Gated only on the os module (or an alias) so a truncate/remove-like method on
-# another receiver stays out. os.truncate zeroes a file like the gated terminal
-# `truncate`; os.kill/os.killpg terminate like the blocked `kill`.
+# Gated only on the os module (or an alias) so a truncate/remove-like method on another receiver stays out.
+# os.truncate zeroes a file like the gated terminal `truncate`; os.kill/os.killpg terminate like the blocked `kill`.
_PY_DESTRUCTIVE_FS_OS_ATTRS = frozenset({"remove", "truncate", "ftruncate", "kill", "killpg"})
_PY_DESTRUCTIVE_FS_IMPORT_NAMES = frozenset(
{
@@ -2701,93 +2488,82 @@ _PY_DESTRUCTIVE_FS_IMPORT_NAMES = frozenset(
"killpg",
}
)
-# Modules whose destructive names are the same calls: posix/nt are os's
-# platform twins (from posix import unlink; nt.remove(...)).
+# Modules whose destructive names are the same calls: posix/nt are os's platform twins.
_PY_DESTRUCTIVE_FS_MODULES = ("os", "posix", "nt", "shutil", "pathlib")
-# Reading these off the host escapes the intent of "read-only is safe": they
-# hold credentials. Path traversal (../) escapes the per-session workdir.
+# Reading these off the host escapes the intent of "read-only is safe": they hold credentials. Path traversal (../)
+# escapes the per-session workdir.
_SENSITIVE_PATH_RE = re.compile(
r"(?:^|[/\\])\.(?:ssh|aws|azure|gnupg|docker|kube|config/gcloud|config/gh)(?:[/\\]|$)"
r"|\.(?:netrc|npmrc|pypirc|git-credentials|env)(?:$|[/\\.\s'\"])"
- # User-level persistence: a write into a shell startup file or an XDG
- # autostart/user-service dir runs on the next login, the /etc boot-hook risk
- # without root, and the sandbox does not confine absolute paths (>> ~/.bashrc
- # reaches the real file). Rarely read in a dev session, so gating any
- # reference does not over-prompt.
+ # User-level persistence: a write into a shell startup file or an XDG autostart/user-service dir runs on the next
+ # login, the /etc boot-hook risk without root, and the sandbox does not confine absolute paths. Rarely read in a
+ # dev session, so gating any reference does not over-prompt.
r"|(?:^|[/\\\s'\"=])\.(?:bashrc|bash_profile|bash_login|bash_logout|bash_aliases"
r"|profile|zshrc|zprofile|zshenv|zlogin|zlogout|kshrc|cshrc|tcshrc|login"
r"|xprofile|xinitrc|xsession)(?:$|[/\\\s'\"])"
r"|(?:^|[/\\])\.config[/\\](?:autostart|systemd[/\\]user|environment\.d)(?:[/\\]|$)"
r"|id_rsa|id_ed25519|id_ecdsa|id_dsa"
- # Hugging Face stores the login token at ~/.cache/huggingface/token and the
- # legacy ~/.huggingface/token (plus the multi-token store stored_tokens); the
- # rest of that cache is model data, so only the credential files match. The
- # optional leading dot covers the .huggingface dotdir form.
+ # Hugging Face stores the login token at ~/.cache/huggingface/token and the legacy ~/.huggingface/token (plus
+ # stored_tokens); the rest of that cache is model data, so only the credential files match.
r"|(?:^|[/\\])\.?huggingface[/\\](?:token|stored_tokens)(?:$|[/\\.\s'\"])"
- # /etc/ssh holds the host private keys (ssh_host_*_key); the whole dir is
- # sensitive, not just passwd/shadow/sudoers. The trailing group is the system
- # persistence set: a write there (tee /etc/ld.so.preload, a drop into
- # /etc/cron.d or /etc/systemd) installs a boot/login/preload hook, and the
- # sandbox keeps host-fs access. Effectively write-only in a dev session, so
- # gating any reference does not over-prompt.
+ # /etc/ssh holds the host private keys; the whole dir is sensitive, not just passwd/shadow/sudoers. The trailing
+ # group is the system persistence set: a write there installs a boot/login/preload hook, and the sandbox keeps
+ # host-fs access. Effectively write-only in a dev session, so gating any reference does not over-prompt.
r"|credentials|/etc/(?:passwd|shadow|sudoers|ssh(?:[/\\]|$)"
r"|cron[^/\\]*(?:[/\\]|$)|profile\.d(?:[/\\]|$)|systemd(?:[/\\]|$)"
r"|ld\.so\.preload(?:$|[/\\.\s'\"])|ld\.so\.conf|rc\.local|init\.d(?:[/\\]|$))"
- # Bash opens /dev/tcp/host/port and /dev/udp/host/port as network sockets,
- # so a redirection to one reaches the network without the confirm prompt.
+ # Bash opens /dev/tcp/host/port and /dev/udp/host/port as network sockets, so a redirection to one reaches the
+ # network without the confirm prompt.
r"|/dev/(?:tcp|udp)/"
# Docker/Kubernetes secret mounts hold injected credentials.
r"|/(?:var/)?run/secrets(?:[/\\]|$)"
- # procfs leaks a (possibly parent) process env/args/memory to a read,
- # including the per-thread aliases under /proc/<pid>/task/<tid>/. The fd/
- # dir holds symlinks to a process's open files (a held credential/db file).
+ # procfs leaks a (possibly parent) process env/args/memory to a read, including the per-thread aliases under
+ # /proc/<pid>/task/<tid>/. The fd/ dir holds symlinks to a process's open files.
r"|/proc/[^/\s'\"]+/(?:task/[^/\s'\"]+/)?(?:environ|cmdline|mem|maps|fd)\b"
- # A .pem/.key file (basename before the extension), not a bare ".key"
- # (e.g. a jq '.key' filter).
+ # A .pem/.key file (basename before the extension), not a bare ".key" (e.g. a jq '.key' filter).
r"|\w[\w.-]*\.(?:pem|key)(?:$|[\s'\"])",
re.IGNORECASE,
)
-# A shell redirection with no following space (cat <../../notes) keeps `..`
-# adjacent to `<`/`>`, so those count as leading delimiters here too.
+# A shell redirection with no following space (cat <../../notes) keeps `..` adjacent to `<`/`>`, so those count as
+# leading delimiters here too.
_PARENT_TRAVERSAL_RE = re.compile(r"(?:^|[\s/\\'\"=:<>])\.\.(?:[/\\]|$|[\s'\"])")
-# A sensitive directory: a dynamic segment under it (open(f"/etc/{name}")) is
-# not provably safe, so fail closed when a folded path has a dynamic piece here.
+# A sensitive directory: a dynamic segment under it (open(f"/etc/{name}")) is not provably safe, so fail closed when a
+# folded path has a dynamic piece here.
_SENSITIVE_DIR_RE = re.compile(
r"/etc/|/(?:var/)?run/secrets[/\\]|(?:^|[/\\])\.(?:ssh|aws|azure|gnupg|docker|kube)[/\\]"
r"|(?:^|[/\\])\.config/(?:gcloud|gh)[/\\]",
re.IGNORECASE,
)
-# Collapse /./ and repeated slashes so /etc/./passwd and /etc//passwd, which
-# the OS resolves to /etc/passwd, still match the sensitive-path regex.
+# Collapse /./ and repeated slashes so /etc/./passwd and /etc//passwd, which the OS resolves to /etc/passwd, still
+# match the sensitive-path regex.
_REDUNDANT_SLASH_RE = re.compile(r"/\.?(?=/)")
-# $name, ${name}, and operator/substring forms (${name:-x}, ${name:0:6}) all
-# reference `name`; substituting the assigned value catches paths hidden behind
-# a substring expansion (p=passwd; cat /etc/${p:0:6}).
+# $name, ${name}, and operator/substring forms all reference `name`; substituting the assigned value catches paths
+# hidden behind a substring expansion (p=passwd; cat /etc/${p:0:6}).
_SHELL_VAR_RE = re.compile(r"\$\{(\w+)(?::[^{}]*)?\}|\$(\w+)")
-# Pattern replacement (${p/X/w}, global ${p//X/w}) transforms the value before
-# the path is used; apply it so p=passXd; cat /etc/${p/X/w} is scanned.
+# Pattern replacement (${p/X/w}) transforms the value before the path is used; apply it so p=passXd; cat /etc/${p/X/w}
+# is scanned.
_SHELL_PARAM_REPL_RE = re.compile(r"\$\{(\w+)/(/)?([^/{}]*)/([^{}]*)\}")
-# Case modification (${p^^} upper, ${p,,} lower, ${p^}/${p,} first char) also
-# transforms the value, so p=PASSWD; cat /etc/${p,,} builds /etc/passwd.
+# Case modification (${p^^}, ${p,,}, ${p^}) also transforms the value, so p=PASSWD; cat /etc/${p,,} builds
+# /etc/passwd.
_SHELL_PARAM_CASE_RE = re.compile(r"\$\{(\w+)(\^\^|,,|\^|,)\}")
-# Indirect expansion ${!p} yields the value of the variable *named* by $p, so
-# x=passwd; p=x; cat /etc/${!p} builds /etc/passwd.
+# Indirect expansion ${!p} yields the value of the variable *named* by $p, so x=passwd; p=x; cat /etc/${!p} builds
+# /etc/passwd.
_SHELL_PARAM_INDIRECT_RE = re.compile(r"\$\{!(\w+)\}")
_SHELL_ASSIGN_RE = re.compile(r"(?:^|[\s;&|(])([A-Za-z_]\w*)=([^\s;&|)]+)")
-# Bash ANSI-C quoting ($'\x77' -> 'w') is expanded after this classifier, so
-# decode $'...' bodies before the sensitive-path scan.
+# Bash ANSI-C quoting ($'\x77' -> 'w') is expanded after this classifier, so decode $'...' bodies before the
+# sensitive-path scan.
_ANSI_C_RE = re.compile(r"\$'((?:[^'\\]|\\.)*)'")
-# Shell quotes only delimit; bash concatenates the pieces (cat /proc/x/enviro''n
-# reads .../environ), so strip them before the sensitive-path scan.
+# Shell quotes only delimit; bash concatenates the pieces (cat /proc/x/enviro''n reads .../environ), so strip them
+# before the scan.
_SHELL_QUOTE_RE = re.compile(r"['\"]")
# A glob bracket class [s] -> s, so .s[s]h de-obfuscates to .ssh for the scan.
_GLOB_BRACKET_RE = re.compile(r"\[([^!\]][^\]]*)\]")
-# Bash POSIX character classes ([[:lower:]]) each match one char; Python fnmatch
-# does not understand them, so normalize to `?` before the glob check.
+# Bash POSIX character classes ([[:lower:]]) each match one char; Python fnmatch does not understand them, so
+# normalize to `?` before the glob check.
_POSIX_CLASS_RE = re.compile(r"\[\[:\w+:\]\]")
-# Canonical sensitive files a ? / * / [..] glob could expand to; fnmatch tests
-# whether the pattern reaches one (cat /e??/passwd -> /etc/passwd).
+# Canonical sensitive files a ? / * / [..] glob could expand to; fnmatch tests whether the pattern reaches one (cat
+# /e??/passwd -> /etc/passwd).
_SENSITIVE_GLOB_TARGETS = (
"/etc/passwd",
"/etc/shadow",
@@ -2800,9 +2576,8 @@ _SENSITIVE_GLOB_TARGETS = (
"/home/u/.netrc",
"/home/u/.git-credentials",
)
-# Directories whose every file is a credential/secret; a glob resolving into one
-# (cat /r?n/secrets/hf_token, cat /root/.s??/id_rsa) reads a secret even though
-# the exact filename is never enumerated, so a globbed token here asks.
+# Directories whose every file is a credential; a glob resolving into one reads a secret even though the exact
+# filename is never enumerated, so a globbed token here asks.
_SENSITIVE_GLOB_DIRS = (
"/run/secrets",
"/var/run/secrets",
@@ -2823,10 +2598,8 @@ _SENSITIVE_GLOB_DIRS = (
"/home/u/.config/gcloud",
"/home/u/.config/gh",
)
-# Credential basenames a glob can reach even when the directory is not wholly
-# sensitive (cat ~/.huggingface/tok?n -> token, cat ~/.netr? -> .netrc); the
-# canonical-target list only covers a few fixed home paths, so match the globbed
-# basename against these directly.
+# Credential basenames a glob can reach even when the directory is not wholly sensitive (cat ~/.netr? -> .netrc); the
+# canonical-target list only covers a few fixed home paths.
_SENSITIVE_GLOB_BASENAMES = frozenset(
{
"token",
@@ -2843,36 +2616,32 @@ _SENSITIVE_GLOB_BASENAMES = frozenset(
"id_dsa",
"passwd",
"shadow",
- # A project .env holds secrets; the literal path is gated elsewhere, so a
- # glob that expands to it (cat .e?v) must be too.
+ # A project .env holds secrets; the literal path is gated elsewhere, so a glob that expands to it (cat .e?v)
+ # must be too.
".env",
}
)
-# A leading shell redirection (<, >, 2>, >>) hides the path from a plain glob
-# scan (cat </e??/passwd); strip it before matching.
+# A leading shell redirection hides the path from a plain glob scan (cat </e??/passwd); strip it before matching.
_REDIR_PREFIX_RE = re.compile(r"^\d*[<>]+")
-# Bash brace expansion (cat /etc/pass{w,}d -> /etc/passwd /etc/passd, and the
-# sequence form cat /etc/pass{w..w}d -> /etc/passwd) runs after this classifier;
-# expand comma groups and .. sequences to scan each result.
+# Bash brace expansion (cat /etc/pass{w,}d, and the sequence form) runs after this classifier; expand comma groups and
+# .. sequences to scan each result.
_BRACE_COMMA_RE = re.compile(r"^\{([^{}]*,[^{}]*)\}$")
_BRACE_SEQ_RE = re.compile(r"^\{([^{}]+)\.\.([^{}]+)(?:\.\.(-?\d+))?\}$")
_BRACE_ANY_RE = re.compile(r"\{[^{}]*,[^{}]*\}|\{[^{}]+\.\.[^{}]+(?:\.\.-?\d+)?\}")
-# Parameter expansion with a default/alternate operator (${x:-passwd},
-# ${x:+passwd}, ${x=passwd}) can synthesize a path after approval; the operand
-# is substituted so the resulting path is scanned.
+# Parameter expansion with a default/alternate operator (${x:-passwd}) can synthesize a path after approval; the
+# operand is substituted so the resulting path is scanned.
_SHELL_PARAM_OP_RE = re.compile(r"\$\{[A-Za-z_]\w*:?[-=+]([^{}]*)\}")
-# The credential-path pattern is superlinear in the text length and a real path
-# is short, so text far past any real path fails closed: the caller asks rather
-# than spending unbounded time. Ordinary commands are far below these bounds.
+# The credential-path pattern is superlinear in the text length and a real path is short, so text far past any real
+# path fails closed rather than spending unbounded time. Ordinary commands are far below these bounds.
_MAX_PATH_SCAN_CHARS = 2048
_MAX_TERMINAL_SCAN_CHARS = 4096
def _references_sensitive_path(text: str) -> bool:
- """True if a command or string literal reads a credential path or escapes
- the sandbox workdir via parent traversal."""
+ """True if a command or string literal reads a credential path or escapes the sandbox workdir
+ via parent traversal."""
if len(text) > _MAX_PATH_SCAN_CHARS:
return True
norm = _REDUNDANT_SLASH_RE.sub("", text)
@@ -2886,8 +2655,8 @@ def _references_sensitive_path(text: str) -> bool:
def _pattern_matches_dir(pattern: str, target: str) -> bool:
- """Segment-wise fnmatch so a glob segment does not cross a '/' boundary
- (`/home/*` must not match `/home/u/.ssh`)."""
+ """Segment-wise fnmatch so a glob segment does not cross a '/' boundary (`/home/*` must not
+ match `/home/u/.ssh`)."""
p = pattern.split("/")
t = target.split("/")
if len(p) != len(t):
@@ -2896,27 +2665,24 @@ def _pattern_matches_dir(pattern: str, target: str) -> bool:
def _glob_token_sensitive(token: str) -> bool:
- """True if a single ? / * / [..] glob token could expand to a sensitive file
- or a file under a secret/credential directory. Shared by the terminal scan
- and the Python glob check (glob.glob('/e??/passwd'))."""
+ """True if a single ? / * / [..] glob token could expand to a sensitive file or a file under a
+ secret/credential directory. Shared by the terminal scan and the Python glob check."""
token = _REDIR_PREFIX_RE.sub("", _SHELL_QUOTE_RE.sub("", token))
- # A POSIX class ([[:lower:]]) matches one char, like `?`, but fnmatch treats
- # it as a literal set; normalize so cat /etc/pass[[:lower:]]d resolves.
+ # A POSIX class ([[:lower:]]) matches one char, like `?`, but fnmatch treats it as a literal set; normalize so cat
+ # /etc/pass[[:lower:]]d resolves.
token = _POSIX_CLASS_RE.sub("?", token)
if not any(c in token for c in "?*["):
return False
if any(fnmatch.fnmatch(target, token) for target in _SENSITIVE_GLOB_TARGETS):
return True
- # A glob that resolves to a credential basename is sensitive wherever it
- # lives (cat ~/.huggingface/tok?n -> token, cat proj/.netr? -> .netrc); the
- # fixed-target list only covers a handful of home paths.
+ # A glob that resolves to a credential basename is sensitive wherever it lives; the fixed-target list only covers
+ # a handful of home paths.
base = token.rsplit("/", 1)[-1]
if any(c in base for c in "?*[") and any(
fnmatch.fnmatch(name, base) for name in _SENSITIVE_GLOB_BASENAMES
):
return True
- # A globbed directory that resolves into a secret/credential dir makes every
- # file below it sensitive (cat /r?n/secrets/hf_token).
+ # A globbed directory that resolves into a secret/credential dir makes every file below it sensitive.
head = token.rsplit("/", 1)[0] if "/" in token else token
return any(
_pattern_matches_dir(token, d) or _pattern_matches_dir(head, d)
@@ -2925,9 +2691,8 @@ def _glob_token_sensitive(token: str) -> bool:
def _glob_hits_sensitive(command: str) -> bool:
- """True if any glob token in a command could expand to a sensitive file, so
- `cat /e??/passwd` and `cat /r?n/secrets/hf_token` ask even without a literal
- sensitive path."""
+ """True if any glob token in a command could expand to a sensitive file, so `cat /e??/passwd`
+ asks even without a literal sensitive path."""
return any(
_glob_token_sensitive(token)
for token in command.replace(";", " ").replace("|", " ").split()
@@ -2935,10 +2700,9 @@ def _glob_hits_sensitive(command: str) -> bool:
def _expand_shell_assignments(command: str) -> str:
- """Best-effort substitution of `NAME=value ... $NAME`, so a sensitive path
- split across an assignment and an argument (p=/etc; cat $p/passwd) is still
- visible to the sensitive-path scan. Also applies pattern replacement
- (p=passXd; cat /etc/${p/X/w}). Fail-open: only adds detections."""
+ """Best-effort substitution of `NAME=value ... $NAME`, so a sensitive path split across an
+ assignment and an argument (p=/etc; cat $p/passwd) is still visible to the scan. Also applies
+ pattern replacement. Fail-open: only adds detections."""
env = dict(_SHELL_ASSIGN_RE.findall(command))
if not env:
return command
@@ -2974,27 +2738,23 @@ def _expand_shell_assignments(command: str) -> str:
def _expand_param_defaults(command: str) -> str:
- """Substitute the operand of a default/alternate parameter expansion
- (cat /etc/pass${x:-wd} -> cat /etc/passwd), which bash applies after this
- classifier. Fail-open: only adds detections."""
+ """Substitute the operand of a default/alternate parameter expansion (cat /etc/pass${x:-wd}),
+ which bash applies after this classifier. Fail-open: only adds detections."""
return _SHELL_PARAM_OP_RE.sub(lambda m: m.group(1), command)
-# Bash expands $'...' to a single word, so a separator inside it is data. Callers
-# that tokenize the decoded text neutralize these first, otherwise
-# `printf '%s' $'a\\nrm -rf x'` reads as two commands and the printf is refused.
+# Bash expands $'...' to a single word, so a separator inside it is data. Callers that tokenize the decoded text
+# neutralize these first, otherwise `printf '%s' $'a\nrm -rf x'` reads as two commands and the printf is refused.
_ANSI_C_SEPARATOR_RE = re.compile(r"[\s;&|()<>`]")
-# A newline revealed by ANSI-C decoding, and the mark standing in for it. Any
-# character shlex leaves inside a quoted word serves, as long as the boundary
-# regex in _find_blocked_commands does not read it as the start of a command.
+# A newline revealed by ANSI-C decoding, and the mark standing in for it. Any character shlex leaves inside a quoted
+# word serves, as long as the boundary regex in _find_blocked_commands does not read it as the start of a command.
_ANSI_C_NEWLINE_MARK = "\x03"
_ANSI_C_NEWLINE_RE = re.compile(r"[\n\r]")
def _folded_str_literal(node) -> "str | None":
- """The string an expression evaluates to when built only from string literals
- ("un" + "link", f"un{'link'}"), else None. Resolves a name spelled
- dynamically but fully known at parse time."""
+ """The string an expression evaluates to when built only from string literals ("un" + "link"),
+ else None. Resolves a name spelled dynamically but fully known at parse time."""
if isinstance(node, ast.Constant):
return node.value if isinstance(node.value, str) else None
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
@@ -3015,10 +2775,9 @@ def _folded_str_literal(node) -> "str | None":
def _decode_ansi_c(command: str, *, keep_one_word: bool = False) -> str:
- """Decode bash ANSI-C quoted words (cat $'/etc/pass\\x77d' -> cat /etc/passwd)
- so an escape-obfuscated path is visible to the scan. Fail-open: only adds
- detections. With ``keep_one_word`` the decoded text cannot introduce new
- shell syntax, which is what bash does with it."""
+ """Decode bash ANSI-C quoted words (cat $'/etc/pass\x77d') so an escape-obfuscated path is
+ visible to the scan. Fail-open: only adds detections. With ``keep_one_word`` the decoded text
+ cannot introduce new shell syntax, which is what bash does with it."""
def dec(m):
try:
@@ -3028,14 +2787,10 @@ def _decode_ansi_c(command: str, *, keep_one_word: bool = False) -> str:
if not keep_one_word:
return text
if _ANSI_C_NEWLINE_MARK not in text:
- # Re-quote rather than flatten: bash gives the command ONE word
- # however much whitespace the decoding reveals, and a sed program
- # ends its COMMENT at a newline, so the spaces and the `#` around it
- # all carry meaning. An apostrophe is re-quoted `'\''` for the same
- # reason. The newline stands as a MARK because it is data for the
- # command bash starts, not a place a new one begins, and the
- # boundary regex below would read a bare one as the latter;
- # _sed_invocation puts it back where its meaning matters.
+ # Re-quote rather than flatten: bash gives the command ONE word however much whitespace the decoding
+ # reveals, and a sed program ends its COMMENT at a newline, so the spaces and the `#` around it all carry
+ # meaning. The newline stands as a MARK because it is data for the command bash starts, not a place a new
+ # one begins, and the boundary regex below would read a bare one as the latter.
body = _ANSI_C_NEWLINE_RE.sub(_ANSI_C_NEWLINE_MARK, text)
return "'" + body.replace("'", "'\\''") + "'"
return _ANSI_C_SEPARATOR_RE.sub("_", text)
@@ -3073,9 +2828,8 @@ def _brace_options(text: str) -> "list[str]":
def _expand_braces(command: str) -> str:
- """Best-effort bash brace expansion (cat /etc/pass{w,}d -> cat /etc/passwd
- /etc/passd, cat /etc/pass{w..w}d -> cat /etc/passwd) so a sensitive path
- split across a brace group is scanned. Bounded. Fail-open: only detects."""
+ """Best-effort bash brace expansion so a sensitive path split across a brace group is scanned.
+ Bounded. Fail-open: only detects."""
results = [command]
for _ in range(6):
if not any(_BRACE_ANY_RE.search(s) for s in results):
@@ -3120,9 +2874,9 @@ def _builtin_open_writes(node) -> bool:
def _attr_open_writes(node) -> bool:
- """Write check for ``x.open(...)`` (e.g. ``Path.open(mode)`` where mode is
- the 1st arg). Only a mode-looking string is read as the mode, so a
- ``ZipFile.open("name.txt")`` read is not mistaken for a write."""
+ """Write check for ``x.open(...)`` (e.g. ``Path.open(mode)`` where mode is the 1st arg). Only a
+ mode-looking string is read as the mode, so a ``ZipFile.open("name.txt")`` read is not
+ mistaken for a write."""
if _has_kwarg_splat(node):
return True # **{"mode": "w"} could request a write
for kw in node.keywords or []:
@@ -3133,9 +2887,8 @@ def _attr_open_writes(node) -> bool:
if isinstance(first, ast.Constant) and isinstance(first.value, str):
if _PY_MODE_LITERAL_RE.match(first.value):
return bool(_PY_WRITE_MODE_RE.search(first.value))
- # A 2nd positional arg is either a mode (x.open(name, "w")) or
- # os.open(path, O_CREAT) flags via an alias: honor a string mode,
- # otherwise cannot prove read-only, so ask.
+ # A 2nd positional arg is either a mode (x.open(name, "w")) or os.open(path, O_CREAT) flags via an alias:
+ # honor a string mode, otherwise cannot prove read-only, so ask.
if len(node.args) >= 2:
second = node.args[1]
if isinstance(second, ast.Constant) and isinstance(second.value, str):
@@ -3154,18 +2907,16 @@ _PATH_CTORS = (
"PosixPath",
"WindowsPath",
)
-# Deterministic path pass-through/normalizer calls that return the same location
-# (os.path.abspath('/etc') -> /etc, Path('/etc').resolve() -> /etc), so folding
-# through them keeps a sensitive root visible to the scan.
+# Deterministic path pass-through/normalizer calls that return the same location (os.path.abspath('/etc') -> /etc), so
+# folding through them keeps a sensitive root visible.
_PATH_PASSTHROUGH_ATTRS = frozenset(
{"abspath", "normpath", "realpath", "expanduser", "expandvars", "resolve", "absolute"}
)
-# pathlib methods that rewrite only the final path component, so the sensitive
-# target is never spelled out as a literal (Path('/etc/x').with_name('passwd')
-# -> /etc/passwd). Folded below so the rewritten path is still scanned.
+# pathlib methods that rewrite only the final path component, so the sensitive target is never spelled out as a
+# literal (Path('/etc/x').with_name('passwd')).
_PATH_NAME_REWRITES = frozenset({"with_name", "with_stem", "with_suffix"})
-# Mapping-style %-format conversion specifier: %(name)s / %(n)5.2f. Used to fold
-# '/etc/%(f)s' % {'f': 'passwd'} to /etc/passwd (a dynamic value becomes NUL).
+# Mapping-style %-format conversion specifier: %(name)s. Used to fold '/etc/%(f)s' % {'f': 'passwd'} to /etc/passwd (a
+# dynamic value becomes NUL).
_PERCENT_NAMED_RE = re.compile(r"%\((\w+)\)[-#0 +]*\d*(?:\.\d+)?[a-zA-Z]")
@@ -3175,14 +2926,14 @@ def _folded_path(
ctors = None,
join_names = None,
) -> "str | None":
- """Best-effort value of a path built from string literals, so a sensitive
- path assembled from pieces (os.path.join('/etc', 'passwd'), '/etc'+'/passwd',
- Path('/etc') / 'passwd', f'/proc/{pid}/environ', f'/etc/{name}') is still
- visible to the scan. A dynamic piece becomes NUL, a non-slash placeholder,
- so a dynamic segment under a sensitive dir (/etc/NUL) is still detectable.
- ``literals`` maps names bound to string literals (base = '/etc'); ``ctors``
- is the set of pathlib constructor names (incl. import aliases); ``join_names``
- are bare names bound to os.path.join (from os.path import join)."""
+ """Best-effort value of a path built from string literals, so a sensitive path assembled from
+ pieces (os.path.join('/etc', 'passwd'), Path('/etc') / 'passwd', f'/etc/{name}') is still
+ visible to the scan. A dynamic piece becomes NUL, a non-slash placeholder, so a dynamic segment
+ under a sensitive dir is still detectable.
+
+ ``literals`` maps names bound to string literals; ``ctors`` is the set of pathlib constructor
+ names; ``join_names`` are bare names bound to os.path.join.
+ """
literals = literals or {}
ctors = ctors or _PATH_CTORS
join_names = join_names or frozenset()
@@ -3198,9 +2949,8 @@ def _folded_path(
if isinstance(node, ast.Name):
return literals.get(node.id)
if isinstance(node, ast.Attribute) and node.attr in ("parent", "parents"):
- # A pathlib .parent/.parents walks above the current dir, escaping
- # the per-session workdir without a literal '..'; mark it so a read
- # folds to unsafe (\x02 is a non-slash escape sentinel).
+ # A pathlib .parent/.parents walks above the current dir, escaping the per-session workdir without a
+ # literal '..'; mark it so a read folds to unsafe (\x02 is a non-slash escape sentinel).
return "\x02"
if (
isinstance(node, ast.Subscript)
@@ -3230,10 +2980,8 @@ def _folded_path(
if template is not None and "%" in template:
rhs = node.right
if "%(" in template:
- # Mapping-style: '/etc/%(f)s' % {'f': 'passwd'} -> /etc/passwd.
- # A literal dict resolves each name; an unresolved value or a
- # non-literal mapping leaves the NUL marker so /etc/<dynamic>
- # still fails closed under a sensitive dir.
+ # Mapping-style: '/etc/%(f)s' % {'f': 'passwd'}. A literal dict resolves each name; an unresolved
+ # value or a non-literal mapping leaves the NUL marker so /etc/<dynamic> still fails closed.
mapping: "dict[str, str]" = {}
if isinstance(rhs, ast.Dict):
for k, v in zip(rhs.keys, rhs.values):
@@ -3262,17 +3010,15 @@ def _folded_path(
parts += [(fold(a) or "\x00") for a in node.args]
return "/".join(parts)
if isinstance(func, ast.Attribute) and func.attr in ("glob", "rglob", "iglob"):
- # Path('/etc').glob('passw?') -> the receiver dir joined with the
- # glob pattern; _glob_token_sensitive then tests /etc/passw?.
+ # Path('/etc').glob('passw?') -> the receiver dir joined with the glob pattern; _glob_token_sensitive
+ # then tests /etc/passw?.
base = fold(func.value)
pattern = fold(node.args[0]) if node.args else "\x00"
return (base if base is not None else "\x00") + "/" + (pattern or "\x00")
if isinstance(func, ast.Attribute) and func.attr in _PATH_NAME_REWRITES:
- # Path('/etc/x').with_name('passwd') -> /etc/passwd; with_stem /
- # with_suffix rewrite only the final component. Fold to the
- # rewritten path so a sensitive target that no literal spells out
- # is still caught. An unresolved receiver stays None (untracked,
- # like a bare variable), and a dynamic arg becomes the NUL marker.
+ # with_name / with_stem / with_suffix rewrite only the final component. Fold to the rewritten path so
+ # a sensitive target that no literal spells out is still caught. An unresolved receiver stays None,
+ # and a dynamic arg becomes the NUL marker.
base = fold(func.value)
if base is None:
return None
@@ -3292,14 +3038,12 @@ def _folded_path(
name = stem + arg
return head + name
if isinstance(func, ast.Attribute) and func.attr in _PATH_PASSTHROUGH_ATTRS:
- # Deterministic normalizers keep the same path: os.path.abspath(
- # '/etc') -> /etc, Path('/etc').resolve() -> /etc. When called with
- # a path arg fold it, else fold the receiver (Path method form).
+ # Deterministic normalizers keep the same path. When called with a path arg fold it, else fold the
+ # receiver (Path method form).
return fold(node.args[0]) if node.args else fold(func.value)
if isinstance(func, ast.Attribute) and func.attr == "join":
- # str.join has the separator as the receiver and the pieces in
- # one iterable arg ("".join(['/etc', '/passwd']) -> /etc/passwd);
- # tell it apart from os.path.join(*pieces).
+ # str.join has the separator as the receiver and the pieces in one iterable arg; tell it apart from
+ # os.path.join(*pieces).
sep = fold(func.value)
if (
sep is not None
@@ -3341,12 +3085,10 @@ def _folded_path(
def _dynamic_name_hits_sensitive(folded) -> bool:
- """True if a folded path with a dynamic piece (NUL) inside a path segment
- could spell a credential target, e.g. open('/et' + chr(99) + '/passwd')
- folds to '/et\\x00/passwd'. NUL matches any run of non-separator chars so the
- dynamic split of a sensitive name resolves, while an all-dynamic ('\\x00\\x00')
- or segment-spanning ('\\x00/\\x00') path cannot form a single credential name
- and stays safe."""
+ """True if a folded path with a dynamic piece (NUL) inside a path segment could spell a
+ credential target, e.g. open('/et' + chr(99) + '/passwd'). NUL matches any run of
+ non-separator chars so the dynamic split of a sensitive name resolves, while an all-dynamic
+ or segment-spanning path cannot form a single credential name and stays safe."""
if not folded or "\x00" not in folded:
return False
pattern = "".join(r"[^/\\]*" if ch == "\x00" else re.escape(ch) for ch in folded)
@@ -3358,37 +3100,31 @@ def _dynamic_name_hits_sensitive(folded) -> bool:
def _folded_is_sensitive(folded) -> bool:
- """A folded path is sensitive if it names a credential file, has a dynamic
- segment (NUL) directly under a sensitive directory (/etc/NUL), walks out of
- the sandbox via a pathlib .parent/.parents escape (\\x02), or is a glob that
- could resolve to a credential path (glob.glob('/e??/passwd'))."""
+ """A folded path is sensitive if it names a credential file, has a dynamic segment (NUL)
+ directly under a sensitive directory, walks out of the sandbox via a pathlib .parent escape
+ (\x02), or is a glob that could resolve to a credential path."""
if not folded:
return False
return (
"\x02" in folded
or _references_sensitive_path(folded)
or ("\x00" in folded and bool(_SENSITIVE_DIR_RE.search(folded)))
- # A dynamic segment (NUL) can be the "/" forming a sensitive root:
- # open(os.sep + "etc/passwd") folds to "\x00etc/passwd", so re-scan with
- # NUL as "/" (a benign "\x00data/file" -> "/data/file" stays safe).
+ # A dynamic segment (NUL) can be the "/" forming a sensitive root: open(os.sep + "etc/passwd") folds to
+ # "\x00etc/passwd", so re-scan with NUL as "/".
or ("\x00" in folded and _references_sensitive_path(folded.replace("\x00", "/")))
- # A dynamic piece can also sit INSIDE a sensitive name: open('/et' +
- # chr(99) + '/passwd') folds to "/et\x00/passwd", which none of the above
- # catch. Match the literals around each NUL against a credential target,
- # treating NUL as "any run of non-separator chars" so /et<dyn>/passwd
- # resolves while an all-dynamic ("\x00\x00" from 1 + 1) or segment-spanning
- # ("\x00/\x00" from a + '/' + b) path stays safe.
+ # A dynamic piece can also sit INSIDE a sensitive name: open('/et' + chr(99) + '/passwd') folds to
+ # "/et\x00/passwd", which none of the above catch. Match the literals around each NUL against a credential
+ # target, treating NUL as any run of non-separator chars, so an all-dynamic or segment-spanning path stays
+ # safe.
or _dynamic_name_hits_sensitive(folded)
or _glob_token_sensitive(folded)
)
def _command_references_sensitive(command: str) -> bool:
- """True if a shell command reads/writes a credential path or escapes the
- sandbox workdir (../), after undoing the shell expansions that would hide it:
- quotes/backslash escapes, brace/parameter/ANSI-C expansion and NAME=value
- prefixes, so `cat /et\\c/passwd`, `p="/proc/$PPID"; cat $p/environ` and
- `cat /e{t,}c/pass?d` are all caught."""
+ """True if a shell command reads/writes a credential path or escapes the sandbox workdir (../),
+ after undoing the shell expansions that would hide it: quotes/backslash escapes,
+ brace/parameter/ANSI-C expansion and NAME=value prefixes."""
stripped = _SHELL_QUOTE_RE.sub("", command).replace("\\", "")
candidates = []
for c in (command, stripped, _decode_ansi_c(command)):
@@ -3401,16 +3137,16 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
"""Classify a terminal command for auto mode (fail closed)."""
if not command or not command.strip():
return False
- # Redirections and substitutions can hide writes or nested commands; a
- # quoted ">" false-positives into a prompt, which is the safe direction.
+ # Redirections and substitutions can hide writes or nested commands; a quoted ">" false-positives into a prompt,
+ # which is the safe direction.
if ">" in command or "`" in command or "$(" in command or "<(" in command:
return True
- # Reads that escape the sandbox workdir (../) or hit credential paths are
- # not "safe" reads; ask before running them.
+ # Reads that escape the sandbox workdir (../) or hit credential paths are not "safe" reads; ask before running
+ # them.
if _command_references_sensitive(command):
return True
- # Newlines (and CR) separate commands in a shell but read as plain
- # whitespace to shlex, which would demote "ls\nrm x" to argument position.
+ # Newlines (and CR) separate commands in a shell but read as plain whitespace to shlex, which would demote "ls\nrm
+ # x" to argument position.
command = command.replace("\r\n", ";").replace("\n", ";").replace("\r", ";")
try:
lexer = shlex.shlex(command, posix = True, punctuation_chars = ";&|()")
@@ -3418,9 +3154,8 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
tokens = list(lexer)
except ValueError:
return True
- # A root can also hide behind an assignment (p=/; grep -R TOKEN $p) or a
- # default parameter (grep -R TOKEN ${root:-/home}); re-lex the fully expanded
- # command so the find/fd and recursive-search scans see the resolved token.
+ # A root can also hide behind an assignment or a default parameter, so re-lex the fully expanded command and let
+ # the find/fd and recursive-search scans see the resolved token.
expanded_command = _expand_shell_assignments(_expand_param_defaults(command))
if expanded_command != command:
try:
@@ -3431,23 +3166,19 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
return True
else:
scan_tokens = tokens
- # find/fd group with (...) which resets command context, so a trailing
- # -delete/-exec could slip past; scan every token when find/fd appears.
+ # find/fd group with (...) which resets command context, so a trailing -delete/-exec could slip past; scan every
+ # token when find/fd appears.
if any(os.path.basename(t.strip(";&|()`{}")).lower() in ("find", "fd") for t in scan_tokens):
if any(t.split("=", 1)[0] in _AUTO_UNSAFE_FIND_LIKE_FLAGS for t in scan_tokens):
return True
- # A recursive reader rooted outside the sandbox reads host files (grep -R
- # TOKEN /home, rg TOKEN /, grep -R TOKEN ~root, p=/; grep -R TOKEN $p, and
- # the always-recursive walkers tree /home / du /); ask. Bash expands
- # ~/~user to a home dir after this decision, so a tilde root is a sandbox
- # escape too. A path-qualified command token starts with "/" as well, but
- # that already asks below.
+ # A recursive reader rooted outside the sandbox reads host files, as do the always-recursive walkers (tree /home,
+ # du /); ask. Bash expands ~/~user to a home dir after this decision, so a tilde root is a sandbox escape too.
if any(t.startswith("/") or t.startswith("~") for t in scan_tokens):
token_bases = [os.path.basename(t.strip(";&|()`{}")).lower() for t in tokens]
if any(b in _AUTO_RECURSIVE_SEARCH or b in _AUTO_RECURSIVE_LISTERS for b in token_bases):
return True
- # ls only walks the whole subtree with -R/--recursive (ls -R /home,
- # ls -laR /); a non-recursive ls /home lists one level and stays here.
+ # ls only walks the whole subtree with -R/--recursive; a non-recursive ls /home lists one level and stays
+ # here.
if "ls" in token_bases and any(
t.split("=", 1)[0] in ("-R", "--recursive")
or (t[:1] == "-" and t[:2] != "--" and "=" not in t and "R" in t[1:])
@@ -3460,8 +3191,8 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
positional_args = 0
pending_flag_value = False
for token in tokens:
- # Runs of punctuation (";;", ";&") lex as one token; any token made
- # purely of separator characters still separates commands.
+ # Runs of punctuation (";;", ";&") lex as one token; any token made purely of separator characters still
+ # separates commands.
if (
token in _SHELL_SEPARATORS
or (token in _SHELL_KEYWORDS_AS_SEP and expect_command)
@@ -3474,24 +3205,20 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
pending_flag_value = False
continue
if token.startswith("-"):
- # A write/exec flag on an otherwise read-only command asks
- # (sort -o, tree -o, xxd -r, find -exec/-delete/...). Match
- # "--output=x", an attached short option "-o/tmp/out", and a short
- # option bundled in a cluster (sort -uo out => -u -o).
+ # A write/exec flag on an otherwise read-only command asks. Match "--output=x", an attached short option
+ # "-o/tmp/out", and a short option bundled in a cluster (sort -uo out => -u -o).
flag_head = token.split("=", 1)[0]
cluster = token[1:] if token[:2] != "--" and "=" not in token else ""
- # GNU tools accept unambiguous abbreviations of a long option, so
- # `sort --out=` reaches --output and `env --ch=/` reaches --chdir;
- # a "--x" prefix of an unsafe long flag fails closed.
+ # GNU tools accept unambiguous abbreviations of a long option, so `sort --out=` reaches --output; a "--x"
+ # prefix of an unsafe long flag fails closed.
is_long_abbrev = flag_head.startswith("--") and len(flag_head) > 2
for uf in _AUTO_UNSAFE_COMMAND_FLAGS.get(current_command, ()):
if flag_head == uf or (len(uf) == 2 and (token.startswith(uf) or uf[1] in cluster)):
return True
if is_long_abbrev and uf.startswith("--") and uf.startswith(flag_head):
return True
- # A flag that takes a following value (date -d STRING / -r FILE;
- # uniq -f N; xxd -c N) so the value token is not mistaken for a
- # clock-setting positional or an output-file positional.
+ # A flag that takes a following value (date -d STRING; uniq -f N) so the value token is not mistaken for a
+ # clock-setting or output-file positional.
pending_flag_value = "=" not in token and (
(current_command == "date" and flag_head in _DATE_DISPLAY_VALUE_FLAGS)
or flag_head in _SECOND_POSITIONAL_VALUE_FLAGS.get(current_command, ())
@@ -3501,10 +3228,9 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
continue
if not expect_command:
raw_pos = token.strip(";&|()`{}")
- # uniq [INPUT [OUTPUT]] writes its second file positional; count file
- # positionals and ask on the second one. A preceding option's value
- # (uniq -f 2) is consumed via pending_flag_value, so a file literally
- # named with digits (uniq 123 out) is still counted.
+ # uniq [INPUT [OUTPUT]] writes its second file positional; count file positionals and ask on the second
+ # one. A preceding option's value is consumed via pending_flag_value, so a file literally named with
+ # digits is still counted.
if current_command in _AUTO_SECOND_POSITIONAL_WRITES:
if pending_flag_value:
pending_flag_value = False
@@ -3512,9 +3238,8 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
positional_args += 1
if positional_args >= 2:
return True
- # hostname NAME sets the hostname; date <timestamp> sets the clock. A
- # positional past a display flag's value therefore mutates state and
- # asks (date's +FORMAT display token stays read-only).
+ # hostname NAME sets the hostname; date <timestamp> sets the clock. A positional past a display flag's
+ # value therefore mutates state and asks (date's +FORMAT display token stays read-only).
elif current_command in _AUTO_ARG_SENSITIVE_COMMANDS:
if pending_flag_value:
pending_flag_value = False
@@ -3522,16 +3247,16 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
return True
continue
if _ASSIGNMENT_RE.match(token):
- # Benign NAME=value prefixes are skipped, but ones that change
- # command lookup/loading (PATH, LD_PRELOAD, ...) fail closed.
+ # Benign NAME=value prefixes are skipped, but ones that change command lookup/loading (PATH, LD_PRELOAD)
+ # fail closed.
if _env_assignment_is_unsafe(token.split("=", 1)[0]):
return True
continue
if prefix_pending and token.lstrip("-").isdigit():
continue
raw = token.strip(";&|()`{}")
- # A path-qualified command (./ls, /tmp/cat) is an arbitrary executable,
- # not the trusted system utility its basename matches; ask first.
+ # A path-qualified command (./ls, /tmp/cat) is an arbitrary executable, not the trusted system utility its
+ # basename matches; ask first.
if "/" in raw or "\\" in raw:
return True
base = os.path.basename(raw).lower()
@@ -3540,8 +3265,8 @@ def _terminal_is_potentially_unsafe(command: str) -> bool:
base = stem
if base in _AUTO_SAFE_WRAPPERS:
prefix_pending = True
- # Track the wrapper so its own flags (env --chdir) are checked;
- # the real command overwrites this when it is reached.
+ # Track the wrapper so its own flags (env --chdir) are checked; the real command overwrites this when it
+ # is reached.
current_command = base
pending_flag_value = False
continue
@@ -3559,54 +3284,47 @@ def _python_is_potentially_unsafe(code: str) -> bool:
"""Classify python-tool code for auto mode (fail closed)."""
if not code or not code.strip():
return False
- # Anything the sandbox's static analysis already objects to would be
- # refused at execution time; surface it as a confirmation first.
+ # Anything the sandbox's static analysis already objects to would be refused at execution time; surface it as a
+ # confirmation first.
if _check_code_safety(code) is not None:
return True
try:
tree = ast.parse(code)
except SyntaxError:
return False # runs into a normal traceback; nothing to guard
- # Names bound to the builtin open (f = open; from builtins import open as f;
- # f, _ = (open, print)) so an aliased writer call is still checked below.
- # builtins_aliases tracks `import builtins [as b]` for builtins.exec/eval.
+ # Names bound to the builtin open (f = open; f, _ = (open, print)) so an aliased writer call is still checked
+ # below. builtins_aliases tracks `import builtins [as b]` for builtins.exec/eval.
open_aliases = {"open"}
- # Attribute names bound to open (box.f = open), so a later box.f('out', 'w')
- # write is still gated even though the callable is an attribute, not a name.
+ # Attribute names bound to open (box.f = open), so a later box.f('out', 'w') write is still gated even though the
+ # callable is an attribute, not a name.
attr_open_aliases: "set[str]" = set()
builtins_aliases = {"builtins", "__builtins__"}
- # Names bound to a dynamic lookup (rm = getattr(os, "remove");
- # f = globals()["open"]) whose calls cannot be proven read-only, so they
+ # Names bound to a dynamic lookup (rm = getattr(os, "remove")) whose calls cannot be proven read-only, so they
# fail closed.
dynamic_aliases = set()
- # Names bound to a dynamic-code builtin, including aliased ones
- # (from builtins import eval as e; e = builtins.exec), so a call or
- # reference through the alias fails closed too. compile() builds a code
- # object that FunctionType/exec can then run.
+ # Names bound to a dynamic-code builtin, including aliased ones, so a call or reference through the alias fails
+ # closed too. compile() builds a code object that FunctionType/exec can then run.
code_exec_aliases = {"exec", "eval", "__import__", "breakpoint", "compile"}
- # Names bound to a string literal (base = '/etc'), so a sensitive path
- # split through a variable (base + '/passwd') folds and is caught.
+ # Names bound to a string literal (base = '/etc'), so a sensitive path split through a variable folds and is
+ # caught.
literal_str_vars: "dict[str, str]" = {}
- # Pathlib constructor names incl. import aliases (from pathlib import Path as
- # P), os.path.join names bound directly (from os.path import join as j), and
- # writer functions imported as bare names (from numpy import save).
+ # Pathlib constructor names incl. import aliases, os.path.join names bound directly, and writer functions imported
+ # as bare names (from numpy import save).
path_ctor_aliases = set(_PATH_CTORS)
pathjoin_aliases: "set[str]" = set()
writer_aliases: "set[str]" = set()
- # Module names bound to os/posix (import os as o), so o.open(...) is still
- # recognized as the low-level create/write that os.open is.
+ # Module names bound to os/posix (import os as o), so o.open(...) is still recognized as the low-level
+ # create/write that os.open is.
os_aliases = {"os", "posix"}
- # Module names bound to a pickle-backed loader (import torch as t), so
- # t.load(...) is still gated as a code-executing deserialize.
+ # Module names bound to a pickle-backed loader (import torch as t), so t.load(...) is still gated as a
+ # code-executing deserialize.
load_module_aliases = set(_AUTO_UNSAFE_PY_LOAD_MODULES)
- # Names bound to the builtin getattr (g = getattr), so a dynamic lookup
- # aliased through it (rm = g(os, "remove"); rm("f")) still fails closed.
+ # Names bound to the builtin getattr (g = getattr), so a dynamic lookup aliased through it still fails closed.
getattr_aliases = {"getattr"}
- # Names bound to functools.partial, so a partial that wraps open/a writer
- # (w = partial(open, mode="w"); w("out.txt")) fails closed when w is called.
+ # Names bound to functools.partial, so a partial that wraps open/a writer fails closed when it is called.
partial_aliases: "set[str]" = set()
- # Archive constructors imported bare (from zipfile import ZipFile), so
- # ZipFile(name, "w") is gated like the zipfile.ZipFile attribute call.
+ # Archive constructors imported bare (from zipfile import ZipFile), so ZipFile(name, "w") is gated like the
+ # attribute call.
archive_ctor_aliases: "set[str]" = set()
# operator.methodcaller("write_text") is dynamic dispatch, like getattr.
operator_aliases = {"operator"}
@@ -3615,17 +3333,15 @@ def _python_is_potentially_unsafe(code: str) -> bool:
basicconfig_aliases: "set[str]" = set()
# fileinput.input(..., inplace=True) rewrites a file in place.
fileinput_aliases = {"fileinput"}
- # Higher-order invokers (map/filter/starmap/reduce) call their first arg, so
- # one handed a writer (map(open, ...)) writes without a direct open() site.
- # Track aliases (m = map; from itertools import starmap as sm) so an aliased
- # invoker is still checked; the write-callable gate keeps map(len, ...) safe.
+ # Higher-order invokers (map/filter/starmap/reduce) call their first arg, so one handed a writer writes without a
+ # direct open() site. Track aliases so an aliased invoker is still checked; the write-callable gate keeps map(len,
+ # ...) safe.
invoker_aliases = set(_HIGHER_ORDER_INVOKERS)
def _is_dynamic_namespace(node) -> bool:
- # A namespace mapping whose .get/.pop/.setdefault (or subscript) can return
- # open/eval/a mutator: globals()/locals()/vars(...), any X.__dict__,
- # __builtins__, sys.modules. Looking a name up through one is as dynamic as
- # getattr, so a value fetched from it fails closed.
+ # A namespace mapping whose .get/.pop/.setdefault (or subscript) can return open/eval/a mutator:
+ # globals()/locals()/vars(...), any X.__dict__, __builtins__, sys.modules. Looking a name up through one is as
+ # dynamic as getattr, so it fails closed.
if isinstance(node, ast.Attribute):
if node.attr == "__dict__":
return True
@@ -3641,9 +3357,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return False
def _methodcaller_writes(call) -> bool:
- # operator.methodcaller("write_text", ...) / methodcaller(name): unsafe
- # when the method name is a known writer/mutator, or non-constant (cannot
- # be proven read-only).
+ # operator.methodcaller("write_text", ...): unsafe when the method name is a known writer/mutator, or
+ # non-constant.
if not call.args:
return False
first = call.args[0]
@@ -3670,8 +3385,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return any(kw.arg == "filename" for kw in call.keywords or [])
def _wraps_write_callable(arg) -> bool:
- # The callable a partial wraps (partial(open, ...)); True when calling it
- # could create/overwrite a file or resolve a dynamic/mutating function.
+ # The callable a partial wraps; True when calling it could create/overwrite a file or resolve a
+ # dynamic/mutating function.
if isinstance(arg, ast.Name):
return (
arg.id in open_aliases
@@ -3691,13 +3406,9 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return False
def _passed_write_callable(arg) -> bool:
- # A concrete write callable handed as an argument to another call: a
- # name bound to open / a writer / an archive constructor, or an
- # attribute reference to a writer method / mutating os attr / archive
- # ctor / .open. Unlike _wraps_write_callable this omits the fail-closed
- # dynamic / getattr / code-exec poison aliases, which are already gated
- # where they are *called* and would over-trigger when a benign alias is
- # merely passed or printed (print(getattr(o, 'name'))).
+ # A concrete write callable handed as an argument to another call. Unlike _wraps_write_callable this omits the
+ # fail-closed dynamic / getattr / code-exec poison aliases, which are already gated where they are CALLED and
+ # would over-trigger when a benign alias is merely passed or printed.
if isinstance(arg, ast.Name):
return (
arg.id in open_aliases or arg.id in writer_aliases or arg.id in archive_ctor_aliases
@@ -3711,12 +3422,9 @@ def _python_is_potentially_unsafe(code: str) -> bool:
)
return False
- # Names bound more than once cannot be folded to a single literal: this scan
- # visits every assignment before any call is checked, so a later benign
- # reassignment (base = '/etc'; open(base + '/passwd'); base = 'data') would
- # otherwise mask the earlier sensitive value and auto-approve. Count every
- # binding target up front and poison multiply-bound names to the escape
- # sentinel so any path folded from them fails closed (asks) instead.
+ # Names bound more than once cannot be folded to a single literal: this scan visits every assignment before any
+ # call is checked, so a later benign reassignment would otherwise mask the earlier sensitive value and
+ # auto-approve. Count every binding target up front and poison multiply-bound names to the escape sentinel.
assign_counts: "dict[str, int]" = {}
for node in ast.walk(tree):
binding_targets = []
@@ -3760,8 +3468,7 @@ def _python_is_potentially_unsafe(code: str) -> bool:
if node.module in _OPEN_ALIAS_MODULES:
for alias in node.names:
if alias.name == "open":
- # gzip/bz2/lzma open(file, mode) writes on "w"/"a"/"x",
- # mode in the 2nd arg like builtin open.
+ # gzip/bz2/lzma open(file, mode) writes on "w"/"a"/"x", mode in the 2nd arg like builtin open.
open_aliases.add(alias.asname or "open")
if node.module == "pathlib":
for alias in node.names:
@@ -3783,8 +3490,7 @@ def _python_is_potentially_unsafe(code: str) -> bool:
for alias in node.names:
if alias.name in _AUTO_UNSAFE_PY_WRITE_METHODS:
writer_aliases.add(alias.asname or alias.name)
- # from itertools import starmap as sm / from functools import
- # reduce as r: an aliased higher-order invoker.
+ # from itertools import starmap as sm: an aliased higher-order invoker.
if alias.name in _HIGHER_ORDER_INVOKERS:
invoker_aliases.add(alias.asname or alias.name)
elif isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
@@ -3834,9 +3540,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
elif isinstance(value, ast.Attribute) and value.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
writer_aliases.update(targets) # s = np.save
elif isinstance(value, ast.Attribute) and value.attr == "open":
- # A captured .open bound method (p = Path('out').open) opens a file
- # on any call; its mode position varies (Path.open mode is 1st arg,
- # builtin open's is 2nd), so fail closed on the call rather than
+ # A captured .open bound method (p = Path('out').open) opens a file on any call; its mode position
+ # varies (Path.open mode is 1st arg, builtin open's is 2nd), so fail closed on the call rather than
# guess the write mode.
dynamic_aliases.update(targets) # p = Path('out').open; p('w')
elif isinstance(value, ast.Attribute) and value.attr in _ARCHIVE_CTOR_NAMES:
@@ -3855,8 +3560,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
and value.func.attr in ("get", "pop", "setdefault")
and _is_dynamic_namespace(value.func.value)
):
- # f = __builtins__.__dict__.get("open") / globals().get("open"):
- # a namespace lookup can return open/eval, so poison like getattr.
+ # f = __builtins__.__dict__.get("open"): a namespace lookup can return open/eval, so poison like
+ # getattr.
dynamic_aliases.update(targets)
elif (
isinstance(value, ast.Call)
@@ -3883,23 +3588,20 @@ def _python_is_potentially_unsafe(code: str) -> bool:
):
dynamic_aliases.update(targets) # w = methodcaller("write_text", ...)
elif isinstance(value, ast.Constant) and isinstance(value.value, str):
- # base = '/etc' -> resolve base in a later folded path. A name
- # bound more than once is poisoned (\x02) so it fails closed.
+ # base = '/etc' -> resolve base in a later folded path. A name bound more than once is poisoned (\x02)
+ # so it fails closed.
for t in targets:
literal_str_vars[t] = "\x02" if t in multi_assigned_names else value.value
elif isinstance(value, (ast.Call, ast.BinOp, ast.Name, ast.JoinedStr)):
- # p = Path('/etc'); q = p; r = os.path.join('/etc','x'): record a
- # fully-literal folded path so a later reuse (p / 'passwd') folds.
+ # p = Path('/etc'); q = p: record a fully-literal folded path so a later reuse (p / 'passwd') folds.
folded = _folded_path(value, literal_str_vars, path_ctor_aliases, pathjoin_aliases)
if folded is not None and "\x00" not in folded and "\x02" not in folded:
for t in targets:
literal_str_vars[t] = "\x02" if t in multi_assigned_names else folded
elif isinstance(value, (ast.Tuple, ast.List)):
- # Destructuring binds each element like a single assignment, so an
- # aliased callable (f, _ = (open, print)) AND a string / path
- # literal (base, leaf = ('/etc', 'passwd')) both propagate; without
- # the latter a path folded from base/leaf would miss the sensitive
- # target and auto-approve.
+ # Destructuring binds each element like a single assignment, so an aliased callable AND a string /
+ # path literal both propagate; without the latter a path folded from base/leaf would miss the
+ # sensitive target and auto-approve.
for target in assign_targets:
if isinstance(target, (ast.Tuple, ast.List)) and len(target.elts) == len(
value.elts
@@ -3935,10 +3637,9 @@ def _python_is_potentially_unsafe(code: str) -> bool:
"\x02" if tid in multi_assigned_names else folded
)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
- # A callable captured as a parameter default (def f(o=open): o('x','w'))
- # binds that parameter to the same alias set, so a later call through
- # the parameter is still gated. defaults align to the tail of
- # posonlyargs+args; kw_defaults align 1:1 with kwonlyargs (None = none).
+ # A callable captured as a parameter default (def f(o=open)) binds that parameter to the same alias set,
+ # so a later call through the parameter is still gated. defaults align to the tail of posonlyargs+args;
+ # kw_defaults align 1:1 with kwonlyargs.
_a = node.args
_defaulted = list(
zip(
@@ -3966,10 +3667,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
elif _did in dynamic_aliases:
dynamic_aliases.add(_param.arg)
elif isinstance(_default, ast.Attribute):
- # An attribute writer / archive ctor / captured .open used as
- # a default (def f(s=np.save), def f(z=zipfile.ZipFile),
- # def f(o=Path('x').open)) binds the parameter like the
- # equivalent assignment; a benign attribute (np.mean) does not.
+ # An attribute writer / archive ctor / captured .open used as a default binds the parameter like
+ # the equivalent assignment; a benign attribute (np.mean) does not.
if _default.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
writer_aliases.add(_param.arg)
elif _default.attr in _ARCHIVE_CTOR_NAMES:
@@ -3992,11 +3691,9 @@ def _python_is_potentially_unsafe(code: str) -> bool:
and _wraps_write_callable(_default.args[0])
):
dynamic_aliases.add(_param.arg) # def f(w=partial(open, mode="w"))
- # Naming a code-executing loader asks, wherever the name appears. Presence
- # rather than dataflow: a loader can be aliased, subclassed, packed into a
- # container, returned from a helper or picked by a conditional, and following
- # it through all of those is a game without an end. A safe read names none of
- # these, so yaml.safe_load and json.load are unaffected.
+ # Naming a code-executing loader asks, wherever the name appears. Presence rather than dataflow: a loader can be
+ # aliased, subclassed, packed into a container, returned from a helper or picked by a conditional, and following
+ # it through all of those is a game without an end. A safe read names none of these.
_module_names = set(_AUTO_UNSAFE_PY_LOAD_MODULES) # receivers: yaml.load
_bare_names = set(_AUTO_UNSAFE_YAML_LOADERS) # loaders named on their own
_imported_modules = set() # only the module itself, for the return rule
@@ -4038,8 +3735,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return True
elif isinstance(node, ast.Name) and node.id in _bare_names:
return True
- # Handing the module out of a function hands out every loader on it, and
- # the caller's name for it cannot be seen from here.
+ # Handing the module out of a function hands out every loader on it, and the caller's name for it cannot be
+ # seen from here.
elif isinstance(node, (ast.Return, ast.Lambda)):
_out = node.value if isinstance(node, ast.Return) else node.body
if isinstance(_out, ast.Name) and _out.id in _imported_modules:
@@ -4053,24 +3750,23 @@ def _python_is_potentially_unsafe(code: str) -> bool:
elif isinstance(node, ast.ImportFrom):
if node.module and node.module.split(".")[0] in _AUTO_UNSAFE_PY_MODULES:
return True
- # from-imports can bind mutating callables to bare names
- # (from os import remove [as rm]); star imports hide anything.
+ # from-imports can bind mutating callables to bare names (from os import remove [as rm]); star imports
+ # hide anything.
for alias in node.names:
if alias.name == "*" or alias.name in _AUTO_UNSAFE_PY_ATTRS:
return True
- # os.open imported as a bare callable is a low-level
- # create/write, like the os.open attribute call below.
+ # os.open imported as a bare callable is a low-level create/write, like the os.open attribute call
+ # below.
if alias.name == "open" and node.module in ("os", "posix"):
return True
elif isinstance(node, ast.Attribute):
- # Any reference to a mutating attribute fails closed, even
- # without an immediate call (rm = os.remove; rm("x")).
+ # Any reference to a mutating attribute fails closed, even without an immediate call (rm = os.remove;
+ # rm("x")).
if node.attr in _AUTO_UNSAFE_PY_ATTRS:
return True
- # builtins.exec / builtins.eval / builtins.__import__ (and
- # compile/breakpoint) are dynamic code execution, matching the
- # bare-name code_exec_aliases path; __builtins__.__import__(...)
- # is a dynamic import that dodges the static import check.
+ # builtins.exec / eval / __import__ (and compile/breakpoint) are dynamic code execution, matching the
+ # bare-name code_exec_aliases path; __builtins__.__import__(...) is a dynamic import that dodges the
+ # static import check.
if (
node.attr in ("exec", "eval", "__import__", "breakpoint", "compile")
and isinstance(node.value, ast.Name)
@@ -4081,9 +3777,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
if node.id in code_exec_aliases:
return True
elif isinstance(node, ast.Constant):
- # Credential paths / parent traversal in a string or bytes
- # literal (open('/etc/passwd') and open(b'/etc/passwd')), or a
- # glob that resolves to one (glob.glob('/e??/passwd')).
+ # Credential paths / parent traversal in a string or bytes literal, or a glob that resolves to one
+ # (glob.glob('/e??/passwd')).
val = node.value
if isinstance(val, bytes):
val = val.decode("latin-1", "ignore")
@@ -4092,10 +3787,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
):
return True
elif isinstance(node, (ast.BinOp, ast.JoinedStr)):
- # A sensitive path concatenated from literals ('/etc'+'/passwd'),
- # a pathlib / chain, an f-string (f'/proc/{pid}/environ'), a
- # dynamic segment under a sensitive dir (f'/etc/{name}'), or one
- # split through a literal variable (base = '/etc'; base+'/passwd').
+ # A sensitive path concatenated from literals, a pathlib / chain, an f-string, a dynamic segment under
+ # a sensitive dir, or one split through a literal variable.
if _folded_is_sensitive(
_folded_path(node, literal_str_vars, path_ctor_aliases, pathjoin_aliases)
):
@@ -4107,20 +3800,15 @@ def _python_is_potentially_unsafe(code: str) -> bool:
):
return True
func = node.func
- # x.__call__(args) is just x(args): unwrap so open.__call__('o',
- # 'w') / save.__call__(...) reach the open/writer checks below
- # instead of looking like a harmless ".__call__" attribute call.
+ # x.__call__(args) is just x(args): unwrap so open.__call__('o', 'w') reaches the open/writer checks
+ # below instead of looking like a harmless ".__call__" attribute call.
if isinstance(func, ast.Attribute) and func.attr == "__call__":
func = func.value
if isinstance(func, (ast.Call, ast.Subscript)):
return True # calling a call/subscript result is dynamic
- # A concrete write callable (open/writer/archive-ctor alias, or a
- # writer/mutating attribute) handed as an argument to any call
- # escapes into a helper that can invoke it without a direct
- # open()/writer site -- the same bypass the map/starmap/reduce
- # branches below gate, but through a user-defined helper
- # (def run(fn): fn('o','w').write('x'); run(open)). A benign
- # callable argument (run(len)) is unaffected.
+ # A concrete write callable handed as an argument to any call escapes into a helper that can invoke it
+ # without a direct open()/writer site: the same bypass the map/starmap/reduce branches gate, but
+ # through a user-defined helper. A benign callable argument (run(len)) is unaffected.
if any(_passed_write_callable(a) for a in node.args) or any(
_passed_write_callable(kw.value) for kw in node.keywords
):
@@ -4133,20 +3821,16 @@ def _python_is_potentially_unsafe(code: str) -> bool:
# A writer imported as a bare name (from numpy import save).
if func.id in writer_aliases:
return True
- # A bare archive constructor (from zipfile import ZipFile)
- # takes the mode as its 2nd arg like open, so ZipFile(x, "w")
- # writes but ZipFile(x) reads.
+ # A bare archive constructor takes the mode as its 2nd arg like open, so ZipFile(x, "w") writes
+ # but ZipFile(x) reads.
if func.id in archive_ctor_aliases and _builtin_open_writes(node):
return True
- # A bare-imported logging.basicConfig(filename=...) opens a
- # log file for writing (from logging import basicConfig).
+ # A bare-imported logging.basicConfig(filename=...) opens a log file for writing.
if func.id in basicconfig_aliases and _basicconfig_writes(node):
return True
- # A writer/open alias handed to a higher-order invoker
- # (map(open, names, modes), starmap(np.save, ...), or an
- # aliased m = map / sm = starmap) is called without a direct
- # open(...)/save(...) site; the callable is the first
- # positional arg. A benign map(len, ...) is unaffected.
+ # A writer/open alias handed to a higher-order invoker is called without a direct
+ # open(...)/save(...) site; the callable is the first positional arg. A benign map(len, ...) is
+ # unaffected.
if (
func.id in invoker_aliases
and node.args
@@ -4154,26 +3838,23 @@ def _python_is_potentially_unsafe(code: str) -> bool:
):
return True
elif isinstance(func, ast.Attribute):
- # Writer methods persist to disk without open() (np.save,
- # img.save, plt.savefig, df.to_csv, json.dump); ask before
- # they mutate the workdir in auto mode.
+ # Writer methods persist to disk without open() (np.save, plt.savefig, df.to_csv); ask before they
+ # mutate the workdir in auto mode.
if func.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
return True
# logging.basicConfig(filename=...) opens a log file for write.
if func.attr == "basicConfig" and _basicconfig_writes(node):
return True
- # A qualified higher-order invoker (itertools.starmap(open, ...),
- # functools.reduce(open, ...)) calls its first arg like the bare
- # map/filter form; the writer-check on that arg keeps a benign
- # itertools.starmap(len, ...) / df.map(transform) safe.
+ # A qualified higher-order invoker (itertools.starmap(open, ...)) calls its first arg like the
+ # bare map/filter form; the writer-check on that arg keeps a benign starmap(len, ...) safe.
if (
func.attr in _HIGHER_ORDER_INVOKERS
and node.args
and _wraps_write_callable(node.args[0])
):
return True
- # fileinput.input(..., inplace=True) rewrites a file in place;
- # the default fileinput.input(...) only reads, so gate inplace.
+ # fileinput.input(..., inplace=True) rewrites a file in place; the default fileinput.input(...)
+ # only reads, so gate inplace.
if (
func.attr == "input"
and isinstance(func.value, ast.Name)
@@ -4181,16 +3862,16 @@ def _python_is_potentially_unsafe(code: str) -> bool:
and _fileinput_inplace(node)
):
return True
- # os.open() always creates/writes a file descriptor
- # (tracked through import aliases: import os as o; o.open()).
+ # os.open() always creates/writes a file descriptor (tracked through import aliases: import os as
+ # o; o.open()).
if (
func.attr == "open"
and isinstance(func.value, ast.Name)
and func.value.id in os_aliases
):
return True
- # A pickle-backed loader (torch.load, joblib.load) can execute
- # code embedded in the file it deserializes.
+ # A pickle-backed loader (torch.load, joblib.load) can execute code embedded in the file it
+ # deserializes.
if (
func.attr == "load"
and isinstance(func.value, ast.Name)
@@ -4199,29 +3880,24 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return True
if func.attr == "open" and _attr_open_writes(node):
return True
- # An open bound onto an attribute (box.f = open; box.f('o','w'))
- # writes on 'w'/'a'/'x' like the builtin, so gate the attr name.
+ # An open bound onto an attribute (box.f = open) writes on 'w'/'a'/'x' like the builtin, so gate
+ # the attr name.
if func.attr in attr_open_aliases and _builtin_open_writes(node):
return True
- # ZipFile/TarFile/GzipFile/BZ2File/LZMAFile take the mode as
- # the 2nd arg (like builtin open), so ZipFile(name, "w") writes
- # but ZipFile(name) reads.
+ # ZipFile/TarFile/GzipFile/BZ2File/LZMAFile take the mode as the 2nd arg, so ZipFile(name, "w")
+ # writes but ZipFile(name) reads.
if func.attr in _ARCHIVE_CTOR_NAMES and _builtin_open_writes(node):
return True
- # Enumerating a directory outside the sandbox reads host
- # filenames (and enables reading their contents) the direct
- # /etc/passwd checks would prompt for: Path('/etc').iterdir(),
- # os.scandir('/etc'), os.listdir('/home'), os.walk('/'),
- # Path('/home').glob('*'), glob.glob('/home/*'). Gate when the
- # target dir folds to an absolute/tilde/sensitive path; a
- # relative dir (Path('.').iterdir(), glob.glob('src/*')) stays
- # safe, and an unresolved dynamic dir is left to other checks.
+ # Enumerating a directory outside the sandbox reads host filenames (and enables reading their
+ # contents) the direct /etc/passwd checks would prompt for. Gate when the target dir folds to an
+ # absolute/tilde/sensitive path; a relative dir stays safe, and an unresolved dynamic dir is left
+ # to other checks.
_enum_dir = None
if func.attr == "iterdir":
_enum_dir = func.value
elif func.attr in ("glob", "rglob", "iglob"):
- # Path('/home').glob('*') enumerates the receiver dir;
- # glob.glob('/home/*') enumerates the pattern's root dir.
+ # Path('/home').glob('*') enumerates the receiver dir; glob.glob('/home/*') enumerates the
+ # pattern's root dir.
_recv = _folded_path(
func.value, literal_str_vars, path_ctor_aliases, pathjoin_aliases
)
@@ -4251,9 +3927,8 @@ def _python_is_potentially_unsafe(code: str) -> bool:
return False
-# Cloud-metadata / link-local hosts (mirrors the sandbox SSRF blocklist): a
-# read-named HTTP MCP tool pointed at one (fetch_url
-# {"url": "http://169.254.169.254/..."}) reads instance credentials, so it asks.
+# Cloud-metadata / link-local hosts (mirrors the sandbox SSRF blocklist): a read-named HTTP MCP tool pointed at one
+# reads instance credentials, so it asks.
_MCP_METADATA_HOST_RE = re.compile(
r"169\.254\.\d{1,3}\.\d{1,3}|"
r"100\.100\.100\.\d{1,3}|"
@@ -4276,18 +3951,16 @@ _MCP_CREDENTIAL_KEY_RE = re.compile(
def _mcp_arguments_reference_sensitive(arguments) -> bool:
- """True if any string in an MCP call's arguments names a credential path, a
- credential/secret environment variable (get_env {"name": "OPENAI_API_KEY"}),
- or a cloud-metadata host (fetch_url {"url": "http://169.254.169.254/..."})."""
+ """True if any string in an MCP call's arguments names a credential path, a credential/secret
+ environment variable, or a cloud-metadata host."""
def key_is_credential(key) -> bool:
return isinstance(key, str) and bool(_MCP_CREDENTIAL_KEY_RE.match(key.strip()))
def walk(value, is_prose: bool = False) -> bool:
if isinstance(value, str):
- # A path can be carried under any argument name, so prose keys are
- # skipped rather than path keys allowlisted: an issue body mentioning
- # a credential file is text to store, not a file to open.
+ # A path can be carried under any argument name, so prose keys are skipped rather than path keys
+ # allowlisted: an issue body mentioning a credential file is text to store, not a file to open.
if is_prose:
return False
return (
@@ -4309,66 +3982,55 @@ def _mcp_arguments_reference_sensitive(arguments) -> bool:
return walk(arguments)
-# DDL object types CREATE / DROP / ALTER share (DROP FUNCTION and ALTER INDEX
-# mutate just like CREATE INDEX).
+# DDL object types CREATE / DROP / ALTER share (DROP FUNCTION and ALTER INDEX mutate just like CREATE INDEX).
_SQL_DDL_OBJECTS = (
r"table|database|schema|index|view|function|procedure|trigger|"
r"sequence|role|user|extension|type|domain|aggregate|policy"
)
-# Modifiers between the DDL verb and object (CREATE OR REPLACE VIEW, DROP
-# MATERIALIZED VIEW, CREATE UNIQUE INDEX).
+# Modifiers between the DDL verb and object (CREATE OR REPLACE VIEW, DROP MATERIALIZED VIEW).
_SQL_DDL_MODIFIERS = (
r"(?:(?:or\s+replace|unique|temp|temporary|global|local|materialized|recursive)\s+)*"
)
-# A SQL identifier (bare, "quoted", `quoted`, [bracketed]), optionally
-# schema-qualified, so UPDATE "users"/public.users/ONLY .../[users] SET all hit.
+# A SQL identifier (bare, "quoted", `quoted`, [bracketed]), optionally schema-qualified, so UPDATE
+# "users"/public.users/ONLY .../[users] SET all hit.
_SQL_IDENT = r'(?:\w+|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]+\])'
_SQL_UPDATE_TARGET = r"(?:only\s+)?" + _SQL_IDENT + r"(?:\s*\.\s*" + _SQL_IDENT + r")*"
-# A read-named MCP tool (query_database, run_query) can still carry a mutating
-# SQL statement; match DML/DDL as whole statements (DELETE FROM, DROP TABLE) so
-# a natural-language query that merely contains the word "delete" stays safe.
+# A read-named MCP tool can still carry a mutating SQL statement; match DML/DDL as whole statements so a
+# natural-language query that merely contains the word "delete" stays safe.
_MCP_ARG_MUTATION_RE = re.compile(
r"\b(?:delete\s+from|"
r"drop\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
- # Match the whole identifier (the outer trailing \b needs the alternative to
- # end on a word boundary, so a bare \w stops mid-name and TRUNCATE users slips
- # through); the optional opening quote/bracket/backtick covers "users"/[users].
+ # Match the whole identifier: the outer trailing \b needs the alternative to end on a word boundary, so a bare \w
+ # stops mid-name and TRUNCATE users slips through.
r"truncate\s+(?:table\s+)?[\"\[`]?\w+|"
- # UPDATE <target> [AS alias] SET: allow an explicit AS alias before SET so
- # UPDATE users AS u SET is caught, not just the bare form. The implicit-alias
- # form (UPDATE users u SET) is left out because it is indistinguishable from
- # the prose "update <noun> <noun> set" and would flag natural language.
+ # UPDATE <target> [AS alias] SET: allow an explicit AS alias before SET. The implicit-alias form is left out
+ # because it is indistinguishable from the prose "update <noun> <noun> set".
r"update\s+" + _SQL_UPDATE_TARGET + r"(?:\s+as\s+" + _SQL_IDENT + r")?\s+set\b|"
r"insert\s+into|replace\s+into|"
- # SELECT ... INTO OUTFILE/DUMPFILE writes a file (MySQL); bare SELECT INTO
- # <table> is left out (PL/pgSQL uses it to read into a variable).
+ # SELECT ... INTO OUTFILE/DUMPFILE writes a file (MySQL); bare SELECT INTO <table> is left out (PL/pgSQL uses it
+ # to read into a variable).
r"select\s+[^;]*?\binto\s+(?:outfile|dumpfile)\b|"
- # ALTER SYSTEM persists PostgreSQL server configuration; SYSTEM is not one of
- # the DDL objects above, so match it explicitly.
+ # ALTER SYSTEM persists PostgreSQL server configuration; SYSTEM is not one of the DDL objects above, so match it
+ # explicitly.
r"alter\s+system\b|"
r"alter\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
r"create\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
r"grant\s+\w+|revoke\s+\w+|merge\s+into|"
- # Catalog mutations: COMMENT ON <obj>, SECURITY LABEL, and LOCK TABLE change
- # metadata or take a lock. Each needs a following keyword, so a "comment"
- # column (SELECT comment FROM t) or "locks" table stays safe.
+ # Catalog mutations: COMMENT ON <obj>, SECURITY LABEL, LOCK TABLE. Each needs a following keyword, so a "comment"
+ # column or "locks" table stays safe.
r"comment\s+on\b|security\s+label\b|lock\s+table\b|"
- # PostgreSQL maintenance writes: REFRESH MATERIALIZED VIEW rewrites the view,
- # REINDEX rebuilds an index. Both need a following object keyword/name, so a
- # column or word "refresh"/"reindex" in prose stays safe.
+ # PostgreSQL maintenance writes: REFRESH MATERIALIZED VIEW, REINDEX. Both need a following object keyword/name, so
+ # the word in prose stays safe.
r"refresh\s+materialized\s+view|reindex\s+\w+|"
- # CALL proc(...) / EXEC[UTE] name / VACUUM mutate; CALL needs a following
- # "(", ";", or end so natural-language "call me back" stays safe.
+ # CALL proc(...) / EXEC[UTE] name / VACUUM mutate; CALL needs a following "(", ";", or end so natural-language
+ # "call me back" stays safe.
r"call\s+\w+(?=\s*[(;]|\s*$)|exec(?:ute)?\s+\w+|vacuum|"
- # COPY ... FROM bulk-loads and COPY ... TO writes a file ([^;] stays in one
- # statement).
+ # COPY ... FROM bulk-loads and COPY ... TO writes a file ([^;] stays in one statement).
r"copy\s+[^;]*?\b(?:from|to)\b)\b",
re.IGNORECASE,
)
-# SQLite statements the base regex misses: ATTACH/DETACH a database (DATABASE
-# optional via the quoted-path form), a write-form PRAGMA (name=value / name(...),
-# unlike the read-form PRAGMA name), and load_extension() which runs a shared
-# library. These tokens are not natural language, so benign text does not trip.
+# SQLite statements the base regex misses: ATTACH/DETACH a database, a write-form PRAGMA (name=value), and
+# load_extension() which runs a shared library. These tokens are not natural language, so benign text does not trip.
_MCP_ARG_SQLITE_MUTATION_RE = re.compile(
r"\b(?:attach|detach)\s+database\b"
r"|\battach\s+(?:database\s+)?['\"]"
@@ -4376,9 +4038,8 @@ _MCP_ARG_SQLITE_MUTATION_RE = re.compile(
r"|\bload_extension\s*\(",
re.IGNORECASE,
)
-# State-changing SQL functions that mutate or write files inside a read-shaped
-# SELECT (pg_terminate_backend, setval, pg_write_file, lo_export, ...). The
-# trailing "(" is required, so a column named setval_count stays safe.
+# State-changing SQL functions that mutate or write files inside a read-shaped SELECT (pg_terminate_backend,
+# pg_write_file, lo_export). The trailing "(" is required, so a column named setval_count stays safe.
_MCP_ARG_SQL_FUNCTION_RE = re.compile(
r"\b(?:pg_terminate_backend|pg_cancel_backend|pg_write_file|lo_export|"
r"lo_import|setval|nextval|set_config|pg_notify|dblink_exec|pg_reload_conf|"
@@ -4389,30 +4050,27 @@ _MCP_ARG_SQL_FUNCTION_RE = re.compile(
r"pg_try_advisory_(?:lock|lock_shared|xact_lock|xact_lock_shared))\s*\(",
re.IGNORECASE,
)
-# SQL engines treat /* */ and -- comments as whitespace, so DELETE/**/FROM and
-# UPDATE/**/users evade the \s+ in the mutation regex; collapse comments to a
-# space before matching.
+# SQL engines treat /* */ and -- comments as whitespace, so DELETE/**/FROM evades the \s+ in the mutation regex;
+# collapse comments to a space before matching.
_SQL_COMMENT_RE = re.compile(r"/\*.*?\*/|--[^\n]*", re.DOTALL)
-# A GraphQL mutation on a read-named tool. Directives are valid between the name
-# and body (mutation M @audit { ... }), so allow @directive[(args)] before ( or {.
+# A GraphQL mutation on a read-named tool. Directives are valid between the name and body, so allow @directive[(args)]
+# before ( or {.
_GRAPHQL_MUTATION_RE = re.compile(
r"\bmutation\b\s*\w*\s*(?:@\w+(?:\s*\([^)]*\))?\s*)*[({]", re.IGNORECASE
)
-# GraphQL # comments run to end-of-line and count as whitespace, so a comment
-# between `mutation` and the body (mutation # note\n { ... }) would otherwise
-# hide it; collapse them to a space before matching.
+# GraphQL # comments run to end-of-line and count as whitespace, so a comment between `mutation` and the body would
+# otherwise hide it.
_GRAPHQL_COMMENT_RE = re.compile(r"#[^\n]*")
-# HTTP verbs that mutate the target resource; a generic HTTP MCP tool
-# (mcp__http__get_url {"method": "DELETE"}) mutates an external service even
-# though its name looks read-only. GET/HEAD/OPTIONS/TRACE only read.
+# HTTP verbs that mutate the target resource; a generic HTTP MCP tool mutates an external service even though its name
+# looks read-only. GET/HEAD/OPTIONS/TRACE only read.
_MUTATING_HTTP_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_HTTP_METHOD_KEYS = frozenset({"method", "http_method", "httpmethod", "verb", "http_verb"})
-# Argument names that carry free text the tool stores or displays rather than
-# acts on, so a path or a statement mentioned inside them is a mention.
+# Argument names that carry free text the tool stores or displays rather than acts on, so a path or a statement
+# mentioned inside them is a mention.
_MCP_PROSE_KEYS = frozenset(
{
"text",
@@ -4436,8 +4094,8 @@ _MCP_PROSE_KEYS = frozenset(
"context",
}
)
-# Argument names that carry a statement the tool will execute, as opposed to
-# free text the tool will merely store or display.
+# Argument names that carry a statement the tool will execute, as opposed to free text the tool will merely store or
+# display.
_MCP_QUERY_KEYS = frozenset(
{
"query",
@@ -4463,15 +4121,13 @@ _MCP_QUERY_KEYS = frozenset(
def _mcp_arguments_mutate(arguments) -> bool:
- """True if an MCP call's arguments carry a mutating command, so a read-named
- but write-capable tool (query_database {"query": "DELETE FROM runs"},
- query_graphql {"query": "mutation { deleteIssue(id: 1) }"}, or an HTTP tool
- {"method": "DELETE"}) asks."""
+ """True if an MCP call's arguments carry a mutating command, so a read-named but write-capable
+ tool asks."""
def walk(value, in_query: bool = False) -> bool:
if isinstance(value, str):
- # Prose that merely mentions DELETE FROM (a chat message, an issue
- # body) is not a statement this call will run.
+ # Prose that merely mentions DELETE FROM (a chat message, an issue body) is not a statement this call will
+ # run.
if not in_query:
return False
_sql = _SQL_COMMENT_RE.sub(" ", value)
@@ -4501,18 +4157,12 @@ def _mcp_arguments_mutate(arguments) -> bool:
return walk(arguments)
-# Tools that are read-only / non state-mutating regardless of their arguments,
-# so auto mode never has to pause them (their safety needs no argument scan).
-# render_html is NOT unconditionally safe: it runs arbitrary HTML/JS in the
-# canvas preview frame. A static canvas (charts, layout, inline SVG) never
-# reaches the network, but code that calls out can exfiltrate or fetch under the
-# preview's CSP when artifact network access is enabled, so those ask; a canvas
-# with no network construct still auto-runs. Matches JS egress APIs, a remote or
-# root-relative <script src>/src=/href=/srcset, a CSS url()/@import that loads a
-# resource, and ws(s) URLs. A leading "/" covers both //host (protocol-relative)
-# and /path (root-relative, which the CSP resolves against the frame origin); a
-# "./x" or bare relative ref and a url(#id)/data: ref are not matched, so an
-# inline-SVG canvas (whose w3.org namespace lives in xmlns=) stays safe.
+# Tools that are read-only regardless of their arguments, so auto mode never has to pause them.
+# render_html is NOT unconditionally safe: it runs arbitrary HTML/JS in the canvas preview frame. A static canvas
+# never reaches the network, but code that calls out can exfiltrate or fetch under the preview's CSP when artifact
+# network access is enabled, so those ask. Matches JS egress APIs, a remote or root-relative <script
+# src>/src=/href=/srcset, a CSS url()/@import, and ws(s) URLs. A leading "/" covers both //host and /path; a "./x" or
+# bare relative ref and a url(#id)/data: ref are not matched, so an inline-SVG canvas stays safe.
_RENDER_HTML_NETWORK_RE = re.compile(
r"\bfetch\s*\(|"
r"XMLHttpRequest|"
@@ -4521,46 +4171,40 @@ _RENDER_HTML_NETWORK_RE = re.compile(
r"\bsendBeacon\b|"
r"\bimportScripts\b|"
r"navigator\s*\.\s*serviceWorker|"
- # new Worker(...) / new SharedWorker(...) run a script off the main thread
- # that this static scan cannot see: a module worker from a CORS-enabled CDN
- # executes remote code, and a blob/same-origin worker can fetch/importScripts
- # to egress, all reachable under worker-src http: https: blob:. Gate the
- # constructor like importScripts/serviceWorker; a var merely named myWorker
+ # new Worker(...) / new SharedWorker(...) run a script off the main thread that this static scan cannot see: a
+ # module worker from a CORS-enabled CDN executes remote code, and a blob/same-origin worker can
+ # fetch/importScripts to egress, all reachable under worker-src http: https: blob:. A var merely named myWorker
# (no "new") stays static.
r"\bnew\s+(?:Shared)?Worker\s*\(|"
r"@import|"
r"url\(\s*[\"']?\s*(?:https?:|/)|"
r"<script[^>]*\bsrc\s*=|"
r"\b(?:src|href|srcset)\s*=\s*[\"']?\s*(?:https?:|/)|"
- # Self-navigation sinks: location.assign/replace(...), window.open(...), and
- # assigning a URL to (window.)location(.href). location.reload()/history.back
- # do not navigate to a new URL, so they stay static.
+ # Self-navigation sinks: location.assign/replace(...), window.open(...), and assigning a URL to
+ # (window.)location(.href). location.reload()/history.back do not navigate to a new URL, so they stay static.
r"\blocation\s*\.\s*(?:assign|replace)\s*\(|"
r"\bwindow\s*\.\s*open\s*\(|"
r"\b(?:window\s*\.\s*)?location(?:\s*\.\s*href)?\s*=\s*[\"'`]?\s*(?:https?:|/)|"
# Bracket-access obfuscation: window['fetch'](...), self["open"](...).
r"\[\s*[\"'](?:fetch|open|XMLHttpRequest|WebSocket|EventSource|importScripts|"
r"sendBeacon|serviceWorker)[\"']\s*\]|"
- # The same for the navigation sinks: location['assign'](...),
- # location["href"] = URL. Anchored to location (dotted or bracketed) so an
- # ordinary str['replace'](...) or obj['href'] read stays static.
+ # The same for the navigation sinks. Anchored to location (dotted or bracketed) so an ordinary str['replace'](...)
+ # or obj['href'] read stays static.
r"(?:\blocation|\[\s*[\"']location[\"']\s*\])\s*\[\s*[\"'](?:assign|replace)[\"']\s*\]\s*\(|"
r"(?:\blocation|\[\s*[\"']location[\"']\s*\])\s*\[\s*[\"']href[\"']\s*\]"
r"\s*=\s*[\"'`]?\s*(?:https?:|/)|"
- # Computed bracket key spliced at runtime on a global host object
- # (window['fet'+'ch'](...)): a quoted fragment adjacent to a + inside the
- # index. Anchored to a host object so a plain obj['a'+'b'] key stays safe.
+ # Computed bracket key spliced at runtime on a global host object (window['fet'+'ch'](...)): a quoted fragment
+ # adjacent to a + inside the index. Anchored to a host object so a plain obj['a'+'b'] key stays safe.
r"\b(?:window|self|globalThis|top|parent|frames)\s*\[[^\]]*"
r"(?:[\"']\s*\+|\+\s*[\"'])[^\]]*\]|"
- # Declarative meta-refresh navigation to a URL (order-tolerant); a bare
- # content="30" self-reload has no url= and stays static.
+ # Declarative meta-refresh navigation to a URL (order-tolerant); a bare content="30" self-reload has no url= and
+ # stays static.
r"<meta\b(?=[^>]*http-equiv\s*=\s*[\"']?\s*refresh)(?=[^>]*\burl\s*=)|"
r"\bwss?://",
re.IGNORECASE,
)
-# Block comments can split an egress token (fetch/*x*/(...)); strip them before
-# matching. Line // comments are left alone -- stripping them would eat the // in
-# an https:// URL and hide a real load.
+# Block comments can split an egress token (fetch/*x*/(...)); strip them before matching. Line // comments are left
+# alone: stripping them would eat the // in an https:// URL and hide a real load.
_JS_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
@@ -4571,12 +4215,9 @@ def _render_html_reaches_network(arguments: dict) -> bool:
return bool(_RENDER_HTML_NETWORK_RE.search(_JS_BLOCK_COMMENT_RE.sub("", code)))
-# Tools that are read-only regardless of their arguments, so auto mode never has
-# to pause them and their safety needs no argument scan. render_html is handled
-# separately above because a networked canvas does need approval.
-# search_conversation only reads this chat's own past turns, so auto mode would otherwise
-# prompt for approval on every call. deep_research runs no code and reaches nothing either: it
-# only reports that the user's own armed research is starting, and without it here
+# Tools that are read-only regardless of their arguments; render_html is handled separately above because a networked
+# canvas does need approval. search_conversation only reads this chat's own past turns, and deep_research runs no code
+# and reaches nothing: it only reports that the user's own armed research is starting, and without it here
# is_high_risk_tool_call's unknown-name default would prompt on every handoff.
_ALWAYS_SAFE_TOOLS = frozenset(
{"web_search", "search_knowledge_base", "search_conversation", "deep_research"}
@@ -4584,36 +4225,29 @@ _ALWAYS_SAFE_TOOLS = frozenset(
def is_always_safe_tool(name: str) -> bool:
- """True for tools that never need an auto-mode prompt on any arguments, so a
- caller (e.g. the streaming provisional card) can allow them before the full
- arguments are known. render_html is intentionally excluded: a networked
- canvas needs approval, which cannot be judged before its arguments stream."""
+ """True for tools that never need an auto-mode prompt on any arguments, so a caller (e.g. the
+ streaming provisional card) can allow them before the full arguments are known. render_html
+ is intentionally excluded: a networked canvas needs approval, which cannot be judged before
+ its arguments stream."""
return name in _ALWAYS_SAFE_TOOLS
-# Tools whose provisional card is only a text preview of the arguments, so it can stream
-# while awaiting approval.
+# Tools whose provisional card is only a text preview of the arguments, so it can stream while awaiting approval.
_TEXT_PREVIEW_TOOLS = frozenset({"python", "terminal", "edit_file"})
def has_text_only_provisional_card(name: str) -> bool:
- """True when streaming this tool's arguments before approval shows only text.
-
- A large code payload takes a minute or more to write, and suppressing the
- card until the call completes leaves the chat blank the whole time. Nothing
- runs before the decision either way, and you have to read the code to make
- it.
- """
+ """True when streaming this tool's arguments before approval shows only text. A large code
+ payload takes a minute or more to write, and suppressing the card until the call completes
+ leaves the chat blank the whole time. Nothing runs before the decision either way."""
return name in _TEXT_PREVIEW_TOOLS
def _web_search_fetches_url(name: str, arguments: dict) -> bool:
- """web_search carrying a ``url`` fetches that exact page instead of searching.
-
- That fetch is egress to a host the *call* names, the one such case in the built-in
- set, so it asks even though plain search stays always-safe. Name-only
- ``is_always_safe_tool`` is deliberately unchanged: it runs before arguments exist
- (provisional card, stream requirement), where a query-only search must not prompt."""
+ """web_search carrying a ``url`` fetches that exact page instead of searching, which is egress
+ to a host the CALL names, so it asks even though plain search stays always-safe. Name-only
+ ``is_always_safe_tool`` is deliberately unchanged: it runs before arguments exist, where a
+ query-only search must not prompt."""
return name == "web_search" and bool(str(arguments.get("url", "") or "").strip())
@@ -4688,13 +4322,13 @@ _HIGH_RISK_COMMANDS = frozenset(
"blkdiscard",
"chattr",
"truncate",
- # Windows cmd.exe built-ins that delete files / trees (reachable when the
- # terminal executor falls back to `cmd /c`; not in _BLOCKED_COMMANDS_WIN)
+ # cmd.exe built-ins that delete files/trees, reachable when the terminal executor falls back to `cmd /c`; not
+ # in _BLOCKED_COMMANDS_WIN
"del",
"erase",
"rd",
- # Ending a process kills work in progress (a training run, the server
- # itself); a power command ends every process at once.
+ # Ending a process kills work in progress (a training run, the server itself); a power command ends every
+ # process at once.
"kill",
"pkill",
"killall",
@@ -4708,8 +4342,8 @@ _HIGH_RISK_COMMANDS = frozenset(
"setcap",
# accounts / persistence / system services
"crontab",
- # at/batch hand the payload to atd, which runs it later as this user and
- # outside this invocation's blocklist, rlimits, timeout and cancellation.
+ # at/batch hand the payload to atd, which runs it later as this user and outside this invocation's blocklist,
+ # rlimits, timeout and cancellation.
"at",
"batch",
"atrm",
@@ -4753,24 +4387,20 @@ _HIGH_RISK_COMMANDS = frozenset(
"tftp",
# POSIX unlink(1) deletes a file exactly like rm, which is gated above.
"unlink",
- # Windows / macOS storage destruction, the platform twins of the POSIX
- # mkfs/wipefs/dd family already gated above.
+ # Windows / macOS storage destruction, the platform twins of the POSIX mkfs/wipefs/dd family above.
"format",
"diskpart",
"diskutil",
- # Windows / macOS scheduled tasks, registry and service control: the twins
- # of crontab/systemctl. Gated wholesale (a read-only `reg query` prompts
- # too) because the destructive subcommand lives in the arguments.
+ # Windows / macOS scheduled tasks, registry and service control: the twins of crontab/systemctl. Gated
+ # wholesale (a read-only `reg query` prompts too) because the destructive subcommand lives in the arguments.
"systemd-run",
"schtasks",
"reg",
"sc",
"launchctl",
- # container/VM runtimes: the daemon acts with host privileges, so
- # `docker run -v /:/host ...` writes the real filesystem, escaping the
- # child's workdir and rlimit sandbox entirely. chroot/nsenter/unshare
- # cross a privilege or namespace boundary and then exec a nested command,
- # so the wrapper hides the real action.
+ # container/VM runtimes: the daemon acts with host privileges, so `docker run -v /:/host ...` writes the real
+ # filesystem, escaping the child's workdir and rlimit sandbox. chroot/nsenter/unshare cross a privilege or
+ # namespace boundary and then exec a nested command, so the wrapper hides the real action.
"chroot",
"nsenter",
"unshare",
@@ -4784,13 +4414,11 @@ _HIGH_RISK_COMMANDS = frozenset(
"kubectl",
}
)
-# sysctl's write and load forms change kernel parameters; a read-only query
-# (sysctl -a, sysctl net.ipv4.ip_forward) stays automatic.
+# sysctl's write and load forms change kernel parameters; a read-only query (sysctl -a) stays automatic.
_SYSCTL_WRITE_FLAGS = frozenset({"-w", "--write", "-p", "--load", "--system"})
-# setpriv changes privilege state and then execs its remaining arguments, so the
-# real command sits behind it. Kept out of _AUTO_SAFE_WRAPPERS (it is not safe in
-# its own right) and instead made transparent only for the high-risk scan, where
-# the flags that raise privilege are gated on their own.
+# setpriv changes privilege state and then execs its remaining arguments, so the real command sits behind it. Kept out
+# of _AUTO_SAFE_WRAPPERS (it is not safe in its own right) and made transparent only for the high-risk scan, where the
+# privilege-raising flags are gated on their own.
_PRIVILEGE_EXEC_WRAPPERS = frozenset({"setpriv"})
_SETPRIV_PRIVILEGE_FLAGS = frozenset(
{
@@ -4810,17 +4438,15 @@ _SETPRIV_PRIVILEGE_FLAGS = frozenset(
"--apparmor-profile",
}
)
-# fallocate replaces a range with a hole, zeroes it or removes it, destroying
-# file contents in place. Plain allocation (-l SIZE) only grows a file.
+# fallocate replaces a range with a hole, zeroes it or removes it, destroying file contents in place. Plain allocation
+# (-l SIZE) only grows a file.
_FALLOCATE_DESTRUCTIVE_FLAGS = frozenset(
{"-p", "--punch-hole", "-z", "--zero-range", "-c", "--collapse-range", "-d", "--dig-holes"}
)
-# High risk only with a recursive flag (chmod -R 777 .); a scoped
-# `chmod +x build.sh` stays out.
+# High risk only with a recursive flag (chmod -R 777 .); a scoped `chmod +x build.sh` stays out.
_HIGH_RISK_RECURSIVE_COMMANDS = frozenset({"chmod", "chown", "chgrp"})
-# Commands that forward command position to a following command name
-# (find . -exec rm, echo x | xargs rm, parallel rm, watch rm), so the wrapped
-# command is checked against the high-risk sets too.
+# Commands that forward command position to a following command name (find . -exec rm, xargs rm, parallel rm, watch
+# rm), so the wrapped command is checked against the high-risk sets too.
_HIGH_RISK_FORWARDING_COMMANDS = frozenset(
{
"find",
@@ -4836,31 +4462,28 @@ _HIGH_RISK_FORWARDING_COMMANDS = frozenset(
"valgrind",
}
)
-# Of those, find/fd only execute a child after an explicit -exec-style flag.
-# A tracer or profiler runs the rest of the line as a child process, so the
-# real command sits in argument position behind it.
+# Of those, find/fd only execute a child after an explicit -exec-style flag. A tracer or profiler runs the rest of the
+# line as a child, so the real command sits in argument position behind it.
_TRACER_LAUNCHERS = frozenset({"strace", "ltrace", "ktrace", "dtruss", "perf", "valgrind"})
_EXEC_FLAG_FORWARDING_COMMANDS = frozenset({"find", "fd"})
_EXEC_FORWARD_FLAGS = frozenset(
{"-exec", "-execdir", "-ok", "-okdir", "--exec", "--exec-batch", "-x", "-X"}
)
-# The long forms also accept the command attached to the flag (fd --exec=rm),
-# where the value is command position rather than a discarded option argument.
+# The long forms also accept the command attached to the flag (fd --exec=rm), where the value is command position
+# rather than a discarded option argument.
_ATTACHED_EXEC_FLAGS = frozenset({"-exec", "-execdir", "--exec", "--exec-batch"})
-# find/fd flags that delete matches outright (a bare `find . -delete`, with no
-# separate command token to catch); an `-exec rm` is caught via forwarding.
+# find/fd flags that delete matches outright (a bare `find . -delete`, with no separate command token to catch); an
+# `-exec rm` is caught via forwarding.
_HIGH_RISK_FIND_FLAGS = frozenset({"-delete"})
-# Flags whose VALUE is a command the tool then executes, so a payload (even a
-# hard-blocked one) rides inside an argument instead of at command position.
-# GNU tar --checkpoint-action=exec=CMD, rsync/scp -e REMOTE_SHELL.
+# Flags whose VALUE is a command the tool then executes, so a payload (even a hard-blocked one) rides inside an
+# argument instead of at command position: GNU tar --checkpoint-action=exec=CMD, rsync/scp -e REMOTE_SHELL.
_HIGH_RISK_ARG_EXEC_FLAGS = frozenset({"--checkpoint-action", "--rsh", "--rsync-path"})
-# ...but only for the utilities that actually run them; otherwise a mere
-# mention (printf '%s' --rsh, a grep for the flag name) would prompt.
+# ...but only for the utilities that actually run them; otherwise a mere mention (printf '%s' --rsh, a grep for the
+# flag name) would prompt.
_ARG_EXEC_FLAG_OWNERS = frozenset({"tar", "gtar", "bsdtar", "rsync", "scp", "sftp"})
-# An interpreter run as a network server (python -m http.server, uvicorn app:api)
-# listens on a socket; the sandbox has no network namespace, so the session
-# workdir becomes reachable wherever that port is exposed. Position-scoped, since
-# a bare mention (pip install uvicorn, grep uvicorn reqs.txt) starts no listener.
+# An interpreter run as a network server (python -m http.server, uvicorn app:api) listens on a socket; the sandbox has
+# no network namespace, so the session workdir becomes reachable wherever that port is exposed. Position-scoped, since
+# a bare mention (pip install uvicorn) starts no listener.
_LISTENER_PY_MODULES = (
r"http\.server|SimpleHTTPServer|uvicorn|gunicorn|waitress|flask|"
r"twisted|websockets|aiohttp\.web"
@@ -4870,9 +4493,8 @@ _LISTENER_PY_MODULE_RE = re.compile(
r"(?:python|pypy)[0-9.]*\s+(?:-\S+\s+)*-m\s+(?:" + _LISTENER_PY_MODULES + r")\b",
re.IGNORECASE,
)
-# The same modules as the command-position regex, matched after wrapper
-# resolution so `env python -m http.server` and `timeout 60 python -m ...`
-# are seen too.
+# The same modules as the command-position regex, matched after wrapper resolution so `env python -m http.server` and
+# `timeout 60 python -m ...` are seen too.
_LISTENER_PY_MODULE_NAMES = frozenset(
{
"http.server",
@@ -4891,8 +4513,8 @@ _LISTENER_BIN_AT_CMD_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*"
r"(?:uvicorn|gunicorn|waitress-serve|hypercorn|daphne)\b"
)
-# curl upload/POST flags: local data sent out (exfiltration surface). The short
-# forms may be attached (-d@f, [email protected]), so they match prefix-wise.
+# curl upload/POST flags: local data sent out (exfiltration surface). The short forms may be attached (-d@f,
+# [email protected]), so they match prefix-wise.
_CURL_UPLOAD_LONG_FLAGS = frozenset(
{
"--data",
@@ -4905,15 +4527,14 @@ _CURL_UPLOAD_LONG_FLAGS = frozenset(
}
)
_CURL_UPLOAD_SHORT_FLAGS = ("-d", "-F", "-T")
-# curl's explicit-method flags and the methods that mutate/delete a remote
-# resource (a plain GET download stays out). POST is omitted: it is the ordinary
-# upload verb and is already caught by the body/upload flags above.
-# wget spells the request method --method=DELETE.
+# curl's explicit-method flags and the methods that mutate/delete a remote resource (a plain GET download stays out).
+# POST is omitted: it is the ordinary upload verb, already caught by the body/upload flags above. wget spells it
+# --method=DELETE.
_WGET_METHOD_FLAGS = frozenset({"--method"})
_CURL_METHOD_FLAGS = frozenset({"-X", "--request"})
_CURL_DESTRUCTIVE_METHODS = frozenset({"delete", "put", "patch"})
-# wget upload/POST flags. Kept separate from curl's so a benign wget short option
-# (wget -T 10 timeout, wget -F force-html) is not misread as an upload.
+# wget upload/POST flags. Kept separate from curl's so a benign wget short option (wget -T 10, wget -F) is not misread
+# as an upload.
_WGET_UPLOAD_FLAGS = frozenset({"--post-data", "--post-file", "--body-data", "--body-file"})
# curl/wget output piped straight into an interpreter is remote code execution.
_PIPE_TO_INTERPRETER_RE = re.compile(
@@ -4923,44 +4544,40 @@ _BARE_TRUNCATING_REDIRECT_RE = re.compile(r"(?:^|[;&|\n(]|&&|\|\|)\s*(?::|true)?
_HERESTRING_TO_INTERPRETER_RE = re.compile(
r"\b(?:sh|bash|zsh|dash|ksh|fish|ash|python[0-9.]*|node|ruby|perl|php)\b[^\n]*<<<"
)
-# An interpreter that executes a process substitution's output as a script
-# (bash <(printf 'rm -rf x'), source <(...)): the generated content is never
-# literal text, so it is unscreenable and fails closed. A non-interpreter consumer
+# An interpreter that executes a process substitution's output as a script (bash <(printf 'rm -rf x'), source <(...)):
+# the generated content is never literal text, so it is unscreenable and fails closed. A non-interpreter consumer
# (diff <(sort a) <(sort b)) only reads the file and stays out.
_PROC_SUBST_EXEC_RE = re.compile(
r"\b(?:sh|bash|zsh|dash|ksh|fish|ash|source|eval|python[0-9.]*|node|nodejs|bun|ruby|perl|php)\b"
r"[^\n]*<\("
r"|(?:^|[;&|\n(]|&&|\|\|)\s*\.\s+<\("
)
-# Network clients beyond curl/wget that open a socket to a remote host: the
-# sandbox has no network namespace, so they can exfil the workdir or fetch and run
-# remote code. Command position only, so a filename argument (scp ./ssh_notes.txt)
-# is not misread as the command.
+# Network clients beyond curl/wget that open a socket to a remote host: the sandbox has no network namespace, so they
+# can exfil the workdir or fetch and run remote code. Command position only, so a filename argument (scp
+# ./ssh_notes.txt) is not misread as the command.
_NETWORK_CLIENT_AT_CMD_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*"
r"(?:nc|ncat|netcat|telnet|socat|ssh|slogin|scp|sftp)\b"
)
-# openssl's s_client/s_server open a TLS socket, the classic no-curl exfil channel
-# (tar czf - . | openssl s_client -connect host:443). Plain openssl (dgst, enc) is
-# local and stays out. Matched on the resolved command segment, so the wrapped
-# forms (env openssl s_client) are seen too.
+# openssl's s_client/s_server open a TLS socket, the classic no-curl exfil channel (tar czf - . | openssl s_client
+# -connect host:443). Plain openssl (dgst, enc) is local and stays out. Matched on the resolved command segment, so
+# wrapped forms are seen too.
_OPENSSL_NETWORK_SUBCOMMANDS = frozenset({"s_client", "s_server"})
-# `getent shadow` returns password hashes straight from NSS, so the read
-# never spells out /etc/shadow for the path check to find.
+# `getent shadow` returns password hashes straight from NSS, so the read never spells out /etc/shadow for the path
+# check to find.
_GETENT_CREDENTIAL_DATABASES = frozenset({"shadow", "gshadow"})
_OPENSSL_NETWORK_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*/)?openssl\s+s_(?:client|server)\b"
)
-# An array expansion (${x[*]}, ${x[@]}) builds a command from elements the static
-# scan cannot resolve; fed to a shell -c/eval it runs an unscreened payload.
-# Paired with the var-executed-as-command test so `echo "${a[@]}"` is left alone.
+# An array expansion (${x[*]}, ${x[@]}) builds a command from elements the static scan cannot resolve; fed to a shell
+# -c/eval it runs an unscreened payload. Paired with the var-executed-as-command test so `echo "${a[@]}"` is left
+# alone.
_ARRAY_EXPANSION_RE = re.compile(r"\$\{\w+\[[@*]\]\}")
-# A wrapper's bare duration/count argument (timeout 5 rm, timeout 1.5s rm) that
-# precedes the real command, so it is not mistaken for the command itself.
+# A wrapper's bare duration/count argument (timeout 5 rm, timeout 1.5s rm) that precedes the real command, so it is
+# not mistaken for the command itself.
_WRAPPER_DURATION_RE = re.compile(r"\d+(?:\.\d+)?[smhd]?$")
-# Non-shell interpreters running an inline program (python -c, node -e, php -r):
-# the terminal path never screens that program the way the python tool does.
-# sh/bash -c are omitted, the hard-block already recurses into their payloads.
+# Non-shell interpreters running an inline program (python -c, node -e, php -r): the terminal path never screens that
+# program the way the python tool does. sh/bash -c are omitted, the hard-block already recursing into their payloads.
_INLINE_CODE_INTERPRETERS = frozenset(
{
"python",
@@ -4978,9 +4595,9 @@ _INLINE_CODE_INTERPRETERS = frozenset(
}
)
_INLINE_CODE_FLAGS = frozenset({"-c", "-e", "-E", "-r", "--eval", "--exec"})
-# Inline-code flags are per-interpreter: a flag that evaluates code for one runtime
-# is an ordinary option for another (`python -E` ignores PYTHON* env, it is not
-# eval). Value is (exact flags, short letters that may appear in a cluster).
+# Inline-code flags are per-interpreter: a flag that evaluates code for one runtime is an ordinary option for another
+# (`python -E` ignores PYTHON* env, it is not eval). Value is (exact flags, short letters that may appear in a
+# cluster).
_INLINE_CODE_FLAG_SPEC = {
"python": (frozenset({"-c"}), "c"),
"pypy": (frozenset({"-c"}), "c"),
@@ -5006,34 +4623,31 @@ def _inline_code_flag_spec(name: str):
return _INLINE_CODE_FLAG_SPEC.get(base)
-# node/bun evaluate and print the argument to -p / --print, arbitrary code just
-# like -e/--eval. Scoped to the JS runtimes: -p is a print-loop switch for
-# perl/ruby/sed, not inline eval.
+# node/bun evaluate and print the argument to -p / --print, arbitrary code just like -e/--eval. Scoped to the JS
+# runtimes: -p is a print-loop switch for perl/ruby/sed, not inline eval.
_NODE_PRINT_INTERPRETERS = frozenset({"node", "nodejs", "bun"})
-# Runtimes that expose inline evaluation as a SUBCOMMAND (deno eval "...",
-# bun eval "..."), which the flag scan above never sees.
+# Runtimes that expose inline evaluation as a SUBCOMMAND (deno eval, bun eval), which the flag scan above never sees.
_EVAL_SUBCOMMAND_INTERPRETERS = frozenset({"deno", "bun"})
_NODE_PRINT_FLAGS = frozenset({"-p", "--print"})
-# Windows cmd.exe runs the rest of the line as a nested command after /c (or /k),
-# so the payload is screened recursively like a shell -c payload. cmd is not in
-# the hard-block set, and del/erase/rd were added to the high-risk set for it.
+# Windows cmd.exe runs the rest of the line as a nested command after /c (or /k), so the payload is screened
+# recursively like a shell -c payload. cmd is not in the hard-block set, and del/erase/rd were added to the high-risk
+# set for it.
_CMD_SHELLS = frozenset({"cmd"})
-# PowerShell runs an arbitrary inline program passed to -Command /
-# -EncodedCommand (and their unambiguous prefixes), which the terminal path cannot
-# parse. On Windows both names are hard-blocked; elsewhere pwsh is not, so gate an
+# PowerShell runs an arbitrary inline program passed to -Command / -EncodedCommand (and their unambiguous prefixes),
+# which the terminal path cannot parse. On Windows both names are hard-blocked; elsewhere pwsh is not, so gate an
# inline-command invocation there. A bare `pwsh script.ps1` file run stays out.
_POWERSHELL_INTERPRETERS = frozenset({"powershell", "pwsh"})
-# Versioned interpreter binaries (python3.11, python2.7, pypy3.10) are the same
-# inline-code risk as their unversioned names, so recognise the version suffix.
+# Versioned interpreter binaries (python3.11, pypy3.10) are the same inline-code risk as their unversioned names, so
+# recognise the version suffix.
_VERSIONED_INTERPRETER_RE = re.compile(r"^(?:python|pypy|perl|ruby|php|node)\d+(?:\.\d+)*$")
-# busybox / toybox dispatch to an applet given as the first argument, so the
-# applet, not the multicall binary, is the command whose risk is judged.
+# busybox / toybox dispatch to an applet given as the first argument, so the applet, not the multicall binary, is the
+# command whose risk is judged.
_MULTICALL_BINARIES = frozenset({"busybox", "toybox"})
-# `cd /proc/$PPID; cat environ` reads a sensitive path after the chdir even though
-# no single token spells it out, so a chdir into a sensitive dir is gated.
+# `cd /proc/$PPID; cat environ` reads a sensitive path after the chdir even though no single token spells it out, so a
+# chdir into a sensitive dir is gated.
_CHDIR_COMMANDS = frozenset({"cd", "pushd", "chdir"})
-# The absolute system dirs are anchored so an unrelated user dir (/home/x/etc)
-# does not match; the credential dotfile dirs match anywhere in the path.
+# The absolute system dirs are anchored so an unrelated user dir (/home/x/etc) does not match; the credential dotfile
+# dirs match anywhere in the path.
_SENSITIVE_CHDIR_RE = re.compile(
r"^~?/proc/[^/\s'\"]+"
r"|^~?/etc(?:/|$)"
@@ -5046,26 +4660,26 @@ _SENSITIVE_CHDIR_RE = re.compile(
def _is_inline_code_interpreter(name: str) -> bool:
- """True for an interpreter whose ``-c`` / ``-e`` runs an inline program the
- terminal path never screens, including versioned python/pypy binaries."""
+ """True for an interpreter whose ``-c`` / ``-e`` runs an inline program the terminal path never
+ screens, including versioned python/pypy binaries."""
return name in _INLINE_CODE_INTERPRETERS or bool(_VERSIONED_INTERPRETER_RE.match(name))
def _short_flag_cluster(token: str) -> "list[str]":
- """Split a combined short-option token into its individual flags
- (`-qf` -> ['-q', '-f']). A long option, a `-x=value` form or a bare `-`
- yields nothing, so only genuine clusters are expanded."""
+ """Split a combined short-option token into its individual flags (`-qf` -> ['-q', '-f']). A long
+ option, a `-x=value` form or a bare `-` yields nothing, so only genuine clusters are
+ expanded."""
if len(token) < 3 or not token.startswith("-") or token.startswith("--") or "=" in token:
return []
return ["-" + ch for ch in token[1:]]
def _short_flag_arg(token: str, letters: str) -> "str | None":
- """For a short-flag cluster (``-lc``, ``-Bc``, ``-c``), if one of ``letters``
- appears as a flag in it, return the text glued after that letter -- ``""`` when
- the value is the next token, or the attached payload for ``-c'cmd'``. ``None``
- when no such flag is present, or for long options / non-flags. Catches combined
- forms (``bash -lc 'git clean'``) an exact ``-c`` match would miss."""
+ """For a short-flag cluster (``-lc``, ``-Bc``, ``-c``), if one of ``letters`` appears as a flag
+ in it, return the text glued after that letter: ``""`` when the value is the next token, or
+ the attached payload for ``-c'cmd'``. ``None`` when no such flag is present, or for long
+ options / non-flags. Catches combined forms (``bash -lc 'git clean'``) an exact ``-c`` match
+ would miss."""
if not token.startswith("-") or token.startswith("--"):
return None
body = token[1:]
@@ -5076,16 +4690,14 @@ def _short_flag_arg(token: str, letters: str) -> "str | None":
def _shell_quote_states(command: str) -> "list[str]":
- """The quote context of every character: ``""`` outside quoting, ``"'"``
- (or ``"$'"`` for ANSI-C, which honours backslash escapes) inside single
- quoting, ``'"'`` inside double quoting, and ``_ESCAPED_CHAR_STATE`` for a
- backslash and the character it quotes. A quote mark itself reports the
- context it opens from, so a character is text bash expands exactly when its
- state is ``""`` or ``'"'``.
-
- Tracked character by character rather than paired off with a regex, because
- a regex matches the apostrophe in `echo "it's"` against the next quote,
- inverting the state for everything after it.
+ """The quote context of every character: ``""`` outside quoting, ``"'"`` (or ``"$'"`` for ANSI-C,
+ which honours backslash escapes) inside single quoting, ``'"'`` inside double quoting, and
+ ``_ESCAPED_CHAR_STATE`` for a backslash and the character it quotes. A quote mark itself reports
+ the context it opens from, so a character is text bash expands exactly when its state is ``""``
+ or ``'"'``.
+
+ Tracked character by character rather than paired off with a regex, because a regex matches the
+ apostrophe in `echo "it's"` against the next quote, inverting the state for everything after it.
"""
states: "list[str]" = []
quote = ""
@@ -5093,8 +4705,8 @@ def _shell_quote_states(command: str) -> "list[str]":
while i < n:
ch = command[i]
if quote in ("'", "$'"):
- # A plain single quote protects even backslashes; ANSI-C does not,
- # so `\'` there is a quote character rather than the end of the word.
+ # A plain single quote protects even backslashes; ANSI-C does not, so `\'` there is a quote character
+ # rather than the end of the word.
if quote == "$'" and ch == "\\" and i + 1 < n:
states += [quote, quote]
i += 2
@@ -5105,11 +4717,9 @@ def _shell_quote_states(command: str) -> "list[str]":
i += 1
continue
if ch == "\\" and i + 1 < n:
- # Reported under its OWN state rather than the surrounding one:
- # marking `\$` as ordinary double-quoted text made `$(` there look
- # like a live substitution, so an everyday `sed "s/\$(CC)/gcc/"
- # Makefile` asked for confirmation while real bash hands sed a
- # literal `$(CC)` and nothing runs (verified: it prints CC=cc).
+ # Reported under its OWN state rather than the surrounding one: marking `\$` as ordinary double-quoted
+ # text made `$(` there look like a live substitution, so an everyday `sed "s/\$(CC)/gcc/" Makefile` asked
+ # for confirmation while real bash hands sed a literal `$(CC)` and nothing runs.
states += [_ESCAPED_CHAR_STATE, _ESCAPED_CHAR_STATE]
i += 2
continue
@@ -5129,20 +4739,15 @@ def _shell_quote_states(command: str) -> "list[str]":
def _substitution_span(command: str, start: int) -> int:
"""Index just past the `)` that closes the `$(` at ``start``.
- The body of a substitution is a FRESH shell context -- bash re-parses it, so
- quoting reopens inside even when the whole thing sits in double quotes --
- and a paren the body QUOTES is text, not nesting. Counting it raised the
- depth, the real `)` then never brought the depth back to zero, and the span
- ran on past the end of the word: `sed "$(printf '(' >/dev/null; printf 'e
- rm -f victim')" input` yielded a span with ` input` glued on, which no
- longer matched the sed program it had to be found inside, so the generated
- script went unnoticed.
-
- _shell_quote_states is a left-to-right machine, so the states it reports for
- a prefix are the ones it reports for the whole string; the window is grown
- until the span closes, which keeps the cost a constant multiple of the
- substitution's own length rather than a walk to the end of the line for
- every one of them.
+ The body of a substitution is a FRESH shell context, so quoting reopens inside even when the
+ whole thing sits in double quotes, and a paren the body QUOTES is text, not nesting. Counting it
+ raised the depth, the real `)` then never brought it back to zero, and the span ran on past the
+ end of the word, so a generated script went unnoticed.
+
+ _shell_quote_states is a left-to-right machine, so the states it reports for a prefix are the
+ ones it reports for the whole string; the window is grown until the span closes, which keeps the
+ cost a constant multiple of the substitution's own length rather than a walk to the end of the
+ line.
"""
n = len(command)
width = _SUBSTITUTION_SPAN_STEP
@@ -5166,9 +4771,8 @@ def _substitution_span(command: str, start: int) -> int:
def _arithmetic_span(command: str, start: int) -> int:
- """Index just past the `))` / `]` closing the arithmetic expansion at
- ``start`` -- `$((...))`, or the deprecated `$[...]` bash 5.2 still
- evaluates (`echo $[1+2]` prints 3)."""
+ """Index just past the `))` / `]` closing the arithmetic expansion at ``start``: `$((...))`, or
+ the deprecated `$[...]` bash 5.2 still evaluates."""
opener = command[start + 1]
closer = ")" if opener == "(" else "]"
depth, i, n = 0, start + 1, len(command)
@@ -5184,8 +4788,8 @@ def _arithmetic_span(command: str, start: int) -> int:
def _brace_param_span(command: str, start: int) -> int:
- """Index just past the `}` closing the `${` at ``start``. Braces nest
- (`${a:-${b}}`) and a backslash quotes the one behind it."""
+ """Index just past the `}` closing the `${` at ``start``. Braces nest (`${a:-${b}}`) and a
+ backslash quotes the one behind it."""
depth, i, n = 0, start + 1, len(command)
while i < n:
if command[i] == "\\":
@@ -5202,16 +4806,13 @@ def _brace_param_span(command: str, start: int) -> int:
def _collapse_shell_arithmetic(program: str) -> str:
- """``program`` with each arithmetic expansion replaced by a digit
- (_ARITHMETIC_VALUE), which is a faithful stand-in because arithmetic always
- evaluates to an integer.
-
- Without it the expansion's own punctuation is read as sed source and hides
- the command behind it: `sed "$((c+1))e rm -f victim"` runs rm for real
- (`$((c+1))` is 1), while the raw text takes the `c` for an append-text
- command and swallows the payload as its operand. An expansion holding a
- COMMAND substitution is left alone, so the substitution stays visible to
- _sed_program_unresolved rather than being collapsed out of sight.
+ """``program`` with each arithmetic expansion replaced by a digit (_ARITHMETIC_VALUE), a faithful
+ stand-in because arithmetic always evaluates to an integer.
+
+ Without it the expansion's own punctuation is read as sed source and hides the command behind
+ it: `sed "$((c+1))e rm -f victim"` runs rm for real, while the raw text takes the `c` for an
+ append-text command and swallows the payload as its operand. An expansion holding a COMMAND
+ substitution is left alone, so the substitution stays visible to _sed_program_unresolved.
"""
out: "list[str]" = []
i, n = 0, len(program)
@@ -5228,20 +4829,16 @@ def _collapse_shell_arithmetic(program: str) -> str:
def _shell_expansions(command: str, quoted: bool = True) -> "list[str]":
- """Every expansion bash performs, as the exact text each one occupies:
- `$(...)`, backticks, `${...}` in ANY form and a bare `$NAME` / `$?`.
-
- With ``quoted`` (the default) the text is a whole command line, so a
- single-quoted or backslash-escaped expansion is literal and reported as
- nothing -- ``sed 's/`//g' NOTES.md`` and `sed "s/\\$(CC)/gcc/" Makefile`
- both yield an empty list. With ``quoted`` False the text is a token shlex
- has already unquoted, where every character counts; comparing the two tells
- an expansion the shell RUNS from one a sed program merely quotes.
-
- ARITHMETIC is skipped: it evaluates to an integer, so it can spell no sed
- command (_ARITHMETIC_VALUE). One holding a command substitution is stepped
- INTO instead, so the substitution inside `sed "$(( $(cat n) ))p"` is still
- reported.
+ """Every expansion bash performs, as the exact text each one occupies: `$(...)`, backticks,
+ `${...}` in ANY form and a bare `$NAME` / `$?`.
+
+ With ``quoted`` (the default) the text is a whole command line, so a single-quoted or
+ backslash-escaped expansion is literal and reported as nothing. With ``quoted`` False the text
+ is a token shlex has already unquoted, where every character counts; comparing the two tells an
+ expansion the shell RUNS from one a sed program merely quotes.
+
+ ARITHMETIC is skipped: it evaluates to an integer, so it can spell no sed command. One holding a
+ command substitution is stepped INTO instead.
"""
found: "list[str]" = []
states = _shell_quote_states(command) if quoted else None
@@ -5258,9 +4855,8 @@ def _shell_expansions(command: str, quoted: bool = True) -> "list[str]":
continue
if command.startswith("$((", i) or command.startswith("$[", i):
end = _arithmetic_span(command, i)
- # Stepping over the `$` alone would report the arithmetic's own
- # `(name)` as a substitution; stepping over the whole span would
- # hide a `$(...)` nested inside it. Do each where it applies.
+ # Stepping over the `$` alone would report the arithmetic's own `(name)` as a substitution; stepping over
+ # the whole span would hide a `$(...)` nested inside it. Do each where it applies.
i = i + 2 if _HAS_COMMAND_SUBST_RE.search(command[i:end]) else end
continue
if command.startswith("$(", i):
@@ -5283,12 +4879,10 @@ def _shell_expansions(command: str, quoted: bool = True) -> "list[str]":
def _separate_unquoted_newlines(text: str) -> str:
- """``text`` with each UNQUOTED newline replaced by `;`, which shlex reads as
- a command boundary. A newline inside quotes is DATA -- a sed comment ends at
- one -- so it survives, unlike a blanket replacement. A BACKSLASH-escaped
- newline is a line continuation bash deletes rather than a separator, so it
- survives too; the blanket pass still supplies that boundary if one is
- wanted, since it replaces every newline unconditionally."""
+ """``text`` with each UNQUOTED newline replaced by `;`, which shlex reads as a command boundary.
+ A newline inside quotes is DATA (a sed comment ends at one) so it survives, as does a
+ BACKSLASH-escaped newline, which bash deletes as a line continuation rather than a separator;
+ the blanket pass still supplies that boundary if one is wanted."""
states = _shell_quote_states(text)
out = []
for i, ch in enumerate(text):
@@ -5301,75 +4895,65 @@ def _separate_unquoted_newlines(text: str) -> str:
return "".join(out)
-# git subcommands that discard or overwrite work: `clean` deletes untracked files,
-# `restore` overwrites the worktree from the index/HEAD, `rm` deletes tracked
-# files, and the plumbing entries delete refs/reflogs/objects or rewrite history.
-# `reset`/`push`/`checkout` only qualify with a destructive flag or pathspec, so
-# `git reset --soft`, a plain `git push` and ordinary git (add/commit/log) run.
+# git subcommands that discard or overwrite work: `clean` deletes untracked files, `restore` overwrites the worktree
+# from the index/HEAD, `rm` deletes tracked files, and the plumbing entries delete refs/reflogs/objects or rewrite
+# history. `reset`/`push`/`checkout` only qualify with a destructive flag or pathspec.
_HIGH_RISK_GIT_SUBCOMMANDS = frozenset(
{"clean", "restore", "rm", "update-ref", "filter-branch", "prune", "gc", "reflog"}
)
_HIGH_RISK_GIT_RESET_FLAGS = frozenset({"--hard"})
_HIGH_RISK_GIT_PUSH_FLAGS = frozenset(
- # --delete/-d removes a remote ref; --mirror and --prune delete remote refs
- # that are absent locally. All are remote data loss, like a force push.
+ # --delete/-d removes a remote ref; --mirror and --prune delete remote refs that are absent locally. All are
+ # remote data loss, like a force push.
{"-f", "--force", "--force-with-lease", "-d", "--delete", "--mirror", "--prune"}
)
-# `git worktree remove --force` deletes a linked worktree even when it holds
-# uncommitted work or is locked. An unforced remove refuses on a dirty worktree,
-# so it stays out.
+# `git worktree remove --force` deletes a linked worktree even when it holds uncommitted work or is locked. An
+# unforced remove refuses on a dirty worktree.
_HIGH_RISK_GIT_WORKTREE_FLAGS = frozenset({"-f", "--force"})
# `git switch -f/--discard-changes` throws away tracked working-tree edits.
_HIGH_RISK_GIT_SWITCH_FLAGS = frozenset({"-C", "-f", "--force", "--discard-changes"})
-# `git branch -D` force-deletes a branch, discarding unmerged commits; -M
-# force-renames over an existing branch. Plain -d/--delete refuses to drop
-# unmerged work, so it stays out.
+# `git branch -D` force-deletes a branch, discarding unmerged commits; -M force-renames over an existing branch. Plain
+# -d/--delete refuses to drop unmerged work.
_HIGH_RISK_GIT_BRANCH_FLAGS = frozenset({"-D", "-M", "-f", "--force"})
# `git stash clear` / `drop` destroy stashed work with no reflog to recover it.
_HIGH_RISK_GIT_STASH_ACTIONS = frozenset({"clear", "drop"})
-# `git checkout -- <path>` / `git checkout .` / `git checkout -f` discard tracked
-# working-tree changes; a bare `git checkout <branch>` (switching) does not.
+# `git checkout -- <path>` / `git checkout .` / `git checkout -f` discard tracked working-tree changes; a bare `git
+# checkout <branch>` does not.
_HIGH_RISK_GIT_CHECKOUT_FLAGS = frozenset({"-f", "--force", "-B"})
# `git checkout-index -f` overwrites working-tree files from the index.
_HIGH_RISK_GIT_CHECKOUT_INDEX_FLAGS = frozenset({"-f", "--force"})
# `git tag -d` deletes a ref; `git tag -f` replaces one that already exists.
_HIGH_RISK_GIT_TAG_FLAGS = frozenset({"-d", "--delete", "-f", "--force"})
-# `git -c alias.NAME=PAYLOAD` defines an alias git then runs; a leading `!` makes
-# the payload a shell command.
+# `git -c alias.NAME=PAYLOAD` defines an alias git then runs; a leading `!` makes the payload a shell command.
_GIT_ALIAS_ASSIGN_RE = re.compile(r"^alias\.[^=]+=(.*)$", re.DOTALL)
-# `git --config-env=alias.n=VAR n` names an environment variable whose value
-# becomes the alias body, so the code is never present in the command text.
+# `git --config-env=alias.n=VAR n` names an environment variable whose value becomes the alias body, so the code is
+# never present in the command text.
_GIT_CONFIG_ENV_ALIAS_RE = re.compile(r"(?:^|=)alias\.", re.IGNORECASE)
-# git global options taking a separate value token (git -C repo clean); the value
-# must be consumed so it is not mistaken for the subcommand.
+# git global options taking a separate value token (git -C repo clean); the value must be consumed so it is not
+# mistaken for the subcommand.
_GIT_GLOBAL_VALUE_FLAGS = frozenset(
{"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"}
)
-# Shells whose `-c PAYLOAD` runs an inline program: the payload is recursively
-# screened, so a high-risk command wrapped in `bash -c '...'` is still caught. The
-# hard-block only recurses for its own smaller command set.
+# Shells whose `-c PAYLOAD` runs an inline program: the payload is recursively screened, so a high-risk command
+# wrapped in `bash -c '...'` is still caught. The hard-block only recurses for its own smaller command set.
_SHELL_C_INTERPRETERS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "fish", "ash"})
-# A command synthesized by a command substitution at command position
-# ($(printf rm) -rf build) cannot be read statically. A substitution in argument
-# position (echo $(date), make $(FILES)) is left alone.
+# A command synthesized by a command substitution at command position ($(printf rm) -rf build) cannot be read
+# statically. A substitution in argument position (echo $(date)) is left alone.
_COMMAND_SUBST_AT_CMD_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=[^\s;&|()]*\s+)*(?:\$\(|`)"
)
-# A command substitution appearing anywhere ($(...) that is not arithmetic
-# $((...)), or a backtick). Used to catch a substitution stashed in a variable
-# (x=`...`) that a later dynamic exec runs, which never surfaces as literal text.
+# A command substitution appearing anywhere ($(...) that is not arithmetic, or a backtick). Used to catch a
+# substitution stashed in a variable (x=`...`) that a later dynamic exec runs, which never surfaces as literal text.
_HAS_COMMAND_SUBST_RE = re.compile(r"\$\((?!\()|`")
-# The same as below, but only when the expansion is the WHOLE command word. A
-# variable used as a path prefix (${VENV}/bin/python) still leaves a literal
-# basename the scan can screen, so it is not unresolvable.
+# The same as below, but only when the expansion is the WHOLE command word. A variable used as a path prefix
+# (${VENV}/bin/python) still leaves a literal basename the scan can screen, so it is not unresolvable.
_BARE_VAR_AS_COMMAND_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*\$\{?\w+\}?(?=\s|$)"
)
-# A variable expansion executed as a command: $VAR at command position, or a shell
-# `-c` / eval whose payload contains a `$` expansion. Paired with
-# _HAS_COMMAND_SUBST_RE this flags `x=`printf 'git clean -fd'`; bash -c "$x"`,
-# assembled at runtime and so unscreenable statically.
+# A variable expansion executed as a command: $VAR at command position, or a shell `-c` / eval whose payload contains
+# a `$` expansion. Paired with _HAS_COMMAND_SUBST_RE this flags a command assembled at runtime and so unscreenable
+# statically.
_VAR_EXECUTED_AS_COMMAND_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*\$\{?\w"
r"|\b(?:sh|bash|zsh|dash|ksh|ash)\b[^\n]*?\s-c\b[^\n]*\$"
@@ -5380,8 +4964,8 @@ _VAR_EXECUTED_AS_COMMAND_RE = re.compile(
_SHELL_SEGMENT_SPLIT_RE = re.compile(r"^(?:;|&&|\|\||\||&)$")
-# Wrappers that may sit in front of a network client without changing what it
-# does, so the client is still at command position behind them.
+# Wrappers that may sit in front of a network client without changing what it does, so the client is still at command
+# position behind them.
_CLIENT_WRAPPERS = frozenset(
{"env", "command", "timeout", "nohup", "nice", "ionice", "stdbuf", "setsid", "exec"}
)
@@ -5389,9 +4973,8 @@ _CLIENT_WRAPPER_PREFIX = (
r"(?:(?:env|command|timeout|nohup|nice|ionice|stdbuf|setsid|exec)\s+"
r"(?:-\S+\s+|\d+(?:\.\d+)?[smhd]?\s+)*)*"
)
-# The terminal sandbox shares the backend's installed environment, so removing
-# a package (pip uninstall torch) breaks the running process. Installing does
-# not, and is ordinary work, so only the removal verbs are gated.
+# The terminal sandbox shares the backend's installed environment, so removing a package (pip uninstall torch) breaks
+# the running process. Installing does not, so only the removal verbs are gated.
_PKG_REMOVE_AT_CMD_RE = re.compile(
r"(?:^|[;&|\n(]|&&|\|\|)\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*/)?"
r"(?:(?:python[0-9.]*\s+-m\s+)?pip[0-9]*|uv\s+pip|pipx|conda|mamba|micromamba)"
@@ -5413,9 +4996,8 @@ _WGET_AT_CMD_RE = re.compile(
def _tokens_for_client_segment(tokens: list, has_curl: bool, has_wget: bool):
- """Tokens of the segments whose command is curl/wget, or None if there is no
- such segment. Keeps an unrelated command's option letters out of the upload
- scan (`ls -T && echo curl`)."""
+ """Tokens of the segments whose command is curl/wget, or None if there is no such segment. Keeps
+ an unrelated command's option letters out of the upload scan (`ls -T && echo curl`)."""
segments: list = []
current: list = []
for t in tokens:
@@ -5450,16 +5032,15 @@ def _tokens_for_client_segment(tokens: list, has_curl: bool, has_wget: bool):
def _command_is_network_exec_or_exfil(command: str) -> bool:
- """curl/wget used to run remote code (piped into a shell, or via process
- substitution) or to upload local data. Plain downloads (curl -O, wget URL)
- are ordinary and stay out. Fails closed on an unparseable command."""
+ """curl/wget used to run remote code (piped into a shell, or via process substitution) or to
+ upload local data. Plain downloads stay out. Fails closed on an unparseable command."""
low = command.lower()
- # A non-curl/wget client (nc/ssh/socat) or openssl's TLS socket is a remote
- # reach in its own right, so gate it before the upload-flag logic below.
+ # A non-curl/wget client (nc/ssh/socat) or openssl's TLS socket is a remote reach in its own right, so gate it
+ # before the upload-flag logic below.
if _NETWORK_CLIENT_AT_CMD_RE.search(command) or _OPENSSL_NETWORK_RE.search(low):
return True
- # A mention in argument position (`grep curl notes.txt`) is not an invocation,
- # and treating it as one lends another command's option letters to the scan.
+ # A mention in argument position (`grep curl notes.txt`) is not an invocation, and treating it as one lends
+ # another command's option letters to the scan.
has_curl = bool(_CURL_AT_CMD_RE.search(command))
has_wget = bool(_WGET_AT_CMD_RE.search(command))
if not has_curl and not has_wget:
@@ -5472,17 +5053,16 @@ def _command_is_network_exec_or_exfil(command: str) -> bool:
tokens = shlex.split(command.replace("\n", " "), posix = True)
except ValueError:
return True
- # Scope the flag scan to the segment that actually runs curl/wget: a shared
- # option letter from an unrelated command (`ls -T && echo curl`) is not an
- # upload flag.
+ # Scope the flag scan to the segment that actually runs curl/wget: a shared option letter from an unrelated
+ # command is not an upload flag.
tokens = _tokens_for_client_segment(tokens, has_curl, has_wget)
if tokens is None:
return False
method_pending = False
for t in tokens:
name = t.split("=", 1)[0]
- # curl -X DELETE / --request PUT mutates a remote resource, not a plain
- # download. Separated, attached (-XDELETE) and --request=DELETE forms.
+ # curl -X DELETE / --request PUT mutates a remote resource, not a plain download. Separated, attached
+ # (-XDELETE) and --request=DELETE forms.
if has_curl:
if method_pending:
method_pending = False
@@ -5522,8 +5102,8 @@ _GIT_CLEAN_DRY_RUN_FLAGS = frozenset({"-n", "--dry-run"})
def _container_subcommand_is_read_only(tokens: list, start: int) -> bool:
- """Whether a container CLI's first positional is a read subcommand. A bare
- `docker` or `docker --version` prints help and runs nothing."""
+ """Whether a container CLI's first positional is a read subcommand. A bare `docker` or `docker
+ --version` prints help and runs nothing."""
for t in tokens[start + 1 :]:
if t in _SHELL_SEPARATORS or not set(t) - set(";&|()"):
break
@@ -5534,9 +5114,9 @@ def _container_subcommand_is_read_only(tokens: list, start: int) -> bool:
def _segment_has_command_after(tokens: list, start: int) -> bool:
- """Whether a command word follows an assignment in the same segment. A bare
- `export PATH=...` or `FOO=bar` runs nothing: every terminal call gets its own
- shell process, so an assignment with no command dies with it."""
+ """Whether a command word follows an assignment in the same segment. A bare `export PATH=...` or
+ `FOO=bar` runs nothing: every terminal call gets its own shell process, so an assignment with
+ no command dies with it."""
for t in tokens[start + 1 :]:
if t in _SHELL_SEPARATORS or not set(t) - set(";&|()"):
return False
@@ -5552,8 +5132,8 @@ def _segment_has_flag(
exact: frozenset,
letters: str = "",
) -> bool:
- """Whether a flag appears in the same command segment as ``start``, so a
- later command's options are not read as this command's."""
+ """Whether a flag appears in the same command segment as ``start``, so a later command's options
+ are not read as this command's."""
for t in tokens[start + 1 :]:
if t in _SHELL_SEPARATORS or not set(t) - set(";&|()"):
break
@@ -5566,9 +5146,9 @@ def _segment_has_flag(
def _segment_is_recursive(tokens: list, start: int) -> bool:
- """Whether a recursive flag (-R / --recursive / an -rf style cluster) belongs
- to the command starting at ``start``: scan only up to the next separator, so
- `grep -R x . && chmod +x f` does not make the chmod look recursive."""
+ """Whether a recursive flag (-R / --recursive / an -rf style cluster) belongs to the command
+ starting at ``start``: scan only up to the next separator, so `grep -R x . && chmod +x f`
+ does not make the chmod look recursive."""
for t in tokens[start + 1 :]:
if t in _SHELL_SEPARATORS or not set(t) - set(";&|()"):
break
@@ -5580,10 +5160,9 @@ def _segment_is_recursive(tokens: list, start: int) -> bool:
def _inline_python_is_high_risk(code: str) -> bool:
- """Screen a `python -c` payload with the same analyzer the python tool uses,
- so an ordinary one-liner runs and a destructive one still asks. Source that
- does not parse fails closed: shell quoting may have mangled it, leaving
- nothing to screen."""
+ """Screen a `python -c` payload with the same analyzer the python tool uses, so an ordinary
+ one-liner runs and a destructive one still asks. Source that does not parse fails closed:
+ shell quoting may have mangled it, leaving nothing to screen."""
try:
ast.parse(code)
except SyntaxError:
@@ -5592,31 +5171,27 @@ def _inline_python_is_high_risk(code: str) -> bool:
def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
- """High-risk terminal command for auto mode: credential/secret access,
- privilege escalation, destructive/persistence changes, or network
- exec/exfil. Ordinary dev commands run without a prompt. Fails closed
- (prompts) on an unparseable command. ``_depth`` bounds the recursion into
- shell ``-c`` payloads."""
+ """High-risk terminal command for auto mode: credential/secret access, privilege escalation,
+ destructive/persistence changes, or network exec/exfil. Ordinary dev commands run without a
+ prompt. Fails closed (prompts) on an unparseable command. ``_depth`` bounds the recursion
+ into shell ``-c`` payloads."""
if len(command) > _MAX_TERMINAL_SCAN_CHARS:
- # Far longer than any ordinary command, and screening it is superlinear,
- # so it asks instead.
+ # Far longer than any ordinary command, and screening it is superlinear, so it asks instead.
return True
if not command or not command.strip():
return False
# A credential/secret path read or write, or a sandbox escape (../), asks.
if _command_references_sensitive(command):
return True
- # A bare redirection with no command (`> notes.txt`, `: > notes.txt`) truncates
- # the file to zero bytes, the same loss as the gated `truncate -s 0`. A
- # redirect after a real command (`python train.py > out.log`) stays out.
+ # A bare redirection with no command (`> notes.txt`, `: > notes.txt`) truncates the file to zero bytes, the same
+ # loss as the gated `truncate -s 0`. A redirect after a real command stays out.
if _BARE_TRUNCATING_REDIRECT_RE.search(command):
return True
- # A process substitution an interpreter executes runs a script the static scan
- # cannot read, so fail closed.
+ # A process substitution an interpreter executes runs a script the static scan cannot read, so fail closed.
if _PROC_SUBST_EXEC_RE.search(command):
return True
- # A script piped into a shell (printf '...' | bash) or fed as a herestring
- # (bash <<< '...') is executed without ever appearing at command position.
+ # A script piped into a shell (printf '...' | bash) or fed as a herestring (bash <<< '...') is executed without
+ # ever appearing at command position.
if _PKG_REMOVE_AT_CMD_RE.search(command):
return True
if _PIPE_TO_INTERPRETER_RE.search(command.lower()):
@@ -5624,18 +5199,17 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
_herestring = _HERESTRING_TO_INTERPRETER_RE.search(command)
if _herestring:
return True
- # Newlines separate commands in a shell but read as whitespace to shlex, and
- # ANSI-C quoting ($'rm') hides the real command name.
+ # Newlines separate commands in a shell but read as whitespace to shlex, and ANSI-C quoting ($'rm') hides the real
+ # command name.
decoded = _decode_ansi_c(command, keep_one_word = True)
normalized = decoded.replace("\r\n", ";").replace("\n", ";").replace("\r", ";")
- # Identical to the blanket form unless a newline is actually present, so the
- # usual single-line command never pays for the quote walk.
+ # Identical to the blanket form unless a newline is actually present, so the usual single-line command never pays
+ # for the quote walk.
quoted_newlines_kept = (
_separate_unquoted_newlines(decoded) if "\n" in decoded or "\r" in decoded else normalized
)
- # Matched against a sed program below to tell an expansion the shell RUNS
- # from one the program merely quotes. Held in both newline forms so the
- # match works whichever pass produced the tokens.
+ # Matched against a sed program below to tell an expansion the shell RUNS from one the program merely quotes. Held
+ # in both newline forms so the match works whichever pass produced the tokens.
live_expansions: "set[str]" = set()
if "$" in command or "`" in command:
live_expansions = {
@@ -5646,37 +5220,32 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
expansion.replace("\r\n", ";").replace("\n", ";").replace("\r", ";"),
)
}
- # A verb hidden behind an assignment (c=rm; $c x) or a default parameter
- # (${c:-rm}) is expanded so the resolved token is scanned too.
+ # A verb hidden behind an assignment (c=rm; $c x) or a default parameter (${c:-rm}) is expanded so the resolved
+ # token is scanned too.
expanded = _expand_shell_assignments(_expand_param_defaults(normalized))
- # Run the network exfil check over the expanded form too, so a curl/wget
- # name assembled from variables (c=cu d=rl; $c$d -F ...) is still seen.
+ # Run the network exfil check over the expanded form too, so a curl/wget name assembled from variables (c=cu d=rl;
+ # $c$d -F ...) is still seen.
if _command_is_network_exec_or_exfil(command) or _command_is_network_exec_or_exfil(expanded):
return True
# A command substitution at command position generates the command Bash runs.
if _COMMAND_SUBST_AT_CMD_RE.search(command):
return True
- # A variable executed at command position hides the name that actually runs. A
- # plain assignment is resolved by the expansion above, so reaching here means
- # the binding came from somewhere this scan cannot follow (a command
+ # A variable executed at command position hides the name that actually runs. A plain assignment is resolved by the
+ # expansion above, so reaching here means the binding came from somewhere this scan cannot follow (a command
# substitution, or `printf -v c rm`). No name left to screen: fail closed.
if _HAS_COMMAND_SUBST_RE.search(command) and _VAR_EXECUTED_AS_COMMAND_RE.search(command):
return True
if _BARE_VAR_AS_COMMAND_RE.search(expanded):
return True
- # An array run as a command (x=(git clean -fd); bash -c "${x[*]}") carries no
- # command substitution, and assignment expansion does not resolve arrays, so
- # the check above misses it. A benign array print is untouched.
+ # An array run as a command (x=(git clean -fd); bash -c "${x[*]}") carries no command substitution, and assignment
+ # expansion does not resolve arrays, so the check above misses it. A benign array print is untouched.
if _ARRAY_EXPANSION_RE.search(command) and _VAR_EXECUTED_AS_COMMAND_RE.search(command):
return True
- # A newline inside a QUOTED argument is data, not a separator, and turning
- # it into `;` rewrites that data: a sed comment ends at a real newline, so
- # `sed '# note<newline>e CMD'` reads as one long comment once the newline is
- # gone. So a pass that only separates the UNQUOTED ones is scanned too. It
- # keeps every command boundary the blanket form has, so the token stream is
- # the same and only quoted content differs: the pass adds detections without
- # merging two commands into one segment. The set collapses to a single scan
- # for the usual single-line command.
+ # A newline inside a QUOTED argument is data, not a separator, and turning it into `;` rewrites that data: a sed
+ # comment ends at a real newline, so `sed '# note<newline>e CMD'` reads as one long comment once the newline is
+ # gone. So a pass that only separates the UNQUOTED ones is scanned too; it keeps every command boundary the
+ # blanket form has, so it adds detections without merging two commands into one segment. The set collapses to a
+ # single scan for the usual single-line command.
for text in {normalized, expanded, quoted_newlines_kept}:
try:
lexer = shlex.shlex(text, posix = True, punctuation_chars = ";&|()")
@@ -5692,19 +5261,18 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
find_like = any(
os.path.basename(t.strip(";&|()`{}")).lower() in ("find", "fd") for t in tokens
)
- # Shared out over the sed words present, so a lone sed reads its whole
- # argument list and a line packed with them stays linear (_sed_scan_limit).
+ # Shared out over the sed words present, so a lone sed reads its whole argument list and a line packed with
+ # them stays linear (_sed_scan_limit).
sed_scan_limit = _sed_scan_limit(
sum(1 for t in tokens if os.path.basename(t.strip(";&|()`{}")).lower() in _SED_COMMANDS)
)
- # Built at most once per pass, and only when a sed program actually
- # names a variable, so a line packed with sed words stays linear.
+ # Built at most once per pass, and only when a sed program actually names a variable, so a line packed with
+ # sed words stays linear.
sed_vars: "dict[str, str] | None" = None
sed_bindings: "list[tuple[int, str, str | None]] | None" = None
sed_cursor = 0
- # Where a sed invocation really ends. Built at most once per pass, and
- # only once a sed is actually reached, so a line without one never pays
- # for the quote walk it needs (_quoted_separator_indexes).
+ # Where a sed invocation really ends. Built at most once per pass, and only once a sed is actually reached, so
+ # a line without one never pays for the quote walk it needs (_quoted_separator_indexes).
sed_stops: "frozenset[int] | None" = None
sed_skips: "frozenset[int]" = frozenset()
sed_quoted: "frozenset[int]" = frozenset()
@@ -5712,14 +5280,13 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
sed_expandable: "frozenset[int]" = frozenset()
if find_like and any(t.split("=", 1)[0] in _HIGH_RISK_FIND_FLAGS for t in tokens):
return True
- # GNU tar runs --checkpoint-action=exec=CMD at each checkpoint, hiding a
- # command (including hard-blocked ones) inside an argument.
+ # GNU tar runs --checkpoint-action=exec=CMD at each checkpoint, hiding a command (including hard-blocked ones)
+ # inside an argument.
if any(
os.path.basename(t.strip(";&|()`{}")).lower() in _ARG_EXEC_FLAG_OWNERS for t in tokens
) and any(t.split("=", 1)[0] in _HIGH_RISK_ARG_EXEC_FLAGS for t in tokens):
return True
- # An interpreter serving on the network exposes the session workdir; the
- # sandbox keeps no network namespace.
+ # An interpreter serving on the network exposes the session workdir; the sandbox keeps no network namespace.
if _LISTENER_PY_MODULE_RE.search(text) or _LISTENER_BIN_AT_CMD_RE.search(text):
return True
expect_command = True # at the start of a command (after a separator)
@@ -5750,8 +5317,7 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
expect_command = True
prefix_pending = False
xargs_index = -1
- # A dangling wrapper option (env -u ; rm ...) must not consume
- # the next segment's command word.
+ # A dangling wrapper option (env -u ; rm ...) must not consume the next segment's command word.
wrapper_value_pending = False
scan_forward = False
current_command = ""
@@ -5776,29 +5342,28 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
return True
continue
if expect_command and token.lower() in _WIN_CONDITIONAL_KEYWORDS:
- # `if exist FILE del FILE`: the operand sits where the command
- # word would be, so the real command is still ahead.
+ # `if exist FILE del FILE`: the operand sits where the command word would be, so the real command is
+ # still ahead.
win_operand_pending = token.lower() != "not"
continue
if win_operand_pending:
win_operand_pending = False
continue
if expect_command and _REDIR_PREFIX_RE.match(token):
- # Bash accepts a redirection before the command word
- # (`</dev/null rm -rf build`); the command is still to come.
+ # Bash accepts a redirection before the command word (`</dev/null rm -rf build`); the command is still
+ # to come.
continue
if exec_flag_pending and token == "--":
- # fd tells a user whose PATTERN starts with a dash to write
- # `fd -- '-foo'`, so nothing behind the marker is an option and
- # `fd -- -x rm` merely lists a file called `-x`.
+ # fd tells a user whose PATTERN starts with a dash to write `fd -- '-foo'`, so nothing behind the
+ # marker is an option and `fd -- -x rm` merely lists a file called `-x`.
exec_flag_pending = False
continue
if token.startswith("-"):
flag = token.split("=", 1)[0]
# find/fd: the command after -exec/-ok is the one that runs.
if exec_flag_pending and flag in _EXEC_FORWARD_FLAGS:
- # `fd . --exec=rm` attaches the command to the flag, so the
- # value is the command that runs, not an option argument.
+ # `fd . --exec=rm` attaches the command to the flag, so the value is the command that runs, not an
+ # option argument.
if "=" in token and flag in _ATTACHED_EXEC_FLAGS:
attached = token.split("=", 1)[1].strip("\"'")
if attached and (
@@ -5809,9 +5374,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
expect_command = True
continue
if exec_flag_pending and token[:2] in {"-x", "-X"} and len(token) > 2:
- # fd takes the command attached to the SHORT option too, and
- # only the exact spellings were read as one: `fd '^victim$'
- # . -xrm` deletes the match for real (fdfind 9.0.0).
+ # fd takes the command attached to the SHORT option too, and only the exact spellings were read as
+ # one: `fd '^victim$' . -xrm` deletes the match for real (fdfind 9.0.0).
attached = token[2:].strip("\"'")
if attached and (_depth >= 3 or _terminal_is_high_risk(attached, _depth + 1)):
return True
@@ -5819,11 +5383,11 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
expect_command = True
continue
if current_command == "setpriv" and flag in _SETPRIV_PRIVILEGE_FLAGS:
- # Ahead of the wrapper-value skip below, which would otherwise
- # swallow `--reuid 0` before it is judged.
+ # Ahead of the wrapper-value skip below, which would otherwise swallow `--reuid 0` before it is
+ # judged.
return True
- # A wrapper option taking a SEPARATE value (env -u NAME): the next
- # token is that value, not the wrapped command.
+ # A wrapper option taking a SEPARATE value (env -u NAME): the next token is that value, not the
+ # wrapped command.
if (
prefix_pending
and "=" not in token
@@ -5831,9 +5395,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
):
wrapper_value_pending = True
continue
- # An interpreter running inline code (python -c, node -e) executes
- # a program the terminal path never screens. Matches the long
- # --eval/--exec forms and any short cluster carrying -c.
+ # An interpreter running inline code (python -c, node -e) executes a program the terminal path never
+ # screens. Matches the long --eval/--exec forms and any short cluster carrying -c.
_inline_spec = (
_inline_code_flag_spec(current_command)
if _is_inline_code_interpreter(current_command)
@@ -5846,13 +5409,11 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
if _inline_spec is not None and (
flag in _inline_spec[0] or _short_flag_arg(token, _inline_spec[1]) is not None
):
- # Python payloads go through the python tool's analyzer, so an
- # ordinary one-liner runs and a destructive one asks. The other
- # runtimes have no analyzer here, so they stay gated.
+ # Python payloads go through the python tool's analyzer, so an ordinary one-liner runs and a
+ # destructive one asks. The other runtimes have no analyzer here, so they stay gated.
if _current_is_python_family:
- # A bare `-c` yields an EMPTY attached value, not None,
- # so the payload is the next token; only a non-empty
- # value is the attached form (python -c'print(1)').
+ # A bare `-c` yields an EMPTY attached value, not None, so the payload is the next token; only
+ # a non-empty value is the attached form (python -c'print(1)').
_attached = _short_flag_arg(token, _inline_spec[1])
if _attached:
if _depth >= 3 or _inline_python_is_high_risk(_attached):
@@ -5861,26 +5422,25 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
inline_python_pending = True
continue
return True
- # node/bun -p / --print evaluate and print arbitrary source, the
- # same inline-code risk as -e/--eval (attached node -p'...' too).
+ # node/bun -p / --print evaluate and print arbitrary source, the same inline-code risk as -e/--eval
+ # (attached node -p'...' too).
if current_command in _NODE_PRINT_INTERPRETERS and (
flag in _NODE_PRINT_FLAGS or _short_flag_arg(token, "p") is not None
):
return True
- # PowerShell -Command / -EncodedCommand run an inline program the
- # terminal path cannot screen; a bare `pwsh script.ps1` still runs.
+ # PowerShell -Command / -EncodedCommand run an inline program the terminal path cannot screen; a bare
+ # `pwsh script.ps1` still runs.
if current_command in _POWERSHELL_INTERPRETERS and flag.lower().startswith(
("-c", "-e")
):
return True
- # A shell `-c PAYLOAD` runs its quoted payload; screen it
- # recursively. Combined clusters (bash -lc) carry -c too.
+ # A shell `-c PAYLOAD` runs its quoted payload; screen it recursively. Combined clusters (bash -lc)
+ # carry -c too.
if current_command in _SHELL_C_INTERPRETERS:
payload = _short_flag_arg(token, "c")
if payload is not None:
- # A short run of plain letters after `c` (bash -ce) is more
- # bash OPTIONS, not an attached payload: the command string
- # still comes from the next token.
+ # A short run of plain letters after `c` (bash -ce) is more bash OPTIONS, not an attached
+ # payload: the command string still comes from the next token.
if payload and payload.isalpha() and len(payload) <= 4:
shell_c_pending = True
elif payload:
@@ -5890,8 +5450,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
return True
else:
shell_c_pending = True
- # env -S 'cmd' runs the string as a new command, so screen it;
- # env -C chdirs (enabling a relative sensitive read), so it asks.
+ # env -S 'cmd' runs the string as a new command, so screen it; env -C chdirs (enabling a relative
+ # sensitive read), so it asks.
if current_command == "env":
if flag in ("-C", "--chdir"):
return True
@@ -5923,8 +5483,7 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
):
return True
if current_command == "git":
- # reset --hard discards the working tree; push --force
- # overwrites a remote ref.
+ # reset --hard discards the working tree; push --force overwrites a remote ref.
if git_subcommand == "reset" and flag in _HIGH_RISK_GIT_RESET_FLAGS:
return True
if git_subcommand == "push" and (
@@ -5932,8 +5491,7 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
or any(f in _HIGH_RISK_GIT_PUSH_FLAGS for f in _short_flag_cluster(token))
):
return True
- # git checkout -f / --force, or an explicit `--` path
- # separator (git checkout -- file), discards tracked edits.
+ # git checkout -f / --force, or an explicit `--` path separator, discards tracked edits.
if git_subcommand == "checkout" and (
flag in _HIGH_RISK_GIT_CHECKOUT_FLAGS
or any(
@@ -5967,26 +5525,24 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
or any(f in _HIGH_RISK_GIT_BRANCH_FLAGS for f in _short_flag_cluster(token))
):
return True
- # --config-env=<key>=<envvar> reads the value from the
- # environment, unresolvable here, so an alias key would store
- # unscreened code git runs on the next call.
+ # --config-env=<key>=<envvar> reads the value from the environment, unresolvable here, so an alias
+ # key would store unscreened code git runs on the next call.
if flag == "--config-env" and _GIT_CONFIG_ENV_ALIAS_RE.search(token):
return True
- # A git global option with a separate value (git -C repo clean)
- # precedes its value, not the subcommand.
+ # A git global option with a separate value (git -C repo clean) precedes its value, not the
+ # subcommand.
if not git_subcommand and "=" not in token and flag in _GIT_GLOBAL_VALUE_FLAGS:
git_glob_pending = True
continue
if _ASSIGNMENT_RE.match(token):
_assign_name, _, _assign_value = token.partition("=")
- # `alias zap='rm -rf'` stores a command bash runs when the alias
- # is invoked, the same shape as a git alias body.
+ # `alias zap='rm -rf'` stores a command bash runs when the alias is invoked, the same shape as a git
+ # alias body.
if current_command == "alias" and _assign_value:
if _depth >= 3 or _terminal_is_high_risk(_assign_value, _depth + 1):
return True
- # PATH/LD_PRELOAD-style assignments hijack command lookup, but only
- # for the command they prefix: a bare `export PATH=...` runs
- # nothing, and the shell it was set in exits immediately.
+ # PATH/LD_PRELOAD-style assignments hijack command lookup, but only for the command they prefix: a
+ # bare `export PATH=...` runs nothing, and the shell it was set in exits immediately.
if _env_assignment_is_unsafe(
_assign_name, _assign_value
) and _segment_has_command_after(tokens, _tok_idx):
@@ -5995,16 +5551,16 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
raw = token.strip(";&|()`{}")
if not raw:
continue
- # cmd.exe /c (or /k) runs the following token as a nested command. /c is
- # not a `-`-flag, so it is handled here in argument position after cmd.
+ # cmd.exe /c (or /k) runs the following token as a nested command. /c is not a `-`-flag, so it is handled
+ # here in argument position after cmd.
if current_command in _CMD_SHELLS and raw.lower() in ("/c", "/k"):
shell_c_pending = True
continue
# The payload of a shell `-c`, screened recursively (bounded depth).
if shell_c_pending:
shell_c_pending = False
- # An unquoted payload (cmd /c git clean -fd) spans the remaining
- # tokens, so screen the whole remainder.
+ # An unquoted payload (cmd /c git clean -fd) spans the remaining tokens, so screen the whole
+ # remainder.
payload = " ".join(tokens[_tok_idx:])
if _depth >= 3:
# Too deeply nested to screen: fail closed.
@@ -6018,20 +5574,18 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
# The value of a git global option (git -C repo clean): not the subcommand.
if git_glob_pending:
git_glob_pending = False
- # `git -c alias.x=BODY` defines an alias git later executes, so the
- # payload is real code hiding in an option value: screen it.
+ # `git -c alias.x=BODY` defines an alias git later executes, so the payload is real code hiding in an
+ # option value: screen it.
m = _GIT_ALIAS_ASSIGN_RE.match(raw)
if m and _depth < 3:
alias_body = m.group(1)
- # A `!` alias runs through a shell; a plain one is a git
- # subcommand, so screen it as `git <body>` to reach the git
- # gates (alias.n='clean -fd' really runs `git clean -fd`).
+ # A `!` alias runs through a shell; a plain one is a git subcommand, so screen it as `git <body>`
+ # to reach the git gates (alias.n='clean -fd' really runs `git clean -fd`).
nested = alias_body[1:] if alias_body.startswith("!") else "git " + alias_body
if _terminal_is_high_risk(nested, _depth + 1):
return True
continue
- # The value of a wrapper option (env -u FOO, stdbuf -o L): not the
- # command, so skip it and keep looking for the wrapped command.
+ # The value of a wrapper option (env -u FOO, stdbuf -o L): not the command, so skip it and keep looking.
if wrapper_value_pending:
wrapper_value_pending = False
continue
@@ -6047,28 +5601,27 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
or base in _MULTICALL_BINARIES
or base in _PRIVILEGE_EXEC_WRAPPERS
):
- # A wrapper (env/timeout) or a multicall binary (busybox rm)
- # precedes the real command; keep seeking it, but track it so its
- # own flags (env -S / -C) are judged in the meantime.
+ # A wrapper (env/timeout) or a multicall binary (busybox rm) precedes the real command; keep seeking
+ # it, but track it so its own flags (env -S / -C) are judged in the meantime.
prefix_pending = True
expect_command = False
current_command = base
continue
if expect_command or prefix_pending or scan_forward:
if base in _HIGH_RISK_COMMANDS or base.startswith("mkfs"):
- # A container CLI reading its own state (docker ps, docker
- # logs) inspects; anything else starts or enters a container.
+ # A container CLI reading its own state (docker ps, docker logs) inspects; anything else starts or
+ # enters a container.
if not (
base in _CONTAINER_CLIS
and _container_subcommand_is_read_only(tokens, _tok_idx)
):
return True
- # Bash expands a command-position glob after this scan, so the name
- # here is not the one that runs (`/bin/r[m] -rf x`): ask.
+ # Bash expands a command-position glob after this scan, so the name here is not the one that runs
+ # (`/bin/r[m] -rf x`): ask.
if _is_unresolved_command_glob(base):
return True
- # A server binary resolved here covers the wrapped and absolute
- # forms (env uvicorn app:api, timeout 60 gunicorn, /usr/bin/uvicorn).
+ # A server binary resolved here covers the wrapped and absolute forms (env uvicorn app:api,
+ # /usr/bin/uvicorn).
if base in _LISTENER_BINARIES:
return True
if base in _HIGH_RISK_RECURSIVE_COMMANDS and _segment_is_recursive(
@@ -6077,41 +5630,36 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
return True
if base in _HIGH_RISK_FORWARDING_COMMANDS:
if base == "xargs" and xargs_index < 0:
- # It builds the argv of whatever follows, so a sed there
- # may be handed a program this scan cannot see.
+ # It builds the argv of whatever follows, so a sed there may be handed a program this scan
+ # cannot see.
xargs_index = _tok_idx
- # find/fd only run a child at -exec/-ok; forwarding from the
- # command itself would make `find . -name rm` prompt.
+ # find/fd only run a child at -exec/-ok; forwarding from the command itself would make `find .
+ # -name rm` prompt.
if base in _EXEC_FLAG_FORWARDING_COMMANDS:
scan_forward = False
exec_flag_pending = True
else:
scan_forward = True
elif base == "git":
- # Only git needs the forwarding scan to stop: its risk lives in
- # the SUBCOMMAND (git clean), so following tokens are git's own
- # arguments. Others keep scanning, since find's predicates sit
+ # Only git needs the forwarding scan to stop: its risk lives in the SUBCOMMAND (git clean), so
+ # following tokens are git's own arguments. Others keep scanning, since find's predicates sit
# between `find` and `-exec rm`.
scan_forward = False
- # Remember the resolved command so its own flags (python -c), git
- # subcommand or chdir target can be judged as they follow.
+ # Remember the resolved command so its own flags (python -c), git subcommand or chdir target can be
+ # judged as they follow.
current_command = base
if base in _CHDIR_COMMANDS:
chdir_pending = True
if base in _AWK_COMMANDS:
awk_program_pending = True
if base in _SED_COMMANDS:
- # `e` / `s///e` shell out from inside the script, which may
- # ride on -e/--expression rather than the next positional.
- # A script --sandbox / --posix stops sed compiling is already
- # left out of the program (_sed_invocation), so a payload
- # inside one never reaches this screen.
+ # `e` / `s///e` shell out from inside the script, which may ride on -e/--expression rather than
+ # the next positional. A script --sandbox / --posix stops sed compiling is already left out of the
+ # program (_sed_invocation).
if sed_stops is None:
- # A quoted `';'` / `'+'` operand is a sed FILE, not the
- # end of the invocation; reading it as one dropped the
- # `-e` script behind it (`sed -n ';' -e '1e rm -f
- # victim' input` really runs rm). A redirection is the
- # other way round: those words never reach sed at all.
+ # A quoted `';'` / `'+'` operand is a sed FILE, not the end of the invocation; reading it as
+ # one dropped the `-e` script behind it (`sed -n ';' -e '1e rm -f victim' input` really runs
+ # rm). A redirection is the other way round: those words never reach sed at all.
sed_quoted = _quoted_separator_indexes(text, tokens, ";&|()")
_flags, sed_stops, sed_skips = _exec_scan_layout(
tokens, sed_quoted, _quoted_redirection_indexes(text, tokens, ";&|()")
@@ -6129,9 +5677,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
)
sed_program = "\n".join(sed_alternatives)
if sed_overflowed:
- # The script was pushed past the scan window by padding
- # options, so "no payload found" only means "not looked
- # at": ask instead of falling through to safe.
+ # The script was pushed past the scan window by padding options, so no payload found only
+ # means not looked at: ask instead of falling through to safe.
return True
if _sed_program_is_a_placeholder(sed_program):
# find rewrites `{}` before the child starts.
@@ -6139,17 +5686,14 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
if xargs_index >= 0 and _xargs_hides_sed_program(
tokens, xargs_index, _tok_idx, sed_program
):
- # xargs builds the argv from stdin or an -I placeholder,
- # so the program is not in the text to read at all.
+ # xargs builds the argv from stdin or an -I placeholder, so the program is not in the text to
+ # read at all.
return True
if "$" in sed_program:
- # A program held in a variable (p='# note<newline>e CMD';
- # sed "$p" f) is only a program once the reference is
- # resolved, and only THIS pass keeps the quoted newline
- # that ends the comment: the blanket one turns the whole
- # value into a single inert comment line. Only the
- # assignments ahead of this sed can reach it, and the
- # last of them is the one bash uses.
+ # A program held in a variable (p='# note<newline>e CMD'; sed "$p" f) is only a program once
+ # the reference is resolved, and only THIS pass keeps the quoted newline that ends the
+ # comment: the blanket one turns the whole value into a single inert comment line. Only the
+ # assignments ahead of this sed can reach it, and the last of them is the one bash uses.
if sed_bindings is None:
sed_bindings = _assignment_bindings(tokens, sed_quoted)
sed_vars = {}
@@ -6161,16 +5705,12 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
]
if any(_sed_exec_payloads(variant) for variant in sed_variants):
return True
- # A program the shell still has to build is not knowable
- # here -- sed splices the result straight into the program
- # text, where it can open `;e CMD` from any position -- so
- # an unread one asks rather than being assumed to only edit
- # text (_sed_program_unresolved).
- # Only where the program's OWN occurrence is one the
- # shell expands: the live set covers the whole command, so
- # matching by text alone made the read-only
- # `echo "$p"; sed 's/$p/x/' f` ask for an expansion another
- # command performs.
+ # A program the shell still has to build is not knowable here (sed splices the result straight
+ # into the program text, where it can open `;e CMD` from any position), so an unread one asks
+ # rather than being assumed to only edit text.
+ # Only where the program's OWN occurrence is one the shell expands: the live set covers the whole
+ # command, so matching by text alone made the read-only `echo "$p"; sed 's/$p/x/' f` ask for an
+ # expansion another command performs.
if sed_live and _sed_program_unresolved(sed_variants, live_expansions):
return True
elif current_command == "git" and not git_subcommand:
@@ -6194,8 +5734,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
and git_subcommand == "submodule"
and git_submodule_action == "foreach"
):
- # `git submodule foreach '<cmd>'` runs the argument in every
- # submodule, so it is a command in its own right.
+ # `git submodule foreach '<cmd>'` runs the argument in every submodule, so it is a command in its own
+ # right.
git_submodule_action = ""
if _depth >= 3 or _terminal_is_high_risk(raw, _depth + 1):
return True
@@ -6209,8 +5749,8 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
# The database name is the whole request; no path is mentioned.
return True
elif current_command == "openssl" and base in _OPENSSL_NETWORK_SUBCOMMANDS:
- # openssl s_client/s_server open a TLS socket. The regex above is
- # anchored at command position, so it misses the wrapped forms.
+ # openssl s_client/s_server open a TLS socket. The regex above is anchored at command position, so it
+ # misses the wrapped forms.
return True
elif current_command == "sysctl" and "=" in raw:
# `sysctl net.ipv4.ip_forward=1` writes without needing -w.
@@ -6222,16 +5762,14 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
):
git_worktree_action = base
elif current_command in _EVAL_SUBCOMMAND_INTERPRETERS and base == "eval":
- # `deno eval "..."` / `bun eval "..."` run inline code as a
- # subcommand rather than a flag, the same risk as -e.
+ # `deno eval` / `bun eval` run inline code as a subcommand rather than a flag, the same risk as -e.
return True
elif current_command == "git" and git_subcommand == "checkout" and base == ".":
# `git checkout .` discards every tracked working-tree change.
return True
elif current_command == "git" and git_subcommand == "checkout":
- # A SECOND positional means the first was a commit-ish and this is
- # a pathspec (git checkout HEAD file), which overwrites the file. A
- # single one is ambiguous with a branch name and is left alone.
+ # A SECOND positional means the first was a commit-ish and this is a pathspec (git checkout HEAD
+ # file), which overwrites the file. A single one is ambiguous with a branch name and is left alone.
git_checkout_positionals += 1
if git_checkout_positionals >= 2:
return True
@@ -6257,13 +5795,13 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
# `git stash clear` / `drop` destroys stashed work unrecoverably.
return True
elif current_command == "git" and git_subcommand == "push" and raw[:1] in ("+", ":"):
- # A refspec forcing (+src:dst) or deleting (:dst) a remote ref is
- # the punctuation form of --force / --delete.
+ # A refspec forcing (+src:dst) or deleting (:dst) a remote ref is the punctuation form of --force /
+ # --delete.
if len(raw) > 1:
return True
elif chdir_pending:
- # A chdir into a sensitive directory sets up a relative read that no
- # single token spells out (cd /proc/$PPID; cat environ).
+ # A chdir into a sensitive directory sets up a relative read that no single token spells out (cd
+ # /proc/$PPID; cat environ).
chdir_pending = False
if any(
_SENSITIVE_CHDIR_RE.search(cand)
@@ -6276,15 +5814,14 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
def _python_is_high_risk(code: str) -> bool:
- """High-risk python for auto mode: code the sandbox static analysis would
- refuse anyway (shell escape, network egress, a sensitive read), that
- reads/writes a credential path, or that runs dynamically built code past
- those static checks. Ordinary in-workdir file writes and computation run
- without a prompt."""
+ """High-risk python for auto mode: code the sandbox static analysis would refuse anyway (shell
+ escape, network egress, a sensitive read), that reads/writes a credential path, or that runs
+ dynamically built code past those static checks. Ordinary in-workdir file writes and
+ computation run without a prompt."""
if not code or not code.strip():
return False
- # _check_code_safety objecting means execution would be refused outright, so a
- # confirmation first beats a silent refusal.
+ # _check_code_safety objecting means execution would be refused outright, so a confirmation first beats a silent
+ # refusal.
if _check_code_safety(code) is not None:
return True
try:
@@ -6292,9 +5829,8 @@ def _python_is_high_risk(code: str) -> bool:
except SyntaxError:
# Unparsable code never runs, but scan the raw text anyway.
return _references_sensitive_path(code)
- # A credential basename only names a file when it appears in a string, so match
- # it there rather than across the source: `credentials = {}` and
- # `def load_credentials()` do no I/O and must not prompt.
+ # A credential basename only names a file when it appears in a string, so match it there rather than across the
+ # source: `credentials = {}` and `def load_credentials()` do no I/O and must not prompt.
for _node in ast.walk(tree):
if (
isinstance(_node, ast.Constant)
@@ -6302,11 +5838,11 @@ def _python_is_high_risk(code: str) -> bool:
and _references_sensitive_path(_node.value)
):
return True
- # A destructive filesystem call (shutil.rmtree, Path.unlink) asks, for parity
- # with the terminal `rm` gate. Collect bare import aliases first.
+ # A destructive filesystem call (shutil.rmtree, Path.unlink) asks, for parity with the terminal `rm` gate. Collect
+ # bare import aliases first.
destructive_fs_aliases: "set[str]" = set()
- # Modules whose handles end processes; tracked so an unrelated .kill() on a
- # user-defined object is not mistaken for one.
+ # Modules whose handles end processes; tracked so an unrelated .kill() on a user-defined object is not mistaken
+ # for one.
psutil_names: "set[str]" = set()
for _node in ast.walk(tree):
if isinstance(_node, ast.Import):
@@ -6318,14 +5854,13 @@ def _python_is_high_risk(code: str) -> bool:
and (_node.module or "").split(".")[0] in _PY_PROCESS_MODULES
):
psutil_names.add("psutil")
- # `import os as filesystem` rebinds the module, so os.remove reached through
- # the alias (filesystem.remove) must resolve too; posix is os's low-level twin.
+ # `import os as filesystem` rebinds the module, so os.remove reached through the alias must resolve too; posix is
+ # os's low-level twin.
os_module_aliases: "set[str]" = {"os", "posix", "nt"}
def _is_os_module_ref(value) -> bool:
- # A Name bound to os/posix/nt, a walrus binding one, or a literal
- # __import__("os") call used directly. builtins.__import__ is the same
- # callable reached through the module, so both spellings resolve.
+ # A Name bound to os/posix/nt, a walrus binding one, or a literal __import__("os") call used directly.
+ # builtins.__import__ is the same callable reached through the module, so both spellings resolve.
if isinstance(value, ast.Name):
return value.id in os_module_aliases
if isinstance(value, ast.NamedExpr):
@@ -6369,16 +5904,15 @@ def _python_is_high_risk(code: str) -> bool:
return isinstance(value, ast.Name) and value.id in _PY_DESTRUCTIVE_FS_MODULES
def _is_process_kill(node) -> bool:
- # psutil.Process(pid).kill() / .terminate(), including a handle bound to
- # a name first. Keyed on the psutil import so an unrelated .kill() on a
- # user object does not prompt.
+ # psutil.Process(pid).kill() / .terminate(), including a handle bound to a name first. Keyed on the psutil
+ # import so an unrelated .kill() on a user object does not prompt.
if "psutil" not in psutil_names:
return False
return isinstance(node, ast.Attribute) and node.attr in _PY_PROCESS_KILL_ATTRS
def _is_destructive_attr(attr: str, value) -> bool:
- # A destructive-name attribute (unlink/rmtree/...) on any receiver, or
- # `remove` specifically on the os module (or an alias of it).
+ # A destructive-name attribute (unlink/rmtree/...) on any receiver, or `remove` specifically on the os module
+ # (or an alias of it).
if attr in _PY_DESTRUCTIVE_FS_ATTRS:
return True
return attr in _PY_DESTRUCTIVE_FS_OS_ATTRS and _is_os_module_ref(value)
@@ -6397,9 +5931,8 @@ def _python_is_high_risk(code: str) -> bool:
return None
def _is_module_dict_lookup(node) -> bool:
- # vars(os)["remove"] / os.__dict__["unlink"] is getattr spelled through
- # the namespace dict, so screen the key the same way. Anchored to a
- # filesystem module, leaving an ordinary d["remove"] alone.
+ # vars(os)["remove"] / os.__dict__["unlink"] is getattr spelled through the namespace dict, so screen the key
+ # the same way. Anchored to a filesystem module, leaving an ordinary d["remove"] alone.
if not isinstance(node, ast.Subscript):
return False
module = _module_dict_target(node.value)
@@ -6410,8 +5943,8 @@ def _python_is_high_risk(code: str) -> bool:
return _is_fs_module_ref(module)
return _is_destructive_attr(attr, module)
- # `rm = getattr(os, "remove")` stores the lookup and calls it later, so the
- # direct getattr(...)(...) shape never sees it. Bind the name here instead.
+ # `rm = getattr(os, "remove")` stores the lookup and calls it later, so the direct getattr(...)(...) shape never
+ # sees it. Bind the name here instead.
for node in ast.walk(tree):
if not (
isinstance(node, ast.Assign)
@@ -6432,9 +5965,8 @@ def _python_is_high_risk(code: str) -> bool:
if isinstance(tgt, ast.Name):
destructive_fs_aliases.add(tgt.id)
- # `f = open(path, "r+")` then `f.truncate(0)` zeroes the file. Gated via the
- # handle name, not the bare `.truncate` attribute: pandas DataFrame.truncate()
- # is common here and non-destructive.
+ # `f = open(path, "r+")` then `f.truncate(0)` zeroes the file. Gated via the handle name, not the bare `.truncate`
+ # attribute: pandas DataFrame.truncate() is common here and non-destructive.
file_handles: "set[str]" = set()
for node in ast.walk(tree):
if (
@@ -6467,8 +5999,8 @@ def _python_is_high_risk(code: str) -> bool:
and node.func.value.id in file_handles
):
return True
- # A bound reference (f = os.remove; f(x)) hides the call site behind a plain
- # Name, so record the target name as a destructive alias to catch f(...) below.
+ # A bound reference (f = os.remove; f(x)) hides the call site behind a plain Name, so record the target name as a
+ # destructive alias to catch f(...) below.
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Subscript):
if _is_module_dict_lookup(node.value):
@@ -6511,9 +6043,8 @@ def _python_is_high_risk(code: str) -> bool:
return True
if _is_module_dict_lookup(inner):
return True
- # getattr(os, "remove")(x) resolves the attribute at runtime. The name is
- # folded first ("un" + "link"); one that cannot be folded at all on a
- # filesystem module fails closed, since there is nothing left to screen.
+ # getattr(os, "remove")(x) resolves the attribute at runtime. The name is folded first ("un" + "link"); one
+ # that cannot be folded at all on a filesystem module fails closed, since there is nothing left to screen.
if (
isinstance(func, ast.Call)
and isinstance(func.func, ast.Name)
@@ -6526,10 +6057,9 @@ def _python_is_high_risk(code: str) -> bool:
return True
elif _is_destructive_attr(attr_name, func.args[0]):
return True
- # A sensitive path split across names or joins (p = "/etc"; open(p + "/shadow"))
- # is not a contiguous literal above, so fold the string-literal variables
- # through _folded_path and re-check. An unresolved fragment folds to a sentinel
- # so a partial fold never false-positives.
+ # A sensitive path split across names or joins (p = "/etc"; open(p + "/shadow")) is not a contiguous literal
+ # above, so fold the string-literal variables through _folded_path and re-check. An unresolved fragment folds to a
+ # sentinel so a partial fold never false-positives.
str_vars: "dict[str, str]" = {}
for node in ast.walk(tree):
if not (
@@ -6542,8 +6072,8 @@ def _python_is_high_risk(code: str) -> bool:
if isinstance(value, ast.Constant) and isinstance(value.value, str):
str_vars[node.targets[0].id] = value.value
elif isinstance(value, (ast.Call, ast.BinOp, ast.JoinedStr, ast.Name)):
- # Record a fully-literal folded path so a later reuse (p / "shadow")
- # resolves; a dynamic fold is skipped so only known paths bind.
+ # Record a fully-literal folded path so a later reuse (p / "shadow") resolves; a dynamic fold is skipped
+ # so only known paths bind.
folded = _folded_path(value, str_vars)
if folded and "\x00" not in folded and "\x02" not in folded:
str_vars[node.targets[0].id] = folded
@@ -6553,9 +6083,8 @@ def _python_is_high_risk(code: str) -> bool:
folded = _folded_path(node, str_vars)
if folded and _folded_is_sensitive(folded):
return True
- # exec/eval/compile/__import__ of a non-literal (exec(b64decode(...)),
- # eval(input()), __import__(name)) runs whatever it builds at runtime, past
- # the static checks above; ask. A literal eval("1+1") is harmless and runs.
+ # exec/eval/compile/__import__ of a non-literal runs whatever it builds at runtime, past the static checks above;
+ # ask. A literal eval("1+1") is harmless and runs.
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
@@ -6570,8 +6099,7 @@ def _python_is_high_risk(code: str) -> bool:
name = func.attr
if name not in ("exec", "eval", "compile", "__import__"):
continue
- # The source is the first positional, or the source=/name= keyword when
- # called by keyword (compile(source=x), importlib.import_module(name=x)).
+ # The source is the first positional, or the source=/name= keyword when called by keyword.
arg = node.args[0] if node.args else None
if arg is None:
for kw in node.keywords:
@@ -6581,12 +6109,10 @@ def _python_is_high_risk(code: str) -> bool:
if arg is None:
continue
if isinstance(arg, ast.Constant) and isinstance(arg.value, (str, bytes)):
- # A literal source is only as safe as the code it runs, so screen it
- # recursively.
+ # A literal source is only as safe as the code it runs, so screen it recursively.
if name == "__import__":
- # A module name is not analyzable as code, but a literal
- # __import__("socket") binds a side-effecting module just like a
- # static import, so apply the same module screen.
+ # A module name is not analyzable as code, but a literal __import__("socket") binds a side-effecting
+ # module just like a static import, so apply the same module screen.
mod = (
arg.value.decode("utf-8", "replace")
if isinstance(arg.value, bytes)
@@ -6606,15 +6132,13 @@ def _python_is_high_risk(code: str) -> bool:
def is_high_risk_tool_call(name: str, arguments: dict) -> bool:
- """Whether a tool call is sensitive enough to pause for approval in auto
- ("Approve for me") mode.
-
- Unlike is_potentially_unsafe_tool_call (which prompts on anything not
- read-only), this prompts only on genuinely sensitive actions - credential
- access, privilege escalation, destructive/persistence changes, and network
- exec/exfil - and lets ordinary development commands run. The hard-block command
- set, rlimits and secret-env stripping remain in force underneath. Unknown tools
- fail closed (prompt).
+ """Whether a tool call is sensitive enough to pause for approval in auto (Approve for me) mode.
+
+ Unlike is_potentially_unsafe_tool_call (which prompts on anything not read-only), this prompts
+ only on genuinely sensitive actions - credential access, privilege escalation,
+ destructive/persistence changes, and network exec/exfil - and lets ordinary development commands
+ run. The hard-block command set, rlimits and secret-env stripping remain in force underneath.
+ Unknown tools fail closed (prompt).
"""
if _web_search_fetches_url(name, arguments):
return True
@@ -6630,9 +6154,8 @@ def is_high_risk_tool_call(name: str, arguments: dict) -> bool:
# Split camelCase into `_`-delimited terms so the term-boundary regexes
# below match camelCase names too.
tool_name = _CAMEL_CASE_RE.sub("_", tool_name)
- # An execution tool runs arbitrary commands on the MCP server, outside the
- # terminal sandbox; a credential noun discloses secrets; a read/write
- # pointed at a sensitive path is a sensitive access. All prompt, while
+ # An execution tool runs arbitrary commands on the MCP server, outside the terminal sandbox; a credential noun
+ # discloses secrets; a read/write pointed at a sensitive path is a sensitive access. All prompt, while
# ordinary create/update/delete MCP calls run.
_reads = bool(_AUTO_READ_MCP_VERB_RE.search(tool_name))
if _AUTO_EXEC_MCP_COMPOUND_RE.search(tool_name):
@@ -6655,15 +6178,13 @@ def is_high_risk_tool_call(name: str, arguments: dict) -> bool:
return True
if _mcp_arguments_reference_sensitive(arguments):
return True
- # A read-named tool carrying a destructive payload (query_database
- # {"query": "DELETE FROM runs"}) masks a destructive external action behind
- # a read-looking name. Honestly-named create/update calls still run.
+ # A read-named tool carrying a destructive payload (query_database {"query": "DELETE FROM runs"}) masks a
+ # destructive external action behind a read-looking name. Honestly-named create/update calls still run.
if _mcp_arguments_mutate(arguments):
return True
- # MCP names are an open vocabulary, not the finite set of POSIX utilities,
- # so the denylists above cannot be complete: an unfamiliar verb
- # (nuke_database) would sail through as ordinary. A name carrying no
- # recognised verb at all therefore asks.
+ # MCP names are an open vocabulary, not the finite set of POSIX utilities, so the denylists above cannot be
+ # complete: an unfamiliar verb (nuke_database) would sail through as ordinary. A name carrying no recognised
+ # verb at all therefore asks.
if not _mcp_verb_is_known(tool_name):
return True
return False
@@ -6675,15 +6196,15 @@ def is_high_risk_tool_call(name: str, arguments: dict) -> bool:
def _canon_win_path(p: str) -> str:
- """Canonical form for trust comparison: realpath (expands 8.3 aliases and
- resolves junctions/symlinks) + normcase/normpath."""
+ """Canonical form for trust comparison: realpath (expands 8.3 aliases and resolves
+ junctions/symlinks) + normcase/normpath."""
return os.path.normcase(os.path.normpath(os.path.realpath(p)))
def _augment_native_program_roots(roots: list[str]) -> list[str]:
- """Add the native Program Files sibling for any x86 root by stripping the
- `` (x86)`` suffix, so a 32-bit process (whose known-folder ids map only to
- the x86 root) still trusts a 64-bit Git install."""
+ """Add the native Program Files sibling for any x86 root by stripping the `` (x86)`` suffix, so
+ a 32-bit process (whose known-folder ids map only to the x86 root) still trusts a 64-bit Git
+ install."""
out = list(roots)
for root in roots:
base = root.rstrip("\\/")
@@ -6695,22 +6216,18 @@ def _augment_native_program_roots(roots: list[str]) -> list[str]:
def _windows_program_roots() -> list[str]:
- """Program Files install roots, resolved ONLY from the Windows known-folder
- API (SHGetKnownFolderPath). Fails closed (returns ``[]``) if the API is
- unavailable: env vars (%ProgramFiles%, even %SystemDrive%) are caller-
- overrideable and could relocate the trust boundary, so we never derive a
- trusted root from them. On any real Windows host shell32 is present, so
- this only returns empty in a broken/non-Windows environment where the
- sandbox git-PATH feature is not needed anyway (#7317).
- """
+ """Program Files install roots, resolved ONLY from the Windows known-folder API
+ (SHGetKnownFolderPath). Fails closed (returns ``[]``) if the API is unavailable: env vars
+ (%ProgramFiles%, even %SystemDrive%) are caller-overrideable and could relocate the trust
+ boundary. On any real Windows host shell32 is present, so this only returns empty where the
+ sandbox git-PATH feature is not needed anyway (#7317)."""
roots: list[str] = []
try:
import ctypes
from ctypes import wintypes
- # FOLDERID_ProgramFiles, _ProgramFilesX86, _ProgramFilesX64. The X64
- # id (Win10 1703+) yields the native root even from a 32-bit process,
- # where the first two both map to Program Files (x86).
+ # FOLDERID_ProgramFiles, _ProgramFilesX86, _ProgramFilesX64. The X64 id (Win10 1703+) yields the native root
+ # even from a 32-bit process, where the first two both map to Program Files (x86).
folder_ids = (
"{905e63b6-c1bf-494e-b29c-65b732d3d21a}",
"{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}",
@@ -6732,12 +6249,11 @@ def _windows_program_roots() -> list[str]:
def _resolve_trusted_windows_git() -> tuple[str, str]:
- """Find a git launcher in a TRUSTED Program Files dir. Returns
- ``(canonical_dir, ext)`` or ``("", "")``.
+ """Find a git launcher in a TRUSTED Program Files dir. Returns ``(canonical_dir, ext)`` or ``("",
+ "")``.
- ``shutil.which`` returns only the first PATH match, which may be an
- untrusted user shim; scan the remaining PATH entries for a later trusted
- Git so bare ``git`` still resolves (#7317).
+ ``shutil.which`` returns only the first PATH match, which may be an untrusted user shim; scan
+ the remaining PATH entries for a later trusted Git so bare ``git`` still resolves (#7317).
"""
exts = [e for e in (os.environ.get("PATHEXT") or ".EXE;.CMD;.BAT;.COM").split(os.pathsep)]
candidates: list[str] = []
@@ -6762,12 +6278,11 @@ def _resolve_trusted_windows_git() -> tuple[str, str]:
def _is_trusted_windows_program_dir(path: str) -> bool:
"""True when ``path`` sits under a system-managed Program Files root.
- Only the Program Files roots are trusted (admin-writable only), resolved
- via the known-folder API so an overridden env var cannot relocate them,
- never ``%SystemRoot%`` (Git does not install there and it holds
- world-writable subdirs like ``Windows\\Temp``). Per-user managers
- (Scoop/Choco shims under the profile) are refused. Paths are canonicalized
- so 8.3 aliases and junctions still resolve to their real root (#7317).
+ Only the Program Files roots are trusted (admin-writable only), resolved via the known-folder
+ API so an overridden env var cannot relocate them, never ``%SystemRoot%`` (Git does not install
+ there and it holds world-writable subdirs like ``Windows\\Temp``). Per-user managers
+ (Scoop/Choco shims under the profile) are refused. Paths are canonicalized so 8.3 aliases and
+ junctions still resolve to their real root (#7317).
"""
norm = _canon_win_path(path)
for root in _windows_program_roots():
@@ -6777,23 +6292,22 @@ def _is_trusted_windows_program_dir(path: str) -> bool:
return False
-# not dot-named: the walks skip dot-dirs, which would hide a model's /tmp write.
-# not "tmp": too common in a workspace, and adopting one is what broke the walks.
+# not dot-named: the walks skip dot-dirs, which would hide a model's /tmp write. not "tmp": too common in a workspace,
+# and adopting one is what broke the walks.
_SANDBOX_TEMP_DIRNAME = "unsloth-tmp"
def _sandbox_temp_dir(workdir: str) -> str:
"""The scratch directory for a sandboxed child, created when missing.
- Inside the workdir, not the workdir itself: Git for Windows mounts /tmp at
- %TEMP% (the msys2 ``usertemp`` fstab entry), so pointing TEMP at the workdir
- made /tmp its shortest POSIX name and ``pwd`` printed /tmp, leaving the user
- no way to find the real folder (#8892). One level down still sits where the
- listings reach, so a /tmp write is offered exactly as before.
+ Inside the workdir, not the workdir itself: Git for Windows mounts /tmp at %TEMP% (the msys2
+ ``usertemp`` fstab entry), so pointing TEMP at the workdir made /tmp its shortest POSIX name and
+ ``pwd`` printed /tmp, leaving the user no way to find the real folder (#8892). One level down
+ still sits where the listings reach.
- Falls back to the workdir when the name is unusable, since a TMPDIR that
- does not exist breaks every tempfile call in the child. os.mkdir, never
- os.makedirs, so a workdir deleted mid-call is not silently recreated.
+ Falls back to the workdir when the name is unusable, since a TMPDIR that does not exist breaks
+ every tempfile call in the child. os.mkdir, never os.makedirs, so a workdir deleted mid-call is
+ not silently recreated.
"""
temp_dir = os.path.join(workdir, _SANDBOX_TEMP_DIRNAME)
try:
@@ -6809,11 +6323,10 @@ def _sandbox_temp_dir(workdir: str) -> str:
def _is_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
"""Whether *temp_dir* is the workdir's own scratch directory.
- Exact stored spelling, because the walks read the name off os.walk: on a
- case-insensitive volume (default APFS, every NTFS) our lowercase probe lands
- on a directory stored as ``TMP``, and realpath does not canonicalise case.
- And the real directory, not a link or junction to one, since os.walk does
- not follow links and the artifacts would land where both walks skip.
+ Exact stored spelling, because the walks read the name off os.walk: on a case-insensitive volume
+ (default APFS, every NTFS) our lowercase probe lands on a directory stored as ``TMP``, and
+ realpath does not canonicalise case. And the real directory, not a link or junction to one,
+ since os.walk does not follow links and the artifacts would land where both walks skip.
"""
try:
with os.scandir(workdir) as entries:
@@ -6832,9 +6345,9 @@ def _is_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
def _reusable_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
"""Whether an existing entry may serve as the scratch directory.
- Identity plus writability, since tempfile abandons an unwritable TMPDIR for
- the platform default. Path accounting asks _is_sandbox_temp_dir instead:
- which directory a segment sits in does not depend on writability.
+ Identity plus writability, since tempfile abandons an unwritable TMPDIR for the platform
+ default. Path accounting asks _is_sandbox_temp_dir instead: which directory a segment sits in
+ does not depend on writability.
"""
return _is_sandbox_temp_dir(temp_dir, workdir) and os.access(temp_dir, os.W_OK | os.X_OK)
@@ -6842,21 +6355,20 @@ def _reusable_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
- Whitelist-built from scratch (parent env NOT inherited): only PATH/HOME/
- TMPDIR/LANG/TERM/PYTHONIOENCODING/PYTHONPATH (+VIRTUAL_ENV or Windows
- SystemRoot and a minimal PATHEXT) reach the child; all credential vars
- (HF_TOKEN, AWS_*, etc.) are absent. HOME points at the sandbox workdir so SDKs can't read the
- operator's cached creds, and the temp vars at _sandbox_temp_dir just inside
- it. PYTHONPATH carries only the sandbox sitecustomize shim directory.
-
- PATH starts with the Unsloth interpreter / venv and OS system dirs so
- ``python``/``pip`` stay pinned. On Windows only, Git-for-Windows install
- dirs from the host PATH are appended so bare ``git`` resolves (#7317).
- User-writable host PATH entries (venv, ``node_modules/.bin``, etc.) are
- never inherited — they could shadow auto-safe terminal commands.
+ Whitelist-built from scratch (parent env NOT inherited): only
+ PATH/HOME/TMPDIR/LANG/TERM/PYTHONIOENCODING/PYTHONPATH (+VIRTUAL_ENV or Windows SystemRoot and a
+ minimal PATHEXT) reach the child; all credential vars (HF_TOKEN, AWS_*, etc.) are absent. HOME
+ points at the sandbox workdir so SDKs can't read the operator's cached creds, and the temp vars
+ at _sandbox_temp_dir just inside it. PYTHONPATH carries only the sandbox sitecustomize shim
+ directory.
+
+ PATH starts with the Unsloth interpreter / venv and OS system dirs so ``python``/``pip`` stay
+ pinned. On Windows only, Git-for-Windows install dirs from the host PATH are appended so bare
+ ``git`` resolves (#7317). User-writable host PATH entries are never inherited: they could shadow
+ auto-safe terminal commands.
"""
- # Start from the running interpreter's dir so 'python'/'pip' resolve to the
- # same environment the Unsloth server runs in.
+ # Start from the running interpreter's dir so 'python'/'pip' resolve to the same environment the Unsloth server
+ # runs in.
exe_dir = os.path.dirname(sys.executable)
path_entries = [exe_dir] if exe_dir else []
@@ -6869,24 +6381,20 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
if sys.platform == "win32":
sysroot = os.environ.get("SystemRoot", r"C:\Windows")
- # Ahead of System32 and its DOS twins (bare `find` would hit FIND.EXE,
- # not GNU find), behind the interpreter dirs so a Git-shipped
- # python.exe cannot shadow the environment this server runs in.
+ # Ahead of System32 and its DOS twins (bare `find` would hit FIND.EXE, not GNU find), behind the interpreter
+ # dirs so a Git-shipped python.exe cannot shadow the environment this server runs in.
path_entries.extend(_windows_bash_userland_dirs())
path_entries.extend([os.path.join(sysroot, "System32"), sysroot])
else:
path_entries.extend(["/usr/local/bin", "/usr/bin", "/bin"])
- # Windows Git installs live outside System32; inherit the dir of the git
- # the HOST shell resolves, but ONLY when it sits under a system install
- # root (Program Files, windir). A user-writable dir (Scoop/Choco shims)
- # is refused: it would let an attacker drop rg.exe/jq.exe beside git and
- # have an auto-approved bare command execute it (#7317).
+ # Windows Git installs live outside System32; inherit the dir of the git the HOST shell resolves, but ONLY when it
+ # sits under a system install root. A user-writable dir (Scoop/Choco shims) is refused: it would let an attacker
+ # drop rg.exe/jq.exe beside git and have an auto-approved bare command execute it (#7317).
git_ext = ""
if sys.platform == "win32":
- # Append the CANONICAL (realpath) trusted git dir, scanning past any
- # untrusted user shim that sorts first on PATH; the canonical path
- # cannot be retargeted via a junction after the trust check.
+ # Append the CANONICAL (realpath) trusted git dir, scanning past any untrusted user shim that sorts first on
+ # PATH; the canonical path cannot be retargeted via a junction after the trust check.
_trusted_git_dir, git_ext = _resolve_trusted_windows_git()
if _trusted_git_dir:
path_entries.append(_trusted_git_dir)
@@ -6904,8 +6412,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
"PYTHONIOENCODING": "utf-8",
# A GUI backend opens a native window and blocks plt.show() until closed.
"MPLBACKEND": "Agg",
- # sitecustomize shim: remaps ChatGPT code-interpreter paths (/mnt/data
- # etc.) onto the sandbox CWD; see sandbox_site/sitecustomize.py.
+ # sitecustomize shim: remaps ChatGPT code-interpreter paths (/mnt/data etc.) onto the sandbox CWD; see
+ # sandbox_site/sitecustomize.py.
"PYTHONPATH": _SANDBOX_SITE_DIR,
}
if venv:
@@ -6913,8 +6421,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# Windows needs SystemRoot for Python/subprocess to work.
if sys.platform == "win32":
env["SystemRoot"] = os.environ.get("SystemRoot", r"C:\Windows")
- # Windows tempfile / native SDKs honour TEMP/TMP, not TMPDIR; without
- # these a child falls back to GetTempPath and writes outside the workdir.
+ # Windows tempfile / native SDKs honour TEMP/TMP, not TMPDIR; without these a child falls back to GetTempPath
+ # and writes outside the workdir.
env["TEMP"] = temp_dir
env["TMP"] = temp_dir
# Restrict PATHEXT so cwd .BAT/.CMD cannot hijack bare names (#7317).
@@ -6923,14 +6431,14 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# Keep the host git launcher (e.g. a .CMD shim) resolvable.
pathext += ";" + git_ext
env["PATHEXT"] = pathext
- # cmd/CreateProcess search cwd before PATH for bare names; disable so
- # a workdir rg.exe/git.exe cannot shadow auto-approved commands.
+ # cmd/CreateProcess search cwd before PATH for bare names; disable so a workdir rg.exe/git.exe cannot shadow
+ # auto-approved commands.
env["NoDefaultCurrentDirectoryInExePath"] = "1"
return env
-# Credential env vars dropped even in bypass mode so tool code cannot read the
-# operator's keys. Over-strips on purpose (a benign var is harmless to lose).
+# Credential env vars dropped even in bypass mode so tool code cannot read the operator's keys. Over-strips on purpose
+# (a benign var is harmless to lose).
_BYPASS_ENV_SECRET_NAMES = frozenset(
{
"HF_TOKEN",
@@ -6954,10 +6462,9 @@ _BYPASS_ENV_SECRET_NAMES = frozenset(
"KAGGLE_KEY",
"MYSQL_PWD", # exact name: markers use PASSWD, not PWD (PWD is the cwd var)
"LD_PRELOAD",
- # Auth brokers / capability handles: hand the child the operator's live
- # agent (ssh/gpg), kube config, or docker daemon. Listed by name (no
- # value signal). URL config vars are NOT name-listed: a credentialed
- # value is dropped by _is_secret_env_value() regardless of name.
+ # Auth brokers / capability handles: hand the child the operator's live agent (ssh/gpg), kube config, or
+ # docker daemon. Listed by name (no value signal). URL config vars are NOT name-listed: a credentialed value
+ # is dropped by _is_secret_env_value() regardless of name.
"SSH_AUTH_SOCK",
"SSH_AGENT_PID",
"GPG_AGENT_INFO",
@@ -6981,27 +6488,23 @@ _BYPASS_ENV_SECRET_MARKERS = (
"CONNSTR",
"CONNECTIONSTRING",
)
-# Non-secret hardening flags that match a secret prefix/marker but must be KEPT
-# so bypass mode does not undo an operator's opt-out (e.g.
-# AWS_EC2_METADATA_DISABLED blocks the AWS SDK from pulling IMDS creds).
+# Non-secret hardening flags that match a secret prefix/marker but must be KEPT so bypass mode does not undo an
+# operator's opt-out (e.g. AWS_EC2_METADATA_DISABLED blocks the AWS SDK from pulling IMDS creds).
_BYPASS_ENV_KEEP_NAMES = frozenset(
{
"AWS_EC2_METADATA_DISABLED",
"AWS_EC2_METADATA_V1_DISABLED",
}
)
-# Matches a URL embedding userinfo before the host ("scheme://user:pass@host"
-# and token-only forms). The userinfo must precede the first '/', so an '@' in
-# a path/query does not false-positive.
+# Matches a URL embedding userinfo before the host (scheme://user:pass@host and token-only forms). The userinfo must
+# precede the first '/', so an '@' in a path/query does not false-positive.
_URL_USERINFO_RE = re.compile(r"://[^/\s@]+@")
-# Connection-string credential fields (ADO.NET / Azure storage / Service Bus)
-# whose names dodge the name classifier. The Name fields (SharedAccessKeyName=)
-# don't match since "=" must follow the keyword.
+# Connection-string credential fields (ADO.NET / Azure storage / Service Bus) whose names dodge the name classifier.
+# The Name fields (SharedAccessKeyName=) don't match since "=" must follow the keyword.
_SECRET_VALUE_RE = re.compile(r"(?i)(?:password|pwd|accountkey|accesskey)\s*=\s*[^\s;]")
-# Names holding no secret value but pointing SDKs at the operator's real
-# home/cache/config (cached tokens, cred files), defeating the HOME repoint.
-# Dropped in bypass mode so tools fall back to the empty repointed HOME.
+# Names holding no secret value but pointing SDKs at the operator's real home/cache/config (cached tokens, cred
+# files), defeating the HOME repoint. Dropped in bypass mode so tools fall back to the empty repointed HOME.
_BYPASS_ENV_CRED_LOCATION_NAMES = frozenset(
{
# HF cache roots (token lives under $HF_HOME/token)
@@ -7045,8 +6548,7 @@ _BYPASS_ENV_CRED_LOCATION_NAMES = frozenset(
"HOMEPATH",
}
)
-# Windows profile dirs SDKs read creds under; repointed (not dropped) since
-# callers expect them present.
+# Windows profile dirs SDKs read creds under; repointed (not dropped) since callers expect them present.
_BYPASS_ENV_WINDOWS_PROFILE_VARS = ("USERPROFILE", "APPDATA", "LOCALAPPDATA")
@@ -7068,25 +6570,21 @@ def _is_cred_location_env_name(name: str) -> bool:
def _is_secret_env_value(value: str) -> bool:
- """True if a value embeds credentials regardless of its name.
-
- Catches URL userinfo (``scheme://user:token@host`` in DATABASE_URL /
- PIP_INDEX_URL / HTTP_PROXY) and connection-string credential fields
- (``...;Password=...`` / ``...;AccountKey=...``) whose names dodge the name
- classifier.
- """
+ """True if a value embeds credentials regardless of its name: URL userinfo
+ (``scheme://user:token@host`` in DATABASE_URL / PIP_INDEX_URL / HTTP_PROXY) and
+ connection-string credential fields (``...;Password=...`` / ``...;AccountKey=...``) whose
+ names dodge the name classifier."""
if not value:
return False
return _URL_USERINFO_RE.search(value) is not None or _SECRET_VALUE_RE.search(value) is not None
def _build_bypass_env(workdir: str) -> dict[str, str]:
- """Env for bypass exec: full host env minus credential vars, with HOME at the
- workdir and TMPDIR just inside it so SDKs cannot read cached creds.
+ """Env for bypass exec: full host env minus credential vars, with HOME at the workdir and TMPDIR
+ just inside it so SDKs cannot read cached creds.
- Stripping the child env is necessary but not sufficient (a same-UID child can
- read the parent's env via procfs), so callers also harden the parent (see
- _harden_parent_against_proc_env_leak).
+ Stripping the child env is necessary but not sufficient (a same-UID child can read the parent's
+ env via procfs), so callers also harden the parent (see _harden_parent_against_proc_env_leak).
"""
env = {
k: v
@@ -7098,18 +6596,18 @@ def _build_bypass_env(workdir: str) -> dict[str, str]:
temp_dir = _sandbox_temp_dir(workdir)
env["HOME"] = workdir
env["TMPDIR"] = temp_dir
- # Windows tempfile / SDKs honour TEMP/TMP, not TMPDIR; repoint all three so
- # the bypassed tool writes under the per-session sandbox dir on every OS.
+ # Windows tempfile / SDKs honour TEMP/TMP, not TMPDIR; repoint all three so the bypassed tool writes under the
+ # per-session sandbox dir on every OS.
env["TEMP"] = temp_dir
env["TMP"] = temp_dir
- # sitecustomize path shim (see _build_safe_env). Bypass inherits the
- # operator's PYTHONPATH, so prepend rather than replace.
+ # sitecustomize path shim (see _build_safe_env). Bypass inherits the operator's PYTHONPATH, so prepend rather than
+ # replace.
inherited_pythonpath = env.get("PYTHONPATH", "")
env["PYTHONPATH"] = os.pathsep.join(
part for part in (_SANDBOX_SITE_DIR, inherited_pythonpath) if part
)
- # Windows SDKs read creds under the profile dirs, not $HOME; repoint set
- # ones to the workdir (HOMEDRIVE/HOMEPATH are dropped above).
+ # Windows SDKs read creds under the profile dirs, not $HOME; repoint set ones to the workdir (HOMEDRIVE/HOMEPATH
+ # are dropped above).
for var in _BYPASS_ENV_WINDOWS_PROFILE_VARS:
if var in os.environ:
env[var] = workdir
@@ -7118,8 +6616,8 @@ def _build_bypass_env(workdir: str) -> dict[str, str]:
def _sandbox_preexec():
- """Best-effort sandbox setup for sandboxed subprocesses (modules are
- resolved at import time so the forked child runs no imports)."""
+ """Best-effort sandbox setup for sandboxed subprocesses (modules are resolved at import time so
+ the forked child runs no imports)."""
try:
os.setsid()
except OSError:
@@ -7141,9 +6639,8 @@ def _sandbox_preexec():
except (OSError, AttributeError):
pass
- # CLONE_NEWNET not applied: with userns enabled it blocks all egress,
- # including allowlisted hosts. Network policy is enforced by the AST
- # host check and the bash blocklist.
+ # CLONE_NEWNET not applied: with userns enabled it blocks all egress, including allowlisted hosts. Network
+ # policy is enforced by the AST host check and the bash blocklist.
if _resource is not None:
# RLIMIT_NPROC is per-real-UID, so the cap is well above normal usage.
@@ -7167,9 +6664,8 @@ def _sandbox_preexec():
except (ValueError, OSError, AttributeError):
pass
try:
- # High enough for multi-shard safetensors mmaps; tunable via env.
- # Clamp to the inherited hard limit so setrlimit doesn't ValueError
- # when the parent's hard cap is below the request.
+ # High enough for multi-shard safetensors mmaps; tunable via env. Clamp to the inherited hard limit so
+ # setrlimit doesn't ValueError when the parent's hard cap is below the request.
nofile = int(os.environ.get("UNSLOTH_STUDIO_SANDBOX_NOFILE", "16384"))
_soft_cur, hard_cur = _resource.getrlimit(_resource.RLIMIT_NOFILE)
target = nofile if hard_cur == _resource.RLIM_INFINITY else min(nofile, hard_cur)
@@ -7179,34 +6675,31 @@ def _sandbox_preexec():
def _bypass_preexec():
- """Minimal pre-exec for bypass exec: os.setsid() only.
-
- Required, not a restriction: _kill_process_tree does killpg(getpgid(child)),
- so without a new session a timeout/cancel would kill the Unsloth server too.
- """
+ """Minimal pre-exec for bypass exec: os.setsid() only. Required, not a restriction:
+ _kill_process_tree does killpg(getpgid(child)), so without a new session a timeout/cancel
+ would kill the Unsloth server too."""
try:
os.setsid()
except OSError:
pass
-# Hardening the Unsloth parent is done once (PR_SET_DUMPABLE is process-global
-# and sticky); guarded so repeated bypass calls do not re-issue the prctl.
+# Hardening the Unsloth parent is done once (PR_SET_DUMPABLE is process-global and sticky); guarded so repeated bypass
+# calls do not re-issue the prctl.
_parent_proc_hardened = False
def _harden_parent_against_proc_env_leak() -> bool:
"""Make the Unsloth process's /proc/<pid>/environ unreadable to its children.
- Stripping the child env is not enough on Linux: a bypassed same-UID child
- can read /proc/<getppid()>/environ to recover the parent's unfiltered
- secrets. Clearing PR_SET_DUMPABLE reparents this process's /proc entries to
- root, closing that read.
+ Stripping the child env is not enough on Linux: a bypassed same-UID child can read
+ /proc/<getppid()>/environ to recover the parent's unfiltered secrets. Clearing PR_SET_DUMPABLE
+ reparents this process's /proc entries to root, closing that read.
- Returns True when hardened or unnecessary (off Linux), False when needed but
- unappliable (e.g. prctl denied by seccomp); callers must then fail closed.
- This is a mitigation, not a full boundary - a bypassed tool can still walk
- /proc to an ancestor or read creds by path. Applied lazily on first bypass.
+ Returns True when hardened or unnecessary (off Linux), False when needed but unappliable (e.g.
+ prctl denied by seccomp); callers must then fail closed. This is a mitigation, not a full
+ boundary: a bypassed tool can still walk /proc to an ancestor or read creds by path. Applied
+ lazily on first bypass.
"""
global _parent_proc_hardened
if _parent_proc_hardened:
@@ -7216,8 +6709,8 @@ def _harden_parent_against_proc_env_leak() -> bool:
if _libc is None:
return False # on Linux but cannot issue prctl -> cannot harden
try:
- # prctl(PR_SET_DUMPABLE=4, SUID_DUMP_DISABLE=0). ctypes returns the
- # syscall result (-1 on failure) and does NOT raise, so check it.
+ # prctl(PR_SET_DUMPABLE=4, SUID_DUMP_DISABLE=0). ctypes returns the syscall result (-1 on failure) and does
+ # NOT raise, so check it.
ret = _libc.prctl(4, 0, 0, 0, 0)
except (OSError, AttributeError):
return False
@@ -7227,12 +6720,12 @@ def _harden_parent_against_proc_env_leak() -> bool:
return True
-# System32\bash.exe and the WindowsApps shim are the WSL launcher, which runs the
-# command inside the WSL filesystem: the sandbox workdir and the blocklist's path
-# checks would both apply to the wrong tree. Only a native Win32 bash is usable.
+# System32\bash.exe and the WindowsApps shim are the WSL launcher, which runs the command inside the WSL filesystem:
+# the sandbox workdir and the blocklist's path checks would both apply to the wrong tree. Only a native Win32 bash is
+# usable.
_WSL_BASH_MARKERS = ("\\system32\\", "\\windowsapps\\")
-# os.path.join, not a literal `Git\bin\...`, so the probe uses the host
-# separator and the resolver stays testable on POSIX.
+# os.path.join, not a literal `Git\bin\...`, so the probe uses the host separator and the resolver stays testable on
+# POSIX.
_WIN_BASH_RELATIVE = (
os.path.join("Git", "bin", "bash.exe"),
os.path.join("Git", "usr", "bin", "bash.exe"),
@@ -7242,12 +6735,11 @@ _WIN_BASH_RELATIVE = (
def _is_trusted_windows_bash(path: str) -> bool:
"""True when ``path`` is a native Win32 bash under a system install root.
- The shell runs every sandboxed command, so an untrusted one defeats the
- PATH / PATHEXT / NoDefaultCurrentDirectoryInExePath hardening in
- _build_safe_env: a bash.exe in a user-writable dir (Scoop, a per-user Git,
- a project checkout) would execute attacker-controlled code for a command
- that already passed the blocklist. Same Program Files trust boundary as
- the sandbox git PATH entry (#7317), and fails closed.
+ The shell runs every sandboxed command, so an untrusted one defeats the PATH / PATHEXT /
+ NoDefaultCurrentDirectoryInExePath hardening in _build_safe_env: a bash.exe in a user-writable
+ dir (Scoop, a per-user Git, a project checkout) would execute attacker-controlled code for a
+ command that already passed the blocklist. Same Program Files trust boundary as the sandbox git
+ PATH entry (#7317), and fails closed.
"""
lowered = path.replace("/", "\\").lower()
if any(marker in lowered for marker in _WSL_BASH_MARKERS):
@@ -7261,8 +6753,8 @@ def _windows_bash() -> "str | None":
candidates: list[str] = []
for root in _windows_program_roots():
candidates.extend(os.path.join(root, relative) for relative in _WIN_BASH_RELATIVE)
- # shutil.which returns only the FIRST PATH match, which may be an untrusted
- # shim; scan the rest too so it cannot mask a trusted Git install (#7317).
+ # shutil.which returns only the FIRST PATH match, which may be an untrusted shim; scan the rest too so it cannot
+ # mask a trusted Git install (#7317).
primary = shutil.which("bash")
if primary:
candidates.append(primary)
@@ -7279,11 +6771,10 @@ def _windows_bash() -> "str | None":
def _windows_bash_userland_dirs() -> list[str]:
"""Trusted dirs holding the resolved bash and the POSIX tools beside it.
- ``bash -c`` is non-login, so /etc/profile never runs and Git for Windows'
- ``usr\\bin`` stays off PATH, leaving ls / cat / grep "command not found".
- bash.exe ships under ``Git\\bin`` or ``Git\\usr\\bin``, so both parents are
- probed. Candidates clear the same Program Files trust boundary as the git
- entry (#7317) and are canonicalised against junctions. Fails closed: no
+ ``bash -c`` is non-login, so /etc/profile never runs and Git for Windows' ``usr\\bin`` stays off
+ PATH, leaving ls / cat / grep command not found. bash.exe ships under ``Git\\bin`` or
+ ``Git\\usr\\bin``, so both parents are probed. Candidates clear the same Program Files trust
+ boundary as the git entry (#7317) and are canonicalised against junctions. Fails closed: no
trusted bash, no entries, PATH unchanged.
"""
bash = _windows_bash()
@@ -7312,10 +6803,9 @@ def _shell_is_posix() -> bool:
def _get_shell_cmd(command: str) -> list[str]:
"""Return the platform-appropriate shell invocation for a command string."""
if sys.platform == "win32":
- # why: the model is told this tool is bash and writes bash. cmd /c runs
- # only the first line of a multi-line command, keeps single quotes
- # literal, and does not understand bash quoting, so a correct script
- # silently half-executes. Use a real bash when the host has one.
+ # The model is told this tool is bash and writes bash. cmd /c runs only the first line of a multi-line
+ # command, keeps single quotes literal, and does not understand bash quoting, so a correct script silently
+ # half-executes. Use a real bash when the host has one.
bash = _windows_bash()
if bash:
return [bash, "-c", command]
@@ -7323,30 +6813,26 @@ def _get_shell_cmd(command: str) -> list[str]:
return ["bash", "-c", command]
-# Per-session working directories so each chat thread gets its own sandbox.
-# Falls back to ~/studio_sandbox/_default for callers without a session_id.
+# Per-session working directories so each chat thread gets its own sandbox. Falls back to ~/studio_sandbox/_default
+# for callers without a session_id.
_workdirs: dict[str, str] = {}
-# Sessions with a tool call in flight. Deleting a chat unlinks its workdir, and
-# a process whose cwd has been removed fails every relative write with ENOENT.
+# Sessions with a tool call in flight. Deleting a chat unlinks its workdir, and a process whose cwd has been removed
+# fails every relative write with ENOENT.
_active_sessions: "dict[str, int]" = {}
-# Deletions that arrived mid-call: the thread has gone from history, so nothing
-# would ask for the folder again. Keyed like the above and holding every exact
-# id that folded onto the key, since each can be its own directory.
+# Deletions that arrived mid-call: the thread has gone from history, so nothing would ask for the folder again. Keyed
+# like the above and holding every exact id that folded onto the key, since each can be its own directory.
_pending_removals: "dict[str, dict[str, bool]]" = {}
_active_sessions_lock = threading.Lock()
-# Sessions whose sandbox is being removed right now. A start for one of these
-# waits on the condition rather than on the lock, so only that chat is held up.
+# Sessions whose sandbox is being removed right now. A start for one of these waits on the condition rather than on
+# the lock, so only that chat is held up.
_removing_sessions: "set[str]" = set()
_sessions_free = threading.Condition(_active_sessions_lock)
def _session_key(session_id: "str | None") -> str:
- """Lifecycle key for a session id.
-
- Case-folded: two ids differing only in case are one directory on Windows and
- on a default macOS volume, and keying them apart let a delete land while the
- other chat was running a tool in there.
- """
+ """Lifecycle key for a session id. Case-folded: two ids differing only in case are one directory
+ on Windows and on a default macOS volume, and keying them apart let a delete land while the
+ other chat was running a tool in there."""
return (session_id or _ANON_KEY).casefold()
@@ -7354,9 +6840,8 @@ def _session_key(session_id: "str | None") -> str:
def _session_in_flight(session_id: "str | None"):
key = _session_key(session_id)
with _sessions_free:
- # A removal for this session runs with the lock released, so a call
- # starting in that window would be handed the directory it is about to
- # rename away. Only this session waits; every other chat is untouched.
+ # A removal for this session runs with the lock released, so a call starting in that window would be handed
+ # the directory it is about to rename away. Only this session waits; every other chat is untouched.
while key in _removing_sessions:
_sessions_free.wait()
_active_sessions[key] = _active_sessions.get(key, 0) + 1
@@ -7372,17 +6857,16 @@ def _session_in_flight(session_id: "str | None"):
_removing_sessions.add(key)
else:
_active_sessions[key] -= 1
- # Not `if not pending: return` -- a return here swallows whatever the
- # tool raised, and the caller reports it as an unknown tool instead.
+ # Not `if not pending: return` -- a return here swallows whatever the tool raised, and the caller reports it
+ # as an unknown tool instead.
if pending:
- # Outside the lock: deciding whether the tree holds files can take
- # seconds, and no other chat could start a call meanwhile. This
- # session stays closed, so nothing starts in the directory removed.
+ # Outside the lock: deciding whether the tree holds files can take seconds, and no other chat could start
+ # a call meanwhile. This session stays closed, so nothing starts in the directory removed.
try:
for pending_id, pending_files in pending.items():
if _thread_exists(pending_id, unknown = True):
- # Recreated while that call ran: this delete belongs to
- # the chat that went, the folder is the new one's now.
+ # Recreated while that call ran: this delete belongs to the chat that went, the folder is the
+ # new one's now.
continue
_remove_session_sandbox_locked(pending_id, pending_files)
finally:
@@ -7410,31 +6894,27 @@ def _usable_session_id(session_id: str) -> bool:
def _orphan_records_dir() -> str:
- """Where a preserved project workspace's path is written down.
-
- One small file per project, named by its id: the row that knew the path is
- gone, and a workspace the user pointed somewhere custom cannot be derived
- from anything else.
- """
+ """Where a preserved project workspace's path is written down. One small file per project, named
+ by its id: the row that knew the path is gone, and a workspace the user pointed somewhere
+ custom cannot be derived from anything else."""
try:
from utils.paths.storage_roots import studio_root
return os.path.join(str(studio_root()), "orphaned-projects")
except Exception:
- # Only if the studio home cannot be resolved at all: beside the sandbox
- # root, whose parent an administrator may have made read-only.
+ # Only if the studio home cannot be resolved at all: beside the sandbox root, whose parent an administrator
+ # may have made read-only.
return os.path.join(
os.path.dirname(os.path.realpath(sandbox_root())),
"orphaned-projects",
)
-# One record per kept folder, named by kind and a digest of the id, with the
-# exact id inside: chats and projects are different tables and can carry the
-# same client-supplied id, which is not always one a filename can hold.
+# One record per kept folder, named by kind and a digest of the id, with the exact id inside: chats and projects are
+# different tables and can carry the same client-supplied id, which is not always one a filename can hold.
_ORPHAN_CHAT = "chat"
_ORPHAN_PROJECT = "project"
-# A pass reads every record: they are a few hundred bytes each, one per deleted
-# folder still kept, and a cap here would strand everything past it for good.
+# A pass reads every record: they are a few hundred bytes each, one per deleted folder still kept, and a cap here
+# would strand everything past it for good.
_MAX_ORPHAN_RECORDS = 10_000
@@ -7463,13 +6943,10 @@ def record_orphaned_project(
pending_delete: bool = False,
root_path: "str | None" = None,
) -> None:
- """Remember where a deleted project's kept workspace lives.
-
- Written whether or not files were to be deleted: the row that knew the path
- has gone either way, and a chat forked out of the project still shows cards
- for it. ``pending_delete`` is what separates "keep this, just make it
- reachable" from "the user asked for it, finish when nothing is using it".
- """
+ """Remember where a deleted project's kept workspace lives. Written whether or not files were to
+ be deleted: the row that knew the path has gone either way, and a chat forked out of the
+ project still shows cards for it. ``pending_delete`` separates keep this, just make it
+ reachable from the user asked for it, finish when nothing is using it."""
if not project_id or not workspace:
return
_write_orphan_record(
@@ -7477,8 +6954,7 @@ def record_orphaned_project(
project_id,
{
"path": os.path.realpath(workspace),
- # The whole workspace is what the delete dialog offers, and the sandbox
- # is one directory inside it.
+ # The whole workspace is what the delete dialog offers, and the sandbox is one directory inside it.
"rootPath": os.path.realpath(root_path) if root_path else None,
"pendingDelete": bool(pending_delete),
},
@@ -7500,11 +6976,9 @@ def _write_orphan_record(kind: str, record_id: str, record: dict) -> None:
def record_kept_sandbox(session_id: str) -> None:
- """Remember a chat sandbox kept because a fork still shows its files.
-
- The user asked for those files and the chat is gone, so nothing would come
- back to that folder: the fork's own delete finishes the job instead.
- """
+ """Remember a chat sandbox kept because a fork still shows its files. The user asked for those
+ files and the chat is gone, so nothing would come back to that folder: the fork's own delete
+ finishes the job instead."""
if not session_id:
return
try:
@@ -7567,12 +7041,9 @@ def list_orphaned_projects() -> "list[tuple[str, str, str | None, bool, bool]]":
def _recorded_workspace_remains(workspace: str, root: "str | None") -> bool:
- """Whether anything a record names is still on disk.
-
- The project root as well as its sandbox: a delete that removed the sandbox
- and stopped at a locked file elsewhere leaves the rest of the workspace,
- and dropping the record here loses both the path and the user's request.
- """
+ """Whether anything a record names is still on disk. The project root as well as its sandbox: a
+ delete that removed the sandbox and stopped at a locked file elsewhere leaves the rest of the
+ workspace, and dropping the record here loses both the path and the user's request."""
for path in (workspace, root):
if path and os.path.isdir(path) and not os.path.islink(path):
return True
@@ -7595,12 +7066,11 @@ def forget_orphaned_project_if_gone(
def _delete_recorded_workspace(project_id: str, workspace: str, root: "str | None") -> None:
"""Remove a recorded workspace the way the immediate delete would.
- Always through the storage helper, whose folder-name and denied-path checks
- decide what may go: a record is a file on disk, and a stale or edited one
- naming an unrelated directory must not become an rmtree of it. Without a
- recorded root the workspace's own parent is offered, which is what the
- default layout puts the sandbox in; anything else it refuses, and the
- record stays pending rather than being deleted on our own authority.
+ Always through the storage helper, whose folder-name and denied-path checks decide what may go:
+ a record is a file on disk, and a stale or edited one naming an unrelated directory must not
+ become an rmtree of it. Without a recorded root the workspace's own parent is offered, which is
+ what the default layout puts the sandbox in; anything else it refuses, and the record stays
+ pending rather than being deleted on our own authority.
"""
from storage.studio_db import delete_project_workspace
@@ -7609,21 +7079,17 @@ def _delete_recorded_workspace(project_id: str, workspace: str, root: "str | Non
def collect_orphaned_project_workspaces() -> None:
- """Finish the workspace deletes the user asked for.
-
- Only records marked pending: one kept merely so a fork's cards resolve is
- not something anybody asked to remove. Skipped while a tool call is still
- running in there, or while a chat still shows its files.
- """
+ """Finish the workspace deletes the user asked for. Only records marked pending: one kept merely
+ so a fork's cards resolve is not something anybody asked to remove. Skipped while a tool call
+ is still running in there, or while a chat still shows its files."""
from storage.studio_db import sandbox_is_referenced_elsewhere
for record_id, workspace, root, pending, is_chat in list_orphaned_projects():
if not pending:
continue
try:
session = record_id if is_chat else project_session_id(record_id)
- # This runs minutes after the row went, and the id is the client's
- # to reuse: a chat or a project created since owns that folder, and
- # a card of its own may not be stored yet.
+ # This runs minutes after the row went, and the id is the client's to reuse: a chat or a project created
+ # since owns that folder, and a card of its own may not be stored yet.
recreated = (
_thread_exists(record_id, unknown = True)
if is_chat
@@ -7637,13 +7103,13 @@ def collect_orphaned_project_workspaces() -> None:
if sandbox_is_referenced_elsewhere(session):
continue
if is_chat:
- # Its own ownership checks decide whether that directory is
- # ours to take, exactly as the chat's own delete would.
+ # Its own ownership checks decide whether that directory is ours to take, exactly as the chat's own
+ # delete would.
remove_session_sandbox(session, delete_files = True)
else:
_delete_recorded_workspace(record_id, workspace, root)
- # A locked file on Windows, or a network volume having a bad
- # moment: the record stays so the next launch tries again.
+ # A locked file on Windows, or a network volume having a bad moment: the record stays so the next launch
+ # tries again.
forget_orphaned_project_if_gone(record_id, workspace, root, is_chat)
except Exception: # noqa: BLE001 - a stuck record must not break a delete
logger.warning("Could not collect workspace for %s", record_id, exc_info = True)
@@ -7652,11 +7118,9 @@ def collect_orphaned_project_workspaces() -> None:
def finish_workspace_delete_when_idle(
project_id: str, timeout: float = 600.0
) -> "threading.Thread":
- """Wait out the tool call still using a workspace, then delete it.
-
- The delete dialog promised those files would go, and nothing else would
- come back to them: the collection otherwise runs only on the next delete.
- """
+ """Wait out the tool call still using a workspace, then delete it. The delete dialog promised
+ those files would go, and nothing else would come back to them: the collection otherwise runs
+ only on the next delete."""
def _wait_and_collect() -> None:
session = project_session_id(project_id)
@@ -7673,27 +7137,22 @@ def finish_workspace_delete_when_idle(
def _recorded_project_workdir(project_id: str) -> "str | None":
- """The kept workspace of a deleted project, wherever the user put it.
-
- By key: a resolve happens on every tool call for such a project, and no
- number of other records may keep it from finding its own.
- """
+ """The kept workspace of a deleted project, wherever the user put it. By key: a resolve happens
+ on every tool call for such a project, and no number of other records may keep it from
+ finding its own."""
record = _read_orphan_record(_ORPHAN_PROJECT, project_id)
if not record:
return None
path = record["path"]
- # Only a sandbox still there: a record kept alive by the rest of its
- # workspace names a directory nothing can be served from.
+ # Only a sandbox still there: a record kept alive by the rest of its workspace names a directory nothing can be
+ # served from.
return path if os.path.isdir(path) else None
def _orphaned_project_workdir(project_id: str) -> "str | None":
- """A deleted project's workspace, when its files were kept.
-
- The record answers for any id, since it is keyed by a digest. Only the
- guess below builds a directory name, so only that needs an id a filename
- can hold.
- """
+ """A deleted project's workspace, when its files were kept. The record answers for any id, since
+ it is keyed by a digest. Only the guess below builds a directory name, so only that needs an
+ id a filename can hold."""
recorded = _recorded_project_workdir(project_id)
if recorded:
return recorded
@@ -7716,12 +7175,9 @@ def _orphaned_project_workdir(project_id: str) -> "str | None":
def _thread_exists(thread_id: str, unknown: bool = False) -> bool:
- """Whether a chat of the user's is stored under this exact id.
-
- ``unknown`` is what a check that could not be made returns: a caller about
- to delete files passes True, so a database hiccup keeps them, while one
- merely routing a call passes False and treats the id as a project's.
- """
+ """Whether a chat of the user's is stored under this exact id. ``unknown`` is what a check that
+ could not be made returns: a caller about to delete files passes True, so a database hiccup
+ keeps them, while one merely routing a call passes False and treats the id as a project's."""
try:
from storage.studio_db import get_chat_thread
return get_chat_thread(thread_id) is not None
@@ -7734,13 +7190,10 @@ def live_project_owns(
workspace: str,
root: "str | None" = None,
) -> bool:
- """Whether a project with this id is the one those folders belong to.
-
- A reused id is not the same workspace: the default root carries the
- project's name, and renaming a project leaves its root where it was. A
- folder the live row does not own is still the deleted project's, and still
- the one the user asked to remove.
- """
+ """Whether a project with this id is the one those folders belong to. A reused id is not the
+ same workspace: the default root carries the project's name, and renaming a project leaves
+ its root where it was. A folder the live row does not own is still the deleted project's, and
+ still the one the user asked to remove."""
try:
from storage.studio_db import get_chat_project
project = get_chat_project(project_id)
@@ -7769,12 +7222,9 @@ def _project_exists(project_id: str) -> bool:
def _project_workdir_for(session_id: "str | None") -> "str | None":
- """The project workspace a session id names, if it names one.
-
- The prefixed id can be longer than a directory name may be, or carry a
- character one may not: it is the project part that has to be usable, and
- the workspace path comes from the row rather than from the id.
- """
+ """The project workspace a session id names, if it names one. The prefixed id can be longer than
+ a directory name may be, or carry a character one may not: it is the project part that has to
+ be usable, and the workspace path comes from the row rather than from the id."""
if not session_id:
return None
if not _usable_session_id(session_id) and not session_id.startswith(_PROJECT_SESSION_PREFIX):
@@ -7789,9 +7239,8 @@ def _get_project_workdir(session_id: str) -> str | None:
if not project_id:
return None
if _thread_exists(session_id):
- # An API client picks its own thread ids, and a chat called this is a
- # chat: sharing the project's workspace would run its tool calls in
- # there and leave its delete refusing to remove anything.
+ # An API client picks its own thread ids, and a chat called this is a chat: sharing the project's workspace
+ # would run its tool calls in there and leave its delete refusing to remove anything.
return None
try:
from storage.studio_db import ensure_chat_project_workspace
@@ -7800,9 +7249,8 @@ def _get_project_workdir(session_id: str) -> str | None:
logger.warning("Failed to resolve project sandbox for %s", session_id, exc_info = True)
return None
if not project:
- # The project is gone but a chat forked out of it still shows cards for
- # this sandbox, and the workspace was kept for exactly that: the record
- # answers for any id, and the folder-name guess needs a usable one.
+ # The project is gone but a chat forked out of it still shows cards for this sandbox, and the workspace was
+ # kept for exactly that: the record answers for any id, and the folder-name guess needs a usable one.
return _orphaned_project_workdir(project_id)
root_path = project.get("rootPath")
sandbox_path = project.get("sandboxPath")
@@ -7815,54 +7263,44 @@ def _get_project_workdir(session_id: str) -> str | None:
return sandbox_real
-# Dropped in every session directory we create. The root can be an existing
-# shared folder the user pointed us at, and a chat id can name something already
-# in there; this is the only evidence the directory is ours to delete.
+# Dropped in every session directory we create. The root can be an existing shared folder the user pointed us at, and
+# a chat id can name something already in there; this is the only evidence the directory is ours to delete.
_SANDBOX_MARKER = ".unsloth_sandbox"
-# Reserved: a directory named this way belongs to the id that hashes to it, and
-# never to a chat that happens to be called the same thing.
+# Reserved: a directory named this way belongs to the id that hashes to it, and never to a chat that happens to be
+# called the same thing.
_DERIVED_PREFIX = "_id-"
-# The directories a call with no usable session id runs in. A chat whose id is
-# one of these gets a derived name instead of sharing that folder, and with it
-# every session-less call's files and the delete that takes them.
+# The directories a call with no usable session id runs in. A chat whose id is one of these gets a derived name
+# instead of sharing that folder, and with it every session-less call's files and the delete that takes them.
_FALLBACK_NAMES = frozenset({"_default", "_invalid"})
-# The cache and lifecycle key for a call with no session id. Holds a character
-# the id charset forbids, so a chat cannot key onto the same entry and be handed
-# the session-less sandbox out of the cache.
+# The cache and lifecycle key for a call with no session id. Holds a character the id charset forbids, so a chat
+# cannot key onto the same entry and be handed the session-less sandbox out of the cache.
_ANON_KEY = "\x00_default"
def _sandbox_name(session_id: str) -> str:
- """The directory name for an id.
-
- An id the filesystem cannot hold gets a name derived from it rather than a
- shared bucket: those ids come from API clients, and one bucket meant every
- such chat could read and delete every other one's files.
- """
+ """The directory name for an id. An id the filesystem cannot hold gets a name derived from it
+ rather than a shared bucket: those ids come from API clients, and one bucket meant every such
+ chat could read and delete every other one's files."""
if (
_usable_session_id(session_id)
and not session_id.startswith(_DERIVED_PREFIX)
and session_id not in _FALLBACK_NAMES
):
return session_id
- # An id that already looks derived is derived too, or it would land on the
- # directory of whichever unusable id hashes to it. surrogatepass because a
- # lone surrogate reaches here from JSON and from surrogateescape alike.
+ # An id that already looks derived is derived too, or it would land on the directory of whichever unusable id
+ # hashes to it. surrogatepass because a lone surrogate reaches here from JSON and from surrogateescape alike.
encoded = session_id.encode("utf-8", "surrogatepass")
return _DERIVED_PREFIX + hashlib.sha256(encoded).hexdigest()[:16]
def _preserve_foreign_marker(workdir: str, name: "str | None" = None) -> None:
- """Move aside a marker-named entry that this migration did not write.
-
- This name was not reserved before the change, so a chat that wrote its own
- .unsloth_sandbox has a real file there, and a short note like "notes" reads
- as a perfectly good session name. Only the exact marker this move is about
- to write is left alone; everything else is renamed, not removed.
- """
+ """Move aside a marker-named entry that this migration did not write. This name was not reserved
+ before the change, so a chat that wrote its own .unsloth_sandbox has a real file there, and a
+ short note like notes reads as a perfectly good session name. Only the exact marker this move
+ is about to write is left alone; everything else is renamed, not removed."""
marker = os.path.join(workdir, _SANDBOX_MARKER)
if not os.path.lexists(marker):
return
@@ -7879,11 +7317,8 @@ def _preserve_foreign_marker(workdir: str, name: "str | None" = None) -> None:
def _mark_sandbox(workdir: str, session_id: str) -> None:
- """(Re)write the marker. Never through a link.
-
- The file sits where tool code runs, so one replaced by a symlink would send
- this write to whatever it points at and truncate it.
- """
+ """(Re)write the marker. Never through a link: the file sits where tool code runs, so one
+ replaced by a symlink would send this write to whatever it points at and truncate it."""
marker = os.path.join(workdir, _SANDBOX_MARKER)
try:
if os.path.islink(marker):
@@ -7899,12 +7334,9 @@ def _mark_sandbox(workdir: str, session_id: str) -> None:
def _marker_owner(workdir: str) -> "str | None":
- """The id this directory was created for, when it says.
-
- Anything that is not an id reads as no owner rather than as somebody else's:
- a tool writing over this file would otherwise send its own chat to a fresh
- directory on the next launch, leaving its files behind.
- """
+ """The id this directory was created for, when it says. Anything that is not an id reads as no
+ owner rather than as somebody else's: a tool writing over this file would otherwise send its
+ own chat to a fresh directory on the next launch, leaving its files behind."""
marker = os.path.join(workdir, _SANDBOX_MARKER)
if os.path.islink(marker):
return None # not a marker we wrote, and not one to follow
@@ -7919,17 +7351,16 @@ def _marker_owner(workdir: str) -> "str | None":
def _session_dir(root: str, session_id: str) -> str:
"""The directory for this exact id.
- Two ids differing only in case are one name on Windows and on a default
- macOS volume. The marker says which id made the directory, and anyone else
- gets one of their own rather than sharing files that either chat's deletion
- would then remove. A directory already sitting in a root the user pointed
- us at is nobody's sandbox: it is stepped around rather than run in, so no
- tool can write a marker into it and make it look like ours.
+ Two ids differing only in case are one name on Windows and on a default macOS volume. The marker
+ says which id made the directory, and anyone else gets one of their own rather than sharing
+ files that either chat's deletion would then remove. A directory already sitting in a root the
+ user pointed us at is nobody's sandbox: it is stepped around rather than run in, so no tool can
+ write a marker into it and make it look like ours.
"""
name = _sandbox_name(session_id)
plain = os.path.join(root, name)
- # A link is never ours, whatever it points at: claiming through one writes
- # the marker into a directory somebody else made, inside the root or not.
+ # A link is never ours, whatever it points at: claiming through one writes the marker into a directory somebody
+ # else made, inside the root or not.
if not os.path.islink(plain):
owner = _marker_owner(plain)
if owner == name:
@@ -7941,32 +7372,27 @@ def _session_dir(root: str, session_id: str) -> str:
def _name_suffix(session_id: str) -> str:
- """A short stable tail, so the same chat lands in the same directory.
-
- surrogatepass for the same reason _sandbox_name uses it: an id with a lone
- surrogate reaches here on the collision path, and a strict encode would
- raise rather than step aside.
- """
+ """A short stable tail, so the same chat lands in the same directory. surrogatepass for the same
+ reason _sandbox_name uses it: an id with a lone surrogate reaches here on the collision path,
+ and a strict encode would raise rather than step aside."""
encoded = session_id.encode("utf-8", "surrogatepass")
return hashlib.sha256(encoded).hexdigest()[:8]
-# Serialises the pick-then-create below. Two case-variant ids racing on a
-# case-insensitive volume could otherwise both see an unowned name and take it.
+# Serialises the pick-then-create below. Two case-variant ids racing on a case-insensitive volume could otherwise both
+# see an unowned name and take it.
_assign_lock = threading.Lock()
-# Directories this run created and claimed. Not a record of ownership beyond
-# this process: it is what lets a marker a tool removed be written again.
+# Directories this run created and claimed. Not a record of ownership beyond this process: it is what lets a marker a
+# tool removed be written again.
_claimed_here: "set[str]" = set()
def _claim_sandbox(workdir: str, session_id: str) -> bool:
- """Write the marker if nobody has, and report whether this id owns it.
-
- O_EXCL, so of two processes creating the same directory exactly one claims
- it and the other is told to go elsewhere.
- """
+ """Write the marker if nobody has, and report whether this id owns it. O_EXCL, so of two
+ processes creating the same directory exactly one claims it and the other is told to go
+ elsewhere."""
marker = os.path.join(workdir, _SANDBOX_MARKER)
name = _sandbox_name(session_id)
try:
@@ -7989,13 +7415,11 @@ def _ensure_session_dir(root: str, session_id: str) -> str:
workdir = _session_dir(root, session_id)
if not _contained_in_root(workdir, root):
return _sandbox_fallback(root, "_invalid")
- # Before creating anything: _session_dir can hand back the fallback
- # name, which in a root the user pointed us at can be a directory of
- # theirs, and claiming it would run this chat inside their files.
+ # Before creating anything: _session_dir can hand back the fallback name, which in a root the user pointed us
+ # at can be a directory of theirs, and claiming it would run this chat inside their files.
if not os.path.exists(workdir):
- # A tree an interrupted migration left marked but not moved in is
- # this chat's, at any root: starting fresh beside it would leave
- # those files unreachable for good.
+ # A tree an interrupted migration left marked but not moved in is this chat's, at any root: starting fresh
+ # beside it would leave those files unreachable for good.
stranded = _marked_sandbox_in(root, session_id)
if stranded:
try:
@@ -8010,14 +7434,13 @@ def _ensure_session_dir(root: str, session_id: str) -> str:
os.makedirs(workdir, exist_ok = True)
if _claim_sandbox(workdir, session_id):
return workdir
- # A marker naming nobody is one a tool wrote over, and at our own root
- # nothing else could have put this directory here.
+ # A marker naming nobody is one a tool wrote over, and at our own root nothing else could have put this
+ # directory here.
if _root_is_ours() and _marker_owner(workdir) is None:
_mark_sandbox(workdir, session_id)
return workdir
- # Somebody else's, so take a name of our own rather than run inside it.
- # The fallback is in the same user-controlled root, so it gets the same
- # test: an unowned directory already sitting there is theirs too.
+ # Somebody else's, so take a name of our own rather than run inside it. The fallback is in the same
+ # user-controlled root, so it gets the same test: an unowned directory already sitting there is theirs too.
workdir = _free_fallback_dir(root, session_id)
if workdir is None or not _contained_in_root(workdir, root):
return _sandbox_fallback(root, "_invalid")
@@ -8027,19 +7450,16 @@ def _ensure_session_dir(root: str, session_id: str) -> str:
def _marked_sandbox_in(root: str, session_id: str) -> "str | None":
- """A directory in *root* whose marker names this chat, if there is one.
-
- A fresh fallback has a name nothing can recompute, so this is what finds it
- again on a later launch, on a read and on a delete. Bounded: a root the
- user pointed us at can hold a lot of their own folders.
- """
+ """A directory in *root* whose marker names this chat, if there is one. A fresh fallback has a
+ name nothing can recompute, so this is what finds it again on a later launch, on a read and
+ on a delete. Bounded: a root the user pointed us at can hold a lot of their own folders."""
name = _sandbox_name(session_id)
- # Only names derived from this id, the plain name a half-finished migration
- # staged beside, and their staging names: tool code can write any owner into
- # the marker, so "whoever claims to be me" would hand over another's files.
+ # Only names derived from this id, the plain name a half-finished migration staged beside, and their staging
+ # names: tool code can write any owner into the marker, so whoever claims to be me would hand over another's
+ # files.
candidates = [os.path.join(root, name), *_fallback_candidates(root, session_id)]
- # Listed once: there are 33 candidate names, and a scan each would be 33
- # walks of a root that can hold a folder per chat, on a first call.
+ # Listed once: there are 33 candidate names, and a scan each would be 33 walks of a root that can hold a folder
+ # per chat, on a first call.
try:
entries = sorted(os.listdir(root))
except OSError:
@@ -8057,13 +7477,10 @@ def _marked_sandbox_in(root: str, session_id: str) -> "str | None":
def _free_fallback_dir(root: str, session_id: str) -> "str | None":
- """A name in *root* this chat may take, or None when they are all spoken for.
-
- The deterministic one first, so the same chat comes back to the same folder,
- then a fresh one rather than running inside anything already there.
- """
- # One we already made wins, wherever it is: a fresh name every launch would
- # scatter this chat's files.
+ """A name in *root* this chat may take, or None when they are all spoken for. The deterministic
+ one first, so the same chat comes back to the same folder, then a fresh one rather than
+ running inside anything already there."""
+ # One we already made wins, wherever it is: a fresh name every launch would scatter this chat's files.
ours = _marked_sandbox_in(root, session_id)
if ours:
return ours
@@ -8073,9 +7490,8 @@ def _free_fallback_dir(root: str, session_id: str) -> "str | None":
return None
-# How many derived names a chat may try in a root the user pointed us at. Each
-# is recomputable, so a later launch finds the folder by name; a random name
-# needed a scan, which a big enough root pushes past its bound.
+# How many derived names a chat may try in a root the user pointed us at. Each is recomputable, so a later launch
+# finds the folder by name; a random name needed a scan, which a big enough root pushes past its bound.
_MAX_FALLBACK_NAMES = 32
@@ -8098,12 +7514,9 @@ def _free_for(path: str, name: str) -> bool:
def _root_is_ours() -> bool:
- """True unless the root is a directory the user pointed us at.
-
- A link is theirs as well: `<studio home>/sandbox` pointing somewhere else
- means the directories under it are the user's, and "ours by construction"
- is what lets a delete rename and remove one of them.
- """
+ """True unless the root is a directory the user pointed us at. A link is theirs as well:
+ `<studio home>/sandbox` pointing somewhere else means the directories under it are the
+ user's, and ours by construction is what lets a delete rename and remove one of them."""
if (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip():
return False
try:
@@ -8113,11 +7526,9 @@ def _root_is_ours() -> bool:
def _sandbox_is_ours(target: str) -> bool:
- """Ours by construction at our own root, otherwise only with the marker.
-
- A real file: isfile() follows a link, so a marker symlinked at any existing
- file would make an unrelated directory in a shared root deletable.
- """
+ """Ours by construction at our own root, otherwise only with the marker. A real file: isfile()
+ follows a link, so a marker symlinked at any existing file would make an unrelated directory
+ in a shared root deletable."""
if _root_is_ours():
return True
marker = os.path.join(target, _SANDBOX_MARKER)
@@ -8130,12 +7541,9 @@ def _legacy_sandbox_root() -> str:
def sandbox_root() -> str:
- """Root of the per-session tool sandboxes.
-
- Under the studio home, so UNSLOTH_STUDIO_HOME keeps everything in one place
- instead of leaving a stray ~/studio_sandbox. Falls back to the legacy path
- only if the studio root cannot be resolved.
- """
+ """Root of the per-session tool sandboxes. Under the studio home, so UNSLOTH_STUDIO_HOME keeps
+ everything in one place instead of leaving a stray ~/studio_sandbox. Falls back to the legacy
+ path only if the studio root cannot be resolved."""
override = (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip()
if override:
return os.path.expanduser(override)
@@ -8150,31 +7558,26 @@ _legacy_sandbox_migrated = False
_legacy_sandbox_lock = threading.Lock()
-# Where a cross-filesystem move is assembled. Not a session name, so nothing
-# resolves to it while it is being filled.
+# Where a cross-filesystem move is assembled. Not a session name, so nothing resolves to it while it is being filled.
_STAGING_SUFFIX = ".arriving-"
def _free_move_target(root: str, name: str) -> "str | None":
- """A name in *root* nothing occupies, for a legacy move to land on.
-
- The resolver's own answer first, so an untouched root keeps the plain name.
- Both derived names can be the user's in a root they pointed us at, and
- returning nothing there stranded the files at the legacy root for good: the
- marker the move writes is what finds this one again.
- """
+ """A name in *root* nothing occupies, for a legacy move to land on. The resolver's own answer
+ first, so an untouched root keeps the plain name. Both derived names can be the user's in a
+ root they pointed us at, and returning nothing there stranded the files at the legacy root
+ for good: the marker the move writes is what finds this one again."""
candidate = _session_dir(root, name)
if not os.path.exists(candidate):
return candidate
if _marker_owner(candidate) == _sandbox_name(name):
- # This session's folder is already at the destination from an earlier
- # move. A duplicate legacy copy is left alone rather than overwritten,
- # or moved somewhere the user could no longer find it.
+ # This session's folder is already at the destination from an earlier move. A duplicate legacy copy is left
+ # alone rather than overwritten, or moved somewhere the user could no longer find it.
return None
if _root_is_ours():
return None # ours and occupied is a real collision, not a borrowed name
- # The same derived names the request path takes, so whichever runs first the
- # other one resolves to the folder that ended up holding the files.
+ # The same derived names the request path takes, so whichever runs first the other one resolves to the folder that
+ # ended up holding the files.
for candidate in _fallback_candidates(root, name):
if not os.path.exists(candidate):
return candidate
@@ -8182,14 +7585,11 @@ def _free_move_target(root: str, name: str) -> "str | None":
def _staged_move(source: str, target: str, name: str) -> None:
- """Move one session in, so an interruption cannot look like a collision.
-
- Across filesystems shutil.move copies as it goes, and a run killed part way
- leaves a partial destination with the original still in place. The next
- launch would read that as a session the new root already has and strand the
- files. Filled under a name nothing resolves to, then renamed, which on one
- filesystem is atomic.
- """
+ """Move one session in, so an interruption cannot look like a collision. Across filesystems
+ shutil.move copies as it goes, and a run killed part way leaves a partial destination with
+ the original still in place; the next launch would read that as a session the new root
+ already has and strand the files. Filled under a name nothing resolves to, then renamed,
+ which on one filesystem is atomic."""
staging = f"{target}{_STAGING_SUFFIX}{uuid.uuid4().hex[:8]}"
try:
shutil.move(source, staging)
@@ -8197,17 +7597,15 @@ def _staged_move(source: str, target: str, name: str) -> None:
# Half filled and ours, and the source is still where it was.
shutil.rmtree(staging, ignore_errors = True)
raise
- # Marked here, not after the rename: across filesystems the move has already
- # removed the legacy copy, so from this instant the staging tree is the only
- # one there is and a kill before the marker would leave it unfindable.
+ # Marked here, not after the rename: across filesystems the move has already removed the legacy copy, so from this
+ # instant the staging tree is the only one there is and a kill before the marker would leave it unfindable.
_preserve_foreign_marker(staging, name)
_mark_sandbox(staging, name)
try:
os.rename(staging, target)
except OSError:
- # The move already took the legacy copy, so this tree is the only one
- # and deleting it would lose the files. It is marked, so
- # _marked_sandbox_in finds it; put it back and let the next pass retry.
+ # The move already took the legacy copy, so this tree is the only one and deleting it would lose the files. It
+ # is marked, so _marked_sandbox_in finds it; put it back and let the next pass retry.
try:
os.rename(staging, source)
except OSError:
@@ -8216,13 +7614,12 @@ def _staged_move(source: str, target: str, name: str) -> None:
_mark_sandbox(target, name)
-# Bookkeeping only, never held across a move: starting the background pass and
-# the sweep. Anything that copies a tree takes that session's own lock below.
+# Bookkeeping only, never held across a move: starting the background pass and the sweep. Anything that copies a tree
+# takes that session's own lock below.
_legacy_one_lock = threading.Lock()
-# One lock per session being moved: a single lock made a first tool call wait
-# out another chat's multi-gigabyte copy, which is what the background pass
-# exists to avoid. Bounded by the chats that had a legacy folder.
+# One lock per session being moved: a single lock made a first tool call wait out another chat's multi-gigabyte copy,
+# which is what the background pass exists to avoid. Bounded by the chats that had a legacy folder.
_legacy_session_locks: "dict[str, threading.Lock]" = {}
_legacy_locks_guard = threading.Lock()
@@ -8233,37 +7630,31 @@ def _legacy_lock_for(name: str) -> threading.Lock:
return _legacy_session_locks.setdefault(name, threading.Lock())
-# Where every id the old code could not use as a directory name went. One
-# bucket for all of them, which is what this change stops doing, so it is never
-# moved up as though it were a chat: several chats' files are in there.
+# Where every id the old code could not use as a directory name went. One bucket for all of them, which is what this
+# change stops doing, so it is never moved up as though it were a chat: several chats' files are in there.
_LEGACY_SHARED_BUCKET = "_invalid"
def _legacy_session_dir(session_id: str) -> "str | None":
- """This session's directory at the legacy root, while one is still there.
-
- Both names, like the migration itself: a chat from before the upgrade whose
- id starts with the derived prefix kept its folder under the literal id.
- """
+ """This session's directory at the legacy root, while one is still there. Both names, like the
+ migration itself: a chat from before the upgrade whose id starts with the derived prefix kept
+ its folder under the literal id."""
legacy_root = _legacy_sandbox_root()
names = [_sandbox_name(session_id)]
if not _usable_session_id(session_id):
- # Before this change an id the filesystem could not hold shared one
- # bucket with every other such chat: read where they are, never moved or
- # deleted, and only for such an id, or a chat reads somebody else's.
+ # Before this change an id the filesystem could not hold shared one bucket with every other such chat: read
+ # where they are, never moved or deleted, and only for such an id, or a chat reads somebody else's.
names.append(_LEGACY_SHARED_BUCKET)
elif session_id not in names and session_id not in _FALLBACK_NAMES:
- # Only the derived-prefix case: an id the old code could hold kept its
- # folder under the literal name while _sandbox_name now hashes it. A
- # fallback name is nobody's chat: every session-less call ran in there.
+ # Only the derived-prefix case: an id the old code could hold kept its folder under the literal name while
+ # _sandbox_name now hashes it. A fallback name is nobody's chat: every session-less call ran in there.
names.append(session_id)
for name in names:
candidate = os.path.join(legacy_root, name)
if not os.path.isdir(candidate) or os.path.islink(candidate):
continue
- # Under this session's move lock, and checked again inside it: the move
- # is a rename, so a path handed back mid-move lists nothing and 404s
- # every card. One that already ran sends the caller to the destination.
+ # Under this session's move lock, and checked again inside it: the move is a rename, so a path handed back
+ # mid-move lists nothing and 404s every card. One that already ran sends the caller to the destination.
with _legacy_lock_for(name):
if os.path.isdir(candidate) and not os.path.islink(candidate):
return candidate
@@ -8280,9 +7671,8 @@ def _migrate_one_legacy_session(root: str, name: str) -> None:
with _legacy_lock_for(name):
if not os.path.isdir(source):
return # the background pass got there first
- # Through the resolver, like the whole-tree pass: at a shared root the
- # plain name can be the user's own, and stopping here would leave this
- # chat with an empty sandbox and its files stranded at the old root.
+ # Through the resolver, like the whole-tree pass: at a shared root the plain name can be the user's own, and
+ # stopping here would leave this chat with an empty sandbox and its files stranded at the old root.
target = _free_move_target(root, name)
if target is None or not _contained_in_root(target, root):
return # nowhere free to land, left for the whole-tree pass
@@ -8309,32 +7699,27 @@ def _start_legacy_migration() -> "threading.Thread | None":
def _migrate_legacy_sandbox(root: str) -> None:
- """Move sessions from ~/studio_sandbox into the studio home, once.
-
- Those files are the user's, so they move rather than being dropped. A
- session already present at the new root wins and its legacy copy is left
- alone, so nothing is silently overwritten.
- """
+ """Move sessions from ~/studio_sandbox into the studio home, once. Those files are the user's,
+ so they move rather than being dropped. A session already present at the new root wins and
+ its legacy copy is left alone, so nothing is silently overwritten."""
global _legacy_sandbox_migrated
if _legacy_sandbox_migrated:
return
- # Flagged only once the move is done: setting it first let a concurrent
- # call create the destination, which then read as a collision.
+ # Flagged only once the move is done: setting it first let a concurrent call create the destination, which then
+ # read as a collision.
with _legacy_sandbox_lock:
if _legacy_sandbox_migrated:
return
- # Only when nothing movable is left: a file locked on Windows is
- # retryable, and one attempt strands it once the destination exists.
+ # Only when nothing movable is left: a file locked on Windows is retryable, and one attempt strands it once
+ # the destination exists.
if _migrate_legacy_sandbox_locked(root):
_legacy_sandbox_migrated = True
def _migrate_legacy_sandbox_locked(root: str) -> bool:
- """True when the legacy root holds nothing that could still be moved.
-
- A collision is not a failure: the new root already has that session, and the
- legacy copy is deliberately left for the user to find.
- """
+ """True when the legacy root holds nothing that could still be moved. A collision is not a
+ failure: the new root already has that session, and the legacy copy is deliberately left for
+ the user to find."""
legacy = _legacy_sandbox_root()
try:
if os.path.realpath(legacy) == os.path.realpath(root) or not os.path.isdir(legacy):
@@ -8344,16 +7729,14 @@ def _migrate_legacy_sandbox_locked(root: str) -> bool:
complete = True
for name in os.listdir(legacy):
source = os.path.join(legacy, name)
- # A link is not a sandbox of ours: the move preserves it, and the
- # marker would then be written inside whatever it points at, which
- # is a directory outside both roots.
+ # A link is not a sandbox of ours: the move preserves it, and the marker would then be written inside
+ # whatever it points at, which is a directory outside both roots.
if os.path.islink(source) or not os.path.isdir(source):
continue
if name == _LEGACY_SHARED_BUCKET:
continue # several chats' files, not one chat's
- # The same choice the request path makes: at a shared root both
- # derived names can be the user's, and skipping here while still
- # reporting the pass complete stranded that chat's files for good.
+ # The same choice the request path makes: at a shared root both derived names can be the user's, and
+ # skipping here while still reporting the pass complete stranded that chat's files for good.
target = _free_move_target(root, name)
if target is None or not _contained_in_root(target, root):
continue
@@ -8364,8 +7747,8 @@ def _migrate_legacy_sandbox_locked(root: str) -> bool:
_staged_move(source, target, name)
moved += 1
except OSError as error:
- # A file locked on Windows is retryable, so this run reports
- # itself unfinished and the next launch tries again.
+ # A file locked on Windows is retryable, so this run reports itself unfinished and the next launch
+ # tries again.
complete = False
logger.warning("Could not move sandbox %s: %s", name, error)
if moved:
@@ -8386,13 +7769,11 @@ def _sandbox_fallback(
name: str,
create: bool = False,
) -> str:
- """``_default`` / ``_invalid`` under the root, contained like any session.
-
- They are ordinary directories in a writable sandbox, so one replaced by a
- symlink would otherwise become the root every unchecked request reads from.
- Dropping that link is only ours to do at our own root; in a directory the
- user pointed us at, the entry is theirs and a fresh one is used instead.
- """
+ """``_default`` / ``_invalid`` under the root, contained like any session. They are ordinary
+ directories in a writable sandbox, so one replaced by a symlink would otherwise become the
+ root every unchecked request reads from. Dropping that link is only ours to do at our own
+ root; in a directory the user pointed us at, the entry is theirs and a fresh one is used
+ instead."""
owner = _sandbox_name(name) # reserved, so it is never a chat's own name
path = os.path.join(root, name)
if os.path.islink(path):
@@ -8404,9 +7785,8 @@ def _sandbox_fallback(
pass
elif _root_is_ours() or not os.path.exists(path) or _marker_owner(path) == owner:
return path
- # In a root the user pointed us at, a directory already sitting under this
- # name is theirs: a call with no session id would otherwise run in it. The
- # one we made instead is remembered, so it is not a new one every call.
+ # In a root the user pointed us at, a directory already sitting under this name is theirs: a call with no session
+ # id would otherwise run in it. The one we made instead is remembered, so it is not a new one every call.
stem = f"{name}_{_name_suffix(name)}"
candidates = [os.path.join(root, stem)] + [
os.path.join(root, f"{stem}-{n}") for n in range(2, _MAX_FALLBACK_NAMES + 1)
@@ -8417,9 +7797,8 @@ def _sandbox_fallback(
return made
return _nothing_to_serve(name)
for made in candidates:
- # exist_ok alone would take a directory of theirs that happens to carry
- # this name, and follow a link out of the root to run wherever it
- # points, so the entry has to be free and the claim has to succeed.
+ # exist_ok alone would take a directory of theirs that happens to carry this name, and follow a link out of
+ # the root to run wherever it points, so the entry has to be free and the claim has to succeed.
if not _free_for(made, owner):
continue
try:
@@ -8431,20 +7810,16 @@ def _sandbox_fallback(
return _nothing_to_serve(name)
-# Where a read is sent when the chat owns nothing. Outside every sandbox root
-# and inside a directory this process makes and empties, so a listing is empty
-# and a download is a 404 rather than whatever the user keeps at that name.
+# Where a read is sent when the chat owns nothing. Outside every sandbox root and inside a directory this process
+# makes and empties, so a listing is empty and a download is a 404 rather than whatever the user keeps at that name.
_NOTHING_ROOT = None
_nothing_lock = threading.Lock()
def _nothing_to_serve(name: str) -> str:
- """A path that exists nowhere the user keeps files.
-
- The name is derived first: callers pass the id straight from the request,
- and an absolute one like ``/etc`` would make os.path.join drop the root it
- was given and hand back a directory of the system's.
- """
+ """A path that exists nowhere the user keeps files. The name is derived first: callers pass the
+ id straight from the request, and an absolute one like ``/etc`` would make os.path.join drop
+ the root it was given and hand back a directory of the system's."""
global _NOTHING_ROOT
leaf = _sandbox_name(name)
with _nothing_lock:
@@ -8455,21 +7830,18 @@ def _nothing_to_serve(name: str) -> str:
_NOTHING_ROOT = os.path.join(tempfile.gettempdir(), "unsloth-unowned")
root = _NOTHING_ROOT
resolved = os.path.join(root, leaf)
- # Belt and braces: a derived name cannot escape, and neither may anything
- # else that reaches here.
+ # Belt and braces: a derived name cannot escape, and neither may anything else that reaches here.
return resolved if _contained_in_root(resolved, root) else root
def _contained_in_root(workdir: str, root: str) -> bool:
- """Whether a resolved session path is still inside the sandbox root.
-
- Applied to cached paths too: a directory replaced by a symlink after it was
- cached would otherwise keep serving from wherever it now points.
- """
+ """Whether a resolved session path is still inside the sandbox root. Applied to cached paths
+ too: a directory replaced by a symlink after it was cached would otherwise keep serving from
+ wherever it now points."""
try:
resolved, base = os.path.realpath(workdir), os.path.realpath(root)
- # commonpath, not a prefix test: a filesystem root already ends in a
- # separator, and appending another failed every real session path.
+ # commonpath, not a prefix test: a filesystem root already ends in a separator, and appending another failed
+ # every real session path.
return resolved != base and os.path.commonpath([resolved, base]) == base
except (OSError, ValueError):
return False
@@ -8477,16 +7849,13 @@ def _contained_in_root(workdir: str, root: str) -> bool:
def _owned_by_session(workdir: str, session_id: str) -> bool:
"""Whether this session may read *workdir*, for a caller that creates nothing.
-
- ``_ensure_session_dir`` claims or steps aside; a read has to decide on what
- is already there, and the name it was given can be somebody else's too.
- """
+ ``_ensure_session_dir`` claims or steps aside; a read has to decide on what is already there,
+ and the name it was given can be somebody else's too."""
owner = _marker_owner(workdir)
if owner is not None:
return owner == _sandbox_name(session_id)
- # No marker, so the name is the only evidence, and `Foo` and `foo` are one
- # directory on Windows and on a default macOS volume. The delete path has
- # always asked this; a read that did not let the other chat's files through.
+ # No marker, so the name is the only evidence, and `Foo` and `foo` are one directory on Windows and on a default
+ # macOS volume. The delete path has always asked this; a read that did not let the other chat's files through.
return _root_is_ours() and os.path.basename(workdir) == _sandbox_name(session_id)
@@ -8498,13 +7867,11 @@ def _get_workdir(session_id: str | None = None) -> str:
if cached is not None and not os.path.isdir(cached):
cached = None
if cached is not None and not _get_project_workdir(session_id or ""):
- # The same checks a fresh resolve makes: the entry can have been
- # renamed and replaced with a link to another chat's directory since,
- # and containment alone accepts that.
+ # The same checks a fresh resolve makes: the entry can have been renamed and replaced with a link to another
+ # chat's directory since, and containment alone accepts that.
root_now = sandbox_root()
- # Tool code runs in here and can delete the marker. For a directory
- # this run claimed it is written again, rather than read as somebody
- # else's, which would strand the files in it and start the chat anew.
+ # Tool code runs in here and can delete the marker. For a directory this run claimed it is written again,
+ # rather than read as somebody else's, which would strand the files in it and start the chat anew.
if (
session_id
and cached in _claimed_here
@@ -8513,9 +7880,8 @@ def _get_workdir(session_id: str | None = None) -> str:
and os.path.isdir(cached)
and _marker_owner(cached) != _sandbox_name(session_id)
):
- # Whatever it says now, this process made this directory for this
- # chat. A tool writing another id into the marker would otherwise
- # send the chat to a new folder and strand what it just wrote.
+ # Whatever it says now, this process made this directory for this chat. A tool writing another id into the
+ # marker would otherwise send the chat to a new folder and strand what it just wrote.
_preserve_foreign_marker(cached, session_id)
_mark_sandbox(cached, session_id)
if (
@@ -8528,13 +7894,11 @@ def _get_workdir(session_id: str | None = None) -> str:
_workdirs.pop(key, None)
sandbox_root_path = sandbox_root()
root_existed = os.path.isdir(sandbox_root_path)
- # The folder may still be at the legacy root right after an upgrade.
- # Only this chat's, so a first tool call never waits on the whole tree:
- # across filesystems that is a copy of every session.
+ # The folder may still be at the legacy root right after an upgrade. Only this chat's, so a first tool call
+ # never waits on the whole tree: across filesystems that is a copy of every session.
if session_id:
- # A pre-upgrade chat whose id already starts with the derived
- # prefix kept its folder under the literal id, so that name is
- # tried too. Only a usable one: the rest never named a directory.
+ # A pre-upgrade chat whose id already starts with the derived prefix kept its folder under the literal id,
+ # so that name is tried too. Only a usable one: the rest never named a directory.
derived = _sandbox_name(session_id)
if (
derived != session_id
@@ -8555,18 +7919,18 @@ def _get_workdir(session_id: str | None = None) -> str:
created = not os.path.isdir(workdir)
os.makedirs(workdir, exist_ok = True)
if not project_workdir and not session_id:
- # The fallbacks are directories like any other: claimed, so the next
- # run knows this one is the one we made.
+ # The fallbacks are directories like any other: claimed, so the next run knows this one is the one we
+ # made.
_claim_sandbox(workdir, "_default")
- # Only a root we just created: the override can name a shared
- # directory, and locking that down would cut off everything else.
+ # Only a root we just created: the override can name a shared directory, and locking that down would cut off
+ # everything else.
if not root_existed or not (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip():
try:
os.chmod(sandbox_root_path, 0o700)
except OSError:
pass
- # Only ours: a shared root can already hold a directory with this name,
- # and tightening it would cut off whoever else uses it.
+ # Only ours: a shared root can already hold a directory with this name, and tightening it would cut off
+ # whoever else uses it.
if created or _sandbox_is_ours(workdir):
try:
os.chmod(workdir, 0o700)
@@ -8581,11 +7945,8 @@ def get_sandbox_workdir(session_id: str | None = None) -> str:
def resolve_sandbox_workdir(session_id: str | None = None) -> str:
- """Where a session's sandbox would be, without creating it.
-
- For read-only callers: serving a file must not materialise a directory for
- every id someone asks about.
- """
+ """Where a session's sandbox would be, without creating it. For read-only callers: serving a
+ file must not materialise a directory for every id someone asks about."""
if session_id:
project = _project_workdir_for(session_id)
if project:
@@ -8601,33 +7962,30 @@ def resolve_sandbox_workdir(session_id: str | None = None) -> str:
return cached
if not session_id:
return _sandbox_fallback(root, "_default")
- # A directory this process made for this chat is this chat's, whatever a
- # tool wrote into the marker since: the check above trusts that file, and
- # without this the files it holds are served from nowhere.
+ # A directory this process made for this chat is this chat's, whatever a tool wrote into the marker since: the
+ # check above trusts that file, and without this the files it holds are served from nowhere.
claimed = _claimed_by_this_run(session_id, os.path.realpath(root))
if claimed:
return claimed
workdir = _session_dir(root, session_id)
- # Same containment _get_workdir applies: a session entry symlinked out of
- # the root would otherwise serve whatever it points at.
+ # Same containment _get_workdir applies: a session entry symlinked out of the root would otherwise serve whatever
+ # it points at.
if not _contained_in_root(workdir, root):
return _sandbox_fallback(root, "_invalid")
if not os.path.isdir(workdir):
- # A migration that moved the tree but could not rename it into place
- # leaves the only copy under a marked name, at any root.
+ # A migration that moved the tree but could not rename it into place leaves the only copy under a marked name,
+ # at any root.
ours = _marked_sandbox_in(root, session_id)
if ours:
return ours
- # Right after an upgrade the files can still be at the legacy root: the
- # move runs in the background and can take minutes. Read where they are
- # rather than 404 every card in the transcript until it finishes.
+ # Right after an upgrade the files can still be at the legacy root: the move runs in the background and can
+ # take minutes. Read where they are rather than 404 every card in the transcript until it finishes.
legacy = _legacy_session_dir(session_id)
if legacy:
return legacy
if not _root_is_ours() and not _owned_by_session(workdir, session_id):
- # In a root the user pointed us at this chat can be in a fallback whose
- # name nothing recomputes, and a read that stops here shows an empty
- # sandbox and 404s the file cards already in the transcript.
+ # In a root the user pointed us at this chat can be in a fallback whose name nothing recomputes, and a read
+ # that stops here shows an empty sandbox and 404s the file cards already in the transcript.
ours = _marked_sandbox_in(root, session_id)
if ours:
return ours
@@ -8638,11 +7996,9 @@ def resolve_sandbox_workdir(session_id: str | None = None) -> str:
def migrate_legacy_sandbox_in_background() -> "threading.Thread":
- """Move the legacy sandbox up at startup, off every request.
-
- Across filesystems this copies every session, which is not something a
- listing or a download can wait on: those run on the event loop.
- """
+ """Move the legacy sandbox up at startup, off every request. Across filesystems this copies
+ every session, which is not something a listing or a download can wait on: those run on the
+ event loop."""
def _run() -> None:
try:
@@ -8657,13 +8013,13 @@ def migrate_legacy_sandbox_in_background() -> "threading.Thread":
# A name no session resolves to, so a detached tree is inert until it is gone.
_DETACHED_SUFFIX = ".deleting-"
-# The exact shape the rename produces. A substring test would also have matched
-# a backup of the user's own named report.deleting-old.
+# The exact shape the rename produces. A substring test would also have matched a backup of the user's own named
+# report.deleting-old.
_DETACHED_RE = re.compile(r"\A.+\.deleting-[0-9a-f]{8}\Z")
-# One worker for every detached tree, rather than a thread per chat: clearing a
-# thousand chats would otherwise start a thousand recursive deletes at once.
+# One worker for every detached tree, rather than a thread per chat: clearing a thousand chats would otherwise start a
+# thousand recursive deletes at once.
_delete_queue: "queue.Queue[tuple[str, int]]" = queue.Queue()
# Attempts at one tree, and how long the first wait is (doubled each time).
_MAX_DETACHED_DELETE_TRIES = 5
@@ -8684,12 +8040,9 @@ def _drain_detached_deletes() -> None:
def _retry_detached_delete(target: str, tries: int) -> None:
- """Queue another attempt at a tree ignore_errors left behind.
-
- A file held open by a scanner or a process still exiting is transient, and
- on Windows routine. The route has already told the user those files went,
- so waiting for the next launch's sweep is not an answer.
- """
+ """Queue another attempt at a tree ignore_errors left behind. A file held open by a scanner or a
+ process still exiting is transient, and on Windows routine. The route has already told the
+ user those files went, so waiting for the next launch's sweep is not an answer."""
if tries + 1 >= _MAX_DETACHED_DELETE_TRIES:
logger.warning("Could not delete %s; the next sweep retries it", target)
return
@@ -8718,8 +8071,8 @@ def _queue_detached_delete(target: str) -> None:
)
_delete_worker.start()
except RuntimeError:
- # No thread to be had: better a slow call than a tree under a
- # name nothing resolves to and nothing deletes.
+ # No thread to be had: better a slow call than a tree under a name nothing resolves to and nothing
+ # deletes.
_delete_worker = None
shutil.rmtree(target, ignore_errors = True)
return
@@ -8729,14 +8082,13 @@ def _queue_detached_delete(target: str) -> None:
def sweep_detached_sandboxes(root: "str | None" = None) -> None:
"""Finish deletes a previous run was killed part way through.
- The rename is what puts the tree out of reach, so a kill between it and the
- rmtree leaves a full copy of the files nothing resolves to.
+ The rename is what puts the tree out of reach, so a kill between it and the rmtree leaves a full
+ copy of the files nothing resolves to.
- At our own root the name is enough: nothing but this code puts a
- ``.deleting-<hex>`` directory there, and a tool that had removed the marker
- before the delete would otherwise leave the tree unreachable for good. In a
- root the user pointed us at, the marker is still required, since a folder of
- theirs can carry any name.
+ At our own root the name is enough: nothing but this code puts a ``.deleting-<hex>`` directory
+ there, and a tool that had removed the marker before the delete would otherwise leave the tree
+ unreachable for good. In a root the user pointed us at, the marker is still required, since a
+ folder of theirs can carry any name.
"""
base = os.path.realpath(root or sandbox_root())
try:
@@ -8770,8 +8122,8 @@ def _start_detached_sweep() -> "threading.Thread | None":
def _sweep() -> None:
sweep_detached_sandboxes()
- # A workspace the user asked to delete, left pending because a tool was
- # still running in it when the app went away.
+ # A workspace the user asked to delete, left pending because a tool was still running in it when the app went
+ # away.
collect_orphaned_project_workspaces()
thread = threading.Thread(target = _sweep, name = "sandbox-sweep", daemon = True)
@@ -8782,49 +8134,45 @@ def _start_detached_sweep() -> "threading.Thread | None":
def remove_session_sandbox(session_id: str, delete_files: bool = False) -> bool:
"""Drop a deleted chat's sandbox. True when something was removed.
- The chat was the only handle on that directory, so leaving it behind means
- one unreachable folder per chat forever. Empty folders always go; files
- need ``delete_files``, since they are the user's and are downloadable from
- the chat. Project workspaces are shared and have their own delete flow.
+ The chat was the only handle on that directory, so leaving it behind means one unreachable
+ folder per chat forever. Empty folders always go; files need ``delete_files``, since they are
+ the user's and are downloadable from the chat. Project workspaces are shared and have their own
+ delete flow.
"""
if not session_id:
return False
- # Only a session that really resolves to a project workspace: an imported
- # chat whose id merely starts with the prefix gets an ordinary directory
- # from _get_workdir, and would otherwise never be cleaned up.
+ # Only a session that really resolves to a project workspace: an imported chat whose id merely starts with the
+ # prefix gets an ordinary directory from _get_workdir, and would otherwise never be cleaned up.
if session_id.startswith(_PROJECT_SESSION_PREFIX) and _get_project_workdir(session_id):
- # Unless this id has a sandbox of its own: a chat named like a project
- # session had one while its row existed, and the row goes first, so the
- # project would inherit the question and those files stay behind.
+ # Unless this id has a sandbox of its own: a chat named like a project session had one while its row existed,
+ # and the row goes first, so the project would inherit the question and those files stay behind.
root_here = os.path.realpath(sandbox_root())
if not _claimed_by_this_run(session_id, root_here) and not _marked_sandbox_in(
root_here,
session_id,
):
return False
- # The folder may still be at the legacy root right after an upgrade. This
- # session only, or a delete would sit behind a copy of every chat, and
- # outside the lock below, since it moves a tree and takes its own.
+ # The folder may still be at the legacy root right after an upgrade. This session only, or a delete would sit
+ # behind a copy of every chat, and outside the lock below, since it moves a tree and takes its own.
root_now = sandbox_root()
_migrate_one_legacy_session(root_now, _sandbox_name(session_id))
if _usable_session_id(session_id) and _sandbox_name(session_id) != session_id:
_migrate_one_legacy_session(root_now, session_id)
_start_legacy_migration()
- # Held across the decision AND the unlink: otherwise a tool can start in
- # between and run in a directory this call then removes.
+ # Held across the decision AND the unlink: otherwise a tool can start in between and run in a directory this call
+ # then removes.
key = _session_key(session_id)
with _sessions_free:
while key in _removing_sessions:
_sessions_free.wait() # another delete for this chat is finishing
if _active_sessions.get(key, 0) > 0:
- # Queued rather than dropped: the chat is already gone from history,
- # so no later delete or clear would ever name this session again.
+ # Queued rather than dropped: the chat is already gone from history, so no later delete or clear would
+ # ever name this session again.
queued = _pending_removals.setdefault(key, {})
queued[session_id] = delete_files or queued.get(session_id, False)
return False # see sandbox_removal_deferred
- # Closed for this chat, then released: deciding whether the sandbox is
- # empty walks the tree, and holding the global lock for that stops tool
- # calls starting in every unrelated chat.
+ # Closed for this chat, then released: deciding whether the sandbox is empty walks the tree, and holding the
+ # global lock for that stops tool calls starting in every unrelated chat.
_removing_sessions.add(key)
try:
return _remove_session_sandbox_locked(session_id, delete_files)
@@ -8835,12 +8183,9 @@ def remove_session_sandbox(session_id: str, delete_files: bool = False) -> bool:
def session_sandbox_has_files(session_id: str) -> bool:
- """Whether this chat's sandbox still holds files of the user's.
-
- For a delete that was not offered the choice: the chat was the only way to
- those files, so the caller can offer it afterwards rather than leave a
- folder nothing can reach.
- """
+ """Whether this chat's sandbox still holds files of the user's. For a delete that was not
+ offered the choice: the chat was the only way to those files, so the caller can offer it
+ afterwards rather than leave a folder nothing can reach."""
if not session_id:
return False
try:
@@ -8856,35 +8201,28 @@ def session_sandbox_has_files(session_id: str) -> bool:
def _is_spill_artifact(sandbox: str, parent: str, name: str) -> bool:
- """Whether ``parent/name`` is a spill this process wrote, rather than anything else.
-
- Both halves are checked: the name has to be one `_spill_full_output` generates, and it
- has to sit at the spill root or one scope below it. A link is never one, whatever it
- is called.
- """
+ """Whether ``parent/name`` is a spill this process wrote, rather than anything else. Both halves
+ are checked: the name has to be one `_spill_full_output` generates, and it has to sit at the
+ spill root or one scope below it. A link is never one, whatever it is called."""
root = os.path.join(sandbox, _SPILL_DIR)
if parent != root and os.path.dirname(parent) != root:
return False
identity, owned = _spill_record(root)
if identity is None or identity != _spill_identity(root):
- # No record of this directory: it came with the sandbox or was replaced, so
- # everything in it is the user's, however the files are named.
+ # No record of this directory: it came with the sandbox or was replaced, so everything in it is the user's,
+ # however the files are named.
return False
return _is_recorded_spill(root, os.path.join(parent, name), owned)
def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:
- """Whether a sandbox holds nothing but (possibly empty) directories.
-
- Our own marker does not count, and only while it is still ours: tool code
- runs in there and can write its own content over that file, which is then
- the only copy of it. Bounded like every other walk here, and a tree too big
- to check is not one to remove without being asked.
- """
+ """Whether a sandbox holds nothing but (possibly empty) directories. Our own marker does not
+ count, and only while it is still ours: tool code runs in there and can write its own content
+ over that file, which is then the only copy of it. Bounded like every other walk here, and a
+ tree too big to check is not one to remove without being asked."""
budget = _MAX_SNAPSHOT_DIRS
for parent, dirs, files in os.walk(target):
- # A link to a directory is listed here, not in files, and a tool made
- # it: a sandbox holding one is not empty.
+ # A link to a directory is listed here, not in files, and a tool made it: a sandbox holding one is not empty.
if any(os.path.islink(os.path.join(parent, name)) for name in dirs):
return False
for name in files:
@@ -8894,12 +8232,11 @@ def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:
marker = _marker_owner(target)
if marker is not None and owner in (None, marker):
continue
- # Unsloth's own, like the marker above: a spill is truncated tool output this
- # process wrote and deliberately kept off the file cards, so counting one as
- # the user's content leaves an unreachable sandbox behind, reported as holding
- # files the user never created. Only the artifacts themselves, by the name
- # `_spill_full_output` generates: the directory is writable, tool code can
- # create anything in it, and a real file there is the user's like any other.
+ # Unsloth's own, like the marker above: a spill is truncated tool output this process wrote and
+ # deliberately kept off the file cards, so counting one as the user's content leaves an unreachable
+ # sandbox behind, reported as holding files the user never created. Only the artifacts themselves, by the
+ # name `_spill_full_output` generates: the directory is writable, tool code can create anything in it, and
+ # a real file there is the user's like any other.
if _is_spill_artifact(target, parent, name):
continue
return False
@@ -8910,14 +8247,11 @@ def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:
def _claimed_by_this_run(session_id: str, root: str) -> "str | None":
- """The directory this process made for this chat, whatever the marker says.
-
- Tool code runs in there and can empty that file or write another id into
- it, and neither makes the directory somebody else's: this process wrote the
- marker with O_EXCL and remembers doing it. Put back here, so the ordinary
- routes find it too rather than leaving the files stranded until some later
- call happens to repair it.
- """
+ """The directory this process made for this chat, whatever the marker says. Tool code runs in
+ there and can empty that file or write another id into it, and neither makes the directory
+ somebody else's: this process wrote the marker with O_EXCL and remembers doing it. Put back
+ here, so the ordinary routes find it too rather than leaving the files stranded until some
+ later call happens to repair it."""
cached = _workdirs.get(session_id)
if not cached or cached not in _claimed_here:
return None
@@ -8937,11 +8271,9 @@ def project_session_id(project_id: str) -> str:
def wait_for_sessions_idle(session_ids, timeout: float = 10.0) -> bool:
- """Wait until no tool call is running for these sessions. True if none is.
-
- Cancelling a generation only sets its event, so the call inside the executor
- is still using its working directory for a moment after.
- """
+ """Wait until no tool call is running for these sessions. True if none is. Cancelling a
+ generation only sets its event, so the call inside the executor is still using its working
+ directory for a moment after."""
keys = {_session_key(session_id) for session_id in session_ids or []}
if not keys:
return True
@@ -8957,12 +8289,9 @@ def wait_for_sessions_idle(session_ids, timeout: float = 10.0) -> bool:
def sandbox_removal_deferred(session_id: str) -> bool:
- """Whether this session's removal is queued behind a running tool call.
-
- The caller reports what it kept, and the answer is not known yet: the call
- still in flight can write a file after the sandbox looked empty, and the
- deferred removal would then keep it with nobody left to say so.
- """
+ """Whether this session's removal is queued behind a running tool call. The caller reports what
+ it kept, and the answer is not known yet: the call still in flight can write a file after the
+ sandbox looked empty, and the deferred removal would then keep it with nobody left to say so."""
if not session_id:
return False
with _active_sessions_lock:
@@ -8975,13 +8304,12 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
entry = os.path.join(root, _sandbox_name(session_id))
if not os.path.islink(entry):
entry = _session_dir(root, session_id)
- # Neither computed name is ours, so this chat may be in a fallback, or
- # in a directory whose marker a tool removed since we made it.
+ # Neither computed name is ours, so this chat may be in a fallback, or in a directory whose marker a tool
+ # removed since we made it.
if not _owned_by_session(entry, session_id):
entry = _marked_sandbox_in(root, session_id) or claimed or entry
- # The entry itself, not what it resolves to: a symlink to a sibling passes
- # the check below and would take that chat's files. Drop the link, but only
- # at our own root: in a shared one it is the user's entry, not a sandbox.
+ # The entry itself, not what it resolves to: a symlink to a sibling passes the check below and would take that
+ # chat's files. Drop the link, but only at our own root: in a shared one it is the user's entry, not a sandbox.
if os.path.islink(entry):
if not _root_is_ours():
return False
@@ -8997,26 +8325,23 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
ours_here = bool(claimed) and target == os.path.realpath(claimed)
if not ours_here and not _sandbox_is_ours(target):
return False
- # Made for a different id: the same directory on a case-insensitive volume,
- # and those files are the other chat's.
+ # Made for a different id: the same directory on a case-insensitive volume, and those files are the other chat's.
owner = _marker_owner(target)
if owner is not None and owner != _sandbox_name(session_id):
return False
if owner is None and not ours_here and os.path.basename(target) != _sandbox_name(session_id):
- # Nothing says whose this is, and on a case-insensitive volume `foo`
- # and `Foo` are one directory: without the marker the name is the only
- # evidence, and it names the other chat.
+ # Nothing says whose this is, and on a case-insensitive volume `foo` and `Foo` are one directory: without the
+ # marker the name is the only evidence, and it names the other chat.
return False
_workdirs.pop(session_id, None)
- # Resolved BEFORE anything is removed: the record is named by the real path of the
- # spill directory, which cannot be derived once the tree is gone. Without this every
- # deleted chat that ever truncated output leaves one small file behind for good.
+ # Resolved BEFORE anything is removed: the record is named by the real path of the spill directory, which cannot
+ # be derived once the tree is gone. Without this every deleted chat that ever truncated output leaves one small
+ # file behind for good.
forget_record = _spill_record_path(os.path.join(target, _SPILL_DIR))
try:
if delete_files:
- # Renamed while locked, deleted after: every tool start takes this
- # lock, so an rmtree of a large tree in here stops calls in every
- # other chat for as long as it runs.
+ # Renamed while locked, deleted after: every tool start takes this lock, so an rmtree of a large tree in
+ # here stops calls in every other chat for as long as it runs.
detached = f"{target}{_DETACHED_SUFFIX}{uuid.uuid4().hex[:8]}"
try:
os.rename(target, detached)
@@ -9029,9 +8354,8 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
_queue_detached_delete(detached)
_forget_spill_record(forget_record)
return True
- # Empty means no files of the user's: a tool that only ran mkdir, or
- # deleted what it wrote, leaves directories behind, and the chat record
- # is already gone by the time this runs.
+ # Empty means no files of the user's: a tool that only ran mkdir, or deleted what it wrote, leaves directories
+ # behind, and the chat record is already gone by the time this runs.
if not _holds_no_user_files(target, _sandbox_name(session_id)):
return False
shutil.rmtree(target, ignore_errors = True)
@@ -9043,48 +8367,39 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
return False
-# edit_file
-#
-# Without it, changing a file means a whole-file `cat > f <<'EOF'` or
-# open(...).write(...): ~7.7k output tokens to rewrite a 500-line file that a
-# patch does in ~45, and anything the model fails to retype is lost.
-#
-# Exact-string replacement, not a unified diff: models corrupt @@ hunk headers
-# far more often than they mis-copy a literal snippet, and a bad header patches
-# the wrong place instead of failing. A missing or non-unique old_string is a
-# hard error naming the match count, so the retry is "add context".
+# edit_file. Without it, changing a file means a whole-file `cat > f <<'EOF'` or open(...).write(...): ~7.7k output
+# tokens to rewrite a 500-line file that a patch does in ~45, and anything the model fails to retype is lost.
+# Exact-string replacement, not a unified diff: models corrupt @@ hunk headers far more often than they mis-copy a
+# literal snippet, and a bad header patches the wrong place instead of failing. A missing or non-unique old_string is
+# a hard error naming the match count, so the retry is add context.
# The whole text is read to find the match, so the cap is on the file.
_EDIT_FILE_MAX_BYTES = _env_int("UNSLOTH_STUDIO_EDIT_FILE_MAX_BYTES", 16 * 1024 * 1024)
-# Bounded receipt: lines alone are no bound, since one line of minified JS can
-# be the whole file, so characters are capped per line and over the receipt.
+# Bounded receipt: lines alone are no bound, since one line of minified JS can be the whole file, so characters are
+# capped per line and over the receipt.
_EDIT_FILE_DIFF_LINES = 40
_EDIT_FILE_DIFF_LINE_CHARS = 200
_EDIT_FILE_DIFF_CHARS = 4000
-# Lines either side of the first change that are handed to difflib. Diffing the
-# whole file would split it into one str per line: 8M of them at the 16MB cap.
+# Lines either side of the first change that are handed to difflib. Diffing the whole file would split it into one str
+# per line: 8M of them at the 16MB cap.
_EDIT_FILE_DIFF_WINDOW_LINES = 120
def _edit_file_resolve(
raw_path: str, session_id: "str | None", disable_sandbox: bool
) -> "tuple[str | None, str]":
- """Resolve the model's path the way python/terminal resolve theirs.
-
- Same rules as the sitecustomize shim: a code-interpreter habit prefix
- (/mnt/data, /workspace, ...) keeps its suffix under the workdir, everything
- else is relative to it. Containment is checked on the realpath, so a symlink
- planted inside cannot reach out.
- """
+ """Resolve the model's path the way python/terminal resolve theirs. Same rules as the
+ sitecustomize shim: a code-interpreter habit prefix (/mnt/data, /workspace, ...) keeps its
+ suffix under the workdir, everything else is relative to it. Containment is checked on the
+ realpath, so a symlink planted inside cannot reach out."""
raw = (raw_path or "").strip()
if not raw:
return None, "Error: 'path' is required."
workdir = _get_workdir(session_id)
candidate = raw
- # An absolute path already inside the workdir is a real path, not a habit
- # one: a project rooted at /workspace/repo would otherwise have its own
- # prefix stripped and be rejoined onto itself.
+ # An absolute path already inside the workdir is a real path, not a habit one: a project rooted at /workspace/repo
+ # would otherwise have its own prefix stripped and be rejoined onto itself.
already_inside = os.path.isabs(raw) and not _is_outside_workdir(raw, workdir)
if not disable_sandbox and not already_inside:
for prefix in _MISSING_PATH_PREFIXES:
@@ -9098,8 +8413,8 @@ def _edit_file_resolve(
target = os.path.realpath(target)
except (OSError, ValueError):
return None, f"Error: cannot resolve path '{raw}'."
- # Full access runs python/terminal unsandboxed already; holding this one
- # tool to the workdir would just push the model back to cat.
+ # Full access runs python/terminal unsandboxed already; holding this one tool to the workdir would just push the
+ # model back to cat.
if not disable_sandbox and _is_outside_workdir(target, workdir):
return None, (
f"Error: '{raw}' is outside this conversation's working directory, "
@@ -9110,13 +8425,10 @@ def _edit_file_resolve(
def _edit_file_decode(data: bytes, path: str) -> "tuple[str, str, str, str]":
- """Decode file bytes into (text, newline, bom, error).
-
- ``text`` is normalized to \\n so an old_string with plain newlines still
- matches a CRLF file; matching raw bytes would fail every edit of a
- Windows-authored source. The original convention is returned so the write
- puts it back instead of converting every line ending in the file.
- """
+ """Decode file bytes into (text, newline, bom, error). ``text`` is normalized to \\n so an
+ old_string with plain newlines still matches a CRLF file; matching raw bytes would fail every
+ edit of a Windows-authored source. The original convention is returned so the write puts it
+ back instead of converting every line ending in the file."""
bom = ""
if data.startswith(codecs.BOM_UTF8):
bom = codecs.BOM_UTF8.decode("utf-8")
@@ -9128,8 +8440,8 @@ def _edit_file_decode(data: bytes, path: str) -> "tuple[str, str, str, str]":
if "\x00" in text:
return "", "\n", "", f"Error: '{os.path.basename(path)}' is a binary file."
crlf = text.count("\r\n")
- # Judged against the total so a file with a couple of stray CRs is still
- # written back as LF; a mixed file is normalized to whichever dominates.
+ # Judged against the total so a file with a couple of stray CRs is still written back as LF; a mixed file is
+ # normalized to whichever dominates.
newline = "\r\n" if crlf and crlf * 2 >= text.count("\n") else "\n"
return text.replace("\r\n", "\n"), newline, bom, ""
@@ -9145,14 +8457,12 @@ def _edit_file_write(
) -> str:
"""Write the new content, replacing the file atomically.
- Sibling temp file then rename: an interrupted write must not leave a source
- file half-replaced. The mode is carried over so an edit keeps the
- executable bit.
+ Sibling temp file then rename: an interrupted write must not leave a source file half-replaced.
+ The mode is carried over so an edit keeps the executable bit.
- ``expect`` are the bytes the edit was computed from, compared again here so
- a file another chat rewrote meanwhile is not reverted to this call's stale
- copy. ``workdir`` re-checks containment just before the rename, so a parent
- swapped for a symlink after the path was resolved is caught.
+ ``expect`` are the bytes the edit was computed from, compared again here so a file another chat
+ rewrote meanwhile is not reverted to this call's stale copy. ``workdir`` re-checks containment
+ just before the rename, so a parent swapped for a symlink after the path was resolved is caught.
"""
payload = (bom + text.replace("\n", newline)).encode("utf-8")
directory = os.path.dirname(path) or "."
@@ -9243,23 +8553,19 @@ def _edit_file_receipt(
count: int,
change_at: int = 0,
) -> str:
- """A bounded unified diff of what changed.
-
- Line-numbered so the model can confirm the edit landed where it meant. Two
- separate bounds, because either alone leaks: difflib sees only a window
- around the first change, and the generator is consumed lazily.
- """
+ """A bounded unified diff of what changed. Line-numbered so the model can confirm the edit
+ landed where it meant. Two separate bounds, because either alone leaks: difflib sees only a
+ window around the first change, and the generator is consumed lazily."""
import difflib
import itertools
window_start, window_end = _edit_file_line_window(
before, change_at, _EDIT_FILE_DIFF_WINDOW_LINES
)
- # The window is cut out of the old text and the replacement replayed on it,
- # rather than a second window of the same LINE COUNT cut out of the new one.
- # An edit that adds or removes lines shifts everything after it, so equal
- # windows end on different text and difflib calls that a second hunk --
- # deletions the edit never made, a window away from anything that changed.
+ # The window is cut out of the old text and the replacement replayed on it, rather than a second window of the
+ # same LINE COUNT cut out of the new one. An edit that adds or removes lines shifts everything after it, so equal
+ # windows end on different text and difflib calls that a second hunk: deletions the edit never made, a window away
+ # from anything that changed.
window_end = max(window_end, change_at + len(old)) # keep the match whole
before_window = before[window_start:window_end]
# Right in both modes: without replace_all the file held exactly one match.
@@ -9288,8 +8594,8 @@ def _edit_file_receipt(
else f"{line[:_EDIT_FILE_DIFF_LINE_CHARS]}... (+{len(line) - _EDIT_FILE_DIFF_LINE_CHARS} chars)"
for line in diff
]
- # difflib numbered the hunks against the window, so shift them back to real
- # file lines; line 3 of a 9000-line file is worse than no numbers at all.
+ # difflib numbered the hunks against the window, so shift them back to real file lines; line 3 of a 9000-line file
+ # is worse than no numbers at all.
if first_line > 1:
diff = [_edit_file_shift_hunk(line, first_line - 1) for line in diff]
body = "\n".join(diff)
@@ -9299,11 +8605,9 @@ def _edit_file_receipt(
def _edit_file_replace_all(value: object) -> "bool | None":
- """Read replace_all strictly; None means "not a boolean".
-
- bool("false") is True, and models do emit the JSON string. Coercing it that
- way turns the multi-match guard off and rewrites every occurrence.
- """
+ """Read replace_all strictly; None means not a boolean. bool("false") is True, and models do
+ emit the JSON string. Coercing it that way turns the multi-match guard off and rewrites every
+ occurrence."""
if value is None:
return False
if isinstance(value, bool):
@@ -9328,14 +8632,14 @@ def _edit_file_create(
) -> str:
"""Handle the empty-old_string case: create a file, never clobber one.
- A zero-byte file is writable here on purpose: refusing every existing target
- would strand the model, since an empty old_string would be refused and no
- other old_string can match an empty file.
+ A zero-byte file is writable here on purpose: refusing every existing target would strand the
+ model, since an empty old_string would be refused and no other old_string can match an empty
+ file.
- The absent case is created with O_EXCL rather than checked and then written:
- two chats sharing a workspace can both pass a lexists() check and the later
- rename drops the earlier file. O_EXCL also gives the new file the usual
- umask-derived mode, where a mkstemp temp file would leave it 0600.
+ The absent case is created with O_EXCL rather than checked and then written: two chats sharing a
+ workspace can both pass a lexists() check and the later rename drops the earlier file. O_EXCL
+ also gives the new file the usual umask-derived mode, where a mkstemp temp file would leave it
+ 0600.
"""
payload = (new.replace("\n", newline)).encode("utf-8")
if not os.path.lexists(target):
@@ -9365,10 +8669,9 @@ def _edit_file_create(
with os.fdopen(fd, "wb") as fh:
fh.write(payload)
except OSError as exc:
- # ENOSPC partway through leaves the bytes that fit -- a file
- # truncated mid-token -- and the retry the message asks for cannot
- # clear it, since an empty old_string refuses a non-empty target.
- # Removing the inode puts the retry back on the create path.
+ # ENOSPC partway through leaves the bytes that fit (a file truncated mid-token) and the retry the message
+ # asks for cannot clear it, since an empty old_string refuses a non-empty target. Removing the inode puts
+ # the retry back on the create path.
with contextlib.suppress(OSError):
os.remove(target)
return f"Error: cannot write '{name}': {exc}"
@@ -9377,9 +8680,8 @@ def _edit_file_create(
st = os.stat(target)
except OSError:
st = None
- # Refused rather than measured: a FIFO reports st_size 0, so it fell into
- # the zero-byte branch below, whose write reopens the target -- and open()
- # on a FIFO with no writer blocks for ever.
+ # Refused rather than measured: a FIFO reports st_size 0, so it fell into the zero-byte branch below, whose write
+ # reopens the target, and open() on a FIFO with no writer blocks for ever.
if st is None or not S_ISREG(st.st_mode) or st.st_size:
return (
f"Error: '{name}' already exists. An empty 'old_string' only "
@@ -9393,30 +8695,29 @@ def _edit_file_create(
return f"Created {name} ({new.count(chr(10)) + 1 if new else 0} lines)"
-# Each entry costs a full `count` scan of the file plus a search pass, and the file may be
-# up to 16 MiB, so the work is entries x size. Unbounded, a model-generated batch of a few
-# thousand one-line edits turns a single call into gigabytes of repeated scanning and holds
-# the tool worker for minutes. High enough that no honest refactor hits it, low enough that
-# the worst case stays bounded.
+# Each entry costs a full `count` scan of the file plus a search pass, and the file may be up to 16 MiB, so the work
+# is entries x size. Unbounded, a model-generated batch of a few thousand one-line edits turns a single call into
+# gigabytes of repeated scanning and holds the tool worker for minutes. High enough that no honest refactor hits it,
+# low enough that the worst case stays bounded.
_MAX_EDITS_PER_CALL = 100
-# And a bound on the matches ONE replace_all may expand into. The entry limit above caps
-# how many patterns are searched, not how many places any of them hits, so a single
-# pathological entry can still swamp the worker on its own.
+# And a bound on the matches ONE replace_all may expand into. The entry limit above caps how many patterns are
+# searched, not how many places any of them hits, so a single pathological entry can still swamp the worker on its
+# own.
_MAX_MATCH_SPANS = 10_000
def _edit_file_parse_edits(raw) -> "tuple[list[tuple[str, str, bool]], str]":
"""Validate the `edits` array into `(old, new, replace_all)` triples.
- Every string is normalized the way the file is, so a snippet copied out of `cat`
- output with plain newlines still matches a Windows-authored file.
+ Every string is normalized the way the file is, so a snippet copied out of `cat` output with
+ plain newlines still matches a Windows-authored file.
- The surrogate check is per entry and up front, before anything is written: a
- truncated emoji escape ("\\ud83d") survives `json.loads` as a lone surrogate that
- cannot be encoded, and the UnicodeEncodeError the write raises is swallowed upstream
- into "Unknown tool: edit_file" -- the one answer that sends the model back to the
- whole-file rewrite. `old_string` needs no check, being only ever compared.
+ The surrogate check is per entry and up front, before anything is written: a truncated emoji
+ escape survives `json.loads` as a lone surrogate that cannot be encoded, and the
+ UnicodeEncodeError the write raises is swallowed upstream into Unknown tool: edit_file, the one
+ answer that sends the model back to the whole-file rewrite. `old_string` needs no check, being
+ only ever compared.
"""
if not isinstance(raw, list) or not raw:
return [], (
@@ -9435,7 +8736,7 @@ def _edit_file_parse_edits(raw) -> "tuple[list[tuple[str, str, bool]], str]":
return [], f"Error: edit {index} is not an object with old_string/new_string."
old = entry.get("old_string")
new = entry.get("new_string")
- # Checked, not coerced: str(None) would write the literal "None" into a file.
+ # Checked, not coerced: str(None) would write the literal None into a file.
if not isinstance(old, str) or not isinstance(new, str):
return [], (
f"Error: edit {index} needs 'old_string' and 'new_string' to both be strings."
@@ -9460,24 +8761,23 @@ def _edit_file_apply_all(
) -> "tuple[str, int, str, str, int, str]":
"""Apply every edit against the ORIGINAL text, or none of them.
- Matched against `before` rather than against the running result, which is the rule
- llama.cpp's own `edit_file` states and the only one a model can reason about: it
- copied each `old_string` out of the file it read, so an entry that silently matched
- the output of an earlier entry would land somewhere it never saw.
+ Matched against `before` rather than against the running result, which is the rule llama.cpp's
+ own `edit_file` states and the only one a model can reason about: it copied each `old_string`
+ out of the file it read, so an entry that silently matched the output of an earlier entry would
+ land somewhere it never saw.
- Spans are resolved for all entries first and checked for overlap, then applied right
- to left so the earlier offsets stay valid. Every failure returns before a single byte
- is written -- a partly applied batch is the one outcome worse than a refused one,
- because the model cannot tell which half landed.
+ Spans are resolved for all entries first and checked for overlap, then applied right to left so
+ the earlier offsets stay valid. Every failure returns before a single byte is written: a partly
+ applied batch is the one outcome worse than a refused one, because the model cannot tell which
+ half landed.
"""
spans: list[tuple[int, int, str, int]] = []
for index, (old, new, replace_all) in enumerate(edits, 1):
if not old:
- # Defence in depth, not a live path: `_edit_file` rejects every empty
- # `old_string` before calling this. It matters because the failure mode if
- # that guard ever moves is not a wrong answer but a HANG -- `find(old, start
- # + len(old))` cannot advance on a zero-length pattern, and the worker keeps
- # a core after its caller has timed out.
+ # Defence in depth, not a live path: `_edit_file` rejects every empty `old_string` before calling this. It
+ # matters because the failure mode if that guard ever moves is not a wrong answer but a HANG: `find(old,
+ # start + len(old))` cannot advance on a zero-length pattern, and the worker keeps a core after its caller
+ # has timed out.
return (
"",
0,
@@ -9516,10 +8816,9 @@ def _edit_file_apply_all(
f"entry to change all {count}."
),
)
- # One entry needs no spans at all. There is nothing to overlap with, so the whole
- # reason to enumerate matches disappears and `str.replace` does the work in linear
- # space. Enumerating cost about 16 million tuples plus a sort on a 16 MiB file of a
- # one-character pattern -- over a gigabyte for an edit the single-edit spelling had
+ # One entry needs no spans at all. There is nothing to overlap with, so the whole reason to enumerate matches
+ # disappears and `str.replace` does the work in linear space. Enumerating cost about 16 million tuples plus a
+ # sort on a 16 MiB file of a one-character pattern, over a gigabyte for an edit the single-edit spelling had
# always done cheaply. The batch limit does not help here: one entry is enough.
if replace_all and len(edits) == 1:
after = before.replace(old, new)
@@ -9560,10 +8859,9 @@ def _edit_file_apply_all(
"two edits cannot cover the same text. Combine them into one entry."
),
)
- # One pass with a cursor, not a slice-and-concat per span. Rebuilding the whole string
- # for every replacement is quadratic, and `replace_all` over a large file is exactly
- # where that bites: a file with tens of thousands of matches took 10s where the single
- # `str.replace` it succeeded took well under one.
+ # One pass with a cursor, not a slice-and-concat per span. Rebuilding the whole string for every replacement is
+ # quadratic, and `replace_all` over a large file is exactly where that bites: a file with tens of thousands of
+ # matches took 10s where the single `str.replace` it succeeded took well under one.
parts: list[str] = []
cursor = 0
for start, end, new, _ in spans:
@@ -9591,10 +8889,8 @@ def _edit_file(
if error:
return error
name = os.path.basename(target)
- # Decided before the no-op check below, not after: both strings empty is the
- # documented way to create __init__.py or .gitkeep, and read as "identical,
- # nothing to change" it was refused, leaving no way to write a zero-byte
- # file.
+ # Decided before the no-op check below, not after: both strings empty is the documented way to create __init__.py
+ # or .gitkeep, and read as identical, nothing to change it was refused, leaving no way to write a zero-byte file.
if not edits[0][0]:
if len(edits) > 1:
return (
@@ -9628,9 +8924,8 @@ def _edit_file(
return f"Error: cannot read '{name}': {exc}"
if os.path.isdir(target):
return f"Error: '{name}' is a directory."
- # A FIFO reads forever and a character device such as /dev/zero reads until
- # memory runs out. Neither reports a useful st_size, and this path carries
- # no timeout or cancel event, so the turn cannot be recovered.
+ # A FIFO reads forever and a character device such as /dev/zero reads until memory runs out. Neither reports a
+ # useful st_size, and this path carries no timeout or cancel event, so the turn cannot be recovered.
if not S_ISREG(st.st_mode):
return f"Error: '{name}' is not a regular file."
if st.st_size > _EDIT_FILE_MAX_BYTES:
@@ -9716,17 +9011,14 @@ def web_search_tool_with_images() -> dict:
def _build_sandbox_paths_note() -> str:
- """Platform and working-directory note, on BOTH tool descriptions.
-
- Models habitually write to /mnt/data, a ChatGPT code-interpreter path that
- does not exist here, so the POSIX text names it. Naming only POSIX paths on
- Windows reads as "you are on Linux" and models then refuse to invoke Windows
- programs that are in fact available, so that text says where the code runs
- instead: without it a model assumes the pipe is its only output and declines
- to open a window it believes nobody can see.
- """
- # Without this a model assumes its output vanished into a scratch dir and
- # says so, which reads as "the file was not really created".
+ """Platform and working-directory note, on BOTH tool descriptions. Models habitually write to
+ /mnt/data, a ChatGPT code-interpreter path that does not exist here, so the POSIX text names
+ it. Naming only POSIX paths on Windows reads as you are on Linux and models then refuse to
+ invoke Windows programs that are in fact available, so that text says where the code runs
+ instead: without it a model assumes the pipe is its only output and declines to open a window
+ it believes nobody can see."""
+ # Without this a model assumes its output vanished into a scratch dir and says so, which reads as the file was not
+ # really created.
created = (
" Any file you create here is kept and shown to the user with a download "
"link, so name the files you created in your reply -- by file name only, "
@@ -9745,34 +9037,28 @@ def _build_sandbox_paths_note() -> str:
)
-# Full access (permission_mode='full') edits, applied to the sandboxed text
-# rather than writing a second copy of it. Everything the two modes share -- the
-# relative-path advice, the persisted workdir, the download-link note -- is prose
-# that gets tuned over time, and a parallel copy would drift out of sync in
-# silence. Only the claims the sandbox makes true are touched. A rewording that
-# stops one of these matching is caught by test_full_access_tool_prompt.py, which
+# Full access (permission_mode='full') edits, applied to the sandboxed text rather than writing a second copy of it.
+# Everything the two modes share (the relative-path advice, the persisted workdir, the download-link note) is prose
+# that gets tuned over time, and a parallel copy would drift out of sync in silence. Only the claims the sandbox makes
+# true are touched. A rewording that stops one of these matching is caught by test_full_access_tool_prompt.py, which
# asserts the sandboxed markers are gone from the result on both platforms.
_FULL_ACCESS_SUBSTITUTIONS = (
- # The only sentence in the python description that names the sandbox. Just
- # dropped, not reworded: where the code runs is said once, by the paths note
- # below, which both tools carry.
+ # The only sentence in the python description that names the sandbox. Just dropped, not reworded: where the code
+ # runs is said once, by the paths note below, which both tools carry.
("Execute Python code in a sandbox and", "Execute Python code and"),
- # POSIX: a blanket denial is wrong with the sandbox off, and so is a blanket
- # promise. POSIX has no sentence saying where the code runs, so it is added
- # here; Windows already has one.
+ # POSIX: a blanket denial is wrong with the sandbox off, and so is a blanket promise. POSIX has no sentence saying
+ # where the code runs, so it is added here; Windows already has one.
(
"; absolute paths like /mnt/data or /tmp/outputs do not exist.",
". This runs wherever Unsloth Studio is running, which may be a remote host "
"or a container with only some paths mounted.{clause}",
),
- # Windows already says where the code runs and never denies absolute paths,
- # so there is nothing false to remove; state the capability instead. "the
- # user's own machine" is narrowed at the same time: --secure and -H 0.0.0.0
- # are documented remote modes (README), and the tools run on the host serving
- # Unsloth, which is then not the device the user is looking at.
- # _TERMINAL_SHELL_NOTE is carried through unchanged except here: its Git Bash
- # branch promises a detached program's window appears on the user's desktop,
- # which only holds while Unsloth is local.
+ # Windows already says where the code runs and never denies absolute paths, so there is nothing false to remove;
+ # state the capability instead. the user's own machine is narrowed at the same time: --secure and -H 0.0.0.0 are
+ # documented remote modes (README), and the tools run on the host serving Unsloth, which is then not the device
+ # the user is looking at.
+ # _TERMINAL_SHELL_NOTE is carried through unchanged except here: its Git Bash branch promises a detached program's
+ # window appears on the user's desktop, which only holds while Unsloth is local.
(
"opens a window on the user's desktop.",
"opens a window on that machine's desktop, which the user sees only if "
@@ -9787,44 +9073,24 @@ _FULL_ACCESS_SUBSTITUTIONS = (
)
-# What "the sandbox is off" actually means for paths, per tool. Shared by both
-# platform substitutions: the split is the shim, not the OS. _build_bypass_env
-# keeps _SANDBOX_SITE_DIR on PYTHONPATH for BOTH tools, so sitecustomize.py still
+# What the sandbox is off actually means for paths, per tool. Shared by both platform substitutions: the split is the
+# shim, not the OS. _build_bypass_env keeps _SANDBOX_SITE_DIR on PYTHONPATH for BOTH tools, so sitecustomize.py still
# loads, and being a CPython startup hook is what separates them. Measured:
-#
-# python, parent exists -> writes the real absolute path
-# python, absent prefix -> _remap keeps the SUFFIX under the workdir
-# (/mnt/data/reports/out.csv -> ./reports/out.csv)
-# and returns before the generic fallback, so no
-# basename collapse and no anti-clobber
-# python, other missing parent -> the fallback keeps only the base name, and
-# raises when an UNRELATED file holds it; the
-# .unsloth_sandbox_remap.json sidecar lets a rewrite
-# of the same invented path re-serve its own target
-# python, prefix present -> a real /mnt/data mount is never shadowed, so a
-# prefix is special only while absent, which is why
-# the clause names one inside a conditional and
-# never categorically
-# API coverage differs per rewrite -> _makedirs calls _remap only, so the
-# generic fallback is open/io.open/os.open alone and
-# os.makedirs under a missing parent OUTSIDE the
-# convention prefixes targets the REAL host path.
-# Inside them _remap still rewrites, measured:
-# makedirs("/mnt/data/reports") created ./reports and
-# raised nothing, so the clause has to name the prefixes
-# rather than say "not rewritten at all" -- a model told
-# otherwise reports the host path for a directory that
-# is in its working directory.
-# An attempt, not an outcome: measured
-# under this shim, makedirs into a mode-500 directory
-# raised PermissionError and created nothing, neither
-# on the host nor in the workdir, so the clause must
-# not promise creation any more than it promises a
-# prefix is absent. os.rename and os.symlink raise, while
-# shutil.copy writes the rewritten file through open
-# and then raises in copymode
-# terminal -> the shell's own rules, except for Python it
-# launches, which is patched like the python tool
+# python, parent exists -> writes the real absolute path.
+# python, absent prefix -> _remap keeps the SUFFIX under the workdir (/mnt/data/reports/out.csv -> ./reports/out.csv)
+# and returns before the generic fallback, so no basename collapse and no anti-clobber.
+# python, other missing parent -> the fallback keeps only the base name, and raises when an UNRELATED file holds it;
+# the .unsloth_sandbox_remap.json sidecar lets a rewrite of the same invented path re-serve its own target.
+# python, prefix present -> a real /mnt/data mount is never shadowed, so a prefix is special only while absent, which
+# is why the clause names one inside a conditional and never categorically.
+# API coverage differs per rewrite -> _makedirs calls _remap only, so the generic fallback is open/io.open/os.open
+# alone and os.makedirs under a missing parent OUTSIDE the convention prefixes targets the REAL host path. Inside them
+# _remap still rewrites: makedirs("/mnt/data/reports") created ./reports and raised nothing, so the clause has to name
+# the prefixes rather than say not rewritten at all. An attempt, not an outcome: makedirs into a mode-500 directory
+# raised PermissionError and created nothing, neither on the host nor in the workdir, so the clause must not promise
+# creation any more than it promises a prefix is absent. os.rename and os.symlink raise, while shutil.copy writes the
+# rewritten file through open and then raises in copymode.
+# terminal -> the shell's own rules, except for Python it launches, which is patched like the python tool.
_FULL_ACCESS_CLAUSE = {
"python": (
" The code sandbox is disabled, so absolute paths under a directory that "
@@ -9857,14 +9123,13 @@ _FULL_ACCESS_CLAUSE = {
def _to_full_access(description: str, tool_name: str) -> str:
"""Rewrite a sandboxed tool description for Full access.
- Under bypass_permissions the loops pass disable_sandbox=True:
- _build_bypass_env / _bypass_preexec skip the static analysis, the command
- blocklist and the rlimits, so the host filesystem really is reachable.
- Handing a model the sandboxed text in that mode makes it answer "I am
- sandboxed and cannot see your files" to a question one tool call would have
- answered. Untouched clauses are the ones still true in both modes: the
- workdir is the per-session dir either way (_build_bypass_env repoints HOME at
- it and TMPDIR / TEMP / TMP just inside it), and so is the download-link note.
+ Under bypass_permissions the loops pass disable_sandbox=True: _build_bypass_env /
+ _bypass_preexec skip the static analysis, the command blocklist and the rlimits, so the host
+ filesystem really is reachable. Handing a model the sandboxed text in that mode makes it answer
+ I am sandboxed and cannot see your files to a question one tool call would have answered.
+ Untouched clauses are the ones still true in both modes: the workdir is the per-session dir
+ either way (_build_bypass_env repoints HOME at it and TMPDIR / TEMP / TMP just inside it), and
+ so is the download-link note.
"""
clause = _FULL_ACCESS_CLAUSE[tool_name]
for sandboxed, full_access in _FULL_ACCESS_SUBSTITUTIONS:
@@ -9875,14 +9140,13 @@ def _to_full_access(description: str, tool_name: str) -> str:
def _build_terminal_shell_note() -> str:
"""Shell-specific note, on the TERMINAL description only.
- Which shell runs is read from the resolver, not assumed: telling a model it
- has bash on a host where _get_shell_cmd fell back to cmd reintroduces the
- multi-line half-execution this note exists to prevent. It stays off the
- python description because none of it applies to the python sandbox, and
- naming a shell there invites subprocess/os.system as a way past the terminal
- blocklist. No program is named either: powershell/pwsh are on that blocklist
- and `cmd /c start` is not, so recommending one hands back a hard block and
- recommending the other advertises the gap.
+ Which shell runs is read from the resolver, not assumed: telling a model it has bash on a host
+ where _get_shell_cmd fell back to cmd reintroduces the multi-line half-execution this note
+ exists to prevent. It stays off the python description because none of it applies to the python
+ sandbox, and naming a shell there invites subprocess/os.system as a way past the terminal
+ blocklist. No program is named either: powershell/pwsh are on that blocklist and `cmd /c start`
+ is not, so recommending one hands back a hard block and recommending the other advertises the
+ gap.
"""
if sys.platform != "win32":
return ""
@@ -9940,11 +9204,10 @@ TERMINAL_TOOL = {
},
}
-# Full access runs these two without the sandbox, so it gets its own pair of
-# schemas rather than a per-request rebuild: the descriptions are
-# platform-derived constants either way. The sandboxed pair stays the module
-# default, so every existing importer keeps the safe wording. The shell note is
-# unaffected by the substitutions and carries through as-is.
+# Full access runs these two without the sandbox, so it gets its own pair of schemas rather than a per-request
+# rebuild: the descriptions are platform-derived constants either way. The sandboxed pair stays the module default, so
+# every existing importer keeps the safe wording. The shell note is unaffected by the substitutions and carries
+# through as-is.
PYTHON_TOOL_FULL_ACCESS = {
"type": "function",
"function": {
@@ -9969,14 +9232,11 @@ _FULL_ACCESS_TOOL_BY_NAME = {
def apply_full_access_tool_descriptions(tools: list[dict]) -> list[dict]:
- """Swap python/terminal/edit_file for their Full access schemas.
-
- Only the sandboxed built-ins are touched; web_search, render_html,
- search_knowledge_base and MCP tools are passed through untouched, and a list
- without any of them is returned as-is so callers can apply this
- unconditionally. The input list is never mutated -- ALL_TOOLS entries are
- module globals shared across requests.
- """
+ """Swap python/terminal/edit_file for their Full access schemas. Only the sandboxed built-ins
+ are touched; web_search, render_html, search_knowledge_base and MCP tools are passed through
+ untouched, and a list without any of them is returned as-is so callers can apply this
+ unconditionally. The input list is never mutated: ALL_TOOLS entries are module globals shared
+ across requests."""
if not tools:
return tools
swapped = False
@@ -9996,8 +9256,8 @@ EDIT_FILE_TOOL = {
"type": "function",
"function": {
"name": "edit_file",
- # The description does the steering: given the tool but no preference,
- # a model keeps writing heredocs because that is what it was trained on.
+ # The description does the steering: given the tool but no preference, a model keeps writing heredocs because
+ # that is what it was trained on.
"description": (
"Change a file by replacing exact strings. Prefer this over rewriting a "
"file with python or a shell heredoc: it sends only what changes. Copy each "
@@ -10055,9 +9315,9 @@ EDIT_FILE_TOOL = {
},
}
-# Appended, not substituted: the sandboxed text never claims absolute paths
-# fail, so there is nothing false to rewrite, only a capability to add. A model
-# that thinks it cannot reach a real checkout falls back to the whole-file rewrite.
+# Appended, not substituted: the sandboxed text never claims absolute paths fail, so there is nothing false to
+# rewrite, only a capability to add. A model that thinks it cannot reach a real checkout falls back to the whole-file
+# rewrite.
_EDIT_FILE_FULL_ACCESS_CLAUSE = (
" The code sandbox is disabled, so an absolute path resolves as written and "
"edits the real file there, anywhere the Unsloth Studio process can reach."
@@ -10101,8 +9361,8 @@ RENDER_HTML_TOOL = {
},
}
-# Duplicated (not imported from core.rag.tool) so the registry never pulls in
-# the RAG stack; dispatch imports it lazily.
+# Duplicated (not imported from core.rag.tool) so the registry never pulls in the RAG stack; dispatch imports it
+# lazily.
SEARCH_KNOWLEDGE_BASE_TOOL = {
"type": "function",
"function": {
@@ -10166,16 +9426,12 @@ ALL_TOOLS = [
SEARCH_CONVERSATION_TOOL,
]
-# Deliberately an ordinary tool with an ordinary result. Studio runs three tool loops -- one for
-# llama.cpp, one for safetensors, one for external providers -- and only a plain result behaves
-# the same in all three. The client starts the run off the tool events every loop already
-# publishes, so nothing here needs to know a research run exists.
-#
+# Deliberately an ordinary tool with an ordinary result. Studio runs three tool loops (llama.cpp, safetensors,
+# external providers) and only a plain result behaves the same in all three. The client starts the run off the tool
+# events every loop already publishes, so nothing here needs to know a research run exists.
# Never in ALL_TOOLS: it is offered only when the composer armed research.
-#
-# The client keys the handoff on this opening rather than on tool_end alone: a denied, skipped,
-# truncated or budget-exhausted call is closed by the same event, and only the result says the
-# call actually ran.
+# The client keys the handoff on this opening rather than on tool_end alone: a denied, skipped, truncated or
+# budget-exhausted call is closed by the same event, and only the result says the call actually ran.
DEEP_RESEARCH_STARTED_MARKER = "Deep Research has started"
DEEP_RESEARCH_STARTED = (
f"{DEEP_RESEARCH_STARTED_MARKER} on that question. Reply with one short sentence saying you "
@@ -10219,14 +9475,14 @@ DEEP_RESEARCH_TOOL = {
}
-# OpenAI's function.name regex; MCP names that violate it would 400 the whole
-# request, so validate up front and skip with a warning.
+# OpenAI's function.name regex; MCP names that violate it would 400 the whole request, so validate up front and skip
+# with a warning.
_OPENAI_FN_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
def _mcp_tool_model_visible(tool: dict) -> bool:
- """False for MCP Apps tools marked app-only (_meta.ui.visibility without
- "model"): those exist for a server-rendered widget to call, not the LLM."""
+ """False for MCP Apps tools marked app-only (_meta.ui.visibility without "model"): those exist
+ for a server-rendered widget to call, not the LLM."""
# model_dump() gives "meta", the wire "_meta"; unrelated keys in one must not mask the other.
for key in ("meta", "_meta"):
meta = tool.get(key)
@@ -10292,15 +9548,15 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:
def cached_mcp_tools() -> tuple[list[dict], bool]:
"""The MCP schemas already in cache, and whether that is the whole set.
- get_enabled_mcp_tools() renders the same servers, but reaches the network to do it: it
- spawns stdio servers, blocks for a probe timeout on one that is down, and writes cache and
- cool-off state. A background token count must not do any of that, so this reads only what
- those probes have already filled in.
+ get_enabled_mcp_tools() renders the same servers, but reaches the network to do it: it spawns
+ stdio servers, blocks for a probe timeout on one that is down, and writes cache and cool-off
+ state. A background token count must not do any of that, so this reads only what those probes
+ have already filled in.
- ``complete`` is False when an enabled server has nothing cached and is not in its
- post-failure cool-off, meaning a completion would probe it and render schemas this cannot
- price. A cool-off server renders nothing on the completion path either, so skipping that one
- is exact rather than short. Callers that must not undercount should decline on False.
+ ``complete`` is False when an enabled server has nothing cached and is not in its post-failure
+ cool-off, meaning a completion would probe it and render schemas this cannot price. A cool-off
+ server renders nothing on the completion path either, so skipping that one is exact rather than
+ short. Callers that must not undercount should decline on False.
"""
servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]
if not stdio_mcp_enabled():
@@ -10329,9 +9585,8 @@ async def get_enabled_mcp_tools() -> list[dict]:
if not servers:
return []
- # Skip servers still in their post-failure cool-off, otherwise a down
- # server gets re-probed -- and blocks the send for the full timeout -- on
- # every message.
+ # Skip servers still in their post-failure cool-off, otherwise a down server gets re-probed, and blocks the send
+ # for the full timeout, on every message.
uncached = [
s for s in servers if get_cached_tools(s["id"]) is None and not in_failure_cooloff(s["id"])
]
@@ -10348,8 +9603,8 @@ async def get_enabled_mcp_tools() -> list[dict]:
),
return_exceptions = True,
)
- # Keep this re-read on-loop so an edit cannot invalidate between it and
- # the cache writes below. Drop results for changed or removed servers.
+ # Keep this re-read on-loop so an edit cannot invalidate between it and the cache writes below. Drop results
+ # for changed or removed servers.
current = {s["id"]: s for s in mcp_servers_db.list_servers()}
for server, payload in zip(uncached, results):
fresh = current.get(server["id"])
@@ -10364,8 +9619,8 @@ async def get_enabled_mcp_tools() -> list[dict]:
server.get("url"),
payload,
)
- # Failures aren't cached, but record one so a down server
- # isn't re-probed every send during the cool-off.
+ # Failures aren't cached, but record one so a down server isn't re-probed every send during the
+ # cool-off.
record_probe_failure(server["id"], bool(fresh.get("use_oauth")))
continue
cache_tools(server["id"], payload)
@@ -10421,36 +9676,29 @@ def execute_tool(
) -> str:
"""Execute a tool by name with the given arguments; returns a string.
- ``timeout``: int seconds, ``None`` = no limit, unset = ``_EXEC_TIMEOUT``.
- ``session_id``: optional ID for per-conversation sandbox isolation.
- ``thread_id``: optional conversation ID; scopes stateful MCP stdio sessions
- per thread (session_id alone can be shared project-wide).
- ``rag_scope``: hidden per-request RAG context the model never sees; consumed
- by ``search_knowledge_base``.
- ``disable_sandbox``: Bypass Permissions; run python/terminal without the
- safety checks, blocklist, or resource caps (secrets still stripped). Only
- affects local code tools; web_search / MCP are unchanged.
- ``output_callback``: optional ``callable(str)`` invoked with incremental
- stdout/stderr chunks while python/terminal executions run (UI live
- output). Purely observational: the returned result string is identical
- with or without it. Tools without incremental output ignore it.
- ``website_policy``: hidden server-validated domain limits for web_search.
+ ``timeout``: int seconds, ``None`` = no limit, unset = ``_EXEC_TIMEOUT``. ``session_id``:
+ optional ID for per-conversation sandbox isolation. ``thread_id``: optional conversation ID;
+ scopes stateful MCP stdio sessions per thread (session_id alone can be shared project-wide).
+ ``rag_scope``: hidden per-request RAG context the model never sees; consumed by
+ ``search_knowledge_base``. ``disable_sandbox``: Bypass Permissions; run python/terminal without
+ the safety checks, blocklist, or resource caps (secrets still stripped). Only affects local code
+ tools; web_search / MCP are unchanged. ``output_callback``: optional ``callable(str)`` invoked
+ with incremental stdout/stderr chunks while python/terminal executions run. Purely
+ observational: the returned result string is identical with or without it. ``website_policy``:
+ hidden server-validated domain limits for web_search.
"""
logger.info(f"execute_tool: name={name}, session_id={session_id}, timeout={timeout}")
- # Set unconditionally, so a value from an earlier call on this thread can never be
- # read by a later one. That is what makes a try/finally reset unnecessary here.
+ # Set unconditionally, so a value from an earlier call on this thread can never be read by a later one. That is
+ # what makes a try/finally reset unnecessary here.
_REQUEST_CONTEXT_TOKENS.set(context_tokens)
- # Same rule, and it matters more here: a stale budget is a budget measured before this
- # turn's own tool exchanges existed, which is precisely the undercount that lets the
- # last result overflow.
+ # Same rule, and it matters more here: a stale budget is a budget measured before this turn's own tool exchanges
+ # existed, which is precisely the undercount that lets the last result overflow.
_REQUEST_RESULT_BUDGET.set(result_budget_tokens)
- # Arguments that never parsed, for a tool with no single argument they could be.
- # Answered here rather than by the tool, which can only report the keys it wanted and
- # would blame the model for omitting them: `edit_file` said "'old_string' and
- # 'new_string' must both be strings" about a call that sent neither because its JSON
- # was cut off mid-string. Naming the real fault is what makes the retry the right one.
- # Imported here for the same reason `strip_result_for_model` is: at module scope this
- # closes an import cycle, since the controller reads this module's own schemas.
+ # Arguments that never parsed, for a tool with no single argument they could be. Answered here rather than by the
+ # tool, which can only report the keys it wanted and would blame the model for omitting them: `edit_file` said
+ # 'old_string' and 'new_string' must both be strings about a call that sent neither because its JSON was cut off
+ # mid-string. Naming the real fault is what makes the retry the right one. Imported here for the same reason
+ # `strip_result_for_model` is: at module scope this closes an import cycle.
from .tool_loop_controller import UNPARSED_ARGUMENTS_KEY # noqa: PLC0415
if isinstance(arguments, dict) and UNPARSED_ARGUMENTS_KEY in arguments:
@@ -10475,8 +9723,8 @@ def execute_tool(
name,
)
if name == "search_conversation":
- # Scoped by thread id alone: the archive is this chat's own evicted turns, so it
- # works with or without a document rag_scope.
+ # Scoped by thread id alone: the archive is this chat's own evicted turns, so it works with or without a
+ # document rag_scope.
return _fit_result_to_room(
_search_knowledge_base_with_budget(
arguments,
@@ -10508,9 +9756,8 @@ def execute_tool(
return f"Error: MCP server '{display}' is disabled"
if is_stdio(server["url"]) and not stdio_mcp_enabled():
return f"Error: stdio MCP server '{display}' is disabled on this host"
- # Persist a stateful stdio session only per conversation (thread_id).
- # session_id is the project-wide sandbox id, so scoping by it alone leaks
- # browser/DB/REPL state across conversations; fall back to one-shot. Tag +
+ # Persist a stateful stdio session only per conversation (thread_id). session_id is the project-wide sandbox
+ # id, so scoping by it alone leaks browser/DB/REPL state across conversations; fall back to one-shot. Tag +
# percent-quote the parts so ids can't collide or ":" merge conversations.
if thread_id:
mcp_scope = "s={}:t={}".format(
@@ -10524,12 +9771,10 @@ def execute_tool(
use_oauth = bool(server.get("use_oauth"))
def _config_current() -> bool:
- # Re-read before an MCP session is cached: this call may have read
- # the row just before an update/delete closed its sessions.
- # use_oauth belongs here with the rest: a row switched to OAuth after
- # we read it must not be reached through the unauthenticated client
- # this call is about to open, and a close cannot stop that on its own
- # (nothing is cached yet, so it has no generation to bump).
+ # Re-read before an MCP session is cached: this call may have read the row just before an update/delete
+ # closed its sessions. use_oauth belongs here with the rest: a row switched to OAuth after we read it must
+ # not be reached through the unauthenticated client this call is about to open, and a close cannot stop
+ # that on its own (nothing is cached yet, so it has no generation to bump).
row = mcp_servers_db.get_server(server_id)
return (
row is not None
@@ -10570,8 +9815,7 @@ def execute_tool(
),
name,
)
- # Both run with the session's sandbox as cwd, so a chat deleted mid-call
- # must not unlink it from under them.
+ # Both run with the session's sandbox as cwd, so a chat deleted mid-call must not unlink it from under them.
if name == "python":
with _session_in_flight(session_id):
return _python_exec(
@@ -10594,8 +9838,8 @@ def execute_tool(
output_callback = output_callback,
thread_id = thread_id,
)
- # Same in-flight guard as the two above: it writes into the session workdir,
- # so a chat deleted mid-call must not unlink it underneath.
+ # Same in-flight guard as the two above: it writes into the session workdir, so a chat deleted mid-call must not
+ # unlink it underneath.
if name == "edit_file":
with _session_in_flight(session_id):
return _fit_result_to_room(
@@ -10623,9 +9867,8 @@ def _scope_retrieval_kwargs(scope: dict) -> dict:
def _search_knowledge_base(arguments: dict, rag_scope: dict | None) -> str:
- """Run the RAG search bound to the hidden per-request ``rag_scope`` (the model
- supplies only ``query``/``top_k``). Lazy import; missing sqlite-vec degrades
- to a friendly message."""
+ """Run the RAG search bound to the hidden per-request ``rag_scope`` (the model supplies only
+ ``query``/``top_k``). Lazy import; missing sqlite-vec degrades to a friendly message."""
scope = rag_scope or {}
query = (arguments or {}).get("query", "")
if not query or not str(query).strip():
@@ -10655,14 +9898,14 @@ def _search_knowledge_base(arguments: dict, rag_scope: dict | None) -> str:
return text
-# Ceiling for a model-supplied top_k. Small on purpose: this returns whole archived turns
-# into a protected exchange the rolling window cannot trim.
+# Ceiling for a model-supplied top_k. Small on purpose: this returns whole archived turns into a protected exchange
+# the rolling window cannot trim.
_MAX_CONVERSATION_SEARCH_TOP_K = 8
def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
- """Search this thread's archived turns. ``rag_scope`` carries only the thread id here;
- the model supplies ``query``/``top_k``."""
+ """Search this thread's archived turns. ``rag_scope`` carries only the thread id here; the model
+ supplies ``query``/``top_k``."""
scope = rag_scope or {}
thread_id = scope.get("thread_id")
query = (arguments or {}).get("query", "")
@@ -10678,19 +9921,18 @@ def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
if not conversation_archive.enabled():
return "Searching earlier conversation is unavailable on this server."
- # Clamped, not trusted: top_k comes from the model, and a negative value reaches a
- # Python slice as out[:-1], returning nearly the whole candidate pool as a ~30k-token
- # tool result that the protected current exchange cannot evict.
+ # Clamped, not trusted: top_k comes from the model, and a negative value reaches a Python slice as out[:-1],
+ # returning nearly the whole candidate pool as a ~30k-token tool result that the protected current exchange cannot
+ # evict.
requested = _opt_int((arguments or {}).get("top_k"))
- # None, not the ceiling: an omitted top_k must fall through to the configured recall
- # default. Defaulting to the maximum returned eight chunks into that same protected
- # exchange, enough to fail the next pass on a 4K chat.
+ # None, not the ceiling: an omitted top_k must fall through to the configured recall default. Defaulting to the
+ # maximum returned eight chunks into that same protected exchange, enough to fail the next pass on a 4K chat.
top_k = (
None if requested is None else max(1, min(_MAX_CONVERSATION_SEARCH_TOP_K, int(requested)))
)
- # Then against the room actually left: the fixed cap bounds what the model may ask
- # for, not what fits. Eight chunks is roughly 4,000 tokens once wrapped, so on a 4K
- # chat overshooting here is a context-length error no later preflight can recover.
+ # Then against the room actually left: the fixed cap bounds what the model may ask for, not what fits. Eight
+ # chunks is roughly 4,000 tokens once wrapped, so on a 4K chat overshooting here is a context-length error no
+ # later preflight can recover.
budget = scope.get("budget_tokens")
if budget is not None:
default_k = 1
@@ -10702,17 +9944,17 @@ def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
affordable = 0
if affordable <= 0:
return "There is no room left in this context to search earlier conversation."
- # An omitted top_k still means the configured default; room is a cap on it, not a
- # target. Taking the room itself asked a 128K chat for 200 passages, past both the
- # default and the ceiling the model's own value is held to.
+ # An omitted top_k still means the configured default; room is a cap on it, not a target. Taking the room
+ # itself asked a 128K chat for 200 passages, past both the default and the ceiling the model's own value is
+ # held to.
top_k = (
min(default_k, _MAX_CONVERSATION_SEARCH_TOP_K, affordable)
if top_k is None
else max(1, min(top_k, affordable))
)
- # The branch this request is on, so a response replaced by Retry cannot be searched
- # back out of the archive. Absent callers fall back to the whole stored thread.
+ # The branch this request is on, so a response replaced by Retry cannot be searched back out of the archive.
+ # Absent callers fall back to the whole stored thread.
def _recall(k):
return conversation_archive.recall(
str(thread_id),
@@ -10725,13 +9967,11 @@ def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
if not found:
return "No earlier turns of this conversation matched that query."
- # Then against what the result actually costs. CHUNK_TOKENS is what the chunker AIMS
- # at, not what a chunk weighs: chunks overlap, the chunker's tokenizer is not the
- # model's, and the rendered block adds markup, source metadata and the tool framing
- # around it. Measured on a 500-token budget: one chunk came back as 1,256 estimated
- # tokens. So the count is halved until the rendered result fits, the same backoff the
- # forced recall uses, and a single chunk that still does not fit is refused rather
- # than appended to an exchange the window is not allowed to evict.
+ # Then against what the result actually costs. CHUNK_TOKENS is what the chunker AIMS at, not what a chunk weighs:
+ # chunks overlap, the chunker's tokenizer is not the model's, and the rendered block adds markup, source metadata
+ # and the tool framing around it. Measured on a 500-token budget: one chunk came back as 1,256 estimated tokens.
+ # So the count is halved until the rendered result fits, the same backoff the forced recall uses, and a single
+ # chunk that still does not fit is refused rather than appended to an exchange the window is not allowed to evict.
if budget is not None:
counter = scope.get("token_counter")
attempt = max(1, int(top_k or 1))
@@ -10748,23 +9988,19 @@ def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
return _rendered_conversation_search(found)
-# What a `tool` message costs beyond its own text: the role, the call id and whatever the
-# template wraps them in. Small, fixed, and left out entirely before, which is the wrong
-# direction on a check whose whole job is to refuse a result that will not fit.
+# What a `tool` message costs beyond its own text: the role, the call id and whatever the template wraps them in.
+# Small, fixed, and left out entirely before, which is the wrong direction on a check whose whole job is to refuse a
+# result that will not fit.
_TOOL_MESSAGE_FRAMING_TOKENS = 8
def _conversation_search_cost(text: str, counter = None) -> int:
- """What admitting this result really costs, exactly when the caller has a tokenizer.
-
- The estimate below is pessimistic for CJK and emoji but still optimistic for ASCII
- that tokenises densely -- source code, minified JSON, hashes, command output all run
- nearer two or three characters per token than four -- so a result could be admitted at
- well under its real cost and then land in the current tool exchange, which the window
- is not allowed to evict. A tokenizer-backed caller passes its own counter, and the
- GGUF path is one, so the check that already computes the budget exactly can now spend
- it exactly too.
- """
+ """What admitting this result really costs, exactly when the caller has a tokenizer. The
+ estimate below is pessimistic for CJK and emoji but still optimistic for ASCII that tokenises
+ densely (source code, minified JSON, hashes, command output all run nearer two or three
+ characters per token than four), so a result could be admitted at well under its real cost
+ and then land in the current tool exchange, which the window is not allowed to evict. A
+ tokenizer-backed caller passes its own counter, and the GGUF path is one."""
if counter is not None:
try:
return int(counter(text)) + _TOOL_MESSAGE_FRAMING_TOKENS
@@ -10774,15 +10010,13 @@ def _conversation_search_cost(text: str, counter = None) -> int:
def _conversation_search_tokens(text: str) -> int:
- """A deliberately pessimistic size for a search result, in tokens.
-
- The shared estimator charges four characters per token, which is about right for
- English and badly wrong for text that tokenises densely: CJK and emoji run closer to
- one token per character, so a result could be accepted at a quarter of its real cost
- and then land in the current tool exchange, which the window cannot evict. No exact
- counter is reachable from here, the provider loop having no tokenizer at all, so
- non-ASCII characters are charged one token each and the rest at the usual rate.
- """
+ """A deliberately pessimistic size for a search result, in tokens. The shared estimator charges
+ four characters per token, which is about right for English and badly wrong for text that
+ tokenises densely: CJK and emoji run closer to one token per character, so a result could be
+ accepted at a quarter of its real cost and then land in the current tool exchange, which the
+ window cannot evict. No exact counter is reachable from here, the provider loop having no
+ tokenizer at all, so non-ASCII characters are charged one token each and the rest at the
+ usual rate."""
dense = sum(1 for char in text if ord(char) > 127)
return max(1, dense + (len(text) - dense) // 4)
@@ -10803,10 +10037,9 @@ def _search_knowledge_base_with_budget(
cancel_event = None,
search_fn = None,
) -> str:
- """Admission-controlled RAG search.
-
- ``search_fn`` swaps in a different search over the same capacity-of-one slot, so
- archive lookups queue behind document lookups instead of racing for the embedder."""
+ """Admission-controlled RAG search. ``search_fn`` swaps in a different search over the same
+ capacity-of-one slot, so archive lookups queue behind document lookups instead of racing for
+ the embedder."""
search_fn = search_fn or _search_knowledge_base
if cancel_event is not None and cancel_event.is_set():
return "Error: knowledge base search cancelled."
@@ -10817,10 +10050,10 @@ def _search_knowledge_base_with_budget(
if deadline is not None and time.monotonic() >= deadline:
return "Error: knowledge base search timed out."
- # The running search owns the admission slot until it actually stops; release it exactly once,
- # from whichever path terminates the work. Releasing on caller timeout/cancel would let a
- # second search in while the first worker is still doing embedding/index/GPU work, defeating
- # the capacity-of-one bound, so the worker frees the slot in its finally instead.
+ # The running search owns the admission slot until it actually stops; release it exactly once, from whichever path
+ # terminates the work. Releasing on caller timeout/cancel would let a second search in while the first worker is
+ # still doing embedding/index/GPU work, defeating the capacity-of-one bound, so the worker frees the slot in its
+ # finally instead.
_slot_lock = threading.Lock()
_slot_released = False
@@ -10861,8 +10094,8 @@ def _search_knowledge_base_with_budget(
release_slot()
raise
while True:
- # Caller gives up, but the worker thread still holds the slot and releases it in its
- # finally when it truly finishes -- so concurrency stays bounded to one.
+ # Caller gives up, but the worker thread still holds the slot and releases it in its finally when it truly
+ # finishes, so concurrency stays bounded to one.
if cancel_event is not None and cancel_event.is_set():
return "Error: knowledge base search cancelled."
if deadline is not None and time.monotonic() >= deadline:
@@ -10879,9 +10112,8 @@ def _search_knowledge_base_with_budget(
raise value
-# Forced first-pass RAG retrieval: a high cosine floor keeps it precise (fires on
-# on-topic queries, skips weak ones) and helps small models that under-call the tool.
-# Tunable via RAG_AUTOINJECT_MIN_SCORE.
+# Forced first-pass RAG retrieval: a high cosine floor keeps it precise (fires on on-topic queries, skips weak ones)
+# and helps small models that under-call the tool. Tunable via RAG_AUTOINJECT_MIN_SCORE.
_AUTOINJECT_DEFAULT_FLOOR = 0.70
@@ -10919,8 +10151,8 @@ def _autoinject_top_k() -> int:
def _thread_whole_doc_enabled(scope: dict) -> bool:
- """Whether a thread-attached file should be injected in full rather than
- retrieved top-K. ``rag_scope.whole_doc=False`` disables it for this request."""
+ """Whether a thread-attached file should be injected in full rather than retrieved top-K.
+ ``rag_scope.whole_doc=False`` disables it for this request."""
override = scope.get("whole_doc")
if override is False:
return False
@@ -11015,12 +10247,10 @@ def build_synthetic_search_exchange(
text: str,
sources: list[dict],
) -> dict:
- """Render a retrieval the loop never asked for as a normal tool exchange.
-
- Returns ``{"events": [...], "messages": [...]}``: the messages are what the model
- reads, the events what the UI draws, so a forced retrieval shows up as an ordinary
- tool card with working citations instead of appearing from nowhere.
- """
+ """Render a retrieval the loop never asked for as a normal tool exchange. Returns ``{"events":
+ [...], "messages": [...]}``: the messages are what the model reads, the events what the UI
+ draws, so a forced retrieval shows up as an ordinary tool card with working citations instead
+ of appearing from nowhere."""
import json as _json
import uuid as _uuid
@@ -11087,17 +10317,17 @@ def build_conversation_recall(
) -> dict | None:
"""Retrieve the archived turns most relevant to the latest user message.
- Deliberately NOT gated on ``rag_scope``: compaction happens whether or not document
- RAG is on, and these turns are the conversation's own, not uploaded files.
+ Deliberately NOT gated on ``rag_scope``: compaction happens whether or not document RAG is on,
+ and these turns are the conversation's own, not uploaded files.
- Forcing this one retrieval is the whole feature. Given only a search tool, a 35B on
- MRCR v2 declined on 56% of rows, scoring 0.099 when it skipped against 0.461 when it
- searched; forcing the lookup on the evicting turn took tool-only 0.258 to 0.604, and
- the model then called the tool on 0% of rows, so it costs nothing on the common path.
+ Forcing this one retrieval is the whole feature. Given only a search tool, a 35B on MRCR v2
+ declined on 56% of rows, scoring 0.099 when it skipped against 0.461 when it searched; forcing
+ the lookup on the evicting turn took tool-only 0.258 to 0.604, and the model then called the
+ tool on 0% of rows, so it costs nothing on the common path.
- ``style="tool"`` renders a tool exchange, for the tool loop which already carries a
- tools array. ``style="inline"`` prefixes the latest user message instead, for the
- plain path: forging tool_calls without a tools array breaks strict templates.
+ ``style="tool"`` renders a tool exchange, for the tool loop which already carries a tools array.
+ ``style="inline"`` prefixes the latest user message instead, for the plain path: forging
+ tool_calls without a tools array breaks strict templates.
"""
if not thread_id:
return None
@@ -11108,16 +10338,15 @@ def build_conversation_recall(
if not conversation_archive.enabled():
return None
- # The BRANCH's latest user turn, not the loop conversation's: a later tool-loop
- # iteration can end with an internal user-role re-prompt (the plan-without-action
- # nudge), and searching for that controller instruction defeats the forced retrieval.
- # branch_messages is what the client sent, so its last user turn is the real request.
+ # The BRANCH's latest user turn, not the loop conversation's: a later tool-loop iteration can end with an internal
+ # user-role re-prompt (the plan-without-action nudge), and searching for that controller instruction defeats the
+ # forced retrieval. branch_messages is what the client sent, so its last user turn is the real request.
query = _last_user_text(branch_messages or conversation) or _last_user_text(conversation)
if not query:
return None
- # A nudge ("continue", "yes") retrieves nothing, so the user's last real instruction is
- # asked for as a SECOND query. Not applied to the model's own `search_conversation`
- # calls: the model wrote that query, and overriding it answers a different question.
+ # A nudge (continue, yes) retrieves nothing, so the user's last real instruction is asked for as a SECOND query.
+ # Not applied to the model's own `search_conversation` calls: the model wrote that query, and overriding it
+ # answers a different question.
anchor = None
thin = False
try:
@@ -11127,21 +10356,19 @@ def build_conversation_recall(
_behind = branch_messages or conversation
anchor = instruction_pin.last_substantive_instruction(_behind)
if not anchor:
- # An instruction is 80 characters; a QUERY need only name something. On a
- # first reset a thread of short prompts ("Write a story about Mars", then
- # "continue") had no anchor at all, so recall was skipped, the block
- # carried nothing (the same length rule) and the archive was written after
- # tool selection, so the model saw the nudge alone with no way to reach
- # what it was continuing. `is_thin_query` already separates "names
- # nothing" from "short", so ask it instead.
+ # An instruction is 80 characters; a QUERY need only name something. On a first reset a thread of
+ # short prompts had no anchor at all, so recall was skipped, the block carried nothing (the same
+ # length rule) and the archive was written after tool selection, so the model saw the nudge alone with
+ # no way to reach what it was continuing. `is_thin_query` already separates names nothing from short,
+ # so ask it instead.
anchor = _last_searchable_text(_behind)
except Exception: # noqa: BLE001 -- a query refinement must never break a chat
anchor = None
thin = False
if thin and not anchor:
- # A nudge with nothing behind it: searching for "continue" returns whatever shares
- # its stopwords, and under checkpoint compaction that block is the model's FIRST
- # sight of the search tool. Skip; the tool stays available.
+ # A nudge with nothing behind it: searching for continue returns whatever shares its stopwords, and under
+ # checkpoint compaction that block is the model's FIRST sight of the search tool. Skip; the tool stays
+ # available.
logger.info(
"Conversation recall skipped: the latest message is a nudge with no "
"earlier instruction to search for instead"
@@ -11187,13 +10414,10 @@ def build_conversation_recall(
def rag_autoinject_reaches_retrieval(
conversation: list[dict], rag_scope: dict | None
) -> tuple[bool, bool]:
- """Everything checked before pre-retrieval searches: switched on, something to search
- for, somewhere to search, and a store to search it in. Whether a hit then clears the
- score floor is the one part not knowable without running the search.
-
- Shared with token counting, which cannot run it and so must not decline a turn that
- stops short of the search here.
- """
+ """Everything checked before pre-retrieval searches: switched on, something to search for,
+ somewhere to search, and a store to search it in. Whether a hit then clears the score floor
+ is the one part not knowable without running the search. Shared with token counting, which
+ cannot run it and so must not decline a turn that stops short of the search here."""
if not rag_scope:
return False, False
enabled = rag_scope.get("autoinject")
@@ -11205,8 +10429,8 @@ def rag_autoinject_reaches_retrieval(
)
if not enabled and not whole_doc_requested:
return False, False
- # What _resolve_scope resolves to nothing: an unpersisted New Chat carries a scope with
- # none of the three ids, and the search stops there.
+ # What _resolve_scope resolves to nothing: an unpersisted New Chat carries a scope with none of the three ids, and
+ # the search stops there.
if not (rag_scope.get("kb_id") or rag_scope.get("project_id") or thread_id):
return False, False
if not _last_user_text(conversation):
@@ -11214,8 +10438,8 @@ def rag_autoinject_reaches_retrieval(
try:
from storage import rag_db
- # rag_available(), not the import flag: the vec0 native library is a separate file a
- # venv can be missing, and nothing finds out until a connection tries.
+ # rag_available(), not the import flag: the vec0 native library is a separate file a venv can be missing, and
+ # nothing finds out until a connection tries.
if not rag_db.rag_available():
return False, False
except Exception: # noqa: BLE001
@@ -11224,14 +10448,15 @@ def rag_autoinject_reaches_retrieval(
def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
- """Pre-retrieve the latest user turn; if a hit clears the cosine floor return
- ``{"events": [...], "messages": [...]}`` to splice into the loop, else ``None``.
- Toggle via ``rag_scope.autoinject`` (else env ``RAG_AUTOINJECT``); floor via
- ``rag_scope.autoinject_min_score`` (else env ``RAG_AUTOINJECT_MIN_SCORE``).
-
- Also the small-model fallback: models below ~4B often answer from memory
- instead of calling ``search_knowledge_base``, so forcing retrieval here keeps
- attachments consulted regardless of model size."""
+ """Pre-retrieve the latest user turn; if a hit clears the cosine floor return ``{"events": [...],
+ "messages": [...]}`` to splice into the loop, else ``None``. Toggle via ``rag_scope.autoinject``
+ (else env ``RAG_AUTOINJECT``); floor via ``rag_scope.autoinject_min_score`` (else env
+ ``RAG_AUTOINJECT_MIN_SCORE``).
+
+ Also the small-model fallback: models below ~4B often answer from memory instead of calling
+ ``search_knowledge_base``, so forcing retrieval here keeps attachments consulted regardless of
+ model size.
+ """
enabled, whole_doc_requested = rag_autoinject_reaches_retrieval(conversation, rag_scope)
if not enabled and not whole_doc_requested:
return None
@@ -11253,20 +10478,20 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
sidebar_k = _opt_int(rag_scope.get("default_top_k"))
top_k = min(sidebar_k, lean_k) if sidebar_k is not None else lean_k
budget: int | None = None
- # The window the budget was sized against, so `_text_token_cost` only trusts
- # a GGUF actually serving this same window.
+ # The window the budget was sized against, so `_text_token_cost` only trusts a GGUF actually serving this same
+ # window.
ctx_tokens = (
_opt_int(rag_scope.get("context_length") or rag_scope.get("max_context_tokens")) or 0
)
def _fits(candidate_text, max_tokens) -> bool:
- # None means the estimate itself failed; zero is a measured "no room left".
+ # None means the estimate itself failed; zero is a measured no room left.
if max_tokens is None:
return True
if max_tokens <= 0:
return False
- # Priced by the serving GGUF when it can, doubled when it cannot, so dense
- # ASCII is not charged the English four characters per token.
+ # Priced by the serving GGUF when it can, doubled when it cannot, so dense ASCII is not charged the English
+ # four characters per token.
return _text_token_cost(candidate_text, ctx_tokens) <= max_tokens
def _trim(
@@ -11275,14 +10500,11 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
max_tokens,
keep_first = 1,
):
- """Drop passages from the tail until the rendered block fits, else None.
-
- Re-renders only when something is dropped. None when not even the first
- ``keep_first`` passages fit: the block joins the current turn, which the
- window may not evict, so it fails the request rather than degrading it.
- ``keep_first`` is the floor of the tail: one for ranked retrieval, but a
- whole document must never be eaten into.
- """
+ """Drop passages from the tail until the rendered block fits, else None. Re-renders only
+ when something is dropped. None when not even the first ``keep_first`` passages fit: the
+ block joins the current turn, which the window may not evict, so it fails the request
+ rather than degrading it. ``keep_first`` is the floor of the tail: one for ranked
+ retrieval, but a whole document must never be eaten into."""
floor = max(1, keep_first)
kept, rendered = list(hit_sources), hit_text
while len(kept) > floor and not _fits(rendered, max_tokens):
@@ -11290,9 +10512,8 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
rendered = render_sources(kept)
return (rendered, kept) if _fits(rendered, max_tokens) else None
- # Whole-document mode: a thread-attached file under budget is injected in
- # full. A KB selection is exclusive so whole-doc never preempts it; project
- # sources are still retrieved top-K and appended under one citation
+ # Whole-document mode: a thread-attached file under budget is injected in full. A KB selection is exclusive so
+ # whole-doc never preempts it; project sources are still retrieved top-K and appended under one citation
# numbering. Oversized/absent thread docs fall through to top-K below.
if whole_doc_requested:
try:
@@ -11317,9 +10538,8 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
logger.warning("RAG project retrieval (whole-doc companion) failed: %s", exc)
proj = None
if proj is not None:
- # Trim into the project tail only: the document was admitted whole
- # and stays whole, so a combination that will not fit falls back
- # to the document alone.
+ # Trim into the project tail only: the document was admitted whole and stays whole, so a
+ # combination that will not fit falls back to the document alone.
merged = sources + proj[1]
trimmed = _trim(render_sources(merged), merged, budget, keep_first = len(sources))
if trimmed is not None:
@@ -11330,11 +10550,10 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
found = search_for_autoinject(query = query, top_k = top_k, **scope)
return _trim(found[0], found[1], max_tokens) if found else None
- # An oversized thread attachment is mandatory grounding: with auto-injection
- # off, search it alone, without the optional-auto relevance floor, then add
- # project context if the combination still fits. The budget binds on that
- # path only -- with auto-injection on this stays the single combined
- # unbudgeted search, so a small context cannot silently switch RAG off.
+ # An oversized thread attachment is mandatory grounding: with auto-injection off, search it alone, without the
+ # optional-auto relevance floor, then add project context if the combination still fits. The budget binds on that
+ # path only: with auto-injection on this stays the single combined unbudgeted search, so a small context cannot
+ # silently switch RAG off.
if text is None and (enabled or whole_doc_requested):
try:
if whole_doc_requested and not enabled:
@@ -11346,9 +10565,8 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
)
project_id = rag_scope.get("project_id")
if found and project_id:
- # Isolated like the whole-document companion above: an
- # unavailable project index must not send the shared handler
- # below into discarding thread grounding already in hand.
+ # Isolated like the whole-document companion above: an unavailable project index must not send the
+ # shared handler below into discarding thread grounding already in hand.
try:
proj = retrieve(
scope_project_id = project_id,
@@ -11359,9 +10577,8 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
logger.warning("RAG project retrieval (fallback companion) failed: %s", exc)
proj = None
if proj:
- # Trim the combination, not the project alone, which was
- # never entitled to the whole budget. The tail is all
- # project, so what fits beside the thread result survives.
+ # Trim the combination, not the project alone, which was never entitled to the whole budget.
+ # The tail is all project, so what fits beside the thread result survives.
merged = found[1] + proj[1]
found = _trim(render_sources(merged), merged, budget) or found
else:
@@ -11396,21 +10613,19 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
_MAX_PAGE_CHARS = 16000 # cap fetched page text (after HTML-to-MD conversion)
-# Share of the loaded window one fetched page may claim. The same window also has to hold
-# the system prompt, the carried-forward block, the user's turn, the call itself and room
-# to answer, so a third is already generous.
+# Share of the loaded window one fetched page may claim. The same window also has to hold the system prompt, the
+# carried-forward block, the user's turn, the call itself and room to answer, so a third is already generous.
_PAGE_CONTEXT_SHARE = 0.35
-# Below this a page is too clipped to answer from, so the fetch is not worth making small.
-# Half, when the room has to be converted to characters with no way to check the answer.
-# See `_dense_char_limit`: the conversion charges ASCII an English four characters per
-# token and the dense ASCII these tools print runs nearer two.
+# Below this a page is too clipped to answer from, so the fetch is not worth making small. Half, when the room has to
+# be converted to characters with no way to check the answer: see `_dense_char_limit`, the conversion charges ASCII an
+# English four characters per token and the dense ASCII these tools print runs nearer two.
_UNMEASURED_ROOM_MARGIN = 0.5
_MIN_PAGE_CHARS = 2000
# A percent-escape is one non-ASCII byte written in ASCII, and tokenises like one.
_HEX_PAIR_RE = re.compile(r"[0-9A-Fa-f]{2}")
-# Raw download cap > _MAX_PAGE_CHARS since SSR pages embed large <head> sections
-# stripped during conversion; 512 KB still reaches article content.
+# Raw download cap > _MAX_PAGE_CHARS since SSR pages embed large <head> sections stripped during conversion; 512 KB
+# still reaches article content.
_MAX_FETCH_BYTES = 512 * 1024
# "%" is safe so an already-encoded URL is not re-encoded into %25.
_IRI_PATH_SAFE = "/%:@!$&'()*+,;="
@@ -11418,8 +10633,8 @@ _IRI_QUERY_SAFE = "/%:@!$&'()*+,;=?"
# PDF cross-reference data lives at EOF, so extraction needs the whole body.
_MAX_PDF_FETCH_BYTES = 10 * 1024 * 1024
_MAX_WEB_PDF_PAGES = 50
-# Control/undecodable chars, excluding text whitespace and ESC (for ANSI logs).
-# Binary when they exceed 12.5%, after allowing 16 minor encoding glitches.
+# Control/undecodable chars, excluding text whitespace and ESC (for ANSI logs). Binary when they exceed 12.5%, after
+# allowing 16 minor encoding glitches.
_BINARY_CHAR_RE = re.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1a\\x1c-\\x1f\\x7f-\\x9f\\ufffd]")
_MIN_BINARY_CHARS = 16
_BINARY_CHAR_DIVISOR = 8
@@ -11686,18 +10901,18 @@ class _PinnedHTTPHandler(urllib.request.HTTPHandler):
def _explicit_proxy_applies(scheme: str, host: str) -> bool:
"""Whether urllib routes a *scheme* request for *host* through a proxy.
- Only a proxied fetch may keep the hostname in the request URL: the proxy
- resolves it, so this host never looks it up again. A direct one would, which
- is the DNS-rebinding window, so it stays pinned to the validated IP.
+ Only a proxied fetch may keep the hostname in the request URL: the proxy resolves it, so this
+ host never looks it up again. A direct one would, which is the DNS-rebinding window, so it stays
+ pinned to the validated IP.
- *host* must be the ``host[:port]`` form ``Request.host`` carries, since that
- is what ``ProxyHandler`` passes to ``proxy_bypass``; probing the bare hostname
- instead would disagree with it on a port-qualified NO_PROXY entry.
+ *host* must be the ``host[:port]`` form ``Request.host`` carries, since that is what
+ ``ProxyHandler`` passes to ``proxy_bypass``; probing the bare hostname instead would disagree
+ with it on a port-qualified NO_PROXY entry.
"""
from urllib.request import getproxies, proxy_bypass
- # ProxyHandler lowercases every mapping key, and the Windows registry can hand
- # back "HTTPS=...", so normalize before testing or a proxy-only host goes direct.
+ # ProxyHandler lowercases every mapping key, and the Windows registry can hand back "HTTPS=...", so normalize
+ # before testing or a proxy-only host goes direct.
if scheme not in {key.lower() for key in getproxies()}:
return False
try:
@@ -11729,8 +10944,8 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, lis
resolved = []
for *_, sockaddr in infos:
ip = ipaddress.ip_address(sockaddr[0])
- # `not ip.is_global` is the source of truth (also rejects CGNAT and
- # benchmarking/doc ranges); the explicit predicates only label the error.
+ # `not ip.is_global` is the source of truth (also rejects CGNAT and benchmarking/doc ranges); the explicit
+ # predicates only label the error.
if (
not ip.is_global
or ip.is_private
@@ -11747,8 +10962,8 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, lis
return True, "", resolved
-# Binary application subtypes rejected by MIME; other application types are
-# sniffed so textual artifacts such as SQL stay usable.
+# Binary application subtypes rejected by MIME; other application types are sniffed so textual artifacts such as SQL
+# stay usable.
_BINARY_APPLICATION_SUBTYPES = frozenset(
{
"epub+zip",
@@ -11822,12 +11037,9 @@ _GITHUB_NAME_RE = re.compile(r"\A[A-Za-z0-9_.\-]{1,100}\Z")
def _github_repo_readme_api_url(url: str) -> str | None:
- """README API URL for a ``github.com/{owner}/{repo}`` page, else None.
-
- A repo root page rendered as HTML is mostly UI chrome (nav, file table,
- stats); the ``/readme`` API returns the raw README markdown unauthenticated,
- which is what the model actually wants to read.
- """
+ """README API URL for a ``github.com/{owner}/{repo}`` page, else None. A repo root page rendered
+ as HTML is mostly UI chrome (nav, file table, stats); the ``/readme`` API returns the raw
+ README markdown unauthenticated, which is what the model actually wants to read."""
from urllib.parse import urlparse
parsed = urlparse(url)
@@ -11847,11 +11059,9 @@ def _github_repo_readme_api_url(url: str) -> str | None:
return f"https://api.github.com/repos/{owner}/{repo}/readme"
-# A single fetch can chain several steps (README API attempt, HTML fallback, up
-# to five redirect hops, each reading a body). A per-operation socket timeout
-# bounds one stalled step but not their sum, and nothing aborts on client
-# disconnect, so one overall wall-clock deadline (plus a cooperative
-# cancel_event) bounds the whole fetch instead.
+# A single fetch can chain several steps (README API attempt, HTML fallback, up to five redirect hops, each reading a
+# body). A per-operation socket timeout bounds one stalled step but not their sum, and nothing aborts on client
+# disconnect, so one overall wall-clock deadline (plus a cooperative cancel_event) bounds the whole fetch instead.
def _fetch_budget_exceeded(deadline, cancel_event):
"""User-facing error string when the fetch must stop early, else None."""
if cancel_event is not None and cancel_event.is_set():
@@ -11862,10 +11072,10 @@ def _fetch_budget_exceeded(deadline, cancel_event):
def _fetch_hop_timeout(timeout, deadline):
- """Per-operation socket timeout: the lesser of the caller's per-op timeout
- and the time left on the deadline, so one slow hop cannot overrun the whole
- budget. Callers check ``_fetch_budget_exceeded`` first, so remaining time is
- positive here; the tiny floor only guards a race."""
+ """Per-operation socket timeout: the lesser of the caller's per-op timeout and the time left on
+ the deadline, so one slow hop cannot overrun the whole budget. Callers check
+ ``_fetch_budget_exceeded`` first, so remaining time is positive here; the tiny floor only
+ guards a race."""
if deadline is None:
return timeout
remaining = deadline - time.monotonic()
@@ -11875,14 +11085,11 @@ def _fetch_hop_timeout(timeout, deadline):
def _resolve_with_budget(hostname, port, deadline, cancel_event):
- """``_validate_and_resolve_host`` bounded by the overall fetch budget.
-
- ``getaddrinfo`` is blocking with no deadline of its own, so a slow resolver
- (or a request cancelled before dispatch) could run past the budget. Resolve
- on a daemon thread and poll the budget so the fetch aborts on time; the
- abandoned lookup is discarded. With no deadline and no cancel_event this is a
- plain synchronous call, so opt-out callers keep the old behavior and cost.
- """
+ """``_validate_and_resolve_host`` bounded by the overall fetch budget. ``getaddrinfo`` is
+ blocking with no deadline of its own, so a slow resolver (or a request cancelled before
+ dispatch) could run past the budget. Resolve on a daemon thread and poll the budget so the
+ fetch aborts on time; the abandoned lookup is discarded. With no deadline and no cancel_event
+ this is a plain synchronous call, so opt-out callers keep the old behavior and cost."""
budget_error = _fetch_budget_exceeded(deadline, cancel_event)
if budget_error is not None:
return False, budget_error, []
@@ -11909,17 +11116,13 @@ def _resolve_with_budget(hostname, port, deadline, cancel_event):
def _read_capped_body(resp, max_bytes, timeout, deadline, cancel_event):
- """Read up to ``max_bytes``, enforcing the overall budget between chunks.
-
- A single ``resp.read(max_bytes)`` can block for the whole transfer if the
- server dribbles bytes just inside each socket-inactivity timeout, so the body
- is read in chunks with the budget re-checked (and the socket timeout
- re-tightened toward the deadline) each round. The joined bytes are identical
- to one capped read. Returns ``(error_or_None, body_bytes)``.
- """
- # Best-effort handle on the underlying socket so its timeout tightens as the
- # deadline nears; absent on test doubles, where the between-chunk budget
- # check still bounds the read.
+ """Read up to ``max_bytes``, enforcing the overall budget between chunks. A single
+ ``resp.read(max_bytes)`` can block for the whole transfer if the server dribbles bytes just
+ inside each socket-inactivity timeout, so the body is read in chunks with the budget
+ re-checked (and the socket timeout re-tightened toward the deadline) each round. The joined
+ bytes are identical to one capped read. Returns ``(error_or_None, body_bytes)``."""
+ # Best-effort handle on the underlying socket so its timeout tightens as the deadline nears; absent on test
+ # doubles, where the between-chunk budget check still bounds the read.
sock = getattr(getattr(getattr(resp, "fp", None), "raw", None), "_sock", None)
chunks = []
remaining = max_bytes
@@ -11952,27 +11155,25 @@ def _read_capped_body(resp, max_bytes, timeout, deadline, cancel_event):
_DOTTED_HOST_RE = re.compile(r"[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+")
-# ASCII-only because str.isdigit() is True for digits int() refuses ("²"), and
-# capped at 5 digits so the range check never converts an unbounded integer.
+# ASCII-only because str.isdigit() is True for digits int() refuses, and capped at 5 digits so the range check never
+# converts an unbounded integer.
_PORT_RE = re.compile(r"[0-9]{1,5}")
def _normalize_url_scheme(url: str) -> str:
"""Prepend ``https://`` to bare hosts (``google.com``, ``example.com:8443``).
- ``urlparse`` reads the host of a ``host:port`` input as the scheme, so those
- are recognised by a dotted host-like scheme with an empty netloc. Rewrites a
- dotted host with an optional in-range port, and the ``//host`` form. Real
- schemes (``file:``, ``javascript:``, including ``file:80``), root-relative
- paths (``/login``) and bad ports are returned untouched so the caller
- rejects them. A dotted scheme is indistinguishable from ``host:port``, so
- ``com.acme.app:443/cb`` is rewritten too; an empty port (``example.com:``)
- is kept as-is, matching ``https://example.com:``.
-
- The host is matched against the raw authority, never against what
- ``urlparse`` returned, because urlsplit strips tabs/newlines (3.10) and
- leading C0/space (3.12). Anything it would strip fails the match, so the
- decision and the rewritten string cannot disagree across versions."""
+ ``urlparse`` reads the host of a ``host:port`` input as the scheme, so those are recognised by a
+ dotted host-like scheme with an empty netloc. Rewrites a dotted host with an optional in-range
+ port, and the ``//host`` form. Real schemes (``file:``, ``javascript:``, including ``file:80``),
+ root-relative paths (``/login``) and bad ports are returned untouched so the caller rejects
+ them. A dotted scheme is indistinguishable from ``host:port``, so ``com.acme.app:443/cb`` is
+ rewritten too; an empty port is kept as-is.
+
+ The host is matched against the raw authority, never against what ``urlparse`` returned, because
+ urlsplit strips tabs/newlines (3.10) and leading C0/space (3.12). Anything it would strip fails
+ the match, so the decision and the rewritten string cannot disagree across versions.
+ """
from urllib.parse import urlparse
url = url.strip()
@@ -12017,25 +11218,23 @@ def _fetch_url_raw(
) -> tuple[str | None, "str | bytes", str]:
"""Fetch a URL with SSRF protection; return ``(error, body_text, content_type)``.
- ``raw_bytes_max`` switches to binary mode: the body is returned as ``bytes``
- untouched (no PDF or text handling) and refused past that many bytes. The
- same scheme, host, redirect and budget gates apply either way.
+ ``raw_bytes_max`` switches to binary mode: the body is returned as ``bytes`` untouched (no PDF
+ or text handling) and refused past that many bytes. The same scheme, host, redirect and budget
+ gates apply either way.
- ``error`` is a user-facing message string when the fetch failed (the
- existing "Blocked:" / "Failed to fetch URL:" wording), else ``None``.
- Blocks private/loopback/link-local targets and caps the download size.
- No input reaches the caller as an exception: the URL is model-supplied, so
- every malformed form resolves to one of these strings.
+ ``error`` is a user-facing message string when the fetch failed, else ``None``. Blocks
+ private/loopback/link-local targets and caps the download size. No input reaches the caller as
+ an exception: the URL is model-supplied, so every malformed form resolves to one of these
+ strings.
- ``deadline`` is an optional ``time.monotonic`` cutoff for the whole fetch
- (redirect hops and body read included) and ``cancel_event`` aborts it when
- the caller goes away; both default off so callers keep the old behavior.
+ ``deadline`` is an optional ``time.monotonic`` cutoff for the whole fetch (redirect hops and
+ body read included) and ``cancel_event`` aborts it when the caller goes away; both default off.
"""
from urllib.parse import urlparse
from .web_access_policy import check_url_access
- # Before the policy gate: it requires an http(s) scheme, so a bare host
- # would be refused there and never reach the fetch.
+ # Before the policy gate: it requires an http(s) scheme, so a bare host would be refused there and never reach the
+ # fetch.
url = _normalize_url_scheme(url)
allowed, reason, canonical_host = check_url_access(url, website_policy)
if not allowed:
@@ -12077,13 +11276,12 @@ def _fetch_url_raw(
validated_netloc = f"[{current_host}]" if ":" in current_host else current_host
if cp.port:
validated_netloc = f"{validated_netloc}:{cp.port}"
- # Decide routing once, on the netloc urllib tests: a pinned request
- # carries an IP, which no NO_PROXY entry matches, so the opener below
- # has to carry the decision rather than re-derive it.
+ # Decide routing once, on the netloc urllib tests: a pinned request carries an IP, which no NO_PROXY entry
+ # matches, so the opener below has to carry the decision rather than re-derive it.
proxied = _explicit_proxy_applies(cp.scheme, validated_netloc)
if os.environ.get(_DISABLE_DNS_PINNING_ENV) == "1" and proxied:
- # Enterprise proxies need the hostname in CONNECT for policy and TLS
- # interception, and they resolve it, so nothing rebinds behind us.
+ # Enterprise proxies need the hostname in CONNECT for policy and TLS interception, and they resolve
+ # it, so nothing rebinds behind us.
request_url = urlunparse(cp._replace(netloc = validated_netloc))
else:
# Pin the first validated IP against DNS rebinding; the rest are below.
@@ -12109,8 +11307,8 @@ def _fetch_url_raw(
headers.update(extra_headers)
req = urllib.request.Request(request_url, headers = headers)
try:
- # Cap the socket timeout at the time left on the overall deadline
- # so a single slow hop cannot outlast the whole fetch budget.
+ # Cap the socket timeout at the time left on the overall deadline so a single slow hop cannot outlast
+ # the whole fetch budget.
resp = opener.open(req, timeout = _fetch_hop_timeout(timeout, deadline))
except _HTTPError as e:
if e.code not in (301, 302, 303, 307, 308):
@@ -12119,8 +11317,8 @@ def _fetch_url_raw(
if not location:
return "Failed to fetch URL: redirect missing Location header.", "", ""
current_url = urljoin(current_url, location)
- # Server-controlled, so never scheme-upgraded; the gate below
- # reads .port first, so the parse after it cannot raise.
+ # Server-controlled, so never scheme-upgraded; the gate below reads .port first, so the parse after it
+ # cannot raise.
allowed, policy_reason, redirect_host = check_url_access(
current_url,
website_policy,
@@ -12140,17 +11338,15 @@ def _fetch_url_raw(
current_host = redirect_host
continue
- # get_content_type() defaults to "text/plain" when the header is
- # absent (RFC 2045); report "" instead so callers can tell a missing
- # header apart from a server that really declared text/plain.
+ # get_content_type() defaults to "text/plain" when the header is absent (RFC 2045); report "" instead so
+ # callers can tell a missing header apart from a server that really declared text/plain.
if resp.headers.get("Content-Type") is None:
content_type = ""
else:
content_type = (resp.headers.get_content_type() or "").lower()
- # Success: read the capped body enforcing the budget between chunks
- # (see _read_capped_body), so a slow-drip server can't stretch a
- # single resp.read past the deadline.
+ # Success: read the capped body enforcing the budget between chunks (see _read_capped_body), so a
+ # slow-drip server can't stretch a single resp.read past the deadline.
declared_pdf = raw_bytes_max is None and content_type == "application/pdf"
if raw_bytes_max is not None:
read_limit = raw_bytes_max + 1
@@ -12168,8 +11364,8 @@ def _fetch_url_raw(
if body_error is not None:
return body_error, "", ""
- # A missing or wrong PDF MIME type is common: once the initial text-sized
- # read identifies PDF magic, finish the bounded download to reach the EOF xref.
+ # A missing or wrong PDF MIME type is common: once the initial text-sized read identifies PDF magic,
+ # finish the bounded download to reach the EOF xref.
if raw_bytes_max is not None:
if len(raw_bytes) > raw_bytes_max:
return f"(content exceeds the {raw_bytes_max} byte limit)", "", content_type
@@ -12210,12 +11406,12 @@ def _fetch_url_raw(
return budget_error, "", content_type
if not pdf_text:
pdf_text = "(PDF contains no extractable text)"
- # Report the true type even for a mislabeled body so the caller's "html"
- # check routes the extracted text to the plain-text path, not html_to_markdown.
+ # Report the true type even for a mislabeled body so the caller's "html" check routes the extracted text
+ # to the plain-text path, not html_to_markdown.
return None, pdf_text, "application/pdf"
- # Reject known-binary MIME types before decoding. Binary is returned as the
- # error string so the caller surfaces the placeholder, not replacement chars.
+ # Reject known-binary MIME types before decoding. Binary is returned as the error string so the caller
+ # surfaces the placeholder, not replacement chars.
if not _is_text_candidate_content_type(content_type):
# Only echo a clean MIME token back to the model.
m = re.match(r"[\w.+-]+/[\w.+-]+", content_type or "")
@@ -12249,8 +11445,8 @@ def _fetch_url_raw(
try:
raw_html = raw_bytes.decode(declared or bom_codec or "utf-8", errors = "replace")
except (LookupError, ValueError):
- # Survives lookup, fails the decode: base64/hex/zlib are not text codecs,
- # "undefined" always raises, idna rejects replace. The fallback cannot raise.
+ # Survives lookup, fails the decode: base64/hex/zlib are not text codecs, "undefined" always raises, idna
+ # rejects replace. The fallback cannot raise.
declared = None
declared_codec = None
raw_html = raw_bytes.decode(bom_codec or "utf-8", errors = "replace")
@@ -12280,9 +11476,9 @@ def _fetch_url_raw(
return f"Failed to fetch URL: {e}", "", ""
-# Tags that, at the very START of a body, mark it as HTML. Excludes ambiguous
-# tags (<div>/<p>/<span>/<a>/<img>/<h1>..<h6>/<table>) that legitimately open
-# centered-logo or badge-layout Markdown READMEs and must stay Markdown.
+# Tags that, at the very START of a body, mark it as HTML. Excludes ambiguous tags
+# (<div>/<p>/<span>/<a>/<img>/<h1>..<h6>/<table>) that legitimately open centered-logo or badge-layout Markdown
+# READMEs and must stay Markdown.
_HTML_LEADING_TAGS = (
"html",
"head",
@@ -12311,23 +11507,17 @@ _HTML_LEADING_RE = re.compile(r"<(?:!doctype\s+html|/?(?:" + "|".join(_HTML_LEAD
def _looks_like_html(body: str) -> bool:
- """True only when the document ITSELF opens with HTML.
-
- Matches an HTML doctype or a leading document/structure tag after optional
- whitespace, not a mere substring, so a Markdown README with a fenced HTML
- example or tags further down stays Markdown. Also detects bare fragments
- (``<body>``/``<article>``/...) with no doctype, so a page with a
- missing/wrong Content-Type is still converted.
- """
+ """True only when the document ITSELF opens with HTML. Matches an HTML doctype or a leading
+ document/structure tag after optional whitespace, not a mere substring, so a Markdown README
+ with a fenced HTML example or tags further down stays Markdown. Also detects bare fragments
+ with no doctype, so a page with a missing/wrong Content-Type is still converted."""
probe = body.lstrip()[:256].lower()
return bool(_HTML_LEADING_RE.match(probe))
-# Stricter than _HTML_LEADING_RE: only a real document opener (doctype or leading
-# <html>/<head>/<body>), never a block tag a Markdown file can open with. Used on
-# the raw GitHub README body so a Markdown README starting with an HTML block is
-# not run through html_to_markdown, which would collapse its headings, lists and
-# fenced code onto one line.
+# Stricter than _HTML_LEADING_RE: only a real document opener (doctype or leading <html>/<head>/<body>), never a block
+# tag a Markdown file can open with. Used on the raw GitHub README body so a Markdown README starting with an HTML
+# block is not run through html_to_markdown, which would collapse its headings, lists and fenced code onto one line.
_HTML_DOCUMENT_RE = re.compile(r"<(?:!doctype\s+html\b|/?(?:html|head|body)\b)")
@@ -12340,17 +11530,15 @@ def _looks_like_html_document(body: str) -> bool:
def _loaded_context_tokens() -> int | None:
"""The active model's context window, or None when it cannot be read.
- Mirrors `research_runs._loaded_context_length` and `routes.inference.
- _monitor_context_length`: llama.cpp first, then the orchestrator the API layer reads.
- Both branches are needed. A native/Transformers chat leaves `is_loaded` false, and
- stopping at that probe reported "unknown", which kept the full 16,000-character cap
- and reproduced on small native models exactly the overflow this budget exists to
- prevent.
-
- The ML backends live in a worker subprocess, so the in-process singleton is
- unpopulated here and importing it pulls in the ML stack; peek at the orchestrator
- instead of constructing one. Every failure is "unknown" so a fetch is never blocked by
- not knowing.
+ Mirrors `research_runs._loaded_context_length` and `routes.inference._monitor_context_length`:
+ llama.cpp first, then the orchestrator the API layer reads. Both branches are needed. A
+ native/Transformers chat leaves `is_loaded` false, and stopping at that probe reported unknown,
+ which kept the full 16,000-character cap and reproduced on small native models exactly the
+ overflow this budget exists to prevent.
+
+ The ML backends live in a worker subprocess, so the in-process singleton is unpopulated here and
+ importing it pulls in the ML stack; peek at the orchestrator instead of constructing one. Every
+ failure is unknown so a fetch is never blocked by not knowing.
"""
try:
from routes.inference import get_llama_cpp_backend # noqa: PLC0415
@@ -12381,28 +11569,24 @@ def _loaded_context_tokens() -> int | None:
def _result_char_budget(cap: int) -> int:
- """`cap`, lowered to what the serving window can actually hold.
-
- Shared by fetched pages and by terminal/python results, because the failure is the
- same: a fixed character cap has no relation to the loaded context, so on a small
- window one result fills most of it. That result lands in the NEWEST turn, which the
- fit protects, so compaction cannot drop the very thing that does not fit and the
- request goes irreducible. Measured live on a 5120-token window: 7043 and 6684 token
- requests refused, both on the code tools, whose 16,000-character cap is about 4,000
- tokens on its own.
- """
+ """`cap`, lowered to what the serving window can actually hold. Shared by fetched pages and by
+ terminal/python results, because the failure is the same: a fixed character cap has no
+ relation to the loaded context, so on a small window one result fills most of it. That result
+ lands in the NEWEST turn, which the fit protects, so compaction cannot drop the very thing
+ that does not fit and the request goes irreducible. Measured live on a 5120-token window:
+ 7043 and 6684 token requests refused, both on the code tools, whose 16,000-character cap is
+ about 4,000 tokens on its own."""
scoped = _REQUEST_CONTEXT_TOKENS.get()
- # An explicit 0/None means "asked, and unknowable" (external provider), and must NOT
- # fall through to the probe. Only an absent value keeps the process-global read.
+ # An explicit 0/None means asked, and unknowable (external provider), and must NOT fall through to the probe. Only
+ # an absent value keeps the process-global read.
ctx = _loaded_context_tokens() if scoped is _UNSET_CONTEXT_TOKENS else scoped
if not ctx:
return cap
- # Clamped to `cap` on the way out, not only on the way in. The floor keeps a result
- # worth reading when the WINDOW is the thing making it small; it is not a licence to
- # hand the model more than the install configured. Unclamped, an install running
- # `UNSLOTH_TOOL_RESULT_MAX_CHARS=500` got 500 characters from the hosted path and
- # 2,000 from this one, the moment a local window became readable -- the one function
- # whose job is to LOWER the cap raising it fourfold instead.
+ # Clamped to `cap` on the way out, not only on the way in. The floor keeps a result worth reading when the WINDOW
+ # is the thing making it small; it is not a licence to hand the model more than the install configured. Unclamped,
+ # an install running `UNSLOTH_TOOL_RESULT_MAX_CHARS=500` got 500 characters from the hosted path and 2,000 from
+ # this one, the moment a local window became readable: the one function whose job is to LOWER the cap raising it
+ # fourfold instead.
return min(cap, max(_MIN_PAGE_CHARS, int(ctx * 4 * _PAGE_CONTEXT_SHARE)))
@@ -12414,20 +11598,18 @@ def _tool_result_char_budget() -> int:
def _page_char_budget() -> int:
"""`_MAX_PAGE_CHARS`, lowered to what the serving window can actually hold.
- 16,000 characters is roughly 4,000 tokens: fine on a 128k model, nonsensical on a
- 4,864-token one. Measured there, a single fetched page came back at 12,295 characters,
- the request went irreducible at 8,995 tokens against a 3,648-token budget with
- `latest_turn_role: "tool"`, and the user was advised to shorten a conversation
- consisting of one 11-token question. Nothing downstream can recover from it either:
- the fit protects the newest turn, so compaction may not drop the very result that does
- not fit.
+ 16,000 characters is roughly 4,000 tokens: fine on a 128k model, nonsensical on a 4,864-token
+ one. Measured there, a single fetched page came back at 12,295 characters, the request went
+ irreducible at 8,995 tokens against a 3,648-token budget with `latest_turn_role: "tool"`, and
+ the user was advised to shorten a conversation consisting of one 11-token question. Nothing
+ downstream can recover from it either: the fit protects the newest turn.
- Above roughly an 11k window this returns the old constant unchanged, so only the models
- that cannot afford a whole page are affected.
+ Above roughly an 11k window this returns the old constant unchanged, so only the models that
+ cannot afford a whole page are affected.
"""
scoped = _REQUEST_CONTEXT_TOKENS.get()
- # An explicit 0/None means "asked, and unknowable" (external provider), and must NOT
- # fall through to the probe. Only an absent value keeps the process-global read.
+ # An explicit 0/None means asked, and unknowable (external provider), and must NOT fall through to the probe. Only
+ # an absent value keeps the process-global read.
ctx = _loaded_context_tokens() if scoped is _UNSET_CONTEXT_TOKENS else scoped
if not ctx:
return _MAX_PAGE_CHARS
@@ -12435,12 +11617,10 @@ def _page_char_budget() -> int:
def _request_result_room() -> int | None:
- """Tokens this result may add before the NEXT prompt is over budget.
-
- None when the caller could not say, and every cap then behaves exactly as it did
- before this existed: external providers, the hosted path and any tool loop that does
- not price its own conversation all take that leg.
- """
+ """Tokens this result may add before the NEXT prompt is over budget. None when the caller could
+ not say, and every cap then behaves exactly as it did before this existed: external
+ providers, the hosted path and any tool loop that does not price its own conversation all
+ take that leg."""
room = _REQUEST_RESULT_BUDGET.get()
if room is None:
return None
@@ -12453,8 +11633,8 @@ def _request_result_room() -> int | None:
def _window_context_tokens() -> int | None:
"""The window this request is served by, or None when it cannot be read."""
scoped = _REQUEST_CONTEXT_TOKENS.get()
- # An explicit 0/None means "asked, and unknowable" (external provider), and must NOT
- # fall through to the probe. Only an absent value keeps the process-global read.
+ # An explicit 0/None means asked, and unknowable (external provider), and must NOT fall through to the probe. Only
+ # an absent value keeps the process-global read.
ctx = _loaded_context_tokens() if scoped is _UNSET_CONTEXT_TOKENS else scoped
return ctx if ctx else None
@@ -12462,12 +11642,11 @@ def _window_context_tokens() -> int | None:
def _dense_prefix_chars(text: str, token_budget: float) -> int:
"""How many leading characters of `text` cost at most `token_budget` tokens.
- Four characters per token is an English rate. Measured with Qwen3, Llama 3.2 and
- tiktoken on real fetched pages, CJK prose runs 1.3-1.6 characters per token, and the
- percent-escaped links a CJK page is full of (`%E7%9F%A5`) run 1.3-1.5: both are the
- same non-ASCII bytes, one spelled in ASCII. Charging them a token each, the rule
- `context_window.estimate_messages_tokens_dense` already uses, keeps the share the
- caller asked to reserve a share instead of the whole budget.
+ Four characters per token is an English rate. Measured with Qwen3, Llama 3.2 and tiktoken on
+ real fetched pages, CJK prose runs 1.3-1.6 characters per token, and the percent-escaped links a
+ CJK page is full of run 1.3-1.5: both are the same non-ASCII bytes, one spelled in ASCII.
+ Charging them a token each, the rule `context_window.estimate_messages_tokens_dense` already
+ uses, keeps the share the caller asked to reserve a share instead of the whole budget.
One pass, so it costs nothing next to the fetch it sizes.
"""
@@ -12482,94 +11661,76 @@ def _dense_prefix_chars(text: str, token_budget: float) -> int:
else:
spent += 1.0 if ord(text[index]) > 127 else 0.25
index += 1
- # Cut on whole characters (and whole escapes), so the tail is never half a
- # percent-escape the model has to guess at.
+ # Cut on whole characters (and whole escapes), so the tail is never half a percent-escape the model has to
+ # guess at.
if spent > token_budget:
return start
return length
-# `count_chat_tokens` prices a chunk by rendering it through the model's chat template
-# (/apply-template) and tokenizing the result, so the probe can only measure text the
-# template actually RENDERS. A standalone tool message is not that text: the Gemma-4
-# templates shipped in `assets/chat_templates` skip it outright -- `gemma-4.jinja:232` is
-# `{%- if message['role'] != 'tool' -%}`, and a tool result is only emitted while scanning
-# forward from an assistant tool call -- so a 600-character payload rendered to 46
-# characters with the payload absent, and 7,168 characters of base64 priced as ~12 tokens
-# of framing sailed under any budget on the first pass. A user turn is rendered by every
-# template checked: both bundled Gemma-4 templates, Qwen3, Llama-3.2, Mistral and
-# Hermes-3. The assistant-tool-call pair is not a safe alternative -- Mistral's template
-# raises on any tool call id that is not nine alphanumeric characters.
+# `count_chat_tokens` prices a chunk by rendering it through the model's chat template (/apply-template) and
+# tokenizing the result, so the probe can only measure text the template actually RENDERS. A standalone tool message
+# is not that text: the Gemma-4 templates in `assets/chat_templates` skip it outright (`gemma-4.jinja:232` is `{%- if
+# message['role'] != 'tool' -%}`, and a tool result is only emitted while scanning forward from an assistant tool
+# call), so a 600-character payload rendered to 46 characters with the payload absent, and 7,168 characters of base64
+# priced as ~12 tokens of framing sailed under any budget on the first pass. A user turn is rendered by every template
+# checked: both bundled Gemma-4 templates, Qwen3, Llama-3.2, Mistral and Hermes-3. The assistant-tool-call pair is not
+# a safe alternative: Mistral's template raises on any tool call id that is not nine alphanumeric characters.
_PROBE_ROLE = "user"
-# The guard below: how few tokens a rendered chunk may cost before the count is treated as
-# not having measured it. Deliberately far past anything real text reaches -- the densest
-# packing measured with Qwen3 is 128 characters per token, for a chunk of nothing but
-# spaces, and ordinary output runs 1-8. A template that drops the content lands at
+# The guard below: how few tokens a rendered chunk may cost before the count is treated as not having measured it.
+# Deliberately far past anything real text reaches: the densest packing measured with Qwen3 is 128 characters per
+# token, for a chunk of nothing but spaces, and ordinary output runs 1-8. A template that drops the content lands at
# hundreds, or at infinity as the chunk grows, because its count does not move at all.
_MAX_PROBE_CHARS_PER_TOKEN = 256
-# A measured count is a pure function of (model, chat template, window, chunk), and each
-# `count_chat_tokens` is two llama-server calls (/apply-template then /tokenize) over a
-# fresh connection. So the framing baseline -- one number for EVERY result the process
-# truncates -- is worth remembering, and so is any prefix already priced.
-#
-# Keyed on the resident llama-server process, because the count depends on the EFFECTIVE
-# chat template and the managed fields cannot reconstruct it: user pass-through args are
-# appended verbatim after Unsloth's own flags (`llama_cpp.py`, "User pass-through args go
-# last") and llama.cpp is last-wins, so `--chat-template` in extra args renders through a
-# template `_chat_template_override` never sees. Reload the same GGUF into the same window
-# with only those args changed and every managed field matches while the rendering does
-# not, which would price a prefix by a template no longer serving it. `is_loaded` is
-# `self._process is not None and self._healthy` and args reach llama-server only on its
-# command line, so any change to them is a new process by construction -- which settles it
-# without enumerating the flags that matter. The content fields ride along so a recycled
-# pid still has to agree on everything before a count is reused.
+# A measured count is a pure function of (model, chat template, window, chunk), and each `count_chat_tokens` is two
+# llama-server calls over a fresh connection. So the framing baseline, one number for EVERY result the process
+# truncates, is worth remembering, and so is any prefix already priced.
+# Keyed on the resident llama-server process, because the count depends on the EFFECTIVE chat template and the managed
+# fields cannot reconstruct it: user pass-through args are appended verbatim after Unsloth's own flags and llama.cpp
+# is last-wins, so `--chat-template` in extra args renders through a template `_chat_template_override` never sees.
+# Reload the same GGUF into the same window with only those args changed and every managed field matches while the
+# rendering does not, which would price a prefix by a template no longer serving it. `is_loaded` is `self._process is
+# not None and self._healthy` and args reach llama-server only on its command line, so any change to them is a new
+# process by construction. The content fields ride along so a recycled pid still has to agree on everything before a
+# count is reused.
_PROBE_COUNT_CACHE: dict = {}
-# Tool calls run in worker threads (`tool_stream_exec.stream_tool_execution` runs each
-# invocation in one), so concurrent chats reach this cache at the same time. A bare dict
-# assignment is atomic under the GIL, but the LRU touch and the eviction below are
-# read-then-mutate sequences and are not: measured with 24 threads over a 3-entry cache,
-# `cache.pop(chunk)` raised KeyError after another thread evicted the same key, `del
-# cache[victim]` raised on a victim already taken, and choosing a victim raised
-# "dictionary changed size during iteration" -- 90 exceptions in one run, none of them
-# caught on the way out of `_truncate`.
-#
-# Held only across the dict work, never across a `count_chat_tokens` call. Serialising the
-# round trips themselves would trade a shared cache for a shared queue, which is the
-# opposite of the point. Two threads may therefore measure the same chunk at once and both
-# store it; the value is the same either way, so that costs one duplicate measurement,
+# Tool calls run in worker threads, so concurrent chats reach this cache at the same time. A bare dict assignment is
+# atomic under the GIL, but the LRU touch and the eviction below are read-then-mutate sequences and are not: measured
+# with 24 threads over a 3-entry cache, `cache.pop(chunk)` raised KeyError after another thread evicted the same key,
+# `del cache[victim]` raised on a victim already taken, and choosing a victim raised dictionary changed size during
+# iteration -- 90 exceptions in one run, none caught on the way out of `_truncate`.
+# Held only across the dict work, never across a `count_chat_tokens` call. Serialising the round trips themselves
+# would trade a shared cache for a shared queue, which is the opposite of the point. Two threads may therefore measure
+# the same chunk at once and both store it; the value is the same either way, so that costs one duplicate measurement,
# which is what the merge base did on every result anyway.
_PROBE_COUNT_LOCK = threading.Lock()
-# The empty chunk: the framing baseline, and the entry eviction pins. Named so the two
-# places that treat it specially cannot drift apart from a bare "".
+# The empty chunk: the framing baseline, and the entry eviction pins. Named so the two places that treat it specially
+# cannot drift apart from a bare "".
_PROBE_BASELINE = ""
-# One model's counts at a time (a new identity clears the map). Ten times the worst case
-# for one result: `_EXACT_FIT_PASSES` prefixes plus the baseline.
+# One model's counts at a time (a new identity clears the map). Ten times the worst case for one result:
+# `_EXACT_FIT_PASSES` prefixes plus the baseline.
_PROBE_COUNT_CACHE_ENTRIES = 64
-# And a bound on what is HELD, since the entry count alone does not give one. Only a
-# fetched page is capped at `_MAX_PAGE_CHARS`; a tool result's prefix is bounded by
-# `min(UNSLOTH_TOOL_RESULT_MAX_CHARS, ctx * 4 * _PAGE_CONTEXT_SHARE)` and `_env_int`
-# accepts any positive integer, so a large configured cap on a large window makes one
-# prefix enormous. Measured: a cap of 1,000,000 on a 262k window cached 733,971 characters
-# from a SINGLE result, which 64 entries would then multiply. This also drops an oversized
-# prefix rather than storing it. The baseline is 0 characters, so the entry that earns the
-# most is never the one squeezed out.
+# And a bound on what is HELD, since the entry count alone does not give one. Only a fetched page is capped at
+# `_MAX_PAGE_CHARS`; a tool result's prefix is bounded by `min(UNSLOTH_TOOL_RESULT_MAX_CHARS, ctx * 4 *
+# _PAGE_CONTEXT_SHARE)` and `_env_int` accepts any positive integer, so a large configured cap on a large window makes
+# one prefix enormous. Measured: a cap of 1,000,000 on a 262k window cached 733,971 characters from a SINGLE result,
+# which 64 entries would then multiply. This also drops an oversized prefix rather than storing it. The baseline is 0
+# characters, so the entry that earns the most is never the one squeezed out.
_PROBE_COUNT_CACHE_CHARS = 1_000_000
def _probe_identity(llama, ctx: int):
- """A key that changes whenever a measured count could, or None to disable the cache.
-
- None is the safe answer: it costs round trips, it never returns a stale number.
- """
+ """A key that changes whenever a measured count could, or None to disable the cache. None is the
+ safe answer: it costs round trips, it never returns a stale number."""
try:
- # The resident llama-server. No process is no key: a backend this module cannot
- # tie a count to keeps paying for its round trips, which is the safe direction.
+ # The resident llama-server. No process is no key: a backend this module cannot tie a count to keeps paying
+ # for its round trips, which is the safe direction.
pid = getattr(getattr(llama, "_process", None), "pid", None)
if not isinstance(pid, int):
return None
@@ -12579,8 +11740,8 @@ def _probe_identity(llama, ctx: int):
getattr(llama, "model_identifier", None),
getattr(llama, "_gguf_load_identity", None),
getattr(llama, "_chat_template_override", None),
- # The gap the process id closes, spelled out: whatever the user appended to
- # the command line, including a template that overrides the managed one.
+ # The gap the process id closes, spelled out: whatever the user appended to the command line, including a
+ # template that overrides the managed one.
tuple(getattr(llama, "_extra_args", None) or ()),
)
hash(key) # an unhashable field is also "do not cache", not a TypeError upstream
@@ -12590,19 +11751,17 @@ def _probe_identity(llama, ctx: int):
def _probe_cache(llama, ctx: int) -> dict:
- """The count cache for the model serving this request.
-
- A fresh per-call dict when the model has no identity, so the caller's code path is the
- same either way and an unidentifiable backend simply gets no reuse between calls.
- """
+ """The count cache for the model serving this request. A fresh per-call dict when the model has
+ no identity, so the caller's code path is the same either way and an unidentifiable backend
+ simply gets no reuse between calls."""
identity = _probe_identity(llama, ctx)
if identity is None:
return {}
with _PROBE_COUNT_LOCK:
cache = _PROBE_COUNT_CACHE.get(identity)
if cache is None:
- # A different model is serving now. Drop the previous one's numbers rather than
- # keep them around to be matched against.
+ # A different model is serving now. Drop the previous one's numbers rather than keep them around to be
+ # matched against.
_PROBE_COUNT_CACHE.clear()
cache = _PROBE_COUNT_CACHE[identity] = {}
return cache
@@ -12611,13 +11770,13 @@ def _probe_cache(llama, ctx: int) -> dict:
def _neutralized_for_prompt(chunk: str, llama) -> str:
"""``chunk`` as the outgoing request will carry it, rather than as it is in hand.
- The same sweep the request path applies, through the same helper and the backend's own
- markup profile, so the two cannot disagree about what a marker becomes. `_PROBE_ROLE`
- is a user role, which takes the full control rewrite a tool result takes rather than
- the boundary-only one an assistant turn takes.
+ The same sweep the request path applies, through the same helper and the backend's own markup
+ profile, so the two cannot disagree about what a marker becomes. `_PROBE_ROLE` is a user role,
+ which takes the full control rewrite a tool result takes rather than the boundary-only one an
+ assistant turn takes.
- Best effort: a sweep that cannot run leaves the text as it was, which is the estimate
- this had before and never worse.
+ Best effort: a sweep that cannot run leaves the text as it was, which is the estimate this had
+ before and never worse.
"""
if not chunk:
return chunk
@@ -12637,14 +11796,12 @@ def _neutralized_for_prompt(chunk: str, llama) -> str:
def _loaded_token_counter(ctx: int):
- """The tokenizer of the model serving this request, or None when there is not one.
-
- Same probe as `_loaded_context_tokens`: whatever can answer for the window can also
- price a string exactly, and `llama_cpp` already hands this same counter to the RAG
- admission check for exactly this reason. Gated on the backend's own window matching
- the one the budget was sized against, so a resident GGUF never prices a request that
- a different model (native, or an external endpoint) is actually answering.
- """
+ """The tokenizer of the model serving this request, or None when there is not one. Same probe as
+ `_loaded_context_tokens`: whatever can answer for the window can also price a string exactly,
+ and `llama_cpp` already hands this same counter to the RAG admission check for exactly this
+ reason. Gated on the backend's own window matching the one the budget was sized against, so a
+ resident GGUF never prices a request that a different model (native, or an external endpoint)
+ is actually answering."""
try:
from routes.inference import get_llama_cpp_backend # noqa: PLC0415
@@ -12660,24 +11817,23 @@ def _loaded_token_counter(ctx: int):
return None
cache = _probe_cache(llama, ctx)
- # Whether anything said here will outlive this call, and whether `/apply-template` has
- # already refused once. Both only gate the strict attempt, never a returned value.
+ # Whether anything said here will outlive this call, and whether `/apply-template` has already refused once. Both
+ # only gate the strict attempt, never a returned value.
retained = bool(_probe_identity(llama, ctx))
template_down: list[bool] = []
def _remember(chunk: str, value: int) -> None:
"""Hold `value` for `chunk`, evicting least-recently-used entries to stay in bounds.
- Refusing new entries once full was worse than not caching at all. Most tool results
- are one-offs, so the first `_PROBE_COUNT_CACHE_ENTRIES` distinct prefixes froze the
- cache on text that would never be asked about again -- and because the baseline is
- only priced when a count comes in OVER budget, a process that handled 64 results
- that FIT first locked it out for good. Measured: after 64 English results, every
- later dense result paid 4 counter calls (8 HTTP) again, exactly the merge base's
- cost, for the life of the process.
+ Refusing new entries once full was worse than not caching at all. Most tool results are
+ one-offs, so the first `_PROBE_COUNT_CACHE_ENTRIES` distinct prefixes froze the cache on
+ text that would never be asked about again, and because the baseline is only priced when a
+ count comes in OVER budget, a process that handled 64 results that FIT first locked it out
+ for good. Measured: after 64 English results, every later dense result paid 4 counter calls
+ (8 HTTP) again, exactly the merge base's cost, for the life of the process.
- So evict, and pin the baseline: it is 0 characters, it is the same number for every
- result this process truncates, and it is the one entry a bounded cache most needs.
+ So evict, and pin the baseline: it is 0 characters, it is the same number for every result
+ this process truncates, and it is the one entry a bounded cache most needs.
"""
if len(chunk) > _PROBE_COUNT_CACHE_CHARS:
return # too large to hold at all; evicting the rest would not help
@@ -12686,8 +11842,8 @@ def _loaded_token_counter(ctx: int):
while len(cache) >= _PROBE_COUNT_CACHE_ENTRIES or (
held + len(chunk) > _PROBE_COUNT_CACHE_CHARS
):
- # `list()` so the scan cannot trip over another thread's insert, and
- # `pop(..., None)` so a victim someone else already took is not an error.
+ # `list()` so the scan cannot trip over another thread's insert, and `pop(..., None)` so a victim
+ # someone else already took is not an error.
victim = next((key for key in list(cache) if key != _PROBE_BASELINE), None)
if victim is None:
return # only the pinned baseline is left, and it stays
@@ -12696,35 +11852,29 @@ def _loaded_token_counter(ctx: int):
cache[chunk] = value
def _rendered(chunk: str):
- # Priced as the request will really carry it. A tool result is swept for control
- # markup before it is sent (`neutralize_control_markup_in_messages`, #7066), and
- # the sweep costs tokens: a live `<|eot_id|>` is one special token raw and several
- # ordinary ones once it has been broken up. A result full of them measured on the
- # raw text fits the room here and does not fit the prompt that follows, which is
- # the overflow this budget exists to prevent, reached through the leg that is
- # supposed to be the accurate one.
+ # Priced as the request will really carry it. A tool result is swept for control markup before it is sent
+ # (`neutralize_control_markup_in_messages`, #7066), and the sweep costs tokens: a live `<|eot_id|>` is one
+ # special token raw and several ordinary ones once it has been broken up. A result full of them measured on
+ # the raw text fits the room here and does not fit the prompt that follows, which is the overflow this budget
+ # exists to prevent, reached through the leg that is supposed to be the accurate one.
chunk = _neutralized_for_prompt(chunk, llama)
with _PROBE_COUNT_LOCK:
hit = cache.get(chunk)
if hit is not None and chunk != _PROBE_BASELINE:
- # Most recently used moves to the back. `pop(..., None)` and the re-check
- # keep this a no-op rather than a KeyError if it lost a race to an evictor.
+ # Most recently used moves to the back. `pop(..., None)` and the re-check keep this a no-op rather
+ # than a KeyError if it lost a race to an evictor.
if cache.pop(chunk, None) is not None:
cache[chunk] = hit
if hit is not None:
return hit
- # Strict, so that a count is only retained when the chat template really rendered
- # it. With `strict = False` a failed `/apply-template` still returns the plain-text
- # fallback, which drops role markers and special tokens -- fine as a one-off answer,
- # but it prices a prompt the model will never be sent, and caching it would let one
+ # Strict, so that a count is only retained when the chat template really rendered it. With `strict = False` a
+ # failed `/apply-template` still returns the plain-text fallback, which drops role markers and special tokens:
+ # fine as a one-off answer, but it prices a prompt the model will never be sent, and caching it would let one
# bad moment quietly under-count that prefix for the life of the process.
- #
- # Asked at most once per counter, and not at all when nothing would be retained
- # anyway. Strictness exists only to decide whether a count may be KEPT, so paying
- # for it twice would spend round trips to answer a question already settled: a
- # template that would not render is not going to start, and this whole change is
- # about not making calls that cannot change an answer. So a template outage costs
- # one extra attempt for the first probe of a result rather than one for every probe.
+ # Asked at most once per counter, and not at all when nothing would be retained anyway. Strictness exists only
+ # to decide whether a count may be KEPT, so paying for it twice would spend round trips to answer a question
+ # already settled. So a template outage costs one extra attempt for the first probe of a result rather than
+ # one for every probe.
message = [{"role": _PROBE_ROLE, "content": chunk}]
rendered = False
if retained and not template_down:
@@ -12740,20 +11890,18 @@ def _loaded_token_counter(ctx: int):
logger.debug("result budget: exact count failed", exc_info = True)
return None
value = int(spent) if isinstance(spent, (int, float)) and spent > 0 else None
- # The fallback's count is USED, exactly as before -- it still tokenizes the real
- # bytes, which is what catches dense ASCII, and the estimate it would otherwise fall
- # back to undercharges base64 several fold. It is simply not retained: like a
- # failure, it is a property of the moment rather than of the text.
+ # The fallback's count is USED, exactly as before: it still tokenizes the real bytes, which is what catches
+ # dense ASCII, and the estimate it would otherwise fall back to undercharges base64 several fold. It is simply
+ # not retained: like a failure, it is a property of the moment rather than of the text.
if value is not None and rendered:
_remember(chunk, value)
return value
- # What the turn costs with nothing in it: the baseline the guard measures growth
- # against, so a template that renders no content is caught by its count not moving
- # rather than by a guess about density. Left IN the total rather than subtracted -- 8
- # tokens on Qwen3 and 11 on the Gemma-4 templates, under 1% of a 1,792-token share, and
- # the real tool turn pays its own framing anyway, so counting it errs toward a smaller
- # result. Priced on demand: see `_count`.
+ # What the turn costs with nothing in it: the baseline the guard measures growth against, so a template that
+ # renders no content is caught by its count not moving rather than by a guess about density. Left IN the total
+ # rather than subtracted -- 8 tokens on Qwen3 and 11 on the Gemma-4 templates, under 1% of a 1,792-token share,
+ # and the real tool turn pays its own framing anyway, so counting it errs toward a smaller result. Priced on
+ # demand: see `_count`.
baseline: list[int] = []
def _framing() -> int:
@@ -12762,14 +11910,12 @@ def _loaded_token_counter(ctx: int):
return baseline[0]
def _count(chunk: str, token_budget: float = 0.0):
- """Tokens for `chunk`, or None when the count did not measure it.
-
- `token_budget` is an optimisation and nothing more. A count within budget and a
- count the guard rejects both make the caller return its own estimate unchanged, so
- when `spent` fits, the baseline that separates those two paths cannot change the
- answer and is not priced -- which is why an English result costs one round trip
- rather than two. The default of 0 means "no budget", so the guard always runs.
- """
+ """Tokens for `chunk`, or None when the count did not measure it. `token_budget` is an
+ optimisation and nothing more. A count within budget and a count the guard rejects both
+ make the caller return its own estimate unchanged, so when `spent` fits, the baseline
+ that separates those two paths cannot change the answer and is not priced, which is why
+ an English result costs one round trip rather than two. The default of 0 means no budget,
+ so the guard always runs."""
spent = _rendered(chunk)
if spent is None:
return None
@@ -12791,9 +11937,9 @@ def _loaded_token_counter(ctx: int):
return _count
-# Measured: English costs one pass (it fits on the first count), base64 two, and a mixed
-# result -- dense output followed by prose -- three, with the last as slack. Bounded
-# rather than a binary search because each pass is a llama-server round trip.
+# Measured: English costs one pass (it fits on the first count), base64 two, and a mixed result (dense output followed
+# by prose) three, with the last as slack. Bounded rather than a binary search because each pass is a llama-server
+# round trip.
_EXACT_FIT_PASSES = 5
@@ -12806,49 +11952,42 @@ def _exact_prefix_chars(
) -> int:
"""`chars`, shrunk until the prefix really costs `token_budget`. Never grown.
- The estimate below charges every ASCII character a flat 0.25 tokens, which is an
- English rate and wrong in the same direction for the ASCII the code tools print most:
- measured with Qwen3-4B and Llama-3.2 on a 5,120-token window, where the character cap
- admits 7,168 characters against a 1,792-token share, `base64 payload.bin` came back at
- 5,361 tokens, `hexdump -C` at 5,540 and `sha256sum *` at 5,109 -- 105-108% of the
- WHOLE window, in the newest turn, which the fit protects. A four-message thread (one
- 8-token question and one such result) was refused irreducible at 5,475 tokens against
- a 3,840-token prompt budget. No character rule closes that: the same rule that charges
- a 76-character base64 line its real 57 tokens charges English prose 40% more than it
- costs and shrinks every page that was already fine. So when a tokenizer is serving the
- request, ask it; when none is, keep the estimate exactly as it was.
- """
- # `floor` is the caller's, not this function's: when a thread has 100 tokens left, the
- # 2,000-character comfort floor is 666 tokens of dense output and the overflow this
- # whole path exists to prevent. Defaulted, so the page callers are unchanged.
+ The estimate below charges every ASCII character a flat 0.25 tokens, which is an English rate
+ and wrong in the same direction for the ASCII the code tools print most: measured with Qwen3-4B
+ and Llama-3.2 on a 5,120-token window, where the character cap admits 7,168 characters against a
+ 1,792-token share, `base64 payload.bin` came back at 5,361 tokens, `hexdump -C` at 5,540 and
+ `sha256sum *` at 5,109 -- 105-108% of the WHOLE window, in the newest turn, which the fit
+ protects. A four-message thread was refused irreducible at 5,475 tokens against a 3,840-token
+ prompt budget. No character rule closes that: the same rule that charges a 76-character base64
+ line its real 57 tokens charges English prose 40% more than it costs. So when a tokenizer is
+ serving the request, ask it; when none is, keep the estimate exactly as it was.
+ """
+ # `floor` is the caller's, not this function's: when a thread has 100 tokens left, the 2,000-character comfort
+ # floor is 666 tokens of dense output and the overflow this whole path exists to prevent. Defaulted, so the page
+ # callers are unchanged.
if floor is None:
floor = _MIN_PAGE_CHARS
- # An estimate already at or below the floor the caller guarantees cannot be improved
- # on, so nothing measured here could change its answer. Every value below is at most
- # `chars` or is exactly `floor`, so with `chars <= floor` the caller lands on the same
- # number whichever branch is taken. Checked before the counter is even looked up: this
- # is the small-window case, and it used to spend a full set of round trips
- # rediscovering a number the caller already had. Against the caller's floor rather
- # than `_MIN_PAGE_CHARS` itself, since a room-aware caller passes a lower one and
- # returning early on the legacy constant would skip the measurement it asked for.
+ # An estimate already at or below the floor the caller guarantees cannot be improved on, so nothing measured here
+ # could change its answer. Every value below is at most `chars` or is exactly `floor`, so with `chars <= floor`
+ # the caller lands on the same number whichever branch is taken. Checked before the counter is even looked up:
+ # this is the small-window case, and it used to spend a full set of round trips rediscovering a number the caller
+ # already had. Against the caller's floor rather than `_MIN_PAGE_CHARS` itself, since a room-aware caller passes a
+ # lower one.
if chars <= floor:
return chars
counter = _loaded_token_counter(ctx)
if counter is None:
return chars
- # Every value this returns is either a MEASURED fit, the caller's own estimate (when
- # nothing could be measured), or the floor. A proportional shrink assumes the retained
- # prefix keeps the average density of the whole, which is false for the shape the code
- # tools produce most: dense output followed by prose. Cutting prose off a
- # base64-then-English result raises the density of what is left, so each pass gains
- # less than it asked for and a fixed pass count used to hand back the last shrink
- # unmeasured -- 3,497 characters costing 1,978 tokens against a 1,792-token share
- # (110%), measured with Qwen3-4B, which is the irreducible overflow this budget exists
- # to prevent.
+ # Every value this returns is either a MEASURED fit, the caller's own estimate (when nothing could be measured),
+ # or the floor. A proportional shrink assumes the retained prefix keeps the average density of the whole, which is
+ # false for the shape the code tools produce most: dense output followed by prose. Cutting prose off a
+ # base64-then-English result raises the density of what is left, so each pass gains less than it asked for and a
+ # fixed pass count used to hand back the last shrink unmeasured -- 3,497 characters costing 1,978 tokens against a
+ # 1,792-token share, measured with Qwen3-4B, which is the irreducible overflow this budget exists to prevent.
previous = None # the last (chars, tokens) pair, for the secant step below
for _ in range(_EXACT_FIT_PASSES):
- # The budget goes with the chunk so a count that already fits can skip pricing the
- # framing baseline it would only be compared against. See `_count`.
+ # The budget goes with the chunk so a count that already fits can skip pricing the framing baseline it would
+ # only be compared against. See `_count`.
spent = counter(text[:chars], token_budget)
if spent is None:
return chars # nothing to measure with; the estimate stands, as before
@@ -12856,38 +11995,35 @@ def _exact_prefix_chars(
return chars # measured, not assumed
fitted = int(chars * token_budget / spent)
if previous is not None:
- # Two measurements price the TAIL that was cut rather than the whole prefix,
- # which is what the proportional step gets wrong. Take whichever is smaller:
- # this only ever shrinks faster, never grows.
+ # Two measurements price the TAIL that was cut rather than the whole prefix, which is what the
+ # proportional step gets wrong. Take whichever is smaller: this only ever shrinks faster, never grows.
prior_chars, prior_spent = previous
per_char = (prior_spent - spent) / (prior_chars - chars)
if per_char > 0:
fitted = min(fitted, chars - int((spent - token_budget) / per_char))
previous = (chars, spent)
- # The floor still applies, and stopping here saves a round trip that cannot
- # change the answer.
+ # The floor still applies, and stopping here saves a round trip that cannot change the answer.
if fitted <= floor:
return floor
chars = min(fitted, chars - 1) # always progress, so the loop cannot stall
- # Out of passes with the last shrink still unmeasured. Returning it would be the
- # unchecked prefix above, so fall back to the floor the caller guarantees anyway.
+ # Out of passes with the last shrink still unmeasured. Returning it would be the unchecked prefix above, so fall
+ # back to the floor the caller guarantees anyway.
return floor
def _can_measure_tokens(ctx: int, text: str) -> bool:
- """Whether this request's tokens can really be counted, not merely whether a counter
- is exposed.
-
- `_loaded_token_counter` returns a callable that answers None whenever the probe does
- not come back with a number: `/apply-template` failing, or a chat template that drops
- the probe role, or a backend that stopped serving between the check and the call.
- `_exact_prefix_chars` then hands back the caller's estimate untouched, which charges
- plain ASCII the English four characters per token; base64, minified JSON and hashes
- run nearer two, so a room that was never halved is spent about twice over. A counter
- that cannot measure has to be treated exactly like a counter that is not there.
-
- Probed on this text's own opening rather than a constant, so a template that refuses
- some content and not other content is judged on what is actually being sized.
+ """Whether this request's tokens can really be counted, not merely whether a counter is exposed.
+
+ `_loaded_token_counter` returns a callable that answers None whenever the probe does not come
+ back with a number: `/apply-template` failing, or a chat template that drops the probe role, or
+ a backend that stopped serving between the check and the call. `_exact_prefix_chars` then hands
+ back the caller's estimate untouched, which charges plain ASCII the English four characters per
+ token; base64, minified JSON and hashes run nearer two, so a room that was never halved is spent
+ about twice over. A counter that cannot measure has to be treated exactly like a counter that is
+ not there.
+
+ Probed on this text's own opening rather than a constant, so a template that refuses some
+ content and not other content is judged on what is actually being sized.
"""
counter = _loaded_token_counter(ctx)
if counter is None:
@@ -12900,12 +12036,10 @@ _MEASURABILITY_PROBE_CHARS = 64
def _text_token_cost(text: str, ctx: int) -> float:
- """What ``text`` really costs, measured when the serving model can measure it.
-
- The estimate is the inverse of `_dense_prefix_chars`: ASCII at the English four
- characters per token, everything else at one. Doubled when nothing can check it, for
- the same reason `_UNMEASURED_ROOM_MARGIN` halves a room that cannot be measured.
- """
+ """What ``text`` really costs, measured when the serving model can measure it. The estimate is
+ the inverse of `_dense_prefix_chars`: ASCII at the English four characters per token,
+ everything else at one. Doubled when nothing can check it, for the same reason
+ `_UNMEASURED_ROOM_MARGIN` halves a room that cannot be measured."""
counter = _loaded_token_counter(ctx) if ctx else None
measured = None
if counter is not None:
@@ -12916,8 +12050,8 @@ def _text_token_cost(text: str, ctx: int) -> float:
logger.debug("token count failed", exc_info = True)
if measured is not None:
return measured
- # A counter that could not answer is a counter that is not there: taking its presence
- # as proof the estimate is safe is what leaves dense ASCII priced at the English rate.
+ # A counter that could not answer is a counter that is not there: taking its presence as proof the estimate is
+ # safe is what leaves dense ASCII priced at the English rate.
estimate = sum(0.25 if character.isascii() else 1.0 for character in text)
return estimate / _UNMEASURED_ROOM_MARGIN
@@ -12927,76 +12061,65 @@ def _dense_char_limit(
max_chars: int,
reserve_tokens: float = 0.0,
) -> int:
- """`max_chars`, lowered when `text` tokenises denser than four characters per token.
-
- Without this the window-derived caps above reserve their share only for English. On
- the 4,864-token window this PR was measured against, the 6,809-character page budget
- is 35% of the window in English and 3,800-4,500 real tokens of a Chinese or Japanese
- page: 80-95% of the whole prompt budget, in the newest turn, which the fit protects.
- That is the same irreducible refusal the budget exists to prevent.
- """
+ """`max_chars`, lowered when `text` tokenises denser than four characters per token. Without
+ this the window-derived caps above reserve their share only for English. On the 4,864-token
+ window this PR was measured against, the 6,809-character page budget is 35% of the window in
+ English and 3,800-4,500 real tokens of a Chinese or Japanese page: 80-95% of the whole prompt
+ budget, in the newest turn, which the fit protects. That is the same irreducible refusal the
+ budget exists to prevent."""
ctx = _window_context_tokens()
room = _request_result_room()
if room is None and (not ctx or len(text) <= _MIN_PAGE_CHARS):
- # Nothing measured, so the caller's cap is the only budget there is, and the
- # reserve comes off it at the same four characters per token used everywhere else
- # the real rate is unknown.
+ # Nothing measured, so the caller's cap is the only budget there is, and the reserve comes off it at the same
+ # four characters per token used everywhere else the real rate is unknown.
return max(0, max_chars - int(reserve_tokens * 4))
if room is not None and not _can_measure_tokens(ctx or 0, text):
- # Nothing here can measure this model's tokens: `_can_measure_tokens` answers only
- # for a resident GGUF that just proved it can price a string, and a native
- # safetensors model is served through a loop with no rolling fit to recover if the
- # estimate is wrong. The estimate below
- # charges plain ASCII four characters per token, which is an English rate; base64,
- # minified JSON and hashes run nearer two, so the room could be spent twice over.
- # Halved so the optimistic rate becomes a pessimistic one. It costs a shorter
- # result on a path that cannot check its own arithmetic, which is the side to be
- # wrong on when being wrong the other way is an unrecoverable turn.
+ # Nothing here can measure this model's tokens: `_can_measure_tokens` answers only for a resident GGUF that
+ # just proved it can price a string, and a native safetensors model is served through a loop with no rolling
+ # fit to recover if the estimate is wrong. The estimate below charges plain ASCII four characters per token,
+ # which is an English rate; base64, minified JSON and hashes run nearer two, so the room could be spent twice
+ # over. Halved so the optimistic rate becomes a pessimistic one. It costs a shorter result on a path that
+ # cannot check its own arithmetic, which is the side to be wrong on when being wrong the other way is an
+ # unrecoverable turn.
room = int(room * _UNMEASURED_ROOM_MARGIN)
- # Kept a float, so English text lands on exactly the character budget rather than
- # one character short of it. Unknown window, known room: the room is the whole answer,
- # which is the native case where nothing here can see a context length.
+ # Kept a float, so English text lands on exactly the character budget rather than one character short of it.
+ # Unknown window, known room: the room is the whole answer, which is the native case where nothing here can see a
+ # context length.
share = float(ctx * _PAGE_CONTEXT_SHARE) if ctx else float(room)
- # Whatever the caller will append is part of what has to fit, and it is taken off the
- # TOKEN budget rather than off the character cap: a punctuation-heavy path tokenises
- # far more densely than the prose characters that would otherwise be dropped to make
- # room for it, so subtracting its length in characters buys less room than it costs.
+ # Whatever the caller will append is part of what has to fit, and it is taken off the TOKEN budget rather than off
+ # the character cap: a punctuation-heavy path tokenises far more densely than the prose characters that would
+ # otherwise be dropped to make room for it, so subtracting its length in characters buys less room than it costs.
share = max(0.0, share - reserve_tokens)
if room is not None:
room = max(0, int(room - reserve_tokens))
- # The share is a fraction of the WINDOW and does not fall as the thread fills, so
- # on its own it lets the last result before an overflow claim as much as the
- # first. Whichever of the two is smaller is the one that has to hold.
+ # The share is a fraction of the WINDOW and does not fall as the thread fills, so on its own it lets the last
+ # result before an overflow claim as much as the first. Whichever of the two is smaller is the one that has to
+ # hold.
share = min(share, float(room))
# Never below the floor that keeps a result worth reading...
floor = _MIN_PAGE_CHARS
if room is not None:
- # ...but the floor is a comfort, not a right. 2,000 characters of dense output on
- # a thread with room for 100 tokens is the overflow this budget exists to prevent,
- # and the fit protects the newest turn so nothing downstream recovers. In the
- # extreme it leaves the stub alone, which is small enough to stay servable.
- #
- # MEASURED, not estimated: the flat four-characters-per-token rule hands back
- # about a third more than the room holds. Bottomed at one character rather than
- # the legacy floor, since going below it is the point.
+ # ...but the floor is a comfort, not a right. 2,000 characters of dense output on a thread with room for 100
+ # tokens is the overflow this budget exists to prevent, and the fit protects the newest turn so nothing
+ # downstream recovers. In the extreme it leaves the stub alone, which is small enough to stay servable.
+ # MEASURED, not estimated: the flat four-characters-per-token rule hands back about a third more than the room
+ # holds. Bottomed at one character rather than the legacy floor, since going below it is the point.
room_chars = _dense_prefix_chars(text, float(room))
if not ctx:
- # No window to measure against, so the estimate above is the answer, already
- # halved for being unmeasurable.
+ # No window to measure against, so the estimate above is the answer, already halved for being
+ # unmeasurable.
return min(max_chars, room_chars)
- # Bottomed at ZERO, not at one character. A thread at its budget measures a room of
- # zero, and a real tokenizer charges for the framing around even an empty string,
- # so the exact fit lands on nothing fitting. One character here is not a rounding
- # detail: it puts `_truncate` past its `limit <= 0` stub and back on the ordinary
- # notice, which is the ~90 tokens the stub exists to avoid spending when the
- # measurement just said there are none.
+ # Bottomed at ZERO, not at one character. A thread at its budget measures a room of zero, and a real tokenizer
+ # charges for the framing around even an empty string, so the exact fit lands on nothing fitting. One
+ # character here is not a rounding detail: it puts `_truncate` past its `limit <= 0` stub and back on the
+ # ordinary notice, which is the ~90 tokens the stub exists to avoid spending when the measurement just said
+ # there are none.
floor = min(floor, _exact_prefix_chars(text, room_chars, float(room), ctx, 0))
fitted = _dense_prefix_chars(text, share)
- # And measured rather than estimated when the serving model can measure it: the rule
- # above is honest about non-ASCII and still optimistic about dense ASCII. The floor
- # goes WITH it: the exact fit bottoms out on that value, so leaving it at the legacy
- # 2,000 would hand back 2,000 characters on a thread with room for a few hundred --
- # the same overflow, reached through the leg that is supposed to be the accurate one.
+ # And measured rather than estimated when the serving model can measure it: the rule above is honest about
+ # non-ASCII and still optimistic about dense ASCII. The floor goes WITH it: the exact fit bottoms out on that
+ # value, so leaving it at the legacy 2,000 would hand back 2,000 characters on a thread with room for a few
+ # hundred, the same overflow reached through the leg that is supposed to be the accurate one.
fitted = _exact_prefix_chars(text, min(fitted, max_chars), share, ctx, floor)
# An explicit cap smaller than the floor still wins.
return min(max_chars, max(floor, fitted))
@@ -13013,27 +12136,22 @@ def _truncate_page_text(text: str, max_chars: int) -> str:
def _fetch_page_text(
url: str,
- # Resolved per call rather than bound at import: the default would freeze the constant
- # before any model is loaded, which is exactly when the window is still unknown.
+ # Resolved per call rather than bound at import: the default would freeze the constant before any model is loaded,
+ # which is exactly when the window is still unknown.
max_chars: int | None = None,
timeout: int = 30,
cancel_event = None,
website_policy: dict | None = None,
) -> str:
- """Fetch a URL and return readable text content.
-
- HTML responses are converted to Markdown with a main-content heuristic
- (``<article>``/``<main>`` scoping, hidden-element and boilerplate
- stripping); non-HTML text responses are returned as-is. GitHub repo root
- pages are rewritten to the README API so the model reads the README
- instead of the repo page's UI chrome. Blocks private/loopback/link-local
- targets (SSRF protection) and caps the download size.
- """
+ """Fetch a URL and return readable text content. HTML responses are converted to Markdown with a
+ main-content heuristic (``<article>``/``<main>`` scoping, hidden-element and boilerplate
+ stripping); non-HTML text responses are returned as-is. GitHub repo root pages are rewritten
+ to the README API so the model reads the README instead of the repo page's UI chrome. Blocks
+ private/loopback/link-local targets (SSRF protection) and caps the download size."""
if max_chars is None:
max_chars = _page_char_budget()
- # One wall-clock budget for the whole fetch. The README API attempt and its
- # HTML fallback both draw from it, so a slow/failed API call cannot hand the
- # fallback a fresh full timeout and double the worst case.
+ # One wall-clock budget for the whole fetch. The README API attempt and its HTML fallback both draw from it, so a
+ # slow/failed API call cannot hand the fallback a fresh full timeout and double the worst case.
deadline = None if timeout is None else time.monotonic() + timeout
from .web_access_policy import check_url_access
@@ -13056,15 +12174,13 @@ def _fetch_page_text(
cancel_event = cancel_event,
**policy_kwargs,
)
- # The README API is unauthenticated and rate-limited; on any failure fall
- # back to the HTML page fetch. A 200 body is authoritative even when it is
- # HTML (a .html README): convert it rather than falling back to the repo
+ # The README API is unauthenticated and rate-limited; on any failure fall back to the HTML page fetch. A 200
+ # body is authoritative even when it is HTML (a .html README): convert it rather than falling back to the repo
# page's UI chrome, keeping the raw body if extraction yields nothing.
if err is None and body.strip():
readme_body = body
- # The raw file is almost always Markdown. Only a real HTML document (a
- # .html README) is converted; a Markdown README that merely opens with
- # a block tag is kept as-is (see _HTML_DOCUMENT_RE).
+ # The raw file is almost always Markdown. Only a real HTML document (a .html README) is converted; a
+ # Markdown README that merely opens with a block tag is kept as-is (see _HTML_DOCUMENT_RE).
if _looks_like_html_document(body):
from ._html_to_md import html_to_markdown
converted = html_to_markdown(body, main_content = True)
@@ -13085,13 +12201,12 @@ def _fetch_page_text(
if err is not None:
return err
- # Trust a declared HTML type, and otherwise sniff the body: servers with a
- # missing or wrong Content-Type (e.g. text/plain on an HTML page) still get
+ # Trust a declared HTML type, and otherwise sniff the body: servers with a missing or wrong Content-Type still get
# converted, matching the pre-extraction behavior of always converting.
is_html = "html" in content_type or _looks_like_html(body)
if not is_html:
- # Plain text / markdown / JSON (e.g. raw.githubusercontent.com):
- # converting through the HTML renderer would collapse its whitespace.
+ # Plain text / markdown / JSON (e.g. raw.githubusercontent.com): converting through the HTML renderer would
+ # collapse its whitespace.
return _truncate_page_text(body.strip(), max_chars)
# Convert HTML to Markdown with the builtin converter (no external deps).
@@ -13103,13 +12218,13 @@ def _fetch_page_text(
def _search_failure_message(exc: BaseException, timeout: int) -> str:
"""Turn a ddgs exception into text the model and the UI can act on.
- ddgs raises for an empty sweep as well as for refusals, so an unclassified
- ``Search failed: {exc}`` reports "nothing matched" and "every engine throttled us" the same
- way. Matched by class name because ddgs is imported lazily and tests stub the module.
+ ddgs raises for an empty sweep as well as for refusals, so an unclassified ``Search failed:
+ {exc}`` reports nothing matched and every engine throttled us the same way. Matched by class
+ name because ddgs is imported lazily and tests stub the module.
The RatelimitException arm is forward-looking: ddgs 9.14.4 defines the class but raises it
- nowhere, and no engine inspects the status code, so a throttled sweep parses to zero items
- and arrives here as the empty-sweep DDGSException instead.
+ nowhere, and no engine inspects the status code, so a throttled sweep parses to zero items and
+ arrives here as the empty-sweep DDGSException instead.
"""
name = type(exc).__name__
if name == "RatelimitException":
@@ -13127,12 +12242,10 @@ def _search_failure_message(exc: BaseException, timeout: int) -> str:
def _image_search_or_none(subjects: list, timeout, cancel_event, website_policy) -> "str | None":
- """``_image_search`` that reports a failure as None instead of raising.
-
- Every caller sits inside ``_web_search``'s own ``except``, which would turn a
- raise into "Search failed: ..." and throw away the text results the search had
- already found. A picture is a garnish: it must not become the answer.
- """
+ """``_image_search`` that reports a failure as None instead of raising. Every caller sits inside
+ ``_web_search``'s own ``except``, which would turn a raise into Search failed: ... and throw
+ away the text results the search had already found. A picture is a garnish: it must not
+ become the answer."""
try:
return _image_search(
subjects,
@@ -13148,13 +12261,11 @@ def _image_search_or_none(subjects: list, timeout, cancel_event, website_policy)
def _empty_result_with_requested_images(
empty_text: str, subjects: list, include_images: bool, timeout, cancel_event, website_policy
) -> str:
- """``empty_text`` plus the pictures the model asked for by name, if any.
-
- An ``image_queries`` call is an explicit request, and it succeeds on its own when
- sent without a query -- so returning the bare "No results found." because the TEXT
- sweep came back empty dropped images that were there to be had. Only the named
- subjects are looked up here; the per-query image pile has no answer to garnish.
- """
+ """``empty_text`` plus the pictures the model asked for by name, if any. An ``image_queries``
+ call is an explicit request, and it succeeds on its own when sent without a query, so
+ returning the bare No results found. because the TEXT sweep came back empty dropped images
+ that were there to be had. Only the named subjects are looked up here; the per-query image
+ pile has no answer to garnish."""
if not subjects:
return empty_text
if not include_images:
@@ -13178,15 +12289,12 @@ def _web_search(
include_images: bool = False,
image_queries = None,
) -> str:
- """Search the web and return formatted results.
-
- ddgs fans the query out across its search engines, so a single engine refusing is already
- covered. If ``url`` is provided, fetches that page directly instead of searching.
- ``include_images`` adds image results registered server-side and offered to the model
- as ``[[img:<id>]]`` tokens, with a frontend-only envelope appended: one picture per
- ``image_queries`` subject when the model named them, else a handful for the query.
- ``image_queries`` alone (no query) is a pure image lookup.
- """
+ """Search the web and return formatted results. ddgs fans the query out across its search
+ engines, so a single engine refusing is already covered. If ``url`` is provided, fetches that
+ page directly instead of searching. ``include_images`` adds image results registered
+ server-side and offered to the model as ``[[img:<id>]]`` tokens, with a frontend-only
+ envelope appended: one picture per ``image_queries`` subject when the model named them, else
+ a handful for the query. ``image_queries`` alone (no query) is a pure image lookup."""
# Direct URL fetch mode.
if url and url.strip():
fetch_timeout = 60 if timeout is None else min(timeout, 60)
@@ -13201,8 +12309,8 @@ def _web_search(
if subjects and not (query and query.strip()):
if not include_images:
return IMAGE_SEARCH_DISABLED
- # Ahead of the try below, so this one has to carry its own guard: execute_tool
- # returns a string for every input, and a raise here would escape _web_search.
+ # Ahead of the try below, so this one has to carry its own guard: execute_tool returns a string for every
+ # input, and a raise here would escape _web_search.
found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)
if found is None:
return "No images found for: " + ", ".join(subjects)
@@ -13210,9 +12318,8 @@ def _web_search(
if not query or not query.strip():
return "No query provided."
- # A disconnect sets cancel_event; DDGS.text() is blocking and cannot be
- # interrupted mid-flight, so gate on either side: skip an already-cancelled
- # request, and discard results that land after the client has gone.
+ # A disconnect sets cancel_event; DDGS.text() is blocking and cannot be interrupted mid-flight, so gate on either
+ # side: skip an already-cancelled request, and discard results that land after the client has gone.
if cancel_event is not None and cancel_event.is_set():
return "Search cancelled."
try:
@@ -13221,10 +12328,9 @@ def _web_search(
from .web_access_policy import check_url_access, scope_search_query
effective_query = scope_search_query(query, website_policy)
- # The policy filters below, so ask for a deeper pool when one actually restricts: a page
- # whose top hits are all disallowed otherwise yields nothing even when valid results rank
- # just under them. Test the domain lists, not the dict: a run always stores a normalized
- # policy, which is truthy even when unrestricted.
+ # The policy filters below, so ask for a deeper pool when one actually restricts: a page whose top hits are
+ # all disallowed otherwise yields nothing even when valid results rank just under them. Test the domain lists,
+ # not the dict: a run always stores a normalized policy, which is truthy even when unrestricted.
restricted = any(
(website_policy or {}).get(key) for key in ("allowedDomains", "blockedDomains")
)
@@ -13287,9 +12393,8 @@ def _web_search(
return text
except Exception as e:
failure = _search_failure_message(e, timeout)
- # ddgs signals an empty sweep by RAISING, so that exit is an empty result too
- # and owes the named subjects their pictures. A genuine failure keeps its
- # message alone: pictures under an error read as a partial answer.
+ # ddgs signals an empty sweep by RAISING, so that exit is an empty result too and owes the named subjects
+ # their pictures. A genuine failure keeps its message alone: pictures under an error read as a partial answer.
if failure == EMPTY_SEARCH_RESULTS[0]:
return _empty_result_with_requested_images(
failure,
@@ -13416,8 +12521,8 @@ def _web_search_images_suffix(client, query, wanted, cancel_event, website_polic
images_fn = getattr(client, "images", None)
if not callable(images_fn):
return ""
- # Before the sweep, like _image_search: clear-all is what bumps this, and an
- # entry registered after one would keep serving a picture the user cleared.
+ # Before the sweep, like _image_search: clear-all is what bumps this, and an entry registered after one would keep
+ # serving a picture the user cleared.
expected_generation = cache_generation()
try:
raw = images_fn(
@@ -13437,9 +12542,9 @@ def _web_search_images_suffix(client, query, wanted, cancel_event, website_polic
def _check_signal_escape_patterns(code: str):
- """Check for patterns that could escape signal-based timeouts. Returns
- (safe: bool, details: dict). Vendored from unsloth_zoo.rl_environments to
- avoid importing unsloth_zoo (needs GPU drivers; fails on Apple Silicon)."""
+ """Check for patterns that could escape signal-based timeouts. Returns (safe: bool, details:
+ dict). Vendored from unsloth_zoo.rl_environments to avoid importing unsloth_zoo (needs GPU
+ drivers; fails on Apple Silicon)."""
try:
tree = ast.parse(code)
except SyntaxError as e:
@@ -13523,8 +12628,7 @@ def _check_signal_escape_patterns(code: str):
return parts
return []
- # Kwarg names that carry command content (not control flags like
- # check=True, text=True, capture_output=True).
+ # Kwarg names that carry command content (not control flags like check=True, text=True, capture_output=True).
_CMD_KWARGS = frozenset({"args", "command", "executable", "path", "file"})
def _check_args_for_blocked(args_nodes):
@@ -13545,8 +12649,7 @@ def _check_signal_escape_patterns(code: str):
self.signal_aliases = {"signal"}
self.os_aliases = {"os"}
self.subprocess_aliases = {"subprocess"}
- # Bare name -> fully-qualified form for from-import tracking
- # (e.g. "system" -> "os.system").
+ # Bare name -> fully-qualified form for from-import tracking (e.g. "system" -> "os.system").
self.shell_exec_aliases: dict[str, str] = {}
self.loop_depth = 0
@@ -13648,8 +12751,7 @@ def _check_signal_escape_patterns(code: str):
}
)
- # --- Shell escape detection ---
- # Resolve the FQ function name for os.*/subprocess.*
+ # Shell escape detection: resolve the FQ function name for os.*/subprocess.*
shell_func = None
if isinstance(func, ast.Attribute):
if isinstance(func.value, ast.Name):
@@ -13701,9 +12803,8 @@ def _check_signal_escape_patterns(code: str):
}
)
else:
- # Only flag dynamic args for funcs that interpret strings as
- # shell commands, or when shell= might be on. Any non-literal-
- # False shell= is treated as potentially True (conservative).
+ # Only flag dynamic args for funcs that interpret strings as shell commands, or when shell= might
+ # be on. Any non-literal-False shell= is treated as potentially True (conservative).
_STRING_SHELL_FUNCS = frozenset(
{
"os.system",
@@ -13761,9 +12862,8 @@ def _check_signal_escape_patterns(code: str):
}
)
elif isinstance(node.type, ast.Name):
- # Flag BaseException/TimeoutError but NOT Exception: `except
- # Exception` can't catch SystemExit/KeyboardInterrupt, so it
- # can't suppress timeout enforcement.
+ # Flag BaseException/TimeoutError but NOT Exception: `except Exception` can't catch
+ # SystemExit/KeyboardInterrupt, so it can't suppress timeout enforcement.
if node.type.id in ("TimeoutError", "BaseException"):
exception_catching.append(
{
@@ -13791,9 +12891,8 @@ def _check_signal_escape_patterns(code: str):
if visitor.imports_signal and not signal_tampering:
warnings.append("Code imports 'signal' module - review manually for safety")
- # Static host policy: block metadata hosts and any literal host outside the
- # trusted allowlist; uploads blocked regardless of host. Dynamic hosts are
- # caught by the bash blocklist.
+ # Static host policy: block metadata hosts and any literal host outside the trusted allowlist; uploads blocked
+ # regardless of host. Dynamic hosts are caught by the bash blocklist.
network_calls: list[dict] = []
sensitive_file_reads: list[dict] = []
_NETWORK_FQ_PREFIXES = (
@@ -14040,9 +13139,8 @@ def _check_signal_escape_patterns(code: str):
return True
return False
- # Bare method-name fallback (`x.upload_file(...)`) is fuzzy, so it fires only
- # when huggingface_hub/hf_api is imported; else paramiko.upload_file,
- # boto3.create_commit, etc. would false-positive. Pre-scan for the imports.
+ # Bare method-name fallback (`x.upload_file(...)`) is fuzzy, so it fires only when huggingface_hub/hf_api is
+ # imported; else paramiko.upload_file, boto3.create_commit, etc. would false-positive. Pre-scan for the imports.
_HF_IMPORT_MODULES = (
"huggingface_hub",
"hf_api",
@@ -14060,8 +13158,8 @@ def _check_signal_escape_patterns(code: str):
if root in _HF_IMPORT_MODULES:
return True
elif isinstance(n, ast.Call) and n.args:
- # __import__('huggingface_hub'), importlib.import_module(...),
- # and bare import_module(...) (via `from importlib import ...`).
+ # __import__('huggingface_hub'), importlib.import_module(...), and bare import_module(...) (via `from
+ # importlib import ...`).
arg0 = n.args[0]
if not (isinstance(arg0, ast.Constant) and isinstance(arg0.value, str)):
continue
@@ -14080,9 +13178,9 @@ def _check_signal_escape_patterns(code: str):
_hf_in_scope = _module_has_hf_import(tree)
def _method_call_hf_upload_name(node: ast.Call) -> str | None:
- """Return the HF upload method name (`upload_file`, ...) or None. Covers
- the Attribute and bare-Name forms; the bare-name branch fires only when
- an HF import is in scope so paramiko/boto3 don't false-positive."""
+ """Return the HF upload method name (`upload_file`, ...) or None. Covers the Attribute and
+ bare-Name forms; the bare-name branch fires only when an HF import is in scope so
+ paramiko/boto3 don't false-positive."""
if not _hf_in_scope:
return None
f = node.func
@@ -14092,8 +13190,8 @@ def _check_signal_escape_patterns(code: str):
return f.id
return None
- # Kwargs that ship a credential over the wire. The sandbox env strips
- # credentials up front, so any value here is hard-coded or lifted from parent.
+ # Kwargs that ship a credential over the wire. The sandbox env strips credentials up front, so any value here is
+ # hard-coded or lifted from parent.
_HF_SENSITIVE_KWARGS = frozenset(
{
"token",
@@ -14112,9 +13210,8 @@ def _check_signal_escape_patterns(code: str):
"(no absolute paths, no '..' segments, no dynamic expressions)"
)
- # Upload methods that take CommitOperation* objects rather than a path, and
- # the kwarg each one carries them in. `preupload_lfs_files` sends the file
- # bytes to the LFS store on its own, so it needs the same gate as a commit.
+ # Upload methods that take CommitOperation* objects rather than a path, and the kwarg each one carries them in.
+ # `preupload_lfs_files` sends the file bytes to the LFS store on its own, so it needs the same gate as a commit.
_HF_OPERATIONS_KWARG = {
"create_commit": "operations",
"preupload_lfs_files": "additions",
@@ -14129,12 +13226,10 @@ def _check_signal_escape_patterns(code: str):
)
def _reads_env_or_secret(node: ast.AST | None) -> bool:
- """True if any node in the subtree resolves to an env/process read.
-
- Walks the whole subtree (not just the root) to catch wrappers like
- `str(os.environ)`. Covers os.environ[/.get]/os.getenv, bare getenv, and
- subprocess.{run,check_output,...} that could lift parent env via printenv.
- """
+ """True if any node in the subtree resolves to an env/process read. Walks the whole subtree
+ (not just the root) to catch wrappers like `str(os.environ)`. Covers
+ os.environ[/.get]/os.getenv, bare getenv, and subprocess.{run,check_output,...} that
+ could lift parent env via printenv."""
if node is None:
return False
for sub in ast.walk(node):
@@ -14199,15 +13294,12 @@ def _check_signal_escape_patterns(code: str):
return False
def _hf_upload_violation(node: ast.Call, method_name: str) -> str | None:
- """Inspect an HF upload call; return a violation reason or None.
-
- Policy: HF uploads are allowed only when (a) no sensitive kwarg is set,
- (b) no positional / keyword value reads `os.environ` or related env
- readers, and (c) the path arg is a sandbox-local literal: a relative
- string with no `..`, an `open(<literal>)`, or inline bytes. Dynamic /
- variable paths are rejected since safety can't be proven statically and
- a wrong-allow means credential exfiltration.
- """
+ """Inspect an HF upload call; return a violation reason or None. Policy: HF uploads are
+ allowed only when (a) no sensitive kwarg is set, (b) no positional / keyword value reads
+ `os.environ` or related env readers, and (c) the path arg is a sandbox-local literal: a
+ relative string with no `..`, an `open(<literal>)`, or inline bytes. Dynamic / variable
+ paths are rejected since safety can't be proven statically and a wrong-allow means
+ credential exfiltration."""
for kw in node.keywords or []:
if kw.arg in _HF_SENSITIVE_KWARGS:
return (
@@ -14223,8 +13315,8 @@ def _check_signal_escape_patterns(code: str):
)
if method_name in _HF_OPERATIONS_KWARG:
ops_kwarg = _HF_OPERATIONS_KWARG[method_name]
- # A `*args` / `**kwargs` splat can smuggle in the operations or a token,
- # and either may sit after `operations=`, so scan before resolving.
+ # A `*args` / `**kwargs` splat can smuggle in the operations or a token, and either may sit after
+ # `operations=`, so scan before resolving.
if any(isinstance(a, ast.Starred) for a in node.args or []):
return _HF_UPLOAD_PATH_VIOLATION
if any(kw.arg is None for kw in node.keywords or []):
@@ -14247,10 +13339,9 @@ def _check_signal_escape_patterns(code: str):
return inner
return None
if method_name == "commit_operation":
- # A CommitOperation* constructor from the list above. Delete and copy get
- # no exemption: a by-name one would trust a name sandboxed code can rebind.
- # Add is (path_in_repo, path_or_fileobj) so both positionals are checked,
- # and other keywords must be literals -- a computed one reads the file.
+ # A CommitOperation* constructor from the list above. Delete and copy get no exemption: a by-name one
+ # would trust a name sandboxed code can rebind. Add is (path_in_repo, path_or_fileobj) so both positionals
+ # are checked, and other keywords must be literals: a computed one reads the file.
path_nodes = list(node.args or [])
for kw in node.keywords or []:
if kw.arg is None:
@@ -14425,14 +13516,12 @@ def _check_signal_escape_patterns(code: str):
def _check_code_safety(code: str) -> str | None:
- """Validate code safety via static analysis.
-
- Returns an error message string if the code is unsafe, or None if OK.
- """
+ """Validate code safety via static analysis. Returns an error message string if the code is
+ unsafe, or None if OK."""
safe, info = _check_signal_escape_patterns(code)
if not safe:
- # Let SyntaxError from ast.parse through so the subprocess produces a
- # normal Python traceback instead of a misleading "unsafe code" message.
+ # Let SyntaxError from ast.parse through so the subprocess produces a normal Python traceback instead of a
+ # misleading "unsafe code" message.
if info.get("error"):
return None
@@ -14460,12 +13549,9 @@ def _check_code_safety(code: str) -> str | None:
def _adopt_tool_pid(pid: "int | None") -> None:
- """Record a tool subprocess for the startup sweep.
-
- macOS has no parent-death signal, so a force quit mid-call would otherwise
- leave a session-leading tool (and whatever it spawned) with nothing able to
- find it. Best-effort: a failure here must never break a tool call.
- """
+ """Record a tool subprocess for the startup sweep. macOS has no parent-death signal, so a force
+ quit mid-call would otherwise leave a session-leading tool (and whatever it spawned) with
+ nothing able to find it. Best-effort: a failure here must never break a tool call."""
if not pid:
return
try:
@@ -14492,20 +13578,19 @@ def _forget_tool_pid(proc) -> None:
def _capture_process_group(proc):
"""Return the setsid process-group id, or ``None`` when unavailable.
- Captured right after ``Popen`` so a later ``poll()`` / ``wait()`` that reaps
- the leader cannot make ``os.getpgid(proc.pid)`` fail first.
+ Captured right after ``Popen`` so a later ``poll()`` / ``wait()`` that reaps the leader cannot
+ make ``os.getpgid(proc.pid)`` fail first.
- Windows has no process groups, so capture the wrapper pid instead, tagged
- for ``_killpg_captured`` to reach with ``taskkill /T``; returning ``None``
- there left a payload that outlived its wrapper unsignalled.
+ Windows has no process groups, so capture the wrapper pid instead, tagged for
+ ``_killpg_captured`` to reach with ``taskkill /T``; returning ``None`` there left a payload that
+ outlived its wrapper unsignalled.
"""
if os.name == "nt":
job = _windows_job_capture(proc)
if job is not None:
return ("windows-job", job)
- # No job available, so fall back to the pid, carrying its creation-time
- # identity: a posix group id cannot be recycled while a member lives,
- # but this bare pid can, and the timeout path may fire much later.
+ # No job available, so fall back to the pid, carrying its creation-time identity: a posix group id cannot be
+ # recycled while a member lives, but this bare pid can, and the timeout path may fire much later.
return ("windows-tree", proc.pid, _windows_pid_identity(proc.pid))
if os.name != "posix" or not hasattr(os, "getpgid"):
return None
@@ -14516,13 +13601,10 @@ def _capture_process_group(proc):
class _WindowsToolJob:
- """A job object holding one tool call's process tree.
-
- Windows has no process groups, and ``taskkill`` cannot reach a tree whose
- root has already exited, which is exactly the case this capture exists for.
- The job stays a valid handle on every descendant either way. Created without
- kill-on-close, so releasing it never kills a process that outlived the call.
- """
+ """A job object holding one tool call's process tree. Windows has no process groups, and
+ ``taskkill`` cannot reach a tree whose root has already exited, which is exactly the case
+ this capture exists for. The job stays a valid handle on every descendant either way. Created
+ without kill-on-close, so releasing it never kills a process that outlived the call."""
def __init__(self, handle, kernel32):
self._handle = handle
@@ -14546,8 +13628,8 @@ class _WindowsToolJob:
def _windows_job_capture(proc) -> "_WindowsToolJob | None":
- """Put ``proc`` in its own job. ``None`` when that is not possible, leaving
- the pid-based fallback."""
+ """Put ``proc`` in its own job. ``None`` when that is not possible, leaving the pid-based
+ fallback."""
if os.name != "nt":
return None
try:
@@ -14556,8 +13638,8 @@ def _windows_job_capture(proc) -> "_WindowsToolJob | None":
H, BOOL, UINT = wintypes.HANDLE, wintypes.BOOL, wintypes.UINT
kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
- # Explicit widths: without them ctypes truncates a 64-bit handle to
- # c_int and every call silently works on a bogus one.
+ # Explicit widths: without them ctypes truncates a 64-bit handle to c_int and every call silently works on a
+ # bogus one.
kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
kernel32.CreateJobObjectW.restype = H
kernel32.AssignProcessToJobObject.argtypes = [H, H]
@@ -14570,8 +13652,8 @@ def _windows_job_capture(proc) -> "_WindowsToolJob | None":
job = kernel32.CreateJobObjectW(None, None)
if not job:
return None
- # The Popen handle, not a fresh OpenProcess: it already refers to this
- # child, so there is no window for the pid to be recycled first.
+ # The Popen handle, not a fresh OpenProcess: it already refers to this child, so there is no window for the
+ # pid to be recycled first.
if not kernel32.AssignProcessToJobObject(job, int(proc._handle)):
kernel32.CloseHandle(job)
return None
@@ -14594,12 +13676,12 @@ def _windows_pid_identity(pid: int) -> "str | None":
def _windows_taskkill_tree(pid: int, identity: "str | None" = None) -> bool:
"""``taskkill /T /F`` a pid and its descendants. True when it succeeded.
- Every tool call runs under a shell wrapper, and Windows has no process
- groups, so a bare ``proc.kill()`` reaps the wrapper and orphans the payload
- (usually the venv python), which then blocks `unsloth studio update`.
+ Every tool call runs under a shell wrapper, and Windows has no process groups, so a bare
+ ``proc.kill()`` reaps the wrapper and orphans the payload (usually the venv python), which then
+ blocks `unsloth studio update`.
- ``identity`` is the creation time captured at spawn; a mismatch means the pid
- now belongs to something else, so nothing is signalled.
+ ``identity`` is the creation time captured at spawn; a mismatch means the pid now belongs to
+ something else, so nothing is signalled.
"""
if os.name != "nt":
return False
@@ -14648,14 +13730,11 @@ def _kill_process_tree(proc) -> None:
def _killpg_captured(pgid) -> None:
- """SIGKILL a process group captured before its leader was waited on.
-
- Once ``proc`` exits, ``os.getpgid(proc.pid)`` fails and ``_kill_process_tree``
- short-circuits, so a stdout-holding grandchild that outlived the parent could
- not otherwise be signaled. The pre-captured setsid group id still targets the
- whole tree. On Windows the capture is a tagged pid and the equivalent reach
- is ``taskkill /T /F``. No-op when nothing was captured.
- """
+ """SIGKILL a process group captured before its leader was waited on. Once ``proc`` exits,
+ ``os.getpgid(proc.pid)`` fails and ``_kill_process_tree`` short-circuits, so a stdout-holding
+ grandchild that outlived the parent could not otherwise be signaled. The pre-captured setsid
+ group id still targets the whole tree. On Windows the capture is a tagged pid and the
+ equivalent reach is ``taskkill /T /F``. No-op when nothing was captured."""
if pgid is None:
return
if isinstance(pgid, tuple):
@@ -14663,9 +13742,8 @@ def _killpg_captured(pgid) -> None:
pgid[1].terminate()
return
_tag, pid, identity = pgid
- # Fail closed: this runs long after the capture, so without a verified
- # identity the pid may be someone else's now. The job object still takes
- # the whole tree when Unsloth exits, which is the safe half to keep.
+ # Fail closed: this runs long after the capture, so without a verified identity the pid may be someone else's
+ # now. The job object still takes the whole tree when Unsloth exits, which is the safe half to keep.
if identity is not None:
_windows_taskkill_tree(pid, identity)
return
@@ -14683,12 +13761,10 @@ def _cancel_watcher(
poll_interval = 0.2,
pgid = None,
):
- """Daemon thread that kills a process when cancel_event is set.
-
- ``pgid`` is the group id captured right after spawn; killing it directly
- reaps a stdout-holding grandchild even when the watcher's own ``poll()``
- already reaped the leader (which makes ``_kill_process_tree`` short-circuit).
- """
+ """Daemon thread that kills a process when cancel_event is set. ``pgid`` is the group id
+ captured right after spawn; killing it directly reaps a stdout-holding grandchild even when
+ the watcher's own ``poll()`` already reaped the leader (which makes ``_kill_process_tree``
+ short-circuit)."""
while proc.poll() is None:
if cancel_event is not None and cancel_event.is_set():
_killpg_captured(pgid)
@@ -14699,12 +13775,10 @@ def _cancel_watcher(
def _appended_by_the_loop(text: str) -> float:
"""What the tool loop will add to this result after the tool has handed it back.
-
- `ToolCallCompletion.model_message` appends `TOOL_ERROR_NUDGE` to a result that opens
- with one of `TOOL_ERROR_PREFIXES`, after this budget has already let the body take the
- whole room, and a parallel batch of failed calls carries one nudge each. Priced in
- tokens like the retry hint, and only for the results that will really carry it.
- """
+ `ToolCallCompletion.model_message` appends `TOOL_ERROR_NUDGE` to a result that opens with one
+ of `TOOL_ERROR_PREFIXES`, after this budget has already let the body take the whole room, and
+ a parallel batch of failed calls carries one nudge each. Priced in tokens like the retry
+ hint, and only for the results that will really carry it."""
try:
from .tool_call_parser import TOOL_ERROR_NUDGE, TOOL_ERROR_PREFIXES # noqa: PLC0415
except Exception: # noqa: BLE001 -- an unpriced nudge, not a failed tool call
@@ -14726,17 +13800,15 @@ def _truncate(
hint: str = "",
reserve_tokens: float = 0.0,
) -> str:
- # Resolved per call, not bound at import: the default would freeze the constant
- # before any model is loaded, which is exactly when the window is still unknown.
+ # Resolved per call, not bound at import: the default would freeze the constant before any model is loaded, which
+ # is exactly when the window is still unknown.
if limit is None:
limit = _tool_result_char_budget()
- # Same correction as a fetched page: a character cap reserves its share of the window
- # only for English, and a command that prints CJK or percent-escaped text costs two to
- # three times what the cap assumed.
- # Whatever the loop will append to this result once it has it: the tool-error nudge
- # goes on after the tool has returned, so a result sized to fill the room arrives at
- # the prompt with the nudge past the end of it. Charged only to the results that will
- # actually carry one, since a reserve taken from every result spends room the thread
+ # Same correction as a fetched page: a character cap reserves its share of the window only for English, and a
+ # command that prints CJK or percent-escaped text costs two to three times what the cap assumed.
+ # Whatever the loop will append to this result once it has it: the tool-error nudge goes on after the tool has
+ # returned, so a result sized to fill the room arrives at the prompt with the nudge past the end of it. Charged
+ # only to the results that will actually carry one, since a reserve taken from every result spends room the thread
# has.
# `reserve_tokens` is whatever the CALLER will put after this result, priced the same
# way as the loop's own nudge. Without it a caller that concatenates two fitted
@@ -14744,53 +13816,47 @@ def _truncate(
# and neither knows about the other, so the message the model is handed is the sum.
cap, cost = limit, _appended_by_the_loop(text) + reserve_tokens
if hint:
- # Priced in tokens, not characters, and taken off the budget before it is converted
- # (see `_dense_char_limit`). A failing absolute path is dense: subtracting its
- # LENGTH from the character cap frees fewer tokens than the hint then spends, which
- # is the unbudgeted overflow this whole change exists to prevent. It may take at
- # most half the room; past that the output is worth more than the advice about it.
+ # Priced in tokens, not characters, and taken off the budget before it is converted (see `_dense_char_limit`).
+ # A failing absolute path is dense: subtracting its LENGTH from the character cap frees fewer tokens than the
+ # hint then spends, which is the unbudgeted overflow this whole change exists to prevent. It may take at most
+ # half the room; past that the output is worth more than the advice about it.
plain = _dense_char_limit(text, limit, cost)
cost += _text_token_cost(hint, _window_context_tokens())
with_hint = _dense_char_limit(text, limit, cost)
if plain > 0 and (len(text) <= with_hint or with_hint * 2 >= plain):
limit = with_hint
else:
- # Nothing to spend on advice: at zero room the stub IS the message, and when
- # paying for it would cut the output in half the output is worth more than the
- # advice about it. Nothing is dropped while the result fits anyway.
+ # Nothing to spend on advice: at zero room the stub IS the message, and when paying for it would cut the
+ # output in half the output is worth more than the advice about it. Nothing is dropped while the result
+ # fits anyway.
limit, hint, cost = plain, "", _appended_by_the_loop(text) + reserve_tokens
else:
limit = _dense_char_limit(text, limit, cost)
- # Mode-neutral notice: this result serves both the streaming UI and
- # non-streaming callers and must stay byte-identical with and without an
- # output_callback (a regression-tested invariant), so it can't claim the
- # user saw the full output.
+ # Mode-neutral notice: this result serves both the streaming UI and non-streaming callers and must stay
+ # byte-identical with and without an output_callback (a regression-tested invariant), so it can't claim the user
+ # saw the full output.
if len(text) <= limit:
return text + hint
- # Only now is a notice certain, and only now is it charged. Held back before the
- # measurement above, it would cut results that fit: a 100-token result with 200 tokens
- # of room would be sized against 72 and come back as 72 tokens of body plus ~70 of
- # notice, which is more of the window spent to say less. See `_RESULT_NOTICE_RESERVE`.
- #
- # Against a priced room only. With none, the caller's character cap is the whole
- # budget and the notice has always been appended past it; taking a token reserve off a
- # character cap there would cut every legacy caller's output to nothing.
+ # Only now is a notice certain, and only now is it charged. Held back before the measurement above, it would cut
+ # results that fit: a 100-token result with 200 tokens of room would be sized against 72 and come back as 72
+ # tokens of body plus ~70 of notice, which is more of the window spent to say less. See `_RESULT_NOTICE_RESERVE`.
+ # Against a priced room only. With none, the caller's character cap is the whole budget and the notice has always
+ # been appended past it; taking a token reserve off a character cap there would cut every legacy caller's output
+ # to nothing.
if _request_result_room() is not None:
limit = _dense_char_limit(text, cap, cost + _RESULT_NOTICE_RESERVE)
if limit <= 0 and len(_zero_room_stub(len(text), None, True)) >= len(text):
- # Decided BEFORE the spill: a result this short is served whole below, and writing
- # a file (and creating the spill directory) for output that is never cut is a side
- # effect with nothing on the other side of it.
+ # Decided BEFORE the spill: a result this short is served whole below, and writing a file (and creating the
+ # spill directory) for output that is never cut is a side effect with nothing on the other side of it.
return text + hint
spill, complete = _spill_full_output(text, workdir, scope)
if limit <= 0:
- # No room for a body, so no room for the usual notice either: at this point the
- # notice IS the message, and the full one costs ~90 tokens of a budget that just
- # reported none. Kept to a line so the thread stays servable and the next fit can
- # evict older turns and recover, which is the whole reason a stub beats a refusal.
+ # No room for a body, so no room for the usual notice either: at this point the notice IS the message, and the
+ # full one costs ~90 tokens of a budget that just reported none. Kept to a line so the thread stays servable
+ # and the next fit can evict older turns and recover, which is the whole reason a stub beats a refusal.
stub = _zero_room_stub(len(text), spill, complete)
- # A short result costs less than the notice explaining it is gone, and replacing
- # "done" with a longer sentence saves nothing and loses the answer.
+ # A short result costs less than the notice explaining it is gone, and replacing "done" with a longer sentence
+ # saves nothing and loses the answer.
return (stub if len(stub) < len(text) else text) + hint
head, on_boundary = _head_whole_lines(text, limit)
if spill is None:
@@ -14803,46 +13869,42 @@ def _truncate(
)
+ hint
)
- # The rest is not advice, it is reachable: the sandbox persists between calls and the
- # model already has the terminal, so naming the exact next command turns a dead end
- # into paging. Truncating without one is what makes a model re-run the same command
- # and truncate identically.
+ # The rest is not advice, it is reachable: the sandbox persists between calls and the model already has the
+ # terminal, so naming the exact next command turns a dead end into paging. Truncating without one is what makes a
+ # model re-run the same command and truncate identically.
if on_boundary:
- # No "+1" when the head already ends in a newline: the count is of the lines
- # SHOWN, and a trailing break closes the last one rather than opening another.
- # Reachable at a limit of 1 on output that starts with a blank line, where the
- # head is "\n" alone and a count of two makes the hint resume at line 3, skipping
- # the first line the reader never saw.
+ # No "+1" when the head already ends in a newline: the count is of the lines SHOWN, and a trailing break
+ # closes the last one rather than opening another. Reachable at a limit of 1 on output that starts with a
+ # blank line, where the head is "\n" alone and a count of two makes the hint resume at line 3, skipping the
+ # first line the reader never saw.
shown = 0 if not head else head.count("\n") + (0 if head.endswith("\n") else 1)
total = text.count("\n") + 1
resume = f"sed -n '{shown + 1},{shown + max(1, shown)}p' {spill}"
where = f"showing lines 1-{shown} of {total}"
else:
- # Cut inside a line, so a line number would name the NEXT one and skip the rest of
- # the line still unread -- on single-line output, everything. Bytes resume exactly
- # where this stopped. Measured in bytes, not characters, because that is what
- # `tail -c` counts and the two differ on any non-ASCII text.
+ # Cut inside a line, so a line number would name the NEXT one and skip the rest of the line still unread; on
+ # single-line output, everything. Bytes resume exactly where this stopped. Measured in bytes, not characters,
+ # because that is what `tail -c` counts and the two differ on any non-ASCII text.
offset = len(head.encode("utf-8", "surrogatepass"))
- # The chunk is as many BYTES as the next `len(head)` characters actually occupy,
- # not as many bytes as this one did. `head -c` counts bytes, and a round number of
- # them lands inside a code point on any mixed-width text, so the model would read
- # back a mangled character at the end of every chunk (the runner decodes with
+ # The chunk is as many BYTES as the next `len(head)` characters actually occupy, not as many bytes as this one
+ # did. `head -c` counts bytes, and a round number of them lands inside a code point on any mixed-width text,
+ # so the model would read back a mangled character at the end of every chunk (the runner decodes with
# errors="replace"). The text is here, so the boundary is not a guess.
chunk = text[len(head) : len(head) * 2 or None]
span = len(chunk.encode("utf-8", "surrogatepass"))
resume = f"tail -c +{offset + 1} {spill} | head -c {max(1, span)}"
where = f"showing the first {len(head)} chars of {len(text)}"
- # The workdir sentence stays whatever else the notice says: it is about the files the
- # CODE wrote, not the spill, and it is the only thing telling the model those survive.
+ # The workdir sentence stays whatever else the notice says: it is about the files the CODE wrote, not the spill,
+ # and it is the only thing telling the model those survive.
common = (
f"\n\n... (truncated to {limit} chars for the model; {where}, {len(text)} chars "
f"total. {_capitalise(_spill_phrase(spill, complete))}, and any files the code "
"wrote persist in the working directory"
)
if not _posix_tools_available():
- # A cmd-only Windows host has none of sed, tail or head, so the command would fail
- # and the model would most likely re-run the command that truncated. Name where
- # the output is and stop there, rather than promising paging that cannot happen.
+ # A cmd-only Windows host has none of sed, tail or head, so the command would fail and the model would most
+ # likely re-run the command that truncated. Name where the output is and stop there, rather than promising
+ # paging that cannot happen.
return head + common + ".)" + hint
return head + common + f" -- continue with:\n {resume})" + hint
@@ -14850,30 +13912,26 @@ def _truncate(
def _fit_result_to_room(text, name = None):
"""Cap a tool that does not cap its own output, when this request priced its room.
- `python` and `terminal` truncate against this same budget before they return, so this
- is a no-op for them. The other tools hand their string back whole: an MCP response is
- unbounded, a fetched page or an edit receipt runs to a few thousand characters, and
- any of them can overflow a nearly full local thread and then be protected as its
- newest exchange, which is the failure the budget exists to prevent.
+ `python` and `terminal` truncate against this same budget before they return, so this is a no-op
+ for them. The other tools hand their string back whole: an MCP response is unbounded, a fetched
+ page or an edit receipt runs to a few thousand characters, and any of them can overflow a nearly
+ full local thread and then be protected as its newest exchange, which is the failure the budget
+ exists to prevent.
- No spill file: these tools have no sandbox of their own, and `edit_file` must not have
- a workdir created underneath a caller running with code execution off. So the cap
- comes with the plain notice and no paging hint, which is the scope limit this change
- states rather than hides.
+ No spill file: these tools have no sandbox of their own, and `edit_file` must not have a workdir
+ created underneath a caller running with code execution off. So the cap comes with the plain
+ notice and no paging hint.
- With no priced room -- external providers, the hosted path, any loop that does not
- measure its own conversation -- the text is returned untouched, so nothing outside a
- local tool loop changes.
+ With no priced room (external providers, the hosted path, any loop that does not measure its own
+ conversation) the text is returned untouched.
"""
if _request_result_room() is None or not isinstance(text, str) or not text:
return text
- # Only the part the model will actually be shown is measured and cut. The rest is a
- # frontend-only envelope -- an MCP image array, web_search thumbnails, RAG sources --
- # which `strip_result_for_model` removes before the result is replayed, so it costs
- # the window nothing and must come back byte-identical: every consumer of the
- # __MCP_IMAGES__ envelope requires the whole valid JSON array, and a cut anywhere
- # inside a megabyte of base64 does not lose the image quietly, it replays the broken
- # fragment to the model instead.
+ # Only the part the model will actually be shown is measured and cut. The rest is a frontend-only envelope (an MCP
+ # image array, web_search thumbnails, RAG sources) which `strip_result_for_model` removes before the result is
+ # replayed, so it costs the window nothing and must come back byte-identical: every consumer of the __MCP_IMAGES__
+ # envelope requires the whole valid JSON array, and a cut anywhere inside a megabyte of base64 does not lose the
+ # image quietly, it replays the broken fragment to the model instead.
body, suffix = _split_frontend_suffix(text, name)
if not body:
return text
@@ -14883,11 +13941,9 @@ def _fit_result_to_room(text, name = None):
def _split_frontend_suffix(text: str, name: "str | None") -> "tuple[str, str]":
"""``text`` split into what the model sees and the trailing frontend-only envelope.
-
- `strip_result_for_model` is the same function the replay path uses, so the split
- follows its validation exactly -- a result that merely mentions a sentinel keeps it in
- the body and is capped with it, which is the conservative half.
- """
+ `strip_result_for_model` is the same function the replay path uses, so the split follows its
+ validation exactly: a result that merely mentions a sentinel keeps it in the body and is
+ capped with it, which is the conservative half."""
from .tool_loop_controller import strip_result_for_model
try:
@@ -14895,8 +13951,8 @@ def _split_frontend_suffix(text: str, name: "str | None") -> "tuple[str, str]":
except Exception:
logger.debug("frontend suffix split failed", exc_info = True)
return text, ""
- # It only ever strips a suffix, so the remainder is the exact bytes that were removed
- # (including whatever whitespace the strip rstripped away).
+ # It only ever strips a suffix, so the remainder is the exact bytes that were removed (including whatever
+ # whitespace the strip rstripped away).
if not isinstance(body, str) or not text.startswith(body):
return text, ""
return body, text[len(body) :]
@@ -14905,63 +13961,55 @@ def _split_frontend_suffix(text: str, name: "str | None") -> "tuple[str, str]":
def _head_whole_lines(text: str, limit: int) -> "tuple[str, bool]":
"""``text`` cut to at most ``limit`` characters, and whether it ended on a line break.
- Whole lines where possible, so the hint can name a line that resumes exactly where
- this stopped; a mid-line cut would repeat or lose one, and on a file printed verbatim
- that is a line of the user's own code.
+ Whole lines where possible, so the hint can name a line that resumes exactly where this stopped;
+ a mid-line cut would repeat or lose one, and on a file printed verbatim that is a line of the
+ user's own code.
- The flag is not decoration. One enormous line (minified JS, base64) has no boundary to
- cut on, and a line number would then name the line AFTER the one the reader is halfway
- through, skipping the rest of it. On single-line output that returns nothing at all.
+ The flag is not decoration. One enormous line (minified JS, base64) has no boundary to cut on,
+ and a line number would then name the line AFTER the one the reader is halfway through, skipping
+ the rest of it. On single-line output that returns nothing at all.
"""
head = text[:limit]
cut = head.rfind("\n")
- # Only when a boundary is actually near the end: rewinding further would throw away
- # the whole result to keep the hint tidy.
+ # Only when a boundary is actually near the end: rewinding further would throw away the whole result to keep the
+ # hint tidy.
if cut > 0 and cut >= limit // 2:
return head[:cut], True
return head, head.endswith("\n")
def _posix_tools_available() -> bool:
- """Whether the shell these tools run in has sed/tail/head.
-
- `_get_shell_cmd` falls back to `cmd /c` on a Windows host with no trusted bash, and
- none of those exist there, so a hint naming them is a command the model cannot run.
- The spill is still worth naming; the command is not.
- """
+ """Whether the shell these tools run in has sed/tail/head. `_get_shell_cmd` falls back to `cmd
+ /c` on a Windows host with no trusted bash, and none of those exist there, so a hint naming
+ them is a command the model cannot run. The spill is still worth naming; the command is not."""
if sys.platform != "win32":
return True
return _windows_bash() is not None
-# Dot-directory on purpose: `_snapshot_workdir_files` skips those, so the spill never
-# appears as a file the model created and never earns a download card in the UI. A plain
-# name here would put a phantom artifact beside every truncated result.
+# Dot-directory on purpose: `_snapshot_workdir_files` skips those, so the spill never appears as a file the model
+# created and never earns a download card in the UI. A plain name here would put a phantom artifact beside every
+# truncated result.
_SPILL_DIR = ".unsloth_tool_output"
_SPILL_KEEP = 20
-# A result reaches here whole, so one `cat` of a multi-gigabyte file would be retained in
-# full and twenty of them would fill the host's disk. The subprocess file-size limit does
-# not apply: this output came through a pipe, not a file the sandbox wrote. A spill exists
-# so the model can page through what it was shown, and 8 MB is already far more of that
-# than any window can consume.
+# A result reaches here whole, so one `cat` of a multi-gigabyte file would be retained in full and twenty of them
+# would fill the host's disk. The subprocess file-size limit does not apply: this output came through a pipe, not a
+# file the sandbox wrote. A spill exists so the model can page through what it was shown, and 8 MB is already far more
+# of that than any window can consume.
_SPILL_MAX_BYTES = 8 * 1024 * 1024
-# How much of a result is encoded at a time when it is hashed. UTF-8 encodes one code
-# point at a time, so a stream built from slices of the string is byte for byte the stream
-# built from the whole of it, whatever the chunk size.
+# How much of a result is encoded at a time when it is hashed. UTF-8 encodes one code point at a time, so a stream
+# built from slices of the string is byte for byte the stream built from the whole of it, whatever the chunk size.
_SPILL_HASH_CHUNK_CHARS = 1 << 20
def _digest_and_head(text: str, max_bytes: int) -> "tuple[str, int, bytes]":
- """``(digest, encoded length, the first max_bytes of it)``, in one bounded pass.
-
- Encoding the whole result to hash it and again to cut it puts two more copies of it
- through memory, and at most `max_bytes` of the second is ever written. The output this
- runs on is by definition the output that did not fit: `cat` of a file the model just
- wrote can be hundreds of megabytes, and spending it twice more inside the backend, at
- the point the result is already in hand, risks the stall or the OOM instead of the
- bounded answer this whole path exists to return.
- """
+ """``(digest, encoded length, the first max_bytes of it)``, in one bounded pass. Encoding the
+ whole result to hash it and again to cut it puts two more copies of it through memory, and at
+ most `max_bytes` of the second is ever written. The output this runs on is by definition the
+ output that did not fit: `cat` of a file the model just wrote can be hundreds of megabytes,
+ and spending it twice more inside the backend risks the stall or the OOM instead of the
+ bounded answer this path exists to return."""
digest = hashlib.sha256()
head = bytearray()
total = 0
@@ -14975,20 +14023,17 @@ def _digest_and_head(text: str, max_bytes: int) -> "tuple[str, int, bytes]":
_SPILL_MAX_TOTAL_BYTES = 64 * 1024 * 1024
-# Exactly the names `_spill_full_output` generates: twelve hex characters of a content
-# digest. The prune below deletes what it matches, and the sandbox is the user's own
-# directory -- a session may open on one that already holds a folder of this name, and
-# anything in it that Unsloth did not write is not Unsloth's to remove.
+# Exactly the names `_spill_full_output` generates: twelve hex characters of a content digest. The prune below deletes
+# what it matches, and the sandbox is the user's own directory: a session may open on one that already holds a folder
+# of this name, and anything in it that Unsloth did not write is not Unsloth's to remove.
_SPILL_NAME_RE = re.compile(r"[0-9a-f]{12}\.txt")
-# Written once, when this process creates the spill directory. Ownership is RECORDED
-# rather than inferred from the names inside: a sandbox can be a project the user opened,
-# a directory of this name in it may be theirs, and a file name proves nothing about who
-# wrote it. Without the marker nothing here writes, prunes or discounts anything there.
+# Written once, when this process creates the spill directory. Ownership is RECORDED rather than inferred from the
+# names inside: a sandbox can be a project the user opened, a directory of this name in it may be theirs, and a file
+# name proves nothing about who wrote it. Without the marker nothing here writes, prunes or discounts anything there.
_SPILL_RECORD_HEADER = "unsloth-studio tool output "
-# One lock per spill root. Appending a spill and rewriting the manifest after a prune are
-# a read-modify-write over one shared file, and a project's chats share a sandbox: two
-# calls spilling at once could otherwise have the pruner drop the entry the other just
-# appended, leaving a file nothing counts, prunes, or recognises as Unsloth's.
+# One lock per spill root. Appending a spill and rewriting the manifest after a prune are a read-modify-write over one
+# shared file, and a project's chats share a sandbox: two calls spilling at once could otherwise have the pruner drop
+# the entry the other just appended, leaving a file nothing counts, prunes, or recognises as Unsloth's.
_SPILL_LOCKS: "dict[str, threading.Lock]" = {}
_SPILL_LOCKS_GUARD = threading.Lock()
@@ -15000,14 +14045,12 @@ def _spill_lock(root: str) -> "threading.Lock":
def _spill_records_dir() -> str:
- """Where the spill manifests live: Unsloth's own storage, NOT the sandbox.
-
- The sandbox is a directory tool code writes to, so nothing kept inside it can be
- evidence about the sandbox. A marker file there was replaceable by a link, and once it
- is a plain file the model can rewrite its contents and name the user's own files as
- Unsloth's, which turns the cleanup into a delete and the prune into an unlink. Held
- beside the other records this file already keeps outside the sandboxes.
- """
+ """Where the spill manifests live: Unsloth's own storage, NOT the sandbox. The sandbox is a
+ directory tool code writes to, so nothing kept inside it can be evidence about the sandbox. A
+ marker file there was replaceable by a link, and once it is a plain file the model can
+ rewrite its contents and name the user's own files as Unsloth's, which turns the cleanup into
+ a delete and the prune into an unlink. Held beside the other records this file already keeps
+ outside the sandboxes."""
try:
from utils.paths.storage_roots import studio_root # noqa: PLC0415
return os.path.join(str(studio_root()), "tool-output-records")
@@ -15024,12 +14067,10 @@ def _spill_record_path(root: str) -> str:
def _spill_identity(root: str) -> "str | None":
- """The directory's device and inode, which is what the record claims ownership OF.
-
- Tool code can delete `.unsloth_tool_output` and make its own in the same place. That
- is a different directory with the same path, and a record that only knew the path
- would hand the new one's contents to the prune.
- """
+ """The directory's device and inode, which is what the record claims ownership OF. Tool code can
+ delete `.unsloth_tool_output` and make its own in the same place. That is a different
+ directory with the same path, and a record that only knew the path would hand the new one's
+ contents to the prune."""
try:
stat = os.lstat(root)
except OSError:
@@ -15040,20 +14081,17 @@ def _spill_identity(root: str) -> "str | None":
def _own_spill_root(root: str) -> bool:
- """Whether the spill directory is one this process made, creating it if it is absent.
-
- Ownership is recorded outside the sandbox (`_spill_records_dir`) and is of a specific
- directory, not of a path: a `.unsloth_tool_output` that came with the sandbox, or one
- tool code deleted and recreated, has no matching record and is left alone entirely.
- """
+ """Whether the spill directory is one this process made, creating it if it is absent. Ownership
+ is recorded outside the sandbox (`_spill_records_dir`) and is of a specific directory, not of
+ a path: a `.unsloth_tool_output` that came with the sandbox, or one tool code deleted and
+ recreated, has no matching record and is left alone entirely."""
if os.path.islink(root):
return False
try:
- # The existence check, the creation and the first record are ONE locked step. Two
- # first-time spills in a shared project sandbox can both see the directory absent,
- # and the slower one would otherwise write an empty record over the winner's, which
- # leaves the winner's spill owned by nobody: never pruned, counted as the user's
- # content on cleanup, and outside the byte budget for good.
+ # The existence check, the creation and the first record are ONE locked step. Two first-time spills in a
+ # shared project sandbox can both see the directory absent, and the slower one would otherwise write an empty
+ # record over the winner's, which leaves the winner's spill owned by nobody: never pruned, counted as the
+ # user's content on cleanup, and outside the byte budget for good.
with _spill_lock(root):
existed = os.path.isdir(root)
if not existed:
@@ -15077,9 +14115,8 @@ def _own_spill_root(root: str) -> bool:
return False
-# Only where the platform can do the whole write through a directory descriptor: Windows
-# has neither O_DIRECTORY nor dir_fd, and there the path-based write below stands, with the
-# link checks it already makes.
+# Only where the platform can do the whole write through a directory descriptor: Windows has neither O_DIRECTORY nor
+# dir_fd, and there the path-based write below stands, with the link checks it already makes.
_DIR_FD_WRITES = (
hasattr(os, "O_DIRECTORY")
and os.open in getattr(os, "supports_dir_fd", set())
@@ -15091,25 +14128,24 @@ _DIR_FD_WRITES = (
def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":
"""Write one spill into ``target_dir``, without following a link at any point.
- The directory is opened ONCE, O_NOFOLLOW, and every step after that is relative to
- that descriptor. Checking the path and then writing to it by name is a race a shared
- project sandbox can lose: another call can replace the directory with a symlink in
- between, and both the create and the rename would follow it, putting this output
- outside the sandbox with the backend's own permissions.
-
- Still written to a fresh O_EXCL file and installed under the real name rather than
- opened over whatever is there: the spill name comes from content the model produced, so
- it can predict it and pre-create it, as a symlink or as a hard link sharing an inode
- with some file elsewhere.
-
- Installed with `os.link`, which fails when the name is taken, rather than a rename,
- which on POSIX replaces silently. The caller checks the destination first, but between
- that check and this write another call sharing the workspace can put a file there, and
- a rename would then destroy it.
-
- Returns the stamp of what was installed, or None if nothing was. The stamp is taken
- here rather than re-read from the path afterwards, because by then another call can
- have replaced the file and the record would name its content as Unsloth's.
+ The directory is opened ONCE, O_NOFOLLOW, and every step after that is relative to that
+ descriptor. Checking the path and then writing to it by name is a race a shared project sandbox
+ can lose: another call can replace the directory with a symlink in between, and both the create
+ and the rename would follow it, putting this output outside the sandbox with the backend's own
+ permissions.
+
+ Still written to a fresh O_EXCL file and installed under the real name rather than opened over
+ whatever is there: the spill name comes from content the model produced, so it can predict it
+ and pre-create it, as a symlink or as a hard link sharing an inode with some file elsewhere.
+
+ Installed with `os.link`, which fails when the name is taken, rather than a rename, which on
+ POSIX replaces silently. The caller checks the destination first, but between that check and
+ this write another call sharing the workspace can put a file there, and a rename would then
+ destroy it.
+
+ Returns the stamp of what was installed, or None if nothing was. The stamp is taken here rather
+ than re-read from the path afterwards, because by then another call can have replaced the file
+ and the record would name its content as Unsloth's.
"""
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
if not _DIR_FD_WRITES:
@@ -15138,13 +14174,12 @@ def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":
os.open(tmp_name, flags, 0o600, dir_fd = dir_fd), "w", encoding = "utf-8", newline = ""
) as handle:
handle.write(body)
- # `os.link` rather than a rename: rename replaces the destination silently on
- # POSIX, and the name may have been taken since the caller looked. link fails with
- # EEXIST instead, which is the answer this wants.
+ # `os.link` rather than a rename: rename replaces the destination silently on POSIX, and the name may have
+ # been taken since the caller looked. link fails with EEXIST instead, which is the answer this wants.
os.link(tmp_name, name, src_dir_fd = dir_fd, dst_dir_fd = dir_fd)
_quiet_unlink(tmp_name, dir_fd = dir_fd)
- # Through the same descriptor, so it is the file just linked rather than whatever
- # the name resolves to by the time this returns.
+ # Through the same descriptor, so it is the file just linked rather than whatever the name resolves to by the
+ # time this returns.
stat = os.stat(name, dir_fd = dir_fd, follow_symlinks = False)
return ":".join(
str(part)
@@ -15176,14 +14211,12 @@ def _forget_spill_record(path: str) -> None:
def _spill_stamp(path: str) -> "str | None":
- """What a spill looked like when it was written: device, inode, size, mtime, ctime.
-
- A recorded PATH is not the file: tool code can write its own content over one, in
- place, keeping the inode. mtime alone is not enough either, since `os.utime` can put
- it back and a coarse-grained filesystem can leave it unchanged on its own; ctime moves
- on any write to the file OR its metadata and cannot be set back from userspace, so
- restoring the mtime is itself a change this sees.
- """
+ """What a spill looked like when it was written: device, inode, size, mtime, ctime. A recorded
+ PATH is not the file: tool code can write its own content over one, in place, keeping the
+ inode. mtime alone is not enough either, since `os.utime` can put it back and a
+ coarse-grained filesystem can leave it unchanged on its own; ctime moves on any write to the
+ file OR its metadata and cannot be set back from userspace, so restoring the mtime is itself
+ a change this sees."""
try:
stat = os.lstat(path)
except OSError:
@@ -15207,14 +14240,14 @@ def _stamp_size(stamp: str) -> "int | None":
def _file_digest(path: str, expected_size: "int | None" = None) -> "str | None":
"""The digest of what is on disk now, or None when it is not a file this may read.
- Opened O_NOFOLLOW and O_NONBLOCK and checked through the DESCRIPTOR, not the path. The
- stamp was taken a moment ago and this runs in the sandbox's own directory: between the
- two, tool code can put a symlink at the name, or a FIFO, or a device. A plain open
- would follow the first and block forever on the others, and this is called
- synchronously by the prune and by chat deletion, neither of which has a timeout.
+ Opened O_NOFOLLOW and O_NONBLOCK and checked through the DESCRIPTOR, not the path. The stamp was
+ taken a moment ago and this runs in the sandbox's own directory: between the two, tool code can
+ put a symlink at the name, or a FIFO, or a device. A plain open would follow the first and block
+ forever on the others, and this is called synchronously by the prune and by chat deletion,
+ neither of which has a timeout.
- ``expected_size`` refuses anything that is not the size the record remembers, so a
- file swapped for an enormous one is not hashed before it is rejected.
+ ``expected_size`` refuses anything that is not the size the record remembers, so a file swapped
+ for an enormous one is not hashed before it is rejected.
"""
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
fd = None
@@ -15239,13 +14272,11 @@ def _file_digest(path: str, expected_size: "int | None" = None) -> "str | None":
def _is_recorded_spill(root: str, path: str, owned: "dict[str, tuple[str, str]]") -> bool:
- """Whether ``path`` is still the file this wrote, rather than one written over it.
-
- Both the stamp and the CONTENT, because the stamp is only evidence about metadata: the
- content is what says this file is still the output this process put there, and it is
- the last word before anything is deleted. Read only after the cheap check passes, so
- the cost falls on the handful of files that already look like ours.
- """
+ """Whether ``path`` is still the file this wrote, rather than one written over it. Both the
+ stamp and the CONTENT, because the stamp is only evidence about metadata: the content is what
+ says this file is still the output this process put there, and it is the last word before
+ anything is deleted. Read only after the cheap check passes, so the cost falls on the handful
+ of files that already look like ours."""
relative = os.path.relpath(path, root).replace(os.sep, "/")
recorded = owned.get(relative)
if recorded is None or recorded[0] != _spill_stamp(path):
@@ -15254,12 +14285,10 @@ def _is_recorded_spill(root: str, path: str, owned: "dict[str, tuple[str, str]]"
def _spill_record(root: str) -> "tuple[str | None, dict[str, tuple[str, str]]]":
- """The recorded identity of ``root`` and the spills written into it.
-
- ``(None, {})`` when there is no record, which is the answer for any directory this
- process did not create. An unreadable or half-written record reads the same way, which
- retains too much rather than deleting something that was never ours.
- """
+ """The recorded identity of ``root`` and the spills written into it. ``(None, {})`` when there
+ is no record, which is the answer for any directory this process did not create. An
+ unreadable or half-written record reads the same way, which retains too much rather than
+ deleting something that was never ours."""
try:
with open(_spill_record_path(root), encoding = "utf-8") as handle:
lines = handle.read().splitlines()
@@ -15273,8 +14302,8 @@ def _spill_record(root: str) -> "tuple[str | None, dict[str, tuple[str, str]]]":
name, _, rest = line.strip().partition("\t")
stamp, _, digest = rest.partition("\t")
if name and stamp and digest:
- # Last line wins: the same content spilled twice rewrites the file, and the
- # stamp of the write actually on disk is the later one.
+ # Last line wins: the same content spilled twice rewrites the file, and the stamp of the write actually on
+ # disk is the later one.
entries[name] = (stamp, digest)
return identity, entries
@@ -15313,13 +14342,10 @@ def _write_spill_manifest(
def _record_spill(root: str, relative: str, stamp: str, digest: str) -> None:
- """Append one written spill, with the stamp and digest of what was INSTALLED.
-
- Not re-read from the path: between the install and this, another call sharing the
- sandbox can replace the file, and stating the path then records that call's content as
- Unsloth's, which a later prune or cleanup would delete. The writer knows what it put
- there, so it says so.
- """
+ """Append one written spill, with the stamp and digest of what was INSTALLED. Not re-read from
+ the path: between the install and this, another call sharing the sandbox can replace the
+ file, and stating the path then records that call's content as Unsloth's, which a later prune
+ or cleanup would delete. The writer knows what it put there, so it says so."""
try:
with _spill_lock(root):
with open(_spill_record_path(root), "a", encoding = "utf-8") as handle:
@@ -15329,20 +14355,19 @@ def _record_spill(root: str, relative: str, stamp: str, digest: str) -> None:
def _spill_scope(session_id: "str | None", thread_id: "str | None") -> "str | None":
- """Where this call's spills belong, or None for "retain nothing".
-
- Nothing is retained in a sandbox that more than one chat runs in. A project's chats
- share one session by design (`project_session_id`) and a call with no session lands in
- the shared `_default` one, and in both the sandbox is a directory every sibling chat's
- model has a terminal in: a sub-directory is not access control, it is a name. Writing
- a result there puts output that existed only in one chat's response on disk where the
- next chat can read it, and lets that chat prune the files this one was told to page
- through.
-
- So the trade is stated rather than hidden: in a project, a large result is truncated
- with a notice and no continuation. Only a chat with a sandbox of its own gets paging.
- ``thread_id`` is taken and unused for that reason -- it identifies the chat, which is
- not the thing that has to be separate.
+ """Where this call's spills belong, or None for retain nothing.
+
+ Nothing is retained in a sandbox that more than one chat runs in. A project's chats share one
+ session by design (`project_session_id`) and a call with no session lands in the shared
+ `_default` one, and in both the sandbox is a directory every sibling chat's model has a terminal
+ in: a sub-directory is not access control, it is a name. Writing a result there puts output that
+ existed only in one chat's response on disk where the next chat can read it, and lets that chat
+ prune the files this one was told to page through.
+
+ So the trade is stated rather than hidden: in a project, a large result is truncated with a
+ notice and no continuation. Only a chat with a sandbox of its own gets paging. ``thread_id`` is
+ taken and unused for that reason: it identifies the chat, which is not the thing that has to be
+ separate.
"""
if not session_id or session_id.startswith(_PROJECT_SESSION_PREFIX):
return None
@@ -15350,11 +14375,9 @@ def _spill_scope(session_id: "str | None", thread_id: "str | None") -> "str | No
def _spill_phrase(spill: str, complete: bool) -> str:
- """How the notice names the spill, which depends on whether all of it got there.
-
- Lower case, and capitalised by the caller that needs it: the phrase ends in a path,
- and case-folding a whole sentence to fit it into another would fold that too.
- """
+ """How the notice names the spill, which depends on whether all of it got there. Lower case, and
+ capitalised by the caller that needs it: the phrase ends in a path, and case-folding a whole
+ sentence to fit it into another would fold that too."""
if complete:
return f"full output saved to {spill}"
return f"the first {_SPILL_MAX_BYTES} bytes of it are saved to {spill}"
@@ -15376,13 +14399,10 @@ def _spill_full_output(
workdir: str | None,
scope: "str | None" = "",
) -> "tuple[str | None, bool]":
- """Write the result into the sandbox; return its relative path and whether it is whole.
-
- ``(None, True)`` whenever it cannot be done -- no workdir, a read-only mount, a full
- disk, a path that is not what it claims to be. The caller then falls back to the plain
- notice, because a hint naming a file that is not there is worse than admitting the
- output is gone.
- """
+ """Write the result into the sandbox; return its relative path and whether it is whole. ``(None,
+ True)`` whenever it cannot be done: no workdir, a read-only mount, a full disk, a path that
+ is not what it claims to be. The caller then falls back to the plain notice, because a hint
+ naming a file that is not there is worse than admitting the output is gone."""
if not workdir or not os.path.isdir(workdir) or scope is None:
return None, True
try:
@@ -15390,12 +14410,11 @@ def _spill_full_output(
return None, True
relative = f"{_SPILL_DIR}/{scope}" if scope else _SPILL_DIR
target_dir = os.path.join(workdir, *relative.split("/"))
- # The sandbox is a directory the model runs commands in, so `.unsloth_tool_output`
- # may already be a symlink it made, or one that came with a project opened as the
- # workdir. makedirs(exist_ok=True) and a plain open() both follow it, which writes
- # this result outside the sandbox with the backend's own permissions and then lets
- # the prune delete files there. Refuse instead: no spill means a notice without a
- # continuation hint, which is a great deal better than a write out of bounds.
+ # The sandbox is a directory the model runs commands in, so `.unsloth_tool_output` may already be a symlink it
+ # made, or one that came with a project opened as the workdir. makedirs(exist_ok=True) and a plain open() both
+ # follow it, which writes this result outside the sandbox with the backend's own permissions and then lets the
+ # prune delete files there. Refuse instead: no spill means a notice without a continuation hint, which is a
+ # great deal better than a write out of bounds.
if any(
os.path.islink(os.path.join(workdir, *relative.split("/")[: n + 1]))
for n in range(len(relative.split("/")))
@@ -15405,50 +14424,42 @@ def _spill_full_output(
expected = os.path.join(os.path.realpath(workdir), *relative.split("/"))
if os.path.realpath(target_dir) != expected:
return None, True
- # Named from the CONTENT, not at random. The result has to come back byte-identical
- # with and without an output_callback (the streaming invariant asserted by
- # test_truncated_result_identical_and_notice_neutral_with_streaming), and a random
- # name puts a different path in the notice on each of the two runs. Content
- # addressing also means asking for the same file twice reuses one spill instead of
- # filling the sandbox with copies, which is the repeat case this whole change is
- # about.
- # Bounded before it is written rather than after: pruning by count alone still
- # lets one enormous result through, and by then it is already on the disk.
+ # Named from the CONTENT, not at random. The result has to come back byte-identical with and without an
+ # output_callback (the streaming invariant asserted by
+ # test_truncated_result_identical_and_notice_neutral_with_streaming), and a random name puts a different path
+ # in the notice on each of the two runs. Content addressing also means asking for the same file twice reuses
+ # one spill instead of filling the sandbox with copies.
+ # Bounded before it is written rather than after: pruning by count alone still lets one enormous result
+ # through, and by then it is already on the disk.
digest, spilled_bytes, head = _digest_and_head(text, _SPILL_MAX_BYTES)
name = f"{digest}.txt"
complete = spilled_bytes <= _SPILL_MAX_BYTES
# Cut on a character boundary, so what lands is still decodable text.
body = text if complete else head.decode("utf-8", "ignore")
- # newline="" so the bytes on disk are the bytes measured. The default translates
- # "\n" to os.linesep, which on Windows writes an extra byte per line, and the
- # byte offset in the continuation hint is counted from the untranslated text --
- # so a mid-line resume would start one byte early for every preceding newline.
+ # newline="" so the bytes on disk are the bytes measured. The default translates "\n" to os.linesep, which on
+ # Windows writes an extra byte per line, and the byte offset in the continuation hint is counted from the
+ # untranslated text, so a mid-line resume would start one byte early for every preceding newline.
path = os.path.join(target_dir, name)
- # Written to a fresh O_EXCL file and moved into place, never opened O_TRUNC over
- # whatever is already at that path. The spill name is derived from content the
- # model produced, so it can predict it and pre-create it: as a symlink (refused by
- # O_NOFOLLOW and the check above) or as a HARD link, which reports islink() false
- # and shares the inode of some file outside the sandbox. Truncating that writes
- # through to it with the backend's privileges; replacing a directory entry does
- # not touch the linked file at all.
- # The name comes from the content, so re-running a command lands on the same path,
- # and the file there may no longer be the spill this wrote: a later call can have
- # put the user's own data at it. `_is_recorded_spill` is what says whether it is
- # still ours, and the rename below would otherwise replace it either way.
+ # Written to a fresh O_EXCL file and moved into place, never opened O_TRUNC over whatever is already at that
+ # path. The spill name is derived from content the model produced, so it can predict it and pre-create it: as
+ # a symlink (refused by O_NOFOLLOW and the check above) or as a HARD link, which reports islink() false and
+ # shares the inode of some file outside the sandbox. Truncating that writes through to it with the backend's
+ # privileges; replacing a directory entry does not touch the linked file at all.
+ # The name comes from the content, so re-running a command lands on the same path, and the file there may no
+ # longer be the spill this wrote: a later call can have put the user's own data at it. `_is_recorded_spill` is
+ # what says whether it is still ours, and the rename below would otherwise replace it either way.
path = os.path.join(target_dir, name)
if os.path.exists(path):
- # The name is the digest of the text, so a recorded spill at it already HOLDS
- # this content: reuse it and write nothing. That is the repeat case this whole
- # change is about, and not writing is also the only way not to race with
- # another call that may be replacing the file right now.
+ # The name is the digest of the text, so a recorded spill at it already HOLDS this content: reuse it and
+ # write nothing. That is the repeat case this whole change is about, and not writing is also the only way
+ # not to race with another call that may be replacing the file right now.
if _is_recorded_spill(
os.path.join(workdir, _SPILL_DIR),
path,
_spill_manifest(os.path.join(workdir, _SPILL_DIR)),
):
return f"{relative}/{name}", complete
- # Not ours: the user's code put something at that path, and the install below
- # would replace it.
+ # Not ours: the user's code put something at that path, and the install below would replace it.
return None, True
stamp = _write_spill_file(target_dir, name, body)
if stamp is None:
@@ -15460,8 +14471,8 @@ def _spill_full_output(
hashlib.sha256(body.encode("utf-8", "surrogatepass")).hexdigest(),
)
_prune_spills(target_dir, os.path.join(workdir, _SPILL_DIR))
- # Relative, so the command works from the cwd the tools already run in, and so
- # the absolute sandbox path never reaches the model.
+ # Relative, so the command works from the cwd the tools already run in, and so the absolute sandbox path never
+ # reaches the model.
return f"{relative}/{name}", complete
except Exception:
logger.debug("tool result spill failed", exc_info = True)
@@ -15470,9 +14481,7 @@ def _spill_full_output(
def _spill_files(root: str, directory: str, owned: "set[str]") -> "list[str]":
"""The spills in one directory: the ones ``owned`` records this process having written.
-
- Everything else there is the user's, whatever it is called. Links are never spills.
- """
+ Everything else there is the user's, whatever it is called. Links are never spills."""
try:
names = os.listdir(directory)
except OSError:
@@ -15487,22 +14496,21 @@ def _spill_files(root: str, directory: str, owned: "set[str]") -> "list[str]":
def _unlink_verified_spill(root: str, path: str, owned: "dict[str, tuple[str, str]]") -> bool:
"""Delete a spill, and only ever the file that was checked.
- Moved to a private name first. A rename is atomic, so from that point the inode this
- verifies is the inode this deletes: a sandbox writer that replaces the original name
- afterwards replaces nothing that is on its way out. Verifying and then unlinking by
- name cannot promise that, because the manifest lock orders Unsloth's own threads and
- the thing racing here is the sandbox.
-
- Checked again under the private name, and put back if it no longer matches, since at
- that point it is not the file this recorded and is not this to delete. The rename
- itself moves ctime, which is ours to move, so the second check compares the device,
- inode, size and mtime, and the content.
-
- Nothing but a regular file with the recorded identity is moved at all: a directory or
- a FIFO left at the name by the sandbox is rejected through its own descriptor before
- the rename, so the restore below is never asked to put back a kind of thing `os.link`
- cannot. That leaves only the vanishing window between the check and the rename, and
- the restore handles it by falling back to a rename when the name is free again.
+ Moved to a private name first. A rename is atomic, so from that point the inode this verifies is
+ the inode this deletes: a sandbox writer that replaces the original name afterwards replaces
+ nothing that is on its way out. Verifying and then unlinking by name cannot promise that,
+ because the manifest lock orders Unsloth's own threads and the thing racing here is the sandbox.
+
+ Checked again under the private name, and put back if it no longer matches, since at that point
+ it is not the file this recorded and is not this to delete. The rename itself moves ctime, which
+ is ours to move, so the second check compares the device, inode, size and mtime, and the
+ content.
+
+ Nothing but a regular file with the recorded identity is moved at all: a directory or a FIFO
+ left at the name by the sandbox is rejected through its own descriptor before the rename, so the
+ restore below is never asked to put back a kind of thing `os.link` cannot. That leaves only the
+ vanishing window between the check and the rename, and the restore handles it by falling back to
+ a rename when the name is free again.
"""
directory, name = os.path.split(path)
recorded = owned.get(os.path.relpath(path, root).replace(os.sep, "/"))
@@ -15528,14 +14536,11 @@ def _unlink_verified_spill(root: str, path: str, owned: "dict[str, tuple[str, st
def _is_stamped_regular(path: str, stamp: str) -> bool:
- """Whether ``path`` is right now the regular file ``stamp`` recorded.
-
- Through a descriptor rather than the path, and for the same reasons `_file_digest`
- does it that way: O_NOFOLLOW refuses a symlink dropped at the name and O_NONBLOCK
- refuses to hang on a FIFO or a device. A directory opens, and is rejected by the
- mode check. ctime is deliberately not compared -- the caller compares it under the
- private name, where the rename it performs has already moved it.
- """
+ """Whether ``path`` is right now the regular file ``stamp`` recorded. Through a descriptor
+ rather than the path, and for the same reasons `_file_digest` does it that way: O_NOFOLLOW
+ refuses a symlink dropped at the name and O_NONBLOCK refuses to hang on a FIFO or a device. A
+ directory opens, and is rejected by the mode check. ctime is deliberately not compared: the
+ caller compares it under the private name, where the rename it performs has already moved it."""
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
fd = None
try:
@@ -15554,16 +14559,13 @@ def _is_stamped_regular(path: str, stamp: str) -> bool:
def _restore_pruned_path(private: str, path: str) -> None:
- """Put back something the prune moved but must not delete.
-
- `os.link` first, because it refuses to overwrite: if the sandbox has taken the name
- again in the meantime, the file it put there is not this to replace. A hard link
- cannot be made to a directory, so when it fails and the name is in fact free, the
- rename that moved this here is reversed instead, which works whatever was moved.
- Neither can promise the name is still free at the instant it runs, so the last resort
- is to leave the data under the private name and say where it went, rather than
- unlink it.
- """
+ """Put back something the prune moved but must not delete. `os.link` first, because it refuses
+ to overwrite: if the sandbox has taken the name again in the meantime, the file it put there
+ is not this to replace. A hard link cannot be made to a directory, so when it fails and the
+ name is in fact free, the rename that moved this here is reversed instead, which works
+ whatever was moved. Neither can promise the name is still free at the instant it runs, so the
+ last resort is to leave the data under the private name and say where it went, rather than
+ unlink it."""
try:
os.link(private, path)
_quiet_unlink(private)
@@ -15576,27 +14578,25 @@ def _restore_pruned_path(private: str, path: str) -> None:
return
except OSError:
pass
- # The name is taken again, so whatever is there now is not this to overwrite either.
- # The file stays, under a name nothing will prune.
+ # The name is taken again, so whatever is there now is not this to overwrite either. The file stays, under a name
+ # nothing will prune.
logger.warning("tool result spill prune: kept a swapped file as %s", private)
def _prune_spills(target_dir: str, root: "str | None" = None) -> None:
"""Bound this scope by count and the whole spill tree by bytes.
- A long session prints many large results and each one is retained; without this the
- sandbox grows without bound for output the model has almost certainly finished paging
- through.
+ A long session prints many large results and each one is retained; without this the sandbox
+ grows without bound for output the model has almost certainly finished paging through.
- The byte budget is enforced across ``root`` rather than per directory. A project's
- chats each get their own scope under one shared sandbox, so a per-directory limit is
- really a per-chat limit and a project with many tool-using chats multiplies it by
- however many there are.
+ The byte budget is enforced across ``root`` rather than per directory. A project's chats each
+ get their own scope under one shared sandbox, so a per-directory limit is really a per-chat
+ limit and a project with many tool-using chats multiplies it by however many there are.
"""
root = root or target_dir
try:
- # Held across the read and the rewrite below, so a spill recorded in between is
- # not dropped from the manifest by a prune that read it before the append.
+ # Held across the read and the rewrite below, so a spill recorded in between is not dropped from the manifest
+ # by a prune that read it before the append.
with _spill_lock(root):
_prune_spills_locked(target_dir, root)
except Exception:
@@ -15628,16 +14628,15 @@ def _prune_spills_locked(target_dir: str, root: str) -> None:
size = os.path.getsize(path)
except OSError:
continue
- # The newest is always kept, whatever the budget says: it is the file the
- # notice about to be returned names, and a hint pointing at a path that was
- # deleted on the way out is worse than no hint at all.
+ # The newest is always kept, whatever the budget says: it is the file the notice about to be returned
+ # names, and a hint pointing at a path that was deleted on the way out is worse than no hint at all.
if kept == 0 or total + size <= _SPILL_MAX_TOTAL_BYTES:
kept, total = kept + 1, total + size
continue
if _unlink_verified_spill(root, path, owned):
removed.add(path)
- # The manifest follows the files: a name left in it after its file is gone would
- # keep being counted as something this owns.
+ # The manifest follows the files: a name left in it after its file is gone would keep being counted as
+ # something this owns.
_write_spill_manifest(
root,
{
@@ -15646,8 +14645,8 @@ def _prune_spills_locked(target_dir: str, root: str) -> None:
if os.path.join(root, *name.split("/")) not in removed
},
)
- # An emptied scope is a chat that stopped spilling, and leaving its directory
- # behind is what makes the sandbox look non-empty to the cleanup.
+ # An emptied scope is a chat that stopped spilling, and leaving its directory behind is what makes the sandbox
+ # look non-empty to the cleanup.
for name in sorted(os.listdir(root)):
scope = os.path.join(root, name)
if os.path.isdir(scope) and not os.path.islink(scope) and not os.listdir(scope):
@@ -15659,8 +14658,8 @@ def _prune_spills_locked(target_dir: str, root: str) -> None:
logger.debug("tool result spill prune failed", exc_info = True)
-# ChatGPT code-interpreter path conventions models write out of habit; none
-# exist in the Unsloth sandbox, so a failure on one earns the retry hint.
+# ChatGPT code-interpreter path conventions models write out of habit; none exist in the Unsloth sandbox, so a failure
+# on one earns the retry hint.
_MISSING_PATH_PREFIXES = (
"/mnt/data",
"/mnt/outputs",
@@ -15669,21 +14668,19 @@ _MISSING_PATH_PREFIXES = (
"/tmp/outputs",
)
-# Matches the quoted path in a Python OSError str and the bare path in a bash
-# "No such file or directory" error; applied only to the error line.
+# Matches the quoted path in a Python OSError str and the bare path in a bash "No such file or directory" error;
+# applied only to the error line.
_QUOTED_ABS_PATH_RE = re.compile(r"""['"](/[^'"\n]+)['"]""")
_BASH_ABS_PATH_RE = re.compile(r"(/[^\s:'\"]+):\s*No such file or directory")
-# The sandbox CWD is a per-session dir under the studio home; an absolute path
-# under it is a genuine local miss, not a hallucinated out-of-sandbox write.
-# Resolved through the same helper as _get_workdir so the two cannot drift.
+# The sandbox CWD is a per-session dir under the studio home; an absolute path under it is a genuine local miss, not a
+# hallucinated out-of-sandbox write. Resolved through the same helper as _get_workdir so the two cannot drift.
def _missing_error_lines(output: str) -> list[str]:
- """The lines that actually name a missing file (a FileNotFoundError message
- or a bash "No such file or directory"). Traceback frame lines such as
- ``File "/workspace/proj/script.py"`` are excluded, so an unrelated absolute
- path mentioned elsewhere in the output is never treated as the failing one."""
+ """The lines that actually name a missing file (a FileNotFoundError message or a bash "No such
+ file or directory"). Traceback frame lines are excluded, so an unrelated absolute path
+ mentioned elsewhere in the output is never treated as the failing one."""
return [
line
for line in output.splitlines()
@@ -15704,14 +14701,11 @@ def _extract_missing_abs_path(output: str) -> str | None:
def _is_outside_workdir(abs_path: str, workdir: str | None = None) -> bool:
- """True when ``abs_path`` is not the working directory or under it.
-
- ``workdir`` is the executor's actual working directory (defaults to the
- sandbox root). Project-backed sessions run under a root OUTSIDE
- ``~/studio_sandbox`` (see ``_get_workdir``), so a legitimate miss inside a
- project must be judged against the real workdir, not a static sandbox root,
- or it is wrongly classed as an external habit path.
- """
+ """True when ``abs_path`` is not the working directory or under it. ``workdir`` is the
+ executor's actual working directory (defaults to the sandbox root). Project-backed sessions
+ run under a root OUTSIDE ``~/studio_sandbox`` (see ``_get_workdir``), so a legitimate miss
+ inside a project must be judged against the real workdir, not a static sandbox root, or it is
+ wrongly classed as an external habit path."""
try:
root = os.path.realpath(workdir or sandbox_root())
rp = os.path.realpath(abs_path)
@@ -15721,22 +14715,20 @@ def _is_outside_workdir(abs_path: str, workdir: str | None = None) -> bool:
def _missing_path_hint(output: str, workdir: str | None = None) -> str:
- """Model-visible healing when an execution fails on an absolute path missing
- in the sandbox (a code-interpreter habit path, or one invented from the CWD).
- Detected on the full pre-truncation output; the hint echoes the failing path
- so the model retries with the right relative name."""
+ """Model-visible healing when an execution fails on an absolute path missing in the sandbox (a
+ code-interpreter habit path, or one invented from the CWD). Detected on the full
+ pre-truncation output; the hint echoes the failing path so the model retries with the right
+ relative name."""
error_lines = _missing_error_lines(output)
if not error_lines:
return ""
abs_path = _extract_missing_abs_path(output)
- # A convention prefix is an out-of-sandbox signal only when the exact failing
- # path could not be isolated; scoped to the failing-path error line(s) so a
- # prefix mentioned elsewhere doesn't trigger a misleading hint.
+ # A convention prefix is an out-of-sandbox signal only when the exact failing path could not be isolated; scoped
+ # to the failing-path error line(s) so a prefix mentioned elsewhere doesn't trigger a misleading hint.
convention = any(prefix in line for line in error_lines for prefix in _MISSING_PATH_PREFIXES)
if abs_path is not None:
- # Judge the isolated path against the real workdir even when it matches a
- # convention prefix, so a genuine miss inside a project rooted under such
- # a prefix (e.g. /workspace/proj) is not steered out of its subdirectory.
+ # Judge the isolated path against the real workdir even when it matches a convention prefix, so a genuine miss
+ # inside a project rooted under such a prefix is not steered out of its subdirectory.
if not _is_outside_workdir(abs_path, workdir):
return ""
elif not convention:
@@ -15761,21 +14753,19 @@ def _drain_process_output(
*,
pgid = None,
) -> tuple[str, bool]:
- """``proc.communicate(timeout=...)`` equivalent that also streams each
- stdout line to ``output_callback`` as it is produced.
-
- Returns ``(output, timed_out)``. The joined output is identical to what
- ``communicate`` would return: the same TextIOWrapper decodes the stream,
- so encoding, error replacement, and newline translation all match. On
- timeout the process tree is killed (mirroring the non-streaming path).
- With ``timeout=None`` the drain waits for EOF like ``communicate`` would,
- stopping early only when ``cancel_event`` is set.
+ """``proc.communicate(timeout=...)`` equivalent that also streams each stdout line to
+ ``output_callback`` as it is produced.
+
+ Returns ``(output, timed_out)``. The joined output is identical to what ``communicate`` would
+ return: the same TextIOWrapper decodes the stream, so encoding, error replacement, and newline
+ translation all match. On timeout the process tree is killed (mirroring the non-streaming path).
+ With ``timeout=None`` the drain waits for EOF like ``communicate`` would, stopping early only
+ when ``cancel_event`` is set.
"""
chunks: list[str] = []
- # Captured before waiting so a stdout-holding grandchild can still be killed
- # after the leader is reaped (getpgid then fails). Callers pass it in from
- # right after Popen; fall back to capturing here for direct callers.
+ # Captured before waiting so a stdout-holding grandchild can still be killed after the leader is reaped (getpgid
+ # then fails). Callers pass it in from right after Popen; fall back to capturing here for direct callers.
if pgid is None:
pgid = _capture_process_group(proc)
@@ -15800,22 +14790,19 @@ def _drain_process_output(
except subprocess.TimeoutExpired:
timed_out = True
_kill_process_tree(proc)
- # Also kill the pre-captured group in case the leader was reaped in the
- # window before _kill_process_tree sampled its pgid, reaping a
- # stdout-holding grandchild (matches the non-streaming timeout path).
+ # Also kill the pre-captured group in case the leader was reaped in the window before _kill_process_tree
+ # sampled its pgid, reaping a stdout-holding grandchild (matches the non-streaming timeout path).
_killpg_captured(pgid)
try:
proc.wait(timeout = 5)
except subprocess.TimeoutExpired:
pass
- # A grandchild that inherited stdout can hold the pipe open past the main
- # process's exit.
+ # A grandchild that inherited stdout can hold the pipe open past the main process's exit.
if not timed_out:
if timeout is not None:
- # Wait out the remaining budget like communicate() would, polling
- # cancel_event in slices (the cancel watcher is gone once the leader
- # exits) so a chatty grandchild doesn't keep draining after a Stop.
- # The normal path still reaches EOF on its own with the same bytes.
+ # Wait out the remaining budget like communicate() would, polling cancel_event in slices (the cancel
+ # watcher is gone once the leader exits) so a chatty grandchild doesn't keep draining after a Stop. The
+ # normal path still reaches EOF on its own with the same bytes.
deadline = started_at + timeout
while reader.is_alive():
remaining = deadline - time.monotonic()
@@ -15828,8 +14815,8 @@ def _drain_process_output(
break
reader.join(timeout = min(0.5, remaining))
else:
- # Unlimited timeout: drain until the pipe closes (like
- # communicate(timeout=None)), stopping early only on cancellation.
+ # Unlimited timeout: drain until the pipe closes (like communicate(timeout=None)), stopping early only on
+ # cancellation.
while reader.is_alive():
if cancel_event is not None and cancel_event.is_set():
_killpg_captured(pgid)
@@ -15840,9 +14827,8 @@ def _drain_process_output(
_MAX_REPORTED_FILES = 25
-# Bounded so an unpacked archive cannot turn a tool call into a filesystem
-# crawl. In path segments, the unit the download route enforces, so a card can
-# never advertise a file that route would refuse.
+# Bounded so an unpacked archive cannot turn a tool call into a filesystem crawl. In path segments, the unit the
+# download route enforces, so a card can never advertise a file that route would refuse.
_MAX_SANDBOX_PATH_SEGMENTS = 4
_MAX_SNAPSHOT_FILES = 2000 # a shard-writing script must not blow up the result
_MAX_SNAPSHOT_DIRS = 2000 # nor a directory-writing one stall the next call
@@ -15851,14 +14837,14 @@ _MAX_SNAPSHOT_DIRS = 2000 # nor a directory-writing one stall the next call
def _user_path_parts(parts: "list[str]", root: "str | None" = None) -> "list[str]":
"""The segments _MAX_SANDBOX_PATH_SEGMENTS applies to.
- The scratch container is Unsloth's, not a name the model chose, and on
- Windows it is what /tmp resolves to, so charging it a segment would drop one
- level of the /tmp artifacts served before the workdir stopped being %TEMP%.
+ The scratch container is Unsloth's, not a name the model chose, and on Windows it is what /tmp
+ resolves to, so charging it a segment would drop one level of the /tmp artifacts served before
+ the workdir stopped being %TEMP%.
- *root* is for callers that resolve the path afterwards. The walks read the
- stored spelling off os.walk and never follow links; the download route
- resolves, and without the root a link named unsloth-tmp (or a wrong-case
- entry on NTFS or APFS) would take the discount for a tree neither walk lists.
+ *root* is for callers that resolve the path afterwards. The walks read the stored spelling off
+ os.walk and never follow links; the download route resolves, and without the root a link named
+ unsloth-tmp (or a wrong-case entry on NTFS or APFS) would take the discount for a tree neither
+ walk lists.
"""
if not parts or parts[0] != _SANDBOX_TEMP_DIRNAME:
return parts
@@ -15869,37 +14855,34 @@ def _user_path_parts(parts: "list[str]", root: "str | None" = None) -> "list[str
return parts[1:]
-# The same allowlist the download route applies per segment, so a name that
-# route would refuse never reaches a file chip.
+# The same allowlist the download route applies per segment, so a name that route would refuse never reaches a file
+# chip.
_SERVABLE_SEGMENT_RE = re.compile(r"\A[^/\\\x00-\x1f]{1,255}\Z")
def _servable_segment(name: str) -> bool:
if name in (".", "..") or not _SERVABLE_SEGMENT_RE.match(name):
return False
- # Non-UTF-8 bytes in a POSIX filename surface as lone surrogates, which
- # encodeURIComponent throws on, so the chip could never issue its download.
+ # Non-UTF-8 bytes in a POSIX filename surface as lone surrogates, which encodeURIComponent throws on, so the chip
+ # could never issue its download.
return not any("\ud800" <= ch <= "\udfff" for ch in name)
-# Unsloth's own bookkeeping, written by the sandbox sitecustomize. One exact
-# name we write ourselves, not a pattern reserved over names a tool may pick.
+# Unsloth's own bookkeeping, written by the sandbox sitecustomize. One exact name we write ourselves, not a pattern
+# reserved over names a tool may pick.
_INTERNAL_SANDBOX_FILES = frozenset({".unsloth_sandbox_remap.json", _SANDBOX_MARKER})
-# Above this a file is identified by mtime and size alone. Rewriting a large
-# artifact byte for byte inside one filesystem tick is not worth reading every
-# artifact twice per tool call.
+# Above this a file is identified by mtime and size alone. Rewriting a large artifact byte for byte inside one
+# filesystem tick is not worth reading every artifact twice per tool call.
_MAX_HASHED_SNAPSHOT_BYTES = 4 * 1024 * 1024
def _content_key(path: str, size: int) -> "str | None":
- """A digest for a file small enough to read, else None.
-
- On FAT/exFAT and some network volumes the timestamp granularity is a second
- or two, so an overwrite with different content of the same length inside one
- tick is invisible to mtime and size, and the call reported no file at all.
- """
+ """A digest for a file small enough to read, else None. On FAT/exFAT and some network volumes
+ the timestamp granularity is a second or two, so an overwrite with different content of the
+ same length inside one tick is invisible to mtime and size, and the call reported no file at
+ all."""
if size > _MAX_HASHED_SNAPSHOT_BYTES:
return None
try:
@@ -15912,23 +14895,22 @@ def _content_key(path: str, size: int) -> "str | None":
return None
-# Volumes already known to timestamp finely, by device id. Only the positive is
-# kept: a negative costs one stat to redo and hashing to get wrong.
+# Volumes already known to timestamp finely, by device id. Only the positive is kept: a negative costs one stat to
+# redo and hashing to get wrong.
_fine_mtime_devices: "set[int]" = set()
def _volume_timestamps_finely(workdir: str) -> bool:
"""Whether this volume records sub-second times, so digests can be skipped.
- That is the only thing the digest buys: at sub-second resolution a program
- cannot overwrite a file inside the tick of its own previous write, and
- reading every artifact twice per call was ~90% of a snapshot's cost.
+ That is the only thing the digest buys: at sub-second resolution a program cannot overwrite a
+ file inside the tick of its own previous write, and reading every artifact twice per call was
+ ~90% of a snapshot's cost.
- Read off the directory rather than probed with a file of our own: several
- chats can share a workdir, and a probe file appearing mid-walk is reported
- as a file the other call created. Three stamps because one whole-second
- reading on a fine volume is chance; three is not. Anything unreadable
- answers False, which hashes exactly as before.
+ Read off the directory rather than probed with a file of our own: several chats can share a
+ workdir, and a probe file appearing mid-walk is reported as a file the other call created. Three
+ stamps because one whole-second reading on a fine volume is chance; three is not. Anything
+ unreadable answers False, which hashes exactly as before.
"""
try:
stat = os.stat(workdir)
@@ -15945,43 +14927,36 @@ def _volume_timestamps_finely(workdir: str) -> bool:
def _defuse_sentinels(text: str) -> str:
- """Break a marker line the executed program printed itself.
-
- Both readers take the last one, so a call that created nothing and printed
- `__FILES__:[{"name": "report.csv", "size": 1}]` had that read as the
- envelope: the line was hidden from the model and the UI offered a download
- for a file nobody wrote. One space is enough, since both anchor on the line
- start, and it leaves the text otherwise as the program wrote it.
- """
+ """Break a marker line the executed program printed itself. Both readers take the last one, so a
+ call that created nothing and printed `__FILES__:[{"name": "report.csv", "size": 1}]` had
+ that read as the envelope: the line was hidden from the model and the UI offered a download
+ for a file nobody wrote. One space is enough, since both anchor on the line start, and it
+ leaves the text otherwise as the program wrote it."""
for marker in ("\n__FILES__:", "\n__IMAGES__:"):
text = text.replace(marker, "\n " + marker[1:])
return text
-# What one snapshot may read to tell a same-size overwrite apart. The file cap
-# alone allowed 2,000 x 4 MiB per walk, twice per call, which on a directory of
-# artifacts made a trivial command look hung.
+# What one snapshot may read to tell a same-size overwrite apart. The file cap alone allowed 2,000 x 4 MiB per walk,
+# twice per call, which on a directory of artifacts made a trivial command look hung.
_MAX_SNAPSHOT_HASH_BYTES = 64 * 1024 * 1024
def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
- """relative path -> change key for every regular file, for the post-run diff.
-
- All files, not just images: a .csv the model wrote used to be invisible.
- Size rides along with mtime because FAT/exFAT and some network volumes have
- coarse timestamps, where an overwrite inside one tick would look unchanged,
- and on those volumes alone a digest rides along too, since a same-length
- rewrite inside one tick matches on all of it otherwise.
- """
+ """relative path -> change key for every regular file, for the post-run diff. All files, not
+ just images: a .csv the model wrote used to be invisible. Size rides along with mtime because
+ FAT/exFAT and some network volumes have coarse timestamps, where an overwrite inside one tick
+ would look unchanged, and on those volumes alone a digest rides along too, since a
+ same-length rewrite inside one tick matches on all of it otherwise."""
snapshot: "dict[str, tuple]" = {}
if not workdir or not os.path.isdir(workdir):
return snapshot
- # Directories are budgeted separately from files: thousands of empty output
- # folders never reach the file cap, and this walk runs twice per tool call.
+ # Directories are budgeted separately from files: thousands of empty output folders never reach the file cap, and
+ # this walk runs twice per tool call.
visited = 0
hash_budget = 0 if _volume_timestamps_finely(workdir) else _MAX_SNAPSHOT_HASH_BYTES
- # Walked, not listed: a script writing outputs/report.csv is ordinary, and a
- # top-level listing saw only the directory and dropped it.
+ # Walked, not listed: a script writing outputs/report.csv is ordinary, and a top-level listing saw only the
+ # directory and dropped it.
for base, dirs, names in os.walk(workdir):
visited += 1
if visited > _MAX_SNAPSHOT_DIRS:
@@ -15989,26 +14964,24 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
# depth 0 is the workdir itself, whose files are one segment.
relative = base[len(workdir) :].strip(os.sep)
depth = len(_user_path_parts(relative.split(os.sep) if relative else []))
- # Dot-directories stay out: .git, .cache and friends are where the noise
- # lives. Dot-FILES are reported, since .gitignore is a real artifact.
+ # Dot-directories stay out: .git, .cache and friends are where the noise lives. Dot-FILES are reported, since
+ # .gitignore is a real artifact.
dirs[:] = (
[]
if depth >= _MAX_SANDBOX_PATH_SEGMENTS - 1
else [d for d in dirs if not d.startswith(".") and _servable_segment(d)]
)
for name in names:
- # Only at the top: a tool that wrote archive/.unsloth_sandbox made an
- # ordinary file, and dropping it hid it from every listing while
- # still counting it as a reason to keep the sandbox.
+ # Only at the top: a tool that wrote archive/.unsloth_sandbox made an ordinary file, and dropping it hid
+ # it from every listing while still counting it as a reason to keep the sandbox.
if base == workdir and name in _INTERNAL_SANDBOX_FILES:
continue
if not _servable_segment(name):
continue
path = os.path.join(base, name)
try:
- # One lstat where isfile + islink + stat were three, on every
- # file of every walk. A link is not a regular file to lstat, so
- # this drops the same entries the pair did.
+ # One lstat where isfile + islink + stat were three, on every file of every walk. A link is not a
+ # regular file to lstat, so this drops the same entries the pair did.
stat = os.lstat(path)
if not S_ISREG(stat.st_mode):
continue
@@ -16026,15 +14999,13 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
return snapshot
-# Scratch scripts of calls running right now. Chats in one project share a
-# workdir and each snapshots all of it, so without this the other call's
-# studio_exec_*.py is offered as this call's file and 404s once it is gone.
+# Scratch scripts of calls running right now. Chats in one project share a workdir and each snapshots all of it, so
+# without this the other call's studio_exec_*.py is offered as this call's file and 404s once it is gone.
_active_scratch: "set[str]" = set()
_scratch_lock = threading.Lock()
-# Tool calls running in each workdir. Chats in one project share one and each
-# call diffs the whole tree, so the other call's file would land on this card.
-# A call ever alongside another claims nothing, and no clock is involved.
+# Tool calls running in each workdir. Chats in one project share one and each call diffs the whole tree, so the other
+# call's file would land on this card. A call ever alongside another claims nothing, and no clock is involved.
_workdir_calls: "dict[str, list]" = {}
_calls_lock = threading.Lock()
@@ -16071,13 +15042,10 @@ def _call_finished(token: "dict | None") -> None:
def _snapshot_differs(before: tuple, after: tuple) -> bool:
- """Whether a file changed between two snapshots of its directory.
-
- The digest only when both snapshots have one: hashing stops at a byte
- budget, so a file added or removed earlier in the walk can push an
- untouched later file in or out of it, and comparing the tuples whole would
- then report that file as one this call wrote.
- """
+ """Whether a file changed between two snapshots of its directory. The digest only when both
+ snapshots have one: hashing stops at a byte budget, so a file added or removed earlier in the
+ walk can push an untouched later file in or out of it, and comparing the tuples whole would
+ then report that file as one this call wrote."""
if before[:2] != after[:2]:
return True
return before[2] is not None and after[2] is not None and before[2] != after[2]
@@ -16089,25 +15057,20 @@ def _created_file_sentinels(
exclude: "str | None" = None,
token: "dict | None" = None,
) -> str:
- """Sentinels naming the files this call created or overwrote.
-
- ``__IMAGES__`` renders inline as before; ``__FILES__`` carries every file
- with its size so the UI can offer a download. Both are stripped before the
- model sees the result.
- """
+ """Sentinels naming the files this call created or overwrote. ``__IMAGES__`` renders inline as
+ before; ``__FILES__`` carries every file with its size so the UI can offer a download. Both
+ are stripped before the model sees the result."""
if token is not None and token.get("shared"):
- # Another call ran in this directory while this one did, so nothing here
- # can be said to be ours. A missing card beats one that names, and
- # downloads, another chat's file.
+ # Another call ran in this directory while this one did, so nothing here can be said to be ours. A missing
+ # card beats one that names, and downloads, another chat's file.
return ""
after = _snapshot_workdir_files(workdir)
if token is not None and token.get("shared"):
- # A call that started while that walk was running. What it wrote is in
- # `after` and cannot be told apart from ours, so the same rule applies:
- # the check above only saves the walk when the sharing was already known.
+ # A call that started while that walk was running. What it wrote is in `after` and cannot be told apart from
+ # ours, so the same rule applies: the check above only saves the walk when the sharing was already known.
return ""
- # ``exclude`` is this call's own scratch script by exact name, not a pattern
- # reserved over names a tool might pick.
+ # ``exclude`` is this call's own scratch script by exact name, not a pattern reserved over names a tool might
+ # pick.
with _scratch_lock:
scratch = set(_active_scratch)
scratch.discard(exclude) # this call's own is named below anyway
@@ -16123,8 +15086,8 @@ def _created_file_sentinels(
import json as _json
- # Same cap on both: a script writing a frame per step would otherwise put
- # every name in the result and the stored chat, and the UI would render them all.
+ # Same cap on both: a script writing a frame per step would otherwise put every name in the result and the stored
+ # chat, and the UI would render them all.
images = [n for n in changed if os.path.splitext(n)[1].lower() in _IMAGE_EXTS]
images = images[:_MAX_REPORTED_FILES]
entries = []
@@ -16135,8 +15098,8 @@ def _created_file_sentinels(
size = None
entries.append({"name": name, "size": size})
- # __IMAGES__ stays LAST: older clients slice from it to the end of the
- # string, so anything after would land inside their JSON.
+ # __IMAGES__ stays LAST: older clients slice from it to the end of the string, so anything after would land inside
+ # their JSON.
out = f"\n__FILES__:{_json.dumps(entries)}"
if images:
out += f"\n__IMAGES__:{_json.dumps(images)}"
@@ -16180,13 +15143,10 @@ def _python_exec(
output_callback = None,
thread_id: str | None = None,
) -> str:
- """Execute Python code in a subprocess sandbox.
-
- disable_sandbox (Bypass Permissions): skip the safety analysis and rlimit
- pre-exec, and use the host env minus secrets.
- output_callback: optional callable(str) streamed each stdout line as it is
- produced; the returned result is unchanged.
- """
+ """Execute Python code in a subprocess sandbox. disable_sandbox (Bypass Permissions): skip the
+ safety analysis and rlimit pre-exec, and use the host env minus secrets. output_callback:
+ optional callable(str) streamed each stdout line as it is produced; the returned result is
+ unchanged."""
if not code or not code.strip():
return "No code provided."
@@ -16194,19 +15154,17 @@ def _python_exec(
if not disable_sandbox:
error = _check_code_safety(code)
if error:
- # Capped like any other result: the analyzer names every occurrence it
- # found, so code that repeats a forbidden construct enough times reports
- # back something larger than the room that is left, which is the overflow
- # this budget exists to prevent. See `_fit_result_to_room`.
+ # Capped like any other result: the analyzer names every occurrence it found, so code that repeats a
+ # forbidden construct enough times reports back something larger than the room that is left, which is the
+ # overflow this budget exists to prevent. See `_fit_result_to_room`.
return _truncate(error)
- # Stripping the child env is not enough: a same-UID child can read
- # /proc/<getppid()>/environ to recover the unfiltered secrets, so close
- # that read here too, not only in bypass mode. Best-effort: the child env
- # is already scrubbed, so a system where prctl is denied still runs.
+ # Stripping the child env is not enough: a same-UID child can read /proc/<getppid()>/environ to recover the
+ # unfiltered secrets, so close that read here too, not only in bypass mode. Best-effort: the child env is
+ # already scrubbed, so a system where prctl is denied still runs.
_harden_parent_against_proc_env_leak()
elif not _harden_parent_against_proc_env_leak():
- # Close the /proc/<parent>/environ secret-recovery path first; if it
- # cannot be applied, fail closed rather than leak the parent environ.
+ # Close the /proc/<parent>/environ secret-recovery path first; if it cannot be applied, fail closed rather
+ # than leak the parent environ.
return (
"Execution error: could not harden the Unsloth process against "
"/proc environment reads; refusing bypass execution."
@@ -16215,21 +15173,20 @@ def _python_exec(
tmp_path = None
_scratch_name = None
workdir = _get_workdir(session_id)
- # `_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share
- # one session by design. Retaining a result in either, under a path the next chat can
- # list, would leave behind output that existed only in this call's own response. See
- # `_spill_scope`, which returns None for exactly those cases.
+ # `_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share one session by design.
+ # Retaining a result in either, under a path the next chat can list, would leave behind output that existed only
+ # in this call's own response. See `_spill_scope`, which returns None for exactly those cases.
spill_scope = _spill_scope(session_id, thread_id)
spill_dir = workdir if session_id else None
call_token = _call_started(workdir)
# Snapshot mtimes to detect new and overwritten files.
_before = _snapshot_workdir_files(workdir)
try:
- # In the workdir: Python puts it on sys.path[0], so an earlier call's
- # helper.py stays importable and __file__ resolves inside the sandbox.
+ # In the workdir: Python puts it on sys.path[0], so an earlier call's helper.py stays importable and __file__
+ # resolves inside the sandbox.
fd, tmp_path = tempfile.mkstemp(suffix = ".py", prefix = "studio_exec_", dir = workdir)
- # utf-8 so non-ASCII in model-written code survives the OS default codec
- # (Windows cp1252 would otherwise raise UnicodeEncodeError).
+ # utf-8 so non-ASCII in model-written code survives the OS default codec (Windows cp1252 would otherwise raise
+ # UnicodeEncodeError).
_scratch_name = os.path.basename(tmp_path)
with _scratch_lock:
_active_scratch.add(_scratch_name)
@@ -16245,8 +15202,8 @@ def _python_exec(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
text = True,
- # Decode child output as utf-8 (it emits utf-8 via PYTHONIOENCODING);
- # replace so non-ASCII output never crashes the read on Windows.
+ # Decode child output as utf-8 (it emits utf-8 via PYTHONIOENCODING); replace so non-ASCII output never
+ # crashes the read on Windows.
encoding = "utf-8",
errors = "replace",
cwd = workdir,
@@ -16257,14 +15214,12 @@ def _python_exec(
else:
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
- # -u forces unbuffered child stdout so a bare print() streams live
- # instead of sitting in the pipe's block buffer until exit. Applied
- # unconditionally to stay byte-identical with and without streaming;
- # unlike PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.
+ # -u forces unbuffered child stdout so a bare print() streams live instead of sitting in the pipe's block
+ # buffer until exit. Applied unconditionally to stay byte-identical with and without streaming; unlike
+ # PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.
proc = subprocess.Popen([sys.executable, "-u", tmp_path], **popen_kwargs)
- # Capture the group before any watcher can reap the leader (see
- # _capture_process_group); None on Windows.
+ # Capture the group before any watcher can reap the leader (see _capture_process_group); None on Windows.
pgid = _capture_process_group(proc)
_adopt_tool_pid(proc.pid)
@@ -16276,15 +15231,14 @@ def _python_exec(
)
watcher.start()
- # Always drain via _drain_process_output (output_callback may be None):
- # it kills the captured group on cancellation, reaping a grandchild that
- # outlived the leader, and returns bytes identical to communicate() so
+ # Always drain via _drain_process_output (output_callback may be None): it kills the captured group on
+ # cancellation, reaping a grandchild that outlived the leader, and returns bytes identical to communicate() so
# the streaming vs non-streaming result stays byte-identical.
output, timed_out = _drain_process_output(
proc, timeout, output_callback, cancel_event, pgid = pgid
)
- # A run that wrote its file and then hung still produced that file, so
- # report it: `printf data > report.csv; sleep 999` is downloadable.
+ # A run that wrote its file and then hung still produced that file, so report it: `printf data > report.csv;
+ # sleep 999` is downloadable.
if timed_out:
ended = _timed_out_result(output, timeout, spill_dir, spill_scope)
return ended + (
@@ -16303,16 +15257,14 @@ def _python_exec(
result = output or ""
if proc.returncode != 0:
result = f"Exit code {proc.returncode}:\n{result}"
- # Detect the missing-path pattern on the full output (truncation could
- # hide the trailing traceback); append the hint after truncation. External
- # paths are judged against the real workdir (project sessions live outside
+ # Detect the missing-path pattern on the full output (truncation could hide the trailing traceback); append
+ # the hint after truncation. External paths are judged against the real workdir (project sessions live outside
# the default sandbox root).
hint = _missing_path_hint(result, workdir)
- # Before the fit, not after it. Defusing inserts a space into every line that
- # opens with a marker, so a result full of them grows after it has been measured
- # and the text replayed to the model is larger than the prefix that was admitted.
- # Before ours is appended, and whether or not one is: a program's own marker line
- # is not an envelope.
+ # Before the fit, not after it. Defusing inserts a space into every line that opens with a marker, so a result
+ # full of them grows after it has been measured and the text replayed to the model is larger than the prefix
+ # that was admitted. Before ours is appended, and whether or not one is: a program's own marker line is not an
+ # envelope.
result = _defuse_sentinels(result)
result = (
_truncate(result, workdir = spill_dir, scope = spill_scope, hint = hint)
@@ -16320,17 +15272,16 @@ def _python_exec(
else "(no output)" + hint
)
- # Only for a chat that has an id: without one every first turn shares
- # the _default workdir, so a card pinned to it would later download
- # whatever the next new chat wrote there.
+ # Only for a chat that has an id: without one every first turn shares the _default workdir, so a card pinned
+ # to it would later download whatever the next new chat wrote there.
if session_id:
result += _created_file_sentinels(workdir, _before, _scratch_name, call_token)
return result
except Exception as e:
- # An exception message carries whatever the failure put in it, so it is capped
- # like the result would have been.
+ # An exception message carries whatever the failure put in it, so it is capped like the result would have
+ # been.
return _truncate(f"Execution error: {e}")
finally:
_call_finished(call_token)
@@ -16354,13 +15305,10 @@ def _bash_exec(
output_callback = None,
thread_id: str | None = None,
) -> str:
- """Execute a bash command in a subprocess sandbox.
-
- disable_sandbox (Bypass Permissions): skip the command blocklist and rlimit
- pre-exec, and use the host env minus secrets.
- output_callback: optional callable(str) streamed each stdout line as it is
- produced; the returned result is unchanged.
- """
+ """Execute a bash command in a subprocess sandbox. disable_sandbox (Bypass Permissions): skip
+ the command blocklist and rlimit pre-exec, and use the host env minus secrets.
+ output_callback: optional callable(str) streamed each stdout line as it is produced; the
+ returned result is unchanged."""
if not command or not command.strip():
return "No command provided."
@@ -16368,17 +15316,16 @@ def _bash_exec(
if not disable_sandbox:
blocked = _find_blocked_commands(command)
if blocked:
- # Capped for the same reason the Python analyzer's error is: it lists what
- # it found in the command it was handed.
+ # Capped for the same reason the Python analyzer's error is: it lists what it found in the command it was
+ # handed.
return _truncate(f"Blocked command(s) for safety: {', '.join(sorted(blocked))}")
- # Stripping the child env is not enough: a same-UID child can read
- # /proc/<getppid()>/environ to recover the unfiltered secrets, so close
- # that read here too, not only in bypass mode. Best-effort: the child env
- # is already scrubbed, so a system where prctl is denied still runs.
+ # Stripping the child env is not enough: a same-UID child can read /proc/<getppid()>/environ to recover the
+ # unfiltered secrets, so close that read here too, not only in bypass mode. Best-effort: the child env is
+ # already scrubbed, so a system where prctl is denied still runs.
_harden_parent_against_proc_env_leak()
elif not _harden_parent_against_proc_env_leak():
- # Close the /proc/<parent>/environ secret-recovery path first; if it
- # cannot be applied, fail closed rather than leak the parent environ.
+ # Close the /proc/<parent>/environ secret-recovery path first; if it cannot be applied, fail closed rather
+ # than leak the parent environ.
return (
"Execution error: could not harden the Unsloth process against "
"/proc environment reads; refusing bypass execution."
@@ -16394,17 +15341,16 @@ def _bash_exec(
spill_scope = _spill_scope(session_id, thread_id)
spill_dir = workdir if session_id else None
call_token = _call_started(workdir)
- # Same pre-run snapshot as _python_exec. A command that writes a file used
- # to produce "(no output)" and no other trace anywhere in the product.
+ # Same pre-run snapshot as _python_exec. A command that writes a file used to produce "(no output)" and no
+ # other trace anywhere in the product.
_before = _snapshot_workdir_files(workdir)
safe_env = _build_bypass_env(workdir) if disable_sandbox else _build_safe_env(workdir)
popen_kwargs = dict(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
text = True,
- # Match _python_exec: decode utf-8 with "replace" so invalid output
- # bytes never raise UnicodeDecodeError (which the streaming reader
- # thread would swallow), keeping both paths byte-identical.
+ # Match _python_exec: decode utf-8 with "replace" so invalid output bytes never raise UnicodeDecodeError
+ # (which the streaming reader thread would swallow), keeping both paths byte-identical.
encoding = "utf-8",
errors = "replace",
cwd = workdir,
@@ -16417,8 +15363,7 @@ def _bash_exec(
proc = subprocess.Popen(_get_shell_cmd(command), **popen_kwargs)
- # Capture the group before any watcher can poll/reap the leader (see
- # _python_exec); None on Windows.
+ # Capture the group before any watcher can poll/reap the leader (see _python_exec); None on Windows.
pgid = _capture_process_group(proc)
_adopt_tool_pid(proc.pid)
@@ -16430,14 +15375,13 @@ def _bash_exec(
)
watcher.start()
- # Always drain via _drain_process_output (see _python_exec): kills the
- # captured group on cancellation and returns bytes identical to
- # communicate(), keeping streaming vs non-streaming byte-identical.
+ # Always drain via _drain_process_output (see _python_exec): kills the captured group on cancellation and
+ # returns bytes identical to communicate(), keeping streaming vs non-streaming byte-identical.
output, timed_out = _drain_process_output(
proc, timeout, output_callback, cancel_event, pgid = pgid
)
- # A run that wrote its file and then hung still produced that file, so
- # report it: `printf data > report.csv; sleep 999` is downloadable.
+ # A run that wrote its file and then hung still produced that file, so report it: `printf data > report.csv;
+ # sleep 999` is downloadable.
if timed_out:
ended = _timed_out_result(output, timeout, spill_dir, spill_scope)
return ended + (
@@ -16466,8 +15410,8 @@ def _bash_exec(
return result
except Exception as e:
- # An exception message carries whatever the failure put in it, so it is capped
- # like the result would have been.
+ # An exception message carries whatever the failure put in it, so it is capped like the result would have
+ # been.
return _truncate(f"Execution error: {e}")
finally:
_call_finished(call_token)
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 5fe3ea58d6e..99058cdaccc 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -21,10 +21,9 @@ import re
from dataclasses import dataclass, field
from typing import Optional
-# declared HERE so the shape gate and the bound cannot drift
# The request model's ceiling on num_frames, declared HERE so the shape gate and the bound cannot drift: the gate's
-# refusal names the lattice point above the request, and suggesting one the request model would itself reject is a dead
-# end. VideoGenerateRequest imports this for its `le`.
+# refusal names the lattice point above the request, and suggesting one the request model would itself reject is a
+# dead end. VideoGenerateRequest imports this for its `le`.
MAX_VIDEO_NUM_FRAMES = 1024
# Runtime->route contract: routes match these EXACTLY for a 409 instead of a 500.
@@ -53,7 +52,6 @@ class VideoFamily:
transformer2_class: Optional[str] = None
is_moe: bool = False
cfg2_kwarg: Optional[str] = None
- # HunyuanVideo-1.5: __call__ takes NO guidance kwarg
# HunyuanVideo-1.5 guidance: __call__ takes NO guidance kwarg; CFG lives on a ``guider`` whose scale is set per
# request.
guidance_via_guider: bool = False
@@ -153,9 +151,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (
max_num_frames = 345,
snap_frames_up = True,
resolution_multiple = 32,
- # model-card ratios use H3's canvas rule; the legacy 1024 square and cheaper 16:9 tiers are kept for
- # compatibility
- # Model-card ratios use H3's canvas rule. Keep the legacy 1024 square and cheaper 16:9 tiers for compatibility.
+ # Model-card ratios use H3's canvas rule. Keep the legacy 1024 square and cheaper 16:9 tiers for
+ # compatibility.
resolution_presets = (
(1344, 768),
(1536, 672),
@@ -169,24 +166,20 @@ _FAMILIES: tuple[VideoFamily, ...] = (
duration_presets = (5.0, 10.0, 14.4),
# Decimal GB resident estimates: transformer, Qwen3-VL conditioner, video+audio VAEs.
bf16_components_gb = (66.3, 66.8, 11.1),
- # regionally compilable: every block sees (1, S, 5376) plus an (S,) index tensor
# Regionally compilable. The DiT declares _repeated_blocks (MiniMaxH3TransformerBlock +
# MiniMaxH3TokenRefinerBlock); every block sees (1, S, 5376) plus an (S,) index tensor, where S is the PACKED
# length (18,870 video + 207 audio rows + the caption's text rows at 960x544x124). The caption moves S by ~2%
- # (19,096 at 19 tokens vs 19,479 at 402) and S cannot change mid-denoise, so dynamic=True traces once and holds:
- # measured 1.298-1.342 s/step eager vs 1.000-1.040 compiled (1.30x), first forward 10.2 s, zero recompiles
- # across captions of 19/19/37/128/402 tokens. The loader engages this only when the denoiser is RESIDENT;
- # compiling inside a full CPU-offload rotation measured slower than eager, so that case stays on the no-compile
- # tier.
+ # and S cannot change mid-denoise, so dynamic=True traces once and holds: measured 1.30x over eager with zero
+ # recompiles across captions of 19 to 402 tokens. The loader engages this only when the denoiser is RESIDENT;
+ # compiling inside a full CPU-offload rotation measured slower than eager.
supports_torch_compile = True,
supports_cuda_graph = True,
gguf_repo = "unsloth/MiniMax-H3-GGUF",
- # the modular workflow builds each component through its own from_pretrained
# Hosted pre-quantized FL2VA denoisers. The modular workflow builds each component through its own
# from_pretrained, so there is no dense module to quantise in place: these are the ONLY way to run the 66.3 GB
# transformer quantized, and seeding one also stops that download. Both schemes live in ONE repo, at the root,
- # named <Model>-<SCHEME>.pt, which is the layout every image-side prequant repo already uses and the one
- # prequant_repo_filename builds without help.
+ # named <Model>-<SCHEME>.pt, the layout every image-side prequant repo uses and the one prequant_repo_filename
+ # builds without help.
prequant_repos = (("int8", "unsloth/MiniMax-H3-FP8"), ("fp8", "unsloth/MiniMax-H3-FP8")),
# The INT8 denoiser is ConvRot-rotated (see diffusion_convrot): its weights live in a Hadamard-rotated basis and
# are wrong unless the loader rotates the activations to match, so it carries the v2 format tag an Unsloth
@@ -203,10 +196,9 @@ _FAMILIES: tuple[VideoFamily, ...] = (
("int8", "ref2va", "MiniMax-H3-Ref2VA-INT8-ConvRot.pt"),
("fp8", "ref2va", "MiniMax-H3-Ref2VA-FP8.pt"),
),
- # without a ref2va row above, a ref2va prequant pick is refused rather than served the keyframe checkpoint;
# Keeps the two partitions honest: without a ref2va row above, a ref2va prequant pick is refused rather than
- # served the keyframe checkpoint. Equal to H3_TASK_REFERENCES; the literal avoids importing the H3 helper module
- # into the registry.
+ # served the keyframe checkpoint. Equal to H3_TASK_REFERENCES; the literal avoids importing the H3 helper
+ # module into the registry.
prequant_partition_tasks = ("ref2va",),
# Both schemes are ~20.3 GB resident against the 66.3 GB dense denoiser; see the field.
prequant_resident_gb = 20.3,
@@ -242,7 +234,6 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# pre-cast Gemma3-12B TE (fp32 ~49 GB on the hub, pre-cast ~13.2 GB): the biggest download win
te_prequant_repos = (("fp8", "text_encoder", "unsloth/LTX-2-FP8"),),
),
- # Wan2.2-TI2V-5B: ~5B single-stream DiT (UMT5 encoder), no audio
# Wan2.2-TI2V-5B (diffusers >= 0.35, verified on 0.39): ~5B single-stream DiT (UMT5 encoder), no audio. Its VAE's
# temporal compression 4 gives valid frame counts 4k+1. Defaults 50 steps / CFG 5.
VideoFamily(
@@ -293,7 +284,6 @@ _FAMILIES: tuple[VideoFamily, ...] = (
resolution_multiple = 16,
# 480p + 720p presets. A14B's VAE is 8x so multiple 16 renders 720 exactly (TI2V-5B's 16x VAE floors it to 704).
resolution_presets = ((1280, 720), (832, 480), (480, 832), (720, 1280)),
- # bf16-RESIDENT: each expert ships FP32, so ~28.6 bf16 each and ~57.2 for BOTH
# bf16-RESIDENT. Each expert ships FP32 (57.15 GB = 14.3B x 4), so ~28.6 bf16 each and ~57.2 for BOTH, not the
# 114.3 fp32 sum. UMT5 TE bf16 (11.4); VAE fp32 (0.5).
bf16_components_gb = (57.2, 11.4, 0.5),
@@ -553,20 +543,17 @@ def validate_video_request_shape(
) -> None:
"""Raise ``ValueError`` when a request asks for a shape ``fam`` does not support.
- The generate route calls this at the API boundary so HTTP enforces exactly the
- rules the Desktop interface offers: its resolution select lists only
- ``resolution_presets`` and its duration select only lattice frame counts, while
- the API took anything inside the coarse request bounds and then SNAPPED it. The
- snap is silent and floors, so a 256x256 request survived untouched (256 divides
- both 16 and 32) and denoised at a size no checkpoint was ever trained for.
+ The generate route calls this at the API boundary so HTTP enforces exactly the rules the Desktop
+ interface offers: its resolution select lists only ``resolution_presets`` and its duration
+ select only lattice frame counts, while the API took anything inside the coarse request bounds
+ and then SNAPPED it. The snap is silent and floors, so a 256x256 request survived untouched and
+ denoised at a size no checkpoint was ever trained for.
This is a separate, explicit check rather than a change to ``snap_video_size`` /
- ``snap_num_frames``, which internal callers still need. It stays silent for
- anything it cannot judge -- a family that declares no presets keeps the old SIZE
- snapping, since there is no table to judge a size against -- and ``None`` means
- "use the family default", which is valid by construction. The frame lattice is
- deliberately NOT part of that escape hatch: every family declares a ``frame_step``
- whether or not it declares presets, so an off-lattice count is always refused.
+ ``snap_num_frames``, which internal callers still need. It stays silent for anything it cannot
+ judge (a family that declares no presets keeps the old SIZE snapping), and ``None`` means "use
+ the family default". The frame lattice is deliberately NOT part of that escape hatch: every
+ family declares a ``frame_step``, so an off-lattice count is always refused.
"""
# Normalised to int pairs so membership holds however a family spelled its presets (the status payload hands them
# out as lists, and a round-trip through it must not silently stop matching).
diff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.py
index f5c39afce75..d6fe6d800e3 100644
--- a/studio/backend/core/inference/video_gallery.py
+++ b/studio/backend/core/inference/video_gallery.py
@@ -284,7 +284,6 @@ def _transcode_webm(path: Path, dest: Path) -> None:
out_v.width = in_v.codec_context.width
out_v.height = in_v.codec_context.height
out_v.pix_fmt = "yuv420p"
- # VP9's default "good" profile is slow; cpu-used 8 + row-mt is much faster at a small quality cost
# Realtime settings: VP9's default "good" profile is slow; cpu-used 8 + row-mt is much faster at a small
# quality cost.
out_v.options = {"deadline": "realtime", "cpu-used": "8", "row-mt": "1"}
@@ -343,7 +342,6 @@ def _transcode_webm(path: Path, dest: Path) -> None:
raise RuntimeError(f"WebM export failed (libvpx-vp9 unavailable?): {exc}") from exc
-# a GIF export holds every kept frame in memory
# Ceilings for a GIF export, which must hold every kept frame in memory before encoding. 720 px and 300 frames (25s at
# the 12 fps target) bound that at roughly 150 MB for the widest clip a generate request allows.
_GIF_MAX_EDGE = 720
@@ -410,9 +408,8 @@ def _sidecar_path(video_id: str) -> Path:
return gallery_dir() / f"{video_id}.json"
-# key-presence only: delete()/clear() own a pair only when its sidecar has all of these
-# Sidecar keys every genuine Unsloth record carries. delete()/clear() own a pair only when its sidecar has all of these,
-# so a hand-dropped MP4 with a partial sidecar is neither counted as ours nor destroyed. Key-presence only.
+# Sidecar keys every genuine Unsloth record carries. delete()/clear() own a pair only when its sidecar has all of
+# these, so a hand-dropped MP4 with a partial sidecar is neither counted as ours nor destroyed. Key-presence only.
_REQUIRED_META = (
"prompt",
"width",
@@ -436,7 +433,6 @@ def _read_meta(sidecar: Path) -> Optional[dict[str, Any]]:
meta = json.loads(raw)
except (ValueError, TypeError):
return None
- # a parseable dict is not enough: delete()/clear() must never destroy a clip the gallery never surfaced
# A parseable dict is not enough: a foreign ("{}") or different-schema sidecar lacks these keys, and
# delete()/clear() must never destroy a clip the gallery never surfaced.
if not isinstance(meta, dict) or any(k not in meta for k in _REQUIRED_META):
@@ -496,13 +492,10 @@ def list_videos(
except OSError:
return []
flags = gallery_flags.read(gallery_dir())
- # both run on file stems BEFORE any sidecar is read
- # Shelf split and pin sort run on file stems, BEFORE any sidecar is read, so they cost one dict lookup per file and
- # leave the early break below intact.
+ # Shelf split and pin sort run on file stems, BEFORE any sidecar is read, so they cost one dict lookup per file
+ # and leave the early break below intact.
paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
paths.sort(key = lambda p: (gallery_flags.pin_rank(flags, p.stem), _mtime(p)), reverse = True)
- # page over READABLE records: filtering an orphan MP4 out of an already-sliced window would drop valid videos and
- # make has_more wrong
# Page over READABLE records, not raw files: filtering an orphan MP4 out of an already-sliced window would drop
# valid videos and make has_more wrong.
want = None if limit is None else offset + limit
@@ -546,9 +539,8 @@ def delete(video_id: str) -> bool:
path = video_path(video_id)
if path is None:
return False
- # a foreign/orphan MP4 is invisible to list_videos, so a guessed id must not destroy it
- # Only delete a pair we own (a readable sidecar); a foreign/orphan MP4 is invisible to list_videos, so a guessed id
- # must not destroy it.
+ # Only delete a pair we own (a readable sidecar); a foreign/orphan MP4 is invisible to list_videos, so a guessed
+ # id must not destroy it.
if _read_meta(_sidecar_path(video_id)) is None:
return False
# delete the MP4 FIRST: sidecar-first plus a failed unlink leaves a clip that vanished from the gallery with no
@@ -606,7 +598,6 @@ def clear(include_archived: bool = False, *, return_ids: bool = False) -> int |
_sidecar_path(path.stem).unlink()
except OSError:
pass
- # once every clip we own is gone an unreadable store protects nothing
# Nothing left for an unreadable store to protect once every clip we own is gone, so this is where the escape
# hatch escapes: replace it, or every later default clear still refuses.
if include_archived and not gallery_flags.is_trusted(directory):
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index 0671b110881..705cb9f6903 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -47,8 +47,6 @@ _EXTRAS_VIDEO_VAE = "vae/ltx-2.3-22b-{variant}_video_vae.safetensors"
_EXTRAS_AUDIO_VAE = "vae/ltx-2.3-22b-{variant}_audio_vae.safetensors"
-# ── configs + rename tables, verbatim from scripts/convert_ltx2_to_diffusers.py ──
-
# from_single_file config overrides on top of the base 2.0 transformer config.
LTX_2_3_TRANSFORMER_CONFIG_OVERRIDES: dict[str, Any] = {
"gated_attn": True,
@@ -250,9 +248,6 @@ _VOCODER_CONFIG: dict[str, Any] = {
_DIT_PREFIX = "model.diffusion_model."
-# ── checkpoint inspection ────────────────────────────────────────────────────
-
-
def read_checkpoint_header(checkpoint_path: Path | str) -> dict[str, tuple[int, ...]]:
"""Tensor name -> shape from the checkpoint HEADER only (no weight data). GGUF shapes come back
in GGML (reversed) order, so callers should membership-test, not assume a dimension position."""
@@ -285,9 +280,6 @@ def is_ltx23_checkpoint(checkpoint_path: Path | str) -> bool:
return False
-# ── state-dict plumbing ──────────────────────────────────────────────────────
-
-
def _apply_rename(state: dict[str, Any], rename: dict[str, str]) -> dict[str, Any]:
out: dict[str, Any] = {}
for key, value in state.items():
@@ -433,9 +425,6 @@ def ltx23_verbatim_sigmas(pipe: Any) -> Any:
return _ctx()
-# ── component builders ───────────────────────────────────────────────────────
-
-
def _build_from_config(
model_cls: Any,
config: dict[str, Any],
@@ -577,9 +566,6 @@ def load_ltx23_audio_vae_and_vocoder(
return audio_vae, vocoder.to(torch_dtype)
-# ── pipeline assembly ────────────────────────────────────────────────────────
-
-
def load_ltx23_pipeline(
checkpoint_path: Path | str,
*,
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index b86d7b5f33f..e15e54d275d 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -23,9 +23,8 @@ H3_GGUF_REPO = "unsloth/MiniMax-H3-GGUF"
# using them through h3_component_source below, because the HF cache is keyed by repo id and repointing alone
# re-downloads ~6 GB.
H3_COMPONENT_REPO = "unsloth/MiniMax-H3-GGUF"
-# only for reusing an existing cache entry; the pairing itself lives in diffusion_families' _SD_CPP_LEGACY_SOURCES
-# Where the component files came from originally. Only for reusing an existing cache entry: a fresh install never reads
-# it. The pairing itself lives in diffusion_families' _SD_CPP_LEGACY_SOURCES, which owns this decision for every
+# Where the component files came from originally. Only for reusing an existing cache entry: a fresh install never
+# reads it. The pairing itself lives in diffusion_families' _SD_CPP_LEGACY_SOURCES, which owns this decision for every
# mirrored asset; this name is what the delete-cached claims read, and a test pins the two together.
H3_LEGACY_COMPONENT_REPO = "Comfy-Org/MiniMax-H3"
H3_VIDEO_VAE = "vae/minimax_h3_video_vae_fp16.safetensors"
@@ -40,19 +39,16 @@ H3_DIFFUSERS_VRAM_BASE_GB = 68.5
H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME = 0.08
# The terms H3_DIFFUSERS_VRAM_BASE_GB is built from, so a load that shrinks one of the big components can rebuild the
-# floor from what it holds instead of the released sizes. With everything under enable_auto_cpu_offload the base is the
-# LARGEST SINGLE RESIDENT COMPONENT plus runtime overhead, not the sum: at any instant one component is on the device
-# and the rest are parked on the host. That is exactly why seeding a 20 GB pre-quantized denoiser moved this number by
-# nothing -- the 66.7 GB conditioner was already the larger of the two and took over as the maximum. Both have to shrink
-# before the floor does. ONE case breaks the max, and it is the case a pre-quantized denoiser creates. A torchao module
-# does not survive being moved mid-block, so _load_h3_modular_pipeline PINS it to the device and takes it out of the
-# offload rotation (see pin_prequantized_module). It is then resident for the whole generation and the floor becomes
-# additive: denoiser + whichever offloaded component is largest. Measured at 960x544x124 with the int8 denoiser pinned,
-# torch.cuda.max_memory_allocated: bfloat16 conditioner 94.62 GB = 20.3 + 66.7 + 5.18 activations + 2.44 int8
-# conditioner 55.20 GB = 20.3 + 27.1 + 5.18 activations + 2.58 so 2.6 covers the pinned overhead on the conservative
-# side of both. Note what the first row says about the shipped constant: a pinned denoiser and a dense conditioner need
-# ~95 GB, and the flat 68.5 under-states that by 26 GB. Rebuilding the floor from the resident components fixes that
-# under-estimate in the same stroke as crediting the saving.
+# floor from what it holds instead of the released sizes. With everything under enable_auto_cpu_offload the base is
+# the LARGEST SINGLE RESIDENT COMPONENT plus runtime overhead, not the sum: at any instant one component is on the
+# device and the rest are parked on the host. That is why seeding a 20 GB pre-quantized denoiser moved this number by
+# nothing -- the 66.7 GB conditioner was already the larger of the two. ONE case breaks the max, and it is the case a
+# pre-quantized denoiser creates: a torchao module does not survive being moved mid-block, so
+# _load_h3_modular_pipeline PINS it to the device and takes it out of the offload rotation, after which the floor
+# becomes additive (denoiser + whichever offloaded component is largest). Measured at 960x544x124 with the int8
+# denoiser pinned: bf16 conditioner 94.62 GB, int8 conditioner 55.20 GB, so 2.6 covers the pinned overhead on the
+# conservative side of both. Note what the first figure says about the shipped constant: a pinned denoiser and a dense
+# conditioner need ~95 GB, and the flat 68.5 under-states that by 26 GB.
H3_DIFFUSERS_VRAM_OVERHEAD_GB = 1.8
H3_DIFFUSERS_VRAM_PINNED_OVERHEAD_GB = 2.6
H3_TEXT_ENCODER_BF16_GB = 66.7
@@ -119,7 +115,6 @@ def estimate_h3_diffusers_vram_gb(
return base + (H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames)
-# both are the shipped values, unchanged: that tier is only reachable on a >= 132 GB device
# The VRAM at which the offload tier changes, and the host floor of the tier above it. Both are the shipped values,
# unchanged: that tier is only reachable on a >= 132 GB device, where the component sizes below are not what stands
# between a load and a generation, and there is no measurement here to justify moving it.
@@ -158,9 +153,8 @@ def estimate_h3_diffusers_host_ram_gb(
return text_encoder + transformer + H3_VAE_RESIDENT_GB + H3_DIFFUSERS_HOST_RAM_HEADROOM_GB
-# torch.autocast casts these module types' weight and bias to the autocast dtype on entry
-# torch.autocast casts the weight and bias of these module types to the autocast dtype on entry. Norms sit on autocast's
-# float32 promote list and bare parameters are read directly, so both must keep their source precision.
+# torch.autocast casts the weight and bias of these module types to the autocast dtype on entry. Norms sit on
+# autocast's float32 promote list and bare parameters are read directly, so both must keep their source precision.
_AUTOCAST_WEIGHT_MODULE_NAMES = ("Linear", "Conv1d", "Conv2d", "Conv3d")
@@ -178,24 +172,24 @@ def _module_bytes(module: Any) -> int:
def trim_h3_video_vae(vae: Any, *, workflow: str) -> dict[str, int]:
"""Drop what the H3 video VAE cannot use and pre-cast what autocast casts anyway.
- Two thirds of an H3 render's peak is not activations. Measured at 640x384 across 124
- frames, a 20.25 GB int8 denoiser peaks at 36.96 GB, and the gap is almost all weights:
- the video VAE alone is 10.42 GB because diffusers pins it to float32, and a further
- 4.91 GB is autocast's own float16 copy of those weights.
+ Two thirds of an H3 render's peak is not activations. Measured at 640x384 across 124 frames, a
+ 20.25 GB int8 denoiser peaks at 36.96 GB, and the gap is almost all weights: the video VAE alone
+ is 10.42 GB because diffusers pins it to float32, and a further 4.91 GB is autocast's own
+ float16 copy of those weights.
- ``MiniMaxH3VideoDecodeStep`` wraps ``vae.decode`` in ``torch.autocast(float16)``. Autocast
- casts every Linear and Conv weight it meets and caches the copy for the lifetime of the
- region, so the float32 original and its float16 twin are both resident through the whole
- decode. Storing those weights as float16 up front makes the cast a no-op and removes both:
- ``x.to(float16).to(float16)`` is ``x.to(float16)``, so the arithmetic is unchanged rather
- than merely close. The audio VAE decode is NOT under autocast, so it is left alone.
+ ``MiniMaxH3VideoDecodeStep`` wraps ``vae.decode`` in ``torch.autocast(float16)``. Autocast casts
+ every Linear and Conv weight it meets and caches the copy for the lifetime of the region, so the
+ float32 original and its float16 twin are both resident through the whole decode. Storing those
+ weights as float16 up front makes the cast a no-op and removes both:
+ ``x.to(float16).to(float16)`` is ``x.to(float16)``, so the arithmetic is unchanged rather than
+ merely close. The audio VAE decode is NOT under autocast, so it is left alone.
- The encoder half goes only for a workflow that never encodes. ``t2va`` starts from noise,
- so ``vae.encoder`` and ``vae.quant_conv`` are dead weight; a future image-conditioned
- workflow needs them, hence the explicit check rather than an unconditional drop.
+ The encoder half goes only for a workflow that never encodes: ``t2va`` starts from noise, so
+ ``vae.encoder`` and ``vae.quant_conv`` are dead weight, while a future image-conditioned
+ workflow needs them.
- Returns a byte report for the caller to log. Never raises: a diffusers release that
- renames these attributes should cost the saving, not the render.
+ Returns a byte report for the caller to log. Never raises: a diffusers release that renames
+ these attributes should cost the saving, not the render.
"""
import torch
@@ -232,9 +226,7 @@ def trim_h3_video_vae(vae: Any, *, workflow: str) -> dict[str, int]:
return report
-# ── canvas geometry ────────────────────────────────────────────────────────── MiniMax-H3's upstream canvas rule,
-# shared by both engines.
-# ── canvas geometry ──────────────────────────────────────────────────────────
+# MiniMax-H3's upstream canvas rule, shared by both engines.
H3_CANVAS_SHORT_EDGE = 768
H3_CANVAS_MAX_PIXELS = 768 * 1344
H3_CANVAS_MULTIPLE = 32
@@ -294,9 +286,7 @@ def fit_h3_keyframe(image: Any, width: int, height: int, *, anchor: str) -> Any:
return image.resize(target, Image.LANCZOS, box = (left, top, left + crop_w, top + crop_h))
-# ── omni references (Ref2VA) ───────────────────────────────────────────────── Ref2VA uses a separate transformer
-# partition selected at load time.
-# ── omni references (Ref2VA) ─────────────────────────────────────────────────
+# Ref2VA uses a separate transformer partition selected at load time.
H3_TASK_KEYFRAMES = "fl2va"
H3_TASK_REFERENCES = "ref2va"
@@ -307,11 +297,9 @@ H3_MAX_REFERENCES = 12
# A reference video's trained window, in seconds.
H3_REF_VIDEO_MIN_SECONDS = 2.0
H3_REF_VIDEO_MAX_SECONDS = 15.0
-# a container reports its longest track, so a file whose audio outruns its video reads as longer than it can show
# How far a trim may reach past the video track before it is refused. A container reports its longest track, so a file
# whose audio outruns its video reads as longer than it can show, and a client picking an interval from that duration
-# (HTMLMediaElement.duration, in Unsloth's case) asks for slightly more video than exists. Within this margin the last
-# frame is held instead.
+# asks for slightly more video than exists. Within this margin the last frame is held instead.
H3_REF_TRIM_COVERAGE_SLACK_SECONDS = 0.5
H3_FPS = 24
@@ -1054,28 +1042,26 @@ def h3_download_error(repo_id: str, filename: str, exc: Exception) -> Exception:
def h3_component_source(*files: str) -> str:
- """The repo to fetch the shared VAEs from: our mirror, or the repack it was mirrored from
- when an existing install already holds those exact bytes under the old id.
+ """The repo to fetch the shared VAEs from: our mirror, or the repack it was mirrored from when an
+ existing install already holds those exact bytes under the old id.
The HF cache is keyed by repo id, so moving the id alone would re-download ~5.8 GB on upgrade
- and fail outright offline. The mirror is byte identical (same sha256), so reusing the old
- entry loads the same weights. Fresh installs never take this branch.
+ and fail outright offline. The mirror is byte identical (same sha256), so reusing the old entry
+ loads the same weights. Fresh installs never take this branch.
``prefer_cached_legacy_source`` rather than a probe of our own: it already owns this exact
- mirror-to-repack decision for every other sd.cpp asset, and it counts BOTH cache roots.
- That second part is the reason it has to be this one. The native fetch below passes
- ``reuse_other_cache_root``, so a repack left behind by a cache-folder change is still
- perfectly usable -- but only the OLD repo id can reach it, and a live-root-only probe would
- call it absent and re-pull ~5.8 GB (offline, fail).
+ mirror-to-repack decision for every other sd.cpp asset, and it counts BOTH cache roots. That
+ second part is why it has to be this one -- the native fetch below passes
+ ``reuse_other_cache_root``, so a repack left behind by a cache-folder change is still usable,
+ but only the OLD repo id can reach it and a live-root-only probe would call it absent and
+ re-pull ~5.8 GB.
Answered for the files GIVEN, and the native loop asks one at a time because that is how it
- downloads them. A pre-move pull interrupted between the two VAEs leaves only one under the old
- id; asking for the pair calls the old id useless and re-pulls the 5.2 GB already on disk,
- while asking per file reuses it and takes only the other from the mirror. With no argument it
- answers for the pair, for callers describing the pair rather than fetching it.
+ downloads them: a pre-move pull interrupted between the two VAEs leaves only one under the old
+ id, and asking per file reuses it. With no argument it answers for the pair.
- PURE: table lookup plus a local stat, no network, so a download plan and the fetch that
- follows it agree on the source.
+ PURE: table lookup plus a local stat, no network, so a download plan and the fetch that follows
+ it agree on the source.
"""
wanted = files or (H3_VIDEO_VAE, H3_AUDIO_VAE)
try:
diff --git a/studio/backend/core/inference/video_minimax_h3_adaln.py b/studio/backend/core/inference/video_minimax_h3_adaln.py
index 5f9c889603d..b631067fd35 100644
--- a/studio/backend/core/inference/video_minimax_h3_adaln.py
+++ b/studio/backend/core/inference/video_minimax_h3_adaln.py
@@ -42,7 +42,6 @@ from __future__ import annotations
import types
from typing import Any, Optional
-# video, text and audio rows each get a modulation row
# Video, text and audio rows each get their own modulation row, so one projection emits three blocks of six chunks.
# Mirrors diffusers' MINIMAX_H3_MODALITY_NUM; hardcoded rather than imported so this module stays importable (and
# unit-testable) without diffusers.
@@ -53,7 +52,6 @@ ADALN_FORM_KEY = "adaln_form"
ADALN_CURVE_FORM = "curve"
CURVE_DIM_KEY = "curve_dim"
CURVE_GRID_KEY = "curve_grid"
-# dtype of the block stack the modulation feeds
# The dtype of the block stack the modulation feeds, recorded by the builder. See `_curve_modulation_forward` for why
# the chunks have to be cast to it.
ADALN_OUT_DTYPE_KEY = "adaln_out_dtype"
@@ -208,12 +206,10 @@ def apply_h3_adaln_curve(
)
def _reshape(linear: Any, where: str) -> Any:
- # rebuild rather than resize: a plain float32 Linear (as the hosted checkpoints store it) that load_state_dict
- # overwrites via assign=True
- # Rebuild rather than resize: the replacement is a plain float32 Linear (the hosted checkpoints store the pruned
- # adaLN in float32) whose weights load_state_dict then overwrites via assign=True. Built on the real device,
- # never meta, so the module is well-formed even if the checkpoint were to omit it and strict=True caught that
- # instead.
+ # Rebuild rather than resize: the replacement is a plain float32 Linear (the hosted checkpoints store the
+ # pruned adaLN in float32) whose weights load_state_dict then overwrites via assign=True. Built on the real
+ # device, never meta, so the module is well-formed even if the checkpoint were to omit it and strict=True
+ # caught that instead.
if not isinstance(linear, nn.Linear):
raise ValueError(f"MiniMax-H3 curve conversion expected a Linear at {where}.")
import torch
@@ -229,11 +225,9 @@ def apply_h3_adaln_curve(
if proj is None:
raise ValueError(f"MiniMax-H3 curve conversion: block {index} has no `adaln_proj`.")
proj.linear = _reshape(proj.linear, f"transformer_blocks.{index}.adaln_proj.linear")
- # plain attribute, not a buffer: it must stay out of the state dict and out of `.to(device)`
- # Plain attribute, not a buffer: it must not reach the state dict, and `.to(device)` on the module must not try
- # to move it.
+ # Plain attribute, not a buffer: it must not reach the state dict, and `.to(device)` on the module must not
+ # try to move it.
proj._unsloth_adaln_out_dtype = out_dtype
- # bind per instance: the dense class is shared with dense loads in the same process
# Bind the SiLU-free forward per instance: the dense class is shared with dense loads in the same process, so
# patching the CLASS would corrupt them.
proj.forward = types.MethodType(_curve_modulation_forward, proj)
diff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.py
index 7aa4f993034..f5d9ced1268 100644
--- a/studio/backend/core/inference/video_minimax_h3_te.py
+++ b/studio/backend/core/inference/video_minimax_h3_te.py
@@ -57,7 +57,6 @@ from .diffusion_convrot import ( # noqa: F401 (re-export: callers and tests na
rotate_convrot_activation,
)
-# no longer H3_COMPONENT_REPO: the VAEs moved to the GGUF mirror and the conditioner did not
# The repo the prequantized denoisers already come from, so this adds no new dependency. It is no longer
# H3_COMPONENT_REPO: the VAEs moved to the GGUF mirror and the conditioner did not, so the two are now separate repos
# and aliasing them would send this file to the wrong one.
@@ -67,8 +66,7 @@ H3_TE_QUANT_REPO = "unsloth/MiniMax-H3-FP8"
# and is read through h3_te_quant_source below.
H3_LEGACY_TE_QUANT_REPO = "Comfy-Org/MiniMax-H3"
-# nvfp4 is deliberately absent: an AWQ NVFP4 layout with two levels of scale
-# Hosted quantized conditioners, by ``text_encoder_quant`` scheme. nvfp4
+# Hosted quantized conditioners, by ``text_encoder_quant`` scheme. nvfp4
# (``qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors``, 14.61 GiB) is deliberately absent: it is an AWQ NVFP4 layout with
# two levels of scale and a per-tensor global scale, a different loader and a different kernel, and shipping it needs
# its own numerical verification. The table is the one place to add it.
@@ -76,8 +74,7 @@ H3_TE_QUANT_FILES: dict[str, str] = {
"int8": "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors",
}
-# the released conditioner is a 66.7 GB dense bfloat16 Qwen3-VL of 64 layers and H3 reads hidden_states[50]
-# The scheme an UNSET ``text_encoder_quant`` resolves to on a device that supports it. The released conditioner is a
+# The scheme an UNSET ``text_encoder_quant`` resolves to on a device that supports it. The released conditioner is a
# 66.7 GB dense bfloat16 Qwen3-VL of 64 decoder layers and H3 reads ``hidden_states[50]``; transformers has no early
# exit, so the default runs all 64 layers and streams 66.7 GB across the CPU-offload boundary every generation. The
# hosted artifact is 27.1 GB over 50 layers with the same read, which is why it is the default rather than an opt-in.
@@ -85,19 +82,15 @@ H3_TE_QUANT_FILES: dict[str, str] = {
# is bytes moved and layers executed, not faster math.
H3_TE_QUANT_DEFAULT = "int8"
-# Resident decimal GB, measured from the safetensors headers (2026-08-09): bf16 51.51 GB, int8_convrot 27.14 GB.
# Resident bytes of each conditioner, decimal GB, measured from the safetensors headers on the Hub (2026-08-09) as the
-# end of the last tensor's data. The quantized load is storage-faithful -- INT8 stays INT8, the per-output-channel
-# scales stay float32, the vision tower and the embedding table stay bfloat16 -- so the file size IS the resident size,
-# unlike a cast-on-load path whose peak is the dense encoder. qwen3vl_32b_minimax_h3_bf16.safetensors 51.51 GB (47.97
-# GiB) qwen3vl_32b_minimax_h3_int8_convrot.safetensors 27.14 GB (25.28 GiB) The bfloat16 number here is the HOSTED
-# 50-layer file. The budget default elsewhere is the RELEASED 64-layer encoder (66.7 GB), which is what a load without
-# this path materialises.
+# end of the last tensor's data: bf16 51.51 GB, int8_convrot 27.14 GB. The quantized load is storage-faithful -- INT8
+# stays INT8, the per-output-channel scales stay float32, the vision tower and the embedding table stay bfloat16 -- so
+# the file size IS the resident size, unlike a cast-on-load path whose peak is the dense encoder. The bfloat16 number
+# here is the HOSTED 50-layer file; the budget default elsewhere is the RELEASED 64-layer encoder (66.7 GB).
H3_TE_QUANT_RESIDENT_GB: dict[str, float] = {
"int8": 27.2,
}
-# must stay equal to MiniMaxH3ModularPipeline.text_encoder_layer
# Which Qwen3-VL hidden state conditions the transformer. Must stay equal to
# ``MiniMaxH3ModularPipeline.text_encoder_layer``; ``h3_te_layer_budget`` below is the only reader.
H3_TE_READ_LAYER = 50
@@ -106,7 +99,6 @@ H3_TE_READ_LAYER = 50
# rather than assumed, so a re-upload under a different group is refused instead of silently decoding to noise.
H3_TE_CONVROT_GROUP = 256
-# any other value in a tensor's `comfy_quant` blob is a format this code has not been verified against
# The quantization format the loader below implements. Any other value in a tensor's ``comfy_quant`` blob is a format
# this code has not been verified against, and is refused.
_H3_TE_EXPECTED_QUANT = {"format": "int8_tensorwise", "convrot": True}
@@ -167,18 +159,15 @@ def h3_te_resident_gb(scheme: Optional[str], *, bf16_gb: float) -> float:
# orthogonal, so H @ H == I exactly).
-# ── ConvRot INT8 ────────────────────────────────────────────────────────────── W_rot = W @ H_block^T offline, x_rot =
-# x @ H_block online, and H is a NORMALIZED REGULAR Hadamard, which is symmetric and orthogonal, so H @ H == I exactly
-# and x_rot @ W_rot^T == x @ H @ H @ W^T == x @ W^T. The rotation is what lets INT8 survive Qwen3-VL's per-channel
-# activation outliers; dequantizing WITHOUT it is not an approximation, it is noise (measured against the hosted
-# bfloat16 file for one projection: 0.9% relative error with the rotation, 137% without). This mirrors comfy-kitchen's
-# ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight`` exactly, in a few lines of torch, rather than taking
-# a dependency on a wheel Unsloth does not ship. ``build_convrot_hadamard`` and ``rotate_convrot_activation`` are
-# imported at the top of this module from ``diffusion_convrot``, where they now live. The DENOISER runs the same ConvRot
-# on its own hosted INT8 checkpoint, and the two rotations have to agree with the same comfy-kitchen definition down to
-# the normalizer -- two copies of a matrix nobody re-derives at review time is exactly how they would stop agreeing.
-# Both stay importable from here.
-# ── ConvRot INT8 ──────────────────────────────────────────────────────────────
+# ConvRot INT8. W_rot = W @ H_block^T offline, x_rot = x @ H_block online, and H is a NORMALIZED REGULAR Hadamard,
+# which is symmetric and orthogonal, so H @ H == I exactly and x_rot @ W_rot^T == x @ W^T. The rotation is what lets
+# INT8 survive Qwen3-VL's per-channel activation outliers; dequantizing WITHOUT it is not an approximation, it is
+# noise (measured against the hosted bfloat16 file for one projection: 0.9% relative error with the rotation, 137%
+# without). This mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight`` exactly
+# rather than taking a dependency on a wheel Unsloth does not ship. ``build_convrot_hadamard`` and
+# ``rotate_convrot_activation`` live in ``diffusion_convrot`` and are imported at the top of this module: the DENOISER
+# runs the same ConvRot on its own hosted INT8 checkpoint, and two copies of a matrix nobody re-derives at review time
+# is exactly how they would stop agreeing. Both stay importable from here.
@lru_cache(maxsize = None)
def _int8_convrot_linear_class() -> Any:
"""The ConvRot INT8 ``nn.Linear`` stand-in, built lazily so importing this module never imports
@@ -273,14 +262,9 @@ def _terminator_layer_class() -> Any:
return H3TextEncoderTerminatorLayer
-# the hosted checkpoint uses the ComfyUI flattening of the Qwen3-VL tree while transformers nests under `model.`;
-
-
-# ── name mapping ────────────────────────────────────────────────────────────── The hosted checkpoint uses the ComfyUI
-# flattening of the Qwen3-VL tree; transformers nests the language model and the vision tower under ``model.``. Verified
-# exhaustive on 2026-08-09: all 902 hosted names map into ``MiniMaxAI/MiniMax-H3``
-# ``text_encoder/model.safetensors.index.json``, with nothing left over on this side.
-# ── name mapping ──────────────────────────────────────────────────────────────
+# Name mapping. The hosted checkpoint uses the ComfyUI flattening of the Qwen3-VL tree; transformers nests the
+# language model and the vision tower under ``model.``. Verified exhaustive on 2026-08-09: all 902 hosted names map
+# into ``MiniMaxAI/MiniMax-H3`` ``text_encoder/model.safetensors.index.json``, with nothing left over on this side.
def h3_te_remap_key(key: str) -> str:
"""A hosted checkpoint tensor name in transformers' ``Qwen3VLForConditionalGeneration`` naming."""
if key.startswith("visual."):
@@ -363,7 +347,6 @@ def load_h3_quantized_text_encoder(
filename,
hf_token,
cache_dir = cache_dir,
- # resolve through whichever root holds it, exactly as the stager did
# Resolve the artifact through whichever root holds it, exactly as the stager that cleared this load did;
# pinned to cache_dir alone a moved cache folder re-pulls 27 GB.
reuse_other_cache_root = True,
@@ -389,23 +372,20 @@ def load_h3_quantized_text_encoder(
f"{base} text_encoder has {released_layers} layers; MiniMax-H3 reads "
f"hidden_states[{H3_TE_READ_LAYER}] and needs more than that"
)
- # one slot past the read layer, so the read lands on the raw state rather than the post-norm one
# See the module docstring: one slot past the read layer, so the read lands on the raw state rather than the
# post-norm one.
text_config.num_hidden_layers = H3_TE_READ_LAYER + 1
- # Include_buffers=False: PARAMETERS go to meta and are replaced wholesale by assign=True below
- # include_buffers=False (it is also accelerate's default, but the whole load turns on it): PARAMETERS go to meta
- # and are replaced wholesale by ``assign=True`` below, while BUFFERS -- the rotary inverse frequencies, which no
- # state dict carries because they are non-persistent -- are built for real on CPU. They are a few KB. Putting
- # them on meta instead would leave the encoder with meta tensors after the load and force a dense CPU rebuild,
- # i.e. the 51 GB allocation this path exists to avoid.
+ # include_buffers=False (it is also accelerate's default, but the whole load turns on it): PARAMETERS go to
+ # meta and are replaced wholesale by ``assign=True`` below, while BUFFERS -- the rotary inverse frequencies,
+ # which no state dict carries because they are non-persistent -- are built for real on CPU. They are a few KB.
+ # Putting them on meta instead would leave the encoder with meta tensors after the load and force a dense CPU
+ # rebuild, i.e. the 51 GB allocation this path exists to avoid.
with init_empty_weights(include_buffers = False):
encoder = transformers.Qwen3VLForConditionalGeneration(config)
language_model = encoder.model.language_model
language_model.layers[H3_TE_READ_LAYER] = _terminator_layer_class()()
- # neither can reach the conditioning: `norm` is only applied to the terminator's output
# Neither is in the artifact and neither can reach the conditioning: ``norm`` is only ever applied to the
# terminator's output, and the head is never called (the pipeline invokes ``text_encoder.model``, not
# ``text_encoder``). Dropping the head alone saves 1.56 GB.
@@ -485,10 +465,9 @@ def load_h3_quantized_text_encoder(
f"path budgets for"
)
encoder.load_state_dict(state_dict, strict = True, assign = True)
- # a dense CPU rebuild is NOT an acceptable repair here (it is the 51 GB allocation this path avoids)
- # Nothing may be left on meta. A dense CPU rebuild is NOT an acceptable repair here (it is the 51 GB allocation
- # this path exists to avoid), so a leftover is a refusal and the caller falls back to the released encoder,
- # which at least loads correctly.
+ # Nothing may be left on meta. A dense CPU rebuild is NOT an acceptable repair here (it is the 51 GB
+ # allocation this path exists to avoid), so a leftover is a refusal and the caller falls back to the released
+ # encoder, which at least loads correctly.
stranded = _meta_tensor_names(encoder)
if stranded:
raise ValueError(
diff --git a/studio/backend/core/inference/web_access_policy.py b/studio/backend/core/inference/web_access_policy.py
index 0b90e09d7b9..b610eeedb9f 100644
--- a/studio/backend/core/inference/web_access_policy.py
+++ b/studio/backend/core/inference/web_access_policy.py
@@ -175,11 +175,10 @@ def scope_search_query(query: str, policy: dict[str, Any] | None) -> str:
allowed = normalize_website_policy(policy)["allowedDomains"]
if not allowed:
return query
- # cap the site: filter and rotate the window by query, else domains past the cap are permanently undiscoverable
- # Cap the site: filter (search engines limit OR operators) instead of dropping scoping for large allow lists, which
- # returned unrelated results that all got filtered out. Rotate the window by query so every allowed domain stays
- # reachable across a multi-step run (a fixed head made domains past the cap permanently undiscoverable) and one
- # query always scopes the same way.
+ # Cap the site: filter (search engines limit OR operators) instead of dropping scoping for large allow lists,
+ # which returned unrelated results that all got filtered out. Rotate the window by query so every allowed domain
+ # stays reachable across a multi-step run (a fixed head made domains past the cap permanently undiscoverable) and
+ # one query always scopes the same way.
window = allowed
if len(allowed) > _SITE_FILTER_LIMIT:
offset = zlib.crc32(query.encode("utf-8")) % len(allowed)
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 702aca1bd87..3c1f42a635a 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -112,9 +112,7 @@ def _activate_transformers_version(model_name: str, hf_token: str | None = None)
def _decode_image(image_base64: str):
- """Decode base64 string to PIL.Image."""
from PIL import Image
-
image_data = base64.b64decode(image_base64)
return Image.open(BytesIO(image_data))
@@ -169,7 +167,6 @@ def _apply_worker_hf_token_environment(config: dict) -> None:
def _build_model_config(config: dict):
- """Build a ModelConfig from the config dict."""
from utils.models import ModelConfig
model_name = config["model_name"]
@@ -393,7 +390,6 @@ def _worker_reclaimable_gpu_gb(config: dict) -> dict[str, float] | None:
def _handle_load(backend, config: dict, resp_queue: Any) -> None:
- """Handle a load command: load a model into the backend."""
try:
mc = _build_model_config(config)
@@ -1013,7 +1009,6 @@ def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_eve
def _handle_unload(backend, cmd: dict, resp_queue: Any) -> None:
- """Handle an unload command."""
model_name = cmd.get("model_name", "")
try:
if model_name and model_name in backend.models:
@@ -1069,16 +1064,12 @@ def run_inference_process(
os.environ["HF_HUB_DISABLE_XET"] = "1"
logger.info("Xet transport disabled (HF_HUB_DISABLE_XET=1)")
- # Offline auto-detect, as the training and export workers already do. The parent's
- # guard is scoped, so child_env deliberately scrubs it rather than turning a
- # per-request flag into a lifetime one; without a probe of its own this worker would
- # then walk back into the retry paths the parent already ruled out, in
- # _remote_lora_base and in tier activation below. Runs before any HF import, so env
- # alone is enough.
- # Skip it entirely for a filesystem-only load: a local checkpoint whose recorded base
- # (an adapter's, or a full checkpoint's config.json one, both of which activation
- # resolves and reads Hub metadata for) is local too never reaches the Hub, so probing
- # would spend seconds before a load that has no Hub dependency.
+ # Offline auto-detect, as the training and export workers already do. The parent's guard is scoped, so child_env
+ # deliberately scrubs it rather than turning a per-request flag into a lifetime one; without a probe of its own
+ # this worker would then walk back into the retry paths the parent already ruled out, in _remote_lora_base and in
+ # tier activation below. Runs before any HF import, so env alone is enough. Skipped entirely for a filesystem-only
+ # load: a local checkpoint whose recorded base is local too never reaches the Hub, so probing would spend seconds
+ # before a load that has no Hub dependency.
_probe_model = config["model_name"]
_probe_base, _probe_needs_hub = _recorded_local_base(_probe_model)
if "HF_HUB_OFFLINE" not in os.environ and (
@@ -1142,7 +1133,6 @@ def run_inference_process(
mask_accelerators_for_cpu_audio(os.environ)
logger.info("Audio model '%s' pinned to CPU RAM; accelerators hidden", model_name)
- # ── 0. MLX fast-path - skip torch/transformers ──
_ensure_backend_on_path()
if is_apple_silicon():
@@ -1320,26 +1310,23 @@ def run_inference_process(
)
return
- # ── Windows: check Triton availability ──
- # Ahead of the torchao stub below, matching the training and export workers' gate-then-stub order.
- # Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).
+ # Windows Triton check, ahead of the torchao stub below, matching the training and export workers' gate-then-stub
+ # order. Importable Triton is not enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).
if sys.platform == "win32":
from core._msvc_env import gate_torch_compile_on_windows
gate_torch_compile_on_windows(logger)
- # ── Stub torchao on Windows ROCm before ANY transformers import ──
- # Must precede every path that pulls transformers, not just the ML imports in section 2:
- # a local LoRA adapter with no recorded base reaches transformers here via
+ # Stub torchao on Windows ROCm before ANY transformers import. Must precede every path that pulls transformers,
+ # not just the ML imports below: a local LoRA adapter with no recorded base reaches transformers here via
# _resolve_base_model -> utils.models. See core/_torchao_stub.py; no-op off Windows ROCm.
from core._torchao_stub import install_torchao_windows_rocm_stub
install_torchao_windows_rocm_stub()
- # ── Resolve the effective base once, before activation/gates/install ──
- # No ML import on the common path; a local adapter with no recorded base pulls
- # transformers via utils.models, which is why the stub above precedes this.
- # A remote LoRA's base is in its Hub adapter_config.json (else surfaced only by ModelConfig
- # after import). _lora_base is set only for a genuine adapter, never a full fine-tune's base.
+ # Resolve the effective base once, before activation, gates and install. No ML import on the common path; a local
+ # adapter with no recorded base pulls transformers via utils.models, which is why the stub above precedes this. A
+ # remote LoRA's base is in its Hub adapter_config.json (else surfaced only by ModelConfig after import).
+ # _lora_base is set only for a genuine adapter, never a full fine-tune's base.
import json as _json
_ensure_backend_on_path()
@@ -1364,7 +1351,6 @@ def run_inference_process(
# fine-tune's recorded base from config.json (its name reveals the SSM/sidecar arch).
_base = _lora_base or _resolve_base_model(model_name)
- # ── 1. Activate transformers version (on the resolved base) BEFORE any ML imports ──
try:
_activate_transformers_version(_base, _hf_token)
except Exception as exc:
@@ -1378,12 +1364,11 @@ def run_inference_process(
)
return
- # ── 1b. Security gates, then SSM/Mamba kernels, BEFORE importing transformers ──
- # transformers snapshots its optional-backend gates at import, so a hybrid model's kernels
- # must be installed before the import below ("mamba-ssm is required" otherwise). The gates
- # are metadata-only, so run them first and refuse a blocked model before any native build.
- # Gate only the model + a genuine LoRA base (matching _handle_load), never a full fine-tune's
- # unloaded base; _handle_load re-runs the authoritative gates with the mc base.
+ # Security gates, then SSM/Mamba kernels, BEFORE importing transformers. transformers snapshots its
+ # optional-backend gates at import, so a hybrid model's kernels must be installed before the import below
+ # ("mamba-ssm is required" otherwise). The gates are metadata-only, so run them first and refuse a blocked model
+ # before any native build. Gate only the model and a genuine LoRA base (matching _handle_load), never a full
+ # fine-tune's unloaded base; _handle_load re-runs the authoritative gates with the mc base.
_gate_targets = _native_audio_security_targets_or_error(model_name, _hf_token, resp_queue)
if _gate_targets is None:
return
@@ -1410,7 +1395,6 @@ def run_inference_process(
if not _ensure_ssm_kernels(_ssm_targets, resp_queue):
return
- # ── 2. Import ML libraries (fresh in this clean process) ──
try:
_send_response(
resp_queue,
@@ -1450,7 +1434,6 @@ def run_inference_process(
)
return
- # ── 3. Create inference backend and load initial model ──
try:
# Native audio picks its device in __init__, so the preference goes there.
backend = (
@@ -1480,9 +1463,8 @@ def run_inference_process(
)
return
- # ── 4. Command loop — process commands until shutdown ──
- # cancel_event is an mp.Event the parent can set anytime to cancel
- # generation instantly (no queue polling needed).
+ # Command loop: process commands until shutdown. cancel_event is an mp.Event the parent can set anytime to cancel
+ # generation instantly, with no queue polling.
logger.info("Inference subprocess ready, entering command loop")
while True:
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.py
index f7787510a6c..0e741cbb3d8 100644
--- a/studio/backend/core/rag/conversation_archive.py
+++ b/studio/backend/core/rag/conversation_archive.py
@@ -3,17 +3,15 @@
"""Keep the turns the rolling context window evicts, and hand them back on request.
-Each evicted turn is indexed into a per-thread RAG scope, reusing the store, chunker,
-embedder and hybrid retrieval that back attached documents. The stored transcript is
-never touched; this is only a search index over turns the projection cannot carry.
-
-Two properties are load-bearing and easy to break:
-
-* The archive is CUMULATIVE. Nothing is cleared or re-scoped per compaction, so the fifth
- compaction can still find what the first evicted. On MRCR v2 over 11 compaction events,
- cumulative scored 0.450 against 0.058 for latest-compaction-only.
-* Nothing here may break a chat. Every entry point no-ops on failure, because the
- alternative to a degraded archive is a working conversation, not an error.
+Each evicted turn is indexed into a per-thread RAG scope, reusing the store, chunker, embedder and
+hybrid retrieval that back attached documents. The stored transcript is never touched; this is only
+a search index over turns the projection cannot carry.
+
+Two properties are load-bearing and easy to break. The archive is CUMULATIVE: nothing is cleared or
+re-scoped per compaction, so the fifth compaction can still find what the first evicted (on MRCR v2
+over 11 compaction events, cumulative scored 0.450 against 0.058 for latest-compaction-only). And
+nothing here may break a chat: every entry point no-ops on failure, because the alternative to a
+degraded archive is a working conversation, not an error.
"""
from __future__ import annotations
@@ -33,38 +31,34 @@ from .parsers import Page
logger = logging.getLogger(__name__)
-# Instructions, not conversation. An archived system prompt could come back quoted as an
-# "earlier turn" and read as user-authored text.
+# Instructions, not conversation. An archived system prompt could come back quoted as an "earlier turn" and read as
+# user-authored text.
_SKIP_ROLES = frozenset({"system", "developer"})
-# Tool call ids this feature and the RAG auto-inject generate. Their results are retrieved
-# passages, so archiving them would feed retrieved text back into its own index.
+# Tool call ids this feature and the RAG auto-inject generate. Their results are retrieved passages, so archiving them
+# would feed retrieved text back into its own index.
_INJECTED_CALL_PREFIXES = ("rag_auto_", "conv_recall_")
-# What render_turn appends where it cut something short. Named because the branch check
-# has to recognise it: a probe carrying it can only be a PREFIX of the live text.
+# What render_turn appends where it cut something short. Named because the branch check has to recognise it: a probe
+# carrying it can only be a PREFIX of the live text.
_TRUNCATION_MARKER = " ..."
_MAX_TOOL_RESULT_CHARS = 4000
# Tool arguments are usually short; the cap only stops a pathological blob dominating.
_MAX_TOOL_ARGS_CHARS = 1000
-# Over-fetch multiple ahead of the live-branch filter. Filtering after a k-sized fetch
-# lets stale turns from an abandoned branch fill the result and starve live matches just
-# below, so recall returns nothing while the answer is in the archive.
+# Over-fetch multiple ahead of the live-branch filter. Filtering after a k-sized fetch lets stale turns from an
+# abandoned branch fill the result and starve live matches just below, so recall returns nothing while the answer is
+# in the archive.
_BRANCH_FILTER_OVERFETCH = 4
-# One over-fetch is not always enough: rewinding a long compacted continuation leaves an
-# abandoned branch big enough to fill any fixed candidate window, so widen and re-ask.
-# Bounded because this is a chat request, not a crawl.
+# One over-fetch is not always enough: rewinding a long compacted continuation leaves an abandoned branch big enough
+# to fill any fixed candidate window, so widen and re-ask. Bounded because this is a chat request, not a crawl.
_BRANCH_FILTER_MAX_CANDIDATES = 256
def _text_of(content, *, include_tool_calls: bool = False) -> str:
- """Flatten OpenAI message content to plain text, dropping non-text parts.
-
- ``include_tool_calls`` also flattens assistant-ui's persisted ``tool-call`` parts,
- whose call lives in structured ``toolName``/``args``/``result`` fields. The branch
- check needs them, or a transcript can never contain the lines ``render_turn`` wrote
- and every archived tool turn looks rolled back.
- """
+ """Flatten OpenAI message content to plain text, dropping non-text parts. ``include_tool_calls``
+ also flattens assistant-ui's persisted ``tool-call`` parts, whose call lives in structured
+ ``toolName``/``args``/``result`` fields. The branch check needs them, or a transcript can
+ never contain the lines ``render_turn`` wrote and every archived tool turn looks rolled back."""
if isinstance(content, str):
return content
if isinstance(content, list):
@@ -86,18 +80,16 @@ def _text_of(content, *, include_tool_calls: bool = False) -> str:
def _probe_text(message: dict) -> str:
"""One message flattened in the ORDER ``render_turn`` writes it.
- The branch check matches in order, so both must agree on it. Bucketing the whole
- message as call, text, result only holds while the text came BEFORE the call. A
- persisted row whose tool call is followed by the model's final answer -- the ordinary
- agent turn -- renders as call, result, answer, and the buckets put the answer in the
- middle: `_scan_probes` advanced its cursor past the answer to find the result and then
- could not find the answer again, so an unchanged evicted tool exchange was classified
- off-branch and no query could return it. Measured end to end: recall came back with
- the user's question alone and the document holding the answer was filtered out.
-
- So the buckets are flushed the way the replay serializer flushes its pending calls,
- when text arrives after a call. Text before a call still rides ahead of it, which is
- the shape it is written in.
+ The branch check matches in order, so both must agree on it. Bucketing the whole message as
+ call, text, result only holds while the text came BEFORE the call: a persisted row whose tool
+ call is followed by the model's final answer -- the ordinary agent turn -- renders as call,
+ result, answer, and the buckets put the answer in the middle, so `_scan_probes` advanced its
+ cursor past the answer to find the result and then could not find the answer again, classifying
+ an unchanged evicted tool exchange as off-branch so no query could return it.
+
+ So the buckets are flushed the way the replay serializer flushes its pending calls, when text
+ arrives after a call. Text before a call still rides ahead of it, which is the shape it is
+ written in.
"""
chunks: list[str] = []
calls: list[str] = []
@@ -111,11 +103,9 @@ def _probe_text(message: dict) -> str:
results.clear()
def rendered(value) -> list[str]:
- """A structured value as the strings a wire-format copy of it could look like.
-
- The store keeps tool arguments as an object; the archived copy is the model's raw
- string, with its own spacing. This is a haystack, so offering both is free.
- """
+ """A structured value as the strings a wire-format copy of it could look like. The store
+ keeps tool arguments as an object; the archived copy is the model's raw string, with its
+ own spacing. This is a haystack, so offering both is free."""
if isinstance(value, str):
return [value]
try:
@@ -138,14 +128,12 @@ def _probe_text(message: dict) -> str:
if result not in (None, "", {}, []):
results.extend(rendered(result))
elif part.get("type") == "reasoning":
- # A thinking model's stored reply is [reasoning, text], but the wire copy
- # the probe is matched against has the text only (the client sends the
- # thought in the `reasoning_content` FIELD). Folding it in, as the
- # `"text" in part` arm below would, makes the stored probe longer than the
- # branch, so `content_on_branch` fails for every assistant turn of every
- # reasoning thread and `_sticky_compaction_boundary` returns 0 forever --
- # which under the checkpoint fit turns every overflowing turn into a fresh
- # reset. Skipped on both sides: the wire shape has no reasoning part.
+ # A thinking model's stored reply is [reasoning, text], but the wire copy the probe is matched against
+ # has the text only (the client sends the thought in the `reasoning_content` FIELD). Folding it in, as
+ # the `"text" in part` arm below would, makes the stored probe longer than the branch, so
+ # `content_on_branch` fails for every assistant turn of every reasoning thread and
+ # `_sticky_compaction_boundary` returns 0 forever -- which under the checkpoint fit turns every
+ # overflowing turn into a fresh reset. Skipped on both sides: the wire shape has no reasoning part.
continue
elif part.get("type") in ("text", "input_text") or "text" in part:
if calls:
@@ -173,11 +161,9 @@ def _is_injected(message: dict) -> bool:
def render_turn(group: list[dict]) -> str:
- """Render one evicted turn group as the text that gets indexed and quoted back.
-
- Both sides go in one document on purpose, so retrieval returns the question with its
- answer rather than a floating fragment.
- """
+ """Render one evicted turn group as the text that gets indexed and quoted back. Both sides go in
+ one document on purpose, so retrieval returns the question with its answer rather than a
+ floating fragment."""
lines: list[str] = []
for message in group:
role = str(message.get("role") or "")
@@ -186,9 +172,9 @@ def render_turn(group: list[dict]) -> str:
text = _text_of(message.get("content")).strip()
calls = message.get("tool_calls") or []
if calls:
- # The arguments, bounded, not just the name: the searchable substance is the
- # command or query that ran, and "assistant called terminal" cannot answer
- # "what did you run earlier?". Assistant text on the same message likewise.
+ # The arguments, bounded, not just the name: the searchable substance is the command or query that ran,
+ # and "assistant called terminal" cannot answer "what did you run earlier?". Assistant text on the same
+ # message likewise.
for call in calls:
function = (call or {}).get("function") or {}
name = str(function.get("name") or "tool")
@@ -206,8 +192,8 @@ def render_turn(group: list[dict]) -> str:
if not text:
continue
if role == "tool":
- # Tool results are huge and the least useful thing to quote back verbatim:
- # keep enough to be searchable without bloating the index.
+ # Tool results are huge and the least useful thing to quote back verbatim: keep enough to be searchable
+ # without bloating the index.
if len(text) > _MAX_TOOL_RESULT_CHARS:
text = text[:_MAX_TOOL_RESULT_CHARS] + _TRUNCATION_MARKER
lines.append(f"tool result: {text}")
@@ -217,13 +203,11 @@ def render_turn(group: list[dict]) -> str:
def _archivable(group: list[dict]) -> list[dict]:
- """The part of an evicted turn worth archiving, or an empty list.
-
- Our own injections come out, the rest stays. Rejecting the whole group threw away real
- answers: ``group_turns`` keeps a tool call, its result and the following reply in ONE
- group, so an injection on that turn took the model's answer down with it, leaving the
- question archived and the answer not -- on compaction turns, which are the point here.
- """
+ """The part of an evicted turn worth archiving, or an empty list. Our own injections come out,
+ the rest stays. Rejecting the whole group threw away real answers: ``group_turns`` keeps a
+ tool call, its result and the following reply in ONE group, so an injection on that turn took
+ the model's answer down with it, leaving the question archived and the answer not -- on
+ compaction turns, which are the point here."""
if any(str(message.get("role") or "") in _SKIP_ROLES for message in group):
return []
kept = [message for message in group if not _is_injected(message)]
@@ -242,15 +226,15 @@ def _retrieval_names() -> frozenset:
def _without_retrieval(group: list[dict]) -> list[dict]:
"""The group with retrieval calls and their results removed.
- `_is_injected` recognises the ids this feature and the RAG auto-inject generate, but a
- search the MODEL asked for gets an ordinary `call_N` id from the parser, so both the
- call and its retrieved passage were archived as new conversation. Measured: a second
- search then indexed the first one's output inside its own, one nesting level per
- distinct search, each copy competing for the four recall slots.
+ `_is_injected` recognises the ids this feature and the RAG auto-inject generate, but a search
+ the MODEL asked for gets an ordinary `call_N` id from the parser, so both the call and its
+ retrieved passage were archived as new conversation. Measured: a second search then indexed the
+ first one's output inside its own, one nesting level per distinct search, each copy competing
+ for the four recall slots.
- Removed by NAME, and only the retrieval parts: an assistant message can carry a
- retrieval call alongside an ordinary one, and the reply that follows a search is real
- conversation that must still be archived.
+ Removed by NAME, and only the retrieval parts: an assistant message can carry a retrieval call
+ alongside an ordinary one, and the reply that follows a search is real conversation that must
+ still be archived.
"""
names = _retrieval_names()
dropped_ids = set()
@@ -345,28 +329,25 @@ def _text_without_folded_retrieval(text: str, dropped_ids: set):
def enabled() -> bool:
- """Whether the archive can actually run here.
-
- ``rag_available()`` and not ``RAG_AVAILABLE``: the flag only records that
- ``import sqlite_vec`` worked, while the vec0 native library is a separate file a venv
- can be missing (the common macOS case). Trusting it there is worse than no feature at
- all: the fit still reserves room, then write and recall both fail, so the user pays
- extra eviction for content that never arrives.
- """
+ """Whether the archive can actually run here. ``rag_available()`` and not ``RAG_AVAILABLE``: the
+ flag only records that ``import sqlite_vec`` worked, while the vec0 native library is a
+ separate file a venv can be missing (the common macOS case). Trusting it there is worse than
+ no feature at all: the fit still reserves room, then write and recall both fail, so the user
+ pays extra eviction for content that never arrives."""
return bool(config.CONVERSATION_ARCHIVE) and bool(rag_db.rag_available())
def can_archive(thread_id: Optional[str]) -> bool:
"""Whether this thread's evicted turns can be archived at all.
- A temporary (incognito) chat is never written to studio.db, yet the frontend still
- sends its thread_id and the request carries no incognito flag, so saved messages are
- the only signal. Archiving one would persist exactly what the user asked not to keep,
- into a scope with no thread row that no deletion flow could reach. An API client that
- sends a thread_id without persisting anything is excluded for the same reason.
+ A temporary (incognito) chat is never written to studio.db, yet the frontend still sends its
+ thread_id and the request carries no incognito flag, so saved messages are the only signal.
+ Archiving one would persist exactly what the user asked not to keep, into a scope with no thread
+ row that no deletion flow could reach. An API client that sends a thread_id without persisting
+ anything is excluded for the same reason.
- Also gates the fit's recall reserve: a thread that cannot be archived cannot be
- recalled, so reserving there would evict history for content that cannot arrive.
+ Also gates the fit's recall reserve: a thread that cannot be archived cannot be recalled, so
+ reserving there would evict history for content that cannot arrive.
"""
if not thread_id or not enabled():
return False
@@ -385,32 +366,31 @@ def archive_turns(
) -> int:
"""Index the evicted turns for ``thread_id``. Returns how many were newly written.
- Idempotent by content hash: the same turns are evicted again on every later request
- in the session, so re-archiving has to be free. After the first write each repeat
- costs one indexed SELECT and writes nothing.
+ Idempotent by content hash: the same turns are evicted again on every later request in the
+ session, so re-archiving has to be free. After the first write each repeat costs one indexed
+ SELECT and writes nothing.
- ``live`` is the fitted conversation, i.e. what the model can still see. It bounds how
- many copies of a repeated turn the archive is allowed to hold right now; see
- ``_write_budget``. Optional, and omitting it keeps the previous behaviour.
+ ``live`` is the fitted conversation, i.e. what the model can still see. It bounds how many
+ copies of a repeated turn the archive is allowed to hold right now; see ``_write_budget``.
+ Optional, and omitting it keeps the previous behaviour.
"""
if not thread_id or not evicted or not enabled():
return 0
- # Incognito and API-only threads are excluded; see can_archive. By the time a chat is
- # long enough to compact, its earlier turns are always persisted.
+ # Incognito and API-only threads are excluded; see can_archive. By the time a chat is long enough to compact, its
+ # earlier turns are always persisted.
if not can_archive(thread_id):
logger.debug("conversation_archive.skipped_unpersisted_thread thread_id=%s", thread_id)
return 0
- # The evictor's own grouper, so an archived unit is exactly the unit the window drops.
- # Imported lazily because the inference layer imports this module.
+ # The evictor's own grouper, so an archived unit is exactly the unit the window drops. Imported lazily because the
+ # inference layer imports this module.
from core.inference.context_window import group_turns
- # Each entry is the archivable messages AND the span of the turn they came from. The
- # two differ whenever `_archivable` drops something: an assistant batch that called
- # `search_conversation` alongside an ordinary tool archives three messages while the
- # live transcript still holds four, and `archive_messages` bounds the branch check's
- # run. Bounded by the shorter figure, a perfectly valid ordinary-tool exchange and its
- # answer were rejected as off-branch and could never be recalled.
+ # Each entry is the archivable messages AND the span of the turn they came from. The two differ whenever
+ # `_archivable` drops something: an assistant batch that called `search_conversation` alongside an ordinary tool
+ # archives three messages while the live transcript still holds four, and `archive_messages` bounds the branch
+ # check's run. Bounded by the shorter figure, a perfectly valid ordinary-tool exchange and its answer were
+ # rejected as off-branch and could never be recalled.
groups = [
(archivable, len(group))
for group, archivable in ((group, _archivable(group)) for group in group_turns(evicted))
@@ -429,13 +409,12 @@ def archive_turns(
try:
count = embeddings.token_counter(model)
conn = rag_db.get_connection()
- # What the query side will ask for. Only a prediction until the encode reports
- # what it actually used, so the authoritative check happens under the write lock.
+ # What the query side will ask for. Only a prediction until the encode reports what it actually used, so the
+ # authoritative check happens under the write lock.
expected_identity = embeddings.embedding_identity(model)
- # Chunk everything first, then embed it in ONE pass. Per group, a first
- # compaction of a long chat ran dozens of one-item embedding jobs back to back
- # before the reply could start, and both backends serialise them.
+ # Chunk everything first, then embed it in ONE pass. Per group, a first compaction of a long chat ran dozens
+ # of one-item embedding jobs back to back before the reply could start, and both backends serialise them.
pending = []
for group, span in groups:
text = render_turn(group)
@@ -445,16 +424,14 @@ def archive_turns(
seats = _occurrences(positions, group)
budget = _write_budget(positions, seats, live_positions, group)
if _archived_under(conn, scope, digest, expected_identity, occurrences = budget):
- # Commit here: this path holds no transaction of its own and can return
- # before reaching the write lock, the ordinary case on a re-compacted
- # thread, so it is the only chance an upgraded archive has to converge.
- #
- # Bounded by the LIVE-AWARE budget, not by every seat: a rewind or a bigger
- # window can put one occurrence of a repeated turn back in the prompt, and
- # keeping a copy per seat then left two byte-identical documents, both
- # passing the branch filter, so a recall slot went on text the model could
- # already read. Measured: 3 passages of which 2 were distinct. At least one
- # survives, since a turn that is momentarily all-live still has an archive.
+ # Commit here: this path holds no transaction of its own and can return before reaching the write
+ # lock, the ordinary case on a re-compacted thread, so it is the only chance an upgraded archive has
+ # to converge.
+ # Bounded by the LIVE-AWARE budget, not by every seat: a rewind or a bigger window can put one
+ # occurrence of a repeated turn back in the prompt, and keeping a copy per seat then left two
+ # byte-identical documents, both passing the branch filter, so a recall slot went on text the model
+ # could already read. At least one survives, since a turn that is momentarily all-live still has an
+ # archive.
_restamp(
conn,
scope,
@@ -475,8 +452,8 @@ def archive_turns(
if not pending:
return 0
- # Identity from the encode that produced these vectors: a concurrent embedder
- # swap would otherwise label them with a space they were never in.
+ # Identity from the encode that produced these vectors: a concurrent embedder swap would otherwise label them
+ # with a space they were never in.
vectors, identity = embeddings.encode_with_identity(
[chunk.text for entry in pending for chunk in entry[3]],
model_name = model,
@@ -489,13 +466,11 @@ def archive_turns(
roles = " + ".join(
dict.fromkeys(str(message.get("role") or "message") for message in group)
)
- # commit=False, then commit once the chunks are in: committing the document
- # first leaves an empty row marked "completed" if the chunk write fails, and
- # `document_by_hash` skips that turn forever after without retrying.
- # Re-checked here under a write lock, not only before the embedding pass: two
- # generations compacting one thread both clear that first check, and
- # `(scope, sha256)` is a plain index, so both insert and the duplicate takes
- # two of the few recall slots. Reproduced with two concurrent archive passes.
+ # commit=False, then commit once the chunks are in: committing the document first leaves an empty row
+ # marked "completed" if the chunk write fails, and `document_by_hash` skips that turn forever after
+ # without retrying. Re-checked here under a write lock, not only before the embedding pass: two
+ # generations compacting one thread both clear that first check, and `(scope, sha256)` is a plain index,
+ # so both insert and the duplicate takes two of the few recall slots.
_write_lock = False
try:
conn.execute("BEGIN IMMEDIATE")
@@ -509,11 +484,10 @@ def archive_turns(
_restamp(conn, scope, digest, seats, copies = copies)
if _write_lock:
conn.commit()
- # Widened here too, not only on the pre-check: both turns can arrive in ONE
- # compaction, the shorter is written first, and the longer then meets this
- # re-check, so leaving without touching the span left the window at the
- # shorter figure and the longer occurrence unsearchable. After the commit
- # above, since the widen carries its own.
+ # Widened here too, not only on the pre-check: both turns can arrive in ONE compaction, the shorter is
+ # written first, and the longer then meets this re-check, so leaving without touching the span left
+ # the window at the shorter figure and the longer occurrence unsearchable. After the commit above,
+ # since the widen carries its own.
_widen_span(conn, scope, digest, span)
continue
ordinal = None
@@ -538,8 +512,8 @@ def archive_turns(
archived_rowid = previous.get("rowid")
store.delete_document(conn, stale, commit = False)
else:
- # The nth copy of a repeated turn takes the nth occurrence's position, so a
- # verbatim repeat lands where it was said, not behind its first saying.
+ # The nth copy of a repeated turn takes the nth occurrence's position, so a verbatim repeat lands
+ # where it was said, not behind its first saying.
ordinal = (
seats[len(copies)]
if seats and len(copies) < len(seats)
@@ -553,19 +527,17 @@ def archive_turns(
sha256 = digest,
status = "completed",
embedding_model = identity,
- # The turn's real size in the TRANSCRIPT, so the branch check can bound its
- # run exactly. Role labels only approximate it (a pasted transcript writes
- # the same lines) and the archived messages undercount what `_archivable`
- # dropped.
+ # The turn's real size in the TRANSCRIPT, so the branch check can bound its run exactly. Role labels
+ # only approximate it (a pasted transcript writes the same lines) and the archived messages undercount
+ # what `_archivable` dropped.
archive_messages = span,
- # Where this turn sits in the conversation. Allocated inside the write lock
- # in `group_turns` order, so it holds within and across epochs, which
- # `created_at` cannot: one compaction writes every evicted turn microseconds
- # apart. Written unconditionally, so switching ordering off punches no
- # permanent holes in the sequence.
+ # Where this turn sits in the conversation. Allocated inside the write lock in `group_turns` order, so
+ # it holds within and across epochs, which `created_at` cannot: one compaction writes every evicted
+ # turn microseconds apart. Written unconditionally, so switching ordering off punches no permanent
+ # holes in the sequence.
archive_ordinal = ordinal,
- # When the turn was archived, not when this row was written. None for a turn
- # seen for the first time, which takes the clock as before.
+ # When the turn was archived, not when this row was written. None for a turn seen for the first time,
+ # which takes the clock as before.
created_at = archived_at,
# Likewise None for a first sighting: SQLite then assigns the next rowid.
rowid = archived_rowid,
@@ -576,26 +548,21 @@ def archive_turns(
except Exception:
conn.rollback()
raise
- # Surplus only, NOT a restamp: the re-embed path never reaches the
- # already-archived branch that retires copies, so a repeat archived twice and
- # then rewound kept its extra copy. Restamping here would renumber a pre-column
- # row. Runs after the new row exists, so the count is what the scope holds.
+ # Surplus only, NOT a restamp: the re-embed path never reaches the already-archived branch that retires
+ # copies, so a repeat archived twice and then rewound kept its extra copy. Restamping here would renumber
+ # a pre-column row. Runs after the new row exists, so the count is what the scope holds.
_retire_surplus(conn, scope, digest, seats)
- # A re-embed keeps the ordinal it found, which goes wrong once a copy is
- # retired: twins at 0 and 2 with the FIRST rewound away left the survivor on 0,
- # so a contradiction at 1 rendered as the later, superseding statement.
- # Restamped against the seats that remain, skipping NULLs.
+ # A re-embed keeps the ordinal it found, which goes wrong once a copy is retired: twins at 0 and 2 with
+ # the FIRST rewound away left the survivor on 0, so a contradiction at 1 rendered as the later,
+ # superseding statement. Restamped against the seats that remain, skipping NULLs.
if stale is not None:
_restamp(conn, scope, digest, seats, skip_null = True)
conn.commit()
written += 1
- # A REPLACEMENT is not an addition: the re-embed branch swaps one copy's
- # vectors and keeps the count, so a repeat evicted while the embedder identity
- # changed was never written at all. Top the copies up to the budget here,
- # reusing the vectors already in hand.
- #
- # Only where the budget counts EVICTED occurrences, which is what `live` buys.
- # Otherwise it falls back to every transcript seat, and topping up to that
+ # A REPLACEMENT is not an addition: the re-embed branch swaps one copy's vectors and keeps the count, so a
+ # repeat evicted while the embedder identity changed was never written at all. Top the copies up to the
+ # budget here, reusing the vectors already in hand. Only where the budget counts EVICTED occurrences,
+ # which is what `live` buys; otherwise it falls back to every transcript seat, and topping up to that
# would write a copy of a turn whose repeat is still in the prompt.
while (
stale is not None
@@ -622,8 +589,8 @@ def archive_turns(
if _INGEST_FAILED:
globals()["_INGEST_FAILED"] = False
except Exception:
- # A chat that cannot archive still beats one that raises. Whatever was written
- # before the failure stays searchable.
+ # A chat that cannot archive still beats one that raises. Whatever was written before the failure stays
+ # searchable.
globals()["_INGEST_FAILED"] = True
logger.warning("conversation_archive.ingest_failed thread_id=%s", thread_id, exc_info = True)
finally:
@@ -633,12 +600,11 @@ def archive_turns(
except Exception:
pass
- # Cancellation is cooperative, and chunking plus embedding is the slowest stretch of
- # this function. A delete landing in that window sweeps the archive scope BEFORE this
- # commit puts rows back, stranding deleted content in a scope no later delete reaches.
- # Re-checking after the commit converges either way: the delete route drops thread
- # rows first and sweeps archives last, so an earlier sweep is caught here and a later
- # one removes these rows itself.
+ # Cancellation is cooperative, and chunking plus embedding is the slowest stretch of this function. A delete
+ # landing in that window sweeps the archive scope BEFORE this commit puts rows back, stranding deleted content in
+ # a scope no later delete reaches. Re-checking after the commit converges either way: the delete route drops
+ # thread rows first and sweeps archives last, so an earlier sweep is caught here and a later one removes these
+ # rows itself.
if written and not can_archive(thread_id):
logger.info("conversation_archive.thread_deleted_mid_ingest thread_id=%s", thread_id)
delete_for_thread(thread_id)
@@ -646,71 +612,58 @@ def archive_turns(
return written
-# Set when an archive write fails, cleared by the next one that succeeds. Process-wide on
-# purpose: what fails here is the embedder or the store, not one thread.
+# Set when an archive write fails, cleared by the next one that succeeds. Process-wide on purpose: what fails here is
+# the embedder or the store, not one thread.
_INGEST_FAILED = False
def degraded() -> bool:
- """Whether the last archive attempt failed outright.
-
- The window reserves recall room before any of this runs and ``archive_turns``
- swallows its failures, so a machine whose embedder cannot start would pay the reserve
- on every compaction for nothing. The caller checks this and stops reserving.
- """
+ """Whether the last archive attempt failed outright. The window reserves recall room before any
+ of this runs and ``archive_turns`` swallows its failures, so a machine whose embedder cannot
+ start would pay the reserve on every compaction for nothing. The caller checks this and stops
+ reserving."""
return _INGEST_FAILED
-# Short enough that a store or embedder coming back is noticed within a turn or two, long
-# enough that one request's refits share a single probe.
+# Short enough that a store or embedder coming back is noticed within a turn or two, long enough that one request's
+# refits share a single probe.
def reachable() -> bool:
"""Whether an archive write attempted RIGHT NOW could reach its store and embedder.
- ``degraded`` is the verdict on the LAST write, the wrong tense for a caller deciding
- whether to reset: this request's write runs afterwards and swallows its own failure, so
- the first request after the store or embedder dies would commit a reset claiming the
- dropped turns are searchable while nothing was indexed.
-
- A probe, not a promise: it cannot see a failure starting after it returns, leaving the
- same one-turn window for a store that dies mid-request (the turns survive anyway, since
- the client re-sends the branch and the write is idempotent).
-
- The counter is CALLED, not merely constructed. `embedding_identity` is string
- formatting over resolver metadata and `token_counter` hands back a lazy closure, so
- both reported a healthy archive while the embedder could not initialize; calling it
- forces the load.
-
- And a real ENCODE, because the tokenizer is not the forward pass. `_st_token_counter`
- reaches only `_get(model).tokenizer`, so a runtime encode failure with no llama binary
- to fall back to -- CUDA OOM against the co-resident chat model, a driver fault, the
- half-precision path -- left this answering yes while `archive_turns` was about to
- raise and swallow it. The reset would already have dropped the history and told the
- model it was searchable, and the epoch is replayed from the boundary, so the loss is
- durable rather than one turn.
-
- NOT memoised across requests. A time-boxed cache handed back a stale yes for the whole
- window after the store or embedder died, and one request inside it is enough: the epoch
- starts, `archive_turns` swallows the write failure, and the fitted prompt has already
- dropped the turns it says are searchable. The caller memoises per fit instead, which is
- the only span where the answer cannot change under it.
-
- `"x"` rather than `""`: an empty input is documented to upset the llama embedding
- server. An encode rather than `dim()`, which caches and on the sentence-transformers
- path runs no forward at all -- that would reintroduce exactly the bug this closes.
+ ``degraded`` is the verdict on the LAST write, the wrong tense for a caller deciding whether to
+ reset: this request's write runs afterwards and swallows its own failure, so the first request
+ after the store or embedder dies would commit a reset claiming the dropped turns are searchable
+ while nothing was indexed. A probe, not a promise: it cannot see a failure starting after it
+ returns, leaving the same one-turn window for a store that dies mid-request (the turns survive
+ anyway, since the client re-sends the branch and the write is idempotent).
+
+ The counter is CALLED, not merely constructed: `embedding_identity` is string formatting over
+ resolver metadata and `token_counter` hands back a lazy closure, so both reported a healthy
+ archive while the embedder could not initialize. And a real ENCODE, because the tokenizer is not
+ the forward pass: `_st_token_counter` reaches only `_get(model).tokenizer`, so a runtime encode
+ failure with no llama binary to fall back to left this answering yes while `archive_turns` was
+ about to raise and swallow it, after the reset had already dropped the history and told the
+ model it was searchable. The epoch is replayed from the boundary, so that loss is durable rather
+ than one turn.
+
+ NOT memoised across requests: a time-boxed cache handed back a stale yes for the whole window
+ after the store or embedder died, and one request inside it is enough. The caller memoises per
+ fit instead, which is the only span where the answer cannot change under it.
+
+ `"x"` rather than `""`: an empty input is documented to upset the llama embedding server. An
+ encode rather than `dim()`, which caches and on the sentence-transformers path runs no forward
+ at all -- that would reintroduce exactly the bug this closes.
"""
if not enabled():
return False
conn = None
try:
conn = rag_db.get_connection()
- # WRITABLE, not merely open. `get_connection` succeeds against a database that is
- # read-only, on a full filesystem, or held by another writer, and the archive
- # write happens after the reset and swallows its own failure, so the block would
- # promise a searchable history that nothing could store.
- #
- # A real statement, rolled back. `BEGIN IMMEDIATE` on its own is NOT enough:
- # sqlite defers the check, and it returns cleanly on a read-only connection that
- # raises the moment anything is written. The rollback leaves the schema untouched.
+ # WRITABLE, not merely open. `get_connection` succeeds against a database that is read-only, on a full
+ # filesystem, or held by another writer, and the archive write happens after the reset and swallows its own
+ # failure, so the block would promise a searchable history that nothing could store. A real statement, rolled
+ # back: `BEGIN IMMEDIATE` on its own is NOT enough, since sqlite defers the check and it returns cleanly on a
+ # read-only connection that raises the moment anything is written. The rollback leaves the schema untouched.
conn.execute("BEGIN IMMEDIATE")
try:
conn.execute("CREATE TABLE IF NOT EXISTS _archive_write_probe(x)")
@@ -725,10 +678,9 @@ def reachable() -> bool:
logger.debug("conversation_archive.unreachable", exc_info = True)
return False
finally:
- # The probe runs on every checkpoint-eligible overflow, and a connection left to
- # cyclic collection is a descriptor held for an unbounded time: measured, 50 calls
- # leaked 50 open handles on rag.db. Every other connection in this module is closed
- # the same way.
+ # The probe runs on every checkpoint-eligible overflow, and a connection left to cyclic collection is a
+ # descriptor held for an unbounded time: measured, 50 calls leaked 50 open handles on rag.db. Every other
+ # connection in this module is closed the same way.
if conn is not None:
try:
conn.close()
@@ -736,15 +688,13 @@ def reachable() -> bool:
pass
-# Returned by ``_stale_document`` for a turn that is already archived under vectors the
-# query side still accepts.
+# Returned by ``_stale_document`` for a turn that is already archived under vectors the query side still accepts.
_ARCHIVED = "archived"
-# How many leaves a branch seed will try. A thread gains one leaf per abandoned retry and
-# the branch the user went BACK to is older than all of them, so a tight cap excluded the
-# very branch this exists to find. Paid for by rendering each stored message once rather
-# than once per leaf: sibling chains share nearly all their ancestors.
+# How many leaves a branch seed will try. A thread gains one leaf per abandoned retry and the branch the user went
+# BACK to is older than all of them, so a tight cap excluded the very branch this exists to find. Paid for by
+# rendering each stored message once rather than once per leaf: sibling chains share nearly all their ancestors.
_BRANCH_SEED_MAX_LEAVES = 512
@@ -774,29 +724,27 @@ def _branch_seed(
) -> Optional[str]:
"""Which stored endpoint the REQUEST proves by matching text. None when no row matches.
- The newest stored row is not the branch the request is on. Switching to a sibling,
- continuing there and switching back leaves the abandoned branch holding the greatest
- created_at, and the frontend says so outright in `refresh-context-usage.ts`: after a
- retry the newest stored leaf is a branch the user left. Measured on a thread with one
- such switch, the walk read the abandoned branch and BOTH of the request branch's
- evicted turns matched no position, taking MAX + 1 over an archive the other branch had
- already pushed up, which the recall header presents as superseding.
-
- Matched on text, not id: the wire carries no message ids. Scored rather than compared,
- since the newest branch message is usually not persisted yet and the evicted turns are
- no longer in the fitted conversation.
+ The newest stored row is not the branch the request is on: switching to a sibling, continuing
+ there and switching back leaves the abandoned branch holding the greatest created_at, and the
+ frontend says so outright in `refresh-context-usage.ts`. Measured on a thread with one such
+ switch, the walk read the abandoned branch and BOTH of the request branch's evicted turns
+ matched no position, taking MAX + 1 over an archive the other branch had already pushed up,
+ which the recall header presents as superseding.
+
+ Matched on text, not id: the wire carries no message ids. Scored rather than compared, since the
+ newest branch message is usually not persisted yet and the evicted turns are no longer in the
+ fitted conversation.
"""
if not branch:
return None
- # A LIST, in order, not a set: sets lose repetition and ordering, so an abandoned
- # sibling with the same distinct texts tied with the request's own branch and, being
- # newer, won. A multiset fixes the repeat case but not the reordered one, so this
- # scores an in-order run. System and developer messages are excluded: Unsloth's
- # prepended chat and project instructions are not part of the stored chain.
+ # A LIST, in order, not a set: sets lose repetition and ordering, so an abandoned sibling with the same distinct
+ # texts tied with the request's own branch and, being newer, won. A multiset fixes the repeat case but not the
+ # reordered one, so this scores an in-order run. System and developer messages are excluded: Unsloth's prepended
+ # chat and project instructions are not part of the stored chain.
def _key(message):
- """What a message matches ON. Role-blind let a rewound, unstored "Continue." match
- an ABANDONED assistant reply of the same text and adopt its boundary."""
+ """What a message matches ON. Role-blind let a rewound, unstored "Continue." match an
+ ABANDONED assistant reply of the same text and adopt its boundary."""
text = _normalise_cased(_probe_text(message))
if not text:
return None
@@ -813,9 +761,9 @@ def _branch_seed(
]
if not wanted:
return None
- # Where each text may be matched, so the scan can SKIP an entry with no stored
- # counterpart. A strict cursor stalled on the first one, every leaf scored zero, and
- # the fallback to the newest row picked the abandoned branch this exists to avoid.
+ # Where each text may be matched, so the scan can SKIP an entry with no stored counterpart. A strict cursor
+ # stalled on the first one, every leaf scored zero, and the fallback to the newest row picked the abandoned branch
+ # this exists to avoid.
where: dict = {}
for index, text in enumerate(wanted):
where.setdefault(text, []).append(index)
@@ -833,8 +781,8 @@ def _branch_seed(
best_matched = None
best_score = 0
best_tied = False
- # Rendered once per STORED ROW, not per leaf: `_as_wire` expands a row the same way
- # whichever chain it is walked in.
+ # Rendered once per STORED ROW, not per leaf: `_as_wire` expands a row the same way whichever chain it is walked
+ # in.
rendered: dict = {}
def _texts_of(record: dict) -> list:
@@ -846,9 +794,8 @@ def _branch_seed(
return rendered[identifier]
for leaf in leaves[:_BRANCH_SEED_MAX_LEAVES]:
- # Greedy in-order scan with gaps allowed on both sides: the newest branch message
- # is usually unpersisted and evicted turns have left the fitted conversation, so
- # neither side is a subsequence of the other.
+ # Greedy in-order scan with gaps allowed on both sides: the newest branch message is usually unpersisted and
+ # evicted turns have left the fitted conversation, so neither side is a subsequence of the other.
cursor = 0
score = 0
last_matched = None
@@ -887,30 +834,29 @@ def _active_chain(
"""The rows on ONE branch, oldest first, rather than the whole stored DAG.
`list_chat_messages` is an unfiltered SELECT ordered by time, but a thread is a tree:
- `parent_id` is a real column and Retry leaves the replaced reply in place as a sibling.
- Read as a flat list, an abandoned sibling lands between two live turns and the grouper
- glues it onto whichever turn precedes it, so the regenerated turn matches no position
- at all and falls back to MAX + 1. Measured on five turns with one Retry: the
- regenerated turn 2 came back numbered 5 out of 4 live turns, colliding with live turn
- 3, under the header that says the higher number supersedes. The cumulative archive is
- what makes MAX + 1 land past everything -- the abandoned branch has already taken the
- high numbers -- so this does not depend on the eviction order.
-
- Walked newest leaf back to root, the same shape the frontend's `orderBySelectedBranch`
- uses to decide what the model is actually shown. `parent_id` is missing on rows written
- before that column, so the previous row stands in for it, which is exactly a flat list
- when nothing branches. Unlike the frontend, this default path never roots a null after
- a recorded parent. ``fallback=False`` lets callers decline when the request cannot seed
- a chain instead of silently reading the newest stored sibling. ``require_unique``
- likewise declines when indistinguishable leaves tie for the best branch match and trims
- the winner after the last stored row the request actually matched.
+ `parent_id` is a real column and Retry leaves the replaced reply in place as a sibling. Read as
+ a flat list, an abandoned sibling lands between two live turns and the grouper glues it onto
+ whichever turn precedes it, so the regenerated turn matches no position at all and falls back to
+ MAX + 1. Measured on five turns with one Retry: the regenerated turn 2 came back numbered 5 out
+ of 4 live turns, colliding with live turn 3, under the header that says the higher number
+ supersedes. The cumulative archive is what makes MAX + 1 land past everything, so this does not
+ depend on the eviction order.
+
+ Walked newest leaf back to root, the same shape the frontend's `orderBySelectedBranch` uses to
+ decide what the model is actually shown. `parent_id` is missing on rows written before that
+ column, so the previous row stands in for it, which is exactly a flat list when nothing
+ branches. Unlike the frontend, this default path never roots a null after a recorded parent.
+ ``fallback=False`` lets callers decline when the request cannot seed a chain instead of silently
+ reading the newest stored sibling. ``require_unique`` likewise declines when indistinguishable
+ leaves tie for the best branch match and trims the winner after the last stored row the request
+ actually matched.
"""
if not messages:
return []
by_id: dict = {}
parent_of: dict = {}
- # Rows whose parent is storage order rather than a real link. The root's absent parent
- # is not synthesized: nothing stood in for it.
+ # Rows whose parent is storage order rather than a real link. The root's absent parent is not synthesized: nothing
+ # stood in for it.
synthesized: set = set()
previous = None
for message in messages:
@@ -919,11 +865,10 @@ def _active_chain(
continue
by_id[identifier] = message
parent = message.get("parentId") or message.get("parent_id")
- # A row that CARRIES the column and holds null is a root the client meant, as
- # editing the first prompt makes. Only a row written before the column exists has
- # nothing to say, and there storage order stands in. Under the legacy path the
- # stand-in is unconditional, as it always was: `_transcript_positions` numbers
- # turns off this chain, and rooting a null there renumbers the whole archive.
+ # A row that CARRIES the column and holds null is a root the client meant, as editing the first prompt makes.
+ # Only a row written before the column exists has nothing to say, and there storage order stands in. Under the
+ # legacy path the stand-in is unconditional, as it always was: `_transcript_positions` numbers turns off this
+ # chain, and rooting a null there renumbers the whole archive.
stated = require_unique and ("parentId" in message or "parent_id" in message)
if parent is None and previous is not None and not stated:
synthesized.add(identifier)
@@ -933,13 +878,11 @@ def _active_chain(
if not by_id:
return list(messages) if fallback else []
if require_unique and synthesized:
- # Storage order is not ancestry. Where it strung INDISTINGUISHABLE rows into one
- # chain it made the abandoned twin an ancestor of the live one, and the greedy trim
- # stopped on the twin, replaying ITS deeper boundary instead of the safe vote
- # across them. The twins need not be adjacent: the abandoned branch's own
- # continuation sits between them. Threads the text can still tell apart are left
- # alone, since declining on every invented link would refuse legacy ancestry that
- # storage order does recover.
+ # Storage order is not ancestry. Where it strung INDISTINGUISHABLE rows into one chain it made the abandoned
+ # twin an ancestor of the live one, and the greedy trim stopped on the twin, replaying ITS deeper boundary
+ # instead of the safe vote across them. The twins need not be adjacent: the abandoned branch's own
+ # continuation sits between them. Threads the text can still tell apart are left alone, since declining on
+ # every invented link would refuse legacy ancestry that storage order does recover.
seen: set = set()
for message in messages:
if message.get("id") is None:
@@ -948,9 +891,8 @@ def _active_chain(
if key[1] and key in seen:
return []
seen.add(key)
- # The request's own branch when it can be found, the newest row when it cannot: empty
- # positions empty every seat and send every turn to MAX + 1, which is worse than
- # reading the wrong branch.
+ # The request's own branch when it can be found, the newest row when it cannot: empty positions empty every seat
+ # and send every turn to MAX + 1, which is worse than reading the wrong branch.
seed = _branch_seed(messages, by_id, parent_of, branch, require_unique = require_unique)
if seed is None:
if not fallback:
@@ -959,41 +901,38 @@ def _active_chain(
return _walk_from(by_id, parent_of, seed) or list(messages)
-# `JSON.stringify({ result: "" })` byte for byte. `json.dumps` puts a space after the
-# colon and `JSON.stringify` does not, so the obvious spelling never equals the archived
-# message: every comparison downstream is exact, and `_normalise` collapses whitespace
-# RUNS, not a single space.
+# `JSON.stringify({ result: "" })` byte for byte. `json.dumps` puts a space after the colon and `JSON.stringify` does
+# not, so the obvious spelling never equals the archived message: every comparison downstream is exact, and
+# `_normalise` collapses whitespace RUNS, not a single space.
_EMPTY_TOOL_RESULT = '{"result":""}'
-# `SERVER_SIDE_BUILTIN_TOOL_NAMES` in `chat-adapter.ts`. The NAME alone never decides: a
-# user function may legitimately be called `web_search`, so the marker or a Gemini native
-# part has to be there too, as the frontend also requires.
+# `SERVER_SIDE_BUILTIN_TOOL_NAMES` in `chat-adapter.ts`. The NAME alone never decides: a user function may
+# legitimately be called `web_search`, so the marker or a Gemini native part has to be there too, as the frontend also
+# requires.
_SERVER_BUILTIN_NAMES = frozenset({"web_search", "web_fetch", "code_execution", "image_generation"})
# `SANDBOX_FILE_TOOLS`, and `tool_loop_controller._SANDBOX_TOOLS`. Only these two wrap.
_SANDBOX_TOOL_NAMES = frozenset({"python", "terminal"})
-# `search-images.ts`. `re.ASCII` on the scheme because Python's IGNORECASE folds Unicode,
-# so `httpſ://` (U+017F) would match where JavaScript's `/i` does not.
+# `search-images.ts`. `re.ASCII` on the scheme because Python's IGNORECASE folds Unicode, so `http\u017f://` would
+# match where JavaScript's `/i` does not.
_SEARCH_IMAGE_ID = re.compile(r"[0-9a-f]{12}")
_SEARCH_IMAGE_SOURCE = re.compile(r"https?://", re.IGNORECASE | re.ASCII)
_SEARCH_IMAGE_TOKEN = re.compile(
r"\n\n[ \t]*\[\[img:[0-9a-f]{12}\]\][ \t]*(?=\n\n|\n?\Z)|\[\[img:[0-9a-f]{12}\]\]"
)
-# `sanitizeAssistantReplayText`. An audio model answers with an `<audio-player src=...>`
-# tag holding the whole wav inline, and the serializer sends `[audio]` in its place.
+# `sanitizeAssistantReplayText`. An audio model answers with an `<audio-player src=...>` tag holding the whole wav
+# inline, and the serializer sends `[audio]` in its place.
_REPLAY_AUDIO_DATA_URI = re.compile(r"data:audio/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+")
def _server_builtin(part: dict) -> tuple[bool, bool]:
- """Whether a persisted call is a provider-side builtin, and whether it has a native part.
-
- The frontend drops a builtin from the replayed history entirely when there is no
- native part, and replays one WITH a native part as a call carrying no `tool` result.
- Reconstructing either as an ordinary local call inserted a phantom exchange, so the
- request-shaped turn no longer matched the persisted run and the turn took a fallback
- ordinal. Both signals ride on the persisted `args`, so this is decidable here.
- """
+ """Whether a persisted call is a provider-side builtin, and whether it has a native part. The
+ frontend drops a builtin from the replayed history entirely when there is no native part, and
+ replays one WITH a native part as a call carrying no `tool` result. Reconstructing either as
+ an ordinary local call inserted a phantom exchange, so the request-shaped turn no longer
+ matched the persisted run and the turn took a fallback ordinal. Both signals ride on the
+ persisted `args`, so this is decidable here."""
args = part.get("args")
args = args if isinstance(args, dict) else {}
if str(part.get("toolName") or "").lower() not in _SERVER_BUILTIN_NAMES:
@@ -1003,8 +942,8 @@ def _server_builtin(part: dict) -> tuple[bool, bool]:
return bool(args.get("_server_tool") is True or native), native
-# One predicate per frontend predicate of the same name. `sessionId` and `subject` are
-# tested for ABSENCE, not null, because the frontend tests them against `undefined`.
+# One predicate per frontend predicate of the same name. `sessionId` and `subject` are tested for ABSENCE, not null,
+# because the frontend tests them against `undefined`.
def _mcp_image_result(result) -> bool:
if not isinstance(result, dict) or not isinstance(result.get("text"), str):
return False
@@ -1048,8 +987,8 @@ def _search_images_result(result) -> bool:
def _sandbox_wrapper(result, tool_name: str) -> bool:
- # The name gates it as well as the shape: another tool answering with
- # `{text, sessionId, images}` is someone else's, and unwrapping it drops its rest.
+ # The name gates it as well as the shape: another tool answering with `{text, sessionId, images}` is someone
+ # else's, and unwrapping it drops its rest.
if not isinstance(result, dict) or not isinstance(result.get("text"), str):
return False
if tool_name not in _SANDBOX_TOOL_NAMES or not isinstance(result.get("sessionId"), str):
@@ -1064,37 +1003,29 @@ def _sandbox_wrapper(result, tool_name: str) -> bool:
def _strip_search_image_tokens(text: str) -> str:
- """`stripSearchImageTokens`. A token resolves only against the message that produced
- it, so the frontend drops them rather than replay an unresolvable id.
-
- Its code-block carve-out is NOT mirrored: deciding it takes the frontend's whole
- markdown scanner, and nothing that reaches this writes a token into code. The tool
- cannot open a region (`_web_search` collapses every title and snippet behind a label,
- and the url branch returns before an envelope is appended); a reply that fences one
- reconstructs exactly as it did before anything here stripped.
- """
+ """`stripSearchImageTokens`. A token resolves only against the message that produced it, so the
+ frontend drops them rather than replay an unresolvable id. Its code-block carve-out is NOT
+ mirrored: deciding it takes the frontend's whole markdown scanner, and nothing that reaches
+ this writes a token into code (the tool cannot open a region, and a reply that fences one
+ reconstructs exactly as it did before anything here stripped)."""
if "[[img:" not in text:
return text
return _SEARCH_IMAGE_TOKEN.sub("", text)
def _sanitised_assistant_text(text: str) -> str:
- """`sanitizeAssistantReplayText`: an assistant reply as the serializer replays it.
-
- The same two substitutions the tool result gets, for the same reason. A reply that
- shows a picture carries the token that placed it, and an audio turn carries its whole
- wav, so a stored reply reconstructed verbatim described a message the request never
- sent and the turn matched no transcript seat.
- """
+ """`sanitizeAssistantReplayText`: an assistant reply as the serializer replays it. The same two
+ substitutions the tool result gets, for the same reason: a reply that shows a picture carries
+ the token that placed it, and an audio turn carries its whole wav, so a stored reply
+ reconstructed verbatim described a message the request never sent and the turn matched no
+ transcript seat."""
return _REPLAY_AUDIO_DATA_URI.sub("[audio]", _strip_search_image_tokens(text))
def _sanitised_assistant_content(content):
- """`content` with every part `_probe_text` reads as text sanitised, others untouched.
-
- Keyed on the `text` field rather than on the type, as `_probe_text` is, so a part
- shape it renders cannot slip past this one.
- """
+ """`content` with every part `_probe_text` reads as text sanitised, others untouched. Keyed on
+ the `text` field rather than on the type, as `_probe_text` is, so a part shape it renders
+ cannot slip past this one."""
if isinstance(content, str):
return _sanitised_assistant_text(content)
if not isinstance(content, list):
@@ -1110,13 +1041,11 @@ def _sanitised_assistant_content(content):
def _unwrapped(result, tool_name: str):
- """A wrapper this app put around a result, reduced to the text the model actually saw.
-
- The adapter replays that text alone, so serialising the wrapper reconstructed a tool
- message that can never equal the archived one. Being a wrapper and losing the tokens
- are two questions, as they are in the serializer: a result carrying both `images` and
- `webImages` is unwrapped by the first and stripped by the second.
- """
+ """A wrapper this app put around a result, reduced to the text the model actually saw. The
+ adapter replays that text alone, so serialising the wrapper reconstructed a tool message that
+ can never equal the archived one. Being a wrapper and losing the tokens are two questions, as
+ they are in the serializer: a result carrying both `images` and `webImages` is unwrapped by
+ the first and stripped by the second."""
if not (
_mcp_image_result(result)
or _search_images_result(result)
@@ -1128,37 +1057,31 @@ def _unwrapped(result, tool_name: str):
def _tool_result_content(result, tool_name: str = "") -> str:
- """A persisted tool result in the string the replay serializer would have sent.
-
- An empty string becomes the sentinel above, because the backend's ChatMessage
- validator rejects a `tool` message with empty content; everything else is JSON with
- JavaScript's separators. Rendering it any other way makes the reconstructed message
- differ from the one that was actually archived, which is the whole point of this
- module comparing the two.
- """
+ """A persisted tool result in the string the replay serializer would have sent. An empty string
+ becomes the sentinel above, because the backend's ChatMessage validator rejects a `tool`
+ message with empty content; everything else is JSON with JavaScript's separators. Rendering
+ it any other way makes the reconstructed message differ from the one that was actually
+ archived, which is the whole point of this module comparing the two."""
if isinstance(result, str):
return result if result else _EMPTY_TOOL_RESULT
unwrapped = _unwrapped(result, tool_name)
if unwrapped is not None:
return unwrapped if unwrapped else _EMPTY_TOOL_RESULT
- # `ensure_ascii = False` because `JSON.stringify` does not escape non-ASCII. Otherwise
- # an accented tool result reconstructs as `Montr\\u00e9al`, loses its transcript seat
- # and is filtered out of recall.
+ # `ensure_ascii = False` because `JSON.stringify` does not escape non-ASCII. Otherwise an accented tool result
+ # reconstructs as `Montr\\u00e9al`, loses its transcript seat and is filtered out of recall.
return json.dumps(result, ensure_ascii = False, separators = (",", ":"))
def _replayable(part: dict) -> bool:
"""Whether the serializer replays this tool call at all.
- `chat-adapter.ts` drops the whole call when it has no result to send and cannot be
- replayed without one: `if (!toolResult && !canReplayToolCallWithoutRoleTool(part))
- continue`. That is every cancelled or still-running LOCAL card. Keeping it here and
- merely omitting its `tool` message invented an assistant `tool_calls` message the
- request never carried, which shifts the groups either side of it and can send an
- otherwise live turn to a wrong ordinal or out of the branch check entirely.
-
- A provider-side builtin is replayable without a result, but one with no native part
- is dropped by `serializeAssistantToolCallPart` instead, so it is not a call here.
+ `chat-adapter.ts` drops the whole call when it has no result to send and cannot be replayed
+ without one: `if (!toolResult && !canReplayToolCallWithoutRoleTool(part)) continue`. That is
+ every cancelled or still-running LOCAL card. Keeping it here and merely omitting its `tool`
+ message invented an assistant `tool_calls` message the request never carried, which shifts the
+ groups either side of it and can send an otherwise live turn to a wrong ordinal or out of the
+ branch check entirely. A provider-side builtin is replayable without a result, but one with no
+ native part is dropped by `serializeAssistantToolCallPart` instead, so it is not a call here.
"""
builtin, native = _server_builtin(part)
if builtin:
@@ -1178,13 +1101,11 @@ def _local_round_id(part: dict):
def _flushes_local_pair(part: dict) -> bool:
- """`shouldFlushCompletedLocalToolPair`: a completed local call is its own round.
-
- A local tool card that already has its result is flushed both BEFORE and AFTER it, so
- two adjacent completed local calls replay as two sequential assistant/tool groups and
- not as one parallel group. Batching them made `group_turns`, the occurrence ordinals
- and the live-branch check all describe a transcript shape the request never sent.
- """
+ """`shouldFlushCompletedLocalToolPair`: a completed local call is its own round. A local tool
+ card that already has its result is flushed both BEFORE and AFTER it, so two adjacent
+ completed local calls replay as two sequential assistant/tool groups and not as one parallel
+ group. Batching them made `group_turns`, the occurrence ordinals and the live-branch check
+ all describe a transcript shape the request never sent."""
provenance = part.get("provenance")
if not isinstance(provenance, dict) or provenance.get("source") != "local":
return False
@@ -1196,37 +1117,35 @@ def _flushes_local_pair(part: dict) -> bool:
def _as_wire(messages: list[dict], sanitise_assistant: bool = True) -> list[dict]:
"""Persisted chat rows in the shape the inference layer sends them.
- The store keeps a tool call as a ``tool-call`` CONTENT PART carrying its own result,
- while the wire form is three messages: the assistant's `tool_calls`, a `tool` result,
- then the assistant's reply. Nothing put them back, and everything here reads the
- persisted rows as if they were wire messages, so an agent turn was invisible twice
- over. `group_turns` splits on `tool_calls`, which a persisted row never has, so the
- whole exchange folded into the preceding user group and the evicted tool group found
- no position of its own -- measured, seats came back empty and the exchange took
- MAX + 1, the number its own opening question already had. And `_live_transcript`
- probes these rows in the same shape, so the branch check compared a call/result/reply
- render against a row reading call/reply/result: measured, the archived agent turn
- failed the live-branch filter and NO query could return it, on every tool-using turn.
-
- The result is stripped from the call part and carried by the `tool` message instead,
- so `_probe_text` renders each piece exactly once and in the order `render_turn` wrote
- it. Only the id goes into `tool_calls`: the arguments stay on the content part, where
- `_probe_text` already offers both JSON spellings, and `_is_injected` still sees the id
- it filters our own injections by.
-
- `sanitise_assistant` is the STORED side of that comparison. A caller projecting the
- request's own messages against something written WITHOUT this projection must pass
- False: `_branch_boundary_anchor` records an anchor straight off the request, so
- `_archive_as_wire` has to hand the same bytes back or the rebase stops matching.
+ The store keeps a tool call as a ``tool-call`` CONTENT PART carrying its own result, while the
+ wire form is three messages: the assistant's `tool_calls`, a `tool` result, then the assistant's
+ reply. Nothing put them back, and everything here reads the persisted rows as if they were wire
+ messages, so an agent turn was invisible twice over. `group_turns` splits on `tool_calls`, which
+ a persisted row never has, so the whole exchange folded into the preceding user group and the
+ evicted tool group found no position of its own -- measured, seats came back empty and the
+ exchange took MAX + 1, the number its own opening question already had. And `_live_transcript`
+ probes these rows in the same shape, so the branch check compared a call/result/reply render
+ against a row reading call/reply/result: the archived agent turn failed the live-branch filter
+ and NO query could return it, on every tool-using turn.
+
+ The result is stripped from the call part and carried by the `tool` message instead, so
+ `_probe_text` renders each piece exactly once and in the order `render_turn` wrote it. Only the
+ id goes into `tool_calls`: the arguments stay on the content part, where `_probe_text` already
+ offers both JSON spellings, and `_is_injected` still sees the id it filters our own injections
+ by.
+
+ `sanitise_assistant` is the STORED side of that comparison. A caller projecting the request's
+ own messages against something written WITHOUT this projection must pass False:
+ `_branch_boundary_anchor` records an anchor straight off the request, so `_archive_as_wire` has
+ to hand the same bytes back or the rebase stops matching.
"""
wire: list[dict] = []
for message in messages:
content = message.get("content")
parts = content if isinstance(content, list) else None
- # Reasoning is not content: the serializer never puts it in `content`, but
- # `_probe_text` renders any part with a `text` field, so forwarding the stored list
- # put a model's thinking inline and the turn matched no transcript seat. Dropped
- # rather than moved, since nothing reads `reasoning_content` on the live side.
+ # Reasoning is not content: the serializer never puts it in `content`, but `_probe_text` renders any part with
+ # a `text` field, so forwarding the stored list put a model's thinking inline and the turn matched no
+ # transcript seat. Dropped rather than moved, since nothing reads `reasoning_content` on the live side.
if parts is not None and any(
isinstance(part, dict) and part.get("type") == "reasoning" for part in parts
):
@@ -1239,10 +1158,9 @@ def _as_wire(messages: list[dict], sanitise_assistant: bool = True) -> list[dict
if sanitise_assistant and str(message.get("role") or "") == "assistant":
content = _sanitised_assistant_content(content)
parts = content if isinstance(content, list) else None
- # A provider-side builtin with no native part is not replayed, so it is not a call
- # here either: counting it invented an exchange the request never carried. Any
- # other tool-call part takes the replay loop even when the serializer drops it,
- # since passthrough would keep it in `content` and render a call never sent.
+ # A provider-side builtin with no native part is not replayed, so it is not a call here either: counting it
+ # invented an exchange the request never carried. Any other tool-call part takes the replay loop even when the
+ # serializer drops it, since passthrough would keep it in `content` and render a call never sent.
calls = [
part
for part in (parts or [])
@@ -1257,11 +1175,10 @@ def _as_wire(messages: list[dict], sanitise_assistant: bool = True) -> list[dict
}
)
continue
- # Replayed the way `chat-adapter.ts` replays it: parts in order, flushing pending
- # calls whenever text arrives, so a row holding two rounds goes out as
- # call/result/text+call/result. Collecting every call into one message rebuilt a
- # different order, and the later calls took an invented ordinal. Text accumulated
- # before a flush rides ON that flush's call message, as it does live.
+ # Replayed the way `chat-adapter.ts` replays it: parts in order, flushing pending calls whenever text arrives,
+ # so a row holding two rounds goes out as call/result/text+call/result. Collecting every call into one message
+ # rebuilt a different order, and the later calls took an invented ordinal. Text accumulated before a flush
+ # rides ON that flush's call message, as it does live.
pending_calls: list[dict] = []
pending_text: list = []
# A one-slot box because `_flush` resets it and Python closures cannot rebind.
@@ -1283,13 +1200,13 @@ def _as_wire(messages: list[dict], sanitise_assistant: bool = True) -> list[dict
wire.append(entry)
for call in pending_calls:
if _server_builtin(call)[0]:
- # A builtin WITH a native part replays as a call and no `tool`
- # message: its result travels in the provider's own native part.
+ # A builtin WITH a native part replays as a call and no `tool` message: its result travels in the
+ # provider's own native part.
continue
if "result" not in call or call.get("result") is None:
- # Only an ABSENT result is absent. The serializer skips exactly
- # `undefined` and `null`, so treating "" / {} / [] as nothing dropped a
- # message the wire carries and left the run short of the archived one.
+ # Only an ABSENT result is absent. The serializer skips exactly `undefined` and `null`, so
+ # treating "" / {} / [] as nothing dropped a message the wire carries and left the run short of
+ # the archived one.
continue
wire.append(
{
@@ -1337,17 +1254,15 @@ def _fallback_ordinal(conn, scope: str, positions: Optional[list[list[str]]]) ->
"""Where a turn that matched no seat goes: past the archive AND past the transcript.
The two numbering spaces are different. Seats are TRANSCRIPT positions, while
- `next_archive_ordinal` counts what has been ARCHIVED, and the newest user group is
- protected from eviction, so during a long tool loop it is in the transcript and not
- in the archive. An in-flight tool group evicted before its assistant row is persisted
- matches no seat and took the archive's next number, which the user turn then claimed
- from the transcript: measured, both documents landed on ordinal 0, and since
- `created_at` breaks the tie the tool answer rendered ahead of the prompt that caused
- it, under the header saying a higher number was said later.
-
- The transcript length is the right floor because an unmatched group is unmatched for
- being newer than the saved rows. A gap in the numbering costs nothing: ordinals only
- have to order.
+ `next_archive_ordinal` counts what has been ARCHIVED, and the newest user group is protected
+ from eviction, so during a long tool loop it is in the transcript and not in the archive. An
+ in-flight tool group evicted before its assistant row is persisted matches no seat and took the
+ archive's next number, which the user turn then claimed from the transcript: measured, both
+ documents landed on ordinal 0, and since `created_at` breaks the tie the tool answer rendered
+ ahead of the prompt that caused it, under the header saying a higher number was said later.
+
+ The transcript length is the right floor because an unmatched group is unmatched for being newer
+ than the saved rows. A gap in the numbering costs nothing: ordinals only have to order.
"""
return max(store.next_archive_ordinal(conn, scope), len(positions or []))
@@ -1355,19 +1270,19 @@ def _fallback_ordinal(conn, scope: str, positions: Optional[list[list[str]]]) ->
def _transcript_positions(thread_id: str, branch = None) -> Optional[list[str]]:
"""The thread's saved messages as normalised probe text, in the order they were said.
- The ordinal has to come from the CONVERSATION, not from the moment a turn happened to
- be archived. Eviction is not strictly oldest-first: `truncate_oldest_messages` always
- protects the newest user group, so an agent turn's tool groups are evicted while the
- user message that opened them is held, and a pinned instruction is evicted only once
- it stops being pinned. Numbering by archive time then records the genuinely oldest
- turn as the newest, and `format_conversation_recall` states outright that the higher
- number "was said later and supersedes the earlier one". Measured before this: a
- standing instruction archived second came back as turn 3 of 3, presented to the model
- as superseding the two turns that actually followed it.
-
- Read from the persisted transcript rather than the request, because four of the five
- archive call sites pass the tool loop's already-fitted messages, whose indices shift
- as earlier groups drop out. `studio_db` holds the whole thread and is never truncated.
+ The ordinal has to come from the CONVERSATION, not from the moment a turn happened to be
+ archived. Eviction is not strictly oldest-first: `truncate_oldest_messages` always protects the
+ newest user group, so an agent turn's tool groups are evicted while the user message that opened
+ them is held, and a pinned instruction is evicted only once it stops being pinned. Numbering by
+ archive time then records the genuinely oldest turn as the newest, and
+ `format_conversation_recall` states outright that the higher number "was said later and
+ supersedes the earlier one". Measured before this: a standing instruction archived second came
+ back as turn 3 of 3, presented to the model as superseding the two turns that actually followed
+ it.
+
+ Read from the persisted transcript rather than the request, because four of the five archive
+ call sites pass the tool loop's already-fitted messages, whose indices shift as earlier groups
+ drop out. `studio_db` holds the whole thread and is never truncated.
"""
try:
from core.inference.context_window import group_turns
@@ -1377,8 +1292,8 @@ def _transcript_positions(thread_id: str, branch = None) -> Optional[list[str]]:
return None
if not messages:
return None
- # Grouped with the evictor's own grouper, so a position is a TURN's index, which is
- # what the ordinal is compared against.
+ # Grouped with the evictor's own grouper, so a position is a TURN's index, which is what the ordinal is compared
+ # against.
wire = _as_wire(_active_chain(messages, branch))
return [
[_normalise_cased(_probe_text(message)) for message in group]
@@ -1390,22 +1305,19 @@ def _transcript_positions(thread_id: str, branch = None) -> Optional[list[str]]:
def _occurrences(positions: Optional[list[list[str]]], group: list[dict]) -> list[int]:
"""Where this turn sits in the transcript, every time it was said.
- The WHOLE turn, not just its opening line. Matching on the first message alone made
- two different turns that merely start the same -- a repeated "continue", the same
- question re-asked, a regenerated reply -- claim each other's seats: measured, both
- were stamped with ordinal 0, and because each then believed it had two occurrences to
- fill, the next compaction wrote both of them AGAIN. Four documents for two turns,
- twice the recall slots spent on the same content, and the older answer quoted under
- the higher turn number, which the header presents as the one that supersedes.
-
- Compared as a prefix, because the transcript legitimately lags the evicted group: a
- turn is archived mid-request, before its own reply has been persisted. A turn that
- matches nothing yields no seats and falls back to the previous allocator, so this can
- never do worse than not looking.
-
- A list rather than one index because a conversation may legitimately contain the same
- turn twice, and the later occurrence is usually the one that matters -- "set X to 1",
- "set X to 2", "set X to 1" ends with X at 1.
+ The WHOLE turn, not just its opening line. Matching on the first message alone made two
+ different turns that merely start the same -- a repeated "continue", the same question re-asked,
+ a regenerated reply -- claim each other's seats: measured, both were stamped with ordinal 0, and
+ because each then believed it had two occurrences to fill, the next compaction wrote both of
+ them AGAIN. Four documents for two turns, twice the recall slots spent on the same content, and
+ the older answer quoted under the higher turn number, which the header presents as the one that
+ supersedes.
+
+ Compared as a prefix, because the transcript legitimately lags the evicted group: a turn is
+ archived mid-request, before its own reply has been persisted. A turn that matches nothing
+ yields no seats and falls back to the previous allocator, so this can never do worse than not
+ looking. A list rather than one index because a conversation may legitimately contain the same
+ turn twice, and the later occurrence is usually the one that matters.
"""
if not positions or not group:
return []
@@ -1415,16 +1327,13 @@ def _occurrences(positions: Optional[list[list[str]]], group: list[dict]) -> lis
calls = [bool(message.get("tool_calls")) for message in group]
def _same(stored: str, live: str, is_call: bool) -> bool:
- # A tool call is compared as needle in haystack, never for equality: the store
- # keeps arguments as an OBJECT and the request carries the model's raw string, so
- # `_probe_text` offers both JSON spellings for the stored copy and one for the live
- # one. Every other message is compared exactly.
- #
- # In two pieces when the whole needle does not fit, since the second spelling is
- # inserted BETWEEN the arguments and what followed them: a call with a preamble
- # renders live as name/args/text and stored as name/args/args/text, so the live
- # string is no longer contiguous. One split point, so this tolerates exactly the
- # one insertion `_probe_text` makes.
+ # A tool call is compared as needle in haystack, never for equality: the store keeps arguments as an OBJECT
+ # and the request carries the model's raw string, so `_probe_text` offers both JSON spellings for the stored
+ # copy and one for the live one. Every other message is compared exactly.
+ # In two pieces when the whole needle does not fit, since the second spelling is inserted BETWEEN the
+ # arguments and what followed them: a call with a preamble renders live as name/args/text and stored as
+ # name/args/args/text, so the live string is no longer contiguous. One split point, so this tolerates exactly
+ # the one insertion `_probe_text` makes.
if is_call:
if not live:
return False
@@ -1444,10 +1353,9 @@ def _occurrences(positions: Optional[list[list[str]]], group: list[dict]) -> lis
index
for index, position in enumerate(positions)
if position
- # A position SHORTER than the turn may only match the trailing one: `zip` stops at
- # the shorter side, so an orphan user row (a deleted reply, or a reload before the
- # reply was appended) prefix-matched and gave the answered turn two seats.
- # `>=` rather than `==`, since a position legitimately runs LONGER: `_archivable`
+ # A position SHORTER than the turn may only match the trailing one: `zip` stops at the shorter side, so an
+ # orphan user row (a deleted reply, or a reload before the reply was appended) prefix-matched and gave the
+ # answered turn two seats. `>=` rather than `==`, since a position legitimately runs LONGER: `_archivable`
# strips our injections and `_as_wire` expands one tool row into several messages.
and (len(position) >= len(texts) or index == len(positions) - 1)
and all(
@@ -1472,15 +1380,13 @@ def _write_copy(
) -> bool:
"""One more copy of an already-embedded turn, at the next unfilled seat.
- Only for topping up after a re-embed, which replaces a copy rather than adding one.
- Returns False when there is no seat left to fill, so the caller stops rather than
- allocating a fresh ordinal and putting a repeat at the end of its own conversation.
+ Only for topping up after a re-embed, which replaces a copy rather than adding one. Returns
+ False when there is no seat left to fill, so the caller stops rather than allocating a fresh
+ ordinal and putting a repeat at the end of its own conversation.
- ``span`` is the turn's size in the TRANSCRIPT and not ``len(group)``: `_archivable`
- strips a retrieval call and its result, so a group of three can span four live
- messages. Written short, the branch check bounds its run by the smaller figure and
- filters this copy out of every recall -- the same bug the primary write path was
- fixed for, reappearing on the top-up path.
+ ``span`` is the turn's size in the TRANSCRIPT and not ``len(group)``: `_archivable` strips a
+ retrieval call and its result, so a group of three can span four live messages. Written short,
+ the branch check bounds its run by the smaller figure and filters this copy out of every recall.
"""
copies = store.documents_by_hash(conn, scope, digest)
if not seats or len(copies) >= len(seats):
@@ -1506,8 +1412,8 @@ def _write_copy(
def _live_positions(live: Optional[list[dict]]) -> Optional[list[list[str]]]:
- """The fitted conversation grouped exactly as ``_transcript_positions`` groups the
- stored one, so a live turn can be matched by the same rules a stored seat is."""
+ """The fitted conversation grouped exactly as ``_transcript_positions`` groups the stored one,
+ so a live turn can be matched by the same rules a stored seat is."""
if live is None:
return None
try:
@@ -1530,25 +1436,23 @@ def _write_budget(
) -> int:
"""How many copies of a repeated turn the archive may hold RIGHT NOW.
- ``seats`` is every place the turn was said, which is what allocates ordinals, but it
- is the wrong number to spend on writes. A thread can hold the same turn twice with
- only the older one evicted; the archive then sees one stored copy against two seats,
- decides it is short, and writes a second document for the occurrence still sitting in
- the prompt. Both are then recallable, so identical text takes two of the four recall
- slots and one of them repeats what the model can already read.
-
- Counted against the LIVE conversation instead: a seat whose every message is still in
- the prompt has not been evicted and buys no write. When that turn is evicted later the
- budget rises on its own and the copy is written then, at its own ordinal.
-
- COUNTED, not tested for membership. A set of live texts cannot tell "one of three
- identical turns is still in the prompt" from "all three are", so every seat looked
- live and a turn said three times with two of them evicted was archived once. Counting
- the live occurrences with `_occurrences`, the same matcher that finds the seats,
- subtracts exactly as many as the prompt really holds.
-
- Floors at 1 so a turn whose seats cannot be told apart from live text is still stored;
- and with no ``live`` to compare against, this is exactly the old ``len(seats)``.
+ ``seats`` is every place the turn was said, which is what allocates ordinals, but it is the
+ wrong number to spend on writes. A thread can hold the same turn twice with only the older one
+ evicted; the archive then sees one stored copy against two seats, decides it is short, and
+ writes a second document for the occurrence still sitting in the prompt. Both are then
+ recallable, so identical text takes two of the four recall slots and one of them repeats what
+ the model can already read.
+
+ Counted against the LIVE conversation instead: a seat whose every message is still in the prompt
+ has not been evicted and buys no write. When that turn is evicted later the budget rises on its
+ own and the copy is written then, at its own ordinal.
+
+ COUNTED, not tested for membership: a set of live texts cannot tell "one of three identical
+ turns is still in the prompt" from "all three are", so every seat looked live and a turn said
+ three times with two of them evicted was archived once. Counting the live occurrences with
+ `_occurrences`, the same matcher that finds the seats, subtracts exactly as many as the prompt
+ really holds. Floors at 1 so a turn whose seats cannot be told apart from live text is still
+ stored; and with no ``live`` to compare against, this is exactly the old ``len(seats)``.
"""
if not seats:
return 1
@@ -1568,14 +1472,11 @@ def _retire_surplus(
) -> bool:
"""Delete copies of this turn the conversation no longer holds. True if any went.
- More copies than occurrences means a rewind removed one. The survivors are
- byte-identical, so the branch filter validates every copy against the single remaining
- occurrence and `recall` dedups on chunk id, which differs: measured, a recall slot went
- on quoting one turn twice, and the surplus kept an ordinal a genuinely later turn had
- since taken.
-
- Does nothing without seats, so a turn that failed to match its occurrences at all --
- an unreconstructable transcript, a thread with no persisted rows -- never loses a copy.
+ More copies than occurrences means a rewind removed one. The survivors are byte-identical, so
+ the branch filter validates every copy against the single remaining occurrence and `recall`
+ dedups on chunk id, which differs: measured, a recall slot went on quoting one turn twice, and
+ the surplus kept an ordinal a genuinely later turn had since taken. Does nothing without seats,
+ so a turn that failed to match its occurrences at all never loses a copy.
"""
if not seats:
return False
@@ -1602,18 +1503,18 @@ def _restamp(
) -> None:
"""Move existing copies of this turn onto the positions the transcript gives them.
- An archive written by an earlier build numbered turns as they arrived, and one written
- before the column existed has no number at all. Both keep an order that was never
- true, and `format_conversation_recall` states that the higher number was said later
- and supersedes the earlier one, so the block asserts it. Re-stamping at the next
- compaction lets those archives converge with no migration pass and no reindex: this is
- an UPDATE on rows that already exist, so nothing is duplicated.
-
- Called from BOTH archived paths. The cheap pre-check that runs before chunking fires
- on exactly the condition the write-lock branch does, so a restamp only in the latter
- was unreachable outside a race: measured, a forced-legacy archive still read NULL,NULL
- after a full re-compaction, and an archive-time order of 1,0 stayed 1,0 with the
- recall rendering the second turn first.
+ An archive written by an earlier build numbered turns as they arrived, and one written before
+ the column existed has no number at all. Both keep an order that was never true, and
+ `format_conversation_recall` states that the higher number was said later and supersedes the
+ earlier one, so the block asserts it. Re-stamping at the next compaction lets those archives
+ converge with no migration pass and no reindex: this is an UPDATE on rows that already exist, so
+ nothing is duplicated.
+
+ Called from BOTH archived paths. The cheap pre-check that runs before chunking fires on exactly
+ the condition the write-lock branch does, so a restamp only in the latter was unreachable
+ outside a race: measured, a forced-legacy archive still read NULL,NULL after a full
+ re-compaction, and an archive-time order of 1,0 stayed 1,0 with the recall rendering the second
+ turn first.
"""
if not seats:
return
@@ -1622,9 +1523,8 @@ def _restamp(
moved = False
for seat, copy in zip(seats, rows):
if skip_null and copy.get("archive_ordinal") is None:
- # A row archived before the column existed stays unnumbered, or it moves to
- # the end of its own conversation and the header calls the oldest statement
- # the latest one.
+ # A row archived before the column existed stays unnumbered, or it moves to the end of its own
+ # conversation and the header calls the oldest statement the latest one.
continue
if copy.get("archive_ordinal") != seat:
store.set_archive_ordinal(conn, copy["id"], seat)
@@ -1646,19 +1546,16 @@ def _stale_document(
):
"""The document id to replace, ``_ARCHIVED`` to skip, or None to write a new one.
- Hash alone is not enough, twice over.
-
- Dense search only reads documents whose recorded embedder matches the query's, so a
- turn archived under the previous model stays hashed-and-skipped while being invisible
- to every paraphrased search. Ingestion re-indexes in that case; so does this.
+ Hash alone is not enough, twice over. Dense search only reads documents whose recorded embedder
+ matches the query's, so a turn archived under the previous model stays hashed-and-skipped while
+ being invisible to every paraphrased search; ingestion re-indexes in that case, and so does
+ this.
- And a hash is not an identity when a user repeats themselves. ``occurrences`` is how
- many times this exact turn appears in the transcript, so a copy is only "already
- archived" once every occurrence has one. Without it the third turn of "set X to 1",
- "set X to 2", "set X to 1" was dropped on the floor: never indexed, so no query could
- reach it, and the recall then handed the model the superseded value under a header
- saying the higher turn number supersedes the lower. Measured: 3 turns in, 2 documents
- stored, and the block asserted X was 2.
+ And a hash is not an identity when a user repeats themselves. ``occurrences`` is how many times
+ this exact turn appears in the transcript, so a copy is only "already archived" once every
+ occurrence has one. Without it the third turn of "set X to 1", "set X to 2", "set X to 1" was
+ dropped on the floor: never indexed, so no query could reach it, and the recall then handed the
+ model the superseded value under a header saying the higher turn number supersedes the lower.
"""
copies = store.documents_by_hash(conn, scope, digest)
if not copies:
@@ -1685,15 +1582,15 @@ def _archived_under(
def _widen_span(conn, scope: str, digest: str, span: int) -> None:
"""Grow a stored turn's window when the same text reappears over a LONGER span.
- The digest is the rendered text, so two turns that read the same are one document,
- but their transcript spans can differ: `_archivable` strips a retrieval call and its
- result, so a three-message exchange and a four-message batch containing the same
- exchange render identically. Archived in that order, the second is skipped and keeps
- the first turn's span of three, and `_document_matches_one_run` then bounds its
- four-message live run by three and rejects it as off-branch, so no query returns it.
+ The digest is the rendered text, so two turns that read the same are one document, but their
+ transcript spans can differ: `_archivable` strips a retrieval call and its result, so a
+ three-message exchange and a four-message batch containing the same exchange render identically.
+ Archived in that order, the second is skipped and keeps the first turn's span of three, and
+ `_document_matches_one_run` then bounds its four-message live run by three and rejects it as
+ off-branch, so no query returns it.
- Only ever UPWARDS. The window is a maximum, so a larger one still matches the shorter
- turn, while narrowing it would break whichever turn was archived first.
+ Only ever UPWARDS. The window is a maximum, so a larger one still matches the shorter turn,
+ while narrowing it would break whichever turn was archived first.
"""
try:
conn.execute(
@@ -1732,57 +1629,47 @@ def has_archive(thread_id: str) -> bool:
def _normalise(text: str) -> str:
"""Probe text for comparison: trimmed at both ends, otherwise exactly as written.
- Case IS the edit. Lowercasing left a turn corrected only in capitalisation matching
- its archived copy, so `_document_matches_one_run` kept the pre-edit document live and
- a recall could answer with it: measured, `Foo` after it was corrected to `foo`, still
- validated. The two sides here are a stored render and the live text of the same
- messages, so there is no spelling difference to be tolerant of, and nothing else
- retires the stale copy -- the edit changes the digest, so it is written as a new
- document and the branch filter is the only thing that could have dropped the old one.
-
- `strip()` and not `rstrip()`, even though trimming each probe also discards leading
- indentation. Keeping leading whitespace looks tighter and is worse: `render_turn`
- strips the whole message, so a live turn beginning with a space or a newline then
- starts its run at a non-zero offset and `_document_matches_one_run` retires it.
- Measured, ` hello there` and a pasted block opening on a newline both went from
- live to retired, which is a silent loss of recall on exactly the pasted code that
- tends to matter.
-
- Indentation-only edits are therefore still tolerated, in both directions: probes are
- matched per line and as substrings, so leading whitespace never decides. Closing that
- needs the probe splitter to carry offsets, which is a bigger change than this bug
- warrants. Lexical search does its own tokenising and never reads this.
+ Case IS the edit. Lowercasing left a turn corrected only in capitalisation matching its archived
+ copy, so `_document_matches_one_run` kept the pre-edit document live and a recall could answer
+ with it. The two sides here are a stored render and the live text of the same messages, so there
+ is no spelling difference to be tolerant of, and nothing else retires the stale copy -- the edit
+ changes the digest, so it is written as a new document and the branch filter is the only thing
+ that could have dropped the old one.
+
+ `strip()` and not `rstrip()`, even though trimming each probe also discards leading indentation.
+ Keeping leading whitespace looks tighter and is worse: `render_turn` strips the whole message,
+ so a live turn beginning with a space or a newline then starts its run at a non-zero offset and
+ `_document_matches_one_run` retires it -- measured on ` hello there` and on a pasted block
+ opening on a newline, which is a silent loss of recall on exactly the pasted code that tends to
+ matter.
+
+ Indentation-only edits are therefore still tolerated, in both directions: probes are matched per
+ line and as substrings, so leading whitespace never decides. Closing that needs the probe
+ splitter to carry offsets, which is a bigger change than this bug warrants. Lexical search does
+ its own tokenising and never reads this.
"""
return (text or "").strip()
def _normalise_cased(text: str) -> str:
- """Whitespace-collapsed but CASE-PRESERVING, for transcript seat matching.
-
- `Set key Foo` and `Set key FOO` are two different turns: they hash differently, so the
- archive keeps a document for each. Folding case here made `_occurrences` hand BOTH
- seats to BOTH of them, and a turn that believes it has two occurrences to fill gets
- written twice at the next compaction. Measured: four documents for two turns, both
- stamped at both ordinals, and the recall unable to say which spelling was said later
- -- exactly the duplication the whole-turn comparison was added to stop. The two sides
- compared here are the same strings from the same thread, so there is no casing to be
- tolerant of; only the free-text branch filter, which compares a QUERY against saved
- text, still folds case.
- """
+ """Whitespace-collapsed but CASE-PRESERVING, for transcript seat matching. `Set key Foo` and
+ `Set key FOO` are two different turns: they hash differently, so the archive keeps a document
+ for each. Folding case here made `_occurrences` hand BOTH seats to BOTH of them, and a turn
+ that believes it has two occurrences to fill gets written twice at the next compaction --
+ four documents for two turns, both stamped at both ordinals, and the recall unable to say
+ which spelling was said later. The two sides compared here are the same strings from the same
+ thread, so there is no casing to be tolerant of; only the free-text branch filter, which
+ compares a QUERY against saved text, still folds case."""
return " ".join((text or "").split())
def _live_transcript(thread_id: str) -> Optional[list[str]]:
- """The thread's saved messages, one normalised string each, or None if it has none.
-
- Keeps recall on the branch the user is on. Editing a message rewinds the thread, but
- the archive is append-only and still holds the abandoned continuation's turns, so
- without this a recall can pull back a turn that never happened on this branch.
- Verified: after rewinding past a turn, querying its text still returned it.
-
- None means the thread has no saved transcript (an API client passing a thread_id
- without persisting), and the caller then does not filter: absence of evidence.
- """
+ """The thread's saved messages, one normalised string each, or None if it has none. Keeps recall
+ on the branch the user is on: editing a message rewinds the thread, but the archive is
+ append-only and still holds the abandoned continuation's turns, so without this a recall can
+ pull back a turn that never happened on this branch. None means the thread has no saved
+ transcript (an API client passing a thread_id without persisting), and the caller then does
+ not filter: absence of evidence."""
try:
from storage import studio_db
messages = studio_db.list_chat_messages(thread_id)
@@ -1790,8 +1677,8 @@ def _live_transcript(thread_id: str) -> Optional[list[str]]:
return None
if not messages:
return None
- # Through the same reconstruction: a persisted tool call read as ONE message renders in
- # a different order, and the in-order branch check then rejected every agent turn.
+ # Through the same reconstruction: a persisted tool call read as ONE message renders in a different order, and the
+ # in-order branch check then rejected every agent turn.
texts = [_normalise(_probe_text(message)) for message in _as_wire(messages)]
return [text for text in texts if text] or None
@@ -1801,20 +1688,18 @@ def branch_message_texts(
) -> Optional[list[str]]:
"""The ACTIVE branch, one normalised string PER MESSAGE, from the request's own messages.
- Per message rather than one blob, so the check stays inside the turn it is checking.
- Flattened, a probe can be satisfied by any later message repeating the words: an
- archived "Should I deploy? / No" whose answer was edited to "Yes" still matched
- because an unrelated later turn said "No". Reproduced before the split.
+ Per message rather than one blob, so the check stays inside the turn it is checking. Flattened,
+ a probe can be satisfied by any later message repeating the words: an archived "Should I deploy?
+ / No" whose answer was edited to "Yes" still matched because an unrelated later turn said "No".
- Preferred over ``_live_transcript`` wherever available: the stored rows are the whole
- message DAG, and retry/regenerate keep the replaced response as a sibling, so a
- thread-wide blob can validate a turn that is not on this branch. The client sends
- exactly one branch per request, and it is the same projection ``render_turn``
- archived from, so the probe compares like with like.
+ Preferred over ``_live_transcript`` wherever available: the stored rows are the whole message
+ DAG, and retry/regenerate keep the replaced response as a sibling, so a thread-wide blob can
+ validate a turn that is not on this branch. The client sends exactly one branch per request, and
+ it is the same projection ``render_turn`` archived from, so the probe compares like with like.
- ``roles`` narrows it to messages of those roles. The rolling window compares stored
- ASSISTANT rows, and against every role a short abandoned reply ("Done") matches a live
- user message that merely contains it ("not done yet").
+ ``roles`` narrows it to messages of those roles. The rolling window compares stored ASSISTANT
+ rows, and against every role a short abandoned reply ("Done") matches a live user message that
+ merely contains it ("not done yet").
"""
if roles:
messages = [
@@ -1827,21 +1712,17 @@ def branch_message_texts(
def message_text(content) -> str:
- """One stored message's content, normalised the way the branch check normalises it.
-
- Exposed so the rolling window compares stored messages on exactly these terms rather
- than inventing a second notion of "same text".
- """
+ """One stored message's content, normalised the way the branch check normalises it. Exposed so
+ the rolling window compares stored messages on exactly these terms rather than inventing a
+ second notion of "same text"."""
return _normalise(_probe_text({"content": content}))
def content_on_branch(content, transcript: Optional[list[str]]) -> bool:
- """Whether one stored message's text appears on the branch ``transcript`` describes.
-
- Shared with the rolling window, which has recall's problem: the stored rows are the
- whole DAG, so "the newest assistant turn" can belong to a sibling branch. Empty text
- counts as on-branch, since nothing to compare is not evidence of another branch.
- """
+ """Whether one stored message's text appears on the branch ``transcript`` describes. Shared with
+ the rolling window, which has recall's problem: the stored rows are the whole DAG, so "the
+ newest assistant turn" can belong to a sibling branch. Empty text counts as on-branch, since
+ nothing to compare is not evidence of another branch."""
if not transcript:
return True
text = _normalise(_probe_text({"content": content}))
@@ -1851,20 +1732,18 @@ def content_on_branch(content, transcript: Optional[list[str]]) -> bool:
_ROLE_PREFIX = re.compile(
r"^(?:user|assistant|system|developer|tool result|message):\s*", re.IGNORECASE
)
-# render_turn labels a tool call "assistant called <name>: <args>". The label is ours,
-# not the stored message's, so it comes off before the probe like any role prefix, or
-# every archived tool line misses and the turn looks rolled back. The name goes with it
-# when arguments follow; with none, the bare name is what the transcript has.
+# render_turn labels a tool call "assistant called <name>: <args>". The label is ours, not the stored message's, so it
+# comes off before the probe like any role prefix, or every archived tool line misses and the turn looks rolled back.
+# The name goes with it when arguments follow; with none, the bare name is what the transcript has.
_TOOL_CALL_PREFIX = re.compile(r"^assistant called (?:[^:\n]+:\s*)?", re.IGNORECASE)
-# The same label with the NAME captured, for the probe that has to keep it. Stripping the
-# label whole discarded which tool was called, so a retry that kept the arguments and
-# changed the tool (`terminal` to `python`) left the archived pre-edit turn matching.
-# `_probe_text` renders a live call as "<name> <arguments>", so the name is there to be
-# found; only our own "assistant called " wrapper and the colon are not.
+# The same label with the NAME captured, for the probe that has to keep it. Stripping the label whole discarded which
+# tool was called, so a retry that kept the arguments and changed the tool (`terminal` to `python`) left the archived
+# pre-edit turn matching. `_probe_text` renders a live call as "<name> <arguments>", so the name is there to be found;
+# only our own "assistant called " wrapper and the colon are not.
_TOOL_CALL_NAME = re.compile(r"^assistant called ([^:\n]+):\s*", re.IGNORECASE)
-# What may sit between two probes of the same message: nothing, or a label the probe had
-# stripped. A pasted transcript carries its own "user:" lines, so the gap is real there
-# and the turn is unedited. Any other text in that gap is content the archive never saw.
+# What may sit between two probes of the same message: nothing, or a label the probe had stripped. A pasted transcript
+# carries its own "user:" lines, so the gap is real there and the turn is unedited. Any other text in that gap is
+# content the archive never saw.
_GAP_IS_LABEL = re.compile(
r"^\s*(?:(?:user|assistant|system|developer|tool result|message):"
r"|assistant called (?:[^:\n]+:)?)?\s*$",
@@ -1873,35 +1752,28 @@ _GAP_IS_LABEL = re.compile(
def _probes_for(text: str) -> list[str]:
- """The lines of an archived chunk, normalised into things to look for on the branch.
-
- Substring containment on a normalised prefix rather than a digest match: the archived
- text came from the inference projection and the saved copy from the message store, so
- exact equality is too brittle. The role labels ``render_turn`` writes exist only in
- the archived copy, so they are stripped first, or every probe misses.
- """
+ """The lines of an archived chunk, normalised into things to look for on the branch. Substring
+ containment on a normalised prefix rather than a digest match: the archived text came from
+ the inference projection and the saved copy from the message store, so exact equality is too
+ brittle. The role labels ``render_turn`` writes exist only in the archived copy, so they are
+ stripped first, or every probe misses."""
probes = []
for line in (text or "").splitlines():
without_role = _ROLE_PREFIX.sub("", line)
named = _TOOL_CALL_NAME.match(without_role.strip())
if named:
- # Its own probe, ahead of the arguments, which is the order `_probe_text`
- # renders them in. Without it the arguments alone decided, and a call to a
- # different tool with the same arguments matched.
- #
- # Except "tool", which is `render_turn`'s own fallback for a call that
- # arrived without a name. The live text carries no name there either, so
- # requiring it would reject every one of those turns.
+ # Its own probe, ahead of the arguments, which is the order `_probe_text` renders them in. Without it the
+ # arguments alone decided, and a call to a different tool with the same arguments matched. Except "tool",
+ # which is `render_turn`'s own fallback for a call that arrived without a name: the live text carries no
+ # name there either, so requiring it would reject every one of those turns.
name = _normalise(named.group(1))
if name and name != "tool":
probes.append(name)
stripped = _normalise(_TOOL_CALL_PREFIX.sub("", without_role))
- # The WHOLE line, except where render_turn cut something short: a prefix probe
- # cannot see an edit past its cut-off, leaving a rewritten tail eligible.
- # Keyed off the marker, not a "tool result:" label: a long tool result is ONE
- # string of many newlines, so only its first line carries the label while the
- # marker is on its last, and nothing in a real transcript ends in the marker, so
- # every over-cap tool turn was rejected. Reproduced on a 400-line result.
+ # The WHOLE line, except where render_turn cut something short: a prefix probe cannot see an edit past its
+ # cut-off, leaving a rewritten tail eligible. Keyed off the marker, not a "tool result:" label: a long tool
+ # result is ONE string of many newlines, so only its first line carries the label while the marker is on its
+ # last, and nothing in a real transcript ends in the marker, so every over-cap tool turn was rejected.
if stripped.endswith(_TRUNCATION_MARKER.strip()):
stripped = stripped[: -len(_TRUNCATION_MARKER.strip())].strip()
probes.append(stripped)
@@ -1909,22 +1781,19 @@ def _probes_for(text: str) -> list[str]:
def _probe_entries(text: str) -> list[tuple[str, bool]]:
- """``_probes_for`` with a flag per line: was it cut short, or is it a tool call.
-
- Both mean the live message may legitimately hold more than the probe: a cut line is a
- prefix by construction, and a tool call is matched against a haystack that renders its
- arguments twice, spaced and compact, so only one of the two can ever be covered.
- """
+ """``_probes_for`` with a flag per line: was it cut short, or is it a tool call. Both mean the
+ live message may legitimately hold more than the probe: a cut line is a prefix by
+ construction, and a tool call is matched against a haystack that renders its arguments twice,
+ spaced and compact, so only one of the two can ever be covered."""
entries = []
for line in (text or "").splitlines():
without_role = _ROLE_PREFIX.sub("", line)
is_call = bool(_TOOL_CALL_PREFIX.match(without_role.strip()))
named = _TOOL_CALL_NAME.match(without_role.strip())
if named:
- # See `_probes_for`: the tool's NAME is a probe of its own, or the arguments
- # alone decide and a retry that swapped the tool still matches. Flagged as a
- # call so it keeps the haystack comparison the rest of the line gets.
- # "tool" is `render_turn`'s fallback for a nameless call; see `_probes_for`.
+ # See `_probes_for`: the tool's NAME is a probe of its own, or the arguments alone decide and a retry that
+ # swapped the tool still matches. Flagged as a call so it keeps the haystack comparison the rest of the
+ # line gets. "tool" is `render_turn`'s fallback for a nameless call.
name = _normalise(named.group(1))
if name and name != "tool":
entries.append((name, True))
@@ -1935,12 +1804,11 @@ def _probe_entries(text: str) -> list[tuple[str, bool]]:
if stripped:
entries.append((stripped, truncated or is_call))
elif truncated and entries:
- # The cut landed exactly on a line boundary, so the marker is a line of its
- # own and the line before it is the one that was cut short. Dropping the empty
- # marker dropped the flag with it, the last real probe was read as complete,
- # and `_document_matches_one_run` retired an unedited over-cap turn: measured
- # on a 900-line tool result whose 4000-character cut fell on a newline, the
- # live turn came back off-branch and no query could return it.
+ # The cut landed exactly on a line boundary, so the marker is a line of its own and the line before it is
+ # the one that was cut short. Dropping the empty marker dropped the flag with it, the last real probe was
+ # read as complete, and `_document_matches_one_run` retired an unedited over-cap turn: measured on a
+ # 900-line tool result whose cut fell on a newline, the live turn came back off-branch and no query could
+ # return it.
entries[-1] = (entries[-1][0], True)
return entries
@@ -1950,13 +1818,11 @@ def _on_live_branch(text: str, transcript: Optional[list[str]]) -> bool:
probes = _probes_for(text)
if not probes or not transcript:
return False
- # EVERY line, IN ORDER, WITHIN ONE RUN OF ADJACENT MESSAGES. All of a turn, because
- # it is archived as a unit and editing only the assistant half leaves the user line
- # matching. In order, because independent membership accepts rearranged lines. In one
- # bounded run, because a global scan lets any later message supply a missing line,
- # which is how "Should I deploy? / No" survived its answer becoming "Yes".
- # The window is the probe count; m messages render at least m lines, so a real turn
- # always fits.
+ # EVERY line, IN ORDER, WITHIN ONE RUN OF ADJACENT MESSAGES. All of a turn, because it is archived as a unit and
+ # editing only the assistant half leaves the user line matching. In order, because independent membership accepts
+ # rearranged lines. In one bounded run, because a global scan lets any later message supply a missing line, which
+ # is how "Should I deploy? / No" survived its answer becoming "Yes". The window is the probe count; m messages
+ # render at least m lines, so a real turn always fits.
window = len(probes)
return any(
_probes_match_from(probes, transcript, start, window) for start in range(len(transcript))
@@ -1966,19 +1832,19 @@ def _on_live_branch(text: str, transcript: Optional[list[str]]) -> bool:
def _scan_probes(
entries: list[tuple[str, bool]], messages: list[str], start: int, last: int
) -> Optional[tuple[int, int, int, bool, int]]:
- """Where the probes finish: message index, end offset, opening offset, tail-is-partial,
- and the message index the run OPENED on.
-
- An index rather than a bool so one document's chunks scan as a single pass, each
- continuing where the last stopped, which stops two chunks of a turn matching two
- places. The cursor within that message is NOT carried over: chunks overlap by
- ``CHUNK_OVERLAP``, so the next one legitimately repeats the previous tail.
-
- The opening index is reported because that repeated tail can begin in an EARLIER
- message than the one the previous chunk finished in -- a short line such as an
- assistant tool call just before a long tool result is carried into the next chunk
- whole. Resuming at the finishing message could then never match it, and an unedited
- document was retired as off-branch, which makes that turn unsearchable.
+ """Where the probes finish: message index, end offset, opening offset, tail-is-partial, and the
+ message index the run OPENED on.
+
+ An index rather than a bool so one document's chunks scan as a single pass, each continuing
+ where the last stopped, which stops two chunks of a turn matching two places. The cursor within
+ that message is NOT carried over: chunks overlap by ``CHUNK_OVERLAP``, so the next one
+ legitimately repeats the previous tail.
+
+ The opening index is reported because that repeated tail can begin in an EARLIER message than
+ the one the previous chunk finished in -- a short line such as an assistant tool call just
+ before a long tool result is carried into the next chunk whole. Resuming at the finishing
+ message could then never match it, and an unedited document was retired as off-branch, which
+ makes that turn unsearchable.
"""
index = start
cursor = 0
@@ -1990,25 +1856,21 @@ def _scan_probes(
while index < last:
found = messages[index].find(probe, cursor)
if found >= 0:
- # A message the run stepped INTO has to be accounted for from its first
- # character: an edit that prepends to it ("no" becoming "correction: no")
- # otherwise leaves every probe matching. A tool call is exempt, and the
- # exemption then covers the rest of that message: the store keeps a call
- # as a structured part, so the live text carries the tool name and BOTH
- # spellings of its arguments while the archived copy has one line of one
- # of them. Nothing there can line up character for character.
+ # A message the run stepped INTO has to be accounted for from its first character: an edit that
+ # prepends to it ("no" becoming "correction: no") otherwise leaves every probe matching. A tool call
+ # is exempt, and the exemption then covers the rest of that message: the store keeps a call as a
+ # structured part, so the live text carries the tool name and BOTH spellings of its arguments while
+ # the archived copy has one line of one of them, and nothing there can line up character for
+ # character.
if fresh and found != 0 and not partial_ok:
return None
- # And text inserted BETWEEN two probes of the same message. The two checks
- # around this one cover an edit that prepends to a message the run stepped
- # into and one that appends to a message it is leaving; a correction
- # dropped between two archived lines matched both of them with the new
- # line sitting unexamined in the gap, so the pre-edit turn stayed
- # recallable. Measured on "A\nB" becoming "A\ncorrection\nB".
- #
- # A gap is only allowed where it is a label `render_turn` wrote and the
- # probe therefore had stripped: a pasted transcript legitimately carries
- # its own "user:" lines. Anything else is content the archive never saw.
+ # And text inserted BETWEEN two probes of the same message. The two checks around this one cover an
+ # edit that prepends to a message the run stepped into and one that appends to a message it is
+ # leaving; a correction dropped between two archived lines matched both of them with the new line
+ # sitting unexamined in the gap, so the pre-edit turn stayed recallable (measured on "A\\nB" becoming
+ # "A\\ncorrection\\nB"). A gap is only allowed where it is a label `render_turn` wrote and the probe
+ # therefore had stripped: a pasted transcript legitimately carries its own "user:" lines, and anything
+ # else is content the archive never saw.
if (
not fresh
and cursor
@@ -2021,14 +1883,12 @@ def _scan_probes(
opened_at = 0 if partial_ok else found
opened_index = index
cursor = found + len(probe)
- # The exemption belongs to the CALL, not to the rest of the message. It
- # exists because a stored tool call cannot line up character for character
- # with the live text (the store keeps arguments as an object and offers
- # both JSON spellings), so the cursor after one is not exact. Once an
- # ordinary text probe has matched, the cursor IS exact again and the gap
- # and trailing-content checks can be enforced. Left sticky, an assistant
- # turn carrying both a call and text stayed matched after a correction was
- # appended to that text, so the pre-edit turn was still recallable.
+ # The exemption belongs to the CALL, not to the rest of the message. It exists because a stored tool
+ # call cannot line up character for character with the live text (the store keeps arguments as an
+ # object and offers both JSON spellings), so the cursor after one is not exact. Once an ordinary text
+ # probe has matched, the cursor IS exact again and the gap and trailing-content checks can be
+ # enforced. Left sticky, an assistant turn carrying both a call and text stayed matched after a
+ # correction was appended to that text, so the pre-edit turn was still recallable.
partial = partial_ok
fresh = False
break
@@ -2064,15 +1924,12 @@ def _probes_match_from(probes: list[str], messages: list[str], start: int, windo
def _rendered_message_count(rows) -> int:
- """How many messages the archived turn was rendered from.
-
- ``render_turn`` labels every message it writes, so labelled lines count messages. That
- bounds the run this document may occupy, far tighter than a line count: a two-message
- turn can be a hundred lines, and a hundred-message window finds its tail anywhere.
-
- Overlapping chunks can double-count a label, which only widens the window: the safe
- direction, since too narrow retires turns that are still live.
- """
+ """How many messages the archived turn was rendered from. ``render_turn`` labels every message
+ it writes, so labelled lines count messages. That bounds the run this document may occupy,
+ far tighter than a line count: a two-message turn can be a hundred lines, and a
+ hundred-message window finds its tail anywhere. Overlapping chunks can double-count a label,
+ which only widens the window: the safe direction, since too narrow retires turns that are
+ still live."""
total = 0
for row in rows:
for line in (row["text"] or "").splitlines():
@@ -2083,15 +1940,11 @@ def _rendered_message_count(rows) -> int:
def _document_on_live_branch(conn, document_id: str, transcript: list[str], cache: dict) -> bool:
- """Whether EVERY chunk of an archived turn is still on the branch.
-
- Per chunk is not enough: a turn over CHUNK_TOKENS spans several chunks, so editing the
- second half of a long answer leaves the untouched earlier chunks eligible on their
- own. The archived unit is the turn, so an edit to any part retires the whole copy.
-
- Cached per call: candidates from one turn share a document, and this is the filter's
- only query.
- """
+ """Whether EVERY chunk of an archived turn is still on the branch. Per chunk is not enough: a
+ turn over CHUNK_TOKENS spans several chunks, so editing the second half of a long answer
+ leaves the untouched earlier chunks eligible on their own. The archived unit is the turn, so
+ an edit to any part retires the whole copy. Cached per call: candidates from one turn share a
+ document, and this is the filter's only query."""
if document_id in cache:
return cache[document_id]
try:
@@ -2105,8 +1958,7 @@ def _document_on_live_branch(conn, document_id: str, transcript: list[str], cach
).fetchone()
message_count = row["archive_messages"] if row else None
except Exception:
- # Never fail a recall on the strictness pass: fall back to what the candidate
- # chunk itself said.
+ # Never fail a recall on the strictness pass: fall back to what the candidate chunk itself said.
cache[document_id] = True
return True
cache[document_id] = _document_matches_one_run(rows, transcript, message_count)
@@ -2118,23 +1970,19 @@ def _document_matches_one_run(
transcript: Optional[list[str]],
message_count: Optional[int] = None,
) -> bool:
- """Every chunk of the turn, found within ONE run of adjacent messages.
-
- Chunk by chunk independently is not enough: they are consecutive slices of one turn,
- so letting each pick its own place reassembles a turn from parts that never sat
- together (head on the current answer, tail on a later message repeating what the edit
- removed). Reproduced before the run was shared. The run is bounded by at least the
- number of messages the turn was rendered from, so a live turn always fits.
- """
+ """Every chunk of the turn, found within ONE run of adjacent messages. Chunk by chunk
+ independently is not enough: they are consecutive slices of one turn, so letting each pick
+ its own place reassembles a turn from parts that never sat together (head on the current
+ answer, tail on a later message repeating what the edit removed). The run is bounded by at
+ least the number of messages the turn was rendered from, so a live turn always fits."""
if not rows or not transcript:
return False
probe_lists = [_probe_entries(row["text"]) for row in rows]
if any(not probes for probes in probe_lists):
return False
- # The messages the turn was rendered from, not the lines it produced: bounding by
- # lines let a long answer's tail be satisfied far outside the turn. Recorded at
- # archive time; the label count is an approximate fallback for older documents, since
- # a pasted transcript contains lines that look like the renderer's own.
+ # The messages the turn was rendered from, not the lines it produced: bounding by lines let a long answer's tail
+ # be satisfied far outside the turn. Recorded at archive time; the label count is an approximate fallback for
+ # older documents, since a pasted transcript contains lines that look like the renderer's own.
window = (
int(message_count)
if message_count
@@ -2147,15 +1995,12 @@ def _document_matches_one_run(
cursor = 0
opened_at = None
partial_tail = False
- # How far back the NEXT chunk may restart. A chunk's leading overlap is the
- # previous chunk's tail, and `CHUNK_OVERLAP` can carry a whole short message with
- # it -- an assistant tool call sitting just before a long tool result. Resuming
- # strictly at the message the previous chunk FINISHED in then cannot match that
- # overlap, and an unedited document was retired as off-branch, which makes the
- # turn unsearchable: reproduced on a 4-message turn for 7 of 89 question lengths.
- # Never earlier than where the previous chunk itself opened, since the overlap
- # cannot predate it, and the forward position is always tried FIRST, so this only
- # ever rescues a scan that used to fail outright.
+ # How far back the NEXT chunk may restart. A chunk's leading overlap is the previous chunk's tail, and
+ # `CHUNK_OVERLAP` can carry a whole short message with it -- an assistant tool call sitting just before a long
+ # tool result. Resuming strictly at the message the previous chunk FINISHED in then cannot match that overlap,
+ # and an unedited document was retired as off-branch, which makes the turn unsearchable. Never earlier than
+ # where the previous chunk itself opened, since the overlap cannot predate it, and the forward position is
+ # always tried FIRST, so this only ever rescues a scan that used to fail outright.
floor = start
for probes in probe_lists:
found = None
@@ -2166,15 +2011,14 @@ def _document_matches_one_run(
if found is None:
return False
position, cursor, chunk_opened_at, partial_tail, floor = found
- # Where the whole run opened, which is the first chunk's answer: an edit that
- # prepends to the turn's FIRST message shows up here and nowhere else.
+ # Where the whole run opened, which is the first chunk's answer: an edit that prepends to the turn's FIRST
+ # message shows up here and nowhere else.
if opened_at is None:
opened_at = chunk_opened_at
- # And the turn has to cover the messages it claims, end to end. An edit that
- # keeps the old text and adds to it leaves every probe matching, whichever side it
- # adds on and whichever message it touches: "No" becoming "No, correction: yes" or
- # "Correction: no", or the question itself growing a clause. Either way the
- # pre-edit copy stayed eligible and could be recalled as the answer.
+ # And the turn has to cover the messages it claims, end to end. An edit that keeps the old text and adds to it
+ # leaves every probe matching, whichever side it adds on and whichever message it touches: "No" becoming "No,
+ # correction: yes" or "Correction: no", or the question itself growing a clause. Either way the pre-edit copy
+ # stayed eligible and could be recalled as the answer.
if opened_at:
return False
return partial_tail or cursor >= len(transcript[position])
@@ -2225,13 +2069,11 @@ def _conversation_order(row) -> tuple:
def _above_floor(hits: list, min_dense_score: float) -> list:
- """Candidates clearing the forced path's cosine floor. Off (0.0) returns them all.
-
- FORCED path only: an automatic lookup returning whatever shares a stopword with the
- question is worse than none, since that block is the model's first sight of the search
- tool. Lexical-only hits are kept, because gating them on a similarity they never
- carried would delete the exact-identifier hits this archive is best at.
- """
+ """Candidates clearing the forced path's cosine floor. Off (0.0) returns them all. FORCED path
+ only: an automatic lookup returning whatever shares a stopword with the question is worse
+ than none, since that block is the model's first sight of the search tool. Lexical-only hits
+ are kept, because gating them on a similarity they never carried would delete the
+ exact-identifier hits this archive is best at."""
if min_dense_score <= 0:
return hits
return [hit for hit in hits if hit.dense_score is None or hit.dense_score >= min_dense_score]
@@ -2240,28 +2082,24 @@ def _above_floor(hits: list, min_dense_score: float) -> list:
def _ends_first_within_ties(conn, hits: list) -> list:
"""Reorder each run of EQUAL lexical scores as newest, oldest, next-newest, ...
- A tie is not an order. FTS5 floors the IDF of a term appearing in more than half the
- index at 1e-6, so in a per-thread archive every turn naming the subject of the
- conversation can score identically -- measured at ONE distinct bm25 across eight
- revisions of the same variable. The candidate list then arrives in rowid order, the
- caller truncates it at `top_k`, and the slots go to the OLDEST turns purely because
- SQLite emitted them first: the current value never reached the model, while
- `format_conversation_recall` told it a later turn supersedes an earlier one. A stale
- answer presented as the authoritative one is worse than a miss.
+ A tie is not an order. FTS5 floors the IDF of a term appearing in more than half the index at
+ 1e-6, so in a per-thread archive every turn naming the subject of the conversation can score
+ identically -- measured at ONE distinct bm25 across eight revisions of the same variable. The
+ candidate list then arrives in rowid order, the caller truncates it at `top_k`, and the slots go
+ to the OLDEST turns purely because SQLite emitted them first: the current value never reached
+ the model, while `format_conversation_recall` told it a later turn supersedes an earlier one. A
+ stale answer presented as the authoritative one is worse than a miss.
Newest-first outright is the obvious fix and it is wrong: measured, it fails BOTH
- `test_asking_what_it_was_originally_still_returns_the_first_assignment` -- the guard
- against a fix that just returns the latest thing it can find -- and the tie test
- below it. Both ends is what keeps "what is it now" and "what was it originally"
- answerable out of the same tied run.
-
- Only WITHIN a run of equal scores, so nothing ever moves past a chunk the ranking pass
- actually separated. Ordering is `_conversation_order`, so legacy NULL ordinals still
- count as oldest.
+ `test_asking_what_it_was_originally_still_returns_the_first_assignment` -- the guard against a
+ fix that just returns the latest thing it can find -- and the tie test below it. Both ends is
+ what keeps "what is it now" and "what was it originally" answerable out of the same tied run.
+ Only WITHIN a run of equal scores, so nothing ever moves past a chunk the ranking pass actually
+ separated. Ordering is `_conversation_order`, so legacy NULL ordinals still count as oldest.
"""
if not config.CONVERSATION_QUERY_FOCUS:
- # Reordering candidates is selection, not presentation, so it belongs behind the
- # rollback knob that promises an identical candidate set.
+ # Reordering candidates is selection, not presentation, so it belongs behind the rollback knob that promises
+ # an identical candidate set.
return hits
if len(hits) < 2:
return hits
@@ -2305,8 +2143,8 @@ def _lexical_pass(
oldest_first: bool = False,
) -> list:
if newest_first or oldest_first:
- # The archive's lexical legs are always mode "lexical", so this is the same call
- # one layer down, with the tie-break reversed.
+ # The archive's lexical legs are always mode "lexical", so this is the same call one layer down, with the
+ # tie-break reversed.
return _ends_first_within_ties(
conn,
retrieval.retrieve_lexical(
@@ -2342,37 +2180,34 @@ def _both_ends(oldest: list, newest: list) -> list:
def _focused_lexical(conn, scope: str, query: str, model, fetch: int) -> list:
"""Archive lexical candidates: the identifiers FILTER, the content words RANK.
- The identifier pass cannot also do the ranking. FTS5 floors the BM25 IDF of a term
- that appears in more than half of the index at 1e-6 (`ext/fts5/fts5_aux.c`: "if
- (N < 2*nHit), the IDF is negative. Which is undesirable. So the minimum allowable IDF
- is (1e-6)"), and in a per-thread archive the identifier the whole conversation is
- about is exactly such a term. Its hits therefore come back in an order that carries
- no information, so cutting that pass off at ``fetch`` drops turns effectively at
- random -- measured on a 20-turn archive naming one variable, the turn stating its
- current value fell outside the 16 candidates and the recall answered with the four
- oldest turns instead.
-
- So the identifiers decide WHICH chunks are eligible and the content-word pass decides
- the order among them. Chunks the ranking pass never saw keep their place behind the
- ones it did, and chunks that match only the content words stay last, which is what
- keeps every slot on the subject of the question.
+ The identifier pass cannot also do the ranking. FTS5 floors the BM25 IDF of a term that appears
+ in more than half of the index at 1e-6 (`ext/fts5/fts5_aux.c`), and in a per-thread archive the
+ identifier the whole conversation is about is exactly such a term. Its hits therefore come back
+ in an order that carries no information, so cutting that pass off at ``fetch`` drops turns
+ effectively at random -- measured on a 20-turn archive naming one variable, the turn stating its
+ current value fell outside the 16 candidates and the recall answered with the four oldest turns
+ instead.
+
+ So the identifiers decide WHICH chunks are eligible and the content-word pass decides the order
+ among them. Chunks the ranking pass never saw keep their place behind the ones it did, and
+ chunks that match only the content words stay last, which is what keeps every slot on the
+ subject of the question.
"""
expressions = (
store.conversation_match_queries(query) if config.CONVERSATION_QUERY_FOCUS else [None]
)
- # Only the kill switch takes the plain path. A query made ONLY of an identifier shapes
- # to a single expression, and returning here would hand the query most likely to tie on
- # the IDF floor the one-ended fetch the comment below exists to prevent.
+ # Only the kill switch takes the plain path. A query made ONLY of an identifier shapes to a single expression, and
+ # returning here would hand the query most likely to tie on the IDF floor the one-ended fetch the comment below
+ # exists to prevent.
if not expressions or expressions[0] is None:
return _lexical_pass(conn, scope, query, model, fetch, None)
- # Fetched from BOTH ENDS of the tied run, not just the front. Every hit on the
- # conversation's own identifier scores the same on the IDF floor and SQLite returns a
- # tied run in rowid order, so `LIMIT 256` is "the oldest 256": on a 300-turn archive
- # the window held ordinals 0-255 and the last turn's value was unreachable. Half from
+ # Fetched from BOTH ENDS of the tied run, not just the front. Every hit on the conversation's own identifier
+ # scores the same on the IDF floor and SQLite returns a tied run in rowid order, so `LIMIT 256` is "the oldest
+ # 256": on a 300-turn archive the window held ordinals 0-255 and the last turn's value was unreachable. Half from
# each end keeps "what is it now" and "what was it originally" both answerable.
_newest_half = _BRANCH_FILTER_MAX_CANDIDATES // 2
- # Re-ordered over the MERGED run, not per half: concatenating two ends-first halves
- # leaves the newest end behind a full window of old turns.
+ # Re-ordered over the MERGED run, not per half: concatenating two ends-first halves leaves the newest end behind a
+ # full window of old turns.
strict = _ends_first_within_ties(
conn,
_both_ends(
@@ -2390,16 +2225,14 @@ def _focused_lexical(conn, scope: str, query: str, model, fetch: int) -> list:
),
),
)
- # One expression means the two passes would run the same query twice: the filter pass
- # already IS the ranking pass, and it is ends-first over both halves.
+ # One expression means the two passes would run the same query twice: the filter pass already IS the ranking pass,
+ # and it is ends-first over both halves.
if len(expressions) < 2:
return strict
- # The ranking pass is fetched to the same bound as the filter pass, not to `fetch`. It
- # ranks the ELIGIBLE chunks, and at `fetch` rows its window can be spent entirely on
- # chunks that never name the identifier, since a content word ("current") is ordinary
- # English: nothing eligible is left to order and the answer is dropped. Two-ended for
- # the same reason, and it matters MORE here, because the merged order comes from this
- # pass.
+ # The ranking pass is fetched to the same bound as the filter pass, not to `fetch`. It ranks the ELIGIBLE chunks,
+ # and at `fetch` rows its window can be spent entirely on chunks that never name the identifier, since a content
+ # word ("current") is ordinary English: nothing eligible is left to order and the answer is dropped. Two-ended for
+ # the same reason, and it matters MORE here, because the merged order comes from this pass.
_loose_k = max(fetch, _BRANCH_FILTER_MAX_CANDIDATES)
_loose_newest = _loose_k // 2
loose = _ends_first_within_ties(
@@ -2419,17 +2252,17 @@ def _focused_lexical(conn, scope: str, query: str, model, fetch: int) -> list:
),
),
)
- # Eligibility is asked of the index, not read off the strict pass's top rows: that pass
- # is capped and arbitrarily ordered, so past `_BRANCH_FILTER_MAX_CANDIDATES` chunks on
- # the subject the turn stating the current value can be the one left out.
+ # Eligibility is asked of the index, not read off the strict pass's top rows: that pass is capped and arbitrarily
+ # ordered, so past `_BRANCH_FILTER_MAX_CANDIDATES` chunks on the subject the turn stating the current value can be
+ # the one left out.
eligible = {hit.chunk_id for hit in strict}
try:
eligible |= store.lexical_matching_ids(
conn, [hit.chunk_id for hit in loose], expressions[0]
)
except Exception:
- # An exact membership test is an improvement, not a dependency: the strict rows on
- # their own are what this did before.
+ # An exact membership test is an improvement, not a dependency: the strict rows on their own are what this did
+ # before.
logger.warning("conversation_archive.eligibility_probe_failed", exc_info = True)
ranked = [hit for hit in loose if hit.chunk_id in eligible]
already = {hit.chunk_id for hit in ranked}
@@ -2440,17 +2273,13 @@ def _focused_lexical(conn, scope: str, query: str, model, fetch: int) -> list:
def _candidates(conn, scope: str, query: str, model, fetch: int, thread_id: str) -> list:
- """Up to ``fetch`` archive chunks for ``query``: lexical first, hybrid for the rest.
-
- The lexical pass runs TWICE when the question contains an identifier: once requiring
- one of them, then once over the content words. Requiring them is what stops an
- incidental word in the question outranking the subject of the whole conversation (see
- `store.conversation_match_queries`); running the permissive pass as well is what
- orders the survivors and what stops a filter that matches nothing from reading
- as an empty archive (see `_focused_lexical`). The merged list is what the caller's
- widening loop measures, so a filter returning few rows cannot be mistaken for
- "nothing left to widen into".
- """
+ """Up to ``fetch`` archive chunks for ``query``: lexical first, hybrid for the rest. The lexical
+ pass runs TWICE when the question contains an identifier: once requiring one of them, then
+ once over the content words. Requiring them is what stops an incidental word in the question
+ outranking the subject of the whole conversation; running the permissive pass as well is what
+ orders the survivors and what stops a filter that matches nothing from reading as an empty
+ archive. The merged list is what the caller's widening loop measures, so a filter returning
+ few rows cannot be mistaken for "nothing left to widen into"."""
hits: list = []
seen: set = set()
for hit in _focused_lexical(conn, scope, query, model, fetch):
@@ -2471,8 +2300,8 @@ def _candidates(conn, scope: str, query: str, model, fetch: int, thread_id: str)
if len(hits) >= fetch:
break
except Exception:
- # Dense retrieval raises rather than degrading when no embedder can start.
- # The lexical hits stand on their own, so this top-up may fail.
+ # Dense retrieval raises rather than degrading when no embedder can start. The lexical hits stand on their
+ # own, so this top-up may fail.
logger.warning(
"conversation_archive.dense_unavailable thread_id=%s", thread_id, exc_info = True
)
@@ -2490,18 +2319,17 @@ def recall(
) -> Optional[tuple[str, list[dict]]]:
"""Most relevant archived turns for ``query``, rendered like any other RAG hit.
- LEXICAL FIRST, then hybrid for the rest of the budget. Recalling your own conversation
- is mostly exact match (a name, a number, a code pasted twenty turns ago), which lives
- or dies on rare tokens. Measured on a 30-turn walkthrough with identical boilerplate
- per turn: the needle chunk ranked 3rd lexically at any k, was never returned by dense
- retrieval at all, and RRF fusion pushed it to 16th behind 30 useless dense hits.
- Hybrid alone lost the answer. Dense still earns its place for paraphrased recall, so
- it fills whatever the lexical pass leaves.
-
- No relevance floor, unlike ``tool.search_for_autoinject``: its 0.70 cosine gate keeps
- off-topic documents out, but here the passages ARE this conversation and the
- alternative to a weak match is no memory at all. It also keeps lexical-only hits,
- since ``filter_min_score`` only gates hits carrying a dense score.
+ LEXICAL FIRST, then hybrid for the rest of the budget. Recalling your own conversation is mostly
+ exact match (a name, a number, a code pasted twenty turns ago), which lives or dies on rare
+ tokens. Measured on a 30-turn walkthrough with identical boilerplate per turn: the needle chunk
+ ranked 3rd lexically at any k, was never returned by dense retrieval at all, and RRF fusion
+ pushed it to 16th behind 30 useless dense hits. Dense still earns its place for paraphrased
+ recall, so it fills whatever the lexical pass leaves.
+
+ No relevance floor, unlike ``tool.search_for_autoinject``: its cosine gate keeps off-topic
+ documents out, but here the passages ARE this conversation and the alternative to a weak match
+ is no memory at all. It also keeps lexical-only hits, since ``filter_min_score`` only gates hits
+ carrying a dense score.
"""
query = (query or "").strip()
if not thread_id or not query or not enabled():
@@ -2510,10 +2338,10 @@ def recall(
scope = store.conversation_archive_scope(thread_id)
limit = top_k or config.CONVERSATION_ARCHIVE_TOP_K
- # Two queries rather than one concatenated string, which would recreate the defect the
- # shaped query fixes: the filler's tokens dilute the instruction's identifiers and the
- # conjunctive pass would AND two unrelated intents. Run separately, each is shaped on
- # its own and spends its own half of the budget; at a limit of one the anchor wins.
+ # Two queries rather than one concatenated string, which would recreate the defect the shaped query fixes: the
+ # filler's tokens dilute the instruction's identifiers and the conjunctive pass would AND two unrelated intents.
+ # Run separately, each is shaped on its own and spends its own half of the budget; at a limit of one the anchor
+ # wins.
queries = [query] + [q.strip() for q in (extra_queries or []) if (q or "").strip()]
if len(queries) > 1:
share = max(1, -(-limit // len(queries)))
@@ -2524,10 +2352,9 @@ def recall(
room = limit - len(merged) if index == len(queries) - 1 else share
if room <= 0:
break
- # Over-fetched by what is already held, because the cut used to happen BEFORE
- # the dedup: two queries from the same thread overlap by construction, so every
- # shared chunk cost a slot that was never refilled and adding the anchor made
- # the recall smaller than leaving it out.
+ # Over-fetched by what is already held, because the cut used to happen BEFORE the dedup: two queries from
+ # the same thread overlap by construction, so every shared chunk cost a slot that was never refilled and
+ # adding the anchor made the recall smaller than leaving it out.
found = recall(
thread_id,
one,
@@ -2538,11 +2365,10 @@ def recall(
if not found:
continue
fresh = [source for source in found[1] if source["chunkId"] not in seen_ids]
- # Re-sorted because the inner call orders its OWN slice chronologically, so a
- # widened fetch arrives oldest-first and its head would spend the refilled
- # slots on the oldest turns. By retrieval rank first, score second: the score
- # is rounded for display and identical across a tied run, so sorting on it
- # alone preserved the chronological order. Re-ordered chronologically below.
+ # Re-sorted because the inner call orders its OWN slice chronologically, so a widened fetch arrives
+ # oldest-first and its head would spend the refilled slots on the oldest turns. By retrieval rank first,
+ # score second: the score is rounded for display and identical across a tied run, so sorting on it alone
+ # preserved the chronological order. Re-ordered chronologically below.
fresh.sort(
key = lambda source: (
source.get("rank") if source.get("rank") is not None else 1 << 30,
@@ -2574,8 +2400,8 @@ def recall(
try:
conn = rag_db.get_connection()
model = config.effective_embedding_model()
- # The request's own branch first: the stored rows are the whole DAG. Falling back
- # to them still beats not filtering when the caller has no branch to offer.
+ # The request's own branch first: the stored rows are the whole DAG. Falling back to them still beats not
+ # filtering when the caller has no branch to offer.
transcript = branch_message_texts(branch_messages) or _live_transcript(thread_id)
fetch = limit * _BRANCH_FILTER_OVERFETCH
rows: dict = {}
@@ -2585,14 +2411,11 @@ def recall(
fetched = _candidates(conn, scope, query, model, fetch, thread_id)
if not fetched:
return None
- # The floor filters CANDIDATES, before the cut to `limit`. After the slice it
- # was a deletion instead: weak hits took the slots and were then removed, so at
- # a floor of 0.5 with four weak hits on top the forced recall returned nothing
- # where the unforced one returned 4.
- #
- # `exhausted` is read off the RAW fetch, or the widening loop would mistake "the
- # floor removed most of this page" for "the index has nothing more" and stop
- # one page early.
+ # The floor filters CANDIDATES, before the cut to `limit`. After the slice it was a deletion instead: weak
+ # hits took the slots and were then removed, so at a floor of 0.5 with four weak hits on top the forced
+ # recall returned nothing where the unforced one returned 4. `exhausted` is read off the RAW fetch, or the
+ # widening loop would mistake "the floor removed most of this page" for "the index has nothing more" and
+ # stop one page early.
exhausted = len(fetched) < fetch
candidates = _above_floor(fetched, min_dense_score)
if not candidates:
@@ -2624,8 +2447,8 @@ def recall(
len(hits),
len(candidates),
)
- # Enough live hits, or nothing more to widen into: an abandoned branch can
- # outrank the live one, but it cannot outrank it forever.
+ # Enough live hits, or nothing more to widen into: an abandoned branch can outrank the live one, but it
+ # cannot outrank it forever.
if len(hits) >= limit or exhausted or fetch >= _BRANCH_FILTER_MAX_CANDIDATES:
hits = hits[:limit]
break
@@ -2633,13 +2456,12 @@ def recall(
if not hits:
return None
if config.CONVERSATION_RECALL_ORDER == "chronological":
- # Retrieval rank, kept before the chronological sort throws it away. The
- # two-query merge refills its slots from these sources and score alone cannot
- # order them: it is rounded to four places, so on a tied archive every
- # candidate carries the SAME score and the refill takes the oldest.
+ # Retrieval rank, kept before the chronological sort throws it away. The two-query merge refills its slots
+ # from these sources and score alone cannot order them: it is rounded to four places, so on a tied archive
+ # every candidate carries the SAME score and the refill takes the oldest.
rank_of = {hit.chunk_id: rank for rank, hit in enumerate(hits)}
- # AFTER the top-k slice, never before: sorting first would make the slice take
- # the oldest turns rather than the most relevant ones.
+ # AFTER the top-k slice, never before: sorting first would make the slice take the oldest turns rather
+ # than the most relevant ones.
hits.sort(key = lambda hit: _conversation_order(rows.get(hit.chunk_id)))
text, sources = tool.format_conversation_recall(rows, hits)
for source in sources:
@@ -2676,14 +2498,14 @@ def _delete_scope_without_vec(
) -> int:
"""Delete a scope's text-bearing rows over a connection with no sqlite-vec.
- Deletion must not depend on the optional native extension. Archives are only WRITTEN
- while vec0 loads, but it can stop loading afterwards (a venv change, common on macOS),
- and a delete that silently does nothing leaves a deleted conversation on disk ready to
- answer again once vec0 returns.
+ Deletion must not depend on the optional native extension. Archives are only WRITTEN while vec0
+ loads, but it can stop loading afterwards (a venv change, common on macOS), and a delete that
+ silently does nothing leaves a deleted conversation on disk ready to answer again once vec0
+ returns.
- The chunks_vec rows are unreachable from here and left behind. They carry vectors, not
- text, and every read path resolves through ``chunks`` joined to ``documents``, both
- gone, so nothing can retrieve an orphan.
+ The chunks_vec rows are unreachable from here and left behind. They carry vectors, not text, and
+ every read path resolves through ``chunks`` joined to ``documents``, both gone, so nothing can
+ retrieve an orphan.
"""
conn = None
removed = 0
@@ -2718,13 +2540,12 @@ def _delete_scope_without_vec(
def delete_for_thread(thread_id: str, *, created_before: Optional[str] = None) -> int:
"""Drop a thread's archive. Called when the thread itself is deleted.
- ``created_before`` bounds the delete to documents archived before an ISO-8601 UTC
- instant, which is how a thread id that came BACK is handled. Skipping the scope
- wholesale spared the recreated chat's memory but also kept the deleted
- conversation's, under a live id with nothing left to sweep it: the endpoint reported
- success while the turns the user asked to delete stayed recallable in the new chat.
- Cutting at the moment the delete was accepted takes exactly the old conversation and
- leaves whatever the recreated thread has archived since.
+ ``created_before`` bounds the delete to documents archived before an ISO-8601 UTC instant, which
+ is how a thread id that came BACK is handled. Skipping the scope wholesale spared the recreated
+ chat's memory but also kept the deleted conversation's, under a live id with nothing left to
+ sweep it: the endpoint reported success while the turns the user asked to delete stayed
+ recallable in the new chat. Cutting at the moment the delete was accepted takes exactly the old
+ conversation and leaves whatever the recreated thread has archived since.
"""
if not thread_id:
return 0
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.py
index 73195e03d47..0a40c111905 100644
--- a/studio/backend/core/rag/embed_llama_server.py
+++ b/studio/backend/core/rag/embed_llama_server.py
@@ -3,15 +3,14 @@
"""GGUF embedder over the bundled llama.cpp, served via HTTP (no torch).
-Opt-in (``RAG_EMBED_BACKEND=llama-server``). Runs a dedicated
-``llama-server --embedding`` subprocess on its own port and calls its OpenAI-style
-``/v1/embeddings`` + ``/tokenize``, fully isolated from the chat backend.
-
-Device is ``auto`` (GPU when present, else CPU, falling back to CPU if a GPU start
-fails); ``RAG_EMBED_DEVICE`` forces it. We call only llama_cpp's *static* helpers
-(no torch), copying the instance-coupled bits locally, since constructing a
-``LlamaCppBackend`` runs an ``__init__`` reaper that kills any Unsloth llama-server
--- so each request re-spawns ours if it died (self-heal).
+Opt-in (``RAG_EMBED_BACKEND=llama-server``). Runs a dedicated ``llama-server --embedding``
+subprocess on its own port and calls its OpenAI-style ``/v1/embeddings`` + ``/tokenize``, fully
+isolated from the chat backend.
+
+Device is ``auto`` (GPU when present, else CPU, falling back to CPU if a GPU start fails);
+``RAG_EMBED_DEVICE`` forces it. We call only llama_cpp's *static* helpers (no torch), copying the
+instance-coupled bits locally, since constructing a ``LlamaCppBackend`` runs an ``__init__`` reaper
+that kills any Unsloth llama-server, so each request re-spawns ours if it died.
"""
from __future__ import annotations
@@ -226,17 +225,13 @@ class LlamaServerBackend:
@staticmethod
@lru_cache(maxsize = 8)
def _help_text(binary: str) -> str:
- """`llama-server --help`, cached. Ignore exit code (some builds exit
- non-zero on --help).
-
- On macOS, runs under the same loader environment as the real launch.
- Without it, a bundle that needs the search path dies in the loader
- here, and its error text reads as help output with no ``--embedding``
- in it, so the caller reports a build that lacks embeddings instead of a
- load failure. Elsewhere the probe keeps inheriting this process's
- environment exactly as it always has: the loader hole is macOS-only,
- and a probe that answers "does this build do embeddings" has no reason
- to run under a different environment than it did before.
+ """`llama-server --help`, cached. Ignore exit code (some builds exit non-zero on --help).
+
+ On macOS, runs under the same loader environment as the real launch. Without it, a bundle
+ that needs the search path dies in the loader here, and its error text reads as help output
+ with no ``--embedding`` in it, so the caller reports a build that lacks embeddings instead
+ of a load failure. Elsewhere the probe keeps inheriting this process's environment: the
+ loader hole is macOS-only.
"""
probe_env = None
if sys.platform == "darwin":
@@ -395,14 +390,13 @@ class LlamaServerBackend:
def _cached_snapshot_dir(repo_id: str) -> Path | None:
"""The snapshot ``refs/main`` names in the active hub cache, or None.
- Only that revision, because it is the one hf_hub_download serves; the remaining
- snapshot directories are commit hashes, which order by nothing, so choosing among
- them could serve a superseded model.
-
- A hit therefore pins the embedder to the cached revision until the cache itself
- changes. Deliberate: a stored embedding identity records no revision, so adopting
- republished weights would leave an index answering one model's queries with another
- model's documents."""
+ Only that revision, because it is the one hf_hub_download serves; the remaining snapshot
+ directories are commit hashes, which order by nothing, so choosing among them could serve a
+ superseded model. A hit therefore pins the embedder to the cached revision until the cache
+ itself changes -- deliberate, since a stored embedding identity records no revision and
+ adopting republished weights would leave an index answering one model's queries with another
+ model's documents.
+ """
from utils.hf_cache_settings import active_hf_hub_cache
from utils.paths import resolve_cached_repo_id_case
@@ -567,14 +561,14 @@ class LlamaServerBackend:
def _is_planned_family(model: str, repo_id: str, path: str) -> bool:
"""Whether ``path`` is one of the files the picker planned for ``model``.
- Compared by the path relative to the snapshot, which is the layout the
- record's repo-relative names already describe. Base names are not enough:
- a repo that files each quant in its own directory publishes
- ``Q8_0/model.gguf`` beside ``Q4_K_M/model.gguf``, and matching on the name
- alone would let a stale quant pass for the planned one.
+ Compared by the path relative to the snapshot, which is the layout the record's
+ repo-relative names already describe. Base names are not enough: a repo that files each
+ quant in its own directory publishes ``Q8_0/model.gguf`` beside ``Q4_K_M/model.gguf``, and
+ matching on the name alone would let a stale quant pass for the planned one.
- False when no family was recorded, which is every resolution written before
- it was stored, so the caller keeps its conservative answer on those."""
+ False when no family was recorded, which is every resolution written before it was stored,
+ so the caller keeps its conservative answer on those.
+ """
try:
from pathlib import PurePosixPath
from utils.embedding_model_settings import get_stored_gguf_files
@@ -705,12 +699,12 @@ class LlamaServerBackend:
def _arch_gated_gpu_ids(binary: str) -> list[int]:
"""GPU ids to pin the embedding child to, or [] when it needs no mask.
- Knowing a supported device exists is not enough: the child enumerates every
- ROCm agent, and that HSA enumeration is what dies on an uncovered GPU (#7624),
- so on a mixed host the gate passes on the dGPU and the server still crashes on
- the iGPU. Pin the survivors instead. Empty unless the gate is both known and
- actually narrowing: NVIDIA, CPU, Vulkan and macOS have no mapped_targets
- marker, and a build covering every card needs no pin."""
+ Knowing a supported device exists is not enough: the child enumerates every ROCm agent, and
+ that HSA enumeration is what dies on an uncovered GPU (#7624), so on a mixed host the gate
+ passes on the dGPU and the server still crashes on the iGPU. Pin the survivors instead.
+ Empty unless the gate is both known and actually narrowing: NVIDIA, CPU, Vulkan and macOS
+ have no mapped_targets marker, and a build covering every card needs no pin.
+ """
from core.inference.llama_cpp import LlamaCppBackend
return LlamaCppBackend._arch_gate_survivors(binary)
@@ -946,12 +940,10 @@ class LlamaServerBackend:
)
def _ensure_ready(self, model_name: str | None = None) -> None:
- """Guarantee a live server on ``model_name``, (re)spawning if needed.
- Double-checked so the current path takes no lock; self-heals after the
- chat reaper kills us and re-resolves after a Settings model change.
-
- One subprocess serves one GGUF, so a request pinned to a model the server
- is not serving respawns onto it rather than answering from the wrong
+ """Guarantee a live server on ``model_name``, (re)spawning if needed. Double-checked so the
+ current path takes no lock; self-heals after the chat reaper kills us and re-resolves
+ after a Settings model change. One subprocess serves one GGUF, so a request pinned to a
+ model the server is not serving respawns onto it rather than answering from the wrong
weights."""
if self._current(model_name):
return
@@ -1108,14 +1100,14 @@ class LlamaServerBackend:
return arr
def dim(self, *, model_name = None) -> int:
- """Embedding width, probed via a 1-text encode and cached per model
- (_resolve_model_path clears it when the effective repo changes).
-
- Under the same lock the request path uses, for the same reason: ``_dim``
- belongs to the one subprocess, so with two jobs pinned to models of
- different width, one could ready A, have the other switch to B and cache
- B's width, and then answer A with it. Reentrant, so the probe's own encode
- re-enters rather than deadlocking."""
+ """Embedding width, probed via a 1-text encode and cached per model (_resolve_model_path clears
+ it when the effective repo changes).
+
+ Under the same lock the request path uses, for the same reason: ``_dim`` belongs to the one
+ subprocess, so with two jobs pinned to models of different width, one could ready A, have
+ the other switch to B and cache B's width, and then answer A with it. Reentrant, so the
+ probe's own encode re-enters rather than deadlocking.
+ """
with self._operation(), self._serve_lock:
self._ensure_ready(model_name)
cached = self._dim
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.py
index 76f42f53971..e96494f73b5 100644
--- a/studio/backend/core/rag/embeddings.py
+++ b/studio/backend/core/rag/embeddings.py
@@ -1,22 +1,19 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Dense embedder facade dispatching to a process-wide backend from
-``config.EMBED_BACKEND`` (``auto`` picks by hardware): ``sentence-transformers``
-(torch) or ``llama-server`` (GGUF, no torch).
-
-Either way the embedder stays off the GPU unless asked: this one runs in the backend
-process, where a CUDA context outlives every unload, and the other runs in a child.
-See ``_device``.
-
-Backends produce different vectors, so switching requires rebuilding the index. We
-degrade to llama.cpp rather than crash when ST breaks on a machine: an init-time
-probe falls back before any vector is produced (so spaces can't mix), and a
-runtime ``encode`` failure swaps the process to llama-server for the rest of its
-life (KBs already embedded with ST should then be reindexed).
-
-Torch driver faults bypass Python handlers, so ``_load_device`` probes allocation
-in a child and falls back to CPU without changing the embedding space.
+"""Dense embedder facade dispatching to a process-wide backend from ``config.EMBED_BACKEND`` (``auto``
+picks by hardware): ``sentence-transformers`` (torch) or ``llama-server`` (GGUF, no torch).
+
+Either way the embedder stays off the GPU unless asked: this one runs in the backend process, where
+a CUDA context outlives every unload, and the other runs in a child. See ``_device``.
+
+Backends produce different vectors, so switching requires rebuilding the index. We degrade to
+llama.cpp rather than crash when ST breaks on a machine: an init-time probe falls back before any
+vector is produced (so spaces cannot mix), and a runtime ``encode`` failure swaps the process to
+llama-server for the rest of its life (KBs already embedded with ST should then be reindexed).
+
+Torch driver faults bypass Python handlers, so ``_load_device`` probes allocation in a child and
+falls back to CPU without changing the embedding space.
"""
from __future__ import annotations
@@ -58,23 +55,18 @@ _TORCH_DEVICE = {DeviceType.CUDA: "cuda", DeviceType.XPU: "xpu"}
def _device() -> str:
"""Torch device for the in-process embedder. CPU unless asked otherwise.
- Defaulting a GPU machine to CPU is deliberate. This embedder runs inside the
- backend process, and the first CUDA allocation there creates a primary context
- that is never returned while the process lives: measured at 712 MiB on a B200,
- against 74 MiB for bge-small's own weights. So ingesting one document used to
- cost most of a gigabyte of VRAM for the rest of the session, on a machine where
- the user had loaded no model at all, and no amount of unloading gets it back --
- ``del model; torch.cuda.empty_cache()`` returns none of it.
-
- The trade is real but small at the sizes this runs at. bge-small is a 33M parameter
- BERT: on the same host, one 128-token chunk takes 18.7ms on CPU against 5.2ms on
- CUDA, which is noise next to parsing and chunking the document it came from. Bulk
- indexing is where it shows, at batch 64: 445 chunks/s on CPU against 3174/s on CUDA.
+ Defaulting a GPU machine to CPU is deliberate: this embedder runs inside the backend process,
+ and the first CUDA allocation there creates a primary context never returned while the process
+ lives (712 MiB on a B200 against 74 MiB for bge-small's own weights), so ingesting one document
+ cost most of a gigabyte of VRAM for the session and no amount of unloading gets it back.
+
+ The trade is small at these sizes: one 128-token chunk takes 18.7ms on CPU against 5.2ms on
+ CUDA. Bulk indexing is where it shows (batch 64: 445 chunks/s on CPU against 3174/s), and
``RAG_EMBED_DEVICE=gpu`` opts back in for a large corpus.
- This reads the same setting as the llama-server backend but resolves ``auto``
- differently, which is intended: that backend offloads inside its own subprocess,
- where the context dies with the child and costs the backend nothing.
+ This reads the same setting as the llama-server backend but resolves ``auto`` differently, which
+ is intended: that backend offloads inside its own subprocess, where the context dies with the
+ child.
"""
if config.embed_device_preference() != "gpu":
return "cpu"
@@ -205,17 +197,16 @@ def _guard_model_security(
display: str | None = None,
) -> None:
"""Refuse to load a repo HF flagged as unsafe: a poisoned pickle deserializes inside
- SentenceTransformer regardless of trust_remote_code. Defense in depth behind the
- /settings gate (a name can also arrive via env/default); local paths and unreachable
- scans fail open inside evaluate_file_security. Never bricks the embedder on a gate error.
+ SentenceTransformer regardless of trust_remote_code. Defense in depth behind the /settings gate
+ (a name can also arrive via env/default); local paths and unreachable scans fail open inside
+ evaluate_file_security, and a gate error never bricks the embedder.
- ``local_only`` (offline) inspects the local cache; subdir probes are skipped (they'd hit the
- network and hang, and the offline gate walks the whole snapshot anyway).
+ ``local_only`` (offline) inspects the local cache; subdir probes are skipped, since they would
+ hit the network and hang and the offline gate walks the whole snapshot anyway.
- ``display`` names the model in the error. The scan runs on ``name``, which the caller has
- already resolved to an absolute snapshot directory, and that path reaches a user through
- /v1/embeddings; the configured model is what they can act on and what the rest of that
- route reports.
+ ``display`` names the model in the error. The scan runs on ``name``, already resolved to an
+ absolute snapshot directory, and that path reaches a user through /v1/embeddings; the configured
+ model is what they can act on.
"""
try:
from utils.security import evaluate_file_security, security_load_subdirs
@@ -255,15 +246,15 @@ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
class _CaptureLoadReport(logging.Filter):
"""Swallow transformers' multi-line "<Model> LOAD REPORT" table, keeping the text.
- transformers >= 5 emits the report through ``logger.warning`` with embedded ANSI
- colour codes, so it lands in the server log as ~7 unstructured lines that break
- every JSON consumer. It fires on every boot for the RAG embedder because
- bge-small-en-v1.5 ships a legacy ``embeddings.position_ids`` key that the current
- BertModel does not expect, which is benign and identical every time.
+ transformers >= 5 emits the report through ``logger.warning`` with embedded ANSI colour codes,
+ so it lands in the server log as ~7 unstructured lines that break every JSON consumer. It fires
+ on every boot for the RAG embedder because bge-small-en-v1.5 ships a legacy
+ ``embeddings.position_ids`` key the current BertModel does not expect, which is benign and
+ identical every time.
- Nothing is lost: the caller re-emits the report (see ``_quiet_transformers_load``)
- at debug when it only reports that known legacy key, and at warning when it
- mentions anything that could change the model's behaviour.
+ Nothing is lost: the caller re-emits the report (see ``_quiet_transformers_load``) at debug when
+ it only reports that known legacy key, and at warning when it mentions anything that could
+ change the model's behaviour.
"""
_SERIOUS = ("MISSING", "MISMATCH", "CONVERSION")
@@ -427,7 +418,6 @@ def _get(model_name: str | None = None):
local_only = offline or download_pending
with _lock:
if _model is None or _name != name:
- # Probe before loading sentence-transformers on the selected device.
device = _load_device()
_install_torchao_stub_once()
from sentence_transformers import SentenceTransformer
@@ -566,13 +556,12 @@ def _st_max_tokens(model_name: str | None = None) -> int | None:
def _st_token_counter(model_name: str | None = None) -> Callable[[str], int]:
- """Token counter using the model's tokenizer, under the compute lock (the same
- fast tokenizer backs encode and isn't thread-safe), with rayon enabled for the
- call. Mirrors ``_st_encode``: admission and model lookup are one lease, so the
- tokenizer is read per call inside the lock rather than captured here. Chunking
- holds this callable for a whole document, and a tokenizer captured up front
- outlives the unload that retired it -- counting on with weights nobody can
- reach, while the endpoint reports the model as gone."""
+ """Token counter using the model's tokenizer, under the compute lock (the same fast tokenizer
+ backs encode and is not thread-safe), with rayon enabled for the call. Mirrors
+ ``_st_encode``: admission and model lookup are one lease, so the tokenizer is read per call
+ inside the lock. Chunking holds this callable for a whole document, and a tokenizer captured
+ up front outlives the unload that retired it, counting on with weights nobody can reach while
+ the endpoint reports the model as gone."""
def _count(t: str) -> int:
with _compute_lock:
@@ -739,11 +728,11 @@ def _resolve_auto_for_model(model_name: str | None = None) -> str:
def sentence_transformers_runtime_available() -> bool:
"""Whether the ST backend can reach the model-loading step in this process.
- This deliberately mirrors the environment-dependent prefix of ``_get`` but
- does not construct a model (which could download the snapshot the picker is
- still planning). It catches missing/broken torch or sentence-transformers
- installs and the fatal device mismatch that ``_build_st_backend_or_fallback``
- would otherwise discover only after an ST-only plan was persisted.
+ Deliberately mirrors the environment-dependent prefix of ``_get`` but does not construct a
+ model, which could download the snapshot the picker is still planning. It catches missing/broken
+ torch or sentence-transformers installs and the fatal device mismatch that
+ ``_build_st_backend_or_fallback`` would otherwise discover only after an ST-only plan was
+ persisted.
"""
try:
_load_device()
@@ -759,7 +748,6 @@ def sentence_transformers_runtime_available() -> bool:
def _llama_server_runtime_available() -> bool:
- """Whether the fallback that ST construction would use can be built."""
try:
from core.inference.llama_cpp import LlamaCppBackend
return bool(LlamaCppBackend._find_llama_server_binary())
@@ -800,14 +788,14 @@ def _try_make_llama_backend():
def _build_st_backend_or_fallback(model_name: str | None = None):
- """Build the ST backend, probing it by loading the model now. If the probe
- raises (no torch, CUDA mismatch, bad wheel) and the GGUF llama-server embedder
- is available, fall back to it. The probe runs before any vector is produced, so
- this never mixes spaces. Re-raises if no embedder can start.
-
- ``model_name`` is the model the caller pinned. Warming ``None`` reads the live
- setting, so a job pinned to A probed B once Settings moved, failing the valid
- A job before its first encode."""
+ """Build the ST backend, probing it by loading the model now. If the probe raises (no torch, CUDA
+ mismatch, bad wheel) and the GGUF llama-server embedder is available, fall back to it; the probe
+ runs before any vector is produced, so this never mixes spaces. Re-raises if no embedder can
+ start.
+
+ ``model_name`` is the model the caller pinned. Warming ``None`` reads the live setting, so a job
+ pinned to A probed B once Settings moved, failing the valid A job before its first encode.
+ """
backend = _SentenceTransformersBackend()
try:
backend.warm(model_name = model_name)
@@ -892,7 +880,6 @@ def _backend_cache_key(raw: str, key: str) -> str:
def _dispose_replaced_backend(old, new = None) -> None:
- """Release resources owned by a backend that is no longer published."""
if old is None or old is new:
return
if isinstance(old, _SentenceTransformersBackend):
@@ -910,15 +897,15 @@ def _dispose_replaced_backend(old, new = None) -> None:
def _get_backend(model_name: str | None = None):
- """The process-wide embedding backend for ``config.EMBED_BACKEND``, built once.
- Cached by the resolved choice, so ``auto`` detection runs only on a miss and a
- config or saved-model change rebuilds it.
-
- ``model_name`` is the model the caller is embedding for, defaulting to the live
- setting. A job pins its model once and passes it down, and per-model stored
- backends mean two models can resolve differently: reading the setting here
- instead would let a Settings change mid-job build the NEW model's backend while
- ``encode_with_identity`` goes on labelling the vectors with the pinned one.
+ """The process-wide embedding backend for ``config.EMBED_BACKEND``, built once. Cached by the
+ resolved choice, so ``auto`` detection runs only on a miss and a config or saved-model change
+ rebuilds it.
+
+ ``model_name`` is the model the caller is embedding for, defaulting to the live setting. A job
+ pins its model once and passes it down, and per-model stored backends mean two models can
+ resolve differently: reading the setting here would let a Settings change mid-job build the NEW
+ model's backend while ``encode_with_identity`` goes on labelling the vectors with the pinned
+ one.
"""
global _backend, _backend_key
raw = _raw_backend()
@@ -965,10 +952,10 @@ def _reset_backend() -> None:
def backend_is_loaded(model_name: str | None = None) -> bool:
"""Whether ``model_name`` is resident, or any embedder when omitted.
- Deliberately lock-free: ``_backend_lock`` and ``_lock`` are both held across a
- whole model load, so taking either here made GET, PUT, reset and unload wait it
- out. Both reads are single attribute loads, and the pre- or post-load value is
- equally true for "is something resident right now".
+ Deliberately lock-free: ``_backend_lock`` and ``_lock`` are both held across a whole model load,
+ so taking either here made GET, PUT, reset and unload wait it out. Both reads are single
+ attribute loads, and the pre- or post-load value is equally true for "is something resident
+ right now".
"""
backend = _backend
if backend is None:
@@ -1022,18 +1009,17 @@ def release_backend() -> bool:
def active_backend_is_llama(model_name: str | None = None) -> bool:
"""True when this process actually embeds via the llama-server (GGUF) backend.
- Reflects the ACTUAL built backend once one exists: an ``auto`` install that
- resolves to sentence-transformers but then falls back to llama-server at
- runtime (``_build_st_backend_or_fallback`` on a torch/CUDA load failure, or
- ``_switch_to_llama_fallback`` on an encode failure) loads only inert GGUF, so
- callers gating on the ST pickle must see llama here. Before any backend is
- built, defers to the resolver (``auto`` -> ``_resolve_auto_for_model()``, else
- the raw key) exactly as a fresh process would.
-
- ``model_name`` names the model to resolve for, defaulting to the live setting.
- A caller embedding under a model pinned for the length of a job passes it, so
- the answer cannot drift when the setting changes underneath that job. Never
- raises: a backend probe must not block saving a model."""
+ Reflects the ACTUAL built backend once one exists: an ``auto`` install that resolves to
+ sentence-transformers but then falls back to llama-server at runtime
+ (``_build_st_backend_or_fallback`` on a torch/CUDA load failure, or
+ ``_switch_to_llama_fallback`` on an encode failure) loads only inert GGUF, so callers gating on
+ the ST pickle must see llama here. Before any backend is built, defers to the resolver exactly
+ as a fresh process would.
+
+ ``model_name`` names the model to resolve for, defaulting to the live setting; a caller
+ embedding under a model pinned for a job passes it so the answer cannot drift mid-job. Never
+ raises: a backend probe must not block saving a model.
+ """
try:
with _backend_lock:
backend = _backend
@@ -1065,17 +1051,14 @@ def _identity(is_llama: bool, name: str) -> str:
def _identity_backend_is_llama(name: str) -> bool:
"""Backend the next encode for ``name`` will use.
- The security-facing active-backend probe deliberately reports a resident
- backend even when Settings has just selected another one. Identity prediction
- is different: ``_get_backend`` will replace a resident backend whose cache key
- no longer matches the stored per-model resolution, so admission/deduplication
- must predict that replacement before the first encode happens.
-
- ``name`` is threaded into the probe rather than left to default: it may be a
- model pinned for the length of one job (a linked-folder reconcile resolves the
- model once and embeds every file under it), and re-reading the live setting per
- file would let a Settings change mid-job tag two files in one folder with two
- different identities.
+ The security-facing active-backend probe deliberately reports a resident backend even when
+ Settings has just selected another one. Identity prediction is different: ``_get_backend`` will
+ replace a resident backend whose cache key no longer matches the stored per-model resolution, so
+ admission/deduplication must predict that replacement before the first encode happens.
+
+ ``name`` is threaded into the probe rather than left to default: it may be a model pinned for
+ the length of one job, and re-reading the live setting per file would let a Settings change
+ mid-job tag two files in one folder with two different identities.
"""
try:
raw = _raw_backend()
@@ -1105,7 +1088,6 @@ def embedding_identity(model_name: str | None = None) -> str:
def _is_llama_backend(backend) -> bool:
- """Whether a concrete backend object embeds through llama-server."""
try:
from .embed_llama_server import LlamaServerBackend
except Exception: # noqa: BLE001 - llama plumbing import must never block
@@ -1167,7 +1149,6 @@ def encode(
def dim(model_name: str | None = None) -> int:
- """Embedding dimension for the (loaded) model."""
return _get_backend(model_name).dim(model_name = model_name)
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index 5c5c604b2e9..d7cf5669509 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -117,35 +117,24 @@ def _is_identifier(token: str, raw_tokens: frozenset[str]) -> bool:
def conversation_match_queries(query: str) -> list[str]:
"""FTS5 expressions for searching a CONVERSATION ARCHIVE, most selective first.
- Why the archive needs its own query shaping, when `_match_query` is fine everywhere
- else: in a per-thread archive the SUBJECT of the conversation is by construction
- present in many chunks, so BM25 gives it almost no weight, while an incidental word
- from the question appears once and dominates. Measured on an archive of 17 chunks
- about one variable: `zqxvara123` scored 0.16 and `value`, from "what is the current
- value of X", scored 4.755. ORing them lets the filler decide the ranking, and a chunk
- about "a good default value for a retry budget" outranks every chunk that names the
- variable. The subject of a long conversation becomes the least discriminative term in
- its own archive.
-
- So: first REQUIRE the identifier-like tokens, which restricts the candidates to
- chunks that are actually about the thing asked about; then fall back to an OR over
- the content words. Two expressions rather than one, because a filter that matches
- nothing must not mean "this archive has nothing to say".
-
- A question made entirely of function words ("what about it?") keeps all its tokens:
- an empty expression would make `search_lexical` return nothing at all, and a query
- that retrieves the wrong turns is still better than a recall that silently vanishes
- on exactly the turns that needed it.
-
- SEVERAL identifiers are ORed, not ANDed. "What are the current values of A123 and
- B456" is two questions in one envelope, and the turn answering either one names one
- of them: requiring both keeps only the turns that DISCUSS the pair, which are exactly
- the older comparisons, and drops both current assignments. Measured on an archive of
- six comparison turns plus one latest assignment each: the conjunction returned the
- four oldest comparisons and neither value, where the permissive pass returns both.
- The filter's job is to keep every slot on something the question asked about, and one
- identifier out of two is still that; the content-word pass still does the ranking,
- and a chunk naming both still outranks a chunk naming one, because it matches more.
+ Why the archive needs its own query shaping when `_match_query` is fine everywhere else: in a
+ per-thread archive the SUBJECT of the conversation is by construction present in many chunks, so
+ BM25 gives it almost no weight, while an incidental word from the question appears once and
+ dominates. Measured on an archive of 17 chunks about one variable: `zqxvara123` scored 0.16 and
+ `value`, from "what is the current value of X", scored 4.755, so ORing them lets the filler
+ decide the ranking.
+
+ So: first REQUIRE the identifier-like tokens, which restricts the candidates to chunks actually
+ about the thing asked about; then fall back to an OR over the content words. Two expressions
+ rather than one, because a filter that matches nothing must not mean "this archive has nothing
+ to say". A question made entirely of function words keeps all its tokens, since an empty
+ expression would make `search_lexical` return nothing at all.
+
+ SEVERAL identifiers are ORed, not ANDed. "What are the current values of A123 and B456" is two
+ questions in one envelope, and the turn answering either one names one of them: requiring both
+ keeps only the turns that DISCUSS the pair and drops both current assignments (measured on six
+ comparison turns plus one latest assignment each). The filter's job is to keep every slot on
+ something the question asked about, and the content-word pass still does the ranking.
"""
tokens = list(dict.fromkeys(_TOKEN.findall(query.lower())))
if not tokens:
@@ -555,12 +544,11 @@ def search_lexical(
newest_first: bool = False,
oldest_first: bool = False,
):
- """BM25 lexical search over one scope or several. Returns
- [(chunk_id, score)], higher = better.
+ """BM25 lexical search over one scope or several. Returns [(chunk_id, score)], higher = better.
- `match_query` lets a caller supply the FTS5 expression itself; the conversation
- archive shapes its own (see `conversation_match_queries`). Omitted, this is byte for
- byte what every other caller has always got.
+ `match_query` lets a caller supply the FTS5 expression itself; the conversation archive shapes
+ its own (see `conversation_match_queries`). Omitted, this is byte for byte what every other
+ caller has always got.
`newest_first` breaks TIES the other way round. FTS5 floors the IDF of a term the
whole index shares, so every hit on a per-thread archive's own subject scores the
diff --git a/studio/backend/core/rag/tool.py b/studio/backend/core/rag/tool.py
index b4c2ed3f509..ac882579926 100644
--- a/studio/backend/core/rag/tool.py
+++ b/studio/backend/core/rag/tool.py
@@ -254,7 +254,6 @@ def search_knowledge_base_with_sources(
def store_rows(conn, hits):
- """Hydrate chunk rows for a list of hits."""
from . import store
return store.chunks_by_id(conn, [h.chunk_id for h in hits])
@@ -376,7 +375,6 @@ def search_knowledge_base(
min_score: float = 0.0,
model_name: str | None = None,
) -> str:
- """Text-only variant of :func:`search_knowledge_base_with_sources`."""
text, _sources = search_knowledge_base_with_sources(
query = query,
scope_kb_id = scope_kb_id,
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 121e93abc8b..652ff62d395 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -362,9 +362,9 @@ def _loaded_context_length(inference: dict[str, Any] | None = None) -> int | Non
Mirrors routes.inference._monitor_context_length (llama.cpp backend, else the inference
orchestrator) so grounding sizes evidence to the same context the API layer serves. The ML
backends live in a worker subprocess, so the core.inference.inference singleton is unpopulated
- here and importing it pulls in the ML stack; read the orchestrator the routes use instead.
-
- A run carrying a providerType runs on that connection, not on either local backend."""
+ here and importing it pulls in the ML stack; read the orchestrator the routes use instead. A run
+ carrying a providerType runs on that connection, not on either local backend.
+ """
if _external_provider_run(inference):
return None
try:
@@ -603,13 +603,13 @@ async def _response_format_unsupported(response: httpx.Response) -> bool:
async def _model_unloaded(response: httpx.Response) -> str | None:
"""Which "not servable right now" refusal this is, or None for any other failure.
- All three are transient for a durable run -- the model can be loaded again -- unlike any
- other 4xx. ``"empty"`` is routes.inference's 400 for a backend with nothing loaded.
- ``"named"`` is its 404 model_not_found, which the same condition produces when auto-switch
- is on and the name resolves to nothing local: a model mid-load or mid-update looks exactly
- like a model that will never resolve, so the caller waits on it far more briefly.
- ``"switching"`` is its 503 model_switch_failed, raised while a swap to the run's model is
- still loading; the generic 5xx backoff gave up in three seconds, well inside a real load.
+ All three are transient for a durable run, unlike any other 4xx. ``"empty"`` is
+ routes.inference's 400 for a backend with nothing loaded. ``"named"`` is its 404
+ model_not_found, which the same condition produces when auto-switch is on and the name resolves
+ to nothing local: a model mid-load or mid-update looks exactly like a model that will never
+ resolve, so the caller waits on it far more briefly. ``"switching"`` is its 503
+ model_switch_failed, raised while a swap to the run's model is still loading; the generic 5xx
+ backoff gave up in three seconds, well inside a real load.
"""
if response.status_code not in (400, 404, 503):
return None
@@ -1000,13 +1000,12 @@ def _preferred_step_error(current: str, candidate: str) -> str:
def _run_moved_on(fresh: dict | None, attempt: int) -> bool:
"""Whether the run this worker was running has since been re-pointed at a newer question.
- A thread reuses its one run row for its lifetime, so between committing a terminal status
- and writing the terminal reply the user can stop the run and ask something else: the row
- is reset, its assistant binding moves, and the reply below -- resolved by run id -- would
- stamp "Research cancelled." and researchStatus cancelled onto the NEW question's
- placeholder, where it stays until that question reaches its own terminal write.
-
- retryCount is the attempt epoch, which rebind_cancelled advances for exactly this reason.
+ A thread reuses its one run row for its lifetime, so between committing a terminal status and
+ writing the terminal reply the user can stop the run and ask something else: the row is reset,
+ its assistant binding moves, and the reply below (resolved by run id) would stamp "Research
+ cancelled." and researchStatus cancelled onto the NEW question's placeholder, where it stays
+ until that question reaches its own terminal write. retryCount is the attempt epoch, which
+ rebind_cancelled advances for exactly this reason.
"""
if not fresh:
return True
@@ -1335,14 +1334,15 @@ class ResearchSupervisor:
) -> bool:
"""Wait, up to the run's model timeout, for a model to be loaded again; True if one was.
- A durable run resumes after an Unsloth restart and is approved long after it was created,
- so the model it was started with can be gone. Waiting keeps the run alive instead of
- ending it on a non-retryable 400 that discards every step and source it gathered.
+ A durable run resumes after an Unsloth restart and is approved long after it was created, so
+ the model it was started with can be gone. Waiting keeps the run alive instead of ending it
+ on a non-retryable 400 that discards every step and source it gathered.
- ``max_seconds`` bounds the wait for refusals that name the model rather than report an
- empty backend. A load already in flight finishes inside it; anything else (an ejected
- model, a llama.cpp update, a name that no longer resolves) needs a user action that no
- wait can outlast, so surfacing the refusal beats burning the whole budget first."""
+ ``max_seconds`` bounds the wait for refusals that name the model rather than report an empty
+ backend. A load already in flight finishes inside it; anything else (an ejected model, a
+ llama.cpp update, a name that no longer resolves) needs a user action that no wait can
+ outlast, so surfacing the refusal beats burning the whole budget first.
+ """
loop = asyncio.get_running_loop()
# Share the model budget across the allowed waits: spending it all on one lets the enclosing wall
# clock fire first and bury the real refusal.
@@ -1784,12 +1784,10 @@ class ResearchSupervisor:
else:
await asyncio.sleep(delay)
attempt += 1
- # re-check the lease and cancellation before re-sending.
await self._check_active(run["id"])
continue
- # A proxied provider 429 arrives as a 200 whose first line is the refusal, so the
- # status cannot see
- # it; no body byte is used yet.
+ # A proxied provider 429 arrives as a 200 whose first line is the refusal, so the status
+ # cannot see it; no body byte is used yet.
stream = self._iter_stream_lines(run["id"], response, semantic_deadline)
head = await _peek_stream_head(stream)
throttled = _stream_rate_limit_delay(head)
@@ -1808,12 +1806,11 @@ class ResearchSupervisor:
if self._cancel_event(run["id"]).is_set():
await self._check_active(run["id"])
if not line.startswith("data:"):
- # Queueing has no timeout by design, so suspend for it and start the budget when the slot is
- # granted.
+ # Queueing has no timeout by design, so suspend for it and start the budget when the slot
+ # is granted.
if line.startswith(_ADMISSION_WAIT_COMMENT):
- # Unlimited has no wall clock behind this, so bound the gap between queue
- # notices; each notice
- # refreshes it.
+ # Unlimited has no wall clock behind this, so bound the gap between queue notices;
+ # each notice refreshes it.
first_output_deadline = (
None if model_timeout else loop.time() + admission_gap_budget
)
@@ -1827,14 +1824,12 @@ class ResearchSupervisor:
continue
# Arming research in the composer is the approval, so the plan is queued as it is stored
# rather than parked for a second confirmation.
- # revoked before the phase event, so a cancel there cannot leak a live key.
try:
chunk = json.loads(data)
_stream_error = stream_error_from_chunk(chunk)
if _stream_error is not None:
- # The server's own text names the cause and both token counts; flattening it to
- # a fixed string left
- # the user nothing to act on.
+ # The server's own text names the cause and both token counts; flattening it to a
+ # fixed string left the user nothing to act on.
raise _stream_error
normalized_usage = _normalize_completion_usage(
chunk.get("usage") if isinstance(chunk, dict) else None
@@ -1897,9 +1892,8 @@ class ResearchSupervisor:
try:
await response.aclose()
except Exception:
- # Closing a broken stream is best-effort and must not replace the generation result
- # or the error
- # that caused teardown.
+ # Closing a broken stream is best-effort and must not replace the generation result or the
+ # error that caused teardown.
logger.warning(
"research.stream_cleanup_failed run_id=%s",
run["id"],
diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.py
index 5adc9a49847..99a550362d1 100644
--- a/studio/backend/core/tool_healing.py
+++ b/studio/backend/core/tool_healing.py
@@ -477,25 +477,23 @@ def _iter_bracket_spans(
start: int = 0,
enabled_tool_names = None,
):
- """Yield ``(span_start, span_end, kind, match)`` for each balanced bracket-tag
- call from ``start`` on, in document order; ``span_end`` exclusive. ``kind`` is
- ``"array"`` ([TOOL_CALLS] [..]), ``"name"`` ([TOOL_CALLS]name{..}, incl. v11
- [CALL_ID]/[ARGS]) or ``"rehearsal"`` (name[ARGS]{..}).
-
- ``enabled_tool_names`` (set, or None = unrestricted) gates only the ambiguous
- bare rehearsal form: name[ARGS]{..} is a call ONLY when ``name`` is markerless-promotable,
- so a disabled ``foo[ARGS]{..}`` or an execution-class ``terminal[ARGS]{..}`` is neither
- parsed nor stripped. Explicit [TOOL_CALLS] markers stay unconditional.
-
- A rehearsal inside markdown code (fenced block or inline span) is documentation
- for the same reason -- the syntax has no sentinel, so quoting it would otherwise
- BE a call -- and is likewise neither parsed nor stripped. Explicit markers stay
- unconditional there too: a ```json block is still a real call for the templates
- that emit one.
-
- Balance-only (no JSON validation) so strip and parse share one scan. The cursor
- jumps past each consumed span, so a marker inside consumed JSON is never
- re-matched and each regex re-searches only once its match falls behind: linear."""
+ """Yield ``(span_start, span_end, kind, match)`` for each balanced bracket-tag call from ``start``
+ on, in document order; ``span_end`` exclusive. ``kind`` is ``"array"`` ([TOOL_CALLS] [..]),
+ ``"name"`` ([TOOL_CALLS]name{..}, incl. v11 [CALL_ID]/[ARGS]) or ``"rehearsal"``
+ (name[ARGS]{..}).
+
+ ``enabled_tool_names`` (set, or None = unrestricted) gates only the ambiguous bare rehearsal
+ form: name[ARGS]{..} is a call ONLY when ``name`` is markerless-promotable, so a disabled
+ ``foo[ARGS]{..}`` or an execution-class ``terminal[ARGS]{..}`` is neither parsed nor stripped.
+ Explicit [TOOL_CALLS] markers stay unconditional, keeping parse/strip/detection symmetric. A
+ rehearsal inside markdown code is documentation for the same reason -- the syntax has no
+ sentinel, so quoting it would otherwise BE a call -- and is likewise neither parsed nor
+ stripped; explicit markers stay unconditional there too.
+
+ Balance-only (no JSON validation) so strip and parse share one scan. The cursor jumps past each
+ consumed span, so a marker inside consumed JSON is never re-matched and each regex re-searches
+ only once its match falls behind: linear.
+ """
n = len(text)
specs = (
("array", _MISTRAL_ARRAY_RE),
@@ -1117,9 +1115,8 @@ def parse_tool_calls_from_text(
"type": "function",
"function": {
"name": item.get("name", ""),
- # A bare scalar string stays raw; json.dumps would double-encode it so the arg
- # healer wraps it with
- # literal quotes.
+ # A bare scalar string stays raw; json.dumps would double-encode it so the arg healer
+ # wraps it with literal quotes.
"arguments": args if isinstance(args, str) else json.dumps(args),
},
}
diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.py
index 1a2f85777bf..d025b9c63fd 100644
--- a/studio/backend/core/training/diffusion_checkpoint.py
+++ b/studio/backend/core/training/diffusion_checkpoint.py
@@ -3,39 +3,30 @@
"""Resumable checkpoints for diffusion (image / future video) LoRA training.
-A diffusion run used to write exactly one thing -- the deployable adapter -- at the very
-end, so a stop at step 11 left the AdamW moments, the LR-schedule position, the RNG
-streams and the step counter to die with the subprocess: restarting the same
-configuration began again at step 1. This module is the single writer and the single
-reader of the state that makes a run continuable.
-
-Layout, under the run's own ``output_dir`` (so the resumed run keeps writing into the
-same folder the adapter is published from)::
-
- <output_dir>/
- pytorch_lora_weights.safetensors <- the deployable adapter (unchanged)
- checkpoint-11/
- trainer_state.json <- manifest + completion marker
- adapter_model.safetensors <- peft-format LoRA tensors
- ema_adapter.safetensors <- the EMA shadow, when ema_decay > 0
- optimizer.pt <- optimizer.state_dict()
- scheduler.pt <- lr_scheduler.state_dict()
- rng_state.pt <- torch CPU + per-device CUDA RNG states
-
-``trainer_state.json`` is written LAST inside a hidden staging directory, and the whole
-staging directory is then promoted with a single ``os.replace``. A process killed at any
-point leaves either the previous checkpoint or a ``.tmp-checkpoint-*`` directory that no
-scanner ever matches -- never a half-written ``checkpoint-<N>`` that looks valid.
-
-Identity: every bundle records the training identity it belongs to (family, base repo +
-revision, dataset fingerprint, LoRA targets/rank/alpha, precision). ``preflight_resume``
-compares that against the incoming request and refuses a mismatch with a user-facing
-reason, so the start route can reject BEFORE it evicts the resident GPU model.
-
-``kind`` ("image" today) is carried in both the manifest and the identity so a future
-video trainer can write and validate its own bundles through this same code without a
-format change: a video checkpoint simply records ``kind = "video"`` and will not be
-offered to an image run (or vice versa).
+A diffusion run used to write exactly one thing, the deployable adapter, at the very end, so a stop
+at step 11 left the AdamW moments, the LR-schedule position, the RNG streams and the step counter to
+die with the subprocess: restarting the same configuration began again at step 1. This module is the
+single writer and the single reader of the state that makes a run continuable.
+
+Layout, under the run's own ``output_dir`` (so the resumed run keeps writing into the same folder
+the adapter is published from): ``<output_dir>/pytorch_lora_weights.safetensors`` is the deployable
+adapter (unchanged), and each ``checkpoint-<N>/`` holds ``trainer_state.json`` (manifest +
+completion marker), ``adapter_model.safetensors`` (peft-format LoRA tensors),
+``ema_adapter.safetensors`` (the EMA shadow, when ema_decay > 0), ``optimizer.pt``, ``scheduler.pt``
+and ``rng_state.pt`` (torch CPU + per-device CUDA RNG states).
+
+``trainer_state.json`` is written LAST inside a hidden staging directory, and the whole staging
+directory is then promoted with a single ``os.replace``. A process killed at any point leaves either
+the previous checkpoint or a ``.tmp-checkpoint-*`` directory that no scanner ever matches, never a
+half-written ``checkpoint-<N>`` that looks valid.
+
+Identity: every bundle records the training identity it belongs to (family, base repo + revision,
+dataset fingerprint, LoRA targets/rank/alpha, precision). ``preflight_resume`` compares that against
+the incoming request and refuses a mismatch with a user-facing reason, so the start route can reject
+BEFORE it evicts the resident GPU model.
+
+``kind`` ("image" today) is carried in both the manifest and the identity so a future video trainer
+can write and validate its own bundles through this same code without a format change.
"""
from __future__ import annotations
@@ -59,8 +50,8 @@ CHECKPOINT_FORMAT = "unsloth-diffusion-checkpoint"
CHECKPOINT_VERSION = 1
CHECKPOINT_PREFIX = "checkpoint-"
-# Hidden, and not prefixed "checkpoint-", so neither glob("checkpoint-*") nor a file browser
-# mistakes a half-written bundle for a real one.
+# Hidden, and not prefixed "checkpoint-", so neither glob("checkpoint-*") nor a file browser mistakes a half-written
+# bundle for a real one.
_STAGING_PREFIX = ".tmp-checkpoint-"
TRAINER_STATE_FILENAME = "trainer_state.json"
@@ -79,7 +70,6 @@ class ResumeError(ValueError):
# Human labels for the identity fields that HARD-REJECT a resume, in report order.
-# ── identity ──────────────────────────────────────────────────────────────────
_IDENTITY_LABELS: tuple[tuple[str, str], ...] = (
("kind", "training type"),
("family", "model family"),
@@ -91,42 +81,41 @@ _IDENTITY_LABELS: tuple[tuple[str, str], ...] = (
("lora_alpha", "LoRA alpha"),
("lora_dropout", "LoRA dropout"),
("cfg_dropout", "caption dropout"),
- # Read from the INCOMING config while the moments and scheduler position come from the bundle, so
- # changing one continues a trajectory those moments were not produced under.
+ # Read from the INCOMING config while the moments and scheduler position come from the bundle, so changing one
+ # continues a trajectory those moments were not produced under.
("flow_shift", "timestep shift"),
("weighting_scheme", "loss weighting scheme"),
("snr_gamma", "min-SNR gamma"),
("lr_scheduler", "learning-rate schedule"),
("lr_warmup_steps", "learning-rate warmup"),
- # The latent cache and crop/flip plan are built from these BEFORE restore_resume_state puts the RNG
- # back, so changing one continues the old sampler against a different image sequence.
+ # The latent cache and crop/flip plan are built from these BEFORE restore_resume_state puts the RNG back, so
+ # changing one continues the old sampler against a different image sequence.
("seed", "random seed"),
("cache_latents", "latent caching"),
("cache_mode", "latent cache path"),
- # The mode the LOOP actually ran in: UNSLOTH_DIFFUSION_NO_LATENT_CACHE turns it off and an
- # over-budget cache falls back to encoding in-loop, and the two paths draw crops and flips from
- # different streams (variant_rng versus the loop rng), so a restored RNG state does not reproduce
- # the run.
+ # The mode the LOOP actually ran in: UNSLOTH_DIFFUSION_NO_LATENT_CACHE turns it off and an over-budget cache falls
+ # back to encoding in-loop, and the two paths draw crops and flips from different streams (variant_rng versus the
+ # loop rng), so a restored RNG state does not reproduce the run.
("cache_variants", "cached crop variants"),
("center_crop", "centre cropping"),
("random_flip", "random flipping"),
- # TF32 versus strict fp32 continues the trajectory at a different numeric precision, and off is the
- # documented strict-reproducibility mode.
+ # TF32 versus strict fp32 continues the trajectory at a different numeric precision, and off is the documented
+ # strict-reproducibility mode.
("enable_tf32", "TF32 matmuls"),
# Batch, accumulation and clip norm all change the trajectory the restored moments were produced on.
("train_batch_size", "batch size"),
("gradient_accumulation_steps", "gradient accumulation"),
("max_grad_norm", "gradient clipping"),
- # Both trainers resize and crop to this before the restored sampler and moments see anything, so a
- # bundle trained at 1024 could report a clean resume and finish at 768.
+ # Both trainers resize and crop to this before the restored sampler and moments see anything, so a bundle trained
+ # at 1024 could report a clean resume and finish at 768.
("resolution", "training resolution"),
("precision", "mixed precision"),
("base_precision", "base precision"),
- # What the frozen base was ACTUALLY converted to: fp8/mxfp8 conversion can fall back to bf16, so
- # recording the request reports a clean resume across different numerics.
+ # What the frozen base was ACTUALLY converted to: fp8/mxfp8 conversion can fall back to bf16, so recording the
+ # request reports a clean resume across different numerics.
("base_precision_effective", "resolved base precision"),
- # LoRAEMA is built from the INCOMING decay while the shadow tensors are restored, so a changed
- # coefficient makes the exported EMA adapter a hybrid.
+ # LoRAEMA is built from the INCOMING decay while the shadow tensors are restored, so a changed coefficient makes
+ # the exported EMA adapter a hybrid.
("ema_decay", "EMA decay"),
)
# Unknown on either side means "cannot tell", which must not be reported as a mismatch.
@@ -136,8 +125,8 @@ _OPTIONAL_IDENTITY_FIELDS = frozenset(
"dataset_fingerprint",
"lora_dropout",
"cfg_dropout",
- # Absent only in a manifest written before these were recorded, which reads as "cannot tell" rather than
- # as a mismatch.
+ # Absent only in a manifest written before these were recorded, which reads as "cannot tell" rather than as a
+ # mismatch.
"ema_decay",
"flow_shift",
"weighting_scheme",
@@ -154,8 +143,8 @@ _OPTIONAL_IDENTITY_FIELDS = frozenset(
"train_batch_size",
"gradient_accumulation_steps",
"max_grad_norm",
- # Known only inside the DiT trainer; unknown reads as "cannot tell", which keeps the route preflight
- # and the SDXL trainer unaffected.
+ # Known only inside the DiT trainer; unknown reads as "cannot tell", which keeps the route preflight and the
+ # SDXL trainer unaffected.
"base_precision_effective",
}
)
@@ -165,37 +154,32 @@ _UNRESOLVED_REVISION = "unresolved"
def _revision_is_comparable(value: Any) -> bool:
"""Only a real Hub commit (``rev-<sha>``) is a hard identity for the base model.
-
``source_revision`` also returns a ``dir-<hash>`` built from the file SIZES AND MTIMES of a
LOCAL base directory. That is the right key for a conditioning cache, but far too brittle for
a resume gate: re-downloading, re-quantizing, or merely touching the local base changes it
- while the weights are the same, and the user would get an unactionable
- "different base model revision (dir-abc vs dir-def)" refusal. Compare Hub revisions, treat a
- local directory's marker as advisory."""
+ while the weights are the same, and the user would get an unactionable "different base model
+ revision (dir-abc vs dir-def)" refusal. Compare Hub revisions, treat a local directory's
+ marker as advisory."""
return isinstance(value, str) and value.startswith("rev-")
def _revision_repo(identity: "CheckpointIdentity") -> str:
- """The repo ``identity.base_revision`` was read from, normalised for comparison.
-
- A bundle written before mirrors existed has no ``base_revision_repo`` and always read the
- canonical base, so it falls back to ``base_model``: that keeps an old bundle comparable with
- a new one on a host that fetched the canonical repo, and only stops the comparison where it
- genuinely cannot be made.
- """
+ """The repo ``identity.base_revision`` was read from, normalised for comparison. A bundle
+ written before mirrors existed has no ``base_revision_repo`` and always read the canonical
+ base, so it falls back to ``base_model``: that keeps an old bundle comparable with a new one
+ on a host that fetched the canonical repo, and only stops the comparison where it genuinely
+ cannot be made."""
return str(getattr(identity, "base_revision_repo", None) or identity.base_model or "").lower()
@dataclass(frozen = True)
class CheckpointIdentity:
- """What a checkpoint was trained as. Two bundles are interchangeable only when every
- field here agrees, so resuming can never continue a FLUX run into an SDXL adapter, or
- feed rank-16 moments to a rank-32 optimizer.
-
- ``base_revision`` and ``dataset_fingerprint`` are optional: the first is resolved from
- the local Hub cache and reads ``unresolved`` when the repo has not been fetched yet, the
- second is only known once the dataset has been walked. Either being unknown skips that
- comparison rather than failing it."""
+ """What a checkpoint was trained as. Two bundles are interchangeable only when every field here
+ agrees, so resuming can never continue a FLUX run into an SDXL adapter, or feed rank-16
+ moments to a rank-32 optimizer. ``base_revision`` and ``dataset_fingerprint`` are optional:
+ the first is resolved from the local Hub cache and reads ``unresolved`` when the repo has not
+ been fetched yet, the second is only known once the dataset has been walked. Either being
+ unknown skips that comparison rather than failing it."""
family: str
base_model: str
@@ -209,15 +193,15 @@ class CheckpointIdentity:
base_revision: Optional[str] = None
dataset_fingerprint: Optional[str] = None
lora_dropout: Optional[float] = None
- # The DiT loop draws rng.random() once per sample while this is above zero, so a change diverges the
- # restored RNG stream on the next step and changes the objective.
+ # The DiT loop draws rng.random() once per sample while this is above zero, so a change diverges the restored RNG
+ # stream on the next step and changes the objective.
cfg_dropout: Optional[float] = None
# Trajectory-defining knobs, all optional for the same reason: a bundle from before they were recorded reads
# unknown, not mismatched.
flow_shift: Optional[str] = None
weighting_scheme: Optional[str] = None
- # Text, not a float: None is the documented way to DISABLE min-SNR, so a float field could not tell
- # "trained with it off" from "written before the field existed".
+ # Text, not a float: None is the documented way to DISABLE min-SNR, so a float field could not tell "trained with
+ # it off" from "written before the field existed".
snr_gamma: Optional[str] = None
lr_scheduler: Optional[str] = None
lr_warmup_steps: Optional[int] = None
@@ -225,8 +209,8 @@ class CheckpointIdentity:
# Booleans as text ("on"/"off") for the same reason snr_gamma is: False is a real value and None has to stay
# reserved for a manifest that predates the field.
cache_latents: Optional[str] = None
- # Resolved, not requested, and left None by the start route so the pre-eviction preflight is
- # unaffected; the trainer's own preflight catches a mismatched cache path.
+ # Resolved, not requested, and left None by the start route so the pre-eviction preflight is unaffected; the
+ # trainer's own preflight catches a mismatched cache path.
cache_mode: Optional[str] = None
cache_variants: Optional[int] = None
center_crop: Optional[str] = None
@@ -236,14 +220,14 @@ class CheckpointIdentity:
gradient_accumulation_steps: Optional[int] = None
# Text, so 0.0 (clipping disabled) is a value and None stays "not recorded".
max_grad_norm: Optional[str] = None
- # Text for the same reason: 0.0 means EMA is off, which is a real setting, and None has to stay reserved for
- # a manifest that predates the field.
+ # Text for the same reason: 0.0 means EMA is off, which is a real setting, and None has to stay reserved for a
+ # manifest that predates the field.
ema_decay: Optional[str] = None
- # Post-conversion, set by the DiT trainer once it knows whether fp8/mxfp8 took. None everywhere else, which
- # the optional rule reads as "cannot tell".
+ # Post-conversion, set by the DiT trainer once it knows whether fp8/mxfp8 took. None everywhere else, which the
+ # optional rule reads as "cannot tell".
base_precision_effective: Optional[str] = None
- # WHICH repo base_revision was read from: a gated base is fetched from its byte-identical ungated
- # mirror and the two repos carry different SHAs, so this only says whether they are comparable.
+ # WHICH repo base_revision was read from: a gated base is fetched from its byte-identical ungated mirror and the
+ # two repos carry different SHAs, so this only says whether they are comparable.
base_revision_repo: Optional[str] = None
def as_dict(self) -> dict[str, Any]:
@@ -257,8 +241,8 @@ class CheckpointIdentity:
"lora_target_modules": list(self.lora_target_modules),
"lora_rank": int(self.lora_rank),
"lora_alpha": int(self.lora_alpha),
- # Passed to the LoRA constructor, so it changes the stochastic forward pass the restored optimizer
- # moments were produced against.
+ # Passed to the LoRA constructor, so it changes the stochastic forward pass the restored optimizer moments
+ # were produced against.
"lora_dropout": self.lora_dropout,
"cfg_dropout": self.cfg_dropout,
"flow_shift": self.flow_shift,
@@ -280,8 +264,8 @@ class CheckpointIdentity:
"base_precision_effective": self.base_precision_effective,
"precision": self.precision,
"base_precision": self.base_precision,
- # A hard identity field: both trainers crop the images to this before the restored sampler sees
- # anything, so loadable tensors are not a faithful resume.
+ # A hard identity field: both trainers crop the images to this before the restored sampler sees anything,
+ # so loadable tensors are not a faithful resume.
"resolution": int(self.resolution),
}
@@ -336,22 +320,22 @@ class CheckpointIdentity:
return replace(self, dataset_fingerprint = fingerprint)
def mismatch_reason(self, other: "CheckpointIdentity") -> Optional[str]:
- """Why ``other`` (the incoming request) cannot continue ``self`` (the checkpoint),
- or None when they are compatible. Reports the FIRST difference so the message names
- one concrete thing to change."""
+ """Why ``other`` (the incoming request) cannot continue ``self`` (the checkpoint), or None
+ when they are compatible. Reports the FIRST difference so the message names one concrete
+ thing to change."""
mine, theirs = self.as_dict(), other.as_dict()
for field, label in _IDENTITY_LABELS:
a, b = mine.get(field), theirs.get(field)
- # None / "" is "cannot tell", NOT falsiness: a lora_dropout of 0.0 is a real value and the
- # commonest one, so truthiness would skip exactly the 0.0-against-0.15 comparison that matters.
+ # None / "" is "cannot tell", NOT falsiness: a lora_dropout of 0.0 is a real value and the commonest one,
+ # so truthiness would skip exactly the 0.0-against-0.15 comparison that matters.
if field in _OPTIONAL_IDENTITY_FIELDS and (a in (None, "") or b in (None, "")):
continue
if field == "base_revision" and not (
_revision_is_comparable(a) and _revision_is_comparable(b)
):
continue
- # Two commit SHAs are comparable only when they name the same repo: a gated base fetched from its
- # ungated mirror carries a different SHA for identical weights.
+ # Two commit SHAs are comparable only when they name the same repo: a gated base fetched from its ungated
+ # mirror carries a different SHA for identical weights.
if field == "base_revision" and _revision_repo(self) != _revision_repo(other):
continue
if a == b:
@@ -377,8 +361,8 @@ def _optional_str(value: Any) -> Optional[str]:
def _optional_float(value: Any) -> Optional[float]:
- """A rounded float, or None for anything unreadable (including a manifest that predates
- the field). None is the "cannot tell" the optional-field rule skips."""
+ """A rounded float, or None for anything unreadable (including a manifest that predates the
+ field). None is the "cannot tell" the optional-field rule skips."""
if value is None:
return None
try:
@@ -388,8 +372,8 @@ def _optional_float(value: Any) -> Optional[float]:
def _snr_gamma_key(value: Any) -> str:
- """min-SNR as a comparable token. None DISABLES the weighting, so it gets its own value
- rather than the unknown the optional-field rule skips."""
+ """min-SNR as a comparable token. None DISABLES the weighting, so it gets its own value rather
+ than the unknown the optional-field rule skips."""
number = _optional_float(value)
return "off" if number is None else f"{number}"
@@ -418,13 +402,11 @@ def _render(value: Any) -> str:
def dataset_fingerprint(pairs: Any) -> str:
- """A stable content marker for the (image, caption) pairs a run trains on.
-
- Built from each image's FILE NAME, byte size and resolved caption, sorted, so it is
- invariant to the dataset folder being moved or re-imported under a different root
- (which the run config already records) while still catching an added, removed,
- re-captioned or replaced image. Never raises: an unstatable file contributes ``?``
- rather than failing a preflight."""
+ """A stable content marker for the (image, caption) pairs a run trains on. Built from each
+ image's FILE NAME, byte size and resolved caption, sorted, so it is invariant to the dataset
+ folder being moved or re-imported under a different root (which the run config already
+ records) while still catching an added, removed, re-captioned or replaced image. Never
+ raises: an unstatable file contributes ``?`` rather than failing a preflight."""
parts: list[str] = []
for entry in pairs or ():
try:
@@ -436,8 +418,8 @@ def dataset_fingerprint(pairs: Any) -> str:
return f"ds-{len(parts)}-{digest[:24]}"
-# Enough of each file to tell two images apart, without reading a multi-gigabyte dataset on a
-# preflight that runs before the resident GPU model is evicted.
+# Enough of each file to tell two images apart, without reading a multi-gigabyte dataset on a preflight that runs
+# before the resident GPU model is evicted.
_PROBE_BYTES = 65536
@@ -445,21 +427,22 @@ def _content_probe(path: Any) -> str:
"""``size-digest`` for one dataset file, or ``?`` when it cannot be read.
Size alone let an image be overwritten IN PLACE with different content of exactly the same
- length -- same filename, same caption -- and the preflight accepted the dataset, so the
- restored optimizer and scheduler carried on an old experiment against different images.
+ length -- same filename, same caption -- and the preflight accepted the dataset, so the restored
+ optimizer and scheduler carried on an old experiment against different images.
- The head and tail rather than the whole file: hashing every image would make this scale with
- the dataset, and two different images agreeing on their first and last 64 KiB as well as
- their exact byte length is not a case that arises from editing a dataset. It is not a
- tamper-proof digest and does not need to be."""
+ The head and tail rather than the whole file: hashing every image would make this scale with the
+ dataset, and two different images agreeing on their first and last 64 KiB as well as their exact
+ byte length is not a case that arises from editing a dataset. It is not a tamper-proof digest
+ and does not need to be.
+ """
try:
size = os.path.getsize(path)
digest = hashlib.sha256()
with open(path, "rb") as handle:
digest.update(handle.read(_PROBE_BYTES))
if size > _PROBE_BYTES:
- # Every byte past the head is covered: the old "> 2 * _PROBE_BYTES" gate left 64-128 KiB files
- # reading only their first 64 KiB, so a same-length replacement sharing a head went unnoticed.
+ # Every byte past the head is covered: the old "> 2 * _PROBE_BYTES" gate left 64-128 KiB files reading
+ # only their first 64 KiB, so a same-length replacement sharing a head went unnoticed.
handle.seek(max(_PROBE_BYTES, size - _PROBE_BYTES))
digest.update(handle.read(_PROBE_BYTES))
# ValueError: open() rejects an embedded NUL rather than raising OSError.
@@ -469,18 +452,17 @@ def _content_probe(path: Any) -> str:
def _resolve_lora_targets(cfg: Any) -> tuple[str, ...]:
- """The LoRA target modules the trainer will actually attach for ``cfg``.
-
- A DiT family replaces the generic attention default with its own projections
- (``_select_lora_targets``), so the identity must resolve the same tuple the trainer
- will; otherwise the start route would compute a different fingerprint from the run and
- every resume would look like a mismatch. Imported lazily -- the DiT trainer imports this
- module at load time, so the reverse edge has to be deferred."""
+ """The LoRA target modules the trainer will actually attach for ``cfg``. A DiT family replaces
+ the generic attention default with its own projections (``_select_lora_targets``), so the
+ identity must resolve the same tuple the trainer will; otherwise the start route would
+ compute a different fingerprint from the run and every resume would look like a mismatch.
+ Imported lazily -- the DiT trainer imports this module at load time, so the reverse edge has
+ to be deferred."""
configured = tuple(cfg.lora_target_modules)
if str(getattr(cfg, "resolved_family", "") or "").strip().lower() == "sdxl":
return configured
- # Deliberately NOT wrapped: falling back to the generic tuple would make the route fingerprint
- # differ from the trainer's, and the mismatch would surface only after the residents were freed.
+ # Deliberately NOT wrapped: falling back to the generic tuple would make the route fingerprint differ from the
+ # trainer's, and the mismatch would surface only after the residents were freed.
from core.training.diffusion_dit_trainer import _SPECS, _select_lora_targets
spec = _SPECS.get(cfg.resolved_family)
@@ -490,25 +472,22 @@ def _resolve_lora_targets(cfg: Any) -> tuple[str, ...]:
def with_cache_mode(identity: "CheckpointIdentity", used_cache: bool) -> "CheckpointIdentity":
- """Record the latent-cache path the loop ACTUALLY took.
-
- The config only carries the request. The environment override and the over-budget fallback
- can both turn it off, and the cached and uncached paths consume different RNG streams for
- crops and flips, so a bundle written on one and resumed on the other restores a state that
- no longer reproduces the training stream."""
+ """Record the latent-cache path the loop ACTUALLY took. The config only carries the request. The
+ environment override and the over-budget fallback can both turn it off, and the cached and
+ uncached paths consume different RNG streams for crops and flips, so a bundle written on one
+ and resumed on the other restores a state that no longer reproduces the training stream."""
return replace(identity, cache_mode = "cached" if used_cache else "in-loop")
def with_resolved_base_precision(
identity: "CheckpointIdentity", resolved: Any
) -> "CheckpointIdentity":
- """Record the base precision the transformer was ACTUALLY converted to.
-
- The config carries the request, and "auto" is not even a precision. Worse, fp8 and mxfp8
- conversion can fail on the host and both fall back to bf16 with only a warning in progress,
- so a bundle requested as fp8 recorded fp8 while its optimizer moments were produced against
- bf16 linears. A later resume on a host where the conversion does take then restores those
- moments onto an fp8 frozen base and calls it a clean continue."""
+ """Record the base precision the transformer was ACTUALLY converted to. The config carries the
+ request, and "auto" is not even a precision. Worse, fp8 and mxfp8 conversion can fail on the
+ host and both fall back to bf16 with only a warning in progress, so a bundle requested as fp8
+ recorded fp8 while its optimizer moments were produced against bf16 linears. A later resume
+ on a host where the conversion does take then restores those moments onto an fp8 frozen base
+ and calls it a clean continue."""
value = str(resolved or "").strip().lower()
if not value:
return identity # nothing resolved; leave it unknown rather than asserting a value
@@ -518,28 +497,27 @@ def with_resolved_base_precision(
def with_resolved_revision(identity: "CheckpointIdentity", base_model: Any) -> "CheckpointIdentity":
"""``identity`` with its base revision re-read now that the base model is on disk.
- The identity is built BEFORE the multi-GB load, deliberately -- a mismatched resume should
- fail in seconds, not after a download. But on the first run of an uncached Hub repo there is
- no local ref to read, so the revision records "unresolved" and the bundle it goes into can
- never enforce which commit it was trained on. Re-read once the loader has populated the
- cache: an unresolved value is not comparable, so a repo that could not be read keeps
- whatever was recorded, and a later resume against a repo that has advanced is refused
- instead of quietly restoring the adapter and the Adam moments onto different frozen base
- weights.
-
- The re-read is unconditional. A local ``refs/main`` can still report the OLD commit before
- the load and be refreshed by ``from_pretrained`` itself, so returning early on an
- already-comparable value left the pre-load revision standing for a base that had since
- advanced -- the resume then compared A against A and restored A's adapter and moments onto
- B's frozen weights, which is the exact outcome this field exists to prevent.
+ The identity is built BEFORE the multi-GB load, deliberately: a mismatched resume should fail in
+ seconds, not after a download. But on the first run of an uncached Hub repo there is no local
+ ref to read, so the revision records "unresolved" and the bundle it goes into can never enforce
+ which commit it was trained on. Re-read once the loader has populated the cache: an unresolved
+ value is not comparable, so a repo that could not be read keeps whatever was recorded, and a
+ later resume against a repo that has advanced is refused instead of quietly restoring the
+ adapter and the Adam moments onto different frozen base weights.
+
+ The re-read is unconditional. A local ``refs/main`` can still report the OLD commit before the
+ load and be refreshed by ``from_pretrained`` itself, so returning early on an already-comparable
+ value left the pre-load revision standing for a base that had since advanced -- the resume then
+ compared A against A and restored A's adapter and moments onto B's frozen weights, which is the
+ exact outcome this field exists to prevent.
"""
from core.training.diffusion_train_extras import source_revision
resolved = source_revision(base_model)
if not _revision_is_comparable(resolved) or resolved == identity.base_revision:
return identity
- # The repo travels with the revision: a SHA without the repo that produced it cannot be compared
- # against one from the other repo.
+ # The repo travels with the revision: a SHA without the repo that produced it cannot be compared against one from
+ # the other repo.
return replace(identity, base_revision = resolved, base_revision_repo = str(base_model or ""))
@@ -550,19 +528,18 @@ def identity_for_config(
resolved_targets: Optional[tuple[str, ...]] = None,
kind: str = "image",
) -> CheckpointIdentity:
- """The identity a run with ``cfg`` would produce.
-
- ``resolved_targets`` is the LoRA target tuple the trainer will actually attach; pass it
- where it is already known (the DiT trainer holds its family spec), otherwise it is
- resolved here the same way, so the start route and the trainer always agree.
- ``base_precision`` is the REQUESTED mode, not the one ``auto`` resolves to at load time
- -- the start route has to compute the same identity before anything is loaded."""
+ """The identity a run with ``cfg`` would produce. ``resolved_targets`` is the LoRA target tuple
+ the trainer will actually attach; pass it where it is already known (the DiT trainer holds
+ its family spec), otherwise it is resolved here the same way, so the start route and the
+ trainer always agree. ``base_precision`` is the REQUESTED mode, not the one ``auto`` resolves
+ to at load time, since the start route has to compute the same identity before anything is
+ loaded."""
from core.training.diffusion_train_common import effective_mixed_precision
from core.training.diffusion_train_extras import source_revision
targets = tuple(resolved_targets) if resolved_targets else _resolve_lora_targets(cfg)
- # ``base_model`` stays canonical everywhere else in the identity; only the revision pair below follows the
- # repo the weights are pulled from.
+ # ``base_model`` stays canonical everywhere else in the identity; only the revision pair below follows the repo
+ # the weights are pulled from.
fetch_base_model = str(getattr(cfg, "fetch_base_model", None) or cfg.base_model or "")
return CheckpointIdentity(
family = str(getattr(cfg, "resolved_family", "") or ""),
@@ -572,8 +549,8 @@ def identity_for_config(
lora_alpha = int(cfg.lora_alpha if cfg.lora_alpha is not None else cfg.lora_rank),
lora_dropout = round(float(getattr(cfg, "lora_dropout", 0.0) or 0.0), 6),
cfg_dropout = round(float(getattr(cfg, "cfg_dropout", 0.0) or 0.0), 6),
- # flow_shift is float | "auto" | None, so it is recorded as text: "auto" and the number it
- # resolves to are different runs, and comparing them as floats would lose that.
+ # flow_shift is float | "auto" | None, so it is recorded as text: "auto" and the number it resolves to are
+ # different runs, and comparing them as floats would lose that.
flow_shift = str(getattr(cfg, "flow_shift", None)),
weighting_scheme = str(getattr(cfg, "weighting_scheme", "") or "none"),
snr_gamma = _snr_gamma_key(getattr(cfg, "snr_gamma", None)),
@@ -589,30 +566,26 @@ def identity_for_config(
gradient_accumulation_steps = int(getattr(cfg, "gradient_accumulation_steps", 0) or 0),
max_grad_norm = f"{round(float(getattr(cfg, 'max_grad_norm', 0.0) or 0.0), 6)}",
ema_decay = f"{round(float(getattr(cfg, 'ema_decay', 0.0) or 0.0), 6)}",
- # The EFFECTIVE precision, not the request: a pre-Ampere card resolves bf16 to fp16, so recording
- # the request let an fp16 bundle resume in bf16 on a newer card.
+ # The EFFECTIVE precision, not the request: a pre-Ampere card resolves bf16 to fp16, so recording the request
+ # let an fp16 bundle resume in bf16 on a newer card.
precision = effective_mixed_precision(cfg),
base_precision = str(getattr(cfg, "base_precision", "") or ""),
resolution = int(cfg.resolution),
kind = kind,
- # Record the revision of the repo actually FETCHED: the mirror is chosen precisely because the
- # canonical repo is not cached, so reading the canonical one records "unresolved", which
- # mismatch_reason then skips.
+ # Record the revision of the repo actually FETCHED: the mirror is chosen precisely because the canonical repo
+ # is not cached, so reading the canonical one records "unresolved", which mismatch_reason then skips.
base_revision = source_revision(fetch_base_model),
base_revision_repo = fetch_base_model,
dataset_fingerprint = dataset_fingerprint(dataset_pairs) if dataset_pairs else None,
)
-# ── RNG capture / restore ─────────────────────────────────────────────────────
def capture_rng_state(streams: Optional[dict[str, Any]] = None) -> dict[str, Any]:
- """Snapshot every random stream a diffusion run draws from.
-
- ``streams`` maps a name to a ``random.Random`` instance the trainer owns (the loop's
- index/crop stream and the latent-cache variant stream are separate objects, so the
- module-level ``random`` state does not cover them). Returns
- ``{"json": <JSON-safe dict>, "tensors": <torch tensors>}``; the caller writes the first
- into the manifest and the second into ``rng_state.pt``. Never raises."""
+ """Snapshot every random stream a diffusion run draws from. ``streams`` maps a name to a
+ ``random.Random`` instance the trainer owns (the loop's index/crop stream and the
+ latent-cache variant stream are separate objects, so the module-level ``random`` state does
+ not cover them). Returns ``{"json": <JSON-safe dict>, "tensors": <torch tensors>}``; the
+ caller writes the first into the manifest and the second into ``rng_state.pt``. Never raises."""
payload: dict[str, Any] = {
"python": _random_state_to_json(random.getstate()),
"streams": {},
@@ -622,8 +595,8 @@ def capture_rng_state(streams: Optional[dict[str, Any]] = None) -> dict[str, Any
try:
payload["streams"][str(name)] = _random_state_to_json(stream.getstate())
except Exception: # noqa: BLE001 -- a stream we cannot read simply is not restored
- # Could not hand it back. Leaving it on disk still beats deleting the only copy of another run's
- # last resumable state.
+ # Could not hand it back. Leaving it on disk still beats deleting the only copy of another run's last
+ # resumable state.
continue
try:
import numpy as np
@@ -661,8 +634,8 @@ def restore_rng_state(
tensors: Optional[dict[str, Any]] = None,
streams: Optional[dict[str, Any]] = None,
) -> None:
- """Undo ``capture_rng_state``. Every part is independent and best-effort: a checkpoint
- written on a 2-GPU box restored on a 1-GPU box still restores everything else."""
+ """Undo ``capture_rng_state``. Every part is independent and best-effort: a checkpoint written
+ on a 2-GPU box restored on a 1-GPU box still restores everything else."""
payload = payload or {}
state = _random_state_from_json(payload.get("python"))
if state is not None:
@@ -704,10 +677,9 @@ def restore_rng_state(
if cpu is not None:
torch.set_rng_state(cpu.cpu().to(torch.uint8))
if torch.cuda.is_available():
- # Per device, not set_rng_state_all: that needs one state per visible device, so a bundle written
- # with fewer devices visible restored NOTHING, cuda:0 included, and the per-step noise stream
- # (randn_like for latent and noise, randint for the timestep) restarted at the wrong offset while
- # the run looked healthy.
+ # Per device, not set_rng_state_all: that needs one state per visible device, so a bundle written with
+ # fewer devices visible restored NOTHING, cuda:0 included, and the per-step noise stream (randn_like for
+ # latent and noise, randint for the timestep) restarted at the wrong offset while the run looked healthy.
for i in range(torch.cuda.device_count()):
state = tensors.get(f"torch_cuda_{i}")
if state is None:
@@ -718,8 +690,8 @@ def restore_rng_state(
def _random_state_to_json(state: Any) -> Optional[list[Any]]:
- """``random.Random.getstate()`` is ``(version, tuple[int, ...], gauss)``; JSON has no
- tuples, so store it as nested lists."""
+ """``random.Random.getstate()`` is ``(version, tuple[int, ...], gauss)``; JSON has no tuples, so
+ store it as nested lists."""
try:
version, keys, gauss = state
return [int(version), [int(k) for k in keys], gauss]
@@ -736,7 +708,6 @@ def _random_state_from_json(value: Any) -> Optional[tuple]:
return None
-# ── writing ───────────────────────────────────────────────────────────────────
def save_checkpoint(
*,
output_dir: str | os.PathLike[str],
@@ -758,24 +729,24 @@ def save_checkpoint(
) -> str:
"""Write one resumable ``checkpoint-<step>`` bundle and return its path.
- The ONE writer: periodic saves (``cfg.save_steps``) and stop-and-save both come through
- here, so a stopped run and a crashed-then-restarted run resume from byte-identical
- state. Everything lands in a hidden staging directory whose manifest is written last;
- the directory is then promoted with a single ``os.replace``, so a kill at any instant
- leaves the previous checkpoint intact and no valid-looking partial behind.
+ The ONE writer: periodic saves (``cfg.save_steps``) and stop-and-save both come through here, so
+ a stopped run and a crashed-then-restarted run resume from byte-identical state. Everything
+ lands in a hidden staging directory whose manifest is written last; the directory is then
+ promoted with a single ``os.replace``, so a kill at any instant leaves the previous checkpoint
+ intact and no valid-looking partial behind.
- ``source_checkpoint`` is the bundle this run resumed FROM, when it resumed. It is what
- makes the "this step is already written" shortcut below safe: without it, a stop at a
- step some OTHER run happens to have written would silently keep that run's state.
+ ``source_checkpoint`` is the bundle this run resumed FROM, when it resumed. It is what makes the
+ "this step is already written" shortcut below safe: without it, a stop at a step some OTHER run
+ happens to have written would silently keep that run's state.
- ``discard_existing`` drops any bundle already in the directory first. A run that did NOT
- resume owns its output dir outright (it overwrites the published adapter there too), so
- checkpoints left by an EARLIER run of the same adapter name must go: they would otherwise
- outrank the new run's lower-numbered ones and a later Resume would silently continue the
- wrong training.
+ ``discard_existing`` drops any bundle already in the directory first. A run that did NOT resume
+ owns its output dir outright (it overwrites the published adapter there too), so checkpoints
+ left by an EARLIER run of the same adapter name must go: they would otherwise outrank the new
+ run's lower-numbered ones and a later Resume would silently continue the wrong training.
- Raises OSError / ValueError / RuntimeError on a real write failure -- callers treat that
- as "this run cannot be resumed" and surface it, rather than failing the training."""
+ Raises OSError / ValueError / RuntimeError on a real write failure -- callers treat that as
+ "this run cannot be resumed" and surface it, rather than failing the training.
+ """
import torch
from safetensors.torch import save_file
@@ -790,14 +761,14 @@ def save_checkpoint(
root.mkdir(parents = True, exist_ok = True)
doomed: list[Path] = []
if discard_existing:
- # Deleted only AFTER the new bundle is promoted: clearing first leaves the directory with no
- # checkpoint at all if the write dies.
+ # Deleted only AFTER the new bundle is promoted: clearing first leaves the directory with no checkpoint at all
+ # if the write dies.
doomed = list_checkpoints(root)
else:
- # Re-reaching a step that already has a valid bundle is safe only when the state is byte-identical,
- # and keeping it avoids _promote's one destructive branch.
- # It has to be THAT bundle: resuming checkpoint-10 in a folder that also holds checkpoint-15 and
- # stopping at 15 would drop the freshly trained state and name an earlier run's bundle.
+ # Re-reaching a step that already has a valid bundle is safe only when the state is byte-identical, and
+ # keeping it avoids _promote's one destructive branch. It has to be THAT bundle: resuming checkpoint-10 in a
+ # folder that also holds checkpoint-15 and stopping at 15 would drop the freshly trained state and name an
+ # earlier run's bundle.
existing = root / f"{CHECKPOINT_PREFIX}{step}"
if (
source_checkpoint is not None
@@ -817,13 +788,13 @@ def save_checkpoint(
_save_tensors(save_file, ema_state, staging / EMA_FILENAME)
files["ema"] = EMA_FILENAME
if optimizer is not None:
- # torch.save, not safetensors: optimizer state is nested tensors AND scalars (AdamW8bit adds uint8
- # moments plus quantization maps), which safetensors cannot express.
+ # torch.save, not safetensors: optimizer state is nested tensors AND scalars (AdamW8bit adds uint8 moments
+ # plus quantization maps), which safetensors cannot express.
_torch_save(torch, optimizer.state_dict(), staging / OPTIMIZER_FILENAME)
files["optimizer"] = OPTIMIZER_FILENAME
optimizer_class = optimizer_key(optimizer)
- # adapter_state is trainable_state_dict(model), i.e. named_parameters() order, the same traversal
- # the trainers build their param list from, so its key order IS the optimizer's positional order.
+ # adapter_state is trainable_state_dict(model), i.e. named_parameters() order, the same traversal the
+ # trainers build their param list from, so its key order IS the optimizer's positional order.
optimizer_param_names = [str(name) for name in adapter_state]
if lr_scheduler is not None:
_torch_save(torch, lr_scheduler.state_dict(), staging / SCHEDULER_FILENAME)
@@ -833,9 +804,9 @@ def save_checkpoint(
rng_json = rng.get("json")
rng_tensors = rng.get("tensors") or {}
if not rng_tensors:
- # capture_rng_state never raises, so a generator it could not snapshot produced a bundle with no
- # rng file that _assert_required_state refuses on Resume; fail the WRITE instead, which the caller
- # reports as resume_blocked_reason.
+ # capture_rng_state never raises, so a generator it could not snapshot produced a bundle with no rng
+ # file that _assert_required_state refuses on Resume; fail the WRITE instead, which the caller reports
+ # as resume_blocked_reason.
raise RuntimeError(
"the run's random-number state could not be captured, so this checkpoint "
"would not be resumable"
@@ -849,22 +820,21 @@ def save_checkpoint(
"kind": identity.kind,
"global_step": step,
"target_steps": int(target_steps),
- # Checkpoints are only taken on an optimizer-step boundary; recorded explicitly so a future mid-
- # accumulation checkpoint is a value change, not a format change.
+ # Checkpoints are only taken on an optimizer-step boundary; recorded explicitly so a future
+ # mid-accumulation checkpoint is a value change, not a format change.
"micro_step": 0,
"created_at": time.time(),
"identity": identity.as_dict(),
"sampler": sampler_state or None,
"rng": rng_json,
"ema_updates": int(ema_updates),
- # bitsandbytes AdamW8bit stores state1/state2 and torch AdamW exp_avg/exp_avg_sq, and the trainers
- # pick between them from the host (bnb present, fused kernel available,
- # UNSLOTH_DIFFUSION_FP32_OPTIM); each loads the other's state_dict and then KeyErrors on the first
- # step, so the resume compares this.
+ # bitsandbytes AdamW8bit stores state1/state2 and torch AdamW exp_avg/exp_avg_sq, and the trainers pick
+ # between them from the host (bnb present, fused kernel available, UNSLOTH_DIFFUSION_FP32_OPTIM); each
+ # loads the other's state_dict and then KeyErrors on the first step, so the resume compares this.
"optimizer_class": optimizer_class,
# Optimizer state is keyed by POSITION, so a traversal-order change rebinds every Adam moment to a
- # different same-shaped tensor and silently corrupts the continuation. Additive, so an older
- # bundle skips the check.
+ # different same-shaped tensor and silently corrupts the continuation. Additive, so an older bundle skips
+ # the check.
"optimizer_param_names": optimizer_param_names,
# Nested rather than merged, so a caller can never shadow a reserved key.
"progress": dict(progress or {}),
@@ -885,8 +855,8 @@ def save_checkpoint(
if stale != final:
shutil.rmtree(stale, ignore_errors = True)
_prune_staging(root)
- # Pin the source bundle too: with keep=2 a run that resumes checkpoint-10 and saves 20 and 30 prunes
- # 10, leaving the original stopped run with no resume point.
+ # Pin the source bundle too: with keep=2 a run that resumes checkpoint-10 and saves 20 and 30 prunes 10, leaving
+ # the original stopped run with no resume point.
prune_checkpoints(
root,
keep = save_total_limit,
@@ -899,14 +869,14 @@ def save_checkpoint(
def optimizer_key(optimizer: Any) -> str:
"""A stable name for an optimizer implementation, e.g. ``bitsandbytes.optim.adamw.AdamW8bit``.
- Fused vs. non-fused torch AdamW share a class and a state layout, so they compare equal."""
+ Fused vs non-fused torch AdamW share a class and a state layout, so they compare equal."""
cls = type(optimizer)
return f"{getattr(cls, '__module__', '?')}.{getattr(cls, '__qualname__', cls.__name__)}"
def _save_tensors(save_file: Any, state: dict[str, Any], path: Path) -> None:
- """safetensors refuses tensors that share storage, so detach/clone every entry onto CPU
- (a LoRA state dict is megabytes, and this runs at most once per save_steps)."""
+ """safetensors refuses tensors that share storage, so detach/clone every entry onto CPU (a LoRA
+ state dict is megabytes, and this runs at most once per save_steps)."""
payload = {
str(k): v.detach().to("cpu", copy = True).contiguous()
for k, v in (state or {}).items()
@@ -937,11 +907,10 @@ def _write_text(path: Path, text: str) -> None:
_fsync_file(path)
-# errno values treated as "this platform or filesystem will not flush that handle": Windows' _commit
-# needs write access, and network/container filesystems return EINVAL/ENOTSUP for fsync. EBADF is the
-# exception and is NOT such a signal -- Windows collapses genuine FlushFileBuffers failures into it
-# too, so it is here as a deliberate tradeoff, not because the data is known to have made it. See
-# _fsync_file for what is left guarding that case.
+# errno values treated as "this platform or filesystem will not flush that handle": Windows' _commit needs write
+# access, and network/container filesystems return EINVAL/ENOTSUP for fsync. EBADF is the exception and is NOT such a
+# signal -- Windows collapses genuine FlushFileBuffers failures into it too, so it is here as a deliberate tradeoff,
+# not because the data is known to have made it. See _fsync_file for what is left guarding that case.
_FSYNC_UNSUPPORTED = frozenset(
code
for code in (
@@ -953,23 +922,24 @@ _FSYNC_UNSUPPORTED = frozenset(
def _fsync_file(path: Path) -> None:
- """Flush the file to the device. Without it a host crash (not just a process kill) can
- promote a directory whose manifest is durable but whose tensors are still in page cache.
-
- A REAL fsync failure is raised, not swallowed: delayed allocation means ENOSPC and writeback
- EIO surface here rather than at write() time, and ``_valid_state_file`` only parses a
- safetensors header, so a bundle whose tensor bytes never reached the device would be
- promoted and later read as valid. The caller turns that into "this run cannot be resumed".
- A platform that simply cannot flush the handle is not such a failure and is ignored.
-
- That discrimination is real on POSIX and NOT available on Windows: CPython maps os.fsync
- to the UCRT's _commit, which collapses every FlushFileBuffers failure into EBADF and puts
- the actual Win32 code in _doserrno, where Python does not look. EBADF has to stay in the
- set below, because a volume that cannot flush reports it too, and failing every save on
- such a volume is the worse error -- especially as the resulting write error is sticky for
- the life of the run record. So on Windows a genuine flush failure is swallowed here, and
- the durability guarantee rests on the per-file size check in read_checkpoint instead,
- which catches the truncation a lost writeback actually produces."""
+ """Flush the file to the device. Without it a host crash (not just a process kill) can promote a
+ directory whose manifest is durable but whose tensors are still in page cache.
+
+ A REAL fsync failure is raised, not swallowed: delayed allocation means ENOSPC and writeback EIO
+ surface here rather than at write() time, and ``_valid_state_file`` only parses a safetensors
+ header, so a bundle whose tensor bytes never reached the device would be promoted and later read
+ as valid. The caller turns that into "this run cannot be resumed". A platform that simply cannot
+ flush the handle is not such a failure and is ignored.
+
+ That discrimination is real on POSIX and NOT available on Windows: CPython maps os.fsync to the
+ UCRT's _commit, which collapses every FlushFileBuffers failure into EBADF and puts the actual
+ Win32 code in _doserrno, where Python does not look. EBADF has to stay in the set below, because
+ a volume that cannot flush reports it too, and failing every save on such a volume is the worse
+ error -- especially as the resulting write error is sticky for the life of the run record. So on
+ Windows a genuine flush failure is swallowed here, and the durability guarantee rests on the
+ per-file size check in read_checkpoint instead, which catches the truncation a lost writeback
+ actually produces.
+ """
try:
# O_RDWR, not O_RDONLY: Windows' _commit maps to FlushFileBuffers, which needs write access on the handle.
fd = os.open(str(path), os.O_RDWR)
@@ -1003,29 +973,30 @@ def _promote(staging: Path, root: Path, step: int) -> Path:
"""Rename the staging directory into place.
``os.replace`` onto an EXISTING directory is not supported (POSIX rename() needs an empty
- target; Windows MoveFileEx rejects it outright), so an occupied slot is first swapped out
- to a staging name. The displaced bundle is KEPT there rather than deleted: two runs can
- share an output directory (resume checkpoint-10 in a folder that also holds checkpoint-15,
- then save at 15), and the older run's bundle is not this run's to spend -- discarding this
- run removes the replacement and hands the slot back to what was there.
+ target; Windows MoveFileEx rejects it outright), so an occupied slot is first swapped out to a
+ staging name. The displaced bundle is KEPT there rather than deleted: two runs can share an
+ output directory (resume checkpoint-10 in a folder that also holds checkpoint-15, then save at
+ 15), and the older run's bundle is not this run's to spend -- discarding this run removes the
+ replacement and hands the slot back to what was there.
A swap-aside that CANNOT be done (a Windows lock, a cross-device oddity) fails the save.
Deleting the occupant to free the slot was the older behaviour and the worse one: a partial
- delete can fail the promotion too, and by then there is no copy left to put back."""
+ delete can fail the promotion too, and by then there is no copy left to put back.
+ """
final = root / f"{CHECKPOINT_PREFIX}{step}"
displaced: Optional[Path] = None
if final.exists():
displaced = root / f"{_STAGING_PREFIX}replaced-{step}-{uuid.uuid4().hex[:8]}"
os.replace(final, displaced)
- # os.replace does NOT restamp the directory, so a moved-aside bundle looked long-abandoned the
- # instant it arrived; stamp it with the moment of the swap.
+ # os.replace does NOT restamp the directory, so a moved-aside bundle looked long-abandoned the instant it
+ # arrived; stamp it with the moment of the swap.
with contextlib.suppress(OSError):
os.utime(displaced, None)
try:
os.replace(staging, final)
except OSError:
- # Put the moved-aside copy back before the failure propagates, else a failed resave of an occupied
- # step leaves the run with no checkpoint at all.
+ # Put the moved-aside copy back before the failure propagates, else a failed resave of an occupied step leaves
+ # the run with no checkpoint at all.
if displaced is not None:
with contextlib.suppress(OSError):
os.replace(displaced, final)
@@ -1034,23 +1005,23 @@ def _promote(staging: Path, root: Path, step: int) -> Path:
return final
-# The step is encoded in the name so an orphan can be handed back to its slot: "stale" is a
-# promotion killed mid-swap, "replaced" is a bundle a later write displaced.
+# The step is encoded in the name so an orphan can be handed back to its slot: "stale" is a promotion killed mid-swap,
+# "replaced" is a bundle a later write displaced.
_STALE_SLOT = re.compile(r"^(?:stale|replaced)-(\d+)-")
_REPLACED_SLOT = re.compile(r"^replaced-(\d+)-")
def _prune_staging(root: Path) -> None:
- """Drop abandoned staging directories from an earlier killed process. Safe because only
- one trainer ever writes into a run's output dir, and this runs after our own promotion.
+ """Drop abandoned staging directories from an earlier killed process. Safe because only one trainer
+ ever writes into a run's output dir, and this runs after our own promotion.
- A ``stale-<step>`` orphan whose slot is EMPTY is not abandoned work: it is the previous
- bundle, moved aside by a promotion that was killed before the rename landed. Deleting it
- would throw away the run's last resumable state, so it is handed back to its slot instead.
+ A ``stale-<step>`` orphan whose slot is EMPTY is not abandoned work: it is the previous bundle,
+ moved aside by a promotion that was killed before the rename landed. Deleting it would throw
+ away the run's last resumable state, so it is handed back to its slot instead.
- A ``replaced-<step>`` orphan is not abandoned work either, even with its slot occupied: it
- is the bundle THIS run displaced, held so that discarding this run does not take another
- run's resume point with it. Only the cleanup paths retire those.
+ A ``replaced-<step>`` orphan is not abandoned work either, even with its slot occupied: it is
+ the bundle THIS run displaced, held so that discarding this run does not take another run's
+ resume point with it. Only the cleanup paths retire those.
"""
try:
entries = list(root.glob(f"{_STAGING_PREFIX}*"))
@@ -1072,21 +1043,19 @@ def _prune_staging(root: Path) -> None:
shutil.rmtree(entry, ignore_errors = True)
-# A read landing in _promote's microsecond window moved the old bundle back, so the writer's
-# os.replace failed and the checkpoint was lost; only replaced- entries wait, and writers pass 0.
+# A read landing in _promote's microsecond window moved the old bundle back, so the writer's os.replace failed and the
+# checkpoint was lost; only replaced- entries wait, and writers pass 0.
_LIVE_REPLACEMENT_GRACE_SECONDS = 5.0
def _recover_orphaned_slots(
root: Path, *, min_age: float = _LIVE_REPLACEMENT_GRACE_SECONDS
) -> None:
- """Hand every stale orphan back to its empty slot. Read paths call this before deciding a
- run has nothing to resume; it never deletes anything.
-
- Newest first per slot, for the reason ``_retire_replaced_slots`` sorts: replacements stack,
- and filesystem order would restore whichever appeared first -- an older branch's adapter,
- optimizer and RNG rather than the bundle that was in the slot immediately before the crash.
- """
+ """Hand every stale orphan back to its empty slot. Read paths call this before deciding a run
+ has nothing to resume; it never deletes anything. Newest first per slot, for the reason
+ ``_retire_replaced_slots`` sorts: replacements stack, and filesystem order would restore
+ whichever appeared first, an older branch's adapter, optimizer and RNG rather than the bundle
+ that was in the slot immediately before the crash."""
try:
entries = list(root.glob(f"{_STAGING_PREFIX}*"))
except OSError:
@@ -1107,9 +1076,9 @@ def _recover_orphaned_slots(
def _recover_orphaned_slot(root: Path, entry: Path) -> bool:
- """True when ``entry`` is a stale bundle that must not be swept up: either it was handed
- back to its empty slot, or the hand-back failed and leaving it on disk beats deleting the
- only copy of the run's last resumable state."""
+ """True when ``entry`` is a stale bundle that must not be swept up: either it was handed back to
+ its empty slot, or the hand-back failed and leaving it on disk beats deleting the only copy
+ of the run's last resumable state."""
match = _STALE_SLOT.match(entry.name[len(_STAGING_PREFIX) :])
if match is None:
return False
@@ -1125,21 +1094,18 @@ def _recover_orphaned_slot(root: Path, entry: Path) -> bool:
def _retire_replaced_slots(root: Path, *, restore: bool) -> None:
- """Settle the bundles this run displaced, once its own are gone.
-
- ``restore`` hands each one back to the slot the cleanup just emptied, which is the whole
- reason it was kept: the pre-existing bundle comes back instead of dying with the run that
- overwrote it. False is the fresh-run case, where the adapter those bundles belong to has
- just been overwritten and they are a trap rather than resumable state. Either way, nothing
- is left behind afterwards.
- """
+ """Settle the bundles this run displaced, once its own are gone. ``restore`` hands each one back
+ to the slot the cleanup just emptied, which is the whole reason it was kept: the pre-existing
+ bundle comes back instead of dying with the run that overwrote it. False is the fresh-run
+ case, where the adapter those bundles belong to has just been overwritten and they are a trap
+ rather than resumable state. Either way, nothing is left behind afterwards."""
try:
entries = list(root.glob(f"{_STAGING_PREFIX}replaced-*"))
except OSError:
return
- # NEWEST first per slot: replacements stack, and restoring whichever sorted first by uuid
- # resurrected an older branch's optimizer state instead of the actual predecessor.
+ # NEWEST first per slot: replacements stack, and restoring whichever sorted first by uuid resurrected an older
+ # branch's optimizer state instead of the actual predecessor.
def _written_at(path: Path) -> float:
try:
return path.stat().st_mtime
@@ -1188,22 +1154,23 @@ def prune_checkpoints(
) -> None:
"""Keep only the ``keep`` newest ``checkpoint-<N>`` bundles. ``keep <= 0`` keeps all.
- ``protect`` and ``also_protect`` are never pruned. Newest is by STEP, and a resume can legitimately write a bundle
- that is not the highest-numbered one in the folder: resume checkpoint-10, stop at 15, with 20
- and 30 still present and keep=2, and the bundle just written is the one deleted -- while the
- service reports checkpoint_saved for a path that no longer exists, and the run's own start
- fence stops those older bundles from making it resumable. So the caller pins the one it just
- promoted, and the limit applies to the rest.
-
- ``preexisting`` are the bundles that were in the directory before this run wrote anything.
- They are not this run's to spend: the supported branched resume (continue checkpoint-10
- while 20 and 30 are still there) pins 10 and the new 15, drops ``keep`` to zero and used to
- delete 20 and 30 outright -- irreversibly, and a later stop-without-saving cannot bring them
- back. They are excluded entirely, so the limit governs only what this run wrote."""
+ ``protect`` and ``also_protect`` are never pruned. Newest is by STEP, and a resume can
+ legitimately write a bundle that is not the highest-numbered one in the folder: resume
+ checkpoint-10, stop at 15, with 20 and 30 still present and keep=2, and the bundle just written
+ is the one deleted, while the service reports checkpoint_saved for a path that no longer exists
+ and the run's own start fence stops those older bundles from making it resumable. So the caller
+ pins the one it just promoted, and the limit applies to the rest.
+
+ ``preexisting`` are the bundles that were in the directory before this run wrote anything. They
+ are not this run's to spend: the supported branched resume (continue checkpoint-10 while 20 and
+ 30 are still there) pins 10 and the new 15, drops ``keep`` to zero and used to delete 20 and 30
+ outright, irreversibly, and a later stop-without-saving cannot bring them back. They are
+ excluded entirely, so the limit governs only what this run wrote.
+ """
if keep <= 0:
return
- # Identity, not pathname: a run can save at a step whose directory already existed, and excluding
- # it as pre-existing let the limit be exceeded once per overwritten slot.
+ # Identity, not pathname: a run can save at a step whose directory already existed, and excluding it as
+ # pre-existing let the limit be exceeded once per overwritten slot.
kept_from_before: set[Path] = set()
for entry in preexisting or ():
if isinstance(entry, tuple):
@@ -1224,8 +1191,8 @@ def prune_checkpoints(
def clear_checkpoints(output_dir: str | os.PathLike[str]) -> None:
- """Remove every ``checkpoint-<N>`` bundle in ``output_dir``. Used when a fresh (non-resumed)
- run takes over an output directory that an earlier run of the same name left checkpoints in."""
+ """Remove every ``checkpoint-<N>`` bundle in ``output_dir``. Used when a fresh (non-resumed) run
+ takes over an output directory that an earlier run of the same name left checkpoints in."""
root = Path(output_dir).expanduser()
for stale in list_checkpoints(root):
shutil.rmtree(stale, ignore_errors = True)
@@ -1233,13 +1200,12 @@ def clear_checkpoints(output_dir: str | os.PathLike[str]) -> None:
def resumed_into_this_dir(cfg: Any, output_dir: "str | os.PathLike[str]") -> bool:
- """Whether the bundle this run resumed FROM lives in ``output_dir``.
-
- The usual case, and the one the first-save discard is skipped for: a resumed run shares its
- source's directory, so clearing "everything that was here" would take the source with it.
- An API caller can instead resume from directory A into a reused output_dir B, and then B's
- contents are as foreign as they would be to a fresh run -- keeping them lets a higher-step
- bundle outlive this run and be picked by a later resume by directory."""
+ """Whether the bundle this run resumed FROM lives in ``output_dir``. The usual case, and the one
+ the first-save discard is skipped for: a resumed run shares its source's directory, so
+ clearing "everything that was here" would take the source with it. An API caller can instead
+ resume from directory A into a reused output_dir B, and then B's contents are as foreign as
+ they would be to a fresh run -- keeping them lets a higher-step bundle outlive this run and
+ be picked by a later resume by directory."""
source = getattr(cfg, "resume_from_checkpoint", None)
if not source:
return False
@@ -1253,11 +1219,10 @@ def resumed_into_this_dir(cfg: Any, output_dir: "str | os.PathLike[str]") -> boo
def snapshot_checkpoints(output_dir: str | os.PathLike[str]) -> list[tuple[Path, Optional[tuple]]]:
- """The bundles in ``output_dir`` right now, each with its identity.
-
- Captured BEFORE the run's first write, because ownership cannot be decided by pathname at
- cleanup time: a resumed run can overwrite a bundle that was already there, and by then the
- directory holds this run's state under the old name."""
+ """The bundles in ``output_dir`` right now, each with its identity. Captured BEFORE the run's
+ first write, because ownership cannot be decided by pathname at cleanup time: a resumed run
+ can overwrite a bundle that was already there, and by then the directory holds this run's
+ state under the old name."""
return [(path, _bundle_identity(path)) for path in list_checkpoints(output_dir)]
@@ -1271,15 +1236,15 @@ def retire_own_checkpoints(
Same selection as ``clear_own_checkpoints`` and a different reason: nothing here is being
discarded, the run simply has no continuation left. Without it the newest bundle in the
- directory is the last periodic save (the final iteration writes none), and a later resume
- -- which cannot see that the run completed -- rolls the whole training state back to it.
+ directory is the last periodic save (the final iteration writes none), and a later resume --
+ which cannot see that the run completed -- rolls the whole training state back to it.
``resumed_here`` False means a FRESH run in this directory, and then the bundles that were
- already here go too. A fresh run that never wrote one of its own (the default
- ``save_steps=0``) never reaches the ``discard_existing`` clear inside the writer, so it
- published its adapter beside a previous run's checkpoints -- which a later resume by output
- directory would continue instead. The adapter those belonged to has just been overwritten,
- so they are not resumable state, only a trap.
+ already here go too. A fresh run that never wrote one of its own (the default ``save_steps=0``)
+ never reaches the ``discard_existing`` clear inside the writer, so it published its adapter
+ beside a previous run's checkpoints, which a later resume by output directory would continue
+ instead. The adapter those belonged to has just been overwritten, so they are not resumable
+ state, only a trap.
"""
if resumed_here:
clear_own_checkpoints(output_dir, preexisting)
@@ -1294,14 +1259,12 @@ def discard_preexisting_checkpoints(
output_dir: str | os.PathLike[str], preexisting: "Iterable[Any]"
) -> None:
"""Remove the bundles this run FOUND, keeping the ones it wrote. The inverse of
- ``clear_own_checkpoints``.
-
- For a fresh retrain that stops WITH save: it owns the directory (it overwrites the published
- adapter there), and its stop bundle is a lower step than an earlier run's leftovers. Resume
- by directory picks the newest bundle by step, so those leftovers outrank the partial the user
- just saved and a Resume continues the wrong training. A run that RESUMED here does not call
- this: the bundles it found include the one it continued from, which is not its to spend.
- """
+ ``clear_own_checkpoints``. For a fresh retrain that stops WITH save: it owns the directory
+ (it overwrites the published adapter there), and its stop bundle is a lower step than an
+ earlier run's leftovers. Resume by directory picks the newest bundle by step, so those
+ leftovers outrank the partial the user just saved and a Resume continues the wrong training.
+ A run that RESUMED here does not call this: the bundles it found include the one it continued
+ from, which is not its to spend."""
root = Path(output_dir).expanduser()
keep: dict[Path, Optional[tuple]] = {}
for entry in preexisting:
@@ -1311,21 +1274,19 @@ def discard_preexisting_checkpoints(
else:
keep[Path(entry)] = _bundle_identity(Path(entry))
for stale in list_checkpoints(root):
- # Identity, not pathname: a bundle this run wrote OVER one that was here is this run's, and deleting
- # it would throw away the stop checkpoint the user asked for.
+ # Identity, not pathname: a bundle this run wrote OVER one that was here is this run's, and deleting it would
+ # throw away the stop checkpoint the user asked for.
if stale in keep and keep[stale] == _bundle_identity(stale):
shutil.rmtree(stale, ignore_errors = True)
_retire_replaced_slots(root, restore = False)
def discard_named_checkpoints(paths: "Iterable[Any]") -> None:
- """Remove the exact bundles named, then hand any slot they displaced back.
-
- The parent-side twin of ``clear_own_checkpoints``: a child that is killed after a
- stop-without-saving never runs its own cleanup, and the parent knows only the paths it saw
- ``checkpoint_saved`` for -- which is precisely the set this run wrote. Anything that predated
- the run is untouched, and a bundle written OVER a predecessor gives its slot back.
- """
+ """Remove the exact bundles named, then hand any slot they displaced back. The parent-side twin
+ of ``clear_own_checkpoints``: a child that is killed after a stop-without-saving never runs
+ its own cleanup, and the parent knows only the paths it saw ``checkpoint_saved`` for, which
+ is precisely the set this run wrote. Anything that predated the run is untouched, and a
+ bundle written OVER a predecessor gives its slot back."""
roots: set[Path] = set()
for value in paths:
if not value:
@@ -1343,16 +1304,14 @@ def discard_named_checkpoints(paths: "Iterable[Any]") -> None:
def clear_own_checkpoints(output_dir: str | os.PathLike[str], preexisting: "Iterable[Any]") -> None:
- """Remove the bundles THIS run wrote, leaving the ones it found.
-
- A discard must not take the checkpoint the run resumed FROM with it: a resumed run writes
- into the same directory the source bundle lives in, so an accidental resume followed by
- "stop without saving" would otherwise leave the original stopped run unresumable -- the one
- thing the user was trying not to disturb. Bundles are identified by the set captured before
- the run's first write, not by step number, because a resume writes lower numbers than the
- ones already there."""
- # Keyed by path AND by identity: a periodic save can REPLACE a pre-existing bundle, and matching
- # on the name alone preserved the discarded run's replacement as the bundle it overwrote.
+ """Remove the bundles THIS run wrote, leaving the ones it found. A discard must not take the
+ checkpoint the run resumed FROM with it: a resumed run writes into the same directory the
+ source bundle lives in, so an accidental resume followed by "stop without saving" would
+ otherwise leave the original stopped run unresumable, the one thing the user was trying not
+ to disturb. Bundles are identified by the set captured before the run's first write, not by
+ step number, because a resume writes lower numbers than the ones already there."""
+ # Keyed by path AND by identity: a periodic save can REPLACE a pre-existing bundle, and matching on the name alone
+ # preserved the discarded run's replacement as the bundle it overwrote.
keep: dict[Path, Optional[tuple]] = {}
for entry in preexisting:
# A bare path (an older caller) keeps the pathname-only behaviour for that entry.
@@ -1365,28 +1324,26 @@ def clear_own_checkpoints(output_dir: str | os.PathLike[str], preexisting: "Iter
if stale in keep and keep[stale] == _bundle_identity(stale):
continue
shutil.rmtree(stale, ignore_errors = True)
- # Put the displaced original back: the replacement is not the bundle it overwrote, so the identity
- # match cannot keep it and the original was already gone.
+ # Put the displaced original back: the replacement is not the bundle it overwrote, so the identity match cannot
+ # keep it and the original was already gone.
_retire_replaced_slots(Path(output_dir).expanduser(), restore = True)
def _bundle_identity(path: Path) -> Optional[tuple]:
- """What distinguishes one bundle at this path from another written over it.
-
- The manifest is written last and carries the writing run's own start time, so it separates
- "the bundle that was here" from "the bundle this run put here" without hashing tensors.
- None for an unreadable or absent manifest, which compares equal to itself and so leaves an
- unreadable pre-existing directory alone."""
+ """What distinguishes one bundle at this path from another written over it. The manifest is
+ written last and carries the writing run's own start time, so it separates "the bundle that
+ was here" from "the bundle this run put here" without hashing tensors. None for an unreadable
+ or absent manifest, which compares equal to itself and so leaves an unreadable pre-existing
+ directory alone."""
try:
manifest = json.loads((path / TRAINER_STATE_FILENAME).read_text(encoding = "utf-8"))
except (OSError, ValueError):
return None
- # created_at is when THIS bundle's manifest was written, the completion marker, so it exists on
- # every valid bundle and differs between two writes at the same step.
+ # created_at is when THIS bundle's manifest was written, the completion marker, so it exists on every valid bundle
+ # and differs between two writes at the same step.
return (manifest.get("created_at"), manifest.get("global_step"))
-# ── reading + validation ──────────────────────────────────────────────────────
def checkpoint_step(path: Path) -> int:
"""The step encoded in a ``checkpoint-<N>`` directory name, or -1."""
name = path.name
@@ -1411,13 +1368,11 @@ def list_checkpoints(output_dir: str | os.PathLike[str]) -> list[Path]:
def read_checkpoint(path: str | os.PathLike[str]) -> Optional[dict[str, Any]]:
- """The manifest of a COMPLETE, self-consistent bundle, or None.
-
- Every gate a resume depends on is checked here: the manifest parses and declares a
- format/version this build understands, its ``global_step`` agrees with the directory
- name, and every file the manifest lists is present and parses as the state file it
- claims to be. A staging directory promoted mid-write cannot pass, because the manifest
- is the last thing written."""
+ """The manifest of a COMPLETE, self-consistent bundle, or None. Every gate a resume depends on
+ is checked here: the manifest parses and declares a format/version this build understands,
+ its ``global_step`` agrees with the directory name, and every file the manifest lists is
+ present and parses as the state file it claims to be. A staging directory promoted mid-write
+ cannot pass, because the manifest is the last thing written."""
directory = Path(path).expanduser()
if not directory.is_dir():
return None
@@ -1450,8 +1405,8 @@ def read_checkpoint(path: str | os.PathLike[str]) -> Optional[dict[str, Any]]:
for role, name in files.items():
if not isinstance(name, str) or not name or Path(name).name != name:
return None
- # Optimizer and scheduler state can validly be tensor-free (SGD without momentum, a constant LR
- # schedule), so only the weight bundles must carry tensors.
+ # Optimizer and scheduler state can validly be tensor-free (SGD without momentum, a constant LR schedule), so
+ # only the weight bundles must carry tensors.
if not _valid_state_file(directory / name, require_tensor = role in ("adapter", "ema")):
return None
expected_size = sizes.get(role)
@@ -1466,13 +1421,11 @@ def read_checkpoint(path: str | os.PathLike[str]) -> Optional[dict[str, Any]]:
def _valid_state_file(path: Path, require_tensor: bool = True) -> bool:
- """Reuse the LLM resume validator: it already parses a safetensors header and walks a
- torch zip's pickle to the STOP opcode without importing torch.
-
- Wrapped in a blanket catch because a resume path is CLIENT-supplied: that validator only
- guards ``(OSError, ValueError, BadZipFile)``, so a deflate-corrupt member raises
- ``zlib.error`` straight out of a route preflight and 500s it. Anything unreadable is, by
- definition, not a usable checkpoint."""
+ """Reuse the LLM resume validator: it already parses a safetensors header and walks a torch
+ zip's pickle to the STOP opcode without importing torch. Wrapped in a blanket catch because a
+ resume path is CLIENT-supplied: that validator only guards ``(OSError, ValueError,
+ BadZipFile)``, so a deflate-corrupt member raises ``zlib.error`` straight out of a route
+ preflight and 500s it. Anything unreadable is, by definition, not a usable checkpoint."""
from core.training.resume import _valid_state_file as _validate
try:
return _validate(path, require_tensor = require_tensor)
@@ -1486,24 +1439,24 @@ def latest_valid_checkpoint(
not_after: Optional[float] = None,
usable: "Optional[Callable[[Path, dict], bool]]" = None,
) -> Optional[tuple[Path, dict]]:
- """The newest complete bundle under ``output_dir`` as ``(path, manifest)``, or None.
- Scans newest-first and skips any bundle that fails validation, so one corrupt
- checkpoint does not hide the good one before it.
+ """The newest complete bundle under ``output_dir`` as ``(path, manifest)``, or None. Scans
+ newest-first and skips any bundle that fails validation, so one corrupt checkpoint does not hide
+ the good one before it.
``not_before`` (a run's start time) skips bundles written BEFORE it. Two runs can share an
- output directory -- training the same adapter name twice writes into the same folder -- and
- the earlier run's bundles can carry higher step numbers than the later run's, so without
- this a fresh run would advertise, and then resume, a different run's training state.
-
- ``not_after`` (a run's end time) is the same fence in the other direction, and it matters
- just as much: with only a lower bound, an EARLIER run that has already finished still sees
- every bundle a LATER run wrote into the shared folder, and offers the newest of them as
- its own. The identity gate cannot catch that -- same family, same base, same dataset, same
- LoRA shape -- so the earlier run resumes the later run's optimizer moments, LR position
- and RNG under its own config, and records the wrong lineage while doing it."""
- # A promotion killed mid-swap leaves the only bundle under the hidden stale name, and
- # _prune_staging runs only after a later save a stuck user never reaches. Idempotent, and it only
- # ever touches an EMPTY slot.
+ output directory -- training the same adapter name twice writes into the same folder -- and the
+ earlier run's bundles can carry higher step numbers than the later run's, so without this a
+ fresh run would advertise, and then resume, a different run's training state.
+
+ ``not_after`` (a run's end time) is the same fence in the other direction, and it matters just
+ as much: with only a lower bound, an EARLIER run that has already finished still sees every
+ bundle a LATER run wrote into the shared folder, and offers the newest of them as its own. The
+ identity gate cannot catch that -- same family, same base, same dataset, same LoRA shape -- so
+ the earlier run resumes the later run's optimizer moments, LR position and RNG under its own
+ config, and records the wrong lineage while doing it.
+ """
+ # A promotion killed mid-swap leaves the only bundle under the hidden stale name, and _prune_staging runs only
+ # after a later save a stuck user never reaches. Idempotent, and it only ever touches an EMPTY slot.
_recover_orphaned_slots(Path(output_dir).expanduser())
for candidate in list_checkpoints(output_dir):
manifest = read_checkpoint(candidate)
@@ -1533,7 +1486,6 @@ def latest_valid_checkpoint(
def iter_valid_checkpoints(output_dir: str | os.PathLike[str]) -> "list[tuple[Path, dict]]":
"""Every structurally complete bundle under ``output_dir``, newest first.
-
``latest_valid_checkpoint`` answers with the first one; the resume preflight needs the rest,
because its own checks (identity, required state, a real torch.load) are stricter than the
header scan. Stopping at the newest defeated the two-checkpoint retention policy: a bundle
@@ -1557,12 +1509,10 @@ _UNRESUMABLE_STATUS = {
def _fully_loadable(path: Path, manifest: dict[str, Any]) -> bool:
"""Whether ``path`` passes every non-identity gate ``preflight_resume`` applies.
-
``read_checkpoint`` is a header scan, so the newest bundle can pass it and still fail the
required-state check or a real torch.load. Advertising THAT one as the run's resume point
pinned it: the UI sends back the exact checkpoint_path, which the preflight then treats as
- explicit and cannot scan past -- defeating the directory fallback built for this case.
- """
+ explicit and cannot scan past, defeating the directory fallback built for this case."""
try:
_assert_required_state(path, manifest)
_assert_optimizer_buildable(path, manifest)
@@ -1577,17 +1527,17 @@ def _source_checkpoint_bundle(
) -> Optional[tuple[Path, dict[str, Any]]]:
"""The bundle a run RESUMED FROM, when it is still readable on disk AND still the same one.
- A resume that ends before writing a bundle of its own -- an OOM on the first restored step
- is the usual way -- has nothing under its own output dir, and if that dir is a new one it
- may not even exist. The source it was validated against is still there and still correct to
- continue from, so it is read directly rather than by widening the started_at fence, which
- exists to keep an unrelated earlier run's bundles out.
-
- ``source_created_at`` is the manifest timestamp recorded when this run actually resumed.
- A pathname is not an identity: another run can write its own ``checkpoint-<N>`` over the
- same slot, and with a matching training identity the route would accept it -- silently
- continuing a different branch's adapter and moments under this run's lineage. Absent (an
- older record), the check is skipped rather than refusing an otherwise valid fallback.
+ A resume that ends before writing a bundle of its own -- an OOM on the first restored step is
+ the usual way -- has nothing under its own output dir, and if that dir is a new one it may not
+ even exist. The source it was validated against is still there and still correct to continue
+ from, so it is read directly rather than by widening the started_at fence, which exists to keep
+ an unrelated earlier run's bundles out.
+
+ ``source_created_at`` is the manifest timestamp recorded when this run actually resumed. A
+ pathname is not an identity: another run can write its own ``checkpoint-<N>`` over the same
+ slot, and with a matching training identity the route would accept it, silently continuing a
+ different branch's adapter and moments under this run's lineage. Absent (an older record), the
+ check is skipped rather than refusing an otherwise valid fallback.
"""
if not source_checkpoint:
return None
@@ -1606,8 +1556,8 @@ def _source_checkpoint_bundle(
# Not the bundle this run resumed: something replaced the slot after the fact.
if not written or abs(written - float(source_created_at)) > 1e-6:
return None
- # Same gate the directory scan applies: this path is pinned back verbatim and read_checkpoint is
- # only a header scan, so a source that lost required state would be advertised as resumable.
+ # Same gate the directory scan applies: this path is pinned back verbatim and read_checkpoint is only a header
+ # scan, so a source that lost required state would be advertised as resumable.
if not _fully_loadable(candidate, manifest):
return None
return (candidate, manifest)
@@ -1623,13 +1573,12 @@ def describe_resume_state(
source_created_at: Optional[float] = None,
total_steps: Optional[int] = None,
) -> dict[str, Any]:
- """What the UI needs to offer (or explain the absence of) a Resume action for a run.
-
- Returns ``can_resume`` / ``checkpoint_step`` / ``checkpoint_path`` /
- ``resume_blocked_reason``. Mirrors the LLM ``can_resume_run`` rules: a completed run has
- nothing left, a stopped run needs remaining steps, an errored run is resumable purely on
- the state it left behind. Never raises: a deleted or unreadable output directory simply
- reports that there is nothing to resume from."""
+ """What the UI needs to offer (or explain the absence of) a Resume action for a run. Returns
+ ``can_resume`` / ``checkpoint_step`` / ``checkpoint_path`` / ``resume_blocked_reason``.
+ Mirrors the LLM ``can_resume_run`` rules: a completed run has nothing left, a stopped run
+ needs remaining steps, an errored run is resumable purely on the state it left behind. Never
+ raises: a deleted or unreadable output directory simply reports that there is nothing to
+ resume from."""
blank: dict[str, Any] = {
"can_resume": False,
"checkpoint_step": None,
@@ -1644,8 +1593,8 @@ def describe_resume_state(
try:
root = Path(str(output_dir)).expanduser()
if not root.is_dir():
- # A resume into a NEW output dir that died before its first save never created it, so the fallback
- # below has to be reachable from here.
+ # A resume into a NEW output dir that died before its first save never created it, so the fallback below
+ # has to be reachable from here.
recovered = _source_checkpoint_bundle(source_checkpoint, source_created_at)
if recovered is None:
return {
@@ -1663,8 +1612,8 @@ def describe_resume_state(
usable = _fully_loadable,
)
if found is None and source_checkpoint:
- # A run that resumed and died before its first save has a source bundle predating started_at: read
- # it directly rather than widening the fence, which exists to hide unrelated earlier runs.
+ # A run that resumed and died before its first save has a source bundle predating started_at: read it
+ # directly rather than widening the fence, which exists to hide unrelated earlier runs.
found = _source_checkpoint_bundle(source_checkpoint, source_created_at)
except OSError:
return blank
@@ -1703,14 +1652,11 @@ def describe_resume_state(
}
-# ── resume preflight ──────────────────────────────────────────────────────────
def resolve_resume_dir(path_value: str) -> Path:
- """Contain a client-supplied resume path under the Unsloth outputs root.
-
- Accepts either the run's ``output_dir`` (what the UI replays, matching the LLM resume
- flow) or an explicit ``checkpoint-<N>`` directory. Raises ResumeError with a
- user-facing message for a path that escapes outputs, comes from another operating
- system, or no longer exists."""
+ """Contain a client-supplied resume path under the Unsloth outputs root. Accepts either the
+ run's ``output_dir`` (what the UI replays, matching the LLM resume flow) or an explicit
+ ``checkpoint-<N>`` directory. Raises ResumeError with a user-facing message for a path that
+ escapes outputs, comes from another operating system, or no longer exists."""
from core.training.resume import normalize_resume_output_dir
from utils.paths import outputs_root
@@ -1719,35 +1665,32 @@ def resolve_resume_dir(path_value: str) -> Path:
except ValueError as error:
message = str(error)
if not message.startswith("Resume checkpoint"):
- # The containment resolver's message quotes server paths at the user; replace it with the resume
- # flow's wording.
+ # The containment resolver's message quotes server paths at the user; replace it with the resume flow's
+ # wording.
message = "Resume checkpoint must be inside Unsloth outputs."
raise ResumeError(message) from error
- # A name that cleans away to nothing (".", "outputs", "./.") lands on the outputs ROOT, where the
- # scan would sweep checkpoint dirs across unrelated runs. Same guard the start route applies to
- # output_dir.
+ # A name that cleans away to nothing (".", "outputs", "./.") lands on the outputs ROOT, where the scan would sweep
+ # checkpoint dirs across unrelated runs. Same guard the start route applies to output_dir.
if resolved.resolve(strict = False) == outputs_root().resolve(strict = False):
- # Named like a bundle, is not one, and holds no bundles either: the original message is the accurate
- # one.
+ # Named like a bundle, is not one, and holds no bundles either: the original message is the accurate one.
raise ResumeError(
f"'{path_value}' is the outputs folder itself, not a training run inside it."
)
return resolved
-# Kept here rather than inferred from the manifest: _assert_loadable only opens the roles the
-# bundle LISTS, so an adapter-only checkpoint passed the route preflight and the child then died
-# after the resident GPU model was evicted.
-# The random.Random streams both trainers hand to capture_rng_state; the preflight has to know what
-# a complete bundle carries.
+# Kept here rather than inferred from the manifest: _assert_loadable only opens the roles the bundle LISTS, so an
+# adapter-only checkpoint passed the route preflight and the child then died after the resident GPU model was evicted.
+# The random.Random streams both trainers hand to capture_rng_state; the preflight has to know what a complete bundle
+# carries.
_TRAINER_RNG_STREAMS: tuple[str, ...] = ("loop", "variant")
_REQUIRED_STATE: tuple[tuple[str, str], ...] = (
("adapter", "the trained LoRA weights"),
("optimizer", "the optimizer moments"),
("scheduler", "the learning-rate schedule position"),
- # Both image trainers draw the latent, noise and timestep from torch immediately after resume, so a
- # bundle with no RNG file continues a different stream and says nothing.
+ # Both image trainers draw the latent, noise and timestep from torch immediately after resume, so a bundle with no
+ # RNG file continues a different stream and says nothing.
("rng", "the random-number generator state"),
)
@@ -1761,14 +1704,14 @@ def _assert_required_state(path: Path, manifest: dict[str, Any]) -> None:
for role, label in _REQUIRED_STATE
if not isinstance(listed.get(role), str) or not listed.get(role)
]
- # Required for an image bundle, where both trainers always supply a sampler and the child refuses
- # without it; optional for any other kind.
+ # Required for an image bundle, where both trainers always supply a sampler and the child refuses without it;
+ # optional for any other kind.
if str(manifest.get("kind") or "image") == "image" and not isinstance(
manifest.get("sampler"), dict
):
missing.append("the dataset sampler position")
- # restore_rng_state is per-part best-effort, so a bundle that lists the rng file but lost either
- # random.Random stream leaves crop/flip selection and the sampler permutation freshly seeded.
+ # restore_rng_state is per-part best-effort, so a bundle that lists the rng file but lost either random.Random
+ # stream leaves crop/flip selection and the sampler permutation freshly seeded.
rng_manifest = manifest.get("rng")
saved_streams = rng_manifest.get("streams") if isinstance(rng_manifest, dict) else None
if not isinstance(saved_streams, dict) or not all(
@@ -1792,17 +1735,17 @@ def _join_clauses(items: list[str]) -> str:
def _assert_optimizer_buildable(path: Path, manifest: dict[str, Any]) -> None:
"""Refuse moments this host provably cannot build an optimizer for, BEFORE teardown.
- The trainers choose bitsandbytes AdamW8bit or torch AdamW from the HOST, so a bundle can
- arrive with foreign moments -- and the child's own check then fires after the route has
- evicted the resident inference models and loaded a multi-GB base, for a run that is
- guaranteed to terminate without training.
+ The trainers choose bitsandbytes AdamW8bit or torch AdamW from the HOST, so a bundle can arrive
+ with foreign moments, and the child's own check then fires after the route has evicted the
+ resident inference models and loaded a multi-GB base, for a run that is guaranteed to terminate
+ without training.
Deliberately one-directional, and deliberately import-free. ``find_spec`` answers "is
- bitsandbytes installed" without creating a CUDA context in the Unsloth process, but it
- cannot tell an installed-and-broken wheel (which the trainer catches and falls back from)
- from a working one. So only the case that cannot be wrong is refused here: 8-bit moments
- with no bitsandbytes to load them, or with the fp32 override forcing torch AdamW. The
- other direction stays with the child, where the real optimizer object exists.
+ bitsandbytes installed" without creating a CUDA context in the Unsloth process, but it cannot
+ tell an installed-and-broken wheel (which the trainer catches and falls back from) from a
+ working one. So only the case that cannot be wrong is refused here: 8-bit moments with no
+ bitsandbytes to load them, or with the fp32 override forcing torch AdamW. The other direction
+ stays with the child, where the real optimizer object exists.
"""
saved = manifest.get("optimizer_class")
if not isinstance(saved, str) or "bitsandbytes" not in saved:
@@ -1827,17 +1770,14 @@ def _assert_optimizer_buildable(path: Path, manifest: dict[str, Any]) -> None:
def _assert_loadable(path: Path, manifest: dict[str, Any]) -> None:
- """Actually open every state file the manifest lists, and turn any failure into a
- ResumeError.
-
+ """Actually open every state file the manifest lists, and turn any failure into a ResumeError.
read_checkpoint deliberately only parses headers -- it is called once per bundle by the
run-history listing, which must stay cheap -- so it cannot tell a torch zip that walks to
STOP from one torch.load will refuse. A pickle carrying a global outside the weights_only
allowlist is exactly that, and it passed the route preflight: 200 OK, resident GPU model
evicted, then the child died on a raw UnpicklingError. That is precisely the outcome the
- module docstring promises this preflight prevents, so pay the load here, on the one
- bundle a user actually asked to resume. These are MB-scale files and this runs in a
- worker thread."""
+ module docstring promises this preflight prevents, so pay the load here, on the one bundle a
+ user actually asked to resume. These are MB-scale files and this runs in a worker thread."""
loaded = LoadedCheckpoint(path = path, manifest = manifest)
files = manifest.get("files")
for role in (files or {}) if isinstance(files, dict) else ():
@@ -1868,18 +1808,15 @@ def _assert_loadable(path: Path, manifest: dict[str, Any]) -> None:
def preflight_resume(
path_value: str, *, identity: CheckpointIdentity, target_steps: int
) -> tuple[str, int]:
- """Validate a resume request and return ``(checkpoint_dir, resumed_step)``.
-
- Called by the start route BEFORE the resident GPU model is evicted, and again inside
- the trainer, so a rejected resume never costs the user their loaded pipeline. Raises
- ResumeError with a message written for the user.
-
- ``identity`` may leave ``dataset_fingerprint`` unset on the first (pre-discovery) pass;
- that comparison is then skipped and re-run once the images are known."""
+ """Validate a resume request and return ``(checkpoint_dir, resumed_step)``. Called by the start
+ route BEFORE the resident GPU model is evicted, and again inside the trainer, so a rejected
+ resume never costs the user their loaded pipeline. Raises ResumeError with a message written
+ for the user. ``identity`` may leave ``dataset_fingerprint`` unset on the first
+ (pre-discovery) pass; that comparison is then skipped and re-run once the images are known."""
root = resolve_resume_dir(path_value)
- # The name alone does not settle it: an adapter can legitimately be called "checkpoint-2026", so
- # its output directory matches the bundle pattern while holding no trainer_state.json of its own.
- # The explicit branch is taken only when the path IS a valid bundle.
+ # The name alone does not settle it: an adapter can legitimately be called "checkpoint-2026", so its output
+ # directory matches the bundle pattern while holding no trainer_state.json of its own. The explicit branch is
+ # taken only when the path IS a valid bundle.
explicit = read_checkpoint(root) if checkpoint_step(root) >= 0 else None
candidates: list[tuple[Path, dict]]
if explicit is not None:
@@ -1896,15 +1833,15 @@ def preflight_resume(
"No complete training checkpoint was found for this run, so there is nothing to "
"resume from. Start a new run instead."
)
- # Newest first, and the cheap header scan means the newest bundle can still fail torch.load while a
- # retained older one is good; stopping at the first failure made retention pointless.
+ # Newest first, and the cheap header scan means the newest bundle can still fail torch.load while a retained older
+ # one is good; stopping at the first failure made retention pointless.
first_error: Optional[ResumeError] = None
for path, manifest in candidates:
try:
return _validated_resume(path, manifest, identity, target_steps)
except ResumeError as exc:
- # "Already at the target" is an answer, not a damaged bundle: falling past it walked back to an
- # earlier checkpoint and retrained completed work.
+ # "Already at the target" is an answer, not a damaged bundle: falling past it walked back to an earlier
+ # checkpoint and retrained completed work.
if getattr(exc, "terminal", False):
raise
if first_error is None:
@@ -1939,8 +1876,8 @@ def _validated_resume(
_assert_loadable(path, manifest)
step = int(manifest.get("global_step") or 0)
if target_steps and step >= int(target_steps):
- # Terminal: nothing is WRONG with the newest bundle, so the scan must stop rather than offer the
- # retained older one.
+ # Terminal: nothing is WRONG with the newest bundle, so the scan must stop rather than offer the retained
+ # older one.
raise _terminal(
ResumeError(
f"This checkpoint is already at step {step} of {int(target_steps)}, so there "
@@ -1950,7 +1887,6 @@ def _validated_resume(
return str(path), step
-# ── loading ───────────────────────────────────────────────────────────────────
@dataclass
class LoadedCheckpoint:
"""A validated bundle, with its tensors read lazily so a preflight never pays for them."""
@@ -1977,8 +1913,8 @@ class LoadedCheckpoint:
@property
def optimizer_param_names(self) -> Optional[list[str]]:
- """The trainable names in the order the optimizer held them, or None on a bundle from
- before this was recorded (which skips the check rather than failing it)."""
+ """The trainable names in the order the optimizer held them, or None on a bundle from before
+ this was recorded (which skips the check rather than failing it)."""
value = self.manifest.get("optimizer_param_names")
if not isinstance(value, list) or not value:
return None
@@ -1991,8 +1927,8 @@ class LoadedCheckpoint:
@property
def running_loss(self) -> float:
- """The loss total accumulated up to ``step``, so a resumed run's reported average
- stays an average over the WHOLE run rather than restarting at the resume point."""
+ """The loss total accumulated up to ``step``, so a resumed run's reported average stays an
+ average over the WHOLE run rather than restarting at the resume point."""
try:
return float(self.progress.get("running_loss") or 0.0)
except (TypeError, ValueError):
@@ -2028,12 +1964,11 @@ class LoadedCheckpoint:
return load_file(str(path), device = device) if path is not None else {}
def torch_state(self, role: str) -> Optional[Any]:
- """A ``torch.save``d state dict (``optimizer`` / ``scheduler`` / ``rng``), or None.
-
- Loaded with ``weights_only = True``: these files are written by Unsloth into its own
- outputs directory, but a resume path is client-supplied, so the loader must never be
- able to execute pickled code. Verified to round-trip bitsandbytes AdamW8bit state,
- whose quantized moments and maps are plain uint8/fp32 tensors."""
+ """A ``torch.save``d state dict (``optimizer`` / ``scheduler`` / ``rng``), or None. Loaded
+ with ``weights_only = True``: these files are written by Unsloth into its own outputs
+ directory, but a resume path is client-supplied, so the loader must never be able to
+ execute pickled code. Verified to round-trip bitsandbytes AdamW8bit state, whose
+ quantized moments and maps are plain uint8/fp32 tensors."""
import torch
path = self._file(role)
@@ -2043,8 +1978,8 @@ class LoadedCheckpoint:
def load_checkpoint(path: str | os.PathLike[str]) -> LoadedCheckpoint:
- """Open a bundle that ``preflight_resume`` already accepted. Raises ResumeError if it
- became unreadable in between (a concurrent delete, a half-mounted volume)."""
+ """Open a bundle that ``preflight_resume`` already accepted. Raises ResumeError if it became
+ unreadable in between (a concurrent delete, a half-mounted volume)."""
directory = Path(path).expanduser()
manifest = read_checkpoint(directory)
if manifest is None:
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 6f8382c5dca..7cb73740679 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -6,25 +6,23 @@
Image: FLUX.1-dev, FLUX.2 (dev + Klein), Qwen-Image, Z-Image, Krea 2. Video: LTX-2 (from a
still-image dataset; see the ``_LTX2_TARGETS`` block for what a video family adds).
-These are rectified-flow transformers, not the SDXL U-Net, so they share only the plumbing
-in ``diffusion_train_common`` (config, dataset discovery, events, stop, publishing). The
-training math here is flow matching: sample a sigma with the logit-normal density used by
-the diffusers dreambooth scripts, form ``noisy = (1 - sigma) * latents + sigma * noise``,
-predict the velocity, and regress it onto ``target = noise - latents``.
-
-The per-family differences (latent normalisation + packing, the transformer forward
-signature, embedding collation, and the LoRA save entrypoint) live in small ``_FamilySpec``
-objects; the loop itself is family-agnostic. Verified against diffusers 0.38.0.
-
-Memory: the text encoder(s) are the largest module (T5-XXL ~9 GB for FLUX, Qwen2.5-VL ~7 GB
-for Qwen-Image, Qwen3 for Z-Image), so captions are encoded ONCE up front and the encoders
-are freed before the loop. VAE latents are likewise precomputed into a small CPU cache
-(``cache_latents``) and the VAE freed: the cache stores the posterior's affine parameters
-(mean/std folded through the family's latent normalisation), so every step still draws a
-fresh VAE sample -- distribution-identical to encoding in the loop, without keeping the VAE
-resident or paying a per-step encode. The transformer trains as a QLoRA (nf4) adapter by
-default with gradient checkpointing and 8-bit AdamW, so only the (small) LoRA params +
-optimizer state and the frozen 4-bit base sit in VRAM during the loop.
+These are rectified-flow transformers, not the SDXL U-Net, so they share only the plumbing in
+``diffusion_train_common`` (config, dataset discovery, events, stop, publishing). The training math
+here is flow matching: sample a sigma with the logit-normal density used by the diffusers dreambooth
+scripts, form ``noisy = (1 - sigma) * latents + sigma * noise``, predict the velocity, and regress
+it onto ``target = noise - latents``. The per-family differences (latent normalisation + packing,
+the transformer forward signature, embedding collation, and the LoRA save entrypoint) live in small
+``_FamilySpec`` objects; the loop itself is family-agnostic. Verified against diffusers 0.38.0.
+
+Memory: the text encoder(s) are the largest module (T5-XXL ~9 GB for FLUX, Qwen2.5-VL ~7 GB for
+Qwen-Image, Qwen3 for Z-Image), so captions are encoded ONCE up front and the encoders are freed
+before the loop. VAE latents are likewise precomputed into a small CPU cache (``cache_latents``) and
+the VAE freed: the cache stores the posterior's affine parameters (mean/std folded through the
+family's latent normalisation), so every step still draws a fresh VAE sample --
+distribution-identical to encoding in the loop, without keeping the VAE resident or paying a
+per-step encode. The transformer trains as a QLoRA (nf4) adapter by default with gradient
+checkpointing and 8-bit AdamW, so only the (small) LoRA params + optimizer state and the frozen
+4-bit base sit in VRAM during the loop.
"""
from __future__ import annotations
@@ -83,8 +81,8 @@ from core.training.diffusion_train_extras import (
save_ema_adapter,
)
-# Per-family LoRA target modules (attention projections). FLUX / Qwen double-stream blocks also
-# carry added-kv projections; Z-Image is single-stream.
+# Per-family LoRA target modules (attention projections). FLUX / Qwen double-stream blocks also carry added-kv
+# projections; Z-Image is single-stream.
_FLUX_TARGETS = (
"to_q",
"to_k",
@@ -97,8 +95,8 @@ _FLUX_TARGETS = (
)
_QWEN_TARGETS = _FLUX_TARGETS
_ZIMAGE_TARGETS = ("to_q", "to_k", "to_v", "to_out.0")
-# The Krea 2 authors' recommended defaults (their DreamBooth script): attention + SwiGLU + text-
-# fusion projector + conditioning embedders. For long runs they suggest narrowing to attention.
+# The Krea 2 authors' recommended defaults (their DreamBooth script): attention + SwiGLU + text-fusion projector +
+# conditioning embedders. For long runs they suggest narrowing to attention.
_KREA2_TARGETS = (
"img_in",
"final_layer.linear",
@@ -121,12 +119,11 @@ _KREA2_TARGETS = (
def _select_lora_targets(
cfg_targets: tuple[str, ...], spec_targets: tuple[str, ...]
) -> tuple[str, ...]:
- """Pick the LoRA target modules for a DiT run.
-
- ``normalized()`` always fills ``lora_target_modules`` with the generic
- ``DEFAULT_LORA_TARGETS`` when a caller does not set it, so that value means "unset"
- here: prefer the family's ``spec.lora_targets`` (which add the DiT-specific
- projections). Any OTHER explicit tuple is a deliberate override and still wins."""
+ """Pick the LoRA target modules for a DiT run. ``normalized()`` always fills
+ ``lora_target_modules`` with the generic ``DEFAULT_LORA_TARGETS`` when a caller does not set
+ it, so that value means "unset" here: prefer the family's ``spec.lora_targets`` (which add
+ the DiT-specific projections). Any OTHER explicit tuple is a deliberate override and still
+ wins."""
if tuple(cfg_targets) == DEFAULT_LORA_TARGETS:
return tuple(spec_targets)
return tuple(cfg_targets)
@@ -140,38 +137,37 @@ class _FamilySpec:
lora_targets: tuple[str, ...]
# bf16 only (Z-Image overflows fp16 and its RoPE/embedder run in fp32).
force_bf16: bool
- # Used by base_precision="auto" to pick a mode that fits free VRAM; a family covering more than one
- # size (flux.2-klein is 4B and 9B) must not be sized off this alone -- see _dense_bf16_gb.
+ # Used by base_precision="auto" to pick a mode that fits free VRAM; a family covering more than one size
+ # (flux.2-klein is 4B and 9B) must not be sized off this alone -- see _dense_bf16_gb.
dense_bf16_gb: float
- # Phased load so the multi-GB transformer never coexists with the text encoders + VAE:
- # load_conditioners builds the pipeline WITHOUT it and returns (pipe, vae), then load_transformer
- # loads it alone once the conditioners are freed.
+ # Phased load so the multi-GB transformer never coexists with the text encoders + VAE: load_conditioners builds
+ # the pipeline WITHOUT it and returns (pipe, vae), then load_transformer loads it alone once the conditioners are
+ # freed.
load_conditioners: Callable[..., tuple[Any, Any]]
load_transformer: Callable[..., Any]
# Encode a list of captions -> a per-caption tuple of CPU tensors (the family's embeds).
encode_prompts: Callable[..., list[tuple]]
# Encode a pixel tensor [B,3,H,W] in [-1,1] -> latents (family-normalised, on device).
encode_latents: Callable[..., Any]
- # Encode pixels to (A, B) affine posterior params so a per-step sample is A + B * randn. B is None
- # for a deterministic family.
+ # Encode pixels to (A, B) affine posterior params so a per-step sample is A + B * randn. B is None for a
+ # deterministic family.
encode_latent_stats: Callable[..., tuple]
- # Collate per-caption embed tuples into one batched tuple on device. ``pad_to`` pins a fixed text
- # length for variable-length embeds (compile).
+ # Collate per-caption embed tuples into one batched tuple on device. ``pad_to`` pins a fixed text length for
+ # variable-length embeds (compile).
collate: Callable[..., tuple]
- # One transformer forward: (transformer, noisy, timesteps, sigmas, embeds_batch, cfg, device, weight_dtype)
- # -> model_pred aligned with target = noise - latents.
+ # One transformer forward: (transformer, noisy, timesteps, sigmas, embeds_batch, cfg, device, weight_dtype) ->
+ # model_pred aligned with target = noise - latents.
forward: Callable[..., Any]
# Save the LoRA in diffusers format via the family pipeline's save_lora_weights.
save: Callable[..., None]
-# ── shared flow-matching helpers ──────────────────────────────────────────────
def _gather_sigmas(sigma_table, indices, device, dtype, n_dim):
- """Gather per-sample sigmas for schedule ``indices`` and broadcast to ``n_dim``.
- Index-based (no per-item search): ``indices`` are the positions ``_sample_timesteps``
- drew from ``scheduler.timesteps``, and ``sigma_table`` (the scheduler's own sigmas, or
- the shifted copy from ``_training_sigma_table``) is aligned with it, so the identity
- table returns exactly what the diffusers ``get_sigmas`` helper would."""
+ """Gather per-sample sigmas for schedule ``indices`` and broadcast to ``n_dim``. Index-based (no
+ per-item search): ``indices`` are the positions ``_sample_timesteps`` drew from
+ ``scheduler.timesteps``, and ``sigma_table`` (the scheduler's own sigmas, or the shifted copy
+ from ``_training_sigma_table``) is aligned with it, so the identity table returns exactly
+ what the diffusers ``get_sigmas`` helper would."""
sigma = sigma_table[indices].to(device = device, dtype = dtype).flatten()
while sigma.ndim < n_dim:
sigma = sigma.unsqueeze(-1)
@@ -179,19 +175,17 @@ def _gather_sigmas(sigma_table, indices, device, dtype, n_dim):
def _training_sigma_table(scheduler, flow_shift):
- """The sigma table training draws index into, per ``cfg.flow_shift``.
-
- ``1.0`` (every non-Qwen family's default) returns ``scheduler.sigmas`` unchanged: the
- historical behavior, correct for the families whose schedule already matches training
- convention. ``"auto"`` (the qwen-image default) reproduces the family's INFERENCE sigma
- distribution, which the scheduler never bakes into ``sigmas`` when
- ``use_dynamic_shifting`` is true (the static ``shift`` at init is skipped, so Qwen-Image
- otherwise trains on unshifted uniform sigmas): apply the scheduler's own ``time_shift``
- at mu = ``max_shift`` (Qwen pins base_shift = max_shift = log 3, so the inference mu is
- constant at every resolution) followed by its ``stretch_shift_to_terminal`` -- using the
- scheduler's methods keeps the transform faithful across diffusers versions. A numeric
- value applies the standard linear shift s*u/(1+(s-1)*u) (musubi/kohya style
- discrete_flow_shift)."""
+ """The sigma table training draws index into, per ``cfg.flow_shift``. ``1.0`` (every non-Qwen
+ family's default) returns ``scheduler.sigmas`` unchanged: the historical behavior, correct
+ for the families whose schedule already matches training convention. ``"auto"`` (the
+ qwen-image default) reproduces the family's INFERENCE sigma distribution, which the scheduler
+ never bakes into ``sigmas`` when ``use_dynamic_shifting`` is true (the static ``shift`` at
+ init is skipped, so Qwen-Image otherwise trains on unshifted uniform sigmas): apply the
+ scheduler's own ``time_shift`` at mu = ``max_shift`` (Qwen pins base_shift = max_shift = log
+ 3, so the inference mu is constant at every resolution) followed by its
+ ``stretch_shift_to_terminal`` -- using the scheduler's methods keeps the transform faithful
+ across diffusers versions. A numeric value applies the standard linear shift s*u/(1+(s-1)*u)
+ (musubi/kohya style discrete_flow_shift)."""
sigmas = scheduler.sigmas
if flow_shift == "auto":
sc = scheduler.config
@@ -200,8 +194,8 @@ def _training_sigma_table(scheduler, flow_shift):
mu = float(getattr(sc, "max_shift", None) or math.log(3.0))
shifted = scheduler.time_shift(mu, 1.0, sigmas)
if getattr(sc, "shift_terminal", None):
- # The stretch scales off the table's own final sigma, so it must see the full descending schedule,
- # never a batch.
+ # The stretch scales off the table's own final sigma, so it must see the full descending schedule, never a
+ # batch.
shifted = scheduler.stretch_shift_to_terminal(shifted)
return shifted
s = float(flow_shift)
@@ -211,9 +205,9 @@ def _training_sigma_table(scheduler, flow_shift):
def _bell_loss_weights(num_train_timesteps):
- """bsmntw-style bell loss-weight table over the training schedule: a Gaussian bell
- centered mid-schedule, floored at 0 and normalized to mean 1 (so the expected loss
- scale is unchanged). Indexed by round(sigma * num_train_timesteps)."""
+ """bsmntw-style bell loss-weight table over the training schedule: a Gaussian bell centered
+ mid-schedule, floored at 0 and normalized to mean 1 (so the expected loss scale is
+ unchanged). Indexed by round(sigma * num_train_timesteps)."""
import torch
steps = num_train_timesteps
@@ -242,11 +236,10 @@ def _sample_timesteps(scheduler, batch_size, device):
def _encoders_to_device(pipe, device) -> None:
- """Move the pipeline's (non-quantized) text encoders to ``device`` before encoding.
-
- A QLoRA FLUX load places the nf4 transformer on GPU but leaves the text encoders on
- CPU, so encode_prompt would mix devices. Best-effort per encoder: a 4-bit encoder that
- is already placed raises on .to() and is left as-is."""
+ """Move the pipeline's (non-quantized) text encoders to ``device`` before encoding. A QLoRA FLUX
+ load places the nf4 transformer on GPU but leaves the text encoders on CPU, so encode_prompt
+ would mix devices. Best-effort per encoder: a 4-bit encoder that is already placed raises on
+ .to() and is left as-is."""
for attr in ("text_encoder", "text_encoder_2", "text_encoder_3"):
enc = getattr(pipe, attr, None)
if enc is None:
@@ -264,14 +257,14 @@ def _bnb_4bit_config():
load_in_4bit = True,
bnb_4bit_quant_type = "nf4",
bnb_4bit_compute_dtype = torch.bfloat16,
- # Double quantization compresses the per-block absmax scales with a second 8-bit pass: ~0.4 bits/param
- # off the frozen base at no fidelity cost, which matters most on the 20B+ DiTs.
+ # Double quantization compresses the per-block absmax scales with a second 8-bit pass: ~0.4 bits/param off the
+ # frozen base at no fidelity cost, which matters most on the 20B+ DiTs.
bnb_4bit_use_double_quant = True,
)
-# The heuristic moved to diffusion_train_common so config validation can use it without importing
-# this module; the name is kept for existing callers.
+# The heuristic moved to diffusion_train_common so config validation can use it without importing this module; the
+# name is kept for existing callers.
_repo_is_prequantized = repo_is_prequantized
@@ -288,9 +281,9 @@ def _load_quantized_transformer(transformer_cls, cfg):
def _load_pipe_without_transformer(pipe_cls, cfg, device):
- """Load a pipeline for conditioning only: ``transformer = None`` skips the multi-GB
- denoiser entirely (the documented diffusers pattern), leaving just the text encoders +
- tokenizers + VAE + scheduler. The transformer loads later, after these are freed."""
+ """Load a pipeline for conditioning only: ``transformer = None`` skips the multi-GB denoiser
+ entirely (the documented diffusers pattern), leaving just the text encoders + tokenizers +
+ VAE + scheduler. The transformer loads later, after these are freed."""
import torch
pipe = pipe_cls.from_pretrained(
@@ -304,14 +297,12 @@ def _load_pipe_without_transformer(pipe_cls, cfg, device):
def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
- """Load the transformer alone in the resolved ``base_precision``:
-
- - nf4: a prequant (bnb-4bit) repo carries its quantization config and loads 4-bit
- as-is; a dense base is quantized to nf4 on the fly. The memory floor.
- - bf16 / fp8 / mxfp8: the dense transformer (fp8/mxfp8 convert its frozen linears to
- float8 training compute AFTER the LoRA attaches; storage stays bf16).
- - int8: the dense transformer quantized in place to torchao weight-only int8 (the
- PEFT-attachable scheme), roughly halving the bf16 weight footprint."""
+ """Load the transformer alone in the resolved ``base_precision``. nf4: a prequant (bnb-4bit)
+ repo carries its quantization config and loads 4-bit as-is, while a dense base is quantized
+ to nf4 on the fly; the memory floor. bf16 / fp8 / mxfp8: the dense transformer (fp8/mxfp8
+ convert its frozen linears to float8 training compute AFTER the LoRA attaches; storage stays
+ bf16). int8: the dense transformer quantized in place to torchao weight-only int8 (the
+ PEFT-attachable scheme), roughly halving the bf16 weight footprint."""
import torch
if base_precision == "nf4":
@@ -328,8 +319,8 @@ def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
transformer = transformer.to(device)
return transformer
- # int8 quantizes AFTER the LoRA attaches: quantizing first makes peft dispatch TorchaoLoraLinear,
- # whose peft-0.18 constructor rejects the torchao-0.16 config API.
+ # int8 quantizes AFTER the LoRA attaches: quantizing first makes peft dispatch TorchaoLoraLinear, whose peft-0.18
+ # constructor rejects the torchao-0.16 config API.
return transformer_cls.from_pretrained(
cfg.base_model,
subfolder = "transformer",
@@ -339,22 +330,23 @@ def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
- """torchao weight-only int8 on the big frozen linears, applied after add_adapter so
- the base_layer inside each LoRA wrapper quantizes while the adapters stay high
- precision. ``make_filter_fn`` (shared with the inference quant layer) keeps only
- Linears with >= 512 features -- which also naturally skips the rank-sized LoRA
- matrices -- and drops the M=1 modulation projections int8 kernels reject.
+ """torchao weight-only int8 on the big frozen linears, applied after add_adapter so the base_layer
+ inside each LoRA wrapper quantizes while the adapters stay high precision. ``make_filter_fn``
+ (shared with the inference quant layer) keeps only Linears with >= 512 features -- which also
+ naturally skips the rank-sized LoRA matrices -- and drops the M=1 modulation projections int8
+ kernels reject.
- ``family`` selects the per-family small-M exclusions on top of those. Passing it is what
- keeps training and inference on the same list: without it LTX-2's one-token audio stream
- (and Qwen-Image's unpadded text stream) is quantized here and the first forward raises,
- after the whole base has been loaded.
+ ``family`` selects the per-family small-M exclusions on top of those. Passing it is what keeps
+ training and inference on the same list: without it LTX-2's one-token audio stream (and
+ Qwen-Image's unpadded text stream) is quantized here and the first forward raises, after the
+ whole base has been loaded.
The family's PAD list is applied for the same reason, and the same way the inference path
applies it: a small-M Linear is either excluded or padded, and a family that chose padding
- (MiniMax-H3's context_embedder and token_refiner blocks) has those names in neither the
- generic nor the family exclusions, so without this they are quantized bare and raise on the
- first forward exactly like an unexcluded one."""
+ (MiniMax-H3's context_embedder and token_refiner blocks) has those names in neither the generic
+ nor the family exclusions, so without this they are quantized bare and raise on the first
+ forward exactly like an unexcluded one.
+ """
from core.inference.diffusion_transformer_quant import (
_quiet_config,
apply_small_m_padding,
@@ -371,16 +363,16 @@ def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
512, exclude_name_tokens = exclude_tokens_for_scheme("int8", family)
),
)
- # After quantize_, as the helper requires (it reparents the Linears it wraps). Not best-effort: a
- # raise means the base is quantized but not safely runnable.
+ # After quantize_, as the helper requires (it reparents the Linears it wraps). Not best-effort: a raise means the
+ # base is quantized but not safely runnable.
apply_small_m_padding(transformer, "int8", family)
def _fp8_module_filter(mod, fqn: str) -> bool:
- """Which frozen linears get float8 training compute: skip anything LoRA-owned (the
- adapters must stay high precision -- PEFT has no float8 base support), the output
- projection, and shapes float8 kernels reject (dims not divisible by 16), matching the
- diffusers FLUX2 reference filter."""
+ """Which frozen linears get float8 training compute: skip anything LoRA-owned (the adapters must
+ stay high precision, since PEFT has no float8 base support), the output projection, and
+ shapes float8 kernels reject (dims not divisible by 16), matching the diffusers FLUX2
+ reference filter."""
import torch.nn as nn
if not isinstance(mod, nn.Linear):
@@ -393,15 +385,14 @@ def _fp8_module_filter(mod, fqn: str) -> bool:
def _fp8_training_config():
- """The float8 training config: per-ROW (rowwise) scaling when this torchao build ships
- the recipe, else the tensorwise default. The DiT families carry extreme activation
- outliers (Z-Image MLP activations peak near 6.6e4, the same range that forced per-row
- scaling in the inference quant layer): one tensor-wide dynamic scale pushes normal
- values (~1-30) below fp8 resolution, so the frozen base's forward -- the signal the
- LoRA regresses against -- degrades. Per-row scaling confines each outlier to its own
- token/channel. The tensorwise fallback keeps pad_inner_dim so a non-16-aligned inner
- dim never aborts the scaled_mm (the rowwise recipe manages its own padding rules and
- rejects the knob, hence the split)."""
+ """The float8 training config: per-ROW (rowwise) scaling when this torchao build ships the
+ recipe, else the tensorwise default. The DiT families carry extreme activation outliers
+ (Z-Image MLP activations peak near 6.6e4, the same range that forced per-row scaling in the
+ inference quant layer): one tensor-wide dynamic scale pushes normal values (~1-30) below fp8
+ resolution, so the frozen base's forward -- the signal the LoRA regresses against --
+ degrades. Per-row scaling confines each outlier to its own token/channel. The tensorwise
+ fallback keeps pad_inner_dim so a non-16-aligned inner dim never aborts the scaled_mm (the
+ rowwise recipe manages its own padding rules and rejects the knob, hence the split)."""
from torchao.float8 import Float8LinearConfig
try:
return Float8LinearConfig.from_recipe_name("rowwise")
@@ -410,9 +401,9 @@ def _fp8_training_config():
def _apply_fp8_training(transformer, on_event) -> bool:
- """Convert the frozen base linears to torchao float8 training compute (dynamic scaling;
- weights stay bf16 in memory). Applied AFTER add_adapter so the filter can exclude the
- LoRA modules. Never fatal: on any failure the run continues in bf16 with a warning."""
+ """Convert the frozen base linears to torchao float8 training compute (dynamic scaling; weights
+ stay bf16 in memory). Applied AFTER add_adapter so the filter can exclude the LoRA modules.
+ Never fatal: on any failure the run continues in bf16 with a warning."""
try:
from torchao.float8 import convert_to_float8_training
convert_to_float8_training(
@@ -427,9 +418,9 @@ def _apply_fp8_training(transformer, on_event) -> bool:
def _mx_module_filter(mod, fqn: str) -> bool:
- """Which frozen linears get mxfp8 training compute: skip anything LoRA-owned (the
- adapters must stay high precision), the output projection (same guard as fp8), and
- shapes the 32-wide MX block scaling cannot tile (dims not divisible by 32)."""
+ """Which frozen linears get mxfp8 training compute: skip anything LoRA-owned (the adapters must
+ stay high precision), the output projection (same guard as fp8), and shapes the 32-wide MX
+ block scaling cannot tile (dims not divisible by 32)."""
import torch.nn as nn
if not isinstance(mod, nn.Linear):
@@ -438,16 +429,16 @@ def _mx_module_filter(mod, fqn: str) -> bool:
return False
if fqn.endswith("proj_out") or ".proj_out." in fqn:
return False
- # Skip biased linears: the torchao 0.17 MX path swaps the weight for a wrapper that drops the bias,
- # changing the output the LoRA regresses against.
+ # Skip biased linears: the torchao 0.17 MX path swaps the weight for a wrapper that drops the bias, changing the
+ # output the LoRA regresses against.
if getattr(mod, "bias", None) is not None:
return False
return mod.in_features % 32 == 0 and mod.out_features % 32 == 0
def _mxfp8_training_config():
- """The torchao MX training config across the prototype API's revisions: torchao 0.16
- ships ``MXLinearConfig`` in ``prototype.mx_formats``; 0.17 removed it in favour of the
+ """The torchao MX training config across the prototype API's revisions: torchao 0.16 ships
+ ``MXLinearConfig`` in ``prototype.mx_formats``; 0.17 removed it in favour of the
``MXFP8TrainingOpConfig`` recipe API shared with MoE training. Both feed ``quantize_``.
Raises ImportError when neither API exists (mxfp8 then falls back to bf16)."""
try:
@@ -463,12 +454,12 @@ def _mxfp8_training_config():
def _apply_mxfp8_training(transformer, on_event) -> bool:
"""Swap the frozen base linears to torchao MX float8 training compute (mxfp8, the
- Blackwell-native block-scaled format; the swap is in place and the weights stay bf16
- in memory, so like fp8 this is a speed mode, not a memory mode). Applied AFTER
- add_adapter so the filter can exclude the LoRA modules. Only competitive under
- torch.compile and only ahead of compiled bf16 at large token counts (high resolution
- or batch), which is why it stays an explicit opt-in rather than an "auto" pick.
- Never fatal: on any failure the run continues in bf16 with a warning."""
+ Blackwell-native block-scaled format; the swap is in place and the weights stay bf16 in
+ memory, so like fp8 this is a speed mode, not a memory mode). Applied AFTER add_adapter so
+ the filter can exclude the LoRA modules. Only competitive under torch.compile and only ahead
+ of compiled bf16 at large token counts (high resolution or batch), which is why it stays an
+ explicit opt-in rather than an "auto" pick. Never fatal: on any failure the run continues in
+ bf16 with a warning."""
try:
from torchao.quantization import quantize_
quantize_(
@@ -491,19 +482,18 @@ def _pick_auto_precision(
has_fp8,
has_torchao = True,
) -> str:
- """Pure policy for base_precision="auto": nf4 for a prequant base or no CUDA; else the
- fastest dense mode whose weights + headroom (activations, optimizer, cache) fit the
- free VRAM at decision time. bf16 + regional compile is the measured speed winner
- (2.3-2.6x over nf4 on B200); fp8 stays an explicit opt-in because torchao float8's
- dynamic-scaling overhead made it SLOWER than compiled bf16 at LoRA-training shapes on
- the same hardware. int8 must still materialise the full bf16 transformer before
- ``quantize_`` shrinks it module-by-module, so its band requires the dense-load
- transient (1.15x dense) to fit -- what int8 buys in that band is steady-state
- headroom for activations and the latent cache, not load-time memory. int8 also needs
- torchao at runtime (``_int8_quantize_base`` has no fallback, unlike fp8), so auto only
- picks it when torchao is importable and drops to nf4 otherwise. ``capability``/``has_fp8``
- remain parameters so the policy can be revisited per GPU generation without changing
- callers."""
+ """Pure policy for base_precision="auto": nf4 for a prequant base or no CUDA; else the fastest
+ dense mode whose weights + headroom (activations, optimizer, cache) fit the free VRAM at
+ decision time. bf16 + regional compile is the measured speed winner (2.3-2.6x over nf4 on
+ B200); fp8 stays an explicit opt-in because torchao float8's dynamic-scaling overhead made it
+ SLOWER than compiled bf16 at LoRA-training shapes on the same hardware. int8 must still
+ materialise the full bf16 transformer before ``quantize_`` shrinks it module-by-module, so
+ its band requires the dense-load transient (1.15x dense) to fit -- what int8 buys in that
+ band is steady-state headroom for activations and the latent cache, not load-time memory.
+ int8 also needs torchao at runtime (``_int8_quantize_base`` has no fallback, unlike fp8), so
+ auto only picks it when torchao is importable and drops to nf4 otherwise.
+ ``capability``/``has_fp8`` remain parameters so the policy can be revisited per GPU
+ generation without changing callers."""
_ = capability, has_fp8
if prequant or device != "cuda" or not free_gb or not dense_gb:
return "nf4"
@@ -518,18 +508,19 @@ def _dense_bf16_gb(spec, base_model: str) -> float:
"""The dense-bf16 transformer size of the base this run actually trains from.
``spec.dense_bf16_gb`` is one number per FAMILY, and flux.2-klein is a family with two
- transformer sizes under it: the 4B default (8.1 GB) and the 9B / base-9B pair (18.2 GB).
- Sizing a 9B run off the family number understates it by 2.3x, so base_precision="auto"
- (the mode /info recommends, and therefore the Train tab's default) resolves to bf16 on a
- 16-24 GB GPU and the dense load OOMs -- the run fails before the first step.
-
- The inference auto-policy already keeps per-base overrides for exactly this, so read them
- here instead of adding a second table that can drift. Reads the per-base OVERRIDES only,
- never the family table underneath them: this spec's own number is the family default, and
- the two are independently maintained, so falling through to the shared family entry would
- silently re-size every base that has no override (klein's 4B default from 8.1 to 7.8, which
- moves the bf16 band by half a GB). Never raises: a sizing lookup must not be able to fail a
- run that would otherwise train."""
+ transformer sizes under it: the 4B default (8.1 GB) and the 9B / base-9B pair (18.2 GB). Sizing
+ a 9B run off the family number understates it by 2.3x, so base_precision="auto" (the mode /info
+ recommends, and therefore the Train tab's default) resolves to bf16 on a 16-24 GB GPU and the
+ dense load OOMs -- the run fails before the first step.
+
+ The inference auto-policy already keeps per-base overrides for exactly this, so read them here
+ instead of adding a second table that can drift. Reads the per-base OVERRIDES only, never the
+ family table underneath them: this spec's own number is the family default, and the two are
+ independently maintained, so falling through to the shared family entry would silently re-size
+ every base that has no override (klein's 4B default from 8.1 to 7.8, which moves the bf16 band
+ by half a GB). Never raises: a sizing lookup must not be able to fail a run that would otherwise
+ train.
+ """
try:
from core.inference.diffusion_auto_policy import base_repo_bf16_components_gb
components = base_repo_bf16_components_gb(base_model)
@@ -541,12 +532,11 @@ def _dense_bf16_gb(spec, base_model: str) -> float:
def _resolve_base_precision(cfg, spec, device) -> str:
- """Resolve "auto" against the live GPU (free VRAM measured BEFORE anything loads);
- explicit modes pass through (normalized() already validated them against the repo and
- compute dtype) but are re-checked against the live device here: the dense modes are
- CUDA-only, and /info never advertises them on a host without a GPU, so an explicit
- request from a stale or direct client fails fast instead of loading a full dense
- transformer onto the CPU."""
+ """Resolve "auto" against the live GPU (free VRAM measured BEFORE anything loads); explicit
+ modes pass through (normalized() already validated them against the repo and compute dtype)
+ but are re-checked against the live device here: the dense modes are CUDA-only, and /info
+ never advertises them on a host without a GPU, so an explicit request from a stale or direct
+ client fails fast instead of loading a full dense transformer onto the CPU."""
mode = (cfg.base_precision or "nf4").strip().lower()
if mode != "auto":
if mode in ("bf16", "int8", "fp8", "mxfp8") and device != "cuda":
@@ -561,25 +551,24 @@ def _resolve_base_precision(cfg, spec, device) -> str:
"sm_89+, mxfp8 sm_100+) and this is a ROCm/AMD GPU. Use base_precision='nf4', "
"'bf16', or 'auto'."
)
- # int8 has no runtime fallback, so gate on a FUNCTIONAL torchao here as the auto pick and /info do;
- # find_spec is satisfied by the Windows-ROCm stub.
+ # int8 has no runtime fallback, so gate on a FUNCTIONAL torchao here as the auto pick and /info do; find_spec
+ # is satisfied by the Windows-ROCm stub.
if mode == "int8" and not has_functional_torchao():
raise ValueError(
"base_precision='int8' needs a functional torchao install; this host's "
"torchao is missing or the non-functional Windows-ROCm stub. Use "
"base_precision='nf4', 'bf16', or 'auto'."
)
- # The stub answers torchao.float8 / torchao.prototype.mx_formats with a no-op that reports success,
- # so the run would report fp8 while training bf16.
- # Keyed on the stub, not has_functional_torchao(): that probes int8's symbols, and a real-but-
- # partial torchao must still reach the arch checks below.
+ # The stub answers torchao.float8 / torchao.prototype.mx_formats with a no-op that reports success, so the run
+ # would report fp8 while training bf16. Keyed on the stub, not has_functional_torchao(): that probes int8's
+ # symbols, and a real-but-partial torchao must still reach the arch checks below.
if mode in ("fp8", "mxfp8") and is_stubbed("torchao"):
raise ValueError(
f"base_precision={mode!r} is not available on this host: torchao is the "
"non-functional Windows-ROCm stub. Use base_precision='nf4', 'bf16', or 'auto'."
)
- # mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, after a full dense
- # load. Re-check here to fail fast for a stale client.
+ # mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, after a full dense load.
+ # Re-check here to fail fast for a stale client.
if mode == "mxfp8" and device == "cuda":
try:
import torch
@@ -592,8 +581,8 @@ def _resolve_base_precision(cfg, spec, device) -> str:
"Use base_precision='bf16', 'int8', 'nf4', or 'auto'."
)
return mode
- # auto may only resolve to the dense modes when the run uses bf16 compute, mirroring the
- # normalized() rule for explicit dense modes; otherwise stay on the nf4 floor.
+ # auto may only resolve to the dense modes when the run uses bf16 compute, mirroring the normalized() rule for
+ # explicit dense modes; otherwise stay on the nf4 floor.
if getattr(cfg, "mixed_precision", "bf16") != "bf16":
return "nf4"
prequant = repo_is_prequantized(cfg.base_model)
@@ -606,8 +595,8 @@ def _resolve_base_precision(cfg, spec, device) -> str:
try:
import torch
- # Windows ROCm over-reports free VRAM (#8403), which would pick a dense precision the card cannot
- # actually hold.
+ # Windows ROCm over-reports free VRAM (#8403), which would pick a dense precision the card cannot actually
+ # hold.
from utils.hardware import trusted_mem_get_info
free_gb = trusted_mem_get_info()[0] / 1e9
@@ -626,7 +615,6 @@ def _resolve_base_precision(cfg, spec, device) -> str:
)
-# ── FLUX.1-dev ────────────────────────────────────────────────────────────────
def _flux_load_conditioners(cfg, device, weight_dtype):
from diffusers import FluxPipeline
return _load_pipe_without_transformer(FluxPipeline, cfg, device)
@@ -681,16 +669,16 @@ def _flux_collate(
):
import torch
- # FLUX embeds are fixed-length, so a plain cat batches them; text_ids are shared position ids,
- # identical across prompts.
+ # FLUX embeds are fixed-length, so a plain cat batches them; text_ids are shared position ids, identical across
+ # prompts.
pe = torch.cat([e[0] for e in entries]).to(device = device, dtype = weight_dtype)
pooled = torch.cat([e[1] for e in entries]).to(device = device, dtype = weight_dtype)
text_ids = entries[0][2].to(device = device, dtype = torch.float32)
return (pe, pooled, text_ids)
-# Per-run cache of the step-invariant FLUX conditioning tensors: their shapes are fixed once
-# resolution and batch are. Cleared at run start.
+# Per-run cache of the step-invariant FLUX conditioning tensors: their shapes are fixed once resolution and batch are.
+# Cleared at run start.
_FLUX_STATIC: dict[tuple, tuple] = {}
@@ -701,8 +689,8 @@ def _flux_static_inputs(bsz, h, w, device):
key = (bsz, h, w, str(device))
hit = _FLUX_STATIC.get(key)
if hit is None:
- # Position ids drive RoPE and are indices, not activations, so keep them float32 regardless of the
- # training dtype.
+ # Position ids drive RoPE and are indices, not activations, so keep them float32 regardless of the training
+ # dtype.
img_ids = FluxPipeline._prepare_latent_image_ids(bsz, h // 2, w // 2, device, torch.float32)
guidance = torch.full((bsz,), 1.0, device = device, dtype = torch.float32)
hit = _FLUX_STATIC[key] = (img_ids, guidance)
@@ -738,15 +726,14 @@ def _flux_save(pipe_cls, out_dir, transformer_lora_layers):
)
-# ── Qwen-Image ────────────────────────────────────────────────────────────────
def _qwen_load_conditioners(cfg, device, weight_dtype):
from diffusers import QwenImagePipeline
return _load_pipe_without_transformer(QwenImagePipeline, cfg, device)
def _qwen_load_transformer(cfg, device, weight_dtype, base_precision):
- # The prequant default ships the transformer 4-bit and loads trainable as-is under nf4; the dense
- # modes need the 20B Qwen/Qwen-Image base.
+ # The prequant default ships the transformer 4-bit and loads trainable as-is under nf4; the dense modes need the
+ # 20B Qwen/Qwen-Image base.
from diffusers import QwenImageTransformer2DModel
return _load_dit_transformer(QwenImageTransformer2DModel, cfg, device, base_precision)
@@ -780,8 +767,8 @@ def _qwen_latent_affine(vae, ref):
def _qwen_encode_latents(vae, pixel_values):
import torch
- # AutoencoderKLQwenImage is a 3D (video) VAE: add a temporal dim, encode, and normalise by the per-
- # channel latents_mean / latents_std.
+ # AutoencoderKLQwenImage is a 3D (video) VAE: add a temporal dim, encode, and normalise by the per-channel
+ # latents_mean / latents_std.
px = pixel_values.to(torch.float32).unsqueeze(2)
with torch.no_grad():
lat = vae.encode(px).latent_dist.sample()
@@ -808,8 +795,8 @@ def _qwen_collate(
import torch
import torch.nn.functional as F
- # Qwen embeds are variable-length: pad to the batch max (or a pinned ``pad_to`` bucket under
- # compile) and batch the validity mask with them.
+ # Qwen embeds are variable-length: pad to the batch max (or a pinned ``pad_to`` bucket under compile) and batch
+ # the validity mask with them.
seqs = [e[0].shape[1] for e in entries]
target = max(pad_to or 0, max(seqs))
pes, masks = [], []
@@ -824,8 +811,8 @@ def _qwen_collate(
masks.append(mask)
pe_b = torch.cat(pes).to(device = device, dtype = weight_dtype)
mask_b = torch.cat(masks).to(device)
- # A single unpadded sample keeps the legacy None mask (identical math; avoids a behaviour delta for
- # existing single-image runs).
+ # A single unpadded sample keeps the legacy None mask (identical math; avoids a behaviour delta for existing
+ # single-image runs).
if len(entries) == 1 and entries[0][1] is None and target == seqs[0]:
mask_b = None
return (pe_b, mask_b)
@@ -837,8 +824,8 @@ def _qwen_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, devi
pe, mask = embeds_batch
bsz, c, f, h, w = noisy.shape
packed = QwenImagePipeline._pack_latents(noisy, bsz, c, h, w)
- # Each batch entry is a LIST of one (frame, h/2, w/2) tuple: the transformer indexes sample[0] /
- # sample[1:] per entry, so a flat list breaks it.
+ # Each batch entry is a LIST of one (frame, h/2, w/2) tuple: the transformer indexes sample[0] / sample[1:] per
+ # entry, so a flat list breaks it.
img_shapes = [[(1, h // 2, w // 2)]] * bsz
pred = transformer(
hidden_states = packed,
@@ -860,15 +847,14 @@ def _qwen_save(pipe_cls, out_dir, transformer_lora_layers):
)
-# ── Z-Image ───────────────────────────────────────────────────────────────────
def _zimage_load_conditioners(cfg, device, weight_dtype):
from diffusers import ZImagePipeline
return _load_pipe_without_transformer(ZImagePipeline, cfg, device)
def _zimage_load_transformer(cfg, device, weight_dtype, base_precision):
- # Prequant default loads 4-bit as-is under nf4; the dense modes use the bf16 Tongyi-MAI base.
- # Z-Image is bf16 only (its RoPE/embedder run fp32; fp16 overflows).
+ # Prequant default loads 4-bit as-is under nf4; the dense modes use the bf16 Tongyi-MAI base. Z-Image is bf16 only
+ # (its RoPE/embedder run fp32; fp16 overflows).
from diffusers import ZImageTransformer2DModel
return _load_dit_transformer(ZImageTransformer2DModel, cfg, device, base_precision)
@@ -900,8 +886,8 @@ def _zimage_encode_latents(vae, pixel_values):
def _zimage_encode_latent_stats(vae, pixel_values):
- # Z-Image trains from the posterior mode (deterministic), so the cached entry is the final latent: B
- # is None and the loop skips the per-step draw.
+ # Z-Image trains from the posterior mode (deterministic), so the cached entry is the final latent: B is None and
+ # the loop skips the per-step draw.
return _zimage_encode_latents(vae, pixel_values), None
@@ -919,8 +905,8 @@ def _zimage_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, de
import torch
(caps,) = embeds_batch
- # List I/O: one [C,1,H,W] latent + one [seq,2560] caption per sample. The timestep convention is
- # REVERSED ((1000 - t) / 1000) and the prediction is NEGATED.
+ # List I/O: one [C,1,H,W] latent + one [seq,2560] caption per sample. The timestep convention is REVERSED ((1000 -
+ # t) / 1000) and the prediction is NEGATED.
x_list = list(noisy.unsqueeze(2).unbind(dim = 0))
t_norm = (1000 - timesteps) / 1000
out = transformer(x_list, t_norm, list(caps), return_dict = False)[0]
@@ -936,10 +922,9 @@ def _zimage_save(pipe_cls, out_dir, transformer_lora_layers):
)
-# ── Krea 2 ────────────────────────────────────────────────────────────────────
def _krea2_load_conditioners(cfg, device, weight_dtype):
- # The krea repo ships transformers-5.x style configs the pinned 4.x line cannot parse, so the
- # conditioning pipeline is assembled per-component (diffusion_krea2.py).
+ # The krea repo ships transformers-5.x style configs the pinned 4.x line cannot parse, so the conditioning
+ # pipeline is assembled per-component (diffusion_krea2.py).
import torch
from core.inference.diffusion_krea2 import load_krea2_pipeline
@@ -951,8 +936,8 @@ def _krea2_load_conditioners(cfg, device, weight_dtype):
def _krea2_load_transformer(cfg, device, weight_dtype, base_precision):
- # The transformer subfolder is diffusers-format. No prequant repo yet, so nf4 quantizes the 12B
- # transformer on the fly.
+ # The transformer subfolder is diffusers-format. No prequant repo yet, so nf4 quantizes the 12B transformer on the
+ # fly.
from diffusers import Krea2Transformer2DModel
return _load_dit_transformer(Krea2Transformer2DModel, cfg, device, base_precision)
@@ -964,8 +949,8 @@ def _krea2_encode_prompts(pipe, captions, device):
out = []
with torch.no_grad():
for cap in captions:
- # encode_prompt pads/truncates to max_sequence_length, so every embed is
- # [1, 512, num_text_layers, 2560] with a [1, 512] mask (static shapes, padding before the suffix).
+ # encode_prompt pads/truncates to max_sequence_length, so every embed is [1, 512, num_text_layers, 2560]
+ # with a [1, 512] mask (static shapes, padding before the suffix).
pe, mask = pipe.encode_prompt(
prompt = cap,
device = device,
@@ -1000,8 +985,8 @@ def _krea2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, dev
from diffusers import Krea2Pipeline
pe, mask = embeds_batch
- # Krea2Pipeline._pack_latents is an instance method (it reads self.patch_size), so the packing is
- # inlined like the reference script.
+ # Krea2Pipeline._pack_latents is an instance method (it reads self.patch_size), so the packing is inlined like the
+ # reference script.
bsz, c, _f, h, w = noisy.shape
packed = noisy.reshape(bsz, c, h // 2, 2, w // 2, 2)
packed = packed.permute(0, 2, 4, 1, 3, 5).reshape(bsz, (h // 2) * (w // 2), c * 4)
@@ -1029,10 +1014,9 @@ def _krea2_save(pipe_cls, out_dir, transformer_lora_layers):
)
-# Both variants share Flux2Transformer2DModel and the upstream packing/forward conventions,
-# differing only in the conditioning stack (dev: Mistral-3-Small; Klein: Qwen3) and size. Latents
-# train patchified and batch-norm-normalised, from the posterior MODE (deterministic).
-# ── FLUX.2 (dev + Klein) ──────────────────────────────────────────────────────
+# FLUX.2 (dev + Klein). Both variants share Flux2Transformer2DModel and the upstream packing/forward conventions,
+# differing only in the conditioning stack (dev: Mistral-3-Small; Klein: Qwen3) and size. Latents train patchified and
+# batch-norm-normalised, from the posterior MODE (deterministic).
_FLUX2_COMMON_TARGETS = (
# Double-stream blocks: separate q/k/v plus the ModuleList out proj.
"to_k",
@@ -1042,16 +1026,16 @@ _FLUX2_COMMON_TARGETS = (
# Single-stream blocks use one fused qkv+mlp input projection.
"to_qkv_mlp_proj",
)
-# A bare "to_out" suffix also matches the double-stream ModuleList, which PEFT cannot wrap, so each
-# single block is named explicitly; missing high indexes are harmless on the Klein-4B layout.
+# A bare "to_out" suffix also matches the double-stream ModuleList, which PEFT cannot wrap, so each single block is
+# named explicitly; missing high indexes are harmless on the Klein-4B layout.
_FLUX2_KLEIN_TARGETS = _FLUX2_COMMON_TARGETS + tuple(
f"single_transformer_blocks.{i}.attn.to_out" for i in range(24)
)
_FLUX2_DEV_TARGETS = _FLUX2_COMMON_TARGETS + tuple(
f"single_transformer_blocks.{i}.attn.to_out" for i in range(48)
)
-# The references train dev with its guidance-distillation vector at 3.5 (Klein applies it only when
-# the variant config carries guidance_embeds).
+# The references train dev with its guidance-distillation vector at 3.5 (Klein applies it only when the variant config
+# carries guidance_embeds).
_FLUX2_TRAIN_GUIDANCE = 3.5
@@ -1077,8 +1061,8 @@ def _flux2_encode_prompts(pipe, captions, device):
out = []
with torch.no_grad():
for cap in captions:
- # encode_prompt pads to max_sequence_length, so embeds are fixed-length and text_ids are per-caption
- # [1, txt_len, 4]. The per-class text_encoder_out_layers defaults are left to the pipeline.
+ # encode_prompt pads to max_sequence_length, so embeds are fixed-length and text_ids are per-caption [1,
+ # txt_len, 4]. The per-class text_encoder_out_layers defaults are left to the pipeline.
pe, text_ids = pipe.encode_prompt(
prompt = cap,
device = device,
@@ -1103,8 +1087,8 @@ def _flux2_encode_latents(vae, pixel_values):
def _flux2_encode_latent_stats(vae, pixel_values):
- # FLUX.2 trains from the posterior mode (deterministic): the cached entry is the final latent
- # itself; B is None and the loop skips the per-step sampling draw.
+ # FLUX.2 trains from the posterior mode (deterministic): the cached entry is the final latent itself; B is None
+ # and the loop skips the per-step sampling draw.
return _flux2_encode_latents(vae, pixel_values), None
@@ -1116,8 +1100,8 @@ def _flux2_collate(
):
import torch
- # Fixed-length embeds give a plain concat; text_ids are PER-SAMPLE (unlike FLUX.1's shared grid), so
- # they concat too.
+ # Fixed-length embeds give a plain concat; text_ids are PER-SAMPLE (unlike FLUX.1's shared grid), so they concat
+ # too.
pe = torch.cat([e[0] for e in entries]).to(device = device, dtype = weight_dtype)
text_ids = torch.cat([e[1] for e in entries]).to(device = device, dtype = torch.float32)
return (pe, text_ids)
@@ -1142,8 +1126,8 @@ def _flux2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, dev
from diffusers import Flux2Pipeline
pe, text_ids = embeds_batch
- # ``noisy`` is already in the patchified normalised space, so packing is the [B,C,H,W] to [B, H*W, C]
- # flatten the pipeline uses.
+ # ``noisy`` is already in the patchified normalised space, so packing is the [B,C,H,W] to [B, H*W, C] flatten the
+ # pipeline uses.
packed = Flux2Pipeline._pack_latents(noisy)
img_ids = _flux2_static_img_ids(noisy, device)
guidance = None
@@ -1161,8 +1145,8 @@ def _flux2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, dev
return_dict = False,
)[0]
pred = pred[:, : packed.size(1)]
- # _unpack_latents_with_ids scatters per sample; diffusers 0.39 stacks them itself (its list
- # annotation is stale), other builds hand back the list. Same-resolution batches align either way.
+ # _unpack_latents_with_ids scatters per sample; diffusers 0.39 stacks them itself (its list annotation is stale),
+ # other builds hand back the list. Same-resolution batches align either way.
unpacked = Flux2Pipeline._unpack_latents_with_ids(pred, img_ids)
if isinstance(unpacked, (list, tuple)):
unpacked = torch.stack(unpacked)
@@ -1187,16 +1171,13 @@ def _flux2_klein_save(pipe_cls, out_dir, transformer_lora_layers):
)
-# Milestone one trains from STILL IMAGES: a 1-frame clip is valid LTX-2 input (its VAE compresses
-# time by 8) and style LoRAs converge on 20-50 stills, so this spec reuses the image dataset layer.
-# AUDIOVISUAL: forward REQUIRES audio arguments and diffusers has no video-only escape hatch, so
-# feed a one-token audio stream with isolate_modalities=True and keep audio out of the loss and
-# out of the LoRA targets. The reason _LTX2_TARGETS names its modules in full.
-# Two-stage conditioning: the Gemma3-12B hidden states are ~370 MB per caption, so encode_prompts
-# runs both stages and caches only the small connector output.
-# Video-stream attention only, fully qualified: a bare "to_q" would also match
-# audio_attn1/audio_attn2 and the cross-modality attentions.
-# ── LTX-2 (video) ─────────────────────────────────────────────────────────────
+# LTX-2 (video). Milestone one trains from STILL IMAGES: a 1-frame clip is valid LTX-2 input (its VAE compresses time
+# by 8) and style LoRAs converge on 20-50 stills, so this spec reuses the image dataset layer. AUDIOVISUAL: forward
+# REQUIRES audio arguments and diffusers has no video-only escape hatch, so feed a one-token audio stream with
+# isolate_modalities=True and keep audio out of the loss and out of the LoRA targets -- the reason _LTX2_TARGETS names
+# its modules in full. Two-stage conditioning: the Gemma3-12B hidden states are ~370 MB per caption, so encode_prompts
+# runs both stages and caches only the small connector output. Video-stream attention only, fully qualified: a bare
+# "to_q" would also match audio_attn1/audio_attn2 and the cross-modality attentions.
_LTX2_TARGETS = (
"attn1.to_q",
"attn1.to_k",
@@ -1208,8 +1189,8 @@ _LTX2_TARGETS = (
"attn2.to_out.0",
)
-# LTX-2's rotary temporal coordinate is in SECONDS, so a 1-frame clip at the native 24 fps lands
-# where a generated clip's first latent frame lands; Lightricks instead pin images to fps=1.0.
+# LTX-2's rotary temporal coordinate is in SECONDS, so a 1-frame clip at the native 24 fps lands where a generated
+# clip's first latent frame lands; Lightricks instead pin images to fps=1.0.
_LTX2_TRAIN_FPS = 24.0
@@ -1232,8 +1213,8 @@ def _ltx2_encode_prompts(pipe, captions, device):
import torch
_encoders_to_device(pipe, device)
- # The Gemma3 hidden states are per-LAYER stacked ([1, 1024, 3840 * layers]); only the connector output
- # reaches the transformer, so that is what gets cached.
+ # The Gemma3 hidden states are per-LAYER stacked ([1, 1024, 3840 * layers]); only the connector output reaches the
+ # transformer, so that is what gets cached.
out = []
with torch.no_grad():
for cap in captions:
@@ -1244,8 +1225,8 @@ def _ltx2_encode_prompts(pipe, captions, device):
max_sequence_length = 1024,
device = device,
)
- # Read AFTER encode_prompt, which sets padding_side="left" itself: the connectors build the valid-
- # token mask from this, so a stale "right" would mask every short caption on the wrong end.
+ # Read AFTER encode_prompt, which sets padding_side="left" itself: the connectors build the valid-token
+ # mask from this, so a stale "right" would mask every short caption on the wrong end.
padding_side = getattr(getattr(pipe, "tokenizer", None), "padding_side", "left")
video_emb, audio_emb, conn_mask = pipe.connectors(pe, mask, padding_side = padding_side)
out.append((video_emb.cpu(), audio_emb.cpu(), conn_mask.cpu()))
@@ -1264,8 +1245,8 @@ def _ltx2_latent_affine(vae, ref):
def _ltx2_encode_latents(vae, pixel_values):
import torch
- # A still is a 1-frame clip: [B,3,H,W] -> [B,3,1,H,W]. The VAE compresses 32x spatially and 8x
- # temporally, so a 512px still becomes [B,128,1,16,16].
+ # A still is a 1-frame clip: [B,3,H,W] -> [B,3,1,H,W]. The VAE compresses 32x spatially and 8x temporally, so a
+ # 512px still becomes [B,128,1,16,16].
px = pixel_values.to(torch.float32).unsqueeze(2)
with torch.no_grad():
lat = vae.encode(px).latent_dist.sample()
@@ -1291,8 +1272,8 @@ def _ltx2_collate(
):
import torch
- # encode_prompt pads to max_sequence_length, so every connector embed is [1, 1024, 3840] and a plain concat batches
- # them; ``pad_to`` is moot.
+ # encode_prompt pads to max_sequence_length, so every connector embed is [1, 1024, 3840] and a plain concat
+ # batches them; ``pad_to`` is moot.
video = torch.cat([e[0] for e in entries]).to(device = device, dtype = weight_dtype)
audio = torch.cat([e[1] for e in entries]).to(device = device, dtype = weight_dtype)
mask = torch.cat([e[2] for e in entries]).to(device)
@@ -1300,13 +1281,11 @@ def _ltx2_collate(
def _ltx2_audio_token_count(config, num_pixel_frames: int, fps: float) -> int:
- """Audio latent tokens accompanying ``num_pixel_frames`` at ``fps``.
-
- The pipeline derives this as ``round(duration_s * sampling_rate / hop_length /
- temporal_compression)``; every term is on the transformer config, so the trainer does not
- need the audio VAE resident (it never encodes audio -- see the spec comment). Floored at
- one token: the transformer indexes the audio stream unconditionally, so an empty one
- would trip its RoPE."""
+ """Audio latent tokens accompanying ``num_pixel_frames`` at ``fps``. The pipeline derives this
+ as ``round(duration_s * sampling_rate / hop_length / temporal_compression)``; every term is
+ on the transformer config, so the trainer does not need the audio VAE resident (it never
+ encodes audio, see the spec comment). Floored at one token: the transformer indexes the audio
+ stream unconditionally, so an empty one would trip its RoPE."""
per_second = (
float(config.audio_sampling_rate)
/ float(config.audio_hop_length)
@@ -1328,14 +1307,13 @@ def _ltx2_unpack(pred, f, h, w, conf):
def _ltx2_audio_state(sigmas, bsz, audio_len, channels, device, dtype):
- """The audio-stream input for a step at ``sigmas``.
-
- A still-image dataset carries no audio ground truth, so the placeholder stream rides the
- SAME flow-matching state a zero clean latent would produce: ``(1 - sigma) * 0 + sigma *
- noise``. Zero is the mean of the normalised audio latent distribution, so this keeps the
- stream at the right SCALE for every sigma instead of feeding unit noise at a timestep the
- model expects nearly-clean latents at. With ``isolate_modalities = True`` it cannot reach
- the video prediction at all; it exists only because ``forward`` requires the argument."""
+ """The audio-stream input for a step at ``sigmas``. A still-image dataset carries no audio
+ ground truth, so the placeholder stream rides the SAME flow-matching state a zero clean
+ latent would produce: ``(1 - sigma) * 0 + sigma * noise``. Zero is the mean of the normalised
+ audio latent distribution, so this keeps the stream at the right SCALE for every sigma
+ instead of feeding unit noise at a timestep the model expects nearly-clean latents at. With
+ ``isolate_modalities = True`` it cannot reach the video prediction at all; it exists only
+ because ``forward`` requires the argument."""
import torch
noise = torch.randn((bsz, audio_len, channels), device = device, dtype = dtype)
@@ -1361,8 +1339,8 @@ def _ltx2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, devi
audio_hidden_states = audio_noisy,
encoder_hidden_states = video_emb,
audio_encoder_hidden_states = audio_emb,
- # LTX-2 conditions on the UNSCALED timestep (its config carries timestep_scale_multiplier = 1000
- # and the pipeline passes scheduler timesteps through as-is), unlike FLUX / Qwen's timestep / 1000.
+ # LTX-2 conditions on the UNSCALED timestep (its config carries timestep_scale_multiplier = 1000 and the
+ # pipeline passes scheduler timesteps through as-is), unlike FLUX / Qwen's timestep / 1000.
timestep = timesteps,
sigma = timesteps,
encoder_attention_mask = mask,
@@ -1372,8 +1350,8 @@ def _ltx2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, devi
width = w,
fps = _LTX2_TRAIN_FPS,
audio_num_frames = audio_len,
- # Disable the a2v / v2a cross attention so the placeholder audio stream cannot perturb the video
- # prediction the LoRA is regressing.
+ # Disable the a2v / v2a cross attention so the placeholder audio stream cannot perturb the video prediction
+ # the LoRA is regressing.
isolate_modalities = True,
return_dict = False,
)
@@ -1465,8 +1443,8 @@ _SPECS: dict[str, _FamilySpec] = {
family = "flux.2-dev",
lora_targets = _FLUX2_DEV_TARGETS,
force_bf16 = True,
- # 32B DiT; the Mistral conditioning stack (~46 GB bf16) is loaded, encoded and freed BEFORE this lands
- # on the device (the shared phased load).
+ # 32B DiT; the Mistral conditioning stack (~46 GB bf16) is loaded, encoded and freed BEFORE this lands on the
+ # device (the shared phased load).
dense_bf16_gb = 64.5,
load_conditioners = _flux2_load_conditioners,
load_transformer = _flux2_load_transformer,
@@ -1481,8 +1459,8 @@ _SPECS: dict[str, _FamilySpec] = {
family = "ltx-2",
lora_targets = _LTX2_TARGETS,
force_bf16 = True,
- # 19B audiovisual DiT (37.76 GB bf16); the Gemma3-12B conditioning stack is loaded, encoded and
- # freed BEFORE this lands on the device, via the shared phased load.
+ # 19B audiovisual DiT (37.76 GB bf16); the Gemma3-12B conditioning stack is loaded, encoded and freed BEFORE
+ # this lands on the device, via the shared phased load.
dense_bf16_gb = 37.8,
load_conditioners = _ltx2_load_conditioners,
load_transformer = _ltx2_load_transformer,
@@ -1496,8 +1474,8 @@ _SPECS: dict[str, _FamilySpec] = {
}
-# HF repos gating access behind a license acceptance: training needs a token whose account accepted
-# it. Checked by name (no network) so a missing token fails fast with an actionable message.
+# HF repos gating access behind a license acceptance: training needs a token whose account accepted it. Checked by
+# name (no network) so a missing token fails fast with an actionable message.
_GATED_TRAIN_REPOS = frozenset({"black-forest-labs/flux.1-dev", "black-forest-labs/flux.2-dev"})
@@ -1506,8 +1484,8 @@ def _assert_gated_access(base_model: str, hf_token: Optional[str]) -> None:
from core.inference.diffusion_families import _is_local_path
name = str(base_model or "").strip().lower()
- # A local clone named like the vendor repo is weights on disk, not a Hub fetch: refusing it by name
- # alone is what made that documented layout untrainable.
+ # A local clone named like the vendor repo is weights on disk, not a Hub fetch: refusing it by name alone is what
+ # made that documented layout untrainable.
if _is_local_path(base_model):
return
if name in _GATED_TRAIN_REPOS and not (hf_token and str(hf_token).strip()):
@@ -1518,8 +1496,8 @@ def _assert_gated_access(base_model: str, hf_token: Optional[str]) -> None:
def _open_resized(path, resolution):
- """Open + EXIF-orient + short-side resize to ``resolution`` (same geometry as the SDXL
- loader). Returns the resized PIL image and its (rw, rh)."""
+ """Open + EXIF-orient + short-side resize to ``resolution`` (same geometry as the SDXL loader).
+ Returns the resized PIL image and its (rw, rh)."""
from PIL import Image, ImageOps
img = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
@@ -1538,8 +1516,8 @@ def _to_unit_tensor(img):
def _load_pixel_tensor(path, resolution, center_crop, random_flip, rng):
- """Load an image -> a normalised [3,H,W] tensor in [-1,1]. Same geometry as the SDXL
- loader but without the SDXL time-ids (DiT families don't use them)."""
+ """Load an image -> a normalised [3,H,W] tensor in [-1,1]. Same geometry as the SDXL loader but
+ without the SDXL time-ids (DiT families don't use them)."""
from PIL import Image
img, rw, rh = _open_resized(path, resolution)
@@ -1555,10 +1533,10 @@ def _load_pixel_tensor(path, resolution, center_crop, random_flip, rng):
def _load_pixel_tensor_planned(path, resolution, center_crop, u_left, u_top, flip):
- """Deterministic variant of ``_load_pixel_tensor`` for the latent cache: the crop comes
- as unit fractions (mapped uniformly over the same inclusive integer range ``randint``
- draws from) and the flip as a bool. ``center_crop`` reproduces the exact legacy
- floor-div center so a cached center-crop run matches the uncached one bit-for-bit."""
+ """Deterministic variant of ``_load_pixel_tensor`` for the latent cache: the crop comes as unit
+ fractions (mapped uniformly over the same inclusive integer range ``randint`` draws from) and
+ the flip as a bool. ``center_crop`` reproduces the exact legacy floor-div center so a cached
+ center-crop run matches the uncached one bit-for-bit."""
from PIL import Image
img, rw, rh = _open_resized(path, resolution)
@@ -1585,14 +1563,14 @@ def _build_latent_cache(
pcache = None,
plan = None,
):
- """Precompute the per-image latent posterior cache: for each planned crop/flip variant,
- encode once and store the affine (A, B) pair on CPU (pinned when possible) in fp32. The
- stats stay fp32 so the per-step sample happens in fp32 and only the RESULT is cast to
- weight_dtype, matching the in-loop path (encode fp32 -> sample/normalise fp32 ->
- .to(weight_dtype)); fp32 doubles the cache RAM over bf16 but the cache is tiny (a handful
- of latents per image). ``pcache`` (a PersistentConditioningCache) serves hits from disk
- and receives every fresh encode, so the next run of the same config starts warm.
- Returns None if the build was interrupted by a stop request."""
+ """Precompute the per-image latent posterior cache: for each planned crop/flip variant, encode
+ once and store the affine (A, B) pair on CPU (pinned when possible) in fp32. The stats stay
+ fp32 so the per-step sample happens in fp32 and only the RESULT is cast to weight_dtype,
+ matching the in-loop path (encode fp32 -> sample/normalise fp32 -> .to(weight_dtype)); fp32
+ doubles the cache RAM over bf16 but the cache is tiny (a handful of latents per image).
+ ``pcache`` (a PersistentConditioningCache) serves hits from disk and receives every fresh
+ encode, so the next run of the same config starts warm. Returns None if the build was
+ interrupted by a stop request."""
if plan is None:
plan = _plan_cache_variants(
@@ -1640,8 +1618,8 @@ def _build_latent_cache(
pass
a, b = _hold(a), _hold(b)
if not forced and not gated:
- # Size-gate the automatic cache off the first REAL encoded variant: packed latents x variants x
- # images can exhaust pinned RAM.
+ # Size-gate the automatic cache off the first REAL encoded variant: packed latents x variants x images
+ # can exhaust pinned RAM.
per_variant = a.numel() * a.element_size()
if b is not None:
per_variant += b.numel() * b.element_size()
@@ -1668,10 +1646,10 @@ def _build_latent_cache(
def _encode_prompts_cached(spec, pipe, to_encode, device, pcache):
- """Encode captions, serving hits from the persistent cache and writing misses back.
- The returned list is aligned with ``to_encode``; without a cache this is exactly
- ``spec.encode_prompts``. The cached tuples are the family's own CPU embed tuples
- (dtype preserved by safetensors), so a hit is identical to a fresh encode."""
+ """Encode captions, serving hits from the persistent cache and writing misses back. The returned
+ list is aligned with ``to_encode``; without a cache this is exactly ``spec.encode_prompts``.
+ The cached tuples are the family's own CPU embed tuples (dtype preserved by safetensors), so
+ a hit is identical to a fresh encode."""
if pcache is None:
return spec.encode_prompts(pipe, to_encode, device)
hits: dict = {}
@@ -1693,12 +1671,11 @@ def _encode_prompts_cached(spec, pipe, to_encode, device, pcache):
def _load_warm_conditioning(pcache, image_paths, plan, to_encode, device):
- """Load the FULL conditioning set (caption embeds + latent posterior stats) from the
- persistent cache. Returns (caption_embeds, latent_cache) on a complete hit, else
- (None, None) so the caller takes the cold path -- any missing/corrupt entry, and also
- an in-memory holding that would blow the host budget (the cold path re-decides that
- with the VAE resident and can fall back to per-step encoding). On success the VAE and
- text encoders are never loaded."""
+ """Load the FULL conditioning set (caption embeds + latent posterior stats) from the persistent
+ cache. Returns (caption_embeds, latent_cache) on a complete hit, else (None, None) so the
+ caller takes the cold path -- any missing/corrupt entry, and also an in-memory holding that
+ would blow the host budget (the cold path re-decides that with the VAE resident and can fall
+ back to per-step encoding). On success the VAE and text encoders are never loaded."""
embeds = []
for cap in to_encode:
entry = pcache.get(pcache.text_key(cap))
@@ -1743,10 +1720,10 @@ def _load_warm_conditioning(pcache, image_paths, plan, to_encode, device):
def _sample_cached_latents(cache, idxs, variant_rng, device, weight_dtype):
- """Draw one latent per index from the cache: pick a variant, then sample the posterior
- (A + B * randn) when the family is stochastic. Fresh noise per step, exactly like an
- in-loop ``latent_dist.sample()``. The cached stats are fp32, so the sample is drawn in
- fp32 and only the RESULT is cast to weight_dtype (matching the in-loop path's
+ """Draw one latent per index from the cache: pick a variant, then sample the posterior (A + B *
+ randn) when the family is stochastic. Fresh noise per step, exactly like an in-loop
+ ``latent_dist.sample()``. The cached stats are fp32, so the sample is drawn in fp32 and only
+ the RESULT is cast to weight_dtype (matching the in-loop path's
``encode_latents(...).to(weight_dtype)``)."""
import torch
@@ -1772,14 +1749,14 @@ def _should_compile(
mode = (cfg.compile_transformer or "auto").strip().lower()
if device != "cuda" or mode == "off":
return False
- # torch.compile cannot trace the torchao int8 subclass in training (inductor rejects the aliased
- # subclass graph outputs), so int8 always runs eager.
+ # torch.compile cannot trace the torchao int8 subclass in training (inductor rejects the aliased subclass graph
+ # outputs), so int8 always runs eager.
if base_precision == "int8":
return False
if mode == "on":
return True
- # Regional compile is the whole point of the dense modes (2.6x measured on Z-Image bf16) but is
- # fragile over bitsandbytes 4-bit modules, so it stays off for QLoRA.
+ # Regional compile is the whole point of the dense modes (2.6x measured on Z-Image bf16) but is fragile over
+ # bitsandbytes 4-bit modules, so it stays off for QLoRA.
return base_precision in ("bf16", "fp8", "mxfp8")
@@ -1791,10 +1768,10 @@ def _maybe_compile_transformer(
on_event,
base_precision = "nf4",
) -> bool:
- """Regionally compile the transformer blocks (diffusers compile_repeated_blocks) after
- the LoRA is attached. Never fatal: a wrap failure falls back to eager with a warning
- event, and dynamo's suppress_errors keeps a frame that fails to COMPILE at the first
- step running eager instead of raising mid-run."""
+ """Regionally compile the transformer blocks (diffusers compile_repeated_blocks) after the LoRA
+ is attached. Never fatal: a wrap failure falls back to eager with a warning event, and
+ dynamo's suppress_errors keeps a frame that fails to COMPILE at the first step running eager
+ instead of raising mid-run."""
if not _should_compile(cfg, base_is_bnb, device, base_precision):
if base_precision in ("fp8", "mxfp8"):
_emit(
@@ -1817,15 +1794,15 @@ def _maybe_compile_transformer(
try:
dynamo_cfg = getattr(getattr(torch, "_dynamo", None), "config", None)
if dynamo_cfg is not None:
- # Heterogeneous-block DiTs (Z-Image: ~11 distinct block shapes) exceed dynamo's default recompile
- # limit of 8; bump it like the inference speed layer does.
+ # Heterogeneous-block DiTs (Z-Image: ~11 distinct block shapes) exceed dynamo's default recompile limit of
+ # 8; bump it like the inference speed layer does.
for attr in ("recompile_limit", "cache_size_limit"):
if hasattr(dynamo_cfg, attr):
setattr(dynamo_cfg, attr, max(getattr(dynamo_cfg, attr) or 0, 64))
if hasattr(dynamo_cfg, "suppress_errors"):
dynamo_cfg.suppress_errors = True
- # dynamic=True matches the inference speed layer: on torch 2.10 / B200 the dynamic=False
- # specialisation failed with CUBLAS_STATUS_EXECUTION_FAILED.
+ # dynamic=True matches the inference speed layer: on torch 2.10 / B200 the dynamic=False specialisation failed
+ # with CUBLAS_STATUS_EXECUTION_FAILED.
fn(fullgraph = not base_is_bnb, dynamic = True)
return True
except Exception as exc: # noqa: BLE001 -- optimisation only, never fatal
@@ -1839,19 +1816,18 @@ def run_dit_lora_training(
on_event: Optional[EventCb] = None,
should_stop: Optional[StopCb] = None,
) -> str:
- """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2 / LTX-2) and export it.
-
- Resumable: ``cfg.resume_from_checkpoint`` restores the adapter, optimizer moments, LR
- position, EMA shadow, sampler cycle and RNG streams from a ``checkpoint-<N>`` bundle,
- and the loop runs steps N+1..train_steps (the TARGET TOTAL). A stop-and-save and every
+ """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2 / LTX-2) and
+ export it. Resumable: ``cfg.resume_from_checkpoint`` restores the adapter, optimizer moments,
+ LR position, EMA shadow, sampler cycle and RNG streams from a ``checkpoint-<N>`` bundle, and
+ the loop runs steps N+1..train_steps (the TARGET TOTAL). A stop-and-save and every
``cfg.save_steps`` interval write such a bundle."""
cfg = config.normalized()
spec = _SPECS.get(cfg.resolved_family)
if spec is None:
raise ValueError(f"No DiT trainer for family {cfg.resolved_family!r}")
- # DiT families train in bf16, so an explicit fp16 request is refused, not silently upgraded.
- # Validated before the heavy imports so a host without diffusers still sees the real error.
+ # DiT families train in bf16, so an explicit fp16 request is refused, not silently upgraded. Validated before the
+ # heavy imports so a host without diffusers still sees the real error.
if cfg.mixed_precision == "fp16" and spec.force_bf16:
raise ValueError(
f"{spec.family} LoRA training requires bf16: fp16 overflows its fp32 RoPE / "
@@ -1878,8 +1854,8 @@ def run_dit_lora_training(
return True
device = "cuda" if torch.cuda.is_available() else "cpu"
- # Fail fast on pre-Ampere CUDA, gating on NATIVE bf16 (capability major >= 8), since
- # is_bf16_supported() counts emulation.
+ # Fail fast on pre-Ampere CUDA, gating on NATIVE bf16 (capability major >= 8), since is_bf16_supported() counts
+ # emulation.
if device == "cuda" and not native_bf16_supported():
raise ValueError(
"This trainer requires a bfloat16-capable GPU (Ampere or newer); "
@@ -1888,17 +1864,17 @@ def run_dit_lora_training(
weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32
_assert_trusted_base_model(cfg.base_model)
- # Check the repo this run will FETCH: the canonical id would raise for a gated base already
- # redirected to its ungated mirror, after the route answered 200 and freed the residents.
+ # Check the repo this run will FETCH: the canonical id would raise for a gated base already redirected to its
+ # ungated mirror, after the route answered 200 and freed the residents.
_assert_gated_access(cfg.fetch_base_model or cfg.base_model, cfg.hf_token)
pairs = discover_image_caption_pairs(
cfg.data_dir, instance_prompt = cfg.instance_prompt, caption_column = cfg.caption_column
)
- # Resolve num_epochs into a concrete train_steps now the dataset size is known, and rebind cfg so every
- # downstream read agrees.
+ # Resolve num_epochs into a concrete train_steps now the dataset size is known, and rebind cfg so every downstream
+ # read agrees.
cfg = replace(cfg, train_steps = resolve_train_steps(cfg, len(pairs)), num_epochs = 0)
- # Validate a resume against this run's identity BEFORE the multi-GB phased load, using the RESOLVED
- # LoRA targets rather than the generic default the config carries.
+ # Validate a resume against this run's identity BEFORE the multi-GB phased load, using the RESOLVED LoRA targets
+ # rather than the generic default the config carries.
identity = identity_for_config(
cfg,
dataset_pairs = pairs,
@@ -1918,14 +1894,14 @@ def run_dit_lora_training(
lora_path = None,
stopped = True,
steps_run = 0,
- # A stop with save=false is a DISCARD however early it lands; without it the resume fallback offers
- # the source bundle back as though the attempt were still live.
+ # A stop with save=false is a DISCARD however early it lands; without it the resume fallback offers the
+ # source bundle back as though the attempt were still live.
discarded = not save_on_stop,
)
return str(out_dir)
- # TF32 / cudnn.benchmark for the run, restored on the way out (the trainer subprocess is disposable, but
- # restoring keeps in-process callers clean).
+ # TF32 / cudnn.benchmark for the run, restored on the way out (the trainer subprocess is disposable, but restoring
+ # keeps in-process callers clean).
perf_snap = _apply_perf_flags(cfg, device)
try:
return _train_dit(
@@ -1957,8 +1933,8 @@ def _train_dit(
from peft import LoraConfig
from peft.utils import get_peft_model_state_dict
- # diffusers honours no env var and is only in sys.modules from here, so its pipeline-loading bars
- # can only be turned off now.
+ # diffusers honours no env var and is only in sys.modules from here, so its pipeline-loading bars can only be
+ # turned off now.
try:
from loggers.config import quiet_third_party_progress_bars
quiet_third_party_progress_bars()
@@ -1967,17 +1943,17 @@ def _train_dit(
use_lora_targets = _select_lora_targets(cfg.lora_target_modules, spec.lora_targets)
out_dir = Path(cfg.output_dir).expanduser()
- # Load from the byte-identical public mirror selected during normalization, while keeping
- # cfg.base_model canonical for the adapter sidecar, completion event and resume identity.
+ # Load from the byte-identical public mirror selected during normalization, while keeping cfg.base_model canonical
+ # for the adapter sidecar, completion event and resume identity.
fetch_cfg = replace(cfg, base_model = cfg.fetch_base_model or cfg.base_model)
- # Phase 0: the persistent conditioning cache (opt-in via cond_cache_dir). When every planned latent variant
- # AND caption embedding is on disk, the run is "warm": the VAE and text encoders never load.
+ # Phase 0: the persistent conditioning cache (opt-in via cond_cache_dir). When every planned latent variant AND
+ # caption embedding is on disk, the run is "warm": the VAE and text encoders never load.
image_paths = [p for p, _ in pairs]
captions = [c for _, c in pairs]
uniq = sorted(set(captions))
- # CFG dropout swaps a sample's conditioning for the empty prompt, so its embedding must be
- # precomputed alongside the captions (the encoders are freed right after).
+ # CFG dropout swaps a sample's conditioning for the empty prompt, so its embedding must be precomputed alongside
+ # the captions (the encoders are freed right after).
cfg_dropout = float(getattr(cfg, "cfg_dropout", 0.0) or 0.0)
to_encode = uniq + ([""] if cfg_dropout > 0 and "" not in uniq else [])
use_cache = cfg.cache_latents and os.environ.get(
@@ -1986,15 +1962,15 @@ def _train_dit(
pcache = None
if getattr(cfg, "cond_cache_dir", None):
try:
- # Namespace on the CHECKPOINT, not just the family: the keys carry only caption/image content, so
- # one cache dir reused for two checkpoints would train on the other model's embeddings.
+ # Namespace on the CHECKPOINT, not just the family: the keys carry only caption/image content, so one
+ # cache dir reused for two checkpoints would train on the other model's embeddings.
from .diffusion_train_extras import source_revision # noqa: PLC0415
namespace = f"{spec.family}_{cfg.base_model}_{source_revision(fetch_cfg.base_model)}"
pcache = PersistentConditioningCache(cfg.cond_cache_dir, namespace, cfg.resolution)
except Exception as exc: # noqa: BLE001 -- the cache is an optimisation, never fatal
_emit(on_event, "warning", message = f"conditioning cache disabled: {exc}")
- # The crop/flip variant plan is seed-deterministic, so persistent keys are stable across runs and
- # the warm check can run before anything loads.
+ # The crop/flip variant plan is seed-deterministic, so persistent keys are stable across runs and the warm check
+ # can run before anything loads.
plan = _plan_cache_variants(
len(image_paths), cfg.cache_variants, cfg.center_crop, cfg.random_flip, cfg.seed
)
@@ -2070,8 +2046,8 @@ def _train_dit(
# Variant picks use their own stream so the training loop index/noise draws stay seed-deterministic.
variant_rng = random.Random(cfg.seed + 1)
- # Phase 3: only now load the transformer, in the resolved base precision (nf4 QLoRA by default; bf16 / int8
- # / fp8 / mxfp8 are the dense speed modes; "auto" picks from free VRAM).
+ # Phase 3: only now load the transformer, in the resolved base precision (nf4 QLoRA by default; bf16 / int8 / fp8
+ # / mxfp8 are the dense speed modes; "auto" picks from free VRAM).
base_precision = _resolve_base_precision(cfg, spec, device)
transformer = spec.load_transformer(fetch_cfg, device, weight_dtype, base_precision)
base_is_bnb = base_precision == "nf4"
@@ -2087,8 +2063,8 @@ def _train_dit(
)
)
if cfg.gradient_checkpointing:
- # Non-reentrant checkpointing: reentrant recompute of a bnb 4-bit LoRA linear can trip an illegal
- # memory access on the larger FLUX transformer, and it is the recommended mode anyway.
+ # Non-reentrant checkpointing: reentrant recompute of a bnb 4-bit LoRA linear can trip an illegal memory
+ # access on the larger FLUX transformer, and it is the recommended mode anyway.
import functools
import torch.utils.checkpoint as _ckpt
transformer.enable_gradient_checkpointing(
@@ -2097,8 +2073,8 @@ def _train_dit(
cast_training_params(transformer, dtype = torch.float32)
lora_params = [p for p in transformer.parameters() if p.requires_grad]
- # int8 / fp8 / mxfp8 convert the frozen base linears AFTER the LoRA attaches, so the adapter modules
- # are excluded and stay high precision.
+ # int8 / fp8 / mxfp8 convert the frozen base linears AFTER the LoRA attaches, so the adapter modules are excluded
+ # and stay high precision.
if base_precision == "int8":
_int8_quantize_base(transformer, cfg.resolved_family)
if base_precision == "fp8" and not _apply_fp8_training(transformer, on_event):
@@ -2106,14 +2082,15 @@ def _train_dit(
if base_precision == "mxfp8" and not _apply_mxfp8_training(transformer, on_event):
base_precision = "bf16"
- # LoRA EMA (opt-in via cfg.ema_decay): shadows ONLY the trainable adapter params, initialised after
- # the precision conversions so they track the final fp32 objects.
+ # LoRA EMA (opt-in via cfg.ema_decay): shadows ONLY the trainable adapter params, initialised after the precision
+ # conversions so they track the final fp32 objects.
ema = LoRAEMA(transformer, decay = cfg.ema_decay) if getattr(cfg, "ema_decay", 0.0) else None
compiled = _maybe_compile_transformer(
transformer, cfg, base_is_bnb, device, on_event, base_precision
)
- # Compiled Qwen graphs need one fixed text length across steps: pin the pad bucket to the dataset's longest caption.
+ # Compiled Qwen graphs need one fixed text length across steps: pin the pad bucket to the dataset's longest
+ # caption.
qwen_pad_to = None
if compiled and spec.family == "qwen-image":
qwen_pad_to = max(e[0].shape[1] for e in caption_embeds.values())
@@ -2134,8 +2111,8 @@ def _train_dit(
if str(getattr(cfg, "weighting_scheme", "none") or "none") == "bell"
else None
)
- # The LR schedule advances once per optimizer update, so warmup/decay count optimizer steps; scaling
- # by the accumulation factor would stretch warmup past the run.
+ # The LR schedule advances once per optimizer update, so warmup/decay count optimizer steps; scaling by the
+ # accumulation factor would stretch warmup past the run.
lr_sched = get_scheduler(
cfg.lr_scheduler,
optimizer = optimizer,
@@ -2144,26 +2121,26 @@ def _train_dit(
)
_emit(on_event, "model_load_completed", compiled = compiled, base_precision = base_precision)
- # Read the commit now the base is on disk: an identity built before the load says "unresolved",
- # which is not comparable, so a later resume could not tell the repo had moved underneath it.
- # Record the repo actually fetched: the canonical base is not on disk at all when the mirror was
- # selected, and mismatch_reason only compares two revisions that came from the same repo.
+ # Read the commit now the base is on disk: an identity built before the load says "unresolved", which is not
+ # comparable, so a later resume could not tell the repo had moved underneath it. Record the repo actually fetched:
+ # the canonical base is not on disk at all when the mirror was selected, and mismatch_reason only compares two
+ # revisions that came from the same repo.
identity = with_resolved_revision(identity, fetch_cfg.base_model)
# See the SDXL trainer: the cache path the loop actually took, not the one requested.
identity = with_cache_mode(identity, latent_cache is not None)
- # base_precision is still the request here ("auto" resolves at load, and a failed fp8/mxfp8
- # conversion has fallen back to bf16), so without this a bundle records a base it never trained on.
+ # base_precision is still the request here ("auto" resolves at load, and a failed fp8/mxfp8 conversion has fallen
+ # back to bf16), so without this a bundle records a base it never trained on.
identity = with_resolved_base_precision(identity, base_precision)
transformer.train()
n_images = len(image_paths)
batch_size = cfg.train_batch_size
- # Permutation-cycle index sampler (shared with the SDXL trainer): visits every image once per cycle,
- # so a short run covers the whole dataset.
+ # Permutation-cycle index sampler (shared with the SDXL trainer): visits every image once per cycle, so a short
+ # run covers the whole dataset.
index_sampler = PermutationBatchSampler(n_images, rng)
- # Restore a previous run (adapter, optimizer moments, LR position, EMA shadow, sampler cycle, RNG streams)
- # before the loop, so it picks up at `resumed + 1`. None for a fresh run.
+ # Restore a previous run (adapter, optimizer moments, LR position, EMA shadow, sampler cycle, RNG streams) before
+ # the loop, so it picks up at `resumed + 1`. None for a fresh run.
rng_streams = {"loop": rng, "variant": variant_rng}
restored = restore_resume_state(
cfg,
@@ -2177,16 +2154,16 @@ def _train_dit(
rng_streams = rng_streams,
)
resumed = restored.step if restored is not None else 0
- # Resuming from directory A into a reused output_dir B leaves B's existing bundles as foreign as
- # for a fresh run, so the first save must clear them or a higher-numbered one outranks this run.
+ # Resuming from directory A into a reused output_dir B leaves B's existing bundles as foreign as for a fresh run,
+ # so the first save must clear them or a higher-numbered one outranks this run.
resumed_here = bool(resumed) and resumed_into_this_dir(cfg, out_dir)
# The bundles already here when this run started, so a discard removes only what this run wrote.
preexisting_checkpoints = snapshot_checkpoints(out_dir)
if restored is not None:
was = restored.progress.get("resolved_base_precision")
if was and was != base_precision:
- # Not fatal, since only the frozen base's numerics change, but base_precision="auto" picks from free
- # VRAM, so this can happen silently.
+ # Not fatal, since only the frozen base's numerics change, but base_precision="auto" picks from free VRAM,
+ # so this can happen silently.
_emit(
on_event,
"warning",
@@ -2206,9 +2183,8 @@ def _train_dit(
done = resumed
def _save_checkpoint(step: int) -> None:
- # write_resume_checkpoint reports its own checkpoint_saved / checkpoint_failed events, so a run
- # that crashes after a save is still known to be resumable and one whose save failed is still
- # known to be blocked.
+ # write_resume_checkpoint reports its own checkpoint_saved / checkpoint_failed events, so a run that crashes
+ # after a save is still known to be resumable and one whose save failed is still known to be blocked.
_written, _error = write_resume_checkpoint(
cfg,
step = step,
@@ -2220,18 +2196,18 @@ def _train_dit(
ema = ema,
sampler = index_sampler,
rng_streams = rng_streams,
- # "auto" resolves from free VRAM at load time, so the identity, which records the REQUESTED mode,
- # cannot tell nf4 from bf16 across two "auto" runs.
+ # "auto" resolves from free VRAM at load time, so the identity, which records the REQUESTED mode, cannot
+ # tell nf4 from bf16 across two "auto" runs.
progress = {"running_loss": running_loss, "resolved_base_precision": base_precision},
- # NOT discard_existing: deleting the previous run's bundles at the FIRST periodic save spends them
- # before this run produced anything, so cancelling a retrain destroyed the thing being retrained.
+ # NOT discard_existing: deleting the previous run's bundles at the FIRST periodic save spends them before
+ # this run produced anything, so cancelling a retrain destroyed the thing being retrained.
discard_existing = False,
# A branched resume must not prune the higher-numbered checkpoints it did not write.
preexisting = preexisting_checkpoints,
)
- # bf16 autocast around the forward + loss, matching the diffusers dreambooth scripts: it reconciles
- # the fp32 LoRA params with the bnb 4-bit base matmuls.
+ # bf16 autocast around the forward + loss, matching the diffusers dreambooth scripts: it reconciles the fp32 LoRA
+ # params with the bnb 4-bit base matmuls.
autocast = (
torch.autocast(device_type = "cuda", dtype = torch.bfloat16)
if device == "cuda"
@@ -2299,8 +2275,8 @@ def _train_dit(
grad_norm = None
if cfg.max_grad_norm and cfg.max_grad_norm > 0:
- # clip_grad_norm_ returns the total PRE-clip norm: the health signal the UI charts (an exploding
- # norm shows even while the clip caps the update).
+ # clip_grad_norm_ returns the total PRE-clip norm: the health signal the UI charts (an exploding norm
+ # shows even while the clip caps the update).
grad_norm = float(torch.nn.utils.clip_grad_norm_(lora_params, cfg.max_grad_norm))
optimizer.step()
lr_sched.step()
@@ -2369,18 +2345,18 @@ def _train_dit(
except Exception as exc: # noqa: BLE001 -- the primary adapter is already saved
_emit(on_event, "warning", message = f"EMA adapter save failed: {exc}")
if not stopped:
- # A completed run has nothing to resume and the final iteration writes no bundle, so save_steps
- # would leave this run's own checkpoint behind for a later resume to roll back to.
+ # A completed run has nothing to resume and the final iteration writes no bundle, so save_steps would
+ # leave this run's own checkpoint behind for a later resume to roll back to.
retire_own_checkpoints(out_dir, preexisting_checkpoints, resumed_here = resumed_here)
elif not resumed_here:
- # A stop-with-save on a fresh retrain is a LOWER step than the earlier run's leftovers, and resume-
- # by-directory picks the newest by step, so those would outrank the partial just saved and continue
+ # A stop-with-save on a fresh retrain is a LOWER step than the earlier run's leftovers, and
+ # resume-by-directory picks the newest by step, so those would outrank the partial just saved and continue
# the wrong training. A run that RESUMED here instead keeps what it found.
discard_preexisting_checkpoints(out_dir, preexisting_checkpoints)
else:
- # save_steps writes bundles as the run goes, so without this a discard leaves up to
- # save_total_limit copies of the optimizer state in a directory the user got no artifact from:
- # invisible to every scanner, unresumable, with no delete path in the UI.
+ # save_steps writes bundles as the run goes, so without this a discard leaves up to save_total_limit copies of
+ # the optimizer state in a directory the user got no artifact from: invisible to every scanner, unresumable,
+ # with no delete path in the UI.
clear_own_checkpoints(out_dir, preexisting_checkpoints)
try:
out_dir.rmdir()
@@ -2400,20 +2376,19 @@ def _train_dit(
steps_run = done if cfg.train_steps else 0,
wall_seconds = round(time.time() - t_start, 1),
resumed_from_step = resumed or None,
- # "Stop without saving" discards the run, so its own periodic checkpoints must not keep offering to continue it.
+ # "Stop without saving" discards the run, so its own periodic checkpoints must not keep offering to continue
+ # it.
discarded = bool(stopped and not _save_on_stop()),
)
return str(out_dir)
def _make_optimizer(params, lr):
- """8-bit AdamW (bitsandbytes) when available -- half the optimizer state, no accuracy
- regression for LoRA -- else torch AdamW, fused on CUDA (with a fallback when this
- build/device lacks the fused kernel).
-
- UNSLOTH_DIFFUSION_FP32_OPTIM forces plain (non-fused) AdamW, as it does for SDXL: the
- accuracy guard wants the reference optimizer, and a host where the override means one
- thing for one trainer and nothing for the other cannot answer "can this checkpoint be
+ """8-bit AdamW (bitsandbytes) when available -- half the optimizer state, no accuracy regression
+ for LoRA -- else torch AdamW, fused on CUDA (with a fallback when this build/device lacks the
+ fused kernel). UNSLOTH_DIFFUSION_FP32_OPTIM forces plain (non-fused) AdamW, as it does for
+ SDXL: the accuracy guard wants the reference optimizer, and a host where the override means
+ one thing for one trainer and nothing for the other cannot answer "can this checkpoint be
resumed here" before the run starts."""
import torch
@@ -2433,11 +2408,11 @@ def _make_optimizer(params, lr):
def _free_text_encoders(pipe) -> None:
- """Drop every conditioning module the pipeline holds once the embeddings are
- precomputed, so they do not sit in VRAM during training. ``connectors`` is LTX-2's
- second conditioning stage (~2.7 GB) and belongs here for the same reason as the text
- encoders; ``audio_vae`` / ``vocoder`` are LTX-2 decode-side modules the trainer never
- touches. Absent attributes are skipped, so this is a no-op for the image families."""
+ """Drop every conditioning module the pipeline holds once the embeddings are precomputed, so
+ they do not sit in VRAM during training. ``connectors`` is LTX-2's second conditioning stage
+ (~2.7 GB) and belongs here for the same reason as the text encoders; ``audio_vae`` /
+ ``vocoder`` are LTX-2 decode-side modules the trainer never touches. Absent attributes are
+ skipped, so this is a no-op for the image families."""
for attr in (
"text_encoder",
"text_encoder_2",
diff --git a/studio/backend/core/training/diffusion_h3_clips.py b/studio/backend/core/training/diffusion_h3_clips.py
index 779266e8252..74563fc49cd 100644
--- a/studio/backend/core/training/diffusion_h3_clips.py
+++ b/studio/backend/core/training/diffusion_h3_clips.py
@@ -24,9 +24,8 @@ from pathlib import Path
from typing import Any, Callable, Optional
from utils.paths.path_utils import drop_appledouble_metadata
-# Checkpoint contracts mirrored from diffusers.modular_pipelines.minimax_h3, which the trainer
-# cannot import; asserted against the live components at load, so a move is caught.
-# ── the model's grid ─────────────────────────────────────────────────────────
+# Checkpoint contracts mirrored from diffusers.modular_pipelines.minimax_h3, which the trainer cannot import; asserted
+# against the live components at load, so a move is caught.
H3_FPS = 24
# The video VAE's clip_length and tokens_chunk_size: 17 pixel frames per chunk, 5 latent frames
# kept per chunk, plus a 2-frame head.
diff --git a/studio/backend/core/training/diffusion_h3_trainer.py b/studio/backend/core/training/diffusion_h3_trainer.py
index 579f230d201..1fa3360eb93 100644
--- a/studio/backend/core/training/diffusion_h3_trainer.py
+++ b/studio/backend/core/training/diffusion_h3_trainer.py
@@ -3,40 +3,36 @@
"""Joint video + audio LoRA training for MiniMax-H3.
-MiniMax-H3 is rectified flow like every family in ``diffusion_dit_trainer``, but three things
-put it outside that trainer's ``_FamilySpec`` seams rather than inside them, so it gets its
-own loop here and shares ``diffusion_train_common`` (config, events, stop, trust gate,
-publishing, EMA, the 8-bit optimizer) with everything else:
-
-1. **One packed sequence, two modalities.** H3 runs a single block stack over one 1-D
- sequence holding ``[text | audio | video]`` rows with full self-attention. There is no
- cross-attention, no per-modality block weights and no ``isolate_modalities`` escape hatch
- (LTX-2 has all three). So a LoRA on the attention/MLP projections is applied to the audio
- rows as well as the video ones, and the audio rows are keys and values for every video
- row. Audio therefore cannot be excluded from the adapter, and the only honest objective is
- the model's own: regress BOTH velocities. That is why the dataset unit is a clip with
- sound (``diffusion_h3_clips``) and why there is no still-image milestone here.
-
-2. **Two coupled schedules.** Video is noised through an exponential shift of 12.0 and audio
- through 3.0. At inference both are indexed by the same step, so the pair
- ``(sigma_video, sigma_audio)`` traverses one curve. Training draws ONE base ``u`` and
- pushes it through both shifts, which reproduces that curve exactly; drawing the two
- independently would train pairs the sampler never visits. ``MiniMaxH3Scheduler`` is also
- not a ``FlowMatchEulerDiscreteScheduler`` (reversed velocity sign, ``t = 1 - sigma`` in
- [0, 1], a different sigma grid), so the shared trainer's sigma table does not apply.
+MiniMax-H3 is rectified flow like every family in ``diffusion_dit_trainer``, but three things put it
+outside that trainer's ``_FamilySpec`` seams, so it gets its own loop here and shares
+``diffusion_train_common`` (config, events, stop, trust gate, publishing, EMA, the 8-bit optimizer)
+with everything else:
+1. **One packed sequence, two modalities.** H3 runs a single block stack over one 1-D sequence
+holding ``[text | audio | video]`` rows with full self-attention. There is no cross-attention, no
+per-modality block weights and no ``isolate_modalities`` escape hatch, so a LoRA on the
+attention/MLP projections is applied to the audio rows as well as the video ones, and the audio rows
+are keys and values for every video row. Audio therefore cannot be excluded from the adapter, and
+the only honest objective is the model's own: regress BOTH velocities. That is why the dataset unit
+is a clip with sound (``diffusion_h3_clips``) and why there is no still-image milestone here.
+
+2. **Two coupled schedules.** Video is noised through an exponential shift of 12.0 and audio through
+3.0. At inference both are indexed by the same step, so the pair ``(sigma_video, sigma_audio)``
+traverses one curve; training draws ONE base ``u`` and pushes it through both shifts, which
+reproduces that curve exactly, where drawing the two independently would train pairs the sampler
+never visits. ``MiniMaxH3Scheduler`` is also not a ``FlowMatchEulerDiscreteScheduler`` (reversed
+velocity sign, ``t = 1 - sigma`` in [0, 1], a different sigma grid), so the shared trainer's sigma
+table does not apply.
3. **It is modular-only.** There is no ``MiniMaxH3Pipeline``; the integration is a
- ``ModularPipeline`` plus blocks. The trainer never builds one: the two layout builders it
- needs are ``@staticmethod``s, and the components load individually -- which is a better fit
- for the phased load than the ``transformer = None`` trick, since ``load_components`` takes
- the component names outright.
+``ModularPipeline`` plus blocks. The trainer never builds one: the two layout builders it needs are
+``@staticmethod``s, and the components load individually, which fits the phased load better than the
+``transformer = None`` trick.
Velocity sign: H3 predicts a DATA-ward velocity (``x0 = x_t + sigma * v``), i.e. the target is
``latents - noise``, the negation of the convention in ``diffusion_dit_trainer``.
-Memory: the Qwen3-VL-32B conditioner is 63 GiB on disk, so captions are encoded once up front
-and it is freed before the VAEs encode and long before the 66 GB transformer loads -- the same
-phased load the DiT trainer uses, expressed through ``load_components``.
+Memory: the Qwen3-VL-32B conditioner is 63 GiB on disk, so captions are encoded once up front and it
+is freed before the VAEs encode and long before the 66 GB transformer loads.
"""
from __future__ import annotations
@@ -538,8 +534,7 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
to_encode = sorted(set(captions))
- # Phase 1: the 63 GiB Qwen3-VL conditioner and both VAEs are resident here and nowhere else.
- # ── phase 1: conditioning. The 63 GiB Qwen3-VL conditioner and both VAEs are resident
+ # Phase 1: conditioning. The 63 GiB Qwen3-VL conditioner and both VAEs are resident here and nowhere else.
pipe = _load_conditioners(cfg, device)
caption_embeds = {cap: _encode_prompt(pipe, cap, device) for cap in to_encode}
_emit(on_event, "preparing", stage = "encode_prompts", done = len(to_encode), total = len(to_encode))
@@ -550,9 +545,8 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
if device == "cuda":
torch.cuda.empty_cache()
- # One canvas for the run, from the FIRST clip's aspect ratio: every other clip is cover-cropped
- # onto it, so a mixed-aspect dataset trains on one geometry.
- # ── phase 2: the clip cache. One canvas for the run, taken from the FIRST clip's aspect
+ # Phase 2: the clip cache. One canvas for the run, from the FIRST clip's aspect ratio: every other clip is
+ # cover-cropped onto it, so a mixed-aspect dataset trains on one geometry.
width, height = _dataset_canvas(clip_paths[0], cfg.resolution)
latent_h, latent_w = height // H3_SPATIAL_COMPRESSION, width // H3_SPATIAL_COMPRESSION
cache: list[tuple[Any, Any, Any]] = []
@@ -605,7 +599,7 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
if device == "cuda":
torch.cuda.empty_cache()
- # ── phase 3: the denoiser.
+ # Phase 3: the denoiser.
base_precision = cfg.base_precision if cfg.base_precision != "auto" else "nf4"
if base_precision in ("fp8", "mxfp8"):
raise ValueError(
diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.py
index 44b8e0f5f74..fcaa525d697 100644
--- a/studio/backend/core/training/diffusion_lora_trainer.py
+++ b/studio/backend/core/training/diffusion_lora_trainer.py
@@ -3,32 +3,26 @@
"""Diffusion LoRA training for Unsloth Studio (text-to-image, SDXL).
-Trains a LoRA adapter on the U-Net of an SDXL pipeline from an image + caption dataset
-and exports it as a diffusers-format ``.safetensors`` that the Unsloth diffusion backend
-(and any diffusers pipeline via ``load_lora_weights``) can load.
-
-Design:
-- Family-agnostic building blocks (dataset discovery, config normalisation + validation,
- event emission, the stop protocol, adapter publishing, and the family/trainer registry)
- live in ``diffusion_train_common`` and are shared with the DiT trainers. They are
- re-exported here so existing import paths keep working.
-- ``run_diffusion_lora_training`` is the SDXL training loop. It reports progress through an
- ``on_event`` callback whose payloads match the training worker's event protocol
- (``{"type": ..., "ts": ...}``) so it can be spawned as a subprocess and streamed to the
- UI, and it polls a ``should_stop`` callback so a stop request ends it cleanly (with a
- partial save).
-- ``run_diffusion_training_process`` is the thin mp.Queue adapter; it dispatches to the
- trainer registered for the resolved family (SDXL here, DiT families in a follow-up).
- ``main`` is a CLI.
-
-Memory/perf: captions are encoded once up front and the CLIP text encoders freed; VAE
-latents are likewise precomputed into a small CPU cache (``cache_latents``) and the VAE
-freed. The cache stores the posterior's affine pair (mean/std, scale folded in), so every
-step still draws a fresh VAE sample -- distribution-identical to encoding in the loop,
-without keeping the VAE resident or paying a per-step encode. TF32 matmuls + cudnn
-autotuning are enabled for the run under ``cfg.enable_tf32``, and the U-Net's repeated
-transformer blocks are regionally torch.compiled (``cfg.compile_transformer``, never
-fatal -- any failure falls back to eager with a warning event).
+Trains a LoRA adapter on the U-Net of an SDXL pipeline from an image + caption dataset and exports
+it as a diffusers-format ``.safetensors`` the Unsloth diffusion backend (and any diffusers pipeline
+via ``load_lora_weights``) can load.
+
+Family-agnostic building blocks (dataset discovery, config normalisation and validation, event
+emission, the stop protocol, adapter publishing, and the family/trainer registry) live in
+``diffusion_train_common`` and are shared with the DiT trainers; they are re-exported here so
+existing import paths keep working. ``run_diffusion_lora_training`` is the SDXL training loop: it
+reports progress through an ``on_event`` callback whose payloads match the training worker's event
+protocol so it can be spawned as a subprocess and streamed to the UI, and it polls a ``should_stop``
+callback so a stop request ends it cleanly with a partial save. ``run_diffusion_training_process``
+is the thin mp.Queue adapter, dispatching to the trainer registered for the resolved family, and
+``main`` is a CLI.
+
+Memory/perf: captions are encoded once up front and the CLIP text encoders freed; VAE latents are
+likewise precomputed into a small CPU cache (``cache_latents``) and the VAE freed. The cache stores
+the posterior's affine pair (mean/std, scale folded in), so every step still draws a fresh VAE
+sample, distribution-identical to encoding in the loop without keeping the VAE resident. TF32
+matmuls and cudnn autotuning are enabled under ``cfg.enable_tf32``, and the U-Net's repeated
+transformer blocks are regionally torch.compiled (``cfg.compile_transformer``, never fatal).
"""
from __future__ import annotations
@@ -122,7 +116,6 @@ def _load_image_tensor(
if random_flip and rng.random() < 0.5:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# A flip mirrors the crop's left origin, so report the mirrored offset (as diffusers does).
- # Mirror the crop's left origin (same as _load_image_tensor's random flip).
crop_left = max(0, resized_w - resolution - left)
arr = np.asarray(img, dtype = np.float32) / 255.0
tensor = torch.from_numpy(arr).permute(2, 0, 1) * 2.0 - 1.0
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index fd04aaedee5..c9316c24d59 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -1,17 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Shared, family-agnostic building blocks for diffusion LoRA training.
-
-Everything here is independent of a specific model architecture, so the SDXL U-Net
-trainer (``diffusion_lora_trainer``) and the flow-matching DiT trainers share it:
-dataset discovery, the request config + validation, image loading, event emission,
-the stop protocol, adapter publishing, and the family/trainer registry.
-
-The pure helpers have no torch/diffusers import at call time and are unit-tested
-without a GPU. ``run_diffusion_lora_training`` and its per-family siblings own the
-actual training loop; this module only routes a request to the right one.
-"""
+"""Shared, family-agnostic building blocks for diffusion LoRA training: dataset discovery, request
+config + validation, image loading, event emission, the stop protocol, adapter publishing, and
+the family/trainer registry, so the SDXL U-Net trainer (``diffusion_lora_trainer``) and the
+flow-matching DiT trainers share them. The pure helpers have no torch/diffusers import at call
+time and are unit-tested without a GPU; this module only routes a request to the right training
+loop."""
from __future__ import annotations
@@ -41,19 +36,19 @@ from core.inference.diffusion_torchao_patches import install_torchao_int_mm_patc
from core.inference.video_families import detect_video_family, supported_video_family_names
from utils.paths.path_utils import drop_appledouble_metadata
-# The trainers run in a spawned child that imports diffusers itself, so the inference-side install
-# does not carry over. Both import this module first.
+# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry
+# over. Both import this module first.
install_xformers_windows_rocm_stub()
install_torchao_windows_rocm_stub()
# Same child: the DiT trainer's int8 base-weight quantisation goes through torchao.
install_torchao_int_mm_patch()
-# Default LoRA target modules: the attention projections common to the SDXL U-Net and the DiTs (the
-# diffusers/kohya convention). A family may override this.
+# Default LoRA target modules: the attention projections common to the SDXL U-Net and the DiTs (the diffusers/kohya
+# convention). A family may override this.
DEFAULT_LORA_TARGETS: tuple[str, ...] = ("to_k", "to_q", "to_v", "to_out.0")
-# piecewise_constant is excluded: it alone needs a step_rules string the trainers never pass, so
-# accepting it would pass normalized(), free the resident GPU workloads, then crash in the child.
+# piecewise_constant is excluded: it alone needs a step_rules string the trainers never pass, so accepting it would
+# pass normalized(), free the resident GPU workloads, then crash in the child.
_LR_SCHEDULERS: frozenset[str] = frozenset(
{
"linear",
@@ -65,29 +60,26 @@ _LR_SCHEDULERS: frozenset[str] = frozenset(
}
)
-# DiT families whose fp32 RoPE/embedder overflow fp16, so they train in bf16 only. Keep in sync with
-# the DiT trainer's own specs.
+# DiT families whose fp32 RoPE/embedder overflow fp16, so they train in bf16 only. Keep in sync with the DiT trainer's
+# own specs.
_FORCE_BF16_FAMILIES: frozenset[str] = frozenset(
{"qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2", "minimax-h3"}
)
-# The video registry has no trainable flag, so the trainable set lives here and every name in it
-# MUST resolve through get_trainer; a video base outside it is refused by name.
+# The video registry has no trainable flag, so the trainable set lives here and every name in it MUST resolve through
+# get_trainer; a video base outside it is refused by name.
TRAINABLE_VIDEO_FAMILIES: frozenset[str] = frozenset({"ltx-2", "minimax-h3"})
-# Families whose flow_shift default is "auto" (reproduce the family's INFERENCE sigma
-# distribution) rather than the identity 1.0. Both schedulers set use_dynamic_shifting, so
-# scheduler.sigmas is the unshifted uniform table and training on it draws a distribution the
-# model never sees at inference: Qwen-Image pins base_shift = max_shift = log 3 and LTX-2
-# evaluates its shift at max_image_seq_len (mu = max_shift = 2.05 at every resolution), so the
-# inference mu is a constant "auto" reproduces. MiniMax-H3 instead applies explicit exponential
-# shifts (12.0 video, 3.0 audio) whenever flow_shift is not a number, so without this entry a
-# default H3 run trained unshifted.
+# Families whose flow_shift default is "auto" (reproduce the family's INFERENCE sigma distribution) rather than the
+# identity 1.0. Both schedulers set use_dynamic_shifting, so scheduler.sigmas is the unshifted uniform table and
+# training on it draws a distribution the model never sees at inference: Qwen-Image pins base_shift = max_shift = log
+# 3 and LTX-2 evaluates its shift at max_image_seq_len, so the inference mu is a constant "auto" reproduces.
+# MiniMax-H3 instead applies explicit exponential shifts (12.0 video, 3.0 audio) whenever flow_shift is not a number,
+# so without this entry a default H3 run trained unshifted.
AUTO_FLOW_SHIFT_FAMILIES: frozenset[str] = frozenset({"qwen-image", "ltx-2", "minimax-h3"})
-# Video latents are allocated on the family's spatial compression grid, so a training resolution
-# off that grid silently changes the latent geometry. LTX-2's VAE compresses 32x spatially,
-# matching its resolution_multiple.
+# Video latents are allocated on the family's spatial compression grid, so a training resolution off that grid
+# silently changes the latent geometry. LTX-2's VAE compresses 32x spatially, matching its resolution_multiple.
_VIDEO_RESOLUTION_MULTIPLE = 32
_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}
@@ -95,33 +87,32 @@ _CAPTION_EXTS = (".txt", ".caption")
# diffusers' canonical single-file LoRA name, so load_lora_weights(dir) finds it.
DEFAULT_LORA_FILENAME = "pytorch_lora_weights.safetensors"
-# Architectures Unsloth can neither train nor load: not in the family registry but recognisable by
-# name, so rejecting them by name gives a clear error instead of a mid-run crash.
+# Architectures Unsloth can neither train nor load: not in the family registry but recognisable by name, so rejecting
+# them by name gives a clear error instead of a mid-run crash.
_NON_TRAINABLE_RESIDUAL_TOKENS = frozenset({"sd3", "pixart", "sana", "lumina", "cogview"})
_NON_TRAINABLE_RESIDUAL_PHRASES = ("stable-diffusion-3", "hunyuan-dit")
EventCb = Callable[[dict[str, Any]], None]
-# Returns a falsy value to keep training, or a truthy stop signal: bare True, or a dict that may
-# carry ``save=False`` to cancel without saving a partial adapter.
+# Returns a falsy value to keep training, or a truthy stop signal: bare True, or a dict that may carry ``save=False``
+# to cancel without saving a partial adapter.
StopCb = Callable[[], Any]
def _all_trainable_family_names() -> tuple[str, ...]:
- """Every family with a trainer: the image registry's ``trainable`` families plus the
- video families listed in ``TRAINABLE_VIDEO_FAMILIES``. The two registries are separate
- by design (a video checkpoint must never route to an image pipeline), so the trainable
- view has to union them."""
+ """Every family with a trainer: the image registry's ``trainable`` families plus the video
+ families listed in ``TRAINABLE_VIDEO_FAMILIES``. The two registries are separate by design (a
+ video checkpoint must never route to an image pipeline), so the trainable view has to union
+ them."""
video = tuple(n for n in supported_video_family_names() if n in TRAINABLE_VIDEO_FAMILIES)
return tuple(trainable_family_names()) + video
def _trainable_family_spec(name: str) -> Any:
- """The registry entry for a trainable family name, from EITHER registry, or None.
-
- Every consumer that starts from a resolved family NAME (rather than from a repo id) needs
- this: the image registry does not know a video family, so a plain ``detect_family`` returns
- None for one and the caller silently skips it. That is how ``ltx-2`` stayed out of
- ``/diffusion/info`` and out of the strict pipeline gate."""
+ """The registry entry for a trainable family name, from EITHER registry, or None. Every consumer
+ that starts from a resolved family NAME rather than a repo id needs this: the image registry
+ does not know a video family, so a plain ``detect_family`` returns None for one and the
+ caller silently skips it. That is how ``ltx-2`` stayed out of ``/diffusion/info`` and out of
+ the strict pipeline gate."""
from core.inference.diffusion_families import detect_family
key = str(name or "").strip().lower()
@@ -132,12 +123,11 @@ def _trainable_family_spec(name: str) -> Any:
def _refuse_untrainable_video_family(name: str) -> None:
- """Raise for a video family Unsloth has no trainer for.
-
- Video bases are invisible to the image registry, so before this gate existed every video
- checkpoint fell through ``resolve_trainable_family``'s unknown-name fallback and was
- handed to the SDXL trainer, which then failed somewhere inside from_pretrained. Refuse by
- name instead, with the list of video families that do train."""
+ """Raise for a video family Unsloth has no trainer for. Video bases are invisible to the image
+ registry, so before this gate every video checkpoint fell through
+ ``resolve_trainable_family``'s unknown-name fallback and was handed to the SDXL trainer,
+ which failed inside from_pretrained. Refuse by name instead, listing the video families that
+ do train."""
trainable = ", ".join(sorted(TRAINABLE_VIDEO_FAMILIES))
raise ValueError(
f"'{name}' is a video model Unsloth can't train yet. Video LoRA training currently "
@@ -146,23 +136,21 @@ def _refuse_untrainable_video_family(name: str) -> None:
def _component_only_repos() -> dict[str, tuple[str, str, str]]:
- """Every repo the family registries list only as a COMPONENT source, keyed by lowercased
- repo id -> (family name, component, that family's base repo).
-
- A pre-cast text-encoder repo (``te_prequant_repos``, present in both the image and the video
- registry) ships a single component archive: no ``model_index.json``, no VAE, no scheduler, no
- pipeline. ``from_pretrained`` on one can only fail. Nothing in the NAME says so, which is the
- whole problem: ``unsloth/LTX-2-FP8`` carries the ``ltx-2`` token, so the family detectors
- claim it and the ``unsloth/*`` trust gate passes it. The registries' own tables are the only
- authority on what a repo actually holds, so read them rather than special-casing repo ids.
-
- A hosted pre-quantized DENOISER (a video family's ``prequant_repos``) is the same shape: the
- DiT alone, no pipeline around it. The image registry's identically-named table means the
- opposite -- a full quantized pipeline mirror -- so the two are read separately rather than
- together.
-
- A repo that is ALSO registered as a base somewhere (a full quantized pipeline mirror, a
- deploy base, a train base) is a base and never appears here."""
+ """Every repo the family registries list only as a COMPONENT source, keyed by lowercased repo id ->
+ (family name, component, that family's base repo).
+
+ A pre-cast text-encoder repo (``te_prequant_repos``, in both registries) ships a single
+ component archive: no ``model_index.json``, no VAE, no scheduler, no pipeline, so
+ ``from_pretrained`` on one can only fail. Nothing in the NAME says so: ``unsloth/LTX-2-FP8``
+ carries the ``ltx-2`` token, so the detectors claim it and the ``unsloth/*`` trust gate passes
+ it. The registries' own tables are the only authority on what a repo holds, so read them rather
+ than special-casing repo ids.
+
+ A hosted pre-quantized DENOISER (a video family's ``prequant_repos``) is the same shape: the DiT
+ alone. The image registry's identically-named table means the opposite -- a full quantized
+ pipeline mirror -- so the two are read separately. A repo ALSO registered as a base somewhere is
+ a base and never appears here.
+ """
from core.inference.diffusion_families import detect_family
from core.inference.video_families import detect_video_family
@@ -178,8 +166,8 @@ def _component_only_repos() -> dict[str, tuple[str, str, str]]:
if repo:
bases.add(str(repo).strip().lower())
bases.update(str(r).strip().lower() for r in getattr(fam, "train_base_repos", ()) if r)
- # An image family's entry is a full quantized PIPELINE mirror, and so a base; a video family's is a
- # hosted pre-quantized DENOISER, a component.
+ # An image family's entry is a full quantized PIPELINE mirror, and so a base; a video family's is a hosted
+ # pre-quantized DENOISER, a component.
for table in ("prequant_repos", "prequant_variant_repos"):
for row in getattr(fam, table, ()) or ():
if not row:
@@ -197,13 +185,12 @@ def _component_only_repos() -> dict[str, tuple[str, str, str]]:
def _refuse_component_only_repo(base_model: str) -> None:
- """Raise for a base model that is a family's component checkpoint rather than a model.
-
- Runs from ``resolve_trainable_family``, so it fires in the ``/diffusion/start`` preflight
- BEFORE the resident GPU workloads are freed. Without it the name match resolved a real
- family, the trust gate passed the ``unsloth/*`` repo, the gated-access probe ignored the
- resulting ``model_index.json`` 404 (a 404 is not an access problem), and the run evicted the
- user's loaded model before failing inside ``from_pretrained`` in the child."""
+ """Raise for a base model that is a family's component checkpoint rather than a model. Runs from
+ ``resolve_trainable_family``, so it fires in the ``/diffusion/start`` preflight BEFORE the
+ resident GPU workloads are freed. Without it the name match resolved a real family, the trust
+ gate passed the ``unsloth/*`` repo, the gated-access probe ignored the resulting
+ ``model_index.json`` 404 (a 404 is not an access problem), and the run evicted the user's
+ loaded model before failing inside ``from_pretrained`` in the child."""
hit = _component_only_repos().get(str(base_model or "").strip().lower())
if hit is None:
return
@@ -216,8 +203,8 @@ def _refuse_component_only_repo(base_model: str) -> None:
def _trainable_hint() -> str:
- """A user-facing hint listing the families Unsloth can train today. Always names SDXL
- explicitly so the message is actionable even as more families become trainable."""
+ """A user-facing hint listing the families Unsloth can train today. Always names SDXL explicitly
+ so the message is actionable even as more families become trainable."""
names = ", ".join(_all_trainable_family_names()) or "sdxl"
return (
f"Trainable families right now: {names} "
@@ -230,31 +217,27 @@ def _assert_family_pipeline_available(fam: Any) -> None:
"""Refuse a family whose pipeline class the installed diffusers does not carry.
``pyproject`` deliberately leaves the diffusers floor conditional -- diffusers dropped Python
- 3.9 in 0.37 and this project still supports 3.9 (``requires-python >= 3.9``), so the pin reads
- ``diffusers>=0.39.0 ; python_version >= '3.10'`` and an unconstrained ``diffusers`` below that.
- A supported install can therefore legitimately predate a family's pipeline class:
- ``Krea2Pipeline`` arrived in 0.39.0 and ``Flux2KleinPipeline`` in 0.37.0, while the newest
- diffusers a 3.9 host can resolve is 0.36.0, and an already-present older one satisfies the
- unconstrained pin outright (``ZImagePipeline`` and ``Flux2Pipeline`` only arrived in 0.36.0).
-
- The inference paths already assert this before a load (``diffusion.py`` and ``video.py``); the
- training preflight did not, so the family resolved as trainable, ``/diffusion/start`` reserved
- the training slot and freed the resident GPU workloads, and only the spawned child discovered
- the pipeline was missing when it ran its own ``from diffusers import <Pipeline>``. Losing a
- loaded model and THEN failing is the worst ordering available, so assert here, while
- ``resolve_trainable_family`` still runs ahead of every teardown.
-
- Not strict: an unimportable diffusers is left to ``training_pipeline_import_error`` below.
- ``resolve_trainable_family`` runs from ``normalized()``, which is pure config validation and is
- called in plenty of places that never train, so making it depend on a working diffusers import
- would refuse configs over an unrelated environment problem.
-
- Family-agnostic on purpose: it reads the probe class off whatever spec it is handed, so the
- image registry and the separate video registry share one gate rather than one each. The class
- comes from ``family_probe_class`` rather than ``fam.pipeline_class`` for the reason that
- helper documents: a modular family's ``pipeline_class`` is the generic ``ModularPipeline``,
- which an older diffusers exports regardless, so probing it accepted a MiniMax-H3 start that
- the listing had already hidden and the child could only fail -- after the teardown."""
+ 3.9 in 0.37 and this project still supports 3.9, so the pin reads ``diffusers>=0.39.0 ;
+ python_version >= '3.10'`` and an unconstrained ``diffusers`` below that. A supported install
+ can therefore legitimately predate a family's pipeline class: ``Krea2Pipeline`` arrived in
+ 0.39.0 and ``Flux2KleinPipeline`` in 0.37.0, while the newest diffusers a 3.9 host can resolve
+ is 0.36.0, and an already-present older one satisfies the unconstrained pin outright.
+
+ The inference paths already assert this before a load; the training preflight did not, so
+ ``/diffusion/start`` reserved the slot and freed the resident GPU workloads, and only the
+ spawned child discovered the pipeline was missing. Losing a loaded model and THEN failing is the
+ worst ordering available, so assert here, while ``resolve_trainable_family`` still runs ahead of
+ every teardown.
+
+ Not strict: an unimportable diffusers is left to ``training_pipeline_import_error``, since
+ ``resolve_trainable_family`` runs from ``normalized()``, pure config validation called in plenty
+ of places that never train.
+
+ Family-agnostic on purpose, so the image and video registries share one gate. The class comes
+ from ``family_probe_class`` rather than ``fam.pipeline_class``: a modular family's
+ ``pipeline_class`` is the generic ``ModularPipeline``, which an older diffusers exports
+ regardless, so probing it accepted a MiniMax-H3 start the listing had already hidden.
+ """
from core.inference.diffusion_families import (
assert_pipeline_class_available,
family_probe_class,
@@ -265,24 +248,23 @@ def _assert_family_pipeline_available(fam: Any) -> None:
def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
"""The reason this host cannot import ``resolved_family``'s pipeline class, or None.
- The strict half of the gate above, and it belongs to the ROUTE rather than to config
- validation. ``assert_pipeline_class_available`` deliberately absorbs an unimportable diffusers
- for inference -- the native sd.cpp engine serves GGUF picks on a CPU or Apple host that has
- none. Training has no such fallback: its child is an ``mp.get_context("spawn")`` process in the
- SAME interpreter, so a diffusers that cannot be imported here cannot be imported there either.
- Staying silent bought nothing but the ordering this whole preflight exists to prevent: the slot
- reserved, the resident GPU models freed, and only then the child failing on its own
- ``from diffusers import <Pipeline>``.
+ The strict half of the gate above, and it belongs to the ROUTE rather than to config validation.
+ ``assert_pipeline_class_available`` deliberately absorbs an unimportable diffusers for inference
+ -- the native sd.cpp engine serves GGUF picks on a CPU or Apple host that has none. Training has
+ no such fallback: its child is an ``mp.get_context("spawn")`` process in the SAME interpreter,
+ so a diffusers that cannot be imported here cannot be imported there either, and staying silent
+ bought only the ordering this preflight exists to prevent.
Returns the message instead of raising, matching ``training_precision_preflight_error``, so the
- route maps it to its own 400."""
+ route maps it to its own 400.
+ """
from core.inference.diffusion_families import (
assert_pipeline_class_available,
family_probe_class,
)
- # A video family is invisible to detect_family, and returning None would hand the strict half of the
- # gate to the spawned child, after the teardown.
+ # A video family is invisible to detect_family, and returning None would hand the strict half of the gate to the
+ # spawned child, after the teardown.
fam = _trainable_family_spec(resolved_family)
if fam is None:
return None
@@ -295,27 +277,20 @@ def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
def resolve_trainable_family(base_model: str, model_family: Optional[str] = None) -> str:
"""Resolve the trainer family for a base model, or raise ValueError with a clear reason.
-
- Positive resolution, before anything is downloaded:
- - a ``.gguf`` name can never be a training base -> reject;
- - an explicit ``model_family`` must name a registry family, and that family must be
- trainable;
- - otherwise the family is detected from the base-model name; a KNOWN but non-trainable
- family (e.g. a DiT family before its trainer ships) is rejected;
- - a name that resolves to no registry family but matches a known non-trainable
- architecture (SD3 / PixArt / ...) is rejected;
- - a resolved family whose pipeline class the installed diffusers lacks is rejected
- (``_assert_family_pipeline_available``), so an environment too old for the pick fails
- here rather than in the child, after the GPU residents are gone;
- - an unclassifiable custom name/path falls through to the SDXL trainer (backwards
- compatible: a genuinely wrong pick still fails cleanly later in from_pretrained).
- No pipeline assert on that path: there is no family spec to read a class off, and the
- family it lands on is SDXL, whose pipeline predates every diffusers in play.
- """
+ Positive resolution, before anything is downloaded: a ``.gguf`` name can never be a training
+ base; an explicit ``model_family`` must name a registry family, and that family must be
+ trainable; otherwise the family is detected from the base-model name, and a KNOWN but
+ non-trainable family is rejected; a name resolving to no registry family but matching a known
+ non-trainable architecture (SD3 / PixArt / ...) is rejected; a resolved family whose pipeline
+ class the installed diffusers lacks is rejected, so an environment too old for the pick fails
+ here rather than in the child, after the GPU residents are gone; and an unclassifiable custom
+ name/path falls through to the SDXL trainer (backwards compatible -- a wrong pick still fails
+ cleanly later in from_pretrained). No pipeline assert on that last path: there is no family
+ spec to read a class off, and SDXL's pipeline predates every diffusers in play."""
name = str(base_model or "").strip().lower()
- # GGUF weights (a ``.gguf`` file or ``*-GGUF`` repo) are inference-only: training needs the full diffusers pipeline.
- # modular_model_index.json counts: a MODULAR_BASE_FAMILIES checkout has that and no
- # model_index.json, so reading only the conventional name refused the one local form the family has.
+ # GGUF weights (a ``.gguf`` file or ``*-GGUF`` repo) are inference-only: training needs the full diffusers
+ # pipeline. modular_model_index.json counts: a MODULAR_BASE_FAMILIES checkout has that and no model_index.json, so
+ # reading only the conventional name refused the one local form the family has.
local = Path(base_model).expanduser() if base_model else None
is_local_diffusers = bool(
local
@@ -328,11 +303,11 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
f"'{base_model}' is a GGUF checkpoint/repo, which can't be a training base "
f"(training needs the full diffusers model). {_trainable_hint()}"
)
- # A component checkpoint is not a base whatever family the name matches, so this precedes every
- # family branch, including an explicit model_family override.
+ # A component checkpoint is not a base whatever family the name matches, so this precedes every family branch,
+ # including an explicit model_family override.
_refuse_component_only_repo(base_model)
- # Same shape as the component-only refusal: the name resolves to a real, trainable family, but the repo is
- # not something the training loader can open.
+ # Same shape as the component-only refusal: the name resolves to a real, trainable family, but the repo is not
+ # something the training loader can open.
_refuse_ltx23_training_base(base_model)
if model_family and str(model_family).strip():
key = str(model_family).strip().lower()
@@ -387,20 +362,20 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
def repo_is_prequantized(base_model: str) -> bool:
- """Heuristic: a repo whose name marks a bitsandbytes 4-bit build already ships a
- quantized transformer, so it loads as-is for nf4 and cannot serve the dense
- (bf16/int8/fp8/mxfp8) base precisions."""
+ """Heuristic: a repo whose name marks a bitsandbytes 4-bit build already ships a quantized
+ transformer, so it loads as-is for nf4 and cannot serve the dense (bf16/int8/fp8/mxfp8) base
+ precisions."""
name = str(base_model or "").lower()
return "bnb-4bit" in name or "-4bit" in name or "int4" in name or "nf4" in name
def _module_is_torchao_stub(module: Any) -> bool:
- """True iff ``module`` is the Unsloth Windows-ROCm torchao import stub rather than the
- real package. The stub (core/_torchao_stub.py) satisfies find_spec and even lets
- ``from torchao.quantization import quantize_`` succeed -- but the imported symbols are
- no-op stub types, so the quantization never happens. Every stub module carries the
- ``_unsloth_stub`` sentinel, so match on it (comparing against the stub module's own
- sentinel object, not identity of a re-created one)."""
+ """True iff ``module`` is the Unsloth Windows-ROCm torchao import stub rather than the real
+ package. The stub (core/_torchao_stub.py) satisfies find_spec and even lets ``from
+ torchao.quantization import quantize_`` succeed, but the imported symbols are no-op stub
+ types, so the quantization never happens. Every stub module carries the ``_unsloth_stub``
+ sentinel, so match on it (against the stub module's own sentinel object, not identity of a
+ re-created one)."""
if module is None:
return False
sentinel = getattr(module, "_unsloth_stub", None)
@@ -415,13 +390,10 @@ def _module_is_torchao_stub(module: Any) -> bool:
def has_functional_torchao() -> bool:
"""True iff the real torchao quantization API is importable (not the Windows-ROCm stub).
-
- ``_int8_quantize_base`` needs ``Int8WeightOnlyConfig`` + ``quantize_`` from
- ``torchao.quantization`` and has no runtime fallback, so gate both the auto int8 pick
- and the advertised int8 mode on a FUNCTIONAL import: a plain ``find_spec("torchao")``
- is satisfied by the stub, whose quantize_ is a no-op that leaves the transformer dense
- while compile is disabled as if it were int8. Import the exact symbols the int8 path
- uses and reject the stub module. Never raises."""
+ ``_int8_quantize_base`` needs ``Int8WeightOnlyConfig`` + ``quantize_`` and has no runtime
+ fallback, so gate both the auto int8 pick and the advertised int8 mode on a FUNCTIONAL
+ import: a plain ``find_spec("torchao")`` is satisfied by the stub, whose quantize_ leaves the
+ transformer dense while compile is disabled as if it were int8. Never raises."""
try:
import importlib
@@ -435,15 +407,14 @@ def has_functional_torchao() -> bool:
def train_precision_modes() -> tuple[list[str], str]:
- """(supported base_precision modes, recommended pick) for the current machine: nf4
- always works; bf16/auto need a bf16-capable CUDA GPU (Ampere+); int8/fp8/mxfp8 additionally
- need a FUNCTIONAL torchao (their explicit paths import torchao with no fallback, and the
- Windows-ROCm stub only looks installed). fp8 also needs an fp8-capable GPU (sm89+); mxfp8
- (block-scaled fp8 compute) needs the Blackwell tensor cores (sm100+) its cuBLAS kernels
- target. The dense modes all train in bf16 compute, which the DiT trainer requires, so a
- non-bf16 CUDA GPU (T4/V100/RTX 20xx) is offered only nf4 -- otherwise /info would advertise
- a start that evicts resident models and then fails the trainer's bf16 guard. Used by the
- /info endpoint so the UI can gate the precision selector. Never raises."""
+ """(supported base_precision modes, recommended pick) for the current machine: nf4 always works;
+ bf16/auto need a bf16-capable CUDA GPU (Ampere+); int8/fp8/mxfp8 additionally need a
+ FUNCTIONAL torchao (their explicit paths import it with no fallback, and the Windows-ROCm
+ stub only looks installed). fp8 also needs sm89+; mxfp8 needs the Blackwell tensor cores
+ (sm100+) its cuBLAS kernels target. The dense modes all train in bf16 compute, which the DiT
+ trainer requires, so a non-bf16 CUDA GPU (T4/V100/RTX 20xx) is offered only nf4 -- otherwise
+ /info would advertise a start that evicts resident models and then fails the trainer's bf16
+ guard. Never raises."""
modes = ["nf4"]
recommended = "nf4"
try:
@@ -467,8 +438,8 @@ def train_precision_modes() -> tuple[list[str], str]:
def get_trainer(family: str) -> Callable[..., str]:
- """Return the training entrypoint for ``family``. Imports the trainer module lazily so
- this shared module stays free of the heavy trainer imports (and any import cycle)."""
+ """Return the training entrypoint for ``family``. Imports the trainer module lazily so this
+ shared module stays free of the heavy trainer imports (and any import cycle)."""
key = (family or "sdxl").strip().lower()
if key == "sdxl":
from core.training.diffusion_lora_trainer import run_diffusion_lora_training
@@ -476,16 +447,16 @@ def get_trainer(family: str) -> Callable[..., str]:
if key in ("flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"):
from core.training.diffusion_dit_trainer import run_dit_lora_training
return run_dit_lora_training
- # MiniMax-H3 denoises video and audio jointly over one packed sequence on two coupled schedules,
- # which is outside the DiT trainer's _FamilySpec seams.
+ # MiniMax-H3 denoises video and audio jointly over one packed sequence on two coupled schedules, which is outside
+ # the DiT trainer's _FamilySpec seams.
if key == "minimax-h3":
from core.training.diffusion_h3_trainer import run_h3_lora_training
return run_h3_lora_training
raise ValueError(f"No trainer is registered for family {family!r}.")
-# Per-family training defaults surfaced by the Train UI: starting points, not hard limits. Families
-# absent here fall back to the DiffusionLoraConfig defaults.
+# Per-family training defaults surfaced by the Train UI: starting points, not hard limits. Families absent here fall
+# back to the DiffusionLoraConfig defaults.
FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"sdxl": {"lora_rank": 16, "learning_rate": 1e-4, "resolution": 1024},
# Plain "constant" ignores lr_warmup_steps, so warmup defaults must use a warmup-capable scheduler.
@@ -506,8 +477,8 @@ FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"z-image": {"lora_rank": 16, "learning_rate": 1e-4, "resolution": 768},
# The Krea 2 authors' recommended starting point (their DreamBooth defaults): rank/alpha 32, lr 3e-4, 512px.
"krea-2": {"lora_rank": 32, "learning_rate": 3e-4, "resolution": 512},
- # Upstream FLUX.2 DreamBooth references default to rank 16 / lr 1e-4; its uniform timestep draw
- # benefits most from a warmup ramp.
+ # Upstream FLUX.2 DreamBooth references default to rank 16 / lr 1e-4; its uniform timestep draw benefits most from
+ # a warmup ramp.
"flux.2-klein": {
"lora_rank": 16,
"learning_rate": 1e-4,
@@ -522,8 +493,8 @@ FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"lr_scheduler": "constant_with_warmup",
"lr_warmup_steps": 20,
},
- # From Lightricks' own ltx-trainer LoRA configs; the resolution must be a multiple of 32, its
- # VAE's spatial compression, and 512 keeps a still at 16x16x1 latents / 256 video tokens.
+ # From Lightricks' own ltx-trainer LoRA configs; the resolution must be a multiple of 32, its VAE's spatial
+ # compression, and 512 keeps a still at 16x16x1 latents / 256 video tokens.
"ltx-2": {
"lora_rank": 32,
"learning_rate": 1e-4,
@@ -531,8 +502,8 @@ FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"lr_scheduler": "constant_with_warmup",
"lr_warmup_steps": 20,
},
- # resolution is the canvas SHORT EDGE and 768 is what the released checkpoint generates on;
- # rank 16 not 32 because the adapter also serves the audio rows through one shared stack.
+ # resolution is the canvas SHORT EDGE and 768 is what the released checkpoint generates on; rank 16 not 32 because
+ # the adapter also serves the audio rows through one shared stack.
"minimax-h3": {
"lora_rank": 16,
"learning_rate": 1e-4,
@@ -549,8 +520,8 @@ def train_defaults(family: str) -> dict[str, Any]:
return dict(FAMILY_TRAIN_DEFAULTS.get((family or "").strip().lower(), {}))
-# Display labels + a short VRAM/access note per trainable family, surfaced by the Train UI so users pick a base
-# with realistic expectations.
+# Display labels + a short VRAM/access note per trainable family, surfaced by the Train UI so users pick a base with
+# realistic expectations.
_FAMILY_LABELS = {
"sdxl": "SDXL",
"flux.1": "FLUX.1-dev",
@@ -581,16 +552,16 @@ _FAMILY_TRAIN_SPECS: dict[str, dict[str, Any]] = {
},
"flux.2-klein": {"params": "4B", "qlora_vram_gb": 10, "gated": False, "note": ""},
"flux.2-dev": {"params": "32B", "qlora_vram_gb": 28, "gated": True, "note": ""},
- # Measured on a B200: the training LOOP peaks at 11.2 GB, but the RUN peaks at 34.8 GB while the
- # Gemma3-12B conditioning stack is resident, and the quoted figure covers the whole run.
+ # Measured on a B200: the training LOOP peaks at 11.2 GB, but the RUN peaks at 34.8 GB while the Gemma3-12B
+ # conditioning stack is resident, and the quoted figure covers the whole run.
"ltx-2": {
"params": "19B",
"qlora_vram_gb": 36,
"gated": False,
"note": "Video: trains a style LoRA on still images.",
},
- # Measured on a B200: the loop peaks near 44 GB, but a 20-step run peaked at 77.76 GB with the
- # 63 GiB Qwen3-VL conditioner resident, so 72 sizes users onto a card that OOMs later.
+ # Measured on a B200: the loop peaks near 44 GB, but a 20-step run peaked at 77.76 GB with the 63 GiB Qwen3-VL
+ # conditioner resident, so 72 sizes users onto a card that OOMs later.
"minimax-h3": {
"params": "31B",
"qlora_vram_gb": 80,
@@ -598,13 +569,13 @@ _FAMILY_TRAIN_SPECS: dict[str, dict[str, Any]] = {
"note": "Video with sound: trains on clips that have a soundtrack.",
},
}
-# Keys are canonical upstream ids; family_train_infos also publishes the mirror aliases, and values
-# overlay the family facts in the client.
+# Keys are canonical upstream ids; family_train_infos also publishes the mirror aliases, and values overlay the family
+# facts in the client.
_BASE_TRAIN_SPECS: dict[str, dict[str, Any]] = {
"black-forest-labs/flux.2-klein-base-9b": {
"params": "9B",
- # The bf16 text encoder alone measures 16.4 GB, so leave room for the VAE and runtime state rather
- # than inheriting the 4B checkpoint's floor.
+ # The bf16 text encoder alone measures 16.4 GB, so leave room for the VAE and runtime state rather than
+ # inheriting the 4B checkpoint's floor.
"qlora_vram_gb": 18,
},
}
@@ -622,8 +593,8 @@ def _family_vram_note(name: str) -> str:
return " ".join([head, *tail])
-# The flow-matching DiT families (run by diffusion_dit_trainer): they expose base_precision /
-# compile and need bf16 on CUDA. SDXL is absent (own mixed_precision path).
+# The flow-matching DiT families (run by diffusion_dit_trainer): they expose base_precision / compile and need bf16 on
+# CUDA. SDXL is absent (own mixed_precision path).
_DIT_TRAIN_FAMILIES = frozenset(
{"flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"}
)
@@ -632,21 +603,19 @@ _FLOW_TRAIN_FAMILIES = _DIT_TRAIN_FAMILIES | {"minimax-h3"}
def effective_mixed_precision(cfg: Any) -> str:
- """The precision the SDXL trainer will actually run in, resolved the same way it resolves it.
-
- A pre-Ampere card has no native bf16, so a bf16 request silently becomes fp16 there. Recording
+ """The precision the SDXL trainer will actually run in, resolved the same way it resolves it. A
+ pre-Ampere card has no native bf16, so a bf16 request silently becomes fp16 there. Recording
the REQUEST in a checkpoint's identity let a bundle written in fp16 resume in bf16 on a newer
card (and the reverse), continuing restored optimizer moments under different frozen-base
numerics while reporting a clean resume. Shared so the start route and the trainer cannot
- disagree about what a checkpoint was trained as.
- """
+ disagree about what a checkpoint was trained as."""
import torch # noqa: PLC0415 -- keep the import list light for the training subprocess
requested = str(getattr(cfg, "mixed_precision", "") or "")
if str(getattr(cfg, "resolved_family", "") or "").strip().lower() in _FLOW_TRAIN_FAMILIES:
- # No flow-matching trainer reads mixed_precision (weight_dtype is bf16 on CUDA, fp32 otherwise),
- # so recording the REQUEST failed a later bf16 resume as a precision mismatch between identical
- # runs. Keyed on _FLOW_TRAIN_FAMILIES so the answer follows the weight dtype.
+ # No flow-matching trainer reads mixed_precision (weight_dtype is bf16 on CUDA, fp32 otherwise), so recording
+ # the REQUEST failed a later bf16 resume as a precision mismatch between identical runs. Keyed on
+ # _FLOW_TRAIN_FAMILIES so the answer follows the weight dtype.
return "bf16" if torch.cuda.is_available() else "no"
if not torch.cuda.is_available():
return "no"
@@ -657,14 +626,11 @@ def effective_mixed_precision(cfg: Any) -> str:
def native_bf16_supported() -> bool:
"""True only when the live CUDA GPU provides NATIVE bf16 compute, not pre-Ampere emulation.
-
``torch.cuda.is_bf16_supported()`` defaults to counting EMULATED bf16, which every pre-Ampere
CUDA card (T4 / V100 / RTX 20xx) reports as supported even though the DiT trainer needs real
- Ampere-or-newer bf16. Gate NVIDIA on compute capability major >= 8 instead -- the same #6658
- fix the inference device resolver (``diffusion_device.py``) already uses; ROCm has no such
- quirk, so ``is_bf16_supported()`` is trustworthy there. Never raises -- a probe failure or a
- no-CUDA host returns False. Shared by the /info modes, the start preflight, and the trainer
- guard so all three stay in sync."""
+ Ampere-or-newer bf16. Gate NVIDIA on compute capability major >= 8 instead, the same #6658
+ fix the inference device resolver already uses; ROCm has no such quirk. Never raises. Shared
+ by the /info modes, the start preflight, and the trainer guard so all three stay in sync."""
try:
import torch
@@ -679,15 +645,13 @@ def native_bf16_supported() -> bool:
def bf16_unsupported_reason(resolved_family: str) -> Optional[str]:
- """Return a user-facing error string if ``resolved_family`` needs bf16 compute that the
- live GPU cannot provide, else None. The DiT trainer requires a bf16-capable GPU (Ampere
- or newer) and otherwise raises deep in model load; the start route uses this to fail fast
- BEFORE evicting resident GPU workloads. CPU-only hosts (which fall back to fp32 for
- import/unit tests) and SDXL (its own mixed_precision path) are exempt. Never raises.
-
- Covers every FLOW-matching trainer, not just the DiT one: MiniMax-H3 has the same bf16
- requirement (its checkpoint keeps the patch projections and output heads in fp32) and the
- same eviction ordering to protect."""
+ """Return a user-facing error string if ``resolved_family`` needs bf16 compute the live GPU
+ cannot provide, else None. The DiT trainer requires Ampere or newer and otherwise raises deep
+ in model load; the start route uses this to fail fast BEFORE evicting resident GPU workloads.
+ CPU-only hosts and SDXL (its own mixed_precision path) are exempt. Never raises. Covers every
+ FLOW-matching trainer, not just the DiT one: MiniMax-H3 has the same bf16 requirement (its
+ checkpoint keeps the patch projections and output heads in fp32) and the same eviction
+ ordering to protect."""
if (resolved_family or "").strip().lower() not in _FLOW_TRAIN_FAMILIES:
return None
try:
@@ -703,24 +667,20 @@ def bf16_unsupported_reason(resolved_family: str) -> Optional[str]:
def dit_accelerator_missing_reason(resolved_family: str) -> Optional[str]:
- """Reason a DiT family cannot train on this host at all, else None. Never raises.
-
- nf4 is not a CPU fallback: the 4-bit base load goes through diffusers' bitsandbytes
- quantizer, whose validate_environment raises "No GPU found. A GPU is needed for
- quantization." unless CUDA, XPU or MPS is present. Without this gate a GPU-less host
- accepts the default nf4 start, evicts the resident Images pipeline, downloads the text
- encoders, and only then dies in the child. SDXL keeps its own fp32-on-CPU path.
-
- Covers MiniMax-H3 too, for the same reason: it loads its denoiser through the same 4-bit
- quantizer.
- """
+ """Reason a DiT family cannot train on this host at all, else None. Never raises. nf4 is not a
+ CPU fallback: the 4-bit base load goes through diffusers' bitsandbytes quantizer, whose
+ validate_environment raises "No GPU found. A GPU is needed for quantization." unless CUDA,
+ XPU or MPS is present. Without this gate a GPU-less host accepts the default nf4 start,
+ evicts the resident Images pipeline, downloads the text encoders, and only then dies in the
+ child. SDXL keeps its own fp32-on-CPU path; MiniMax-H3 is covered too, since it loads its
+ denoiser through the same quantizer."""
if (resolved_family or "").strip().lower() not in _FLOW_TRAIN_FAMILIES:
return None
try:
import torch
def probe(owner: Any) -> bool:
- # Each accelerator is probed on its own: torch.mps.is_available() only exists from torch 2.5 while
- # the floor is 2.4, so a shared try/except would wave a CPU-only host through.
+ # Each accelerator is probed on its own: torch.mps.is_available() only exists from torch 2.5 while the
+ # floor is 2.4, so a shared try/except would wave a CPU-only host through.
try:
fn = getattr(owner, "is_available", None)
return bool(fn()) if callable(fn) else False
@@ -743,16 +703,14 @@ def dit_accelerator_missing_reason(resolved_family: str) -> Optional[str]:
def training_precision_preflight_error(resolved_family: str, base_precision: str) -> Optional[str]:
- """Reason the requested DiT precision cannot run on this host, else None -- checked by the
- start route BEFORE evicting resident GPU workloads (the trainer's own checks fire only in the
+ """Reason the requested DiT precision cannot run on this host, else None -- checked by the start
+ route BEFORE evicting resident GPU workloads (the trainer's own checks fire only in the
child, after eviction). Every gate mirrors one in _resolve_base_precision, so a doomed run is
- rejected before teardown: the bf16-GPU requirement (bf16_unsupported_reason); no accelerator at
- all (dit_accelerator_missing_reason, which covers nf4 too); the dense precisions
- (bf16/int8/fp8/mxfp8) needing CUDA; the torchao precisions (int8/fp8/mxfp8) against a ROCm
- build, which clears the stub test and hands the sm100 floor an AMD gfx version; explicit int8
- needing a FUNCTIONAL torchao (its _int8_quantize_base has no fallback); explicit fp8/mxfp8
- against the Windows-ROCm torchao stub; explicit mxfp8 needing Blackwell (sm100+). Add a gate
- there, add it here. Never raises."""
+ rejected before teardown: the bf16-GPU requirement; no accelerator at all (which covers nf4
+ too); the dense precisions needing CUDA; the torchao precisions against a ROCm build, which
+ clears the stub test and hands the sm100 floor an AMD gfx version; explicit int8 needing a
+ FUNCTIONAL torchao; explicit fp8/mxfp8 against the Windows-ROCm stub; explicit mxfp8 needing
+ Blackwell. Add a gate there, add it here. Never raises."""
reason = bf16_unsupported_reason(resolved_family)
if reason:
return reason
@@ -763,8 +721,8 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
fam = (resolved_family or "").strip().lower()
mode = (base_precision or "").strip().lower()
if fam in _FLOW_TRAIN_FAMILIES and mode in ("bf16", "int8", "fp8", "mxfp8"):
- # The DiT trainer's dense precisions all require CUDA, and bf16_unsupported_reason exempts a CPU-
- # only host, so without this a dense request would evict residents then raise in the child.
+ # The DiT trainer's dense precisions all require CUDA, and bf16_unsupported_reason exempts a CPU-only host, so
+ # without this a dense request would evict residents then raise in the child.
try:
import torch
has_cuda = torch.cuda.is_available()
@@ -793,8 +751,8 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
f"base_precision={mode!r} is not available on this host: torchao is the "
"non-functional Windows-ROCm stub. Use 'nf4', 'bf16', or 'auto'."
)
- # mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, AFTER a full dense
- # load. Re-check here so a stale client fails fast before eviction.
+ # mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, AFTER a full dense load.
+ # Re-check here so a stale client fails fast before eviction.
if mode == "mxfp8":
try:
import torch
@@ -810,15 +768,13 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
def family_train_infos() -> list[dict[str, Any]]:
- """Describe every trainable family for the Train UI: name, label, the default + allowed
- base repos, the recommended starting hyperparameters, and a VRAM/access note. Built from
- the family registry so it stays in sync with what the trainers actually support.
-
- Both registries: a video family with a trainer is as trainable as an image one, and reading
- only the image registry is what kept ``ltx-2`` out of the Train tab entirely -- the trainer,
- the preflight and the start route all accepted it, but nothing ever offered it. A family whose
- pipeline class the installed diffusers lacks is dropped rather than advertised, since the start
- route refuses it (``training_pipeline_import_error``) and no choice in the UI can fix that."""
+ """Describe every trainable family for the Train UI: name, label, the default + allowed base
+ repos, the recommended starting hyperparameters, and a VRAM/access note. Built from the
+ family registry so it stays in sync with what the trainers support. Both registries: a video
+ family with a trainer is as trainable as an image one, and reading only the image registry is
+ what kept ``ltx-2`` out of the Train tab entirely. A family whose pipeline class the
+ installed diffusers lacks is dropped rather than advertised, since the start route refuses it
+ and no choice in the UI can fix that."""
from core.inference.diffusion_families import family_pipeline_available, mirror_repo
from core.inference.diffusion_transformer_quant import _family_train_denied
@@ -831,18 +787,18 @@ def family_train_infos() -> list[dict[str, Any]]:
# A video family carries no train_base_repos/deploy_base_repo: its own base repo is the one training base.
repos = list(getattr(fam, "train_base_repos", ()) or ()) or [fam.base_repo]
# base_precision applies to every flow-matching trainer, not only the shared DiT one: reading
- # _DIT_TRAIN_FAMILIES here reported precision_modes = [] for H3, which the Train panel shows as
- # "Not supported on this GPU".
+ # _DIT_TRAIN_FAMILIES here reported precision_modes = [] for H3, which the Train panel shows as "Not supported
+ # on this GPU".
is_dit = name in _FLOW_TRAIN_FAMILIES
- # On a non-bf16 CUDA GPU the start preflight rejects EVERY DiT family, so advertise no precision
- # rather than an option that always 400s; also drop schemes the TRAINING bar holds back.
+ # On a non-bf16 CUDA GPU the start preflight rejects EVERY DiT family, so advertise no precision rather than
+ # an option that always 400s; also drop schemes the TRAINING bar holds back.
dit_block = (
bf16_unsupported_reason(name) or dit_accelerator_missing_reason(name)
if is_dit
else None
)
- # H3 refuses compile_transformer="on" (its packed sequence changes length with every caption, so
- # each step would re-trace), so advertising the control would offer a selection that always 400s.
+ # H3 refuses compile_transformer="on" (its packed sequence changes length with every caption, so each step
+ # would re-trace), so advertising the control would offer a selection that always 400s.
supports_compile = bool(not dit_block) and name in _DIT_TRAIN_FAMILIES
if not is_dit or dit_block:
fam_modes: list[str] = []
@@ -861,8 +817,8 @@ def family_train_infos() -> list[dict[str, Any]]:
base_specs[repo_mirror] = dict(base_spec)
for training_repo, inference_repo in getattr(fam, "deploy_base_repos", ()):
deploy_bases[training_repo] = inference_repo
- # A custom base entered with the public mirror id must follow the same pairing as the advertised
- # vendor id; return the inference mirror too so Deploy stays ungated.
+ # A custom base entered with the public mirror id must follow the same pairing as the advertised vendor
+ # id; return the inference mirror too so Deploy stays ungated.
training_mirror = mirror_repo(training_repo)
if training_mirror:
deploy_bases[training_mirror] = mirror_repo(inference_repo) or inference_repo
@@ -881,22 +837,22 @@ def family_train_infos() -> list[dict[str, Any]]:
"note": "" if dit_block else spec.get("note", ""),
"precision_modes": fam_modes,
"recommended_precision": "nf4" if (not is_dit or dit_block) else dit_recommended,
- # compile is offered for SDXL's regional U-Net and the shared DiT trainer, except a family the
- # GPU cannot train in bf16, and except a trainer that cannot compile.
+ # compile is offered for SDXL's regional U-Net and the shared DiT trainer, except a family the GPU
+ # cannot train in bf16, and except a trainer that cannot compile.
"supports_compile": supports_compile or name == "sdxl",
# save_steps is REFUSED for a checkpointless family, not ignored, so a panel that keeps offering
# "Checkpoint every" turns a nonzero value into a rejected Start with no way to see why.
"supports_checkpoints": name not in CHECKPOINTLESS_FAMILIES,
- # A batch > 1 is REFUSED for a family whose forward covers one packed sequence, so leaving the
- # control unrestricted turns a reasonable 2 into a rejected Start with nothing to say why.
+ # A batch > 1 is REFUSED for a family whose forward covers one packed sequence, so leaving the control
+ # unrestricted turns a reasonable 2 into a rejected Start with nothing to say why.
"max_train_batch_size": 1 if name in SINGLE_SEQUENCE_FAMILIES else None,
# Krea trains on Raw but previews adapters on Turbo; None elsewhere (and never for a video family).
"deploy_base": getattr(fam, "deploy_base_repo", None),
# Families with several train/deploy pairs cannot use the scalar above.
"deploy_bases": deploy_bases,
- # Dropped on a dit_block for the same reason as the family chips: the overlay wins and
- # FamilyFacts renders vram_note only when there are no chips, so keeping these would replace the
- # actionable hardware reason with a size the host cannot act on.
+ # Dropped on a dit_block for the same reason as the family chips: the overlay wins and FamilyFacts
+ # renders vram_note only when there are no chips, so keeping these would replace the actionable
+ # hardware reason with a size the host cannot act on.
"base_specs": {} if dit_block else base_specs,
}
)
@@ -905,20 +861,18 @@ def family_train_infos() -> list[dict[str, Any]]:
@dataclass
class DiffusionLoraConfig:
- """Everything a diffusion LoRA training run needs. Only ``base_model`` /
- ``data_dir`` / ``output_dir`` are required; the rest have sensible defaults."""
+ """Everything a diffusion LoRA training run needs. Only ``base_model`` / ``data_dir`` /
+ ``output_dir`` are required; the rest have sensible defaults."""
base_model: str
data_dir: str
output_dir: str
- # Dreambooth-style caption applied to any image without its own. Required if the dataset has no
- # captions.jsonl / sidecars.
+ # Dreambooth-style caption applied to any image without its own. Required if the dataset has no captions.jsonl /
+ # sidecars.
instance_prompt: Optional[str] = None
resolution: int = 1024
train_steps: int = 500
- # 0 = disabled (train for train_steps). Above 0 it overrides train_steps with num_epochs full passes
- # LoRA EMA decay (DiT trainer only). 0.0 disables; a positive value keeps a warmup-ramped EMA of
- # the trainable params and exports it under ema/.
+ # 0 = disabled (train for train_steps). Above 0 it overrides train_steps with num_epochs full passes.
num_epochs: int = 0
learning_rate: float = 1e-4
train_batch_size: int = 1
@@ -939,20 +893,20 @@ class DiffusionLoraConfig:
caption_column: str = "text"
adapter_name: str = "default"
hf_token: Optional[str] = None
- # Derived by normalized(): the byte-identical mirror used by from_pretrained, while base_model stays
- # the canonical id in metadata and resume identity.
+ # Derived by normalized(): the byte-identical mirror used by from_pretrained, while base_model stays the canonical
+ # id in metadata and resume identity.
fetch_base_model: Optional[str] = None
# cache_variants crop/flip draws are frozen per image; the per-step VAE sampling noise is preserved.
cache_latents: bool = True
cache_variants: int = 4
- # A directory persists latent stats and caption embeddings keyed by content hash, so a warm cache
- # skips the VAE and text encoders.
+ # A directory persists latent stats and caption embeddings keyed by content hash, so a warm cache skips the VAE
+ # and text encoders.
cond_cache_dir: Optional[str] = None
- # LoRA EMA decay (DiT trainer only). 0.0 disables; a positive value keeps a warmup-ramped EMA of
- # the trainable params and exports it under ema/.
+ # LoRA EMA decay (DiT trainer only). 0.0 disables; a positive value keeps a warmup-ramped EMA of the trainable
+ # params and exports it under ema/.
ema_decay: float = 0.0
- # Regional torch.compile of the transformer blocks: "off" | "on" | "auto" (auto turns it on only for
- # a dense, non-bitsandbytes base where it is a clean win).
+ # Regional torch.compile of the transformer blocks: "off" | "on" | "auto" (auto turns it on only for a dense,
+ # non-bitsandbytes base where it is a clean win).
compile_transformer: str = "auto"
# TF32 matmuls + cudnn autotuning for the run. Near-lossless; disable for strict bit-reproducibility A/Bs.
enable_tf32: bool = True
@@ -960,36 +914,35 @@ class DiffusionLoraConfig:
# eager), "int8" (torchao weight-only), "fp8" (Ada/Hopper/Blackwell + compile) or "auto". Non-nf4 needs a dense
# base.
base_precision: str = "nf4"
- # None resolves per family in normalized(); a number applies s*u/(1+(s-1)*u), and "auto" without
- # dynamic shifting falls back to identity.
+ # None resolves per family in normalized(); a number applies s*u/(1+(s-1)*u), and "auto" without dynamic shifting
+ # falls back to identity.
flow_shift: Optional[Any] = None
- # Per-sample probability of replacing the caption with the empty prompt (classifier-free-guidance dropout).
- # 0.0 disables.
+ # Per-sample probability of replacing the caption with the empty prompt (classifier-free-guidance dropout). 0.0
+ # disables.
cfg_dropout: float = 0.0
- # Per-sample loss weighting over the drawn timestep: "none" (unweighted MSE) or "bell" (Gaussian, normalized
- # to mean 1).
+ # Per-sample loss weighting over the drawn timestep: "none" (unweighted MSE) or "bell" (Gaussian, normalized to
+ # mean 1).
weighting_scheme: str = "none"
# How often to emit a progress event (in optimizer steps).
log_every: int = 1
- # 0 writes no periodic checkpoints; a stop-and-save always writes one regardless, so the Resume
- # action stays available.
+ # 0 writes no periodic checkpoints; a stop-and-save always writes one regardless, so the Resume action stays
+ # available.
save_steps: int = 0
# How many checkpoint-<N> bundles to keep in the output dir; 0 keeps every one.
save_total_limit: int = 2
- # The run's output_dir, or one of its checkpoint-<N> directories; the start route resolves and
- # validates it before the trainer spawns.
+ # The run's output_dir, or one of its checkpoint-<N> directories; the start route resolves and validates it before
+ # the trainer spawns.
resume_from_checkpoint: Optional[str] = None
- # Optional explicit family override; None = detect from base_model. ``resolved_family`` is filled by
- # normalized() with the trainer family that will run.
+ # Optional explicit family override; None = detect from base_model. ``resolved_family`` is filled by normalized()
+ # with the trainer family that will run.
model_family: Optional[str] = None
resolved_family: str = "sdxl"
def normalized(self) -> "DiffusionLoraConfig":
- """Return a copy with derived/validated fields filled in. Raises ValueError on a
- request that cannot train (bad numbers, or an untrainable base model).
-
- Also coerces values that arrive as strings/blanks through the Unsloth config path
- (``learning_rate`` is preserved as a string there; ``hf_token`` defaults to "")."""
+ """Return a copy with derived/validated fields filled in. Raises ValueError on a request
+ that cannot train (bad numbers, or an untrainable base model). Also coerces values that
+ arrive as strings/blanks through the Unsloth config path (``learning_rate`` is preserved
+ as a string there; ``hf_token`` defaults to "")."""
resolved_family = resolve_trainable_family(self.base_model, self.model_family)
if self.train_steps < 1:
raise ValueError("train_steps must be >= 1")
@@ -1007,8 +960,8 @@ class DiffusionLoraConfig:
)
if self.resolution < 64 or self.resolution % 8 != 0:
raise ValueError("resolution must be a multiple of 8 and >= 64")
- # A video family's VAE compresses space by 32, so an off-grid resolution changes the latent geometry
- # silently. Refuse it before the GPU models are evicted.
+ # A video family's VAE compresses space by 32, so an off-grid resolution changes the latent geometry silently.
+ # Refuse it before the GPU models are evicted.
if (
resolved_family in TRAINABLE_VIDEO_FAMILIES
and self.resolution % _VIDEO_RESOLUTION_MULTIPLE != 0
@@ -1020,8 +973,8 @@ class DiffusionLoraConfig:
)
if self.mixed_precision not in ("bf16", "fp16", "no"):
raise ValueError("mixed_precision must be one of bf16 / fp16 / no")
- # torch.manual_seed unpacks int64/uint64, so anything wider raises inside the trainer, after
- # eviction. Catch it here.
+ # torch.manual_seed unpacks int64/uint64, so anything wider raises inside the trainer, after eviction. Catch
+ # it here.
if not -(2**63) <= int(self.seed) <= 2**64 - 1:
raise ValueError("seed must fit in torch's 64-bit range")
# Refuse fp16 for a bf16-only DiT family up front, before evicting resident models.
@@ -1035,8 +988,8 @@ class DiffusionLoraConfig:
f"lr_scheduler must be one of {', '.join(sorted(_LR_SCHEDULERS))}; "
f"got {self.lr_scheduler!r}"
)
- # Do not rewrite the scheduler: it is part of checkpoint identity, so legacy runs with ("constant",
- # warmup > 0) would become unresumable.
+ # Do not rewrite the scheduler: it is part of checkpoint identity, so legacy runs with ("constant", warmup >
+ # 0) would become unresumable.
try:
lr_warmup_steps = int(self.lr_warmup_steps or 0)
except (TypeError, ValueError) as exc:
@@ -1059,15 +1012,15 @@ class DiffusionLoraConfig:
raise ValueError("save_steps must be >= 0 (0 disables periodic checkpoints)")
if save_total_limit < 0:
raise ValueError("save_total_limit must be >= 0 (0 keeps every checkpoint)")
- # A blank resume path (the Unsloth default when the field is present but unset) means "fresh run",
- # not the outputs root.
+ # A blank resume path (the Unsloth default when the field is present but unset) means "fresh run", not the
+ # outputs root.
resume_from_checkpoint = (
str(self.resume_from_checkpoint).strip()
if self.resume_from_checkpoint is not None
else ""
) or None
- # The H3 loop neither writes a resume bundle nor restores one, and accepting these silently gave a
- # resume request a FRESH optimization that then overwrote the outputs it was meant to continue.
+ # The H3 loop neither writes a resume bundle nor restores one, and accepting these silently gave a resume
+ # request a FRESH optimization that then overwrote the outputs it was meant to continue.
if resolved_family in CHECKPOINTLESS_FAMILIES:
if resume_from_checkpoint:
raise ValueError(
@@ -1084,8 +1037,8 @@ class DiffusionLoraConfig:
ema_decay = float(self.ema_decay or 0.0)
except (TypeError, ValueError) as exc:
raise ValueError(f"ema_decay must be a number, got {self.ema_decay!r}") from exc
- # decay = 1.0 would freeze the shadow at its init forever; the update is shadow * decay + param * (1
- # - decay), so valid decays live in [0, 1).
+ # decay = 1.0 would freeze the shadow at its init forever; the update is shadow * decay + param * (1 - decay),
+ # so valid decays live in [0, 1).
if not 0.0 <= ema_decay < 1.0:
raise ValueError("ema_decay must be in [0, 1); 0 disables the EMA adapter")
# A blank cond_cache_dir (the Unsloth default when unset) means "off", not cwd.
@@ -1098,8 +1051,8 @@ class DiffusionLoraConfig:
base_precision = str(self.base_precision or "nf4").strip().lower()
if base_precision not in ("nf4", "bf16", "int8", "fp8", "mxfp8", "auto"):
raise ValueError("base_precision must be one of nf4 / bf16 / int8 / fp8 / mxfp8 / auto")
- # base_precision is a DiT-only lever, so the dense-mode gates apply only to the DiT families. The
- # mode-name check above still runs for every family.
+ # base_precision is a DiT-only lever, so the dense-mode gates apply only to the DiT families. The mode-name
+ # check above still runs for every family.
if resolved_family != "sdxl" and base_precision in ("bf16", "int8", "fp8", "mxfp8"):
if repo_is_prequantized(self.base_model):
raise ValueError(
@@ -1113,9 +1066,9 @@ class DiffusionLoraConfig:
f"mixed_precision to bf16."
)
# qwen-image fp8 renders inside the accuracy gate, but no one has measured whether a LoRA converges
- # against fp8-frozen linears, so training fails fast rather than training on faith.
- # MiniMax-H3 runs all three modalities through one set of linears, so the per-family activation
- # range the fp8 module filter was measured against does not describe it.
+ # against fp8-frozen linears, so training fails fast rather than training on faith. MiniMax-H3 runs all
+ # three modalities through one set of linears, so the per-family activation range the fp8 module filter
+ # was measured against does not describe it.
if resolved_family == "minimax-h3" and base_precision in ("fp8", "mxfp8"):
raise ValueError(
f"base_precision={base_precision!r} is not supported for minimax-h3: its "
@@ -1123,8 +1076,8 @@ class DiffusionLoraConfig:
f"so the activation range fp8 was measured against does not apply. Use "
f"'nf4', 'int8', 'bf16', or 'auto'."
)
- # _family_train_denied is the strict superset of _family_denied, so importing the narrower helper
- # here would let a scheme cleared only for rendering reach a trainer.
+ # _family_train_denied is the strict superset of _family_denied, so importing the narrower helper here
+ # would let a scheme cleared only for rendering reach a trainer.
from core.inference.diffusion_transformer_quant import _family_train_denied
if _family_train_denied(resolved_family, base_precision):
@@ -1148,8 +1101,8 @@ class DiffusionLoraConfig:
) from exc
if not isinstance(flow_shift, str):
flow_shift = float(flow_shift)
- # isfinite as well as positive: JSON accepts 1e309, which floats to inf and would poison every
- # sampled sigma while progress looks normal.
+ # isfinite as well as positive: JSON accepts 1e309, which floats to inf and would poison every sampled
+ # sigma while progress looks normal.
if not math.isfinite(flow_shift) or flow_shift <= 0:
raise ValueError(
"flow_shift must be a finite number > 0 (1.0 disables the shift), or 'auto'"
@@ -1163,11 +1116,12 @@ class DiffusionLoraConfig:
weighting_scheme = str(self.weighting_scheme or "none").strip().lower()
if weighting_scheme not in ("none", "bell"):
raise ValueError("weighting_scheme must be one of none / bell")
- # A zero/negative gamma would zero out (or invert) the min-SNR weight and silently train on a
- # degenerate loss; None is the documented disable.
+ # A zero/negative gamma would zero out (or invert) the min-SNR weight and silently train on a degenerate loss;
+ # None is the documented disable.
if self.snr_gamma is not None and float(self.snr_gamma) <= 0:
raise ValueError("snr_gamma must be > 0, or null to disable min-SNR weighting")
- # learning_rate can arrive as a string ("1e-4") from the Unsloth config path, so coerce it before AdamW sees it.
+ # learning_rate can arrive as a string ("1e-4") from the Unsloth config path, so coerce it before AdamW sees
+ # it.
try:
learning_rate = float(self.learning_rate)
except (TypeError, ValueError) as exc:
@@ -1176,8 +1130,8 @@ class DiffusionLoraConfig:
raise ValueError("learning_rate must be > 0")
alpha = self.lora_alpha if self.lora_alpha is not None else self.lora_rank
targets = tuple(self.lora_target_modules) or DEFAULT_LORA_TARGETS
- # A blank Hub token (the Unsloth default when none is configured) must load anonymously, not as an
- # explicit empty credential.
+ # A blank Hub token (the Unsloth default when none is configured) must load anonymously, not as an explicit
+ # empty credential.
token = self.hf_token.strip() if isinstance(self.hf_token, str) else self.hf_token
from core.inference.diffusion_families import (
_is_local_path,
@@ -1190,13 +1144,12 @@ class DiffusionLoraConfig:
fetch_base_model = self.base_model
else:
fetch_base_model = prefer_ungated_mirror(self.base_model, token or None)
- # For a GATED upstream with no token, override the cache preference: prefer_ungated_mirror's
- # probe counts any cached weight as a hit, so one leftover shard kept the vendor id.
- # Only gated: the rest of the mirror table is reachable anonymously, and an override there would
- # discard a complete local cache and re-pull gigabytes, or fail offline.
- # UNSLOTH_DIFFUSION_NO_MIRROR still wins, exactly as it does inside prefer_ungated_mirror.
- # A local clone wins over both: a base can be a directory named exactly like the vendor id, and
- # rewriting it sends the fetch to the Hub past weights the user already has.
+ # For a GATED upstream with no token, override the cache preference: prefer_ungated_mirror's probe counts
+ # any cached weight as a hit, so one leftover shard kept the vendor id. Only gated: the rest of the mirror
+ # table is reachable anonymously, and an override there would discard a complete local cache and re-pull
+ # gigabytes, or fail offline. UNSLOTH_DIFFUSION_NO_MIRROR still wins, exactly as inside
+ # prefer_ungated_mirror, and a local clone wins over both (a base can be a directory named exactly like
+ # the vendor id).
if (
not token
and upstream_is_gated(self.base_model)
@@ -1204,9 +1157,9 @@ class DiffusionLoraConfig:
and not os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip()
):
fetch_base_model = mirror_repo(self.base_model) or fetch_base_model
- # A blank caption_column means the default, as the start route's preflight assumes: otherwise
- # route and trainer resolve different captions from a metadata.jsonl and their fingerprints
- # disagree, so an accepted resume is refused in the child.
+ # A blank caption_column means the default, as the start route's preflight assumes: otherwise route and
+ # trainer resolve different captions from a metadata.jsonl and their fingerprints disagree, so an accepted
+ # resume is refused in the child.
caption_column = str(self.caption_column or "").strip() or "text"
return replace(
self,
@@ -1235,10 +1188,10 @@ class DiffusionLoraConfig:
def resolve_train_steps(cfg: "DiffusionLoraConfig", n_images: int) -> int:
- """The effective optimizer-step count for a run. When ``cfg.num_epochs`` is set (> 0),
- one epoch is one full pass over the dataset in optimizer steps -- ceil(N / (batch x
- grad_accum)) steps -- so the run is ``num_epochs`` such passes, capped at 100000. With
- ``num_epochs == 0`` the explicit ``cfg.train_steps`` is used unchanged."""
+ """The effective optimizer-step count for a run. When ``cfg.num_epochs`` is set (> 0), one epoch
+ is one full pass over the dataset in optimizer steps -- ceil(N / (batch x grad_accum)) -- so
+ the run is ``num_epochs`` such passes, capped at 100000. With ``num_epochs == 0`` the
+ explicit ``cfg.train_steps`` is used unchanged."""
if cfg.num_epochs > 0:
per_step = max(1, cfg.train_batch_size * cfg.gradient_accumulation_steps)
steps_per_epoch = max(1, math.ceil(n_images / per_step))
@@ -1247,18 +1200,13 @@ def resolve_train_steps(cfg: "DiffusionLoraConfig", n_images: int) -> int:
class PermutationBatchSampler:
- """Yields batch indices as consecutive slices of a reshuffled permutation of
- ``range(n)``, so every index is visited exactly once per cycle before any repeats --
- an epoch-style full pass instead of the with-replacement draw that leaves part of a
- small dataset unseen at low step counts (num_epochs converts to a step budget, but the
- per-batch index draw is what decides coverage). When a cycle is exhausted the order is
- reshuffled from the run's own ``rng`` so the index stream stays seed-deterministic and
- each cycle differs.
-
- Both trainers share this so the SDXL ``_next_batch`` path and the DiT per-sample draw
- select indices the same way. Only the index selection changes (with-replacement ->
- permutation cycles); step count and batch shapes are unchanged.
- """
+ """Yields batch indices as consecutive slices of a reshuffled permutation of ``range(n)``, so
+ every index is visited exactly once per cycle before any repeats -- an epoch-style full pass
+ instead of the with-replacement draw that leaves part of a small dataset unseen at low step
+ counts. When a cycle is exhausted the order is reshuffled from the run's own ``rng`` so the
+ index stream stays seed-deterministic and each cycle differs. Both trainers share this so the
+ SDXL ``_next_batch`` path and the DiT per-sample draw select indices the same way; step count
+ and batch shapes are unchanged."""
def __init__(self, n: int, rng: random.Random) -> None:
if n <= 0:
@@ -1274,8 +1222,8 @@ class PermutationBatchSampler:
self._pos = 0
def next_batch(self, k: int) -> list[int]:
- # k may exceed n (batch larger than the dataset): the permutation refills across cycles so the
- # caller always gets exactly k indices.
+ # k may exceed n (batch larger than the dataset): the permutation refills across cycles so the caller always
+ # gets exactly k indices.
out: list[int] = []
while len(out) < k:
if self._pos >= len(self._order):
@@ -1286,21 +1234,18 @@ class PermutationBatchSampler:
return out
def state_dict(self) -> dict[str, Any]:
- """The position inside the current permutation cycle, for a resume checkpoint. The
- order itself is stored (not just the position): it was drawn from the run's rng, and
- restoring the rng alone would not reproduce a cycle that was already in progress."""
+ """The position inside the current permutation cycle, for a resume checkpoint. The order
+ itself is stored (not just the position): it was drawn from the run's rng, and restoring
+ the rng alone would not reproduce a cycle already in progress."""
return {"n": self._n, "order": list(self._order), "pos": int(self._pos)}
def load_state_dict(self, state: Optional[dict[str, Any]]) -> bool:
- """Restore a cycle saved by ``state_dict``. True when it was restored.
-
- Refuses a state for a different dataset size (the resume preflight already rejects a
- changed dataset; this keeps a manually edited checkpoint from indexing out of range)
- and clamps a bad position. The BOOLEAN matters: silently leaving a fresh sampler in
- place looks like a clean resume while the RNG -- already restored to a point after this
- permutation was drawn -- generates a different order, so the run quietly reorders and
- skips images.
- """
+ """Restore a cycle saved by ``state_dict``. True when it was restored. Refuses a state for a
+ different dataset size (the resume preflight already rejects a changed dataset; this
+ keeps a manually edited checkpoint from indexing out of range) and clamps a bad position.
+ The BOOLEAN matters: silently leaving a fresh sampler in place looks like a clean resume
+ while the RNG -- already restored to a point after this permutation was drawn --
+ generates a different order, so the run quietly reorders and skips images."""
if not isinstance(state, dict) or int(state.get("n") or 0) != self._n:
return False
order = state.get("order")
@@ -1310,8 +1255,8 @@ class PermutationBatchSampler:
restored = [int(i) for i in order]
except (TypeError, ValueError):
return False
- # A shortened or duplicate-carrying order is in range and plausible, so the cycle reshuffles
- # early or serves the same image twice with the RNG already past the original draw.
+ # A shortened or duplicate-carrying order is in range and plausible, so the cycle reshuffles early or serves
+ # the same image twice with the RNG already past the original draw.
if restored and sorted(restored) != list(range(self._n)):
return False
self._order = restored
@@ -1319,8 +1264,8 @@ class PermutationBatchSampler:
pos = int(state.get("pos") or 0)
except (TypeError, ValueError):
return False
- # A position outside 0..len(order) is a damaged manifest, and clamping it re-serves the permutation
- # from the top or ends the cycle early behind an already-restored RNG.
+ # A position outside 0..len(order) is a damaged manifest, and clamping it re-serves the permutation from the
+ # top or ends the cycle early behind an already-restored RNG.
if not 0 <= pos <= len(self._order):
return False
self._pos = pos
@@ -1336,25 +1281,21 @@ def discover_image_caption_pairs(
) -> list[tuple[str, str]]:
"""Resolve ``(image_path, caption)`` pairs from a dataset directory.
- Caption sources, in priority order per image:
- 1. a per-image sidecar ``<stem>.txt`` / ``<stem>.caption``,
- 2. a ``metadata.jsonl`` / ``captions.jsonl`` row keyed by ``file_name`` (or ``image``)
- carrying the caption in ``caption_column`` (default ``text``),
- 3. ``instance_prompt`` (dreambooth) for any remaining image.
-
- A sidecar wins over the metadata row because it is the user's explicit per-image edit
- (the labeling grid writes a .txt sidecar), which must override the bulk metadata file.
- Must agree with ``routes.training._image_record``, which resolves captions the same way.
+ Caption sources, in priority order per image: a per-image sidecar ``<stem>.txt`` /
+ ``<stem>.caption``; then a ``metadata.jsonl`` / ``captions.jsonl`` row keyed by ``file_name``
+ (or ``image``) carrying the caption in ``caption_column`` (default ``text``); then
+ ``instance_prompt`` (dreambooth). A sidecar wins over the metadata row because it is the user's
+ explicit per-image edit (the labeling grid writes a .txt sidecar). Must agree with
+ ``routes.training._image_record``.
Images with no caption from any source are skipped. Pure filesystem + JSON, so it is
- unit-testable without torch. Raises FileNotFoundError for a missing dir and ValueError
- when nothing is captionable.
-
- ``verify_images`` (opt-in) additionally runs a cheap PIL header probe on each captioned
- image and raises ValueError on a corrupt/zero-byte/truncated file. The start route enables
- it so a bad upload is rejected BEFORE the resident GPU models are freed, instead of crashing
- the spawned trainer after teardown; the trainers leave it off (they decode every image
- anyway, so a second probe pass would be redundant).
+ unit-testable without torch. Raises FileNotFoundError for a missing dir and ValueError when
+ nothing is captionable.
+
+ ``verify_images`` (opt-in) additionally runs a cheap PIL header probe on each captioned image
+ and raises ValueError on a corrupt/zero-byte/truncated file. The start route enables it so a bad
+ upload is rejected BEFORE the resident GPU models are freed; the trainers leave it off, since
+ they decode every image anyway.
"""
root = Path(data_dir).expanduser()
if not root.is_dir():
@@ -1371,8 +1312,8 @@ def discover_image_caption_pairs(
meta_path = root / meta_name
if not meta_path.is_file():
continue
- # Tolerate a bad upload (invalid UTF-8, or non-object JSON): skip the record so the instance_prompt
- # fallback still applies.
+ # Tolerate a bad upload (invalid UTF-8, or non-object JSON): skip the record so the instance_prompt fallback
+ # still applies.
try:
meta_lines = meta_path.read_text(encoding = "utf-8").splitlines()
except (OSError, UnicodeError):
@@ -1397,8 +1338,8 @@ def discover_image_caption_pairs(
for img in images:
caption: Optional[str] = None
sidecar_present = False
- # An EMPTY sidecar is a deliberate tombstone: it suppresses the metadata caption and leaves the
- # image uncaptioned.
+ # An EMPTY sidecar is a deliberate tombstone: it suppresses the metadata caption and leaves the image
+ # uncaptioned.
for ext in _CAPTION_EXTS:
sidecar = img.with_suffix(ext)
if sidecar.is_file():
@@ -1410,8 +1351,8 @@ def discover_image_caption_pairs(
# instead of a 500.
caption = ""
break
- # 2. metadata row keyed by file name (basename or relative path, as_posix so Windows paths
- # match). A sidecar, even empty, wins.
+ # 2. metadata row keyed by file name (basename or relative path, as_posix so Windows paths match). A sidecar,
+ # even empty, wins.
if not sidecar_present:
caption = meta_caption.get(img.name) or meta_caption.get(
img.relative_to(root).as_posix()
@@ -1423,9 +1364,6 @@ def discover_image_caption_pairs(
if verify_images:
# Reject a corrupt or truncated image now: otherwise it passes filename-only discovery, the start
# route frees the GPU models, and the trainer crashes in Image.open.
- # Epoch-mode payloads carry max_steps: 0 as the "use epochs" sentinel, which the alias copies as
- # train_steps: 0. normalized() rejects train_steps < 1 before resolve_train_steps() applies
- # num_epochs, so drop a falsy value here.
try:
from PIL import Image
with Image.open(img) as _probe:
@@ -1445,18 +1383,18 @@ def discover_image_caption_pairs(
return pairs
-# The shared DiffusionLoraConfig carries save_steps / resume_from_checkpoint for every family, so a
-# loop that implements neither has to say so rather than ignore them.
+# The shared DiffusionLoraConfig carries save_steps / resume_from_checkpoint for every family, so a loop that
+# implements neither has to say so rather than ignore them.
CHECKPOINTLESS_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
-# The batch axis is a pure replication axis for these: the layout, the rotary grid and the row
-# timesteps are set by one clip's geometry and its caption's length.
+# The batch axis is a pure replication axis for these: the layout, the rotary grid and the row timesteps are set by
+# one clip's geometry and its caption's length.
SINGLE_SEQUENCE_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
-# Families whose trainer loads its base through ModularPipeline.from_pretrained. Their local
-# layout is modular_model_index.json and no model_index.json, so the conventional shape check
-# refuses the only local form the family HAS. One allow_modular set, read by the trainer and by
-# the START ROUTE, so the two cannot disagree about the same directory.
+# Families whose trainer loads its base through ModularPipeline.from_pretrained. Their local layout is
+# modular_model_index.json and no model_index.json, so the conventional shape check refuses the only local form the
+# family HAS. One allow_modular set, read by the trainer and by the START ROUTE, so the two cannot disagree about the
+# same directory.
MODULAR_BASE_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
# MiniMax-H3 canvas multiple: a 16x VAE compression and a 2x patch.
@@ -1464,13 +1402,11 @@ _H3_CANVAS_MULTIPLE = 32
def h3_train_unsupported_reason(cfg: Any) -> Optional[str]:
- """Reason this config cannot run the MiniMax-H3 trainer, else None. Never raises.
-
- Called by the START ROUTE before it frees the resident GPU models, and again by the trainer
- itself so a direct call is refused the same way. Config-only by construction: every check
- here reads the request, never the host, so the route can answer without importing torch or
- touching the GPU. Host capability stays in the precision preflight next to it.
- """
+ """Reason this config cannot run the MiniMax-H3 trainer, else None. Never raises. Called by the
+ START ROUTE before it frees the resident GPU models, and again by the trainer itself so a
+ direct call is refused the same way. Config-only by construction: every check reads the
+ request, never the host, so the route can answer without importing torch. Host capability
+ stays in the precision preflight next to it."""
if (getattr(cfg, "resolved_family", "") or "").strip().lower() != "minimax-h3":
return None
if cfg.mixed_precision != "bf16":
@@ -1497,16 +1433,16 @@ def h3_train_unsupported_reason(cfg: Any) -> Optional[str]:
"audio at different sigmas in the same step, so a single weight over 'the' "
"timestep is ambiguous. Use weighting_scheme='none'."
)
- # Two clips with different captions have different text lengths and therefore different layouts, so
- # a batch > 1 cannot be formed without padding the model has no mask for.
+ # Two clips with different captions have different text lengths and therefore different layouts, so a batch > 1
+ # cannot be formed without padding the model has no mask for.
if cfg.train_batch_size != 1:
return (
"MiniMax-H3 trains at batch size 1: one forward covers one packed sequence, whose "
"row layout is set by the clip's own geometry and its caption's length. Use "
"gradient_accumulation_steps to raise the effective batch."
)
- # torch.compile is never invoked here (the packed layout changes shape with every caption length),
- # so an explicit "on" would be accepted and then ignored.
+ # torch.compile is never invoked here (the packed layout changes shape with every caption length), so an explicit
+ # "on" would be accepted and then ignored.
if str(getattr(cfg, "compile_transformer", "auto") or "auto").strip().lower() == "on":
return (
"MiniMax-H3 does not compile: its packed sequence changes length with every clip's "
@@ -1523,9 +1459,8 @@ def h3_train_unsupported_reason(cfg: Any) -> Optional[str]:
return None
-# These have a DEFAULT the H3 loop disagrees with, so they are normalised rather than refused
-# (which would 422 every untouched request): one centre cover-crop, nothing flipped, a plain
-# unweighted MSE, and exactly one cached tuple.
+# These have a DEFAULT the H3 loop disagrees with, so they are normalised rather than refused (which would 422 every
+# untouched request): one centre cover-crop, nothing flipped, a plain unweighted MSE, and exactly one cached tuple.
_H3_FIXED_RECIPE: dict[str, Any] = {
"center_crop": True,
"random_flip": False,
@@ -1536,15 +1471,12 @@ _H3_FIXED_RECIPE: dict[str, Any] = {
def train_recipe_overrides(cfg: Any) -> dict[str, Any]:
- """The fields whose REQUESTED value this family's loop replaces, mapped to what it runs.
-
- Shared for the same reason ``h3_train_unsupported_reason`` is: the trainer applies these in
- the CHILD, while the run record is written by the PARENT from the config handed to
- ``service.start``. Normalising in the trainer alone therefore fixed what ran and left Previous
- Runs describing cropping, flipping and min-SNR weighting that never happened -- exactly the
- recipe drift the normalisation exists to prevent. Both sides read this one table instead.
-
- Empty for every other family: their loops honour all three."""
+ """The fields whose REQUESTED value this family's loop replaces, mapped to what it runs. Shared
+ for the same reason ``h3_train_unsupported_reason`` is: the trainer applies these in the
+ CHILD, while the run record is written by the PARENT from the config handed to
+ ``service.start``. Normalising in the trainer alone therefore fixed what ran and left
+ Previous Runs describing cropping, flipping and min-SNR weighting that never happened. Empty
+ for every other family: their loops honour all three."""
if (getattr(cfg, "resolved_family", "") or "").strip().lower() != "minimax-h3":
return {}
return dict(_H3_FIXED_RECIPE)
@@ -1562,18 +1494,13 @@ def discover_training_pairs(
caption_column: str = "text",
verify_images: bool = False,
) -> list[tuple[str, str]]:
- """The ``(path, caption)`` pairs for ``resolved_family``, from whichever discovery its
- trainer runs.
-
- The /diffusion/start preflight exists so a bad dataset 400s BEFORE the resident GPU models
- are freed, which only holds while it runs the SAME discovery as the trainer. It ran the
- image one unconditionally, so a MiniMax-H3 dataset -- captioned clips, which is the only
- thing its trainer accepts -- was rejected at the route with "No captioned images found" and
- the advertised H3 trainer could not be reached through /diffusion/start at all.
-
- ``verify_images`` is image-only: the clip discovery has no cheap header probe to match it
- (a container has to be opened to be judged), so it is ignored for a clip family rather than
- quietly implying a check that did not happen."""
+ """The ``(path, caption)`` pairs for ``resolved_family``, from whichever discovery its trainer
+ runs. The /diffusion/start preflight exists so a bad dataset 400s BEFORE the resident GPU
+ models are freed, which only holds while it runs the SAME discovery as the trainer. It ran
+ the image one unconditionally, so a MiniMax-H3 dataset -- captioned clips, the only thing its
+ trainer accepts -- was rejected at the route with "No captioned images found".
+ ``verify_images`` is image-only: the clip discovery has no cheap header probe to match it, so
+ it is ignored for a clip family rather than quietly implying a check that did not happen."""
if str(resolved_family or "").strip().lower() in CLIP_TRAINED_FAMILIES:
from core.training.diffusion_h3_clips import discover_clip_caption_pairs
return discover_clip_caption_pairs(
@@ -1595,12 +1522,11 @@ def _emit(on_event: Optional[EventCb], type_: str, **kw: Any) -> None:
def _plan_cache_variants(
num_images: int, cache_variants: int, center_crop: bool, random_flip: bool, seed: int
) -> list[list[tuple[float, float, bool]]]:
- """Seed-deterministic crop/flip plan for the latent cache: per image, up to
- ``cache_variants`` draws of (u_left, u_top, flip) with the crop as unit fractions the
- loader maps onto its integer crop range. Uses its own rng stream so the training
- loop's draws are untouched. Center-crop / no-flip collapse duplicate variants (a
- center crop without flip is one variant no matter how many draws), so callers encode
- each distinct variant exactly once. Pure (no torch) for CPU unit tests."""
+ """Seed-deterministic crop/flip plan for the latent cache: per image, up to ``cache_variants``
+ draws of (u_left, u_top, flip) with the crop as unit fractions the loader maps onto its
+ integer crop range. Uses its own rng stream so the training loop's draws are untouched.
+ Center-crop / no-flip collapse duplicate variants, so callers encode each distinct variant
+ exactly once. Pure (no torch) for CPU unit tests."""
crop_rng = random.Random(seed)
plan: list[list[tuple[float, float, bool]]] = []
for _ in range(max(0, num_images)):
@@ -1617,20 +1543,19 @@ def _plan_cache_variants(
return plan
-# Two fp32 posterior tensors per crop/flip variant per image, so a few thousand images can exhaust
-# pinned RAM; over budget it falls back to per-step VAE encoding.
+# Two fp32 posterior tensors per crop/flip variant per image, so a few thousand images can exhaust pinned RAM; over
+# budget it falls back to per-step VAE encoding.
_LATENT_CACHE_BUDGET_BYTES = 4 * 1024**3 # 4 GiB
-# Returned by the cache builders when the estimate exceeds budget: the caller keeps the VAE
-# resident. Distinct from ``None`` (a stop requested mid-build).
+# Returned by the cache builders when the estimate exceeds budget: the caller keeps the VAE resident. Distinct from
+# ``None`` (a stop requested mid-build).
LATENT_CACHE_OVER_BUDGET: Any = object()
def _latent_cache_forced() -> bool:
- """The user explicitly forced the latent cache on, bypassing the size gate. This is the
- explicit opt-in counterpart to ``UNSLOTH_DIFFUSION_NO_LATENT_CACHE`` (the explicit
- opt-out); only the automatic default is size-gated, so an explicit choice is honoured
- verbatim in either direction."""
+ """The user explicitly forced the latent cache on, bypassing the size gate. The explicit opt-in
+ counterpart to ``UNSLOTH_DIFFUSION_NO_LATENT_CACHE``; only the automatic default is
+ size-gated, so an explicit choice is honoured verbatim in either direction."""
return os.environ.get("UNSLOTH_DIFFUSION_FORCE_LATENT_CACHE", "") in ("1", "true")
@@ -1642,8 +1567,8 @@ def _latent_cache_over_budget(
"""True when a cache of ``total_variants`` entries, each two fp32 tensors totalling
``per_variant_bytes``, is estimated to exceed ``budget_bytes``. ``per_variant_bytes`` is
measured from a real encoded latent, so the estimate tracks the actual per-family tensor
- shape (SDXL 4-channel vs. a packed 16-channel DiT latent) rather than a guess. The budget
- is read from the module constant at call time when not given, so tests can override it."""
+ shape (SDXL 4-channel vs a packed 16-channel DiT latent) rather than a guess. The budget is
+ read from the module constant at call time when not given, so tests can override it."""
if budget_bytes is None:
budget_bytes = _LATENT_CACHE_BUDGET_BYTES
return per_variant_bytes * max(0, total_variants) > budget_bytes
@@ -1654,13 +1579,12 @@ def _apply_perf_flags(
device: str,
cudnn_benchmark: bool = False,
) -> dict:
- """Set the run-scoped torch backend knobs: TF32 matmuls + high fp32 matmul precision
- when ``cfg.enable_tf32`` is on, strict fp32 (all TF32 flags cleared) when it is off,
- plus cudnn autotuning when the caller opts in. Autotune is
- for the conv-heavy SDXL U-Net only: measured on B200, it DOUBLES peak VRAM (fp32 VAE
- conv workspaces) while the DiT loop -- pure matmuls once the latent cache is built --
- gains nothing from it. Returns a snapshot for ``_restore_perf_flags``. Best-effort:
- missing attributes on a CPU/other-vendor build are skipped."""
+ """Set the run-scoped torch backend knobs: TF32 matmuls + high fp32 matmul precision when
+ ``cfg.enable_tf32`` is on, strict fp32 (all TF32 flags cleared) when it is off, plus cudnn
+ autotuning when the caller opts in. Autotune is for the conv-heavy SDXL U-Net only: measured
+ on B200, it DOUBLES peak VRAM (fp32 VAE conv workspaces) while the DiT loop gains nothing.
+ Returns a snapshot for ``_restore_perf_flags``. Best-effort: missing attributes on a
+ CPU/other-vendor build are skipped."""
from core.inference.diffusion_speed import snapshot_backend_flags
snap: dict[str, Any] = {"flags": snapshot_backend_flags(), "matmul_precision": None}
@@ -1675,15 +1599,15 @@ def _apply_perf_flags(
torch.backends.cudnn.allow_tf32 = True
torch.set_float32_matmul_precision("high")
else:
- # The opt-out is a strict-fp32 A/B mode, so actively clear the flags rather than inherit ambient
- # state (cudnn TF32 defaults ON).
+ # The opt-out is a strict-fp32 A/B mode, so actively clear the flags rather than inherit ambient state
+ # (cudnn TF32 defaults ON).
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.set_float32_matmul_precision("highest")
if cudnn_benchmark:
torch.backends.cudnn.benchmark = True
- # The cuDNN SDPA TRAINING graph is broken for the FLUX attention shapes on torch 2.10 + cu130 (B200)
- # and poisons the context, so pin flash / mem-efficient SDPA for the run (restored on exit).
+ # The cuDNN SDPA TRAINING graph is broken for the FLUX attention shapes on torch 2.10 + cu130 (B200) and
+ # poisons the context, so pin flash / mem-efficient SDPA for the run (restored on exit).
cuda_backends = getattr(torch.backends, "cuda", None)
if cuda_backends is not None and hasattr(cuda_backends, "enable_cudnn_sdp"):
try:
@@ -1698,8 +1622,8 @@ def _apply_perf_flags(
def _restore_perf_flags(snap: Optional[dict]) -> None:
- """Undo ``_apply_perf_flags`` (the trainer subprocess is disposable, but in-process
- callers -- tests, notebooks -- must not inherit mutated globals)."""
+ """Undo ``_apply_perf_flags`` (the trainer subprocess is disposable, but in-process callers --
+ tests, notebooks -- must not inherit mutated globals)."""
if not snap:
return
from core.inference.diffusion_speed import restore_backend_flags
@@ -1710,8 +1634,8 @@ def _restore_perf_flags(snap: Optional[dict]) -> None:
if snap.get("matmul_precision"):
torch.set_float32_matmul_precision(snap["matmul_precision"])
- # Restore the exact pre-run cudnn SDPA state; None means the flag was unreadable at apply time and
- # never touched.
+ # Restore the exact pre-run cudnn SDPA state; None means the flag was unreadable at apply time and never
+ # touched.
cuda_backends = getattr(torch.backends, "cuda", None)
if (
snap.get("cudnn_sdp") is not None
@@ -1723,8 +1647,8 @@ def _restore_perf_flags(snap: Optional[dict]) -> None:
pass
-# Kept here so the training gate stays independent of the inference allowlist. Exact-match
-# lowercased; never add pickles or remote code.
+# Kept here so the training gate stays independent of the inference allowlist. Exact-match lowercased; never add
+# pickles or remote code.
_TRAIN_EXTRA_TRUSTED_REPOS = frozenset(
{
"black-forest-labs/flux.2-dev",
@@ -1738,10 +1662,10 @@ _TRAIN_EXTRA_TRUSTED_REPOS = frozenset(
}
)
-# LTX-2.3 repos hold SINGLE-FILE checkpoints and no diffusers layout; inference assembles them
-# with from_single_file plus 2.3 config overrides (see core/inference/video_ltx2.py), while the
-# trainer only knows LTX2Pipeline.from_pretrained. The name still resolves to the ltx-2 family, so
-# without an explicit refusal the run evicts residents and only then fails in the child.
+# LTX-2.3 repos hold SINGLE-FILE checkpoints and no diffusers layout; inference assembles them with from_single_file
+# plus 2.3 config overrides (see core/inference/video_ltx2.py), while the trainer only knows
+# LTX2Pipeline.from_pretrained. The name still resolves to the ltx-2 family, so without an explicit refusal the run
+# evicts residents and only then fails in the child.
_LTX23_TRAIN_UNSUPPORTED = ("lightricks/ltx-2.3", "lightricks/ltx-2.3-fp8")
@@ -1758,14 +1682,13 @@ def _refuse_ltx23_training_base(base_model: str) -> None:
def _assert_trusted_base_model(base_model: str, *, allow_modular: bool = False) -> None:
- """Gate the training base model the same way the inference backend gates non-GGUF loads:
- a local path or a trusted repo (``unsloth/*`` or an allowlisted official base). This runs
- BEFORE ``from_pretrained`` so an untrusted remote repo (which could ship pickle weights)
- is never fetched or deserialised.
-
- ``allow_modular`` is for a trainer whose loader is ``ModularPipeline.from_pretrained``: a
- local MiniMax-H3 pipeline carries ``modular_model_index.json`` and no ``model_index.json``,
- so the conventional shape check rejected the one local layout that family HAS."""
+ """Gate the training base model the same way the inference backend gates non-GGUF loads: a local
+ path or a trusted repo (``unsloth/*`` or an allowlisted official base). This runs BEFORE
+ ``from_pretrained`` so an untrusted remote repo (which could ship pickle weights) is never
+ fetched or deserialised. ``allow_modular`` is for a trainer whose loader is
+ ``ModularPipeline.from_pretrained``: a local MiniMax-H3 pipeline carries
+ ``modular_model_index.json`` and no ``model_index.json``, so the conventional shape check
+ rejected the one local layout that family HAS."""
from core.inference.diffusion import _assert_local_base_is_pipeline, _is_trusted_diffusion_repo
trusted = (
@@ -1777,34 +1700,29 @@ def _assert_trusted_base_model(base_model: str, *, allow_modular: bool = False)
f"Refusing to train from untrusted base model '{base_model}'. Use a local path or "
f"a trusted repo (an unsloth/* repo or an official base)."
)
- # An existing LOCAL base is loaded as a full pipeline, which needs an index; reject a non-pipeline
- # local dir before /diffusion/start frees the GPU models.
+ # An existing LOCAL base is loaded as a full pipeline, which needs an index; reject a non-pipeline local dir
+ # before /diffusion/start frees the GPU models.
_assert_local_base_is_pipeline(base_model, allow_modular = allow_modular)
# One writer and one reader for BOTH trainers, so an SDXL and a DiT run resume from the same bundle shape.
-# ── resume checkpoints ────────────────────────────────────────────────────────
def trainable_state_dict(model: Any) -> dict[str, Any]:
- """The trainable (LoRA) parameters of ``model``, keyed by parameter name.
-
- Deliberately NOT the peft/diffusers export format: this is the checkpoint's private
- copy of exactly the tensors the optimizer holds moments for, so restoring it and the
- optimizer state together reproduces the run bit-for-bit. Parameter names are stable
- across a re-attach and across regional torch.compile (which compiles submodules in
- place without renaming), which is the same assumption ``LoRAEMA`` already makes."""
+ """The trainable (LoRA) parameters of ``model``, keyed by parameter name. Deliberately NOT the
+ peft/diffusers export format: this is the checkpoint's private copy of exactly the tensors
+ the optimizer holds moments for, so restoring it and the optimizer state together reproduces
+ the run bit-for-bit. Parameter names are stable across a re-attach and across regional
+ torch.compile (which compiles submodules in place without renaming), the same assumption
+ ``LoRAEMA`` makes."""
return {name: p.detach() for name, p in model.named_parameters() if p.requires_grad}
def load_trainable_state_dict(model: Any, state: Optional[dict[str, Any]]) -> int:
- """Copy a ``trainable_state_dict`` back into ``model`` in place, returning how many
- parameters were restored. Copies rather than reassigns, so the optimizer's parameter
- references (and their loaded moments) stay valid.
-
- Every saved tensor must land. A partial match means the parameter NAMES moved (a different
- adapter name, a wrapper that re-prefixes them), and because the optimizer state is keyed by
- parameter INDEX it would still load cleanly -- leaving restored Adam moments and a restored
- LR position driving freshly initialised LoRA weights, while the run reports a normal resume.
- Raise instead."""
+ """Copy a ``trainable_state_dict`` back into ``model`` in place, returning how many parameters
+ were restored. Copies rather than reassigns, so the optimizer's parameter references (and
+ their loaded moments) stay valid. Every saved tensor must land: a partial match means the
+ parameter NAMES moved, and because the optimizer state is keyed by parameter INDEX it would
+ still load cleanly, leaving restored Adam moments and a restored LR position driving freshly
+ initialised LoRA weights while the run reports a normal resume. Raise instead."""
if not state:
return 0
import torch
@@ -1826,8 +1744,8 @@ def load_trainable_state_dict(model: Any, state: Optional[dict[str, Any]]) -> in
)
p.copy_(saved.to(device = p.device, dtype = p.dtype))
restored += 1
- # BOTH directions: counting only the checkpoint's own tensors let a truncated adapter holding a
- # strict SUBSET pass, and the optimizer state then loaded on top of freshly initialised weights.
+ # BOTH directions: counting only the checkpoint's own tensors let a truncated adapter holding a strict SUBSET
+ # pass, and the optimizer state then loaded on top of freshly initialised weights.
unsaved = sorted(trainable - set(state))
unknown = sorted(set(state) - trainable)
if unsaved or unknown:
@@ -1847,7 +1765,7 @@ def load_trainable_state_dict(model: Any, state: Optional[dict[str, Any]]) -> in
def _json_safe_progress(progress: Optional[dict[str, Any]]) -> dict[str, Any]:
"""Drop non-finite floats from the manifest's progress block. A diverged run pushes
``running_loss`` to NaN/inf, which json.dumps writes as the JS-only NaN/Infinity tokens --
- invalid strict JSON that a stricter reader (or a future consumer of these files) rejects."""
+ invalid strict JSON that a stricter reader rejects."""
out: dict[str, Any] = {}
for key, value in (progress or {}).items():
if isinstance(value, float) and not math.isfinite(value):
@@ -1872,15 +1790,13 @@ def write_resume_checkpoint(
discard_existing: bool = False,
preexisting: Optional[Any] = None,
) -> tuple[Optional[str], Optional[str]]:
- """Write one resume bundle for the run, returning ``(checkpoint_path, error)``.
-
- Never raises: a checkpoint failure must not lose a training run that is otherwise fine,
- so the error is returned (and emitted as a warning) for the caller to report as
- ``resume_blocked_reason``. Used for BOTH the periodic ``save_steps`` saves and the
- stop-and-save, so the two produce identical state.
-
- ``discard_existing`` is set on the FIRST write of a run that did not resume, so bundles
- left in the output dir by an earlier run of the same adapter name cannot outrank it."""
+ """Write one resume bundle for the run, returning ``(checkpoint_path, error)``. Never raises: a
+ checkpoint failure must not lose a training run that is otherwise fine, so the error is
+ returned (and emitted as a warning) for the caller to report as ``resume_blocked_reason``.
+ Used for BOTH the periodic ``save_steps`` saves and the stop-and-save, so the two produce
+ identical state. ``discard_existing`` is set on the FIRST write of a run that did not resume,
+ so bundles left in the output dir by an earlier run of the same adapter name cannot outrank
+ it."""
from core.training.diffusion_checkpoint import capture_rng_state, save_checkpoint
try:
path = save_checkpoint(
@@ -1898,15 +1814,15 @@ def write_resume_checkpoint(
progress = _json_safe_progress(progress),
save_total_limit = int(cfg.save_total_limit or 0),
discard_existing = discard_existing,
- # Which bundle THIS is, so the "step already written" shortcut can tell a re-save of our own source
- # apart from another run's bundle at the same number.
+ # Which bundle THIS is, so the "step already written" shortcut can tell a re-save of our own source apart
+ # from another run's bundle at the same number.
source_checkpoint = getattr(cfg, "resume_from_checkpoint", None),
- # Bundles that predated this run are never pruned to make room for its own: a branched resume used
- # to delete them irreversibly on the first save.
+ # Bundles that predated this run are never pruned to make room for its own: a branched resume used to
+ # delete them irreversibly on the first save.
preexisting = preexisting,
)
- # Reported per save, so a run that later crashes is still known to have resumable state and one
- # whose write failed is still known to be blocked.
+ # Reported per save, so a run that later crashes is still known to have resumable state and one whose write
+ # failed is still known to be blocked.
_emit(on_event, "checkpoint_saved", checkpoint_path = path, step = step)
return path, None
except Exception as exc: # noqa: BLE001 -- reported, never fatal to the run
@@ -1919,17 +1835,18 @@ def _reapply_lr_schedule(optimizer: Any, lr_scheduler: Any) -> None:
"""Recompute the learning rate for the NEXT step from the LIVE schedule.
``optimizer.load_state_dict`` restores the rate the checkpoint was written with and
- ``LRScheduler.load_state_dict`` restores only the position, never re-evaluating the lambda,
- so the first step after a resume runs at the OLD schedule's value. That is invisible while
- ``train_steps`` is unchanged (the UI always replays it) but wrong the moment the target
- moves -- continuing a finished cosine run by raising the step count would take its first
- step at lr 0.0, leaving every parameter untouched.
-
- Only for the closed-form ``LambdaLR`` diffusers' ``get_scheduler`` returns, and evaluated
- from its own public ``lr_lambdas`` / ``base_lrs`` / ``last_epoch`` rather than ``get_lr()``
- (which warns when called outside a step). A chainable scheduler derives its next rate from
- the current one, so re-applying it there would double-step. Best-effort: a schedule we
- cannot re-evaluate keeps the restored value."""
+ ``LRScheduler.load_state_dict`` restores only the position, never re-evaluating the lambda, so
+ the first step after a resume runs at the OLD schedule's value. That is invisible while
+ ``train_steps`` is unchanged but wrong the moment the target moves -- continuing a finished
+ cosine run by raising the step count would take its first step at lr 0.0, leaving every
+ parameter untouched.
+
+ Only for the closed-form ``LambdaLR`` diffusers' ``get_scheduler`` returns, and evaluated from
+ its own public ``lr_lambdas`` / ``base_lrs`` / ``last_epoch`` rather than ``get_lr()`` (which
+ warns when called outside a step). A chainable scheduler derives its next rate from the current
+ one, so re-applying it there would double-step. Best-effort: a schedule we cannot re-evaluate
+ keeps the restored value.
+ """
try:
import torch
@@ -1958,15 +1875,12 @@ def restore_resume_state(
sampler: Any = None,
rng_streams: Optional[dict[str, Any]] = None,
) -> Any:
- """Load ``cfg.resume_from_checkpoint`` into a freshly built run.
-
- Returns the ``LoadedCheckpoint`` (whose ``.step`` is the last COMPLETED optimizer step,
- so the loop restarts at ``.step``), or None when no resume was requested.
-
- Re-runs the full preflight in the child: the start route already validated the request
- before evicting the GPU, but the trainer must not trust a config it did not check
- itself. Raises ResumeError (a ValueError) on a mismatch, which the process adapter
- surfaces as the run's error message."""
+ """Load ``cfg.resume_from_checkpoint`` into a freshly built run. Returns the
+ ``LoadedCheckpoint`` (whose ``.step`` is the last COMPLETED optimizer step, so the loop
+ restarts at ``.step``), or None when no resume was requested. Re-runs the full preflight in
+ the child: the start route already validated the request before evicting the GPU, but the
+ trainer must not trust a config it did not check itself. Raises ResumeError (a ValueError) on
+ a mismatch, which the process adapter surfaces as the run's error message."""
if not cfg.resume_from_checkpoint:
return None
from core.training.diffusion_checkpoint import (
@@ -1986,13 +1900,12 @@ def restore_resume_state(
if optimizer_state is not None:
# The trainers pick their optimizer from the HOST (bnb present, fused kernel available,
# UNSLOTH_DIFFUSION_FP32_OPTIM), so foreign moments arrive legitimately (state1/state2 versus
- # exp_avg/exp_avg_sq): shapes match, load_state_dict accepts them, and the first step dies on a
- # bare KeyError.
+ # exp_avg/exp_avg_sq): shapes match, load_state_dict accepts them, and the first step dies on a bare KeyError.
saved_optimizer = ckpt.optimizer_class
live_optimizer = optimizer_key(optimizer)
if not saved_optimizer:
- # An optimizer file with no class beside it is a hand-edited or half-written bundle, and foreign
- # moments load cleanly then die on the first step, after the preflight evicted the residents.
+ # An optimizer file with no class beside it is a hand-edited or half-written bundle, and foreign moments
+ # load cleanly then die on the first step, after the preflight evicted the residents.
raise ResumeError(
"This checkpoint does not record which optimizer wrote its state, so its "
"moments cannot be safely restored. Resume from an earlier checkpoint, or "
@@ -2004,9 +1917,8 @@ def restore_resume_state(
f"machine builds {live_optimizer}. Install the same optimizer backend (or unset "
f"UNSLOTH_DIFFUSION_FP32_OPTIM) to continue this run."
)
- # Optimizer state is keyed by parameter POSITION while the adapter was restored by NAME, so a
- # PEFT/diffusers upgrade that changes traversal order loads every moment cleanly onto a
- # same-shaped wrong tensor.
+ # Optimizer state is keyed by parameter POSITION while the adapter was restored by NAME, so a PEFT/diffusers
+ # upgrade that changes traversal order loads every moment cleanly onto a same-shaped wrong tensor.
saved_names = ckpt.optimizer_param_names
live_names = list(trainable_state_dict(model))
if saved_names is not None and saved_names != live_names:
@@ -2015,12 +1927,12 @@ def restore_resume_state(
"than this build produces, so its moments cannot be matched to this run's "
"tensors. Start a new run, or resume on the version that wrote it."
)
- # load_state_dict replaces the param groups too, so the checkpoint's learning rate wins over a
- # changed cfg, the same semantics as HF Trainer's resume.
+ # load_state_dict replaces the param groups too, so the checkpoint's learning rate wins over a changed cfg,
+ # the same semantics as HF Trainer's resume.
optimizer.load_state_dict(optimizer_state)
elif optimizer is not None:
- # Every bundle this writer produces has an optimizer, so continuing without one restarts Adam's
- # moments from zero at step N while reporting a clean resume.
+ # Every bundle this writer produces has an optimizer, so continuing without one restarts Adam's moments from
+ # zero at step N while reporting a clean resume.
raise ResumeError(
"This checkpoint carries no optimizer state, so the run cannot be continued from "
"it: the moments would restart from zero at the resumed step. Start a new run."
@@ -2036,8 +1948,8 @@ def restore_resume_state(
"restart from step 0. Start a new run."
)
if sampler is not None and not sampler.load_state_dict(ckpt.sampler_state):
- # Every image checkpoint carries sampler state, so a missing or malformed one leaves a fresh sampler
- # behind an RNG restored past the saved permutation: images silently skipped or repeated.
+ # Every image checkpoint carries sampler state, so a missing or malformed one leaves a fresh sampler behind an
+ # RNG restored past the saved permutation: images silently skipped or repeated.
raise ResumeError(
"This checkpoint's dataset sampler state is missing or unreadable, so the image "
"order cannot be continued. Start a new run."
@@ -2047,8 +1959,8 @@ def restore_resume_state(
if ema_state:
missing = ema.missing_from(ema_state)
if missing:
- # load_state_dict keeps the freshly initialised shadow for anything it cannot match, so an
- # incomplete set blends restored EMA weights with initialisation noise under a clean resume.
+ # load_state_dict keeps the freshly initialised shadow for anything it cannot match, so an incomplete
+ # set blends restored EMA weights with initialisation noise under a clean resume.
named = ", ".join(missing[:3]) + ("..." if len(missing) > 3 else "")
raise ResumeError(
f"This checkpoint's EMA state is missing or mis-shaped for {len(missing)} "
@@ -2057,8 +1969,8 @@ def restore_resume_state(
)
ema.load_state_dict(ema_state, updates = ckpt.ema_updates)
else:
- # EMA is not part of the validated identity, so a resume may turn it on: the object is built
- # BEFORE the adapter is restored, so its shadow holds freshly initialised weights.
+ # EMA is not part of the validated identity, so a resume may turn it on: the object is built BEFORE the
+ # adapter is restored, so its shadow holds freshly initialised weights.
ema.reseed_from(model)
restore_rng_state(ckpt.rng_json, ckpt.torch_state("rng"), rng_streams)
_emit(
@@ -2067,8 +1979,8 @@ def restore_resume_state(
checkpoint_path = str(path),
step = step,
total_steps = cfg.train_steps,
- # Which bundle THIS is, not just where it sat: another run can write its own checkpoint over the
- # same slot, and the pathname alone would offer that replacement back as this run's lineage.
+ # Which bundle THIS is, not just where it sat: another run can write its own checkpoint over the same slot,
+ # and the pathname alone would offer that replacement back as this run's lineage.
source_created_at = ckpt.manifest.get("created_at"),
)
return ckpt
@@ -2079,22 +1991,20 @@ def _publish_to_lora_catalog(
cfg: DiffusionLoraConfig,
steps: Optional[int] = None,
) -> Optional[str]:
- """Best-effort copy of the trained adapter into the Unsloth diffusion LoRA directory so
- the Images LoRA picker (which scans only files directly under ``loras/diffusion``) finds
- it without the user moving files. Also writes a ``<alias>.json`` metadata sidecar so the
- picker can family-gate the adapter (family, base model, trigger prompt, ...). Returns the
- published path, or None on any failure.
-
- ``steps`` is the step count the run actually REACHED, which is what the sidecar must
- record: a run stopped at step 11 of 500 published an adapter claiming 500 steps. None
- keeps the old behaviour for callers that do not know the reached step.
-
- A VIDEO family publishes nothing. ``loras/diffusion`` is read by the Images LoRA picker
- alone, and ``core/inference/video.py`` has no LoRA surface at all, so mirroring a video
- adapter there would copy a large file into a catalog nothing can load and hand the UI a
- deployment path Unsloth cannot honour. The run still reports ``lora_path`` (and ``ema_path``),
- which is the adapter a caller loads directly. Giving video its own catalog and a load path
- on the Video tab is a separate, larger piece of work."""
+ """Best-effort copy of the trained adapter into the Unsloth diffusion LoRA directory so the Images
+ LoRA picker (which scans only files directly under ``loras/diffusion``) finds it without the
+ user moving files. Also writes a ``<alias>.json`` metadata sidecar so the picker can family-gate
+ the adapter. Returns the published path, or None on any failure.
+
+ ``steps`` is the step count the run actually REACHED, which is what the sidecar must record: a
+ run stopped at step 11 of 500 published an adapter claiming 500 steps. None keeps the old
+ behaviour for callers that do not know the reached step.
+
+ A VIDEO family publishes nothing: ``loras/diffusion`` is read by the Images LoRA picker alone
+ and ``core/inference/video.py`` has no LoRA surface, so mirroring a video adapter there would
+ copy a large file into a catalog nothing can load. The run still reports ``lora_path`` (and
+ ``ema_path``), which is the adapter a caller loads directly.
+ """
if detect_video_family("", override = cfg.resolved_family) is not None:
return None
try:
@@ -2132,11 +2042,10 @@ def _write_lora_sidecar(
cfg: DiffusionLoraConfig,
steps: Optional[int] = None,
) -> None:
- """Write the adapter metadata sidecar read back by diffusion_lora._scan_local. Best
- effort: a failure here must not fail publishing, so callers wrap it.
-
- ``steps`` records the step the run REACHED. It used to record ``cfg.train_steps``, the
- CONFIGURED length, so an adapter saved by stopping at step 11 of 500 advertised 500."""
+ """Write the adapter metadata sidecar read back by diffusion_lora._scan_local. Best effort: a
+ failure here must not fail publishing, so callers wrap it. ``steps`` records the step the run
+ REACHED. It used to record ``cfg.train_steps``, the CONFIGURED length, so an adapter saved by
+ stopping at step 11 of 500 advertised 500."""
meta = {
"family": cfg.resolved_family,
"families": [cfg.resolved_family],
@@ -2152,13 +2061,13 @@ def _write_lora_sidecar(
sidecar_path.write_text(json.dumps(meta, indent = 2), encoding = "utf-8")
-# Aliases from the generic Unsloth training payload onto DiffusionLoraConfig fields, so the shared
-# request shape can also drive this trainer.
+# Aliases from the generic Unsloth training payload onto DiffusionLoraConfig fields, so the shared request shape can
+# also drive this trainer.
_CONFIG_ALIASES = {
"model_name": "base_model",
"max_steps": "train_steps",
- # num_epochs already matches the diffusion field name, but list it so the epochs override is
- # threaded through explicitly.
+ # num_epochs already matches the diffusion field name, but list it so the epochs override is threaded through
+ # explicitly.
"num_epochs": "num_epochs",
"batch_size": "train_batch_size",
"lora_r": "lora_rank",
@@ -2169,26 +2078,26 @@ _CONFIG_ALIASES = {
def _coerce_gradient_checkpointing(value: Any) -> bool:
- """Unsloth sends gradient_checkpointing as a string ("none" / "true" / "unsloth"); the
- disable words are False, anything else truthy is True. A real bool passes through."""
+ """Unsloth sends gradient_checkpointing as a string ("none" / "true" / "unsloth"); the disable
+ words are False, anything else truthy is True. A real bool passes through."""
if isinstance(value, str):
return value.strip().lower() not in ("", "none", "false", "0", "no", "off")
return bool(value)
def _coerce_bool(value: Any) -> bool:
- """Coerce a flag that may arrive as a string through the generic Unsloth config path
- (e.g. "false" / "0" / "off"). A non-empty string like "false" is otherwise truthy, so
- an opt-out would silently no-op. A real bool passes through."""
+ """Coerce a flag that may arrive as a string through the generic Unsloth config path (e.g.
+ "false" / "0" / "off"). A non-empty string like "false" is otherwise truthy, so an opt-out
+ would silently no-op. A real bool passes through."""
if isinstance(value, str):
return value.strip().lower() not in ("", "none", "false", "0", "no", "off")
return bool(value)
def _config_from_dict(config: dict) -> DiffusionLoraConfig:
- """Build a DiffusionLoraConfig from a plain dict. Unknown keys are ignored so a richer
- request payload (UI form) does not break construction; a small set of generic Unsloth
- training keys are aliased onto the diffusion field names, and string flags are coerced."""
+ """Build a DiffusionLoraConfig from a plain dict. Unknown keys are ignored so a richer request
+ payload (UI form) does not break construction; a small set of generic Unsloth training keys
+ are aliased onto the diffusion field names, and string flags are coerced."""
valid = DiffusionLoraConfig.__dataclass_fields__.keys()
kwargs: dict[str, Any] = {}
# Aliases first (lowest priority); a canonical key present in the payload overrides.
@@ -2198,8 +2107,8 @@ def _config_from_dict(config: dict) -> DiffusionLoraConfig:
for k, v in config.items():
if k in valid:
kwargs[k] = v
- # Epoch-mode payloads carry max_steps: 0 as the "use epochs" sentinel, and normalized() rejects
- # train_steps < 1 before resolve_train_steps() applies num_epochs.
+ # Epoch-mode payloads carry max_steps: 0 as the "use epochs" sentinel, and normalized() rejects train_steps < 1
+ # before resolve_train_steps() applies num_epochs.
try:
_num_epochs = int(kwargs.get("num_epochs") or 0)
except (TypeError, ValueError):
diff --git a/studio/backend/core/training/diffusion_train_extras.py b/studio/backend/core/training/diffusion_train_extras.py
index 89f6ab1aaff..a6a18592f43 100644
--- a/studio/backend/core/training/diffusion_train_extras.py
+++ b/studio/backend/core/training/diffusion_train_extras.py
@@ -41,9 +41,8 @@ from pathlib import Path
from typing import Any, Iterable, Optional
-# Effective decay is min(decay, (1 + updates) / (WARMUP_OFFSET + updates)); at offset 10 step 1
-# averages aggressively (~0.18) and the ramp reaches 0.99 after ~1000 updates.
-# ── LoRA EMA ──────────────────────────────────────────────────────────────────
+# Effective decay is min(decay, (1 + updates) / (WARMUP_OFFSET + updates)); at offset 10 step 1 averages aggressively
+# (~0.18) and the ramp reaches 0.99 after ~1000 updates.
_EMA_WARMUP_OFFSET = 10.0
@@ -202,8 +201,6 @@ def save_ema_adapter(ema: "LoRAEMA", transformer: Any, spec_save: Any, out_dir:
return str(ema_dir)
-# ── persistent conditioning cache ─────────────────────────────────────────────
-
_CACHE_VERSION = "1"
@@ -393,9 +390,8 @@ class PersistentConditioningCache:
return None
-# Buckets snap to 64 pixels: the DiT families divide by 8 in the VAE and 2 again in latent patching,
-# and regional torch.compile prefers few distinct shapes.
-# ── aspect-ratio bucketing ────────────────────────────────────────────────────
+# Buckets snap to 64 pixels: the DiT families divide by 8 in the VAE and 2 again in latent patching, and regional
+# torch.compile prefers few distinct shapes.
BUCKET_DIVISOR = 64
@@ -431,7 +427,6 @@ def assign_buckets(
divisor: int = BUCKET_DIVISOR,
max_ratio: float = MAX_BUCKET_RATIO,
) -> dict[tuple[int, int], list[int]]:
- """Group dataset indices by their bucket shape."""
buckets: dict[tuple[int, int], list[int]] = {}
for i, (w, h) in enumerate(sizes):
buckets.setdefault(compute_bucket(w, h, base_resolution, divisor, max_ratio), []).append(i)
@@ -459,7 +454,6 @@ class BucketBatchSampler:
self._pos = {s: 0 for s in self._shapes}
def next_batch(self, k: int) -> tuple[tuple[int, int], list[int]]:
- """Returns (bucket_shape, indices) with exactly ``k`` indices."""
shape = self._rng.choices(self._shapes, weights = self._weights, k = 1)[0]
out: list[int] = []
while len(out) < k:
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 874f740398c..86bc9b47375 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -105,7 +105,6 @@ def _llm_training_active() -> bool:
# One JSON file per terminal run, not the LLM sqlite, so diffusion runs stay off the LLM Runs page.
-# ── persisted run history ──────────────────────────────────────────────────────
def _runs_dir() -> Path:
from utils.paths.storage_roots import studio_root
@@ -125,17 +124,16 @@ def _resume_fields(
source_checkpoint: Optional[str] = None,
source_created_at: Optional[float] = None,
) -> dict[str, Any]:
- """``can_resume`` / ``checkpoint_step`` / ``resume_blocked_reason`` for a run, read from
- the checkpoints that are actually on disk.
-
- Derived, not trusted: a persisted record is a snapshot of the moment the run ended, but
- the user can delete the output folder afterwards. ``started_at`` fences off bundles an
- EARLIER run of the same adapter name left in the same folder, and ``ended_at`` fences off
- the ones a LATER run put there after this one finished -- without the upper bound a
- finished run offers, and resumes, its successor's training state. ``write_error`` is the run's
- own report that a checkpoint write failed; that is sticky and blocks resume (mirroring the
- MLX trainer's ``resume_blocked``), because whatever older state is on disk predates the
- adapter that was published, so continuing from it would silently lose steps. Never raises."""
+ """``can_resume`` / ``checkpoint_step`` / ``resume_blocked_reason`` for a run, read from the
+ checkpoints that are actually on disk.
+
+ Derived, not trusted: a persisted record is a snapshot of the moment the run ended, but the user
+ can delete the output folder afterwards. ``started_at`` fences off bundles an EARLIER run of the
+ same adapter name left in the same folder, and ``ended_at`` fences off the ones a LATER run put
+ there after this one finished. ``write_error`` is the run's own report that a checkpoint write
+ failed; that is sticky and blocks resume (mirroring the MLX trainer's ``resume_blocked``),
+ because whatever older state is on disk predates the adapter that was published. Never raises.
+ """
try:
from core.training.diffusion_checkpoint import describe_resume_state
state = describe_resume_state(
@@ -452,7 +450,6 @@ class DiffusionTrainingService:
# The active job's start config, scrubbed of secrets, kept for the run record.
self._config: dict[str, Any] = {}
- # ── lifecycle ────────────────────────────────────────────────────────────
def is_active(self) -> bool:
with self._lock:
if self._reserved:
@@ -460,17 +457,16 @@ class DiffusionTrainingService:
return self._proc is not None and self._proc.is_alive()
def reserve(self) -> None:
- """Mark a diffusion-training start as in flight so the image/video load guards (which
- read is_active) refuse a concurrent load BEFORE the route frees resident GPU models.
- Without this the training becomes active only at start(), after the free, so an
- overlapping load passes its guard, acquires the GPU, and both workloads allocate VRAM.
+ """Mark a diffusion-training start as in flight so the image/video load guards (which read
+ is_active) refuse a concurrent load BEFORE the route frees resident GPU models. Without this
+ the training becomes active only at start(), after the free, so an overlapping load passes
+ its guard, acquires the GPU, and both workloads allocate VRAM.
Compare-and-set: raise if a start is already reserved or a job is already running, so a
- second overlapping /diffusion/start is rejected (409) BEFORE it frees GPU residents,
- instead of both requests tearing down residents and racing to start() (whichever finishes
- first wins, so a double-click or a retry with different parameters could start the wrong
- config). Paired with unreserve() in a finally by the reserving caller, so a failed start
- never leaves training 'active'."""
+ second overlapping /diffusion/start is rejected (409) BEFORE it frees GPU residents, instead
+ of both requests tearing down residents and racing to start(). Paired with unreserve() in a
+ finally by the reserving caller, so a failed start never leaves training active.
+ """
with self._lock:
if self._reserved or (self._proc is not None and self._proc.is_alive()):
raise RuntimeError("A diffusion training job is already running.")
@@ -532,16 +528,16 @@ class DiffusionTrainingService:
"""Hold the GPU-admission interlock across a load's guard -> arbiter -> registration.
The load guards read ``is_active()`` and only THEN acquire the arbiter and register the
- load, so a start reserving inside that gap freed residents the load had not registered
- yet and the trainer came up beside a brand-new pipeline. Registering the admission under
- the same lock ``reserve()`` uses closes it from both sides, exactly like
- ``dataset_mutation``: this raises once a start is reserved or running, and ``reserve()``
- raises while an admission is open, so neither waits on the other.
-
- The span is deliberately short. ``begin_load`` returns as soon as the load is registered
- (the download and build run on a daemon thread), and from that point
- ``_free_gpu_for_diffusion_training`` preempts the in-flight load, so holding this for the
- whole load would block starts for minutes to no purpose."""
+ load, so a start reserving inside that gap freed residents the load had not registered yet
+ and the trainer came up beside a brand-new pipeline. Registering the admission under the
+ same lock ``reserve()`` uses closes it from both sides, exactly like ``dataset_mutation``:
+ this raises once a start is reserved or running, and ``reserve()`` raises while an admission
+ is open, so neither waits on the other.
+
+ The span is deliberately short: ``begin_load`` returns as soon as the load is registered,
+ and from that point ``_free_gpu_for_diffusion_training`` preempts the in-flight load, so
+ holding this for the whole load would block starts for minutes to no purpose.
+ """
with self._lock:
if self._reserved or (self._proc is not None and self._proc.is_alive()):
raise TrainingActiveError(
@@ -671,14 +667,12 @@ class DiffusionTrainingService:
snap["active"] = self._proc is not None and self._proc.is_alive()
return snap
- # ── event pump ───────────────────────────────────────────────────────────
def _pump_loop(self, event_queue: Any, proc: Any) -> None:
while True:
try:
ev = event_queue.get(timeout = 1.0)
except Exception: # noqa: BLE001 -- Empty (timeout) or a closed queue
if not proc.is_alive():
- # Drain anything buffered, then decide if it exited cleanly.
drained = False
while True:
try:
@@ -734,15 +728,15 @@ class DiffusionTrainingService:
def _apply_discard_intent(self, *, delete: bool = True) -> None:
"""Carry out a stop-without-saving the child could not report itself.
- The trainer does this on its own completion path; a child that OOMs, is killed, or dies
- on the current step never gets there. Blocking the resume is the visible half -- the
- bundles are the other one, and they hold optimizer and scheduler state, are sizeable,
- and have no delete path in the UI once the run is marked discarded.
+ The trainer does this on its own completion path; a child that OOMs, is killed, or dies on
+ the current step never gets there. Blocking the resume is the visible half; the bundles are
+ the other one, and they hold optimizer and scheduler state, are sizeable, and have no delete
+ path in the UI once the run is marked discarded.
- ``delete`` False is the case where the child DID get there. Its cleanup restores any
- bundle this run wrote over, so the paths remembered here no longer name this run's
- bundles -- deleting them then destroys the predecessor that was just handed back, which
- is another run's resume point. The state half still applies either way.
+ ``delete`` False is the case where the child DID get there. Its cleanup restores any bundle
+ this run wrote over, so the paths remembered here no longer name this run's bundles, and
+ deleting them then destroys the predecessor that was just handed back. The state half still
+ applies either way.
"""
with self._lock:
own = list(self._own_checkpoints) if delete else []
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index b8f8468260f..deb6d86e3d5 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -1,22 +1,19 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Unsloth Training Backend
-Integrates Unsloth training with the FastAPI backend.
-"""
+"""Unsloth training backend: integrates Unsloth training with the FastAPI backend."""
import gc
import os
import sys
import types
-# Off on Linux so datasets' forked map() workers cannot deadlock; on spawn platforms map() runs in-
-# process, so the fast tokenizer's Rust threads stay on.
+# Off on Linux so datasets' forked map() workers cannot deadlock; on spawn platforms map() runs in-process, so the
+# fast tokenizer's Rust threads stay on.
os.environ["TOKENIZERS_PARALLELISM"] = "true" if sys.platform in ("win32", "darwin") else "false"
-# Spawned dataset.map() workers re-import top-level modules whose cache files import torch +
-# unsloth_zoo. Do NOT import unsloth_zoo.compiler here: it pulls in heavy torch/triton imports.
+# Spawned dataset.map() workers re-import top-level modules whose cache files import torch + unsloth_zoo. Do NOT
+# import unsloth_zoo.compiler here: it pulls in heavy torch/triton imports.
if sys.platform in ("win32", "darwin"):
_compile_cache = os.environ.get("UNSLOTH_COMPILE_LOCATION", "unsloth_compiled_cache")
if not os.path.isabs(_compile_cache):
@@ -108,11 +105,9 @@ def _build_report_targets(training_args) -> list[str] | str:
def _verbose_logging_requested() -> bool:
- """Whether `unsloth studio --verbose` is in effect.
-
- --verbose zeroes both access-log windows (unsloth_cli/commands/studio.py), and the
- env is inherited by the training subprocess, so the same pair is the signal here.
- """
+ """Whether `unsloth studio --verbose` is in effect. --verbose zeroes both access-log windows
+ (unsloth_cli/commands/studio.py), and the env is inherited by the training subprocess, so the
+ same pair is the signal here."""
def _zero(name: str) -> bool:
raw = (os.environ.get(name) or "").strip()
@@ -127,14 +122,11 @@ def _verbose_logging_requested() -> bool:
def _hf_stdout_progress_disabled() -> bool:
- """`disable_tqdm` for the HF training args, unless --verbose asked for everything.
-
- The trainer subprocess has no terminal: its stdout is teed into the server log, so
- the tqdm bar becomes a burst of carriage-return fragments that can also land inside
- a structlog JSON record and make it unparseable. Every number the bar carries is
- already published twice, as the throttled `training_progress` event added in #7087
- and as the per-step SSE stream the UI charts.
- """
+ """`disable_tqdm` for the HF training args, unless --verbose asked for everything. The trainer
+ subprocess has no terminal: its stdout is teed into the server log, so the tqdm bar becomes a
+ burst of carriage-return fragments that can also land inside a structlog JSON record and make
+ it unparseable. Every number the bar carries is already published twice, as the throttled
+ `training_progress` event added in #7087 and as the per-step SSE stream the UI charts."""
return not _verbose_logging_requested()
@@ -153,14 +145,12 @@ _RESERVED_LOG_KEYS = frozenset({"event", "level", "timestamp", "logger"})
def _drop_hf_stdout_callbacks(trainer) -> None:
- """Remove HF's stdout progress callbacks from an already-built trainer.
-
- `disable_tqdm=True` only swaps ProgressCallback for PrinterCallback, which prints a
- raw dict per step instead (`{'loss': '0.5684', 'grad_norm': ..., 'epoch': ...}`).
- Both write to the same stdout, so both have to go; Unsloth's own progress callback,
- the SSE stream and `training_progress` are unaffected. Best effort: a transformers
- build without these classes just keeps its current behaviour.
- """
+ """Remove HF's stdout progress callbacks from an already-built trainer. `disable_tqdm=True` only
+ swaps ProgressCallback for PrinterCallback, which prints a raw dict per step instead
+ (`{'loss': '0.5684', 'grad_norm': ..., 'epoch': ...}`). Both write to the same stdout, so
+ both have to go; Unsloth's own progress callback, the SSE stream and `training_progress` are
+ unaffected. Best effort: a transformers build without these classes just keeps its current
+ behaviour."""
if _verbose_logging_requested():
return
try:
@@ -175,18 +165,16 @@ def _drop_hf_stdout_callbacks(trainer) -> None:
def _spark_tts_tokenizer_kwargs(audio_type: Optional[str], lookup_name: str) -> dict:
- """``subfolder`` for a Spark-TTS repo root, empty for anything else.
-
- Only the canonical repo layout needs it: a local checkpoint or an alias that already
- names LLM/ points at the tokenizer directly.
- """
+ """``subfolder`` for a Spark-TTS repo root, empty for anything else. Only the canonical repo
+ layout needs it: a local checkpoint or an alias that already names LLM/ points at the
+ tokenizer directly."""
if audio_type != "bicodec":
return {}
name = str(lookup_name).replace("\\", "/").rstrip("/")
if name.endswith("/LLM"):
return {}
- # A cache-pinned or offline snapshot root also has an LLM/ child, and treating that as "already at
- # the tokenizer" sent AutoTokenizer at a root that holds none.
+ # A cache-pinned or offline snapshot root also has an LLM/ child, and treating that as "already at the tokenizer"
+ # sent AutoTokenizer at a root that holds none.
if os.path.isdir(os.path.join(lookup_name, "LLM")):
return {"subfolder": "LLM"}
# A local checkpoint that carries its own tokenizer is already the right directory.
@@ -198,27 +186,27 @@ def _spark_tts_tokenizer_kwargs(audio_type: Optional[str], lookup_name: str) ->
# Enough rows to see past a leading null or malformed value, few enough to stay cheap on a streamed dataset.
_AUDIO_SNIFF_ROWS = 16
-# Kept in step with detect_multimodal_dataset, so the veto answers False only about the very columns
-# that set the flag it is vetoing.
+# Kept in step with detect_multimodal_dataset, so the veto answers False only about the very columns that set the flag
+# it is vetoing.
_AUDIO_COLUMN_KEYWORDS = ("audio", "speech", "wav", "waveform", "sound")
def _dataset_has_audio_column(dataset) -> Optional[bool]:
"""Whether `dataset` really carries audio. None when it cannot be told.
- `is_dataset_audio` comes from the format check's `is_audio`, set by a column-NAME
- keyword match that never inspects the value, so a text dataset with a column called
- `audio` holding prose reports audio. Refusing such a run would take away a text path
- that works today, so the dataset itself gets the last word.
+ `is_dataset_audio` comes from the format check's `is_audio`, set by a column-NAME keyword match
+ that never inspects the value, so a text dataset with a column called `audio` holding prose
+ reports audio. Refusing such a run would take away a text path that works today, so the dataset
+ itself gets the last word.
- An ``Audio`` feature is audio without reading a row. Otherwise look at the values: an
- audio column loaded from JSON/CSV is a ``Value("string")`` of paths until the
- preprocessor casts it (``_preprocess_snac_dataset`` does exactly that), so trusting the
- schema would call a real audio dataset textual.
+ An ``Audio`` feature is audio without reading a row. Otherwise look at the values: an audio
+ column loaded from JSON/CSV is a ``Value("string")`` of paths until the preprocessor casts it
+ (``_preprocess_snac_dataset`` does exactly that), so trusting the schema would call a real audio
+ dataset textual.
- None for a DatasetDict, a schema-less iterable dataset, or an unreadable row: an
- unreadable model probe is still the likelier explanation, so the caller keeps refusing
- unless this says False outright.
+ None for a DatasetDict, a schema-less iterable dataset, or an unreadable row: an unreadable
+ model probe is still the likelier explanation, so the caller keeps refusing unless this says
+ False outright.
"""
try:
from datasets.features.audio import Audio
@@ -234,9 +222,9 @@ def _dataset_has_audio_column(dataset) -> Optional[bool]:
except Exception: # noqa: BLE001 - a mapping that is not a features dict
return None
- # Several rows, not one: a JSON/CSV audio dataset can carry a null or malformed first value and real paths after it.
- # Only an audio-NAMED column can answer False: a transcript is populated in every row of a path-
- # backed audio dataset. No evidence stays None.
+ # Several rows, not one: a JSON/CSV audio dataset can carry a null or malformed first value and real paths after
+ # it. Only an audio-NAMED column can answer False: a transcript is populated in every row of a path-backed audio
+ # dataset. No evidence stays None.
try:
from utils.datasets.format_detection import (
_AUDIO_EXTENSIONS,
@@ -268,10 +256,6 @@ def _dataset_has_audio_column(dataset) -> Optional[bool]:
class UnslothTrainer:
- """
- Unsloth Training Backend
- """
-
def __new__(cls, *args, **kwargs):
if cls is UnslothTrainer and should_use_mlx_training_backend():
return create_mlx_trainer_adapter(*args, **kwargs)
@@ -325,14 +309,11 @@ class UnslothTrainer:
local_files_only: bool = False,
model_revision: Optional[str] = None,
) -> None:
- """Lightweight detection and tokenizer load — no model weights, no VRAM.
-
- Sets is_vlm, _audio_type, is_audio_vlm, model_name and loads a lightweight
- tokenizer for dataset formatting. Call before load_and_format_dataset() so
- the dataset is processed before the training model loads (avoids VRAM
- contention). load_model() later re-detects and loads the full model +
- tokenizer, overwriting the lightweight one set here.
- """
+ """Lightweight detection and tokenizer load: no model weights, no VRAM. Sets is_vlm,
+ _audio_type, is_audio_vlm, model_name and loads a lightweight tokenizer for dataset
+ formatting. Call before load_and_format_dataset() so the dataset is processed before the
+ training model loads (avoids VRAM contention). load_model() later re-detects and loads
+ the full model + tokenizer, overwriting the lightweight one set here."""
self.model_name = model_name
self.max_seq_length = max_seq_length
self.trust_remote_code = trust_remote_code
@@ -341,8 +322,8 @@ class UnslothTrainer:
if hf_token:
os.environ["HF_TOKEN"] = hf_token
- # Checked, because an unreadable tokenizer_config.json (gated, offline, or a weights-only cache)
- # otherwise reads as "not an audio model" and sends a TTS run down the text path.
+ # Checked, because an unreadable tokenizer_config.json (gated, offline, or a weights-only cache) otherwise
+ # reads as "not an audio model" and sends a TTS run down the text path.
self._audio_type, self._audio_type_known = detect_audio_type_checked(
lookup_name,
hf_token,
@@ -381,8 +362,8 @@ class UnslothTrainer:
self.is_vlm,
)
- # Load tokenizer/processor (CPU only, no VRAM) Whisper needs AutoProcessor; others AutoTokenizer (CSM
- # loads its own inline).
+ # Load tokenizer/processor (CPU only, no VRAM). Whisper needs AutoProcessor; others AutoTokenizer (CSM loads
+ # its own inline).
def _load_tokenizer_for_detected_type():
if self._audio_type == "whisper":
from transformers import AutoProcessor
@@ -406,9 +387,8 @@ class UnslothTrainer:
**_spark_tts_tokenizer_kwargs(self._audio_type, lookup_name),
)
- # The probe and the tokenizer load are separate reads of the same repo, so a transient 5xx can
- # leave the probe inconclusive while the read after it succeeds; detect_audio_type_checked caches
- # only definitive results.
+ # The probe and the tokenizer load are separate reads of the same repo, so a transient 5xx can leave the probe
+ # inconclusive while the read after it succeeds; detect_audio_type_checked caches only definitive results.
def _retry_audio_detection() -> bool:
"""Re-probe an inconclusive type. True if the answer changed."""
if self._audio_type_known:
@@ -438,8 +418,8 @@ class UnslothTrainer:
)
return self._audio_type != previous_type
- # An inconclusive probe leaves _audio_type None, so a Spark-TTS repo is read at its tokenizer-less
- # root; re-probe, or the retry below is unreachable for exactly those models.
+ # An inconclusive probe leaves _audio_type None, so a Spark-TTS repo is read at its tokenizer-less root;
+ # re-probe, or the retry below is unreachable for exactly those models.
try:
_load_tokenizer_for_detected_type()
except Exception:
@@ -454,9 +434,9 @@ class UnslothTrainer:
logger.info("Pre-loaded tokenizer for %s", model_name)
- # A retry that changes the answer leaves the wrong object in self.tokenizer: whisper needs an
- # AutoProcessor (_preprocess_whisper_dataset reads .feature_extractor and .tokenizer off it) and
- # Spark-TTS its LLM/ subfolder.
+ # A retry that changes the answer leaves the wrong object in self.tokenizer: whisper needs an AutoProcessor
+ # (_preprocess_whisper_dataset reads .feature_extractor and .tokenizer off it) and Spark-TTS its LLM/
+ # subfolder.
if _retry_audio_detection():
_load_tokenizer_for_detected_type()
logger.info(
@@ -466,7 +446,6 @@ class UnslothTrainer:
)
def add_progress_callback(self, callback: Callable[[TrainingProgress], None]):
- """Add callback for training progress updates"""
self.progress_callbacks.append(callback)
def _update_progress(self, **kwargs):
@@ -504,8 +483,8 @@ class UnslothTrainer:
trainer_ref = self
class _ProgressCallback(TrainerCallback):
- # Republished, throttled: without HF's tqdm bar a long eval looks stalled between the last step log
- # and the eval result.
+ # Republished, throttled: without HF's tqdm bar a long eval looks stalled between the last step log and
+ # the eval result.
_eval_seen = 0
_eval_last_report = 0.0
@@ -641,9 +620,8 @@ class UnslothTrainer:
*,
extra_args = None,
):
- """Build the training args dict for audio branches: common config (batch
- size, lr, warmup, fp16/bf16, etc.) with per-branch overrides via extra_args.
- """
+ """Build the training args dict for audio branches: common config (batch size, lr, warmup,
+ fp16/bf16, etc.) with per-branch overrides via extra_args."""
batch_size = training_args.get("batch_size", 2)
gradient_accumulation_steps = training_args.get("gradient_accumulation_steps", 4)
warmup_steps_val = training_args.get("warmup_steps", 5)
@@ -726,13 +704,10 @@ class UnslothTrainer:
)
def _cleanup_audio_artifacts(self):
- """Remove sys.path/sys.modules entries from previous audio preprocessing.
-
- After audio training, codec source dirs and heavy
- modules (snac, whisper, sparktts, outetts) linger; the next
- dataset.map(num_proc=N) forks children that inherit this stale state and
- deadlock.
- """
+ """Remove sys.path/sys.modules entries from previous audio preprocessing. After audio
+ training, codec source dirs and heavy modules (snac, whisper, sparktts, outetts) linger;
+ the next dataset.map(num_proc=N) forks children that inherit this stale state and
+ deadlock."""
audio_paths = []
if self._spark_tts_code_dir:
audio_paths.append(str(self._spark_tts_code_dir))
@@ -763,10 +738,8 @@ class UnslothTrainer:
dataset,
custom_format_mapping: dict = None,
):
- """Resolve audio/text/speaker columns from user mapping or fallback.
-
- Returns dict with keys audio_col, text_col, speaker_col (may be None).
- """
+ """Resolve audio/text/speaker columns from user mapping or fallback. Returns dict with keys
+ audio_col, text_col, speaker_col (may be None)."""
cols = dataset.column_names
if custom_format_mapping:
@@ -857,8 +830,8 @@ class UnslothTrainer:
_preserve = ["Unsloth*Trainer.py"] if sys.platform in ("win32", "darwin") else None
clear_unsloth_compiled_cache(preserve_patterns = _preserve)
- # Checked: this reassigns _audio_type, so an unchecked answer would leave the flag describing the
- # previous probe.
+ # Checked: this reassigns _audio_type, so an unchecked answer would leave the flag describing the previous
+ # probe.
self._audio_type, self._audio_type_known = detect_audio_type_checked(
lookup_name,
hf_token,
@@ -956,8 +929,8 @@ class UnslothTrainer:
f"Using device_map='{device_map}' ({get_visible_gpu_count()} GPU(s) visible)"
)
- # ROCm without native bf16 (e.g. RDNA2/gfx103x) dies with an LLVM error on the first bf16 kernel
- # when dtype=None picks bf16, so force float16; NVIDIA keeps None so T4/V100 are not coerced.
+ # ROCm without native bf16 (e.g. RDNA2/gfx103x) dies with an LLVM error on the first bf16 kernel when
+ # dtype=None picks bf16, so force float16; NVIDIA keeps None so T4/V100 are not coerced.
_is_rocm = (
bool(getattr(torch.version, "hip", None)) or "rocm" in torch.__version__.lower()
)
@@ -1024,13 +997,11 @@ class UnslothTrainer:
logger.info(f"Loaded {self._audio_type} audio model (FastLanguageModel)")
elif self._audio_type == "bicodec":
- # Download the full repo (sparktts + BiCodec weights) but load only the LLM subfolder; model_name is
- # "Spark-TTS-0.5B/LLM" or "unsloth/Spark-TTS-0.5B".
- # Use FastModel.get_peft_model (codec audio + audio VLM)
- # Audio VLM (e.g. Gemma 3N): FastModel returns (model, processor).
- # OuteTTS: uses FastModel (not FastLanguageModel) with load_in_4bit=False
- # Spark-TTS: download the full repo (sparktts + BiCodec weights), load only the LLM subfolder.
- # model_name is "Spark-TTS-0.5B/LLM" (YAML mapping) or "unsloth/Spark-TTS-0.5B".
+ # Branch selection for the audio families. Audio VLM (e.g. Gemma 3N) and the codec models use
+ # FastModel.get_peft_model, and FastModel returns (model, processor) for the audio VLM. OuteTTS uses
+ # FastModel (not FastLanguageModel) with load_in_4bit=False. Spark-TTS downloads the full repo
+ # (sparktts + BiCodec weights) but loads only the LLM subfolder, so model_name is "Spark-TTS-0.5B/LLM"
+ # (YAML mapping) or "unsloth/Spark-TTS-0.5B".
from unsloth import FastModel
from huggingface_hub import snapshot_download
@@ -1243,9 +1214,6 @@ class UnslothTrainer:
use_dora: bool = False,
modules_to_save: list = None,
) -> bool:
- """
- Prepare model for training (with optional LoRA).
- """
try:
if self.model is None:
raise ValueError("Model not loaded. Call load_model() first.")
@@ -1460,13 +1428,10 @@ class UnslothTrainer:
return False
def _apply_csm_forward_fix(self):
- """Monkey-patch CsmForConditionalGeneration.forward for depth decoder kwargs.
-
- The original forward leaks raw **kwargs (num_items_in_batch, causal_mask,
- etc.) from Trainer/PEFT into the depth decoder, causing
- depth_decoder_loss=None and a 'Tensor + NoneType' crash. Patch at both
- instance and class level and strip non-TransformersKwargs params.
- """
+ """Monkey-patch CsmForConditionalGeneration.forward for depth decoder kwargs. The original
+ forward leaks raw **kwargs (num_items_in_batch, causal_mask, etc.) from Trainer/PEFT into
+ the depth decoder, causing depth_decoder_loss=None and a 'Tensor + NoneType' crash. Patch
+ at both instance and class level and strip non-TransformersKwargs params."""
import torch
import torch.nn as nn
from transformers.models.csm.modeling_csm import (
@@ -1641,8 +1606,8 @@ class UnslothTrainer:
trust_remote_code = getattr(self, "trust_remote_code", False),
)
- # Some fine-tuned models save pad_to_multiple_of in tokenizer_config.json and _merge_kwargs leaks it
- # into audio_kwargs, where EncodecFeatureExtractor rejects it.
+ # Some fine-tuned models save pad_to_multiple_of in tokenizer_config.json and _merge_kwargs leaks it into
+ # audio_kwargs, where EncodecFeatureExtractor rejects it.
processor.tokenizer.init_kwargs.pop("pad_to_multiple_of", None)
resolved = self._resolve_audio_columns(dataset, custom_format_mapping)
@@ -1747,11 +1712,9 @@ class UnslothTrainer:
dataset,
custom_format_mapping = None,
):
- """Format dataset as audio chat messages for multimodal models (e.g. Gemma 3N).
-
- Expects columns audio (Audio), text (str). Produces a messages column
- with system/user/assistant chat format.
- """
+ """Format dataset as audio chat messages for multimodal models (e.g. Gemma 3N). Expects
+ columns audio (Audio), text (str). Produces a messages column with system/user/assistant
+ chat format."""
from datasets import Audio
resolved = self._resolve_audio_columns(dataset, custom_format_mapping)
@@ -1808,12 +1771,10 @@ class UnslothTrainer:
dataset,
custom_format_mapping = None,
):
- """Preprocess dataset for Orpheus TTS training with SNAC codec.
-
- Mirrors Orpheus_(3B)-TTS.ipynb: encode audio with SNAC (24kHz, 3
- hierarchical layers), interleave 7 codes per frame, wrap with Orpheus
- special tokens, train on full sequence (no label masking).
- """
+ """Preprocess dataset for Orpheus TTS training with SNAC codec. Mirrors
+ Orpheus_(3B)-TTS.ipynb: encode audio with SNAC (24kHz, 3 hierarchical layers), interleave
+ 7 codes per frame, wrap with Orpheus special tokens, train on full sequence (no label
+ masking)."""
import torch
import torchaudio.transforms as T
@@ -1989,12 +1950,9 @@ class UnslothTrainer:
dataset,
custom_format_mapping = None,
):
- """Preprocess dataset for Spark-TTS training with BiCodec tokenizer.
-
- Mirrors Spark_TTS_(0_5B).ipynb: encode audio with BiCodec (semantic +
- global tokens), format as special-token text strings for SFTTrainer
- with dataset_text_field="text".
- """
+ """Preprocess dataset for Spark-TTS training with BiCodec tokenizer. Mirrors
+ Spark_TTS_(0_5B).ipynb: encode audio with BiCodec (semantic + global tokens), format as
+ special-token text strings for SFTTrainer with dataset_text_field="text"."""
import torch
import numpy as np
import torchaudio.transforms as T
@@ -2024,8 +1982,8 @@ class UnslothTrainer:
f"BiCodec dataset needs 'audio' and 'text' columns, got: {dataset.column_names}"
)
- # Cast so datasets 4.x AudioDecoder objects decode to dicts; no resample here, since BiCodec's
- # target_sr may differ.
+ # Cast so datasets 4.x AudioDecoder objects decode to dicts; no resample here, since BiCodec's target_sr may
+ # differ.
from datasets import Audio
dataset = dataset.cast_column(audio_col, Audio())
@@ -2183,13 +2141,10 @@ class UnslothTrainer:
dataset,
custom_format_mapping = None,
):
- """Preprocess dataset for OuteTTS training with DAC codec.
-
- Mirrors Oute_TTS_(1B).ipynb DataCreationV3: Whisper for word timings,
- OuteTTS AudioProcessor for speaker representations, PromptProcessor for
- training prompts. Outputs text strings for SFTTrainer with
- dataset_text_field="text".
- """
+ """Preprocess dataset for OuteTTS training with DAC codec. Mirrors Oute_TTS_(1B).ipynb
+ DataCreationV3: Whisper for word timings, OuteTTS AudioProcessor for speaker
+ representations, PromptProcessor for training prompts. Outputs text strings for
+ SFTTrainer with dataset_text_field="text"."""
import io
import tempfile
import torch
@@ -2438,13 +2393,10 @@ class UnslothTrainer:
custom_format_mapping = None,
eval_dataset = None,
):
- """Preprocess dataset for Whisper speech-to-text training.
-
- Mirrors Whisper.ipynb: extract audio features with Whisper's feature
- extractor, tokenize text labels. Returns (train_data, eval_data),
- each a list of dicts with 'input_features' and 'labels'. The 6% carve-out
- is only the fallback for when ``eval_dataset`` is absent.
- """
+ """Preprocess dataset for Whisper speech-to-text training. Mirrors Whisper.ipynb: extract
+ audio features with Whisper's feature extractor, tokenize text labels. Returns
+ (train_data, eval_data), each a list of dicts with 'input_features' and 'labels'. The 6%
+ carve-out is only the fallback for when ``eval_dataset`` is absent."""
from datasets import Audio
WHISPER_SAMPLE_RATE = 16000
@@ -2610,33 +2562,28 @@ class UnslothTrainer:
max_train_rows: Optional[int] = None,
max_train_rows_seed: int = 3407,
) -> Optional[tuple]:
- """
- Load and prepare a dataset for training.
+ """Load and prepare a dataset for training.
- Strategy: format first, then split — ensures both train and eval
- portions are formatted and templated.
-
- max_train_rows bounds the rows kept before formatting, for a max_steps
+ Strategy: format first, then split, which ensures both train and eval portions are formatted
+ and templated. ``max_train_rows`` bounds the rows kept before formatting, for a max_steps
run that cannot reach the whole dataset; see max_steps_dataset_rows.
- Returns (dataset_info, eval_dataset) or None on error; eval_dataset
- may be None if no eval split is available.
-
- hf_token must reach every load_dataset and get_dataset_split_names call below,
- or a gated dataset is read under the ambient HF_TOKEN instead of the request.
+ Returns (dataset_info, eval_dataset) or None on error; eval_dataset may be None if no eval
+ split is available. hf_token must reach every load_dataset and get_dataset_split_names call
+ below, or a gated dataset is read under the ambient HF_TOKEN instead of the request.
"""
from core.training.s3_dataset import S3DownloadCancelled
- # datasets exposes no env var, so its bars can only be quieted through the class, and this is the
- # first point before any load_dataset() in either branch.
+ # datasets exposes no env var, so its bars can only be quieted through the class, and this is the first point
+ # before any load_dataset() in either branch.
try:
from loggers.config import quiet_third_party_progress_bars
quiet_third_party_progress_bars()
except Exception: # noqa: BLE001 - never let log tidying stop a run
pass
- # An Audio column decodes inside load_dataset() below, and this worker starts without the shim the
- # API process installs, so the load raised datasets' own "please install torchcodec".
+ # An Audio column decodes inside load_dataset() below, and this worker starts without the shim the API process
+ # installs, so the load raised datasets' own "please install torchcodec".
try:
ensure_audio_decoding()
except Exception: # noqa: BLE001 - never let a broken librosa stop a text run
@@ -2714,8 +2661,8 @@ class UnslothTrainer:
logger.info(f"Downloaded {len(local_datasets)} file(s) from S3\n")
if local_datasets:
- # load_dataset() is Arrow-backed; an in-memory Dataset.from_list() has no cache and forces
- # num_proc=1 during tokenization.
+ # load_dataset() is Arrow-backed; an in-memory Dataset.from_list() has no cache and forces num_proc=1
+ # during tokenization.
all_files = self._resolve_local_files(local_datasets)
if all_files:
@@ -2791,8 +2738,8 @@ class UnslothTrainer:
# With a slice end, stream only the needed rows and materialize them rather than downloading
# everything.
_slice_start = dataset_slice_start or 0
- # streaming=True rejects HF slice syntax with "Bad split", so fall back to the regular download path
- # when train_split already carries a slice.
+ # streaming=True rejects HF slice syntax with "Bad split", so fall back to the regular download
+ # path when train_split already carries a slice.
_split_has_slice = (train_split or "").find("[") != -1
dataset = None
if dataset_local_files_only:
@@ -2900,9 +2847,8 @@ class UnslothTrainer:
eval_load_kwargs["token"] = hf_token
if dataset_streaming:
- # load_dataset(streaming=True) returns an IterableDataset without validating the
- # name, so a typo
- # would only surface on the first eval batch.
+ # load_dataset(streaming=True) returns an IterableDataset without validating the name, so
+ # a typo would only surface on the first eval batch.
from datasets import get_dataset_split_names
probe_kwargs = {"path": dataset_source}
@@ -2919,8 +2865,8 @@ class UnslothTrainer:
f"Could not list splits for '{dataset_source}' "
f"to validate eval_split='{eval_split}': {probe_err}"
)
- # Streaming rejects HF slice syntax and the request validator blocks bracketed
- # streaming splits, so eval_split is always a bare split name here.
+ # Streaming rejects HF slice syntax and the request validator blocks bracketed streaming
+ # splits, so eval_split is always a bare split name here.
if eval_split not in available_splits:
raise ValueError(
f"Requested eval split '{eval_split}' not found in "
@@ -2928,9 +2874,8 @@ class UnslothTrainer:
f"{available_splits}"
)
eval_dataset = load_dataset(**eval_load_kwargs, streaming = True)
- # Streaming eval has no __len__; .take() stays lazy and survives the later format
- # and raw-text map()
- # passes.
+ # Streaming eval has no __len__; .take() stays lazy and survives the later format and
+ # raw-text map() passes.
if not hasattr(eval_dataset, "__len__"):
eval_dataset = eval_dataset.take(STREAMING_EVAL_MAX_SAMPLES)
logger.info(
@@ -3041,8 +2986,8 @@ class UnslothTrainer:
if dataset is None:
raise ValueError("No dataset provided")
- # Streaming already sliced lazily via skip()/take(); the non-streaming path fetched end+1 rows and
- # is trimmed here.
+ # Streaming already sliced lazily via skip()/take(); the non-streaming path fetched end+1 rows and is
+ # trimmed here.
if (not dataset_streaming) and (
dataset_slice_start is not None or dataset_slice_end is not None
):
@@ -3059,9 +3004,9 @@ class UnslothTrainer:
status_message = f"Sliced dataset to {len(dataset)} rows (indices {start}-{end})"
)
- # Bound before the formatting and tokenization passes, and skipped when streaming or when the user
- # named an explicit range, including a bracketed split like train[1000:2000]: those rows are
- # already what they asked for.
+ # Bound before the formatting and tokenization passes, and skipped when streaming or when the user named
+ # an explicit range, including a bracketed split like train[1000:2000]: those rows are already what they
+ # asked for.
if (
(not dataset_streaming)
and dataset_slice_start is None
@@ -3090,10 +3035,10 @@ class UnslothTrainer:
# No separate HF eval split - caller handles programmatic splitting
return None
+ # An inconclusive probe must not read as "not an audio model": falling through lands on the text path,
+ # which fails later with a column-mapping complaint. _dataset_has_audio_column is the tiebreaker because
+ # _is_dataset_audio is true on a column-NAME match alone; raw/CPT is exempt.
# ========== AUDIO MODELS: custom preprocessing ==========
- # An inconclusive probe must not read as "not an audio model": falling through lands on the text
- # path, which fails later with a column-mapping complaint. _dataset_has_audio_column is the
- # tiebreaker because _is_dataset_audio is true on a column-NAME match alone; raw/CPT is exempt.
if (
not self._audio_type
and not getattr(self, "_audio_type_known", True)
@@ -3162,12 +3107,11 @@ class UnslothTrainer:
),
)
- # ========== RAW TEXT BYPASS ==========
if raw_text_mode:
- # Say which variable said so: a stale size from an earlier mpirun or an HPC container image
- # reads as a multi-rank launch on a one-process machine, and the only symptom is this run being
- # told it makes several passes. The row bound already trusts the same variables; what was
- # missing was a way to see them.
+ # Say which variable said so: a stale size from an earlier mpirun or an HPC container image reads as a
+ # multi-rank launch on a one-process machine, and the only symptom is this run being told it makes
+ # several passes. The row bound already trusts the same variables; what was missing was a way to see
+ # them.
logger.info(
f"{_raw_mode_label().capitalize()} mode: bypassing chat template, "
"using raw text\n"
@@ -3360,10 +3304,8 @@ class UnslothTrainer:
return None
def _resolve_eval_split_from_dataset(self, dataset) -> Optional[tuple]:
- """Split a dataset into train and eval portions.
-
- Returns (train_dataset, eval_dataset), or None if too small.
- """
+ """Split a dataset into train and eval portions. Returns (train_dataset, eval_dataset), or
+ None if too small."""
from core.training.eval_dataset import (
MIN_TOTAL_ROWS_FOR_EVAL,
split_dataset_for_evaluation,
@@ -3414,8 +3356,6 @@ class UnslothTrainer:
tensorboard_dir: str | None = None,
**kwargs,
) -> bool:
- """Start training in a separate thread"""
-
if self.is_training:
logger.warning("Training already in progress")
return False
@@ -3424,8 +3364,8 @@ class UnslothTrainer:
self._update_progress(error = "Model not loaded")
return False
- # Pre-import heavy transformers modules on the main thread: Unsloth's patched_import is not thread-
- # safe with importlib's cache.
+ # Pre-import heavy transformers modules on the main thread: Unsloth's patched_import is not thread-safe with
+ # importlib's cache.
import transformers # noqa: F401 - ensures submodules are cached
from transformers import ( # noqa: F401
Trainer as _HFTrainer,
@@ -3509,14 +3449,11 @@ class UnslothTrainer:
raw_text_mode: bool,
is_deepseek_ocr: bool,
):
- """Switch the plain-text path to lazy, worker-side tokenization.
-
- Mutates ``config_args`` and the ``dataset`` wrapper in place when the run
- qualifies, and leaves both untouched otherwise.
- ``self._online_eval_dataset`` returns the transformed eval split, and
- ``self._online_prewarm_batches`` tells ``_preflight_first_batch`` how deep
- to prime. Never raises: any failure degrades to the eager path.
- """
+ """Switch the plain-text path to lazy, worker-side tokenization. Mutates ``config_args`` and
+ the ``dataset`` wrapper in place when the run qualifies, and leaves both untouched
+ otherwise. ``self._online_eval_dataset`` returns the transformed eval split, and
+ ``self._online_prewarm_batches`` tells ``_preflight_first_batch`` how deep to prime.
+ Never raises: any failure degrades to the eager path."""
from utils.datasets.online_tokenization import (
OnlineTokenizationDecision,
attach_online_tokenization,
@@ -3536,16 +3473,16 @@ class UnslothTrainer:
if max_steps > 0:
try:
rows = len(train_dataset)
- # Every launcher variable, not WORLD_SIZE alone: Open MPI sets OMPI_COMM_WORLD_SIZE, Hydra/Intel
- # MPI PMI_SIZE, mlx.launch's CUDA-only NCCL backend MLX_WORLD_SIZE, and LOCAL_WORLD_SIZE is
- # defensive since torchrun sets both. Reading one variable calls an mpirun launch single-process
- # or raises on junk like int("auto"), leaving resolved_epochs None. Env-only, deliberately NOT
- # worker.py's _data_parallel_world_size, which also counts visible CUDA devices: Unsloth's
- # multi-GPU load is a sharding device_map, model-parallel to transformers.
+ # Every launcher variable, not WORLD_SIZE alone: Open MPI sets OMPI_COMM_WORLD_SIZE, Hydra/Intel MPI
+ # PMI_SIZE, mlx.launch's CUDA-only NCCL backend MLX_WORLD_SIZE, and LOCAL_WORLD_SIZE is defensive
+ # since torchrun sets both. Reading one variable calls an mpirun launch single-process or raises on
+ # junk like int("auto"), leaving resolved_epochs None. Env-only, deliberately NOT worker.py's
+ # _data_parallel_world_size, which also counts visible CUDA devices: Unsloth's multi-GPU load is a
+ # sharding device_map, model-parallel to transformers.
world_size = world_size_from_env()
if world_size > 1:
- # Say which variable said so: a stale size from an earlier mpirun reads as a multi-rank launch, and
- # this veto is the only symptom.
+ # Say which variable said so: a stale size from an earlier mpirun reads as a multi-rank launch,
+ # and this veto is the only symptom.
logger.info(
f"Launcher environment reports {world_size} data-parallel "
f"processes ({world_size_env_report()}); a step-capped run "
@@ -3596,9 +3533,8 @@ class UnslothTrainer:
try:
text_field = config_args.get("dataset_text_field", "text") or "text"
max_length = int(config_args.get("max_seq_length") or 2048)
- # The generated __init__ clamps max_seq_length to the model's cap and derives max_length from it,
- # but runs after this: apply the same cap here or the transform truncates wider than the eager map
- # it replaces.
+ # The generated __init__ clamps max_seq_length to the model's cap and derives max_length from it, but runs
+ # after this: apply the same cap here or the transform truncates wider than the eager map it replaces.
model_cap = getattr(self.model, "max_seq_length", None)
try:
if model_cap is not None and 0 < int(model_cap) < max_length:
@@ -3652,15 +3588,12 @@ class UnslothTrainer:
return OnlineTokenizationDecision(enabled = False, reason = f"setup error: {exc}")
def _release_online_dataloader(self) -> None:
- """Shut down the online path's persistent DataLoader workers.
-
- Persistence is what carries the prewarm barrier's workers into train();
- nothing else drops them, so they would stay resident through merging,
- quantization and GGUF export -- the most memory-hungry part of a run --
- each a fork of a process that had already initialised CUDA. Called from a
- finally (so it covers preflight errors and a raising train()), and
- idempotent because those paths reach it twice.
- """
+ """Shut down the online path's persistent DataLoader workers. Persistence is what carries
+ the prewarm barrier's workers into train(); nothing else drops them, so they would stay
+ resident through merging, quantization and GGUF export -- the most memory-hungry part of
+ a run -- each a fork of a process that had already initialised CUDA. Called from a
+ finally (so it covers preflight errors and a raising train()), and idempotent because
+ those paths reach it twice."""
if not getattr(self, "_online_prewarm_batches", 0):
return
trainer = getattr(self, "trainer", None)
@@ -3672,30 +3605,31 @@ class UnslothTrainer:
except Exception as exc: # noqa: BLE001 - cleanup must never fail a finished run
logger.warning(f"Online tokenization worker shutdown failed: {exc}")
return
- # _online_prewarm_batches records how the run was configured and the A/B harness reads it back; a
- # second call is a no-op.
+ # _online_prewarm_batches records how the run was configured and the A/B harness reads it back; a second call
+ # is a no-op.
if released:
logger.info(f"Online tokenization: shut down {released} DataLoader workers\n")
def _preflight_first_batch(self) -> Optional[str]:
- """Validate the first real batch before train(). A base model whose chat
- template renders empty yields empty float32 input_ids that crash the
- embedding on step 1; catch it here. Returns None for a valid batch.
-
- On the online path this doubles as the prewarm barrier: enough
- microbatches for the first optimizer step and the DataLoader's in-flight
- depth are pulled through here, so step 1 never waits on a cold worker.
-
- The workers survive, not the batches: ``train()`` calls ``iter()`` again
- and torch answers with ``_iterator._reset(...)``, restarting the sampler
- at row 0, so these batches are tokenized twice. No rows are lost, and what
- it buys is forked workers past their first import and tokenizer touch plus
- a warm page cache."""
+ """Validate the first real batch before train(). A base model whose chat template renders empty
+ yields empty float32 input_ids that crash the embedding on step 1; catch it here. Returns
+ None for a valid batch.
+
+ On the online path this doubles as the prewarm barrier: enough microbatches for the first
+ optimizer step and the DataLoader's in-flight depth are pulled through here, so step 1 never
+ waits on a cold worker.
+
+ The workers survive, not the batches: ``train()`` calls ``iter()`` again and torch answers
+ with ``_iterator._reset(...)``, restarting the sampler at row 0, so these batches are
+ tokenized twice. No rows are lost, and what it buys is forked workers past their first
+ import and tokenizer touch plus a warm page cache.
+ """
prewarm = int(getattr(self, "_online_prewarm_batches", 0) or 0)
if prewarm:
from utils.datasets.online_tokenization import memoize_train_dataloader
- # Hold the loader this barrier fills, or train() forks fresh workers and everything drained here is wasted.
+ # Hold the loader this barrier fills, or train() forks fresh workers and everything drained here is
+ # wasted.
memoize_train_dataloader(self.trainer)
try:
loader = self.trainer.get_train_dataloader()
@@ -3706,8 +3640,8 @@ class UnslothTrainer:
next(iterator)
except StopIteration:
break
- # Drop the local names: on the eager path that tears the loader down, while on the online path the
- # memo still holds it so the workers survive.
+ # Drop the local names: on the eager path that tears the loader down, while on the online path the memo
+ # still holds it so the workers survive.
del iterator, loader
except StopIteration:
return (
@@ -3755,17 +3689,14 @@ class UnslothTrainer:
)
def _train_worker(self, dataset: Dataset | dict, **training_args):
- """Worker function for training (runs in separate thread).
-
- ``dataset`` is either a raw ``datasets.Dataset`` (audio preprocessing
- paths such as CSM / Whisper / SNAC / Audio-VLM) or a ``dict`` wrapper
- returned by ``format_and_template_dataset`` (text and image VLM paths).
- Streaming HF datasets arrive wrapped in the latter ``dict`` — they are
- never passed as a bare ``IterableDataset``.
- """
+ """Worker function for training (runs in a separate thread). ``dataset`` is either a raw
+ ``datasets.Dataset`` (audio preprocessing paths such as CSM / Whisper / SNAC / Audio-VLM)
+ or a ``dict`` wrapper returned by ``format_and_template_dataset`` (text and image VLM
+ paths). Streaming HF datasets arrive wrapped in the latter ``dict``, never as a bare
+ ``IterableDataset``."""
try:
- # On spawn platforms, put the compiled-cache dirs on sys.path/PYTHONPATH before any dataset.map()
- # so spawned workers can import e.g. UnslothSFTTrainer.
+ # On spawn platforms, put the compiled-cache dirs on sys.path/PYTHONPATH before any dataset.map() so
+ # spawned workers can import e.g. UnslothSFTTrainer.
if sys.platform in ("win32", "darwin"):
from utils.cache_cleanup import register_compiled_cache_on_path
register_compiled_cache_on_path()
@@ -3812,8 +3743,6 @@ class UnslothTrainer:
self.trainer.add_callback(self._create_progress_callback())
# Unsloth publishes progress itself, so HF's stdout callbacks are pure duplication in a log that has
# no terminal; --verbose keeps them.
- # Unsloth publishes progress itself, so HF's stdout callbacks are pure duplication in a log that
- # has no terminal. --verbose keeps them.
_drop_hf_stdout_callbacks(self.trainer)
batch_size = training_args.get("batch_size", 2)
@@ -3939,7 +3868,6 @@ class UnslothTrainer:
f"Audio training for '{self._audio_type}' not yet implemented"
)
- # ========== DATA COLLATOR SELECTION ==========
model_name_lower = self.model_name.lower()
is_deepseek_ocr = "deepseek" in model_name_lower and "ocr" in model_name_lower
@@ -3969,8 +3897,8 @@ class UnslothTrainer:
logger.info("Configuring DeepSeek OCR data collator...\n")
FastVisionModel.for_training(self.model)
- # (image_size, base_size, crop_mode) is a coupled preset: changing image_size alone desyncs the per-
- # crop grid from num_queries.
+ # (image_size, base_size, crop_mode) is a coupled preset: changing image_size alone desyncs the
+ # per-crop grid from num_queries.
if training_args.get("vision_image_size") is not None:
logger.info(
"Vision image resize ignored for DeepSeek OCR "
@@ -4048,7 +3976,6 @@ class UnslothTrainer:
)
logger.info("Vision data collator configured\n")
- # ========== TRAINING CONFIGURATION ==========
warmup_steps_val = training_args.get("warmup_steps", None)
warmup_ratio_val = training_args.get("warmup_ratio", None)
@@ -4071,9 +3998,9 @@ class UnslothTrainer:
"report_to": _build_report_targets(training_args),
"disable_tqdm": _hf_stdout_progress_disabled(),
"include_num_input_tokens_seen": True,
- # serial_as_none = False: this is a config boundary, not a map() call site. The audio paths ask
- # for 1 to keep dataset workers off a process holding audio/CUDA state; pass None otherwise, so
- # the shared policy sizes it from CPU affinity and cgroup quota rather than host os.cpu_count().
+ # serial_as_none = False: this is a config boundary, not a map() call site. The audio paths ask for 1
+ # to keep dataset workers off a process holding audio/CUDA state; pass None otherwise, so the shared
+ # policy sizes it from CPU affinity and cgroup quota rather than host os.cpu_count().
"dataset_num_proc": dataset_map_num_proc(
1 if (self.is_audio or self.is_audio_vlm or self._cuda_audio_used) else None,
serial_as_none = False,
@@ -4210,8 +4137,8 @@ class UnslothTrainer:
config_args["packing"] = False
logger.info("Applied DAC overrides: packing=False\n")
- # Plain-text single-pass runs tokenize in the DataLoader workers instead of a blocking .map();
- # everything else stays eager.
+ # Plain-text single-pass runs tokenize in the DataLoader workers instead of a blocking .map(); everything
+ # else stays eager.
self._online_prewarm_batches = 0
online_decision = self._configure_online_tokenization(
config_args = config_args,
@@ -4228,10 +4155,9 @@ class UnslothTrainer:
logger.info(f"The configuration is: {config_args}")
logger.info("Training configuration prepared\n")
- # ========== TRAINER INITIALIZATION ==========
if self.is_audio_vlm and not raw_text_mode:
- # Image VLM: dict wrapper from format_and_template_dataset (raw-text uses the text path).
- # Audio VLM (e.g. Gemma 3N + audio): raw Dataset from _format_audio_vlm_dataset. Notebook uses
+ # Image VLM: dict wrapper from format_and_template_dataset (raw-text uses the text path). Audio VLM
+ # (e.g. Gemma 3N + audio): raw Dataset from _format_audio_vlm_dataset, and the notebook uses
# processing_class=processor.tokenizer; raw-text runs use the text path.
train_dataset = dataset["dataset"] if isinstance(dataset, dict) else dataset
processing_class = (
@@ -4262,10 +4188,8 @@ class UnslothTrainer:
trainer_kwargs["eval_dataset"] = eval_dataset
self.trainer = SFTTrainer(**trainer_kwargs)
else:
- # Unwrap a Processor for text-only (Gemma-3 returns ProcessorMixin even for text), else SFTTrainer
- # sets _is_vlm, skips _prepare_dataset and produces no input_ids.
# For text-only, unwrap a Processor (Gemma-3 returns ProcessorMixin even for text) to the raw
- # tokenizer; else SFTTrainer sets _is_vlm, skips _prepare_dataset, no input_ids.
+ # tokenizer; else SFTTrainer sets _is_vlm, skips _prepare_dataset and produces no input_ids.
from transformers import ProcessorMixin
sft_tokenizer = self.tokenizer
@@ -4326,7 +4250,7 @@ class UnslothTrainer:
self.trainer.processing_class = self.tokenizer
logger.info("Trainer initialized\n")
- # ========== TRAIN ON RESPONSES ONLY ========== Raw-text datasets always train on all tokens.
+ # Raw-text datasets always train on all tokens.
is_cpt = training_args.get("is_cpt", False)
train_on_responses_enabled = (
False
@@ -4341,8 +4265,8 @@ class UnslothTrainer:
"Raw-text mode: skipping train_on_responses_only — training on all tokens\n"
)
- # Markers auto-detected from the chat template first, with the manual table as fallback; gpt-oss
- # stays on manual markers. See apply_completion_masking.
+ # Markers auto-detected from the chat template first, with the manual table as fallback; gpt-oss stays on
+ # manual markers. See apply_completion_masking.
if (
train_on_responses_enabled
and not self.is_audio_vlm
@@ -4359,8 +4283,8 @@ class UnslothTrainer:
else:
logger.info(f"{message}\n")
- # No try/except: the helper handles detection failures itself, so an exception here is a real
- # masking failure that must fail the run, not silently train full sequences.
+ # No try/except: the helper handles detection failures itself, so an exception here is a real masking
+ # failure that must fail the run, not silently train full sequences.
self.trainer, masking_applied = apply_completion_masking(
self.trainer,
self.model_name,
@@ -4375,8 +4299,8 @@ class UnslothTrainer:
if masking_applied:
try:
- # Safety net: train_on_responses_only masks non-response tokens with -100, and a row becomes all
- # -100 (Unsloth drops it) when the response template is missing from the formatted text;
+ # Safety net: train_on_responses_only masks non-response tokens with -100, and a row becomes
+ # all -100 (Unsloth drops it) when the response template is missing from the formatted text;
# len()-based, so skipped for streaming.
if detect_streaming_dataset(self.trainer.train_dataset):
logger.info("Skipping post-filter length check for streaming dataset\n")
@@ -4428,10 +4352,8 @@ class UnslothTrainer:
logger.info("Training on full sequences (including prompts)\n")
self.trainer.add_callback(self._create_progress_callback())
- # Unsloth publishes progress itself, so HF's stdout callbacks duplicate a log that has no terminal;
- # --verbose keeps them.
- # Unsloth publishes progress itself, so HF's stdout callbacks are pure duplication in a log that has
- # no terminal. --verbose keeps them.
+ # Unsloth publishes progress itself, so HF's stdout callbacks are pure duplication in a log that has no
+ # terminal; --verbose keeps them.
_drop_hf_stdout_callbacks(self.trainer)
train_dataset_obj = dataset["dataset"] if isinstance(dataset, dict) else dataset
@@ -4468,7 +4390,6 @@ class UnslothTrainer:
self._update_progress(total_steps = total_steps)
# Fail fast on an invalid first batch (empty/float input_ids) vs a step-1 crash.
- # ========== START TRAINING ==========
preflight_error = self._preflight_first_batch()
if preflight_error:
logger.error(preflight_error)
@@ -4486,7 +4407,6 @@ class UnslothTrainer:
# hold a fork of this process.
self._release_online_dataloader()
- # ========== SAVE MODEL ==========
self._finalize_training(output_dir)
except Exception as e:
@@ -4497,17 +4417,14 @@ class UnslothTrainer:
self._update_progress(is_training = False, error = str(e))
finally:
- # Backstop for returns that never reach train(), notably a preflight error, which has already forked
- # the workers.
+ # Backstop for returns that never reach train(), notably a preflight error, which has already forked the
+ # workers.
self._release_online_dataloader()
self.is_training = False
def _patch_adapter_config(self, output_dir: str) -> None:
- """Patch adapter_config.json with unsloth_training_method.
-
- Values: 'qlora', 'lora', 'FT', 'CPT', 'DPO', 'GRPO', etc.
- For LoRA/QLoRA, the distinction comes from load_in_4bit.
- """
+ """Patch adapter_config.json with unsloth_training_method. Values: 'qlora', 'lora', 'FT',
+ 'CPT', 'DPO', 'GRPO', etc. For LoRA/QLoRA, the distinction comes from load_in_4bit."""
config_path = os.path.join(output_dir, "adapter_config.json")
if not os.path.exists(config_path):
logger.info("No adapter_config.json found — skipping training method patch")
@@ -4534,7 +4451,6 @@ class UnslothTrainer:
logger.warning(f"Failed to patch adapter_config.json: {e}")
def stop_training(self, save: bool = True):
- """Stop ongoing training"""
logger.info(f"\nStopping training (save={save})...")
self.should_stop = True
self.save_on_stop = save
@@ -4551,12 +4467,10 @@ class UnslothTrainer:
logger.error(f"Error stopping trainer: {e}")
def get_training_progress(self) -> TrainingProgress:
- """Get current training progress"""
with self._lock:
return self.training_progress
def cleanup(self):
- """Cleanup resources"""
if self.trainer:
self.trainer = None
if self.model:
@@ -4568,10 +4482,8 @@ class UnslothTrainer:
def _ensure_deepseek_ocr_installed():
- """Auto-install the DeepSeek OCR module from HF hub if missing.
-
- Returns True if available (already installed or just installed).
- """
+ """Auto-install the DeepSeek OCR module from HF hub if missing. Returns True if available
+ (already installed or just installed)."""
try:
from deepseek_ocr.modeling_deepseekocr import format_messages
logger.info("DeepSeek OCR module already available")
@@ -4613,7 +4525,6 @@ _trainer_instance = None
def get_trainer() -> UnslothTrainer:
- """Get global trainer instance"""
global _trainer_instance
if _trainer_instance is None:
_trainer_instance = UnslothTrainer()
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index 777437852cd..60587badd08 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -1074,10 +1074,8 @@ def create_mlx_trainer_adapter(*args, **kwargs):
class TrainingBackend:
- """
- Training orchestration backend — subprocess-based.
- Launches a fresh subprocess per job, communicates via mp.Queue.
- """
+ """Training orchestration backend: launches a fresh subprocess per job and communicates via
+ mp.Queue."""
FLUSH_THRESHOLD: int = 10
@@ -1100,7 +1098,6 @@ class TrainingBackend:
self._stop_watchdog_proc: Optional[mp.Process] = None
self._complete_seen = threading.Event()
- # Progress state (updated by pump thread from subprocess events)
self._progress = TrainingProgress()
self._should_stop = False
self._cancel_requested = False # True only for stop(save=False)
@@ -1114,7 +1111,6 @@ class TrainingBackend:
self._last_progress_log_elapsed: Optional[float] = None
self._last_progress_log_tokens: Optional[int] = None
- # Training metrics (consumed by routes for SSE and /metrics)
self.loss_history: list = []
self.lr_history: list = []
self.step_history: list = []
@@ -1574,17 +1570,14 @@ class TrainingBackend:
spawn_already_reserved: bool = False,
**kwargs,
) -> bool:
- """Spawn a subprocess to run the full training pipeline.
-
- All kwargs are serialized into a config dict and sent to the worker.
- Returns True if the subprocess started successfully.
-
- ``before_spawn`` is an optional no-arg callable run after synchronous
- validation (start guards, config build, explicit gpu_ids) passes but
- before VRAM-dependent auto GPU-selection and the spawn -- used to free
- VRAM (e.g. unload chat) without tearing it down on a refused start, while
- still letting auto-selection place training against the freed memory.
- Hook failures never block the start.
+ """Spawn a subprocess to run the full training pipeline. All kwargs are serialized into a
+ config dict and sent to the worker; returns True if the subprocess started successfully.
+
+ ``before_spawn`` is an optional no-arg callable run after synchronous validation (start
+ guards, config build, explicit gpu_ids) passes but before VRAM-dependent auto GPU-selection
+ and the spawn -- used to free VRAM (e.g. unload chat) without tearing it down on a refused
+ start, while still letting auto-selection place training against the freed memory. Hook
+ failures never block the start.
"""
with self._lock:
if not self._start_request_allows_spawn_locked(start_request_id, job_id):
@@ -1873,7 +1866,6 @@ class TrainingBackend:
*,
expected_job_id: str,
) -> bool:
- """Send stop signal to the training subprocess."""
from .lifecycle import training_lifecycle_guard
with training_lifecycle_guard():
return self._stop_training_with_lifecycle_reserved(
@@ -2102,22 +2094,21 @@ class TrainingBackend:
target_proc: "Optional[mp.Process]" = None,
watched_job_id: Optional[str] = None,
) -> None:
- """Finalize parent state after a force-terminate so the UI leaves "Stopping..."
- even if the worker is wedged in driver teardown; preserves output_dir on a save so
- the checkpoint is kept, and clears it on a cancel (Stop without saving must not
- offer resume/export). No-ops if a new run already replaced the watched worker, so a
- stale watchdog never marks a fresh run stopped or drops its handle.
+ """Finalize parent state after a force-terminate so the UI leaves "Stopping..." even if the
+ worker is wedged in driver teardown; preserves output_dir on a save so the checkpoint is
+ kept, and clears it on a cancel (Stop without saving must not offer resume/export). No-ops
+ if a new run already replaced the watched worker.
Supersession is checked on both the watched proc and job id: start_training sets
- current_job_id before it installs the new _proc, so a stale watchdog entering that
- startup window still sees the old (dead) handle and is caught by the job-id guard.
-
- The run's terminal DB state is recorded (create-if-needed + finish by captured id)
- BEFORE _proc is dropped: a wedged worker still reports alive, so the pump never
- reaches its own finalize and would bail on its _proc-is-None guard once the handle
- is gone. While the handle is held is_training_active() stays true, so no new run can
- start and current_job_id stays the watched run for the write. _proc is dropped last,
- re-guarded on target_proc so a run that did replace the worker keeps its handle."""
+ current_job_id before it installs the new _proc, so a stale watchdog entering that startup
+ window still sees the old (dead) handle and is caught by the job-id guard.
+
+ The run's terminal DB state is recorded (create-if-needed + finish by captured id) BEFORE
+ _proc is dropped: a wedged worker still reports alive, so the pump never reaches its own
+ finalize and would bail on its _proc-is-None guard once the handle is gone. While the handle
+ is held is_training_active() stays true, so no new run can start and current_job_id stays
+ the watched run for the write. _proc is dropped last, re-guarded on target_proc.
+ """
with self._lock:
if target_proc is not None and self._proc is not target_proc:
return
@@ -2500,11 +2491,11 @@ class TrainingBackend:
def _ensure_pump_alive(self) -> bool:
"""Restart the event pump if it crashed, even after the worker exited.
- Defence in depth behind _pump_loop's guards. _pump_running stays True only
- after an abnormal exit (the loop clears it on intended exits), so a True
- flag plus a dead thread is an unambiguous crash. Restarts even after worker
- exit so a fresh pump can drain the terminal events and finalize; otherwise
- the run looks stuck "running" forever. Returns True if restarted.
+ Defence in depth behind _pump_loop's guards. _pump_running stays True only after an abnormal
+ exit (the loop clears it on intended exits), so a True flag plus a dead thread is an
+ unambiguous crash. Restarts even after worker exit so a fresh pump can drain the terminal
+ events and finalize; otherwise the run looks stuck running forever. Returns True if
+ restarted.
"""
with self._lock:
if not self._pump_running:
@@ -2543,7 +2534,6 @@ class TrainingBackend:
return self._run_finished_locked()
def is_training_active(self) -> bool:
- """Check if training is currently active."""
# A spawn past its sidecar-swap recheck counts as active even before _proc is recorded.
if getattr(self, "_new_job_spawn_id", None) is not None or getattr(
self, "_spawn_in_progress", False
@@ -2608,7 +2598,6 @@ class TrainingBackend:
return str(output_dir) if output_dir else None
def get_training_status(self, theme: str = "light") -> Tuple:
- """Get current training status and loss plot."""
with self._lock:
progress = self._progress
@@ -2619,7 +2608,6 @@ class TrainingBackend:
return (plot, progress)
def refresh_plot_for_theme(self, theme: str) -> "Optional[plt.Figure]":
- """Refresh plot with new theme."""
if theme and isinstance(theme, str) and theme in ["light", "dark"]:
self.current_theme = theme
if self.loss_history:
@@ -2672,11 +2660,10 @@ class TrainingBackend:
def _pump_loop(self) -> None:
"""Background thread: consume subprocess events and update state.
- Sole writer of the in-memory progress state that /progress, /status,
- /metrics and DB history read. If it exited while the worker still ran, the
- run would burn GPU with events piling up while every surface froze. So no
- single bad event or transient queue/DB error may end it; it returns only
- through intended exits (worker gone, respawn handed off, finalized).
+ Sole writer of the in-memory progress state that /progress, /status, /metrics and DB history
+ read. If it exited while the worker still ran, the run would burn GPU with events piling up
+ while every surface froze, so no single bad event or transient queue/DB error may end it; it
+ returns only through intended exits (worker gone, respawn handed off, finalized).
"""
self._pump_running = True
while True:
@@ -3491,12 +3478,10 @@ class TrainingBackend:
return fig
-# ========== GLOBAL INSTANCE ==========
_training_backend = None
def get_training_backend() -> TrainingBackend:
- """Get global training backend instance"""
global _training_backend
if _training_backend is None:
_training_backend = TrainingBackend()
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 793371b5294..ff5912b4aae 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -1,13 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Training subprocess entry point.
-
-Each job runs in a fresh subprocess (mp.get_context("spawn")): a clean
-interpreter with no stale module state, which solves transformers
-version-switching. Pattern follows core/data_recipe/jobs/worker.py.
-"""
+"""Training subprocess entry point. Each job runs in a fresh subprocess (mp.get_context("spawn")): a
+clean interpreter with no stale module state, which solves transformers version-switching.
+Pattern follows core/data_recipe/jobs/worker.py."""
from __future__ import annotations
@@ -31,11 +27,9 @@ from typing import Any, Callable, TYPE_CHECKING
if TYPE_CHECKING:
from core.training.training import TrainingProgress
-# ── WSL AMD Strix Halo (gfx1151): enable ROCDXG before any torch import ──────
-# Mirrors main.py. In WSL the AMD GPU is reached via the ROCDXG bridge (librocdxg.so
-# over /dev/dxg), which HSA loads only when HSA_ENABLE_DXG_DETECTION=1 is set before
-# torch touches the GPU; a worker spawned outside a login shell misses the installer's
-# persisted env. Gated on both /dev/dxg and librocdxg.so, so other platforms no-op.
+# Mirrors main.py. In WSL the AMD GPU is reached via the ROCDXG bridge (librocdxg.so over /dev/dxg), which HSA loads
+# only when HSA_ENABLE_DXG_DETECTION=1 is set before torch touches the GPU; a worker spawned outside a login shell
+# misses the installer's persisted env. Gated on both /dev/dxg and librocdxg.so, so other platforms no-op.
if sys.platform.startswith("linux") and "HSA_ENABLE_DXG_DETECTION" not in os.environ:
try:
if os.path.exists("/dev/dxg") and any(
@@ -56,8 +50,8 @@ activate_native_tls()
from utils.hardware import apply_gpu_ids
from utils.hf_dataset_options import hf_dataset_split_instruction_names
-# Light module on purpose: the MLX branch below runs on torch-less hosts, so it
-# cannot reach these through core.training.trainer.
+# Light module on purpose: the MLX branch below runs on torch-less hosts, so it cannot reach these through
+# core.training.trainer.
from core.training.dataset_bounds import (
bound_dataset_rows,
max_train_rows_for_config,
@@ -85,23 +79,20 @@ def _output_dir_from_resume_checkpoint(resume_from_checkpoint: str | None) -> st
def _data_parallel_world_size() -> int:
"""Replicas that each draw a full batch of rows per optimizer step.
- Two things multiply row consumption and only one of them is in the env: a
- distributed launch (torchrun, accelerate, mpirun, mlx.launch), and plain
- DataParallel, which transformers reaches for whenever a non-distributed run
- sees more than one CUDA device -- it sets n_gpu to the visible device count and
- scales the train batch by it, so an extra visible GPU eats rows exactly as an
- extra rank does. XPU and MPS stay at one device there, so only CUDA counts.
-
- The larger of the two, never the sum: a distributed run forces n_gpu to 1, and a
- model-parallel one (a sharding device_map, which is what Unsloth's own multi-GPU
- load uses) forces it to 1 as well. Rounding up when the model turns out to be
- sharded rather than replicated only tokenizes a larger subset of a corpus this
- bound is orders of magnitude below anyway; rounding down means the run silently
- re-reads rows it has already trained on.
-
- torch is read out of sys.modules rather than imported: this also runs on the MLX
- path, on hosts where no torch exists, and a process that never imported it has
- no CUDA devices to count either.
+ Two things multiply row consumption and only one of them is in the env: a distributed launch
+ (torchrun, accelerate, mpirun, mlx.launch), and plain DataParallel, which transformers reaches
+ for whenever a non-distributed run sees more than one CUDA device -- it sets n_gpu to the
+ visible device count and scales the train batch by it. XPU and MPS stay at one device there, so
+ only CUDA counts.
+
+ The larger of the two, never the sum: a distributed run forces n_gpu to 1, and a model-parallel
+ one (a sharding device_map, which is what Unsloth's own multi-GPU load uses) forces it to 1 as
+ well. Rounding up when the model turns out to be sharded rather than replicated only tokenizes a
+ larger subset of a corpus this bound is orders of magnitude below anyway; rounding down means
+ the run silently re-reads rows it has already trained on.
+
+ torch is read out of sys.modules rather than imported: this also runs on the MLX path, on hosts
+ where no torch exists, and a process that never imported it has no CUDA devices to count either.
"""
sizes = [world_size_from_env()]
torch_module = sys.modules.get("torch")
@@ -120,8 +111,8 @@ def _data_parallel_world_size() -> int:
try:
sizes.append(int(torch_module.cuda.device_count()))
except Exception:
- # A CPU-only build answers 0, which the filter below drops; a broken or
- # stubbed torch.cuda raises instead, and that must not fail a run either.
+ # A CPU-only build answers 0, which the filter below drops; a broken or stubbed torch.cuda raises instead,
+ # and that must not fail a run either.
pass
return max([size for size in sizes if size > 0], default = 1)
@@ -177,14 +168,11 @@ def _drop_model_pin_for_fallback(config: dict, hf_token: str | None) -> str:
def _is_model_cache_artifact_error(error: BaseException | None) -> bool:
- """Classify model-only failures that mean a local snapshot is incomplete.
-
- Transformers does not consistently report a missing tokenizer or processor as
- a file error. Some families raise a bare ``TypeError`` after resolving a
- missing vocabulary path to ``None``. Keep those otherwise-generic messages
- scoped to the model-cache retry path so they cannot make unrelated dataset or
- training failures retryable.
- """
+ """Classify model-only failures that mean a local snapshot is incomplete. Transformers does not
+ consistently report a missing tokenizer or processor as a file error: some families raise a
+ bare ``TypeError`` after resolving a missing vocabulary path to ``None``. Keep those
+ otherwise-generic messages scoped to the model-cache retry path so they cannot make unrelated
+ dataset or training failures retryable."""
from hub.utils.dataset_cache import is_cache_artifact_error
if is_cache_artifact_error(error):
@@ -195,10 +183,10 @@ def _is_model_cache_artifact_error(error: BaseException | None) -> bool:
"can't load feature extractor for",
"stat: path should be string, bytes, os.pathlike or integer, not nonetype",
"expected str, bytes or os.pathlike object, not nonetype",
- # SentencePiece/BPE families resolve a missing vocab path to None and dereference it, so
- # the failure arrives as a bare AttributeError with no cache-specific text. Without these,
- # 26 tokenizer families (XLMRoberta, MBart, NLLB, Bloom, ...) get zero Hub retry and a
- # pinned tokenizer-less snapshot is terminal. A false positive costs one Hub attempt.
+ # SentencePiece/BPE families resolve a missing vocab path to None and dereference it, so the failure arrives
+ # as a bare AttributeError with no cache-specific text. Without these, 26 tokenizer families (XLMRoberta,
+ # MBart, NLLB, Bloom, ...) get zero Hub retry and a pinned tokenizer-less snapshot is terminal. A false
+ # positive costs one Hub attempt.
"'nonetype' object has no attribute 'endswith'",
"'nonetype' object has no attribute 'readlines'",
"argument should be a str or an os.pathlike object",
@@ -267,13 +255,10 @@ def _model_cache_fallback_error(config: dict, error: BaseException | None) -> Ru
def _mlx_revision_fallback_error(config: dict) -> RuntimeError | None:
- """Refuse an exact retry when MLX would remap the repo and drop its commit.
-
- ``FastMLXModel`` maps Unsloth bitsandbytes repositories to their full-precision
- base because MLX cannot read bnb-packed weights. A commit from the selected
- repository has no guaranteed meaning in that different repository, so silently
- applying it (or dropping it) would violate the cache pin.
- """
+ """Refuse an exact retry when MLX would remap the repo and drop its commit. ``FastMLXModel``
+ maps Unsloth bitsandbytes repositories to their full-precision base because MLX cannot read
+ bnb-packed weights, and a commit from the selected repository has no guaranteed meaning in
+ that different repository, so silently applying or dropping it would violate the cache pin."""
model_name = str(config.get("model_name") or "")
revision = config.get("model_revision")
if (
@@ -747,13 +732,11 @@ _NOTHING_TO_TRAIN = (
def _finetune_selectors(config: dict) -> tuple[bool, bool, bool, bool]:
- """(vision, language, attention, mlp), read exactly the way the consumers read them.
-
- A guard that models the run differently from the code it guards rejects runs that would
- have trained, so every default here is the CUDA consumer's own default for an omitted key.
- Only the MLX consumer defaults vision False, and _check_mlx_finetune_targets discards the
- vision element, so True is safe there too.
- """
+ """(vision, language, attention, mlp), read exactly the way the consumers read them. A guard
+ that models the run differently from the code it guards rejects runs that would have trained,
+ so every default here is the CUDA consumer's own default for an omitted key. Only the MLX
+ consumer defaults vision False, and _check_mlx_finetune_targets discards the vision element,
+ so True is safe there too."""
return (
bool(config.get("finetune_vision_layers", True)),
bool(config.get("finetune_language_layers", True)),
@@ -764,12 +747,10 @@ def _finetune_selectors(config: dict) -> tuple[bool, bool, bool, bool]:
def _requests_all_linear(config: dict) -> bool:
"""Whether target_modules is PEFT's bare "all-linear" keyword rather than a leaf list.
-
- get_peft_model forces every selector True for the keyword, so all-linear with the
- selectors off trains every linear layer today and rejecting it would break the very
- requests the selectors are not consulted for. A list naming all-linear alongside other
- leaves is not the keyword: the caller strips it and the rest take the scoped path.
- """
+ get_peft_model forces every selector True for the keyword, so all-linear with the selectors
+ off trains every linear layer today and rejecting it would break the very requests the
+ selectors are not consulted for. A list naming all-linear alongside other leaves is not the
+ keyword: the caller strips it and the rest take the scoped path."""
target_modules = config.get("target_modules")
if isinstance(target_modules, str):
return target_modules == "all-linear"
@@ -779,12 +760,12 @@ def _requests_all_linear(config: dict) -> bool:
def _check_finetune_targets_after_detect(trainer, config: dict) -> None:
- """Reject a LoRA run that selects no adapter layers, once detection has settled which
- branch it takes. The request model cannot decide this: the codec/ASR branches ignore the
- selectors that is_audio_vlm reads, is_vlm needs a vision-capable model and not just an
- image-tagged dataset, and only the probe in pre_detect separates those. pre_detect is
- config/tokenizer only, so this still fires before any weights load, instead of surfacing
- as get_peft_regex's "No layers to finetune" with the model already in memory."""
+ """Reject a LoRA run that selects no adapter layers, once detection has settled which branch it
+ takes. The request model cannot decide this: the codec/ASR branches ignore the selectors that
+ is_audio_vlm reads, is_vlm needs a vision-capable model and not just an image-tagged dataset,
+ and only the probe in pre_detect separates those. pre_detect is config/tokenizer only, so
+ this still fires before any weights load, instead of surfacing as get_peft_regex's "No layers
+ to finetune" with the model already in memory."""
if config.get("training_type", "LoRA/QLoRA") != "LoRA/QLoRA":
return # Full Finetuning / CPT build adapters from target_modules alone
if not (getattr(trainer, "is_vlm", False) or getattr(trainer, "is_audio_vlm", False)):
@@ -797,8 +778,8 @@ def _check_finetune_targets_after_detect(trainer, config: dict) -> None:
raise ValueError(_NOTHING_TO_TRAIN)
-# Targets the MLX loader trains regardless of the layer-family flags: on the CPT path
-# embed_tokens becomes a full trainable module and lm_head its own adapter.
+# Targets the MLX loader trains regardless of the layer-family flags: on the CPT path embed_tokens becomes a full
+# trainable module and lm_head its own adapter.
_CPT_TARGET_NAMES = frozenset({"embed_tokens", "lm_head"})
@@ -815,38 +796,34 @@ def _names_a_cpt_target(target_modules) -> bool:
def _check_mlx_finetune_targets(config: dict) -> None:
"""MLX equivalent, called from the LoRA branch of the MLX worker.
- Two things differ from the CUDA path. FastMLXModel.get_peft_model is handed these
- selectors for text models too, so there is no is_vlm gate. And the caller back-fills
- finetune_language_layers whenever a module type is on, so only an empty module selection
- can survive here.
+ Two things differ from the CUDA path: FastMLXModel.get_peft_model is handed these selectors for
+ text models too, so there is no is_vlm gate; and the caller back-fills finetune_language_layers
+ whenever a module type is on, so only an empty module selection can survive here.
- Surviving the module-type filter is NOT enough to train. get_peft_model drops only the
- names it recognises as attention or MLP leaves, so a fused qkv, a c_fc or an expanded
- all-linear survives with both module types off -- but the text branch then gates the LoRA
- application on finetune_language_layers, and with all four selectors off the caller's
- back-fill never fires. Those runs apply no adapters at all: the model warns and trains
- nothing, and a VLM raises only once the weights are loaded.
+ Surviving the module-type filter is NOT enough to train. get_peft_model drops only the names it
+ recognises as attention or MLP leaves, so a fused qkv, a c_fc or an expanded all-linear survives
+ with both module types off, but the text branch then gates the LoRA application on
+ finetune_language_layers, and with all four selectors off the caller's back-fill never fires.
+ Those runs apply no adapters at all: the model warns and trains nothing, and a VLM raises only
+ once the weights are loaded.
The exception is a target the loader handles independently of the layer families: naming
- embed_tokens or lm_head puts it on the CPT path, which trains whatever the flags say.
-
- An explicit list that merely filters down to nothing still gets the loader's own message,
- which names the two flags."""
+ embed_tokens or lm_head puts it on the CPT path. An explicit list that merely filters down to
+ nothing still gets the loader's own message, which names the two flags.
+ """
targets = config.get("target_modules")
if targets:
if _names_a_cpt_target(targets):
return
_, language, attention, mlp = _finetune_selectors(config)
- # Vision read the way the MLX call site reads it, NOT the way _finetune_selectors
- # does: that helper carries the CUDA consumer's defaults, where an omitted vision
- # selector means True, while MLX defaults it False and forces it False for a text
- # model. Taking True from an omitted key would wave through every legacy config
+ # Vision read the way the MLX call site reads it, NOT the way _finetune_selectors does: that helper carries
+ # the CUDA consumer's defaults, where an omitted vision selector means True, while MLX defaults it False and
+ # forces it False for a text model. Taking True from an omitted key would wave through every legacy config
# that never sent the selectors at all.
vision = bool(config.get("finetune_vision_layers", False))
- # Any one of them leaves something that can train, or leaves the loader to say so
- # with a better message. Vision counts because this runs BEFORE detection, so a VLM
- # whose vision tower is the only selection must not be refused here;
- # _check_mlx_effective_targets catches the text case once is_vlm is known.
+ # Any one of them leaves something that can train, or leaves the loader to say so with a better message.
+ # Vision counts because this runs BEFORE detection, so a VLM whose vision tower is the only selection must not
+ # be refused here; _check_mlx_effective_targets catches the text case once is_vlm is known.
if attention or mlp or language or vision:
return
raise ValueError(_NOTHING_TO_TRAIN)
@@ -859,15 +836,12 @@ def _check_mlx_effective_targets(
config: dict, *, finetune_language: bool, finetune_vision: bool
) -> None:
"""The same refusal, re-asked with the values get_peft_model will actually receive.
-
- ``_check_mlx_finetune_targets`` runs before the model is loaded, so it cannot tell a VLM
- from a text model and has to let a vision-only selection through. The call site can: it
- has forced vision to False for a text model and applied the language back-fill, so if
- both layer families are still off here, no adapter is coming and the run would train
- nothing but its own warning.
-
- Later than the preflight deliberately: this is the first point the answer is knowable,
- and it is still before the trainer is built and before a single step runs."""
+ ``_check_mlx_finetune_targets`` runs before the model is loaded, so it cannot tell a VLM from
+ a text model and has to let a vision-only selection through. The call site can: it has forced
+ vision to False for a text model and applied the language back-fill, so if both layer
+ families are still off here, no adapter is coming and the run would train nothing but its own
+ warning. Later than the preflight deliberately: this is the first point the answer is
+ knowable, and still before the trainer is built."""
if finetune_language or finetune_vision:
return
if _names_a_cpt_target(config.get("target_modules") or ()):
@@ -1000,14 +974,11 @@ _WINDOWS_ROCM_GROUPED_MM_LIB = None
def _install_grouped_mm_cpu_fallback(torch_mod, logger, label):
- """Register a Python mm/bmm fallback for torch._grouped_mm and return the Library.
-
- RDNA4 (gfx1200/gfx1201) ships a null HIP _grouped_mm kernel on ROCm <= 7.12
- (fixed in 7.13; ROCm/TheRock #5284). JitDecomp dispatches _grouped_mm to the
- null kernel and crashes; overriding the CUDA dispatch key bypasses it. Shared
- by the Windows and Linux ROCm guards. Keep the returned Library referenced so
- the registration outlives the caller.
- """
+ """Register a Python mm/bmm fallback for torch._grouped_mm and return the Library. RDNA4
+ (gfx1200/gfx1201) ships a null HIP _grouped_mm kernel on ROCm <= 7.12 (fixed in 7.13;
+ ROCm/TheRock #5284). JitDecomp dispatches _grouped_mm to the null kernel and crashes;
+ overriding the CUDA dispatch key bypasses it. Shared by the Windows and Linux ROCm guards.
+ Keep the returned Library referenced so the registration outlives the caller."""
import warnings as _warnings
_gm_lib = torch_mod.library.Library("aten", "IMPL")
@@ -1071,8 +1042,8 @@ def _install_grouped_mm_cpu_fallback(torch_mod, logger, label):
return _gm_lib
-# Subprocesses don't inherit os.add_dll_directory registrations. Replicate main.py's
-# Windows ROCm DLL setup so the first `import torch` finds amdhip64.dll; handles kept.
+# Subprocesses don't inherit os.add_dll_directory registrations. Replicate main.py's Windows ROCm DLL setup so the
+# first `import torch` finds amdhip64.dll; handles kept.
_ROCM_DLL_HANDLES: list = []
if sys.platform == "win32":
@@ -1121,14 +1092,11 @@ def _model_wants_causal_conv1d(model_name: str) -> bool:
def _hipcc_gcc_install_dir() -> str | None:
- """Highest-numbered ``/usr/lib/gcc/x86_64-linux-gnu/<N>`` that has BOTH the
- gcc runtime dir AND ``/usr/include/c++/<N>`` headers, or None.
-
- Ubuntu 24.04 ships gcc-14 runtime but not ``/usr/include/c++/14``; ROCm
- clang-20 picks the highest runtime dir, finds no ``<cstdlib>``, and the HIP
- build fails. The returned path is passed to clang via
- ``--gcc-install-dir``. Mirrors bbf004c in studio/setup.sh (PR #5301).
- """
+ """Highest-numbered ``/usr/lib/gcc/x86_64-linux-gnu/<N>`` that has BOTH the gcc runtime dir AND
+ ``/usr/include/c++/<N>`` headers, or None. Ubuntu 24.04 ships gcc-14 runtime but not
+ ``/usr/include/c++/14``; ROCm clang-20 picks the highest runtime dir, finds no ``<cstdlib>``,
+ and the HIP build fails. The returned path is passed to clang via ``--gcc-install-dir``.
+ Mirrors bbf004c in studio/setup.sh (PR #5301)."""
if not sys.platform.startswith("linux"):
return None
import platform as _platform
@@ -1150,8 +1118,8 @@ def _is_importable(import_name: str) -> bool:
__import__(import_name)
return True
except Exception as exc:
- # A wrong-arch/ABI wheel raises OSError/RuntimeError ("undefined symbol"), not
- # ImportError, so catch everything and let the caller fall back.
+ # A wrong-arch/ABI wheel raises OSError/RuntimeError ("undefined symbol"), not ImportError, so catch
+ # everything and let the caller fall back.
logger.debug("%s is not importable (%s: %s)", import_name, type(exc).__name__, exc)
return False
@@ -1161,12 +1129,9 @@ _IMPORT_PROBE_TIMEOUT = 300
def _is_importable_isolated(import_name: str) -> bool:
- """Probe the import in a child process.
-
- A wrong-arch wheel can abort or segfault in its initialiser instead of raising, which
- would kill this worker rather than fall back. A child turns that into a return code
- (negative = fatal signal).
- """
+ """Probe the import in a child process. A wrong-arch wheel can abort or segfault in its
+ initialiser instead of raising, which would kill this worker rather than fall back. A child
+ turns that into a return code (negative = fatal signal)."""
try:
result = _sp.run(
[
@@ -1210,13 +1175,11 @@ def _uninstall_package(pypi_name: str, display_name: str) -> bool:
def _distribution_present(pypi_name: str) -> bool:
- """Whether the distribution's METADATA is installed, without importing it.
-
- Metadata is what matters: unsloth/models/_utils.py gates on ``_package_available`` and
- only then imports the native module, so metadata left behind is what turns a rejected
- wheel into an in-process crash. Reading it never loads the extension, so this is safe
- even for a wheel that would abort.
- """
+ """Whether the distribution's METADATA is installed, without importing it. Metadata is what
+ matters: unsloth/models/_utils.py gates on ``_package_available`` and only then imports the
+ native module, so metadata left behind is what turns a rejected wheel into an in-process
+ crash. Reading it never loads the extension, so this is safe even for a wheel that would
+ abort."""
importlib.invalidate_caches()
try:
importlib.metadata.distribution(pypi_name)
@@ -1226,12 +1189,10 @@ def _distribution_present(pypi_name: str) -> bool:
def _reject_install(event_queue: Any, pypi_name: str, display_name: str, reason: str) -> None:
- """Discard an install that will not import, and say which state we ended in.
-
- Idempotent, so it is safe on EVERY exit rather than only the ones somebody remembered:
- it no-ops when the distribution is already gone. Leaving it in place is not the same as
- never having installed it, since the metadata gate above imports it anyway.
- """
+ """Discard an install that will not import, and say which state we ended in. Idempotent, so it
+ is safe on EVERY exit rather than only the ones somebody remembered: it no-ops when the
+ distribution is already gone. Leaving it in place is not the same as never having installed
+ it, since the metadata gate above imports it anyway."""
if not _distribution_present(pypi_name):
return
logger.warning("%s %s", display_name, reason)
@@ -1248,15 +1209,12 @@ def _reject_install(event_queue: Any, pypi_name: str, display_name: str, reason:
def _install_package_wheel_first(
*, event_queue: Any, import_name: str, display_name: str, pypi_name: str, **kwargs: Any
) -> bool:
- """Install a fast-path package, wheel first, and never leave an unusable one behind.
-
- The two "touch nothing" guards run here, outside the cleanup: an already-working
- package returns before any subprocess, and offline changes nothing. Everything after
- them is an install attempt, so ANY unsuccessful exit -- timeout, failed install, bad
- import -- discards what is left rather than leaving metadata the in-process import
- would pick up. Enforced here rather than at each return because four separate exits
- have now been found that forgot to clean up.
- """
+ """Install a fast-path package, wheel first, and never leave an unusable one behind. The two
+ "touch nothing" guards run here, outside the cleanup: an already-working package returns
+ before any subprocess, and offline changes nothing. Everything after them is an install
+ attempt, so ANY unsuccessful exit -- timeout, failed install, bad import -- discards what is
+ left rather than leaving metadata the in-process import would pick up. Enforced here rather
+ than at each return because four separate exits have now been found that forgot to clean up."""
if _is_importable(import_name):
logger.info("%s already installed", display_name)
return True
@@ -1321,9 +1279,8 @@ def _attempt_package_install(
run = _sp.run,
):
if result.returncode == 0:
- # A wheel can install yet fail to import (CUDA/ABI or arch mismatch), so
- # verify rather than trust the exit code, and do it out of process: a bad
- # one can take the worker down with it.
+ # A wheel can install yet fail to import (CUDA/ABI or arch mismatch), so verify rather than trust the
+ # exit code, and do it out of process: a bad one can take the worker down with it.
if _is_importable_isolated(import_name):
logger.info("Installed prebuilt %s wheel successfully", display_name)
return True
@@ -1367,13 +1324,10 @@ def _attempt_package_install(
pypi_status_message = f"Installing {display_name} from PyPI for faster training..."
if wheel_rejected:
- # Remove it rather than install over it: pip/uv would report the broken
- # distribution as already satisfying the spec and do nothing. --force-reinstall is
- # not the answer either, since both scope it to the whole resolved transaction,
- # which for flash-attn means torch and the running CUDA stack.
- #
- # A failure here is caught by the _reject_install in the finally below, which is
- # reached from every exit rather than only the ones that remember to clean up.
+ # Remove it rather than install over it: pip/uv would report the broken distribution as already satisfying the
+ # spec and do nothing. --force-reinstall is not the answer either, since both scope it to the whole resolved
+ # transaction, which for flash-attn means torch and the running CUDA stack. A failure here is caught by the
+ # _reject_install in the finally below, which is reached from every exit.
_uninstall_package(pypi_name, display_name)
_send_status(event_queue, pypi_status_message)
@@ -1418,9 +1372,9 @@ def _attempt_package_install(
pypi_spec,
]
- # ROCm source compilation can take 10-30 min; use a generous timeout. Non-HIP installs
- # keep the pre-existing "no timeout" behaviour so unrelated slow builds (causal-conv1d
- # on aarch64, unsupported torch/CUDA combos) aren't aborted at 5 minutes.
+ # ROCm source compilation can take 10-30 min; use a generous timeout. Non-HIP installs keep the pre-existing "no
+ # timeout" behaviour so unrelated slow builds (causal-conv1d on aarch64, unsupported torch/CUDA combos) aren't
+ # aborted at 5 minutes.
_run_kwargs: dict[str, Any] = {
"stdout": _sp.PIPE,
"stderr": _sp.STDOUT,
@@ -1432,9 +1386,9 @@ def _attempt_package_install(
}
if is_hip:
_run_kwargs["timeout"] = 1800
- # On Ubuntu 24.04 + ROCm clang-20 the HIP source build dies on a missing <cstdlib>
- # (gcc-14 runtime dir lacks C++ headers). Inject --gcc-install-dir for a gcc whose
- # headers exist, respecting any pre-existing one. Mirrors bbf004c in setup.sh (PR #5301).
+ # On Ubuntu 24.04 + ROCm clang-20 the HIP source build dies on a missing <cstdlib> (gcc-14 runtime dir lacks
+ # C++ headers). Inject --gcc-install-dir for a gcc whose headers exist, respecting any pre-existing one.
+ # Mirrors bbf004c in setup.sh (PR #5301).
_existing_flags = os.environ.get("HIPCC_COMPILE_FLAGS_APPEND", "")
if "--gcc-install-dir" not in _existing_flags:
_gcc_dir = _hipcc_gcc_install_dir()
@@ -1481,8 +1435,8 @@ def _attempt_package_install(
)
else:
if sys.platform == "win32":
- # No prebuilt wheel and no source toolchain on Windows -- expected for packages like
- # causal-conv1d. Log at info so users aren't alarmed by what looks like an error.
+ # No prebuilt wheel and no source toolchain on Windows -- expected for packages like causal-conv1d.
+ # Log at info so users aren't alarmed by what looks like an error.
logger.info(
"%s is not available on Windows (no prebuilt wheel); skipping",
display_name,
@@ -1496,8 +1450,8 @@ def _attempt_package_install(
)
return False
- # rc=0 is not proof again here: pip/uv exit 0 on "Requirement already satisfied" without
- # installing anything. Returning False is enough; the caller's finally discards it.
+ # rc=0 is not proof again here: pip/uv exit 0 on "Requirement already satisfied" without installing anything.
+ # Returning False is enough; the caller's finally discards it.
if not _is_importable_isolated(import_name):
logger.warning("%s installed from PyPI but will not import", display_name)
return False
@@ -1578,27 +1532,19 @@ def _ensure_mamba_ssm(event_queue: Any, model_name: str) -> None:
def _rocm_classify_unified_memory(props: Any) -> tuple[str, bool]:
- """Classify a ROCm device as unified-memory (APU) or discrete.
-
- Returns ``(gcn_arch, is_unified)``:
- - ``gcn_arch``: canonical arch string (e.g. ``"gfx1151"``) when a known
- attribute is present, else ``""``.
- - ``is_unified``: ``True`` for AMD APUs with a shared GPU/system-RAM pool
- (gfx1150 Strix Point, gfx1151 Strix Halo, gfx1152 Krackan Point) — these
- need a lower ``set_per_process_memory_fraction`` cap to leave OS headroom.
-
- Classification priority:
- 1. ``props.is_integrated`` truthy (hipDeviceProp_t.integrated -- the
- driver's own unified-memory answer; covers APUs beyond the hardcoded
- arch set, e.g. gfx1103 Phoenix iGPUs). Only ever upgrades to unified.
- 2. ``gcnArchName`` / variant spellings (stable, naming-independent).
- 3. Device-name substring match (last resort when all arch attrs absent;
- AMD SDK / Radeon wheels may not populate them):
- - gfx1150 Strix Point: ``Radeon 890M``, ``Radeon 880M``
- - gfx1151 Strix Halo / Gorgon Halo: ``Radeon 8065S`` (Ryzen AI
- Max+ 495), ``Radeon 8060S`` (Ryzen AI MAX+
- 395), ``Radeon 8050S`` (cut-down SKU)
- - gfx1152 Krackan Point: ``Radeon 860M``, ``Radeon 840M``
+ """Classify a ROCm device as unified-memory (APU) or discrete, returning ``(gcn_arch,
+ is_unified)``. ``gcn_arch`` is the canonical arch string (e.g. ``"gfx1151"``) when a known
+ attribute is present, else ``""``; ``is_unified`` is True for AMD APUs with a shared
+ GPU/system-RAM pool (gfx1150 Strix Point, gfx1151 Strix Halo, gfx1152 Krackan Point), which need
+ a lower ``set_per_process_memory_fraction`` cap to leave OS headroom.
+
+ Classification priority: (1) ``props.is_integrated`` truthy (hipDeviceProp_t.integrated, the
+ driver's own unified-memory answer, which covers APUs beyond the hardcoded arch set such as
+ gfx1103 Phoenix) and only ever upgrades to unified; (2) ``gcnArchName`` / variant spellings,
+ stable and naming-independent; (3) device-name substring match as a last resort when all arch
+ attrs are absent, since AMD SDK / Radeon wheels may not populate them -- gfx1150 is ``Radeon
+ 890M`` / ``880M``, gfx1151 is ``Radeon 8065S`` / ``8060S`` / ``8050S``, gfx1152 is ``Radeon
+ 860M`` / ``840M``.
"""
gcn_arch = ""
for _attr in ("gcnArchName", "gcn_arch_name", "arch_name", "gfx_arch_name"):
@@ -1607,20 +1553,20 @@ def _rocm_classify_unified_memory(props: Any) -> tuple[str, bool]:
gcn_arch = _v
break
- # Driver's own answer first: hipDeviceProp_t.integrated (props.is_integrated, the same
- # gate PR #5988's UMA safetensors fast-load uses). Strictly additive -- only a truthy
- # value upgrades to unified, so a wheel that omits the field can't downgrade the known
- # APU set. Covers unified APUs outside the hardcoded arches (gfx1103 Phoenix, future).
+ # Driver's own answer first: hipDeviceProp_t.integrated (props.is_integrated, the same gate PR #5988's UMA
+ # safetensors fast-load uses). Strictly additive -- only a truthy value upgrades to unified, so a wheel that omits
+ # the field can't downgrade the known APU set. Covers unified APUs outside the hardcoded arches (gfx1103 Phoenix,
+ # future).
if getattr(props, "is_integrated", 0):
return gcn_arch, True
if gcn_arch:
- # gfx1152 is Krackan Point: same shared GPU/system-RAM pool as gfx1150/gfx1151.
- # Case-folded: the attribute is lowercase in practice but is not guaranteed.
+ # gfx1152 is Krackan Point: same shared GPU/system-RAM pool as gfx1150/gfx1151. Case-folded: the attribute is
+ # lowercase in practice but is not guaranteed.
return gcn_arch, gcn_arch.lower() in {"gfx1150", "gfx1151", "gfx1152"}
- # Arch attrs absent -- fall back to device-name matching. Only reached under _hw.IS_ROCM,
- # so the NVIDIA GeForce 840M cannot collide with the Krackan markers.
+ # Arch attrs absent -- fall back to device-name matching. Only reached under _hw.IS_ROCM, so the NVIDIA GeForce
+ # 840M cannot collide with the Krackan markers.
dev_lower = (getattr(props, "name", "") or "").lower()
is_unified = (
"890m" in dev_lower
@@ -1634,8 +1580,8 @@ def _rocm_classify_unified_memory(props: Any) -> tuple[str, bool]:
return gcn_arch, is_unified
-# 16 GiB, not a percentage: on a 128 GiB Strix Halo a flat 20% withholds 25.6 GiB, while
-# 0.90 there reserves 12.8 GiB and was measured as OS-starving. The constant sits between.
+# 16 GiB, not a percentage: on a 128 GiB Strix Halo a flat 20% withholds 25.6 GiB, while 0.90 there reserves 12.8 GiB
+# and was measured as OS-starving. The constant sits between.
_UNIFIED_OS_RESERVE_BYTES = 16 * 1024**3
_UNIFIED_MAX_RESERVE_FRACTION = 0.20
_DISCRETE_MEM_FRACTION = 0.90
@@ -1643,28 +1589,23 @@ _MEM_FRACTION_ENV = "UNSLOTH_ROCM_MEM_FRACTION"
def _parse_mem_fraction_env(env_value: str | None) -> float | None:
- """``UNSLOTH_ROCM_MEM_FRACTION`` as a float, None when unset or unusable.
-
- Shared with the OOM guard's log line so it can say whether the override was
- actually honoured, rather than just whether the variable was set.
- """
+ """``UNSLOTH_ROCM_MEM_FRACTION`` as a float, None when unset or unusable. Shared with the OOM
+ guard's log line so it can say whether the override was actually honoured, rather than just
+ whether the variable was set."""
try:
override = float(env_value) # None -> TypeError, "" / " " -> ValueError
except (TypeError, ValueError):
return None
- # Two-sided on purpose: NaN loses every comparison, so this rejects it. A one-sided
- # `override <= 0.0 or override > 1.0` would pass NaN to set_per_process_memory_fraction.
+ # Two-sided on purpose: NaN loses every comparison, so this rejects it. A one-sided `override <= 0.0 or override >
+ # 1.0` would pass NaN to set_per_process_memory_fraction.
return override if 0.0 < override <= 1.0 else None
def _allocator_divides_by_props_total(torch_version: str | None) -> bool:
- """Whether ``set_per_process_memory_fraction`` scales ``props.total_memory``.
-
- c10's ``CUDACachingAllocator::setMemoryFraction`` caps at
- ``fraction * device_prop.totalGlobalMem`` from torch 2.10, and at
- ``fraction * hipMemGetInfo total`` through 2.9. Unparsable versions answer True,
- so a surprise string keeps today's denominator rather than switching it.
- """
+ """Whether ``set_per_process_memory_fraction`` scales ``props.total_memory``. c10's
+ ``CUDACachingAllocator::setMemoryFraction`` caps at ``fraction * device_prop.totalGlobalMem``
+ from torch 2.10, and at ``fraction * hipMemGetInfo total`` through 2.9. Unparsable versions
+ answer True, so a surprise string keeps today's denominator rather than switching it."""
release = str(torch_version or "").split("+", 1)[0].split(".")
try:
major, minor = int(release[0]), int(release[1])
@@ -1683,24 +1624,20 @@ def _rocm_memory_fraction(
"""Pick the ``set_per_process_memory_fraction`` cap for a ROCm device.
``total_bytes`` is the pool the reserve comes out of, always
- ``get_device_properties().total_memory``: on a unified APU that is what the OS
- shares, while ``hipMemGetInfo``'s total is a runtime budget spanning GTT.
-
- ``denominator_bytes`` is what the allocator multiplies the fraction by, when that
- is a different number (see ``_allocator_divides_by_props_total``). An absolute
- byte reserve only lands where intended if the two agree, so passing it re-solves
- the cap for the same allowed bytes, floored at the historical cap so a larger
- driver total can never leave this tighter than the 0.80 it replaced.
-
- - ``env_value`` (``UNSLOTH_ROCM_MEM_FRACTION``) wins when it parses to a
- float in ``(0.0, 1.0]``; anything else is ignored, never fatal.
- - Unified + win32: ``1.0``. The WDDM budget already excludes the OS share,
- so any sub-1.0 cap double-taxes it (see the guard's own comment).
- - Unified elsewhere: reserve ``min(_UNIFIED_MAX_RESERVE_FRACTION of total,
- _UNIFIED_OS_RESERVE_BYTES)``, then clamp the cap to ``_DISCRETE_MEM_FRACTION``
- so a huge pool never ends up looser than a discrete card. The percentage
- ceiling keeps small pools at exactly the historical cap.
- - Discrete: ``_DISCRETE_MEM_FRACTION``.
+ ``get_device_properties().total_memory``: on a unified APU that is what the OS shares, while
+ ``hipMemGetInfo``'s total is a runtime budget spanning GTT. ``denominator_bytes`` is what the
+ allocator multiplies the fraction by, when that is a different number (see
+ ``_allocator_divides_by_props_total``); an absolute byte reserve only lands where intended if
+ the two agree, so passing it re-solves the cap for the same allowed bytes, floored at the
+ historical cap so a larger driver total can never leave this tighter than the 0.80 it replaced.
+
+ ``env_value`` (``UNSLOTH_ROCM_MEM_FRACTION``) wins when it parses to a float in ``(0.0, 1.0]``;
+ anything else is ignored, never fatal. Unified + win32 gets ``1.0``, since the WDDM budget
+ already excludes the OS share and any sub-1.0 cap double-taxes it. Unified elsewhere reserves
+ ``min(_UNIFIED_MAX_RESERVE_FRACTION of total, _UNIFIED_OS_RESERVE_BYTES)``, then clamps the cap
+ to ``_DISCRETE_MEM_FRACTION`` so a huge pool never ends up looser than a discrete card; the
+ percentage ceiling keeps small pools at exactly the historical cap. Discrete gets
+ ``_DISCRETE_MEM_FRACTION``.
"""
override = _parse_mem_fraction_env(env_value)
if override is not None:
@@ -1711,13 +1648,12 @@ def _rocm_memory_fraction(
if platform == "win32":
return 1.0
if total_bytes <= 0:
- # The caller defaults a missing or None total to 0; with no pool size there is
- # nothing to solve against, so keep the historical cap.
+ # The caller defaults a missing or None total to 0; with no pool size there is nothing to solve against, so
+ # keep the historical cap.
return 1.0 - _UNIFIED_MAX_RESERVE_FRACTION
- # Solved in fraction space, not bytes: (total - 0.20 * total) / total rounds
- # to 0.7999999999999999 on some pool sizes (12/24/28/48 GiB), which would
- # break the "never tighter than the historical 0.80" guarantee by a ULP.
+ # Solved in fraction space, not bytes: (total - 0.20 * total) / total rounds to 0.7999999999999999 on some pool
+ # sizes (12/24/28/48 GiB), which would break the "never tighter than the historical 0.80" guarantee by a ULP.
reserve_fraction = min(_UNIFIED_MAX_RESERVE_FRACTION, _UNIFIED_OS_RESERVE_BYTES / total_bytes)
fraction = 1.0 - reserve_fraction
@@ -1727,17 +1663,16 @@ def _rocm_memory_fraction(
and denominator_bytes > 0
and denominator_bytes != total_bytes
):
- # Re-solve for the same allowed bytes against the total the allocator scales.
- # Floored, so a larger driver total cannot leave a host tighter than the 0.80
- # this replaced. Byte arm only: the percentage arm is scale-free, and those
- # small pools are the OOM-prone ones that must stay exactly as they were.
+ # Re-solve for the same allowed bytes against the total the allocator scales. Floored, so a larger driver
+ # total cannot leave a host tighter than the 0.80 this replaced. Byte arm only: the percentage arm is
+ # scale-free, and those small pools are the OOM-prone ones that must stay exactly as they were.
fraction = max(
fraction * total_bytes / denominator_bytes,
1.0 - _UNIFIED_MAX_RESERVE_FRACTION,
)
- # Past ~160 GiB the byte reserve is under 10% of the pool, which would hand a unified
- # host a looser cap than a discrete card and invert the ordering the guard is built on.
+ # Past ~160 GiB the byte reserve is under 10% of the pool, which would hand a unified host a looser cap than a
+ # discrete card and invert the ordering the guard is built on.
return min(fraction, _DISCRETE_MEM_FRACTION)
@@ -1748,11 +1683,9 @@ def _rocm_memory_fraction(
def _rebind_in_already_imported_modules(*, attr_name: str, old_obj: Any, new_obj: Any) -> int:
- """Rebind `attr_name -> new_obj` in every module that imported `old_obj`.
-
- `from X import Y` creates a local binding that reassigning X.Y won't reach.
- Uses `__dict__.get` to skip lazy `__getattr__` aliases.
- """
+ """Rebind `attr_name -> new_obj` in every module that imported `old_obj`. `from X import Y`
+ creates a local binding that reassigning X.Y won't reach. Uses `__dict__.get` to skip lazy
+ `__getattr__` aliases."""
count = 0
missing = object()
for mod_name, mod in list(sys.modules.items()):
@@ -1938,15 +1871,11 @@ def _activate_transformers_version(model_name: str, hf_token: str | None = None)
def _activate_transformers_version_or_warn(model_name: str, hf_token: str | None = None) -> None:
- """Activate the required transformers version for the MLX fast-path.
-
- Unlike the non-MLX path (which treats activation failure as fatal and
- reports it via the event queue), the MLX path is intentionally non-fatal:
- it falls through with whatever transformers version is installed. The
- failure used to be swallowed by a bare ``except: pass``, leaving no trace
- and only a confusing downstream crash. Log a warning instead so the cause
- is visible, while keeping the fall-through behaviour.
- """
+ """Activate the required transformers version for the MLX fast-path. Unlike the non-MLX path
+ (which treats activation failure as fatal and reports it via the event queue), the MLX path
+ is intentionally non-fatal: it falls through with whatever transformers version is installed.
+ The failure used to be swallowed by a bare ``except: pass``, leaving no trace and only a
+ confusing downstream crash, so log a warning while keeping the fall-through."""
try:
_activate_transformers_version(model_name, hf_token)
except Exception as exc:
@@ -1964,8 +1893,8 @@ def _mlx_vlm_max_resized_size(width: int, height: int, target: int) -> tuple[int
largest_side = max(width, height)
if largest_side <= target:
return width, height
- # Integer formula matches unsloth_zoo's collator (Python round() differs by
- # 1px on half-pixel cases). max(1, _) avoids a zero-side degenerate output.
+ # Integer formula matches unsloth_zoo's collator (Python round() differs by 1px on half-pixel cases). max(1, _)
+ # avoids a zero-side degenerate output.
new_w = max(1, (width * target + largest_side // 2) // largest_side)
new_h = max(1, (height * target + largest_side // 2) // largest_side)
return new_w, new_h
@@ -2052,8 +1981,8 @@ def _resize_mlx_vlm_image(
if new_size != image.size:
resampling = getattr(Image, "Resampling", Image).LANCZOS
image = image.resize(new_size, resampling)
- # On resize, hand mlx-vlm a writable RGB ndarray so its PIL-path square-resize is skipped
- # and HF processors don't warn on non-writable views. resize=None keeps the original PIL.
+ # On resize, hand mlx-vlm a writable RGB ndarray so its PIL-path square-resize is skipped and HF processors don't
+ # warn on non-writable views. resize=None keeps the original PIL.
array = np.array(image, copy = True)
if image_layout == "chw":
return np.ascontiguousarray(array.transpose(2, 0, 1))
@@ -2075,13 +2004,10 @@ def _adapt_for_mlx_vlm(
resize = None,
image_layout = None,
):
- """Adapt GPU-path VLM dataset output for mlx-vlm.
-
- The GPU path embeds PIL images in message content as
- {"type": "image", "image": PIL_Image}, but mlx-vlm's prepare_inputs needs
- images at top-level to produce pixel_values (any model type). Extract them
- and leave bare {"type": "image"} placeholders.
- """
+ """Adapt GPU-path VLM dataset output for mlx-vlm. The GPU path embeds PIL images in message
+ content as {"type": "image", "image": PIL_Image}, but mlx-vlm's prepare_inputs needs images
+ at top-level to produce pixel_values (any model type). Extract them and leave bare {"type":
+ "image"} placeholders."""
adapted = []
for item in items:
images = []
@@ -2129,8 +2055,8 @@ def _adapt_for_mlx_vlm(
_MLX_STUDIO_LR_SCHEDULERS = {"linear", "cosine", "constant"}
-# Fallback alias map mirroring unsloth_zoo._normalize_mlx_optimizer_name, used only when
-# mlx isn't importable. The zoo function stays the source of truth.
+# Fallback alias map mirroring unsloth_zoo._normalize_mlx_optimizer_name, used only when mlx isn't importable. The zoo
+# function stays the source of truth.
_MLX_STUDIO_ADAMW_ALIASES = frozenset(
(
"adamw_8bit",
@@ -2323,13 +2249,10 @@ def _resolve_mlx_output_dir(config, model_name):
def _resolve_mlx_max_grad_norm(value):
- """Global-norm clip threshold for MLX runs; None keeps the trainer's default.
-
- The worker used to hardcode 0.0 and drop the requested value, so an API caller
- asking for a threshold got none. Unset stays 0.0 so MLX keeps its cheap
- per-parameter clipping: the gradient-norm chart is fed by report_grad_norm
- instead, which measures the same norm without changing what gets clipped.
- """
+ """Global-norm clip threshold for MLX runs; None keeps the trainer's default. The worker used to
+ hardcode 0.0 and drop the requested value, so an API caller asking for a threshold got none.
+ Unset stays 0.0 so MLX keeps its cheap per-parameter clipping: the gradient-norm chart is fed
+ by report_grad_norm instead, which measures the same norm without changing what gets clipped."""
if value is None:
return 0.0
try:
@@ -2348,11 +2271,9 @@ def _resolve_mlx_max_grad_norm(value):
def _run_mlx_training(event_queue, stop_queue, config):
- """Self-contained MLX training path for Apple Silicon.
-
- Uses unsloth_zoo's MLXTrainer directly (no torch/SFTTrainer). Mirrors the
- event_queue protocol so the parent process pump works unchanged.
- """
+ """Self-contained MLX training path for Apple Silicon. Uses unsloth_zoo's MLXTrainer directly
+ (no torch/SFTTrainer). Mirrors the event_queue protocol so the parent process pump works
+ unchanged."""
import time
import math
from pathlib import Path
@@ -2426,12 +2347,11 @@ def _run_mlx_training(event_queue, stop_queue, config):
optim_name = _normalize_mlx_studio_optimizer(config.get("optim", "adamw_8bit"))
lr_scheduler_type = _normalize_mlx_studio_scheduler(config.get("lr_scheduler_type", "linear"))
- # ── 1. Load model ──
# Force text-only for non-image datasets even on vision-capable models (e.g. Qwen3.5-VL on alpaca).
_send("status", status_message = f"Loading {model_name}...")
- # Pull through resume_from_checkpoint so MLXTrainer.train() can restore optimizer + step
- # state. Previously dropped on the MLX path, so the Resume button silently restarted from
- # step 0 (the CUDA path has been forwarding it all along).
+ # Pull through resume_from_checkpoint so MLXTrainer.train() can restore optimizer + step state. Previously dropped
+ # on the MLX path, so the Resume button silently restarted from step 0 (the CUDA path has been forwarding it all
+ # along).
resume_from_checkpoint = config.get("resume_from_checkpoint") or None
is_dataset_image = bool(config.get("is_dataset_image", False))
training_type = config.get("training_type", "LoRA/QLoRA")
@@ -2534,7 +2454,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
"status",
status_message = f"MLX vision image resize: {vision_image_size} (max dimension)",
)
- # ── 2. Apply LoRA / full FT ──
# gradient_checkpointing stays a string; get_peft_model and MLXTrainer both accept strings.
gc_setting = config.get("gradient_checkpointing", "mlx")
if isinstance(gc_setting, str):
@@ -2588,31 +2507,28 @@ def _run_mlx_training(event_queue, stop_queue, config):
peft_kwargs["finetune_vision_layers"] = finetune_vision
model = FastMLXModel.get_peft_model(model, **peft_kwargs)
- # ── 3. Load dataset ──
_send("status", status_message = "Loading dataset...")
hf_dataset = config.get("hf_dataset", "")
slice_start = config.get("dataset_slice_start")
slice_end = config.get("dataset_slice_end")
config["_dataset_loaded_from_exact_snapshot"] = False
- # A max_steps run cannot reach the whole dataset, and everything below here
- # (formatting, templating, tokenization) maps over every row. Recomputed from
- # the config, never carried over from the parent, so a bound can never be stale.
- # The vision branch is gated on `not raw_text_mode`, so a raw or CPT run takes
- # the text path, which honours the requested packing.
+ # A max_steps run cannot reach the whole dataset, and everything below here (formatting, templating, tokenization)
+ # maps over every row. Recomputed from the config, never carried over from the parent, so a bound can never be
+ # stale. The vision branch is gated on `not raw_text_mode`, so a raw or CPT run takes the text path, which honours
+ # the requested packing.
mlx_raw_text_mode = (
training_type == "Continued Pretraining" or config.get("format_type") == "raw"
)
- # An mlx.launch run shards the batch across its processes the same way DDP does,
- # and it advertises the count in the env this reads.
+ # An mlx.launch run shards the batch across its processes the same way DDP does, and it advertises the count in
+ # the env this reads.
mlx_max_train_rows = max_train_rows_for_config(
config,
branch_never_packs = is_vlm and not mlx_raw_text_mode,
world_size = _data_parallel_world_size(),
)
- # MLXTrainer resumes by jumping a batch cursor into a schedule rebuilt from
- # whatever dataset it is handed, so bounding a checkpoint written without one
- # continues on unrelated rows. Same marker, same rule as the CUDA path.
+ # MLXTrainer resumes by jumping a batch cursor into a schedule rebuilt from whatever dataset it is handed, so
+ # bounding a checkpoint written without one continues on unrelated rows. Same marker, same rule as the CUDA path.
mlx_max_train_rows, mlx_max_train_rows_seed = row_bound_for_resume(
resume_from_checkpoint, mlx_max_train_rows, random_seed
)
@@ -2698,14 +2614,12 @@ def _run_mlx_training(event_queue, stop_queue, config):
dataset_loaded_from_exact_snapshot = bool(config.get("_dataset_loaded_from_exact_snapshot")),
)
- # Eval dataset (separate split or local file)
from core.training.eval_dataset import evaluation_enabled
eval_enabled = evaluation_enabled(config.get("eval_steps"))
if eval_enabled and not hf_dataset and config.get("local_eval_datasets"):
eval_dataset = _load_local(config["local_eval_datasets"])
- # ── 3b. Format dataset (VLM or text) ──
# Reuse the GPU format pipeline for VLM (OCR/caption/llava/sharegpt+images) and text.
format_type = config.get("format_type", "")
custom_format_mapping = config.get("custom_format_mapping")
@@ -2809,7 +2723,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
else:
dataset, eval_dataset = split_result
- # ── 4. Resolve training steps ──
max_steps = config.get("max_steps", 0) or 0
num_epochs = config.get("num_epochs", 3)
max_seq_length = config.get("max_seq_length", 2048)
@@ -2832,7 +2745,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
if warmup_steps is None:
warmup_steps = 5
- # ── 5. Build output dir ──
# Resolve to ~/.unsloth/studio/outputs/ so the export page finds it
from utils.paths import ensure_dir
@@ -2857,7 +2769,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
),
)
- # ── 6. Create trainer ──
raw_eval_steps = config.get("eval_steps", 0)
if evaluation_enabled(raw_eval_steps):
eval_steps_value = float(raw_eval_steps)
@@ -2929,9 +2840,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
if "max_grad_leaf_norm" in _supported_fields:
mlx_config_kwargs["max_grad_leaf_norm"] = max_grad_leaf_norm
if "report_grad_norm" in _supported_fields:
- # Refills the gradient-norm chart. MLX returns a norm for free only under
- # global-norm clipping; asking for it beats switching clip modes, which
- # would alter the loss trajectory and cost VLM runs mx.compile.
+ # Refills the gradient-norm chart. MLX returns a norm for free only under global-norm clipping; asking for it
+ # beats switching clip modes, which would alter the loss trajectory and cost VLM runs mx.compile.
mlx_config_kwargs["report_grad_norm"] = True
if "append_eos" in _supported_fields:
# Unsloth SFT formatting owns rendered examples; raw/CPT text still needs MLX to append EOS.
@@ -2952,18 +2862,16 @@ def _run_mlx_training(event_queue, stop_queue, config):
if eval_dataset is not None and eval_steps_val > 0:
_send("eval_configured")
- # ── 7. Apply train_on_responses_only if requested ──
- # Auto-detect markers from the chat template first, manual table as fallback. Mirror the
- # CUDA skips: raw/CPT text has no chat turns.
- # Check the resolved format too, since format_type="auto" can land on alpaca or raw.
+ # Auto-detect markers from the chat template first, manual table as fallback. Mirror the CUDA skips: raw/CPT text
+ # has no chat turns. Check the resolved format too, since format_type="auto" can land on alpaca or raw.
if (
config.get("train_on_completions", False)
and not raw_text_mode
and dataset_final_format != "raw_text"
):
_send("status", status_message = "Configuring response-only training...")
- # No catch: the helper handles detection failures and double misses, so an exception here
- # is a real masking failure that must fail the run, not silently train full sequences.
+ # No catch: the helper handles detection failures and double misses, so an exception here is a real masking
+ # failure that must fail the run, not silently train full sequences.
from utils.datasets.completion_masking import apply_completion_masking
trainer, masking_applied = apply_completion_masking(
@@ -2974,9 +2882,9 @@ def _run_mlx_training(event_queue, stop_queue, config):
dataset_template = "alpaca" if dataset_final_format == "alpaca" else None,
)
if not masking_applied:
- # A miss changes the training objective for the whole run, so it belongs in the
- # sticky warning list the eval-split fallback already uses, not a status line
- # that scrolls past. Recovered detection failures stay status: masking applied.
+ # A miss changes the training objective for the whole run, so it belongs in the sticky warning list the
+ # eval-split fallback already uses, not a status line that scrolls past. Recovered detection failures stay
+ # status: masking applied.
_send(
"warning",
message = (
@@ -2986,7 +2894,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
),
)
- # ── 8. Setup wandb / tensorboard ──
wandb_run = None
tb_writer = None
if config.get("enable_wandb", False):
@@ -3025,7 +2932,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
status_message = "tensorboard unavailable (install tensorboardX)",
)
- # ── 9. Real-time progress callback ──
_send("status", status_message = f"Training {model_name}...")
def _on_step(
@@ -3110,7 +3016,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
trainer._build_optimizer = _capture_optimizer
- # ── 11. Run training ──
gc.collect()
mx.synchronize()
_save_model = trainer.save_model
@@ -3124,7 +3029,6 @@ def _run_mlx_training(event_queue, stop_queue, config):
finally:
trainer.save_model = _save_model
- # ── 12. Save and finalize ──
def _finish_tracking() -> None:
# Runs on every save/finalize exit so TB/W&B never leak on early return.
if tb_writer is not None:
@@ -3259,11 +3163,9 @@ def run_mlx_training_process(
def _training_job_is_local(config) -> bool:
- """True when neither the model nor the dataset needs the Hub, so the probe is wasted.
-
- Fail closed: anything unresolvable counts as remote, since skipping a needed probe
- costs the retry backoff the probe exists to avoid.
- """
+ """True when neither the model nor the dataset needs the Hub, so the probe is wasted. Fail
+ closed: anything unresolvable counts as remote, since skipping a needed probe costs the retry
+ backoff the probe exists to avoid."""
try:
from utils.paths import is_local_path
except Exception:
@@ -3274,8 +3176,8 @@ def _training_job_is_local(config) -> bool:
try:
if not (model and is_local_path(model)):
return False
- # A local checkpoint can name a remote base, which activation resolves and training and
- # security code later fetches. Readable from disk, so no network needed to decide.
+ # A local checkpoint can name a remote base, which activation resolves and training and security code later
+ # fetches. Readable from disk, so no network needed to decide.
base, needs_hub = _recorded_local_base(model)
if needs_hub:
return False
@@ -3285,11 +3187,9 @@ def _training_job_is_local(config) -> bool:
def _recorded_local_base(model_name) -> "tuple[str | None, bool]":
- """``(base, needs_hub)`` for the base this checkpoint records on disk.
-
- Delegates to the resolver's own disk reads so the gate cannot drift from what
- activation later resolves. Fail closed on an unavailable reader.
- """
+ """``(base, needs_hub)`` for the base this checkpoint records on disk. Delegates to the
+ resolver's own disk reads so the gate cannot drift from what activation later resolves. Fail
+ closed on an unavailable reader."""
try:
from utils.transformers_version import recorded_local_base
return recorded_local_base(model_name)
@@ -3298,13 +3198,9 @@ def _recorded_local_base(model_name) -> "tuple[str | None, bool]":
def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -> None:
- """Subprocess entrypoint. Fresh Python — no stale module state.
-
- Args:
- event_queue: mp.Queue for progress/status/error events to the parent.
- stop_queue: mp.Queue for stop commands from the parent.
- config: Training config dict with all parameters.
- """
+ """Subprocess entrypoint. Fresh Python, no stale module state. ``event_queue`` carries
+ progress/status/error events to the parent, ``stop_queue`` carries stop commands from it, and
+ ``config`` is the training config dict."""
# Off on Linux (forked map() workers deadlock); on spawn platforms map() is in-process.
os.environ["TOKENIZERS_PARALLELISM"] = (
"true" if sys.platform in ("win32", "darwin") else "false"
@@ -3323,9 +3219,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
flush = True,
)
- # Offline auto-detect: skip ~25s of HF retries per call when the hub is unreachable.
- # Skipped for a filesystem-only job: a local checkpoint with a local dataset never reaches
- # the Hub, and probing unconditionally would add seconds to every such startup.
+ # Offline auto-detect: skip ~25s of HF retries per call when the hub is unreachable. Skipped for a filesystem-only
+ # job: a local checkpoint with a local dataset never reaches the Hub, and probing unconditionally would add
+ # seconds to every such startup.
if "HF_HUB_OFFLINE" not in os.environ and not _training_job_is_local(config):
_offline = False
_network_offline = False
@@ -3338,8 +3234,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
if not _offline:
_offline = _network_offline = hf_dns_dead()
if not _offline and not hf_probe_disabled():
- # DNS answers even without egress (WAN down, captive portal). These flags last the whole
- # job, so only a connection failure counts: a momentary 502/503 must not block downloads.
+ # DNS answers even without egress (WAN down, captive portal). These flags last the whole job, so only
+ # a connection failure counts: a momentary 502/503 must not block downloads.
from utils.transformers_version import hf_endpoint_unreachable
_offline = _network_offline = hf_endpoint_unreachable(
gateway_errors_offline = False,
@@ -3350,8 +3246,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
if _offline:
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
- # Only when the network itself is the reason. TRANSFORMERS_OFFLINE alone asks for cached
- # model files, not a cache-only dataset: an uncached hf_dataset would fail the whole job.
+ # Only when the network itself is the reason. TRANSFORMERS_OFFLINE alone asks for cached model files, not
+ # a cache-only dataset: an uncached hf_dataset would fail the whole job.
if _network_offline:
os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
# logger isn't configured yet; print to stderr instead.
@@ -3367,11 +3263,10 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
warnings.filterwarnings("ignore")
- # This worker READS the bars: the monitor thread further down polls tqdm._instances
- # to turn the Hub download and "Loading checkpoint shards" bars into the UI's status
- # line, and a disabled bar is never registered there. So it redirects their output
- # instead of disabling them, and does so before the inherited
- # HF_HUB_DISABLE_PROGRESS_BARS reaches huggingface_hub's import-time constant.
+ # This worker READS the bars: the monitor thread further down polls tqdm._instances to turn the Hub download and
+ # "Loading checkpoint shards" bars into the UI's status line, and a disabled bar is never registered there. So it
+ # redirects their output instead of disabling them, and does so before the inherited HF_HUB_DISABLE_PROGRESS_BARS
+ # reaches huggingface_hub's import-time constant.
keep_progress_bars_countable()
LogConfig.setup_logging(
@@ -3387,8 +3282,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
model_name = config["model_name"]
model_load_target = _resolve_cached_model_load_name(config)
- # ── 0. MLX FAST-PATH (must run before any torch/transformers imports) ──
- # Apple Silicon uses MLXTrainer directly -- skip torch imports / installs.
+ # MLX fast path, before any torch/transformers import: Apple Silicon uses MLXTrainer directly and skips the torch
+ # imports and installs.
backend_path = str(Path(__file__).resolve().parent.parent.parent)
if backend_path not in sys.path:
sys.path.insert(0, backend_path)
@@ -3419,7 +3314,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 1. Activate correct transformers version BEFORE any ML imports ──
try:
_activate_transformers_version(
model_load_target,
@@ -3436,9 +3330,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 1a. Auto-enable trust_remote_code for NemotronH/Nano models ──
- # NemotronH needs trust_remote_code=True to work around config-parsing bugs; other 5.x
- # models are native (it bypasses the compiler, disabling fused CE). Not Llama-Nemotron.
+ # NemotronH needs trust_remote_code=True to work around config-parsing bugs; other 5.x models are native (it
+ # bypasses the compiler, disabling fused CE). Not Llama-Nemotron.
from utils.security.trusted_org import is_trusted_org_repo
_NEMOTRON_TRUST_SUBSTRINGS = ("nemotron_h", "nemotron-h", "nemotron-3-nano")
@@ -3509,23 +3402,21 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # No start-method override: Dataset.map() imports Pool from `multiprocess`, so forcing
- # stdlib multiprocessing onto "fork" never reached it; the guard now asks multiprocess.
+ # No start-method override: Dataset.map() imports Pool from `multiprocess`, so forcing stdlib multiprocessing onto
+ # "fork" never reached it; the guard now asks multiprocess.
- # ── 1c. On Windows, check Triton availability (must be before import torch) ──
- # Importable Triton isn't enough on AMD: its clang-cl JIT also needs the MSVC CRT headers (#7595).
+ # On Windows, check Triton availability before importing torch. Importable Triton isn't enough on AMD: its
+ # clang-cl JIT also needs the MSVC CRT headers (#7595).
if sys.platform == "win32":
from core._msvc_env import gate_torch_compile_on_windows
gate_torch_compile_on_windows(logger)
- # ── 1d. Stub torchao on Windows ROCm ──
- # See core/_torchao_stub.py (no RCCL on Windows ROCm); run before transformers/unsloth_zoo.
+ # Stub torchao on Windows ROCm; see core/_torchao_stub.py (no RCCL there). Run before transformers/unsloth_zoo.
from core._torchao_stub import install_torchao_windows_rocm_stub
install_torchao_windows_rocm_stub()
- # ── 1e. Ensure torch.distributed helper attrs are present ──
- # Single-GPU never inits the process group, but transformers/trl import these anyway.
+ # Single-GPU never inits the process group, but transformers/trl import these torch.distributed attrs anyway.
_td_stubs = {
"is_initialized": lambda: False,
"is_available": lambda: False,
@@ -3551,17 +3442,16 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
except Exception:
pass
- # ── 1f. Windows ROCm runtime patches ──
- # torch._grouped_mm has a null HIP kernel on gfx1200 (ROCm <= 7.12 Windows), causing
- # 0xC0000005 during training. JitDecomp (not torch.compile) dispatches _grouped_mm to the
- # null crash and TORCHDYNAMO_DISABLE doesn't cover it, so also override the CUDA dispatch
- # key with a Python fallback. Fixed in torch==2.11.0+rocm7.13.0, so gate on HIP < 7.13.
- # Schema: _grouped_mm(self, mat2, offs=None, bias=None, out_dtype=None); offs = group splits.
+ # Windows ROCm runtime patches. torch._grouped_mm has a null HIP kernel on gfx1200 (ROCm <= 7.12 Windows), causing
+ # 0xC0000005 during training. JitDecomp (not torch.compile) dispatches _grouped_mm to the null crash and
+ # TORCHDYNAMO_DISABLE doesn't cover it, so also override the CUDA dispatch key with a Python fallback. Fixed in
+ # torch==2.11.0+rocm7.13.0, so gate on HIP < 7.13. Schema: _grouped_mm(self, mat2, offs=None, bias=None,
+ # out_dtype=None); offs = group splits.
global _WINDOWS_ROCM_GROUPED_MM_LIB
if sys.platform == "win32":
_torch_for_rocm = sys.modules.get("torch")
- # Broad check (torch.version.hip OR "rocm" in __version__): AMD SDK / Radeon wheels don't
- # always set torch.version.hip, and the BNB pin, dynamo-disable and fallback would skip.
+ # Broad check (torch.version.hip OR "rocm" in __version__): AMD SDK / Radeon wheels don't always set
+ # torch.version.hip, and the BNB pin, dynamo-disable and fallback would skip.
_build_version_for_rocm = (
getattr(_torch_for_rocm, "__version__", "").lower()
if _torch_for_rocm is not None
@@ -3580,19 +3470,19 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
os.environ["TORCHDYNAMO_DISABLE"] = "1"
logger.info("Windows ROCm: torch.compile (dynamo) disabled")
- # bitsandbytes' import-time get_rocm_gpu_arch() probe runs `hipinfo.exe` from PATH; the AMD
- # torch wheel ships it in the venv Scripts dir, which is on PATH only for activated venvs.
- # Prepend it so the probe succeeds instead of logging a scary (harmless) error on every
- # import. Normally inherited from main.py, but workers can also be spawned standalone.
+ # bitsandbytes' import-time get_rocm_gpu_arch() probe runs `hipinfo.exe` from PATH; the AMD torch wheel
+ # ships it in the venv Scripts dir, which is on PATH only for activated venvs. Prepend it so the probe
+ # succeeds instead of logging a scary (harmless) error on every import. Normally inherited from main.py,
+ # but workers can also be spawned standalone.
_scripts_dir = os.path.dirname(sys.executable)
if os.path.isfile(os.path.join(_scripts_dir, "hipInfo.exe")):
import shutil as _shutil
if not _shutil.which("hipinfo.exe"):
os.environ["PATH"] = _scripts_dir + os.pathsep + os.environ.get("PATH", "")
- # BNB picks a rocm DLL from torch.version.hip, but AMD's Windows BNB wheel may ship a DLL
- # whose suffix doesn't match, so detect the actual DLL name and override. Installer-seeded
- # values are redetectable defaults; caller overrides stay authoritative.
+ # BNB picks a rocm DLL from torch.version.hip, but AMD's Windows BNB wheel may ship a DLL whose suffix
+ # doesn't match, so detect the actual DLL name and override. Installer-seeded values are redetectable
+ # defaults; caller overrides stay authoritative.
if (
"BNB_ROCM_VERSION" not in os.environ
or os.environ.get("UNSLOTH_BNB_ROCM_VERSION_SOURCE") == "sitecustomize"
@@ -3623,9 +3513,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_bnb_rocm_ver = max(_all_vers, key = lambda v: int(v))
except Exception:
pass
- # Only when a ROCm bnb DLL actually exists (mirrors main.py): without one the seeded value
- # and its marker stay untouched, so later import fixes can still redetect or opt out.
- # A DLL with an unparsable name falls back to the seeded value or "72".
+ # Only when a ROCm bnb DLL actually exists (mirrors main.py): without one the seeded value and its
+ # marker stay untouched, so later import fixes can still redetect or opt out. A DLL with an unparsable
+ # name falls back to the seeded value or "72".
if _found_rocm_bnb:
_bnb_rocm_ver = _bnb_rocm_ver or os.environ.get("BNB_ROCM_VERSION") or "72"
os.environ["BNB_ROCM_VERSION"] = _bnb_rocm_ver
@@ -3637,16 +3527,16 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_bnb_rocm_ver,
)
- # Setting BNB_ROCM_VERSION makes bitsandbytes log a benign override notice on import;
- # drop only that record so real errors and mismatch warnings still show.
+ # Setting BNB_ROCM_VERSION makes bitsandbytes log a benign override notice on import; drop only that
+ # record so real errors and mismatch warnings still show.
if os.environ.get("BNB_ROCM_VERSION"):
import logging as _logging
_logging.getLogger("bitsandbytes.cextension").addFilter(
lambda _r: "environment variable detected" not in _r.getMessage()
)
- # Parse HIP version for the kernel-fix gate below, falling back to the rocm version in
- # torch.__version__ when version.hip is unset (AMD SDK / Radeon wheels).
+ # Parse HIP version for the kernel-fix gate below, falling back to the rocm version in torch.__version__
+ # when version.hip is unset (AMD SDK / Radeon wheels).
def _hip_ver_at_least(major: int, minor: int) -> bool:
_hip_str = getattr(getattr(_torch_for_rocm, "version", None), "hip", None)
if not _hip_str:
@@ -3709,15 +3599,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
"skipping Python fallback (AMD fixed gfx1200 null kernel in ROCm 7.13)"
)
+ # The win32 guard above misses Linux: RDNA4 (gfx1200/gfx1201) hits the same null HIP _grouped_mm kernel at ROCm <=
+ # 7.12 (fixed 7.13, ROCm/TheRock #5284). Gate on arch + HIP.
# ── 1f-linux. Linux ROCm RDNA4 _grouped_mm null kernel ──
- # The win32 guard above misses Linux: RDNA4 (gfx1200/gfx1201) hits the same null HIP
- # _grouped_mm kernel at ROCm <= 7.12 (fixed 7.13, ROCm/TheRock #5284). Gate on arch + HIP.
if sys.platform.startswith("linux") and _hw.IS_ROCM:
try:
_torch_lin = sys.modules.get("torch")
if _torch_lin is not None and _torch_lin.cuda.is_available():
- # Prefer torch.version.hip, else rocmX.Y from torch.__version__ (AMD SDK / Radeon wheels
- # leave it unset). Unknown version on gfx120X -> assume affected unless a post-fix rocmsdk.
+ # Prefer torch.version.hip, else rocmX.Y from torch.__version__ (AMD SDK / Radeon wheels leave it
+ # unset). Unknown version on gfx120X -> assume affected unless a post-fix rocmsdk.
_hip_str = str(getattr(getattr(_torch_lin, "version", None), "hip", "") or "")
_ver = getattr(_torch_lin, "__version__", "").lower()
_m = re.match(r"(\d+)\.(\d+)", _hip_str) or re.search(r"rocm(\d+)\.(\d+)", _ver)
@@ -3725,8 +3615,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_hip_lt_713 = (int(_m.group(1)), int(_m.group(2))) < (7, 13)
else:
_hip_lt_713 = "rocmsdk" not in _ver
- # Scan every visible GPU (device_map="balanced" can place layers on a later RDNA4 card).
- # Match gfx120X by arch, or by RX 9000 / R9700 name when the wheel omits gcnArchName.
+ # Scan every visible GPU (device_map="balanced" can place layers on a later RDNA4 card). Match gfx120X
+ # by arch, or by RX 9000 / R9700 name when the wheel omits gcnArchName.
_rdna4 = False
for _i in range(_torch_lin.cuda.device_count()):
_props = _torch_lin.cuda.get_device_properties(_i)
@@ -3744,12 +3634,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
except Exception as _gm_lin_exc:
logger.warning("Linux ROCm gfx120X: could not patch _grouped_mm: %s", _gm_lin_exc)
- # ── 1g. ROCm OOM guard ──
- # On ROCm, exhausting VRAM can hang the HIP driver instead of raising.
- # set_per_process_memory_fraction caps the allocator so PyTorch raises OutOfMemoryError
- # first. Unified hosts share GPU+system RAM and need OS headroom, so the cap depends on
- # the classification and the pool size (see _rocm_memory_fraction and
+ # ROCm OOM guard: exhausting VRAM can hang the HIP driver instead of raising, so set_per_process_memory_fraction
+ # caps the allocator and PyTorch raises OutOfMemoryError first. Unified hosts share GPU+system RAM and need OS
+ # headroom, so the cap depends on the classification and the pool size (see _rocm_memory_fraction and
# _rocm_classify_unified_memory). Skipped if no torch.
+ # ── 1g. ROCm OOM guard ──
if _hw.IS_ROCM:
try:
import torch as _torch_mem
@@ -3764,17 +3653,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
"unified memory from device name %r; applying unified cap",
_dev_name,
)
- # Unified hosts on native Windows: mem_get_info's total is the WDDM budget the driver
- # grants HIP (BIOS carve + ~half of remaining RAM). The OS share is already outside it, so
- # any sub-1.0 starve-protection double-taxes (48.49 GiB budget -> 38.79 allowed) and
- # blocks loads that fit in free memory. Current AMD Windows wheels only enforce sub-1.0
- # fractions (gfx1151: 0.5 caps, 1.0 overcommits via WDDM), so 1.0 behaves like torch's
- # uncapped default. On Linux the total spans nearly all RAM, so keep a bounded headroom
- # (see _rocm_memory_fraction).
- # props.total_memory is the pool the reserve comes out of, and from torch
- # 2.10 also what the allocator scales. Through 2.9 it scales hipMemGetInfo's
- # total, a different number on a unified APU, so hand that to the helper on
- # those wheels and the reserve is the same bytes either way.
+ # Unified hosts on native Windows: mem_get_info's total is the WDDM budget the driver grants HIP (BIOS
+ # carve + ~half of remaining RAM). The OS share is already outside it, so any sub-1.0
+ # starve-protection double-taxes (48.49 GiB budget -> 38.79 allowed) and blocks loads that fit in free
+ # memory. Current AMD Windows wheels only enforce sub-1.0 fractions (gfx1151: 0.5 caps, 1.0
+ # overcommits via WDDM), so 1.0 behaves like torch's uncapped default. On Linux the total spans nearly
+ # all RAM, so keep a bounded headroom. props.total_memory is the pool the reserve comes out of, and
+ # from torch 2.10 also what the allocator scales; through 2.9 it scales hipMemGetInfo's total, a
+ # different number on a unified APU, so hand that to the helper on those wheels and the reserve is the
+ # same bytes either way.
_total_bytes = int(getattr(_props, "total_memory", 0) or 0)
_driver_total = 0
if not _allocator_divides_by_props_total(getattr(_torch_mem, "__version__", "")):
@@ -3794,8 +3681,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_mem_fraction = _rocm_memory_fraction(
_total_bytes, _is_unified, sys.platform, _env_raw, _driver_total or None
)
- # A wheel that reports no total still gets a cap; say so rather than
- # printing "0.0 of 0.0 GiB allowed" on the one host whose props are suspect.
+ # A wheel that reports no total still gets a cap; say so rather than printing "0.0 of 0.0 GiB allowed"
+ # on the one host whose props are suspect.
_allowed = (
f"{_total_bytes * _mem_fraction / 1024**3:.1f} of "
f"{_total_bytes / 1024**3:.1f} GiB allowed"
@@ -3815,9 +3702,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
if _env_fraction is not None
else f"computed; override with {_MEM_FRACTION_ENV}",
)
- # When the totals differ the cap was solved against the driver's, so the
- # budget printed above is not the one enforced. Give both, and the headroom
- # that results, which the floor can leave under the intended reserve.
+ # When the totals differ the cap was solved against the driver's, so the budget printed above is not
+ # the one enforced. Give both, and the headroom that results, which the floor can leave under the
+ # intended reserve.
if (
_is_unified
and sys.platform != "win32"
@@ -3837,8 +3724,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_UNIFIED_OS_RESERVE_BYTES / 1024**3,
_MEM_FRACTION_ENV,
)
- # Unified Windows APUs: the WDDM budget is user-raisable, but nothing on the box says so
- # -- users see "48 GB VRAM" on a 96 GB machine. Say where the limit comes from.
+ # Unified Windows APUs: the WDDM budget is user-raisable, but nothing on the box says so -- users see
+ # "48 GB VRAM" on a 96 GB machine. Say where the limit comes from.
if _is_unified and sys.platform == "win32":
try:
import psutil as _psutil
@@ -3896,9 +3783,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 2b. EMBEDDING MODEL FAST-PATH ──
- # Embedding models use a different pipeline (FastSentenceTransformer +
- # SentenceTransformerTrainer + MultipleNegativesRankingLoss), so branch early.
+ # Embedding models use a different pipeline (FastSentenceTransformer + SentenceTransformerTrainer +
+ # MultipleNegativesRankingLoss), so branch early.
if config.get("is_embedding", False):
try:
_run_embedding_training(event_queue, stop_queue, config)
@@ -3913,7 +3799,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 3. Create a fresh trainer instance ──
trainer = UnslothTrainer()
trainer.add_progress_callback(_create_trainer_progress_callback(event_queue))
@@ -3925,8 +3810,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_start_worker_stop_poller(stop_queue, _apply_stop)
- # ── 4. Execute the training pipeline ──
- # Order: detect -> dataset -> model -> prepare -> train, so both never hold VRAM at once.
+ # Pipeline order: detect -> dataset -> model -> prepare -> train, so both never hold VRAM at once.
try:
hf_token = config.get("hf_token", "")
hf_token = hf_token if hf_token and hf_token.strip() else None
@@ -3983,7 +3867,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
config["dataset_snapshot_path"] = snapshot
return loaded_dataset, loaded_eval_dataset
- # ── 4a. Lightweight detection + tokenizer (no VRAM) ──
_send_status(event_queue, "Detecting model type...")
try:
_pre_detect_training_model(
@@ -4028,30 +3911,27 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})
return
- # 4a has probed the model, so the packing opt-out can read the real branch
- # instead of guessing from the client's dataset flags. Streaming and explicit
- # train-split ranges opt out inside load_and_format_dataset.
- # Audio codecs are chosen before the raw-text bypass and use plain Trainers
- # with no packing argument, so they hold either way; the vision and audio-VLM
- # branches are gated on `not raw_text_mode`, so a raw or CPT run takes the
- # text path, which honours packing.
+ # 4a has probed the model, so the packing opt-out can read the real branch instead of guessing from the
+ # client's dataset flags. Streaming and explicit train-split ranges opt out inside load_and_format_dataset.
+ # Audio codecs are chosen before the raw-text bypass and use plain Trainers with no packing argument, so they
+ # hold either way; the vision and audio-VLM branches are gated on `not raw_text_mode`, so a raw or CPT run
+ # takes the text path, which honours packing.
raw_text_mode = is_cpt_for_dataset or config.get("format_type") == "raw"
branch_never_packs = bool(getattr(trainer, "_audio_type", None)) or (
bool(getattr(trainer, "is_vlm", False) or getattr(trainer, "is_audio_vlm", False))
and not raw_text_mode
)
- # Every replica draws its own batch per step, so the subset has to cover all of
- # them; sized here rather than in the config because it is a property of this
- # machine's launch. Model probing is done, so torch and the GPU mask are settled.
+ # Every replica draws its own batch per step, so the subset has to cover all of them; sized here rather than
+ # in the config because it is a property of this machine's launch. Model probing is done, so torch and the GPU
+ # mask are settled.
max_train_rows = max_train_rows_for_config(
config,
branch_never_packs = branch_never_packs,
world_size = _data_parallel_world_size(),
)
- # A resume trains on the rows its first start chose, read back from the marker
- # beside the checkpoints. No marker means the checkpoint predates the bound and
- # trained on the whole dataset; since the trainer fast-forwards by batch count
- # over the current dataloader, bounding it now would continue on unrelated rows.
+ # A resume trains on the rows its first start chose, read back from the marker beside the checkpoints. No
+ # marker means the checkpoint predates the bound and trained on the whole dataset; since the trainer
+ # fast-forwards by batch count over the current dataloader, bounding it now would continue on unrelated rows.
resumed_rows, max_train_rows_seed = row_bound_for_resume(
config.get("resume_from_checkpoint"), max_train_rows, max_train_rows_seed
)
@@ -4061,9 +3941,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
f"({resumed_rows} rows) instead of {max_train_rows}\n"
)
if resumed_rows and max_train_rows and resumed_rows < max_train_rows:
- # Sized for fewer replicas than this machine has: the recorded subset
- # is what the run trained on and re-deriving it would continue on
- # unrelated rows, so it stays, but say that the extra ranks may reach
+ # Sized for fewer replicas than this machine has: the recorded subset is what the run trained on and
+ # re-deriving it would continue on unrelated rows, so it stays, but say that the extra ranks may reach
# the end of it and start over.
logger.info(
"That subset was sized for a smaller data-parallel world than this "
@@ -4072,7 +3951,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
max_train_rows = resumed_rows
- # ── 4b. Load and format dataset (LLM helper may use VRAM briefly) ──
_send_status(event_queue, "Loading and formatting dataset...")
dataset, eval_dataset = _load_training_dataset()
@@ -4090,7 +3968,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── Start tqdm monitor early to capture download + tokenization bars ──
+ # Start the tqdm monitor early to capture download + tokenization bars.
import threading as _th
_tqdm_stop = _th.Event()
@@ -4117,8 +3995,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
use_lora = training_type in ("LoRA/QLoRA", "Continued Pretraining")
cpt_trains_embeddings = False
- # ── 4c. Load training model (uses VRAM — dataset already formatted) ──
- # Watchdog lets the parent recover a stalled Xet download via respawn.
+ # Loading the training model uses VRAM, and the dataset is already formatted. The watchdog lets the parent
+ # recover a stalled Xet download via respawn.
_send_status(event_queue, "Loading model...")
from utils.hf_xet_fallback import start_watchdog
@@ -4259,12 +4137,10 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
}
)
- # ── 4d. Prepare model (LoRA, full finetuning, or CPT) ──
if is_cpt:
_send_status(event_queue, "Configuring LoRA for continued pretraining...")
- # Both go to modules_to_save: trained full-precision at
- # embedding_learning_rate, since LoRA on either never trains.
- # By leaf: PEFT resolves model.embed_tokens to the same module.
+ # Both go to modules_to_save: trained full-precision at embedding_learning_rate, since LoRA on either
+ # never trains. By leaf: PEFT resolves model.embed_tokens to the same module.
_embedding_modules = ("embed_tokens", "lm_head")
_user_modules = config.get("target_modules") or []
_leaf = lambda m: str(m).rsplit(".", 1)[-1] # noqa: E731
@@ -4373,11 +4249,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
output_dir = str(resolve_output_dir(output_dir))
ensure_dir(Path(output_dir))
_emit_output_dir(event_queue, output_dir)
- # Pin the subset before any checkpoint lands here, so a resume reads it back
- # rather than deriving it from a config the user may have edited in between.
+ # Pin the subset before any checkpoint lands here, so a resume reads it back rather than deriving it from a
+ # config the user may have edited in between.
if not record_row_bound(output_dir, max_train_rows, max_train_rows_seed) and max_train_rows:
- # Not fatal, and nothing to fall back to: the dataset is already bounded.
- # Say it, so a later resume reading this run as unbounded is explainable.
+ # Not fatal, and nothing to fall back to: the dataset is already bounded. Say it, so a later resume
+ # reading this run as unbounded is explainable.
logger.warning(
f"Could not record the max_steps row bound in {output_dir}: "
"resuming this run later will read it as unbounded\n"
@@ -4546,10 +4422,8 @@ def _mlx_has_checkpoint_at_step(output_dir, step: int) -> bool:
def _write_mlx_stop_checkpoint(trainer, optimizer, output_dir) -> bool:
- """Write a full resume checkpoint for a stopped MLX run.
-
- Returns True when a checkpoint for the current training step exists.
- """
+ """Write a full resume checkpoint for a stopped MLX run. Returns True when a checkpoint for the
+ current training step exists."""
step = int(getattr(trainer, "_global_step", 0) or 0)
# A periodic save or a resumed run may already cover the current step.
if _mlx_has_checkpoint_at_step(output_dir, step):
@@ -4587,14 +4461,14 @@ def _write_mlx_stop_checkpoint(trainer, optimizer, output_dir) -> bool:
def _create_trainer_progress_callback(event_queue: Any) -> Callable[[TrainingProgress], None]:
"""UnslothTrainer callback that reports training progress to the parent.
- Status events go out only while the status is non-empty, so the empty status the
- trainer reports on every log leaves the parent's last real status standing.
+ Status events go out only while the status is non-empty, so the empty status the trainer reports
+ on every log leaves the parent's last real status standing.
- The trainer shares one TrainingProgress for metrics and status, so a status-only
- update (an evaluation line, a warning) carries the last step's numbers unchanged.
- The parent appends every progress event to the loss / grad-norm / eval-loss
- histories without deduplicating the step, so those replays would plot the same
- point again. Only a changed measurement is published; the status still is.
+ The trainer shares one TrainingProgress for metrics and status, so a status-only update (an
+ evaluation line, a warning) carries the last step's numbers unchanged. The parent appends every
+ progress event to the loss / grad-norm / eval-loss histories without deduplicating the step, so
+ those replays would plot the same point again. Only a changed measurement is published; the
+ status still is.
"""
sent_warnings: set[str] = set()
@@ -4603,15 +4477,14 @@ def _create_trainer_progress_callback(event_queue: Any) -> Callable[[TrainingPro
def _on_progress(progress: TrainingProgress) -> None:
has_train_loss = progress.step > 0 and progress.loss is not None
has_eval_loss = progress.eval_loss is not None
- # The end-of-run summary carries no loss (it is the mean, not a step), but it
- # does carry the elapsed time including the final evaluation, checkpoint save
- # and best-model reload, and a run stopped early never reaches total_steps, so
- # the flag the trainer sets on that record is what marks it terminal.
+ # The end-of-run summary carries no loss (it is the mean, not a step), but it does carry the elapsed time
+ # including the final evaluation, checkpoint save and best-model reload, and a run stopped early never reaches
+ # total_steps, so the flag the trainer sets on that record is what marks it terminal.
is_terminal = bool(getattr(progress, "is_run_summary", False)) or (
progress.total_steps > 0 and progress.step >= progress.total_steps
)
- # Wall-clock fields are excluded: they move on every call, so keeping them
- # would make each status replay look like a new measurement.
+ # Wall-clock fields are excluded: they move on every call, so keeping them would make each status replay look
+ # like a new measurement.
metrics = (
progress.step,
progress.loss,
@@ -4663,11 +4536,8 @@ def _create_embedding_progress_callback(
training_start_time: float,
should_stop: Callable[[], bool],
):
- """TrainerCallback that reports embedding training progress to the parent.
-
- ``should_stop`` is polled in on_train_begin and on_step_end, so a stop signal
- arriving mid-run is seen.
- """
+ """TrainerCallback that reports embedding training progress to the parent. ``should_stop`` is
+ polled in on_train_begin and on_step_end, so a stop signal arriving mid-run is seen."""
from transformers import TrainerCallback
class _EmbeddingProgressCallback(TrainerCallback):
@@ -4687,9 +4557,9 @@ def _create_embedding_progress_callback(
):
if not logs:
return
- # Trainer's end-of-run summary carries train_runtime, samples and steps per
- # second, total_flos and memory, which nothing else here publishes. It used
- # to reach the log only through PrinterCallback's raw stdout dict.
+ # Trainer's end-of-run summary carries train_runtime, samples and steps per second, total_flos and memory,
+ # which nothing else here publishes. It used to reach the log only through PrinterCallback's raw stdout
+ # dict.
from core.training.trainer import _RESERVED_LOG_KEYS, _TRAINER_SUMMARY_KEYS
if any(k in logs for k in _TRAINER_SUMMARY_KEYS):
@@ -4701,8 +4571,8 @@ def _create_embedding_progress_callback(
if isinstance(k, str) and k not in _RESERVED_LOG_KEYS
},
)
- # See the note in trainer.py: "train_loss" in HF's terminal summary record is
- # the run mean, not a step loss, so it must not become the final step.
+ # See the note in trainer.py: "train_loss" in HF's terminal summary record is the run mean, not a step
+ # loss, so it must not become the final step.
loss_value = logs.get("loss")
if loss_value is None and logs.get("train_loss") is not None:
print(
@@ -4747,14 +4617,10 @@ def _create_embedding_progress_callback(
def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) -> None:
- """Self-contained embedding model training pipeline.
-
- Uses FastSentenceTransformer + SentenceTransformerTrainer +
- MultipleNegativesRankingLoss — separate from UnslothTrainer's LLM/VLM/audio
- paths. Mirrors the reference embedding notebooks:
- All_MiniLM_L6_v2.py, BGE_M3.py, EmbeddingGemma_300M.py,
- ModernBert.py, Qwen3_Embedding_0_6B.py
- """
+ """Self-contained embedding model training pipeline. Uses FastSentenceTransformer +
+ SentenceTransformerTrainer + MultipleNegativesRankingLoss, separate from UnslothTrainer's
+ LLM/VLM/audio paths. Mirrors the reference embedding notebooks: All_MiniLM_L6_v2.py,
+ BGE_M3.py, EmbeddingGemma_300M.py, ModernBert.py, Qwen3_Embedding_0_6B.py"""
import math
model_name = config["model_name"]
@@ -4763,7 +4629,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
model_revision = None if model_local_only else config.get("model_revision")
training_start_time = time.time()
- # ── 1. Import embedding-specific libraries ──
_send_status(event_queue, "Importing embedding libraries...")
try:
# Recover from a namespace-package shadow (embedding imports unsloth directly).
@@ -4792,17 +4657,15 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # datasets is only in the process now, and setup_logging ran long before it, so
- # this is the first point where its Generating/Map bars can be quieted. Without
- # it a local JSON/CSV/Parquet or Hub load_dataset writes them into this worker's
- # structured log.
+ # datasets is only in the process now, and setup_logging ran long before it, so this is the first point where its
+ # Generating/Map bars can be quieted. Without it a local JSON/CSV/Parquet or Hub load_dataset writes them into
+ # this worker's structured log.
try:
from loggers.config import quiet_third_party_progress_bars
quiet_third_party_progress_bars()
except Exception: # noqa: BLE001 - never let log tidying stop a run
pass
- # ── Stop signal handling ──
_should_stop = False
_save_on_stop = True
@@ -4817,7 +4680,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
_start_worker_stop_poller(stop_queue, _apply_stop)
- # ── 2. Load model ──
_send_status(event_queue, "Loading embedding model...")
try:
hf_token = config.get("hf_token", "")
@@ -4884,12 +4746,11 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})
return
- # ── 3. Apply LoRA ──
if use_lora:
_send_status(event_queue, "Configuring LoRA adapters (FEATURE_EXTRACTION)...")
try:
gradient_checkpointing = config.get("gradient_checkpointing", False)
- # Normalize "none"/empty → False.
+ # Normalize "none"/empty to False.
if gradient_checkpointing in ("none", "", None):
gradient_checkpointing = False
@@ -4925,7 +4786,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})
return
- # ── 4. Load dataset ──
_send_status(event_queue, "Loading dataset...")
try:
config["_dataset_loaded_from_exact_snapshot"] = False
@@ -5043,10 +4903,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
dataset_loaded_from_exact_snapshot = bool(config.get("_dataset_loaded_from_exact_snapshot")),
)
- # ── 5. Create loss function ──
loss = MultipleNegativesRankingLoss(model)
- # ── 6. Build training arguments ──
_send_status(event_queue, "Configuring training...")
try:
lr_value = float(config.get("learning_rate", "2e-4"))
@@ -5098,9 +4956,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
"optim": config.get("optim", "adamw_8bit"),
"weight_decay": config.get("weight_decay", 0.001),
"seed": config.get("random_seed", 3407),
- # Same reason as the UnslothTrainer path: this worker has no terminal, its
- # stdout is teed into the server log, and _create_embedding_progress_callback
- # already publishes every number the bar carries.
+ # Same reason as the UnslothTrainer path: this worker has no terminal, its stdout is teed into the server log,
+ # and _create_embedding_progress_callback already publishes every number the bar carries.
"disable_tqdm": _hf_stdout_progress_disabled(),
}
@@ -5121,7 +4978,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
args = SentenceTransformerTrainingArguments(**training_args_kwargs)
- # ── 7. Calculate total steps for progress tracking ──
if max_steps_val and max_steps_val > 0:
total_steps = max_steps_val
else:
@@ -5130,7 +4986,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
steps_per_epoch = max(len_dataloader // gradient_accumulation_steps, 1)
total_steps = steps_per_epoch * effective_epochs
- # ── 8. Create progress callback ──
progress_callback = _create_embedding_progress_callback(
event_queue,
total_steps = total_steps,
@@ -5138,7 +4993,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
should_stop = lambda: _should_stop,
)
- # ── 9. Create trainer and train ──
_send_status(event_queue, "Starting embedding training...")
try:
trainer = SentenceTransformerTrainer(
@@ -5148,8 +5002,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
args = args,
callbacks = [progress_callback],
)
- # disable_tqdm only swaps ProgressCallback for PrinterCallback, which prints a
- # raw dict per step instead; both write to the same stdout.
+ # disable_tqdm only swaps ProgressCallback for PrinterCallback, which prints a raw dict per step instead; both
+ # write to the same stdout.
_drop_hf_stdout_callbacks(trainer)
trainer.train(resume_from_checkpoint = resume_from_checkpoint)
@@ -5164,7 +5018,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 10. Save model ──
if _should_stop and not _save_on_stop:
event_queue.put(
{
@@ -5195,7 +5048,6 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── 11. Done ──
event_queue.put(
{
"type": "complete",