Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make code comments and docstrings more succinct (#6029)

Daniel Han8292e699e4d4
diff --git a/studio/backend/_platform_compat.py b/studio/backend/_platform_compat.py
index 490e1820d71..37bf5e3fb53 100644
--- a/studio/backend/_platform_compat.py
+++ b/studio/backend/_platform_compat.py
@@ -4,17 +4,17 @@
"""
Compatibility shim for Anaconda/conda-forge Python builds.
-Anaconda modifies sys.version to include distributor metadata between pipe
-characters, e.g. '3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'.
-Python's platform._sys_version() has a hardcoded regex that cannot parse this,
-raising ValueError. CPython closed this as "not planned" (cpython#102396).
+Anaconda puts distributor metadata between pipes in sys.version, e.g.
+'3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'. The hardcoded
+regex in platform._sys_version() can't parse this and raises ValueError;
+CPython closed it as "not planned" (cpython#102396).
-This module seeds platform._sys_version_cache so the stdlib parser never sees
-the problematic string, fixing the import chain:
+We seed platform._sys_version_cache so the stdlib parser never sees the bad
+string, fixing the import chain:
structlog -> rich.pretty -> attrs._compat -> platform.python_implementation()
-Import this module before any library imports that may trigger the above chain.
-Safe to import multiple times (no-op if cache is already seeded or no pipes).
+Import before any library that may trigger that chain. Idempotent (no-op if the
+cache is already seeded or there are no pipes).
"""
import platform
@@ -29,12 +29,12 @@ def _seed_sys_version_cache() -> None:
# Strip paired |...| segments (Anaconda, conda-forge metadata)
cleaned = re.sub(r"\s*\|[^|]*\|\s*", " ", raw).strip()
- # Format B: "ver (build) | label | (build_dup) \n[compiler]"
- # After pipe-strip, two consecutive (...) groups remain; drop the second.
+ # Format B: "ver (build) | label | (build_dup) \n[compiler]" leaves two
+ # consecutive (...) groups after pipe-strip; drop the second.
cleaned = re.sub(r"(\([^)]*\))\s+\([^)]*\)", r"\1", cleaned)
if "|" in cleaned:
- # Unpaired pipe remaining -- keep version + everything from "(" onward
+ # Unpaired pipe left: keep version + everything from "(" onward
m = re.match(r"([\w.+]+)\s*", cleaned)
p = cleaned.find("(")
if m and p > 0:
@@ -47,9 +47,9 @@ def _seed_sys_version_cache() -> None:
try:
result = platform._sys_version(cleaned)
except ValueError:
- return # Cleaning didn't produce a parseable string; don't make things worse
+ return # Still unparsable; don't make things worse
- # Seed the cache so future calls with the raw string skip parsing entirely
+ # Seed the cache so future calls with the raw string skip parsing
cache = getattr(platform, "_sys_version_cache", None)
if isinstance(cache, dict):
cache[raw] = result
diff --git a/studio/backend/auth/__init__.py b/studio/backend/auth/__init__.py
index b3e1a8a9c05..a63d5303d4b 100644
--- a/studio/backend/auth/__init__.py
+++ b/studio/backend/auth/__init__.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Authentication module for JWT-based auth with SQLite storage.
-"""
+"""Authentication module for JWT-based auth with SQLite storage."""
from .authentication import (
create_access_token,
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.py
index bb5b873e659..6509cb68250 100644
--- a/studio/backend/auth/authentication.py
+++ b/studio/backend/auth/authentication.py
@@ -58,7 +58,7 @@ def create_access_token(
"""
Create a signed JWT for the given subject (e.g. username).
- Tokens are valid across restarts because the signing secret is stored in SQLite.
+ Valid across restarts: the signing secret is stored in SQLite.
"""
to_encode = {"sub": subject}
if desktop:
@@ -100,7 +100,7 @@ def create_refresh_token(subject: str, *, desktop: bool = False) -> str:
"""
Create a random refresh token, store its hash in SQLite, and return it.
- Refresh tokens are opaque (not JWTs) and expire after REFRESH_TOKEN_EXPIRE_DAYS.
+ Refresh tokens are opaque (not JWTs); expire after REFRESH_TOKEN_EXPIRE_DAYS.
"""
token = secrets.token_urlsafe(48)
expires_at = datetime.now(timezone.utc) + timedelta(days = REFRESH_TOKEN_EXPIRE_DAYS)
@@ -112,8 +112,8 @@ def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[st
"""
Validate a refresh token and issue a new access token.
- The refresh token itself is NOT consumed — it stays valid until expiry.
- Returns a new access_token or None if the refresh token is invalid/expired.
+ The refresh token is NOT consumed; it stays valid until expiry.
+ Returns a new access_token, or None if the refresh token is invalid/expired.
"""
verified = verify_refresh_token(refresh_token)
if verified is None:
@@ -128,7 +128,7 @@ def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[st
def reload_secret() -> None:
"""
- Keep legacy API compatibility for callers expecting auth storage init.
+ Legacy API compat for callers expecting auth storage init.
Auth now resolves the current signing secret directly from SQLite.
"""
@@ -157,9 +157,9 @@ async def _get_current_subject(
credentials: HTTPAuthorizationCredentials, *, allow_password_change: bool
) -> str:
"""
- FastAPI dependency to validate the JWT and return the subject.
+ FastAPI dependency: validate the JWT and return the subject.
- Use this as a dependency on routes that should be protected, e.g.:
+ Use as a dependency on protected routes, e.g.:
@router.get("/secure")
async def secure_endpoint(current_subject: str = Depends(get_current_subject)):
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 0e34a0cf286..42e2de74509 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-SQLite storage for authentication data (user credentials + JWT secret).
-"""
+"""SQLite storage for auth data (user credentials + JWT secret)."""
import hashlib
import os
@@ -17,20 +15,19 @@ from utils.paths import auth_db_path, ensure_dir
DB_PATH = auth_db_path()
DEFAULT_ADMIN_USERNAME = "unsloth"
-# Plaintext bootstrap password file — lives beside auth.db, deleted on
-# first password change so the credential never lingers on disk.
+# Plaintext bootstrap password file beside auth.db, deleted on first password
+# change so the credential never lingers on disk.
_BOOTSTRAP_PW_PATH = DB_PATH.parent / ".bootstrap_password"
-# In-process cache so we don't re-read the file on every HTML serve.
+# In-process cache to avoid re-reading the file on every HTML serve.
_bootstrap_password: Optional[str] = None
def generate_bootstrap_password() -> str:
"""Generate a 4-word diceware passphrase and persist it to disk.
- The passphrase is written to ``_BOOTSTRAP_PW_PATH`` so that it
- survives server restarts (the DB only stores the *hash*). On
- subsequent calls / restarts, the persisted value is returned.
+ Written to ``_BOOTSTRAP_PW_PATH`` so it survives restarts (the DB only
+ stores the *hash*). Later calls / restarts return the persisted value.
"""
global _bootstrap_password
@@ -51,7 +48,7 @@ def generate_bootstrap_password() -> str:
options = diceware.handle_options(args = ["-n", "4", "-d", "", "-c"])
)
- # Persist so the *same* passphrase is used if the server restarts
+ # Persist so the *same* passphrase is reused if the server restarts
# before the user changes the password.
ensure_dir(_BOOTSTRAP_PW_PATH.parent)
_BOOTSTRAP_PW_PATH.write_text(_bootstrap_password)
@@ -88,21 +85,19 @@ def clear_bootstrap_password() -> None:
def _hash_token(token: str) -> str:
- """SHA-256 hash helper used for refresh token storage.
-
- Plain SHA-256 is intentional here: refresh tokens are high-entropy
- random strings from ``secrets.token_urlsafe(48)`` (384 bits of
- entropy), so a slow KDF (Argon2 / bcrypt / PBKDF2) provides zero
- additional security — no attacker can brute-force 2^384 regardless
- of hash speed — while adding tens of ms of CPU to every refresh.
- See the OWASP Password Storage Cheat Sheet on fast-vs-slow hashing
- of high-entropy inputs.
-
- API keys use the separate ``_pbkdf2_api_key`` helper below, which
- runs PBKDF2-HMAC-SHA256 with a persistent server-side salt — not
- for cryptographic reasons (128-bit random tokens don't need slow
- hashing), but because CodeQL's ``py/weak-sensitive-data-hashing``
- query mislabels API keys as passwords and demands a KDF.
+ """SHA-256 hash helper for refresh token storage.
+
+ Plain SHA-256 is intentional: refresh tokens are high-entropy random
+ strings from ``secrets.token_urlsafe(48)`` (384 bits), so a slow KDF
+ (Argon2 / bcrypt / PBKDF2) adds zero security (2^384 is unbruteforceable
+ regardless of hash speed) while costing tens of ms per refresh. See the
+ OWASP Password Storage Cheat Sheet on hashing high-entropy inputs.
+
+ API keys use the separate ``_pbkdf2_api_key`` helper (PBKDF2-HMAC-SHA256
+ with a persistent server-side salt) — not for crypto reasons (128-bit
+ random tokens don't need slow hashing) but because CodeQL's
+ ``py/weak-sensitive-data-hashing`` query mislabels them as passwords and
+ demands a KDF.
"""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
@@ -176,22 +171,20 @@ def get_connection() -> sqlite3.Connection:
# ── API-key PBKDF2 salt ────────────────────────────────────────────────
#
-# Module-level cache for the persistent API-key PBKDF2 salt. Populated
-# lazily on first use via ``_get_or_create_api_key_pbkdf2_salt``. Not
-# protected by a lock because (a) the ``INSERT OR IGNORE`` provides
-# atomicity at the SQLite layer and (b) concurrent populations converge
-# on the same value, so the worst case is a harmless duplicate read on
-# startup.
+# Module-level cache for the persistent API-key PBKDF2 salt, populated lazily
+# via ``_get_or_create_api_key_pbkdf2_salt``. No lock needed: (a) ``INSERT OR
+# IGNORE`` is atomic at the SQLite layer and (b) concurrent populations
+# converge on the same value, so the worst case is a harmless duplicate read
+# on startup.
_api_key_pbkdf2_salt_cache: Optional[bytes] = None
def _get_or_create_api_key_pbkdf2_salt() -> bytes:
"""Return the persistent API-key PBKDF2 salt, generating it once if missing.
- Stored as a hex-encoded 32-byte random value in the ``app_secrets``
- table under key ``"api_key_pbkdf2_salt"``. Regenerated only if the row
- is missing (i.e. fresh install, or operator manually deleted the row
- and accepts invalidating existing API keys).
+ Stored as a hex-encoded 32-byte random value in ``app_secrets`` under key
+ ``"api_key_pbkdf2_salt"``. Regenerated only when the row is missing (fresh
+ install, or operator deleted it and accepts invalidating existing keys).
"""
global _api_key_pbkdf2_salt_cache
if _api_key_pbkdf2_salt_cache is not None:
@@ -233,22 +226,18 @@ _DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"
def _pbkdf2_api_key(raw_key: str) -> str:
"""PBKDF2-HMAC-SHA256 an API key with a persistent server-side salt.
- Used for API-key storage ONLY, not refresh tokens. Matches the
- PBKDF2 algorithm + iteration count used by the password hasher in
- ``auth/hashing.py`` so the codebase is consistent on which KDF it
- uses for credential storage.
-
- Notes on why a slow KDF here is *only* a CodeQL appeasement and
- *not* a cryptographic requirement: API keys are cryptographically
- random 128-bit tokens (via ``secrets.token_hex``), so brute force
- against 2^128 is infeasible regardless of hash speed. CodeQL's
- ``py/weak-sensitive-data-hashing`` query mislabels these tokens as
- "password" sensitive data and then demands a KDF from its
- allowlist (Argon2 / scrypt / bcrypt / PBKDF2). Per the query's
- own recommendation page we use PBKDF2. The persistent salt is
- still loaded from ``app_secrets`` so an attacker dumping the
- ``api_keys`` table alone cannot derive hashes for candidate
- tokens without also obtaining the salt row.
+ For API-key storage ONLY, not refresh tokens. Matches the PBKDF2 algorithm
+ + iteration count used by the password hasher in ``auth/hashing.py`` so
+ the codebase is consistent on its credential-storage KDF.
+
+ The slow KDF here is *only* a CodeQL appeasement, not a crypto
+ requirement: API keys are random 128-bit tokens (``secrets.token_hex``),
+ so brute force against 2^128 is infeasible regardless of hash speed.
+ CodeQL's ``py/weak-sensitive-data-hashing`` query mislabels them as
+ "password" data and demands a KDF from its allowlist (Argon2 / scrypt /
+ bcrypt / PBKDF2); we use PBKDF2 per its recommendation page. The salt is
+ still loaded from ``app_secrets`` so dumping the ``api_keys`` table alone
+ can't derive hashes for candidate tokens without the salt row.
"""
salt = _get_or_create_api_key_pbkdf2_salt()
dk = hashlib.pbkdf2_hmac(
diff --git a/studio/backend/colab.py b/studio/backend/colab.py
index c3a1e03fbeb..1f618a34abb 100644
--- a/studio/backend/colab.py
+++ b/studio/backend/colab.py
@@ -2,15 +2,14 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Colab-specific helpers for running Unsloth Studio.
-Uses Colab's built-in proxy - no external tunneling needed!
+Colab helpers for Unsloth Studio. Uses Colab's built-in proxy.
"""
from pathlib import Path
import sys
-# Fix for Anaconda/conda-forge Python: seed platform._sys_version_cache before
-# any library imports that trigger attrs -> rich -> structlog -> platform crash.
+# Anaconda/conda-forge Python: seed platform._sys_version_cache before any
+# import that triggers attrs -> rich -> structlog -> platform crash.
# See: https://github.com/python/cpython/issues/102396
_backend_dir = str(Path(__file__).parent)
if _backend_dir not in sys.path:
@@ -25,11 +24,10 @@ logger = get_logger(__name__)
def get_colab_url(port: int = 8888) -> str:
"""
- Get the actual Colab proxy URL for a port.
+ Get the Colab proxy URL for a port.
- Retries up to 3 times and validates that the result is a real HTTPS Colab
- URL before returning. Falls back to http://localhost:{port} only when all
- attempts fail.
+ Retries up to 3 times, validating the result is a real HTTPS Colab URL.
+ Falls back to http://localhost:{port} only when all attempts fail.
"""
import time as _time
@@ -43,7 +41,7 @@ def get_colab_url(port: int = 8888) -> str:
for attempt in range(3):
try:
url = eval_js(f"google.colab.kernel.proxyPort({port})", timeout_sec = 10)
- # A valid Colab proxy URL starts with https:// and embeds the port.
+ # Valid Colab proxy URL starts with https:// and embeds the port.
if url and isinstance(url, str) and url.startswith("https://") and str(port) in url:
return url.rstrip("/")
except Exception as e:
@@ -61,16 +59,16 @@ def get_colab_url(port: int = 8888) -> str:
def show_link(port: int = 8888, *, _url: "str | None" = None):
"""Display a styled clickable link to the UI.
- *_url* is an optional pre-fetched Colab proxy URL. When omitted,
- ``get_colab_url(port)`` is called internally. Pass it from
- ``_show_and_embed`` to avoid a second ``eval_js`` round-trip.
+ *_url* is an optional pre-fetched Colab proxy URL; when omitted,
+ ``get_colab_url(port)`` is called. Pass it from ``_show_and_embed`` to
+ avoid a second ``eval_js`` round-trip.
"""
from IPython.display import display, HTML
url = _url if _url is not None else get_colab_url(port)
- # Build a truncated display URL. Wrap in try/except so an unexpected URL
- # shape never prevents the link from rendering.
+ # Truncated display URL. try/except so an unexpected URL shape never
+ # prevents the link from rendering.
try:
port_prefix = f"{port}-"
idx = url.index(port_prefix)
@@ -79,8 +77,7 @@ def show_link(port: int = 8888, *, _url: "str | None" = None):
except (ValueError, IndexError):
short_url = url
- # Also emit a plain-text line so the URL is visible even if HTML display
- # is suppressed or fails.
+ # Plain-text line so the URL is visible even if HTML display fails.
logger.info(f"🌐 Unsloth Studio URL: {url}")
html = f"""
@@ -123,12 +120,10 @@ def _is_studio_healthy(port: int, timeout: float = 2.0) -> bool:
def _show_and_embed(port: int):
"""Embed the Studio inline for *port* with a branded header bar.
- Fetches the Colab proxy URL once (registering the port with Colab's
- reverse-proxy at the same time) then renders a header bar + full-height
- iframe as a single HTML block.
-
- Falls back to ``serve_kernel_port_as_iframe`` if ``IPython.display.HTML``
- is unavailable for any reason.
+ Fetches the Colab proxy URL once (also registering the port with Colab's
+ reverse-proxy) then renders a header bar + full-height iframe as one HTML
+ block. Falls back to ``serve_kernel_port_as_iframe`` if
+ ``IPython.display.HTML`` is unavailable.
"""
url = get_colab_url(port)
logger.info(f"🌐 Unsloth Studio URL: {url}")
@@ -138,7 +133,7 @@ def _show_and_embed(port: int):
iframe_id = f"unsloth-studio-{port}"
- # Truncated URL shown in the header — best-effort, falls back to full URL.
+ # Truncated header URL — best-effort, falls back to full URL.
try:
port_prefix = f"{port}-"
idx = url.index(port_prefix)
@@ -188,8 +183,8 @@ def start(port: int = 8888):
logger.info("🦥 Starting Unsloth Studio...")
# --- Fast path: Studio is already running (cell re-run) ---
- # Re-launching would either collide on the port or silently shift to a new
- # port and confuse the user. Just re-show the link and iframe instead.
+ # Re-launching would collide on the port or silently shift to a new one.
+ # Just re-show the link and iframe instead.
if _is_studio_healthy(port):
logger.info(f" Studio is already running on port {port} — reusing existing server.")
_show_and_embed(port)
@@ -222,16 +217,16 @@ def start(port: int = 8888):
logger.error(f"❌ Unsloth Studio failed to start: {exc}")
return
- # run_server auto-increments the port when the requested one is already in
- # use (e.g. Jupyter occupying 8888). Read back the actual bound port so the
- # Colab proxy URL and iframe always point at the right place.
+ # run_server auto-increments the port if the requested one is in use (e.g.
+ # Jupyter on 8888). Read back the bound port so the Colab proxy URL and
+ # iframe point at the right place.
actual_port: int = getattr(getattr(app, "state", None), "server_port", None) or port
logger.info(f" Server started on port {actual_port}!")
- # Poll health endpoint to confirm the server is truly reachable before
- # showing the link and registering the iframe — avoids the race where
- # ready_event fires but the process hasn't finished binding.
+ # Poll health endpoint to confirm reachability before showing the link and
+ # registering the iframe — avoids the race where ready_event fires but the
+ # process hasn't finished binding.
import urllib.request
server_ready = False
@@ -252,9 +247,9 @@ def start(port: int = 8888):
_show_and_embed(actual_port)
- # Keep kernel alive so the daemon server thread stays running.
- # Handle KeyboardInterrupt cleanly so the user gets a readable message
- # rather than a raw traceback when they interrupt the cell.
+ # Keep kernel alive so the daemon server thread stays running. Handle
+ # KeyboardInterrupt cleanly so interrupting the cell gives a readable
+ # message, not a raw traceback.
try:
for _ in range(10000):
time.sleep(300)
diff --git a/studio/backend/core/__init__.py b/studio/backend/core/__init__.py
index 2ba9d5c65c5..5400ef0d352 100644
--- a/studio/backend/core/__init__.py
+++ b/studio/backend/core/__init__.py
@@ -4,18 +4,16 @@
"""
Unified core module for Unsloth backend
-Imports are LAZY (via __getattr__) so that training subprocesses can
-import core.training.worker without pulling in heavy ML dependencies
-like unsloth, transformers, or torch before the version activation
-code has a chance to run.
+Imports are LAZY (via __getattr__) so training subprocesses can import
+core.training.worker without pulling in heavy ML deps (unsloth, transformers,
+torch) before the version-activation code runs.
"""
import sys
from pathlib import Path
-# Ensure the backend directory is on sys.path so that bare "from utils.*"
-# imports used throughout the backend work when core is imported as a package
-# (e.g. from the CLI: "from studio.backend.core import ModelConfig").
+# Put the backend dir on sys.path so bare "from utils.*" imports work when core
+# is imported as a package (e.g. CLI: "from studio.backend.core import ModelConfig").
_backend_dir = str(Path(__file__).resolve().parent.parent)
if _backend_dir not in sys.path:
sys.path.insert(0, _backend_dir)
@@ -69,7 +67,7 @@ def __getattr__(name):
globals()["TrainingProgress"] = TrainingProgress
return globals()[name]
- # Config (from utils.models)
+ # Config (utils.models)
if name in (
"is_vision_model",
"ModelConfig",
diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.py
index 217c25fda3b..4a62004bac1 100644
--- a/studio/backend/core/_torchao_stub.py
+++ b/studio/backend/core/_torchao_stub.py
@@ -6,15 +6,14 @@
torchao (pulled in by transformers.quantizers) imports
torch.distributed._functional_collectives at module level, which imports
distributed_c10d.py unconditionally — that file crashes on Windows ROCm because
-torch._C._distributed_c10d (the RCCL backend) is absent.
-torch/distributed/__init__.py itself is guarded by `if is_available()` so
-`import torch.distributed` alone is safe; the crash only comes via torchao's
-import chain. Stubbing torchao short-circuits it entirely.
+torch._C._distributed_c10d (the RCCL backend) is absent. `import
+torch.distributed` alone is safe (guarded by `if is_available()`); the crash
+only comes via torchao's import chain, so stubbing torchao short-circuits it.
_StubSubpackageFinder handles any depth of torchao.xxx.yyy imports.
-This logic used to be duplicated inline inside run_export_process() and
-run_training_process(); it now lives here so both worker subprocesses call the
-single `install_torchao_windows_rocm_stub()` entrypoint before importing
+Previously duplicated inline in run_export_process() and run_training_process();
+now both worker subprocesses call the single
+`install_torchao_windows_rocm_stub()` entrypoint before importing
transformers / unsloth_zoo.
"""
@@ -28,9 +27,9 @@ import importlib.machinery
_STUB_SENTINEL = object()
-# Metaclass for stub types so that isinstance(x, StubClass) returns False
-# instead of raising TypeError ("arg 2 must be a type").
-# peft/tuners/lora/torchao.py does:
+# Metaclass for stub types so isinstance(x, StubClass) returns False instead
+# of raising TypeError ("arg 2 must be a type"). peft/tuners/lora/torchao.py
+# does:
# from torchao.dtypes import AffineQuantizedTensor, LinearActivationQuantizedTensor
# isinstance(weight, (AffineQuantizedTensor, LinearActivationQuantizedTensor))
# If those names resolve to stub modules rather than types, isinstance() raises.
@@ -71,8 +70,8 @@ def _make_mod_stub(mod_name):
):
if attr.startswith("__"):
raise AttributeError(attr)
- # Return a stub CLASS (not a module) so that isinstance(x, attr)
- # works and returns False instead of raising TypeError.
+ # Return a stub CLASS (not a module) so isinstance(x, attr) returns
+ # False instead of raising TypeError.
child = _make_stub_type(f"{_n}.{attr}")
setattr(_m, attr, child)
return child
@@ -114,14 +113,13 @@ class _StubSubpackageFinder(importlib.abc.MetaPathFinder):
def install_torchao_windows_rocm_stub() -> None:
"""Pre-stub torchao on Windows ROCm so transformers/peft imports don't crash.
- No-op on every other platform (Windows CUDA included — there torchao is real
- and shadowing it would break torchao-based quantization paths). Must run
- before any import of transformers / unsloth_zoo. Safe to call once per worker
- process.
+ No-op on every other platform (incl. Windows CUDA — there torchao is real
+ and shadowing it would break torchao quantization paths). Must run before
+ any import of transformers / unsloth_zoo. Safe to call once per worker.
"""
# Gate on the active torch runtime, not env-var presence -- HIP_PATH /
- # ROCM_PATH stay set after a user installs the HIP SDK and reverts to a
- # CUDA torch wheel. AMD SDK / Radeon ROCm wheels may not set torch.version.hip
+ # ROCM_PATH stay set after installing the HIP SDK and reverting to a CUDA
+ # torch wheel. AMD SDK / Radeon ROCm wheels may not set torch.version.hip
# but still encode "rocm" in torch.__version__, so accept either.
_is_win32_rocm = False
if sys.platform == "win32":
@@ -135,8 +133,8 @@ def install_torchao_windows_rocm_stub() -> None:
except Exception:
pass
if _is_win32_rocm:
- # Register the finder only on Windows ROCm -- on other platforms there
- # are no stub modules seeded, so appending is a pure accumulation.
+ # Register the finder only on Windows ROCm -- elsewhere no stub modules
+ # are seeded, so appending would be pure accumulation.
sys.meta_path.append(_StubSubpackageFinder())
# Seed torchao top-level + key submodules; the finder handles the rest.
for _tao_name in (
diff --git a/studio/backend/core/data_recipe/huggingface.py b/studio/backend/core/data_recipe/huggingface.py
index d5a6db6baf2..3012fed1ea5 100644
--- a/studio/backend/core/data_recipe/huggingface.py
+++ b/studio/backend/core/data_recipe/huggingface.py
@@ -95,8 +95,8 @@ def publish_recipe_dataset(
tags = None,
)
card.text = card.text.replace(_DATA_DESIGNER_FOOTER, _UNSLOTH_STUDIO_FOOTER)
- # Data Designer currently drops the explicit token when pushing the
- # dataset card. Push it ourselves so auth stays request-local.
+ # Data Designer drops the explicit token when pushing the dataset
+ # card, so push it ourselves to keep auth request-local.
card.push_to_hub(repo_id, token = hf_token, repo_type = "dataset")
client._upload_main_dataset_files(
diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.py
index 75dc1efb9ca..71c2b7468f9 100644
--- a/studio/backend/core/data_recipe/jobs/manager.py
+++ b/studio/backend/core/data_recipe/jobs/manager.py
@@ -134,8 +134,8 @@ class JobManager:
``internal_api_key_id`` is the row id of a workflow-scoped
sk-unsloth-* key minted by the route layer for local providers.
- JobManager revokes it when the job reaches a terminal state so the
- key's live window is no longer than the run.
+ JobManager revokes it on terminal state so the key's live window is
+ no longer than the run.
"""
llm_columns = recipe.get("columns") or []
llm_column_count = 0
@@ -202,7 +202,7 @@ class JobManager:
return True
def get_status(self, job_id: str) -> dict | None:
- """UI friendly snapshot that we need. Alternative to sse kinda of and structured"""
+ """UI-friendly structured snapshot; an alternative to SSE."""
with self._lock:
if self._job is None or self._job.job_id != job_id:
return None
@@ -537,9 +537,9 @@ class JobManager:
def _retire_workflow_key(self, job: Job) -> None:
"""Revoke the workflow-scoped sk-unsloth-* key, if one was minted.
- Best-effort: revocation failures are swallowed. The key would
- expire on its own after 24h, so a missed revoke is a latency
- concern, not a correctness one.
+ Best-effort: revocation failures are swallowed. The key expires on
+ its own after 24h, so a missed revoke is a latency concern, not a
+ correctness one.
"""
key_id = getattr(job, "internal_api_key_id", None)
if not key_id:
diff --git a/studio/backend/core/data_recipe/jobs/parse.py b/studio/backend/core/data_recipe/jobs/parse.py
index 8ca3702edde..e37d7064ed8 100644
--- a/studio/backend/core/data_recipe/jobs/parse.py
+++ b/studio/backend/core/data_recipe/jobs/parse.py
@@ -46,7 +46,7 @@ class ParsedUpdate:
source_progress: SourceProgress | None = None
-# kinda of a bummber but currently only option, Best effort parser from data-designer logs -> structured status for UI.
+# Best-effort parser from data-designer logs -> structured status for UI.
_RE_SAMPLERS = re.compile(
r"Preparing samplers to generate (?P<rows>\d+) records across (?P<cols>\d+) columns"
)
@@ -327,7 +327,7 @@ def apply_update(job: Job, update: ParsedUpdate) -> None:
_apply_source_progress(job, update.source_progress)
if update.stage in USAGE_RESET_STAGES:
- # usage summary is a short block so we reset once we move into the next stage.
+ # Usage summary is a short block; reset on entering the next stage.
job._in_usage_summary = False
if update.usage_section_start is not None:
diff --git a/studio/backend/core/data_recipe/jobs/types.py b/studio/backend/core/data_recipe/jobs/types.py
index 3d3ddb974e7..6dd4db59730 100644
--- a/studio/backend/core/data_recipe/jobs/types.py
+++ b/studio/backend/core/data_recipe/jobs/types.py
@@ -91,8 +91,8 @@ class Job:
source_progress_estimated_total: int | None = None
completed_columns: list[str] = field(default_factory = list)
# Id of the internal sk-unsloth-* API key minted for a local-model
- # workflow. Revoked when the job terminates so the key's live window
- # matches the run rather than its 24h TTL.
+ # workflow. Revoked when the job ends so the key's window matches the
+ # run rather than its 24h TTL.
internal_api_key_id: int | None = None
_current_usage_model: str | None = None
_in_usage_summary: bool = False
diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.py
index f59538769e1..27d08e90fe0 100644
--- a/studio/backend/core/data_recipe/jobs/worker.py
+++ b/studio/backend/core/data_recipe/jobs/worker.py
@@ -73,10 +73,7 @@ def _build_dataset_name(*, run_name: str | None, job_id: str, artifact_root: Pat
def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any]) -> None:
- """
- Subprocess entrypoint.
- Sends events to `event_queue`.
- """
+ """Subprocess entrypoint. Sends events to `event_queue`."""
import os
os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports
@@ -115,8 +112,8 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any])
builder = build_config_builder(recipe)
designer = create_data_designer(recipe, artifact_path = str(_ARTIFACT_ROOT))
- # DataDesigner configures root logging in DataDesigner.__init__.
- # Attach queue logger directly to `data_designer` so parser events survive root resets.
+ # DataDesigner configures root logging in __init__. Attach the queue
+ # logger to `data_designer` directly so parser events survive root resets.
handler = _QueueLogHandler(event_queue)
handler.setLevel(logging.INFO)
for logger_name in (
diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.py
index cb5901f04ea..addbe8f8486 100644
--- a/studio/backend/core/data_recipe/service.py
+++ b/studio/backend/core/data_recipe/service.py
@@ -167,9 +167,10 @@ def _validate_recipe_runtime_support(recipe: dict[str, Any], model_providers: li
def build_mcp_providers(recipe: dict[str, Any]) -> list:
from data_designer.config.mcp import LocalStdioMCPProvider, MCPProvider # pyright: ignore[reportMissingImports]
- # Same gate as the chat MCP path: stdio providers spawn a local subprocess,
- # so only build them when this host allows it (desktop / explicit opt-in).
- # Skip them otherwise so a recipe carried onto a hosted host cannot spawn.
+ # Same gate as the chat MCP path: stdio providers spawn a local
+ # subprocess, so build them only when this host allows it (desktop /
+ # explicit opt-in). Otherwise a recipe carried onto a hosted host
+ # cannot spawn.
from core.inference.mcp_client import stdio_mcp_enabled
stdio_allowed = stdio_mcp_enabled()
@@ -258,7 +259,7 @@ def build_config_builder(recipe: dict[str, Any]):
)
# DataDesignerConfigBuilder.from_config currently skips processors.
- # Re-attach explicitly so drop_columns/schema_transform survive API payload.
+ # Re-attach so drop_columns/schema_transform survive the API payload.
for processor in recipe_core.get("processors") or []:
if not isinstance(processor, dict):
continue
@@ -283,8 +284,8 @@ def create_data_designer(recipe: dict[str, Any], *, artifact_path: str | None =
_validate_recipe_runtime_support(recipe, model_providers)
# DataDesigner requires at least one model provider in its registry even
- # when the pipeline contains no LLM columns. Supply a lightweight stub
- # so sampler/expression-only recipes can run without a real provider.
+ # when the pipeline has no LLM columns. Supply a lightweight stub so
+ # sampler/expression-only recipes can run without a real provider.
if not model_providers:
from data_designer.config.models import ModelProvider # pyright: ignore[reportMissingImports]
model_providers = [
diff --git a/studio/backend/core/export/__init__.py b/studio/backend/core/export/__init__.py
index 16fba368ef3..db9d1b352c0 100644
--- a/studio/backend/core/export/__init__.py
+++ b/studio/backend/core/export/__init__.py
@@ -5,8 +5,8 @@
Export submodule - Model export operations
The default get_export_backend() returns an ExportOrchestrator that
-delegates to a subprocess. The original ExportBackend runs inside
-the subprocess and can be imported directly from .export when needed.
+delegates to a subprocess. The original ExportBackend runs inside the
+subprocess and can be imported directly from .export when needed.
"""
from .orchestrator import ExportOrchestrator, get_export_backend
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index e74dc13e8a7..aaae8002fcb 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -2,9 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
# backend/export.py
-"""
-Export backend - handles model exporting in various formats
-"""
+"""Export backend - exports models in various formats."""
import glob
import json
@@ -46,10 +44,10 @@ def _is_wsl():
def _apply_wsl_sudo_patch():
"""On WSL, monkey-patch do_we_need_sudo() to return False.
- WSL doesn't have passwordless sudo, and do_we_need_sudo() runs
- `sudo apt-get update` which hangs waiting for a stdin password
- inside a non-interactive subprocess. setup.sh pre-installs the
- build dependencies on WSL, so sudo is not needed at runtime.
+ WSL lacks passwordless sudo, and do_we_need_sudo() runs
+ `sudo apt-get update`, which hangs on a stdin password in a
+ non-interactive subprocess. setup.sh pre-installs the build deps on
+ WSL, so sudo isn't needed at runtime.
"""
if not _is_wsl():
return
@@ -110,7 +108,7 @@ class ExportBackend:
try:
logger.info("Starting memory cleanup...")
- # Unload all models from inference backend
+ # Unload all inference-backend models
model_names = list(self.inference_backend.models.keys())
for model_name in model_names:
self.inference_backend.unload_model(model_name)
@@ -121,7 +119,7 @@ class ExportBackend:
self.current_checkpoint = None
self._audio_type = None
- # Clear GPU memory cache (handles gc + backend-specific cleanup)
+ # Clear GPU cache (handles gc + backend-specific cleanup)
clear_gpu_cache()
logger.info("Memory cleanup completed successfully")
@@ -137,8 +135,7 @@ class ExportBackend:
"""
Scan outputs folder for training runs and their checkpoints.
- Returns:
- List of tuples: [(model_name, [(display_name, checkpoint_path), ...]), ...]
+ Returns: [(model_name, [(display_name, checkpoint_path), ...]), ...]
"""
from utils.models.checkpoints import scan_checkpoints
return scan_checkpoints(outputs_dir = outputs_dir)
@@ -159,12 +156,12 @@ class ExportBackend:
try:
logger.info(f"Loading checkpoint: {checkpoint_path}")
- # First, cleanup existing models
+ # Cleanup existing models first
self.cleanup_memory()
checkpoint_path_obj = Path(checkpoint_path)
- # Determine the model identity for type detection
+ # Model identity for type detection
adapter_config = checkpoint_path_obj / "adapter_config.json"
base_model = None
if adapter_config.exists():
@@ -246,7 +243,7 @@ class ExportBackend:
load_in_4bit = load_in_4bit,
trust_remote_code = trust_remote_code,
)
- tokenizer = processor # For vision models, processor acts as tokenizer
+ tokenizer = processor # vision: processor acts as tokenizer
else:
logger.info("Loading as text model...")
@@ -258,14 +255,13 @@ class ExportBackend:
trust_remote_code = trust_remote_code,
)
- # Check if PEFT / LoRA model
+ # Detect PEFT / LoRA model
if _IS_MLX:
# MLX doesn't use PeftModel — detect LoRA via adapter_config.json
self.is_peft = adapter_config.exists()
else:
self.is_peft = isinstance(model, (PeftModel, PeftModelForCausalLM))
- # Store loaded model
self.current_model = model
self.current_tokenizer = tokenizer
self.current_checkpoint = checkpoint_path
@@ -459,7 +455,7 @@ class ExportBackend:
if _IS_MLX:
# MLX: save_pretrained_merged handles non-LoRA models too
- # (fuse() is a no-op when there are no LoRA layers)
+ # (fuse() is a no-op without LoRA layers)
self.current_model.save_pretrained_merged(
save_directory,
self.current_tokenizer,
@@ -509,12 +505,11 @@ class ExportBackend:
private = private,
)
else:
- # Get base model name from request or model config
+ # Base model name from request or model config
base_model = (
base_model_id or self.current_model.config._name_or_path or "unknown"
)
- # Create repo
hf_api = HfApi(token = hf_token)
repo_id = PushToHubMixin._create_repo(
PushToHubMixin,
@@ -524,7 +519,7 @@ class ExportBackend:
)
username = repo_id.split("/")[0]
- # Create and push model card
+ # Build and push model card
content = MODEL_CARD.format(
username = username,
base_model = base_model,
@@ -535,7 +530,7 @@ class ExportBackend:
card = ModelCard(content)
card.push_to_hub(repo_id, token = hf_token, commit_message = "Unsloth Model Card")
- # Upload model files
+ # Upload files
if save_directory:
hf_api.upload_folder(
folder_path = save_directory,
@@ -585,7 +580,7 @@ class ExportBackend:
output_path: Optional[str] = None
try:
- # Convert quantization method to lowercase for unsloth
+ # unsloth expects lowercase quant method
quant_method = quantization_method.lower()
# Pin convert_hf_to_gguf.py to the same llama.cpp ref as the
@@ -613,27 +608,26 @@ class ExportBackend:
# Save locally if requested
if save_directory:
save_directory = str(resolve_export_dir(save_directory))
- # Resolve to absolute path so unsloth's relative-path internals
+ # Use absolute path so unsloth's relative-path internals
# (check_llama_cpp, use_local_gguf, _download_convert_hf_to_gguf)
- # all resolve against the repo root cwd, NOT the export directory.
+ # resolve against the repo root cwd, NOT the export directory.
abs_save_dir = os.path.abspath(save_directory)
logger.info(f"Saving GGUF model locally to: {abs_save_dir}")
- # Create the directory if it doesn't exist
ensure_dir(Path(abs_save_dir))
# On WSL, patch out sudo check before llama.cpp build
_apply_wsl_sudo_patch()
- # Snapshot existing .gguf files in cwd before conversion.
- # unsloth's convert_to_gguf writes output files relative to
- # cwd (repo root), so we diff afterwards and relocate them.
+ # Snapshot existing .gguf files in cwd before conversion;
+ # unsloth's convert_to_gguf writes output relative to cwd
+ # (repo root), so we diff afterwards and relocate.
cwd = os.getcwd()
pre_existing_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf")))
- # Pass absolute path — no os.chdir needed.
- # unsloth saves intermediate HF model files into model_save_path.
- # unsloth-zoo's check_llama_cpp() uses ~/.unsloth/llama.cpp by default.
+ # Absolute path — no os.chdir needed. unsloth saves intermediate
+ # HF model files into model_save_path; unsloth-zoo's
+ # check_llama_cpp() uses ~/.unsloth/llama.cpp by default.
model_save_path = os.path.join(abs_save_dir, "model")
self.current_model.save_pretrained_gguf(
model_save_path,
@@ -642,17 +636,17 @@ class ExportBackend:
)
# Relocate GGUF artifacts into the export directory.
- # convert_to_gguf writes .gguf files to cwd (repo root)
- # because --outfile is a relative path like "model.Q4_K_M.gguf".
+ # convert_to_gguf writes .gguf to cwd (repo root) because
+ # --outfile is a relative path like "model.Q4_K_M.gguf".
new_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf"))) - pre_existing_ggufs
for src in sorted(new_ggufs):
dest = os.path.join(abs_save_dir, os.path.basename(src))
shutil.move(src, dest)
logger.info(f"Relocated GGUF: {os.path.basename(src)} → {abs_save_dir}/")
- # Flatten any .gguf files from subdirectories into abs_save_dir.
+ # Flatten any .gguf from subdirs into abs_save_dir.
# save_pretrained_gguf may create subdirs (e.g. model_gguf/)
- # with a name different from model_save_path.
+ # named differently from model_save_path.
for sub in list(Path(abs_save_dir).iterdir()):
if not sub.is_dir():
continue
@@ -660,13 +654,13 @@ class ExportBackend:
dest = os.path.join(abs_save_dir, src.name)
shutil.move(str(src), dest)
logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/")
- # Clean up the subdirectory (intermediate HF files, etc.)
+ # Clean up the subdir (intermediate HF files, etc.)
shutil.rmtree(str(sub), ignore_errors = True)
logger.info(f"Cleaned up subdirectory: {sub.name}")
# For non-PEFT models, save_pretrained_gguf redirects to the
- # checkpoint path, leaving a *_gguf directory in outputs/.
- # Relocate any GGUFs from there and clean it up.
+ # checkpoint path, leaving a *_gguf dir in outputs/. Relocate
+ # any GGUFs from there and clean it up.
if self.current_checkpoint:
ckpt = Path(self.current_checkpoint)
gguf_dir = ckpt.parent / f"{ckpt.name}_gguf"
@@ -686,8 +680,7 @@ class ExportBackend:
# Write export metadata so the Chat page can identify the base model
self._write_export_metadata(abs_save_dir)
- # Log final file locations (after relocation) so it's clear
- # where the GGUF files actually ended up.
+ # Log final file locations (post-relocation).
final_ggufs = sorted(glob.glob(os.path.join(abs_save_dir, "*.gguf")))
logger.info(
"GGUF export complete. Final files in %s:\n %s",
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index 90a946163ee..49c1af8822b 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -1,15 +1,13 @@
# 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.
+"""Export orchestrator — subprocess-based.
-Provides the same API as ExportBackend, but delegates all ML work
-to a persistent subprocess. The subprocess is spawned on first checkpoint
-load and stays alive for subsequent export operations.
+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 that need different transformers versions,
-the old subprocess is killed and a new one is spawned with the correct version.
+When switching between checkpoints needing different transformers
+versions, the old subprocess is killed and a new one spawned.
Pattern follows core/inference/orchestrator.py.
"""
@@ -30,9 +28,9 @@ logger = get_logger(__name__)
_CTX = mp.get_context("spawn")
-# Maximum number of captured log lines kept in memory per export
-# orchestrator. Acts as scrollback for the live export log panel in the
-# UI. 4000 lines is ~1 MB worst-case at 256 chars/line.
+# Max captured log lines kept in memory per export orchestrator;
+# scrollback for the live export log panel. 4000 lines is ~1 MB
+# worst-case at 256 chars/line.
_LOG_BUFFER_MAXLEN = 4000
@@ -41,46 +39,44 @@ class ExportOrchestrator:
Export backend orchestrator — subprocess-based.
Exposes the same API surface as ExportBackend so routes/export.py
- needs minimal changes. Internally, all heavy ML operations happen in
- a persistent subprocess.
+ needs minimal changes. All heavy ML work happens in a persistent
+ subprocess.
"""
def __init__(self):
- # Subprocess state
+ # Subprocess state.
self._proc: Optional[mp.Process] = None
self._cmd_queue: Any = None
self._resp_queue: Any = None
- # Serializes export operations (load_checkpoint, export_*,
- # cleanup) so concurrent HTTP requests can never interleave
- # commands on the subprocess queue. Previously unused.
+ # Serializes export ops (load_checkpoint, export_*, cleanup) so
+ # concurrent HTTP requests can't interleave commands on the
+ # subprocess queue.
self._lock = threading.Lock()
- # Local state mirrors (updated from subprocess responses)
+ # Local state mirrors (updated from subprocess responses).
self.current_checkpoint: Optional[str] = None
self.is_vision: bool = False
self.is_peft: bool = False
# ── Live log capture ─────────────────────────────────────
- # Thread-safe ring buffer of log lines forwarded from the
- # worker subprocess. Powers the GET /api/export/logs/stream
- # SSE endpoint that the export dialog consumes.
+ # Thread-safe ring buffer of log lines from the worker
+ # subprocess. Powers the GET /api/export/logs/stream SSE
+ # endpoint the export dialog consumes.
self._log_buffer: Deque[Dict[str, Any]] = deque(maxlen = _LOG_BUFFER_MAXLEN)
self._log_lock = threading.Lock()
- # Monotonically increasing sequence number. Never reset across
- # operations, so SSE clients can use it as a stable cursor even
- # if clear_logs() is called mid-session.
+ # Monotonic sequence number. Never reset across operations, so
+ # SSE clients can use it as a stable cursor even if clear_logs()
+ # runs mid-session.
self._log_seq: int = 0
- # Snapshot of _log_seq captured at the start of the current run
- # (updated by clear_logs()). The SSE endpoint defaults its
- # cursor to this value so a client that connects AFTER the
- # worker has already emitted its first lines still sees the
- # full run. Every line appended during the current run has seq
- # strictly greater than _run_start_seq, and every line from
- # prior runs has seq less than or equal to it.
+ # Snapshot of _log_seq at the start of the current run (set by
+ # clear_logs()). The SSE endpoint defaults its cursor here so a
+ # client connecting AFTER the worker's first lines still sees the
+ # full run. Lines in the current run have seq > _run_start_seq;
+ # prior-run lines have seq <= it.
self._run_start_seq: int = 0
- # True while an export operation (load/export/cleanup) is
- # running. The SSE endpoint ends the stream 1 second after
- # this flips back to False to drain any trailing log lines.
+ # True while an export op (load/export/cleanup) is running. The
+ # SSE endpoint ends the stream 1s after this flips False to drain
+ # trailing log lines.
self._export_active: bool = False
atexit.register(self._cleanup)
@@ -91,12 +87,11 @@ class ExportOrchestrator:
# ------------------------------------------------------------------
def _append_log(self, entry: Dict[str, Any]) -> None:
- """Append a log line from the worker subprocess to the buffer.
+ """Append a worker-subprocess log line to the buffer.
Entries look like {"type": "log", "stream": "stdout"|"stderr",
- "line": "...", "ts": ...}. Each is stamped with a monotonic
- seq number before it lands in the buffer so SSE clients can
- cursor through new lines.
+ "line": "...", "ts": ...}. Each gets a monotonic seq number so
+ SSE clients can cursor through new lines.
"""
line = entry.get("line")
if not line:
@@ -113,17 +108,16 @@ class ExportOrchestrator:
)
def clear_logs(self) -> None:
- """Drop any buffered log lines from a previous operation.
+ """Drop buffered log lines from a previous operation.
Called at the start of each export op so the UI shows only the
- output of the current run. The seq counter is NOT reset, so an
- SSE client that captured the cursor before clear_logs() will
- still see new lines (with strictly greater seq numbers).
-
- Also snapshots the current seq into ``_run_start_seq`` so the
- SSE endpoint can anchor its default cursor at the start of
- this run. Anything appended after this call has seq strictly
- greater than the snapshot and is reachable via
+ current run. The seq counter is NOT reset, so an SSE client that
+ captured the cursor before clear_logs() still sees new lines
+ (with strictly greater seq).
+
+ Also snapshots the current seq into ``_run_start_seq`` so the SSE
+ endpoint can anchor its default cursor at this run's start.
+ Anything appended after has seq > the snapshot, reachable via
``get_logs_since(get_run_start_seq())``.
"""
with self._log_lock:
@@ -144,11 +138,11 @@ class ExportOrchestrator:
return self._log_seq
def get_run_start_seq(self) -> int:
- """Return the seq value captured at the start of the current run.
+ """Return the seq captured at the start of the current run.
The SSE endpoint uses this as the default cursor so a client
- that connects AFTER the worker has already started emitting
- output still sees every line from the current run.
+ connecting AFTER the worker started emitting still sees every
+ line from the current run.
"""
with self._log_lock:
return self._run_start_seq
@@ -193,22 +187,22 @@ class ExportOrchestrator:
self._proc = None
return
- # 1. Drain stale responses
+ # 1. Drain stale responses.
self._drain_queue()
- # 2. Send shutdown command
+ # 2. Send shutdown command.
try:
self._cmd_queue.put({"type": "shutdown"})
except (OSError, ValueError):
pass
- # 3. Wait for graceful shutdown
+ # 3. Wait for graceful shutdown.
try:
self._proc.join(timeout = timeout)
except Exception:
pass
- # 4. Force kill if still alive
+ # 4. 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:
@@ -268,9 +262,8 @@ class ExportOrchestrator:
) -> dict:
"""Block until a response of the expected type arrives.
- Export operations can take a very long time — GGUF conversion for
- large models (30B+) easily takes 20-30 minutes. Default timeout
- is 1 hour.
+ Export ops can take a long time — GGUF conversion for large
+ models (30B+) easily takes 20-30 minutes. Default timeout 1 hour.
"""
deadline = time.monotonic() + timeout
@@ -279,7 +272,7 @@ class ExportOrchestrator:
resp = self._read_resp(timeout = min(remaining, 2.0))
if resp is None:
- # Check subprocess health
+ # Check subprocess health.
if not self._ensure_subprocess_alive():
raise RuntimeError("Export subprocess crashed during wait")
continue
@@ -294,17 +287,16 @@ class ExportOrchestrator:
raise RuntimeError(f"Subprocess error: {error_msg}")
if rtype == "log":
- # Forwarded stdout/stderr line from the worker process.
+ # Forwarded stdout/stderr line from the worker.
self._append_log(resp)
continue
if rtype == "status":
message = resp.get("message", "")
logger.info("Export subprocess status: %s", message)
- # Surface status messages in the live log panel too so
- # users see high level progress (e.g. "Importing
- # Unsloth...", "Loading checkpoint: ...") alongside
- # subprocess output.
+ # Surface status in the live log panel too so users see
+ # high-level progress (e.g. "Importing Unsloth...",
+ # "Loading checkpoint: ...") alongside subprocess output.
if message:
self._append_log(
{
@@ -315,7 +307,7 @@ class ExportOrchestrator:
)
continue
- # Other response types during wait — skip
+ # Other response types during wait — skip.
logger.debug(
"Skipping response type '%s' while waiting for '%s'",
rtype,
@@ -362,12 +354,11 @@ class ExportOrchestrator:
}
with self._lock:
- # Start a fresh log buffer for this operation so the UI
- # sees only the current run's output.
+ # Fresh log buffer so the UI sees only this run's output.
self.clear_logs()
self._export_active = True
try:
- # Always kill existing subprocess and spawn fresh.
+ # Always kill any existing subprocess and spawn fresh.
if self._ensure_subprocess_alive():
self._shutdown_subprocess()
elif self._proc is not None:
@@ -488,12 +479,11 @@ class ExportOrchestrator:
def _run_export(self, export_type: str, params: dict) -> Tuple[bool, str, Optional[str]]:
"""Send an export command to the subprocess and wait for result.
- Returns ``(success, message, output_path)``. ``output_path`` is the
- resolved on-disk directory the worker actually wrote to (None when
- the export only pushed to Hub or failed before any file was
- written). Surfaced via the export route's ``details.output_path``
- so the dialog's success screen can show the user where the model
- landed.
+ Returns ``(success, message, output_path)``. ``output_path`` is
+ the resolved on-disk dir the worker wrote to (None when the
+ export only pushed to Hub or failed before writing). Surfaced via
+ the export route's ``details.output_path`` so the dialog's success
+ screen shows where the model landed.
"""
with self._lock:
if not self._ensure_subprocess_alive():
@@ -527,7 +517,7 @@ class ExportOrchestrator:
"""Cleanup export-related models from memory."""
with self._lock:
if not self._ensure_subprocess_alive():
- # No subprocess — just clear local state
+ # No subprocess — clear local state.
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
@@ -542,7 +532,7 @@ class ExportOrchestrator:
except RuntimeError:
success = False
- # Shut down subprocess after cleanup — no model loaded
+ # Shut down subprocess after cleanup — no model loaded.
self._shutdown_subprocess()
self.current_checkpoint = None
@@ -553,7 +543,7 @@ class ExportOrchestrator:
self._export_active = False
def scan_checkpoints(self, outputs_dir: str = str(outputs_root())) -> List[Tuple[str, list]]:
- """Scan for checkpoints — no ML imports needed, runs locally."""
+ """Scan for checkpoints — runs locally, no ML imports."""
from utils.models.checkpoints import scan_checkpoints
return scan_checkpoints(outputs_dir = outputs_dir)
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index 405956ec9d0..a517d6d7b1d 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -4,9 +4,9 @@
"""
Export subprocess entry point.
-Each export session runs in a persistent subprocess (mp.get_context("spawn")).
-This gives us a clean Python interpreter with no stale module state —
-solving the transformers version-switching problem completely.
+Each export session runs in a persistent subprocess (mp.get_context("spawn")),
+giving a clean interpreter with no stale module state — solving the
+transformers version-switching problem completely.
The subprocess stays alive while a model is loaded, accepting commands
(load, export_merged, export_base, export_gguf, export_lora, cleanup,
@@ -31,41 +31,39 @@ from typing import Any
logger = get_logger(__name__)
-# Gate that controls whether captured stdout/stderr lines are forwarded
-# to the parent's resp_queue (and from there to the export-dialog SSE
-# stream). Closed by default so the noisy bootstrap phase -- transformers
-# venv activation, Unsloth/torch imports, base-model resolution, "Top
-# GGUF/hub models" lists, vision detection, weight loading bars -- is
-# suppressed in the UI. _handle_export() opens the gate at the start of
-# the actual export work and leaves it open; the orchestrator always
-# spawns a fresh subprocess for the next checkpoint load (see
-# orchestrator._spawn_subprocess) which resets this state.
+# Gate controlling whether captured stdout/stderr lines are forwarded to
+# the parent's resp_queue (and on to the export-dialog SSE stream). Closed
+# by default so the noisy bootstrap phase -- transformers venv activation,
+# Unsloth/torch imports, base-model resolution, "Top GGUF/hub models" lists,
+# vision detection, weight loading bars -- is suppressed in the UI.
+# _handle_export() opens the gate when actual export work starts and leaves
+# it open; the orchestrator spawns a fresh subprocess for the next checkpoint
+# load (see orchestrator._spawn_subprocess), resetting this state.
#
# Lines dropped while the gate is closed are still echoed to the saved
-# original stdout/stderr fds so the server console / log file keeps the
-# full output for debugging.
+# original stdout/stderr fds so the server console / log file keeps the full
+# output for debugging.
_log_forward_gate = threading.Event()
def _setup_log_capture(resp_queue: Any) -> None:
"""Redirect fds 1 and 2 through pipes so every line printed by this
- worker process and any child process it spawns is forwarded to the
- parent process via resp_queue as {"type": "log", ...} messages.
+ worker and any child it spawns is forwarded to the parent via resp_queue
+ as {"type": "log", ...} messages.
- Must be called BEFORE LogConfig.setup_logging and BEFORE any ML
- imports, otherwise library handlers may capture the original stderr
- reference and bypass the pipe.
+ Must run BEFORE LogConfig.setup_logging and any ML imports, else library
+ handlers may capture the original stderr reference and bypass the pipe.
- Lines are also echoed back to the original stdout/stderr so the
- server console keeps receiving the full subprocess output, even
- while ``_log_forward_gate`` is closed.
+ Lines are also echoed back to the original stdout/stderr so the server
+ console keeps the full subprocess output, even while
+ ``_log_forward_gate`` is closed.
"""
try:
saved_out_fd = os.dup(1)
saved_err_fd = os.dup(2)
except OSError:
- # dup failed (exotic platforms) - give up quietly, export still
+ # dup failed (exotic platforms) - give up quietly; export still
# works, just no live log streaming.
return
@@ -88,13 +86,13 @@ def _setup_log_capture(resp_queue: Any) -> None:
pass
return
- # Close the write ends we just dup2'd (fds 1 and 2 are the real
- # write ends now).
+ # Close the write ends we just dup2'd (fds 1 and 2 are now the real
+ # write ends).
os.close(w_out)
os.close(w_err)
- # Replace Python's sys.stdout/sys.stderr with line-buffered writers
- # bound to the (now-redirected) fds 1 and 2.
+ # Replace sys.stdout/sys.stderr with line-buffered writers bound to the
+ # (now-redirected) 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")
@@ -112,8 +110,8 @@ def _setup_log_capture(resp_queue: Any) -> None:
continue
if not chunk:
break
- # Echo to the original fd so the server console still sees
- # the full output.
+ # Echo to the original fd so the server console keeps the
+ # full output.
try:
os.write(echo_fd, chunk)
except OSError:
@@ -133,9 +131,9 @@ def _setup_log_capture(resp_queue: Any) -> None:
if not line:
continue
if not _log_forward_gate.is_set():
- # Gate closed (bootstrap phase) -- already echoed to
- # the saved console fd above; drop the line so the
- # export dialog doesn't see import / vendoring noise.
+ # Gate closed (bootstrap) -- already echoed to the saved
+ # console fd above; drop the line so the export dialog
+ # doesn't see import / vendoring noise.
continue
try:
resp_queue.put_nowait(
@@ -147,8 +145,8 @@ def _setup_log_capture(resp_queue: Any) -> None:
}
)
except Exception:
- # Queue put failed (full, closed, etc.) - drop the
- # line rather than crash the reader thread.
+ # Queue put failed (full, closed, etc.) - drop the line
+ # rather than crash the reader thread.
pass
if buf and _log_forward_gate.is_set():
try:
@@ -181,7 +179,7 @@ def _setup_log_capture(resp_queue: Any) -> None:
def _activate_transformers_version(model_name: str) -> None:
"""Activate the correct transformers version BEFORE any ML imports."""
- # Ensure backend is on path for utils imports
+ # Ensure backend is on sys.path for utils imports
backend_path = str(Path(__file__).resolve().parent.parent.parent)
if backend_path not in sys.path:
sys.path.insert(0, backend_path)
@@ -267,11 +265,11 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
export_type = cmd["export_type"] # "merged", "base", "gguf", "lora"
response_type = f"export_{export_type}_done"
- # Open the log forwarding gate so the user sees the actual export
- # progress (Unsloth merge bars, file copies, GGUF conversion, etc.)
- # in the live log panel. The gate stays open for the rest of this
- # subprocess's life; the orchestrator spawns a fresh subprocess for
- # the next checkpoint load, which resets the gate to closed.
+ # Open the log forwarding gate so the user sees actual export progress
+ # (Unsloth merge bars, file copies, GGUF conversion, etc.) in the live
+ # log panel. The gate stays open for the rest of this subprocess's life;
+ # the orchestrator spawns a fresh subprocess for the next checkpoint
+ # load, which resets the gate to closed.
_log_forward_gate.set()
output_path: Any = None
@@ -372,23 +370,23 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
"""
import queue as _queue
- # Install fd-level stdout/stderr capture FIRST so every subsequent
- # print and every child process inherits the redirected fds. This
- # is what powers the live export log stream in the UI.
+ # Install fd-level stdout/stderr capture FIRST so every subsequent print
+ # and every child process inherits the redirected fds. This powers the
+ # live export log stream in the UI.
_setup_log_capture(resp_queue)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports
- # Force unbuffered output from any child Python process (e.g. the
- # GGUF converter) so their prints surface in the log stream as they
- # happen rather than at the end.
+ # Force unbuffered output from child Python processes (e.g. the GGUF
+ # converter) so their prints surface in the log stream as they happen,
+ # not at the end.
os.environ["PYTHONUNBUFFERED"] = "1"
# tqdm defaults to a 10-second mininterval when stdout is not a tty
- # (which it isn't here -- we redirected fd 1/2 to a pipe). That makes
- # multi-step progress bars look frozen in the export log panel. Force
- # frequent flushes so the user sees movement during merge / GGUF
- # conversion. Has no effect on single-step bars (e.g. "Copying 1
- # files") which only emit start/end events regardless.
+ # (it isn't -- we redirected fd 1/2 to a pipe), making multi-step
+ # progress bars look frozen in the export log panel. Force frequent
+ # flushes so the user sees movement during merge / GGUF conversion. No
+ # effect on single-step bars (e.g. "Copying 1 files") which only emit
+ # start/end events anyway.
os.environ.setdefault("TQDM_MININTERVAL", "0.5")
import warnings
@@ -419,7 +417,7 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
)
return
- # ── 1b. On Windows, check Triton availability (must be before import torch) ──
+ # ── 1b. Check Triton on Windows (must precede import torch) ──
if sys.platform == "win32":
try:
import triton # noqa: F401
@@ -433,9 +431,9 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
# ── 1c. Stub torchao on Windows ROCm ──
# Shared with the training worker; see core/_torchao_stub.py for the full
- # rationale (torchao -> torch.distributed._functional_collectives crashes on
- # Windows ROCm because the RCCL backend is absent). No-op off Windows ROCm.
- # Must run before any import of transformers / unsloth_zoo.
+ # rationale (torchao -> torch.distributed._functional_collectives crashes
+ # on Windows ROCm: RCCL backend 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()
@@ -511,7 +509,7 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None
try:
if cmd_type == "load":
- # Load a new checkpoint (reusing this subprocess)
+ # Load a new checkpoint, reusing this subprocess
backend.cleanup_memory()
_handle_load(backend, cmd, resp_queue)
diff --git a/studio/backend/core/inference/__init__.py b/studio/backend/core/inference/__init__.py
index 35318f63571..2faf70bb79b 100644
--- a/studio/backend/core/inference/__init__.py
+++ b/studio/backend/core/inference/__init__.py
@@ -2,17 +2,17 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Inference submodule - Inference backend for model loading and generation
+Inference submodule - backend for model loading and generation.
The default get_inference_backend() returns an InferenceOrchestrator that
-delegates to a subprocess. The original InferenceBackend runs inside
-the subprocess and can be imported directly from .inference when needed.
+delegates to a subprocess. The original InferenceBackend runs inside the
+subprocess and can be imported directly from .inference when needed.
"""
from .orchestrator import InferenceOrchestrator, get_inference_backend
from .llama_cpp import LlamaCppBackend
-# Expose InferenceOrchestrator as InferenceBackend for backward compat
+# Expose InferenceOrchestrator as InferenceBackend for backward compat.
InferenceBackend = InferenceOrchestrator
__all__ = [
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.py
index f999120ffb7..b6262d99742 100644
--- a/studio/backend/core/inference/_html_to_md.py
+++ b/studio/backend/core/inference/_html_to_md.py
@@ -5,7 +5,7 @@
Minimal HTML-to-Markdown converter using only the standard library.
Replaces the external ``html2text`` (GPL-3.0) dependency with a ~250-line
-``html.parser.HTMLParser`` subclass. Covers headings, links, bold/italic,
+``html.parser.HTMLParser`` subclass. Covers headings, links, bold/italic,
lists, tables, blockquotes, code blocks, and entity decoding.
"""
@@ -81,9 +81,9 @@ class _MarkdownRenderer(HTMLParser):
self._pre_parts: list[str] = []
self._in_inline_code: bool = False
- # Blockquote state -- stack of output buffers so nested
- # blockquotes each collect their own content and get prefixed
- # with the correct number of ">" markers on close.
+ # Blockquote state -- stack of output buffers so nested blockquotes
+ # each collect their own content and get prefixed with the correct
+ # number of ">" markers on close.
self._bq_stack: list[list[str]] = []
# ------------------------------------------------------------------
@@ -102,7 +102,7 @@ class _MarkdownRenderer(HTMLParser):
# ------------------------------------------------------------------
def _prefix_blockquote(self, content: str) -> str:
"""Prefix every line of *content* with ``> ``."""
- # Strip trailing whitespace first, then collapse blank lines
+ # Strip trailing whitespace, then collapse blank lines.
content = re.sub(r"[ \t]+$", "", content, flags = re.MULTILINE)
content = re.sub(r"\n{3,}", "\n\n", content).strip()
if not content:
@@ -117,8 +117,8 @@ class _MarkdownRenderer(HTMLParser):
return "\n".join(prefixed)
# ------------------------------------------------------------------
- # Table helpers -- flush open cells and rows so that HTML with
- # omitted optional end tags (</td>, </tr>) does not lose data.
+ # Table helpers -- flush open cells/rows so HTML with omitted optional
+ # end tags (</td>, </tr>) does not lose data.
# ------------------------------------------------------------------
def _finish_cell(self) -> None:
if not self._in_cell:
@@ -143,8 +143,8 @@ class _MarkdownRenderer(HTMLParser):
self._row_has_th = False
# ------------------------------------------------------------------
- # Link text helper -- normalize whitespace so block-level content
- # inside an <a> does not produce multiline Markdown link labels.
+ # Link text helper -- normalize whitespace so block-level content inside
+ # an <a> does not produce multiline Markdown link labels.
# ------------------------------------------------------------------
def _finish_link(self) -> None:
text = re.sub(r"\s+", " ", "".join(self._link_text_parts)).strip()
@@ -234,13 +234,13 @@ class _MarkdownRenderer(HTMLParser):
self._emit("\n\n")
elif tag == "tr":
- # Flush any open cell/row from a previous row that may
- # have omitted its optional </td> or </tr> end tags.
+ # Flush any open cell/row from a previous row that omitted its
+ # optional </td> or </tr> end tags.
self._finish_cell()
self._finish_row()
elif tag in ("th", "td"):
- # Flush any open cell (handles omitted </td>/<th>)
+ # Flush any open cell (handles omitted </td>/<th>).
self._finish_cell()
self._cell_parts = []
self._in_cell = True
@@ -248,8 +248,8 @@ class _MarkdownRenderer(HTMLParser):
self._row_has_th = True
elif tag == "img":
- # Skip images -- keeps fetched page text focused on readable
- # content and avoids data-URI amplification.
+ # Skip images -- keeps page text focused on readable content and
+ # avoids data-URI amplification.
return
def handle_endtag(self, tag: str) -> None:
@@ -310,7 +310,7 @@ class _MarkdownRenderer(HTMLParser):
self._finish_row()
elif tag == "table":
- # Flush any remaining row (handles omitted </tr>)
+ # Flush any remaining row (handles omitted </tr>).
self._finish_cell()
self._finish_row()
self._in_table = False
@@ -325,15 +325,15 @@ class _MarkdownRenderer(HTMLParser):
if self._in_pre:
self._pre_parts.append(data)
return
- # Preserve literal whitespace inside inline <code> spans
+ # Preserve literal whitespace inside inline <code> spans.
if self._in_inline_code:
self._emit(data)
return
- # Collapse all whitespace (including newlines) per HTML rules
+ # Collapse all whitespace (including newlines) per HTML rules.
text = re.sub(r"\s+", " ", data)
- # Suppress whitespace-only text nodes between table structural
- # elements (indentation from source HTML) to prevent leading
- # spaces from breaking Markdown table row alignment.
+ # Suppress whitespace-only text nodes between table structural elements
+ # (source indentation) so leading spaces don't break Markdown table
+ # row alignment.
if self._in_table and not self._in_cell and not text.strip():
return
self._emit(text)
@@ -354,9 +354,9 @@ class _MarkdownRenderer(HTMLParser):
def flush_pending(self) -> None:
"""Flush any open side-buffers into ``_out``.
- Called after ``close()`` to recover content from truncated HTML
- where closing tags were never seen (common when ``_fetch_page_text``
- caps the download by byte count).
+ Called after ``close()`` to recover content from truncated HTML where
+ closing tags were never seen (common when ``_fetch_page_text`` caps the
+ download by byte count).
"""
# Flush innermost buffers first so their content propagates outward.
@@ -376,7 +376,7 @@ class _MarkdownRenderer(HTMLParser):
block = "```\n" + raw + "\n```"
self._emit("\n\n" + block + "\n\n")
- # Flatten any open blockquote buffers (innermost first)
+ # Flatten any open blockquote buffers (innermost first).
while self._bq_stack:
content = "".join(self._bq_stack.pop())
prefixed = self._prefix_blockquote(content)
@@ -394,8 +394,8 @@ class _MarkdownRenderer(HTMLParser):
def _cleanup(text: str) -> str:
"""Normalize whitespace and blank lines in the final output.
- Preserves content inside fenced code blocks verbatim so that
- intentional blank lines in ``<pre>`` content are not collapsed.
+ Preserves content inside fenced code blocks verbatim so intentional blank
+ lines in ``<pre>`` content are not collapsed.
"""
lines = text.split("\n")
out: list[str] = []
@@ -411,7 +411,7 @@ def _cleanup(text: str) -> str:
continue
if in_fence:
- # Preserve code block content exactly as-is
+ # Preserve code block content exactly as-is.
out.append(line)
continue
@@ -433,11 +433,11 @@ def _cleanup(text: str) -> str:
def html_to_markdown(source_html: str) -> str:
"""Convert an HTML string to Markdown.
- Handles headings, links, bold/italic, lists (ordered and unordered),
- tables, blockquotes, code blocks, and HTML entities. ``<script>``,
- ``<style>``, and ``<head>`` sections are stripped entirely.
+ Handles headings, links, bold/italic, ordered/unordered lists, tables,
+ blockquotes, code blocks, and HTML entities. ``<script>``, ``<style>``,
+ and ``<head>`` sections are stripped entirely.
"""
- # Normalize line endings before parsing
+ # Normalize line endings before parsing.
source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")
renderer = _MarkdownRenderer()
renderer.feed(source_html)
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.py
index 61dea5c010d..ce5f5c220fb 100644
--- a/studio/backend/core/inference/anthropic_compat.py
+++ b/studio/backend/core/inference/anthropic_compat.py
@@ -4,7 +4,7 @@
"""
Anthropic Messages API ↔ OpenAI format translation utilities.
-Pure functions and a stateful stream emitter — no FastAPI, no I/O.
+Pure functions plus stateful stream emitters; no FastAPI, no I/O.
"""
from __future__ import annotations
@@ -46,9 +46,9 @@ def anthropic_messages_to_openai(
) -> list[dict]:
"""Convert Anthropic messages + system to OpenAI-format message dicts.
- User messages that carry ``image`` blocks are emitted as OpenAI
- multimodal content arrays (``[{type: "text", ...}, {type: "image_url", ...}]``)
- so they flow through llama-server's native vision pathway.
+ User messages with ``image`` blocks are emitted as OpenAI multimodal
+ content arrays (``[{type: "text", ...}, {type: "image_url", ...}]``) so
+ they flow through llama-server's native vision pathway.
"""
result: list[dict] = []
@@ -104,9 +104,9 @@ def anthropic_messages_to_openai(
continue
if role == "user":
- # Build an ordered part list so text/image interleaving is
- # preserved (e.g. [text, image, text, image]). tool_result
- # blocks become their own OpenAI "tool" role messages.
+ # Ordered part list to preserve text/image interleaving (e.g.
+ # [text, image, text, image]). tool_result blocks become their
+ # own OpenAI "tool" role messages.
user_parts: list[dict] = []
has_image = False
tool_results: list[dict] = []
@@ -137,8 +137,8 @@ def anthropic_messages_to_openai(
if has_image:
result.append({"role": "user", "content": user_parts})
else:
- # No images — collapse text parts to a plain string so
- # existing text-only callers keep their simple shape.
+ # No images: collapse text parts to a plain string so
+ # text-only callers keep their simple shape.
text = "\n".join(p["text"] for p in user_parts)
if text:
result.append({"role": "user", "content": text})
@@ -181,8 +181,8 @@ def anthropic_tool_choice_to_openai(tc: Any) -> Any:
- ``{"type": "tool", "name": "get_weather"}``
→ ``{"type": "function", "function": {"name": "get_weather"}}``
- Returns ``None`` for ``None`` or any unrecognized shape (caller may
- then fall back to its own default, typically ``"auto"``).
+ Returns ``None`` for ``None`` or any unrecognized shape (caller falls
+ back to its own default, typically ``"auto"``).
"""
if tc is None:
return None
@@ -209,8 +209,8 @@ def build_anthropic_sse_event(event_type: str, data: dict) -> str:
class AnthropicStreamEmitter:
- """Converts generator events from generate_chat_completion_with_tools()
- into Anthropic Messages SSE strings."""
+ """Converts generate_chat_completion_with_tools() events into Anthropic
+ Messages SSE strings."""
def __init__(self) -> None:
self.block_index: int = 0
@@ -320,8 +320,8 @@ class AnthropicStreamEmitter:
# Close current text block if open.
if self._text_block_open:
events.append(self._close_block())
- # Defensive: if a replacement/different tool_start arrives while a
- # tool_use block is open, close the stale block before starting another.
+ # Defensive: if a different tool_start arrives while a tool_use
+ # block is open, close the stale block before starting another.
elif self._open_tool_call_id is not None:
events.append(self._close_block())
self._open_tool_call_id = None
@@ -421,10 +421,10 @@ class AnthropicStreamEmitter:
class AnthropicPassthroughEmitter:
"""Converts llama-server's OpenAI-format streaming chunks into Anthropic SSE.
- Used for the client-side tool-use pass-through path: the client (e.g. Claude
- Code) sends its own tool definitions in the ``tools`` field and expects to
- execute them itself. We forward them to llama-server and translate the
- streaming response back to Anthropic format without executing anything.
+ Used for the client-side tool-use pass-through path: the client (e.g.
+ Claude Code) sends its own tool definitions in ``tools`` and executes
+ them itself. We forward them to llama-server and translate the streaming
+ response back to Anthropic format without executing anything.
"""
def __init__(self) -> None:
diff --git a/studio/backend/core/inference/audio_codecs.py b/studio/backend/core/inference/audio_codecs.py
index e6b7f9c6134..c6d87d44f00 100644
--- a/studio/backend/core/inference/audio_codecs.py
+++ b/studio/backend/core/inference/audio_codecs.py
@@ -90,8 +90,8 @@ class AudioCodecManager:
import os
import sys
- # Clone SparkAudio/Spark-TTS GitHub repo for the sparktts Python package
- # (same approach as training — the HF model repos don't contain the package)
+ # Clone SparkAudio/Spark-TTS for the sparktts package (same as
+ # training; the HF model repos don't contain it)
spark_code_dir = os.path.join(os.path.dirname(model_repo_path or "."), "Spark-TTS")
sparktts_pkg = os.path.join(spark_code_dir, "sparktts")
if not os.path.isdir(sparktts_pkg):
@@ -115,7 +115,7 @@ class AudioCodecManager:
from sparktts.models.audio_tokenizer import BiCodecTokenizer
- # BiCodecTokenizer needs the MODEL repo path (contains BiCodec/ weights)
+ # BiCodecTokenizer needs the MODEL repo path (has BiCodec/ weights)
tokenizer_path = model_repo_path or spark_code_dir
self._bicodec_repo_path = tokenizer_path
self._bicodec_tokenizer = BiCodecTokenizer(tokenizer_path, device)
@@ -127,9 +127,9 @@ class AudioCodecManager:
import os
import sys
- # Clone OuteTTS repo (same pattern as Spark-TTS / BiCodec)
- # The pip package has problematic dependencies; the notebook clones and
- # removes gguf_model.py, interface.py, __init__.py before importing.
+ # Clone OuteTTS (same pattern as Spark-TTS / BiCodec). The pip
+ # package has problematic deps; the notebook clones and removes
+ # gguf_model.py, interface.py, __init__.py before importing.
base_dir = os.path.dirname(os.path.abspath(__file__))
outetts_code_dir = os.path.join(base_dir, "OuteTTS")
outetts_pkg = os.path.join(outetts_code_dir, "outetts")
@@ -148,8 +148,8 @@ class AudioCodecManager:
env = child_env_without_native_path_secret(),
**_windows_hidden_subprocess_kwargs(),
)
- # Remove files that pull in heavy / incompatible dependencies
- # (matches notebook: gguf_model.py is under models/, others under outetts/)
+ # Remove files pulling in heavy / incompatible deps (matches
+ # notebook: gguf_model.py under models/, others under outetts/)
remove_paths = [
os.path.join(outetts_pkg, "models", "gguf_model.py"),
os.path.join(outetts_pkg, "interface.py"),
@@ -181,9 +181,9 @@ class AudioCodecManager:
"""
Decode SNAC tokens (Orpheus) into WAV bytes.
- generated_ids: full model output including prompt tokens.
- Looks for START_OF_SPEECH (128257) marker, extracts codes after it,
- strips EOS (128258), redistributes 7-per-frame codes into 3 SNAC layers.
+ generated_ids: full model output including prompt tokens. Finds the
+ START_OF_SPEECH (128257) marker, extracts codes after it, strips EOS
+ (128258), redistributes 7-per-frame codes into 3 SNAC layers.
Returns (wav_bytes, 24000).
"""
@@ -192,7 +192,7 @@ class AudioCodecManager:
if len(token_indices[1]) > 0:
cropped = generated_ids[:, token_indices[1][-1] + 1 :]
else:
- # Gracefully fall back to using entire output if marker not found
+ # Fall back to the entire output if the marker is missing
logger.warning("No START_OF_SPEECH token (128257) found — using full generated output")
cropped = generated_ids
row = cropped[0]
@@ -256,8 +256,8 @@ class AudioCodecManager:
semantic_ids = torch.tensor([int(t) for t in semantic_matches]).long().unsqueeze(0)
- # Speaker encoder expects exactly 32 global tokens (token_num=32 in BiCodec config).
- # Pad with zeros or truncate to 32.
+ # Speaker encoder expects exactly 32 global tokens (token_num=32 in
+ # BiCodec config). Pad with zeros or truncate to 32.
GLOBAL_TOKEN_NUM = 32
if global_matches:
raw = [int(t) for t in global_matches]
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index c70e9b3c535..b85e9c348ad 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -2,8 +2,8 @@
# 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.
+Dependency-light wrapper around tokenizer.apply_chat_template with a kwarg
+fallback for templates that reject reasoning/tools args.
"""
from typing import Optional
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 3142434d09a..3132ad6f860 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -2,10 +2,10 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Async HTTP client for proxying chat completions to external LLM providers.
+Async HTTP client proxying chat completions to external LLM providers.
-Most registry providers expose OpenAI-compatible /v1/chat/completions endpoints;
-Anthropic uses native Messages API with translation in this client.
+Most providers use OpenAI-compatible /v1/chat/completions; Anthropic uses
+the native Messages API, translated in this client.
"""
import base64
@@ -19,40 +19,36 @@ from urllib.parse import urlparse
import httpx
import structlog
-# Use structlog so INFO-level diagnostics actually surface in the
-# studio backend's JSON log stream. The stdlib root logger defaults to
-# WARNING and is not configured with handlers, so plain
-# `logging.getLogger(__name__).info(...)` was being silently dropped —
-# only WARNING/ERROR made it through (because they bypassed the root
-# level threshold via uvicorn's stderr capture). All existing call
-# sites use printf-style positional args, which structlog accepts.
+# Use structlog so INFO diagnostics surface in the backend's JSON log
+# stream. The stdlib root logger defaults to WARNING with no handlers, so
+# `logging.getLogger(__name__).info(...)` was silently dropped (only
+# WARNING/ERROR reached uvicorn's stderr capture). Existing call sites use
+# printf-style positional args, which structlog accepts.
logger = structlog.get_logger(__name__)
# Claude 4.7 (Opus/Sonnet/Haiku) removed temperature, top_p, and top_k —
-# the API returns 400 "<param> is deprecated for this model" if any of
-# them is set to a non-default value. The "Sampling parameters removed"
-# section of the 4.7 release notes is the authoritative reference:
+# the API returns 400 "<param> is deprecated for this model" if any is set
+# to a non-default value. Authoritative ref ("Sampling parameters removed"):
# https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7
-# 3.x and 4.5/4.6 still accept all three; match the 4-7 line strictly so
-# the knobs keep working on earlier families. The trailing -4-7[-.]/EOL
-# anchor keeps future versions (e.g. claude-opus-5) unaffected.
+# 3.x and 4.5/4.6 still accept all three; match the 4-7 line strictly so the
+# knobs keep working on earlier families. The -4-7[-.]/EOL anchor keeps
+# future versions (e.g. claude-opus-5) unaffected.
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 an attacker can't bypass the gate with a
- path or subdomain like ``https://evil.com/api.openai.com/v1`` or
+ Anchored to the URL host so the gate can't be bypassed with a path or
+ subdomain like ``https://evil.com/api.openai.com/v1`` or
``https://api.openai.com.attacker.com/v1`` (CodeQL py/incomplete-url-
- substring-sanitization). Used to scope cloud-only Responses-API
- extensions (prompt_cache_retention, context_management compaction,
- container shell tool) that 400 on non-cloud OpenAI-compatible
- servers (ollama / llama.cpp / vLLM).
-
- Azure Foundry resources are scoped to
- ``<resource-name>.openai.azure.com``; match any subdomain via an
- `endswith` on the lowercased hostname, with the leading dot so
- `openai.azure.com` itself doesn't slip through (there is no
- apex-hosted Azure Foundry endpoint).
+ substring-sanitization). Scopes cloud-only Responses-API extensions
+ (prompt_cache_retention, context_management compaction, container shell
+ tool) that 400 on non-cloud OpenAI-compatible servers (ollama /
+ llama.cpp / vLLM).
+
+ Azure Foundry resources live at ``<resource-name>.openai.azure.com``;
+ match any subdomain via `endswith` on the lowercased host, with the
+ leading dot so `openai.azure.com` itself doesn't slip through (no
+ apex-hosted Azure Foundry endpoint exists).
"""
if not base_url:
return False
@@ -78,10 +74,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's image-generation docs allow follow-up edits by sending the
- previous ``image_generation_call`` id. Reasoning models can additionally
- require the paired ``reasoning`` output item in manually managed context,
- so keep the public replay fields only and drop everything else.
+ 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.
"""
if not isinstance(item, dict) or item.get("type") != "reasoning":
return None
@@ -113,9 +109,9 @@ def _sanitize_openai_reasoning_replay_item(item: Any) -> Optional[dict[str, Any]
# 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 the delim-separated tokens; each resolvable token expands
-# to `[[N]](URL)`, unresolved tokens (locators, unknown ids) drop silently
-# so no garbled glyph reaches the renderer.
+# 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_CITE_OPEN = "cite"
_OPENAI_CITE_STOP = ""
_OPENAI_CITE_DELIM = ""
@@ -128,7 +124,7 @@ def _build_citation_lookup(url_citations: list[dict[str, Any]]) -> dict[str, tup
"""Map every known ``source_id`` alias to ``(citation_index, url)``.
Accepts singular ``source_id`` and plural ``source_ids``. First-seen
- wins on alias collision so an earlier citation keeps its number.
+ 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):
@@ -150,17 +146,17 @@ 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 silently. Idempotent on text without
- private-use codepoints.
+ 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 silently.
- # Handles multi-source (all resolve) and source+locator (only the
- # 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,
+ # locator drops). Empty result strips the marker.
rendered: list[str] = []
for tok in match.group(1).split(_OPENAI_CITE_DELIM):
if not tok:
@@ -181,10 +177,10 @@ def _rewrite_citation_markers_partial(
"""Like ``_replace_openai_citation_markers`` but also reports whether
any marker referenced a source_id not yet in ``url_citations``.
- The ``annotation.added`` event for a url_citation typically arrives
- AFTER the delta carrying the marker referencing 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.
+ 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.
"""
if not text or _OPENAI_CITE_STOP not in text:
return text, False
@@ -205,7 +201,7 @@ def _rewrite_citation_markers_partial(
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 the unresolved ids once the source text is dropped.
+ # would lose unresolved ids once the source text is dropped.
if any_unresolved:
has_unresolved = True
return match.group(0)
@@ -222,14 +218,14 @@ def _split_pending_citation_tail(text: str) -> tuple[str, str]:
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 marker or a fully closed one.
+ emit. Empty tail when ``text`` has no open or a fully closed marker.
"""
if not text:
return text, ""
last_open = text.rfind("")
if last_open == -1:
return text, ""
- # Stop byte after the last open byte means the marker closed in this delta.
+ # A stop byte after the last open byte means the marker closed here.
if _OPENAI_CITE_STOP in text[last_open:]:
return text, ""
return text[:last_open], text[last_open:]
@@ -271,11 +267,10 @@ def _anthropic_thinking_spec(model: str) -> Optional[_AnthropicThinkingSpec]:
# tool-reference docs (https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference)
# the newer `_20260209` / `_20260120` variants only run on Opus 4.6/4.7
# and Sonnet 4.6 (web_search / web_fetch) or Opus 4.5+ and Sonnet 4.5+
-# (code_execution). Sending the new versions to an older model returns
-# 400 "tool not supported", and sending the old versions on a new model
-# misses the dynamic-filtering and free-with-search pricing path. Pick
-# the newest combination the model accepts, falling back to the GA
-# (`_20250305` / `_20250910` / `_20250825`) defaults for everything else.
+# (code_execution). New versions on an older model return 400 "tool not
+# supported"; old versions on a new model miss the dynamic-filtering and
+# free-with-search pricing path. Pick the newest combination the model
+# accepts, else the GA (`_20250305` / `_20250910` / `_20250825`) defaults.
_ANTHROPIC_NEW_WEB_PREFIXES = (
"claude-opus-4-7",
"claude-opus-4-6",
@@ -314,18 +309,18 @@ 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 the same
+# `code-execution-2025-08-25` header per the upstream docs.
_ANTHROPIC_CODE_EXECUTION_BETA = "code-execution-2025-08-25"
# Anthropic server-side context compaction (beta as of compact-2026-01-12).
-# Per the docs, the compaction tool is currently supported on Opus 4.6,
-# Opus 4.7, Sonnet 4.6 and Mythos Preview. The beta header is the same
-# for every supported model; the dated `compact_20260112` type lives in
-# the body's `context_management.edits` array. Anything sent to a model
-# outside this prefix list is silently ignored so we don't 400 upstream.
+# The compaction tool currently supports Opus 4.6, Opus 4.7, Sonnet 4.6 and
+# Mythos Preview. The beta header is the same for every supported model; the
+# dated `compact_20260112` type lives in the body's
+# `context_management.edits` array. Models outside this prefix list are
+# silently ignored so we don't 400 upstream.
_ANTHROPIC_COMPACTION_PREFIXES = (
"claude-opus-4-7",
"claude-opus-4-6",
@@ -334,8 +329,8 @@ _ANTHROPIC_COMPACTION_PREFIXES = (
)
_ANTHROPIC_COMPACTION_BETA = "compact-2026-01-12"
_ANTHROPIC_COMPACTION_TYPE = "compact_20260112"
-# The docs require the threshold to be at least 50K tokens; lower values
-# would 400. We 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 can't underflow.
_ANTHROPIC_COMPACTION_MIN = 50_000
@@ -355,13 +350,12 @@ 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" do not match.
+ # "claude-opus-4-70" / "claude-opus-4-7b" don't 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;
-# keeps SSE bytes bounded 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 (frontend trims to 240 chars anyway).
_CITED_TEXT_MAX_LEN = 512
@@ -370,12 +364,11 @@ def _anthropic_citation_key(citation: dict[str, Any]) -> tuple:
Anchor fields vary per type (char_location, page_location,
content_block_location, search_result_location); both start AND
- exclusive end indices are part of 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
+ 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.
"""
@@ -462,9 +455,9 @@ def _apply_mistral_reasoning_controls(
"""
Translate generic reasoning controls into Mistral's model-specific shape.
- Current contract:
+ Contract:
- magistral-medium-latest: baseline (no extra field) or
- `prompt_mode="reasoning"` for the explicit reasoning mode.
+ `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.
@@ -475,8 +468,8 @@ def _apply_mistral_reasoning_controls(
body.pop("reasoning_effort", None)
if spec.style == "prompt_mode":
- # Magistral baseline is already reasoning-capable. The explicit
- # prompt_mode path is only used 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
@@ -491,8 +484,8 @@ def _apply_mistral_reasoning_controls(
# 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.
+# Auth headers and timeouts are per-request, so one client handles every
+# provider without storing credentials.
_http_client = httpx.AsyncClient()
@@ -508,15 +501,15 @@ def _safe_fetch_image_for_gemini_sync(
) -> 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 actual connection cannot
- redirect us to a private/metadata address. Follows up to 4 hops,
- re-validating each redirect target. Returns (mime, base64) or None.
+ 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 additionally 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 after the fact.
+ `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.
"""
import urllib.error
import urllib.request
@@ -527,7 +520,7 @@ def _safe_fetch_image_for_gemini_sync(
if _byte_limit <= 0:
return None
- # Share tools.py's pinned-IP hardening: validate-once-then-pin.
+ # Reuse tools.py's pinned-IP hardening: validate-once-then-pin.
from .tools import (
_NoRedirect,
_SNIHTTPSHandler,
@@ -537,7 +530,7 @@ 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 otherwise raise ValueError mid-build.
+ would else raise ValueError mid-build.
"""
try:
parsed_url = urlparse(raw_url)
@@ -576,7 +569,7 @@ def _safe_fetch_image_for_gemini_sync(
return None
for _hop in range(4):
- # Pin to validated IP; SNI + cert still use hostname via _SNIHTTPSHandler.
+ # Pin to validated IP; SNI + cert still use the hostname via _SNIHTTPSHandler.
cp_info = _safe_parse_https(current_url)
if cp_info is None:
return None
@@ -643,7 +636,7 @@ def _safe_fetch_image_for_gemini_sync(
logger.info("Gemini image fetch: status=%s host=%s", status, current_host)
return None
_hdr_mime = (resp.headers.get("content-type") or "").split(";")[0].strip().lower()
- # Declared non-image MIME is a refusal; missing MIME falls back to caller's.
+ # Declared non-image MIME is refused; missing MIME uses the caller's.
if _hdr_mime and not _hdr_mime.startswith("image/"):
logger.info(
"Gemini image fetch: non-image content-type=%s host=%s",
@@ -689,31 +682,29 @@ async def _safe_fetch_image_for_gemini(
) -> 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.
+ 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 distinguish provider-side cards from real user-declared
-# tools of the same name. Mirrored on the TS side.
+# 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
- distinguish 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 existing shape because we keep this 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; 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.
"""
if not isinstance(payload, dict):
return
@@ -734,11 +725,11 @@ def _build_kimi_tool_end(
) -> str:
"""Format Kimi web_search citations into the tool_end payload.
- Same shape parseSourcesFromResult on the frontend 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 shows the
- tool card transitioning to a completed state.
+ 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.
"""
blocks: list[str] = []
for cit in citations:
@@ -767,9 +758,9 @@ class ExternalProviderClient:
):
self.provider_type = provider_type
self.base_url = base_url.rstrip("/")
- # 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 (
@@ -780,10 +771,10 @@ class ExternalProviderClient:
self.base_url = self.base_url[: -len("/openai")]
self.api_key = api_key
self._timeout = httpx.Timeout(timeout, connect = 10.0)
- # Disable read timeout on SSE streams: reasoning-heavy models
- # pause tens of seconds between bytes while thinking, and httpx's
- # read timeout is the per-byte gap, not wall clock. connect/write
- # bounds still surface real network failures.
+ # Disable read timeout on SSE streams: reasoning-heavy models pause
+ # tens of seconds between bytes while thinking, and httpx's read
+ # timeout is the per-byte gap, not wall clock. connect/write bounds
+ # still surface real network failures.
self._stream_timeout = httpx.Timeout(timeout, connect = 10.0, read = None)
def _auth_headers(self) -> dict[str, str]:
@@ -795,7 +786,7 @@ class ExternalProviderClient:
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 registry default.
+ # 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":
@@ -807,17 +798,17 @@ class ExternalProviderClient:
# httpx rejects an empty `Bearer ` value as "Illegal header value".
if self.api_key:
headers[auth_header] = f"{auth_prefix}{self.api_key}"
- # Merge any provider-specific extra headers (e.g. anthropic-version, OpenRouter attribution)
+ # Merge provider-specific extra headers (anthropic-version, OpenRouter attribution).
headers.update(provider_info.get("extra_headers", {}))
return headers
def _is_openai_compatible(self) -> bool:
- """Return False for providers that need request/response translation (e.g. Anthropic)."""
+ """Return False for providers needing request/response translation (e.g. Anthropic)."""
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":
@@ -849,19 +840,19 @@ class ExternalProviderClient:
"""
Yield OpenAI-format SSE lines from the external provider.
- For OpenAI-compatible providers, lines are forwarded verbatim.
- For Anthropic, the native Messages API SSE is translated to OpenAI format.
+ OpenAI-compatible providers forward lines verbatim. For Anthropic, the
+ native Messages API SSE is translated to OpenAI format.
``top_k`` and ``presence_penalty`` are forwarded only when the caller
- supplies a value the provider accepts — the frontend's
- provider-capability map already filters these per provider, so we
- treat them as opt-in here.
+ supplies a value the provider accepts; the frontend's
+ provider-capability map already filters these per provider, so they're
+ opt-in here.
``fast_mode`` only applies to Anthropic Opus 4.6 / 4.7 (silently
dropped elsewhere); 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="none" hard-disables hosted/builtin tools across every
+ # provider so enabled_tools can't accidentally bill or leak.
tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
@@ -870,7 +861,7 @@ class ExternalProviderClient:
# Gemini speaks its own native REST shape (contents/parts);
# `_stream_gemini` translates request/response into the OpenAI
# Chat Completions chunk format the rest of Studio expects.
- # API reference: https://ai.google.dev/gemini-api/docs
+ # API ref: https://ai.google.dev/gemini-api/docs
if self.provider_type == "gemini":
async for line in self._stream_gemini(
messages,
@@ -909,9 +900,9 @@ class ExternalProviderClient:
yield line
return
- # OpenAI moved their flagship models (gpt-5.x) off /v1/chat/completions
- # — those endpoints return 404 with "This is not a chat model" for the
- # new families. Route all OpenAI traffic through /v1/responses instead;
+ # 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.
if self.provider_type == "openai":
@@ -933,8 +924,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.
+ # 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_tool_choice_forced_function = (
isinstance(tool_choice, dict)
@@ -966,24 +957,24 @@ class ExternalProviderClient:
"presence_penalty": presence_penalty,
}
if max_tokens is not None:
- # OpenAI newer models (gpt-4o, gpt-5.x) reject max_tokens
+ # Newer OpenAI models (gpt-4o, gpt-5.x) reject max_tokens
if self.provider_type == "openai":
body["max_completion_tokens"] = max_tokens
else:
body["max_tokens"] = max_tokens
- # Drop fields the registry flags as unusable so reasoning-class
- # models with fixed defaults (Kimi k2.6 etc) don't 400 on pydantic
- # default values that the route layer still fills in.
+ # 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.
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.
@@ -1018,8 +1009,8 @@ class ExternalProviderClient:
body["reasoning"] = {"enabled": False}
# OpenRouter web plugin works on every model id including
- # meta-routers (unlike the `:online` suffix). Forced-function
- # tool_choice suppresses it, matching Gemini/Anthropic.
+ # meta-routers (unlike `:online`). Forced-function tool_choice
+ # suppresses it, matching Gemini/Anthropic.
# https://openrouter.ai/docs/guides/features/plugins/web-search
_or_tool_choice_forced_function = (
isinstance(tool_choice, dict)
@@ -1042,10 +1033,10 @@ 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 that wire 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:
@@ -1084,18 +1075,17 @@ class ExternalProviderClient:
yield _error_sse_line(response.status_code, error_text, self.provider_type)
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; surfaces
- # OpenRouter mid-stream errors that would otherwise be
- # 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
@@ -1129,10 +1119,9 @@ 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
@@ -1191,8 +1180,8 @@ class ExternalProviderClient:
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" in the
- # UI before the stream closes.
+ # tool-card transitions to "complete" before
+ # the stream closes.
if (
web_search_active
and web_search_tool_started
@@ -1208,7 +1197,7 @@ class ExternalProviderClient:
if isinstance(parsed, dict):
# Mid-stream provider error event. OpenRouter
# in particular returns 200 then surfaces the
- # actual failure as an SSE error event.
+ # failure as an SSE error event.
if "error" in parsed:
event_counts["error"] = event_counts.get("error", 0) + 1
logger.warning(
@@ -1219,20 +1208,18 @@ class ExternalProviderClient:
else:
event_counts["delta"] = event_counts.get("delta", 0) + 1
# OpenRouter (and most OAI-compat providers)
- # report the underlying model that handled
- # the request in every chunk's `model` field.
- # Latch the first non-empty value so the
- # router-picked model surfaces in logs and
- # is available to the proxy caller.
+ # 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"]
- # When the user has 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):
@@ -1249,8 +1236,8 @@ class ExternalProviderClient:
_record_or_url_citation(ann)
yield line
# Stream ended without [DONE] (some upstreams just close
- # the connection). Emit tool_end so the card doesn't
- # stay in "running" forever.
+ # the connection). Emit tool_end so the card doesn't 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
@@ -1303,30 +1290,30 @@ class ExternalProviderClient:
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 (they
- are an 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 that
- echoes the same arguments back 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 — that is the final answer the
- user sees, with search results already incorporated.
+ 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 the other providers.
+ 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 silently
- # would have 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"}}],
}
@@ -1438,10 +1425,9 @@ class ExternalProviderClient:
)
return
- # If the model decided not to search, fall back to a plain
- # streaming call without the builtin tool. That mirrors the UX
- # of every other provider when web_search is on but the model
- # didn't actually 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 didn't need it.
search_calls = [
tc for tc in tool_calls_acc.values() if tc["function"]["name"] == "$web_search"
]
@@ -1470,7 +1456,7 @@ class ExternalProviderClient:
yield _error_sse_line(response.status_code, error_text, self.provider_type)
return
# Manual __anext__ loop instead of `async for` — see the
- # comment in stream_chat_completion for the Python 3.13 +
+ # stream_chat_completion comment for the Python 3.13 +
# httpcore 1.0.x GeneratorExit interaction this avoids.
lines_gen = response.aiter_lines().__aiter__()
try:
@@ -1497,20 +1483,19 @@ 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 = {}
- # Log the raw arguments so we can confirm the server actually
- # ran the search. The shape is documented loosely but in practice
- # the model emits `{"search_result":{"search_id":...},
- # "usage":{"total_tokens":N}}` — an opaque receipt where N is the
- # token cost of the injected search context. The query string is
- # NOT present; Kimi runs the search server-side during the first
- # call and bakes the results straight into the model's context.
+ # Log the raw arguments to confirm the server ran the search. The shape
+ # is loosely documented but in practice the model emits
+ # `{"search_result":{"search_id":...}, "usage":{"total_tokens":N}}` —
+ # an opaque receipt where N is the token cost of the injected search
+ # context. The query string is NOT present; Kimi runs the search
+ # server-side during the first call and bakes the results into context.
logger.info(
"Kimi $web_search: %d tool_call(s), args[0]=%s",
len(search_calls),
@@ -1531,14 +1516,13 @@ class ExternalProviderClient:
"arguments": first_args if isinstance(first_args, dict) else {},
}
)
- # Kimi's search has already executed server-side by the time the
- # first call returns (the tool_call envelope encodes the search
- # result reference, not a query for us to dispatch). Emit
- # tool_end NOW so the UI's web-search card transitions to
- # "complete" before the second call starts streaming the
- # answer, instead of after — otherwise the card sits in
- # "running" all the way through the answer streaming and the
- # user perceives the model answering before search finishes.
+ # Kimi's search has already run server-side by the time the first call
+ # returns (the tool_call envelope encodes the search result reference,
+ # not a query for us to dispatch). Emit tool_end NOW so the UI's
+ # web-search card transitions to "complete" before the second call
+ # streams the answer — otherwise the card sits in "running" through the
+ # whole answer and the user perceives the model answering before search
+ # finishes.
yield _build_kimi_tool_end(_synthetic_chunk, tool_call_id, [])
# ---- Second call: echo the tool_calls back and stream answer ----
@@ -1558,14 +1542,14 @@ class ExternalProviderClient:
]
followup_body = dict(body)
followup_body["messages"] = list(messages) + [assistant_msg] + tool_msgs
- # Ask the SSE stream to include a final `usage` block so we can
- # see prompt_tokens (which jumps to thousands when the server
- # injects search context). Without this, OpenAI-compat streams
- # omit usage entirely. Kimi follows the same convention.
+ # Ask the SSE stream for a final `usage` block so we see prompt_tokens
+ # (which jumps to thousands when the server injects search context).
+ # Without this, OpenAI-compat streams omit usage entirely; Kimi follows
+ # the same convention.
followup_body["stream_options"] = {"include_usage": True}
- # Keep the tool definition on the second call so the model can
- # decide to search again mid-turn if needed. Kimi's doc shows
- # the same tools array on every step.
+ # Keep the tool definition on the second call so the model can search
+ # again mid-turn if needed. Kimi's doc shows the same tools array on
+ # every step.
try:
async with _http_client.stream(
@@ -1587,10 +1571,10 @@ class ExternalProviderClient:
return
lines_gen = response.aiter_lines().__aiter__()
- # Diagnostics: latch usage.prompt_tokens from the final
- # chunk. The Kimi docs say search results count toward
- # prompt_tokens, so a big value here is direct evidence
- # the server actually injected results into context.
+ # Diagnostics: latch usage.prompt_tokens from the final chunk.
+ # Kimi docs say search results count toward prompt_tokens, so a
+ # big value here is direct evidence the server injected results
+ # into context.
last_usage: Optional[dict[str, Any]] = None
annotation_shapes: set[str] = set()
try:
@@ -1614,9 +1598,9 @@ class ExternalProviderClient:
last_usage = usage
# Scan annotations only for diagnostics —
# Kimi today doesn't emit url_citation, but
- # if a future model version starts to we'll
- # see the type name in the final log line
- # and can wire it into the tool_end payload.
+ # if a future version does we'll see the
+ # type name in the final log line and can
+ # wire it into the tool_end payload.
for choice in parsed.get("choices") or []:
if not isinstance(choice, dict):
continue
@@ -1687,7 +1671,7 @@ class ExternalProviderClient:
"""
import json as _json
- # Extract system prompt and translate image_url parts to Anthropic format
+ # Extract system prompt; translate image_url parts to Anthropic format
system: Optional[str] = None
filtered: list[dict[str, Any]] = []
for msg in messages:
@@ -1702,10 +1686,10 @@ class ExternalProviderClient:
content = msg.get("content")
# OpenAI role="tool" with list content -> Anthropic native
- # tool_result block on a user message. Translating in the
- # string-content branch only (below) leaves the list-content
- # form forwarded as an invalid `role:"tool"` message that
- # Anthropic rejects. Handle both upfront.
+ # 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.
if msg.get("role") == "tool":
_tr_id = msg.get("tool_call_id") or ""
if isinstance(content, list):
@@ -1749,12 +1733,11 @@ class ExternalProviderClient:
if part.get("type") == "text":
anthropic_parts.append({"type": "text", "text": part["text"]})
elif part.get("type") == "compaction":
- # Round-trip the compaction block. When the
- # prior assistant turn ran server-side
- # compaction, that block must land back on this
- # turn's assistant message so Anthropic skips
- # re-compaction from scratch. Forward verbatim
- # under the {type:"compaction", content:"..."}
+ # Round-trip the compaction block. When the prior
+ # assistant turn ran server-side compaction, that block
+ # must land back on this turn's assistant message so
+ # Anthropic skips re-compaction from scratch. Forward
+ # verbatim under the {type:"compaction", content:"..."}
# shape the API expects. See
# https://platform.claude.com/docs/en/build-with-claude/compaction
summary = part.get("content") or ""
@@ -1777,7 +1760,7 @@ class ExternalProviderClient:
}
)
else:
- # Remote URL -- Anthropic supports url source type natively.
+ # 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(
{
@@ -1793,16 +1776,15 @@ class ExternalProviderClient:
# for PDFs / docs. The frontend sends either
# `{type:"input_document", file_data:"data:application/pdf;base64,..."}`
# or `{type:"input_document", file_url:"https://..."}`,
- # plus optional `filename` and `media_type`.
- # Translate to Anthropic's native `document` block.
+ # plus optional `filename` and `media_type`. Translate
+ # to Anthropic's native `document` block.
url = part.get("file_url") or ""
data_uri = part.get("file_data") or ""
title = part.get("filename")
- # Treat any "data:" URI with no actual base64
- # payload (`data:application/pdf;base64,` or
- # whitespace-only) as missing so the file_url
- # branch below can take over. Matches the
- # OpenAI-side fallback so a malformed inline
+ # Treat any "data:" URI with no actual base64 payload
+ # (`data:application/pdf;base64,` or whitespace-only) as
+ # missing so the file_url branch below can take over.
+ # Matches the OpenAI-side fallback so a malformed inline
# payload + valid remote URL still attaches.
data_uri_valid = False
b64data = ""
@@ -1844,11 +1826,10 @@ 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. Anthropic native
- # Messages API does not accept OpenAI's top-level
- # `tool_calls` field; the call lives inside a content
- # block with `{type:"tool_use", id, name, input}`.
+ # 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}`.
if msg.get("role") == "assistant" and isinstance(msg.get("tool_calls"), list):
for _tc in msg["tool_calls"]:
if not isinstance(_tc, dict):
@@ -1871,17 +1852,16 @@ 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 the Anthropic API 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")
@@ -1904,11 +1884,10 @@ 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. Without this,
+ # the top-level tool_calls leaks through unchanged.
if (
msg.get("role") == "assistant"
and isinstance(msg.get("tool_calls"), list)
@@ -1944,12 +1923,12 @@ class ExternalProviderClient:
continue
filtered.append(msg)
- # Claude 4.7 family removed temperature / top_p / top_k entirely.
- # The earlier guard only handled top_k; temperature is now also
- # rejected with 400 "temperature is deprecated for this model".
- # Latch the match once and reuse it everywhere temperature or
- # top_k would otherwise be set — including the thinking-mode
- # override below, which used to force temperature=1.
+ # Claude 4.7 family removed temperature / top_p / top_k entirely. The
+ # earlier guard only handled top_k; temperature is now also rejected
+ # with 400 "temperature is deprecated for this model". Latch the match
+ # once and reuse it everywhere temperature or top_k would be set —
+ # including the thinking-mode override below, which used to force
+ # temperature=1.
sampling_removed = bool(_ANTHROPIC_4_7_SAMPLING_REMOVED.match(model))
body: dict[str, Any] = {
@@ -1962,15 +1941,14 @@ 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 only caches a prefix when at least one cache_control
- # marker is attached to it — the frontend defaults
- # enable_prompt_caching to True for Anthropic, so treat `None` the
- # same as True here (callers that don't set the flag still get
- # caching). Pass False explicitly to opt out.
+ # Anthropic only caches a prefix when at least one cache_control marker
+ # is attached. The frontend defaults enable_prompt_caching to True for
+ # Anthropic, so treat `None` as True here (callers that don't set the
+ # flag still get caching). Pass False explicitly to opt out.
prompt_caching_enabled = enable_prompt_caching is not False
- # Optional 1h cache TTL is GA as of 2026-05 (no beta header). 1h
- # writes are 2x vs 5m's 1.25x but reads are 0.1x for both, so 1h
- # wins after a single extra hit. Unknown TTL strings drop.
+ # Optional 1h cache TTL is GA as of 2026-05 (no beta header). 1h writes
+ # are 2x vs 5m's 1.25x but reads are 0.1x for both, so 1h wins after a
+ # single extra hit. Unknown TTL strings drop.
cache_marker: dict[str, Any] = {"type": "ephemeral"}
if prompt_cache_ttl in ("5m", "1h"):
cache_marker["ttl"] = prompt_cache_ttl
@@ -1989,14 +1967,13 @@ class ExternalProviderClient:
body["system"] = system
if prompt_caching_enabled and filtered:
- # Second breakpoint at the end of the conversation. Anthropic
- # caches the longest matching prefix up to a cache_control
- # marker; placing one on the latest message means turn N+1
- # rehydrates everything up through turn N from cache instead
- # of recomputing it. This is what makes caching actually work
- # when the system prompt is empty or shorter than Anthropic's
- # ~1024-token cache floor — the conversation history carries
- # the bulk of the input tokens. Anthropic allows up to 4
+ # Second breakpoint at the end of the conversation. Anthropic caches
+ # the longest matching prefix up to a cache_control marker; placing
+ # one on the latest message means turn N+1 rehydrates everything
+ # through turn N from cache instead of recomputing. This makes
+ # caching work when the system prompt is empty or shorter than
+ # Anthropic's ~1024-token cache floor — the conversation history
+ # carries the bulk of input tokens. Anthropic allows up to 4
# breakpoints per request; we use at most 2 (system + tail).
last_msg = filtered[-1]
content = last_msg.get("content")
@@ -2010,9 +1987,9 @@ class ExternalProviderClient:
]
elif isinstance(content, list) and content:
# Don't mutate the caller's list. Rebuild the tail with
- # cache_control attached to the final block so an
- # upstream image-bearing turn still cleanly slots into
- # the cache as part of the conversational prefix.
+ # cache_control on the final block so an upstream image-bearing
+ # turn still cleanly slots into the cache as part of the
+ # conversational prefix.
head = list(content[:-1])
tail = content[-1]
if isinstance(tail, dict):
@@ -2027,8 +2004,8 @@ class ExternalProviderClient:
effort = reasoning_effort if reasoning_effort in allowed_efforts else None
# Claude 4.6 Opus/Sonnet accept top-tier adaptive effort as "max" only;
# "xhigh" is rejected (supported on Claude 4.7). Map our shared "xhigh"
- # semantic to "max" for 4.6 outbound requests while still accepting
- # both in ``allowed_efforts`` for persisted / cross-provider UI state.
+ # to "max" for 4.6 outbound requests while still accepting both in
+ # ``allowed_efforts`` for persisted / cross-provider UI state.
if effort == "xhigh" and model.startswith(("claude-opus-4-6", "claude-sonnet-4-6")):
effort = "max"
if effort is None:
@@ -2041,31 +2018,30 @@ class ExternalProviderClient:
if effort and effort != "none":
# Anthropic rejects top_k whenever thinking is enabled.
body.pop("top_k", None)
- # Earlier families (4.5/4.6) require temperature=1 when
- # thinking is enabled and forbid top_p in the same request:
+ # Earlier families (4.5/4.6) require temperature=1 when thinking is
+ # enabled and forbid top_p in the same request:
# "temperature and top_p cannot both be specified for this
# model. Please use only one."
- # On Claude 4.7, temperature was removed entirely — sending
- # any value (including 1) returns 400 — so skip the override
- # there and let the model use its default sampling.
+ # On Claude 4.7, temperature was removed entirely — any value
+ # (including 1) returns 400 — so skip the override there and let
+ # the model use its default sampling.
if not sampling_removed:
body["temperature"] = 1
body.pop("top_p", None)
if thinking_spec and thinking_spec.kind == "adaptive":
# `display` defaults to "omitted" on Claude Opus 4.7 (per the
- # adaptive-thinking docs) — without an explicit opt-in the
- # API emits an empty thinking block plus a signature_delta,
- # so our SSE handler would surface a stray <think></think>
- # and the reasoning panel would stay blank. Force
- # "summarized" so 4.7 streams thinking_delta events like
- # 4.6 does. On 4.6 / Sonnet 4.6 this is the default, so
- # setting it explicitly is harmless.
+ # adaptive-thinking docs) — without an explicit opt-in the API
+ # emits an empty thinking block plus a signature_delta, so our
+ # SSE handler would surface a stray <think></think> and the
+ # reasoning panel would stay blank. Force "summarized" so 4.7
+ # streams thinking_delta events like 4.6 does. On 4.6 / Sonnet
+ # 4.6 this is the default, so setting it is harmless.
body["thinking"] = {"type": "adaptive", "display": "summarized"}
- # Per the Messages API reference, the effort knob for
- # adaptive thinking lives under `output_config.effort` —
- # NOT as a top-level field. Sending `effort: ...` directly
- # produces a 400 "effort: Extra inputs are not permitted".
- # Allowed values: low | medium | high | xhigh | max. See:
+ # Per the Messages API reference, the effort knob for adaptive
+ # thinking lives under `output_config.effort` — NOT as a
+ # top-level field. Sending `effort: ...` directly produces a 400
+ # "effort: Extra inputs are not permitted". Allowed values:
+ # low | medium | high | xhigh | max. See:
# https://platform.claude.com/docs/en/api/messages
body["output_config"] = {"effort": effort}
elif thinking_spec and thinking_spec.kind == "manual":
@@ -2079,8 +2055,8 @@ class ExternalProviderClient:
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 can't fire server-side search/code-exec.
_anthropic_tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
@@ -2141,13 +2117,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.
+ # 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
compaction_active = (
compaction_threshold is not None
@@ -2171,9 +2147,9 @@ class ExternalProviderClient:
]
}
- # fast_mode is Opus 4.6/4.7 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 4.6/4.7 only; silently drop elsewhere. Incompatible
+ # with the Priority service_tier (frontend gate prevents both at once;
+ # 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"
@@ -2182,7 +2158,7 @@ class ExternalProviderClient:
completion_id = f"chatcmpl-anthropic-{model.replace('/', '-')}"
# Log outgoing config keys (not messages) to prove which thinking /
- # effort fields actually reached the wire.
+ # 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, "
@@ -2197,9 +2173,9 @@ 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).
+ # 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
_finish_reason_map: dict[str, Optional[str]] = {
"end_turn": "stop",
@@ -2243,12 +2219,11 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- # Stale container detection (mirror of the OpenAI
- # path). When we sent a `container` field and the
- # response is 4xx with any hint that 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 (
@@ -2268,47 +2243,44 @@ 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 the next time the user reports
- # "no thinking content" — distinguishes "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 didn't 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 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 don't 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 the 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 that uses both does not collide.
+ # 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.
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 here).
- # Accumulate in `current_compaction["content"]` and emit
- # on content_block_stop so the chat-adapter can persist
- # it onto the assistant message for round-tripping on
- # the next turn.
+ # `{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.
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]] = []
# Counts surfaced in the final log line so reports of
# "Code execution did nothing" can be triaged at a
@@ -2326,12 +2298,12 @@ class ExternalProviderClient:
# from the inbound id — no churn on reuse.
latched_container_id: Optional[str] = None
container_id_emitted = False
- # Cache usage tracking. message_start carries the input
- # accounting (incl. cache_creation_input_tokens and
+ # Cache usage tracking. message_start carries input accounting
+ # (incl. cache_creation_input_tokens and
# cache_read_input_tokens); message_delta carries cumulative
- # output_tokens. Both are surfaced in the "stream complete"
- # log so prompt caching can be verified per-request without
- # opening the Anthropic dashboard.
+ # output_tokens. Both surface in the "stream complete" log so
+ # prompt caching can be verified per-request without opening the
+ # Anthropic dashboard.
last_usage: dict[str, Any] = {}
def _content_chunk(text: str) -> str:
@@ -2379,20 +2351,18 @@ 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 already expect from the
- web_search path.
+ """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 do not surface the base64
- bytes; the title + url is enough for the source
- pill, and the model still sees the document
- contents on its side.
+ 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}.
"""
inner_type = inner.get("type") or ""
@@ -2408,15 +2378,15 @@ 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
- # since the 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] = []
@@ -2429,11 +2399,11 @@ 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"):
@@ -2453,9 +2423,9 @@ class ExternalProviderClient:
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, but
- # that's encoded into the tool_start arguments
- # already — here we only format the result body.
+ # 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:
@@ -2494,11 +2464,11 @@ class ExternalProviderClient:
key = event_type or "<unknown>"
event_counts[key] = event_counts.get(key, 0) + 1
- # message_start carries the input-side usage block
- # including cache_creation_input_tokens and
+ # message_start carries the input-side usage block incl.
+ # cache_creation_input_tokens and
# cache_read_input_tokens. message_delta updates
- # output_tokens (and may overwrite the input fields
- # with final values). Merge both into last_usage.
+ # output_tokens (and may overwrite the input fields with
+ # final values). Merge both into last_usage.
if event_type == "message_start":
start_usage = (event.get("message") or {}).get("usage")
if isinstance(start_usage, dict):
@@ -2522,10 +2492,10 @@ 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; 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,
@@ -2574,12 +2544,12 @@ class ExternalProviderClient:
"bash_code_execution_tool_result",
"text_editor_code_execution_tool_result",
):
- # Anthropic ships the full result content
- # on the start event for code-exec result
- # blocks (unlike web_search, which can
- # split across deltas). Capture it and
- # finalize on content_block_stop so the
- # ordering matches the web_search path.
+ # Anthropic ships the full result content on the
+ # start event for code-exec result blocks
+ # (unlike web_search, which can split across
+ # deltas). Capture it and finalize on
+ # content_block_stop so ordering matches the
+ # web_search path.
tool_use_id = content_block.get("tool_use_id", "")
inner = content_block.get("content") or {}
current_code_exec_result = {
@@ -2607,19 +2577,18 @@ class ExternalProviderClient:
yield _content_chunk(thinking_text)
elif delta_type == "text_delta":
text = delta.get("text", "")
- # text_deltas inside a compaction block
- # carry the 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 DON'T 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 we opened above. Anthropic emits
- # a content_block_stop between blocks, but
+ # <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:
@@ -2630,9 +2599,8 @@ class ExternalProviderClient:
# 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
+ # 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
cit = delta.get("citation")
if isinstance(cit, dict):
@@ -2647,14 +2615,13 @@ class ExternalProviderClient:
idx_for_marker = len(document_citations)
yield _content_chunk(f"[{idx_for_marker}]")
elif delta_type == "input_json_delta":
- # Streamed partial_json carrying tool inputs
- # — the search query for web_search, or the
- # command/path/etc. for code execution.
- # Route to whichever buffer is open. The two
- # state slots are exclusive in practice
- # (Anthropic doesn't interleave tool input
- # streams), but checking both keeps the
- # dispatch robust if that ever changes.
+ # Streamed partial_json carrying tool inputs —
+ # the search query for web_search, or
+ # command/path/etc. for code execution. Route to
+ # whichever buffer is open. The state slots are
+ # exclusive in practice (Anthropic doesn't
+ # interleave tool input streams), but checking
+ # all keeps the dispatch robust if that changes.
partial = delta.get("partial_json", "")
if current_server_tool_use is not None:
current_server_tool_use["buffer"] += partial
@@ -2662,17 +2629,17 @@ 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 any other delta types are
- # intentionally 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.
+ # 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:
@@ -2697,11 +2664,10 @@ 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. parseSourcesFromResult
- # on the frontend 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:
@@ -2716,11 +2682,11 @@ 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:
@@ -2746,13 +2712,12 @@ class ExternalProviderClient:
current_code_exec_use = None
elif current_compaction is not None:
# End of a compaction block. Emit it as a
- # synthetic tool_event so the chat-adapter
- # can persist the {type:"compaction",
- # content:"..."} payload onto the
- # assistant message. The next turn's
- # request body forwards the content_part
- # verbatim and Anthropic recognises it
- # as the prior compaction state.
+ # synthetic tool_event so the chat-adapter can
+ # persist the {type:"compaction", content:"..."}
+ # payload onto the assistant message. The next
+ # turn's request body forwards the content_part
+ # verbatim and Anthropic recognises it as the
+ # prior compaction state.
compaction_blocks_seen += 1
yield _emit_tool_event(
{
@@ -2762,13 +2727,13 @@ 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):
@@ -2789,11 +2754,10 @@ 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
+ # 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 = ""
@@ -2823,15 +2787,14 @@ class ExternalProviderClient:
)
current_web_fetch_use = None
elif current_web_fetch_result is not None:
- # End of the web_fetch_tool_result —
- # format Title / URL / snippet for the
- # frontend source pill and emit tool_end.
- # `inner` is sanitised to a dict at the
- # matching content_block_start, and the
- # formatter always returns a non-empty
- # string (defaulting to "(fetch complete)"
- # when no fields are present), so no
- # extra fallback is needed here.
+ # End of the web_fetch_tool_result — format Title
+ # / URL / snippet for the frontend source pill
+ # and emit tool_end. `inner` is sanitised to a
+ # dict at the matching content_block_start, and
+ # the formatter always returns a non-empty string
+ # (defaulting to "(fetch complete)" when no
+ # fields are present), so no extra fallback is
+ # needed here.
tool_use_id = current_web_fetch_result["tool_use_id"]
result_text = _format_web_fetch_result(
current_web_fetch_result["inner"]
@@ -2849,8 +2812,8 @@ class ExternalProviderClient:
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).
+ # display=omitted on Claude 4.7, or
+ # thinking-only turns).
yield _content_chunk("</think>")
thinking_open = False
@@ -2872,14 +2835,14 @@ class ExternalProviderClient:
if c_in or c_out:
last_usage["compaction_input_tokens"] = c_in
last_usage["compaction_output_tokens"] = c_out
- # Anthropic reports the code_execution container
- # id on `message_delta.delta.container.{id,
- # expires_at}` (NOT on message_start — at start
- # the container hasn't been provisioned yet).
- # Latch on first sight and emit container_ready
- # only when the value differs from the inbound
- # id, so steady-state reuse doesn't re-write
- # the same id to the thread record every turn.
+ # Anthropic reports the code_execution container id
+ # on `message_delta.delta.container.{id,
+ # expires_at}` (NOT on message_start — at start the
+ # container isn't provisioned yet). Latch on first
+ # sight and emit container_ready only when the value
+ # differs from the inbound id, so steady-state reuse
+ # doesn't re-write the same id to the thread record
+ # 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:
@@ -2903,16 +2866,15 @@ 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
+ # `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.
+ # finish_reason="stop" chunk that would truncate
+ # the rendered message in the UI.
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
+ # 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
if stop_reason == "refusal":
@@ -2920,9 +2882,9 @@ class ExternalProviderClient:
"Anthropic refusal stop_reason (model=%s)",
model,
)
- # Drop signal rides _toolEvent (not
- # text) so assistant content cannot
- # spoof a context reset.
+ # Drop signal rides _toolEvent (not text) so
+ # assistant content can't spoof a context
+ # reset.
yield _content_chunk(
"\n\n_The response was stopped by "
"Anthropic's safety classifier. Edit "
@@ -2948,10 +2910,10 @@ 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:
@@ -2966,9 +2928,9 @@ class ExternalProviderClient:
"citations": clean_cits,
}
)
- # Final include_usage-style chunk so callers can
- # 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",
@@ -2985,8 +2947,8 @@ class ExternalProviderClient:
raise
finally:
# Surface per-event-type counts + web_search summary so
- # reports of "no reasoning panel content" / "Search
- # didn't do anything" can be triaged at a glance.
+ # reports of "no reasoning panel content" / "Search didn't
+ # do anything" can be triaged at a glance.
web_search_requested = bool(enabled_tools and "web_search" in enabled_tools)
web_search_invocations = len(web_search_calls)
total_results = sum(
@@ -2994,11 +2956,10 @@ class ExternalProviderClient:
)
queries = [sc["query"] for sc in web_search_calls.values() if sc.get("query")]
# cache_read_input_tokens > 0 on turn N proves the
- # cache_control marker on the system block is doing
- # its job — turn 1 will show cache_creation > 0
- # instead. cache_creation tokens are billed at a
- # small premium; cache_read tokens are billed at a
- # discount.
+ # cache_control marker on the system block is working —
+ # turn 1 shows cache_creation > 0 instead. cache_creation
+ # tokens are billed at a small premium; cache_read tokens
+ # at a discount.
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
@@ -3089,11 +3050,10 @@ class ExternalProviderClient:
) -> AsyncGenerator[str, None]:
"""
Call Google's native Gemini API and translate its streaming
- ``streamGenerateContent`` response into OpenAI Chat Completions
- chunk format.
+ ``streamGenerateContent`` response into OpenAI Chat Completions chunks.
- Gemini does NOT speak the OpenAI Chat Completions contract on
- its primary endpoint. The wire shape is:
+ Gemini does NOT speak the OpenAI Chat Completions contract on its
+ primary endpoint. The wire shape is:
POST /v1beta/models/{model}:streamGenerateContent?alt=sse
{
@@ -3113,12 +3073,11 @@ class ExternalProviderClient:
"usageMetadata": {"promptTokenCount": 7, "candidatesTokenCount": 3}}
Image generation uses the same endpoint with model
- ``gemini-2.5-flash-image`` (also called Nano Banana); the
- response carries an ``inlineData`` part with the 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.
+ ``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
@@ -3129,12 +3088,12 @@ class ExternalProviderClient:
"""
import json as _json
- # Validate the user-controlled model id BEFORE any message
- # translation. A model like `../cachedContents/x` is path-
- # traversal that lands in `/v1beta/cachedContents/...`; rejecting
- # it here also avoids triggering user-controlled outbound fetches
- # (remote image_url inlining) on a request we'll error out
- # anyway. Documented catalog ids match `[A-Za-z0-9._-]+`.
+ # Validate the user-controlled model id BEFORE any message translation.
+ # A model like `../cachedContents/x` is path-traversal landing in
+ # `/v1beta/cachedContents/...`; rejecting it here also avoids triggering
+ # user-controlled outbound fetches (remote image_url inlining) on a
+ # request we'll error out anyway. Documented catalog ids match
+ # `[A-Za-z0-9._-]+`.
if not re.fullmatch(r"[A-Za-z0-9._-]+", model):
yield _error_sse_line(
400,
@@ -3143,21 +3102,21 @@ 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 isn't 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; we
- # set it 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
@@ -3201,12 +3160,11 @@ class ExternalProviderClient:
header.split(";")[0].replace("data:", "").strip().lower()
or "image/jpeg"
)
- # Symmetry with the fetched remote image
- # path, which already rejects non-image
- # Content-Type. A `data:text/html;base64,...`
- # URL otherwise lands as Gemini inlineData
- # with mimeType="text/html" and 400s the
- # whole request.
+ # Symmetry with the fetched remote image path, which
+ # already rejects non-image Content-Type. A
+ # `data:text/html;base64,...` URL otherwise lands as
+ # Gemini inlineData with mimeType="text/html" and
+ # 400s the whole request.
if not media_type.startswith("image/"):
logger.info(
"Gemini inlineData: refusing non-image data URL media_type=%s",
@@ -3240,11 +3198,11 @@ class ExternalProviderClient:
}
)
elif url:
- # fileData.fileUri only accepts Files-API URIs
- # and YouTube; everything else must be downloaded
- # and inlined. Parse fields explicitly so
- # attacker URLs like https://evil.com/youtube.com/x
- # aren't misclassified as YouTube.
+ # fileData.fileUri only accepts Files-API URIs and
+ # YouTube; everything else must be downloaded and
+ # inlined. Parse fields explicitly so attacker URLs
+ # like https://evil.com/youtube.com/x aren't
+ # misclassified as YouTube.
try:
_parsed_image_url = urlparse(url)
except (ValueError, UnicodeError):
@@ -3299,9 +3257,9 @@ class ExternalProviderClient:
_GEMINI_REMOTE_IMAGE_MAX_COUNT,
)
else:
- # Refuse pre-fetch when the per-request
- # byte budget is spent; pass the remainder
- # so over-budget URLs reject on Content-Length.
+ # 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
)
@@ -3310,8 +3268,8 @@ 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
+ # don't each burn the timeout.
_remote_image_count += 1
_fetched = await _safe_fetch_image_for_gemini(
url,
@@ -3340,10 +3298,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.
+ # 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):
@@ -3360,8 +3317,8 @@ class ExternalProviderClient:
break
# 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.
+ # (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):
for tc in tool_calls:
@@ -3385,9 +3342,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, with fallback 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] = {}
@@ -3405,8 +3362,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
+ # 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 = (
@@ -3427,11 +3384,10 @@ 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 does not 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
+ # doesn't 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)
@@ -3439,20 +3395,18 @@ 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`. This preserves Gemini 3's
- # strict per-part replay requirement when the
- # frontend has 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:
@@ -3460,9 +3414,9 @@ class ExternalProviderClient:
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.
+ # 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"
)
@@ -3493,10 +3447,10 @@ class ExternalProviderClient:
continue
# Forward the OpenAI tool_call id into Gemini's
- # functionCall.id so a follow-up turn that issues
- # multiple calls to the same function (different
- # args, same name) can be disambiguated on the
- # response side. Gemini accepts the field per
+ # 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.
function_call_part: dict[str, Any] = {
"name": fn_name,
@@ -3505,11 +3459,11 @@ class ExternalProviderClient:
if isinstance(tc_id, str) and tc_id:
function_call_part["id"] = tc_id
# Gemini 3 function-calling requires the prior
- # thoughtSignature to be 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).
+ # 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"
@@ -3518,23 +3472,23 @@ class ExternalProviderClient:
fc_part["thoughtSignature"] = sig
parts.append(fc_part)
if role == "tool":
- # If the matching assistant-side tool_call was either
- # dropped (synthetic server-tool with no native part)
- # or already replayed as Gemini-native parts
- # (code_execution/image_generation native_part), drop
- # the follow-up too. Emitting it as a functionResponse
- # would be orphaned or duplicate the native result.
+ # If the matching assistant-side tool_call was dropped
+ # (synthetic server-tool with no native part) or already
+ # replayed as Gemini-native parts
+ # (code_execution/image_generation native_part), drop the
+ # follow-up too. Emitting it as a functionResponse would be
+ # orphaned or duplicate the native result.
_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
+ # doesn't 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")
@@ -3546,9 +3500,9 @@ class ExternalProviderClient:
# (`[{"type":"text","text":"..."}]`). Forwarding the
# content-part objects verbatim into Gemini's
# `functionResponse.response.result` yields
- # `result:[{"type":"text","text":"..."}]` instead of
- # the actual tool output text; flatten text parts so
- # the result mirrors the string-content path.
+ # `result:[{"type":"text","text":"..."}]` instead of the
+ # actual tool output text; flatten text parts so the result
+ # mirrors the string-content path.
_flat_parts: list[str] = []
for _cpart in content:
if (
@@ -3577,22 +3531,21 @@ 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:
- # Gemini expects parallel functionResponses (multiple
- # OpenAI role="tool" messages in a row) to ride on a
- # single user content with multiple functionResponse
- # parts -- the docs show parallel responses grouped
- # together in the next turn. Merge consecutive
- # functionResponse-only user blocks so realistic
- # parallel tool loops round-trip correctly.
+ # Gemini expects parallel functionResponses (multiple OpenAI
+ # role="tool" messages in a row) to ride on a single user
+ # content with multiple functionResponse parts -- the docs show
+ # parallel responses grouped in the next turn. Merge consecutive
+ # functionResponse-only user blocks so realistic parallel tool
+ # loops round-trip correctly.
if (
role == "tool"
and contents
@@ -3610,9 +3563,9 @@ 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
@@ -3620,29 +3573,29 @@ 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 bothers to set 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. Gemini only accepts
- # `responseModalities: ["TEXT","IMAGE"]` on the image-capable
- # model family (id contains `-image` or `nano-banana`). Text-
- # only models such as `gemini-2.5-flash` 400 on the same body,
- # so only force image mode when the selected model actually
- # supports it -- a stale `enabled_tools=["image_generation"]`
- # on a text model is silently treated as a regular turn.
+ # `responseModalities: ["TEXT","IMAGE"]` on the image-capable model
+ # family (id contains `-image` or `nano-banana`). Text-only models such
+ # as `gemini-2.5-flash` 400 on the same body, so only force image mode
+ # when the selected model supports it -- a stale
+ # `enabled_tools=["image_generation"]` on a text model is silently
+ # treated as a regular turn.
# https://ai.google.dev/gemini-api/docs/image-generation
model_lc = model.lower()
is_image_picker_model = "-image" in model_lc or "nano-banana" in model_lc
- # tool_choice="none" / forced-function tool_choice must also
- # suppress the implicit image-generation hosted tool. Otherwise
- # an explicit OpenAI-style opt-out (or an explicit user-function
- # pin) still flips `responseModalities=["TEXT","IMAGE"]` on
- # image-tier models and bills for image output.
+ # tool_choice="none" / forced-function tool_choice must also suppress
+ # the implicit image-generation hosted tool. Otherwise an explicit
+ # OpenAI-style opt-out (or user-function pin) still flips
+ # `responseModalities=["TEXT","IMAGE"]` on image-tier models and bills
+ # for image output.
_tool_choice_disabled = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
)
@@ -3653,15 +3606,14 @@ class ExternalProviderClient:
and bool(tool_choice["function"].get("name"))
)
_hosted_builtins_allowed = not _tool_choice_disabled and not _tool_choice_forced_function
- # Image-tier model IDs reject text-only tools (code_execution,
- # user functions) and thinkingConfig regardless of whether the
- # Images pill is on -- those are model-level constraints
- # documented by Google. The pill only controls whether we ask
- # Gemini to actually emit image output via
- # `responseModalities: ["TEXT","IMAGE"]`. Decoupling the two
- # avoids the case where Images is off + Code/Search is on
- # forwards `tools: [{codeExecution: {}}]` plus
- # `thinkingConfig` to an image model and 400s.
+ # Image-tier model IDs reject text-only tools (code_execution, user
+ # functions) and thinkingConfig regardless of the Images pill -- those
+ # are model-level constraints documented by Google. The pill only
+ # controls whether we ask Gemini to emit image output via
+ # `responseModalities: ["TEXT","IMAGE"]`. Decoupling the two avoids the
+ # case where Images off + Code/Search on forwards
+ # `tools: [{codeExecution: {}}]` plus `thinkingConfig` to an image model
+ # and 400s.
image_tool_requested = bool(
_hosted_builtins_allowed and enabled_tools and "image_generation" in enabled_tools
)
@@ -3672,8 +3624,8 @@ 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 doesn't
+ # still bill for image output.
gen_config["responseModalities"] = ["TEXT"]
# Thinking control. Gemini 3 uses thinkingLevel (str), 2.5 uses
@@ -3731,11 +3683,11 @@ 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
- # existing frontend picker maps cleanly.
- # NOTE: gemini-2.5-flash-lite rejects positive budgets below
- # 512 with HTTP 400, so minimal=512 sits at that floor.
+ # 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
+ # with HTTP 400, so minimal=512 sits at that floor.
_EFFORT_TO_BUDGET: dict[str, int] = {
"minimal": 512,
"low": 2048,
@@ -3746,8 +3698,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]
@@ -3779,8 +3731,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
@@ -3798,12 +3750,11 @@ class ExternalProviderClient:
tools_array.append({"codeExecution": {}})
# OpenAI-style 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 documented
- # at https://ai.google.dev/api/caching#Schema; OpenAI's strict
- # tool definitions routinely include `additionalProperties`,
- # `$schema`, `$defs`, `strict`, `examples`, and similar keys
- # which 400 the request as INVALID_ARGUMENT. Strip them
- # recursively before forwarding.
+ # Gemini's Schema accepts only the OpenAPI 3.0 subset documented at
+ # https://ai.google.dev/api/caching#Schema; OpenAI's strict tool
+ # definitions routinely include `additionalProperties`, `$schema`,
+ # `$defs`, `strict`, `examples`, and similar keys which 400 the request
+ # as INVALID_ARGUMENT. Strip them recursively before forwarding.
_GEMINI_ALLOWED_SCHEMA_KEYS = frozenset(
{
"type",
@@ -3831,9 +3782,9 @@ 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 doesn't 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("#/"):
@@ -3854,27 +3805,26 @@ class ExternalProviderClient:
_seen_refs: Optional[frozenset[str]] = None,
) -> Any:
# Recursively filter to Gemini's OpenAPI 3.0 subset. At a
- # Schema-keyword dict layer we drop keys not in the
- # allowlist; under `properties` the keys are user-defined
- # field names and the values are themselves Schemas; under
- # `items` / `anyOf` the values are also Schemas.
+ # Schema-keyword dict layer we drop keys not in the allowlist; under
+ # `properties` the keys are user-defined field names and the values
+ # are Schemas; under `items` / `anyOf` the values are also Schemas.
# OpenAI strict tools commonly use JSON Schema's
- # `"type": ["string", "null"]` form for nullable fields;
- # Gemini's OpenAPI Schema uses `"type": "string"` plus
- # `"nullable": true`. Translate that here.
+ # `"type": ["string", "null"]` form for nullable fields; Gemini's
+ # OpenAPI Schema uses `"type": "string"` plus `"nullable": true`.
+ # Translate that here.
if root is None and isinstance(node, dict):
root = node
if _seen_refs is None:
_seen_refs = frozenset()
if isinstance(node, dict):
- # Pydantic / OpenAI strict tools commonly hoist nested
- # object schemas into `$defs` and reference them via
- # `{"$ref": "#/$defs/Address"}`. Gemini's OpenAPI subset
- # has no $ref and drops anything not in the allowlist,
- # so the referenced shape would vanish if we didn't
- # inline it here. Recurse into the resolved target with
- # local siblings overriding the reference (normal JSON
- # Schema composition), guarding against ref cycles.
+ # Pydantic / OpenAI strict tools commonly hoist nested object
+ # schemas into `$defs` and reference them via
+ # `{"$ref": "#/$defs/Address"}`. Gemini's OpenAPI subset has no
+ # $ref and drops anything not in the allowlist, so the
+ # referenced shape would vanish if we didn't inline it here.
+ # Recurse into the resolved target with local siblings
+ # overriding the reference (normal JSON Schema composition),
+ # guarding against ref cycles.
_ref = node.get("$ref")
if isinstance(_ref, str):
if _ref in _seen_refs:
@@ -3898,9 +3848,9 @@ 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):
@@ -3917,13 +3867,12 @@ class ExternalProviderClient:
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.
+ # `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.
_saw_null = any(
isinstance(_entry, dict) and _entry.get("type") == "null"
for _entry in _v
@@ -3982,8 +3931,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
@@ -4007,18 +3956,17 @@ class ExternalProviderClient:
_fcc["allowedFunctionNames"] = _allowed
body["toolConfig"] = {"functionCallingConfig": _fcc}
- # Prompt caching. The Gemini caching contract is "create a
- # CachedContent resource, then pass its name on
- # `cachedContent`". The cache itself 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").
+ # 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
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('/', '-')}"
@@ -4064,10 +4012,10 @@ 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 need to
- 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 + 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}}
@@ -4089,31 +4037,29 @@ 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 (matches 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
- # web_search_active drives the tool_start / tool_end envelope.
- # Track on whether `googleSearch` was actually forwarded above,
- # not the raw caller intent -- image-mode requests filter the
- # tool out, and emitting a phantom "search complete" card on a
- # turn where Gemini was never told to search confuses the UI.
+ # web_search_active drives the tool_start / tool_end envelope. Keyed on
+ # whether `googleSearch` was actually forwarded above, not raw caller
+ # intent -- image-mode requests filter the tool out, and a phantom
+ # "search complete" card on a turn where Gemini was never told to search
+ # confuses the UI.
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]] = []
- # Tracks the tool_call_id minted on the most recent
- # executableCode part so the matching codeExecutionResult can
- # close 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 rendered by 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 = ""
@@ -4147,9 +4093,9 @@ class ExternalProviderClient:
)
web_search_tool_started = True
- # NOTE: same manual __anext__ loop pattern as the other
- # streaming helpers (see stream_chat_completion for the
- # Python 3.13 + httpcore 1.0.x GeneratorExit ordering).
+ # 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).
lines_gen = response.aiter_lines().__aiter__()
final_finish_reason: Optional[str] = None
try:
@@ -4176,24 +4122,24 @@ 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: Gemini ships zero
- # candidates plus a `promptFeedback.blockReason`
- # (e.g. SAFETY). The downstream OAI client would
- # otherwise see an empty successful assistant
- # response. Surface as a content_filter error
- # event so the UI can render the block reason.
+ # Prompt-level safety block: Gemini ships zero candidates
+ # plus a `promptFeedback.blockReason` (e.g. SAFETY). The
+ # downstream OAI client would otherwise see an empty
+ # successful assistant response. Surface as a
+ # content_filter error event so the UI can render the
+ # block reason.
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 does not show a spinner stuck on
- # "searching..." after the error toast lands.
+ # Close out the synthetic web_search start so the UI
+ # doesn't show a spinner stuck on "searching..."
+ # after the error toast lands.
if (
web_search_active
and web_search_tool_started
@@ -4224,9 +4170,9 @@ class ExternalProviderClient:
if not isinstance(cand, dict):
continue
# Citations / grounding metadata.
- # `groundingMetadata.groundingChunks[].web`
- # carries `uri` + `title`. Collect for the
- # tool_end emission at stream close.
+ # `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 []
@@ -4259,9 +4205,9 @@ class ExternalProviderClient:
if not isinstance(part, dict):
continue
# Text delta. Stow part-level
- # `thoughtSignature` on the delta so
- # Gemini 3 turns that need an exact
- # signature echo round-trip cleanly.
+ # `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:
@@ -4279,8 +4225,8 @@ class ExternalProviderClient:
)
):
# Empty-content part carrying a
- # thoughtSignature: emit an empty delta
- # so the signature is preserved.
+ # thoughtSignature: emit an empty delta to
+ # preserve the signature.
yield _text_chunk(
"",
extra_content = _part_extra,
@@ -4297,10 +4243,9 @@ class ExternalProviderClient:
emitted_function_call_ids.add(fc_id)
# Each distinct functionCall in an
# assistant turn needs its own
- # tool_calls[*].index. Consumers
- # that reassemble tool_calls by
- # index collapse all calls onto
- # the same slot when this is
+ # tool_calls[*].index. Consumers that
+ # reassemble tool_calls by index collapse
+ # all calls onto one slot if this is
# hardcoded to 0, breaking
# parallel/multi-tool turns.
tc_index = len(emitted_function_call_ids) - 1
@@ -4314,14 +4259,13 @@ class ExternalProviderClient:
},
}
# Gemini 3 function-calling: the
- # part-level `thoughtSignature`
- # must be echoed back on the
- # next turn or the model rejects
- # the tool-result envelope. Stow
- # it on `extra_content.google`
- # so the frontend can persist it
- # and our outbound translator
- # (below) can replay it.
+ # part-level `thoughtSignature` must be
+ # echoed on the next turn or the model
+ # rejects the tool-result envelope. Stow
+ # it on `extra_content.google` so the
+ # frontend can persist it and our
+ # outbound translator (below) can replay
+ # it.
thought_sig = part.get("thoughtSignature") or part.get(
"thought_signature"
)
@@ -4344,13 +4288,12 @@ 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 can render Gemini sandbox
- # output through CodeExecutionToolUI.
+ # 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
exec_code = part.get("executableCode")
if isinstance(exec_code, dict):
@@ -4362,11 +4305,10 @@ class ExternalProviderClient:
)
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).
+ # 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")
@@ -4410,18 +4352,18 @@ 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; fall back
- # to exec_result.id then a fresh id.
+ # executableCode tool_start; else
+ # exec_result.id, then a fresh id.
pair_id = (
gemini_code_exec_pending_id
or exec_result.get("id")
@@ -4468,10 +4410,10 @@ 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 ""
@@ -4491,8 +4433,8 @@ class ExternalProviderClient:
+ _json.dumps([image_uri])
)
# Stow inlineData so a follow-up
- # turn can replay the plot with
- # its per-part thoughtSignature.
+ # turn replays the plot with its
+ # per-part thoughtSignature.
_plot_thought_sig = part.get(
"thoughtSignature"
) or part.get("thought_signature")
@@ -4585,11 +4527,11 @@ class ExternalProviderClient:
if mapped is not None:
final_finish_reason = mapped
- # End-of-stream emission order: web_search tool_end
- # (with citations) -> finish_reason chunk -> usage
- # chunk -> [DONE]. Matches the Anthropic / OpenAI
- # helpers' contract so the frontend handler does
- # not need provider-specific ordering knowledge.
+ # End-of-stream emission order: web_search tool_end (with
+ # citations) -> finish_reason chunk -> usage chunk -> [DONE].
+ # Matches the Anthropic / OpenAI helpers' contract so the
+ # frontend handler needs no provider-specific ordering
+ # knowledge.
if web_search_active and web_search_tool_started and not web_search_tool_ended:
blocks: list[str] = []
for cit in web_search_citations:
@@ -4610,9 +4552,8 @@ class ExternalProviderClient:
if final_finish_reason:
# OpenAI clients trigger tool execution when
- # finish_reason="tool_calls". Gemini emits
- # "STOP" even when the turn was a pure
- # functionCall request, so override after the
+ # finish_reason="tool_calls". Gemini emits "STOP" even
+ # for a pure functionCall request, so override after the
# fact to match the OAI contract.
if emitted_any_function_call and final_finish_reason == "stop":
final_finish_reason = "tool_calls"
@@ -4630,15 +4571,15 @@ 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.
+ # thoughtsTokenCount is billed output too — fold it in so
+ # cost calculators don't 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 does not undercount tool turns.
+ # Gemini bills tool-call prompt slices separately via
+ # `toolUsePromptTokenCount`. Fold into input so
+ # total_tokens doesn't undercount tool turns.
tool_use_prompt_tokens = last_usage.get("toolUsePromptTokenCount") or 0
translated_usage = {
"input_tokens": prompt_tokens + tool_use_prompt_tokens,
@@ -4657,9 +4598,9 @@ class ExternalProviderClient:
yield "data: [DONE]"
finally:
- # Close response first so lines_gen.aclose() becomes
- # a no-op (avoids the httpcore 1.0 GeneratorExit
- # path and the aclose-never-awaited RuntimeWarning).
+ # Close response first so lines_gen.aclose() becomes a no-op
+ # (avoids the httpcore 1.0 GeneratorExit path and the
+ # aclose-never-awaited RuntimeWarning).
await response.aclose()
await lines_gen.aclose()
@@ -4732,12 +4673,12 @@ class ExternalProviderClient:
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`` instead of
+ 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`` are not part of the Responses contract
- and are dropped here intentionally.
+ ``presence_penalty`` / ``top_k`` aren't part of the Responses contract
+ and are dropped here.
"""
import json as _json
@@ -4746,15 +4687,14 @@ class ExternalProviderClient:
enabled_tools and "image_generation" in enabled_tools and is_openai_cloud
)
- # Split system messages out into a single `instructions` string and
+ # 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 contains an orphan
- # `function_call_output` with no matching `function_call`, which
- # OpenAI Responses can reject or mis-associate.
+ # 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]] = []
previous_response_id: Optional[str] = None
@@ -4772,19 +4712,17 @@ class ExternalProviderClient:
instructions_parts.append(part["text"])
continue
- # OpenAI Responses uses item-shape history for function
- # calling: assistant turns that invoked user tools must
- # serialize each call as a `function_call` input item, and
- # each role="tool" follow-up as a `function_call_output`
- # item keyed by the matching `call_id`. Without this the
- # second turn after a function call sends Chat Completions
- # shape and Responses 400s the request.
+ # OpenAI Responses uses item-shape history for function calling:
+ # assistant turns that invoked user tools must serialize each call
+ # as a `function_call` input item, and each role="tool" follow-up as
+ # a `function_call_output` item keyed by the matching `call_id`.
+ # Without this the second turn after a function call sends Chat
+ # Completions shape and Responses 400s the request.
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 emitting 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):
@@ -4805,22 +4743,20 @@ class ExternalProviderClient:
)
continue
- # Assistant turns that returned tool_calls translate each
- # call as a `function_call` item (carrying name + JSON
- # arguments + call_id). Skip builtin server-side cards
- # (canonical builtin name + `args._server_tool` marker)
- # which never round-trip as user functions. We require both
- # checks so a user function literally named `_server_tool`
- # in its argument schema is not dropped.
+ # Assistant turns that returned tool_calls translate each call as a
+ # `function_call` item (name + JSON arguments + call_id). Skip
+ # builtin server-side cards (canonical builtin name +
+ # `args._server_tool` marker) which never round-trip as user
+ # functions. Both checks are required so a user function literally
+ # named `_server_tool` in its argument schema isn't dropped.
_tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else None
if role == "assistant" and isinstance(_tool_calls, list):
- # Preserve the prior `response.output` ordering: the
- # model's text precedes its function_call items, and
- # the matching role=tool follow-up arrives AFTER the
- # call. Without this guard, history replay puts
- # function_call -> assistant text -> function_call_output,
- # which can put the tool output after an unrelated
- # assistant message and confuse multi-turn function
+ # Preserve the prior `response.output` ordering: the model's text
+ # precedes its function_call items, and the matching role=tool
+ # follow-up arrives AFTER the call. Without this guard, history
+ # replay puts function_call -> assistant text ->
+ # function_call_output, which can place tool output after an
+ # unrelated assistant message and confuse multi-turn function
# calling.
if isinstance(content, str) and content:
input_items.append({"role": "assistant", "content": content})
@@ -4882,8 +4818,8 @@ class ExternalProviderClient:
"arguments": _args_raw,
}
)
- # 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 don't
+ # fall through to the generic content branches.
continue
if isinstance(content, str):
@@ -4941,18 +4877,17 @@ class ExternalProviderClient:
# or `{type:"input_file", file_url:"https://..."}`,
# with optional `filename`. See
# https://developers.openai.com/api/docs/guides/images-vision
- # Map Studio's normalised `input_document` shape
- # straight onto Responses' `input_file`.
+ # Map Studio's normalised `input_document` onto
+ # Responses' `input_file`.
file_url = part.get("file_url")
file_data = part.get("file_data")
filename = part.get("filename")
# Mirror the Anthropic-side guard: any "data:" URI
# without an actual base64 payload (`data:application/pdf;base64,`
- # or whitespace-only) would otherwise be forwarded
- # to OpenAI as `file_data=""`, which 400s the whole
- # turn. Treat such payloads as missing AND fall
- # back to file_url if one is also present, so a
- # recoverable remote URL doesn't get discarded in
+ # or whitespace-only) would otherwise be forwarded to
+ # OpenAI as `file_data=""`, which 400s the turn. Treat
+ # such payloads as missing AND fall back to file_url if
+ # present, so a recoverable remote URL isn't discarded in
# favour of a malformed inline payload.
file_data_valid = bool(
isinstance(file_data, str)
@@ -4978,9 +4913,9 @@ class ExternalProviderClient:
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; keep replay below as a fallback for
- # older stored turns that only have an image_generation_call id.
+ # 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)
@@ -5027,11 +4962,11 @@ class ExternalProviderClient:
# NOTE: gpt-5.x / o3 / gpt-4.5 are reasoning-class models. They reject
# temperature and top_p with `Unsupported parameter` 400s on
- # /v1/responses (and on /v1/chat/completions for the same families).
- # The PROVIDER_REGISTRY['openai'] model_id_allowlist already scopes
- # the picker to those families, so we never need to send sampling
- # knobs here. ``reasoning.effort`` defaults to "medium" server-side
- # if omitted — surface it in a future commit if a knob is wanted.
+ # /v1/responses (and /v1/chat/completions for the same families). The
+ # PROVIDER_REGISTRY['openai'] model_id_allowlist already scopes the
+ # picker to those families, so we never send sampling knobs here.
+ # ``reasoning.effort`` defaults to "medium" server-side if omitted —
+ # surface it in a future commit if a knob is wanted.
del temperature, top_p # explicit drop — params are accepted for
# API symmetry with the other stream methods but not forwarded.
@@ -5042,12 +4977,12 @@ 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 OpenAI returns no thinking text on
- # most reasoning models, the SSE handler has no <think>…</think>
- # to wrap, and the chat reasoning panel stays blank. Always pair
- # an explicit effort with summary except for the explicit "off"
- # case (effort: "none"), where summaries are pointless.
+ # `summary: "auto"` is what makes /v1/responses emit reasoning summary
+ # events — without it OpenAI returns no thinking text on most reasoning
+ # models, the SSE handler has no <think>…</think> to wrap, and the chat
+ # reasoning panel stays blank. Always pair an explicit effort with
+ # summary except for the "off" case (effort: "none"), where summaries
+ # are pointless.
summary_unsupported = bool(
_OPENAI_REASONING_SUMMARY_UNSUPPORTED.match(model.strip().lower())
)
@@ -5073,10 +5008,9 @@ class ExternalProviderClient:
if max_tokens is not None:
body["max_output_tokens"] = max_tokens
- # Opt into 24h prompt-cache retention (free, vs the default
- # ~5-10 min). Gated on the OpenAI cloud host because ollama /
- # llama.cpp / "custom" presets reach this code path too and
- # would 400 on the unknown field.
+ # Opt into 24h prompt-cache retention (free, vs the default ~5-10 min).
+ # Gated on the OpenAI cloud host because ollama / llama.cpp / "custom"
+ # presets reach this path too and would 400 on the unknown field.
if is_openai_cloud and enable_prompt_caching is not False:
body["prompt_cache_retention"] = "24h"
@@ -5108,7 +5042,7 @@ class ExternalProviderClient:
return tool
# Translate Chat-Completions function tools into the Responses
- # function-tool shape (flattened name/description/parameters).
+ # function-tool shape (flat name/description/parameters).
responses_user_function_tools: list[dict[str, Any]] = []
if tools:
for _tool in tools:
@@ -5170,9 +5104,9 @@ 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 isn't one yet. Stale ids 400 and are
+ # cleared via container_invalidated.
shell_env: dict[str, Any]
if openai_code_exec_container_id:
shell_env = {
@@ -5195,10 +5129,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 doesn't share state with the first attempt.
"""
attempt_body = dict(body)
if (enabled_tools or responses_user_function_tools) and not _responses_tool_choice_none:
@@ -5230,8 +5163,8 @@ class ExternalProviderClient:
def _is_openai_container_expired_error(error_text: str) -> bool:
"""Match the substring patterns OpenAI uses for expired / missing
- code-exec containers. There's no official error code in the public
- docs, so we substring-match a small set.
+ code-exec containers. No official error code exists in the public
+ docs, so substring-match a small set.
"""
lowered = error_text.lower()
if "container" not in lowered:
@@ -5292,19 +5225,19 @@ class ExternalProviderClient:
# 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
+ # 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_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: 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.
+ # 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
@@ -5315,10 +5248,10 @@ class ExternalProviderClient:
# 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.
+ # 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:
@@ -5336,7 +5269,7 @@ class ExternalProviderClient:
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 are stripped."""
+ ``force`` (end-of-stream), where lingering markers drop."""
out: list[str] = []
while pending_citation_segments:
seg = pending_citation_segments[0]
@@ -5369,8 +5302,8 @@ class ExternalProviderClient:
if not tail:
return ""
if _OPENAI_CITE_STOP not in tail:
- # Unterminated: drop the whole tail, otherwise 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).
@@ -5398,13 +5331,13 @@ class ExternalProviderClient:
return f"data: {_json.dumps(chunk)}"
def _format_shell_output(output: Any) -> str:
- """Render an OpenAI `shell_call_output.output` list
- as the preformatted text payload the frontend's
- CodeExecutionToolUI displays inside a <pre>. Each
- entry has stdout/stderr/outcome — concatenate them
- with a separator block per entry and append
- `return_code` / `(timeout)` annotations only when
- they convey information beyond "succeeded".
+ """Render an OpenAI `shell_call_output.output` list as the
+ preformatted text payload the frontend's
+ CodeExecutionToolUI displays inside a <pre>. Each entry
+ has stdout/stderr/outcome — concatenate them with a
+ separator block per entry and append `return_code` /
+ `(timeout)` annotations only when they convey info beyond
+ "succeeded".
"""
if not isinstance(output, list):
return ""
@@ -5434,13 +5367,12 @@ class ExternalProviderClient:
def _record_url_citation(payload: dict[str, Any]) -> None:
"""Append a url_citation onto the shared all_url_citations
- list. Dedup by URL — the same URL can be cited many
- times under different ``source_id`` aliases (one per
- span/locator), so collect every alias we see onto
- the matching entry's ``source_ids`` list. The
- delta-text rewriter resolves any of those aliases
- back to this entry's URL. The id may live under
- ``source_id``, ``id``, or ``locator`` across the
+ list. Dedup by URL — the same URL can be cited many times
+ under different ``source_id`` aliases (one per
+ span/locator), so collect every alias onto the matching
+ entry's ``source_ids`` list. The delta-text rewriter
+ resolves any alias back to this entry's URL. The id may
+ live under ``source_id``, ``id``, or ``locator`` across
Responses API revisions."""
if payload.get("type") != "url_citation":
return
@@ -5453,9 +5385,9 @@ 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
@@ -5548,7 +5480,7 @@ class ExternalProviderClient:
out.append(text)
return "".join(out)
if isinstance(payload, dict):
- # OpenAI responses may carry reasoning summaries in
+ # OpenAI responses carry reasoning summaries in
# different envelope fields across event variants.
for key in ("text", "delta", "content", "summary"):
if key in payload:
@@ -5599,7 +5531,7 @@ class ExternalProviderClient:
reasoning_open = False
yield _chunk_with_text(flushed)
# Force-drain any segment still awaiting an
- # annotation; lingering codepoints are stripped.
+ # annotation; lingering codepoints drop.
tail_flushed = _drain_pending_segments(
force = True,
)
@@ -5624,9 +5556,9 @@ 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 itself.
+ # 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)
@@ -5641,9 +5573,10 @@ 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,
)
@@ -5679,8 +5612,8 @@ class ExternalProviderClient:
item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")
web_search_calls.setdefault(item_id, {"query": ""})
# Register shell_call eagerly so out-of-order
- # output links back. Probe env.container_id
- # to emit container_ready before response.completed.
+ # 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(
@@ -5735,12 +5668,12 @@ class ExternalProviderClient:
# done is the canonical place to read the
# query, so emit both tool_start and tool_end
# here. Frontend then renders a card per call
- # with the proper "Searching: <query>" label.
+ # with the "Searching: <query>" label.
# Citations are aggregated separately and the
# *last* call's result is overwritten at
# response.completed with the citation list
- # (so the source-pill extraction at message
- # tail surfaces them once).
+ # (so source-pill extraction at message tail
+ # surfaces them once).
item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")
action = item.get("action")
query = (
@@ -5767,13 +5700,12 @@ class ExternalProviderClient:
)
elif item.get("type") == "shell_call":
# OpenAI ships the commands array on the
- # action field. Join them onto one
- # command string for the tool card —
- # the renderer is shared with Anthropic
- # bash, which only carries a single
- # `command`. Multiple commands in one
- # shell_call get joined with newlines so
- # they still render as one card.
+ # action field. Join them onto one command
+ # string for the tool card — the renderer is
+ # shared with Anthropic bash, which carries a
+ # single `command`. Multiple commands in one
+ # shell_call are joined with newlines so they
+ # still render as one card.
item_id = item.get("id", "") or (f"sc_{len(shell_calls)}")
action = item.get("action") or {}
commands = (
@@ -5821,10 +5753,9 @@ class ExternalProviderClient:
)
elif item.get("type") == "shell_call_output":
# `call_id` links back to the shell_call's
- # `id`, which is what we used as the
- # tool_call_id on tool_start. Match on
- # call_id when present so the matching
- # card transitions to complete.
+ # `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
@@ -5845,7 +5776,7 @@ 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 stay unique.
+ # 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 = (
@@ -5943,14 +5874,12 @@ class ExternalProviderClient:
completed_usage = (event.get("response") or {}).get("usage")
if isinstance(completed_usage, dict):
last_usage = completed_usage
- # Flush any unterminated citation tail
- # held over from the last delta. By
- # the time we get here every annotation
- # has been recorded so a late-arriving
- # source_id may resolve cleanly; if it
- # still doesn't, the helper strips the
- # private-use bytes so no garbled
- # glyph reaches the user.
+ # Flush any unterminated citation tail held over
+ # from the last delta. By now every annotation is
+ # recorded so a late-arriving source_id may
+ # resolve; if not, the helper strips the
+ # private-use bytes so no garbled glyph reaches
+ # the user.
if pending_marker_tail:
flushed = _flush_pending_marker_tail(pending_marker_tail)
pending_marker_tail = ""
@@ -5960,7 +5889,7 @@ class ExternalProviderClient:
reasoning_open = False
yield _chunk_with_text(flushed)
# Force-drain any segment still awaiting an
- # annotation; lingering codepoints are stripped.
+ # annotation; lingering codepoints drop.
tail_flushed = _drain_pending_segments(
force = True,
)
@@ -5974,11 +5903,10 @@ class ExternalProviderClient:
reasoning_open = False
# Probe response.container_id (top-level) and
# response.container.id for the shell-tool
- # container id. OpenAI's docs don't pin the
- # exact field, so we scan both. Emit
- # `container_ready` only when the value
- # differs from the inbound one — no churn on
- # reuse.
+ # container id. OpenAI's docs don't pin the exact
+ # field, so scan both. Emit `container_ready` only
+ # when the value differs from the inbound one — no
+ # churn on reuse.
response_obj = event.get("response") or {}
if isinstance(response_obj, dict):
probe_id = response_obj.get("container_id")
@@ -6006,8 +5934,8 @@ class ExternalProviderClient:
container_id_emitted = True
# Overwrite the last web_search call with the
# citation list; the source-pill extractor
- # flatMaps across cards. Earlier cards keep
- # their per-call "Searching:" text.
+ # flatMaps across cards. Earlier cards keep their
+ # per-call "Searching:" text.
if web_search_calls and all_url_citations:
last_id = list(web_search_calls.keys())[-1]
blocks: list[str] = []
@@ -6067,9 +5995,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 = ""
@@ -6079,7 +6006,7 @@ class ExternalProviderClient:
reasoning_open = False
yield _chunk_with_text(flushed)
# Force-drain any segment still awaiting an
- # annotation; lingering codepoints are stripped.
+ # annotation; lingering codepoints drop.
tail_flushed = _drain_pending_segments(
force = True,
)
@@ -6092,11 +6019,11 @@ class ExternalProviderClient:
yield _chunk_with_text("</think>")
reasoning_open = False
# Same backfill as response.completed — apply
- # whatever citations we managed to gather
- # before truncation onto the last call. All
- # earlier tool cards already have their proper
- # query + empty placeholder result from the
- # output_item.done emissions above.
+ # whatever citations we gathered before
+ # truncation onto the last call. Earlier tool
+ # cards already have their query + empty
+ # placeholder result from the output_item.done
+ # emissions above.
if web_search_calls and all_url_citations:
last_id = list(web_search_calls.keys())[-1]
blocks = []
@@ -6142,8 +6069,7 @@ class ExternalProviderClient:
yield f"data: {_json.dumps(chunk)}"
# Emit include_usage-style chunk after the
# length-truncated finish_reason too, so
- # incomplete responses still report
- # cached_tokens.
+ # incomplete responses still report cached_tokens.
usage_line = _build_usage_chunk(
completion_id,
"openai",
@@ -6153,8 +6079,8 @@ class ExternalProviderClient:
yield usage_line
elif event_type in ("response.failed", "error"):
- # Surface the failure to the client; let the
- # outer route emit [DONE] as part of its cleanup.
+ # Surface the failure to the client; the outer
+ # route emits [DONE] as part of its cleanup.
error_payload = event.get("response", {}).get("error", {}) or {
"message": event.get("message", "Unknown error"),
"code": event.get("code"),
@@ -6170,10 +6096,10 @@ class ExternalProviderClient:
await lines_gen.aclose()
raise
finally:
- # Summarise what the model actually did this turn so
- # support reports of "I clicked Search and got nothing"
- # can be triaged at a glance: was the tool requested,
- # did OpenAI invoke it, and how many sources came back?
+ # Summarise what the model did this turn so support
+ # reports of "I clicked Search and got nothing" can be
+ # triaged at a glance: was the tool requested, did OpenAI
+ # invoke it, and how many sources came back?
web_search_requested = bool(enabled_tools and "web_search" in enabled_tools)
web_search_invocations = len(web_search_calls)
total_citations = len(all_url_citations)
@@ -6183,10 +6109,9 @@ class ExternalProviderClient:
# cached_input_tokens > 0 on turn N proves
# prompt_cache_retention="24h" is letting the previous
# turn's prefix hit the cache instead of being
- # recomputed. On /v1/responses the field is nested as
+ # recomputed. On /v1/responses the field is nested at
# usage.input_tokens_details.cached_tokens (not
- # prompt_tokens_details, which is the /v1/chat/completions
- # shape).
+ # prompt_tokens_details, the /v1/chat/completions shape).
cached_input_tokens = None
if isinstance(last_usage, dict):
details = last_usage.get("input_tokens_details")
@@ -6259,9 +6184,9 @@ class ExternalProviderClient:
) -> dict[str, Any]:
"""Non-streaming chat completion. Returns the full response dict.
- Note: only valid for OpenAI-compatible providers. Anthropic requires its
- own Messages API; use stream_chat_completion (with stream=False) instead
- if a non-streaming Anthropic path is needed in the future.
+ 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.
"""
body: dict[str, Any] = {
"model": model,
@@ -6290,8 +6215,8 @@ class ExternalProviderClient:
"""
Call GET /models on the provider to discover available models.
- Returns a list of model dicts with at least 'id' and optionally
- 'created', 'owned_by', etc.
+ Returns model dicts with at least 'id' and optionally 'created',
+ 'owned_by', etc.
All supported providers expose a /models endpoint:
- OpenAI-compatible: standard {"data": [...]} response
@@ -6316,8 +6241,8 @@ class ExternalProviderClient:
models = await self._list_ollama_native_models()
# Gemini's native /v1beta/models returns
# {"models": [{"name": "models/gemini-2.5-flash", ...}]}
- # -- repackage into the OpenAI-compatible shape the rest
- # of Studio expects so dynamic model discovery works.
+ # -- repackage into the OpenAI-compatible shape the rest of Studio
+ # expects so dynamic model discovery works.
if not models and self.provider_type == "gemini":
models = self._parse_gemini_models(data)
return models
@@ -6335,10 +6260,9 @@ class ExternalProviderClient:
"displayName": "Gemini 2.5 Flash",
"supportedGenerationMethods": [...]}]}
- We only keep entries that advertise
- ``generateContent`` / ``streamGenerateContent`` so the picker
- does not surface embedding-only models the chat path can't
- drive.
+ We only keep entries that advertise ``generateContent`` /
+ ``streamGenerateContent`` so the picker doesn't surface embedding-only
+ models the chat path can't drive.
"""
if not isinstance(payload, dict):
return []
@@ -6358,8 +6282,8 @@ 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
@@ -6401,8 +6325,8 @@ class ExternalProviderClient:
"""
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.
+ 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:
@@ -6427,11 +6351,11 @@ class ExternalProviderClient:
def _container_headers(self) -> dict[str, str]:
"""Auth headers plus the OpenAI-Beta opt-in for /v1/containers.
- OpenAI's containers API requires ``OpenAI-Beta: containers=v1``.
- Without it, DELETE silently no-ops: the API returns 200 with a
- ``{"deleted": true}`` body but does not actually remove the
- container (verified 2026-05-15). The header is required for
- list / create / delete to behave consistently.
+ OpenAI's containers API requires ``OpenAI-Beta: containers=v1``. Without
+ it, DELETE silently no-ops: the API returns 200 with a
+ ``{"deleted": true}`` body but doesn't actually remove the container
+ (verified 2026-05-15). The header is required for list / create / delete
+ to behave consistently.
"""
headers = self._auth_headers()
headers["OpenAI-Beta"] = "containers=v1"
@@ -6441,13 +6365,13 @@ class ExternalProviderClient:
"""
GET /v1/containers on the user's OpenAI account.
- Returns the raw container records (id, name, created_at,
- last_active_at, expires_after, status). The route layer
- reshapes these into the UI summary shape.
+ Returns the raw container records (id, name, created_at, last_active_at,
+ expires_after, status). The route layer reshapes these into the UI
+ summary shape.
- Only valid against api.openai.com — non-cloud OpenAI-compat
- servers don't implement /v1/containers and would 404 here.
- Caller is responsible for the is_openai_cloud guard.
+ Only valid against api.openai.com — non-cloud OpenAI-compat servers
+ don't implement /v1/containers and would 404 here. Caller is responsible
+ for the is_openai_cloud guard.
"""
response = await _http_client.get(
f"{self.base_url}/containers",
@@ -6468,8 +6392,8 @@ class ExternalProviderClient:
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 that
- touches the container resets the timer.
+ ``ttl_minutes`` is the idle timeout — every API call touching the
+ container resets the timer.
"""
body = {
"name": name,
@@ -6491,16 +6415,14 @@ class ExternalProviderClient:
"""DELETE /v1/containers/{id}. 404s are surfaced as HTTPError.
Uses a fresh httpx client (not the shared ``_http_client``) so
- connection-pool state from earlier chat requests cannot
- interfere — observed in the wild that DELETEs over the shared
- pool returned ``deleted: true`` while the container persisted
- in subsequent /containers list calls, even though the same
- DELETE issued from a fresh client genuinely removed it.
-
- Verifies the response body reports ``deleted: true``. OpenAI
- returns a 2xx ``deleted: true`` body even when the request is
- silently rejected (e.g. missing OpenAI-Beta header), so a
- status-only check is not sufficient.
+ connection-pool state from earlier chat requests can't interfere —
+ observed that DELETEs over the shared pool returned ``deleted: true``
+ while the container persisted in later /containers list calls, even
+ though the same DELETE from a fresh client genuinely removed it.
+
+ Verifies the response body reports ``deleted: true``. OpenAI returns a
+ 2xx ``deleted: true`` body even when the request is silently rejected
+ (e.g. missing OpenAI-Beta header), so a status-only check isn't enough.
"""
url = f"{self.base_url}/containers/{container_id}"
headers = self._container_headers()
@@ -6588,41 +6510,38 @@ def _error_sse_line(status_code: int, message: str, provider_type: str) -> str:
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 that carries the
- 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.
- Until now Studio captured ``cache_creation_input_tokens`` /
+ Studio captured ``cache_creation_input_tokens`` /
``cache_read_input_tokens`` (Anthropic) and
- ``input_tokens_details.cached_tokens`` (OpenAI Responses) on
- ``last_usage`` and only wrote them to the structlog stream.
- Browser / SDK clients had no way to see how many tokens hit the cache
- -- so the "you saved $X" UX in the chat panel was impossible without
- scraping the server log.
-
- This helper emits the standard OpenAI chunk shape -- ``choices: []``
- with a populated ``usage`` block -- so any client that already
- consumes ``stream_options={"include_usage": true}`` keeps working,
- and the Anthropic-native counts are surfaced as extra keys on the
- same ``usage`` dict:
+ ``input_tokens_details.cached_tokens`` (OpenAI Responses) on ``last_usage``
+ but only wrote them to the structlog stream. Browser / SDK clients couldn't
+ see how many tokens hit the cache, so the "you saved $X" UX was impossible
+ without scraping the server log.
+
+ This emits the standard OpenAI chunk shape -- ``choices: []`` with a
+ populated ``usage`` block -- so any client consuming
+ ``stream_options={"include_usage": true}`` keeps working, with the
+ Anthropic-native counts surfaced as extra keys on the same ``usage`` dict:
usage.prompt_tokens_details.cached_tokens
normalised cache-read count, present for both providers.
usage.cache_creation_input_tokens
Anthropic-only; tokens billed at the cache-write premium.
usage.cache_read_input_tokens
- Anthropic-only; same value as cached_tokens, kept for
- callers that already key off the native Anthropic name.
-
- Anthropic's ``input_tokens`` excludes the cache buckets -- the
- real prompt size is ``input_tokens + cache_creation_input_tokens
- + cache_read_input_tokens``. Emitting ``input_tokens`` alone as
- ``prompt_tokens`` undercounts cache-heavy turns and breaks
- downstream context / cost displays, so we add all three input
- buckets together. OpenAI Responses already folds cached tokens
- into ``input_tokens`` so no extra arithmetic is needed there.
-
- Returns ``None`` when there are no usage numbers to report (e.g. an
- upstream error before ``message_start`` / ``response.completed``).
+ Anthropic-only; same value as cached_tokens, kept for callers
+ that key off the native Anthropic name.
+
+ Anthropic's ``input_tokens`` excludes the cache buckets -- real prompt size
+ is ``input_tokens + cache_creation_input_tokens + cache_read_input_tokens``.
+ Emitting ``input_tokens`` alone as ``prompt_tokens`` undercounts cache-heavy
+ turns and breaks downstream context / cost displays, so we sum all three
+ input buckets. OpenAI Responses already folds cached tokens into
+ ``input_tokens`` so no extra arithmetic is needed there.
+
+ Returns ``None`` when there are no usage numbers to report (e.g. an upstream
+ error before ``message_start`` / ``response.completed``).
"""
if not isinstance(last_usage, dict):
return None
@@ -6644,14 +6563,14 @@ 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 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 can apply
- # 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
@@ -6669,9 +6588,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
+ # 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")
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 33647a6cd17..0cef6c41ff2 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Core inference backend - streamlined
-"""
+"""Core inference backend."""
from unsloth import FastLanguageModel, FastVisionModel
from unsloth.chat_templates import get_chat_template
@@ -36,29 +34,25 @@ logger = get_logger(__name__)
class HarmonyTextStreamer:
- """Streaming text decoder for gpt-oss harmony channel protocol.
+ """Streaming text decoder for the gpt-oss harmony channel protocol.
- gpt-oss models emit multi-channel output using special tokens like
- ``<|channel|>analysis<|message|>...`` and ``<|channel|>final<|message|>...``.
- A plain ``TextIteratorStreamer(skip_special_tokens=True)`` strips the special
- tokens but leaves the channel names concatenated with content, producing
- garbled output such as ``analysisWe need to respond...assistantfinalHello!``.
+ gpt-oss emits multi-channel output via special tokens like
+ ``<|channel|>analysis<|message|>...`` / ``<|channel|>final<|message|>...``.
+ A plain ``TextIteratorStreamer(skip_special_tokens=True)`` drops the tokens
+ but leaves channel names glued to content, producing garbled output like
+ ``analysisWe need to respond...assistantfinalHello!``.
- This streamer decodes with ``skip_special_tokens=False`` so the full
- harmony markup is visible, then uses **stateful incremental** parsing
- to emit properly-formatted text:
+ This streamer decodes with ``skip_special_tokens=False`` so the harmony
+ markup is visible, then uses stateful incremental parsing:
- - ``<think>`` emitted once when the ``analysis`` channel is first seen
- - Analysis content streamed incrementally
- - ``</think>`` emitted once when the ``final`` channel is first seen
- - Final content streamed incrementally
+ - ``<think>`` once when ``analysis`` channel is first seen
+ - analysis content streamed incrementally
+ - ``</think>`` once when ``final`` channel is first seen
+ - final content streamed incrementally
This avoids the delta-on-transformed bug where wrapping tags shift
- position as content grows.
-
- Implements the same ``put`` / ``end`` / iterator interface as
- ``TextIteratorStreamer`` so ``generate_stream`` can use it as a drop-in
- replacement.
+ position as content grows. Implements the same ``put`` / ``end`` / iterator
+ interface as ``TextIteratorStreamer`` for drop-in use in ``generate_stream``.
"""
import re as _re
@@ -87,7 +81,7 @@ class HarmonyTextStreamer:
self._is_first_put: bool = True
self._stop: bool = False
- # Stateful channel tracking — avoids delta-on-transformed bugs
+ # 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
@@ -102,7 +96,7 @@ class HarmonyTextStreamer:
import torch
if isinstance(value, torch.Tensor):
- # value shape: (batch, seq) — take first batch element
+ # 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)
@@ -110,7 +104,7 @@ class HarmonyTextStreamer:
ids = [value]
if self._is_first_put and self.skip_prompt:
- # First call contains the full prompt; remember its length
+ # First call is the full prompt; remember its length
self._prompt_len = len(ids)
self._token_ids = list(ids)
self._is_first_put = False
@@ -125,7 +119,7 @@ class HarmonyTextStreamer:
def end(self):
"""Signal generation is complete."""
- # Final decode to capture any remaining content
+ # 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)
@@ -164,19 +158,19 @@ class HarmonyTextStreamer:
# ------------------------------------------------------------------
def _process_incremental(self, raw: str) -> None:
- """Parse harmony channels and emit deltas per-channel.
+ """Parse harmony channels and emit per-channel deltas.
- Instead of transforming the entire raw text and computing a string
- delta (which breaks when wrapping ``<think>`` tags shift position),
- this tracks per-channel content lengths and emits:
+ Tracks per-channel content lengths (instead of diffing transformed
+ whole-text, which breaks when wrapping ``<think>`` tags shift position)
+ and emits:
- ``<think>`` once when analysis channel first appears
- analysis content deltas (computed on channel content directly)
- ``</think>`` once when final channel first appears
- final content deltas
"""
- # If raw contains <|channel|> but no complete channel+message pair yet,
- # buffer silently — don't emit partial channel names as text.
+ # raw has <|channel|> but no complete channel+message pair yet:
+ # buffer silently, don't emit partial channel names as text.
has_channel_token = "<|channel|>" in raw
matches = list(self._HARMONY_RE.finditer(raw))
@@ -185,8 +179,7 @@ class HarmonyTextStreamer:
return
if not has_channel_token and not matches:
- # No harmony protocol at all — should not happen for gpt-oss
- # but handle gracefully by not emitting anything
+ # No harmony protocol (shouldn't happen for gpt-oss) — emit nothing
return
for m in matches:
@@ -228,11 +221,11 @@ class InferenceBackend:
self.device = get_device().value
self._audio_codec_manager = AudioCodecManager()
- # Thread safety — _generation_lock serializes model.generate() calls.
- # Must be a regular Lock (NOT RLock) because in async FastAPI, multiple
- # requests share the same event-loop thread, so RLock reentrancy lets
- # concurrent compare-mode requests race on the GPU. The lock is
- # acquired by the *background generation thread*, not the event-loop.
+ # _generation_lock serializes model.generate() calls. Must be a plain
+ # Lock (NOT RLock): in async FastAPI requests share one event-loop
+ # thread, so RLock reentrancy would let concurrent compare-mode
+ # requests race on the GPU. Acquired by the *background generation
+ # thread*, not the event-loop.
import threading
self._generation_lock = threading.Lock()
@@ -242,7 +235,7 @@ class InferenceBackend:
@staticmethod
def _normalize_top_k(top_k: int) -> int:
- # API supports -1 as "disable top-k"; transformers expects 0 to disable.
+ # API uses -1 to disable top-k; transformers uses 0.
return 0 if top_k < 0 else top_k
def load_model(
@@ -255,9 +248,7 @@ class InferenceBackend:
trust_remote_code: bool = False,
gpu_ids: Optional[list[int]] = None,
) -> bool:
- """
- Load any model: base, LoRA adapter, text, or vision.
- """
+ """Load any model: base, LoRA adapter, text, or vision."""
# GGUF uses max_seq_length=0 as "model default"; Unsloth crashes on it.
if max_seq_length <= 0:
max_seq_length = 2048
@@ -265,13 +256,13 @@ class InferenceBackend:
try:
model_name = config.identifier
- # Check if already loaded
+ # Already loaded?
if model_name in self.models and self.models[model_name].get("model"):
logger.info(f"Model {model_name} already loaded")
self.active_model_name = model_name
return True
- # Check if currently loading
+ # Currently loading?
if model_name in self.loading_models:
logger.info(f"Model {model_name} is already being loaded")
return False
@@ -322,9 +313,9 @@ class InferenceBackend:
from unsloth import FastModel
if config.is_lora and config.base_model:
- # LoRA adapter: load from local adapter path.
- # base_model is e.g. /home/.../Spark-TTS-0.5B/LLM
- # The BiCodec weights are in the parent dir (Spark-TTS-0.5B/).
+ # LoRA adapter from local path. base_model is e.g.
+ # /home/.../Spark-TTS-0.5B/LLM; BiCodec weights live in
+ # the parent dir (Spark-TTS-0.5B/).
base_path = config.base_model
if os.path.isdir(base_path):
abs_repo_path = os.path.abspath(os.path.dirname(base_path))
@@ -348,7 +339,7 @@ class InferenceBackend:
trust_remote_code = trust_remote_code,
)
else:
- # Base model: download full HF repo, then load from /LLM subfolder
+ # Base model: download full HF repo, load from /LLM subfolder
from huggingface_hub import snapshot_download
hf_repo = config.path
@@ -406,7 +397,7 @@ class InferenceBackend:
FastModel.for_inference(model)
model.eval()
- # Create ASR pipeline (per notebook)
+ # ASR pipeline (per notebook)
from transformers import pipeline as hf_pipeline
whisper_pipe = hf_pipeline(
@@ -435,8 +426,8 @@ class InferenceBackend:
self.models[model_name]["model"] = model
self.models[model_name]["tokenizer"] = tokenizer
- # Load the external codec for TTS audio types
- # (Whisper is ASR, audio_vlm is audio input — neither needs a codec)
+ # Load external codec for TTS audio types
+ # (Whisper is ASR, audio_vlm is audio input — neither needs one)
if audio_type not in ("whisper", "audio_vlm"):
model_repo_path = self.models[model_name].get("model_repo_path")
self._audio_codec_manager.load_codec(
@@ -457,7 +448,7 @@ class InferenceBackend:
logger.info(f"Loading {model_type} model{adapter_info}: {model_name}")
log_gpu_memory(f"Before loading {model_name}")
- # Load model - same approach for base models and LoRA adapters
+ # Same load path for base models and LoRA adapters
if config.is_vision:
# Vision model (or vision LoRA adapter)
model, processor = FastVisionModel.from_pretrained(
@@ -470,19 +461,19 @@ class InferenceBackend:
trust_remote_code = trust_remote_code,
)
- # Apply inference optimization
FastVisionModel.for_inference(model)
- # FastVisionModel may return a raw tokenizer (e.g. GemmaTokenizerFast)
- # instead of a proper Processor for some models (e.g. Gemma-3).
- # In that case, load the real processor from the base model.
+ # FastVisionModel may return a raw tokenizer (e.g.
+ # GemmaTokenizerFast) instead of a proper Processor for some
+ # models (e.g. Gemma-3). If so, load the real processor from
+ # the base model.
from transformers import ProcessorMixin
if not (
isinstance(processor, ProcessorMixin) or hasattr(processor, "image_processor")
):
- # For LoRA adapters, use the base model. For local merged exports,
- # read export_metadata.json to find the original base model.
+ # LoRA adapters: use the base model. Local merged exports:
+ # read export_metadata.json for the original base model.
processor_source = config.base_model if config.is_lora else config.identifier
if not config.is_lora and config.is_local:
_meta_path = Path(config.path) / "export_metadata.json"
@@ -522,7 +513,6 @@ class InferenceBackend:
trust_remote_code = trust_remote_code,
)
- # Apply inference optimization
FastLanguageModel.for_inference(model)
self.models[model_name]["model"] = model
@@ -530,7 +520,6 @@ class InferenceBackend:
raise_if_offloaded(self.models[model_name]["model"], device_map, "Inference")
- # Load chat template info
self._load_chat_template_info(model_name)
self.active_model_name = model_name
@@ -552,29 +541,25 @@ class InferenceBackend:
raise Exception(error_msg)
def unload_model(self, model_name: str) -> bool:
- """
- Completely removes a model from the registry and clears GPU memory.
- """
+ """Remove a model from the registry and clear GPU memory."""
if model_name in self.models:
try:
- # If this was an audio model, clean up codecs
+ # 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.")
- # Delete the model entry from our registry
del self.models[model_name]
- # Clear the active model if it was the one being unloaded
+ # Clear the active model if it was the one unloaded
if self.active_model_name == model_name:
self.active_model_name = None
- # Clear GPU memory cache
clear_gpu_cache()
- # Remove stale compiled cache so the next model gets a fresh one.
- # On spawn-based platforms, preserve trainer files so that any
- # concurrent training dataset.map() workers can still import them.
+ # Drop stale compiled cache so the next model gets a fresh one.
+ # On spawn-based platforms, preserve trainer files so concurrent
+ # training dataset.map() workers can still import them.
import sys as _sys
from utils.cache_cleanup import clear_unsloth_compiled_cache
@@ -593,26 +578,23 @@ class InferenceBackend:
return True
def revert_to_base_model(self, base_model_name: str) -> bool:
- """
- Reverts the model to its pristine base state by unloading AND
- deleting all adapter configurations, as instructed.
- """
+ """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:
- # Step 1: Unload the adapter weights if model is a PeftModel.
+ # 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()
self.models[base_model_name]["model"] = unwrapped_base_model
model = unwrapped_base_model
- # Step 2: Clear any lingering peft_config from the unwrapped model.
- # After model.unload(), the base model may still carry a peft_config
- # attribute. Removing it ensures PeftModel.from_pretrained() gets
+ # Clear any lingering peft_config. model.unload() can leave a
+ # peft_config attribute; removing it gives PeftModel.from_pretrained()
# a clean base model without "multiple adapters" warnings.
if hasattr(model, "peft_config"):
del model.peft_config
@@ -636,10 +618,8 @@ class InferenceBackend:
hf_token: Optional[str] = None,
gpu_ids: Optional[list[int]] = None,
) -> Tuple[bool, Optional[str], Optional[str]]:
- """
- Final Corrected Version:
- Ensures the base model and the specified adapter are loaded.
- This function is idempotent and handles all states correctly.
+ """Ensure the base model and the given adapter are loaded.
+ Idempotent and handles all states correctly.
"""
try:
from utils.models import ModelConfig
@@ -650,7 +630,7 @@ class InferenceBackend:
base_model_name = lora_config.base_model
- # 1. Load the base model if it's not already in memory
+ # 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)
@@ -666,11 +646,11 @@ class InferenceBackend:
self.active_model_name = base_model_name
- # 2. Determine the required adapter name from the user's selection
+ # 2. Derive adapter name from the user's selection
adapter_name = lora_path.split("/")[-1].replace(".", "_")
- # 3. Call our robust load_adapter function to ensure this specific adapter is loaded.
- # It will only load from disk if the model doesn't already have it.
+ # 3. Ensure this adapter is loaded (load_adapter only reads from
+ # disk if the model doesn't already have it).
adapter_success = self.load_adapter(
base_model_name = base_model_name,
adapter_path = lora_path,
@@ -679,7 +659,7 @@ class InferenceBackend:
if not adapter_success:
return False, base_model_name, None
- # 4. Return the correct, verified adapter name for the UI logic to use.
+ # 4. Return the verified adapter name for the UI.
return True, base_model_name, adapter_name
except Exception as e:
@@ -690,12 +670,10 @@ class InferenceBackend:
return False, None, None
def load_adapter(self, base_model_name: str, adapter_path: str, adapter_name: str) -> bool:
- """
- Loads an adapter onto the model ONLY if it's not already attached.
- """
+ """Load an adapter onto the model only if not already attached."""
model = self.models[base_model_name].get("model")
- # Check if this adapter name is already part of the model's config. This is the most reliable check.
+ # Most reliable check: adapter name already in the model's config.
if hasattr(model, "peft_config") and adapter_name in model.peft_config:
logger.info(
f"Adapter '{adapter_name}' is already attached to the model. Skipping load."
@@ -708,7 +686,7 @@ class InferenceBackend:
)
model.load_adapter(adapter_path, adapter_name = adapter_name)
- # Update our internal registry ONLY after a successful load.
+ # 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
@@ -723,9 +701,8 @@ class InferenceBackend:
return False
def set_active_adapter(self, base_model_name: str, adapter_name: str) -> bool:
- """
- Sets the active adapter for generation. This replaces the flawed 'enable_adapter'.
- """
+ """Set the active adapter for generation (replaces the flawed
+ 'enable_adapter')."""
model = self.models[base_model_name].get("model")
try:
logger.info(f"Setting active adapter to: '{adapter_name}'")
@@ -733,18 +710,17 @@ class InferenceBackend:
self.models[base_model_name]["active_adapter"] = adapter_name
return True
except Exception as e:
- # This will catch the "adapter not found" error if something goes wrong.
+ # 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 be called under _generation_lock.
+ """Apply adapter state before generation. Must hold _generation_lock.
- Uses PEFT's disable_adapter_layers() / enable_adapter_layers() which toggle
- a boolean flag on each LoRA layer. Unsloth's fast_linear_forward checks this
- flag (proj.disable_adapters) and skips LoRA computation when True.
- This is non-destructive — no model unloading/reloading needed.
+ Uses PEFT's disable_adapter_layers() / enable_adapter_layers(), which
+ toggle a flag (proj.disable_adapters) on each LoRA layer; Unsloth's
+ fast_linear_forward checks it and skips LoRA when True. Non-destructive,
+ no unload/reload.
Args:
use_adapter: None = no change, False = disable (base model),
@@ -781,7 +757,7 @@ class InferenceBackend:
logger.warning("use_adapter=true but model is not a PeftModel")
elif isinstance(use_adapter, str):
- # Enable adapters and set the specific one active
+ # 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()
@@ -795,13 +771,12 @@ class InferenceBackend:
cancel_event = None,
**gen_kwargs,
) -> Generator[str, None, None]:
- """
- Thread-safe generation with optional adapter toggling.
+ """Thread-safe generation with optional adapter toggling.
The adapter toggle + model.generate() are serialized by _generation_lock
- inside the background generation thread — NOT in the event-loop thread.
- This prevents the RLock-reentrant race that occurs when two async SSE
- handlers share the same event-loop thread.
+ in the background generation thread, NOT the event-loop thread. Prevents
+ the RLock-reentrant race when two async SSE handlers share one
+ event-loop thread.
Args:
use_adapter: Adapter control (None/False/True/str). See _apply_adapter_state.
@@ -833,9 +808,8 @@ class InferenceBackend:
):
"""Run an agentic tool loop on top of ``generate_chat_response``.
- Yields the same event-dict protocol used by the GGUF path so
- the route layer can stream both backends through one helper.
- Each event is one of:
+ Yields the same event-dict protocol as the GGUF path so the route
+ layer can stream both backends through one helper. Each event is one of:
* ``{"type": "status", "text": ...}``
* ``{"type": "content", "text": cumulative_text}``
@@ -896,15 +870,14 @@ class InferenceBackend:
reasoning_effort: Optional[str] = None,
preserve_thinking: Optional[bool] = None,
) -> Generator[str, None, None]:
- """
- Generate response for text or vision models.
+ """Generate response for text or vision models.
The generation lock is acquired by the background generation thread.
``tools`` / ``enable_thinking`` / ``reasoning_effort`` /
``preserve_thinking`` are forwarded into
- ``tokenizer.apply_chat_template`` so templates that understand
- these kwargs (Qwen3, Llama 3.1+, gpt-oss harmony, ...) advertise
- the tool schemas and reasoning controls to the model.
+ ``tokenizer.apply_chat_template`` so templates that understand them
+ (Qwen3, Llama 3.1+, gpt-oss harmony, ...) advertise the tool schemas
+ and reasoning controls to the model.
"""
yield from self._generate_chat_response_inner(
messages = messages,
@@ -941,9 +914,8 @@ class InferenceBackend:
reasoning_effort: Optional[str] = None,
preserve_thinking: Optional[bool] = None,
) -> Generator[str, None, None]:
- """
- Inner generation logic. Called by both generate_chat_response
- and generate_with_adapter_control.
+ """Inner generation logic, called by generate_chat_response and
+ generate_with_adapter_control.
_adapter_state is passed to generate_stream/vision so the background
thread can toggle adapters under the generation lock.
@@ -960,10 +932,10 @@ class InferenceBackend:
top_k = self._normalize_top_k(top_k)
if is_vision and image:
- # Vision model generation (only when an image is actually provided)
- # Check that the stored processor can actually handle images.
- # FastVisionModel may return a raw tokenizer (e.g. GemmaTokenizerFast)
- # instead of a proper ProcessorMixin for some models (e.g. Gemma-3).
+ # Vision generation (only with an actual image). Verify the stored
+ # processor can handle images — FastVisionModel may return a raw
+ # tokenizer (e.g. GemmaTokenizerFast) instead of a ProcessorMixin
+ # for some models (e.g. Gemma-3).
from transformers import ProcessorMixin
processor = model_info.get("processor")
@@ -991,10 +963,10 @@ class InferenceBackend:
f"falling back to text-only generation (image will be ignored)."
)
- # Text path: Use training pipeline approach
- # Messages are already in ChatML format from eval.py
+ # Text path: training-pipeline approach. Messages are already in
+ # ChatML format from eval.py.
- # Step 1: Apply get_chat_template if model is in mapper
+ # Step 1: apply get_chat_template if model is in mapper
try:
from utils.datasets import (
MODEL_TO_TEMPLATE_MAPPER,
@@ -1002,14 +974,13 @@ class InferenceBackend:
)
model_name_lower = self.active_model_name.lower()
- # Check if model has a registered template
if model_name_lower in MODEL_TO_TEMPLATE_MAPPER:
template_name = MODEL_TO_TEMPLATE_MAPPER[model_name_lower]
logger.info(
f"Applying chat template '{template_name}' for {self.active_model_name}"
)
- # This modifies the tokenizer with the correct template
+ # Sets the correct template on the tokenizer
tokenizer = get_chat_template(
tokenizer,
chat_template = template_name,
@@ -1021,7 +992,7 @@ class InferenceBackend:
except Exception as e:
logger.warning(f"Could not apply get_chat_template: {e}")
- # Step 2: Format with tokenizer.apply_chat_template()
+ # Step 2: format with tokenizer.apply_chat_template()
if system_prompt:
template_messages = [{"role": "system", "content": system_prompt}] + messages
else:
@@ -1046,10 +1017,10 @@ class InferenceBackend:
logger.debug(f"Formatted prompt: {formatted_prompt[:200]}...")
except Exception as e:
logger.error(f"Error applying chat template: {e}")
- # Fallback to manual formatting
+ # Fall back to manual formatting
formatted_prompt = self.format_chat_prompt(messages, system_prompt)
- # Step 3: Generate
+ # Step 3: generate
yield from self.generate_stream(
formatted_prompt,
temperature,
@@ -1080,7 +1051,7 @@ class InferenceBackend:
model = model_info["model"]
processor = model_info["processor"]
# FastVisionModel may return a raw tokenizer (e.g. GemmaTokenizerFast)
- # instead of a Processor for some models. Safe unwrap for tokenize-only ops.
+ # for some models. Safe unwrap for tokenize-only ops.
raw_tokenizer = getattr(processor, "tokenizer", processor)
# Extract user message
@@ -1136,7 +1107,7 @@ class InferenceBackend:
return_tensors = "pt",
).to(model.device)
else:
- # Text-only for vision model
+ # Text-only path for a vision model
formatted_prompt = self.format_chat_prompt(messages, system_prompt)
inputs = raw_tokenizer(formatted_prompt, return_tensors = "pt").to(model.device)
@@ -1233,7 +1204,7 @@ class InferenceBackend:
repetition_penalty,
cancel_event = None,
) -> Generator[str, None, None]:
- """Handle audio input (ASR) generation — accepts audio numpy array, streams text output.
+ """Audio-input (ASR) generation: takes an audio numpy array, streams text.
Uses processor.apply_chat_template with audio embedded in messages (Gemma 3n pattern).
"""
@@ -1245,7 +1216,7 @@ class InferenceBackend:
processor = model_info.get("processor") or model_info.get("tokenizer")
raw_tokenizer = getattr(processor, "tokenizer", processor)
- # Extract last user text — default matches notebook prompt
+ # Last user text; default matches the notebook prompt
user_text = "Please transcribe this audio."
if messages:
for msg in reversed(messages):
@@ -1253,11 +1224,11 @@ class InferenceBackend:
user_text = msg["content"]
break
- # Use ASR-specific system prompt if user hasn't set a custom one
+ # ASR-specific default system prompt if none set
if not system_prompt:
system_prompt = "You are an assistant that transcribes speech accurately."
- # Build messages in Gemma 3n format — audio goes INTO apply_chat_template
+ # Gemma 3n format — audio goes INTO apply_chat_template
audio_messages = [
{"role": "system", "content": [{"type": "text", "text": system_prompt}]},
{
@@ -1269,7 +1240,7 @@ class InferenceBackend:
},
]
- # apply_chat_template handles audio embedding + tokenization in one step
+ # apply_chat_template does audio embedding + tokenization in one step
inputs = processor.apply_chat_template(
audio_messages,
add_generation_prompt = True,
@@ -1290,7 +1261,7 @@ class InferenceBackend:
timeout = 0.2,
)
- # Notebook uses do_sample=False for ASR (greedy decoding for accuracy)
+ # Notebook uses do_sample=False (greedy) for ASR accuracy
generation_kwargs = dict(
**inputs,
streamer = streamer,
@@ -1354,9 +1325,9 @@ class InferenceBackend:
audio_array,
cancel_event = None,
) -> Generator[str, None, None]:
- """Whisper ASR — takes audio numpy array, yields transcribed text.
+ """Whisper ASR: takes an audio numpy array, yields transcribed text.
- Uses the pre-built transformers pipeline (created during model loading).
+ Uses the pre-built transformers pipeline created at model load.
"""
model_info = self.models[self.active_model_name]
whisper_pipe = model_info.get("whisper_pipeline")
@@ -1376,7 +1347,7 @@ class InferenceBackend:
yield f"Error: {str(e)}"
def _is_gpt_oss_model(self, model_name: str = None) -> bool:
- """Check if the given (or active) model uses the gpt-oss harmony protocol."""
+ """Whether the given (or active) model uses the gpt-oss harmony protocol."""
from utils.datasets import is_gpt_oss_model_name
return is_gpt_oss_model_name(model_name or self.active_model_name or "")
@@ -1392,10 +1363,10 @@ class InferenceBackend:
cancel_event = None,
_adapter_state = None,
) -> Generator[str, None, None]:
- """Generate streaming text response (text models only).
+ """Generate a streaming text response (text models only).
_adapter_state: if not None, the background thread toggles adapters
- before model.generate(), all under _generation_lock.
+ before model.generate(), under _generation_lock.
"""
if not self.active_model_name:
yield "Error: No active model"
@@ -1403,9 +1374,9 @@ class InferenceBackend:
model_info = self.models[self.active_model_name]
model = model_info["model"]
- # For VLMs the stored "tokenizer" is actually the processor.
- # Unwrap to get the real tokenizer so TextIteratorStreamer's
- # skip_prompt / skip_special_tokens work correctly.
+ # For VLMs the stored "tokenizer" is actually the processor. Unwrap to
+ # the real tokenizer so TextIteratorStreamer's skip_prompt /
+ # skip_special_tokens work correctly.
tokenizer = model_info["tokenizer"]
tokenizer = getattr(tokenizer, "tokenizer", tokenizer)
@@ -1415,8 +1386,8 @@ class InferenceBackend:
from transformers import TextIteratorStreamer
import threading
- # Use HarmonyTextStreamer for gpt-oss models to properly parse
- # the multi-channel harmony protocol into <think> tags
+ # gpt-oss models: HarmonyTextStreamer parses the multi-channel
+ # harmony protocol into <think> tags
if self._is_gpt_oss_model():
try:
streamer = HarmonyTextStreamer(
@@ -1513,11 +1484,10 @@ class InferenceBackend:
cleaned = self._clean_generated_text(output)
yield cleaned
finally:
- # Only set cancel_event when we exited early (user cancel),
- # NOT on normal completion. cancel_event is a shared mp.Event
- # — setting it unconditionally would leave a stale cancel
- # signal that could interfere with the next serialized
- # generation request (e.g. in compare mode).
+ # Set cancel_event only on early exit (user cancel), NOT on
+ # normal completion. It's a shared mp.Event; setting it
+ # unconditionally would leave a stale cancel signal that could
+ # disrupt the next serialized request (e.g. compare mode).
if cancel_event is not None and not generation_complete:
cancel_event.set()
thread.join(timeout = 10)
@@ -1544,10 +1514,8 @@ class InferenceBackend:
repetition_penalty: float = 1.0,
use_adapter: Optional[Union[bool, str]] = None,
) -> Tuple[bytes, int]:
- """
- Generate audio from text for TTS models.
- Returns (wav_bytes, sample_rate).
- Blocking — generates complete audio before returning.
+ """Generate audio from text for TTS models.
+ Returns (wav_bytes, sample_rate). Blocking — full audio before return.
"""
if not self.active_model_name:
raise RuntimeError("No active model")
@@ -1661,8 +1629,8 @@ class InferenceBackend:
repetition_penalty,
):
"""Generate audio using DAC (OuteTTS). Follows Oute_TTS_(1B).ipynb exactly."""
- # Monkey-patch RepetitionPenaltyLogitsProcessor with a 64-token penalty
- # window (same as the OuteTTS notebook) to avoid degenerate repetition.
+ # Monkey-patch RepetitionPenaltyLogitsProcessor with a 64-token window
+ # (same as the OuteTTS notebook) to avoid degenerate repetition.
self._patch_repetition_penalty_processor()
prompt = (
@@ -1689,10 +1657,9 @@ class InferenceBackend:
@classmethod
def _patch_repetition_penalty_processor(cls):
- """
- Monkey-patch transformers' RepetitionPenaltyLogitsProcessor with a
- 64-token sliding window variant (from the OuteTTS notebook).
- Only applied once per process.
+ """Monkey-patch transformers' RepetitionPenaltyLogitsProcessor with a
+ 64-token sliding-window variant (from the OuteTTS notebook).
+ Applied once per process.
"""
if cls._repetition_penalty_patched:
return
@@ -1743,10 +1710,10 @@ class InferenceBackend:
reasoning_effort: Optional[str] = None,
preserve_thinking: Optional[bool] = None,
) -> str:
- """Render the chat prompt, peeling kwargs the template does not
- understand. Delegates to the dependency-light helper module so
- the fallback chain can be unit-tested without pulling unsloth /
- torch into the test sandbox.
+ """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.
"""
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
@@ -1846,8 +1813,7 @@ class InferenceBackend:
return self._format_generic_template(chat_messages, {})
def _format_chat_manual(self, messages: list, template_type: str, special_tokens: dict) -> str:
- """
- Manual chat formatting fallback for when tokenizer template fails
+ """Manual chat-formatting fallback when the tokenizer template fails.
Args:
messages: List of message dictionaries
@@ -1960,12 +1926,7 @@ class InferenceBackend:
return formatted
def check_vision_model_compatibility(self) -> bool:
- """
- Check if current model supports vision.
-
- Returns:
- bool: True if current model supports vision, False otherwise
- """
+ """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)
@@ -1981,7 +1942,7 @@ class InferenceBackend:
return
try:
- # This is a common pattern for Unsloth/Hugging Face models
+ # Common pattern for Unsloth/Hugging Face models
if hasattr(model, "past_key_values"):
model.past_key_values = None
if hasattr(model, "generation_config"):
@@ -1995,7 +1956,7 @@ class InferenceBackend:
def reset_generation_state(self):
"""Reset any cached generation state to prevent hanging after errors"""
try:
- # Clear cached states for ALL loaded models
+ # Clear cached state for ALL loaded models
for model_name in self.models.keys():
self._reset_model_generation_state(model_name)
@@ -2029,9 +1990,9 @@ class InferenceBackend:
def _clean_generated_text(self, text: str) -> str:
"""Strip leaked special tokens using the tokenizer's own token list."""
if self._is_gpt_oss_model():
- # HarmonyTextStreamer produces clean <think>...</think> output.
- # Strip harmony protocol tokens and other gpt-oss added tokens
- # (e.g. <|return|>) that may leak past the streamer.
+ # HarmonyTextStreamer emits clean <think>...</think>. Strip any
+ # harmony protocol tokens and other gpt-oss tokens (e.g.
+ # <|return|>) that leak past the streamer.
import re
text = re.sub(r"<\|[a-z_]+\|>", "", text)
return text.strip()
@@ -2059,7 +2020,7 @@ class InferenceBackend:
try:
from utils.datasets import MODEL_TO_TEMPLATE_MAPPER
- # Try exact match first
+ # 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]
@@ -2067,7 +2028,7 @@ class InferenceBackend:
f"Detected template '{chat_template_info['template_name']}' for {model_name} from mapper"
)
else:
- # Try partial match (for variants like model_name-bnb-4bit)
+ # Partial match (for variants like model_name-bnb-4bit)
for key in MODEL_TO_TEMPLATE_MAPPER:
if key in model_name_lower or model_name_lower in key:
chat_template_info["template_name"] = MODEL_TO_TEMPLATE_MAPPER[key]
@@ -2127,15 +2088,15 @@ class InferenceBackend:
logger.info(f"No built-in chat template for {model_name}, will use generic formatting")
def get_current_model(self) -> Optional[str]:
- """Get currently active model name"""
+ """Currently active model name."""
return self.active_model_name
def is_model_loading(self) -> bool:
- """Check if any model is currently loading"""
+ """Whether any model is currently loading."""
return len(self.loading_models) > 0
def get_loading_model(self) -> Optional[str]:
- """Get name of currently loading model"""
+ """Name of the currently loading model."""
return next(iter(self.loading_models)) if self.loading_models else None
def load_model_simple(
@@ -2145,9 +2106,8 @@ class InferenceBackend:
max_seq_length: int = 2048,
load_in_4bit: bool = True,
) -> bool:
- """
- Simple model loading wrapper for chat interface.
- Accepts model path as string and handles ModelConfig creation internally.
+ """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")
@@ -2159,14 +2119,12 @@ class InferenceBackend:
bool: True if successful, False otherwise
"""
try:
- # Create config from string path
config = ModelConfig.from_ui_selection(
model_path,
lora_path = None, # No LoRA for chat
is_lora = False,
)
- # Call existing load_model with config
return self.load_model(
config = config,
max_seq_length = max_seq_length,
diff --git a/studio/backend/core/inference/key_exchange.py b/studio/backend/core/inference/key_exchange.py
index f43bb16cf67..ddc726751db 100644
--- a/studio/backend/core/inference/key_exchange.py
+++ b/studio/backend/core/inference/key_exchange.py
@@ -4,13 +4,13 @@
"""
RSA key pair for encrypting API keys in transit.
-The frontend encrypts API keys with the server's public key before
-including them in requests. The backend decrypts with its private key
-before forwarding to external providers.
+The frontend encrypts API keys with the server's public key before sending
+them; the backend decrypts with its private key before forwarding to external
+providers.
-The key pair is generated at server startup and lives only in memory —
-it is regenerated on each restart. The frontend fetches the public key
-via GET /api/providers/public-key on load.
+The key pair is generated at server startup, lives only in memory, and is
+regenerated on each restart. The frontend fetches the public key via
+GET /api/providers/public-key on load.
"""
import base64
@@ -36,9 +36,9 @@ def init_key_pair() -> None:
"""Generate an RSA-2048 key pair. Called once at server startup."""
global _private_key, _public_key_pem, _public_key_fingerprint
if _private_key is not None:
- # Re-entry is suspicious — every fresh keypair invalidates all
- # in-flight ciphertext encrypted against the previous public key.
- # Log loudly so a regression that calls init twice is visible.
+ # Re-entry is suspicious — a fresh keypair invalidates all in-flight
+ # ciphertext encrypted against the previous public key. Log loudly so a
+ # regression that calls init twice is visible.
logger.warning(
"init_key_pair called again — replacing existing RSA keypair "
"(previous fingerprint=%s). Any frontend that cached the old "
@@ -111,9 +111,9 @@ def decrypt_api_key(encrypted_b64: str) -> str:
),
)
except Exception as exc:
- # Surface enough state to distinguish key mismatch (wrong public key
- # used on encrypt) from a padding/algo mismatch or corrupted bytes.
- # Expected ciphertext length for RSA-2048 is exactly 256 bytes.
+ # Surface enough state to tell a key mismatch (wrong public key used on
+ # encrypt) from a padding/algo mismatch or corrupted bytes. Expected
+ # RSA-2048 ciphertext length is exactly 256 bytes.
logger.warning(
"decrypt_api_key: RSA decrypt failed (ciphertext_len=%d, expected=256, "
"fingerprint=%s, exc=%s): %s",
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 72dcc11bebe..e2b2533d2ec 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -4,8 +4,8 @@
"""
llama-server inference backend for GGUF models.
-Manages a llama-server subprocess and proxies chat completions
-through its OpenAI-compatible /v1/chat/completions endpoint.
+Manages a llama-server subprocess and proxies chat completions through
+its OpenAI-compatible /v1/chat/completions endpoint.
"""
import atexit
@@ -60,16 +60,14 @@ logger = get_logger(__name__)
# ── Pre-compiled patterns for plan-without-action re-prompt ──
-# Forward-looking intent signals that indicate the model is
-# describing what it *will* do rather than giving a final answer.
+# Forward-looking intent signals: the model is describing what it *will*
+# do rather than giving a final answer.
_INTENT_SIGNAL = re.compile(
r"(?i)("
- # Direct intent: "I'll ...", "I will ...", "Let me ...", "I am going to ..."
- # Handles both straight and curly apostrophes.
- # Excludes "I can", "I should", "I want to", "let's" which
- # appear frequently in direct answers / explanations.
- # Negative lookahead drops negated forms ("I will not", "I'll never")
- # so a refusal doesn't trigger a re-prompt.
+ # Direct intent ("I'll ...", "Let me ...", straight + curly apostrophes).
+ # Excludes "I can"/"I should"/"I want to"/"let's" (common in answers).
+ # Negative lookahead drops negated forms ("I will not") so a refusal
+ # doesn't trigger a re-prompt.
r"\b(i['\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall|let me|allow me)\b(?!\s+(?:not|never)\b)"
r"|"
# Step/plan framing: "First ...", "Step 1:", "Here's my plan"
@@ -81,18 +79,17 @@ _INTENT_SIGNAL = re.compile(
)
_MAX_REPROMPTS = 3
-# Without max_tokens, llama-server defaults to n_predict = n_ctx (up to
+# Without max_tokens, llama-server defaults n_predict = n_ctx (up to
# 262144 for Qwen3.5), producing many-minute zombie decodes when cancel
-# fails. t_max_predict_ms is a wall-clock backstop applied unconditionally,
-# but the llama.cpp README notes it ONLY fires after a newline has been
-# generated -- a model stuck in a long unbroken non-newline sequence is
-# unbounded by it. So we still want a token cap as the front-line limiter.
+# fails. t_max_predict_ms is an unconditional wall-clock backstop, but the
+# llama.cpp README notes it ONLY fires after a newline -- a model stuck in
+# a long non-newline sequence is unbounded by it. So we keep a token cap
+# as the front-line limiter.
#
-# The cap is the model's effective context length when we know it,
-# falling back to a generous floor when metadata is unavailable. 4096 was
-# too low: Qwen3 / gpt-oss reasoning traces routinely exceed it, and any
-# OpenAI-API caller that omits max_tokens (langchain, llama-index, raw
-# curl) sees responses silently truncated mid-sentence.
+# The cap is the model's effective context length when known, else a
+# generous floor. 4096 was too low: Qwen3 / gpt-oss reasoning traces
+# exceed it, and any OpenAI-API caller omitting max_tokens (langchain,
+# llama-index, raw curl) sees responses truncated mid-sentence.
_DEFAULT_MAX_TOKENS_FLOOR = 32768
_DEFAULT_T_MAX_PREDICT_MS = 600_000 # 10 min
_REPROMPT_MAX_CHARS = 2000
@@ -103,15 +100,14 @@ _SHARD_RE = re.compile(r"^(.*)-\d{5}-of-\d{5}\.gguf$")
# ── Sliding-window-pattern resolver ───────────────────────────
-# Resolves the per-layer SWA mask when a GGUF reports a sliding window
-# but no `sliding_window_pattern` field. Tier order in
-# `_resolve_swa_pattern`: GGUF metadata, on-disk cache, bootstrap dict
-# below, transformers introspection, HF Hub config.json, legacy 1/4
-# fallback. Period N means layer i is SWA iff `(i + 1) % N != 0`,
-# matching transformers. Skipped on purpose: phi3 (no key/val length
-# in GGUF, window >= ctx anyway), qwen2 family (converter strips
-# sliding_window when use_sliding_window=False), mistral v0.1/v0.2
-# (all-SWA can't be expressed as a period).
+# Resolves the per-layer SWA mask when a GGUF reports a sliding window but
+# no `sliding_window_pattern` field. Tier order in `_resolve_swa_pattern`:
+# GGUF metadata, on-disk cache, bootstrap dict below, transformers
+# introspection, HF Hub config.json, legacy 1/4 fallback. Period N means
+# layer i is SWA iff `(i + 1) % N != 0`, matching transformers. Skipped on
+# purpose: phi3 (no key/val length in GGUF, window >= ctx anyway), qwen2
+# family (converter strips sliding_window when use_sliding_window=False),
+# mistral v0.1/v0.2 (all-SWA can't be a period).
_BOOTSTRAP_SWA_DEFAULTS: dict[str, int] = {
"gemma2": 2, # Gemma2Config.sliding_window_pattern
"gemma3": 6, # Gemma3TextConfig.sliding_window_pattern
@@ -127,8 +123,8 @@ _SWA_CACHE_LOCK = threading.Lock()
def _probe_dns_dead(host: str = "huggingface.co", timeout: float = 2.0) -> bool:
- """Quick DNS check. Runs on a daemon thread so concurrent sockets
- in the same process are not affected by socket.setdefaulttimeout."""
+ """Quick DNS check on a daemon thread, so concurrent sockets in the
+ same process aren't affected by socket.setdefaulttimeout."""
result: list[Optional[bool]] = [None]
def _probe() -> None:
@@ -141,16 +137,15 @@ def _probe_dns_dead(host: str = "huggingface.co", timeout: float = 2.0) -> bool:
t = threading.Thread(target = _probe, daemon = True)
t.start()
t.join(timeout)
- # Thread still running -> resolver wedged -> treat as dead.
+ # Thread still running -> resolver wedged -> dead.
return True if result[0] is None else result[0]
@contextlib.contextmanager
def _hf_offline_if_dns_dead():
- """Set HF_HUB_OFFLINE for the body of this block only when DNS to
- huggingface.co fails. Restores the env on exit so a transient
- resolver hiccup at the start of one load can't quarantine the whole
- process. Respects an explicit user setting (no-op if already set)."""
+ """Set HF_HUB_OFFLINE for this block only when DNS to huggingface.co
+ fails. Restores the env on exit so a transient resolver hiccup can't
+ quarantine the whole process. No-op if the user already set it."""
if "HF_HUB_OFFLINE" in os.environ:
yield False
return
@@ -205,8 +200,8 @@ def _save_swa_cache(cache: dict) -> None:
def _period_from_layer_types(layer_types: list) -> Optional[int]:
- """Smallest period N where `(i+1) % N != 0` matches the SWA mask,
- or None if no fixed period fits."""
+ """Smallest period N where `(i+1) % N != 0` matches the SWA mask, or
+ None if no fixed period fits."""
if not layer_types:
return None
is_swa = ["full" not in str(t).lower() for t in layer_types]
@@ -260,8 +255,8 @@ _SWA_PATTERN_SOURCE_RE = re.compile(r"sliding_window_pattern\s*(?::\s*[\w\[\], ]
def _resolve_swa_entry_from_transformers(arch: str) -> Optional[object]:
- """Default-instantiate the matching Config; on failure, regex-parse
- its source for `sliding_window_pattern = N`."""
+ """Default-instantiate the matching Config; on failure, regex-parse its
+ source for `sliding_window_pattern = N`."""
try:
from transformers.models.auto.configuration_auto import (
CONFIG_MAPPING,
@@ -348,7 +343,7 @@ def _resolve_swa_pattern(
_persist(entry)
return _entry_to_mask(entry)
- # Tier 3: live HF fetch (with persistent caching of the result)
+ # Tier 3: live HF fetch (result persistently cached)
if allow_network:
for repo_id in source_repo_candidates:
if not repo_id:
@@ -362,7 +357,7 @@ def _resolve_swa_pattern(
def _hf_repo_from_url(url: Optional[str]) -> Optional[str]:
- """Strip `https://huggingface.co/owner/name(/...)` to `owner/name`."""
+ """Strip `https://huggingface.co/owner/name(/...)` -> `owner/name`."""
if not url or "huggingface.co/" not in url:
return None
tail = url.split("huggingface.co/", 1)[1].rstrip("/")
@@ -372,8 +367,8 @@ def _hf_repo_from_url(url: Optional[str]) -> Optional[str]:
return f"{parts[0]}/{parts[1]}"
-# Model size extraction — lazy import to avoid pulling in transformers
-# at module level. See PR description for the full explanation.
+# Lazy import to avoid pulling transformers in at module level.
+# See PR description for the full explanation.
def _extract_model_size_b(model_id: str):
from utils.models import extract_model_size_b
return extract_model_size_b(model_id)
@@ -399,13 +394,12 @@ def detect_reasoning_flags(
) -> dict:
"""Classify a chat template's reasoning and tool-calling capabilities.
- Returns a dict with the same five keys populated by the GGUF sniffer:
- ``supports_reasoning``, ``reasoning_style``
- (``"enable_thinking"`` | ``"reasoning_effort"``),
- ``reasoning_always_on``, ``supports_preserve_thinking``, and
- ``supports_tools``. Used by both the llama-server backend at load
- time and the safetensors/transformers paths in ``routes/inference``
- so the two agree on what the frontend will see.
+ Returns the same five keys as the GGUF sniffer: ``supports_reasoning``,
+ ``reasoning_style`` (``"enable_thinking"`` | ``"reasoning_effort"``),
+ ``reasoning_always_on``, ``supports_preserve_thinking``,
+ ``supports_tools``. Used by both the llama-server backend at load time
+ and the safetensors/transformers paths in ``routes/inference`` so they
+ agree on what the frontend sees.
"""
flags = {
"supports_reasoning": False,
@@ -424,28 +418,28 @@ def detect_reasoning_flags(
flags["reasoning_style"] = "enable_thinking"
logger.info(f"{prefix}model supports reasoning (enable_thinking)")
elif "reasoning_effort" in tpl:
- # gpt-oss / Harmony templates use reasoning_effort
- # ("low" | "medium" | "high") instead of a boolean.
+ # gpt-oss / Harmony use reasoning_effort
+ # ("low" | "medium" | "high"), not a boolean.
flags["supports_reasoning"] = True
flags["reasoning_style"] = "reasoning_effort"
logger.info(f"{prefix}model supports reasoning (reasoning_effort)")
elif "thinking" in tpl:
- # DeepSeek uses 'thinking' instead of 'enable_thinking'
+ # DeepSeek uses 'thinking', not 'enable_thinking'
normalized_id = (model_identifier or "").lower()
if "deepseek" in normalized_id:
flags["supports_reasoning"] = True
logger.info(f"{prefix}model supports reasoning (DeepSeek thinking)")
# Hardcoded <think> tags or reasoning_content in the template mean
- # thinking is always on (no toggle to disable it).
+ # thinking is always on (no toggle).
if not flags["supports_reasoning"]:
if ("<think>" in tpl and "</think>" in tpl) or "reasoning_content" in tpl:
flags["supports_reasoning"] = True
flags["reasoning_always_on"] = True
logger.info(f"{prefix}model always reasons (<think> tags in template)")
- # preserve_thinking is an independent kwarg on some Qwen templates
- # that keeps historical <think> blocks in prior assistant turns.
+ # preserve_thinking: independent kwarg on some Qwen templates that
+ # keeps historical <think> blocks in prior assistant turns.
if "preserve_thinking" in tpl:
flags["supports_preserve_thinking"] = True
logger.info(f"{prefix}model supports preserve_thinking")
@@ -466,9 +460,8 @@ def _is_mtp_model_name(model_identifier: Optional[str], gguf_path: Optional[str]
def _extra_args_set_spec_type(extra_args: Optional[Iterable[str]]) -> bool:
- """User passed --spec-type / --spec-default? llama-server takes a
- single --spec-type (comma-separated to chain), so suppress
- auto-emit when this is true."""
+ """User passed --spec-type / --spec-default? llama-server takes one
+ --spec-type (comma-separated to chain), so suppress auto-emit."""
if not extra_args:
return False
for raw in extra_args:
@@ -490,11 +483,11 @@ def _build_ngram_mod_flags(
"""Emit the right ngram-mod knob flags for the running llama-server.
Post-rename builds expose ``--spec-ngram-mod-n-{match,min,max}``;
- pre-rename builds expose the legacy ``--spec-ngram-size-n`` /
+ pre-rename builds expose legacy ``--spec-ngram-size-n`` /
``--draft-min`` / ``--draft-max``. ``caps`` comes from
- ``probe_server_capabilities``; ``ngram_mod_flavor`` tells us which
- set is real (vs a removal-stub entry). Returns ``[]`` when neither
- set is available so the caller can drop ngram-mod entirely.
+ ``probe_server_capabilities``; ``ngram_mod_flavor`` says which set is
+ real (vs a removal-stub). Returns ``[]`` when neither is available so
+ the caller can drop ngram-mod entirely.
"""
flavor = caps.get("ngram_mod_flavor") if caps else None
if flavor == "new":
@@ -507,9 +500,8 @@ def _build_ngram_mod_flags(
str(n_max),
]
if flavor == "legacy":
- # Legacy llama.cpp before the spec arg rename: same knobs lived
- # under --spec-ngram-size-n (lookup length) and the generic
- # --draft-min / --draft-max (ngram size N range).
+ # Pre-rename llama.cpp: same knobs lived under --spec-ngram-size-n
+ # (lookup length) and generic --draft-min / --draft-max (N range).
return [
"--spec-ngram-size-n",
str(n_match),
@@ -522,9 +514,9 @@ def _build_ngram_mod_flags(
# Canonical Speculative Decoding modes exposed by the Studio chat UI.
-# The dropdown renders five options (auto, mtp, ngram, mtp+ngram, off);
-# the load API also accepts legacy values that the original Switch and
-# external callers emit (default, draft-mtp, ngram-mod, ngram-simple).
+# Dropdown renders five (auto, mtp, ngram, mtp+ngram, off); the load API
+# also accepts legacy values the original Switch and external callers emit
+# (default, draft-mtp, ngram-mod, ngram-simple).
_CANONICAL_SPEC_MODES = {"auto", "mtp", "ngram", "mtp+ngram", "off", "ngram-simple"}
_LEGACY_SPEC_MODE_MAP = {
"default": "auto",
@@ -536,10 +528,10 @@ _LEGACY_SPEC_MODE_MAP = {
def _canonicalize_spec_mode(value):
"""Map any accepted ``speculative_type`` input onto a canonical mode.
- Returns one of ``auto``, ``mtp``, ``ngram``, ``mtp+ngram``, ``off``,
+ Returns ``auto``, ``mtp``, ``ngram``, ``mtp+ngram``, ``off``,
``ngram-simple``, or ``None`` (callers treat ``None`` as ``auto``).
- Unknown strings collapse to ``auto`` so a stale UI value or typo
- falls back to the safe platform-aware path.
+ Unknown strings collapse to ``auto`` so a stale UI value or typo falls
+ back to the safe platform-aware path.
"""
if value is None:
return None
@@ -552,7 +544,7 @@ def _canonicalize_spec_mode(value):
return stripped
if stripped in _LEGACY_SPEC_MODE_MAP:
return _LEGACY_SPEC_MODE_MAP[stripped]
- # llama.cpp comma-chains are emitted by old persisted state e.g.
+ # Old persisted state emits llama.cpp comma-chains e.g.
# "ngram-mod,draft-mtp"; collapse the most common one explicitly.
pieces = [p.strip() for p in stripped.split(",") if p.strip()]
has_mtp = any(p in ("mtp", "draft-mtp") for p in pieces)
@@ -571,12 +563,11 @@ def _backfill_usage_from_timings(usage, timings):
OpenAI-style usage block is missing or reports zero tokens.
The Studio chat UI computes generation t/s from
- ``meta.usage.completion_tokens / totalStreamTime``. llama-server
- always populates ``timings.predicted_n`` (true decoded count) and
- ``timings.prompt_n``, but the ``usage`` field on the final SSE chunk
- can be absent or zero on some server builds / streaming
- configurations, which makes the UI fall back to wall-clock t/s and
- dilute speculative-decoding speedups.
+ ``meta.usage.completion_tokens / totalStreamTime``. llama-server always
+ populates ``timings.predicted_n`` (true decoded count) and
+ ``timings.prompt_n``, but the final SSE chunk's ``usage`` can be absent
+ or zero on some server builds / streaming configs, making the UI fall
+ back to wall-clock t/s and dilute speculative-decoding speedups.
"""
if not timings:
return usage
@@ -602,9 +593,9 @@ class LlamaCppBackend:
Manages a llama-server subprocess for GGUF model inference.
Lifecycle:
- 1. load_model() — starts llama-server with the GGUF file
- 2. generate_chat_completion() — proxies to /v1/chat/completions, streams back
- 3. unload_model() — terminates llama-server subprocess
+ 1. load_model() — start llama-server with the GGUF file
+ 2. generate_chat_completion() — proxy to /v1/chat/completions, stream back
+ 3. unload_model() — terminate the subprocess
"""
def __init__(self):
@@ -631,14 +622,13 @@ class LlamaCppBackend:
self._cache_type_kv: Optional[str] = None
self._reasoning_default: bool = True
self._speculative_type: Optional[str] = None
- # Canonical UI-facing mode the user requested: one of
+ # Canonical UI-facing mode the user requested:
# ``auto``/``mtp``/``ngram``/``mtp+ngram``/``off``/``ngram-simple``.
- # Round-tripped through the status API so the dropdown reflects
- # the picked mode rather than the resolved internal flag set
- # (auto on a 27B MTP GGUF resolves to draft-mtp but the dropdown
- # should still read "Auto").
+ # Round-tripped through the status API so the dropdown reflects the
+ # picked mode, not the resolved internal flag set (auto on a 27B MTP
+ # GGUF resolves to draft-mtp but the dropdown still reads "Auto").
self._requested_spec_mode: Optional[str] = None
- # User-supplied --spec-draft-n-max override (None = platform default).
+ # User --spec-draft-n-max override (None = platform default).
self._spec_draft_n_max: Optional[int] = None
# KV-cache estimation fields (populated by _read_gguf_metadata)
self._n_layers: Optional[int] = None
@@ -658,17 +648,17 @@ class LlamaCppBackend:
self._kv_value_length_swa: Optional[int] = None
self._ssm_inner_size: Optional[int] = None
self._ssm_state_size: Optional[int] = None
- # Last N layers reuse KV from earlier layers and don't allocate
- # their own cache (Gemma 3n / Gemma 4: <arch>.attention.shared_kv_layers).
+ # Last N layers reuse earlier layers' KV and don't allocate their own
+ # cache (Gemma 3n / Gemma 4: <arch>.attention.shared_kv_layers).
self._shared_kv_layers: Optional[int] = None
# MTP head count (llama.cpp #22673); >0 enables --spec-type draft-mtp.
self._nextn_predict_layers: Optional[int] = None
self._lock = threading.Lock()
- # Wraps load_model() end-to-end so concurrent loads serialise
- # and never coexist as two llama-server processes (#5401).
+ # Wraps load_model() end-to-end so concurrent loads serialise and
+ # never coexist as two llama-server processes (#5401).
self._serial_load_lock = threading.Lock()
- # Last extra_args / requested n_ctx, preserved across unload so
- # the chat UI's /unload+/load Apply path can inherit them (#5401).
+ # Last extra_args / requested n_ctx, preserved across unload so the
+ # chat UI's /unload+/load Apply path can inherit them (#5401).
# ``_extra_args_source`` records the (model_identifier, hf_variant)
# the stored args came from so the route can refuse cross-model
# inheritance.
@@ -725,8 +715,9 @@ class LlamaCppBackend:
@property
def extra_args(self) -> Optional[List[str]]:
- """Extra llama-server flags from the last load. Copy; None = never
- set, [] = explicitly cleared. Used by the route for inheritance."""
+ """Extra llama-server flags from the last load (a copy). None =
+ never set, [] = explicitly cleared. Used by the route for
+ inheritance."""
return list(self._extra_args) if self._extra_args is not None else None
@property
@@ -751,14 +742,12 @@ class LlamaCppBackend:
def max_context_length(self) -> Optional[int]:
"""Return the largest context that fits on this hardware at load time.
- This is the "safe zone" threshold the UI renders warnings
- against. For a model whose weights fit on some GPU subset, it
- is the binary-search cap from ``_fit_context_to_vram`` for that
- subset. For a model whose weights exceed 90% of every GPU
- subset, it is the 4096 fallback -- the spec's default when the
- model will not fit. The UI slider ceiling is
- ``native_context_length``; dragging above ``max_context_length``
- triggers the "might be slower" warning.
+ The UI's "safe zone" warning threshold. If the weights fit on some
+ GPU subset, it's the binary-search cap from ``_fit_context_to_vram``
+ for that subset; if they exceed 90% of every subset, it's the 4096
+ fallback (the spec's default when the model won't fit). The UI
+ slider ceiling is ``native_context_length``; dragging above
+ ``max_context_length`` triggers the "might be slower" warning.
"""
return self._max_context_length or self._context_length
@@ -770,17 +759,16 @@ class LlamaCppBackend:
def load_progress(self) -> Optional[dict]:
"""Return live model-load progress, or None if not loading.
- While llama-server is warming up, its process is typically in
- kernel state D (disk sleep) mmap'ing the weight shards into
- page cache before pushing layers to VRAM. During that window
- ``/api/inference/status`` only reports ``loading``, which gives
- the UI nothing to display besides a spinner that looks stuck
- for minutes on large MoE models.
+ While llama-server warms up, its process is typically in kernel
+ state D (disk sleep) mmap'ing weight shards into page cache before
+ pushing layers to VRAM. During that window
+ ``/api/inference/status`` only reports ``loading``, so the UI has
+ nothing but a spinner that looks stuck for minutes on large MoEs.
- This method samples ``/proc/<pid>/status VmRSS`` against the
- sum of the GGUF shard sizes so the UI can render a real bar
- and compute rate / ETA. Returns ``None`` when no load is in
- flight (no process, or process already healthy).
+ Samples ``/proc/<pid>/status VmRSS`` against the sum of GGUF shard
+ sizes so the UI can render a real bar and compute rate / ETA.
+ Returns ``None`` when no load is in flight (no process, or already
+ healthy).
Shape::
@@ -791,9 +779,8 @@ class LlamaCppBackend:
"fraction": float, # bytes_loaded / bytes_total, 0..1
}
- Linux-only in the current implementation. On macOS/Windows the
- equivalent would be a different API; this returns ``None`` on
- platforms where ``/proc/<pid>/status`` is unavailable.
+ Linux-only for now; returns ``None`` where ``/proc/<pid>/status``
+ is unavailable (macOS/Windows would need a different API).
"""
proc = self._process
if proc is None:
@@ -802,7 +789,7 @@ class LlamaCppBackend:
if pid is None:
return None
- # Sum up shard sizes (primary + any extras sitting alongside).
+ # Sum shard sizes (primary + any extras alongside).
bytes_total = 0
gguf_path = self._gguf_path
if gguf_path:
@@ -812,8 +799,8 @@ class LlamaCppBackend:
bytes_total += primary.stat().st_size
except OSError:
pass
- # Extra shards live alongside the primary with the same prefix
- # before the shard index (e.g. ``-00001-of-00004.gguf``).
+ # Extra shards share the primary's prefix before the shard
+ # index (e.g. ``-00001-of-00004.gguf``).
try:
parent = primary.parent
stem = primary.name
@@ -834,7 +821,7 @@ class LlamaCppBackend:
except OSError:
pass
- # Read VmRSS from /proc/<pid>/status. Kilobytes on Linux.
+ # Read VmRSS from /proc/<pid>/status (kilobytes on Linux).
bytes_loaded = 0
try:
with open(f"/proc/{pid}/status", "r", encoding = "utf-8") as f:
@@ -898,13 +885,13 @@ class LlamaCppBackend:
) -> Optional[dict]:
"""Build chat_template_kwargs from per-request reasoning fields.
- Produces a merged dict covering the active model's reasoning style
- (``enable_thinking`` or ``reasoning_effort``) plus the independent
- ``preserve_thinking`` kwarg when the template supports it.
+ Merges the active model's reasoning style (``enable_thinking`` or
+ ``reasoning_effort``) plus the independent ``preserve_thinking``
+ kwarg when the template supports it.
"""
kwargs: dict = {}
- # Always-on reasoning models hardcode <think> tags in their template
- # and do not consume enable_thinking / reasoning_effort -- skip.
+ # Always-on reasoning models hardcode <think> tags and don't consume
+ # enable_thinking / reasoning_effort -- skip.
if self._supports_reasoning and not self._reasoning_always_on:
if self._reasoning_style == "reasoning_effort":
if reasoning_effort in ("low", "medium", "high"):
@@ -937,8 +924,8 @@ class LlamaCppBackend:
@property
def spec_draft_n_max(self) -> Optional[int]:
- """User --spec-draft-n-max override active on the load, or None
- when the platform default (6 GPU / 3 CPU) is in effect."""
+ """User --spec-draft-n-max override active on the load, or None when
+ the platform default (6 GPU / 3 CPU) is in effect."""
return self._spec_draft_n_max
# ── Binary discovery ──────────────────────────────────────────
@@ -961,12 +948,12 @@ class LlamaCppBackend:
"""
binary_name = "llama-server.exe" if sys.platform == "win32" else "llama-server"
- # 1. Env var — direct path to binary
+ # 1. Env var: direct path to binary
env_path = os.environ.get("LLAMA_SERVER_PATH")
if env_path and Path(env_path).is_file():
return env_path
- # 1b. UNSLOTH_LLAMA_CPP_PATH — custom llama.cpp install directory
+ # 1b. UNSLOTH_LLAMA_CPP_PATH: custom llama.cpp install dir
custom_llama_cpp = os.environ.get("UNSLOTH_LLAMA_CPP_PATH")
if custom_llama_cpp:
custom_dir = Path(custom_llama_cpp)
@@ -974,11 +961,11 @@ class LlamaCppBackend:
root_bin = custom_dir / binary_name
if root_bin.is_file():
return str(root_bin)
- # build/bin/ (cmake builds on Linux)
+ # build/bin/ (cmake on Linux)
cmake_bin = custom_dir / "build" / "bin" / binary_name
if cmake_bin.is_file():
return str(cmake_bin)
- # build/bin/Release/ (cmake builds on Windows)
+ # build/bin/Release/ (cmake on Windows)
if sys.platform == "win32":
win_bin = custom_dir / "build" / "bin" / "Release" / binary_name
if win_bin.is_file():
@@ -999,10 +986,10 @@ class LlamaCppBackend:
if _is_legacy:
search_roots = [legacy_llama]
else:
- # why: _kill_orphaned_servers excludes the legacy root in custom
- # mode; discovery must match so we never spawn a server we then
- # refuse to clean up. UNSLOTH_LLAMA_CPP_PATH (handled earlier)
- # is the explicit way to share a build across roots.
+ # _kill_orphaned_servers excludes the legacy root in custom
+ # mode; discovery must match so we never spawn a server we
+ # then refuse to clean up. UNSLOTH_LLAMA_CPP_PATH (handled
+ # earlier) is the explicit way to share a build across roots.
search_roots = [_resolved_sr / "llama.cpp"]
except (ImportError, OSError, ValueError):
search_roots = [legacy_llama]
@@ -1025,7 +1012,7 @@ class LlamaCppBackend:
if home_win.is_file():
return str(home_win)
- # 5–6. Legacy: in-tree build (older setup.sh / setup.ps1 versions)
+ # 5-6. Legacy: in-tree build (older setup.sh / setup.ps1)
project_root = Path(__file__).resolve().parents[4]
# Root dir (make builds)
root_path = project_root / "llama.cpp" / binary_name
@@ -1063,17 +1050,17 @@ class LlamaCppBackend:
{found, mtp_token, supports_mtp, ngram_mod_flavor,
supports_ngram_mod, spec_draft_n_max_flag}.
- ``ngram_mod_flavor`` is ``"new"`` when the binary exposes the
- post-rename ``--spec-ngram-mod-n-match / -n-min / -n-max`` as
- real args, ``"legacy"`` when only the pre-rename
- ``--spec-ngram-size-n / --draft-min / --draft-max`` are real
- (the rename ships with stub removal entries for the legacy
- names; we tell stubs apart by the "argument has been removed"
- description), or ``None`` if neither set is usable.
-
- ``spec_draft_n_max_flag`` is the actual flag name the binary
- accepts: ``--spec-draft-n-max`` on post-rename builds, or
- ``--draft-max`` on legacy. ``None`` means n_max cannot be set.
+ ``ngram_mod_flavor``: ``"new"`` when the post-rename
+ ``--spec-ngram-mod-n-match / -n-min / -n-max`` are real args;
+ ``"legacy"`` when only the pre-rename
+ ``--spec-ngram-size-n / --draft-min / --draft-max`` are real (the
+ rename ships stub removal entries for legacy names, told apart by
+ the "argument has been removed" description); ``None`` if neither
+ set is usable.
+
+ ``spec_draft_n_max_flag``: the flag the binary accepts --
+ ``--spec-draft-n-max`` post-rename, ``--draft-max`` on legacy.
+ ``None`` means n_max cannot be set.
"""
bin_path = binary or cls._find_llama_server_binary()
if not bin_path or not Path(bin_path).is_file():
@@ -1106,9 +1093,9 @@ class LlamaCppBackend:
check = False,
)
help_text = (result.stdout or "") + "\n" + (result.stderr or "")
- # Split into per-flag blocks: each --flag line plus its
- # indented continuation lines, so the "argument has been
- # removed" description sits with its flag.
+ # Split into per-flag blocks (each --flag line + its indented
+ # continuation), so the "argument has been removed" description
+ # sits with its flag.
blocks: dict[str, str] = {}
current_flags: list[str] = []
current_desc: list[str] = []
@@ -1124,8 +1111,8 @@ class LlamaCppBackend:
current_desc = [stripped]
# Extract long-form flag tokens from the DECLARATION
# prefix only (comma-separated aliases). Stop at the
- # first token that isn't itself a flag, so flag
- # references inside descriptions are ignored.
+ # first non-flag token so flag references inside
+ # descriptions are ignored.
for tok in re.split(r"[,\s]+", stripped):
if tok.startswith("--") and re.match(r"--[A-Za-z][A-Za-z0-9_-]*$", tok):
current_flags.append(tok)
@@ -1149,7 +1136,7 @@ class LlamaCppBackend:
return False
return "argument has been removed" not in desc
- # MTP token detection from --spec-type line.
+ # MTP token from the --spec-type line.
spec_line = ""
for line in help_text.splitlines():
if "--spec-type" in line:
@@ -1161,9 +1148,9 @@ class LlamaCppBackend:
elif re.search(r"[|,\[]mtp[|,\]]", spec_line):
mtp_token = "mtp"
- # ngram-mod flag flavor. Post-rename builds advertise both
- # the new args (real) and the legacy ones (stubs); pre-rename
- # builds only have the legacy ones as real.
+ # ngram-mod flag flavor. Post-rename builds advertise both new
+ # args (real) and legacy ones (stubs); pre-rename builds only
+ # have legacy ones as real.
new_ngram_real = (
_is_real("--spec-ngram-mod-n-match")
and _is_real("--spec-ngram-mod-n-min")
@@ -1202,11 +1189,11 @@ class LlamaCppBackend:
@staticmethod
def _get_gguf_size_bytes(model_path: str) -> int:
- """Get total GGUF size in bytes, including split shards."""
+ """Total GGUF size in bytes, including split shards."""
main = Path(model_path)
total = main.stat().st_size
- # Check for split shards (e.g., model-00001-of-00003.gguf)
+ # Check for split shards (e.g. model-00001-of-00003.gguf)
m = _SHARD_FULL_RE.match(main.name)
if m:
prefix, _, num_total = m.group(1), m.group(2), m.group(3)
@@ -1222,9 +1209,10 @@ class LlamaCppBackend:
@staticmethod
def _amd_apu_wants_unified_memory() -> bool:
"""True only for AMD unified-memory APUs (gfx1150/gfx1151), where
- GGML_CUDA_ENABLE_UNIFIED_MEMORY lets llama.cpp use shared system RAM.
- False for discrete AMD, NVIDIA, CPU and macOS (the env hurts discrete
- GPUs). ROCm reuses torch.cuda.*; the gcnArchName suffix is stripped."""
+ GGML_CUDA_ENABLE_UNIFIED_MEMORY lets llama.cpp use shared system
+ RAM. False for discrete AMD, NVIDIA, CPU and macOS (the env hurts
+ discrete GPUs). ROCm reuses torch.cuda.*; gcnArchName suffix is
+ stripped."""
try:
import torch
@@ -1250,15 +1238,14 @@ class LlamaCppBackend:
Order:
1. ``nvidia-smi`` (NVIDIA CUDA hosts) -- respects
``CUDA_VISIBLE_DEVICES``.
- 2. ``torch.cuda.mem_get_info`` -- universal fallback that
- works on AMD ROCm too because the HIP runtime
- reuses the entire ``torch.cuda.*`` namespace. Covers the
- AMD case for issue #5106 (nvidia-smi-only probe silently
- returned [] on AMD hosts) and also rescues NVIDIA hosts
- where ``nvidia-smi`` is missing from PATH.
-
- Returns list of (gpu_index, free_mib) sorted by index. Empty
- list if no supported GPU is reachable.
+ 2. ``torch.cuda.mem_get_info`` -- universal fallback that works
+ on AMD ROCm too (HIP runtime reuses the ``torch.cuda.*``
+ namespace). Covers the AMD case for issue #5106 (nvidia-smi
+ probe returned [] on AMD) and NVIDIA hosts missing
+ ``nvidia-smi`` from PATH.
+
+ Returns list of (gpu_index, free_mib) sorted by index; empty if no
+ supported GPU is reachable.
"""
# ── NVIDIA via nvidia-smi ────────────────────────────────────
try:
@@ -1280,10 +1267,10 @@ class LlamaCppBackend:
if cvd is not None:
try:
# `if x.strip()` filters trailing-comma masks like
- # "0,1," which would otherwise raise ValueError on
- # an empty token. An explicitly empty mask (CVD="")
- # yields an empty `allowed` set so all GPUs are
- # filtered out, matching the codebase convention.
+ # "0,1," that would raise ValueError on an empty
+ # token. An empty mask (CVD="") yields an empty
+ # `allowed` set so all GPUs are filtered out, per
+ # the codebase convention.
allowed = set(int(x.strip()) for x in cvd.split(",") if x.strip())
except ValueError:
pass
@@ -1296,9 +1283,8 @@ class LlamaCppBackend:
if allowed is not None and idx not in allowed:
continue
gpus.append((idx, free_mib))
- # Match the docstring's sort-by-id guarantee. nvidia-smi
- # almost always returns sorted output, but driver order
- # is not formally guaranteed.
+ # Match the docstring's sort-by-id guarantee; nvidia-smi
+ # output is usually sorted but driver order isn't guaranteed.
gpus.sort(key = lambda g: g[0])
if gpus:
return gpus
@@ -1313,20 +1299,18 @@ class LlamaCppBackend:
return []
if not hasattr(torch.cuda, "mem_get_info"):
return []
- # torch.cuda enumerates GPUs RELATIVE to the visibility mask.
- # On NVIDIA builds the mask is CUDA_VISIBLE_DEVICES; on AMD
- # ROCm builds it is HIP_VISIBLE_DEVICES (or ROCR_VISIBLE_DEVICES
- # if HIP is unset). Downstream we feed these IDs back into the
- # llama-server subprocess as CVD, so we must translate visible
- # ordinals back to physical indices first; otherwise launching
- # with ``CUDA_VISIBLE_DEVICES=2,3`` would get rewritten to
- # ``CUDA_VISIBLE_DEVICES=0,1`` and target the wrong GPUs.
+ # torch.cuda enumerates GPUs RELATIVE to the visibility mask
+ # (CUDA_VISIBLE_DEVICES on NVIDIA; HIP_VISIBLE_DEVICES, or
+ # ROCR_VISIBLE_DEVICES if HIP unset, on AMD ROCm). We feed
+ # these IDs back into the subprocess as CVD, so visible
+ # ordinals must be translated to physical indices first;
+ # otherwise ``CUDA_VISIBLE_DEVICES=2,3`` gets rewritten to
+ # ``0,1`` and targets the wrong GPUs.
physical_ids: Optional[list[int]] = None
- # Match the codebase convention in
- # ``utils/hardware/hardware.py::_get_parent_visible_gpu_spec``:
- # treat an explicitly empty mask (``HIP_VISIBLE_DEVICES=""``)
- # as "set to no GPUs" rather than falling through to the next
- # var. ``or`` would coerce empty string to falsy and silently
+ # Match ``utils/hardware/hardware.py::
+ # _get_parent_visible_gpu_spec``: treat an empty mask
+ # (``HIP_VISIBLE_DEVICES=""``) as "no GPUs" rather than falling
+ # through to the next var. ``or`` would coerce "" to falsy and
# promote the wrong source.
if getattr(torch.version, "hip", None) is not None:
hip_v = os.environ.get("HIP_VISIBLE_DEVICES")
@@ -1342,9 +1326,9 @@ class LlamaCppBackend:
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
if cvd is not None:
try:
- # Empty mask (CVD="") yields an empty list so the
- # below loop produces no GPUs, consistent with the
- # nvidia-smi path and utils/hardware/hardware.py.
+ # Empty mask (CVD="") yields an empty list so the loop
+ # produces no GPUs, consistent with the nvidia-smi path
+ # and utils/hardware/hardware.py.
physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
except ValueError:
physical_ids = None
@@ -1363,8 +1347,8 @@ class LlamaCppBackend:
logger.debug(f"torch GPU probe failed: {e}")
return []
- # Skip the wait when the last kill is older than this; the GPU
- # driver has already reclaimed the prior process's allocations.
+ # Skip the wait when the last kill is older than this; the driver has
+ # already reclaimed the prior process's allocations.
_VRAM_SETTLE_WINDOW_S: float = 15.0
@staticmethod
@@ -1376,18 +1360,17 @@ class LlamaCppBackend:
) -> None:
"""Poll ``_get_gpu_free_memory`` until free VRAM stabilises.
- The GPU driver reclaims a dead process's allocations
- asynchronously, so sampling free memory in the kill-to-spawn
- window reads artificially low and pushes ``_select_gpus`` /
- ``_fit_context_to_vram`` toward needless CPU offload -- on a
- tight VRAM card this is the Apply-reload OOM that bare-shell
- launches with the same flags never see.
-
- Short-circuits on cold start (``since_kill`` zero) or stale
- kill (older than ``_VRAM_SETTLE_WINDOW_S``); also on CPU-only
- hosts (empty probe), probe exceptions, and GPU-set changes.
- ``max_wait`` is a wall-clock bound that includes probe time,
- so a wedged ``nvidia-smi`` cannot extend the reload.
+ The driver reclaims a dead process's allocations asynchronously, so
+ sampling free memory in the kill-to-spawn window reads artificially
+ low and pushes ``_select_gpus`` / ``_fit_context_to_vram`` toward
+ needless CPU offload -- on a tight VRAM card, the Apply-reload OOM
+ that bare-shell launches with the same flags never see.
+
+ Short-circuits on cold start (``since_kill`` zero), stale kill
+ (older than ``_VRAM_SETTLE_WINDOW_S``), CPU-only hosts (empty
+ probe), probe exceptions, and GPU-set changes. ``max_wait`` is a
+ wall-clock bound including probe time, so a wedged ``nvidia-smi``
+ cannot extend the reload.
"""
now = time.monotonic()
if since_kill <= 0.0:
@@ -1423,8 +1406,8 @@ class LlamaCppBackend:
stable = False
break
prev_free = prev_map[idx]
- # Adaptive: 2 % of the larger sample dominates the
- # 256 MiB floor on large-VRAM cards.
+ # Adaptive: 2% of the larger sample dominates the 256 MiB
+ # floor on large-VRAM cards.
per_gpu_tol = max(tolerance_mib, int(max(free, prev_free) * 0.02))
if abs(free - prev_free) >= per_gpu_tol:
stable = False
@@ -1433,11 +1416,10 @@ class LlamaCppBackend:
return
prev = curr
- # Free-VRAM fraction at which Studio pins the GPU directly instead
- # of deferring to ``--fit on``. 5% headroom covers CUDA context +
- # compute buffers; 0.90 was too conservative and dropped 91-94%
- # fits to CPU offload (#5106). The fork's --fit on still catches
- # the truly-too-large case.
+ # Free-VRAM fraction at which Studio pins the GPU directly instead of
+ # deferring to ``--fit on``. 5% headroom covers CUDA context + compute
+ # buffers; 0.90 was too conservative, dropping 91-94% fits to CPU
+ # offload (#5106). --fit on still catches the truly-too-large case.
_GPU_PIN_VRAM_FRACTION = 0.95
@staticmethod
@@ -1445,28 +1427,25 @@ class LlamaCppBackend:
"""Return DLL dirs from pip-installed CUDA wheels under
``<prefix>/Lib/site-packages/`` so llama-server.exe can load
``cudart64_X.dll`` / ``cublas64_X.dll`` without a system CUDA
- toolkit. Mirrors the Linux ``nvidia/cu*/lib`` LD_LIBRARY_PATH
- block, with parity for the Windows-specific wheel layouts seen
- in the wild. Covered patterns:
+ toolkit. Mirrors the Linux ``nvidia/cu*/lib`` LD_LIBRARY_PATH block,
+ with parity for the Windows wheel layouts seen in the wild:
* ``nvidia/<pkg>/bin`` -- legacy modular wheels
(``nvidia-cuda-runtime-cu12``, ``nvidia-cublas-cu12``, etc.).
* ``nvidia/<pkg>/bin/x86_64`` and ``.../bin/x64`` -- current
- CUDA 13 wheel layout used by the unsuffixed
- ``nvidia-cuda-runtime`` / ``nvidia-cublas`` packages, which
- ship under ``nvidia/cu13/bin/x86_64/`` (#5106).
- * ``nvidia/<pkg>/Library/bin`` (and arch subdirs) -- conda-
- style wheel repacks.
- * ``torch/lib`` -- PyTorch's own CUDA-bundled Windows wheel,
- which can ship ``cudart64_*.dll`` directly here instead of
- as separate ``nvidia-*`` wheels. The install-side helper
- ``python_runtime_dirs`` in ``install_llama_prebuilt.py``
- covers this path for the same reason.
-
- Walks the tree with ``Path.iterdir`` rather than ``glob.glob``
- so the resolver is safe against Windows paths containing
- ``[`` or ``]`` (valid in usernames; would otherwise be
- interpreted as a glob character class and silently miss
- existing dirs)."""
+ CUDA 13 layout for the unsuffixed ``nvidia-cuda-runtime`` /
+ ``nvidia-cublas`` packages (under ``nvidia/cu13/bin/x86_64/``)
+ (#5106).
+ * ``nvidia/<pkg>/Library/bin`` (and arch subdirs) -- conda-style
+ wheel repacks.
+ * ``torch/lib`` -- PyTorch's CUDA-bundled Windows wheel can ship
+ ``cudart64_*.dll`` here instead of as separate ``nvidia-*``
+ wheels. The install-side ``python_runtime_dirs`` in
+ ``install_llama_prebuilt.py`` covers this for the same reason.
+
+ Walks the tree with ``Path.iterdir`` rather than ``glob.glob`` so
+ it's safe against Windows paths containing ``[`` or ``]`` (valid in
+ usernames; otherwise read as a glob character class, silently
+ missing existing dirs)."""
site_packages = Path(prefix) / "Lib" / "site-packages"
out: list[str] = []
seen: set[str] = set()
@@ -1485,9 +1464,8 @@ class LlamaCppBackend:
for pkg_dir in nvidia_root.iterdir():
if not pkg_dir.is_dir():
continue
- # Order matters for PATH search: arch-specific subdirs
- # first so the explicit cudart64_X.dll location wins
- # over a sibling ``bin`` that might be empty.
+ # Order matters: arch-specific subdirs first so the explicit
+ # cudart64_X.dll location wins over an empty sibling ``bin``.
for sub in (
pkg_dir / "bin" / "x86_64",
pkg_dir / "bin" / "x64",
@@ -1505,7 +1483,7 @@ class LlamaCppBackend:
"""Ordered PATH entries the win32 branch of start_llama_server
prepends so llama-server.exe resolves cudart / cublas DLLs:
binary_dir, pip nvidia wheels, CUDA_PATH/bin, CUDA_PATH/bin/x64.
- Extracted so test_windows_gpu_detection_mock asserts against
+ Extracted so test_windows_gpu_detection_mock asserts against the
production logic, not a hand-copy. #5106."""
path_dirs = [binary_dir]
path_dirs.extend(LlamaCppBackend._windows_pip_nvidia_dll_dirs(prefix))
@@ -1522,16 +1500,16 @@ class LlamaCppBackend:
def _select_gpus(
model_size_bytes: int, gpus: list[tuple[int, int]]
) -> tuple[Optional[list[int]], bool]:
- """Pick GPU(s) for a model based on estimated VRAM and free memory.
+ """Pick GPU(s) for a model from estimated VRAM and free memory.
- ``model_size_bytes`` should include both model weights and estimated
- KV cache. The ``_GPU_PIN_VRAM_FRACTION`` threshold provides headroom
- for compute buffers, CUDA context, and other runtime overhead.
+ ``model_size_bytes`` should include weights and estimated KV cache.
+ ``_GPU_PIN_VRAM_FRACTION`` provides headroom for compute buffers,
+ CUDA context, and other runtime overhead.
Returns (gpu_indices, use_fit):
- - ([1], False) model fits on 1 GPU at the headroom threshold
- - ([1, 2], False) model needs 2 GPUs
- - (None, True) model too large, let --fit handle it
+ - ([1], False) fits on 1 GPU at the headroom threshold
+ - ([1, 2], False) needs 2 GPUs
+ - (None, True) too large, let --fit handle it
"""
if not gpus:
return None, True
@@ -1542,11 +1520,11 @@ class LlamaCppBackend:
# Sort GPUs by free memory descending
ranked = sorted(gpus, key = lambda g: g[1], reverse = True)
- # Try fitting on 1 GPU at the usable-VRAM threshold.
+ # Try 1 GPU at the usable-VRAM threshold.
if ranked[0][1] * usable_fraction >= model_size_mib:
return [ranked[0][0]], False
- # Try fitting on N GPUs (accumulate free memory from most-free)
+ # Try N GPUs (accumulate free memory from most-free)
cumulative = 0
selected = []
for idx, free_mib in ranked:
@@ -1555,7 +1533,7 @@ class LlamaCppBackend:
if cumulative >= model_size_mib:
return sorted(selected), False
- # Model is too large even for all GPUs, let --fit handle it
+ # Too large even for all GPUs; let --fit handle it
logger.debug(
"Model does not fit in available GPU memory, falling back to --fit",
model_size_mib = round(model_size_mib, 2),
@@ -1569,10 +1547,10 @@ class LlamaCppBackend:
"""True if we have enough GGUF metadata to estimate KV cache size."""
if self._n_layers is None:
return False
- # MLA: kv_lora_rank is sufficient (K-only cache)
+ # MLA: kv_lora_rank suffices (K-only cache)
if self._kv_lora_rank is not None:
return True
- # New-style: need both explicit key AND value dimensions
+ # New-style: need explicit key AND value dimensions
if self._kv_key_length is not None and self._kv_value_length is not None:
return True
# Legacy: need embedding_length + a head count (scalar or per-layer).
@@ -1599,7 +1577,7 @@ class LlamaCppBackend:
) -> int:
"""Estimate KV cache VRAM for a given context length.
- Uses 5-path architecture-aware estimation:
+ 5-path architecture-aware estimation:
1. MLA -- compressed KV latent + RoPE, K-only (no separate V)
2. Hybrid -- only attention layers need KV (Mamba layers don't)
3. SWA -- sliding-window layers cache min(ctx, window) tokens
@@ -1609,29 +1587,28 @@ class LlamaCppBackend:
Server-flag knobs (mirror llama-server's CLI):
swa_full -- ``--swa-full``: force SWA layers to cache the
full ``n_ctx`` (collapses path 3 to path 4
- sizing for the SWA layers).
- n_parallel -- ``--parallel``: number of server slots.
- Verified empirically against llama-server:
- non-SWA layers stay constant (cells split
- across slots), SWA layers scale linearly
- (per-slot window).
- kv_unified -- ``--kv-unified`` (default on): retained for
- API forward-compat. Currently a no-op for
- memory math because the unified buffer total
- matches per-slot buffers in measured cases.
- ctx_checkpoints -- ``--ctx-checkpoints``: SWA snapshot count per
- slot (PR #15293). Each snapshot stores one
- sliding-window of state per SWA layer.
-
- Returns 0 if metadata is insufficient for estimation.
+ for SWA layers).
+ n_parallel -- ``--parallel``: server slots. Verified against
+ llama-server: non-SWA layers stay constant
+ (cells split across slots), SWA layers scale
+ linearly (per-slot window).
+ kv_unified -- ``--kv-unified`` (default on): kept for API
+ forward-compat. A no-op for memory math; the
+ unified buffer total matches per-slot buffers
+ in measured cases.
+ ctx_checkpoints -- ``--ctx-checkpoints``: SWA snapshots per slot
+ (PR #15293). Each stores one sliding-window of
+ state per SWA layer.
+
+ Returns 0 if metadata is insufficient.
"""
if not self._can_estimate_kv() or n_ctx <= 0:
return 0
n_layers = self._n_layers # type: ignore[assignment]
- # Gemma 3n / Gemma 4 reuse KV from earlier layers in the last
- # ``shared_kv_layers`` blocks -- those don't allocate their own
- # cache. Floor at 1 so a misconfigured GGUF can't zero out KV.
+ # Gemma 3n / Gemma 4 reuse earlier layers' KV in the last
+ # ``shared_kv_layers`` blocks -- those allocate no cache. Floor at 1
+ # so a misconfigured GGUF can't zero out KV.
shared = self._shared_kv_layers or 0
n_layers_kv = max(1, n_layers - shared)
n_kv = self._n_kv_heads or self._n_heads or 1 # type: ignore[assignment]
@@ -1652,11 +1629,11 @@ class LlamaCppBackend:
slots = max(1, n_parallel)
# Path 1: MLA (DeepSeek-V2/V3, GLM-4.7, GLM-5, Kimi-K2.5)
- # MLA stores one compressed KV latent per token/layer (shared across heads).
- # V is reconstructed from the latent on the fly -- no separate V cache.
- # key_length = kv_lora_rank + rope_dim (the full compressed representation).
+ # Stores one compressed KV latent per token/layer (shared across
+ # heads); V is reconstructed from the latent, no separate V cache.
+ # key_length = kv_lora_rank + rope_dim (full compressed rep).
# MLA GGUFs set head_count_kv=1; default to 1 if absent to avoid
- # falling back to n_heads (e.g., 128 for DeepSeek-V3) which would 128x.
+ # falling back to n_heads (e.g. 128 for DeepSeek-V3) which 128x's.
if self._kv_lora_rank is not None:
n_kv_mla = self._n_kv_heads or 1
rope_dim = self._key_length_mla or 64
@@ -1667,7 +1644,7 @@ class LlamaCppBackend:
val_len = self._kv_value_length
# Path 2: Hybrid Mamba/Attention (Qwen3.5-27B, Qwen3.5-35B-A3B)
- # Only 1 in N layers is attention; the rest are Mamba (no KV cache).
+ # Only 1 in N layers is attention; rest are Mamba (no KV cache).
if self._ssm_inner_size is not None and self._full_attention_interval is not None:
fai = self._full_attention_interval
n_attn = -(-n_layers // fai) if fai > 0 else n_layers # ceiling division
@@ -1677,16 +1654,16 @@ class LlamaCppBackend:
return int(n_attn * n_ctx * n_kv * 2 * head_dim * bpe)
# Path 3: Sliding window (Gemma 2/3/3n/4, gpt-oss, Cohere2 ...).
- # Pattern is filled in by the resolver at parse time; if absent,
- # falls through to the legacy 1/4-global heuristic below.
- # Per-layer-type ``--parallel N`` accounting (verified empirically
- # against ``llama-server``):
+ # Pattern filled in by the resolver at parse time; if absent, falls
+ # through to the legacy 1/4-global heuristic below.
+ # Per-layer-type ``--parallel N`` accounting (verified against
+ # ``llama-server``):
# * non-SWA layers: total cells = n_ctx, partitioned across
# slots -> total memory CONSTANT in slots.
# * SWA layers: per-slot cells = 2 * sliding_window
- # (capped at n_ctx and at per_slot_ctx
- # when ctx is split among many slots) ->
- # total memory grows LINEARLY in slots.
+ # (capped at n_ctx and at per_slot_ctx when
+ # ctx is split among slots) -> total memory
+ # grows LINEARLY in slots.
# ``--swa-full`` forces full n_ctx for SWA layers instead.
# ``--ctx-checkpoints N`` adds N snapshots per SWA layer per slot.
if (
@@ -1697,11 +1674,11 @@ class LlamaCppBackend:
):
swa = self._sliding_window
per_slot_ctx = max(1, n_ctx // slots)
- # ``--swa-full`` makes SWA layers cache the full context just
- # like non-SWA: cells get partitioned across slots, so per-slot
- # cells = per_slot_ctx and the slots*per-slot product collapses
- # back to the constant ``n_ctx`` total. Otherwise SWA caches
- # 2*sliding_window per slot, clamped at the per-slot ctx.
+ # ``--swa-full`` makes SWA layers cache the full context like
+ # non-SWA: cells partitioned across slots, so per-slot cells =
+ # per_slot_ctx and slots*per-slot collapses to the constant
+ # ``n_ctx`` total. Otherwise SWA caches 2*sliding_window per
+ # slot, clamped at the per-slot ctx.
swa_cells_per_slot = per_slot_ctx if swa_full else min(n_ctx, 2 * swa, per_slot_ctx)
key_len_swa = self._kv_key_length_swa or key_len
val_len_swa = self._kv_value_length_swa or val_len
@@ -1709,8 +1686,8 @@ class LlamaCppBackend:
global_bytes = 0.0 # constant across slots
swa_bytes_per_slot = 0.0 # multiplied by slots
checkpoint_extra_per_slot = 0.0
- # Iterate only over layers that allocate their own KV;
- # the trailing ``shared`` layers reuse earlier caches.
+ # Only layers that allocate their own KV; trailing ``shared``
+ # layers reuse earlier caches.
for layer_idx in range(n_layers_kv):
layer_n_kv = self._kv_heads_for_layer(layer_idx, n_kv)
is_swa = (
@@ -1770,22 +1747,21 @@ class LlamaCppBackend:
) -> int:
"""Return the largest context length that fits in GPU VRAM.
- Uses 90% of available VRAM as the ctx-fit budget. Tighter than
- ``_GPU_PIN_VRAM_FRACTION`` on purpose: over-promising context
- OOMs at runtime, while pinning conservatively just defers to
- --fit on. If the weights alone don't fit, returns
- ``requested_ctx`` unchanged.
+ Uses 90% of available VRAM as the ctx-fit budget -- tighter than
+ ``_GPU_PIN_VRAM_FRACTION`` on purpose: over-promising context OOMs
+ at runtime, while pinning conservatively just defers to --fit on. If
+ the weights alone don't fit, returns ``requested_ctx`` unchanged.
- ``kv_on_gpu`` mirrors ``--kv-offload`` (default on). When False
- the KV cache lives in CPU RAM and doesn't compete with weights
- for VRAM; the requested context is honored verbatim. The other
- keyword args mirror ``_estimate_kv_cache_bytes``.
+ ``kv_on_gpu`` mirrors ``--kv-offload`` (default on). When False the
+ KV cache lives in CPU RAM and doesn't compete with weights for VRAM;
+ the requested context is honored verbatim. Other keyword args mirror
+ ``_estimate_kv_cache_bytes``.
- ``mtp_engaged`` reserves extra VRAM for the MTP draft model's
- KV cache + compute graph buffers. llama.cpp's MTP path keeps a
+ ``mtp_engaged`` reserves extra VRAM for the MTP draft model's KV
+ cache + compute graph buffers. llama.cpp's MTP path keeps a
secondary cache sized off the target's KV; on tight VRAM tiers
- (e.g. 32 GB) auto-fit at native context would otherwise spill
- and force llama-server into a slower partial-offload path.
+ (e.g. 32 GB) auto-fit at native context would otherwise spill and
+ force a slower partial-offload path.
"""
if not self._can_estimate_kv():
logger.debug(
@@ -1811,13 +1787,13 @@ class LlamaCppBackend:
budget_bytes = available_mib * 1024 * 1024 * budget_frac
model_footprint = model_size_bytes
- # Check if requested context already fits
+ # Already fits?
kv = self._estimate_kv_cache_bytes(requested_ctx, cache_type_kv, **kv_kwargs)
if model_footprint + kv <= budget_bytes:
return requested_ctx
- # Model weights alone exceed budget -- can't help by reducing ctx.
- # Return requested_ctx unchanged; --fit will handle VRAM management.
+ # Weights alone exceed budget -- reducing ctx can't help. Return
+ # requested_ctx unchanged; --fit will handle VRAM management.
if model_footprint >= budget_bytes:
logger.debug(
"Model footprint exceeds GPU budget before KV cache",
@@ -1841,7 +1817,7 @@ class LlamaCppBackend:
else:
hi = mid - 1
- # Round down to nearest 256 for alignment, but never exceed requested_ctx
+ # Round down to nearest 256 for alignment, never above requested_ctx
best = (best // 256) * 256
best = max(effective_min, best)
best = min(best, requested_ctx)
@@ -1857,10 +1833,10 @@ class LlamaCppBackend:
) -> Optional[tuple[str, int]]:
"""Find the smallest GGUF variant (including all shards) that fits.
- Groups split shards by variant prefix and sums their sizes.
- For example, UD-Q4_K_XL with 9 shards of 50 GB each = 450 GB total.
+ Groups split shards by variant prefix and sums their sizes (e.g.
+ UD-Q4_K_XL with 9 shards of 50 GB each = 450 GB total).
- Returns (first_shard_filename, total_size_bytes) or None if nothing fits.
+ Returns (first_shard_filename, total_size_bytes) or None.
"""
try:
from huggingface_hub import get_paths_info, list_repo_files
@@ -1870,11 +1846,11 @@ class LlamaCppBackend:
if not gguf_files:
return None
- # Get sizes for all GGUF files
+ # Sizes for all GGUF files
path_infos = list(get_paths_info(hf_repo, gguf_files, token = hf_token))
size_map = {p.path: (p.size or 0) for p in path_infos}
- # Group files by variant: shards share a prefix before -NNNNN-of-NNNNN
+ # Group by variant: shards share a prefix before -NNNNN-of-NNNNN
variants: dict[str, list[str]] = {}
for f in gguf_files:
m = _SHARD_RE.match(f)
@@ -1888,7 +1864,7 @@ class LlamaCppBackend:
first = sorted(shard_files)[0]
variant_sizes.append((first, total, shard_files))
- # Sort by total size ascending and pick the smallest that fits
+ # Smallest that fits
variant_sizes.sort(key = lambda x: x[1])
for first_file, total_size, _ in variant_sizes:
if total_size > 0 and total_size <= free_bytes:
@@ -1911,16 +1887,15 @@ class LlamaCppBackend:
def _drain_stdout(self):
"""
- Read lines from the subprocess stdout in a background thread.
+ Read subprocess stdout lines in a background thread.
- This prevents a pipe-buffer deadlock on Windows where the default
- pipe buffer is only ~4 KB. Without draining, llama-server blocks
- on writes and never becomes healthy.
+ Prevents a pipe-buffer deadlock on Windows (default buffer ~4 KB):
+ without draining, llama-server blocks on writes and never becomes
+ healthy.
- Each line is also teed to ``self._llama_log_fh`` when set so a
- post-mortem (especially in CI) has the full subprocess output
- even if the crash predates the drain-thread join in
- ``_wait_for_health``.
+ Each line is also teed to ``self._llama_log_fh`` when set, so a
+ post-mortem (especially in CI) has the full output even if the crash
+ predates the drain-thread join in ``_wait_for_health``.
"""
try:
for line in self._process.stdout:
@@ -1937,7 +1912,7 @@ class LlamaCppBackend:
# Log file closed under us; tee silently.
pass
except (ValueError, OSError):
- # Pipe closed — process is terminating
+ # Pipe closed -- process terminating
pass
# GGUF KV type sizes for fast skipping
@@ -1997,8 +1972,8 @@ class LlamaCppBackend:
Parses only the KV pairs we need (~30ms even for multi-GB files).
For split GGUFs, metadata is always in shard 1.
"""
- # Reset metadata from any previously loaded model so stale flags
- # (eg _supports_reasoning) do not carry over when switching models.
+ # Reset metadata so stale flags (e.g. _supports_reasoning) don't
+ # carry over when switching models.
self._context_length = None
self._chat_template = None
self._supports_reasoning = False
@@ -2042,8 +2017,7 @@ class LlamaCppBackend:
"general.size_label",
"general.finetune",
}
- # Additional arch-specific keys are added dynamically once
- # we know the architecture name.
+ # Arch-specific keys added dynamically once we know the arch.
arch_keys: dict[str, str] = {} # gguf_key -> attribute name
arch = None
sliding_window_pattern_period: Optional[int] = None
@@ -2057,10 +2031,9 @@ class LlamaCppBackend:
_tensor_count, kv_count = struct.unpack("<QQ", f.read(16))
for _ in range(kv_count):
- # Tolerate truncated input (e.g., a partial header
- # fetched via HTTP byte-range): bail out gracefully
- # so the resolver fallback still runs on whatever
- # we did manage to parse.
+ # Tolerate truncated input (e.g. a partial header from an
+ # HTTP byte-range fetch): bail out so the resolver
+ # fallback runs on whatever we parsed.
try:
key_len_bytes = f.read(8)
if len(key_len_bytes) < 8:
@@ -2137,9 +2110,9 @@ class LlamaCppBackend:
else:
self._gguf_skip_value(f, vtype)
except (struct.error, UnicodeDecodeError):
- # Truncated input (e.g., HTTP byte-range fetch
- # of just the GGUF header); break so the
- # resolver fallback still runs on what we have.
+ # Truncated input (e.g. HTTP byte-range header
+ # fetch); break so the resolver fallback runs on
+ # what we have.
break
# Expand a scalar period straight from the GGUF first.
@@ -2153,7 +2126,7 @@ class LlamaCppBackend:
]
# Otherwise hand off to the resolver (cache / bootstrap /
- # transformers / HF). See `_resolve_swa_pattern`.
+ # transformers / HF); see `_resolve_swa_pattern`.
if self._sliding_window_pattern is None and self._sliding_window and self._n_layers:
hf_repo_candidates = (
general.get("general.source.huggingface.repository"),
@@ -2184,7 +2157,7 @@ class LlamaCppBackend:
logger.info(f"GGUF metadata: context_length={self._context_length}")
if self._chat_template:
logger.info(f"GGUF metadata: chat_template={len(self._chat_template)} chars")
- # Detect thinking/reasoning support from chat template
+ # Detect thinking/reasoning support from chat template.
flags = detect_reasoning_flags(
self._chat_template,
self._model_identifier,
@@ -2209,9 +2182,8 @@ class LlamaCppBackend:
) -> str:
"""Download GGUF file(s) from HuggingFace. Returns local path.
- Runs WITHOUT self._lock so that unload_model() can set
- _cancel_event at any time. Checks _cancel_event between
- each shard download.
+ Runs WITHOUT self._lock so unload_model() can set _cancel_event at
+ any time; checks it between each shard download.
"""
try:
from huggingface_hub import hf_hub_download
@@ -2221,7 +2193,7 @@ class LlamaCppBackend:
"Install it with: pip install huggingface_hub"
)
- # Determine the filename from the variant
+ # Resolve the filename from the variant
gguf_filename = None
gguf_extra_shards: list[str] = []
if hf_variant:
@@ -2250,10 +2222,10 @@ class LlamaCppBackend:
logger.warning(f"Could not list repo files: {e}")
# Offline: resolve variant -> filename from the local HF cache.
- # The heuristic below assumes filenames echo the repo name,
- # which breaks for e.g. Qwen3.6-27B-MTP-GGUF (no "MTP" in file).
- # Match against the rel path (not just basename) so subdir
- # layouts like ``BF16/foo.gguf`` are findable.
+ # The heuristic below assumes filenames echo the repo name, which
+ # breaks for e.g. Qwen3.6-27B-MTP-GGUF (no "MTP" in file). Match
+ # against the rel path (not just basename) so subdir layouts like
+ # ``BF16/foo.gguf`` are findable.
if not gguf_filename:
try:
from utils.models.model_config import _iter_hf_cache_snapshots
@@ -2297,7 +2269,7 @@ class LlamaCppBackend:
repo_name = hf_repo.split("/")[-1].replace("-GGUF", "")
gguf_filename = f"{repo_name}-{hf_variant}.gguf"
- # Check disk space and fall back to a smaller variant if needed
+ # Check disk space; fall back to a smaller variant if needed
all_gguf_files = [gguf_filename] + gguf_extra_shards
try:
from huggingface_hub import get_paths_info, try_to_load_from_cache
@@ -2305,11 +2277,11 @@ class LlamaCppBackend:
path_infos = list(get_paths_info(hf_repo, all_gguf_files, token = hf_token))
total_bytes = sum((p.size or 0) for p in path_infos)
- # Subtract bytes already present in the HF cache so we only
- # preflight against what we actually have to download. Without
- # this, re-loading a cached large model (e.g. MiniMax-M2.7-GGUF
- # at 131 GB) fails cold whenever free disk is below the full
- # weight footprint, even though nothing needs downloading.
+ # Subtract bytes already in the HF cache so we only preflight
+ # against what we must download. Without this, re-loading a
+ # cached large model (e.g. MiniMax-M2.7-GGUF at 131 GB) fails
+ # cold whenever free disk is below the full weight footprint,
+ # even though nothing needs downloading.
already_cached_bytes = 0
for p in path_infos:
if not p.size:
@@ -2323,7 +2295,7 @@ class LlamaCppBackend:
on_disk = os.path.getsize(cached_path)
except OSError:
on_disk = 0
- # Count as satisfied only when the full blob is present.
+ # Satisfied only when the full blob is present.
if on_disk >= p.size:
already_cached_bytes += p.size
@@ -2430,8 +2402,8 @@ class LlamaCppBackend:
) -> Optional[str]:
"""Download the mmproj (vision projection) file from a GGUF repo.
- Prefers mmproj-F16.gguf, falls back to any mmproj*.gguf file.
- Returns the local path, or None if no mmproj file exists.
+ Prefers mmproj-F16.gguf, else any mmproj*.gguf. Returns the local
+ path, or None if none exists.
"""
def _pick_mmproj(candidates: list[str]) -> Optional[str]:
@@ -2454,8 +2426,8 @@ class LlamaCppBackend:
except Exception as e:
logger.debug(f"Could not list repo files for mmproj: {e}")
- # Offline: resolve mmproj from the local HF cache snapshot, same
- # shape as _download_gguf's offline fallback above.
+ # Offline: resolve mmproj from the local HF cache snapshot, same as
+ # _download_gguf's offline fallback above.
if target is None:
try:
from utils.models.model_config import _iter_hf_cache_snapshots
@@ -2490,7 +2462,7 @@ class LlamaCppBackend:
) -> Optional[str]:
"""Return mmproj_path iff it exists on disk AND matches the model family.
- Returns None if mmproj_path is None, missing on disk, or family-mismatched.
+ None if mmproj_path is None, missing, or family-mismatched.
"""
if not mmproj_path:
return None
@@ -2519,8 +2491,8 @@ class LlamaCppBackend:
# the patched stable-diffusion.cpp / ComfyUI-GGUF enums (LLM_ARCH_FLUX,
# LLM_ARCH_QWEN_IMAGE, ...). Unsloth publishes FLUX and Qwen-Image GGUFs
# under https://huggingface.co/collections/unsloth/unsloth-diffusion-ggufs.
- # Matched exactly (not as a substring) so a chat arch merely containing a
- # short token like "wan"/"sd1" (e.g. "taiwan") is not misrouted to Images.
+ # Matched exactly (not a substring) so a chat arch merely containing a
+ # short token like "wan"/"sd1" (e.g. "taiwan") isn't misrouted to Images.
_DIFFUSION_ARCHES = frozenset(
(
"qwen_image",
@@ -2544,13 +2516,13 @@ class LlamaCppBackend:
) -> str:
"""Explain *why* llama-server failed to start, from its output.
- Several distinct failures all otherwise collapse into the same
- opaque "invalid GGUF or out of memory" message. The worst case is
- a diffusion / image GGUF (FLUX, Qwen-Image, ...) loaded as a chat
- model: the file is perfectly valid and there is plenty of memory,
- but llama.cpp has no such architecture, so the user is told to free
- memory that was never the problem (issue #5842). Pick the most
- specific message the captured output supports.
+ Several distinct failures otherwise collapse into the same opaque
+ "invalid GGUF or out of memory" message. Worst case: a diffusion /
+ image GGUF (FLUX, Qwen-Image, ...) loaded as a chat model -- the
+ file is valid and memory is plentiful, but llama.cpp has no such
+ architecture, so the user is told to free memory that was never the
+ problem (issue #5842). Pick the most specific message the captured
+ output supports.
"""
lowered = (output or "").lower()
@@ -2566,7 +2538,7 @@ class LlamaCppBackend:
# "unknown model architecture: '<arch>'": diffusion -> Images page,
# Ollama -> Ollama hint, else a precise "unsupported" message. Exact
- # match so chat archs are never misrouted.
+ # match so chat archs aren't misrouted.
arch_match = re.search(r"unknown model architecture:\s*'([^']+)'", lowered)
if arch_match:
arch = arch_match.group(1)
@@ -2589,7 +2561,7 @@ class LlamaCppBackend:
"be run with llama-server."
)
- # Other Ollama compat failures that do not name an arch. Only when
+ # Other Ollama compat failures that don't name an arch. Only when
# the output shows a GGUF compat issue, not OOM / missing binaries.
if is_ollama:
gguf_compat_hints = (
@@ -2604,7 +2576,7 @@ class LlamaCppBackend:
"Ollama instead."
)
- # Fallback: genuinely unknown failure (OOM, missing binary, ...).
+ # Fallback: genuinely unknown failure (OOM, missing binary ...).
return (
"llama-server failed to start. "
"Check that the GGUF file is valid and you have enough memory."
@@ -2630,7 +2602,7 @@ class LlamaCppBackend:
speculative_type: Optional[str] = None,
spec_draft_n_max: Optional[int] = None,
n_threads: Optional[int] = None,
- n_gpu_layers: Optional[int] = None, # Accepted for caller compat, unused
+ n_gpu_layers: Optional[int] = None, # caller compat, unused
n_parallel: int = 1,
extra_args: Optional[List[str]] = None,
) -> bool:
@@ -2641,18 +2613,18 @@ class LlamaCppBackend:
- Local: ``gguf_path="/path/to/model.gguf"`` → uses ``-m``
- HF: ``hf_repo="unsloth/gemma-3-4b-it-GGUF", hf_variant="Q4_K_M"`` → uses ``-hf``
- In HF mode, llama-server handles downloading, caching, and
- auto-loading mmproj files for vision models.
+ In HF mode, llama-server handles download, caching, and auto-loading
+ mmproj files for vision models.
- Returns True if server started and health check passed.
+ Returns True if the server started and health check passed.
"""
- # Serialise the whole load so concurrent /load calls never
- # leave two llama-server processes alive (#5401 / #5161). Does
- # not block /unload, /status, /load-progress.
+ # Serialise the whole load so concurrent /load calls never leave two
+ # llama-server processes alive (#5401 / #5161). Doesn't block
+ # /unload, /status, /load-progress.
with self._serial_load_lock:
- # Duplicate /load that raced past the route-level check
- # (the first one hadn't published _healthy=True yet). If the
- # live server already satisfies this request, do nothing.
+ # Duplicate /load that raced past the route-level check (first
+ # one hadn't published _healthy=True yet). If the live server
+ # already satisfies this request, do nothing.
if self._already_in_target_state(
gguf_path = gguf_path,
model_identifier = model_identifier,
@@ -2669,7 +2641,7 @@ class LlamaCppBackend:
f"load_model: backend already in target state for "
f"'{model_identifier}', skipping reload"
)
- # Retry probe only if a prior attempt didn't complete.
+ # Retry probe only if a prior attempt didn't finish.
if not self._audio_probed:
try:
detected = self._detect_audio_type_strict()
@@ -2695,8 +2667,8 @@ class LlamaCppBackend:
return False
elif detected:
# csm / whisper / audio_vlm: track type but keep
- # _is_audio False -- GGUF TTS routing only fires
- # for snac/bicodec/dac.
+ # _is_audio False -- GGUF TTS routing only fires for
+ # snac/bicodec/dac.
with self._lock:
if not self._healthy:
return False
@@ -2728,7 +2700,7 @@ class LlamaCppBackend:
# ── Phase 2: download (NO lock held, so cancel can proceed) ──
# Scope HF_HUB_OFFLINE to the download block only when DNS is
# dead; cleanup runs even on exception so a transient hiccup
- # at the start of one load cannot quarantine future loads.
+ # can't quarantine future loads.
if hf_repo:
with _hf_offline_if_dns_dead():
model_path = self._download_gguf(
@@ -2752,7 +2724,7 @@ class LlamaCppBackend:
# Set identifier early so _read_gguf_metadata can use it for DeepSeek detection
self._model_identifier = model_identifier
- # Read GGUF metadata (context_length, chat_template) -- fast, header only
+ # Read GGUF metadata (context_length, chat_template); fast, header only
self._read_gguf_metadata(model_path)
# Check cancel after download
@@ -2760,10 +2732,10 @@ class LlamaCppBackend:
logger.info("Load cancelled after download phase")
return False
- # Outside ``self._lock`` so /unload, /cancel, /status are
- # not blocked. ``unload_model`` also records the kill, so
- # the frontend /unload+/load Apply path engages the wait
- # here even though no in-process kill happened.
+ # Outside ``self._lock`` so /unload, /cancel, /status aren't
+ # blocked. ``unload_model`` also records the kill, so the
+ # frontend /unload+/load Apply path engages the wait here even
+ # without an in-process kill.
self._wait_for_vram_settle(since_kill = self._last_kill_monotonic)
# ── Phase 3: start llama-server (under lock) ──────────────
@@ -2775,9 +2747,9 @@ class LlamaCppBackend:
self._port = self._find_free_port()
- # Select GPU(s) based on model size + estimated KV cache.
- # Seed safe defaults before GPU probing so the except path
- # still has valid state to publish.
+ # Select GPU(s) from model size + estimated KV cache. Seed
+ # safe defaults before probing so the except path has valid
+ # state to publish.
ctx_override = parse_ctx_override(extra_args)
requested_ctx = resolve_requested_ctx(extra_args, n_ctx)
cache_override = parse_cache_override(extra_args)
@@ -2793,9 +2765,9 @@ class LlamaCppBackend:
model_size = self._get_gguf_size_bytes(model_path)
gpus = self._get_gpu_free_memory()
- # Resolve effective context: 0 means let llama-server use the
- # model's native length. Only expand to a known native length
- # if metadata is available; otherwise preserve 0 as a sentinel.
+ # Resolve effective context: 0 means let llama-server use
+ # the model's native length. Only expand to a known native
+ # length if metadata exists; else keep 0 as a sentinel.
if requested_ctx > 0:
effective_ctx = requested_ctx
elif self._context_length is not None:
@@ -2803,18 +2775,17 @@ class LlamaCppBackend:
else:
effective_ctx = 0
original_ctx = effective_ctx
- # Default UI ceiling to the model's native context length.
- # GPU/VRAM-fit logic below may shrink this if hardware is limited.
+ # Default UI ceiling to the native context length;
+ # GPU/VRAM-fit logic below may shrink it on limited HW.
max_available_ctx = self._context_length or effective_ctx
- # Will MTP engage on this load? If so, the auto-fit
- # budget needs to reserve extra VRAM for the draft
- # model's KV cache + compute graph. Mirrors the
- # canonical-mode resolver in _build_speculative_flags:
- # forced mtp / mtp+ngram always engage; auto only
- # engages on an MTP GGUF >= 3B (sub-3B auto falls
- # back to ngram-mod which doesn't need headroom);
- # ngram / ngram-simple / off never engage MTP.
+ # Will MTP engage on this load? If so, auto-fit must
+ # reserve extra VRAM for the draft model's KV cache +
+ # compute graph. Mirrors _build_speculative_flags'
+ # canonical-mode resolver: forced mtp / mtp+ngram always
+ # engage; auto only on an MTP GGUF >= 3B (sub-3B auto
+ # falls back to ngram-mod, no headroom needed); ngram /
+ # ngram-simple / off never engage MTP.
_mtp_canonical = _canonicalize_spec_mode(speculative_type)
_mtp_effective = _mtp_canonical or "auto"
_mtp_size_for_fit = _extract_model_size_b(model_identifier)
@@ -2834,26 +2805,23 @@ class LlamaCppBackend:
)
)
- # Auto-cap context to fit in GPU VRAM and select GPUs.
+ # Auto-cap context to fit GPU VRAM and select GPUs.
+ # Two policies by whether the user set n_ctx:
#
- # Two policies depending on whether the user set n_ctx:
+ # Explicit n_ctx: honor it. Try the full requested context
+ # with _select_gpus (uses as many GPUs as needed); only
+ # cap if it doesn't fit on any GPU combination.
#
- # Explicit n_ctx (user chose a context length):
- # Honor it. Try the full requested context with _select_gpus
- # (which uses as many GPUs as needed). Only cap if it doesn't
- # fit on any GPU combination.
- #
- # Auto n_ctx=0 (model's native context):
- # Prefer fewer GPUs with reduced context over more GPUs,
- # since multi-GPU is slower and the user didn't ask for a
- # specific context length.
+ # Auto n_ctx=0 (native context): prefer fewer GPUs with
+ # reduced context, since multi-GPU is slower and the user
+ # didn't ask for a specific length.
gpu_indices, use_fit = None, True
explicit_ctx = requested_ctx > 0
if gpus and self._can_estimate_kv() and effective_ctx > 0:
- # Compute the largest hardware-aware cap from the model's
- # native context across all usable GPU subsets (for UI
- # bounds), independent of the currently requested context.
+ # Largest hardware-aware cap from the native context
+ # across all usable GPU subsets (for UI bounds),
+ # independent of the requested context.
native_ctx_for_cap = self._context_length or effective_ctx
if native_ctx_for_cap > 0:
ranked_for_cap = sorted(gpus, key = lambda g: g[1], reverse = True)
@@ -2879,30 +2847,28 @@ class LlamaCppBackend:
max_available_ctx = best_cap
else:
# Weights exceed 90% of every GPU subset's free
- # memory, so there is no fitting context. Anchor
- # the UI's "safe zone" threshold at 4096 (the
- # spec's default when the model cannot fit) so
- # the ctx slider shows the "might be slower"
- # warning as soon as the user drags above the
- # fallback default instead of never.
+ # memory, so no context fits. Anchor the UI's
+ # "safe zone" threshold at 4096 (the spec's
+ # default when the model can't fit) so the ctx
+ # slider shows the "might be slower" warning as
+ # soon as the user drags above the fallback.
max_available_ctx = min(4096, native_ctx_for_cap)
if explicit_ctx:
- # Honor the user's requested context verbatim. If it
- # fits, pin GPUs and skip --fit; if it doesn't, ship
+ # Honor the requested context verbatim. If it fits,
+ # pin GPUs and skip --fit; if not, ship
# -c <user_ctx> --fit on and let llama-server flex
- # -ngl (CPU layer offload). The UI is expected to
- # have surfaced the "might be slower" warning before
- # the user submitted a ctx above the fit ceiling.
+ # -ngl (CPU layer offload). The UI should have
+ # surfaced the "might be slower" warning before a
+ # ctx above the fit ceiling was submitted.
requested_total = model_size + self._estimate_kv_cache_bytes(
effective_ctx, cache_type_kv, n_parallel = n_parallel
)
gpu_indices, use_fit = self._select_gpus(requested_total, gpus)
# No silent shrink: effective_ctx stays == requested_ctx.
else:
- # Auto context: prefer fewer GPUs, cap context
- # to fit. Same headroom threshold as
- # _select_gpus (#5106).
+ # Auto context: prefer fewer GPUs, cap to fit. Same
+ # headroom threshold as _select_gpus (#5106).
ranked = sorted(gpus, key = lambda g: g[1], reverse = True)
pin_fraction = self._GPU_PIN_VRAM_FRACTION
for n_gpus in range(1, len(ranked) + 1):
@@ -2927,9 +2893,9 @@ class LlamaCppBackend:
break
else:
# Native ctx doesn't fit. Drop to 4096 and
- # re-check before deferring to --fit on:
- # a model that overflows at 131k may pin
- # comfortably with a 4096 KV cache (#5106).
+ # re-check before deferring to --fit on: a model
+ # that overflows at 131k may pin comfortably
+ # with a 4096 KV cache (#5106).
effective_ctx = min(4096, effective_ctx)
if effective_ctx > 0:
for n_gpus in range(1, len(ranked) + 1):
@@ -2947,9 +2913,9 @@ class LlamaCppBackend:
break
elif gpus:
- # Can't estimate KV -- fall back to file-size-only check.
- # Without KV estimation we cannot prove a hardware cap, so
- # keep the ceiling at the native context (already the default).
+ # Can't estimate KV -- file-size-only check. Without KV
+ # estimation we can't prove a hardware cap, so keep the
+ # ceiling at the native context (already the default).
logger.debug(
"Falling back to file-size-only GPU selection",
model_size_gb = round(model_size / (1024**3), 2),
@@ -2957,8 +2923,8 @@ class LlamaCppBackend:
gpu_indices, use_fit = self._select_gpus(model_size, gpus)
if use_fit and not explicit_ctx:
# Weights don't fit on any subset. Default the UI to
- # 4096 so the slider doesn't land on an unusable native
- # context. --fit on will flex -ngl at runtime.
+ # 4096 so the slider doesn't land on an unusable
+ # native context; --fit on flexes -ngl at runtime.
effective_ctx = min(4096, effective_ctx) if effective_ctx > 0 else 4096
if effective_ctx < original_ctx:
@@ -3032,15 +2998,16 @@ class LlamaCppBackend:
if use_fit:
cmd.extend(["--fit", "on"])
elif gpu_indices is not None:
- # Model fits on selected GPU(s) -- offload all layers
+ # Fits on selected GPU(s) -- offload all layers
cmd.extend(["-ngl", "-1"])
- # -1 = llama.cpp auto-detect (physical cores). Pass explicitly so we
- # do not inherit llama-server's internal default, which has historically
- # varied (hardware concurrency incl. hyperthreads on some builds).
+ # -1 = llama.cpp auto-detect (physical cores). Pass explicitly
+ # so we don't inherit llama-server's internal default, which
+ # has varied (hardware concurrency incl. hyperthreads on some
+ # builds).
cmd.extend(["--threads", str(n_threads if n_threads is not None else -1)])
- # Always enable Jinja chat template rendering for proper template support
+ # Enable Jinja chat template rendering
cmd.extend(["--jinja"])
# KV cache data type
@@ -3069,11 +3036,11 @@ class LlamaCppBackend:
else:
self._cache_type_kv = None
- # Speculative decoding (n-gram self-speculation, zero VRAM cost)
- # ngram-mod: ~16 MB shared hash pool, constant memory/complexity,
- # variable draft lengths. Helps most when the model repeats
- # existing text (code refactoring, summarization, reasoning).
- # For general chat with low repetition, overhead is ~5 ms.
+ # Speculative decoding (n-gram self-speculation, zero VRAM).
+ # ngram-mod: ~16 MB shared hash pool, constant memory/
+ # complexity, variable draft lengths. Helps most when the
+ # model repeats existing text (code refactor, summarization,
+ # reasoning); for low-repetition chat, overhead is ~5 ms.
#
# Benchmarks from upstream llama.cpp speculative-decoding PRs:
# Scenario | Without | With | Speedup
@@ -3090,8 +3057,8 @@ class LlamaCppBackend:
# ref: https://github.com/ggml-org/llama.cpp/pull/18471
# draft-mtp: MTP heads on Unsloth's *-MTP GGUFs
# (llama.cpp #22673). Auto-enabled via nextn_predict_layers,
- # fallback to -MTP in name. GPU: MTP-only. CPU/Mac: chain
- # with ngram-mod. See unsloth.ai/docs/models/qwen3.6#mtp-guide.
+ # fallback to -MTP in name. GPU: MTP-only. CPU/Mac: chain with
+ # ngram-mod. See unsloth.ai/docs/models/qwen3.6#mtp-guide.
spec_flags = self._build_speculative_flags(
speculative_type = speculative_type,
spec_draft_n_max = spec_draft_n_max,
@@ -3103,7 +3070,7 @@ class LlamaCppBackend:
)
cmd.extend(spec_flags)
- # Apply custom chat template override if provided
+ # Apply custom chat template override if provided.
self._chat_template_override = chat_template_override
if chat_template_override:
import tempfile
@@ -3130,10 +3097,9 @@ class LlamaCppBackend:
cmd.extend(["--chat-template-file", self._chat_template_file.name])
logger.info(f"Using custom chat template file: {self._chat_template_file.name}")
- # For reasoning models, set default thinking mode.
- # Qwen3.5/3.6 models below 9B (0.8B, 2B, 4B) disable thinking by default.
- # Only 9B and larger enable thinking.
- # Always-on templates ignore the kwarg entirely, so skip.
+ # For reasoning models, set default thinking mode. Qwen3.5/3.6
+ # below 9B (0.8B, 2B, 4B) disable thinking by default; 9B+
+ # enable it. Always-on templates ignore the kwarg, so skip.
if self._supports_reasoning and not self._reasoning_always_on:
thinking_default = True
mid = (model_identifier or "").lower()
@@ -3155,7 +3121,7 @@ class LlamaCppBackend:
cmd.extend(["--mmproj", launch_mmproj_path])
logger.info(f"Using mmproj for vision: {launch_mmproj_path}")
- # Option C: add --api-key for direct client access when enabled
+ # Option C: --api-key for direct client access when enabled
import os as _os
import secrets as _secrets
@@ -3166,11 +3132,10 @@ class LlamaCppBackend:
else:
self._api_key = None
- # User-supplied pass-through args go last so llama.cpp's
- # last-wins flag parsing lets the user override Studio's
- # auto-set tier-2 flags (e.g. --cache-type-k, --spec-type).
- # The route layer has already validated this list against
- # the managed-flag denylist via validate_extra_args().
+ # User pass-through args go last so llama.cpp's last-wins
+ # parsing lets the user override Studio's auto-set tier-2 flags
+ # (e.g. --cache-type-k, --spec-type). The route layer already
+ # validated this list via validate_extra_args().
if extra_args:
cmd.extend(str(a) for a in extra_args)
logger.info(f"Appending user extra args to llama-server: {list(extra_args)}")
@@ -3182,7 +3147,7 @@ class LlamaCppBackend:
_log_cmd[_ki] = "<redacted>"
logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")
- # Set library paths so llama-server can find its shared libs and CUDA DLLs
+ # Set library paths so llama-server finds its shared libs and CUDA DLLs
import os
import sys
@@ -3196,7 +3161,7 @@ class LlamaCppBackend:
logger.info("AMD unified-memory APU: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1")
if sys.platform == "win32":
- # See _build_windows_path_dirs for ordering. #5106.
+ # Ordering: see _build_windows_path_dirs. #5106.
path_dirs = self._build_windows_path_dirs(
binary_dir,
sys.prefix,
@@ -3206,28 +3171,28 @@ class LlamaCppBackend:
env["PATH"] = ";".join(path_dirs) + ";" + existing_path
# ROCm: the llama.cpp prebuilt bundles its own rocblas.dll
- # but NOT the Tensile kernel library files it needs
- # (rocblas/library/TensileLibrary*.dat + *.hsaco). The
- # bundled DLL searches relative to its own location by
- # default (i.e. <binary_dir>/rocblas/library/) which does
- # not exist, causing a silent crash on the first GEMM.
- # ROCBLAS_TENSILE_LIBPATH overrides that search to point at
- # the ROCm installation where the kernel files actually are.
+ # but NOT the Tensile kernel files it needs
+ # (rocblas/library/TensileLibrary*.dat + *.hsaco). The
+ # bundled DLL searches relative to its own location
+ # (<binary_dir>/rocblas/library/), which doesn't exist ->
+ # silent crash on the first GEMM. ROCBLAS_TENSILE_LIBPATH
+ # repoints that search at the ROCm install where the kernel
+ # files actually are.
_hip_path = os.environ.get("HIP_PATH", os.environ.get("ROCM_PATH", ""))
if _hip_path:
_rocblas_lib = os.path.join(_hip_path, "bin", "rocblas", "library")
if os.path.isdir(_rocblas_lib):
env.setdefault("ROCBLAS_TENSILE_LIBPATH", _rocblas_lib)
else:
- # Linux: set LD_LIBRARY_PATH for shared libs next to the binary
- # and CUDA runtime libs (libcudart, libcublas, etc.)
+ # Linux: LD_LIBRARY_PATH for shared libs next to the binary
+ # plus CUDA runtime libs (libcudart, libcublas, etc.)
import platform
lib_dirs = [binary_dir]
_arch = platform.machine() # x86_64, aarch64, etc.
# Pip-installed nvidia CUDA runtime libs (e.g. torch's
- # bundled cuda-bindings). The prebuilt llama.cpp binary
+ # bundled cuda-bindings). The prebuilt llama.cpp binary
# links against libcudart.so.13 / libcublas.so.13 which
# live here, not in /usr/local/cuda.
import glob as _glob
@@ -3269,8 +3234,7 @@ class LlamaCppBackend:
"/usr/local/cuda/lib64",
f"/usr/local/cuda/targets/{_arch}-linux/lib",
# Fallback CUDA compat paths (e.g. binary built with
- # CUDA 12 on a system where default /usr/local/cuda
- # points to CUDA 13+).
+ # CUDA 12 where default /usr/local/cuda is CUDA 13+).
"/usr/local/cuda-12/lib64",
"/usr/local/cuda-12.8/lib64",
f"/usr/local/cuda-12/targets/{_arch}-linux/lib",
@@ -3283,9 +3247,9 @@ class LlamaCppBackend:
env["LD_LIBRARY_PATH"] = f"{new_ld}:{existing_ld}" if existing_ld else new_ld
# Pin to selected GPU(s). On ROCm, llama-server (and any torch
- # in the subprocess) honors HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES;
- # narrowing only CUDA_VISIBLE_DEVICES leaves an AMD child seeing
- # the full HIP/ROCR set the parent inherited.
+ # in the subprocess) honors HIP_VISIBLE_DEVICES /
+ # ROCR_VISIBLE_DEVICES; narrowing only CUDA_VISIBLE_DEVICES
+ # leaves an AMD child seeing the full HIP/ROCR set inherited.
if gpu_indices is not None:
pinned = ",".join(str(i) for i in gpu_indices)
env["CUDA_VISIBLE_DEVICES"] = pinned
@@ -3298,18 +3262,17 @@ class LlamaCppBackend:
logger.debug("Failed to set ROCm visibility env vars for child: %s", e)
# Defensive kill: if a concurrent load slipped past Phase 1
- # (because its `self._process` was None at the time) and
- # already stored a Popen handle here, drop that orphan
- # before we overwrite the reference. See issue #5161.
+ # (its `self._process` was None then) and already stored a
+ # Popen handle here, drop that orphan before we overwrite the
+ # reference. See issue #5161.
self._kill_process()
self._stdout_lines = []
# Tee llama-server output to a dedicated log file so a
- # post-mortem in CI (or after a remote-debug session)
- # has the full subprocess trail even when the parent
- # only stored the last 50 lines. Path lives under the
- # studio home so it ships in the same place all other
- # Studio logs live.
+ # post-mortem in CI (or after a remote-debug session) has the
+ # full subprocess trail even when the parent only kept the last
+ # 50 lines. Path lives under the studio home alongside other
+ # Studio logs.
self._llama_log_fh = None
try:
log_dir = _swa_cache_path().parent / "logs" / "llama-server"
@@ -3337,20 +3300,19 @@ class LlamaCppBackend:
**_windows_hidden_subprocess_kwargs(),
)
- # Start background thread to drain stdout and prevent pipe deadlock
+ # Background thread to drain stdout (prevents pipe deadlock)
self._stdout_thread = threading.Thread(
target = self._drain_stdout, daemon = True, name = "llama-stdout"
)
self._stdout_thread.start()
# Store the resolved on-disk path, not the caller's kwarg. In
- # HF mode the caller passes gguf_path=None and the real path
- # (``model_path``) is what llama-server is actually mmap'ing.
- # Downstream consumers (load_progress, log lines, etc.) need
- # the path that exists on disk.
+ # HF mode the caller passes gguf_path=None and ``model_path``
+ # is what llama-server actually mmap's. Downstream consumers
+ # (load_progress, log lines, etc.) need the real on-disk path.
self._gguf_path = model_path
self._hf_repo = hf_repo
- # For local GGUF files, extract variant from filename if not provided
+ # For local GGUF files, extract variant from filename if absent
if hf_variant:
self._hf_variant = hf_variant
elif gguf_path:
@@ -3364,9 +3326,9 @@ class LlamaCppBackend:
self._is_vision = effective_is_vision
self._model_identifier = model_identifier
- # Store the effective (possibly capped) context separately.
- # Do NOT overwrite _context_length -- it holds the model's native
- # context length from GGUF metadata and is used for display/info.
+ # Store the effective (possibly capped) context separately. Do
+ # NOT overwrite _context_length -- it holds the native context
+ # length from GGUF metadata, used for display/info.
self._effective_context_length = (
effective_ctx if effective_ctx > 0 else self._context_length
)
@@ -3374,7 +3336,7 @@ class LlamaCppBackend:
max_available_ctx if max_available_ctx > 0 else self._effective_context_length
)
- # Wait for llama-server to become healthy
+ # Wait for llama-server to become healthy.
if not self._wait_for_health(timeout = 600.0):
self._kill_process()
raise RuntimeError(
@@ -3387,11 +3349,11 @@ class LlamaCppBackend:
self._healthy = True
- # Commit caller intent only after _healthy=True so a
- # failed startup can't poison the next inheritance check.
- # None keeps prior, [] clears, list sets. Source records
- # the caller's hf_variant (None for local files) so the
- # route's same_source check stays symmetric.
+ # Commit caller intent only after _healthy=True so a failed
+ # startup can't poison the next inheritance check. None keeps
+ # prior, [] clears, list sets. Source records the caller's
+ # hf_variant (None for local files) so the route's same_source
+ # check stays symmetric.
if extra_args is not None:
self._extra_args = list(extra_args)
self._extra_args_source = (model_identifier, hf_variant)
@@ -3436,7 +3398,7 @@ class LlamaCppBackend:
self._is_audio = True
self._audio_type = detected
except Exception as exc:
- # Surface as HTTP 500 -- matches pre-PR contract.
+ # Surface as HTTP 500 (matches pre-PR contract).
logger.warning(
"Failed to init audio codec '%s': %s",
detected,
@@ -3452,7 +3414,7 @@ class LlamaCppBackend:
return False
self._audio_type = detected
- # Audio input = token probe (audio_vlm/whisper) OR mmproj audio encoder.
+ # Audio input = token probe (audio_vlm/whisper) OR mmproj encoder.
from utils.models.model_config import is_audio_input_type
self._has_audio_input = bool(is_audio_input_type(self._audio_type)) or bool(
@@ -3481,11 +3443,11 @@ class LlamaCppBackend:
status round-trip), and ``self._spec_draft_n_max`` (user override
only; None when the platform default applies).
- Speculative decoding (n-gram self-speculation, zero VRAM cost):
+ Speculative decoding (n-gram self-speculation, zero VRAM):
ngram-mod uses a ~16 MB shared hash pool, constant memory /
complexity, variable draft lengths. Helps most when the model
- repeats existing text (code refactor, summarisation, reasoning).
- For general chat with low repetition, overhead is ~5 ms.
+ repeats existing text (code refactor, summarisation, reasoning);
+ for low-repetition chat, overhead is ~5 ms.
Benchmarks from upstream llama.cpp speculative-decoding PRs:
Scenario | Without | With | Speedup
@@ -3493,18 +3455,17 @@ class LlamaCppBackend:
Qwen3-235B offloaded | 12 t/s | 21 t/s | 1.8x
gpt-oss-120b repeat (92% accept)| 181 t/s | 814 t/s | 4.5x
- Sub-3B dense MTP regresses vs spec-off because the draft head's
- per-token cost exceeds the acceptance savings at this scale.
- Q4_K_XL clean bench (each prompt once after an unrelated warmup)
- on B200 + x86 CPU:
+ Sub-3B dense MTP regresses vs spec-off: the draft head's per-token
+ cost exceeds the acceptance savings at this scale. Q4_K_XL clean
+ bench (each prompt once after an unrelated warmup) on B200 + x86 CPU:
0.8B GPU: draft-mtp n=2 = 0.58x vs OFF; ngram-only = 1.10x
2B GPU: draft-mtp n=2 = 0.82x vs OFF; OFF or ngram = 1.00x
0.8B CPU: chained n=2 = 0.86x vs OFF; ngram-only = 1.19x
2B CPU: chained n=2 = 0.83x vs OFF; ngram-only = 1.01x
4B+ GPU/CPU: spec on is a net win (1.08x-1.46x).
Auto falls back to ngram-mod (zero-VRAM, near-zero idle cost on
- diverse content); forced MTP variants engage anyway and just log
- a warning per the user's choice.
+ diverse content); forced MTP variants engage anyway and just log a
+ warning per the user's choice.
"""
flags: List[str] = []
# Reset; emit branches re-set on the resolved emission.
@@ -3512,7 +3473,7 @@ class LlamaCppBackend:
self._speculative_type = None
# Canonical UI-facing requested mode: auto / mtp / ngram /
- # mtp+ngram / off / ngram-simple. Legacy values are mapped via
+ # mtp+ngram / off / ngram-simple. Legacy values mapped via
# _canonicalize_spec_mode (default->auto, draft-mtp->mtp,
# ngram-mod->ngram, "ngram-mod,draft-mtp"->mtp+ngram).
canonical_mode = _canonicalize_spec_mode(speculative_type)
@@ -3525,8 +3486,8 @@ class LlamaCppBackend:
if user_owns_spec_type:
# User --spec-type in extra_args wins outright; suppress
- # auto-emit so we don't emit a duplicate / conflicting
- # spec block. Record requested mode as None.
+ # auto-emit to avoid a duplicate / conflicting spec block.
+ # Record requested mode as None.
self._requested_spec_mode = None
return flags
@@ -3536,8 +3497,7 @@ class LlamaCppBackend:
def _resolved_draft_n_max() -> int:
# User override wins; else platform default (the B200 / x86
# clean-sweep sweet spot from PR #5582 is n=2 GPU, n=3 CPU;
- # raising past 3 starts to regress on essay-style
- # low-acceptance prompts).
+ # past 3 regresses on essay-style low-acceptance prompts).
if spec_draft_n_max is not None:
n = int(spec_draft_n_max)
self._spec_draft_n_max = n
@@ -3646,14 +3606,14 @@ class LlamaCppBackend:
_emit_mtp(chain_ngram = True)
return flags
- # effective_mode == "auto": today's promotion path. llama.cpp
- # #22673: MTP is compatible with mmproj, so there's no vision gate.
+ # effective_mode == "auto": the promotion path. llama.cpp #22673:
+ # MTP is compatible with mmproj, so there's no vision gate.
if is_mtp_model and not _mtp_too_small:
# GPU: MTP-only. CPU/Mac: chain ngram-mod + MTP.
_emit_mtp(chain_ngram = not gpus)
elif is_mtp_model and _mtp_too_small:
- # Sub-3B fallback: drop the MTP draft head, keep ngram-mod
- # when the binary supports it.
+ # Sub-3B fallback: drop the MTP draft head, keep ngram-mod when
+ # the binary supports it.
_small_caps = self.probe_server_capabilities(binary)
if _small_caps.get("supports_ngram_mod"):
logger.info(
@@ -3693,17 +3653,16 @@ class LlamaCppBackend:
) -> bool:
"""True iff the live server already satisfies these load kwargs.
- Mirrors ``routes/inference.py:_request_matches_loaded_settings``
- but compares raw kwargs so ``load_model`` can short-circuit a
- duplicate /load that raced past the route-level check (#5401).
+ Mirrors ``routes/inference.py:_request_matches_loaded_settings`` but
+ compares raw kwargs so ``load_model`` can short-circuit a duplicate
+ /load that raced past the route-level check (#5401).
"""
if not self.is_loaded:
return False
if (self._model_identifier or "").lower() != (model_identifier or "").lower():
return False
- # Direct-file loads pass hf_variant=None while the backend
- # stores an extracted filename label; compare paths instead
- # to keep the guard symmetric.
+ # Direct-file loads pass hf_variant=None while the backend stores an
+ # extracted filename label; compare paths to keep the guard symmetric.
if gguf_path is not None and self._gguf_path:
try:
if Path(self._gguf_path).resolve() != Path(gguf_path).resolve():
@@ -3726,11 +3685,10 @@ class LlamaCppBackend:
if _norm(self._cache_type_kv) != _norm(cache_type_kv):
return False
- # Compare on the canonical UI-facing mode the user requested.
- # When extra_args carries --spec-type, the route-layer code paths
- # bypass the dropdown anyway and the backend stores
- # _requested_spec_mode = None; the request mirrors that by
- # canonicalising to None.
+ # Compare on the canonical UI-facing requested mode. When extra_args
+ # carries --spec-type, the route layer bypasses the dropdown and the
+ # backend stores _requested_spec_mode = None; the request mirrors
+ # that by canonicalising to None.
if _extra_args_set_spec_type(extra_args):
req_mode = None
else:
@@ -3739,10 +3697,10 @@ class LlamaCppBackend:
if req_mode != backend_mode:
return False
- # spec_draft_n_max only matters when an MTP variant is actually
- # engaged. Compare on the resolved spec rather than the requested
- # mode so an Auto request that auto-promoted to draft-mtp under
- # the hood still bounces a reload when the user changes n_max.
+ # spec_draft_n_max only matters when an MTP variant is engaged.
+ # Compare on the resolved spec, not the requested mode, so an Auto
+ # request that auto-promoted to draft-mtp still bounces a reload
+ # when the user changes n_max.
if (
self._speculative_type == "draft-mtp"
and spec_draft_n_max is not None
@@ -3753,8 +3711,8 @@ class LlamaCppBackend:
if (self._chat_template_override or None) != (chat_template_override or None):
return False
- # extra_args=None means "no opinion" (inherit semantics handled
- # at the route layer); only an explicit list forces equality.
+ # extra_args=None means "no opinion" (inherit handled at the route
+ # layer); only an explicit list forces equality.
if extra_args is not None:
current = list(self._extra_args) if self._extra_args is not None else []
if list(extra_args) != current:
@@ -3765,13 +3723,13 @@ class LlamaCppBackend:
self, expected_gpu: bool, detected_gpus: list[tuple[int, int]]
) -> Optional[bool]:
"""True if a GPU model buffer was allocated, False if only CPU
- buffers landed despite GPU intent, None when there's no signal
- (no GPU detected, no buffer-size lines, etc.)."""
+ buffers landed despite GPU intent, None when there's no signal (no
+ GPU detected, no buffer-size lines, etc.)."""
if not detected_gpus or not expected_gpu:
return None
- # llama-server logs one ``... model buffer size = N MiB`` line
- # per backend buffer; CUDA0 / ROCm0 / Metal / Vulkan0 /
- # OpenCL0 / SYCL0 are GPU, CPU / CPU_Mapped are not.
+ # llama-server logs one ``... model buffer size = N MiB`` line per
+ # backend buffer; CUDA0 / ROCm0 / Metal / Vulkan0 / OpenCL0 / SYCL0
+ # are GPU, CPU / CPU_Mapped are not.
gpu_markers = ("CUDA", "ROCm", "Metal", "Vulkan", "OpenCL", "SYCL")
saw_buffer_line = False
saw_gpu_buffer = False
@@ -3787,7 +3745,7 @@ class LlamaCppBackend:
return saw_gpu_buffer
def unload_model(self) -> bool:
- """Terminate the llama-server subprocess and cancel any in-flight download."""
+ """Terminate the subprocess and cancel any in-flight download."""
self._cancel_event.set()
with self._lock:
self._kill_process()
@@ -3837,7 +3795,7 @@ class LlamaCppBackend:
self._ssm_state_size = None
self._shared_kv_layers = None
self._nextn_predict_layers = None
- # Clean up temp chat template file
+ # Clean up temp chat template file.
if hasattr(self, "_chat_template_file") and self._chat_template_file:
try:
import os
@@ -3845,7 +3803,7 @@ class LlamaCppBackend:
except Exception:
pass
self._chat_template_file = None
- # Free audio codec GPU memory
+ # Free audio codec GPU memory.
if LlamaCppBackend._codec_mgr is not None:
LlamaCppBackend._codec_mgr.unload()
LlamaCppBackend._codec_mgr = None
@@ -3871,12 +3829,12 @@ class LlamaCppBackend:
finally:
self._process = None
# Clear healthy so a /load arriving during the replacement
- # server's warm-up window cannot short-circuit against the
+ # server's warm-up window can't short-circuit against the
# previous server's health (#5401).
self._healthy = False
- # Drives _wait_for_vram_settle in the next load_model;
- # set in finally so both in-process and frontend
- # /unload+/load Apply paths record the kill.
+ # Drives _wait_for_vram_settle in the next load_model; set in
+ # finally so both in-process and frontend /unload+/load Apply
+ # paths record the kill.
self._last_kill_monotonic = time.monotonic()
if self._stdout_thread is not None:
self._stdout_thread.join(timeout = 2)
@@ -3894,23 +3852,21 @@ class LlamaCppBackend:
"""Kill orphaned llama-server processes started by studio.
Only kills processes whose resolved binary lives under a known
- Studio install directory (or matches an exact env-var override)
- to avoid terminating unrelated llama-server instances.
-
- Mirrors every location that _find_llama_server_binary() can
- return from so that orphans from any supported install path
- are still cleaned up.
-
- Uses psutil for cross-platform support (Linux, macOS, Windows).
- Falls back to pgrep + /proc/<pid>/exe on Linux when psutil is
- not installed.
+ Studio install dir (or matches an exact env-var override), to avoid
+ terminating unrelated llama-server instances. Mirrors every location
+ _find_llama_server_binary() can return, so orphans from any
+ supported install path are cleaned up.
+
+ Uses psutil for cross-platform support (Linux, macOS, Windows);
+ falls back to pgrep + /proc/<pid>/exe on Linux when psutil is
+ absent.
"""
try:
# -- Build the ownership allowlist --------------------------------
- # Two kinds of matches:
+ # Two match kinds:
# exact_binaries -- env var overrides (exact path match only)
- # install_roots -- directory trees that are Studio-owned
- # (binary must be *under* one of these)
+ # install_roots -- Studio-owned dir trees (binary must be
+ # *under* one of these)
install_roots: list[Path] = []
# Env-mode custom root (mirrors _find_llama_server_binary).
@@ -3930,12 +3886,12 @@ class LlamaCppBackend:
pass
# Primary install dir (default mode only). Env-mode skips this so
- # a custom-root Studio cannot kill a concurrent default-install
+ # a custom-root Studio can't kill a concurrent default-install
# Studio's llama-server (same OS user, different install).
if not _is_custom_root:
install_roots.append(Path.home() / ".unsloth" / "llama.cpp")
- # Legacy in-tree build dirs (older setup.sh versions)
+ # Legacy in-tree build dirs (older setup.sh)
project_root = Path(__file__).resolve().parents[4]
install_roots.append(project_root / "llama.cpp")
@@ -3956,7 +3912,7 @@ class LlamaCppBackend:
except OSError:
pass
- # Resolve all roots so is_relative_to works reliably
+ # Resolve all roots so is_relative_to works reliably.
resolved_roots: list[Path] = []
for root in install_roots:
try:
@@ -3967,8 +3923,8 @@ class LlamaCppBackend:
my_pid = os.getpid()
# -- Enumerate processes -------------------------------------------
- # Prefer psutil (cross-platform). Fall back to pgrep + /proc on
- # Linux when psutil is not installed.
+ # Prefer psutil (cross-platform); fall back to pgrep + /proc on
+ # Linux when psutil is absent.
try:
import psutil
has_psutil = True
@@ -3991,9 +3947,8 @@ class LlamaCppBackend:
exe_path = Path(exe).resolve()
- # Check ownership: exact binary match OR binary is
- # under a known install root (proper ancestry, not
- # substring).
+ # Ownership: exact binary match OR binary under a
+ # known install root (proper ancestry, not substring).
is_ours = exe_path in exact_binaries or any(
exe_path.is_relative_to(root) for root in resolved_roots
)
@@ -4032,11 +3987,10 @@ class LlamaCppBackend:
if pid == my_pid:
continue
- # Resolve the actual executable. /proc/<pid>/exe is a
- # symlink to the real binary and avoids all cmdline-
- # parsing ambiguities (spaces in paths, argv rewriting).
- # Fall back to the first cmdline token when /proc is
- # unavailable.
+ # Resolve the actual executable. /proc/<pid>/exe is a
+ # symlink to the real binary and avoids cmdline-parsing
+ # ambiguities (spaces in paths, argv rewriting). Fall back
+ # to the first cmdline token when /proc is unavailable.
proc_exe = Path(f"/proc/{pid}/exe")
try:
binary = proc_exe.resolve(strict = True)
@@ -4075,15 +4029,15 @@ class LlamaCppBackend:
"""
Poll llama-server's /health endpoint until it responds 200.
- Also monitors subprocess for early exit/crash.
+ Also monitors the subprocess for early exit/crash.
"""
deadline = time.monotonic() + timeout
url = f"http://127.0.0.1:{self._port}/health"
while time.monotonic() < deadline:
- # Check if process crashed
+ # Process crashed?
if self._process.poll() is not None:
- # Give the drain thread a moment to collect final output
+ # Let the drain thread collect final output.
if self._stdout_thread is not None:
self._stdout_thread.join(timeout = 2)
output = "\n".join(self._stdout_lines[-50:])
@@ -4102,8 +4056,8 @@ class LlamaCppBackend:
httpx.TimeoutException,
# ReadError covers TCP RST mid-read while llama-server is
# still binding the port (Windows: WinError 10054). The
- # crash-detection branch above catches a real exit; this
- # one keeps a transient socket close from masking it.
+ # crash branch above catches a real exit; this keeps a
+ # transient socket close from masking it.
httpx.ReadError,
httpx.RemoteProtocolError,
httpx.WriteError,
@@ -4119,8 +4073,8 @@ class LlamaCppBackend:
@staticmethod
def _parse_tool_calls_from_text(content: str) -> list[dict]:
- """Thin wrapper around the shared parser in tool_call_parser
- so safetensors and llama_cpp pick up the same fixes."""
+ """Thin wrapper around the shared tool_call_parser so safetensors
+ and llama_cpp pick up the same fixes."""
return _shared_parse_tool_calls_from_text(content)
@staticmethod
@@ -4129,12 +4083,12 @@ class LlamaCppBackend:
Build OpenAI-format messages, optionally injecting an image_url
content part into the last user message for vision models.
- If no image is provided, returns messages as-is.
+ Returns messages as-is if no image is provided.
"""
if not image_b64:
return messages
- # Find the last user message and convert to multimodal content parts
+ # Convert the last user message to multimodal content parts
result = [msg.copy() for msg in messages]
last_user_idx = None
for i, msg in enumerate(result):
@@ -4163,11 +4117,11 @@ class LlamaCppBackend:
) -> Generator[str, None, None]:
"""Iterate over an httpx streaming response with cancel support.
- Checks cancel_event between chunks and on ReadTimeout. The
- cancel watcher in _stream_with_retry also calls response.close()
- on cancel, which unblocks iter_text() once the response exists.
- During normal streaming llama-server sends tokens frequently,
- so the cancel check between chunks is the primary mechanism.
+ Checks cancel_event between chunks and on ReadTimeout. The cancel
+ watcher in _stream_with_retry also calls response.close() on cancel,
+ unblocking iter_text() once the response exists. During normal
+ streaming llama-server sends tokens frequently, so the between-chunk
+ check is the primary mechanism.
"""
text_iter = response.iter_text()
while True:
@@ -4180,8 +4134,8 @@ class LlamaCppBackend:
except StopIteration:
return
except httpx.ReadTimeout:
- # No data within the timeout window -- just loop back
- # and re-check cancel_event.
+ # No data within the timeout window -- loop back and re-check
+ # cancel_event.
continue
@staticmethod
@@ -4195,21 +4149,18 @@ class LlamaCppBackend:
):
"""Open an httpx streaming POST with cancel support.
- Sends the request once with a long read timeout (120 s) so
- prompt processing (prefill) can finish without triggering a
- retry storm. The previous 0.5 s timeout caused duplicate POST
- requests every half second, forcing llama-server to restart
- processing each time.
-
- A background watcher thread provides cancel by closing the
- response when cancel_event is set. Limitation: httpx does not
- allow interrupting a blocked read from another thread before
- the response object exists, so cancel during the initial
- header wait (prefill phase) only takes effect once headers
- arrive. After that, response.close() unblocks reads promptly.
- In practice llama-server prefill is 1-5 s for typical prompts,
- during which cancel is deferred -- still much better than the
- old retry storm which made prefill slower.
+ Sends the request once with a long read timeout (120 s) so prefill
+ (prompt processing) can finish without a retry storm. The previous
+ 0.5 s timeout caused duplicate POSTs every half second, forcing
+ llama-server to restart processing each time.
+
+ A background watcher thread cancels by closing the response when
+ cancel_event is set. Limitation: httpx can't interrupt a blocked
+ read from another thread before the response object exists, so
+ cancel during the initial header wait (prefill) only takes effect
+ once headers arrive; after that response.close() unblocks reads
+ promptly. Prefill is 1-5 s for typical prompts, during which cancel
+ is deferred -- still much better than the old retry storm.
"""
if cancel_event is not None and cancel_event.is_set():
raise GeneratorExit
@@ -4222,9 +4173,9 @@ class LlamaCppBackend:
def _cancel_watcher():
while not _cancel_closed.is_set():
if cancel_event.wait(timeout = 0.3):
- # Cancel requested. Keep polling until the response object
- # exists so we can close it, or until the main thread
- # finishes on its own (_cancel_closed is set in finally).
+ # Cancel requested. Poll until the response object exists
+ # so we can close it, or until the main thread finishes
+ # (_cancel_closed set in finally).
while not _cancel_closed.is_set():
r = _response_ref[0]
if r is not None:
@@ -4243,10 +4194,9 @@ class LlamaCppBackend:
watcher.start()
try:
- # Long read timeout so prefill (prompt processing) can finish
- # without triggering a retry storm. Cancel during both
- # prefill and streaming is handled by the watcher thread
- # which closes the response, unblocking any httpx read.
+ # Long read timeout so prefill can finish without a retry storm.
+ # Cancel during prefill and streaming is handled by the watcher
+ # thread closing the response, unblocking any httpx read.
prefill_timeout = httpx.Timeout(
connect = 30,
read = 120.0,
@@ -4291,10 +4241,10 @@ class LlamaCppBackend:
preserve_thinking: Optional[bool] = None,
) -> Generator[str | dict, None, None]:
"""
- Send a chat completion request to llama-server and stream tokens back.
+ Send a chat completion to llama-server and stream tokens back.
- Uses /v1/chat/completions — llama-server handles chat template
- application and vision (multimodal image_url parts) natively.
+ Uses /v1/chat/completions -- llama-server applies the chat template
+ and handles vision (multimodal image_url parts) natively.
Yields cumulative text (matching InferenceBackend's convention).
"""
@@ -4313,15 +4263,14 @@ class LlamaCppBackend:
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
}
- # Pass enable_thinking / reasoning_effort / preserve_thinking per-request
+ # Per-request enable_thinking / reasoning_effort / preserve_thinking
_reasoning_kw = self._request_reasoning_kwargs(
enable_thinking, reasoning_effort, preserve_thinking
)
if _reasoning_kw is not None:
payload["chat_template_kwargs"] = _reasoning_kw
- # Default cap to the model's effective context length when known,
- # otherwise the conservative floor. The wall-clock backstop below
- # keeps a stuck model from running indefinitely either way.
+ # Cap to the effective context length when known, else the floor.
+ # The wall-clock backstop below stops a stuck model regardless.
payload["max_tokens"] = (
max_tokens
if max_tokens is not None
@@ -4340,9 +4289,9 @@ class LlamaCppBackend:
_metadata_timings = None
try:
- # _stream_with_retry uses a 120 s read timeout so prefill
- # can finish. Cancel during streaming is handled by the
- # watcher thread (closes the response on cancel_event).
+ # _stream_with_retry uses a 120 s read timeout so prefill can
+ # finish. Cancel during streaming is handled by the watcher
+ # thread (closes the response on cancel_event).
stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)
_auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
with httpx.Client(
@@ -4379,10 +4328,10 @@ class LlamaCppBackend:
cumulative += "</think>"
yield cumulative
else:
- # Only reasoning_content, no content tokens:
- # the model put its entire reply in reasoning
- # (e.g. Qwen3 always-think mode). Show it
- # as the main response, not as a thinking block.
+ # Only reasoning_content, no content:
+ # model put its whole reply in reasoning
+ # (e.g. Qwen3 always-think). Show it as
+ # the main response, not a thinking block.
cumulative = reasoning_text
yield cumulative
_stream_done = True
@@ -4392,7 +4341,7 @@ class LlamaCppBackend:
try:
data = json.loads(line[6:])
- # Capture server timings/usage from final chunks
+ # Capture server timings/usage from final chunks.
_chunk_timings = data.get("timings")
if _chunk_timings:
_metadata_timings = _chunk_timings
@@ -4403,9 +4352,9 @@ class LlamaCppBackend:
if choices:
delta = choices[0].get("delta", {})
- # Handle reasoning/thinking tokens
- # llama-server sends these as "reasoning_content"
- # Wrap in <think> tags for the frontend parser
+ # Reasoning/thinking tokens: llama-server
+ # sends these as "reasoning_content"; wrap
+ # in <think> tags for the frontend parser.
reasoning = delta.get("reasoning_content", "")
if reasoning:
reasoning_text += reasoning
@@ -4470,7 +4419,7 @@ class LlamaCppBackend:
"""
Agentic loop: let the model call tools, execute them, and continue.
- Yields dicts with:
+ Yields dicts:
{"type": "status", "text": "Searching: ..."/"Reading: ..."} -- tool status updates
{"type": "content", "text": "token"} -- streamed content tokens (cumulative)
{"type": "reasoning", "text": "token"} -- streamed reasoning tokens (cumulative)
@@ -4491,38 +4440,37 @@ class LlamaCppBackend:
return text
return strip_tool_call_markup(text, final = final)
- # XML prefixes that signal a tool call in content.
- # Empty when auto_heal is disabled so the buffer never
- # speculatively holds content for XML detection.
+ # XML prefixes that signal a tool call in content. Empty when
+ # auto_heal is disabled so the buffer never speculatively holds
+ # content for XML detection.
_TOOL_XML_SIGNALS = ("<tool_call>", "<function=") if auto_heal_tool_calls else ()
_MAX_BUFFER_CHARS = 32
# ── Duplicate tool-call detection ────────────────────────
- # Track recent (tool_name, arguments) hashes to detect loops
- # where the model repeats the exact same call. Retries after
- # a transient failure are allowed (only block when the previous
- # identical call succeeded).
+ # Track recent (tool_name, arguments) hashes to detect loops where
+ # the model repeats the exact same call. Retries after a transient
+ # failure are allowed (only block when the prior identical call
+ # succeeded).
_tool_call_history: list[tuple[str, bool]] = [] # (key, failed)
_render_html_succeeded = False
# ── Re-prompt on plan-without-action ─────────────────
# When the model describes what it intends to do (forward-looking
- # language) without actually calling a tool, re-prompt once.
- # Only triggers on responses that signal intent/planning -- a
- # direct answer like "4" or "Hello!" will not match.
- # Pattern is compiled once at module level (_INTENT_SIGNAL).
+ # language) without calling a tool, re-prompt once. Only triggers on
+ # responses signaling intent/planning -- a direct answer like "4" or
+ # "Hello!" won't match. Pattern compiled at module level
+ # (_INTENT_SIGNAL).
_reprompt_count = 0
- # Reserve extra iterations for re-prompts so they don't
- # consume the caller's tool-call budget. Only add the
- # extra slot when tool iterations are actually allowed.
+ # Reserve extra iterations for re-prompts so they don't consume the
+ # caller's tool-call budget; only when tool iterations are allowed.
_extra = _MAX_REPROMPTS if max_tool_iterations > 0 else 0
for iteration in range(max_tool_iterations + _extra):
if cancel_event is not None and cancel_event.is_set():
return
- # Build payload -- stream: True so we detect tool signals
- # in the first 1-2 chunks without a non-streaming penalty.
+ # stream: True so we detect tool signals in the first 1-2 chunks
+ # without a non-streaming penalty.
payload = {
"messages": conversation,
"stream": True,
@@ -4556,9 +4504,9 @@ class LlamaCppBackend:
)
# ── Speculative buffer state machine ──────────────────
- # BUFFERING: accumulating content, checking for tool signals
- # STREAMING: no tool detected, yielding tokens to caller
- # DRAINING: tool signal found, silently consuming rest
+ # BUFFERING: accumulate content, check for tool signals
+ # STREAMING: no tool detected, yield tokens to caller
+ # DRAINING: tool signal found, silently consume rest
_S_BUFFERING = 0
_S_STREAMING = 1
_S_DRAINING = 2
@@ -4567,7 +4515,7 @@ class LlamaCppBackend:
content_buffer = "" # Raw content held during BUFFERING
content_accum = "" # All content tokens (for tool parsing)
reasoning_accum = ""
- cumulative_display = "" # Cumulative text yielded (with <think>)
+ cumulative_display = "" # Cumulative yielded text (with <think>)
in_thinking = False
has_content_tokens = False
tool_calls_acc = {} # Structured delta.tool_calls fragments
@@ -4655,8 +4603,8 @@ class LlamaCppBackend:
tc_deltas = delta.get("tool_calls")
if tc_deltas:
# Once visible content has been
- # emitted, do not reclassify this
- # turn as a tool call.
+ # emitted, don't reclassify this turn
+ # as a tool call.
if _last_emitted:
continue
has_structured_tc = True
@@ -4673,8 +4621,8 @@ class LlamaCppBackend:
},
}
elif tc_d.get("id"):
- # Update ID if real one
- # arrives on a later delta
+ # Update ID if a real one
+ # arrives on a later delta.
tool_calls_acc[idx]["id"] = tc_d["id"]
func = tc_d.get("function", {})
if func.get("name"):
@@ -4712,10 +4660,10 @@ class LlamaCppBackend:
continue
# ── Reasoning tokens ──
- # Only yield in STREAMING state. In BUFFERING
- # and DRAINING, accumulate silently so we don't
+ # Yield only in STREAMING. In BUFFERING and
+ # DRAINING, accumulate silently so we don't
# corrupt the consumer's prev_text tracker
- # (routes/inference.py never resets prev_text
+ # (routes/inference.py never resets it
# between tool iterations).
reasoning = delta.get("reasoning_content", "")
if reasoning:
@@ -4760,7 +4708,7 @@ class LlamaCppBackend:
if not stripped_buf:
continue
- # Check tool signal prefixes
+ # Check tool signal prefixes.
is_prefix = False
is_match = False
for sig in _TOOL_XML_SIGNALS:
@@ -4780,8 +4728,8 @@ class LlamaCppBackend:
else:
# Not a tool -- flush buffer
detect_state = _S_STREAMING
- # Flush any reasoning accumulated
- # during BUFFERING phase
+ # Flush reasoning accumulated
+ # during BUFFERING.
if reasoning_accum:
cumulative_display += "<think>"
cumulative_display += reasoning_accum
@@ -4814,7 +4762,7 @@ class LlamaCppBackend:
elif content_accum or reasoning_accum:
detect_state = _S_STREAMING
if content_buffer:
- # Flush any reasoning accumulated first
+ # Flush reasoning first.
if reasoning_accum:
cumulative_display += "<think>"
cumulative_display += reasoning_accum
@@ -4828,9 +4776,8 @@ class LlamaCppBackend:
),
}
elif reasoning_accum and not has_content_tokens:
- # Reasoning-only response (no content tokens):
- # show reasoning as plain text, matching
- # the final streaming pass behavior for
+ # Reasoning-only response: show reasoning as plain
+ # text, matching the final streaming pass for
# models that put everything in reasoning.
cumulative_display = reasoning_accum
yield {
@@ -4842,10 +4789,10 @@ class LlamaCppBackend:
# ── STREAMING path: no tool call ──
if detect_state == _S_STREAMING:
- # Safety net: check for XML tool signals in content.
- # The route layer resets prev_text on tool_start, so
- # post-tool synthesis streams correctly even if
- # content was already emitted before the tool XML.
+ # Safety net: check for XML tool signals in content. The
+ # route layer resets prev_text on tool_start, so post-tool
+ # synthesis streams correctly even if content was emitted
+ # before the tool XML.
_safety_tc = None
if auto_heal_tool_calls and any(s in content_accum for s in _TOOL_XML_SIGNALS):
_safety_tc = self._parse_tool_calls_from_text(
@@ -4853,14 +4800,12 @@ class LlamaCppBackend:
)
if not _safety_tc:
# ── Re-prompt on plan-without-action ──
- # If the model described what it intends to do
- # (forward-looking language) without calling any
- # tool, nudge it to act. Only fires once per
- # request and only on short responses that
- # contain intent signals -- a direct answer
- # like "4" or "Hello!" won't trigger this.
- # Use content if available, otherwise fall back
- # to reasoning text (reasoning-only stalls).
+ # If the model described its intent (forward-looking
+ # language) without calling a tool, nudge it to act.
+ # Fires at most once per request, only on short
+ # responses with intent signals -- "4" or "Hello!"
+ # won't trigger it. Use content if available, else
+ # fall back to reasoning text (reasoning-only stalls).
_stripped = content_accum.strip()
if not _stripped:
_stripped = reasoning_accum.strip()
@@ -4899,7 +4844,7 @@ class LlamaCppBackend:
),
}
)
- # Accumulate tokens and timing from this iteration
+ # Accumulate tokens and timing from this iteration.
_fu_r = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}
_accumulated_completion_tokens += _fu_r.get("completion_tokens", 0)
_it_r = _iter_timings or {}
@@ -4908,7 +4853,7 @@ class LlamaCppBackend:
yield {"type": "status", "text": ""}
continue
- # Content was already streamed. Yield metadata.
+ # Content already streamed; yield metadata.
yield {"type": "status", "text": ""}
_fu = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}
_fc = _fu.get("completion_tokens", 0)
@@ -4936,7 +4881,7 @@ class LlamaCppBackend:
}
return
- # Safety net caught tool XML -- treat as tool call
+ # Safety net caught tool XML -- treat as tool call.
tool_calls = _safety_tc
content_text = _strip_tool_markup(
content_accum,
@@ -4951,8 +4896,8 @@ class LlamaCppBackend:
tool_calls = None
content_text = content_accum
if has_structured_tc:
- # Filter out incomplete fragments (e.g. from
- # truncation by max_tokens or disconnect).
+ # Drop incomplete fragments (e.g. from max_tokens
+ # truncation or disconnect).
tool_calls = [
tool_calls_acc[i]
for i in sorted(tool_calls_acc)
@@ -4977,12 +4922,12 @@ class LlamaCppBackend:
f"{'structured delta' if has_structured_tc else 'content text'}"
)
if not tool_calls:
- # DRAINING but no tool calls (false positive).
- # Merge accumulated metrics from prior tool
- # iterations so they are not silently dropped.
+ # DRAINING but no tool calls (false positive). Merge
+ # accumulated metrics from prior tool iterations so
+ # they aren't silently dropped.
yield {"type": "status", "text": ""}
if content_accum:
- # Strip leaked tool-call XML before yielding
+ # Strip leaked tool-call XML before yielding.
content_accum = _strip_tool_markup(content_accum, final = True)
if content_accum:
yield {"type": "content", "text": content_accum}
@@ -5083,7 +5028,7 @@ class LlamaCppBackend:
}
# ── Duplicate call detection ──────────────
- # str(dict) is stable here: arguments always comes from
+ # str(dict) is stable here: arguments always come from
# json.loads on the same model output within one request,
# so insertion order is deterministic (Python 3.7+).
_tc_key = tool_name + str(arguments)
@@ -5103,11 +5048,10 @@ class LlamaCppBackend:
_effective_timeout = (
None if tool_call_timeout >= 9999 else tool_call_timeout
)
- # Guard against the model emitting a tool not in the
- # per-request advertised set: filtered MCP names, a
- # built-in the caller opted out of, or a stale name
- # from a prior turn. Mirrors the safetensors loop's
- # allowed_tool_names check.
+ # Guard against a tool not in the per-request
+ # advertised set: filtered MCP names, an opted-out
+ # built-in, or a stale name from a prior turn. Mirrors
+ # the safetensors loop's allowed_tool_names check.
_allowed = {
(t.get("function") or {}).get("name")
for t in (tools or [])
@@ -5136,7 +5080,7 @@ class LlamaCppBackend:
"result": result,
}
- # Nudge model to try a different approach on errors
+ # Nudge the model toward a different approach on errors.
_error_prefixes = (
"Error",
"Search failed",
@@ -5153,8 +5097,8 @@ class LlamaCppBackend:
if tool_name == "render_html" and not _is_error:
_render_html_succeeded = True
_tool_call_history.append((_tc_key, _is_error))
- # Strip image sentinel before feeding result to the LLM
- # (the full result with sentinel is still yielded via
+ # Strip image sentinel before feeding the result to the
+ # LLM (the full result with sentinel is still yielded via
# tool_end so the frontend can extract image paths).
_result_content = result
if "\n__IMAGES__:" in _result_content:
@@ -5175,9 +5119,9 @@ class LlamaCppBackend:
tool_msg["tool_call_id"] = tool_call_id
conversation.append(tool_msg)
- # Clear tool status badge before next generation iteration
+ # Clear tool status badge before the next generation.
yield {"type": "status", "text": ""}
- # Continue the loop to let model respond with context
+ # Continue so the model responds with tool context.
continue
except httpx.ConnectError:
@@ -5188,9 +5132,9 @@ class LlamaCppBackend:
raise
# ── Tool iteration cap reached -- synthesize final answer ──
- # The model used all iterations without producing a final text
- # response. Inject a nudge so the final streaming pass produces
- # a useful answer instead of continuing to request tools.
+ # The model used all iterations without a final text response. Nudge
+ # the final streaming pass to produce a useful answer instead of
+ # continuing to request tools.
if max_tool_iterations > 0:
conversation.append(
{
@@ -5203,10 +5147,10 @@ class LlamaCppBackend:
}
)
- # Clear status
+ # Clear status.
yield {"type": "status", "text": ""}
- # Final streaming pass with the full conversation context
+ # Final streaming pass with the full conversation context.
stream_payload = {
"messages": conversation,
"stream": True,
@@ -5287,7 +5231,7 @@ class LlamaCppBackend:
try:
chunk_data = json.loads(line[6:])
- # Capture server timings/usage from final chunks
+ # Capture server timings/usage from final chunks.
_chunk_timings = chunk_data.get("timings")
if _chunk_timings:
_metadata_timings = _chunk_timings
@@ -5315,7 +5259,7 @@ class LlamaCppBackend:
in_thinking = False
cumulative += token
cleaned = _strip_tool_markup(cumulative)
- # Only emit when cleaned text grows (monotonic).
+ # Emit only when cleaned text grows (monotonic).
if len(cleaned) > len(_last_emitted):
_last_emitted = cleaned
yield {"type": "content", "text": cleaned}
@@ -5362,7 +5306,7 @@ class LlamaCppBackend:
# ── TTS support ────────────────────────────────────────────
def detect_audio_type(self) -> Optional[str]:
- """Detect audio/TTS codec; swallows errors (use _strict variant to distinguish)."""
+ """Detect audio/TTS codec; swallows errors (use _strict to distinguish)."""
try:
return self._detect_audio_type_strict()
except Exception as e:
@@ -5370,7 +5314,7 @@ class LlamaCppBackend:
return None
def _detect_audio_type_strict(self) -> Optional[str]:
- """Codec name on match, None on definitive non-audio, raises on transport/JSON errors."""
+ """Codec name on match, None on non-audio, raises on transport/JSON errors."""
if not self.is_loaded:
return None
_auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
@@ -5393,7 +5337,7 @@ class LlamaCppBackend:
return []
return r.json().get("tokens", [])
- # Check codec-specific tokens (not generic ones that may exist in non-audio models)
+ # Codec-specific tokens (not generic ones that non-audio models may have)
if "<custom_token_" in _detok(128258) and "<custom_token_" in _detok(128259):
return "snac"
if len(_tok("<|AUDIO|>")) == 1 and len(_tok("<|audio_eos|>")) == 1:
@@ -5409,8 +5353,8 @@ class LlamaCppBackend:
return "dac"
return None
- # Prompt format per codec: (template, stop_tokens, needs_token_ids)
- # Matches prompts in InferenceBackend._generate_snac/bicodec/dac
+ # Prompt format per codec: (template, stop_tokens, needs_token_ids).
+ # Matches InferenceBackend._generate_snac/bicodec/dac.
_TTS_PROMPTS = {
"snac": (
"<custom_token_3>{text}<|eot_id|><custom_token_4>",
@@ -5432,7 +5376,7 @@ class LlamaCppBackend:
_codec_mgr = None # Shared AudioCodecManager instance
def init_audio_codec(self, audio_type: str) -> None:
- """Load the audio codec at model load time (mirrors non-GGUF path)."""
+ """Load the audio codec at model load time (mirrors the non-GGUF path)."""
import torch
from core.inference.audio_codecs import AudioCodecManager
@@ -5442,7 +5386,7 @@ class LlamaCppBackend:
device = "cuda" if torch.cuda.is_available() else "cpu"
model_repo_path = None
- # BiCodec needs a repo with BiCodec/ weights — download canonical SparkTTS
+ # BiCodec needs a repo with BiCodec/ weights -- download canonical SparkTTS
if audio_type == "bicodec":
from huggingface_hub import snapshot_download
import os
@@ -5465,7 +5409,7 @@ class LlamaCppBackend:
repetition_penalty: float = 1.1,
) -> tuple:
"""
- Generate TTS audio via llama-server /completion + codec decoding.
+ Generate TTS audio via llama-server /completion + codec decode.
Returns (wav_bytes, sample_rate).
"""
if audio_type not in self._TTS_PROMPTS:
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index 66cd138d99a..9d11157bf9a 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -3,11 +3,10 @@
"""Boundary validator for user-supplied llama-server pass-through args.
-Reject only flags Studio manages (model identity, auth, network,
-parallel slots). Everything else (sampling, ``-c``, ``-ngl``,
-``--flash-attn``, ``--cache-type-*``, ``--spec-*``, ``--jinja``, ...)
-is appended after Studio's auto-set flags so llama.cpp's last-wins
-parser lets the user override.
+Reject only flags Studio manages (model identity, auth, network, parallel
+slots). Everything else (sampling, ``-c``, ``-ngl``, ``--flash-attn``,
+``--cache-type-*``, ``--spec-*``, ``--jinja``, ...) is appended after
+Studio'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
"""
@@ -19,11 +18,11 @@ from typing import Iterable, Optional
# Each group = every alias (short + long) of one hard-denied flag.
# Extend the matching group when llama.cpp adds a new alias.
_DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
- # Parallel slots: owned by typer --parallel; a pass-through would
- # desync app.state.llama_parallel_slots from llama-server.
+ # Parallel slots: owned by typer --parallel; a pass-through would desync
+ # app.state.llama_parallel_slots from llama-server.
frozenset({"-np", "--parallel", "--n-parallel"}),
- # Model identity: Studio resolves it from LoadRequest; a second
- # -m would load a different model than Studio thinks it loaded.
+ # Model identity: Studio resolves it from LoadRequest; a second -m would
+ # load a different model than Studio thinks it loaded.
frozenset({"-m", "--model"}),
frozenset({"-mu", "--model-url"}),
frozenset({"-dr", "--docker-repo"}),
@@ -40,15 +39,15 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
frozenset({"--path"}),
frozenset({"--api-prefix"}),
frozenset({"--reuse-port"}),
- # Auth / TLS: Studio terminates auth; upstream --api-key / TLS
- # shadows Studio's key and breaks the proxy hop.
+ # Auth / TLS: Studio terminates auth; upstream --api-key / TLS shadows
+ # Studio's key and breaks the proxy hop.
frozenset({"--api-key"}),
frozenset({"--api-key-file"}),
frozenset({"--ssl-key-file"}),
frozenset({"--ssl-cert-file"}),
- # Built-in web UI. --webui/--no-webui is the legacy spelling;
- # upstream renamed to --ui/--no-ui + --ui-*. Keep both so prebuilt
- # and system llama.cpp binaries both match.
+ # Built-in web UI. --webui/--no-webui is the legacy spelling; upstream
+ # renamed to --ui/--no-ui + --ui-*. Keep both so prebuilt and system
+ # llama.cpp binaries match.
frozenset({"--webui", "--no-webui"}),
frozenset({"--ui", "--no-ui"}),
frozenset({"--ui-config"}),
@@ -62,8 +61,8 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
# those endpoints, breaking Studio's /v1/chat/completions hop.
frozenset({"--embedding", "--embeddings"}),
frozenset({"--rerank", "--reranking"}),
- # llama-server's own built-in tools flag would silently stack on top
- # of Studio's --enable-tools / --disable-tools policy resolver.
+ # llama-server's own built-in tools flag would silently stack on top of
+ # Studio's --enable-tools / --disable-tools policy resolver.
frozenset({"--tools"}),
)
@@ -74,10 +73,9 @@ def _flag_name(token: str) -> Optional[str]:
"""Flag name for ``token``, or None if it isn't a flag.
Peels `--key=value` to `--key`, treats `-1` / `-0.5` as values
- (llama-server shorts always start with a letter), strips
- whitespace, and normalises attached `-np8` / signed `-np-1` /
- digit-prefix-junk `-np8x` to `-np`. Mirrors the CLI's
- `_expand_attached_np_short`.
+ (llama-server shorts always start with a letter), strips whitespace, and
+ normalises attached `-np8` / signed `-np-1` / digit-prefix-junk `-np8x`
+ to `-np`. Mirrors the CLI's `_expand_attached_np_short`.
"""
token = token.strip()
if not token.startswith("-") or token in {"-", "--"}:
@@ -95,9 +93,9 @@ def _flag_name(token: str) -> Optional[str]:
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] = []
@@ -116,15 +114,15 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:
def is_managed_flag(flag: str) -> bool:
- """True if ``flag`` is Studio-managed. Normalises via ``_flag_name``
- so `-np8` / `--parallel=8` classify like the canonical tokens."""
+ """True if ``flag`` is Studio-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
-# Pass-through flags that shadow first-class LoadRequest fields;
-# stripped from inherited extras so they can't last-wins-override an
-# Apply that re-sets the same field.
+# Pass-through flags that shadow first-class LoadRequest fields; stripped
+# from inherited extras so they can't last-wins-override an Apply that
+# re-sets the same field.
_CONTEXT_FLAGS: frozenset[str] = frozenset({"-c", "--ctx-size"})
_CACHE_FLAGS: frozenset[str] = frozenset({"-ctk", "--cache-type-k", "-ctv", "--cache-type-v"})
_SPEC_FLAGS: frozenset[str] = frozenset(
@@ -157,16 +155,15 @@ _TEMPLATE_FLAGS: frozenset[str] = frozenset(
_SHADOWING_FLAGS: frozenset[str] = _CONTEXT_FLAGS | _CACHE_FLAGS | _SPEC_FLAGS | _TEMPLATE_FLAGS
-# Shadowing flags that take no value -- strip the flag only, never the
-# following token.
+# Shadowing flags that take no value -- strip the flag only, not the next token.
_BOOLEAN_SHADOWING_FLAGS: frozenset[str] = frozenset({"--spec-default", "--jinja", "--no-jinja"})
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 flag parsing for the one pass-through
- numeric knob Studio's load-time fit logic needs to see.
+ Mirrors llama.cpp's last-wins parsing for the one pass-through numeric
+ knob Studio's load-time fit logic needs to see.
"""
if not args:
return None
@@ -204,10 +201,10 @@ def parse_ctx_override(args: Optional[Iterable[str]]) -> Optional[int]:
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 the two-line ``ctx_override = parse_ctx_override(...);
- requested_ctx = ctx_override if ctx_override is not None else n_ctx`` pattern
- used by ``load_model`` so tests don't have to reimplement the conditional
- locally and then assert against their own reimplementation.
+ Single source of truth for the ``ctx_override = parse_ctx_override(...);
+ requested_ctx = ctx_override if ctx_override is not None else n_ctx``
+ pattern used by ``load_model``, so tests don't reimplement the
+ conditional and assert against their own reimplementation.
"""
override = parse_ctx_override(args)
return override if override is not None else fallback_n_ctx
@@ -216,10 +213,10 @@ def resolve_requested_ctx(args: Optional[Iterable[str]], fallback_n_ctx: int) ->
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
- Studio's KV estimate has a single cache_type_kv knob.
+ Like parse_ctx_override but for cache type. Recognises -ctk (key) and
+ -ctv (value); when both appear, returns the last-wins value, treating
+ key and value flags as one setting because Studio's KV estimate has a
+ single cache_type_kv knob.
"""
if not args:
return None
@@ -256,8 +253,7 @@ def resolve_cache_type_kv(
) -> Optional[str]:
"""Return the cache type load_model should treat as requested.
- Single source of truth for the cache override conditional used by
- ``load_model``.
+ 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
@@ -274,10 +270,9 @@ def strip_shadowing_flags(
"""Strip flags that shadow first-class Studio 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). Each ``strip_*`` toggle
- controls one group; the route only strips groups whose first-class
- field the caller actually supplied.
+ inherited `-c 4096` can't override the current `max_seq_length` (same for
+ cache / spec / template). Each ``strip_*`` toggle controls one group; the
+ route only strips groups whose first-class field the caller supplied.
"""
shadowing: set[str] = set()
if strip_context:
@@ -299,8 +294,8 @@ def strip_shadowing_flags(
out.append(tok)
i += 1
continue
- # Drop the flag; consume the next token too unless it's
- # boolean, already inline (`-c=4096`), or another flag.
+ # Drop the flag; also consume the next token unless it's boolean,
+ # already inline (`-c=4096`), or another flag.
if flag in _BOOLEAN_SHADOWING_FLAGS or "=" in tok:
i += 1
elif i + 1 < n and _flag_name(tokens[i + 1]) is None:
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index ad5f67f325a..d1a565b2323 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -31,20 +31,20 @@ def parse_stdio_command(address: str) -> list[str]:
posix = sys.platform != "win32"
parts = shlex.split(address, posix = posix)
if not posix:
- # posix=False keeps backslash paths intact but also keeps the surrounding
- # quotes on a token. Strip a matched pair so the argv reaches the
- # subprocess clean ('"C:\\Program Files\\node"' -> C:\\Program Files\\node).
+ # posix=False keeps backslash paths intact but also keeps surrounding
+ # quotes on a token. Strip a matched pair so argv reaches the subprocess
+ # clean ('"C:\\Program Files\\node"' -> C:\\Program Files\\node).
parts = [p[1:-1] if len(p) >= 2 and p[0] == p[-1] and p[0] in "\"'" else p for p in parts]
return parts
def stdio_mcp_enabled() -> bool:
- """stdio MCP servers spawn local processes as the backend user (and bypass
- the python/terminal sandbox), so they are only allowed when the backend
- host is the user's own machine. The Tauri desktop app sets
+ """stdio MCP servers spawn local processes as the backend user (bypassing
+ the python/terminal sandbox), so they're allowed only when the backend host
+ is the user's own machine. The Tauri desktop app sets
UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 (see main.py); advanced localhost /
- self-hosted users can opt in with the same variable. It stays off for
- Colab and any network (0.0.0.0) bind."""
+ self-hosted users can opt in with the same variable. Stays off for Colab
+ and any network (0.0.0.0) bind."""
return os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") == "1"
@@ -63,8 +63,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
- environment 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
@@ -83,7 +83,7 @@ def _oauth_store():
from utils.paths.storage_roots import ensure_dir, studio_root
# Hash keys/collections — fastmcp uses raw URLs like https://x.com as
- # keys and FileTreeStore would treat the "://" as nested directories.
+ # 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(),
@@ -93,12 +93,11 @@ def _oauth_store():
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 have to
- clear the old credentials explicitly. Otherwise re-registering the
- same URL would silently reuse the old account's token. The entire
- body runs inside the protected block -- store / OAuth construction
- failing must not make the delete / update route 500."""
+ """Drop any persisted OAuth tokens for ``url``. fastmcp keys tokens by MCP
+ URL, so on server delete / URL change / OAuth disable we must clear old
+ credentials explicitly; otherwise re-registering the same URL silently
+ reuses the old account's token. The whole body is protected -- store / OAuth
+ construction failing must not 500 the delete / update route."""
try:
from fastmcp.client.auth import OAuth
auth = OAuth(mcp_url = url, token_storage = _oauth_store())
@@ -124,9 +123,9 @@ 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's safe default env).
- # keep_alive=False tears the subprocess down on exit, so a one-shot
- # probe/tool call never leaves an orphan process.
+ # env vars ride the headers field (merged over the SDK's safe default
+ # env). keep_alive=False tears the subprocess down on exit, so a
+ # one-shot probe/tool call never leaves an orphan.
return Client(
StdioTransport(
command = parts[0],
@@ -192,10 +191,10 @@ def call_tool_sync(
) -> str:
"""Synchronously call an MCP tool.
- ``cancel_event``: optional ``threading.Event``. When set, the in-flight
- HTTP call is cancelled and the function returns a cancellation Error.
- Polled in parallel with the tool call via ``asyncio.wait`` so a /cancel
- POST from the UI interrupts even mid-network-read.
+ ``cancel_event``: optional ``threading.Event``. When set, the in-flight HTTP
+ call is cancelled and a cancellation Error is returned. Polled in parallel
+ with the tool call via ``asyncio.wait`` so a /cancel POST from the UI
+ interrupts even mid-network-read.
"""
async def _call() -> Any:
@@ -204,14 +203,14 @@ def call_tool_sync(
async def _watch_cancel() -> None:
# 50 ms cadence keeps cancellation responsive without busy-looping;
- # matches the cadence routes/inference.py uses for cancel watchers.
+ # matches routes/inference.py's cancel watcher cadence.
while cancel_event is not None and not cancel_event.is_set():
await asyncio.sleep(0.05)
async def _race() -> Any:
- # Check cancellation before spawning the call task so a pre-set
- # event short-circuits before opening the transport / HTTP
- # connection (reviewer-reproduced race).
+ # Check cancellation before spawning the call task so a pre-set event
+ # short-circuits before opening the transport / HTTP connection
+ # (reviewer-reproduced race).
if cancel_event is not None and cancel_event.is_set():
raise _MCPCancelled
call_task = asyncio.create_task(_call())
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 5913c292823..31bca0f5d62 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -65,10 +65,10 @@ class MLXInferenceBackend:
def _configure_memory_limits(self):
"""Apply Metal memory caps before loading a model.
- Mirrors MLXTrainer._configure_memory_limits's defaults:
+ Mirrors MLXTrainer._configure_memory_limits defaults:
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.
+ wired_limit = min(recommended, memory_limit). Recorded so unload can
+ lower wired_limit back to release pinned RAM.
"""
import mlx.core as mx
@@ -109,18 +109,16 @@ class MLXInferenceBackend:
model_name = config.identifier if hasattr(config, "identifier") else str(config)
is_vision = getattr(config, "is_vision", False)
- # GGUF guard. GGUF models are served via llama-server in the
- # parent process, NOT via mlx-lm in this MLX subprocess. The
- # route at studio/backend/routes/inference.py:592 (`if config.
- # is_gguf:`) is responsible for sending GGUF traffic to the
- # llama-server backend before reaching the MLX orchestrator.
- # If we end up here with is_gguf=True, the route's
- # `detect_gguf_model_remote` returned None on its first call
- # (transient HF Hub flake) but the subprocess re-detection
- # succeeded. The subprocess cannot reach into the parent's
- # llama-server, so all we can do is raise loudly so the caller
- # gets a clear error instead of a cryptic
- # "config.json does not exist" from mlx_lm.utils.load_model.
+ # GGUF guard. GGUF models are served via llama-server in the parent
+ # process, NOT via mlx-lm in this MLX subprocess. The route at
+ # studio/backend/routes/inference.py:592 (`if config.is_gguf:`) sends
+ # GGUF traffic to llama-server before reaching the MLX orchestrator.
+ # Reaching here with is_gguf=True means the route's
+ # `detect_gguf_model_remote` returned None on its first call (transient
+ # HF Hub flake) but the subprocess re-detection succeeded. The
+ # subprocess can't reach the parent's llama-server, so raise loudly to
+ # give the caller a clear error instead of a cryptic "config.json does
+ # not exist" from mlx_lm.utils.load_model.
if getattr(config, "is_gguf", False):
raise RuntimeError(
f"MLXInferenceBackend cannot load GGUF model '{model_name}': "
@@ -187,9 +185,9 @@ class MLXInferenceBackend:
"audio_type": None,
"has_audio_input": False,
}
- # Capture chat_template_info so the worker IPC reply can ship
- # it back to the parent and the route layer classifies
- # capabilities the same way as the transformers / GGUF paths.
+ # Capture chat_template_info so the worker IPC reply can ship it back
+ # to the parent and the route layer classifies capabilities the same
+ # way as the transformers / GGUF paths.
self._populate_chat_template_info(model_name)
logger.info("Model %s loaded successfully", model_name)
@@ -198,10 +196,9 @@ class MLXInferenceBackend:
def _populate_chat_template_info(self, model_name: str) -> None:
"""Mirror InferenceBackend._load_chat_template_info for MLX.
- Stores ``chat_template_info`` on ``self.models[model_name]``
- with the resolved ``tokenizer.chat_template`` so
- ``_detect_safetensors_features`` (route layer) sees the same
- template the model actually uses."""
+ Stores ``chat_template_info`` on ``self.models[model_name]`` with the
+ resolved ``tokenizer.chat_template`` so ``_detect_safetensors_features``
+ (route layer) sees the template the model actually uses."""
entry = self.models.get(model_name)
if not entry:
return
@@ -276,10 +273,9 @@ class MLXInferenceBackend:
max_new_tokens = 256,
repetition_penalty = 1.0,
cancel_event = None,
- # Reasoning / tool kwargs forwarded by the route + worker -- the
- # MLX path renders the template via apply_chat_template_for_
- # generation so these are honoured the same way as the
- # transformers path.
+ # Reasoning / tool kwargs forwarded by the route + worker -- the MLX
+ # path renders the template via apply_chat_template_for_generation so
+ # these are honoured the same way as the transformers path.
tools = None,
enable_thinking = None,
reasoning_effort = None,
@@ -308,7 +304,7 @@ class MLXInferenceBackend:
{"type": "text", "text": content},
]
elif isinstance(content, list):
- # Prepend image if not already there
+ # Prepend image if not already present
has_image = any(
p.get("type") == "image" for p in content if isinstance(p, dict)
)
@@ -389,8 +385,8 @@ class MLXInferenceBackend:
min_p = float(min_p or 0.0),
min_tokens_to_keep = 1,
)
- # Only build a logits processor when we actually have a non-trivial
- # repetition penalty (1.0 is the no-op value).
+ # Only build a logits processor for a non-trivial repetition penalty
+ # (1.0 is the no-op value).
logits_processors = None
if repetition_penalty is not None and float(repetition_penalty) not in (
0.0,
@@ -425,7 +421,7 @@ class MLXInferenceBackend:
):
final_response = response
token_ids.append(response.token)
- # Decode full sequence with skip_special_tokens — same as GPU
+ # Decode full sequence with skip_special_tokens — like GPU
cumulative = self._tokenizer.decode(
token_ids,
skip_special_tokens = True,
@@ -471,10 +467,9 @@ class MLXInferenceBackend:
apply_chat_template_for_generation,
)
- # Pick the chat-template-aware caller: processors that expose
- # their own apply_chat_template + chat_template attr (e.g.
- # Qwen2.5-VL) use it directly; otherwise fall back to the
- # nested tokenizer.
+ # Pick the chat-template-aware caller: processors that expose their own
+ # apply_chat_template + chat_template attr (e.g. Qwen2.5-VL) use it
+ # directly; otherwise fall back to the nested tokenizer.
chat_target = self._processor
if (
getattr(self._processor, "apply_chat_template", None) is None
@@ -492,8 +487,8 @@ class MLXInferenceBackend:
preserve_thinking = preserve_thinking,
)
- # For VLM: always use mlx_vlm's stream_generate which handles
- # pixel_values properly (passes None for text-only, image for VLM)
+ # For VLM: always use mlx_vlm's stream_generate, which handles
+ # pixel_values properly (None for text-only, image for VLM)
images = [image] if image is not None else None
cumulative = ""
@@ -503,8 +498,8 @@ class MLXInferenceBackend:
image is not None,
)
# mlx_vlm.stream_generate forwards **kwargs into generate_step, which
- # accepts temp/top_p/top_k/repetition_penalty (and builds the sampler
- # + logits_processors internally). Pass them through.
+ # accepts temp/top_p/top_k/repetition_penalty (building the sampler +
+ # logits_processors internally). Pass them through.
# NOTE: mlx_vlm.generate_step expects ``temperature=`` (long form) —
# passing ``temp=`` silently falls into **kwargs and is ignored,
# leaving generation stuck at the default 0.0 (greedy).
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 1c132c3f523..d7fc1ef9a67 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -4,13 +4,12 @@
"""
Inference orchestrator — subprocess-based.
-Provides the same API as InferenceBackend, but delegates all ML work
-to a persistent subprocess. The subprocess is spawned on first model load
-and stays alive for subsequent requests.
+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 that need 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 is spawned with the correct version.
+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.
"""
@@ -51,9 +50,8 @@ class InferenceOrchestrator:
"""
Inference backend orchestrator — subprocess-based.
- Exposes the same API surface as InferenceBackend so routes/inference.py
- needs minimal changes. Internally, all heavy ML operations happen in
- a persistent subprocess.
+ Same API surface as InferenceBackend (so routes/inference.py needs
+ minimal changes); all heavy ML work happens in a persistent subprocess.
"""
def __init__(self):
@@ -66,9 +64,9 @@ class InferenceOrchestrator:
self._gen_lock = threading.Lock() # Serializes generation — one request at a time
# Dispatcher state — for compare mode (adapter-controlled requests).
- # Instead of serializing via _gen_lock, adapter-controlled requests
- # send commands directly to the subprocess and read from per-request
- # mailboxes. A dispatcher thread routes resp_queue events by request_id.
+ # These bypass _gen_lock: they send commands directly and read from
+ # per-request mailboxes. A dispatcher thread routes resp_queue events
+ # by request_id.
self._mailboxes: dict[str, queue.Queue] = {}
self._mailbox_lock = threading.Lock() # Protects _mailboxes dict
self._dispatcher_thread: Optional[threading.Thread] = None
@@ -92,7 +90,7 @@ class InferenceOrchestrator:
atexit.register(self._cleanup)
logger.info("InferenceOrchestrator initialized (subprocess mode)")
- # Kick off background fetch of top models from HF
+ # Background fetch of top models from HF
threading.Thread(target = self._fetch_top_models, daemon = True, name = "top-models").start()
# ------------------------------------------------------------------
@@ -105,10 +103,9 @@ class InferenceOrchestrator:
self._top_models_ready.wait(timeout = 5)
top_gguf = self._top_gguf_cache or []
top_hub = self._top_hub_cache or []
- # Curated static defaults first (editorial picks like new models),
- # then HF download-ranked models to backfill.
- # Send extras so the frontend still has 4 per category
- # after removing already-downloaded models.
+ # Curated static defaults first (editorial picks), then HF
+ # download-ranked models to backfill. Send extras so the frontend
+ # still has 4 per category after removing downloaded ones.
result: list[str] = []
seen: set[str] = set()
for m in self._static_models + top_gguf + top_hub:
@@ -133,8 +130,8 @@ class InferenceOrchestrator:
)
if resp.status_code == 200:
models = resp.json()
- # Top 40 GGUFs - frontend pages through them on-demand via
- # infinite scroll, so we send a deep pool.
+ # Top 40 GGUFs - frontend pages through them via infinite
+ # scroll, so send a deep pool.
gguf_ids = [m["id"] for m in models if m.get("id", "").upper().endswith("-GGUF")][
:40
]
@@ -201,7 +198,7 @@ class InferenceOrchestrator:
self._cancel_generation()
time.sleep(0.5) # Brief wait for generation to stop
- # 2. Drain stale responses from queue
+ # 2. Drain stale responses
self._drain_queue()
# 3. Send shutdown command
@@ -243,7 +240,7 @@ class InferenceOrchestrator:
self._shutdown_subprocess(timeout = 5.0)
def _ensure_subprocess_alive(self) -> bool:
- """Check if subprocess is alive."""
+ """True if the subprocess is alive."""
return self._proc is not None and self._proc.is_alive()
# ------------------------------------------------------------------
@@ -277,14 +274,12 @@ class InferenceOrchestrator:
) -> 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 subprocess crash.
+ Also handles 'status' and 'error' events during the wait. Returns the
+ matching response dict; raises RuntimeError on timeout or crash.
- The *timeout* is an **inactivity** timeout: it resets whenever the
- subprocess sends a status message, so long-running operations (large
- downloads, slow model loads) won't be killed as long as the subprocess
- keeps reporting progress.
+ *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.
"""
deadline = time.monotonic() + timeout
@@ -345,8 +340,8 @@ class InferenceOrchestrator:
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 to ensure stale tokens from the cancelled
- generation don't leak into the next request.
+ 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:
@@ -367,10 +362,9 @@ class InferenceOrchestrator:
def _start_dispatcher(self) -> None:
"""Start the dispatcher thread if not already running.
- The dispatcher reads from the shared resp_queue and routes
- responses to per-request mailbox queues. This allows multiple
- adapter-controlled (compare) requests to be in-flight without
- holding _gen_lock.
+ 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.
"""
if self._dispatcher_thread is not None and self._dispatcher_thread.is_alive():
return
@@ -422,9 +416,8 @@ class InferenceOrchestrator:
mbox.put(resp)
continue
- # No matching mailbox — might be for a _gen_lock reader or orphaned
- # Push it back so _read_resp can pick it up. But we can't un-get
- # from mp.Queue, so log a warning.
+ # No matching mailbox — maybe for a _gen_lock reader or orphaned.
+ # Can't un-get from mp.Queue, so just log a warning.
if rtype not in ("status",):
logger.debug(
"Dispatcher: no mailbox for request_id=%s type=%s, dropping",
@@ -453,13 +446,13 @@ class InferenceOrchestrator:
) -> Generator[str, None, None]:
"""Dispatched generation — sends command without holding _gen_lock.
- Uses a per-request mailbox to receive tokens. This allows two
- compare-mode requests to be queued in the subprocess simultaneously,
- eliminating the inter-generation round-trip overhead.
+ Uses a per-request mailbox for tokens, so two compare-mode requests
+ can be queued in the subprocess at once, avoiding the
+ inter-generation round-trip overhead.
- The subprocess processes commands sequentially from its cmd_queue,
- so generation is still serialized at the GPU level — we just avoid
- the orchestrator-level lock contention.
+ The subprocess runs commands sequentially from its cmd_queue, so
+ generation stays serialized at the GPU level — this only avoids
+ orchestrator-level lock contention.
"""
if not self._ensure_subprocess_alive():
yield "Error: Inference subprocess is not running"
@@ -532,7 +525,7 @@ class InferenceOrchestrator:
rtype = resp.get("type", "")
if rtype == "token":
- # Check cancel from route (e.g. SSE connection closed)
+ # Cancel from route (e.g. SSE connection closed)
if cancel_event is not None and cancel_event.is_set():
self._cancel_generation()
# Drain remaining events for this request
@@ -574,8 +567,8 @@ class InferenceOrchestrator:
def _wait_dispatcher_idle(self) -> None:
"""Wait for all dispatched requests to complete, then stop dispatcher.
- Called by _generate_inner before using the _gen_lock path, to ensure
- the dispatcher thread isn't competing for resp_queue reads.
+ Called by _generate_inner before the _gen_lock path so the dispatcher
+ thread isn't competing for resp_queue reads.
"""
if self._dispatcher_thread is None or not self._dispatcher_thread.is_alive():
return
@@ -588,9 +581,9 @@ class InferenceOrchestrator:
break
time.sleep(0.1)
- # Only stop dispatcher if all mailboxes drained. If compare
- # requests are still active, leave the dispatcher running so
- # their token routing isn't killed mid-stream.
+ # Only stop dispatcher if all mailboxes drained. If compare requests
+ # are still active, leave it running so their token routing isn't
+ # killed mid-stream.
with self._mailbox_lock:
still_active = bool(self._mailboxes)
if still_active:
@@ -618,9 +611,9 @@ class InferenceOrchestrator:
) -> bool:
"""Load a model for inference.
- Always spawns a fresh subprocess for each model load. This ensures
- a clean Python interpreter — no stale unsloth patches, torch.compile
- caches, or inspect.getsource() failures from a previous model.
+ Always spawns a fresh subprocess per load for a clean interpreter —
+ no stale unsloth patches, torch.compile caches, or
+ inspect.getsource() failures from a previous model.
"""
from utils.transformers_version import needs_transformers_5
@@ -649,9 +642,9 @@ class InferenceOrchestrator:
sub_config["resolved_gpu_ids"] = resolved_gpu_ids
sub_config["gpu_selection"] = gpu_selection
- # Always kill existing subprocess and spawn fresh.
- # Reusing a subprocess after unsloth patches torch internals
- # causes inspect.getsource() failures on the next model load.
+ # Always kill the existing subprocess and spawn fresh: reusing one
+ # after unsloth patches torch internals causes
+ # inspect.getsource() failures on the next load.
if self._ensure_subprocess_alive():
self._cancel_generation()
time.sleep(0.3)
@@ -680,7 +673,7 @@ class InferenceOrchestrator:
try:
resp = self._wait_response("loaded")
except DownloadStallError:
- # First stall and Xet was enabled -> retry with Xet disabled
+ # First stall with Xet enabled -> retry with Xet disabled
if attempt == 0 and not disable_xet:
logger.warning(
"Download stalled for '%s' -- retrying with HF_HUB_DISABLE_XET=1",
@@ -689,7 +682,7 @@ class InferenceOrchestrator:
self._shutdown_subprocess(timeout = 5)
disable_xet = True
continue
- # Second stall (or already had xet disabled) -> give up
+ # Second stall (or xet already disabled) -> give up
self._shutdown_subprocess(timeout = 5)
raise RuntimeError(
f"Download stalled for '{model_name}' even with "
@@ -745,7 +738,7 @@ class InferenceOrchestrator:
return True
if not self._ensure_subprocess_alive():
- # No subprocess — just clear local state
+ # No subprocess — clear local state
self.models.pop(model_name, None)
if self.active_model_name == model_name:
self.active_model_name = None
@@ -797,13 +790,13 @@ class InferenceOrchestrator:
"""Generate response, streaming tokens from subprocess.
Optional ``tools`` / ``enable_thinking`` / ``reasoning_effort`` /
- ``preserve_thinking`` kwargs are forwarded into the worker so
+ ``preserve_thinking`` kwargs are forwarded to the worker so
``tokenizer.apply_chat_template`` can render tool schemas and
- reasoning controls when the template understands them.
+ reasoning controls when the template supports them.
- ``stats_holder``: caller-owned dict; on gen_done its "stats" key
- receives the worker's usage/timings. Request-scoped by design so
- concurrent streams cannot read each other's stats.
+ ``stats_holder``: caller-owned dict; on gen_done its "stats" key gets
+ the worker's usage/timings. Request-scoped so concurrent streams cannot
+ read each other's stats.
"""
yield from self._generate_inner(
messages = messages,
@@ -847,13 +840,12 @@ class InferenceOrchestrator:
stats_holder: Optional[dict] = None,
**_unused,
):
- """Run the safetensors agentic tool loop in this (parent)
- process, calling the worker for each generation turn.
+ """Run the safetensors agentic tool loop in this (parent) process,
+ calling the worker for each generation turn.
- Yields the same event dicts as the GGUF tool loop so the route
- layer can stream both backends through one helper. See
- ``safetensors_agentic.run_safetensors_tool_loop`` for the
- event protocol.
+ Yields the same event dicts as the GGUF tool loop so the route layer
+ can stream both backends through one helper. See
+ ``safetensors_agentic.run_safetensors_tool_loop`` for the protocol.
"""
from core.inference.safetensors_agentic import run_safetensors_tool_loop
from core.inference.tools import execute_tool
@@ -861,8 +853,8 @@ class InferenceOrchestrator:
max_new_tokens = max_tokens if max_tokens and max_tokens > 0 else 2048
def _single_turn(conv: list):
- # ``conv`` already carries any system message because the
- # loop appends to a list seeded with system+user above.
+ # ``conv`` already carries any system message: the loop appends
+ # to a list seeded with system+user above.
common_kwargs = dict(
messages = conv,
system_prompt = "",
@@ -914,9 +906,9 @@ class InferenceOrchestrator:
) -> Generator[str, None, None]:
"""Generate with adapter control, streaming tokens from subprocess.
- Uses the dispatcher path (no _gen_lock) so that compare-mode
- requests don't block each other. The subprocess naturally
- serializes them via its sequential command loop.
+ 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.
"""
yield from self._generate_dispatched(
use_adapter = use_adapter,
@@ -946,9 +938,8 @@ class InferenceOrchestrator:
) -> Generator[str, None, None]:
"""Inner generation logic — sends command to subprocess, yields tokens.
- Serialized by _gen_lock: only one generation runs at a time.
- This prevents concurrent readers from consuming each other's
- tokens off the shared resp_queue.
+ 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 "Error: Inference subprocess is not running"
@@ -959,13 +950,13 @@ class InferenceOrchestrator:
return
# If the dispatcher is running (from a previous compare-mode request),
- # wait for all dispatched requests to finish, then stop the dispatcher
- # so we can safely read from resp_queue directly.
+ # wait for dispatched requests to finish then stop it, so we can read
+ # from resp_queue directly.
self._wait_dispatcher_idle()
- # Serialize generation — single GPU, one generation at a time.
- # Without this lock, two concurrent readers on the same resp_queue
- # can consume and drop each other's token events.
+ # Serialize generation — single GPU, one generation at a time. Without
+ # this lock, two concurrent readers on the same resp_queue can consume
+ # and drop each other's token events.
with self._gen_lock:
yield from self._generate_locked(
messages = messages,
@@ -1029,8 +1020,8 @@ class InferenceOrchestrator:
if use_adapter is not None:
cmd["use_adapter"] = use_adapter
- # Only forward template kwargs the caller actually set so older
- # workers that ignore unknown keys still work.
+ # Only forward template kwargs the caller set, so older workers that
+ # ignore unknown keys still work.
if tools is not None:
cmd["tools"] = tools
if enable_thinking is not None:
@@ -1046,8 +1037,8 @@ class InferenceOrchestrator:
yield f"Error: {exc}"
return
- # Yield tokens from response queue — we are the only reader
- # because _gen_lock is held.
+ # Yield tokens from response queue — we are the only reader since
+ # _gen_lock is held.
while True:
resp = self._read_resp(timeout = 30.0)
@@ -1071,10 +1062,10 @@ class InferenceOrchestrator:
return
if rtype == "token":
- # Check cancel from route (e.g. SSE connection closed)
+ # Cancel from route (e.g. SSE connection closed)
if cancel_event is not None and cancel_event.is_set():
self._cancel_generation()
- # Wait for the subprocess to acknowledge cancellation
+ # Wait for the subprocess to ack cancellation
# (gen_done/gen_error) so stale events don't leak into
# the next generation request.
self._drain_until_gen_done(timeout = 5.0)
@@ -1117,7 +1108,7 @@ class InferenceOrchestrator:
) -> Tuple[bytes, int]:
"""Generate TTS audio. Returns (wav_bytes, sample_rate).
- Blocking — sends command and waits for the complete audio response.
+ Blocking — sends command and waits for the full audio response.
"""
if not self._ensure_subprocess_alive():
raise RuntimeError("Inference subprocess is not running")
@@ -1242,7 +1233,7 @@ class InferenceOrchestrator:
request_id = str(uuid.uuid4())
- # Convert numpy array to list for mp.Queue serialization
+ # numpy array -> list for mp.Queue serialization
audio_data = (
audio_array.tolist() if hasattr(audio_array, "tolist") else list(audio_array)
)
@@ -1310,8 +1301,8 @@ class InferenceOrchestrator:
img,
max_size: int = 800,
):
- """Resize image while maintaining aspect ratio.
- No ML imports needed — runs locally in parent process.
+ """Resize image preserving aspect ratio.
+ No ML imports — runs locally in the parent process.
"""
if img is None:
return None
@@ -1331,26 +1322,26 @@ class InferenceOrchestrator:
return base64.b64encode(buf.getvalue()).decode("ascii")
def get_current_model(self) -> Optional[str]:
- """Get currently active model name."""
+ """Currently active model name."""
return self.active_model_name
def is_model_loading(self) -> bool:
- """Check if any model is currently loading."""
+ """True if any model is loading."""
return len(self.loading_models) > 0
def get_loading_model(self) -> Optional[str]:
- """Get name of currently loading model."""
+ """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:
- """Check if current model supports vision."""
+ """True if the current model supports vision."""
if self.active_model_name and self.active_model_name in self.models:
return self.models[self.active_model_name].get("is_vision", False)
return False
def _is_gpt_oss_model(self, model_name: str = None) -> bool:
- """Parent-side gpt-oss detection so the safetensors route can run
- the same guard without an IPC round-trip to the subprocess."""
+ """Parent-side gpt-oss detection so the safetensors route can run the
+ same guard without an IPC round-trip to the subprocess."""
from utils.datasets import is_gpt_oss_model_name
return is_gpt_oss_model_name(model_name or self.active_model_name or "")
@@ -1360,7 +1351,7 @@ _inference_backend = None
def get_inference_backend() -> InferenceOrchestrator:
- """Get global inference backend instance (orchestrator)."""
+ """Global inference backend instance (orchestrator)."""
global _inference_backend
if _inference_backend is None:
_inference_backend = InferenceOrchestrator()
diff --git a/studio/backend/core/inference/pricing.py b/studio/backend/core/inference/pricing.py
index a604749c9cb..efb92681708 100644
--- a/studio/backend/core/inference/pricing.py
+++ b/studio/backend/core/inference/pricing.py
@@ -1,8 +1,7 @@
# 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 per-MTok pricing tables and ``calculate_cost`` helper for
-turning an upstream ``usage`` block into a USD figure.
+"""Per-MTok pricing tables and ``calculate_cost`` (usage block -> USD).
Sources: Anthropic prompt-caching docs (5m write 1.25x, 1h write 2x,
read 0.1x), web search ($10/1000), code execution; OpenAI pricing page.
@@ -12,13 +11,13 @@ from __future__ import annotations
from typing import Any, Optional
-# Per-MTok base pricing in USD. Cache multipliers are applied ON
-# `input_per_mtok` (not absolute prices), matching Anthropic's docs.
+# Per-MTok base USD. Cache multipliers apply to `input_per_mtok`
+# (not absolute prices), per Anthropic docs.
ANTHROPIC_PRICING: dict[str, dict[str, float]] = {
"claude-opus-4-7": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-6": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
- # Alias both the bare id and dated id: backend defaults reference
- # the bare form, which won't prefix-match the dated key.
+ # Alias bare + dated id: backend defaults use the bare form, which
+ # won't prefix-match the dated key.
"claude-opus-4-5": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-5-20251101": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-1": {"input_per_mtok": 15.0, "output_per_mtok": 75.0},
@@ -34,8 +33,8 @@ ANTHROPIC_PRICING: dict[str, dict[str, float]] = {
OPENAI_PRICING: dict[str, dict[str, float]] = {
# Verified against developers.openai.com/api/docs/pricing.
- # `long_context_*` keys apply once input exceeds the threshold
- # (gpt-5.5/5.4: 272k); families without these keys ship a single rate.
+ # `long_context_*` keys apply past the threshold (gpt-5.5/5.4: 272k);
+ # families without them ship a single rate.
"gpt-5.5": {
"input_per_mtok": 5.0,
"output_per_mtok": 30.0,
@@ -58,28 +57,28 @@ OPENAI_PRICING: dict[str, dict[str, float]] = {
# chat-latest aliases gpt-5.5.
"gpt-5.3-chat-latest": {"input_per_mtok": 5.0, "output_per_mtok": 30.0},
"chat-latest": {"input_per_mtok": 5.0, "output_per_mtok": 30.0},
- # o-series and gpt-4.5 are no longer on the pricing page; omit them
- # so calculate_cost returns priced=False rather than silently $0.
+ # o-series / gpt-4.5 left off the pricing page: omit so calculate_cost
+ # returns priced=False instead of silently $0.
}
-# Shared multipliers (same across every Anthropic model).
+# Shared multipliers (all Anthropic models).
ANTHROPIC_CACHE_5M_WRITE_MULT = 1.25
ANTHROPIC_CACHE_1H_WRITE_MULT = 2.0
ANTHROPIC_CACHE_READ_MULT = 0.1
-# Anthropic fast-mode (Opus 4.6 / 4.7 only): 6x standard on input + output.
+# Anthropic fast-mode (Opus 4.6/4.7 only): 6x on input + output.
# https://platform.claude.com/docs/en/build-with-claude/fast-mode#pricing
ANTHROPIC_FAST_MODE_MULT = 6.0
-# OpenAI: cache reads 0.1x; cache writes pay normal input price.
+# OpenAI: cache reads 0.1x; cache writes pay input price.
OPENAI_CACHE_READ_MULT = 0.1
-# Server-tool surcharges. Anthropic code_exec is $0.05/hr marginal
-# (50 free hours/day per org, not visible here).
+# Server-tool surcharges. Anthropic code_exec: $0.05/hr marginal
+# (50 free hours/day per org, not shown here).
ANTHROPIC_WEB_SEARCH_USD_PER_1K = 10.0
ANTHROPIC_CODE_EXEC_USD_PER_HOUR = 0.05
-# OpenAI container bills per memory tier; we report the 1g default
-# ($0.09/hour) since the tier isn't surfaced to the cost ledger.
+# OpenAI container bills per memory tier; report the 1g default
+# ($0.09/hr) since the tier isn't surfaced to the ledger.
OPENAI_WEB_SEARCH_USD_PER_1K = 10.0
OPENAI_CONTAINER_USD_PER_HOUR = 0.09 # 1g default tier
@@ -96,10 +95,9 @@ def _lookup(provider: str, model: str) -> Optional[dict[str, float]]:
return None
if model in table:
return table[model]
- # Longest-prefix match on a dash boundary: lets dated snapshots
- # inherit canonical prices while preventing "claude-opus-4-15"
- # from matching "claude-opus-4-1" or "gpt-5.5-prod" from matching
- # "gpt-5.5-pro". Sort longest-first to pick the most specific row.
+ # Longest-prefix match on a dash boundary, longest-first: dated
+ # snapshots inherit canonical prices, but "claude-opus-4-15" won't
+ # match "claude-opus-4-1" nor "gpt-5.5-prod" match "gpt-5.5-pro".
for key in sorted(table, key = len, reverse = True):
if model.startswith(key) and (len(model) == len(key) or model[len(key)] == "-"):
return table[key]
@@ -107,11 +105,10 @@ def _lookup(provider: str, model: str) -> Optional[dict[str, float]]:
def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str, float]:
- """Return a per-turn USD cost breakdown with per-bucket + total
- fields so the frontend can render either a single number or a
- tooltip without re-doing the math. When the model isn't in the
- static table, ``priced`` is False and USD fields are 0.0 (token
- counts still report).
+ """Return a per-turn USD cost breakdown (per-bucket + total) so the
+ frontend renders a number or tooltip without redoing the math.
+ Unknown model -> ``priced`` False and USD fields 0.0 (token counts
+ still report).
"""
prices = _lookup(provider, model)
out: dict[str, float] = {
@@ -128,22 +125,20 @@ def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str
}
# Accept raw (input_tokens/output_tokens) and Studio chat-style
- # (prompt_tokens/completion_tokens) envelopes. Cache buckets
- # behave differently per envelope:
+ # (prompt_tokens/completion_tokens) envelopes. Cache buckets differ:
# raw Anthropic: input_tokens EXCLUDES cache buckets
# raw OpenAI: input_tokens INCLUDES cache_read
# Studio Anthropic: prompt_tokens INCLUDES cache_creation + cache_read
# Studio OpenAI: prompt_tokens == raw input_tokens
- # Clamp tokens >=0 so corrupted payloads can't produce a negative bill.
+ # Clamp >=0 so corrupted payloads can't produce a negative bill.
cache_creation = max(0, int(usage.get("cache_creation_input_tokens") or 0))
cache_read_native_present = (
"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))
- # Fallback to mirrored prompt_tokens_details only when the native
- # cache_read_input_tokens key is absent. An explicit native 0 is
- # authoritative, so a stale mirrored block from a proxy can never
- # inflate cache_read past the native count.
+ # 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):
@@ -152,22 +147,22 @@ def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str
if has_input_tokens:
input_tokens = max(0, int(usage.get("input_tokens") or 0))
else:
- # Chat-style: peel cache buckets back out for Anthropic to
- # recover the raw uncached prompt count.
+ # Chat-style: peel cache buckets back out for Anthropic to get
+ # the raw uncached prompt count.
prompt_tokens = max(0, int(usage.get("prompt_tokens") or 0))
if provider == "anthropic":
input_tokens = max(0, prompt_tokens - cache_creation - cache_read)
else:
input_tokens = prompt_tokens
- # Prefer raw output_tokens even when 0 (an `or` fallback would
- # silently pick a stale completion_tokens).
+ # Prefer raw output_tokens even when 0 (an `or` would pick a stale
+ # completion_tokens).
if "output_tokens" in usage and usage.get("output_tokens") is not None:
output_tokens = max(0, int(usage.get("output_tokens") or 0))
else:
output_tokens = max(0, int(usage.get("completion_tokens") or 0))
if provider == "openai":
- # Cached tokens land on either input_tokens_details (raw
- # Responses) or prompt_tokens_details (Studio chat-style).
+ # Cached tokens land on input_tokens_details (raw Responses) or
+ # prompt_tokens_details (Studio chat-style).
for key in ("input_tokens_details", "prompt_tokens_details"):
details = usage.get(key) or {}
if isinstance(details, dict):
@@ -200,8 +195,8 @@ def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str
out_per = prices["output_per_mtok"]
# Anthropic fast-mode: 6x on input + output. Cache multipliers stack
- # on top of fast-mode, so applying once to (base, out_per) propagates
- # into the cache_*_usd buckets computed below.
+ # on top, so applying once to (base, out_per) flows into the
+ # cache_*_usd buckets below.
if provider == "anthropic" and usage.get("speed") == "fast":
base *= ANTHROPIC_FAST_MODE_MULT
out_per *= ANTHROPIC_FAST_MODE_MULT
@@ -235,15 +230,15 @@ def calculate_cost(provider: str, model: str, usage: dict[str, Any]) -> dict[str
+ code_exec_hours * ANTHROPIC_CODE_EXEC_USD_PER_HOUR
)
else:
- # OpenAI: cache writes pay base input; only cache reads get
- # 0.1x. Subtract cached from already-counted input_usd to
- # avoid double-billing (OpenAI folds cache into input_tokens).
+ # OpenAI: cache writes pay base input, only reads get 0.1x.
+ # Subtract cached from already-counted input_usd to avoid
+ # double-billing (OpenAI folds cache into input_tokens).
if cache_read > 0:
non_cached_input = max(0, input_tokens - cache_read)
out["input_usd"] = (non_cached_input / 1_000_000.0) * base
out["cache_read_usd"] = (cache_read / 1_000_000.0) * base * OPENAI_CACHE_READ_MULT
# OpenAI server-tool surcharges arrive under `openai_tool_use`
- # (normalised by the SSE finaliser from output array items).
+ # (normalised by the SSE finaliser from output items).
srv = usage.get("openai_tool_use") or {}
if isinstance(srv, dict):
web_searches = int(srv.get("web_search_requests") or 0)
diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.py
index 19b776a6d92..9c98133f672 100644
--- a/studio/backend/core/inference/providers.py
+++ b/studio/backend/core/inference/providers.py
@@ -5,7 +5,7 @@
Static registry of supported external LLM providers.
All providers expose OpenAI-compatible /v1/chat/completions endpoints
-with Bearer token authentication and SSE streaming support.
+with Bearer token auth and SSE streaming.
"""
import re
@@ -26,11 +26,10 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"supports_tool_calling": True,
"auth_header": "Authorization",
"auth_prefix": "Bearer ",
- # Keep the model picker scoped to the current generation. The remote
- # /v1/models listing returns dozens of historical snapshots, fine-tunes
- # and non-chat models (embeddings, TTS, image, moderation) that we
- # never want to surface in the chat UI. Filtering here so backend
- # is the single source of truth.
+ # Scope the picker to the current generation. /v1/models returns
+ # dozens of historical snapshots, fine-tunes, and non-chat models
+ # (embeddings, TTS, image, moderation) we never want in the chat
+ # UI. Filter here so the backend is the single source of truth.
"model_id_allowlist": re.compile(r"^(gpt-5\.[345]|gpt-4\.5|o3)(?:[-.]|$)"),
# Hide dated snapshots and the retired plain gpt-5.3 id.
"model_id_denylist": re.compile(r"^(gpt-5\.3)$|-\d{4}-\d{2}-\d{2}$"),
@@ -48,9 +47,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
],
# Anthropic /v1/models returns dated snapshot ids alongside the
# canonical names (e.g. claude-3-5-sonnet-20241022). Hide the
- # YYYYMMDD-suffixed variants from the picker — same intent as the
- # OpenAI denylist, just a different date format (no dashes between
- # year/month/day).
+ # YYYYMMDD-suffixed variants — same intent as the OpenAI denylist,
+ # just a different date format (no dashes).
"model_id_denylist": re.compile(r"-\d{8}$"),
"supports_streaming": True,
"supports_vision": True,
@@ -68,20 +66,18 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
# Native Gemini REST endpoint -- the Gemini API does NOT speak
# OpenAI Chat Completions on this base. Requests/responses are
# translated in `_stream_gemini` in external_provider.py.
- # API reference: https://ai.google.dev/gemini-api/docs
+ # https://ai.google.dev/gemini-api/docs
"base_url": "https://generativelanguage.googleapis.com/v1beta",
- # Curated lineup -- the live ListModels response returns dozens
- # of historical / experimental / embedding ids. Cap to the
- # current chat-capable Gemini families (3.5 / 3.1 / 3 Flash /
- # 2.5) plus the Nano Banana image trio and the rolling
- # `*-latest` aliases. Excluded on purpose:
+ # Curated lineup -- live ListModels returns dozens of historical /
+ # experimental / embedding ids. Cap to current chat-capable Gemini
+ # families (3.5 / 3.1 / 3 Flash / 2.5) plus the Nano Banana image
+ # trio and the rolling `*-latest` aliases. Excluded on purpose:
# - `gemini-2.0-flash*` (Google retired 2026-06-01; 404 on use)
# - `gemini-3-pro-preview` (shut down 2026-03-09; auto-redirects
# to `gemini-3.1-pro-preview` per Google's deprecation notice,
# so we surface 3.1 directly and skip the redirect).
- # The allowlist below blocks the retired ids from re-appearing
- # via the live ListModels fetch. Verified against the live
- # `/v1beta/models` catalog 2026-05-24.
+ # The allowlist below keeps the retired ids from re-appearing via
+ # live ListModels. Verified against `/v1beta/models` 2026-05-24.
"default_models": [
"gemini-3.1-pro-preview",
"gemini-3.5-flash",
@@ -100,8 +96,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"supports_streaming": True,
"supports_vision": True,
"supports_tool_calling": True,
- # The native API takes the API key on the `x-goog-api-key`
- # header. An empty `auth_prefix` ensures we send the bare key.
+ # Native API takes the key on `x-goog-api-key`; empty `auth_prefix`
+ # sends the bare key.
"auth_header": "x-goog-api-key",
"auth_prefix": "",
"openai_compatible": False,
@@ -110,20 +106,19 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"API key from https://aistudio.google.com/apikey. "
"See https://ai.google.dev/gemini-api/docs for endpoint shapes."
),
- # Even after the regex match, drop ids that Google still
- # returns from ListModels but routes via implicit redirect.
- # gemini-3-pro-preview was shut down 2026-03-09 and is
- # auto-aliased to gemini-3.1-pro-preview; we surface the
- # canonical id only so users do not see two cards for the
- # same underlying model.
+ # Even after the regex match, drop ids Google still returns from
+ # ListModels but routes via implicit redirect. gemini-3-pro-preview
+ # was shut down 2026-03-09 and auto-aliased to
+ # gemini-3.1-pro-preview; surface the canonical id only so users
+ # don't see two cards for the same model.
"model_id_deny_exact": ("gemini-3-pro-preview",),
# Matches the chat-capable 3.5 / 3.1 / 3 / 2.5 families plus the
- # rolling *-latest aliases (which Google rolls forward as new
- # generations ship). Image-tier ids (`-image`, `-image-preview`,
+ # rolling *-latest aliases (rolled forward as new generations ship).
+ # Image-tier ids (`-image`, `-image-preview`,
# `nano-banana-pro-preview`) flow through the Nano Banana
- # `responseModalities` path in `_stream_gemini`. Retired 2.0
- # ids ARE NOT in this regex on purpose -- Google's ListModels
- # would otherwise re-surface them and they 404 on use.
+ # `responseModalities` path in `_stream_gemini`. Retired 2.0 ids are
+ # excluded on purpose -- ListModels would re-surface them and they
+ # 404 on use.
"model_id_allowlist": re.compile(
r"^("
r"gemini-3\.5-(?:flash|pro)(?:-preview)?|"
@@ -186,12 +181,12 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"base_url": "https://api.moonshot.ai/v1",
# Current Kimi model lineup per the official docs:
# https://platform.kimi.ai/docs/models
- # Listing/overview endpoints used to enumerate them:
+ # Listing/overview endpoints:
# https://platform.kimi.ai/docs/api/list-models
# https://platform.kimi.ai/docs/api/overview
# kimi-k2.6 and kimi-k2.5 are the two SoTA multimodal models we
- # surface in the picker; everything else (moonshot-v1-*, dated
- # k2 previews) is filtered out by model_id_allowlist below.
+ # surface; everything else (moonshot-v1-*, dated k2 previews) is
+ # filtered out by model_id_allowlist below.
"default_models": [
"kimi-k2.6",
"kimi-k2.5",
@@ -205,8 +200,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"model_id_allowlist": re.compile(r"^kimi-k2\.[56]$"),
# Both k2.6 and k2.5 are reasoning-class. The API rejects custom
# sampling: "invalid temperature: only 1 is allowed for this model"
- # (and the same shape for top_p). Strip both fields from the
- # outbound body so the server falls back to its required defaults.
+ # (same for top_p). Strip both fields from the outbound body so the
+ # server falls back to its required defaults.
"body_omit": ("temperature", "top_p"),
},
"qwen": {
@@ -228,9 +223,9 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"huggingface": {
"display_name": "Hugging Face",
"base_url": "https://router.huggingface.co/v1",
- # Seed the picker with a few popular ids so something is selectable
- # before the live /v1/models call resolves. The remote listing is
- # the source of truth — see model_list_mode below.
+ # Seed the picker with popular ids so something is selectable before
+ # the live /v1/models call resolves. The remote listing is the
+ # source of truth -- see model_list_mode below.
"default_models": [
"openai/gpt-oss-120b",
"deepseek-ai/DeepSeek-V3",
@@ -249,27 +244,26 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"https://huggingface.co/docs/inference-providers/index."
),
# /v1/models works on the HF router and returns the full chat-model
- # catalog (state.org/model[:policy] ids). Switch to remote so users
- # see live availability — the picker has a search box, and
- # loadModels() merges defaults so default_models entries remain
- # visible if the remote call fails.
+ # catalog (state.org/model[:policy] ids). Remote so users see live
+ # availability -- the picker has search, and loadModels() merges
+ # defaults so default_models stay visible if the remote call fails.
"model_list_mode": "remote",
- # Scope the catalog to first-party org repos we trust as primary
- # sources. The HF /v1/models response is otherwise hundreds of
- # ids long (community fine-tunes, mirrors, fp8 variants, etc.).
+ # Scope to first-party org repos we trust as primary sources. The HF
+ # /v1/models response is otherwise hundreds of ids long (community
+ # fine-tunes, mirrors, fp8 variants, etc.).
"model_id_allowlist": re.compile(
r"^(openai|deepseek-ai|google|meta-llama|Qwen|moonshotai|mistralai|zai-org)/"
),
- # Cap the post-filter list. /v1/models has no server-side limit
- # or popularity sort, so this is just "first N matches" — pair it
- # with the default_models seed so the most useful flagship ids
- # are always among the top regardless of the API's order.
+ # Cap the post-filter list. /v1/models has no server-side limit or
+ # popularity sort, so this is just "first N matches"; the
+ # default_models seed keeps flagship ids near the top regardless of
+ # the API's order.
"model_id_limit": 15,
},
"vllm": {
"display_name": "vLLM",
- # User-supplied via provider_base_url; the route layer already falls
- # back to the payload's base_url when the registry entry has none.
+ # User-supplied via provider_base_url; the route layer falls back to
+ # the payload's base_url when the registry entry has none.
"base_url": "",
"default_models": [],
"supports_streaming": True,
@@ -277,15 +271,14 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"supports_tool_calling": True,
"auth_header": "Authorization",
"auth_prefix": "Bearer ",
- # Force /v1/chat/completions in stream_chat_completion — vLLM's
- # /v1/responses rebuilds messages and runs them through the loaded
- # model's chat template, which 400s on strict-alternation templates
- # (Gemma 3 raises "Conversation roles must alternate user/assistant
- # /user/assistant/..."). The chat-completions path takes messages
- # verbatim and avoids that template gauntlet.
+ # Force /v1/chat/completions in stream_chat_completion -- vLLM's
+ # /v1/responses rebuilds messages through the model's chat template,
+ # which 400s on strict-alternation templates (Gemma 3 raises
+ # "Conversation roles must alternate user/assistant/user/assistant
+ # /..."). The chat-completions path takes messages verbatim.
"notes": "Self-hosted vLLM server. Always routed to /v1/chat/completions.",
- # Surfaced through the frontend's CUSTOM_PROVIDER_PRESETS, not the
- # /api/providers/registry dropdown — see list_available_providers.
+ # Surfaced via the frontend's CUSTOM_PROVIDER_PRESETS, not the
+ # /api/providers/registry dropdown -- see list_available_providers.
"hidden": True,
},
"ollama": {
@@ -371,10 +364,10 @@ def get_base_url(provider_type: str) -> str | None:
def list_available_providers() -> list[dict[str, Any]]:
"""Return all registered providers (for the /registry endpoint).
- Hidden entries (``"hidden": True``) are filtered out — they exist in the
- registry only for backend lookups (e.g. ``supports_vision`` for vLLM) and
- are surfaced in the frontend via ``CUSTOM_PROVIDER_PRESETS`` instead of
- the cloud-provider dropdown.
+ Hidden entries (``"hidden": True``) are filtered out: they exist only
+ for backend lookups (e.g. ``supports_vision`` for vLLM) and are
+ surfaced in the frontend via ``CUSTOM_PROVIDER_PRESETS`` instead of the
+ cloud-provider dropdown.
"""
result = []
for provider_type, info in PROVIDER_REGISTRY.items():
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index e4eb0cd1002..954a2b3d195 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -4,17 +4,16 @@
"""
Safetensors/transformers agentic tool loop.
-Wraps a single-turn cumulative-text generator (the existing
-``InferenceOrchestrator.generate_chat_response`` pipeline that streams
-from a worker subprocess) with the tool-calling, thinking-block,
-status, and metadata event protocol used by the GGUF path. Keeps the
-front-end SSE shape identical across backends so the chat UI does not
-care which engine actually ran the model.
-
-The GGUF path lives in ``llama_cpp.py`` and talks to llama-server's
-structured ``delta.tool_calls`` directly. Native transformers has no
-such structured channel, so this loop parses tool calls from the
-cumulative text and dispatches them via ``core.inference.tools``.
+Wraps a single-turn cumulative-text generator (the
+``InferenceOrchestrator.generate_chat_response`` pipeline streaming from a
+worker subprocess) with the tool-calling, thinking-block, status, and
+metadata event protocol used by the GGUF path. The front-end SSE shape
+stays identical across backends, so the chat UI is engine-agnostic.
+
+The GGUF path (``llama_cpp.py``) uses llama-server's structured
+``delta.tool_calls`` directly. Native transformers has no such channel, so
+this loop parses tool calls from the cumulative text and dispatches them
+via ``core.inference.tools``.
"""
import json
@@ -41,7 +40,7 @@ from core.inference.tool_call_parser import (
logger = get_logger(__name__)
-# Buffer cap while waiting to disambiguate a possible tool-call prefix.
+# Buffer cap while disambiguating a possible tool-call prefix.
_MAX_BUFFER_CHARS = 32
@@ -105,10 +104,10 @@ def _coerce_arguments(
"""Normalise tool ``arguments`` to a dict.
Some templates emit a JSON string, others a bare query string. With
- ``heal=True`` we accept a bare string as ``{<canonical_key>: ...}``
- so a Hermes-style call without proper JSON still runs the tool. The
- canonical key is picked per tool: ``code`` for python, ``command``
- for terminal, ``query`` for everything else (e.g. web_search).
+ ``heal=True`` a bare string becomes ``{<canonical_key>: ...}`` so a
+ Hermes-style call without proper JSON still runs. Canonical key per
+ tool: ``code`` for python, ``command`` for terminal, ``query`` otherwise
+ (e.g. web_search).
"""
if isinstance(raw_args, dict):
return raw_args
@@ -140,28 +139,23 @@ 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 including all previously emitted tokens).
- The loop:
+ ``single_turn(messages)`` must yield cumulative assistant text (each
+ yield is a snapshot of all tokens so far). The loop:
- * Buffers the leading characters of every turn so it can decide
- whether the model is about to emit a tool call. Plain content
- starts streaming as soon as the buffer rules it out.
- * On detecting ``<tool_call>`` or ``<function=`` in the cumulative
- text, drains the rest of the turn silently and parses tool calls
- out of the full content.
+ * 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 the tool result to the conversation, and
- re-enters ``single_turn`` for the next iteration.
- * After ``max_tool_iterations`` turns without a final answer, asks
- the model once more to produce a final answer with no tools.
+ 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.
Yields event dicts matching the GGUF path:
* ``{"type": "status", "text": ...}`` -- empty string clears the badge.
* ``{"type": "content", "text": ...}`` -- cumulative cleaned text for
- the current assistant turn (the consumer should diff against its
- own ``prev_text`` cursor).
+ 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"}``
"""
@@ -205,7 +199,7 @@ def run_safetensors_tool_loop(
return
if not isinstance(cumulative, str):
- continue # defensive: pipeline only yields strings
+ continue # defensive: pipeline yields only strings
delta = cumulative[len(prev_cumulative) :]
prev_cumulative = cumulative
@@ -308,7 +302,7 @@ def run_safetensors_tool_loop(
return
if detect_state == _state_buffering:
- # Buffer never resolved -- tool XML or plain content.
+ # Buffer never resolved -- tool XML or plain content?
stripped = content_buffer.lstrip()
if stripped and has_tool_signal(stripped):
detect_state = _state_draining
@@ -331,9 +325,9 @@ def run_safetensors_tool_loop(
id_offset = next_call_id,
)
if not safety_tc:
- # Final answer: streaming already emitted content.
- # Skip a final=True re-strip so literal "<tool_call>"
- # in prose survives when no real tool call parsed.
+ # Final answer: streaming already emitted content. Skip the
+ # final=True re-strip so literal "<tool_call>" in prose
+ # survives when no real tool call parsed.
yield {"type": "status", "text": ""}
return
tool_calls = safety_tc
@@ -349,8 +343,8 @@ def run_safetensors_tool_loop(
id_offset = next_call_id,
)
if not tool_calls and auto_heal_tool_calls:
- # Parser found nothing -- surface raw content so any
- # literal "<tool_call>" prose is preserved.
+ # Parser found nothing -- surface raw content so literal
+ # "<tool_call>" prose is preserved.
if content_accum:
yield {"type": "content", "text": content_accum}
if provisional_render_html_started:
@@ -436,9 +430,8 @@ def run_safetensors_tool_loop(
render_html_succeeded = True
tool_call_history.append((tc_key, is_error))
- # Strip frontend image sentinel from the model's view.
- # Cut at the first occurrence so leading and consecutive
- # sentinels are both removed.
+ # Strip frontend image sentinel from the model's view. Cut at the
+ # first occurrence so leading and consecutive sentinels both go.
result_for_model = result
if isinstance(result_for_model, str) and "__IMAGES__:" in result_for_model:
result_for_model = result_for_model.split("__IMAGES__:", 1)[0].rstrip()
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index 23b7d4c97ac..1b453df0ffa 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -13,9 +13,9 @@ import re
# _TOOL_CLOSED_PATS: closed pairs only. _TOOL_ALL_PATS: also trailing
# unclosed runs so truncated tails don't leak markup.
-# Function-name char set tracks OpenAI's ^[a-zA-Z0-9_-]{1,64}$ so MCP
-# tool names that contain a hyphen (e.g. mcp__srv__list-issues) parse
-# the same as the built-in web_search/python/terminal names.
+# Function-name char set tracks OpenAI's ^[a-zA-Z0-9_-]{1,64}$ so hyphenated
+# MCP tool names (e.g. mcp__srv__list-issues) parse the same as built-in
+# web_search/python/terminal names.
_TOOL_CLOSED_PATS = [
re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL),
re.compile(r"<function=[\w-]+>.*?</function>", re.DOTALL),
@@ -72,8 +72,8 @@ _TC_JSON_START_RE = re.compile(r"<tool_call>\s*\{")
_TC_FUNC_START_RE = re.compile(r"<function=([\w-]+)>\s*")
_TC_END_TAG_RE = re.compile(r"</tool_call>")
_TC_FUNC_CLOSE_RE = re.compile(r"\s*</function>\s*$")
-# Parameter names can carry hyphens too (e.g. MCP tool schemas with
-# `issue-number`, `repo-name`); using `\w+` here dropped those keys.
+# Parameter names can carry hyphens too (e.g. MCP schemas with
+# `issue-number`, `repo-name`); `\w+` alone dropped those keys.
_TC_PARAM_START_RE = re.compile(r"<parameter=([\w-]+)>\s*")
_TC_PARAM_CLOSE_RE = re.compile(r"\s*</parameter>\s*$")
_PARAM_CLOSE_TAG = "</parameter>"
@@ -124,8 +124,8 @@ def parse_tool_calls_from_text(content: str, *, id_offset: int = 0) -> list[dict
"""
tool_calls: list[dict] = []
- # Pattern 1: <tool_call>{json}. Balanced-brace scan that skips
- # braces inside JSON strings.
+ # Pattern 1: <tool_call>{json}. Balanced-brace scan skipping braces
+ # inside JSON strings.
for m in _TC_JSON_START_RE.finditer(content):
brace_start = m.end() - 1 # position of the opening {
depth, i = 0, brace_start
@@ -165,9 +165,9 @@ def parse_tool_calls_from_text(content: str, *, id_offset: int = 0) -> list[dict
except (json.JSONDecodeError, ValueError):
pass
- # Pattern 2: <function=name><parameter=k>v... -- closing tags
- # optional; don't use </function> as body boundary because code
- # values can contain that literal.
+ # Pattern 2: <function=name><parameter=k>v... -- closing tags optional;
+ # don't use </function> as body boundary since code values can contain
+ # that literal.
if not tool_calls:
func_starts = [
fm
@@ -190,8 +190,8 @@ def parse_tool_calls_from_text(content: str, *, id_offset: int = 0) -> list[dict
arguments: dict = {}
param_starts = list(_TC_PARAM_START_RE.finditer(body))
if len(param_starts) == 1:
- # Single param: take everything to body end so
- # embedded </parameter> in code strings is preserved.
+ # Single param: take everything to body end so embedded
+ # </parameter> in code strings is preserved.
pm = param_starts[0]
val = body[pm.end() :]
val = _TC_PARAM_CLOSE_RE.sub("", val)
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 9be2276d3dc..bc1897199f9 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -4,7 +4,7 @@
"""
Tool definitions and executors for LLM tool calling.
-Supports web search (DuckDuckGo), Python code execution, and terminal commands.
+Web search (DuckDuckGo), Python code execution, and terminal commands.
"""
import ast
@@ -42,9 +42,8 @@ logger = get_logger(__name__)
_EXEC_TIMEOUT = 300 # 5 minutes
-# Pre-import modules used in _sandbox_preexec at module level so that
-# the preexec_fn closure does not trigger the import machinery in the
-# forked child (which can deadlock in multi-threaded servers).
+# Pre-import _sandbox_preexec modules at module level so the preexec_fn closure
+# doesn't trigger imports in the forked child (can deadlock multi-threaded servers).
_libc = None
if sys.platform == "linux":
try:
@@ -64,8 +63,8 @@ if sys.platform != "win32":
except ImportError:
pass
-# Strict raster-image allowlist for sandbox file serving.
-# No .svg (XSS risk via embedded scripts), no .html, no .pdf.
+# Raster-image allowlist for sandbox file serving.
+# No .svg (XSS via embedded scripts), no .html, no .pdf.
_IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})
_MAX_OUTPUT_CHARS = 8000 # truncate long output
_BLOCKED_COMMANDS_COMMON = frozenset(
@@ -122,9 +121,9 @@ _BLOCKED_COMMANDS = (
_SHELL_SEPARATORS = frozenset({";", "&&", "||", "|", "&", "\n", "(", ")", "`", "{", "}"})
-# Bash keywords that introduce a new command position (then $cmd, do $cmd, etc.).
+# Bash keywords starting a new command position (then $cmd, do $cmd, etc.).
_SHELL_KEYWORDS_AS_SEP = frozenset({"then", "do", "else", "elif"})
-# Wrappers whose next non-flag argument is itself the command Bash will exec.
+# Wrappers whose next non-flag argument is the command Bash will exec.
_COMMAND_PREFIXES = frozenset(
{
"env",
@@ -152,21 +151,19 @@ _FIND_EXEC_FLAGS = frozenset({"-exec", "-execdir", "-ok", "-okdir"})
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 if the
- preceding token is a shell separator / brace-group opener / keyword
- that starts a new command (`then`, `do`, etc.), or a command-prefix
- wrapper like `env` / `time` / `xargs` (the next token is the real
- command). Tokens in argument position (`grep -r curl .`,
- `echo source the data`, `ls /usr/bin/curl`) are passed 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 (`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.
"""
blocked: set[str] = set()
# shlex with punctuation_chars splits `;`, `&&`, `||`, `|`, `(`, `)`, `` ` ``
- # off as their own tokens so we can detect command position even when a
- # caller writes `echo done; rm -rf x` (no whitespace) or quote-splits the
- # command name itself (`r''m` collapses to a single token `rm` at command
- # position after the `;` separator).
+ # into their own tokens, so we detect command position even for
+ # `echo done; rm -rf x` (no whitespace) or quote-split command names
+ # (`r''m` collapses to `rm` at command position after `;`).
try:
if sys.platform == "win32":
tokens = shlex.split(command, posix = False)
@@ -178,9 +175,8 @@ def _find_blocked_commands(command: str) -> set[str]:
tokens = command.split()
def _token_basename(tok: str) -> str:
- # shlex may glue trailing meta-chars onto a token (`rm;`); strip them
- # so the basename match still hits `rm`. Leading shell-state chars
- # likewise.
+ # shlex may glue meta-chars onto a token (`rm;`); strip leading and
+ # trailing ones so the basename still matches `rm`.
tok = tok.strip(";&|()`{}")
base = os.path.basename(tok).lower()
stem, ext = os.path.splitext(base)
@@ -189,33 +185,32 @@ def _find_blocked_commands(command: str) -> set[str]:
return base
expect_command = True # start of string is a command position
- prefix_pending = False # last command-position token was env/time/timeout/xargs/...
+ prefix_pending = False # last cmd-position token was a wrapper (env/time/xargs/...)
for token in tokens:
if token in _SHELL_SEPARATORS or token in _SHELL_KEYWORDS_AS_SEP:
expect_command = True
prefix_pending = False
continue
if token.startswith("-"):
- # Flags belong to the active command. While a wrapper prefix is
- # waiting for its command (`stdbuf -oL cmd`, `xargs -- cmd`),
- # keep expect_command intact.
+ # Flags belong to the active command. While a wrapper prefix awaits
+ # its command (`stdbuf -oL cmd`, `xargs -- cmd`), keep expect_command.
if not prefix_pending:
expect_command = False
continue
if not expect_command:
continue
- # FOO=bar prefix: assignment list, next non-assignment token is the command.
+ # FOO=bar assignment prefix; next non-assignment token is the command.
if _ASSIGNMENT_RE.match(token):
continue
- # `timeout 1 cmd` / `nice -n 5 cmd` style numeric wrapper arg.
+ # Numeric wrapper arg: `timeout 1 cmd` / `nice -n 5 cmd`.
if prefix_pending and token.lstrip("-").isdigit():
continue
base = _token_basename(token)
if base in _BLOCKED_COMMANDS:
blocked.add(base)
# Wrappers (`env` / `time` / `xargs` / `sudo`) consume one command; the
- # next non-flag, non-numeric token is the real command. `sudo` is
- # already in _BLOCKED_COMMANDS, so it's flagged AND we keep walking.
+ # next non-flag, non-numeric token is the real command. `sudo` is in
+ # _BLOCKED_COMMANDS, so it's flagged AND we keep walking.
if base in _COMMAND_PREFIXES:
prefix_pending = True
continue
@@ -229,10 +224,10 @@ def _find_blocked_commands(command: str) -> set[str]:
if base in _BLOCKED_COMMANDS:
blocked.add(base)
- # Regex: blocked words at shell command boundaries that shlex won't see,
- # e.g. inside an unquoted $(rm -rf), <(rm), backtick chain, or appended to
- # a separator with no whitespace ("foo;rm"). Anchored to command-position
- # delimiters; does not match in argument position.
+ # Regex: blocked words at command boundaries shlex won't see, e.g. inside
+ # unquoted $(rm -rf), <(rm), backtick chains, or after a separator with no
+ # whitespace ("foo;rm"). Anchored to command-position delimiters; no match
+ # in argument position.
lowered = command.lower()
if _BLOCKED_COMMANDS:
words_alt = "|".join(re.escape(w) for w in sorted(_BLOCKED_COMMANDS))
@@ -243,11 +238,10 @@ def _find_blocked_commands(command: str) -> set[str]:
)
blocked.update(re.findall(pattern, lowered))
- # Nested shell invocations (bash -c 'sudo whoami',
- # bash -lc '...', bash --login -c '...', cmd /c '...').
- # When a -c or /c flag is found, look backwards for a shell name
- # (skipping intermediate flags like --login, -l, -x) and recursively
- # scan the nested command string.
+ # Nested shell invocations (bash -c 'sudo whoami', bash -lc '...',
+ # bash --login -c '...', cmd /c '...'). On a -c or /c flag, look
+ # backwards for a shell name (skipping flags like --login, -l, -x)
+ # and recursively scan the nested command string.
_SHELLS = {"bash", "sh", "zsh", "dash", "ksh", "csh", "tcsh", "fish"}
_SHELLS_WIN = {"cmd", "cmd.exe"}
for i, token in enumerate(tokens):
@@ -259,10 +253,9 @@ def _find_blocked_commands(command: str) -> set[str]:
is_win_c = tok_lower == "/c"
if not (is_unix_c or is_win_c) or i < 1 or i + 1 >= len(tokens):
continue
- # Look backwards past any flags to find the shell binary.
- # On Unix, flags start with - (skip those). On Windows, flags
- # start with / but so do absolute paths, so only skip short
- # single-char /X flags (not /bin/bash style paths).
+ # Look backwards past flags to find the shell binary. Unix flags
+ # start with - (skip). Windows flags start with / but so do absolute
+ # paths, so only skip short single-char /X flags (not /bin/bash).
for j in range(i - 1, -1, -1):
prev = tokens[j]
if prev.startswith("-"):
@@ -282,17 +275,15 @@ def _find_blocked_commands(command: str) -> set[str]:
def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
- Whitelist-built from scratch -- the parent process env is NOT inherited.
- Only PATH / HOME / TMPDIR / LANG / TERM / PYTHONIOENCODING (+ VIRTUAL_ENV
- or Windows SystemRoot when applicable) reach the child. HF_TOKEN,
- WANDB_API_KEY, AWS_*, GH_TOKEN, OPENAI_API_KEY, LD_PRELOAD, DYLD_*, and
- every other parent var are absent by construction. HOME points at the
- sandbox workdir so HF / wandb / aws SDKs cannot read cached credentials
- from the operator's real ~/.
+ Whitelist-built from scratch; parent env is NOT inherited. Only PATH /
+ HOME / TMPDIR / LANG / TERM / PYTHONIOENCODING (+ VIRTUAL_ENV or Windows
+ SystemRoot when applicable) reach the child. HF_TOKEN, WANDB_API_KEY,
+ AWS_*, GH_TOKEN, OPENAI_API_KEY, LD_PRELOAD, DYLD_*, and all other parent
+ vars are absent. HOME points at the sandbox workdir so HF / wandb / aws
+ SDKs can't read cached credentials from the operator's real ~/.
"""
- # Start with the directory containing the running Python interpreter
- # so that subprocess calls to 'python', 'pip', etc. resolve to the
- # same environment the Studio server is running in.
+ # Start with the running interpreter's directory so 'python', 'pip', etc.
+ # resolve to the same environment the Studio server runs in.
exe_dir = os.path.dirname(sys.executable)
path_entries = [exe_dir] if exe_dir else []
@@ -354,9 +345,9 @@ def _sandbox_preexec():
except (OSError, AttributeError):
pass
- # CLONE_NEWNET intentionally not applied: where userns is 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.
@@ -381,10 +372,9 @@ def _sandbox_preexec():
pass
try:
# Default high enough for multi-shard safetensors mmaps + Python's
- # own handle count; tunable via env for installs that hit the cap.
- # Clamp to the inherited hard limit so setrlimit doesn't ValueError
- # on machines where the parent's hard cap is below the requested
- # value (would otherwise leave NOFILE at the parent's default).
+ # handle count; tunable via env. Clamp to the inherited hard limit
+ # so setrlimit doesn't ValueError where the parent's hard cap is
+ # below the request (else NOFILE stays at the parent's default).
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)
@@ -401,8 +391,7 @@ def _get_shell_cmd(command: str) -> list[str]:
# Per-session working directories so each chat thread gets its own sandbox.
-# Falls back to a shared ~/studio_sandbox/_default for API callers without a
-# session_id.
+# Falls back to ~/studio_sandbox/_default for callers without a session_id.
_workdirs: dict[str, str] = {}
@@ -681,10 +670,10 @@ def execute_tool(
timeout: int | None = _TIMEOUT_UNSET,
session_id: str | None = None,
) -> str:
- """Execute a tool by name with the given arguments. Returns result as a string.
+ """Execute a tool by name with the given arguments. Returns a string.
- ``timeout``: int sets per-call limit in seconds, ``None`` means no limit,
- unset (default) uses ``_EXEC_TIMEOUT`` (300 s).
+ ``timeout``: int = per-call limit in seconds, ``None`` = no limit,
+ unset (default) = ``_EXEC_TIMEOUT`` (300 s).
``session_id``: optional thread/session ID for per-conversation sandbox isolation.
"""
logger.info(f"execute_tool: name={name}, session_id={session_id}, timeout={timeout}")
@@ -726,10 +715,10 @@ def execute_tool(
_MAX_PAGE_CHARS = 16000 # limit fetched page text (after HTML-to-MD conversion)
-# Raw download cap. Must be larger than _MAX_PAGE_CHARS because SSR pages
-# embed large <head> sections (CSS, JS, SVGs) that are stripped during
-# HTML-to-Markdown conversion. 512 KB is enough to reach article content
-# on GitBook / Next.js / Docusaurus pages whose <head> alone can be 200 KB.
+# Raw download cap. Larger than _MAX_PAGE_CHARS because SSR pages embed large
+# <head> sections (CSS, JS, SVGs) stripped during HTML-to-Markdown conversion.
+# 512 KB reaches article content on GitBook / Next.js / Docusaurus pages whose
+# <head> alone can be 200 KB.
_MAX_FETCH_BYTES = 512 * 1024
_USER_AGENTS = (
@@ -750,14 +739,13 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):
class _PinnedHTTPSConnection(http.client.HTTPSConnection):
- """HTTPS connection that connects to a pinned IP but uses a different
- hostname for SNI and certificate verification.
-
- The SSRF IP-pinning rewrites URLs to raw IPs. A normal HTTPSConnection
- would then send no SNI and verify the cert against the IP, both of which
- fail. This subclass splits the two concerns: TCP connects to the pinned
- IP (``host`` parameter) while TLS uses ``sni_hostname`` for the
- ClientHello and cert check.
+ """HTTPS connection to a pinned IP, using a different hostname for SNI
+ and certificate verification.
+
+ SSRF IP-pinning rewrites URLs to raw IPs. A normal HTTPSConnection would
+ then send no SNI and verify the cert against the IP, both of which fail.
+ This subclass splits the concerns: TCP connects to the pinned IP (``host``)
+ while TLS uses ``sni_hostname`` for the ClientHello and cert check.
"""
def __init__(self, host: str, *, sni_hostname: str, **kwargs):
@@ -765,8 +753,8 @@ class _PinnedHTTPSConnection(http.client.HTTPSConnection):
self._sni_hostname = sni_hostname
def connect(self):
- # TCP connect to the pinned IP stored in self.host (+ tunnel if
- # a proxy is configured via set_tunnel, though we do not use one).
+ # TCP connect to the pinned IP in self.host (+ tunnel if a proxy is set
+ # via set_tunnel, though we don't use one).
http.client.HTTPConnection.connect(self)
# TLS handshake with the real hostname for SNI + cert verification.
self.sock = self._context.wrap_socket(
@@ -778,8 +766,8 @@ class _PinnedHTTPSConnection(http.client.HTTPSConnection):
class _SNIHTTPSHandler(urllib.request.HTTPSHandler):
"""HTTPS handler that sends the correct SNI hostname during TLS handshake.
- The SSRF IP-pinning rewrites URLs to raw IPs, which breaks SNI and cert
- verification. This handler returns a ``_PinnedHTTPSConnection`` that
+ SSRF IP-pinning rewrites URLs to raw IPs, breaking SNI and cert
+ verification. This handler returns a ``_PinnedHTTPSConnection`` that
connects to the pinned IP but verifies TLS against the original hostname.
"""
@@ -798,9 +786,9 @@ class _SNIHTTPSHandler(urllib.request.HTTPSHandler):
def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str]:
"""Resolve *hostname*, reject non-public IPs, return a pinned IP string.
- Returns ``(ok, reason_or_empty, resolved_ip)``. The caller should
- connect to *resolved_ip* (with a ``Host`` header) to prevent DNS
- rebinding between validation and the actual fetch.
+ Returns ``(ok, reason_or_empty, resolved_ip)``. The caller should connect
+ to *resolved_ip* (with a ``Host`` header) to prevent DNS rebinding between
+ validation and the actual fetch.
"""
import ipaddress
import socket
@@ -815,14 +803,14 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str
for *_, sockaddr in infos:
ip = ipaddress.ip_address(sockaddr[0])
- # `not ip.is_global` rejects every category the denylist below
- # also rejects PLUS shared address space (100.64.0.0/10 carrier-
- # grade NAT) and benchmarking/documentation/exchange ranges that
- # Python classifies with `is_private=False` and `is_global=False`
+ # `not ip.is_global` rejects every category the denylist below rejects
+ # PLUS shared address space (100.64.0.0/10 carrier-grade NAT) and
+ # benchmarking/documentation/exchange ranges Python marks
+ # `is_private=False` and `is_global=False`
# (see https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address.is_global).
- # The explicit predicates after it give human-readable categories
- # in the error message, but a single non-global check is the
- # source of truth and prevents future ranges from leaking.
+ # The explicit predicates after it give human-readable categories in
+ # the error message; the non-global check is the source of truth and
+ # prevents future ranges from leaking.
if (
not ip.is_global
or ip.is_private
@@ -872,8 +860,8 @@ def _fetch_page_text(
ua = random.choice(_USER_AGENTS)
for _hop in range(5):
- # Pin to the validated IP to prevent DNS rebinding.
- # Rewrite the URL to use the IP and set the Host header.
+ # Pin to the validated IP (prevents DNS rebinding): rewrite the URL
+ # to the IP and set the Host header.
cp = urlparse(current_url)
# Bracket IPv6 addresses so the netloc is valid in a URL.
ip_str = f"[{pinned_ip}]" if ":" in pinned_ip else pinned_ip
@@ -926,7 +914,7 @@ def _fetch_page_text(
except Exception as e:
return f"Failed to fetch URL: {e}"
- # Convert HTML to Markdown using the builtin converter (no external deps)
+ # Convert HTML to Markdown with the builtin converter (no external deps)
from ._html_to_md import html_to_markdown
text = html_to_markdown(raw_html)
@@ -981,7 +969,7 @@ def _web_search(
def _check_signal_escape_patterns(code: str):
"""
- Check if code contains patterns that could escape signal-based timeouts.
+ Check for patterns that could escape signal-based timeouts.
Vendored from unsloth_zoo.rl_environments to avoid importing unsloth_zoo
(which requires GPU drivers and fails on Mac/Apple Silicon).
@@ -1071,8 +1059,8 @@ def _check_signal_escape_patterns(code: str):
return parts
return []
- # Keyword argument names that carry command content (as opposed to
- # 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):
@@ -1093,8 +1081,8 @@ def _check_signal_escape_patterns(code: str):
self.signal_aliases = {"signal"}
self.os_aliases = {"os"}
self.subprocess_aliases = {"subprocess"}
- # Maps bare function names to their fully-qualified form
- # for from-import tracking (e.g. "system" -> "os.system")
+ # Maps bare function names to fully-qualified form for
+ # from-import tracking (e.g. "system" -> "os.system")
self.shell_exec_aliases: dict[str, str] = {}
self.loop_depth = 0
@@ -1197,7 +1185,7 @@ def _check_signal_escape_patterns(code: str):
)
# --- Shell escape detection ---
- # Resolve the fully qualified function name for os.*/subprocess.*
+ # Resolve the FQ function name for os.*/subprocess.*
shell_func = None
if isinstance(func, ast.Attribute):
if isinstance(func.value, ast.Name):
@@ -1229,7 +1217,7 @@ def _check_signal_escape_patterns(code: str):
blocked_in_args = _check_args_for_blocked(all_call_args)
if has_opaque_kwargs:
- # Can't inspect dynamic **kwargs -- flag as unsafe
+ # Can't inspect dynamic **kwargs; flag as unsafe
shell_escapes.append(
{
"type": "shell_escape_dynamic",
@@ -1251,8 +1239,8 @@ def _check_signal_escape_patterns(code: str):
else:
# Only flag dynamic args for functions that interpret
# strings as shell commands, or when shell= might be
- # enabled. Treat any non-literal-False shell= value
- # as potentially True (conservative).
+ # enabled. Treat any non-literal-False shell= value as
+ # potentially True (conservative).
_STRING_SHELL_FUNCS = frozenset(
{
"os.system",
@@ -1268,7 +1256,7 @@ def _check_signal_escape_patterns(code: str):
shell_safe = shell_node is None or (
isinstance(shell_node, ast.Constant) and shell_node.value is False
)
- # Dynamic shell-exec args (chr/format/concat bypasses).
+ # Dynamic shell-exec args (chr/format/concat bypasses)
if (
shell_func in _STRING_SHELL_FUNCS
or shell_func in _SHELL_EXEC_FUNCS
@@ -1311,10 +1299,9 @@ def _check_signal_escape_patterns(code: str):
)
elif isinstance(node.type, ast.Name):
# Only flag BaseException and TimeoutError, NOT Exception.
- # except Exception does not catch SystemExit or
- # KeyboardInterrupt, so it cannot suppress timeout
- # enforcement. Flagging Exception causes false positives
- # on normal error-handling patterns.
+ # except Exception doesn't catch SystemExit/KeyboardInterrupt,
+ # so it can't suppress timeout enforcement; flagging it would
+ # false-positive on normal error handling.
if node.type.id in ("TimeoutError", "BaseException"):
exception_catching.append(
{
@@ -1342,9 +1329,9 @@ 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 instead.
+ # 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 instead.
network_calls: list[dict] = []
sensitive_file_reads: list[dict] = []
_NETWORK_FQ_PREFIXES = (
@@ -1591,9 +1578,9 @@ def _check_signal_escape_patterns(code: str):
return False
# Bare method-name fallback (`x.upload_file(...)`) is intentionally fuzzy,
- # but should only fire when huggingface_hub / hf_api is actually imported
- # somewhere in the snippet -- otherwise paramiko.upload_file, boto3
- # create_commit, etc. hit a false positive. We pre-scan for the imports.
+ # but should only fire when huggingface_hub / hf_api is imported in the
+ # snippet; else paramiko.upload_file, boto3 create_commit, etc. would
+ # false-positive. We pre-scan for the imports.
_HF_IMPORT_MODULES = (
"huggingface_hub",
"hf_api",
@@ -1611,8 +1598,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('huggingface_hub'),
- # and bare import_module('huggingface_hub') (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
@@ -1635,8 +1622,8 @@ def _check_signal_escape_patterns(code: str):
Catches `HfApi().upload_file(...)` (Attribute) and
`from huggingface_hub import upload_file; upload_file(...)` (Name).
- The bare-name branch fires only when an HF import is in scope, mirroring
- the Attribute branch's gating so paramiko/boto3 do not false-positive.
+ 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
@@ -1649,7 +1636,7 @@ def _check_signal_escape_patterns(code: str):
# Kwargs that ship a credential over the wire. Sandbox env strips HF_TOKEN
# / WANDB_API_KEY / AWS_* up front, so any value here is hard-coded or
- # lifted from the parent process.
+ # lifted from the parent.
_HF_SENSITIVE_KWARGS = frozenset(
{
"token",
@@ -1674,14 +1661,14 @@ 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.
- Walking the subtree (not just the root) means wrapper calls like
- `str(os.environ)`, `json.dumps(os.environ)`, or
- `'-'.join(os.environ.values())` are caught too.
+ Walking the subtree (not just the root) catches wrapper calls like
+ `str(os.environ)`, `json.dumps(os.environ)`,
+ `'-'.join(os.environ.values())`.
Covers: `os.environ`, `os.environ[K]`, `os.environ.get(K)`, `os.getenv(K)`,
bare `getenv(K)` (after `from os import getenv`), and
`subprocess.{run,check_output,Popen,getoutput,getstatusoutput}` which
- the LLM could use to lift parent env via `printenv` / `env` / `set`.
+ could lift parent env via `printenv` / `env` / `set`.
"""
if node is None:
return False
@@ -1729,7 +1716,7 @@ def _check_signal_escape_patterns(code: str):
if node is None:
return False
if isinstance(node, ast.Constant) and isinstance(node.value, (bytes, bytearray)):
- return True # inline bytes, no file access
+ return True # inline bytes; no file access
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return _is_safe_relative_path(node.value)
if isinstance(node, ast.Call):
@@ -1751,10 +1738,10 @@ def _check_signal_escape_patterns(code: str):
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 argument is a sandbox-local literal -- a
- relative string with no `..`, an `open(<literal>)`, or inline bytes.
- Dynamic / variable paths are rejected; the policy cannot prove safety
- statically and the cost of a wrong-allow is a credential exfiltration.
+ 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:
@@ -1813,7 +1800,7 @@ def _check_signal_escape_patterns(code: str):
}
)
- # Direct sock.connect((host, port)) bypasses the FQ-prefix branch below.
+ # Direct sock.connect((host, port)) bypasses the FQ-prefix branch.
if isinstance(node.func, ast.Attribute) and node.func.attr == "connect" and node.args:
a0 = node.args[0]
host_lit = None
@@ -1947,9 +1934,8 @@ def _check_code_safety(code: str) -> str | None:
"""
safe, info = _check_signal_escape_patterns(code)
if not safe:
- # SyntaxError from ast.parse -- let these through so the subprocess
- # produces a normal Python traceback instead of a misleading
- # "unsafe code detected" 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
@@ -2032,7 +2018,7 @@ def _python_exec(
tmp_path = None
workdir = _get_workdir(session_id)
- # Snapshot image mtimes so we detect both new and overwritten files.
+ # Snapshot image mtimes to detect new and overwritten files.
_before: dict[str, int] = {}
if os.path.isdir(workdir):
for _name in os.listdir(workdir):
@@ -2088,7 +2074,7 @@ def _python_exec(
result = f"Exit code {proc.returncode}:\n{result}"
result = _truncate(result) if result.strip() else "(no output)"
- # Detect new or overwritten image files and append sentinel for frontend
+ # Detect new/overwritten images and append sentinel for the frontend
if session_id and os.path.isdir(workdir):
new_images = []
for _name in os.listdir(workdir):
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 525aa53a700..72783f1031b 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -4,9 +4,9 @@
"""
Inference subprocess entry point.
-Each inference session runs in a persistent subprocess (mp.get_context("spawn")).
-This gives us a clean Python interpreter with no stale module state —
-solving the transformers version-switching problem completely.
+Each inference session runs in a persistent subprocess
+(mp.get_context("spawn")), giving a clean Python interpreter with no stale
+module state — fully solving the transformers version-switching problem.
The subprocess stays alive while a model is loaded, accepting commands
(generate, load, unload) via mp.Queue. It exits on shutdown or unload.
@@ -35,7 +35,7 @@ from utils.hardware import apply_gpu_ids
def _activate_transformers_version(model_name: str) -> None:
"""Activate the correct transformers version BEFORE any ML imports."""
- # Ensure backend is on path for utils imports
+ # Ensure backend is on path for utils imports.
backend_path = str(Path(__file__).resolve().parent.parent.parent)
if backend_path not in sys.path:
sys.path.insert(0, backend_path)
@@ -96,18 +96,16 @@ def _build_model_config(config: dict):
def _get_hf_download_state(model_names: list[str] | None = None) -> tuple[int, bool] | None:
"""Return (total_bytes, has_incomplete) for the HF Hub cache, or None on error.
- When *model_names* is provided, only those models' ``blobs/``
- directories are checked instead of scanning every cached model --
- much faster on systems with many models. Accepts multiple names so
- that LoRA loads can watch both the adapter repo and the base model
- repo simultaneously.
+ When *model_names* is provided, only those models' ``blobs/`` dirs are
+ checked instead of scanning every cached model -- much faster with many
+ models. Accepts multiple names so LoRA loads can watch both the adapter
+ repo and the base model repo at once.
*has_incomplete* is True when any ``*.incomplete`` files exist in the
- watched blobs directories, indicating that ``huggingface_hub`` is
- actively downloading.
+ watched blobs dirs, indicating ``huggingface_hub`` is actively downloading.
- Returns None if the state cannot be determined (import error,
- permission error, etc.) so callers can skip stall logic.
+ Returns None if the state cannot be determined (import error, permission
+ error, etc.) so callers can skip stall logic.
"""
try:
from huggingface_hub.constants import HF_HUB_CACHE
@@ -127,12 +125,12 @@ def _get_hf_download_state(model_names: list[str] | None = None) -> tuple[int, b
continue
# Skip local filesystem paths -- HF model IDs use forward
# slashes (org/model) but never start with / . ~ or contain
- # backslashes. This distinguishes them from absolute paths,
- # relative paths, and Windows paths.
+ # backslashes, distinguishing them from absolute, relative,
+ # and Windows paths.
if name.startswith(("/", ".", "~")) or "\\" in name:
continue
name = resolve_cached_repo_id_case(name)
- # HF cache dir format: models--org--name (slashes -> --)
+ # HF cache dir format: models--org--name (slashes -> --).
cache_dir_name = "models--" + name.replace("/", "--")
blobs_dir = cache / cache_dir_name / "blobs"
if blobs_dir.exists():
@@ -165,14 +163,14 @@ def _start_heartbeat(
) -> threading.Event:
"""Start a daemon thread that sends periodic status heartbeats.
- Monitors the HF Hub cache directory for download activity. A stall
- is only reported when ``*.incomplete`` files are present (indicating
- ``huggingface_hub`` is actively downloading) **and** the total cache
- size has not changed for *stall_timeout* seconds.
+ Monitors the HF Hub cache for download activity. A stall is reported only
+ when ``*.incomplete`` files are present (``huggingface_hub`` is actively
+ downloading) **and** the total cache size has not changed for
+ *stall_timeout* seconds.
- Once the download finishes (no more ``.incomplete`` files), the stall
- timer resets, so post-download initialization (quantization, GPU
- weight loading) is never misclassified as a stalled download.
+ Once the download finishes (no more ``.incomplete`` files), the stall timer
+ resets, so post-download init (quantization, GPU weight loading) is never
+ misclassified as a stalled download.
Returns a stop event -- set it to terminate the heartbeat thread.
"""
@@ -188,7 +186,7 @@ def _start_heartbeat(
state = _get_hf_download_state(model_names)
now = time.monotonic()
- # Skip stall logic if we cannot measure the cache
+ # Skip stall logic if we cannot measure the cache.
if state is None:
_send_response(
resp_queue,
@@ -206,9 +204,8 @@ def _start_heartbeat(
last_size = current_size
last_change = now
- # Only fire stall when .incomplete files are present,
- # confirming a download is actively in progress.
- # Once downloads finish (no .incomplete), reset the timer
+ # Only fire stall when .incomplete files confirm a download is in
+ # progress. Once downloads finish (no .incomplete), reset the timer
# so model init time is not counted as a stall.
if not has_incomplete:
last_change = now
@@ -224,7 +221,7 @@ def _start_heartbeat(
"ts": time.time(),
},
)
- # Only fire once -- the orchestrator will kill us
+ # Only fire once -- the orchestrator will kill us.
return
_send_response(
@@ -249,7 +246,7 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
hf_token = config.get("hf_token")
hf_token = hf_token if hf_token and hf_token.strip() else None
- # Auto-detect quantization for LoRA adapters
+ # Auto-detect quantization for LoRA adapters.
load_in_4bit = config.get("load_in_4bit", True)
if mc.is_lora and mc.path:
import json
@@ -280,7 +277,7 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
except Exception as e:
logger.warning("Could not read adapter_config.json: %s", e)
- # Auto-enable trust_remote_code for NemotronH/Nano models only.
+ # Auto-enable trust_remote_code for NemotronH/Nano models only:
# NemotronH has config parsing bugs requiring trust_remote_code=True.
# Other transformers 5.x models are native and do NOT need it.
# NOTE: Must NOT match Llama-Nemotron (standard Llama architecture).
@@ -298,12 +295,12 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
model_name,
)
- # Send heartbeats every 30s so the orchestrator knows we're still alive
- # (download / weight loading can take a long time on slow connections)
+ # Send heartbeats every 30s so the orchestrator knows we're alive
+ # (download/weight loading can be slow on slow connections).
xet_disabled = os.environ.get("HF_HUB_DISABLE_XET") == "1"
- # Watch both the model repo and base model repo (for LoRA loads
- # where the base model download is the actual bottleneck)
+ # Watch both the model repo and base model repo (for LoRA loads where
+ # the base model download is the real bottleneck).
watch_repos = [mc.identifier]
base = getattr(mc, "base_model", None)
if base and str(base) != mc.identifier:
@@ -328,7 +325,7 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
heartbeat_stop.set()
if success:
- # Build model_info for the parent to mirror
+ # Build model_info for the parent to mirror.
model_info = {
"identifier": mc.identifier,
"display_name": mc.display_name,
@@ -341,8 +338,8 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"audio_type": getattr(mc, "audio_type", None),
"has_audio_input": getattr(mc, "has_audio_input", False),
}
- # Forward chat_template_info so the parent can classify
- # capabilities without re-entering the subprocess.
+ # Forward chat_template_info so the parent can classify capabilities
+ # without re-entering the subprocess.
try:
_bm = getattr(backend, "models", {}) or {}
_entry = (
@@ -397,22 +394,21 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
"""Handle a generate command: stream tokens back via resp_queue.
- cancel_event is an mp.Event shared with the parent process.
- The parent can set it at any time (e.g. user stops generation,
- or user loads a new model while generating) and generation
- stops within 1-2 tokens.
+ cancel_event is an mp.Event shared with the parent. The parent can set it
+ at any time (e.g. user stops generation, or loads a new model mid-generate)
+ and generation stops within 1-2 tokens.
"""
request_id = cmd.get("request_id", "")
try:
- # Decode image if provided
+ # Decode image if provided.
image = None
image_b64 = cmd.get("image_base64")
if image_b64:
image = _decode_image(image_b64)
image = _resize_image(image)
- # Build generation kwargs
+ # Build generation kwargs.
gen_kwargs = {
"messages": cmd["messages"],
"system_prompt": cmd.get("system_prompt", ""),
@@ -426,9 +422,8 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
"cancel_event": cancel_event,
}
- # Optional template/tool plumbing: only forward keys that are
- # actually present so the backend signature can evolve without
- # breaking older command payloads.
+ # Optional template/tool plumbing: only forward keys that are present so
+ # the backend signature can evolve without breaking older payloads.
for opt_key in (
"tools",
"enable_thinking",
@@ -438,7 +433,7 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
if opt_key in cmd:
gen_kwargs[opt_key] = cmd[opt_key]
- # Choose generation path
+ # Choose generation path.
use_adapter = cmd.get("use_adapter")
if use_adapter is not None:
generator = backend.generate_with_adapter_control(
@@ -451,7 +446,7 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
logger.info("Starting text generation for request_id=%s", request_id)
for cumulative_text in generator:
- # cancel_event is an mp.Event — checked instantly, no queue polling
+ # cancel_event is an mp.Event — checked instantly, no queue polling.
if cancel_event.is_set():
logger.info("Generation cancelled for request %s", request_id)
break
@@ -508,7 +503,7 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any) -> None:
use_adapter = cmd.get("use_adapter"),
)
- # Send WAV bytes as base64 (bytes can't go through mp.Queue directly)
+ # Send WAV bytes as base64 (bytes can't go through mp.Queue directly).
_send_response(
resp_queue,
{
@@ -542,7 +537,7 @@ def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_eve
try:
import numpy as np
- # Decode audio array from list (numpy arrays can't go through mp.Queue)
+ # Decode audio array from list (numpy arrays can't go through mp.Queue).
audio_array = np.array(cmd["audio_data"], dtype = np.float32)
audio_type = cmd.get("audio_type")
@@ -638,12 +633,12 @@ def _handle_unload(backend, cmd: dict, resp_queue: Any) -> None:
def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, config: dict) -> None:
- """Subprocess entrypoint. Persistent — runs command loop until shutdown.
+ """Subprocess entrypoint. Persistent — runs the command loop until shutdown.
Args:
cmd_queue: mp.Queue for receiving commands from parent.
resp_queue: mp.Queue for sending responses to parent.
- cancel_event: mp.Event shared with parent — set by parent to cancel generation.
+ cancel_event: mp.Event the parent sets to cancel generation.
config: Initial configuration dict with model info.
"""
os.environ["TOKENIZERS_PARALLELISM"] = "false"
@@ -668,7 +663,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
model_name = config["model_name"]
- # ── 0. MLX fast-path — skip torch/transformers entirely ──
+ # ── 0. MLX fast-path — skip torch/transformers ──
backend_path = str(Path(__file__).resolve().parent.parent.parent)
if backend_path not in sys.path:
sys.path.insert(0, backend_path)
@@ -702,7 +697,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
)
return
- # Enter same command loop as GPU path
+ # Enter the same command loop as the GPU path.
logger.info("MLX inference subprocess ready, entering command loop")
while True:
try:
@@ -760,7 +755,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
)
return
- # ── 1. Activate correct transformers version BEFORE any ML imports ──
+ # ── 1. Activate transformers version BEFORE any ML imports ──
try:
_activate_transformers_version(model_name)
except Exception as exc:
@@ -775,7 +770,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
)
return
- # ── 1b. On Windows, check Triton availability (must be before import torch) ──
+ # ── 1b. Windows: check Triton availability (must precede import torch) ──
if sys.platform == "win32":
try:
import triton # noqa: F401
@@ -848,8 +843,8 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
return
# ── 4. Command loop — process commands until shutdown ──
- # cancel_event is an mp.Event shared with parent — parent can set it
- # at any time to cancel generation instantly (no queue polling needed).
+ # cancel_event is an mp.Event the parent can set anytime to cancel
+ # generation instantly (no queue polling needed).
logger.info("Inference subprocess ready, entering command loop")
while True:
@@ -873,8 +868,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
_handle_generate(backend, cmd, resp_queue, cancel_event)
elif cmd_type == "load":
- # Load a new model (reusing this subprocess)
- # First unload current model
+ # Load a new model in this subprocess; unload the current one first.
if backend.active_model_name:
backend.unload_model(backend.active_model_name)
_handle_load(backend, cmd, resp_queue)
@@ -891,7 +885,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
_handle_unload(backend, cmd, resp_queue)
elif cmd_type == "cancel":
- # Redundant with mp.Event but handle gracefully
+ # Redundant with mp.Event but handle gracefully.
cancel_event.set()
logger.info("Cancel command received")
@@ -907,7 +901,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
)
elif cmd_type == "status":
- # Return current status
+ # Return current status.
_send_response(
resp_queue,
{
@@ -927,7 +921,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
elif cmd_type == "shutdown":
logger.info("Shutdown command received, exiting")
- # Unload all models
+ # Unload all models.
for model_name in list(backend.models.keys()):
try:
backend.unload_model(model_name)
diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.py
index 77619bcdb3a..9ef60e00dfd 100644
--- a/studio/backend/core/tool_healing.py
+++ b/studio/backend/core/tool_healing.py
@@ -3,24 +3,24 @@
"""Tool-call XML parsing and stripping helpers.
-Extracted verbatim from studio/backend/core/inference/llama_cpp.py so that
+Extracted verbatim from studio/backend/core/inference/llama_cpp.py so
external inference servers (llama-server wrappers, llama-swap, custom
-shims) can reuse the same logic without importing the inference
-orchestrator, structlog, httpx, or the rest of the studio backend.
+shims) can reuse the logic without importing the inference orchestrator,
+structlog, httpx, or the rest of the studio backend.
-The regexes and function bodies are byte-for-byte identical to the
-original inline implementation in llama_cpp.py. Any change made here must
-preserve that equivalence; tests/python/test_tool_healing_extraction_is_exact.py
+Regexes and function bodies are byte-for-byte identical to the original
+inline implementation in llama_cpp.py; any change must preserve that
+equivalence. tests/python/test_tool_healing_extraction_is_exact.py
verifies it with AST comparison.
"""
import json
import re
-# Pre-compiled patterns for tool XML stripping. Hyphen in the
-# function/parameter name char-class tracks OpenAI's allowed set so
-# MCP tool names with dashes (mcp__srv__list-issues) and parameter
-# names with dashes (`issue-number`) parse alongside the built-ins.
+# Pre-compiled patterns for tool XML stripping. The hyphen in the
+# function/parameter name char-class tracks OpenAI's allowed set so MCP
+# tool names (mcp__srv__list-issues) and parameter names (`issue-number`)
+# with dashes parse alongside the built-ins.
_TOOL_CLOSED_PATS = [
re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL),
re.compile(r"<function=[\w-]+>.*?</function>", re.DOTALL),
@@ -46,13 +46,13 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:
Handles formats like:
<tool_call>{"name":"web_search","arguments":{"query":"..."}}</tool_call>
<tool_call><function=web_search><parameter=query>...</parameter></function></tool_call>
- Closing tags (</tool_call>, </function>, </parameter>) are all optional
- since models frequently omit them.
+ Closing tags (</tool_call>, </function>, </parameter>) are all
+ optional since models frequently omit them.
"""
tool_calls = []
- # Pattern 1: JSON inside <tool_call> tags.
- # Use balanced-brace extraction that skips braces inside JSON strings.
+ # Pattern 1: JSON inside <tool_call> tags. Balanced-brace extraction
+ # that skips braces inside JSON strings.
for m in _TC_JSON_START_RE.finditer(content):
brace_start = m.end() - 1 # position of the opening {
depth, i = 0, brace_start
@@ -96,11 +96,10 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:
# All closing tags optional -- models frequently omit </parameter>,
# </function>, and/or </tool_call>.
if not tool_calls:
- # Step 1: Find all <function=name> positions and extract their bodies.
- # Body boundary: use only </tool_call> or next <function= as hard
- # boundaries. We avoid using </function> as a boundary because
- # code parameter values can contain that literal string.
- # After extracting, we trim a trailing </function> if present.
+ # Step 1: Find all <function=name> positions and extract bodies.
+ # Use only </tool_call> or the next <function= as hard boundaries;
+ # </function> is avoided since code values can contain it. Trim a
+ # trailing </function> afterwards if present.
func_starts = list(_TC_FUNC_START_RE.finditer(content))
for idx, fm in enumerate(func_starts):
func_name = fm.group(1)
@@ -114,18 +113,18 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:
body_end = len(content)
body_end = min(body_end, next_func)
body = content[body_start:body_end]
- # Trim trailing </function> if present (it's the real closing tag)
+ # Trim the real closing </function> tag if present
body = _TC_FUNC_CLOSE_RE.sub("", body)
- # Step 2: Extract parameters from body.
- # For single-parameter functions (the common case: code, command,
- # query), use body end as the only boundary to avoid false matches
- # on </parameter> inside code strings.
+ # Step 2: Extract parameters from body. For single-parameter
+ # functions (the common code/command/query case), use body end
+ # as the only boundary to avoid matching </parameter> inside
+ # code strings.
arguments = {}
param_starts = list(_TC_PARAM_START_RE.finditer(body))
if len(param_starts) == 1:
- # Single parameter: value is everything from after the tag
- # to end of body, trimming any trailing </parameter>.
+ # Single parameter: value is everything after the tag to
+ # end of body, trimming any trailing </parameter>.
pm = param_starts[0]
val = body[pm.end() :]
val = _TC_PARAM_CLOSE_RE.sub("", val)
@@ -134,7 +133,7 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:
for pidx, pm in enumerate(param_starts):
param_name = pm.group(1)
val_start = pm.end()
- # Value ends at next <parameter= or end of body
+ # Value ends at the next <parameter= or end of body
next_param = (
param_starts[pidx + 1].start()
if pidx + 1 < len(param_starts)
diff --git a/studio/backend/core/training/__init__.py b/studio/backend/core/training/__init__.py
index 6e19805eb09..6ce85aab0d9 100644
--- a/studio/backend/core/training/__init__.py
+++ b/studio/backend/core/training/__init__.py
@@ -1,9 +1,7 @@
# 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 submodule - Training backends and trainer classes
-"""
+"""Training submodule: backends and trainer classes."""
from .training import TrainingBackend, TrainingProgress, get_training_backend
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 781c18ff15f..c43c269aed3 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -3,7 +3,7 @@
"""
Unsloth Training Backend
-Integrates Unsloth training capabilities with the FastAPI backend
+Integrates Unsloth training with the FastAPI backend.
"""
import gc
@@ -14,12 +14,12 @@ import types
# Prevent tokenizer parallelism deadlocks when datasets uses multiprocessing fork
os.environ["TOKENIZERS_PARALLELISM"] = "false"
-# Ensure compiled cache modules are importable by any subprocess.
-# On spawn-based platforms (Windows, macOS), spawned dataset.map() workers must
+# Make compiled cache modules importable by any subprocess.
+# On spawn-based platforms (Windows, macOS), spawned dataset.map() workers
# re-import all top-level modules. The compiled cache's trainer files import
-# torch and unsloth_zoo (which initializes CUDA), making spawn impractical.
-# Propagating UNSLOTH_COMPILE_LOCATION via PYTHONPATH ensures any subprocess
-# (not just Pool workers) can find compiled modules.
+# torch and unsloth_zoo (which inits CUDA), making spawn impractical.
+# Propagating UNSLOTH_COMPILE_LOCATION via PYTHONPATH lets any subprocess
+# (not just Pool workers) find compiled modules.
# NOTE: Do NOT import unsloth_zoo.compiler here -- it triggers heavy torch/triton imports.
if sys.platform in ("win32", "darwin"):
_compile_cache = os.environ.get("UNSLOTH_COMPILE_LOCATION", "unsloth_compiled_cache")
@@ -43,7 +43,7 @@ from utils.hardware import (
)
# recompile_limit was removed in some ROCm torch builds (e.g. pytorch.org/whl/rocm6.2).
-# Guard so training doesn't crash on RDNA2/RDNA3 with older ROCm torch wheels.
+# Guard so training doesn't crash on RDNA2/RDNA3 with older ROCm wheels.
if hasattr(torch._dynamo.config, "recompile_limit"):
torch._dynamo.config.recompile_limit = 64
from unsloth import FastLanguageModel, FastVisionModel, is_bfloat16_supported
@@ -105,7 +105,7 @@ class TrainingProgress:
is_training: bool = False
is_completed: bool = False
error: Optional[str] = None
- status_message: str = "Ready to train" # Current stage message
+ status_message: str = "Ready to train" # Current stage
elapsed_seconds: Optional[float] = None
eta_seconds: Optional[float] = None
grad_norm: Optional[float] = None
@@ -128,16 +128,16 @@ class UnslothTrainer:
self.is_training = False
self.should_stop = False
self.save_on_stop = True
- self.load_in_4bit = True # Track quantization mode for metadata
+ self.load_in_4bit = True # Quantization mode for metadata
# Model state tracking
- self.is_cpt = False # Set to True for Continued Pretraining
+ self.is_cpt = False # True for Continued Pretraining
self.is_vlm = False
self.is_audio = False
self.is_audio_vlm = False # Multimodal model (e.g. Gemma 3N) trained on audio data
self._audio_type = None # 'csm', 'whisper', 'snac', 'bicodec', 'dac'
self._cuda_audio_used = False # Set once after audio CUDA preprocessing; never cleared
- self._spark_tts_repo_dir = None # Path to downloaded Spark-TTS repo (for BiCodecTokenizer)
+ self._spark_tts_repo_dir = None # Downloaded Spark-TTS repo path (for BiCodecTokenizer)
self.model_name = None
# Training metrics tracking
@@ -149,7 +149,7 @@ class UnslothTrainer:
# Thread safety
self._lock = threading.Lock()
- # Store training context for later transfer
+ # Training context for later transfer
self.training_context = {
"base_model_name": None,
"output_dir": None,
@@ -168,13 +168,12 @@ class UnslothTrainer:
"""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 this before
- load_and_format_dataset() when you want to process the dataset
- BEFORE loading the training model (avoids VRAM contention with
- the LLM-assisted detection helper).
+ lightweight tokenizer for dataset formatting. Call before
+ load_and_format_dataset() to process the dataset BEFORE loading the
+ training model (avoids VRAM contention with the LLM-assisted detector).
- load_model() may be called afterwards — it will re-detect and load
- the full model + tokenizer, overwriting the lightweight one set here.
+ load_model() may run afterwards — it 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
@@ -209,8 +208,8 @@ class UnslothTrainer:
)
# --- Load lightweight tokenizer/processor (CPU only, no VRAM) ---
- # Whisper needs AutoProcessor (has feature_extractor + tokenizer).
- # All others work with AutoTokenizer (CSM loads its own processor inline).
+ # Whisper needs AutoProcessor (feature_extractor + tokenizer); others
+ # use AutoTokenizer (CSM loads its own processor inline).
if self._audio_type == "whisper":
from transformers import AutoProcessor
self.tokenizer = AutoProcessor.from_pretrained(
@@ -239,7 +238,6 @@ class UnslothTrainer:
if hasattr(self.training_progress, key):
setattr(self.training_progress, key, value)
- # Notify all callbacks
for callback in self.progress_callbacks:
try:
callback(self.training_progress)
@@ -322,9 +320,9 @@ class UnslothTrainer:
*,
extra_args = None,
):
- """Build training args dict for audio branches.
+ """Build the training args dict for audio branches.
- Constructs the common config (batch size, lr, warmup, fp16/bf16, etc.)
+ Builds the common config (batch size, lr, warmup, fp16/bf16, etc.)
and applies per-branch overrides via extra_args.
"""
batch_size = training_args.get("batch_size", 2)
@@ -410,12 +408,12 @@ class UnslothTrainer:
)
def _cleanup_audio_artifacts(self):
- """Remove sys.path entries and sys.modules from previous audio preprocessing.
+ """Remove sys.path/sys.modules entries from previous audio preprocessing.
- After audio training, cloned repo dirs (OuteTTS, Spark-TTS) remain on
- sys.path and heavy audio modules (snac, whisper, sparktts, outetts) stay
- in sys.modules. When the next training run calls dataset.map(num_proc=N),
- forked child processes inherit this stale state and deadlock.
+ After audio training, cloned repo dirs (OuteTTS, Spark-TTS) stay on
+ sys.path and heavy modules (snac, whisper, sparktts, outetts) stay in
+ sys.modules. On the next dataset.map(num_proc=N), forked children
+ inherit this stale state and deadlock.
"""
# Remove cloned audio repo paths from sys.path
base_dir = os.path.dirname(os.path.abspath(__file__))
@@ -450,10 +448,9 @@ class UnslothTrainer:
dataset,
custom_format_mapping: dict = None,
):
- """Resolve audio, text, and speaker columns from user mapping or hardcoded fallback.
+ """Resolve audio/text/speaker columns from user mapping or fallback.
- Returns:
- dict with keys: audio_col, text_col, speaker_col (speaker_col may be None)
+ Returns dict with keys audio_col, text_col, speaker_col (may be None).
"""
cols = dataset.column_names
@@ -468,7 +465,7 @@ class UnslothTrainer:
text_col = col
elif role == "speaker_id":
speaker_col = col
- # Use mapping if both required columns exist in the dataset
+ # Use mapping if both required columns exist
if audio_col and audio_col in cols and text_col and text_col in cols:
return {
"audio_col": audio_col,
@@ -476,7 +473,7 @@ class UnslothTrainer:
"speaker_col": speaker_col,
}
- # Hardcoded fallback (existing behavior)
+ # Hardcoded fallback
audio_col = next((c for c in cols if c.lower() in ("audio", "speech")), None)
text_col = next(
(c for c in cols if c.lower() in ("text", "sentence", "transcript", "transcription")),
@@ -508,7 +505,7 @@ class UnslothTrainer:
gpu_ids: Optional[list[int]] = None,
) -> bool:
"""Load model for training (supports both text and vision models)"""
- self.load_in_4bit = load_in_4bit # Store for training_meta.json
+ self.load_in_4bit = load_in_4bit # For training_meta.json
self.trust_remote_code = trust_remote_code # For AutoProcessor etc. used during training
try:
if self.model is not None:
@@ -522,16 +519,16 @@ class UnslothTrainer:
logger.info("\nClearing GPU memory before training...")
clear_gpu_cache()
- # Clean up sys.path and sys.modules from previous audio preprocessing
- # to prevent deadlocks when forking worker processes in dataset.map()
+ # Clean up sys.path/sys.modules from previous audio preprocessing
+ # to prevent deadlocks when forking dataset.map() workers
self._cleanup_audio_artifacts()
- # Reload Unsloth-patched transformers modeling modules before clearing
- # the compiled cache. unsloth_compile_transformers() sets __UNSLOTH_PATCHED__
- # on each modeling module and replaces methods with exec'd code.
- # clear_unsloth_compiled_cache() deletes the disk cache, but the flag
- # prevents re-compilation — leaving missing cache files. Reloading
- # restores original class definitions so Unsloth can re-compile cleanly.
+ # Reload Unsloth-patched transformers modeling modules before
+ # clearing the compiled cache. unsloth_compile_transformers() sets
+ # __UNSLOTH_PATCHED__ and replaces methods with exec'd code.
+ # clear_unsloth_compiled_cache() deletes the disk cache, but the
+ # flag blocks re-compilation, leaving missing cache files. Reloading
+ # restores original class defs so Unsloth re-compiles cleanly.
import importlib
for _key, _mod in list(sys.modules.items()):
@@ -540,7 +537,7 @@ class UnslothTrainer:
try:
importlib.reload(_mod)
except Exception:
- pass # Non-critical — Unsloth will handle stale modules
+ pass # Non-critical — Unsloth handles stale modules
# Remove stale compiled cache so the new model gets a fresh one
from utils.cache_cleanup import clear_unsloth_compiled_cache
@@ -549,7 +546,7 @@ class UnslothTrainer:
clear_unsloth_compiled_cache(preserve_patterns = _preserve)
# Detect audio model type dynamically (config.json + tokenizer)
self._audio_type = detect_audio_type(model_name, hf_token)
- # audio_vlm is detected as an audio_type now, handle it separately
+ # audio_vlm is detected as an audio_type now; handle separately
if self._audio_type == "audio_vlm":
self.is_audio = False
self.is_audio_vlm = is_dataset_audio # Only use audio VLM path if dataset has audio
@@ -561,7 +558,7 @@ class UnslothTrainer:
if not self.is_audio and not self.is_audio_vlm:
self._cuda_audio_used = False
- # VLM: vision model with image dataset (mutually exclusive with audio paths)
+ # VLM: vision model + image dataset (mutually exclusive with audio)
vision = is_vision_model(model_name, hf_token = hf_token) if not self.is_audio else False
self.is_vlm = not self.is_audio_vlm and vision and is_dataset_image
self.model_name = model_name
@@ -583,7 +580,7 @@ class UnslothTrainer:
epoch = 0,
)
- # Update UI immediately with loading message
+ # Update UI with loading message
model_display = model_name.split("/")[-1] if "/" in model_name else model_name
model_type_label = "audio" if self.is_audio else ("vision" if self.is_vlm else "text")
self._update_progress(
@@ -596,15 +593,15 @@ class UnslothTrainer:
if hf_token:
os.environ["HF_TOKEN"] = hf_token
- # Proactive gated-model check: verify access BEFORE from_pretrained.
- # Catches ALL gated/private models (text, vision, audio) globally.
- # Skip when offline -- from_pretrained will use the cache.
+ # Proactive gated-model check before from_pretrained. Catches ALL
+ # gated/private models (text, vision, audio) globally. Skip when
+ # offline -- from_pretrained uses the cache.
if "/" in model_name and not _env_offline():
try:
from huggingface_hub import model_info as hf_model_info
info = hf_model_info(model_name, token = hf_token or None)
- # model_info succeeds even for gated repos (metadata is public),
- # but info.gated tells us if files require acceptance/token.
+ # model_info succeeds for gated repos (metadata is public);
+ # info.gated tells us if files require acceptance/token.
if info.gated and not hf_token:
friendly = (
f"Access denied for '{model_name}'. This model is gated. "
@@ -634,15 +631,15 @@ class UnslothTrainer:
f"Using device_map='{device_map}' ({get_visible_gpu_count()} GPU(s) visible)"
)
- # AMD ROCm hardware without native bfloat16 (e.g. RDNA2 / gfx103x)
- # crashes with an LLVM error at the first bf16 kernel dispatch if
- # dtype=None lets unsloth auto-pick bf16. Force float16 there so that
- # path is never reached. NVIDIA keeps dtype=None so unsloth's own
- # bf16/fp16/float32 auto-detection (including FORCE_FLOAT32 models) is
- # honored -- older NVIDIA without bf16 (T4/V100) must NOT be coerced to
- # float16 here, which the previous unconditional branch did wrongly.
- # Derive ROCm inline (not hardware.IS_ROCM) because that flag is unset
- # until detect_hardware() runs, which isn't guaranteed in this subprocess.
+ # AMD ROCm without native bfloat16 (e.g. RDNA2 / gfx103x) crashes
+ # with an LLVM error at the first bf16 kernel dispatch if dtype=None
+ # lets unsloth auto-pick bf16. Force float16 there. NVIDIA keeps
+ # dtype=None so unsloth's bf16/fp16/float32 auto-detection (incl.
+ # FORCE_FLOAT32 models) is honored -- older NVIDIA without bf16
+ # (T4/V100) must NOT be coerced to float16 (the previous
+ # unconditional branch did this wrongly). Derive ROCm inline (not
+ # hardware.IS_ROCM) since that flag is unset until detect_hardware()
+ # runs, not guaranteed in this subprocess.
_is_rocm = (
bool(getattr(torch.version, "hip", None)) or "rocm" in torch.__version__.lower()
)
@@ -650,7 +647,7 @@ class UnslothTrainer:
# Branch based on model type
if self._audio_type == "csm":
- # CSM: FastModel + auto_model=CsmForConditionalGeneration + load_in_4bit=False
+ # CSM: FastModel, auto_model=CsmForConditionalGeneration, load_in_4bit=False
from unsloth import FastModel
from transformers import CsmForConditionalGeneration
@@ -668,7 +665,7 @@ class UnslothTrainer:
logger.info("Loaded CSM audio model")
elif self._audio_type == "whisper":
- # Whisper: FastModel + auto_model=WhisperForConditionalGeneration + load_in_4bit=False
+ # Whisper: FastModel, auto_model=WhisperForConditionalGeneration, load_in_4bit=False
from unsloth import FastModel
from transformers import WhisperForConditionalGeneration
@@ -684,7 +681,7 @@ class UnslothTrainer:
token = hf_token,
trust_remote_code = trust_remote_code,
)
- # Configure generation settings (notebook lines 100-105)
+ # Generation settings (notebook lines 100-105)
self.model.generation_config.language = "<|en|>"
self.model.generation_config.task = "transcribe"
self.model.config.suppress_tokens = []
@@ -706,8 +703,8 @@ class UnslothTrainer:
logger.info(f"Loaded {self._audio_type} audio model (FastLanguageModel)")
elif self._audio_type == "bicodec":
- # Spark-TTS: download full repo (contains sparktts package + BiCodec weights),
- # then load only the LLM subfolder with FastModel.
+ # Spark-TTS: download full repo (sparktts package + BiCodec
+ # weights), then load only the LLM subfolder with FastModel.
# model_name may be:
# "Spark-TTS-0.5B/LLM" (local-style, from YAML mapping)
# "unsloth/Spark-TTS-0.5B" (HF repo ID)
@@ -726,7 +723,7 @@ class UnslothTrainer:
llm_path = f"{local_dir}/LLM"
repo_path = snapshot_download(hf_repo, local_dir = local_dir)
- self._spark_tts_repo_dir = os.path.abspath(repo_path) # Absolute path for sys.path
+ self._spark_tts_repo_dir = os.path.abspath(repo_path) # Absolute for sys.path
llm_path = os.path.join(self._spark_tts_repo_dir, "LLM")
self.model, self.tokenizer = FastModel.from_pretrained(
@@ -756,8 +753,8 @@ class UnslothTrainer:
logger.info("Loaded OuteTTS (dac) model (FastModel)")
elif self.is_audio_vlm:
- # Audio VLM: multimodal model trained on audio (e.g. Gemma 3N)
- # Uses FastModel (general loader) — returns (model, processor)
+ # Audio VLM: multimodal model trained on audio (e.g. Gemma 3N).
+ # FastModel (general loader) returns (model, processor).
from unsloth import FastModel
self.model, self.tokenizer = FastModel.from_pretrained(
model_name = model_name,
@@ -785,7 +782,7 @@ class UnslothTrainer:
)
logger.info("Loaded vision model")
- # Diagnostic: check if FastVisionModel returned a real Processor or a raw tokenizer
+ # Diagnostic: did FastVisionModel return a Processor or a raw tokenizer?
from transformers import ProcessorMixin
tok = self.tokenizer
@@ -818,8 +815,7 @@ class UnslothTrainer:
return False
if full_finetuning:
- # Enable training mode for full fine-tuning
- # This ensures all model parameters are trainable; otherwise, they might be frozen.
+ # Enable training mode so all params are trainable (else frozen)
self.model.for_training()
self._update_progress(status_message = "Model loaded successfully")
@@ -832,9 +828,9 @@ class UnslothTrainer:
):
# Unsloth's patching can leave stale state that makes
# inspect.getsource() fail when switching model families
- # (e.g. gemma3 → gemma3n). The load always succeeds on a
- # second attempt because the failed first call's partial
- # imports clean up the stale state as a side effect.
+ # (e.g. gemma3 → gemma3n). The second attempt always succeeds
+ # because the failed first call's partial imports clean up the
+ # stale state as a side effect.
self._source_code_retried = True
logger.info(f"\n'could not get source code' — retrying once...\n")
return self.load_model(
@@ -870,7 +866,7 @@ class UnslothTrainer:
return False
except Exception as e:
error_msg = str(e)
- # Catch gated/auth errors and surface a friendly message
+ # Surface a friendly message for gated/auth errors
error_lower = error_msg.lower()
if any(
k in error_lower
@@ -918,14 +914,14 @@ class UnslothTrainer:
if self.model is None:
raise ValueError("Model not loaded. Call load_model() first.")
- # Full finetuning mode - skip PEFT entirely
+ # Full finetuning - skip PEFT entirely
if not use_lora:
self._update_progress(status_message = "Full finetuning mode - no LoRA adapters")
logger.info("Full finetuning mode - training all parameters\n")
return True
- # LoRA/QLoRA mode - apply PEFT
- # "all-linear" is a PEFT keyword that targets every linear layer
+ # LoRA/QLoRA - apply PEFT.
+ # "all-linear" is a PEFT keyword targeting every linear layer.
if isinstance(target_modules, list) and "all-linear" in target_modules:
if len(target_modules) == 1:
target_modules = "all-linear"
@@ -944,8 +940,7 @@ class UnslothTrainer:
"down_proj",
]
- # Validate and normalize gradient_checkpointing
- # Must be one of: True, False, or "unsloth"
+ # Normalize gradient_checkpointing to True, False, or "unsloth"
if isinstance(use_gradient_checkpointing, str):
use_gradient_checkpointing = use_gradient_checkpointing.strip().lower()
if use_gradient_checkpointing == "" or use_gradient_checkpointing == "unsloth":
@@ -955,13 +950,13 @@ class UnslothTrainer:
elif use_gradient_checkpointing in ("false", "0", "no"):
use_gradient_checkpointing = False
else:
- # Invalid value, default to "unsloth"
+ # Invalid value -> "unsloth"
logger.warning(
f"Invalid gradient_checkpointing value: {use_gradient_checkpointing}, defaulting to 'unsloth'"
)
use_gradient_checkpointing = "unsloth"
elif use_gradient_checkpointing not in (True, False, "unsloth"):
- # Invalid type or value, default to "unsloth"
+ # Invalid type/value -> "unsloth"
logger.warning(
f"Invalid gradient_checkpointing type/value: {use_gradient_checkpointing}, defaulting to 'unsloth'"
)
@@ -974,7 +969,7 @@ class UnslothTrainer:
self._update_progress(error = error_msg)
return False
- # Check if model has the expected attributes
+ # Check expected attributes
if not hasattr(self.model, "config"):
error_msg = (
"Model does not have config attribute - model may not be loaded correctly"
@@ -988,9 +983,9 @@ class UnslothTrainer:
f"Gradient checkpointing: {use_gradient_checkpointing} (type: {type(use_gradient_checkpointing).__name__})\n"
)
- # Branch based on model type: audio, audio_vlm, vision, or text
+ # Branch by model type: audio, audio_vlm, vision, or text
if self._audio_type in ("csm", "bicodec", "dac") or self.is_audio_vlm:
- # Models using FastModel.get_peft_model (codec audio + audio VLM)
+ # Use FastModel.get_peft_model (codec audio + audio VLM)
from unsloth import FastModel
label = self._audio_type or "audio_vlm"
@@ -1026,7 +1021,7 @@ class UnslothTrainer:
self.model = FastModel.get_peft_model(self.model, **peft_kwargs)
elif self._audio_type == "whisper":
- # Phase 2: Whisper uses FastModel.get_peft_model with task_type=None
+ # Whisper: FastModel.get_peft_model with task_type=None
from unsloth import FastModel
logger.info(f"Audio model (whisper) LoRA configuration:")
@@ -1047,7 +1042,7 @@ class UnslothTrainer:
)
elif self._audio_type == "snac":
- # Orpheus uses FastLanguageModel.get_peft_model
+ # Orpheus: FastLanguageModel.get_peft_model
logger.info(f"Audio model ({self._audio_type}) LoRA configuration:")
logger.info(f" - Target modules: {target_modules}\n")
@@ -1135,14 +1130,14 @@ class UnslothTrainer:
return False
def _apply_csm_forward_fix(self):
- """Monkey-patch CsmForConditionalGeneration.forward to fix depth decoder kwargs.
+ """Monkey-patch CsmForConditionalGeneration.forward for depth decoder kwargs.
- The original transformers forward passes raw **kwargs (num_items_in_batch,
- causal_mask, etc.) from the Trainer/PEFT through to the depth decoder,
- causing depth_decoder_loss=None and 'Tensor + NoneType' crash.
+ The original forward passes raw **kwargs (num_items_in_batch,
+ causal_mask, etc.) from Trainer/PEFT through to the depth decoder,
+ causing depth_decoder_loss=None and a 'Tensor + NoneType' crash.
- We patch at both instance AND class level for maximum reliability,
- and strip non-TransformersKwargs params that Unsloth/PEFT inject.
+ Patch at both instance AND class level for reliability, and strip
+ non-TransformersKwargs params that Unsloth/PEFT inject.
"""
import torch
import torch.nn as nn
@@ -1153,10 +1148,10 @@ class UnslothTrainer:
base_csm = self.model.base_model.model # CsmForConditionalGeneration
- # Save original forward (the @can_return_tuple wrapped version)
+ # Original forward (@can_return_tuple wrapped version)
_original_forward = CsmForConditionalGeneration.forward
- # Keys that the depth decoder and its sub-layers actually understand
+ # Keys the depth decoder and its sub-layers understand
_TRANSFORMERS_KWARGS = {
"num_items_in_batch",
"output_hidden_states",
@@ -1183,7 +1178,7 @@ class UnslothTrainer:
logits_to_keep = 0,
**kwargs,
):
- # Strip non-standard kwargs injected by Unsloth/PEFT (causal_mask,
+ # Strip non-standard kwargs from Unsloth/PEFT (causal_mask,
# num_logits_to_keep, task_ids, return_dict, etc.)
output_attentions = kwargs.pop("output_attentions", None)
output_hidden_states = kwargs.pop("output_hidden_states", None)
@@ -1247,9 +1242,9 @@ class UnslothTrainer:
]
depth_decoder_labels = labels[train_mask]
- # Build clean kwargs for depth decoder
+ # Clean kwargs for depth decoder; scale num_items_in_batch
+ # for its 31 codebooks
dd_kwargs = clean_kwargs.copy()
- # Scale num_items_in_batch for depth decoder (31 codebooks)
if "num_items_in_batch" in dd_kwargs:
dd_kwargs["num_items_in_batch"] = dd_kwargs["num_items_in_batch"] * (
self.config.num_codebooks - 1
@@ -1273,7 +1268,7 @@ class UnslothTrainer:
f"labels shape={depth_decoder_labels.shape}, "
f"train_mask sum={train_mask.sum().item()}"
)
- # Fallback: use only backbone loss instead of crashing
+ # Fallback: use only backbone loss to avoid crashing
loss = backbone_loss
else:
loss = backbone_loss + depth_decoder_loss
@@ -1300,10 +1295,10 @@ class UnslothTrainer:
),
)
- # Patch at BOTH instance and class level for maximum reliability.
- # Instance-level: catches calls via BaseTuner.forward -> self.model.forward()
+ # Patch BOTH instance and class level for reliability.
+ # Instance: catches calls via BaseTuner.forward -> self.model.forward()
base_csm.forward = types.MethodType(_fixed_csm_forward, base_csm)
- # Class-level: catches any path that resolves through the class dict
+ # Class: catches any path resolving through the class dict
CsmForConditionalGeneration.forward = _fixed_csm_forward
logger.info("Applied CSM forward fix (class + instance level)\n")
@@ -1322,9 +1317,10 @@ class UnslothTrainer:
trust_remote_code = getattr(self, "trust_remote_code", False),
)
- # Strip pad_to_multiple_of from tokenizer init_kwargs — fine-tuned models
- # (e.g. keanteng/sesame-csm-elise) save it in tokenizer_config.json, and
- # _merge_kwargs leaks it into audio_kwargs where EncodecFeatureExtractor rejects it.
+ # Strip pad_to_multiple_of from tokenizer init_kwargs — fine-tuned
+ # models (e.g. keanteng/sesame-csm-elise) save it 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)
# Resolve columns from user mapping or hardcoded fallback
@@ -1376,7 +1372,7 @@ class UnslothTrainer:
}
]
# NOTE: pad_to_multiple_of intentionally omitted from text_kwargs —
- # CsmProcessor._merge_kwargs leaks it to EncodecFeatureExtractor which rejects it.
+ # CsmProcessor._merge_kwargs leaks it to EncodecFeatureExtractor, which rejects it.
model_inputs = processor.apply_chat_template(
conversation,
tokenize = True,
@@ -1433,8 +1429,8 @@ class UnslothTrainer:
):
"""Format dataset as audio chat messages for multimodal models (e.g. Gemma 3N).
- Expects columns: audio (Audio), text (str).
- Produces: messages column with system/user/assistant chat format.
+ Expects columns audio (Audio), text (str). Produces a messages column
+ with system/user/assistant chat format.
"""
from datasets import Audio
@@ -1496,9 +1492,9 @@ class UnslothTrainer:
):
"""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).
+ 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
@@ -1529,12 +1525,12 @@ class UnslothTrainer:
f"SNAC dataset needs 'audio' and 'text' columns, got: {dataset.column_names}"
)
- # Cast audio column so datasets 4.x AudioDecoder objects are decoded to dicts
+ # Cast audio so datasets 4.x AudioDecoder objects decode to dicts
from datasets import Audio
dataset = dataset.cast_column(audio_col, Audio(sampling_rate = SNAC_SAMPLE_RATE))
- # Get dataset sample rate from first example (after cast, always SNAC_SAMPLE_RATE)
+ # Sample rate from first example (after cast, always SNAC_SAMPLE_RATE)
first_audio = dataset[0][audio_col]
ds_sample_rate = (
first_audio.get("sampling_rate", SNAC_SAMPLE_RATE)
@@ -1582,7 +1578,7 @@ class UnslothTrainer:
skipped += 1
continue
- # --- Encode audio with SNAC (notebook lines 122-142) ---
+ # --- Encode audio with SNAC (notebook 122-142) ---
waveform = (
torch.from_numpy(audio_data["array"]).unsqueeze(0).to(dtype = torch.float32)
)
@@ -1593,7 +1589,7 @@ class UnslothTrainer:
with torch.inference_mode():
codes = snac_model.encode(waveform)
- # Interleave 7 codes per frame with layer offsets (notebook lines 134-142)
+ # Interleave 7 codes per frame with layer offsets (notebook 134-142)
all_codes = []
for i in range(codes[0].shape[1]):
all_codes.append(codes[0][0][i].item() + AUDIO_OFFSET)
@@ -1608,14 +1604,14 @@ class UnslothTrainer:
skipped += 1
continue
- # Deduplicate consecutive frames with same first code (notebook lines 185-207)
+ # Dedup consecutive frames with same first code (notebook 185-207)
deduped = all_codes[:7]
for i in range(7, len(all_codes), 7):
if all_codes[i] != deduped[-7]:
deduped.extend(all_codes[i : i + 7])
all_codes = deduped
- # --- Build text tokens (notebook lines 217-224) ---
+ # --- Build text tokens (notebook 217-224) ---
text_prompt = (
f"{example[speaker_col]}: {text}"
if has_source and example.get(speaker_col)
@@ -1624,7 +1620,7 @@ class UnslothTrainer:
text_ids = tokenizer.encode(text_prompt, add_special_tokens = True)
text_ids.append(END_OF_TEXT)
- # --- Build full input_ids (notebook lines 225-234) ---
+ # --- Build full input_ids (notebook 225-234) ---
input_ids = (
[START_OF_HUMAN]
+ text_ids
@@ -1639,7 +1635,7 @@ class UnslothTrainer:
# Truncate to max_length
input_ids = input_ids[:max_length]
- # Labels = input_ids (no masking — Orpheus trains on full sequence)
+ # Labels = input_ids (no masking; Orpheus trains full sequence)
labels = list(input_ids)
attention_mask = [1] * len(input_ids)
@@ -1685,8 +1681,9 @@ class UnslothTrainer:
):
"""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".
+ 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
@@ -1694,8 +1691,8 @@ class UnslothTrainer:
device = "cuda" if torch.cuda.is_available() else "cpu"
- # The sparktts Python package lives in the SparkAudio/Spark-TTS GitHub repo,
- # NOT in the unsloth/Spark-TTS-0.5B HF model repo. Clone it if needed.
+ # The sparktts package lives in the SparkAudio/Spark-TTS GitHub repo,
+ # NOT in the unsloth/Spark-TTS-0.5B HF model repo. Clone if needed.
spark_code_dir = os.path.join(os.path.dirname(self._spark_tts_repo_dir), "Spark-TTS")
sparktts_pkg = os.path.join(spark_code_dir, "sparktts")
if not os.path.isdir(sparktts_pkg):
@@ -1732,8 +1729,8 @@ class UnslothTrainer:
f"BiCodec dataset needs 'audio' and 'text' columns, got: {dataset.column_names}"
)
- # Cast audio column so datasets 4.x AudioDecoder objects are decoded to dicts.
- # Don't resample here — BiCodec's target_sr may differ; the loop handles resampling.
+ # Cast audio so datasets 4.x AudioDecoder objects decode to dicts.
+ # Don't resample here — BiCodec's target_sr may differ; the loop does it.
from datasets import Audio
dataset = dataset.cast_column(audio_col, Audio())
@@ -1837,7 +1834,7 @@ class UnslothTrainer:
]
)
- # Format text with source prefix if available
+ # Prefix text with source if available
text_content = (
f"{example[speaker_col]}: {text}"
if has_source and example.get(speaker_col)
@@ -1891,7 +1888,7 @@ class UnslothTrainer:
f"BiCodec preprocessing complete: {len(result_dataset)} examples "
f"({skipped} skipped)\n"
)
- # Debug: show first example text (truncated)
+ # Debug: first example text (truncated)
sample = result_dataset[0]["text"]
logger.info(f"Sample text (first 200 chars): {sample[:200]}...\n")
logger.info(f"Sample text length: {len(sample)} chars\n")
@@ -1904,9 +1901,10 @@ class UnslothTrainer:
):
"""Preprocess dataset for OuteTTS training with DAC codec.
- Mirrors Oute_TTS_(1B).ipynb DataCreationV3: uses Whisper for word timings,
+ 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".
+ training prompts. Outputs text strings for SFTTrainer with
+ dataset_text_field="text".
"""
import io
import tempfile
@@ -1964,7 +1962,7 @@ class UnslothTrainer:
f"DAC dataset needs 'audio' and 'text' columns, got: {dataset.column_names}"
)
- # Cast audio to 24kHz (notebook: dataset.cast_column("audio", Audio(sampling_rate=24000)))
+ # Cast audio to 24kHz (notebook: cast_column("audio", Audio(sampling_rate=24000)))
from datasets import Audio
dataset = dataset.cast_column(audio_col, Audio(sampling_rate = 24000))
@@ -2079,7 +2077,7 @@ class UnslothTrainer:
status_message = f"Preprocessing audio with OuteTTS... {idx + 1}/{len(dataset)}"
)
- # Free Whisper from GPU (notebook: data_processor.whisper_model.to('cpu'))
+ # Free Whisper from GPU (notebook: whisper_model.to('cpu'))
logger.info("Moving Whisper model to CPU...\n")
whisper_model.to("cpu")
del whisper_model
@@ -2110,8 +2108,8 @@ class UnslothTrainer:
"""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) where
- each is a list of dicts with 'input_features' and 'labels'.
+ extractor, tokenize text labels. Returns (train_data, eval_data),
+ each a list of dicts with 'input_features' and 'labels'.
"""
from datasets import Audio
@@ -2157,11 +2155,11 @@ class UnslothTrainer:
skipped += 1
continue
- # Extract audio features (notebook line 112-115)
+ # Extract audio features (notebook 112-115)
features = self.tokenizer.feature_extractor(
audio_data["array"], sampling_rate = audio_data["sampling_rate"]
)
- # Tokenize text (notebook line 116)
+ # Tokenize text (notebook 116)
tokenized_text = self.tokenizer.tokenizer(text)
processed.append(
@@ -2254,14 +2252,13 @@ class UnslothTrainer:
is_cpt: bool = False,
) -> Optional[tuple]:
"""
- Load and prepare dataset for training.
+ Load and prepare a dataset for training.
Strategy: format first, then split — ensures both train and eval
- portions are properly formatted and templated.
+ portions are formatted and templated.
- Returns:
- Tuple of (dataset_info, eval_dataset) or None on error.
- eval_dataset may be None if no eval split is available.
+ Returns (dataset_info, eval_dataset) or None on error; eval_dataset
+ may be None if no eval split is available.
"""
try:
dataset = None
@@ -2299,10 +2296,10 @@ class UnslothTrainer:
return result.dataset
if local_datasets:
- # Load local datasets using load_dataset() so the result is
- # Arrow-backed (has cache files). Dataset.from_list() creates
- # an in-memory dataset with no cache, which forces num_proc=1
- # during tokenization/map because sharding requires Arrow files.
+ # Use load_dataset() so the result is Arrow-backed (has cache
+ # files). Dataset.from_list() is in-memory with no cache, which
+ # forces num_proc=1 during tokenization/map (sharding needs
+ # Arrow files).
all_files = self._resolve_local_files(local_datasets)
if all_files:
@@ -2346,8 +2343,7 @@ class UnslothTrainer:
and dataset_slice_end >= 0
and dataset_slice_end >= _slice_start
):
- # Manual slice — stream only the rows we need instead of
- # downloading the entire dataset.
+ # Manual slice — stream only needed rows, not the whole dataset.
rows_to_stream = dataset_slice_end + 1
logger.info(
f"[dataset-slice] Manual slice specified "
@@ -2382,11 +2378,11 @@ class UnslothTrainer:
f"Loaded dataset from Hugging Face: {dataset_source} ({n_rows:,} rows)\n"
)
- # Resolve eval split from a separate HF split (explicit or auto-detected)
+ # Resolve eval split from a separate HF split (explicit or auto)
if eval_enabled:
effective_train = train_split or "train"
if eval_split and eval_split != effective_train:
- # Explicit eval split provided - load it directly
+ # Explicit eval split — load directly
logger.info(f"Loading explicit eval split: '{eval_split}'\n")
eval_load_kwargs = {"path": dataset_source, "split": eval_split}
if subset:
@@ -2397,12 +2393,12 @@ class UnslothTrainer:
f"Loaded eval split '{eval_split}' with {len(eval_dataset)} rows\n"
)
elif eval_split and eval_split == effective_train:
- # Same split as training — will do 80/20 split after formatting
+ # Same split as training — split 80/20 after formatting
logger.info(
f"Eval split '{eval_split}' is the same as train split — will split 80/20\n"
)
else:
- # Auto-detect eval split from HF (returns a separate dataset, or None)
+ # Auto-detect eval split from HF (separate dataset or None)
eval_dataset = self._auto_detect_eval_split_from_hf(
dataset_source = dataset_source,
subset = subset,
@@ -2415,7 +2411,7 @@ class UnslothTrainer:
if dataset is None:
raise ValueError("No dataset provided")
- # Apply index range slicing if requested (inclusive on both ends)
+ # Apply index range slicing if requested (inclusive both ends)
if dataset_slice_start is not None or dataset_slice_end is not None:
total_rows = len(dataset)
start = dataset_slice_start if dataset_slice_start is not None else 0
@@ -2575,7 +2571,7 @@ class UnslothTrainer:
def _auto_detect_eval_split_from_hf(
self, dataset_source: str, subset: str
) -> Optional[Dataset]:
- """Auto-detect an eval split from HF dataset (separate named split only)."""
+ """Auto-detect an eval split from an HF dataset (named split only)."""
try:
from datasets import get_dataset_split_names
@@ -2605,14 +2601,13 @@ class UnslothTrainer:
except Exception as e:
logger.warning(f"Could not check dataset splits: {e}")
- # No separate HF eval split found — caller will handle programmatic splitting
+ # No separate HF eval split — caller handles programmatic splitting
return None
def _resolve_eval_split_from_dataset(self, dataset) -> Optional[tuple]:
"""Split a dataset into train and eval portions.
- Returns:
- Tuple of (train_dataset, eval_dataset), or None if dataset too small.
+ Returns (train_dataset, eval_dataset), or None if too small.
"""
MIN_EVAL_ROWS = 16
MIN_TOTAL_ROWS = 32 # Need at least 16 train + 16 eval
@@ -2623,7 +2618,7 @@ class UnslothTrainer:
return None
eval_size = max(MIN_EVAL_ROWS, min(128, int(0.05 * n)))
- # Ensure we don't take more than half the dataset
+ # Don't take more than half the dataset
eval_size = min(eval_size, n // 2)
logger.info(f"Auto-splitting: {eval_size} rows for eval from {n} total\n")
@@ -2669,10 +2664,10 @@ class UnslothTrainer:
self._update_progress(error = "Model not loaded")
return False
- # Pre-import heavy transformers modules on the main thread.
- # Unsloth's patched_import hook (deepseek_v3_moe.py) is not thread-safe
- # with Python's importlib cache, causing KeyError: 'size' if these are
- # first imported inside the worker thread.
+ # Pre-import heavy transformers modules on the main thread. Unsloth's
+ # patched_import hook (deepseek_v3_moe.py) isn't thread-safe with
+ # importlib's cache, causing KeyError: 'size' if first imported in the
+ # worker thread.
import transformers # noqa: F401 – ensures submodules are cached
from transformers import ( # noqa: F401
Trainer as _HFTrainer,
@@ -2730,7 +2725,7 @@ class UnslothTrainer:
"""Worker function for training (runs in separate thread)"""
try:
# On spawn-based platforms (Windows, macOS), register all known
- # compiled-cache directories on sys.path and PYTHONPATH before any
+ # compiled-cache dirs on sys.path/PYTHONPATH before any
# dataset.map() call so spawned workers can import dynamically
# compiled modules such as UnslothSFTTrainer.
if sys.platform in ("win32", "darwin"):
@@ -2759,8 +2754,8 @@ class UnslothTrainer:
# ========== AUDIO TRAINER BRANCH ==========
if self._audio_type == "csm":
- # CSM uses plain HF Trainer (NOT SFTTrainer)
- # Needs remove_unused_columns=False for depth decoder (input_values + cutoffs)
+ # CSM uses plain HF Trainer (NOT SFTTrainer). Needs
+ # remove_unused_columns=False for depth decoder (input_values + cutoffs).
from transformers import Trainer as HFTrainer, TrainingArguments
self._apply_csm_forward_fix()
@@ -2796,9 +2791,9 @@ class UnslothTrainer:
return
elif self._audio_type == "snac":
- # Orpheus: language model with SNAC codec tokens — plain HF Trainer
- # DataCollatorForSeq2Seq dynamically pads variable-length sequences per batch
- # (text + audio codes vary in length) and pads labels with -100.
+ # Orpheus: LM with SNAC codec tokens — plain HF Trainer.
+ # DataCollatorForSeq2Seq pads variable-length sequences per
+ # batch (text + audio codes vary) and pads labels with -100.
from transformers import (
Trainer as HFTrainer,
TrainingArguments,
@@ -2890,7 +2885,6 @@ class UnslothTrainer:
)
# ========== DATA COLLATOR SELECTION ==========
- # Detect special model types
model_name_lower = self.model_name.lower()
is_deepseek_ocr = "deepseek" in model_name_lower and "ocr" in model_name_lower
@@ -2901,11 +2895,10 @@ class UnslothTrainer:
)
raw_text_mode = dataset_final_format == "raw_text"
- data_collator = None # Default to built-in data collator
+ data_collator = None # Default: built-in collator
if is_deepseek_ocr:
- # Special DeepSeek OCR collator - auto-install if needed
+ # DeepSeek OCR collator - auto-install if needed
logger.info("Detected DeepSeek OCR model\n")
- # Ensure DeepSeek OCR module is installed
if not _ensure_deepseek_ocr_installed():
error_msg = (
"Failed to install DeepSeek OCR module. "
@@ -2924,7 +2917,7 @@ class UnslothTrainer:
FastVisionModel.for_training(self.model)
# DeepSeek OCR's (image_size, base_size, crop_mode) is a
# coupled preset; changing image_size alone desyncs the
- # per-crop pixel grid from num_queries. Use Gundam.
+ # per-crop pixel grid from num_queries. Use Gundam preset.
if training_args.get("vision_image_size") is not None:
logger.info(
"Vision image resize ignored for DeepSeek OCR "
@@ -2947,8 +2940,8 @@ class UnslothTrainer:
return
elif self.is_audio_vlm and not raw_text_mode:
- # Audio VLM collator (e.g. Gemma 3N with audio data)
- # Mirrors the collate_fn from Gemma3N_(4B)-Audio notebook
+ # Audio VLM collator (e.g. Gemma 3N with audio).
+ # Mirrors the collate_fn from Gemma3N_(4B)-Audio notebook.
logger.info("Configuring audio VLM data collator...\n")
processor = self.tokenizer # FastModel returns processor as tokenizer
@@ -3006,7 +2999,6 @@ class UnslothTrainer:
logger.info("Vision data collator configured\n")
# ========== TRAINING CONFIGURATION ==========
- # Handle warmup_steps vs warmup_ratio
warmup_steps_val = training_args.get("warmup_steps", None)
warmup_ratio_val = training_args.get("warmup_ratio", None)
@@ -3044,14 +3036,14 @@ class UnslothTrainer:
)
# On spawn-based platforms (Windows, macOS) with transformers 5.x,
- # disable DataLoader multiprocessing to avoid issues with modified
- # sys.path (.venv_t5) in spawned workers.
+ # disable DataLoader multiprocessing to avoid modified sys.path
+ # (.venv_t5) issues in spawned workers.
if sys.platform in ("win32", "darwin"):
import transformers as _tf
if _tf.__version__.startswith("5."):
config_args["dataloader_num_workers"] = 0
- # Add warmup parameter - use warmup_ratio if provided, otherwise warmup_steps
+ # Use warmup_ratio if provided, else warmup_steps
if warmup_ratio_val is not None:
config_args["warmup_ratio"] = warmup_ratio_val
logger.info(f"Using warmup_ratio: {warmup_ratio_val}\n")
@@ -3059,7 +3051,7 @@ class UnslothTrainer:
config_args["warmup_steps"] = warmup_steps_val
logger.info(f"Using warmup_steps: {warmup_steps_val}\n")
else:
- # Default to warmup_steps if neither provided
+ # Default if neither provided
config_args["warmup_steps"] = 5
logger.info(f"Using default warmup_steps: 5\n")
@@ -3072,8 +3064,8 @@ class UnslothTrainer:
# If max_steps is specified, use it instead of epochs
max_steps_val = training_args.get("max_steps", 0)
if max_steps_val and max_steps_val > 0:
- del config_args["num_train_epochs"] # Remove epochs
- config_args["max_steps"] = max_steps_val # Use steps instead
+ del config_args["num_train_epochs"]
+ config_args["max_steps"] = max_steps_val
logger.info(f"Training for {max_steps_val} steps\n")
else:
logger.info(f"Training for {config_args['num_train_epochs']} epochs\n")
@@ -3100,17 +3092,17 @@ class UnslothTrainer:
else:
logger.info("No eval dataset — evaluation disabled\n")
- # Add model-specific parameters
- # Use optim and lr_scheduler_type from training_args if provided, otherwise use defaults
+ # Model-specific params: use training_args optim/lr_scheduler_type if given, else defaults
optim_value = training_args.get("optim", "adamw_8bit")
lr_scheduler_type_value = training_args.get("lr_scheduler_type", "linear")
if (self.is_vlm or self.is_audio_vlm) and not raw_text_mode:
- # Vision / audio VLM config (both need skip_prepare_dataset + remove_unused_columns)
- # Raw-text runs on VLM-capable models are routed to the text path below.
+ # Vision / audio VLM config (both need skip_prepare_dataset +
+ # remove_unused_columns). Raw-text on VLM models goes to the
+ # text path below.
label = "audio VLM" if self.is_audio_vlm else "vision"
logger.info(f"Configuring {label} model training parameters\n")
- # Use provided values or defaults for vision models
+ # Provided values or vision defaults
optim_value = training_args.get("optim", "adamw_torch_fused")
lr_scheduler_type_value = training_args.get("lr_scheduler_type", "cosine")
config_args.update(
@@ -3143,7 +3135,7 @@ class UnslothTrainer:
}
)
- # Only add packing for text models (not DeepSeek OCR which is VLM)
+ # Packing for text models only (DeepSeek OCR is VLM)
if not is_deepseek_ocr:
packing_enabled = training_args.get("packing", False)
config_args["packing"] = packing_enabled
@@ -3164,9 +3156,10 @@ class UnslothTrainer:
logger.info("Training configuration prepared\n")
# ========== TRAINER INITIALIZATION ==========
if self.is_audio_vlm and not raw_text_mode:
- # Audio VLM (e.g. Gemma 3N + audio): raw Dataset from _format_audio_vlm_dataset
- # Notebook uses processing_class=processor.tokenizer (text tokenizer only)
- # Raw-text runs are routed to the text path below.
+ # Audio VLM (e.g. Gemma 3N + audio): raw Dataset from
+ # _format_audio_vlm_dataset. Notebook uses
+ # processing_class=processor.tokenizer (text tokenizer only).
+ # Raw-text runs go to the text path below.
train_dataset = dataset if isinstance(dataset, Dataset) else dataset["dataset"]
processing_class = (
self.tokenizer.tokenizer
@@ -3184,8 +3177,8 @@ class UnslothTrainer:
trainer_kwargs["eval_dataset"] = eval_dataset
self.trainer = SFTTrainer(**trainer_kwargs)
elif self.is_vlm and not raw_text_mode:
- # Image VLM: dataset is dict wrapper from format_and_template_dataset
- # Raw-text runs are routed to the text path below.
+ # Image VLM: dataset is a dict wrapper from
+ # format_and_template_dataset. Raw-text runs go to the text path below.
train_dataset = dataset["dataset"] if isinstance(dataset, dict) else dataset
trainer_kwargs = {
"model": self.model,
@@ -3198,11 +3191,11 @@ class UnslothTrainer:
trainer_kwargs["eval_dataset"] = eval_dataset
self.trainer = SFTTrainer(**trainer_kwargs)
else:
- # For text-only training, if the tokenizer is actually a Processor
- # (e.g., Gemma-3 returns a ProcessorMixin even for text), we must
- # unwrap to the raw tokenizer. Otherwise Unsloth's SFTTrainer detects
- # ProcessorMixin → sets _is_vlm=True → skips _prepare_dataset entirely,
- # and the 'text' column never gets tokenized to 'input_ids'.
+ # For text-only training, if the tokenizer is actually a
+ # Processor (e.g. Gemma-3 returns ProcessorMixin even for text),
+ # unwrap to the raw tokenizer. Otherwise Unsloth's SFTTrainer
+ # sets _is_vlm=True, skips _prepare_dataset, and the 'text'
+ # column never gets tokenized to 'input_ids'.
from transformers import ProcessorMixin
sft_tokenizer = self.tokenizer
@@ -3256,14 +3249,13 @@ class UnslothTrainer:
if eval_dataset is not None:
trainer_kwargs["eval_dataset"] = eval_dataset
self.trainer = SFTTrainer(**trainer_kwargs)
- # Restore the full processor as processing_class so checkpoint
- # saves include preprocessor_config.json (needed for GGUF export).
+ # Restore full processor as processing_class so checkpoints
+ # include preprocessor_config.json (needed for GGUF export).
if sft_tokenizer is not self.tokenizer:
self.trainer.processing_class = self.tokenizer
logger.info("Trainer initialized\n")
# ========== TRAIN ON RESPONSES ONLY ==========
- # Determine if we should train on responses only
# Raw-text datasets always train on all tokens.
instruction_part = None
response_part = None
@@ -3292,7 +3284,7 @@ class UnslothTrainer:
try:
logger.info("Configuring train on responses only...\n")
- # Get the template mapping for this model
+ # Template mapping for this model
model_name_lower = self.model_name.lower()
if model_name_lower in MODEL_TO_TEMPLATE_MAPPER:
@@ -3341,11 +3333,10 @@ class UnslothTrainer:
logger.info("Train on responses only configured successfully\n")
# ── Safety net: check if all samples were filtered out ──
- # Unsloth's train_on_responses_only masks non-response
- # tokens with -100. If max_seq_length is too short and the
- # response portion gets truncated away, EVERY sample ends
- # up with all labels == -100 and Unsloth removes them,
- # leaving 0 usable training samples.
+ # train_on_responses_only masks non-response tokens with
+ # -100. If max_seq_length is too short and the response is
+ # truncated away, EVERY sample ends up all -100 and Unsloth
+ # removes them, leaving 0 usable samples.
filtered_len = len(self.trainer.train_dataset)
original_len = len(dataset["dataset"])
dropped = original_len - filtered_len
@@ -3451,7 +3442,7 @@ class UnslothTrainer:
with open(config_path, "r") as f:
config = json.load(f)
- # Determine the training method
+ # Determine training method
if self.is_cpt:
method = "CPT"
elif self.load_in_4bit:
@@ -3481,7 +3472,7 @@ class UnslothTrainer:
# If trainer exists, try to stop it gracefully
if self.trainer:
try:
- # The callback will catch should_stop flag and stop the training loop
+ # The callback catches should_stop and stops the loop
logger.info("Training will stop at next step...\n")
except Exception as e:
logger.error(f"Error stopping trainer: {e}")
@@ -3506,14 +3497,13 @@ class UnslothTrainer:
def _ensure_deepseek_ocr_installed():
"""
- Auto-install DeepSeek OCR module if not available.
- Downloads from HuggingFace hub as a local module.
+ Auto-install the DeepSeek OCR module if missing (from HuggingFace hub as
+ a local module).
- Returns:
- bool: True if available (either already installed or just installed)
+ Returns True if available (already installed or just installed).
"""
try:
- # Try importing to see if already available
+ # Already available?
from deepseek_ocr.modeling_deepseekocr import format_messages
logger.info("DeepSeek OCR module already available")
return True
@@ -3528,20 +3518,20 @@ def _ensure_deepseek_ocr_installed():
import sys
import os
- # Get the script directory to install locally
+ # Install locally at project root
script_dir = os.path.dirname(os.path.abspath(__file__))
- parent_dir = os.path.dirname(script_dir) # Go up to project root
+ parent_dir = os.path.dirname(script_dir) # project root
# Download to project root as 'deepseek_ocr' folder
local_dir = os.path.join(parent_dir, "deepseek_ocr")
snapshot_download("unsloth/DeepSeek-OCR", local_dir = local_dir, local_dir_use_symlinks = False)
- # Add to sys.path if not already there
+ # Add to sys.path if needed
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
- # Try importing again
+ # Retry import
from deepseek_ocr.modeling_deepseekocr import format_messages
logger.info("DeepSeek OCR module installed successfully")
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index d27109aedb0..5c5626625bd 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -4,12 +4,12 @@
"""
Training backend — subprocess orchestrator.
-Each training job runs in a fresh subprocess (mp.get_context("spawn")),
-solving the transformers version-switching problem. The old in-process
-UnslothTrainer singleton is only used inside the subprocess (worker.py).
+Each training job runs in a fresh subprocess (mp.get_context("spawn")), solving
+the transformers version-switching problem. The old in-process UnslothTrainer
+singleton is only used inside the subprocess (worker.py).
-This file orchestrates the subprocess lifecycle, pumps events from the
-worker's mp.Queue, and exposes the same API surface to routes/training.py.
+This file orchestrates the subprocess lifecycle, pumps events from the worker's
+mp.Queue, and exposes the same API surface to routes/training.py.
Pattern follows core/data_recipe/jobs/manager.py.
"""
@@ -47,9 +47,9 @@ _HF_TMP_CHECKPOINT_RE = re.compile(r"^tmp-checkpoint-\d+$")
def _cleanup_cancelled_checkpoints(output_dir: str | os.PathLike) -> None:
"""Remove only HF Trainer ``tmp-checkpoint-<step>/`` partials after a cancel.
- Completed ``checkpoint-<int>/`` dirs and any non-numeric-suffix tmp dir
- are user-owned and survive. Symlinked output_dir / children are skipped
- so containment cannot be bypassed.
+ Completed ``checkpoint-<int>/`` dirs and any non-numeric-suffix tmp dir are
+ user-owned and survive. Symlinked output_dir / children are skipped so
+ containment can't be bypassed.
"""
out = Path(output_dir)
if not out.exists() or not out.is_dir() or out.is_symlink():
@@ -95,8 +95,8 @@ PLOT_HEIGHT = 3.5
@dataclass
class TrainingProgress:
- """Mirror of trainer.TrainingProgress — kept here so the parent process
- never needs to import the heavy ML modules."""
+ """Mirror of trainer.TrainingProgress — here so the parent process never
+ imports the heavy ML modules."""
epoch: float = 0
step: int = 0
@@ -118,7 +118,7 @@ class TrainingProgress:
class TrainingBackend:
"""
Training orchestration backend — subprocess-based.
- Launches a fresh subprocess per training job, communicates via mp.Queue.
+ Launches a fresh subprocess per job, communicates via mp.Queue.
"""
FLUSH_THRESHOLD: int = 10
@@ -136,7 +136,7 @@ class TrainingBackend:
self._should_stop = False
self._cancel_requested = False # True only for stop(save=False)
- # Training Metrics (consumed by routes for SSE and /metrics)
+ # Training metrics (consumed by routes for SSE and /metrics)
self.loss_history: list = []
self.lr_history: list = []
self.step_history: list = []
@@ -169,7 +169,7 @@ class TrainingBackend:
"""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 was started successfully.
+ Returns True if the subprocess started successfully.
"""
with self._lock:
if self._proc is not None and self._proc.is_alive():
@@ -244,8 +244,8 @@ class TrainingBackend:
"gpu_ids": kwargs.get("gpu_ids"),
}
- # Full finetuning always runs in 16-bit. LoRA/QLoRA and CPT preserve the
- # explicit request so 4-bit adapter/raw-text runs remain possible.
+ # Full finetuning always runs in 16-bit. LoRA/QLoRA and CPT keep the
+ # explicit request so 4-bit adapter/raw-text runs stay possible.
if config["training_type"] == "Full Finetuning":
config["load_in_4bit"] = False
@@ -296,8 +296,7 @@ class TrainingBackend:
logger.info("Training subprocess started (pid=%s)", proc.pid)
- # Reset state — safe because old pump thread is confirmed dead
- # and proc.start() succeeded
+ # Reset state — safe: old pump thread confirmed dead, proc.start() succeeded
self.current_job_id = job_id
self._should_stop = False
self._cancel_requested = False
@@ -325,7 +324,7 @@ class TrainingBackend:
self._stop_queue = stop_queue
self._proc = proc
- # Eagerly create DB run row so the run appears in history during model loading
+ # Eagerly create DB run row so it appears in history during model loading
self._ensure_db_run_created()
# Start event pump thread
@@ -368,7 +367,7 @@ class TrainingBackend:
proc.join(timeout = 2.0)
# Wait for pump thread to finish DB finalization before returning
- # (8s covers SQLite's default 5s lock timeout plus execution overhead)
+ # (8s covers SQLite's 5s lock timeout plus execution overhead)
if self._pump_thread is not None and self._pump_thread.is_alive():
self._pump_thread.join(timeout = 8.0)
@@ -399,7 +398,7 @@ class TrainingBackend:
if p.is_completed or p.error:
return False
- # Check status message for activity indicators
+ # Check status message for activity
status_lower = (p.status_message or "").lower()
if any(
k in status_lower
@@ -530,9 +529,8 @@ class TrainingBackend:
def _handle_event(self, event: dict) -> None:
"""Apply a subprocess event to local state.
- State updates happen inside self._lock; DB I/O happens after
- releasing it so status-polling API endpoints are never blocked
- by slow SQLite writes.
+ State updates happen inside self._lock; DB I/O happens after releasing
+ it so status-polling endpoints aren't blocked by slow SQLite writes.
"""
etype = event.get("type")
db_action: Optional[str] = None
@@ -542,7 +540,7 @@ class TrainingBackend:
if etype == "progress":
self._progress.step = event.get("step", self._progress.step)
self._progress.epoch = event.get("epoch", self._progress.epoch)
- # loss/lr are sanitized below; update progress after coercion
+ # loss/lr sanitized below; update progress after coercion
_raw_loss = event.get("loss")
_raw_lr = event.get("learning_rate")
try:
@@ -580,7 +578,7 @@ class TrainingBackend:
if status:
self._progress.status_message = status
- # Update metric histories — reuse sanitized values from above
+ # Update metric histories — reuse sanitized values above
step = event.get("step", 0)
loss = _safe_loss
lr = _safe_lr
@@ -616,7 +614,7 @@ class TrainingBackend:
else:
eval_loss = None
- # Buffer metric for DB flush (loss/lr already sanitized above)
+ # Buffer metric for DB flush (loss/lr already sanitized)
self._metric_buffer.append(
{
"step": step,
@@ -630,7 +628,7 @@ class TrainingBackend:
}
)
- # Decide which DB action to take after releasing the lock
+ # Pick the DB action to run after releasing the lock
if not self._db_run_created and self.current_job_id and self._db_config:
db_action = "create_run"
db_action_kwargs = {
@@ -784,14 +782,14 @@ class TrainingBackend:
"""Flush buffered metrics to the database and update live progress."""
if not self._metric_buffer or not self.current_job_id or not self._db_run_created:
return
- # Cap buffer to prevent unbounded memory growth
+ # Cap buffer to bound memory growth
if len(self._metric_buffer) > 500:
logger.warning(
"Metric buffer exceeded 500 entries (%d) — trimming oldest",
len(self._metric_buffer),
)
self._metric_buffer = self._metric_buffer[-500:]
- # Snapshot before insert so metrics arriving during the write are preserved
+ # Snapshot before insert so metrics arriving during the write survive
batch = list(self._metric_buffer)
try:
from storage.studio_db import insert_metrics_batch, update_run_progress
@@ -831,7 +829,7 @@ class TrainingBackend:
return events
# ------------------------------------------------------------------
- # Plot generation (unchanged from original)
+ # Plot generation
# ------------------------------------------------------------------
def _create_loss_plot(
@@ -954,9 +952,9 @@ class TrainingBackend:
def _transfer_to_inference_backend(self) -> bool:
"""Transfer model to inference backend.
- With subprocess-based training, the model lives in the subprocess
- and is freed when it exits. Inference must load from the saved
- checkpoint on disk. This is a no-op placeholder.
+ With subprocess-based training, the model lives in the subprocess and is
+ freed when it exits. Inference must load from the saved checkpoint on
+ disk. No-op placeholder.
"""
logger.info(
"_transfer_to_inference_backend: subprocess training — "
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index d5d81868151..e9d98909a67 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -4,11 +4,9 @@
"""
Training subprocess entry point.
-Each training job runs in a fresh subprocess (mp.get_context("spawn")).
-This gives us a clean Python interpreter with no stale module state —
-solving the transformers version-switching problem completely.
-
-Pattern follows core/data_recipe/jobs/worker.py.
+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
@@ -57,7 +55,7 @@ _FLASH_ATTN_SKIP_ENV = "UNSLOTH_STUDIO_SKIP_FLASHATTN_INSTALL"
_TILELANG_PACKAGE_VERSION = "0.1.8"
_APACHE_TVM_FFI_PACKAGE_VERSION = "0.1.9"
_TILELANG_SKIP_ENV = "UNSLOTH_STUDIO_SKIP_TILELANG_INSTALL"
-# Pin both so plain pip cannot silently upgrade torch under the worker (fla-core needs torch>=2.7).
+# Pin both so plain pip can't silently upgrade torch under the worker (fla-core needs torch>=2.7).
_FLA_PACKAGE_VERSION = "0.5.0"
_FLA_CORE_PACKAGE_VERSION = "0.5.0"
_FLA_SKIP_ENV = "UNSLOTH_STUDIO_SKIP_FLA_INSTALL"
@@ -72,14 +70,13 @@ _TVM_FFI_BROKEN_VERSIONS = ("0.1.10", "0.1.11")
_FAST_PATH_HOOKS_SKIP_ENV = "UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS"
# Module-level handle so the torch.library.Library registration survives past
-# run_training_process() and is not garbage collected mid-run.
+# run_training_process() and isn't GC'd mid-run.
_WINDOWS_ROCM_GROUPED_MM_LIB = None
-# Worker subprocesses inherit the parent env but not the parent's
-# os.add_dll_directory registrations. Replicate main.py's Windows ROCm DLL
-# setup at module load so the first `import torch` can find amdhip64.dll even
-# when HIP_PATH\bin is not on the system PATH. Handles retained at module
-# scope so they are not garbage collected.
+# Worker subprocesses inherit the parent env but not its os.add_dll_directory
+# registrations. Replicate main.py's Windows ROCm DLL setup at module load so
+# the first `import torch` finds amdhip64.dll even when HIP_PATH\bin is not on
+# PATH. Handles retained at module scope so they aren't GC'd.
_ROCM_DLL_HANDLES: list = []
if sys.platform == "win32":
@@ -147,21 +144,20 @@ def _model_wants_causal_conv1d(model_name: str) -> bool:
def _hipcc_gcc_install_dir() -> str | None:
"""Return the highest-numbered ``/usr/lib/gcc/x86_64-linux-gnu/<N>`` that has
- BOTH the gcc runtime dir AND the corresponding ``/usr/include/c++/<N>`` C++
- headers, or ``None`` if no match (or non-Linux / non-x86_64).
+ BOTH the gcc runtime dir AND ``/usr/include/c++/<N>`` C++ headers, or
+ ``None`` if no match (or non-Linux / non-x86_64).
- Ubuntu 24.04 ships ``/usr/lib/gcc/x86_64-linux-gnu/14/`` (gcc-14 runtime
- objects) but does NOT ship ``/usr/include/c++/14`` in its default apt set;
- libstdc++ headers come from ``libstdc++-13-dev``. ROCm clang-20 picks the
- highest-numbered runtime dir by default, finds no ``<cstdlib>``, and the
- HIP source build fails with::
+ Ubuntu 24.04 ships gcc-14 runtime objects but not ``/usr/include/c++/14`` in
+ its default apt set (libstdc++ headers come from ``libstdc++-13-dev``). ROCm
+ clang-20 picks the highest-numbered runtime dir, finds no ``<cstdlib>``, and
+ the HIP source build fails with::
/opt/rocm-X.Y/lib/llvm/lib/clang/20/include/__clang_hip_runtime_wrapper.h:112:10:
fatal error: 'cstdlib' file not found
Returning a path lets the caller pass ``--gcc-install-dir=<path>`` to clang
- via ``HIPCC_COMPILE_FLAGS_APPEND``. Mirrors the same loop ``bbf004c`` added
- to ``studio/setup.sh`` for the llama.cpp HIP build branch (PR #5301).
+ via ``HIPCC_COMPILE_FLAGS_APPEND``. Mirrors the loop ``bbf004c`` added to
+ ``studio/setup.sh`` for the llama.cpp HIP build (PR #5301).
"""
if not sys.platform.startswith("linux"):
return None
@@ -300,11 +296,10 @@ def _install_package_wheel_first(
pypi_spec,
]
- # Source compilation on ROCm can take 10-30 minutes; use a generous
- # timeout. Non-HIP installs preserve the pre-existing "no timeout"
- # behaviour so unrelated slow installs (e.g. causal-conv1d source
- # build on Linux aarch64 or unsupported torch/CUDA combinations)
- # are not aborted at 5 minutes by this PR.
+ # 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 installs (e.g. causal-conv1d source build on Linux aarch64, or
+ # unsupported torch/CUDA combos) aren't aborted at 5 minutes.
_run_kwargs: dict[str, Any] = {
"stdout": _sp.PIPE,
"stderr": _sp.STDOUT,
@@ -313,15 +308,14 @@ def _install_package_wheel_first(
if is_hip:
_run_kwargs["timeout"] = 1800
# On Ubuntu 24.04 + ROCm clang-20, the HIP source build (causal-conv1d,
- # mamba-ssm source fallback, flash-attn source fallback) defaults to
+ # mamba-ssm / flash-attn source fallbacks) defaults to
# /usr/lib/gcc/x86_64-linux-gnu/14/ which has the runtime dir but no
# /usr/include/c++/14 headers, and dies at:
# __clang_hip_runtime_wrapper.h:112:10:
# fatal error: 'cstdlib' file not found
- # Inject --gcc-install-dir for a gcc whose C++ headers actually exist.
- # Respect any pre-existing --gcc-install-dir in HIPCC_COMPILE_FLAGS_APPEND
- # (user knows best); otherwise append. Mirrors the same fix bbf004c
- # added to studio/setup.sh for the llama.cpp HIP build (PR #5301).
+ # Inject --gcc-install-dir for a gcc whose C++ headers exist. Respect any
+ # pre-existing --gcc-install-dir in HIPCC_COMPILE_FLAGS_APPEND; else
+ # append. Mirrors fix bbf004c in studio/setup.sh (llama.cpp HIP, 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()
@@ -369,9 +363,9 @@ def _install_package_wheel_first(
)
else:
if sys.platform == "win32":
- # No prebuilt wheel and no source build toolchain on Windows --
- # this is 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,
@@ -487,7 +481,7 @@ def _ensure_flash_linear_attention_unconditional(event_queue: Any) -> bool:
)
return False
- # Probe once; reuse result so the --force-reinstall decision and the short-circuit
+ # Probe once; reuse so the --force-reinstall decision and the short-circuit
# share the same call count (stable for tests).
already_importable = _flash_linear_attention_importable()
if already_importable and _flash_linear_attention_current(already_importable = True):
@@ -499,7 +493,7 @@ def _ensure_flash_linear_attention_unconditional(event_queue: Any) -> bool:
f"Installing flash-linear-attention=={_FLA_PACKAGE_VERSION} for faster training...",
)
- # `--no-deps` blocks the silent torch upgrade; we bring the non-torch runtime deps in by hand.
+ # `--no-deps` blocks the silent torch upgrade; bring non-torch runtime deps in by hand.
specs = [
*_FLA_RUNTIME_DEPS,
f"fla-core=={_FLA_CORE_PACKAGE_VERSION}",
@@ -616,7 +610,7 @@ _MODEL_NAME_SEP_CHARS = ("-", ".", "/", " ")
def _discover_fla_model_types() -> frozenset[str]:
- """Model_types in the installed transformers whose modeling file imports `from fla.*`."""
+ """Installed-transformers model_types whose modeling file imports `from fla.*`."""
global _TRANSFORMERS_FLA_MODEL_TYPES_CACHE
if _TRANSFORMERS_FLA_MODEL_TYPES_CACHE is not None:
return _TRANSFORMERS_FLA_MODEL_TYPES_CACHE
@@ -690,17 +684,17 @@ def _torch_has_hip() -> bool:
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)`` where:
- - ``gcn_arch`` is the canonical arch string (e.g. ``"gfx1151"``) when a
- known attribute is present, or ``""`` when all arch attrs are absent.
- - ``is_unified`` is ``True`` for AMD APUs with a shared GPU/system-RAM pool
+ 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) — these need a lower
- ``set_per_process_memory_fraction`` cap to leave headroom for the OS.
+ ``set_per_process_memory_fraction`` cap to leave OS headroom.
Classification priority:
1. ``gcnArchName`` / variant spellings (stable, naming-independent).
- 2. Device-name substring match as a last-resort fallback when all arch
- attrs are absent (AMD SDK / Radeon wheels may not populate them):
+ 2. 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: ``Radeon 8060S`` (Ryzen AI MAX+ 395),
``Radeon 8050S`` (cut-down SKU)
@@ -726,7 +720,7 @@ def _rocm_classify_unified_memory(props: Any) -> tuple[str, bool]:
def _tilelang_platform_supported() -> bool:
"""True iff a tilelang 0.1.8 wheel will load: Linux x86_64/aarch64, non-HIP torch.
- HIP excluded because tilelang 0.1.8 has no HIP GEMM instruction and crashes mid-backward.
+ HIP excluded: tilelang 0.1.8 has no HIP GEMM and crashes mid-backward.
"""
import platform as _platform
@@ -770,9 +764,10 @@ def _run_pip(cmd: list[str], event_queue: Any, label: str) -> bool:
def _ensure_tilelang_backend_unconditional(event_queue: Any) -> bool:
"""Install pinned tilelang + apache-tvm-ffi; two-step repair if a broken tvm-ffi is present.
- Returns True iff both import post-call. Step 1 surgically downgrades a broken tvm-ffi
- with --force-reinstall --no-deps so torch / CUDA stay untouched; step 2 is a regular
- install for missing transitive deps. Bypass via UNSLOTH_STUDIO_SKIP_TILELANG_INSTALL=1.
+ Returns True iff both import post-call. Step 1 downgrades a broken tvm-ffi
+ with --force-reinstall --no-deps so torch / CUDA stay untouched; step 2 is a
+ regular install for missing transitive deps. Bypass via
+ UNSLOTH_STUDIO_SKIP_TILELANG_INSTALL=1.
"""
if os.getenv(_TILELANG_SKIP_ENV) == "1":
return False
@@ -800,7 +795,7 @@ def _ensure_tilelang_backend_unconditional(event_queue: Any) -> bool:
logger.info("tilelang + apache-tvm-ffi already installed")
return True
- # Step 1: --no-deps keeps --force-reinstall from touching torch/CUDA via the dep graph.
+ # Step 1: --no-deps keeps --force-reinstall off torch/CUDA via the dep graph.
if needs_repair:
logger.info(
"Forcing apache-tvm-ffi downgrade: %s is on the broken list",
@@ -822,7 +817,7 @@ def _ensure_tilelang_backend_unconditional(event_queue: Any) -> bool:
if not _run_pip(repair_cmd, event_queue, "TileLang backend repair"):
return False
- # Step 2: regular install pulls in transitive deps (z3-solver, ml-dtypes) without touching torch.
+ # Step 2: regular install pulls transitive deps (z3-solver, ml-dtypes) without touching torch.
_send_status(
event_queue,
f"Installing TileLang=={_TILELANG_PACKAGE_VERSION} for faster training...",
@@ -855,9 +850,9 @@ def _ensure_tilelang_backend(event_queue: Any, model_name: str) -> None:
# ── Fast-path hooks ──
-# Wrap transformers' is_{flash_linear_attention,causal_conv1d}_available so the first call
-# (at modeling import time) drives the install. Any model that queries the gate gets the
-# install; models that never query it (Llama, Gemma, dense Qwen) pay nothing.
+# Wrap transformers' is_{flash_linear_attention,causal_conv1d}_available so the
+# first call (at modeling import) drives the install. Models that query the gate
+# get the install; those that never query it (Llama, Gemma, dense Qwen) pay nothing.
# UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 falls back to the legacy substring path.
@@ -894,8 +889,8 @@ def _install_fast_path_hooks(event_queue: Any, model_name: str) -> None:
logger.info("Fast-path hooks disabled via env; using substring fallback")
return
- # On HIP torch, even already-installed tilelang crashes FLA's TileLang dispatch.
- # User can override with FLA_TILELANG=1.
+ # On HIP torch, even installed tilelang crashes FLA's TileLang dispatch.
+ # Override with FLA_TILELANG=1.
if _torch_has_hip() and os.environ.get("FLA_TILELANG") is None:
os.environ["FLA_TILELANG"] = "0"
logger.info(
@@ -937,8 +932,8 @@ def _install_fast_path_hooks(event_queue: Any, model_name: str) -> None:
logger.warning("%s install raised: %s; falling back to torch", gate_name, exc)
ok = False
logger.info("%s hook done; available=%s", gate_name, ok)
- # post_available_fn handles "gate already True but ancillary kernel broken" (e.g. tilelang
- # missing while FLA imports fine); skip when install_fn already chained the follow-up.
+ # post_available_fn handles "gate already True but ancillary kernel broken"
+ # (e.g. tilelang missing while FLA imports); skip when install_fn already chained it.
if ok and not ran_install and post_available_fn is not None:
try:
post_available_fn(event_queue)
@@ -966,7 +961,7 @@ def _install_fast_path_hooks(event_queue: Any, model_name: str) -> None:
return True
def _fla_post_available(eq: Any) -> None:
- # FLA already imports; repair tilelang if missing or on the broken tvm-ffi list.
+ # FLA imports; repair tilelang if missing or on the broken tvm-ffi list.
if not _model_wants_tilelang(model_name):
return
if _installed_tvm_ffi_version() not in _TVM_FFI_BROKEN_VERSIONS and _tilelang_importable():
@@ -1057,8 +1052,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 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
@@ -1079,9 +1074,9 @@ def _resize_mlx_vlm_image(image, resize):
if new_size != image.size:
resampling = getattr(Image, "Resampling", Image).LANCZOS
image = image.resize(new_size, resampling)
- # When a resize is requested, 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 (Default) above 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 above keeps the original PIL.
return np.array(image, copy = True)
@@ -1092,12 +1087,12 @@ def _resize_mlx_vlm_images(value, resize):
def _adapt_for_mlx_vlm(items, resize = None):
- """Adapt GPU-path VLM dataset output for mlx-vlm consumption.
+ """Adapt GPU-path VLM dataset output for mlx-vlm.
- The GPU path embeds PIL images inside messages content as
- {"type": "image", "image": PIL_Image}. mlx-vlm's prepare_inputs
- needs images at top-level to produce pixel_values — regardless of
- model type. Extract them and leave bare {"type": "image"} placeholders.
+ 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:
@@ -1218,8 +1213,8 @@ def _mlx_local_dataset_loader_for_files(files: list[str]) -> str:
def _run_mlx_training(event_queue, stop_queue, config):
"""Self-contained MLX training path for Apple Silicon.
- Uses MLXTrainer from unsloth_zoo directly -- no torch/SFTTrainer needed.
- Mirrors the event_queue protocol so the parent process pump works unchanged.
+ 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
@@ -1276,8 +1271,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
lr_scheduler_type = _normalize_mlx_studio_scheduler(config.get("lr_scheduler_type", "linear"))
# ── 1. Load model ──
- # Force text-only if the dataset is not an image dataset, even if the model
- # has vision capabilities (e.g. Qwen3.5-VL trained on plain alpaca text).
+ # Force text-only for non-image datasets even on vision-capable models
+ # (e.g. Qwen3.5-VL trained on plain alpaca text).
_send("status", status_message = f"Loading {model_name}...")
is_dataset_image = bool(config.get("is_dataset_image", False))
training_type = config.get("training_type", "LoRA/QLoRA")
@@ -1314,8 +1309,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
)
# ── 2. Apply LoRA / full FT ──
- # Pass gradient_checkpointing as string ("mlx"/"unsloth"/"none"/etc.)
- # get_peft_model and MLXTrainer both accept strings and handle them.
+ # gradient_checkpointing stays a string ("mlx"/"unsloth"/"none"/etc.);
+ # get_peft_model and MLXTrainer both accept and handle strings.
gc_setting = config.get("gradient_checkpointing", "mlx")
if isinstance(gc_setting, str):
use_grad_checkpoint = (
@@ -1418,8 +1413,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
eval_dataset = _load_local(config["local_eval_datasets"])
# ── 3b. Format dataset (VLM or text) ──
- # Reuse the GPU path's format pipeline for both VLM (auto-detects OCR/caption/
- # llava/sharegpt+images) and text (alpaca/sharegpt/chatml → "text" column).
+ # Reuse the GPU format pipeline for VLM (auto-detects OCR/caption/llava/
+ # sharegpt+images) and text (alpaca/sharegpt/chatml → "text" column).
format_type = config.get("format_type", "")
try:
from utils.datasets import format_and_template_dataset
@@ -1511,7 +1506,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
output_dir = config.get("output_dir", "")
if not output_dir:
output_dir = f"{model_name.replace('/', '_')}_{int(time.time())}"
- # Resolve to ~/.unsloth/studio/outputs/ so the export page can find it
+ # Resolve to ~/.unsloth/studio/outputs/ so the export page finds it
from utils.paths import resolve_output_dir, ensure_dir
output_dir = str(resolve_output_dir(output_dir))
@@ -1525,9 +1520,9 @@ def _run_mlx_training(event_queue, stop_queue, config):
else:
eval_steps_val = int(eval_steps_val)
- # MLX: per-element clip to [-1, 1]; norm clip disabled (it needs a
- # global reduction that breaks MLX's eager pipeline). 1.0 (not 5.0):
- # |g_i| > 5 rarely fires, so the historical 5.0 was effectively no-op.
+ # MLX: per-element clip to [-1, 1]; norm clip disabled (its global reduction
+ # breaks MLX's eager pipeline). 1.0 not 5.0: |g_i| > 5 rarely fires, so the
+ # historical 5.0 was effectively a no-op.
max_grad_norm = 0.0
max_grad_value = 1.0 # TODO: expose MLX grad-clip in Studio UI for power users
@@ -1561,7 +1556,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
),
)
- # Tell the parent that eval is configured so the frontend shows the eval chart
+ # Tell the parent eval is configured so the frontend shows the eval chart
if eval_dataset is not None and eval_steps_val > 0:
_send("eval_configured")
@@ -1716,7 +1711,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
except _queue.Empty:
continue
except (EOFError, OSError):
- # why safe: pipe permanently broken, no further messages can arrive
+ # Safe: pipe permanently broken, no more messages can arrive.
return
stop_thread = threading.Thread(target = _poll_stop, daemon = True)
@@ -1753,15 +1748,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
"""Subprocess entrypoint. Fresh Python — no stale module state.
Args:
- event_queue: mp.Queue for sending progress/status/error events to parent.
- stop_queue: mp.Queue for receiving stop commands from parent.
- config: Training configuration dict with all parameters.
+ 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.
"""
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports
- # Offline auto-detect: skip ~25s of HF retries per call when DNS is
- # dead. Scoped to this subprocess (orchestrator spawns a fresh one).
+ # Offline auto-detect: skip ~25s of HF retries per call when DNS is dead.
+ # Scoped to this subprocess (orchestrator spawns a fresh one).
if "HF_HUB_OFFLINE" not in os.environ:
import socket as _socket
import threading as _threading
@@ -1807,7 +1802,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
# ── 0. MLX FAST-PATH (must run before any torch/transformers imports) ──
# Apple Silicon uses MLXTrainer directly -- skip transformers version
- # activation, causal-conv1d install, and torch imports entirely.
+ # activation, causal-conv1d install, and torch imports.
backend_path = str(Path(__file__).resolve().parent.parent.parent)
if backend_path not in sys.path:
sys.path.insert(0, backend_path)
@@ -1827,7 +1822,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
# Activate correct transformers version (Gemma-4 needs 5.5.0, etc.)
- # Must happen before any transformers/mlx-lm imports in _run_mlx_training.
+ # before any transformers/mlx-lm imports in _run_mlx_training.
try:
_activate_transformers_version(model_name)
except Exception:
@@ -1860,10 +1855,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
return
# ── 1a. Auto-enable trust_remote_code for NemotronH/Nano models ──
- # NemotronH has config parsing bugs in transformers that require
- # trust_remote_code=True as a workaround. Other transformers 5.x models
- # (Qwen3.5, Gemma 4, etc.) are native and do NOT need it — enabling it
- # bypasses the compiler (disabling fused CE).
+ # NemotronH has transformers config-parsing bugs needing trust_remote_code=True
+ # as a workaround. Other transformers 5.x models (Qwen3.5, Gemma 4, etc.) are
+ # native and do NOT need it — enabling it bypasses the compiler (disabling fused CE).
# NOTE: Must NOT match Llama-Nemotron (standard Llama architecture).
_NEMOTRON_TRUST_SUBSTRINGS = ("nemotron_h", "nemotron-h", "nemotron-3-nano")
_lowered = model_name.lower()
@@ -1880,19 +1874,17 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
# ── 1b. Install fast-path kernel libraries for the chosen model.
#
- # 1) causal-conv1d ALWAYS runs eagerly via the substring path.
- # Some SSM modeling files (nemotron_h, falcon_h1, granitemoehybrid)
- # use `lazy_load_kernel("causal-conv1d")` directly and never call
- # transformers' `is_causal_conv1d_available()`, so the runtime
- # hook on that gate would not fire for them.
- # 2) FLA + tilelang: primary gate is the runtime hook on transformers'
- # `is_flash_linear_attention_available`. Models whose architecture
- # queries that gate auto-trigger the install; others never pay.
- # `_install_fast_path_hooks` also wraps `is_causal_conv1d_available`
- # as a defence in depth for newer modeling files that do use it.
+ # 1) causal-conv1d ALWAYS runs eagerly via the substring path. Some SSM
+ # modeling files (nemotron_h, falcon_h1, granitemoehybrid) call
+ # `lazy_load_kernel("causal-conv1d")` directly and never call
+ # `is_causal_conv1d_available()`, so the runtime hook wouldn't fire.
+ # 2) FLA + tilelang: primary gate is the runtime hook on
+ # `is_flash_linear_attention_available`. Architectures that query it
+ # auto-trigger the install; others never pay. `_install_fast_path_hooks`
+ # also wraps `is_causal_conv1d_available` as defence in depth.
# 3) mamba-ssm + flash-attn keep their existing substring / size gates.
- # 4) `UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1` falls back to the
- # substring path for FLA / tilelang.
+ # 4) `UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1` falls back to the substring
+ # path for FLA / tilelang.
try:
_ensure_causal_conv1d_fast_path(event_queue, model_name)
if os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1":
@@ -1923,12 +1915,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
return
# ── 1c. Set fork start method so dataset.map() can multiprocess ──
- # The parent launched us via spawn (clean process), but the compiled
- # SFTTrainer checks get_start_method() and disables num_proc if not "fork".
- # Linux only: fork is the default start method and is safe here (no CUDA
- # context exists yet). macOS defaults to spawn since Python 3.8 because
- # fork is unsafe with macOS frameworks (Metal/MPS, CoreFoundation) --
- # do NOT override on macOS. Windows has no fork at all.
+ # Parent launched us via spawn, but the compiled SFTTrainer checks
+ # get_start_method() and disables num_proc if not "fork". Linux only: fork
+ # is the default and safe here (no CUDA context yet). macOS defaults to spawn
+ # since Python 3.8 (fork unsafe with Metal/MPS, CoreFoundation) -- do NOT
+ # override there. Windows has no fork.
if sys.platform == "linux":
import multiprocessing as _mp
try:
@@ -1951,15 +1942,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
# ── 1d. Stub torchao on Windows ROCm ──
# Shared with the export worker; see core/_torchao_stub.py for the full
# rationale (torchao -> torch.distributed._functional_collectives crashes on
- # Windows ROCm because the RCCL backend is absent). No-op off Windows ROCm.
- # Must run before any import of transformers / unsloth_zoo.
+ # Windows ROCm: no RCCL backend). No-op off Windows ROCm. Must run before any
+ # import of 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 training never initialises the process group, so these helpers
- # are never called — but transformers/trl import them unconditionally.
+ # Single-GPU training never inits the process group, so these helpers are
+ # never called — but transformers/trl import them unconditionally.
_td_stubs = {
"is_initialized": lambda: False,
"is_available": lambda: False,
@@ -1989,16 +1980,14 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
# torch._grouped_mm has a null HIP kernel on gfx1200 (ROCm ≤ 7.12 Windows),
# causing 0xC0000005 (access violation) during training.
#
- # Root cause: the JitDecomp autograd decomposition system (NOT torch.compile)
- # dispatches _grouped_mm → _fused_adagrad_ → _grouped_mm HIP → null crash.
- # TORCHDYNAMO_DISABLE=1 stops the compiler frontend but does NOT stop
- # JitDecomp, so we must also override the CUDA dispatch key for _grouped_mm
- # with a safe Python fallback.
+ # Root cause: JitDecomp autograd decomposition (NOT torch.compile) dispatches
+ # _grouped_mm → _fused_adagrad_ → _grouped_mm HIP → null crash.
+ # TORCHDYNAMO_DISABLE=1 stops the compiler frontend but not JitDecomp, so we
+ # also override the CUDA dispatch key for _grouped_mm with a Python fallback.
#
- # Fixed in AMD's wheel: torch==2.11.0+rocm7.13.0 — the 3-D batch and grouped
- # (with offs) variants of _grouped_mm now have working HIP kernels on gfx1200.
- # We gate the dispatch override on HIP < 7.13 so users on the fixed wheel get
- # the real GPU kernel rather than our Python fallback.
+ # Fixed in torch==2.11.0+rocm7.13.0: the 3-D batch and grouped (with offs)
+ # variants now have working HIP kernels on gfx1200. We gate the override on
+ # HIP < 7.13 so the fixed wheel uses the real GPU kernel.
#
# Verified: null on torch==2.10.0+rocm7.12.0; fixed on torch==2.11.0+rocm7.13.0.
#
@@ -2006,17 +1995,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
# Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor
# offs: optional group-split offsets (MoE-style variable-size batches)
#
- # torch is already in sys.modules from section 1e's `import torch.distributed`.
- # Module-level _WINDOWS_ROCM_GROUPED_MM_LIB keeps the registration alive past
- # function return / mid-run GC.
+ # torch is already in sys.modules from section 1e. Module-level
+ # _WINDOWS_ROCM_GROUPED_MM_LIB keeps the registration alive past return / GC.
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 torch.__version__.
- # AMD SDK / Radeon Windows wheels do not always populate
- # torch.version.hip; without the broad check the BNB version pin,
- # dynamo-disable, and _grouped_mm fallback below silently skip
- # (matches the torchao stub gate above and main.py).
+ # Broad check: torch.version.hip OR "rocm" in torch.__version__. AMD SDK /
+ # Radeon Windows wheels don't always populate torch.version.hip; without
+ # the broad check the BNB version pin, dynamo-disable, and _grouped_mm
+ # fallback below silently skip (matches the torchao stub gate and main.py).
_build_version_for_rocm = (
getattr(_torch_for_rocm, "__version__", "").lower()
if _torch_for_rocm is not None
@@ -2030,20 +2017,19 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
)
if _is_win_rocm_torch:
- # Disable dynamo (belt-and-suspenders; JitDecomp patch below is the
- # real fix, but keeping dynamo off avoids any other compile paths).
+ # Disable dynamo (belt-and-suspenders; the JitDecomp patch below is
+ # the real fix, but dynamo off avoids any other compile paths).
if "TORCHDYNAMO_DISABLE" not in os.environ:
os.environ["TORCHDYNAMO_DISABLE"] = "1"
logger.info("Windows ROCm: torch.compile (dynamo) disabled")
- # BNB auto-detects the HIP version from torch.version.hip and uses
- # it to choose which DLL to load (e.g. "7.13" → rocm713.dll).
- # AMD's Windows BNB prerelease wheel ships only one rocm DLL, and its
- # version suffix does not always match the torch HIP version (e.g.
- # torch==2.11.0+rocm7.13.0 ships HIP 7.13, but the BNB wheel still
- # ships rocm72.dll). We detect the actual DLL name from the installed
- # package and override BNB's auto-detection. "72" is a safe fallback
- # if detection fails. Callers may override by pre-setting the var.
+ # BNB auto-detects the HIP version from torch.version.hip to pick a
+ # DLL (e.g. "7.13" → rocm713.dll). AMD's Windows BNB prerelease wheel
+ # ships only one rocm DLL whose version suffix may not match the torch
+ # HIP version (e.g. torch==2.11.0+rocm7.13.0 ships HIP 7.13, but the
+ # BNB wheel still ships rocm72.dll). Detect the actual DLL name from
+ # the installed package and override auto-detection. "72" is a safe
+ # fallback if detection fails. Callers may override by pre-setting the var.
if "BNB_ROCM_VERSION" not in os.environ:
_bnb_rocm_ver = None
try:
@@ -2064,10 +2050,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
if _m:
_all_vers.append(_m.group(1))
- # Pick the highest numeric suffix so that e.g. "713"
- # wins over "72" when both variants are present.
- # Filesystem glob order is not guaranteed, so always
- # sort rather than stopping at the first match.
+ # Pick the highest numeric suffix so "713" wins over
+ # "72" when both are present. Glob order isn't guaranteed,
+ # so always sort rather than take the first match.
if _all_vers:
_bnb_rocm_ver = max(_all_vers, key = lambda v: int(v))
except Exception:
@@ -2081,17 +2066,15 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
_bnb_rocm_ver,
)
- # Parse HIP version for the kernel-fix gate below.
- # torch.version.hip can be "7.13.99004", "7.2.0", etc.
- # AMD SDK / Radeon wheels may leave torch.version.hip unset and
- # encode the ROCm version in torch.__version__ instead
- # (e.g. "2.11.0+rocm7.13.0" or "2.9.0+rocmsdk20251116"); fall back
- # to that string when version.hip is missing.
+ # Parse HIP version for the kernel-fix gate below. torch.version.hip
+ # can be "7.13.99004", "7.2.0", etc. AMD SDK / Radeon wheels may leave
+ # it unset and encode the ROCm version in torch.__version__ instead
+ # (e.g. "2.11.0+rocm7.13.0" or "2.9.0+rocmsdk20251116"); fall back to
+ # that string when version.hip is missing.
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:
- # Try the standard "+rocmX.Y.Z" embedded version first
- # (e.g. "2.11.0+rocm7.13.0").
+ # Try the standard "+rocmX.Y.Z" embedded version first.
_ver_match = re.search(r"rocm(\d+)\.(\d+)", _build_version_for_rocm)
if _ver_match:
return (
@@ -2100,12 +2083,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
) >= (major, minor)
# AMD SDK / Radeon Windows wheels encode the build as
# "+rocmsdk<date>" (e.g. "2.9.0+rocmsdk20251116") with no
- # explicit rocmX.Y component. The rocmsdk format was
- # introduced after the gfx120X null-kernel fix landed in
- # ROCm 7.13, so any wheel with this suffix is new enough to
- # have working HIP kernels. Treat as >= 7.13 rather than
- # falling back to False and installing the Python workaround
- # on a wheel that doesn't need it.
+ # explicit rocmX.Y. The rocmsdk format postdates the gfx120X
+ # null-kernel fix (ROCm 7.13), so any such wheel has working
+ # HIP kernels. Treat as >= 7.13 rather than returning False
+ # and installing the Python workaround on a wheel that
+ # doesn't need it.
if "rocmsdk" in _build_version_for_rocm:
logger.debug(
"Windows ROCm: AMD SDK wheel detected (%r); "
@@ -2139,10 +2121,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return False
- # _grouped_mm HIP kernel was null on gfx1200 in ROCm ≤ 7.12,
- # causing 0xC0000005. AMD fixed it in ROCm 7.13 (torch 2.11+).
- # Only install the Python fallback on the affected versions so users
- # on 7.13+ get the real GPU kernel for MoE workloads.
+ # _grouped_mm HIP kernel was null on gfx1200 in ROCm ≤ 7.12 (causing
+ # 0xC0000005); fixed in ROCm 7.13 (torch 2.11+). Install the Python
+ # fallback only on affected versions so 7.13+ gets the real GPU kernel.
if not _hip_ver_at_least(7, 13):
try:
import warnings as _warnings
@@ -2159,24 +2140,22 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
"""Python mm/bmm fallback for _grouped_mm on gfx1200 (null HIP kernel, ROCm ≤ 7.12)."""
_t = _torch_for_rocm
if offs is None:
- # No offsets: behave like the real op, which
- # accepts either (M, K) x (K, N) -> mm, or 3-D
- # batched inputs -> bmm. Picking torch.mm
- # unconditionally previously raised "self must be
- # a matrix" on 3-D MoE workloads.
+ # No offsets: match the real op — (M, K) x (K, N) ->
+ # mm, or 3-D batched -> bmm. An unconditional torch.mm
+ # previously raised "self must be a matrix" on 3-D MoE.
if self.dim() == 3 and mat2.dim() == 3:
result = _t.bmm(self.contiguous(), mat2.contiguous())
elif self.dim() == 3 and mat2.dim() == 2:
# Broadcast 2-D mat2 across the batch dim.
result = _t.matmul(self.contiguous(), mat2.contiguous())
elif self.dim() == 2 and mat2.dim() == 3:
- # Broadcast 2-D self across batch via matmul semantics.
+ # Broadcast 2-D self across batch via matmul.
result = _t.matmul(self.contiguous(), mat2.contiguous())
else:
result = _t.mm(self.contiguous(), mat2.contiguous())
else:
- # Grouped case: offs[i] is the exclusive end-row of
- # group i in `self`; mat2 may be 3-D or 2-D.
+ # Grouped: offs[i] is the exclusive end-row of group
+ # i in `self`; mat2 may be 3-D or 2-D.
offs_list = offs.tolist()
pieces = []
prev = 0
@@ -2189,7 +2168,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
b_part = mat2.contiguous()
pieces.append(_t.mm(a_part, b_part))
prev = end
- # Include any trailing rows not covered by offs
+ # Include trailing rows not covered by offs.
if prev < self.shape[0]:
a_tail = self[prev:].contiguous()
b_tail = (
@@ -2237,26 +2216,23 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
# ── 1g. ROCm OOM guard ──
- # On RDNA 4 (gfx1200/gfx1201) and other ROCm GPUs, exhausting VRAM can
- # cause a HIP driver hang that freezes the entire system rather than
- # raising a Python exception. set_per_process_memory_fraction caps the
- # HIP allocator so PyTorch raises OutOfMemoryError before hitting the
- # hardware limit, giving the UI a clean error instead of a system freeze.
- # Only applied on ROCm -- NVIDIA CUDA has a graceful OOM path and does
- # not need this cap.
+ # On RDNA 4 (gfx1200/gfx1201) and other ROCm GPUs, exhausting VRAM can hang
+ # the HIP driver and freeze the whole system instead of raising. So
+ # set_per_process_memory_fraction caps the HIP allocator and PyTorch raises
+ # OutOfMemoryError before the hardware limit, giving the UI a clean error.
+ # ROCm only -- NVIDIA CUDA has a graceful OOM path.
# Unified-memory APUs (gfx1150 Strix Point / gfx1151 Strix Halo) share GPU
- # and system RAM in one pool: 0.90 of 128 GB starves the OS. Use 0.80 there.
- # Primary classifier: gcnArchName from device properties — stable within a
- # product family and naming-independent. AMD SDK / Radeon wheels may omit
- # gcnArchName or expose it under a variant spelling, so we try several attr
- # names then fall back to known device-name markers as a last resort.
+ # and system RAM in one pool: 0.90 of 128 GB starves the OS, so use 0.80.
+ # Primary classifier: gcnArchName (stable within a product family,
+ # naming-independent). AMD SDK / Radeon wheels may omit it or use a variant
+ # spelling, so try several attrs then fall back to device-name markers.
# Non-fatal: silently skipped if torch is not importable.
if _hw.IS_ROCM:
try:
import torch as _torch_mem
if _torch_mem.cuda.is_available():
- # Classify unified vs discrete via _rocm_classify_unified_memory.
- # See that function's docstring for classification priority.
+ # Classify unified vs discrete via _rocm_classify_unified_memory
+ # (see its docstring for classification priority).
_props = _torch_mem.cuda.get_device_properties(0)
_dev_name = _props.name
_gcn_arch, _is_unified = _rocm_classify_unified_memory(_props)
@@ -2310,9 +2286,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
return
# ── 2b. EMBEDDING MODEL FAST-PATH ──
- # Embedding models use a completely different pipeline (FastSentenceTransformer
- # + SentenceTransformerTrainer + MultipleNegativesRankingLoss) so we branch
- # early and handle the entire flow in a self-contained function.
+ # Embedding models use a different pipeline (FastSentenceTransformer +
+ # SentenceTransformerTrainer + MultipleNegativesRankingLoss), so branch early
+ # and handle the whole flow in a self-contained function.
if config.get("is_embedding", False):
try:
_run_embedding_training(event_queue, stop_queue, config)
@@ -2380,9 +2356,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
stop_thread.start()
# ── 4. Execute the training pipeline ──
- # Order: detect → dataset → model → prepare → train
- # Dataset processing (including LLM-assisted detection) runs BEFORE model
- # loading so both never occupy VRAM at the same time.
+ # Order: detect → dataset → model → prepare → train. Dataset processing
+ # (incl. LLM-assisted detection) runs BEFORE model loading so both never
+ # occupy VRAM at once.
try:
hf_token = config.get("hf_token", "")
hf_token = hf_token if hf_token and hf_token.strip() else None
@@ -2451,8 +2427,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
if eval_steps is not None and float(eval_steps) <= 0:
eval_dataset = None
- # Tell the parent process that eval is configured so the frontend
- # shows "Waiting for first evaluation step..." instead of "not configured"
+ # Tell the parent eval is configured so the frontend shows
+ # "Waiting for first evaluation step..." instead of "not configured".
if eval_dataset is not None:
event_queue.put(
{
@@ -2475,7 +2451,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # ── Start tqdm monitor early so it captures download + tokenization bars ──
+ # ── Start tqdm monitor early to capture download + tokenization bars ──
import threading as _th
_tqdm_stop = _th.Event()
@@ -2533,9 +2509,9 @@ 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...")
- # embed_tokens (if the user included it) goes to modules_to_save —
- # trained full-precision at embedding_learning_rate. lm_head stays as
- # a LoRA target for merge compatibility (see unsloth PR #4106).
+ # embed_tokens (if included) goes to modules_to_save — trained
+ # full-precision at embedding_learning_rate. lm_head stays a LoRA
+ # target for merge compatibility (see unsloth PR #4106).
_user_modules = config.get("target_modules") or []
wants_embed = "embed_tokens" in _user_modules
cpt_trains_embeddings = wants_embed
@@ -2610,13 +2586,13 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
)
return
- # embedding_learning_rate is validated by the Pydantic model (Optional[float],
- # gt=0, lt=1.0); if present it is already a finite float in range.
+ # embedding_learning_rate is validated by Pydantic (Optional[float],
+ # gt=0, lt=1.0); if present it's already a finite float in range.
embedding_lr_value = config.get("embedding_learning_rate")
if is_cpt:
if cpt_trains_embeddings:
if embedding_lr_value is None:
- # Default embedding_learning_rate = lr/10 per Unsloth's CPT notebook.
+ # Default embedding_learning_rate = lr/10 (Unsloth CPT notebook).
embedding_lr_value = lr_value / 10.0
logger.info(
f"CPT: using default embedding_learning_rate={embedding_lr_value:.1e} "
@@ -2644,7 +2620,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
tensorboard_dir = str(resolve_tensorboard_dir(tensorboard_dir))
ensure_dir(Path(tensorboard_dir))
- # Start training (directly — no inner thread, we ARE the subprocess)
+ # Start training directly — no inner thread, we ARE the subprocess.
dataset_display = config.get("hf_dataset", "") or config.get("uploaded_file", "") or ""
_send_status(
event_queue,
@@ -2761,10 +2737,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
"""Self-contained embedding model training pipeline.
Uses FastSentenceTransformer + SentenceTransformerTrainer +
- MultipleNegativesRankingLoss — completely separate from the
- LLM/VLM/audio paths in UnslothTrainer.
-
- Mirrors the pattern from the reference embedding notebooks:
+ 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
"""
@@ -2860,7 +2834,7 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
_send_status(event_queue, "Configuring LoRA adapters (FEATURE_EXTRACTION)...")
try:
gradient_checkpointing = config.get("gradient_checkpointing", False)
- # Normalize: "none" or empty → False
+ # Normalize "none"/empty → False.
if gradient_checkpointing in ("none", "", None):
gradient_checkpointing = False
@@ -2913,8 +2887,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
token = hf_token,
)
elif local_datasets:
- # Load from local file(s) — mirrors the non-embedding pipeline's
- # directory handling so recipe outputs (parquet-files/) work.
+ # Load local file(s) — mirrors the non-embedding pipeline's directory
+ # handling so recipe outputs (parquet-files/) work.
all_files: list[str] = []
for dataset_file in local_datasets:
file_path = (
@@ -3050,7 +3024,7 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
else:
training_args_kwargs["num_train_epochs"] = num_epochs if num_epochs > 0 else 2
- # warmup: prefer warmup_ratio (standard for embedding scripts), fallback to steps
+ # warmup: prefer warmup_ratio (standard for embedding scripts), else steps
if warmup_ratio is not None and warmup_ratio > 0:
training_args_kwargs["warmup_ratio"] = warmup_ratio
elif warmup_steps_val is not None and warmup_steps_val > 0:
@@ -3074,7 +3048,7 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->
# ── 8. Create progress callback ──
class _EmbeddingProgressCallback(TrainerCallback):
- """Sends training progress events to the parent process via event_queue."""
+ """Send training progress events to the parent via event_queue."""
def on_log(
self,
diff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.py
index 4a27f13d388..35e2764fe9a 100644
--- a/studio/backend/loggers/config.py
+++ b/studio/backend/loggers/config.py
@@ -1,15 +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
-"""Logging configuration for structured logging with structlog.
+"""Structured logging configuration via structlog.
-This module provides centralized logging configuration with environment-specific
-formats and processors. Supports both development and production environments
-with consistent structured logging.
+Centralized config with environment-specific formats and processors for
+development and production.
-Key Features:
-- Environment-specific formatting (JSON for production, console for development)
-- Timestamp standardization (ISO format)
+Key features:
+- Environment-specific formatting (JSON for prod, console for dev)
+- ISO timestamps
- Context variable integration
- Log level filtering
- Logger caching for performance
@@ -28,8 +27,8 @@ from loggers.handlers import filter_sensitive_data
class LogConfig:
"""Structured logging configuration for the application.
- Provides static method to configure structlog with environment-specific
- formatting and processors for consistent structured logging.
+ Static method to configure structlog with environment-specific
+ formatting and processors.
"""
@staticmethod
@@ -41,9 +40,8 @@ class LogConfig:
service_name: Name of the service for logging identification
env: Environment (development/production), affects logging format
"""
- # Determine log level from environment
+ # Log level from environment; fall back to INFO if invalid.
log_level_name = os.getenv("LOG_LEVEL", "INFO").upper()
- # Fallback to INFO if an invalid level is provided
log_level = getattr(logging, log_level_name, logging.INFO)
if sys.platform == "win32":
@@ -56,13 +54,13 @@ class LogConfig:
structlog.configure(
processors = [
- # Reorder processors to control field order
+ # Ordered to control output field order.
structlog.processors.TimeStamper(fmt = "iso"), # timestamp first
structlog.processors.add_log_level, # level second
structlog.contextvars.merge_contextvars,
structlog.processors.format_exc_info,
filter_sensitive_data,
- # Custom processor to flatten the extra field
+ # Flatten the extra field into the main dict.
lambda logger, method_name, event_dict: {
"timestamp": event_dict.get("timestamp"),
"level": event_dict.get("level"),
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.py
index e80bd4fafbc..419e041a72f 100644
--- a/studio/backend/loggers/handlers.py
+++ b/studio/backend/loggers/handlers.py
@@ -3,16 +3,16 @@
"""Logging handlers and middleware for structured logging.
-This module provides FastAPI middleware and structlog processors for:
+FastAPI middleware + structlog processors for:
- Request/response logging with timing
-- Sensitive data filtering in logs
-- Structured logging configuration
-- Error handling with detailed context
-
-Key Components:
-- LoggingMiddleware: FastAPI middleware for request/response logging
-- filter_sensitive_data: Structlog processor for data sanitization
-- get_logger: Factory function for structured loggers
+- Sensitive data filtering
+- Structured logging config
+- Error handling with context
+
+Key components:
+- LoggingMiddleware: request/response logging
+- filter_sensitive_data: structlog processor for sanitization
+- get_logger: factory for structured loggers
"""
import re
@@ -38,7 +38,6 @@ class LoggingMiddleware(BaseHTTPMiddleware):
try:
response = await call_next(request)
- # Log response
process_time = (time.time() - start_time) * 1000
EXCLUDED_PATHS = {
@@ -108,10 +107,8 @@ def filter_sensitive_data(logger, method_name, event_dict):
def get_logger(name: str) -> structlog.BoundLogger:
- """Get a logger instance for a specific module.
+ """Get a bound structured logger for a module.
Args:
name: Usually __name__ of the module
- Returns:
- A bound structured logger
"""
return structlog.get_logger(name)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 8e3a118e276..1bc96c62063 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -9,20 +9,20 @@ import os
import sys
from pathlib import Path as _Path
-# Suppress annoying C-level dependency warnings globally
+# Suppress C-level dependency warnings globally
os.environ["PYTHONWARNINGS"] = "ignore"
# ── Windows AMD ROCm DLL injection ──────────────────────────────────────────
# Python 3.8+ ignores PATH for extension modules; register ROCm bin dirs with
# os.add_dll_directory() so amdhip64.dll etc. are found before any torch import.
if sys.platform == "win32":
- # Retained at module scope -- os.add_dll_directory returns a handle that
+ # Retained at module scope; os.add_dll_directory returns a handle that
# removes the search-path entry when garbage collected.
_ROCM_DLL_HANDLES: list = []
def _add_rocm_dll_dirs() -> None:
candidates = []
- # 1. HIP_PATH / ROCM_PATH -- set by the AMD HIP SDK installer
+ # 1. HIP_PATH / ROCM_PATH set by the AMD HIP SDK installer
for _var in ("HIP_PATH", "ROCM_PATH"):
_val = os.environ.get(_var)
if _val:
@@ -34,7 +34,7 @@ if sys.platform == "win32":
)
def _ver_key(name: str) -> tuple:
- # Numeric tuple key so "10.0" sorts after "7.0"; non-numeric chunks fall back to string.
+ # Numeric tuple key so "10.0" sorts after "7.0"; non-numeric chunks fall back to string
parts = []
for chunk in name.split("."):
try:
@@ -62,16 +62,15 @@ if sys.platform == "win32":
del _add_rocm_dll_dirs
# ── Windows AMD ROCm: set BNB_ROCM_VERSION before any bitsandbytes import ─
- # bitsandbytes on Windows ROCm tries to load libbitsandbytes_rocm<ver>.dll
- # where <ver> comes from torch.version.hip (e.g. "7.13..." → "713").
- # The installed BNB wheel ships rocm72.dll (not rocm713.dll), so without
- # this the server process crashes with "Configured ROCm binary not found".
- # Detect the available DLL, fall back to "72", and set BNB_ROCM_VERSION
- # before any import that pulls in bitsandbytes (mirrors worker.py logic).
- # Gate on the rocm bnb DLL (the exact file this configures) or HIP_PATH/
- # ROCM_PATH, not on torch.version.hip: that needed importing torch on every
- # Windows host (NVIDIA/CPU included), adding seconds to startup. Radeon
- # wheels without HIP_PATH still ship the rocm bnb DLL, so they are covered.
+ # bitsandbytes on Windows ROCm loads libbitsandbytes_rocm<ver>.dll where
+ # <ver> comes from torch.version.hip (e.g. "7.13..." → "713"). The installed
+ # BNB wheel ships rocm72.dll (not rocm713.dll), so without this the server
+ # crashes with "Configured ROCm binary not found". Detect the available DLL,
+ # fall back to "72", and set BNB_ROCM_VERSION before any bitsandbytes import
+ # (mirrors worker.py). Gate on the rocm bnb DLL (the file this configures) or
+ # HIP_PATH/ROCM_PATH, not torch.version.hip: that needed importing torch on
+ # every Windows host (NVIDIA/CPU too), adding startup seconds. Radeon wheels
+ # without HIP_PATH still ship the rocm bnb DLL, so they're covered.
if "BNB_ROCM_VERSION" not in os.environ:
import glob as _glob
import logging as _logging
@@ -82,7 +81,7 @@ if sys.platform == "win32":
try:
import importlib.util as _ilu
_bnb_spec = _ilu.find_spec("bitsandbytes")
- # submodule_search_locations (not spec.origin) handles editable installs.
+ # submodule_search_locations (not spec.origin) handles editable installs
if _bnb_spec and _bnb_spec.submodule_search_locations:
import re as _re_bnb
@@ -102,7 +101,7 @@ if sys.platform == "win32":
"Windows ROCm: BNB DLL detection failed (%s); falling back to version '72'",
_e,
)
- # rocm bnb DLL present, or HIP_PATH/ROCM_PATH set (DLL unparsable -> "72").
+ # rocm bnb DLL present, or HIP_PATH/ROCM_PATH set (DLL unparsable -> "72")
if _found_rocm_bnb or _hip_env:
_bnb_rocm_ver_final = _bnb_rocm_ver or "72"
os.environ["BNB_ROCM_VERSION"] = _bnb_rocm_ver_final
@@ -111,8 +110,8 @@ if sys.platform == "win32":
_bnb_rocm_ver_final,
)
-# Ensure backend dir is on sys.path so _platform_compat is importable when
-# main.py is launched directly (e.g. `uvicorn main:app`).
+# Put backend dir on sys.path so _platform_compat is importable when main.py
+# is launched directly (e.g. `uvicorn main:app`).
_backend_dir = str(_Path(__file__).parent)
if _backend_dir not in sys.path:
sys.path.insert(0, _backend_dir)
@@ -126,14 +125,14 @@ except ValueError as exc:
_raw = os.environ.get("UNSLOTH_CPU_THREADS")
raise SystemExit(f"Error: Invalid UNSLOTH_CPU_THREADS value {_raw!r}: {exc}") from None
-# Fix for Anaconda/conda-forge Python: seed platform._sys_version_cache before
-# any library imports that trigger attrs -> rich -> structlog -> platform crash.
+# Anaconda/conda-forge Python: seed platform._sys_version_cache before any
+# library import triggers attrs -> rich -> structlog -> platform crash.
# See: https://github.com/python/cpython/issues/102396
import _platform_compat # noqa: F401
# Direct `uvicorn main:app` launches bypass run.py, so re-export here too
-# (mirrors run.py). Required BEFORE the unsloth-zoo import below, since
-# its LLAMA_CPP_DEFAULT_DIR binding is import-time.
+# (mirrors run.py). Required BEFORE the unsloth-zoo import below, whose
+# LLAMA_CPP_DEFAULT_DIR binding is import-time.
from utils.paths.storage_roots import studio_root as _studio_root
try:
@@ -166,15 +165,13 @@ _STUDIO_INSTALL_ID_RE = _re.compile(r"^[0-9a-f]{64}$")
def _read_studio_install_id() -> str:
"""Per-install opaque id written by install.sh / install.ps1 at
- $STUDIO_HOME/share/studio_install_id. Returns "" when the file is
- absent (pre-PR install, fresh tree never run through the installer)
- or contains anything other than a 64-char lowercase-hex token --
- in which case /api/health emits "" and the launcher's _check_health
- falls back to the existing "no baked id, accept any healthy
- Unsloth backend" path. This intentionally replaces a previous
- sha256(resolved_install_path) so the field carries no install-path
- information for callers reaching /api/health (relevant when Studio
- is run with -H 0.0.0.0)."""
+ $STUDIO_HOME/share/studio_install_id. Returns "" when the file is absent
+ (pre-PR install, or fresh tree never run through the installer) or holds
+ anything other than a 64-char lowercase-hex token; then /api/health emits
+ "" and the launcher's _check_health falls back to "no baked id, accept any
+ healthy Unsloth backend". Replaces a previous sha256(resolved_install_path)
+ so the field carries no install-path info for callers reaching /api/health
+ (relevant when Studio runs with -H 0.0.0.0)."""
try:
token = (_STUDIO_ROOT_RESOLVED / "share" / "studio_install_id").read_text().strip()
except (OSError, ValueError):
@@ -186,29 +183,28 @@ _STUDIO_ROOT_ID_CACHE: str = _read_studio_install_id()
def _studio_root_id() -> str:
- """Same-install discriminator for /api/health: a per-install opaque
- token written once by the installer and read once at module import.
- Empty when no installer-written token is present; the launcher
- contract treats "" as "no baked id, accept any healthy backend"."""
+ """Same-install discriminator for /api/health: a per-install opaque token
+ written once by the installer and read once at module import. Empty when no
+ installer token is present; the launcher contract treats "" as "no baked id,
+ accept any healthy backend"."""
return _STUDIO_ROOT_ID_CACHE
-# Fix broken Windows registry MIME types. Some Windows installs map .js to
-# "text/plain" in the registry (HKCR\.js\Content Type). Python's mimetypes
-# module reads from the registry, and FastAPI/Starlette's StaticFiles uses
-# mimetypes.guess_type() to set Content-Type headers. Browsers enforce strict
-# MIME checking for ES module scripts (<script type="module">) and will refuse
-# to execute .js files served as text/plain — resulting in a blank page.
-# Calling add_type() *before* StaticFiles is instantiated ensures the correct
-# types are used regardless of the OS registry.
+# Fix broken Windows registry MIME types. Some Windows installs map .js to
+# "text/plain" in the registry (HKCR\.js\Content Type). Python's mimetypes reads
+# from the registry, and Starlette's StaticFiles uses mimetypes.guess_type() for
+# Content-Type. Browsers strictly MIME-check ES module scripts
+# (<script type="module">) and refuse .js served as text/plain, giving a blank
+# page. Calling add_type() *before* StaticFiles is instantiated forces the
+# correct types regardless of the OS registry.
if sys.platform == "win32":
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("text/css", ".css")
-# Suppress annoying dependency warnings in production
+# Suppress dependency warnings in production
if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
warnings.filterwarnings("ignore")
- # Alternatively, you can be more specific:
+ # Or be more specific:
# warnings.filterwarnings("ignore", category=DeprecationWarning)
# warnings.filterwarnings("ignore", module="triton.*")
@@ -300,7 +296,7 @@ def _desktop_owner() -> dict[str, str] | None:
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""
- # Clean up any stale compiled cache from previous runs
+ # Clean up stale compiled cache from previous runs
clear_unsloth_compiled_cache()
# Remove stale .venv_overlay from previous versions — no longer used.
@@ -354,8 +350,8 @@ async def lifespan(app: FastAPI):
import structlog
structlog.get_logger(__name__).warning("cleanup_orphaned_runs failed at startup: %s", exc)
- # Pre-cache the helper GGUF model for LLM-assisted dataset detection.
- # Runs in a background thread so it doesn't block server startup.
+ # Pre-cache the helper GGUF model for LLM-assisted dataset detection,
+ # in a background thread so it doesn't block server startup.
import threading
def _precache():
@@ -412,7 +408,7 @@ app.add_middleware(LoggingMiddleware)
# Citation favicons load from www.google.com/s2/favicons; *.gstatic.com is
-# kept for legacy web-search faviconV2 paths. Everything else is same-origin.
+# kept for legacy web-search faviconV2 paths. All else is same-origin.
from starlette.middleware.base import BaseHTTPMiddleware # noqa: E402
from starlette.requests import Request as _StarletteRequest # noqa: E402
@@ -421,7 +417,7 @@ _CSP_SCRIPT_NONCE_HEADER = "x-internal-script-nonce"
_ARTIFACT_PREVIEW_FRAME_PATH = "/api/inference/artifact-preview-frame"
-# /content is Colab's working directory — more reliable than env vars which
+# /content is Colab's working directory — more reliable than env vars, which
# aren't always set depending on Colab runtime version.
import importlib.util as _importlib_util
@@ -437,19 +433,18 @@ def _build_csp(script_nonce: "str | None" = None) -> str:
if script_nonce:
script_src += f" 'nonce-{script_nonce}'"
# In Colab the parent frame can be colab.research.google.com, a multi-level
- # *.prod.colab.dev subdomain (e.g. foo.region.prod.colab.dev — note: CSP
- # wildcards only match one level, so *.prod.colab.dev misses these), or a
- # sandboxed null-origin output iframe. Use '*' so any ancestor is allowed;
- # Colab is already a sandboxed single-user environment.
+ # *.prod.colab.dev subdomain (e.g. foo.region.prod.colab.dev — CSP wildcards
+ # only match one level, so *.prod.colab.dev misses these), or a sandboxed
+ # null-origin output iframe. Use '*' to allow any ancestor; Colab is already
+ # a sandboxed single-user environment.
frame_ancestors = "*" if _IS_COLAB else "'none'"
# In Colab the frontend is served over the Colab reverse-proxy at an HTTPS
- # *.prod.colab.dev URL. Colab's kernel communication layer and the output
- # iframe scaffolding inject scripts from *.prod.colab.dev and
- # *.googleusercontent.com, and make fetch/WebSocket connections to those
- # same origins. Widen script-src and connect-src in Colab mode so those
- # requests are not blocked. 'unsafe-inline' for scripts is still omitted;
- # our own inline script uses a nonce.
+ # *.prod.colab.dev URL. Colab's kernel layer and output-iframe scaffolding
+ # inject scripts from *.prod.colab.dev and *.googleusercontent.com, and
+ # fetch/WebSocket to those origins. Widen script-src and connect-src in
+ # Colab mode so those aren't blocked. 'unsafe-inline' for scripts is still
+ # omitted; our inline script uses a nonce.
if _IS_COLAB:
script_src += " https://*.prod.colab.dev https://*.googleusercontent.com"
connect_src = (
@@ -482,7 +477,7 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: _StarletteRequest, call_next):
response = await call_next(request)
- # Strip the internal nonce hand-off header so it never reaches the client.
+ # Strip the internal nonce hand-off header so it never reaches the client
nonce = response.headers.get(_CSP_SCRIPT_NONCE_HEADER)
if nonce is not None:
del response.headers[_CSP_SCRIPT_NONCE_HEADER]
@@ -505,7 +500,7 @@ app.add_middleware(SecurityHeadersMiddleware)
# Cap request bodies on protected POSTs. Upload routes get explicit multipart
-# headroom, while non-upload routes keep the default body cap.
+# headroom; non-upload routes keep the default body cap.
import json as _json_for_413 # noqa: E402
from utils.upload_limits import ( # noqa: E402
UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,
@@ -651,7 +646,7 @@ class MaxBodyMiddleware:
if mtype == "http.disconnect":
return
if mtype != "http.request":
- # Mid-stream unexpected frame: forwarding would corrupt downstream.
+ # Mid-stream unexpected frame: forwarding would corrupt downstream
return
body = msg.get("body", b"") or b""
if body:
@@ -730,13 +725,13 @@ app.include_router(training_router, prefix = "/api/train", tags = ["training"])
app.include_router(models_router, prefix = "/api/models", tags = ["models"])
app.include_router(chat_history_router, prefix = "/api/chat", tags = ["chat"])
app.include_router(inference_router, prefix = "/api/inference", tags = ["inference"])
-# Studio-only inference endpoints (cancel, etc.) are intentionally NOT
-# exposed on the /v1 OpenAI-compat prefix below.
+# Studio-only inference endpoints (cancel, etc.) are NOT exposed on the /v1
+# OpenAI-compat prefix below.
app.include_router(inference_studio_router, prefix = "/api/inference", tags = ["inference"])
-# OpenAI-compatible endpoints: mount the same inference router at /v1
-# so external tools (Open WebUI, SillyTavern, etc.) can use the
-# standard /v1/chat/completions path.
+# OpenAI-compatible endpoints: mount the same inference router at /v1 so
+# external tools (Open WebUI, SillyTavern, etc.) can use the standard
+# /v1/chat/completions path.
app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])
app.include_router(providers_router, prefix = "/api/providers", tags = ["providers"])
app.include_router(settings_router, prefix = "/api/settings", tags = ["settings"])
@@ -757,9 +752,9 @@ async def health_check(request: Request):
Unauthenticated callers (Tauri watchdog, frontend bootstrap polls) need
``service`` / ``studio_root_id`` / ``chat_only`` / ``desktop_*`` / ``native_path_leases_supported``
to (a) re-adopt a sibling backend across restarts and (b) gate UI surfaces
- before any token is available. None of those leak install path or version.
- ``version`` / ``studio_version`` / ``device_type`` still require a bearer
- because they fingerprint the host.
+ before a token is available. None of those leak install path or version.
+ ``version`` / ``studio_version`` / ``device_type`` require a bearer since
+ they fingerprint the host.
"""
base = {
"status": "healthy",
@@ -783,7 +778,7 @@ async def health_check(request: Request):
from fastapi.security import HTTPAuthorizationCredentials
creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = auth.split(" ", 1)[1])
- # Must await: a bare coroutine is truthy and would skip the auth check.
+ # Must await: a bare coroutine is truthy and would skip the auth check
subject = await _gcs(creds)
except HTTPException:
return base
@@ -819,7 +814,7 @@ async def shutdown_server(request: Request, current_subject: str = Depends(get_c
"""Gracefully shut down the Unsloth Studio server.
Called by the frontend quit dialog so users can stop the server from the UI
- without needing to use the CLI or kill the process manually.
+ without the CLI or killing the process manually.
"""
import asyncio
@@ -842,11 +837,11 @@ async def shutdown_server(request: Request, current_subject: str = Depends(get_c
async def get_system_info(current_subject: str = Depends(get_current_subject)):
"""Get system information.
- Gated behind auth: the response includes platform, Python version,
- GPU name, memory total, and ML package set -- enough to fingerprint
- a host. Studio's chat-only-mode design assumes only the local user
- reaches /api/system; in -H 0.0.0.0 / Colab / Tauri-relayed setups
- that assumption breaks unless we require a bearer.
+ Gated behind auth: the response includes platform, Python version, GPU name,
+ memory total, and ML package set -- enough to fingerprint a host. Studio's
+ chat-only design assumes only the local user reaches /api/system; in
+ -H 0.0.0.0 / Colab / Tauri-relayed setups that breaks unless we require a
+ bearer.
"""
import platform
import psutil
@@ -865,9 +860,8 @@ async def get_system_info(current_subject: str = Depends(get_current_subject)):
return {
"platform": platform.platform(),
"python_version": platform.python_version(),
- # Use the centralized _backend_label helper so the /api/system
- # endpoint reports "rocm" on AMD hosts instead of "cuda", matching
- # the /api/hardware and /api/gpu-visibility endpoints.
+ # Centralized _backend_label so /api/system reports "rocm" on AMD hosts
+ # instead of "cuda", matching /api/hardware and /api/gpu-visibility.
"device_backend": _backend_label(get_device()),
"cpu_count": psutil.cpu_count(),
"memory": {
@@ -888,8 +882,8 @@ async def get_gpu_visibility(current_subject: str = Depends(get_current_subject)
async def get_hardware_info(current_subject: str = Depends(get_current_subject)):
"""Return GPU name, total VRAM, and key ML package versions.
- Gated behind auth alongside /api/system -- same fingerprinting
- concern. /api/system/gpu-visibility is also auth-gated already.
+ Gated behind auth alongside /api/system -- same fingerprinting concern.
+ /api/system/gpu-visibility is also auth-gated.
"""
from utils.hardware import get_gpu_summary, get_package_versions
return {
@@ -904,11 +898,10 @@ async def get_hardware_info(current_subject: str = Depends(get_current_subject))
def _strip_crossorigin(html_bytes: bytes) -> bytes:
"""Remove ``crossorigin`` attributes from script/link tags.
- Vite adds ``crossorigin`` by default which forces CORS mode on font
- subresource loads. When Studio is served over plain HTTP, Firefox
- HTTPS-Only Mode does not exempt CORS font requests -- causing all
- @font-face downloads to fail silently. Stripping the attribute
- makes them regular same-origin fetches that work on any protocol.
+ Vite adds ``crossorigin`` by default, forcing CORS mode on font subresource
+ loads. Over plain HTTP, Firefox HTTPS-Only Mode doesn't exempt CORS font
+ requests, so all @font-face downloads fail silently. Stripping the attribute
+ makes them same-origin fetches that work on any protocol.
"""
html = html_bytes.decode("utf-8")
html = _re.sub(r'\s+crossorigin(?:="[^"]*")?', "", html)
@@ -917,8 +910,8 @@ def _strip_crossorigin(html_bytes: bytes) -> bytes:
def _inject_bootstrap(html_bytes: bytes, app: FastAPI):
"""Inject bootstrap credentials when password change is pending.
- Returns ``(html_bytes, script_nonce_or_None)``; callers forward the
- nonce via ``_CSP_SCRIPT_NONCE_HEADER`` so CSP allows the inline script.
+ Returns ``(html_bytes, script_nonce_or_None)``; callers forward the nonce
+ via ``_CSP_SCRIPT_NONCE_HEADER`` so CSP allows the inline script.
"""
import json as _json
import secrets as _secrets
@@ -949,9 +942,9 @@ _DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]]:
"""Canonicalise an Origin to ``(scheme, host, port)`` for equality.
Browsers strip default ports (RFC 6454 sec 6.1) and scheme/host are
- case-insensitive (RFC 3986), so bare string compare misclassifies
- same-origin requests as cross-origin. Returns ``None`` on unparseable
- input so callers fall to the safer cross-origin default.
+ case-insensitive (RFC 3986), so a bare string compare misclassifies
+ same-origin requests as cross-origin. Returns ``None`` on unparseable input
+ so callers fall to the safer cross-origin default.
"""
scheme = (scheme or "").strip().lower()
if not scheme or not netloc:
@@ -960,7 +953,7 @@ def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]
if "@" in netloc:
netloc = netloc.rsplit("@", 1)[1]
# IPv6 hosts use brackets (RFC 3986 sec 3.2.2): ``[::1]:8902``. Bare
- # ``partition(":")`` mis-parses these and breaks ``unsloth studio -H ::1``.
+ # ``partition(":")`` mis-parses these, breaking ``unsloth studio -H ::1``.
if netloc.startswith("["):
close = netloc.find("]")
if close == -1:
@@ -993,7 +986,7 @@ def _is_same_origin_request(request: Request) -> bool:
Top-level same-document GETs omit Origin, so missing counts as same-origin.
Callers must also emit ``Vary: Origin``. Both sides are canonicalised via
:func:`_canonical_origin` so default-port stripping and scheme/host case
- do not misclassify same-origin requests as cross-origin.
+ don't misclassify same-origin requests as cross-origin.
"""
origin = request.headers.get("origin")
if origin is None:
@@ -1064,7 +1057,7 @@ def setup_frontend(app: FastAPI, build_path: Path):
file_path = (build_path / full_path).resolve()
- # Block path traversal — ensure resolved path stays inside build_path
+ # Block path traversal — resolved path must stay inside build_path
if not file_path.is_relative_to(build_path.resolve()):
return Response(status_code = 403)
diff --git a/studio/backend/models/__init__.py b/studio/backend/models/__init__.py
index 7addca02cab..dbedeeca00d 100644
--- a/studio/backend/models/__init__.py
+++ b/studio/backend/models/__init__.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic models for API request/response schemas
-"""
+"""Pydantic models for API request/response schemas."""
from .training import (
TrainingStartRequest,
diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.py
index 9550e354a88..f451f8d9ddc 100644
--- a/studio/backend/models/auth.py
+++ b/studio/backend/models/auth.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for Authentication API
-"""
+"""Pydantic schemas for the Authentication API."""
from typing import Optional
diff --git a/studio/backend/models/data_recipe.py b/studio/backend/models/data_recipe.py
index f3faddf8436..e6f27e64dfa 100644
--- a/studio/backend/models/data_recipe.py
+++ b/studio/backend/models/data_recipe.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for Data Recipe (DataDesigner) API.
-"""
+"""Pydantic schemas for Data Recipe (DataDesigner) API."""
from __future__ import annotations
diff --git a/studio/backend/models/datasets.py b/studio/backend/models/datasets.py
index f20d6f2d15b..9a2d8e91cbd 100644
--- a/studio/backend/models/datasets.py
+++ b/studio/backend/models/datasets.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Dataset-related Pydantic models for API requests and responses.
-"""
+"""Dataset Pydantic models for API requests and responses."""
from typing import Any, Dict, List, Optional
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 86ce2b05bf4..0d54b435a6b 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for Export API.
-"""
+"""Pydantic schemas for Export API."""
from pathlib import Path
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index d2fa45dd92e..d7ce6741411 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for Inference API
-"""
+"""Pydantic schemas for the Inference API."""
from __future__ import annotations
@@ -108,11 +106,8 @@ class UnloadRequest(BaseModel):
class ValidateModelRequest(BaseModel):
- """
- Lightweight validation request to check whether a model identifier
- *can be resolved* into a ModelConfig.
-
- This does NOT actually load weights into GPU memory.
+ """Lightweight check whether a model identifier *can be resolved* into a
+ ModelConfig. Does NOT load weights into GPU memory.
"""
model_path: str = Field(..., description = "Model identifier or local path")
@@ -126,8 +121,7 @@ class ValidateModelRequest(BaseModel):
class ValidateModelResponse(BaseModel):
- """
- Result of model validation.
+ """Result of model validation.
valid == True means ModelConfig.from_identifier() succeeded and basic
introspection (GGUF / LoRA / vision flags) is available.
@@ -245,10 +239,9 @@ class UnloadResponse(BaseModel):
class LoadProgressResponse(BaseModel):
"""Progress of the active GGUF load, sampled on demand.
- Used by the UI to show a real progress bar during the
- post-download warmup window (mmap + CUDA upload), rather than a
- generic "Starting model..." spinner that freezes for minutes on
- large MoE models.
+ Drives a real progress bar during the post-download warmup window
+ (mmap + CUDA upload), instead of a generic "Starting model..." spinner
+ that freezes for minutes on large MoE models.
"""
phase: Optional[str] = Field(
@@ -409,10 +402,10 @@ class InputDocumentContentPart(BaseModel):
Studio-normalised shape. The frontend sends either
``{type:"input_document", file_data:"data:application/pdf;base64,..."}``
or ``{type:"input_document", file_url:"https://..."}``, plus optional
- ``filename`` and ``media_type``. ``external_provider`` translates this
- onto Anthropic's ``document`` block or OpenAI Responses' ``input_file``
- block for vision-capable providers; non-vision providers drop the
- part entirely (handled in ``_build_external_messages``).
+ ``filename`` and ``media_type``. ``external_provider`` maps this onto
+ Anthropic's ``document`` block or OpenAI Responses' ``input_file`` block
+ for vision-capable providers; non-vision providers drop the part
+ (handled in ``_build_external_messages``).
"""
type: Literal["input_document"]
@@ -437,10 +430,10 @@ class InputDocumentContentPart(BaseModel):
class OpenAIReasoningContentPart(BaseModel):
"""OpenAI Responses reasoning item paired with a tool output.
- Reasoning models can require the previous ``reasoning`` output item
- to be replayed immediately before an ``image_generation_call`` id
- when manually managing Responses context. This part is OpenAI-only;
- routes strip it for every other provider before proxying.
+ Reasoning models can require the previous ``reasoning`` output item to be
+ replayed immediately before an ``image_generation_call`` id when manually
+ managing Responses context. OpenAI-only; routes strip it for every other
+ provider before proxying.
"""
type: Literal["reasoning"]
@@ -452,12 +445,12 @@ class OpenAIReasoningContentPart(BaseModel):
class ImageGenerationCallContentPart(BaseModel):
"""OpenAI Responses image_generation call reference.
- OpenAI accepts prior ``image_generation_call`` items in the next
- Responses ``input`` array so follow-up prompts can edit or refine a
- generated image without resending the base64 payload. The frontend
- forwards this as a synthetic assistant content part when building
- the next OpenAI Responses request; ``external_provider`` translates
- it back to the provider-specific top-level input item.
+ OpenAI accepts prior ``image_generation_call`` items in the next Responses
+ ``input`` array so follow-up prompts can edit or refine a generated image
+ without resending the base64 payload. The frontend forwards this as a
+ synthetic assistant content part when building the next request;
+ ``external_provider`` maps it back to the provider-specific top-level
+ input item.
"""
type: Literal["image_generation_call"]
@@ -472,14 +465,13 @@ class CompactionContentPart(BaseModel):
"""Anthropic server-side compaction state, attached to an assistant
message for round-tripping on the next turn.
- When Anthropic runs compaction during a request, the response
- carries a ``{"type": "compaction", "content": "<summary>"}`` block
- on the assistant message. The chat-adapter persists it onto the
- stored message; the next turn's outbound request must forward it
- back so Anthropic recognises the existing compaction state and
- doesn't re-summarise the conversation from scratch. See
- ``external_provider._stream_anthropic`` for the wire-side handling
- and https://platform.claude.com/docs/en/build-with-claude/compaction
+ When Anthropic compacts during a request, the response carries a
+ ``{"type": "compaction", "content": "<summary>"}`` block on the assistant
+ message. The chat-adapter persists it; the next turn's outbound request
+ must forward it back so Anthropic recognises the existing compaction state
+ and doesn't re-summarise from scratch. See
+ ``external_provider._stream_anthropic`` for the wire-side handling and
+ https://platform.claude.com/docs/en/build-with-claude/compaction
for the upstream contract.
"""
@@ -516,9 +508,9 @@ ContentPart = Annotated[
class ChatMessage(BaseModel):
"""Single message in a chat conversation.
- ``content`` is a string or a list of multimodal content parts. Assistant
- messages with only ``tool_calls`` populated may set ``content=None``.
- Missing ``tool_call_id`` on ``role="tool"`` is resolved at the
+ ``content`` is a string or list of multimodal content parts. Assistant
+ messages with only ``tool_calls`` may set ``content=None``. Missing
+ ``tool_call_id`` on ``role="tool"`` is resolved at the
``ChatCompletionRequest`` layer by walking back to the preceding assistant.
"""
@@ -571,16 +563,15 @@ class ChatMessage(BaseModel):
class ChatCompletionRequest(BaseModel):
- """
- OpenAI-compatible chat completion request.
+ """OpenAI-compatible chat completion request.
- Extensions (non-OpenAI fields) are marked with 'x-unsloth'.
+ Non-OpenAI extension fields are marked with 'x-unsloth'.
"""
- # Accept unknown fields defensively so future OpenAI fields (seed,
- # response_format, logprobs, frequency_penalty, etc.) don't get
- # silently dropped by Pydantic before route code runs. Mirrors
- # AnthropicMessagesRequest and ResponsesRequest.
+ # Accept unknown fields so future OpenAI fields (seed, response_format,
+ # logprobs, frequency_penalty, etc.) aren't silently dropped by Pydantic
+ # before route code runs. Mirrors AnthropicMessagesRequest and
+ # ResponsesRequest.
model_config = {"extra": "allow"}
model: str = Field(
@@ -738,18 +729,16 @@ class ChatCompletionRequest(BaseModel):
@field_validator("enable_prompt_caching", mode = "before")
@classmethod
def _coerce_enable_prompt_caching(cls, value: Any) -> Any:
- """Preserve the pre-PR coercion: the field used to be Optional[bool],
- so callers historically sent JSON strings `"true"` / `"false"` and
- Pydantic v1 coerced them. Widening to Optional[Union[bool, str]] for
- Gemini cache resource names lets `"false"` slip through as a truthy
- string. Coerce the canonical bool literals back so explicit opt-outs
- stay opt-out."""
+ """Preserve the pre-PR coercion. The field was once Optional[bool], so
+ callers historically sent JSON strings `"true"` / `"false"` that
+ Pydantic v1 coerced. Widening to Optional[Union[bool, str]] for Gemini
+ cache resource names lets `"false"` slip through as truthy; coerce the
+ canonical bool literals back so explicit opt-outs stay opt-out."""
if isinstance(value, str):
lowered = value.strip().lower()
# Match Pydantic v1's BooleanField coercion table (yes/y/on/t/1
- # and no/n/off/f/0) so opt-outs that used to parse still parse.
- # Anything else is preserved as a string for Gemini's
- # cachedContent resource path.
+ # and no/n/off/f/0) so old opt-outs still parse. Anything else
+ # stays a string for Gemini's cachedContent resource path.
if lowered in ("true", "t", "1", "yes", "y", "on"):
return True
if lowered in ("false", "f", "0", "no", "n", "off"):
@@ -836,10 +825,10 @@ class ChatCompletionRequest(BaseModel):
OpenAI / Anthropic passthrough require the result id to match the
assistant's tool_calls[].id. Prefer function.name match, else first
- unconsumed tool_call; synth random id only if no candidate exists.
- Crossing a user turn breaks the lookup.
+ unconsumed tool_call; synth a random id only if none exists. A user
+ turn breaks the lookup.
"""
- # Pre-mark explicit ids first so a sibling missing-id result does not
+ # Pre-mark explicit ids first so a sibling missing-id result doesn't
# steal one already claimed by name.
consumed: set[tuple[int, int]] = set()
@@ -902,12 +891,10 @@ class ChatCompletionRequest(BaseModel):
class OpenAIContainerRequest(BaseModel):
- """
- Shared body for the three OpenAI container endpoints (list / create
- / delete). Carries the encrypted API key + base URL so the route
- handler can decrypt it and proxy to the user's OpenAI account.
- Same pattern as the inference proxy endpoints — keeps the key off
- persistent storage on the backend.
+ """Shared body for the three OpenAI container endpoints (list / create /
+ delete). Carries the encrypted API key + base URL so the route handler
+ can decrypt it and proxy to the user's OpenAI account. Same pattern as the
+ inference proxy endpoints — keeps the key off backend persistent storage.
"""
encrypted_api_key: str = Field(
@@ -1055,10 +1042,10 @@ class ResponsesOutputTextPart(BaseModel):
"""Assistant ``output_text`` content part replayed on subsequent turns.
When a client (OpenAI Codex CLI, OpenAI Python SDK agents) loops on a
- stateless Responses endpoint, prior assistant messages are round-tripped
- as ``{"role":"assistant","content":[{"type":"output_text","text":...,
- "annotations":[],"logprobs":[]}]}``. We preserve the text and ignore
- the annotations/logprobs metadata when flattening into Chat Completions.
+ stateless Responses endpoint, prior assistant messages round-trip as
+ ``{"role":"assistant","content":[{"type":"output_text","text":...,
+ "annotations":[],"logprobs":[]}]}``. We keep the text and ignore the
+ annotations/logprobs metadata when flattening into Chat Completions.
"""
type: Literal["output_text"]
@@ -1073,8 +1060,8 @@ class ResponsesUnknownContentPart(BaseModel):
"""Catch-all for content-part types we don't model explicitly.
Keeps validation green when a client sends newer part types (e.g.
- ``input_audio``, ``input_file``) we haven't mapped; these are silently
- skipped during normalisation rather than rejected with a 422.
+ ``input_audio``, ``input_file``) we haven't mapped; these are skipped
+ during normalisation rather than rejected with a 422.
"""
type: str
@@ -1099,16 +1086,15 @@ class ResponsesInputMessage(BaseModel):
# Codex (gpt-5.3-codex+) attaches a `phase` field ("commentary" |
# "final_answer") to assistant messages and requires clients to preserve
- # it on subsequent turns. We accept and round-trip it; llama-server does
- # not care about it.
+ # it across turns. We accept and round-trip it; llama-server ignores it.
model_config = {"extra": "allow"}
class ResponsesFunctionCallInputItem(BaseModel):
- """A prior assistant function_call being replayed in a multi-turn Responses input.
+ """A prior assistant function_call replayed in a multi-turn Responses input.
The Responses API represents tool calls as top-level input items (not
- nested inside assistant messages), correlated across turns by ``call_id``.
+ nested in assistant messages), correlated across turns by ``call_id``.
"""
type: Literal["function_call"]
@@ -1125,7 +1111,7 @@ class ResponsesFunctionCallInputItem(BaseModel):
class ResponsesFunctionCallOutputInputItem(BaseModel):
"""A tool result supplied by the client for a prior function_call.
- Replaces Chat Completions' ``role="tool"`` message. Correlated to the
+ Replaces Chat Completions' ``role="tool"`` message. Correlated to its
originating call by ``call_id``.
"""
@@ -1142,10 +1128,9 @@ class ResponsesUnknownInputItem(BaseModel):
"""Catch-all for Responses input item types we don't model explicitly.
Covers ``reasoning`` items (replayed from prior o-series / gpt-5 turns)
- and any future item types the client may send. These items are dropped
- during normalisation — llama-server-backed GGUFs cannot consume them —
- but keeping them in the request-model union stops unrelated turns from
- failing validation with a 422.
+ and any future item types. Dropped during normalisation (llama-server
+ GGUFs can't consume them), but keeping them in the request-model union
+ stops unrelated turns from failing validation with a 422.
"""
type: str
@@ -1156,12 +1141,11 @@ class ResponsesUnknownInputItem(BaseModel):
def _responses_input_item_discriminator(v: Any) -> str:
"""Route a Responses input item to the correct tagged variant.
- Pydantic's default smart-union matching fails when one variant in the
- union is tagged with a strict ``Literal`` (``function_call`` /
- ``function_call_output``) and the incoming dict uses a different
- ``type`` — the other variants' validation errors are hidden and the
- outer ``Union[str, list[...]]`` reports a misleading "Input should be a
- valid string" error. An explicit discriminator makes the routing
+ Pydantic's smart-union matching fails when one union variant is tagged
+ with a strict ``Literal`` (``function_call`` / ``function_call_output``)
+ and the incoming dict has a different ``type``: other variants' errors are
+ hidden and the outer ``Union[str, list[...]]`` reports a misleading "Input
+ should be a valid string". An explicit discriminator makes routing
deterministic and lets us fall through to the catch-all.
"""
if isinstance(v, dict):
@@ -1191,12 +1175,12 @@ ResponsesInputItem = Annotated[
class ResponsesFunctionTool(BaseModel):
- """Flat function-tool definition used by the Responses API request.
+ """Flat function-tool definition for the Responses API request.
Unlike Chat Completions (which nests ``{"name": ..., "parameters": ...}``
- inside a ``"function"`` key), the Responses API uses a flat shape with
- ``type``, ``name``, ``description``, ``parameters``, and ``strict`` at the
- top level of each tool entry.
+ under a ``"function"`` key), the Responses API uses a flat shape with
+ ``type``, ``name``, ``description``, ``parameters``, ``strict`` at the top
+ level of each tool entry.
"""
type: Literal["function"]
@@ -1220,11 +1204,11 @@ class ResponsesRequest(BaseModel):
max_output_tokens: Optional[int] = Field(None, ge = 1)
stream: bool = Field(False, description = "Whether to stream the response via SSE")
- # OpenAI function-calling fields — forwarded to llama-server via the
- # Chat Completions pass-through (see routes/inference.py). Typed as a
- # plain list so built-in tool shapes (``web_search``, ``file_search``,
- # ``mcp``, ...) round-trip without validation errors — the translator
- # picks out only ``type=="function"`` entries for forwarding.
+ # OpenAI function-calling fields, forwarded to llama-server via the Chat
+ # Completions pass-through (see routes/inference.py). Plain list so
+ # built-in tool shapes (``web_search``, ``file_search``, ``mcp``, ...)
+ # round-trip without validation errors; the translator forwards only
+ # ``type=="function"`` entries.
tools: Optional[list[dict]] = Field(
None,
description = (
@@ -1280,10 +1264,9 @@ class ResponsesOutputMessage(BaseModel):
class ResponsesOutputFunctionCall(BaseModel):
"""A function-call output item in the Responses API response.
- Unlike Chat Completions (which nests tool calls inside the assistant
- message), the Responses API emits each tool call as its own top-level
- ``output`` item so clients can correlate results via ``call_id`` on the
- next turn.
+ Unlike Chat Completions (tool calls nested in the assistant message), the
+ Responses API emits each tool call as its own top-level ``output`` item so
+ clients can correlate results via ``call_id`` on the next turn.
"""
type: Literal["function_call"] = "function_call"
@@ -1439,7 +1422,7 @@ class AnthropicMessagesRequest(BaseModel):
top_k: Optional[int] = None
stop_sequences: Optional[list[str]] = None
metadata: Optional[dict] = None
- # [x-unsloth] extensions — mirror the OpenAI endpoint convenience fields
+ # [x-unsloth] extensions mirroring the OpenAI endpoint convenience fields
min_p: Optional[float] = Field(
None, ge = 0.0, le = 1.0, description = "[x-unsloth] Min-p sampling threshold"
)
diff --git a/studio/backend/models/models.py b/studio/backend/models/models.py
index 3dd8e779f7a..ff00363ff8d 100644
--- a/studio/backend/models/models.py
+++ b/studio/backend/models/models.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for Model Management API
-"""
+"""Pydantic schemas for Model Management API"""
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any, Literal
@@ -56,7 +54,7 @@ class CheckpointListResponse(BaseModel):
class ModelDetails(BaseModel):
- """Detailed model configuration and metadata - can be used for both list and detail views"""
+ """Model configuration and metadata; used for both list and detail views"""
id: str = Field(..., description = "Model identifier")
model_name: Optional[str] = Field(
diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.py
index e9d2d859f5b..8f90e19df65 100644
--- a/studio/backend/models/providers.py
+++ b/studio/backend/models/providers.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Pydantic schemas for the external LLM providers API.
-"""
+"""Pydantic schemas for the external LLM providers API."""
from typing import Literal, Optional
diff --git a/studio/backend/models/responses.py b/studio/backend/models/responses.py
index f6357bf9991..cc420c0f69f 100644
--- a/studio/backend/models/responses.py
+++ b/studio/backend/models/responses.py
@@ -1,10 +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
-"""
-Pydantic response schemas for endpoints that previously returned raw dicts.
-These are small response models for training and model management routes.
-"""
+"""Pydantic response models for training and model management routes
+(previously returned as raw dicts)."""
from pydantic import BaseModel, Field
from typing import Optional, List
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index cef0b8f36f3..829be12c916 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -26,7 +26,7 @@ _MAX_LR_VALUE = 1.0
_MAX_LORA_R = 16_384
_MAX_LORA_ALPHA = 32_768
_MIN_VISION_IMAGE_SIZE = 256
-# 2048 was the most I could get most llms to work at without getting unstable
+# 2048 is the highest most llms stay stable at
_MAX_VISION_IMAGE_SIZE = 2048
@@ -343,7 +343,7 @@ class TrainingStartRequest(BaseModel):
@model_validator(mode = "after")
def _check_steps_or_epochs(self) -> "TrainingStartRequest":
# num_epochs and max_steps each accept 0 as a "use the other one"
- # sentinel. If both resolve to 0 there's nothing to train against.
+ # sentinel. Both 0 means nothing to train against.
if (self.max_steps is None or self.max_steps == 0) and self.num_epochs == 0:
raise ValueError("Either num_epochs or max_steps must be > 0; both cannot be 0.")
return self
diff --git a/studio/backend/models/users.py b/studio/backend/models/users.py
index 6a28d3ea55a..738c76c576c 100644
--- a/studio/backend/models/users.py
+++ b/studio/backend/models/users.py
@@ -1,10 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Pydantic models for authentication tokens.
-
-This module defines the Token response model used by auth routes.
-"""
+"""Pydantic models for authentication tokens."""
from pydantic import BaseModel, Field
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/__init__.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/__init__.py
index f57af4c6c35..fd3846dc21e 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/__init__.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/__init__.py
@@ -3,5 +3,5 @@
# Intentionally empty. Data-designer loads submodules lazily via qualified names
# (impl_qualified_name / config_qualified_name in plugin.py), so importing this
-# package must NOT touch modules that depend on data_designer.engine.* during
+# package must NOT touch modules depending on data_designer.engine.* during
# Studio's bootstrap (circular import).
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
index 5a38e26d6bd..9190b6a738f 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
@@ -17,13 +17,12 @@ from .scraper import ScrapeConfig, materialize_to_jsonl
# In-process cache mapping a stable config signature to the JSONL materialization
-# path. A single recipe job invokes the seed reader multiple times (validation,
-# preview, per-column sampling), and the default flow re-scrapes the repo on
-# every call: for a 2-repo preview that is ~15s of redundant GitHub GraphQL
-# traffic before any generation fires. Memoize the materialization so the second
-# and third passes reuse the file the first pass wrote. Cache key excludes the
-# raw token and uses a short SHA-256 digest so token values never hit memory
-# twice and token rotation invalidates cleanly.
+# path. A recipe job calls the seed reader multiple times (validation, preview,
+# per-column sampling) and the default flow re-scrapes on every call: a 2-repo
+# preview is ~15s of redundant GitHub GraphQL traffic before any generation.
+# Memoize so later passes reuse the first pass's file. The key excludes the raw
+# token and uses a short SHA-256 digest, so token values never hit memory twice
+# and rotation invalidates cleanly.
_SCRAPE_CACHE: dict[tuple, str] = {}
_SCRAPE_CACHE_LOCK = threading.Lock()
@@ -47,8 +46,8 @@ def _lookup_cached_scrape(key: tuple) -> Optional[str]:
path = _SCRAPE_CACHE.get(key)
if path and Path(path).exists():
return path
- # Stale entry (tmp cleanup, user restarted, ...); drop it so the caller
- # materializes a fresh file rather than returning a dangling path.
+ # Stale entry (tmp cleanup, restart, ...); drop it so the caller
+ # materializes a fresh file instead of returning a dangling path.
if path:
with _SCRAPE_CACHE_LOCK:
_SCRAPE_CACHE.pop(key, None)
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper.py
index d468db70d28..926606c24ca 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper.py
@@ -3,11 +3,10 @@
"""Multi-repo GitHub scraper for the Studio seed plugin.
-Drives the GraphQL-based scraper in `scraper_impl/` per repo. Each repo is
-scraped with a trial_limits cap so we stop at `limit` items per resource.
-After scraping, we read the per-resource JSONL shards and flatten them into
-a single unified JSONL with stable columns (`item_type`, `repo`, `number`,
-`title`, `body`, ...).
+Drives the GraphQL scraper in `scraper_impl/` per repo, capped via trial_limits
+to stop at `limit` items per resource. Then reads the per-resource JSONL shards
+and flattens them into one unified JSONL with stable columns (`item_type`,
+`repo`, `number`, `title`, `body`, ...).
"""
from __future__ import annotations
@@ -166,7 +165,7 @@ def scrape(cfg: ScrapeConfig, base_dir: Path):
client = GitHubClient(token = token.value, token_source = token.source)
base_dir.mkdir(parents = True, exist_ok = True)
- # Per-resource trial limits. limit <= 0 means "all": use a very large cap.
+ # Per-resource trial limits. limit <= 0 means "all": use a large cap.
effective_limit = cfg.limit if cfg.limit and cfg.limit > 0 else 1_000_000
trial_limits: dict[str, int] = {}
if "issues" in cfg.item_types:
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/gh_client.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/gh_client.py
index eda242a6ea7..9ab174c2d4f 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/gh_client.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/gh_client.py
@@ -110,12 +110,11 @@ class GitHubClient:
)
def _is_auth_failure(self, r: "requests.Response") -> bool:
- """Distinguish auth failures from rate limiting on 401/403 responses.
+ """Tell auth failures apart from rate limiting on 401/403.
- 401: always an auth failure (invalid / expired / wrong-scope token).
- - 403: an auth failure UNLESS the response carries a clear rate-limit signal
- (Retry-After header, X-RateLimit-Remaining: 0, or GitHub's secondary /
- abuse rate-limit response text).
+ - 403: auth failure UNLESS it carries a rate-limit signal (Retry-After,
+ X-RateLimit-Remaining: 0, or secondary / abuse rate-limit text).
"""
if r.status_code == 401:
return True
@@ -169,7 +168,7 @@ class GitHubClient:
timeout = 120,
)
self.calls_graphql += 1
- # Update rate info from response headers
+ # Update rate info from headers
rem = r.headers.get("X-RateLimit-Remaining")
rst = r.headers.get("X-RateLimit-Reset")
if rem is not None:
@@ -190,7 +189,7 @@ class GitHubClient:
if self._is_auth_failure(r):
self._raise_auth_error(r, "GraphQL")
if r.status_code == 403 or r.status_code == 429:
- # Check for secondary/abuse
+ # Secondary/abuse rate limit
retry_after = _retry_after_seconds(r.headers.get("Retry-After"))
if retry_after is not None:
log.warning("Secondary rate limit. Sleep %ds.", retry_after)
@@ -204,15 +203,14 @@ class GitHubClient:
r.raise_for_status()
data = r.json()
if "errors" in data and data["errors"]:
- # Surface errors but allow partial data
+ # Surface errors but allow partial data; retry on RATE_LIMITED
errs = data["errors"]
- # Retry on RATE_LIMITED
for e in errs:
if e.get("type") == "RATE_LIMITED":
self._sleep_until((self.graphql_reset or int(time.time()) + 60))
break
else:
- # No rate-limit error, log and return partial
+ # No rate-limit error: log and return partial
log.warning("GraphQL errors: %s", json.dumps(errs)[:400])
return data
continue
@@ -268,7 +266,7 @@ class GitHubClient:
log.warning("Secondary rate limit on REST. Sleep %ds.", retry_after)
time.sleep(retry_after + 2)
continue
- # Check if primary rate
+ # Primary rate limit
if self.rest_remaining == 0 and self.rest_reset:
self._sleep_until(self.rest_reset)
continue
@@ -299,11 +297,11 @@ class GitHubClient:
return
items = r.json()
if isinstance(items, dict):
- # Some endpoints return dict with list field
+ # Some endpoints wrap the list in an "items" field
items = items.get("items", [])
for it in items:
yield it
- # Follow link header
+ # Follow Link header
link = r.headers.get("Link", "")
nxt = None
for part in link.split(","):
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/queries.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/queries.py
index 9dc7613db53..ff2a81d1c32 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/queries.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/queries.py
@@ -3,11 +3,11 @@
"""GraphQL queries for GitHub data scraping.
-GitHub's GraphQL rejects queries that define unused fragments, so each query
-only includes the fragments it actually references.
+GitHub's GraphQL rejects queries with unused fragments, so each query includes
+only the fragments it references.
"""
-# ---- Fragments (kept as raw strings, composed per query) ----
+# ---- Fragments (raw strings, composed per query) ----
F_ACTOR = """
fragment ActorFields on Actor {
__typename
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/scraper.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/scraper.py
index 826ffc1256a..08e2a28ceb9 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/scraper.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/scraper.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Main scraper orchestration. Collects issues, PRs, discussions, commits, releases, etc.
+"""Scraper orchestration: issues, PRs, discussions, commits, releases, etc.
Resumable via state file. Writes JSONL shards under data/{repo}/{resource}.jsonl.
"""
@@ -49,9 +49,9 @@ class RepoScraper:
self.base_dir = base_dir
self.client = client
self.trial_limits = trial_limits or {}
- # When light=True, use trimmed GraphQL queries (no reviewThreads,
- # reviews, commits, timelineItems, files) so PR pages can be much
- # larger without blowing GitHub's node-count ceiling.
+ # light=True uses trimmed GraphQL queries (no reviewThreads,
+ # reviews, commits, timelineItems, files) so PR pages can be larger
+ # without hitting GitHub's node-count ceiling.
self.light = light
self.repo_dir = base_dir / f"{owner}__{name}"
self.repo_dir.mkdir(parents = True, exist_ok = True)
@@ -225,8 +225,8 @@ class RepoScraper:
page = 0
# Heavy nested PR query is capped at 3 per page (GitHub node-count
# ceiling); light query skips reviewThreads/reviews/commits/etc and
- # can safely go to 25 per page. Clamp by trial_limit for small
- # previews so limit=1 does not fetch a whole 25-item page.
+ # goes to 25 per page. Clamp by trial_limit so limit=1 does not
+ # fetch a whole 25-item page.
page_cap = 25 if self.light else 3
trial_cap = self.trial_limits.get(key)
per_page = min(page_cap, trial_cap) if trial_cap and trial_cap > 0 else page_cap
@@ -370,7 +370,7 @@ class RepoScraper:
f["_owner"] = self.owner
f["_repo"] = self.name
f["_prNumber"] = number
- # files don't have id, synthesize one
+ # files have no id; synthesize one
f["_syntheticId"] = f"{self.owner}/{self.name}#{number}:{f.get('path')}"
self.writers[out_key].write(f)
info = ff.get("pageInfo") or {}
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/state_store.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/state_store.py
index de9ccca82b5..67107c285a0 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/state_store.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/scraper_impl/state_store.py
@@ -65,7 +65,7 @@ class JsonlWriter:
self._lock = threading.Lock()
self._fh = self.path.open("a", buffering = 1)
self._count_seen_keys: set[str] = set()
- # Preload seen keys if file exists (for dedup across resumes)
+ # Preload seen keys for dedup across resumes
if self.path.exists() and self.path.stat().st_size > 0:
try:
with self.path.open() as f:
diff --git a/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py b/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py
index 4da46634e5e..e5c2f7a492d 100644
--- a/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py
+++ b/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py
@@ -70,11 +70,11 @@ def build_multi_file_preview_rows(
def _round_robin_preview(rows: list[dict[str, str]], preview_size: int) -> list[dict[str, str]]:
- """Pick preview rows round-robin across source files so every file is represented."""
+ """Pick preview rows round-robin across source files so each is represented."""
if not rows or preview_size <= 0:
return []
- # Group rows by source_file, preserving order of first appearance
+ # Group rows by source_file, preserving first-appearance order.
from collections import OrderedDict
grouped: OrderedDict[str, list[dict[str, str]]] = OrderedDict()
@@ -147,7 +147,7 @@ def materialize_multi_file_unstructured_seed(
chunk_size: int,
chunk_overlap: int,
) -> tuple[Path, list[dict[str, str]]]:
- """Chunk multiple files and combine into one parquet dataset with source_file column."""
+ """Chunk multiple files into one parquet dataset with a source_file column."""
chunk_size, chunk_overlap = resolve_chunking(chunk_size, chunk_overlap)
cache_key = _compute_multi_file_cache_key(file_entries, chunk_size, chunk_overlap)
cached = _CACHE_DIR / f"{cache_key}.parquet"
diff --git a/studio/backend/requirements/single-env/patch_metadata.py b/studio/backend/requirements/single-env/patch_metadata.py
index 7bcaa56ac8b..6c3ee4af524 100644
--- a/studio/backend/requirements/single-env/patch_metadata.py
+++ b/studio/backend/requirements/single-env/patch_metadata.py
@@ -2,14 +2,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
-"""Relax strict metadata pins so pip check matches known working single-env stack.
+"""Relax strict metadata pins so pip check passes on the single-env stack.
Why:
- data-designer pins huggingface-hub>=1.0.1 and pyarrow<20.
- unsloth/transformers pins huggingface-hub<1.
- studio datasets pins pyarrow>=21.
-Runtime works in this app with hub 0.36.x + pyarrow 23.x, but metadata conflicts.
+Runtime works with hub 0.36.x + pyarrow 23.x; only the metadata conflicts.
"""
from __future__ import annotations
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index 7c60545595c..c19560c5298 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -43,17 +43,17 @@ router = APIRouter()
def _reset_password_command() -> str:
"""Shell command shown in the 'incorrect password' hint.
- Prefer the ABSOLUTE path to this install's ``unsloth`` launcher (a sibling
- of the running interpreter) so the hint works even when the launcher's
- directory is not on PATH -- e.g. a terminal opened before install, a stale
- Windows PATH, or ``~/.local/bin`` not on PATH (the default on macOS) -- and
- regardless of the current working directory.
-
- On POSIX the path is shell-quoted so spaces are handled. On Windows we only
- use the bare absolute path when it has no spaces, because a quoted path needs
- different syntax in cmd (``"..."``) vs PowerShell (``& "..."``); when it has
- a space we fall back to the PATH-based form to stay unambiguous across
- shells. If the launcher can't be located we fall back to the PATH form too.
+ Prefer the ABSOLUTE path to this install's ``unsloth`` launcher (sibling of
+ the running interpreter) so the hint works even when the launcher's dir
+ isn't on PATH -- e.g. a terminal opened before install, a stale Windows
+ PATH, or ``~/.local/bin`` not on PATH (the macOS default) -- regardless of
+ the cwd.
+
+ On POSIX the path is shell-quoted to handle spaces. On Windows we use the
+ bare absolute path only when it has no spaces, since a quoted path needs
+ different syntax in cmd (``"..."``) vs PowerShell (``& "..."``); with a
+ space we fall back to the PATH-based form to stay unambiguous across shells.
+ We also fall back to the PATH form if the launcher can't be located.
"""
try:
bin_dir = os.path.dirname(os.path.abspath(sys.executable))
@@ -72,7 +72,7 @@ def _reset_password_command() -> str:
# Per-(ip, username) bucket + per-IP aggregate. Account bucket stops one user's
# typos from blocking others; the aggregate stops username-rotation spray.
-# Single-process only -- multi-worker deployments need a shared store.
+# Single-process only; multi-worker deployments need a shared store.
_LOGIN_BUCKETS: dict[tuple[str, str], deque] = {}
_LOGIN_IP_BUCKETS: dict[str, deque] = {}
_LOGIN_BUCKETS_LOCK = threading.Lock()
@@ -80,18 +80,18 @@ _LOGIN_WINDOW_SECONDS = 60.0
_LOGIN_MAX_FAILS = 5
_LOGIN_IP_MAX_FAILS = 30
_LOGIN_LOCKOUT_SECONDS = 60
-# Bucket-dict cap. On overflow we prune stale entries; if still full the
-# failure folds into the per-IP aggregate only.
+# Bucket-dict cap. On overflow, prune stale entries; if still full the failure
+# folds into the per-IP aggregate only.
_LOGIN_MAX_BUCKETS = 4096
# Unrepresentable as a real username (leading NUL); folds unknown-user attempts
-# into one slot so attacker cardinality cannot blow the bucket dict.
+# into one slot so attacker cardinality can't blow the bucket dict.
_UNKNOWN_LOGIN_USER = "\x00unknown-user"
def _trust_forwarded_for() -> bool:
"""Honour X-Forwarded-For only when UNSLOTH_STUDIO_TRUST_FORWARDED is set.
- Off by default so a direct caller cannot spoof the header.
+ Off by default so a direct caller can't spoof the header.
"""
return os.environ.get("UNSLOTH_STUDIO_TRUST_FORWARDED", "").lower() in (
"1",
@@ -112,7 +112,7 @@ def _normalize_forwarded_addr(value: str) -> str:
return ""
host = value[1:end]
elif value.count(":") == 1:
- # IPv4:port. Bare IPv6 has multiple colons and takes the else branch.
+ # IPv4:port. Bare IPv6 has multiple colons → else branch.
head, _, tail = value.rpartition(":")
host = head if tail.isdigit() and head else value
else:
@@ -144,7 +144,7 @@ def _client_ip(request: Request | None) -> str:
return normalized
fwd = request.headers.get("forwarded", "")
if fwd:
- # First element only -- multi-element headers cannot fork buckets.
+ # First element only; multi-element headers can't fork buckets.
normalized = _forwarded_for_from_element(fwd.split(",", 1)[0])
if normalized:
return normalized
@@ -190,7 +190,7 @@ def _record_login_failure(key: tuple[str, str]) -> int:
_prune_bucket(account_bucket, now)
account_bucket.append(now)
return len(account_bucket)
- # Bucket dict is at its cap; per-IP cap still applies via ip_bucket.
+ # Bucket dict at cap; per-IP cap still applies via ip_bucket.
return len(ip_bucket)
@@ -242,16 +242,16 @@ async def login(payload: AuthLoginRequest, request: Request) -> Token:
if blocked_for > 0:
raise HTTPException(
status_code = status.HTTP_429_TOO_MANY_REQUESTS,
- # IP is intentionally not interpolated into the body; behind a
- # proxy or NAT it is either misleading or an info leak.
+ # IP not interpolated into the body; behind a proxy/NAT it's
+ # misleading or an info leak.
detail = (f"Too many failed login attempts. " f"Try again in {blocked_for} seconds."),
headers = {"Retry-After": str(blocked_for)},
)
record = storage.get_user_and_secret(payload.username)
if record is None:
- # Record under a single sentinel key per IP so attacker-controlled
- # username cardinality does not allocate buckets without bound.
+ # Record under one sentinel key per IP so attacker-controlled username
+ # cardinality can't allocate unbounded buckets.
_record_login_failure(unknown_key)
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 68d2c67ec8a..8496c970d01 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -189,21 +189,20 @@ class ChatMessagesBatchResponse(BaseModel):
class ChatImportLedgerResponse(BaseModel):
- # Plain list of legacy thread ids. Keeping the payload key-less keeps
- # the client diff to a single Set construction.
+ # Plain list of legacy thread ids; key-less payload keeps the client diff
+ # to a single Set construction.
threadIds: list[str]
class ChatImportLedgerRecordRequest(BaseModel):
- # 10k cap keeps the request body bounded; real users have << 1k threads.
+ # 10k cap bounds the request body; real users have << 1k threads.
threadIds: list[str] = Field(default_factory = list, max_length = 10_000)
class ChatImportLedgerRecordResponse(BaseModel):
# accepted: deduped non-empty input count. inserted: rows actually new
# (ON CONFLICT DO NOTHING skips already-recorded ids). The client uses
- # `accepted >= 0` as the "endpoint exists" signal and ignores the split
- # otherwise.
+ # `accepted >= 0` as the "endpoint exists" signal and ignores the split.
accepted: int
inserted: int
@@ -353,7 +352,7 @@ async def batch_thread_messages(
payload: ChatMessagesBatchRequest, current_subject: str = Depends(get_current_subject)
):
"""One round-trip per sidebar/search rebuild instead of N. Unknown thread
- ids are returned as empty lists so callers don't need a pre-flight."""
+ ids return empty lists so callers don't need a pre-flight."""
by_thread: dict[str, list[ChatMessage]] = {tid: [] for tid in payload.threadIds}
for m in list_chat_messages_for_threads(payload.threadIds):
tid = m["threadId"]
@@ -444,11 +443,10 @@ async def count_threads(current_subject: str = Depends(get_current_subject)):
@router.get("/import-ledger", response_model = ChatImportLedgerResponse)
async def get_import_ledger(current_subject: str = Depends(get_current_subject)):
- """Legacy-Dexie import ledger. Returns the set of legacy thread ids
- already copied into chat_threads / chat_messages. The frontend
- uses this on every fresh tab open to decide whether to re-run the
- Dexie -> studio.db import. Source of truth lives inside studio.db
- so a studio.db wipe makes the import recoverable."""
+ """Legacy-Dexie import ledger. Returns the legacy thread ids already copied
+ into chat_threads / chat_messages. The frontend uses this on every fresh tab
+ open to decide whether to re-run the Dexie -> studio.db import. Source of
+ truth lives in studio.db, so a studio.db wipe makes the import recoverable."""
return ChatImportLedgerResponse(threadIds = list_chat_legacy_imports())
@@ -480,8 +478,8 @@ async def put_settings(
parsed = ChatSettingsPayload.model_validate(payload)
except ValidationError as exc:
raise HTTPException(status_code = 400, detail = exc.errors()) from exc
- # Atomic read + deep-merge + write inside one BEGIN IMMEDIATE so two
- # concurrent slider drags can't drop each other's updates.
+ # Atomic read + deep-merge + write in one BEGIN IMMEDIATE so concurrent
+ # slider drags can't drop each other's updates.
try:
return ChatSettingsResponse(
settings = upsert_chat_settings_merge(parsed.model_dump(exclude_unset = True))
diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.py
index a2d41f87b02..01991cd8656 100644
--- a/studio/backend/routes/data_recipe/jobs.py
+++ b/studio/backend/routes/data_recipe/jobs.py
@@ -36,14 +36,14 @@ def _resolve_local_v1_endpoint(request: Request) -> str:
"""Return the loopback /v1 URL for the actual backend listen port.
Resolution order:
- 1. ``app.state.server_port`` - explicitly published by run.py after
- the uvicorn server has bound. This is the most reliable source
- because it survives reverse proxies, TLS terminators and tunnels.
+ 1. ``app.state.server_port`` - published by run.py after uvicorn
+ binds. Most reliable; survives reverse proxies, TLS terminators,
+ and tunnels.
2. ``request.scope["server"]`` - the real (host, port) tuple uvicorn
- sets when the request is dispatched. Used when Studio is started
- outside ``run_server`` (e.g. ``uvicorn studio.backend.main:app``).
- 3. ``request.base_url`` parsed - last resort for test fixtures that
- do not route through a live uvicorn server.
+ sets per request. Used when Studio starts outside ``run_server``
+ (e.g. ``uvicorn studio.backend.main:app``).
+ 3. ``request.base_url`` parsed - last resort for test fixtures with
+ no live uvicorn server.
"""
port: Any = getattr(request.app.state, "server_port", None)
if not isinstance(port, int) or port <= 0:
@@ -76,14 +76,14 @@ def _request_has_desktop_access_token(request: Request) -> bool:
def _used_llm_model_aliases(recipe: dict[str, Any]) -> set[str]:
- """Return the set of model_aliases that are actually referenced by an
- LLM column. Used to narrow the "Chat model loaded" gate so that orphan
- model_config nodes on the canvas do not block unrelated recipe runs.
+ """Return model_aliases actually referenced by an LLM column. Narrows
+ the "Chat model loaded" gate so orphan model_config nodes on the canvas
+ do not block unrelated recipe runs.
- The ``llm-`` prefix matches the existing convention in
+ The ``llm-`` prefix matches the convention in
``core/data_recipe/service.py::_recipe_has_llm_columns`` and covers all
- LLM column types emitted by the frontend (llm-text, llm-code,
- llm-structured, llm-judge).
+ frontend LLM column types (llm-text, llm-code, llm-structured,
+ llm-judge).
"""
aliases: set[str] = set()
for column in recipe.get("columns", []):
@@ -180,18 +180,17 @@ def _ensure_selected_local_model_loaded(
def _inject_local_structured_response_format(
recipe: dict[str, Any], local_provider_names: set[str]
) -> None:
- """For each llm-structured column that targets a local-provider model_config,
- clone the model_config and inject an OpenAI ``response_format`` with the
- column's ``output_format`` JSON schema. The column is rewritten to point at
- the clone so llm-text / llm-judge columns that share the same alias keep
- free-form sampling.
+ """For each llm-structured column targeting a local-provider model_config,
+ clone the config and inject an OpenAI ``response_format`` with the
+ column's ``output_format`` JSON schema. The column is repointed at the
+ clone so llm-text / llm-judge columns sharing the alias keep free-form
+ sampling.
Without this, data_designer only injects a prompt-level "return JSON in a
- ```json fence" instruction. Small GGUF models frequently break format,
- wasting the full ``max_tokens`` budget per row and then failing to parse.
- Forwarding ``response_format`` lets llama-server apply grammar-constrained
- sampling from the JSON schema, which guarantees a parseable response and
- terminates early.
+ ```json fence" instruction. Small GGUFs often break format, wasting the
+ full ``max_tokens`` budget per row and then failing to parse. Forwarding
+ ``response_format`` lets llama-server apply grammar-constrained sampling
+ from the schema, guaranteeing a parseable response and terminating early.
"""
columns = recipe.get("columns")
model_configs = recipe.get("model_configs")
@@ -210,8 +209,8 @@ def _inject_local_structured_response_format(
return
# Clone per (alias, column) so each llm-structured column gets its own
- # schema without leaking response_format onto other columns that share the
- # same base alias.
+ # schema without leaking response_format onto other columns sharing the
+ # base alias.
seen_clone_aliases: set[str] = {
mc.get("alias") for mc in model_configs if isinstance(mc.get("alias"), str)
}
@@ -243,15 +242,14 @@ def _inject_local_structured_response_format(
if not isinstance(params, dict):
params = {}
clone["inference_parameters"] = params
- # data_designer's BaseInferenceParams is a pydantic model with
- # extra="forbid", so response_format cannot sit at the top level of
- # inference_parameters. It does expose an `extra_body: dict` pass-
- # through that the OpenAI client spreads into the request body at the
- # top level, which is where llama-server reads response_format from.
- # llama.cpp server shape (tools/server/README.md): the schema sits
- # directly under response_format, not nested in a json_schema object
- # the way OpenAI's Chat Completions API expects. llama-server converts
- # the schema to a GBNF grammar and applies it during sampling.
+ # data_designer's BaseInferenceParams is pydantic extra="forbid", so
+ # response_format cannot sit at the top level of inference_parameters.
+ # Its `extra_body: dict` passthrough is spread into the request body
+ # top level by the OpenAI client, where llama-server reads
+ # response_format. llama.cpp server shape (tools/server/README.md):
+ # the schema sits directly under response_format, not nested in a
+ # json_schema object like OpenAI's Chat Completions API expects.
+ # llama-server converts the schema to a GBNF grammar for sampling.
extra_body = params.get("extra_body")
if not isinstance(extra_body, dict):
extra_body = {}
@@ -269,21 +267,21 @@ def _inject_local_structured_response_format(
def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optional[int]:
"""
- Mutate recipe dict in-place: for any provider with is_local=True,
- fill in the endpoint pointing at this server and inject a short-lived
- internal sk-unsloth-* API key for workflow auth.
+ Mutate recipe dict in-place: for any provider with is_local=True, set
+ the endpoint to this server and inject a short-lived internal
+ sk-unsloth-* API key for workflow auth.
- Returns the row id of the minted internal key (so the caller can
- revoke it on job completion) or ``None`` when no local provider is
- actually reachable from an LLM column.
+ Returns the row id of the minted internal key (for the caller to revoke
+ on job completion) or ``None`` when no local provider is reachable from
+ an LLM column.
"""
providers = recipe.get("model_providers")
if not providers:
return None
- # Collect local providers and pop is_local from ALL dicts unconditionally.
- # Strict `is True` guard so malformed payloads (is_local: 1,
- # is_local: "true") do not accidentally trigger the loopback rewrite.
+ # Collect local providers and pop is_local from ALL dicts. Strict
+ # `is True` guard so malformed payloads (is_local: 1, is_local: "true")
+ # do not trigger the loopback rewrite.
local_indices: list[int] = []
for i, provider in enumerate(providers):
if not isinstance(provider, dict):
@@ -297,10 +295,10 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona
endpoint = _resolve_local_v1_endpoint(request)
- # Only gate on model-loaded if a local provider is actually reachable
- # from an LLM column through a model_config. Orphan model_config nodes
- # that reference a local provider but that no LLM column uses should
- # not block runs; the recipe would never call /v1 for them.
+ # Only gate on model-loaded if a local provider is reachable from an LLM
+ # column via a model_config. Orphan model_config nodes referencing a
+ # local provider that no LLM column uses should not block runs; the
+ # recipe would never call /v1 for them.
local_names = {providers[i].get("name") for i in local_indices if providers[i].get("name")}
used_aliases = _used_llm_model_aliases(recipe)
referenced_providers = {
@@ -313,19 +311,19 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona
internal_key_id: Optional[int] = None
if local_names & referenced_providers:
# Verify the selected local model is loaded before minting a workflow
- # key. This still remains a point-in-time singleton-backend check
- # (TOCTOU): a future generation token should bind frontend load and
- # job creation, and the inference endpoint returns a clear 400 if the
- # model is later unloaded or swapped before the subprocess calls /v1.
+ # key. Still a point-in-time singleton-backend check (TOCTOU): a
+ # future generation token should bind frontend load to job creation;
+ # the inference endpoint returns a clear 400 if the model is unloaded
+ # or swapped before the subprocess calls /v1.
_ensure_selected_local_model_loaded(recipe, local_names)
from auth import storage # deferred: avoids circular import
- # Mint an internal sk-unsloth-* key scoped to this workflow run.
- # Uses the unified API-key issuance path (one mint/revoke/verify
- # surface instead of a second JWT code path). The key is marked
- # internal so it is hidden from the user's API-key list, and the
- # caller revokes it when the job terminates.
+ # Mint an internal sk-unsloth-* key scoped to this workflow run via
+ # the unified API-key issuance path (one mint/revoke/verify surface
+ # instead of a second JWT code path). Marked internal so it is hidden
+ # from the user's API-key list; the caller revokes it when the job
+ # terminates.
expires_at = (datetime.now(timezone.utc) + timedelta(hours = 24)).isoformat()
token, row = storage.create_api_key(
username = "unsloth",
@@ -335,11 +333,11 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona
)
internal_key_id = int(row["id"])
- # Defensively strip any stale "external"-only fields the frontend may
- # have left on the dict (extra_headers/extra_body/api_key_env). The UI
- # hides these inputs in local mode but the payload builder still serializes
- # them, so a previously external provider that flipped to local can carry
- # invalid JSON or rogue auth headers into the local /v1 call.
+ # Strip stale "external"-only fields the frontend may have left
+ # (extra_headers/extra_body/api_key_env). The UI hides these in local
+ # mode but the payload builder still serializes them, so a provider
+ # flipped from external to local could carry invalid JSON or rogue auth
+ # headers into the local /v1 call.
for i in local_indices:
providers[i]["endpoint"] = endpoint
providers[i]["api_key"] = token
@@ -348,29 +346,27 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona
providers[i].pop("extra_headers", None)
providers[i].pop("extra_body", None)
- # Force skip_health_check on any model_config that references a local
- # provider. The frontend now sends the explicit selected local model id,
- # but llama-server's /v1/models response can still differ from that id
- # for local paths, cache aliases, and GGUF variant loads. The recipe run
- # has already gated on a loaded local inference backend above, so the
- # data_designer model-list health check would be redundant and can reject
- # valid local selections.
+ # Force skip_health_check on any model_config referencing a local
+ # provider. The frontend sends the explicit selected local model id, but
+ # llama-server's /v1/models response can differ from it for local paths,
+ # cache aliases, and GGUF variant loads. The run already gated on a
+ # loaded local backend above, so data_designer's model-list health check
+ # would be redundant and can reject valid local selections.
for mc in recipe.get("model_configs", []):
if not isinstance(mc, dict):
continue
if mc.get("provider") in local_names:
mc["skip_health_check"] = True
# Disable thinking for data-recipe inference on local providers.
- # Reasoning models emit a <think>...</think> preamble before the
- # answer, which roughly doubles generated token count per row and
- # pushes the visible answer past data_designer's json-fence
- # regex. Forward chat_template_kwargs={enable_thinking: False}
- # through the OpenAI SDK's extra_body passthrough so llama-server
- # renders the template without the reasoning preamble. Free-form
- # llm-text columns benefit from the latency cut, and structured
- # columns also stop leaking think tags into the grammar-
- # constrained JSON (llama-server's GBNF path still enforces the
- # schema either way).
+ # Reasoning models emit a <think>...</think> preamble that roughly
+ # doubles generated tokens per row and pushes the answer past
+ # data_designer's json-fence regex. Forward
+ # chat_template_kwargs={enable_thinking: False} via the OpenAI
+ # SDK's extra_body passthrough so llama-server renders the
+ # template without the preamble. llm-text columns get the latency
+ # cut; structured columns stop leaking think tags into the
+ # grammar-constrained JSON (GBNF still enforces the schema either
+ # way).
params = mc.get("inference_parameters")
if not isinstance(params, dict):
params = {}
@@ -387,7 +383,7 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona
# Forward each llm-structured column's output_format as an OpenAI
# response_format so llama-server uses grammar-constrained sampling and
- # small GGUFs stop wasting the full max_tokens budget on broken JSON.
+ # small GGUFs stop wasting the max_tokens budget on broken JSON.
_inject_local_structured_response_format(recipe, local_names)
return internal_key_id
@@ -446,11 +442,11 @@ def create_job(payload: RecipePayload, request: Request):
log = logger,
) from exc
- # Single try block covers get_job_manager() AND mgr.start() so a workflow
- # key minted above never outlives the request even when an unexpected
+ # Single try covers get_job_manager() AND mgr.start() so a minted
+ # workflow key never outlives the request even on an unexpected
# exception type (TypeError from a stale kwarg, OSError from a queue
- # write, etc.) bubbles up. Without the bare except, such exceptions let
- # the sk-unsloth-* key live until its 24h TTL.
+ # write, etc.). Without the bare except, those would let the
+ # sk-unsloth-* key live until its 24h TTL.
try:
mgr = get_job_manager()
job_id = mgr.start(
@@ -488,7 +484,7 @@ def create_job(payload: RecipePayload, request: Request):
def _revoke_internal_api_key_safe(key_id: int) -> None:
"""Best-effort revoke of a workflow-minted key; swallow any error so
- that revocation failures never mask the caller's own error path."""
+ revocation failures never mask the caller's own error path."""
try:
from auth import storage # deferred: avoids circular import
storage.revoke_internal_api_key(key_id)
diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.py
index 63685859327..848ed7d5571 100644
--- a/studio/backend/routes/data_recipe/seed.py
+++ b/studio/backend/routes/data_recipe/seed.py
@@ -394,7 +394,7 @@ def inspect_seed_dataset(payload: SeedInspectRequest) -> SeedInspectResponse:
def _extract_text_from_file(file_path: Path, ext: str) -> str:
- """Extract text from uploaded file based on extension, converting to markdown where possible."""
+ """Extract text from an uploaded file by extension, to markdown where possible."""
if ext in {".txt", ".md"}:
raw = file_path.read_text(encoding = "utf-8", errors = "ignore")
elif ext == ".pdf":
@@ -581,7 +581,7 @@ def inspect_seed_upload(payload: SeedInspectUploadRequest) -> SeedInspectRespons
seed_source_type = _normalize_optional_text(payload.seed_source_type) or "local"
filename = _sanitize_filename(payload.filename)
ext = Path(filename).suffix.lower()
- # Legacy single-file unstructured path only supports .txt/.md
+ # Legacy single-file unstructured path supports only .txt/.md;
# PDF/DOCX extraction uses the multi-file upload endpoint instead
_LEGACY_UNSTRUCTURED_EXTS = {".txt", ".md"}
if seed_source_type == "unstructured":
diff --git a/studio/backend/routes/data_recipe/validate.py b/studio/backend/routes/data_recipe/validate.py
index e26093d6bfb..732fa902d64 100644
--- a/studio/backend/routes/data_recipe/validate.py
+++ b/studio/backend/routes/data_recipe/validate.py
@@ -121,9 +121,8 @@ def _collect_validation_errors(recipe: dict[str, Any]) -> list[ValidateError]:
def _patch_local_providers(recipe: dict[str, Any]) -> None:
"""Strip is_local and fill a dummy endpoint so validation doesn't choke.
- Uses a strict `is True` check to match _inject_local_providers in
- jobs.py - malformed payloads with truthy but non-boolean is_local
- values should not be treated as local.
+ Strict `is True` check matches _inject_local_providers in jobs.py:
+ truthy but non-boolean is_local values are not treated as local.
"""
for provider in recipe.get("model_providers", []):
if not isinstance(provider, dict):
@@ -152,13 +151,12 @@ def validate(payload: RecipePayload) -> ValidateResponse:
build_config_builder(recipe)
except ModuleNotFoundError as exc:
# data_designer is an optional runtime dep. Static validation
- # already passed; live access + full config validation are
- # deferred to run start (per _GITHUB_VALIDATE_NOTE), so a missing
- # optional import at validate time should not block the recipe.
- # Restrict the bypass to the data_designer module specifically so
- # other ImportErrors (e.g. broken internal imports or missing
- # transitive deps after a package upgrade) still surface as
- # validation failures instead of being silently swallowed.
+ # passed; live access + full config validation are deferred to
+ # run start (per _GITHUB_VALIDATE_NOTE), so a missing optional
+ # import here should not block the recipe. Restrict the bypass to
+ # the data_designer module so other ImportErrors (broken internal
+ # imports, missing transitive deps after an upgrade) still surface
+ # as validation failures instead of being swallowed.
if not (exc.name or "").startswith("data_designer"):
raise
logger.debug(
diff --git a/studio/backend/routes/datasets.py b/studio/backend/routes/datasets.py
index 711e9723d52..1bf035b6843 100644
--- a/studio/backend/routes/datasets.py
+++ b/studio/backend/routes/datasets.py
@@ -45,9 +45,9 @@ def _get_dataset_size_cached(repo_id: str) -> int:
def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
"""Pick the most useful on-disk path for a HF cache repo dir.
- Mirrors the helper in routes/models.py: prefer the most-recent
- snapshot dir, fall back to the cache repo root, return resolved
- realpath. Duplicated here to keep routes/datasets.py self-contained.
+ Mirrors routes/models.py: prefer the most-recent snapshot dir, else the
+ cache repo root, returned as a resolved realpath. Duplicated here to keep
+ routes/datasets.py self-contained.
"""
try:
snapshots_dir = repo_dir / "snapshots"
@@ -61,12 +61,12 @@ def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
return None
-# Add backend directory to path
+# Add backend directory to path.
backend_path = Path(__file__).parent.parent.parent
if str(backend_path) not in sys.path:
sys.path.insert(0, str(backend_path))
-# Import dataset utilities
+# Import dataset utilities.
from utils.datasets import check_dataset_format
from utils.upload_limits import get_upload_limit_bytes, get_upload_limit_label
from auth.authentication import get_current_subject
@@ -93,7 +93,7 @@ from utils.paths import (
def _serialize_preview_value(value):
- """make it json safe for client preview ⊂(◉‿◉)つ"""
+ """Make a value JSON-safe for the client preview."""
if value is None or isinstance(value, (str, int, float, bool)):
return value
@@ -130,10 +130,10 @@ def _serialize_preview_rows(rows):
# --- Endpoints ---
-# Recognized data-file extensions for the single-file fallback approach.
-# Tabular formats are preferred over archives for Tier 1 preview because
-# archives (e.g. images.zip) may be loaded as ImageFolder datasets with
-# synthetic columns (image/label) that don't match the real dataset schema.
+# Recognized data-file extensions for the single-file fallback.
+# Tier 1 preview prefers tabular over archives: archives (e.g. images.zip) can
+# load as ImageFolder datasets with synthetic image/label columns that don't
+# match the real schema.
_TABULAR_EXTS = (".parquet", ".json", ".jsonl", ".csv", ".tsv", ".arrow")
_ARCHIVE_EXTS = (".tar", ".tar.gz", ".tgz", ".gz", ".zst", ".zip", ".txt")
DATA_EXTS = _TABULAR_EXTS + _ARCHIVE_EXTS
@@ -331,9 +331,9 @@ async def upload_dataset(
stored_name = f"{uuid4().hex}_{stem}{ext}"
stored_path = DATASET_UPLOAD_DIR / stored_name
- # Stream file to disk in chunks to avoid holding entire file in memory.
- # Keep a route-level cap so users get a clear training-dataset-specific
- # error and oversized partial files are not left in the Studio uploads directory.
+ # Stream to disk in chunks to avoid holding the whole file in memory. The
+ # route-level cap gives a clear training-dataset error and avoids leaving
+ # oversized partial files in the Studio uploads directory.
upload_limit_bytes = get_upload_limit_bytes()
total_bytes = 0
upload_complete = False
@@ -378,12 +378,10 @@ async def get_dataset_download_progress(
"""Return download progress for a HuggingFace dataset repo.
Mirrors ``GET /api/models/download-progress`` but scans the
- ``datasets--owner--name`` cache directory under HF_HUB_CACHE.
- Modern ``datasets``/``huggingface_hub`` caches both raw model and
- raw dataset blobs in HF_HUB_CACHE; the ``datasets`` library writes
- its processed Arrow shards elsewhere, but the in-progress *download*
- bytes are observable here. Returns ``cache_path`` so the UI can
- show users where the dataset blobs landed on disk.
+ ``datasets--owner--name`` cache directory under HF_HUB_CACHE. Modern
+ ``datasets``/``huggingface_hub`` cache raw dataset blobs there (processed
+ Arrow shards live elsewhere, but in-progress *download* bytes are visible
+ here). Returns ``cache_path`` so the UI can show where blobs landed.
"""
_empty = {
"downloaded_bytes": 0,
@@ -433,9 +431,9 @@ async def get_dataset_download_progress(
"cache_path": cache_path,
}
- # Same 95% completion threshold as the model endpoint -- HF blob
- # dedup makes completed_bytes drift slightly under expected_bytes,
- # and inter-file gaps would otherwise look like "done".
+ # Same 95% completion threshold as the model endpoint -- HF blob dedup
+ # makes completed_bytes drift slightly under expected_bytes, and
+ # inter-file gaps would otherwise look "done".
if completed_bytes >= expected_bytes * 0.95:
progress = 1.0
else:
@@ -456,15 +454,13 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(get
"""
Check if a dataset requires manual column mapping.
- Strategy for HuggingFace datasets:
- 1. list_repo_files → pick the first data file → load_dataset(data_files=[…])
+ HuggingFace strategy:
+ 1. list_repo_files → first data file → load_dataset(data_files=[…]).
Avoids resolving thousands of files; typically ~2-4 s.
2. Full streaming load_dataset as a last-resort fallback.
- Local files are loaded directly.
-
- Using a plain `def` (not async) so FastAPI runs this in a thread-pool,
- preventing any blocking IO from freezing the event loop.
+ Local files load directly. Plain `def` (not async) so FastAPI runs it in a
+ thread-pool, keeping blocking IO off the event loop.
"""
try:
from itertools import islice
@@ -502,14 +498,14 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(get
)
data_files = [f for f in repo_files if any(f.endswith(ext) for ext in DATA_EXTS)]
- # Prefer tabular formats over archives (e.g. images.zip → ImageFolder
- # with synthetic image/label columns that don't match the real schema).
+ # Prefer tabular over archives (e.g. images.zip → ImageFolder
+ # with synthetic image/label columns not in the real schema).
tabular_files = [
f for f in data_files if any(f.endswith(ext) for ext in _TABULAR_EXTS)
]
candidates = tabular_files or data_files
- # When a subset is specified, narrow to files whose name matches
+ # With a subset, narrow to files whose name matches
# (e.g. subset="testmini" → prefer "testmini.parquet").
if request.subset and candidates:
subset_matches = [f for f in candidates if request.subset in Path(f).stem]
@@ -560,26 +556,26 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(get
preview_slice = Dataset.from_list(rows)
total_rows = None
- # Run lightweight format check on the preview slice
+ # Lightweight format check on the preview slice.
result = check_dataset_format(preview_slice, is_vlm = request.is_vlm)
logger.info(
f"Format check result: requires_mapping={result['requires_manual_mapping']}, format={result['detected_format']}, is_image={result.get('is_image', False)}"
)
- # Generate preview samples
+ # Generate preview samples.
preview_samples = None
if not result["requires_manual_mapping"]:
if result.get("suggested_mapping"):
# Heuristic-detected: show raw data so columns match the API response.
- # Processing (column stripping) happens at training time, not preview.
+ # Column stripping happens at training time, not preview.
preview_samples = _serialize_preview_rows(preview_slice)
else:
try:
format_result = format_dataset(
preview_slice,
format_type = "auto",
- num_proc = None, # Only 10 preview rows -- no need for multiprocessing
+ num_proc = None, # Only 10 preview rows -- no multiprocessing needed
)
processed = format_result["dataset"]
preview_samples = _serialize_preview_rows(processed)
@@ -589,7 +585,7 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(get
else:
preview_samples = _serialize_preview_rows(preview_slice)
- # Collect warnings: from check_dataset_format + URL-based image detection
+ # Collect warnings from check_dataset_format + URL-based image detection.
warning = result.get("warning")
image_col = result.get("detected_image_column")
if image_col and image_col in (result.get("columns") or []):
@@ -636,17 +632,17 @@ def ai_assist_mapping(
"""
Run LLM-assisted dataset conversion advisor (user-triggered).
- Multi-pass analysis using a 7B helper model:
- Pass 1: Classify dataset type from HF card + samples
- Pass 2: Generate conversion strategy (system prompt, templates)
- Pass 3: Validate conversion quality
+ Multi-pass analysis with a 7B helper model:
+ Pass 1: Classify dataset type from HF card + samples.
+ Pass 2: Generate conversion strategy (system prompt, templates).
+ Pass 3: Validate conversion quality.
Falls back to simple column classification if the advisor fails.
"""
try:
from utils.datasets.llm_assist import llm_conversion_advisor
- # Truncate sample values for the LLM prompt
+ # Truncate sample values for the LLM prompt.
truncated = [
{col: str(s.get(col, ""))[:200] for col in request.columns} for s in request.samples[:5]
]
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 302d5348747..d687a22f8ed 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -1,9 +1,7 @@
# 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 API routes: checkpoint discovery and model export operations.
-"""
+"""Export API routes: checkpoint discovery and model export operations."""
import asyncio
import json
@@ -28,7 +26,7 @@ from auth.authentication import get_current_subject
from utils.utils import safe_error_detail
-# Import backend functions
+# Backend functions
try:
from core.export import get_export_backend
except ImportError:
@@ -37,7 +35,7 @@ except ImportError:
sys.path.insert(0, str(parent_backend))
from core.export import get_export_backend
-# Import Pydantic models
+# Pydantic models
from models import (
LoadCheckpointRequest,
ExportStatusResponse,
@@ -56,16 +54,12 @@ logger = get_logger(__name__)
async def load_checkpoint(
request: LoadCheckpointRequest, current_subject: str = Depends(get_current_subject)
):
- """
- Load a checkpoint into the export backend.
-
- Wraps ExportBackend.load_checkpoint.
- """
+ """Load a checkpoint into the export backend (ExportBackend.load_checkpoint)."""
try:
- # Version switching is handled automatically by the subprocess-based
- # export backend — no need for ensure_transformers_version() here.
+ # The subprocess-based export backend handles version switching
+ # automatically — no ensure_transformers_version() needed here.
- # Free GPU memory: shut down any running inference/training subprocesses
+ # Free GPU memory: shut down running inference/training subprocesses
# before loading the export checkpoint (they'd compete for VRAM).
try:
from core.inference import get_inference_backend
@@ -87,8 +81,8 @@ async def load_checkpoint(
if trn.is_training_active():
logger.info("Stopping active training to free GPU memory for export")
trn.stop_training()
- # Wait for training subprocess to actually exit before proceeding,
- # otherwise it may still hold GPU memory when export tries to load.
+ # Wait for the training subprocess to exit; else it may still
+ # hold GPU memory when export tries to load.
for _ in range(60): # up to 30s
if not trn.is_training_active():
break
@@ -101,8 +95,8 @@ async def load_checkpoint(
backend = get_export_backend()
# load_checkpoint spawns and waits on a subprocess and can take
- # minutes. Run it in a worker thread so the event loop stays
- # free to serve the live log SSE stream concurrently.
+ # minutes. Run it in a worker thread so the event loop stays free
+ # to serve the live log SSE stream concurrently.
success, message = await asyncio.to_thread(
backend.load_checkpoint,
checkpoint_path = request.checkpoint_path,
@@ -127,11 +121,7 @@ async def load_checkpoint(
@router.post("/cleanup", response_model = ExportOperationResponse)
async def cleanup_export_memory(current_subject: str = Depends(get_current_subject)):
- """
- Cleanup export-related models from memory (GPU/CPU).
-
- Wraps ExportBackend.cleanup_memory.
- """
+ """Cleanup export-related models from memory (ExportBackend.cleanup_memory)."""
try:
backend = get_export_backend()
success = await asyncio.to_thread(backend.cleanup_memory)
@@ -158,9 +148,7 @@ async def cleanup_export_memory(current_subject: str = Depends(get_current_subje
@router.get("/status", response_model = ExportStatusResponse)
async def get_export_status(current_subject: str = Depends(get_current_subject)):
- """
- Get current export backend status (loaded checkpoint, model type, PEFT flag).
- """
+ """Get export backend status (loaded checkpoint, model type, PEFT flag)."""
try:
backend = get_export_backend()
return ExportStatusResponse(
@@ -177,7 +165,7 @@ async def get_export_status(current_subject: str = Depends(get_current_subject))
def _export_details(output_path: Optional[str]) -> Optional[Dict[str, Any]]:
- """Return the export path relative to exports_root so the install path is not leaked."""
+ """Return the export path relative to exports_root, hiding the install path."""
if not output_path:
return None
try:
@@ -195,8 +183,7 @@ def _export_details(output_path: Optional[str]) -> Optional[Dict[str, Any]]:
async def export_merged_model(
request: ExportMergedModelRequest, current_subject: str = Depends(get_current_subject)
):
- """
- Export a merged PEFT model (e.g., 16-bit or 4-bit) and optionally push to Hub.
+ """Export a merged PEFT model (16-bit or 4-bit), optionally pushing to Hub.
Wraps ExportBackend.export_merged_model.
"""
@@ -234,8 +221,7 @@ async def export_merged_model(
async def export_base_model(
request: ExportBaseModelRequest, current_subject: str = Depends(get_current_subject)
):
- """
- Export a non-PEFT base model and optionally push to Hub.
+ """Export a non-PEFT base model, optionally pushing to Hub.
Wraps ExportBackend.export_base_model.
"""
@@ -273,8 +259,7 @@ async def export_base_model(
async def export_gguf(
request: ExportGGUFRequest, current_subject: str = Depends(get_current_subject)
):
- """
- Export the current model to GGUF format and optionally push to Hub.
+ """Export the current model to GGUF format, optionally pushing to Hub.
Wraps ExportBackend.export_gguf.
"""
@@ -311,8 +296,7 @@ async def export_gguf(
async def export_lora_adapter(
request: ExportLoRAAdapterRequest, current_subject: str = Depends(get_current_subject)
):
- """
- Export only the LoRA adapter (if the loaded model is PEFT).
+ """Export only the LoRA adapter (if the loaded model is PEFT).
Wraps ExportBackend.export_lora_adapter.
"""
@@ -349,18 +333,18 @@ async def export_lora_adapter(
# Live export log stream (Server-Sent Events)
# ─────────────────────────────────────────────────────────────────────
#
-# The export worker subprocess redirects its stdout/stderr into a pipe
-# that a reader thread forwards to the orchestrator as log entries (see
+# The export worker subprocess redirects its stdout/stderr into a pipe a
+# reader thread forwards to the orchestrator as log entries (see
# core/export/worker.py::_setup_log_capture and
-# core/export/orchestrator.py::_append_log). This endpoint streams
-# those entries to the browser so the export dialog can show a live
-# terminal-style output panel while load_checkpoint / export_merged /
-# export_gguf / export_lora / export_base run.
+# core/export/orchestrator.py::_append_log). This endpoint streams those
+# entries to the browser so the export dialog shows a live terminal-style
+# panel while load_checkpoint / export_merged / export_gguf / export_lora /
+# export_base run.
#
# Shape follows the training progress SSE endpoint
-# (routes/training.py::stream_training_progress): each event carries
-# `id`, `event`, and `data` fields, the stream starts with a `retry:`
-# directive, and `Last-Event-ID` is honored on reconnect.
+# (routes/training.py::stream_training_progress): each event carries `id`,
+# `event`, `data` fields, the stream starts with a `retry:` directive, and
+# `Last-Event-ID` is honored on reconnect.
def _format_sse(
@@ -389,28 +373,26 @@ async def stream_export_logs(
current_subject: str = Depends(get_current_subject),
):
"""
- Stream live stdout/stderr output from the export worker subprocess
- as Server-Sent Events.
+ Stream live stdout/stderr from the export worker subprocess as
+ Server-Sent Events.
Events:
- `log` : a single log line (data: {"stream","line","ts"})
- `heartbeat`: periodic keepalive when no new lines are available
- - `complete` : emitted once the export worker is idle and no new
- lines arrived for ~1 second. Clients should close.
+ - `complete` : once the worker is idle and no new lines arrived for
+ ~1 second. Clients should close.
- `error` : unrecoverable server-side error
- The `id:` field on each event is the log entry's monotonic seq
- number so the browser can resume via `Last-Event-ID` on reconnect.
+ Each event's `id:` field is the log entry's monotonic seq number so the
+ browser can resume via `Last-Event-ID` on reconnect.
"""
backend = get_export_backend()
- # Determine starting cursor. Explicit `since` wins, then
- # Last-Event-ID header on reconnect, otherwise start from the
- # run-start snapshot captured by clear_logs() so the client sees
- # every line emitted since the current run began -- even if the
- # SSE connection opened after the POST that kicked off the export.
- # Using get_current_log_seq() here would lose the early bootstrap
- # lines that arrive in the gap between POST and SSE connect.
+ # Starting cursor: explicit `since` wins, then Last-Event-ID header on
+ # reconnect, else the run-start snapshot from clear_logs() so the client
+ # sees every line since the run began -- even if the SSE connection
+ # opened after the POST that kicked off the export. get_current_log_seq()
+ # would lose the early bootstrap lines arriving between POST and connect.
last_event_id = request.headers.get("last-event-id")
if since is None and last_event_id is not None:
try:
@@ -425,8 +407,7 @@ async def stream_export_logs(
async def event_generator() -> AsyncGenerator[str, None]:
nonlocal cursor
- # Tell the browser to reconnect after 3 seconds if the
- # connection drops mid-export.
+ # Reconnect after 3 seconds if the connection drops mid-export.
yield "retry: 3000\n\n"
last_yield = time.monotonic()
@@ -460,9 +441,8 @@ async def stream_export_logs(
yield _format_sse("{}", event = "heartbeat")
last_yield = now
if not backend.is_export_active():
- # Give the reader thread a moment to drain any
- # trailing lines the worker process printed
- # just before signalling done.
+ # Give the reader thread a moment to drain trailing
+ # lines the worker printed just before signalling done.
if idle_since is None:
idle_since = now
elif now - idle_since > 1.0:
@@ -477,8 +457,8 @@ async def stream_export_logs(
await asyncio.sleep(0.1)
except asyncio.CancelledError:
- # Client disconnected mid-yield. Don't re-raise, just end
- # the generator cleanly so StreamingResponse finalizes.
+ # Client disconnected mid-yield. Don't re-raise; end the
+ # generator cleanly so StreamingResponse finalizes.
return
except Exception as exc:
logger.error("Export log stream failed: %s", exc, exc_info = True)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 70a9aa27d0a..86b4251d15d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -30,31 +30,27 @@ from utils.models import extract_model_size_b as _extract_model_size_b
def _install_httpcore_asyncgen_silencer() -> None:
"""Silence benign httpx/httpcore asyncgen GC noise on Python 3.13.
- When Studio proxies a streaming response from llama-server via httpx,
- the innermost ``HTTP11ConnectionByteStream.__aiter__`` async generator
- is finalised by Python's asyncgen GC hook on a task different from the
- one that opened it. Its ``aclose`` path then calls
- ``anyio.Lock.acquire`` → ``cancel_shielded_checkpoint`` which enters a
- ``CancelScope`` on the finaliser task — Python 3.13 flags the
- cross-task exit as ``"Attempted to exit cancel scope in a different
- task"`` and prints ``"async generator ignored GeneratorExit"`` as an
- unraisable warning.
-
- This is a known httpx + httpcore + anyio interaction (see MCP SDK
- python-sdk#831, agno #3556, chainlit #2361, langchain-mcp-adapters
- #254). It is benign: the response has already been delivered with a
- 200. The streaming pass-throughs (``/v1/chat/completions``,
- ``/v1/messages``, ``/v1/responses``, ``/v1/completions``) already
- manage their httpx lifecycle inside a single task with explicit
- ``aclose()`` of the lines iterator, response, and client; the errant
- generator is not one we hold a reference to and therefore cannot
- close ourselves.
-
- We install a single process-wide unraisable hook that swallows just
- this specific interaction — identified by the tuple of (RuntimeError
- mentioning cancel scope / GeneratorExit) + (object repr referencing
- HTTP11ConnectionByteStream) — and defers to the default hook for
- everything else. The filter is idempotent.
+ When Studio proxies a llama-server stream via httpx, the innermost
+ ``HTTP11ConnectionByteStream.__aiter__`` async generator is finalised by
+ the asyncgen GC hook on a task different from the one that opened it. Its
+ ``aclose`` calls ``anyio.Lock.acquire`` → ``cancel_shielded_checkpoint``,
+ entering a ``CancelScope`` on the finaliser task; Python 3.13 flags the
+ cross-task exit as ``"Attempted to exit cancel scope in a different task"``
+ and prints ``"async generator ignored GeneratorExit"`` as an unraisable
+ warning.
+
+ Known httpx + httpcore + anyio interaction (MCP SDK python-sdk#831, agno
+ #3556, chainlit #2361, langchain-mcp-adapters #254). Benign: the 200
+ response is already delivered. The streaming pass-throughs
+ (``/v1/chat/completions``, ``/v1/messages``, ``/v1/responses``,
+ ``/v1/completions``) manage their httpx lifecycle in one task with explicit
+ ``aclose()``; we don't hold a reference to the errant generator and can't
+ close it ourselves.
+
+ Install one process-wide unraisable hook that swallows only this
+ interaction -- identified by (RuntimeError mentioning cancel scope /
+ GeneratorExit) + (object repr referencing HTTP11ConnectionByteStream) --
+ and defers to the default hook otherwise. Idempotent.
"""
prior_hook = sys.unraisablehook
if getattr(prior_hook, "_unsloth_httpcore_silencer", False):
@@ -85,12 +81,10 @@ _install_httpcore_asyncgen_silencer()
def _friendly_error(exc: Exception) -> str:
"""Extract a user-friendly message from known llama-server errors."""
- # httpx transport-layer failures reaching the managed llama-server —
- # raised by the async pass-through helpers that talk to llama-server
- # directly. Treat any RequestError subclass (ConnectError, ReadError,
- # RemoteProtocolError, WriteError, PoolTimeout, ...) as "the upstream
- # subprocess is unreachable", which for Studio always means the
- # llama-server subprocess crashed or is still coming up.
+ # httpx transport failures from the async pass-through helpers. Any
+ # RequestError subclass (ConnectError, ReadError, RemoteProtocolError,
+ # WriteError, PoolTimeout, ...) means the llama-server subprocess is
+ # unreachable -- crashed or still coming up.
if isinstance(exc, httpx.RequestError):
return (
"Lost connection to the model server. It may have crashed -- try reloading the model."
@@ -372,10 +366,9 @@ async def artifact_preview_frame(
def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
- """Classify reasoning/tool capabilities via the GGUF classifier so
- flags match across backends. gpt-oss is overridden because Harmony
- routes reasoning and tools through tokenizer channels, not template
- markup."""
+ """Classify reasoning/tool capabilities via the GGUF classifier so flags
+ match across backends. gpt-oss is overridden: Harmony routes reasoning and
+ tools through tokenizer channels, not template markup."""
model_id = getattr(backend, "active_model_name", None)
flags = (
detect_reasoning_flags(
@@ -392,11 +385,11 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
"supports_tools": False,
}
)
- # Our safetensors loop only parses <tool_call>{json}</tool_call>
- # and <function=name>...</function>. Llama uses <|python_tag|>,
- # Mistral uses [TOOL_CALLS]; advertising tools for those would
- # enable a pill the parser cannot honour. GGUF is unaffected --
- # llama-server normalises every format into structured deltas.
+ # Our safetensors loop only parses <tool_call>{json}</tool_call> and
+ # <function=name>...</function>. Llama uses <|python_tag|>, Mistral uses
+ # [TOOL_CALLS]; advertising tools for those enables a pill the parser
+ # can't honour. GGUF is unaffected -- llama-server normalises every
+ # format into structured deltas.
if (
flags.get("supports_tools")
and chat_template
@@ -410,7 +403,7 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
)
flags["supports_tools"] = False
- # gpt-oss: keep reasoning on, drop tools (Harmony channel, not
+ # gpt-oss: keep reasoning on, drop tools (Harmony channel, not the
# <tool_call> XML this loop parses).
try:
if hasattr(backend, "_is_gpt_oss_model") and backend._is_gpt_oss_model():
@@ -426,7 +419,7 @@ def _effective_enable_tools(payload) -> Optional[bool]:
"""Resolve `payload.enable_tools` against the process-level tool policy.
Returns the policy value when set (CLI hard-override from `unsloth run`),
- otherwise the per-request value.
+ else the per-request value.
"""
from state.tool_policy import get_tool_policy
@@ -434,15 +427,15 @@ def _effective_enable_tools(payload) -> Optional[bool]:
return policy if policy is not None else payload.enable_tools
-# Cancel registry. Proxies (e.g. Colab) can swallow client fetch aborts
-# so is_disconnected() never fires. POST /inference/cancel looks up
-# in-flight cancel_events here by cancel_id (per-run) or session_id /
-# completion_id (fallbacks).
+# Cancel registry. Proxies (e.g. Colab) can swallow client fetch aborts so
+# is_disconnected() never fires. POST /inference/cancel looks up in-flight
+# cancel_events here by cancel_id (per-run) or session_id / completion_id
+# (fallbacks).
_CANCEL_REGISTRY: dict[str, set[threading.Event]] = {}
_CANCEL_LOCK = threading.Lock()
-# Cancel POSTs that arrive before registration are stashed; the next
-# matching __enter__ replays set() within the TTL.
+# Cancel POSTs arriving before registration are stashed; the next matching
+# __enter__ replays set() within the TTL.
_PENDING_CANCELS: dict[str, float] = {}
_PENDING_CANCEL_TTL_S = 30.0
@@ -460,8 +453,8 @@ class _TrackedCancel:
self.keys = tuple(k for k in keys if k)
def __enter__(self):
- # Register + consume-pending must be one critical section to close
- # the TOCTOU race against a concurrent cancel POST.
+ # Register + consume-pending in one critical section to close the
+ # TOCTOU race against a concurrent cancel POST.
should_cancel = False
with _CANCEL_LOCK:
for k in self.keys:
@@ -489,9 +482,9 @@ class _TrackedCancel:
def _cancel_by_keys(keys) -> int:
"""Set cancel_event for matching registry entries; no stash.
- session_id/completion_id are shared across runs on the same thread,
- so stashing them would ghost-cancel the user's next request. Only
- cancel_id is per-run unique (see _cancel_by_cancel_id_or_stash)."""
+ session_id/completion_id are shared across runs on the same thread, so
+ stashing them would ghost-cancel the user's next request. Only cancel_id
+ is per-run unique (see _cancel_by_cancel_id_or_stash)."""
if not keys:
return 0
events: set[threading.Event] = set()
@@ -526,17 +519,15 @@ def _cancel_by_cancel_id_or_stash(cancel_id: str) -> int:
async def _await_cancel_then_close(cancel_event, resp) -> None:
"""Watch a threading.Event from asyncio and close ``resp`` when it fires.
- Used by the passthrough streamers so a /cancel POST can interrupt
- while the async iterator is blocked waiting for llama-server prefill.
- Without this watcher the in-loop ``cancel_event.is_set()`` check is
- unreachable until the first SSE chunk arrives, which is exactly the
- proxy/Colab scenario the cancel POST exists to handle.
-
- Polls a threading.Event because the cancel registry is keyed by
- threading.Event so the synchronous /cancel handler can call .set().
- 50ms cadence adds at most that much latency to a prefill cancel; the
- common-case streaming cancel path still observes the event in the
- iterator's first iteration after the next chunk.
+ Used by passthrough streamers so a /cancel POST can interrupt while the
+ async iterator is blocked on llama-server prefill. Without it the in-loop
+ ``cancel_event.is_set()`` check is unreachable until the first SSE chunk
+ arrives -- exactly the proxy/Colab case the cancel POST exists for.
+
+ Polls a threading.Event since the cancel registry is keyed by
+ threading.Event (so the sync /cancel handler can call .set()). The 50ms
+ cadence adds at most that latency to a prefill cancel; the common
+ streaming-cancel path still sees the event on the iterator's next chunk.
"""
try:
while not cancel_event.is_set():
@@ -550,9 +541,9 @@ async def _await_cancel_then_close(cancel_event, resp) -> None:
# Appended to tool-use nudge to discourage plan-without-action.
-# Keep render_html guidance gated to turns where the artifact tool is actually
-# present in the tool schema; otherwise small local models can hallucinate a
-# missing tool call instead of following the fenced-HTML fallback prompt.
+# Gate render_html guidance to turns where the artifact tool is in the schema;
+# otherwise small local models hallucinate a missing tool call instead of the
+# fenced-HTML fallback prompt.
_TOOL_ACTION_NUDGE = (
" IMPORTANT: Always call tools directly -- never write code yourself."
" Never describe what you plan to do -- just call the tool immediately."
@@ -581,7 +572,7 @@ def _tool_action_nudge(has_artifact: bool) -> str:
# `\Z` so mid-text `<parameter>` in user code samples survives.
_TOOL_XML_RE = _re.compile(
# Hyphen in the name char-class matches MCP tool names with dashes
- # (mcp__srv__list-issues) which would otherwise leak past this strip.
+ # (mcp__srv__list-issues) that would otherwise leak past this strip.
r"<(?:tool_call|function=[\w-]+)>.*?(?:</(?:tool_call|function)>|\Z)"
r"|</(?:tool_call|function)>"
r"|</parameter>\s*\Z",
@@ -633,19 +624,19 @@ def _normalise_settings_str(value: Optional[str]) -> Optional[str]:
def _request_matches_loaded_settings(request: LoadRequest, llama_backend: LlamaCppBackend) -> bool:
- """True iff every runtime setting on the request matches the loaded
- server. Caller has already checked model+variant+is_loaded. See #5401."""
- # Compare requested n_ctx (not effective) so VRAM-cap doesn't mask
- # an Auto-vs-explicit slider flip.
+ """True iff every runtime setting on the request matches the loaded server.
+ Caller has already checked model+variant+is_loaded. See #5401."""
+ # Compare requested n_ctx (not effective) so VRAM-cap doesn't mask an
+ # Auto-vs-explicit slider flip.
if request.max_seq_length != llama_backend.requested_n_ctx:
return False
if _normalise_settings_str(request.cache_type_kv) != _normalise_settings_str(
llama_backend.cache_type_kv
):
return False
- # Vision loads silently drop speculative decoding (llama_cpp.py gates
- # spec on ``not is_vision``), so treat the request as ``off`` against
- # the backend's ``None`` to avoid forcing a redundant reload.
+ # Vision loads silently drop speculative decoding (llama_cpp.py gates spec
+ # on ``not is_vision``), so treat the request as ``off`` against the
+ # backend's ``None`` to avoid a redundant reload.
if llama_backend.is_vision:
req_mode = "off"
else:
@@ -653,17 +644,17 @@ def _request_matches_loaded_settings(request: LoadRequest, llama_backend: LlamaC
backend_mode = llama_backend.requested_spec_mode or "auto"
if req_mode != backend_mode:
return False
- # spec_draft_n_max only matters when an MTP variant is engaged; None
- # means "platform default" and matches whatever the backend chose.
+ # spec_draft_n_max only matters with an MTP variant; None means "platform
+ # default" and matches whatever the backend chose.
if backend_mode in ("mtp", "mtp+ngram") and request.spec_draft_n_max is not None:
if int(request.spec_draft_n_max) != (llama_backend.spec_draft_n_max or 0):
return False
if (request.chat_template_override or None) != (llama_backend.chat_template_override or None):
return False
- # llama_extra_args=None means "inherit"; only an explicit list that
- # differs forces a reload. On the inherit path, refuse to match if
- # stored extras contain any shadow flag, so the reload path can
- # strip them instead of leaving a stale override in effect.
+ # llama_extra_args=None means "inherit"; only an explicit differing list
+ # forces a reload. On the inherit path, refuse to match if stored extras
+ # contain any shadow flag, so the reload path strips them rather than
+ # leaving a stale override in effect.
backend_extra = list(llama_backend.extra_args) if llama_backend.extra_args else []
if request.llama_extra_args is None:
if backend_extra and strip_shadowing_flags(backend_extra) != backend_extra:
@@ -716,17 +707,17 @@ async def load_model(
"""
Load a model for inference.
- The model_path should be a clean identifier from GET /models/list.
- Returns inference configuration parameters (temperature, top_p, top_k, min_p)
- from the model's YAML config, falling back to default.yaml for missing values.
+ model_path is a clean identifier from GET /models/list. Returns inference
+ config (temperature, top_p, top_k, min_p) from the model's YAML, falling
+ back to default.yaml for missing values.
- GGUF models are loaded via llama-server (llama.cpp) instead of Unsloth.
+ GGUF models load via llama-server (llama.cpp) instead of Unsloth.
"""
native_grant_backed = False
model_log_label = request.model_path
try:
- # Validate user-supplied llama-server pass-through args up front
- # so a managed-flag collision returns 400 before any model work.
+ # Validate user pass-through args up front so a managed-flag collision
+ # returns 400 before any model work.
try:
extra_llama_args = validate_extra_args(request.llama_extra_args)
except ValueError as exc:
@@ -736,8 +727,8 @@ async def load_model(
status_code = 400,
detail = redact_native_paths(str(exc)),
)
- # Re-narrow []-from-None back to None so the inheritance path
- # below can tell "caller omitted" from "caller explicit []".
+ # Re-narrow []-from-None back to None so the inheritance path below can
+ # tell "caller omitted" from "caller explicit []".
extra_llama_args: Optional[list[str]] = (
None if request.llama_extra_args is None else extra_llama_args
)
@@ -745,8 +736,8 @@ async def load_model(
model_identifier, model_log_label, native_grant_backed = (
_resolve_model_identifier_for_request(request, operation = "load-model")
)
- # Version switching is handled automatically by the subprocess-based
- # inference backend — no need for ensure_transformers_version() here.
+ # Version switching is handled by the subprocess-based inference
+ # backend -- no ensure_transformers_version() needed here.
# ── Already-loaded check: skip reload if the exact model is active ──
backend = get_inference_backend()
@@ -764,7 +755,7 @@ async def load_model(
and gguf_variant_matches
and llama_backend.model_identifier
and llama_backend.model_identifier.lower() == model_identifier.lower()
- # Match runtime settings too so Apply isn't dropped (#5401).
+ # Match runtime settings so Apply isn't dropped (#5401).
and _request_matches_loaded_settings(request, llama_backend)
# Skip if a prior audio probe failed -- let load_model retry.
and getattr(llama_backend, "_audio_probed", True)
@@ -854,8 +845,8 @@ async def load_model(
)
# is_lora auto-detected from adapter_config.json on disk/HF.
- # DNS-probe wrap so offline loads skip 30-60s of soft-failed
- # network checks before the worker starts.
+ # DNS-probe wrap so offline loads skip 30-60s of soft-failed network
+ # checks before the worker starts.
with _hf_offline_if_dns_dead():
config = ModelConfig.from_identifier(
model_id = model_identifier,
@@ -883,28 +874,26 @@ async def load_model(
llama_backend = get_llama_cpp_backend()
unsloth_backend = get_inference_backend()
- # Unload any active Unsloth model first to free VRAM
+ # Unload any active Unsloth model to free VRAM
if unsloth_backend.active_model_name:
logger.info(
f"Unloading Unsloth model '{unsloth_backend.active_model_name}' before loading GGUF"
)
unsloth_backend.unload_model(unsloth_backend.active_model_name)
- # Inherit llama_extra_args from the previous load when the
- # request omits the field (the chat-settings Apply path
- # does not round-trip them; explicit [] still clears).
- # Inheritance is gated on (model_identifier, hf_variant)
- # to refuse cross-model pickup, and shadowing flags are
- # stripped so an inherited override can't win the last-wins
- # CLI parse against a freshly-supplied first-class field.
+ # Inherit llama_extra_args from the previous load when the request
+ # omits the field (the chat-settings Apply path doesn't round-trip
+ # them; explicit [] still clears). Gated on (model_identifier,
+ # hf_variant) to refuse cross-model pickup, and shadowing flags are
+ # stripped so an inherited override can't win the last-wins CLI
+ # parse against a freshly-supplied first-class field.
if request.llama_extra_args is None and llama_backend.extra_args:
source = llama_backend.extra_args_source
- # Compare against the resolved variant, not the request
- # field: callers commonly omit gguf_variant for local
- # ``.gguf`` paths and HF auto-pick flows. ``config.gguf_
- # variant`` is the variant load_model was actually
- # invoked with (see the HF / local branches below), so
- # both sides of the comparison key off the same string.
+ # Compare against the resolved variant, not the request field:
+ # callers commonly omit gguf_variant for local ``.gguf`` paths
+ # and HF auto-pick flows. ``config.gguf_variant`` is the variant
+ # load_model was actually invoked with (see HF / local branches
+ # below), so both sides key off the same string.
resolved_variant = config.gguf_variant
same_source = bool(
source
@@ -918,14 +907,13 @@ async def load_model(
source,
(model_identifier, resolved_variant),
)
- # Cross-model: clear explicitly so the backend
- # doesn't inherit via "no opinion" semantics.
+ # Cross-model: clear explicitly so the backend doesn't
+ # inherit via "no opinion" semantics.
extra_llama_args = []
else:
- # Strip only the groups whose first-class field
- # was actually set by the caller, so an inherited
- # --chat-template-file survives an Apply that omits
- # chat_template_override.
+ # Strip only the groups whose first-class field was set by
+ # the caller, so an inherited --chat-template-file survives
+ # an Apply that omits chat_template_override.
fields_set = getattr(request, "model_fields_set", set())
stripped = strip_shadowing_flags(
llama_backend.extra_args,
@@ -939,8 +927,8 @@ async def load_model(
try:
extra_llama_args = validate_extra_args(stripped)
except ValueError:
- # Should not happen on already-validated args; degrade
- # to no-extras rather than 400 if managed flags changed.
+ # Shouldn't happen on already-validated args; degrade to
+ # no-extras rather than 400 if managed flags changed.
logger.warning(
"Stored llama_extra_args failed revalidation; "
"loading without them: %s",
@@ -955,10 +943,9 @@ async def load_model(
extra_llama_args,
)
- # Route to HF mode or local mode based on config
- # Run in a thread so the event loop stays free for progress
- # polling and other requests during the (potentially long)
- # GGUF download + llama-server startup.
+ # Route to HF or local mode based on config. Run in a thread so the
+ # event loop stays free for progress polling and other requests
+ # during the (potentially long) GGUF download + llama-server start.
_n_parallel = getattr(fastapi_request.app.state, "llama_parallel_slots", 1)
if config.gguf_hf_repo:
@@ -986,9 +973,9 @@ async def load_model(
llama_backend.load_model,
gguf_path = config.gguf_file,
mmproj_path = config.gguf_mmproj_file,
- # Pass the resolved variant so _extra_args_source
- # is keyed off the same string the inheritance
- # check at the top of /load uses (#5401 followup).
+ # Pass the resolved variant so _extra_args_source keys off
+ # the same string the inheritance check at the top of /load
+ # uses (#5401 followup).
hf_variant = config.gguf_variant,
model_identifier = config.identifier,
is_vision = config.is_vision,
@@ -1069,9 +1056,9 @@ async def load_model(
except Exception as e:
logger.warning("Could not shut down export subprocess: %s", e)
- # Auto-detect quantization for LoRA adapters from adapter_config.json
- # The training pipeline patches this file with "unsloth_training_method"
- # which is 'qlora' or 'lora'. Only LoRA (16-bit) needs load_in_4bit=False.
+ # Auto-detect quantization for LoRA adapters from adapter_config.json.
+ # The training pipeline writes "unsloth_training_method" ('qlora' or
+ # 'lora'); only LoRA (16-bit) needs load_in_4bit=False.
load_in_4bit = request.load_in_4bit
if config.is_lora and config.path:
import json
@@ -1100,7 +1087,7 @@ async def load_model(
f"Training method: {training_method}, load_in_4bit={load_in_4bit}"
)
else:
- # No unsloth_training_method — fallback to base model name
+ # No unsloth_training_method -- fall back to base model name
if (
config.base_model
and "-bnb-4bit" not in config.base_model.lower()
@@ -1115,8 +1102,8 @@ async def load_model(
except Exception as e:
logger.warning(f"Could not read adapter_config.json: {e}")
- # Load the model in a thread so the event loop stays free
- # for download progress polling and other requests.
+ # Load in a thread so the event loop stays free for download progress
+ # polling and other requests.
success = await asyncio.to_thread(
backend.load_model,
config = config,
@@ -1128,7 +1115,7 @@ async def load_model(
)
if not success:
- # Check if YAML says this model needs trust_remote_code
+ # Check if YAML says this model needs trust_remote_code.
if not request.trust_remote_code:
model_defaults = load_model_defaults(config.identifier)
yaml_trust = model_defaults.get("inference", {}).get("trust_remote_code", False)
@@ -1199,7 +1186,7 @@ async def load_model(
# User-facing validation (e.g. "Invalid gpu_ids [99]"): redact paths, keep detail.
raise HTTPException(status_code = 400, detail = redact_native_paths(str(e)))
except Exception as e:
- # Surface a friendlier message for models that Unsloth cannot load
+ # Friendlier message for models Unsloth cannot load.
not_supported_hints = [
"No config file found",
"not yet supported",
@@ -1234,8 +1221,8 @@ async def validate_model(
"""
Lightweight validation endpoint for model identifiers.
- This checks that ModelConfig.from_identifier() can resolve the given
- model_path, but it does NOT actually load model weights into GPU memory.
+ Checks that ModelConfig.from_identifier() can resolve model_path, but does
+ NOT load model weights into GPU memory.
"""
native_grant_backed = False
model_log_label = request.model_path
@@ -1310,7 +1297,7 @@ async def unload_model(request: UnloadRequest, current_subject: str = Depends(ge
Routes to the correct backend (llama-server for GGUF, Unsloth otherwise).
"""
try:
- # Check if the GGUF backend has this model loaded or is loading it
+ # Check if the GGUF backend has this model loaded or is loading it.
llama_backend = get_llama_cpp_backend()
if llama_backend.is_active and (
llama_backend.model_identifier == request.model_path
@@ -1341,8 +1328,8 @@ async def cancel_inference(request: Request, current_subject: str = Depends(get_
session_id - fallback when cancel_id is absent.
completion_id - fallback when cancel_id is absent.
- A cancel_id arriving before its stream registers is stashed briefly
- and replayed on registration. Returns {"cancelled": N}.
+ A cancel_id arriving before its stream registers is stashed briefly and
+ replayed on registration. Returns {"cancelled": N}.
"""
try:
body = await request.json()
@@ -1357,8 +1344,8 @@ async def cancel_inference(request: Request, current_subject: str = Depends(get_
return {"cancelled": _cancel_by_cancel_id_or_stash(cancel_id)}
keys = []
- # `message_id` is the Anthropic passthrough's per-run identifier --
- # included so /v1/messages clients can cancel by their native id.
+ # `message_id` is the Anthropic passthrough's per-run identifier, so
+ # /v1/messages clients can cancel by their native id.
for k in ("completion_id", "session_id", "message_id"):
v = body.get(k)
if isinstance(v, str) and v:
@@ -1378,7 +1365,7 @@ async def generate_stream(
"""
Generate a chat response with Server-Sent Events (SSE) streaming.
- For vision models, provide image_base64 with the base64-encoded image.
+ For vision models, provide image_base64 (base64-encoded image).
"""
backend = get_inference_backend()
@@ -1387,7 +1374,7 @@ async def generate_stream(
status_code = 400, detail = "No model loaded. Call POST /inference/load first."
)
- # Decode image if provided (for vision models)
+ # Decode image if provided (vision models)
image = None
if request.image_base64:
try:
@@ -1395,7 +1382,7 @@ async def generate_stream(
from PIL import Image
from io import BytesIO
- # Check if current model supports vision
+ # Check current model supports vision
model_info = backend.models.get(backend.active_model_name, {})
if not model_info.get("is_vision"):
raise HTTPException(
@@ -1452,12 +1439,12 @@ async def generate_stream(
async def get_status(current_subject: str = Depends(get_current_subject)):
"""
Get current inference backend status.
- Reports whichever backend (Unsloth or llama-server) is currently active.
+ Reports whichever backend (Unsloth or llama-server) is active.
"""
try:
llama_backend = get_llama_cpp_backend()
- # MTP probe + freshness check (both cached). Drive the UI banner.
+ # MTP probe + freshness check (both cached); drive the UI banner.
try:
_bin = type(llama_backend)._find_llama_server_binary()
_caps = type(llama_backend).probe_server_capabilities(_bin)
@@ -1585,15 +1572,13 @@ async def get_load_progress(current_subject: str = Depends(get_current_subject))
"""
Return the active GGUF load's mmap/upload progress.
- During the warmup window after a GGUF download -- when llama-server
- is paging ~tens-to-hundreds of GB of shards into the page cache
- before pushing layers to VRAM -- ``/api/inference/status`` only
- shows a generic spinner. This endpoint exposes sampled progress so
- the UI can render a real bar plus rate/ETA during that window.
+ During the warmup window after a GGUF download -- when llama-server pages
+ ~tens-to-hundreds of GB of shards into the page cache before pushing layers
+ to VRAM -- ``/api/inference/status`` only shows a generic spinner. This
+ exposes sampled progress so the UI can render a real bar plus rate/ETA.
- Returns an empty payload (``phase=null, bytes=0``) when no load is
- in flight. The frontend should stop polling once ``phase`` becomes
- ``ready``.
+ Returns an empty payload (``phase=null, bytes=0``) when no load is in
+ flight. The frontend should stop polling once ``phase`` becomes ``ready``.
"""
try:
llama_backend = get_llama_cpp_backend()
@@ -1619,7 +1604,7 @@ async def generate_audio(
):
"""
Generate audio (TTS) from the latest user message.
- Returns a JSON response with base64-encoded WAV audio.
+ Returns JSON with base64-encoded WAV audio.
Works with both GGUF (llama-server) and Unsloth/transformers backends.
"""
import base64
@@ -1707,8 +1692,8 @@ def _decode_audio_base64(b64: str) -> np.ndarray:
from utils.paths import ensure_dir, tmp_root
raw = base64.b64decode(b64)
- # torchaudio.load needs a file path or file-like object with format hint
- # Write to a temp file so torchaudio can auto-detect the format
+ # torchaudio.load needs a path or file-like with a format hint; write a
+ # temp file so it can auto-detect the format.
with tempfile.NamedTemporaryFile(
suffix = ".audio",
delete = False,
@@ -1741,9 +1726,9 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
(``[{type: "text", ...}, {type: "image_url", ...}]``).
Returns:
- system_prompt: The system message text (empty string if none provided).
+ system_prompt: System message text (empty string if none).
chat_messages: Non-system messages with content flattened to strings.
- image_base64: Base64 data of the *first* image found, or ``None``.
+ image_base64: Base64 of the *first* image found, or ``None``.
"""
system_prompt = ""
chat_messages: list[dict] = []
@@ -1772,7 +1757,7 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
elif part.type == "image_url" and first_image_b64 is None:
url = part.image_url.url
if url.startswith("data:"):
- # data:image/png;base64,<DATA> → extract <DATA>
+ # data:image/png;base64,<DATA> -> extract <DATA>
first_image_b64 = url.split(",", 1)[1] if "," in url else None
else:
logger.warning(f"Remote image URLs not yet supported: {url[:80]}...")
@@ -1785,14 +1770,14 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
# ── External provider proxy ──────────────────────────────────────
-# Providers whose stream helper translates `input_document` parts into
-# a native attachment block on the wire. For Anthropic the mapping is
-# `_stream_anthropic` -> {type:"document", source:...}; for OpenAI it
-# is `_stream_openai_responses` -> {type:"input_file", file_data|file_url}.
-# Every other provider (gemini / mistral / kimi / openrouter / deepseek /
-# custom OpenAI-compat) goes through the generic /chat/completions
-# passthrough that forwards messages verbatim, so handing them an
-# `input_document` part would 400 with an unknown content_part type.
+# Providers whose stream helper translates `input_document` parts into a
+# native attachment block on the wire. Anthropic: `_stream_anthropic` ->
+# {type:"document", source:...}; OpenAI: `_stream_openai_responses` ->
+# {type:"input_file", file_data|file_url}. Every other provider (gemini /
+# mistral / kimi / openrouter / deepseek / custom OpenAI-compat) goes through
+# the generic /chat/completions passthrough that forwards messages verbatim,
+# so handing them an `input_document` part would 400 with an unknown
+# content_part type.
_INPUT_DOCUMENT_PROVIDERS = frozenset({"anthropic", "openai"})
@@ -1808,32 +1793,29 @@ def _build_external_messages(
Behaviour per content-part type:
- `text`: always preserved.
- `image_url`: preserved on vision providers; stripped on non-vision.
- - `input_document`: preserved ONLY when the provider's stream helper
- has explicit translation logic for it (Anthropic + OpenAI today,
- see ``_INPUT_DOCUMENT_PROVIDERS``). For every other provider the
- part is stripped so the unknown content type doesn't reach generic
- /chat/completions passthrough and 400 the request.
- - `reasoning`: OpenAI-only Responses reasoning item paired with a
- prior tool output. Forwarded ONLY when provider_type=="openai"
- so follow-up image edits can replay the required reasoning item.
- - `image_generation_call`: OpenAI-only Responses image reference.
- Forwarded ONLY when provider_type=="openai" so follow-up image
- edits can reference prior generated images.
+ - `input_document`: preserved ONLY when the provider's stream helper has
+ explicit translation logic (Anthropic + OpenAI today, see
+ ``_INPUT_DOCUMENT_PROVIDERS``). Stripped for every other provider so the
+ unknown type doesn't reach generic /chat/completions and 400.
+ - `reasoning`: OpenAI-only Responses reasoning item paired with a prior
+ tool output. Forwarded ONLY when provider_type=="openai" so follow-up
+ image edits can replay the required reasoning item.
+ - `image_generation_call`: OpenAI-only Responses image reference. Forwarded
+ ONLY when provider_type=="openai" so follow-up image edits can reference
+ prior generated images.
- `compaction`: Anthropic-only synthetic part (round-trips server-side
compaction state). Forwarded ONLY when provider_type=="anthropic";
- stripped for every other provider so the unknown part doesn't
- reach generic /chat/completions passthrough where it would 400
- (e.g. DeepSeek, Mistral, Gemini, Kimi, OpenRouter, etc.).
+ stripped elsewhere so the unknown part doesn't reach generic
+ /chat/completions and 400 (DeepSeek, Mistral, Gemini, Kimi, OpenRouter).
"""
document_provider = provider_type in _INPUT_DOCUMENT_PROVIDERS
anthropic = provider_type == "anthropic"
openai = provider_type == "openai"
- # `extra_content` is a Gemini-specific carrier for the assistant's
- # text-part `thoughtSignature` round-trip on the native
- # streamGenerateContent endpoint. Custom Gemini OpenAI-compatible
- # gateways (LiteLLM etc.) route through /chat/completions where
- # the field is unknown and can be rejected -- gate strictly on the
- # Google-hosted Gemini base.
+ # `extra_content` carries the assistant's text-part `thoughtSignature`
+ # round-trip on Gemini's native streamGenerateContent endpoint. Custom
+ # Gemini OpenAI-compat gateways (LiteLLM etc.) route through
+ # /chat/completions where the field is unknown and can be rejected -- gate
+ # strictly on the Google-hosted Gemini base.
_native_gemini = False
if provider_type == "gemini" and base_url:
try:
@@ -1849,16 +1831,15 @@ def _build_external_messages(
)
def _is_marked_server_builtin_tool_call(tc: Any) -> bool:
- """Return True iff `tc` is a synthetic provider-side tool card
- with one of the canonical builtin names and either:
- - the new `args._server_tool` marker stamped by the backend, or
- - a Gemini `args.google.native_part` payload (durable replay
- signal for code_execution / image_generation that predates
- the marker).
- Such cards must not be forwarded to non-native providers
- because they are not real user functions and the receiving API
- will reject the orphan tool history. Real user functions with
- these names normally have neither signal.
+ """Return True iff `tc` is a synthetic provider-side tool card with a
+ canonical builtin name and either:
+ - the `args._server_tool` marker stamped by the backend, or
+ - a Gemini `args.google.native_part` payload (durable replay signal
+ for code_execution / image_generation that predates the marker).
+ Such cards must not be forwarded to non-native providers: they aren't
+ real user functions, so the receiving API rejects the orphan tool
+ history. Real user functions with these names normally have neither
+ signal.
"""
if not isinstance(tc, dict):
return False
@@ -1880,31 +1861,28 @@ def _build_external_messages(
google = args.get("google")
return isinstance(google, dict) and isinstance(google.get("native_part"), dict)
- # When we drop a server-side builtin tool_call here, the matching
- # `role="tool"` follow-up must also be dropped from the outbound
- # history -- otherwise the provider receives an orphan
- # tool_call_id with no matching assistant call, which OpenAI
- # Responses and Anthropic both reject.
+ # When we drop a server-side builtin tool_call, the matching `role="tool"`
+ # follow-up must also be dropped -- else the provider gets an orphan
+ # tool_call_id with no matching assistant call, which OpenAI Responses and
+ # Anthropic both reject.
dropped_server_builtin_tool_call_ids: set[str] = set()
def _filter_tool_calls(tool_calls: Any) -> Optional[list]:
"""Sanitize assistant `tool_calls` for non-native-Gemini providers.
Two concerns:
- 1. `tool_calls[i].extra_content` carries Gemini-only
- thoughtSignature metadata; strip it for providers that
- cannot parse the unknown key.
- 2. Marked server-side builtin cards (`_server_tool: true` on
- a canonical builtin name, or a Gemini `native_part`
- payload) are provider-internal Studio tool cards from a
- prior native Gemini turn; forwarding them to OpenAI /
- Anthropic / custom OAI-compat gateways sends an orphan
- `tool_calls` entry (no matching tool declaration, often
- no matching `role="tool"` reply) that can be rejected.
- We record the dropped call_ids so the matching role=tool
- message is also skipped below.
- Native Gemini keeps both untouched so the native translator can
- replay them via `native_part`.
+ 1. `tool_calls[i].extra_content` carries Gemini-only thoughtSignature
+ metadata; strip it for providers that can't parse the unknown key.
+ 2. Marked server-side builtin cards (`_server_tool: true` on a
+ canonical builtin name, or a Gemini `native_part` payload) are
+ Studio-internal tool cards from a prior native Gemini turn;
+ forwarding them to OpenAI / Anthropic / custom OAI-compat gateways
+ sends an orphan `tool_calls` entry (no matching tool declaration,
+ often no matching `role="tool"` reply) that can be rejected. We
+ record the dropped call_ids so the matching role=tool message is
+ skipped below.
+ Native Gemini keeps both untouched so the translator can replay them
+ via `native_part`.
"""
if not tool_calls:
return None
@@ -1931,10 +1909,9 @@ def _build_external_messages(
result = []
for msg in messages:
- # Drop role=tool messages whose matching server-builtin
- # tool_call was already filtered above. Forwarding an orphan
- # tool_result with no matching tool_call would be rejected by
- # OpenAI Responses and Anthropic.
+ # Drop role=tool messages whose matching server-builtin tool_call was
+ # filtered above. An orphan tool_result with no matching tool_call is
+ # rejected by OpenAI Responses and Anthropic.
if (
msg.role == "tool"
and isinstance(msg.tool_call_id, str)
@@ -1942,10 +1919,10 @@ def _build_external_messages(
):
continue
if isinstance(msg.content, str):
- # Drop bare assistant messages with no content AND no
- # tool_calls (some providers reject empty assistant turns).
- # Preserve assistant turns whose only payload is tool_calls
- # so multi-turn function-call loops round-trip.
+ # Drop bare assistant messages with no content AND no tool_calls
+ # (some providers reject empty assistant turns). Preserve assistant
+ # turns whose only payload is tool_calls so multi-turn
+ # function-call loops round-trip.
if msg.role == "assistant" and not msg.content.strip() and not msg.tool_calls:
continue
out: dict[str, Any] = {"role": msg.role, "content": msg.content}
@@ -1954,10 +1931,10 @@ def _build_external_messages(
if _tcs:
out["tool_calls"] = _tcs
elif not msg.content.strip():
- # Every tool_call was a synthetic provider-side
- # card and was dropped; the assistant turn would
- # be an empty `{"role":"assistant","content":""}`
- # which some providers reject. Skip it entirely.
+ # Every tool_call was a dropped synthetic provider card;
+ # the turn would be an empty
+ # `{"role":"assistant","content":""}` that some providers
+ # reject. Skip it entirely.
continue
if msg.role == "tool":
if msg.tool_call_id:
@@ -1968,15 +1945,14 @@ def _build_external_messages(
out["extra_content"] = msg.extra_content
result.append(out)
continue
- # Assistant messages with content=None but populated tool_calls
- # are valid (post-tool-call assistant turn). Forward them so the
- # provider helper can rebuild the functionCall part.
+ # Assistant messages with content=None but populated tool_calls are
+ # valid (post-tool-call turn). Forward them so the provider helper can
+ # rebuild the functionCall part.
if msg.content is None and msg.role == "assistant" and msg.tool_calls:
_filtered_tcs = _filter_tool_calls(msg.tool_calls)
if not _filtered_tcs:
- # Every tool_call on this turn was provider-side
- # synthetic and dropped; skipping the whole message
- # avoids forwarding an empty assistant turn.
+ # Every tool_call was provider-side synthetic and dropped;
+ # skip the whole message to avoid an empty assistant turn.
continue
_assistant_only: dict[str, Any] = {
"role": "assistant",
@@ -2015,16 +1991,15 @@ def _build_external_messages(
# ExternalProviderClient maps this onto a top-level
# Responses input item after the current user prompt,
# or onto `previous_response_id` when response_id is
- # available from the prior Responses turn.
+ # available from the prior turn.
image_ref = {"type": "image_generation_call", "id": part.id}
if getattr(part, "response_id", None):
image_ref["response_id"] = part.response_id
parts.append(image_ref)
elif part.type == "input_document" and document_provider:
- # ExternalProviderClient maps this onto
- # Anthropic's `document` or OpenAI Responses'
- # `input_file` block per provider; every other
- # provider would 400 on the unknown part type.
+ # ExternalProviderClient maps this onto Anthropic's
+ # `document` or OpenAI Responses' `input_file` block;
+ # every other provider would 400 on the unknown part.
doc: dict[str, Any] = {"type": "input_document"}
if part.file_data:
doc["file_data"] = part.file_data
@@ -2036,10 +2011,9 @@ def _build_external_messages(
doc["media_type"] = part.media_type
parts.append(doc)
elif part.type == "compaction" and anthropic:
- # Anthropic stream helper forwards this as a
- # native `compaction` block; every other
- # provider would 400 on the unknown part, so
- # gate by provider_type.
+ # Anthropic stream helper forwards this as a native
+ # `compaction` block; every other provider would 400 on
+ # the unknown part, so gate by provider_type.
parts.append({"type": "compaction", "content": part.content})
entry: dict[str, Any] = {"role": msg.role, "content": parts}
if msg.role == "assistant" and msg.tool_calls:
@@ -2047,10 +2021,9 @@ def _build_external_messages(
if _tcs:
entry["tool_calls"] = _tcs
elif not parts:
- # All tool_calls were synthetic and dropped,
- # and no preserved content parts survived.
- # Skip rather than forward an empty assistant
- # turn that downstream providers reject.
+ # All tool_calls were synthetic and dropped, and no
+ # content parts survived. Skip rather than forward an
+ # empty assistant turn that downstream providers reject.
continue
elif msg.role == "assistant" and not parts:
continue
@@ -2063,11 +2036,10 @@ def _build_external_messages(
entry["extra_content"] = msg.extra_content
result.append(entry)
else:
- # Non-vision provider: strip images / documents, keep
- # text, optionally keep compaction (Anthropic only --
+ # Non-vision provider: strip images / documents, keep text,
+ # optionally keep compaction (Anthropic only --
# compaction-capable Anthropic models all report
- # supports_vision=True today, but the gate is here for
- # safety).
+ # supports_vision=True today, but gate here for safety).
preserved = []
for p in msg.content:
if p.type == "text":
@@ -2091,8 +2063,8 @@ def _build_external_messages(
if msg.role == "assistant" and not preserved:
continue
if len(preserved) == 1 and preserved[0]["type"] == "text":
- # Single text part collapses back to a string for
- # providers that don't accept content arrays.
+ # Single text part collapses to a string for providers that
+ # don't accept content arrays.
entry = {"role": msg.role, "content": preserved[0]["text"]}
else:
entry = {"role": msg.role, "content": preserved}
@@ -2101,8 +2073,8 @@ def _build_external_messages(
if _tcs:
entry["tool_calls"] = _tcs
else:
- # All tool_calls were synthetic and dropped;
- # skip if there's no surviving content either.
+ # All tool_calls were synthetic and dropped; skip if no
+ # content survived either.
_entry_content = entry.get("content")
_has_text = (
isinstance(_entry_content, str) and _entry_content.strip()
@@ -2126,8 +2098,8 @@ async def _proxy_to_external_provider(
"""
Proxy a chat completion request to an external LLM provider.
- Resolves provider config (from DB or registry), decrypts the API key,
- and streams the response back in OpenAI SSE format.
+ Resolves provider config (DB or registry), decrypts the API key, and
+ streams the response back in OpenAI SSE format.
"""
# Resolve provider type and base URL
provider_type = payload.provider_type
@@ -2181,7 +2153,7 @@ async def _proxy_to_external_provider(
detail = "external_model is required when using an external provider.",
)
- # Build messages preserving multimodal content for vision-capable providers
+ # Build messages, preserving multimodal content for vision providers
from core.inference.providers import get_provider_info as _get_provider_info
_pinfo = _get_provider_info(provider_type) or {}
@@ -2199,11 +2171,10 @@ async def _proxy_to_external_provider(
api_key = api_key,
)
- # `top_k` defaults to 20 in ChatCompletionRequest because the local
- # inference path expects an int, but the external-provider path
- # should treat "field omitted from JSON" as "use provider default"
- # so callers that send only model/messages do not silently get
- # different sampling than before this PR. Pydantic's
+ # `top_k` defaults to 20 in ChatCompletionRequest because the local path
+ # expects an int, but the external-provider path treats "field omitted from
+ # JSON" as "use provider default" so callers sending only model/messages
+ # don't silently get different sampling than before this PR. Pydantic's
# `model_fields_set` tracks explicit-vs-default per request.
_top_k_explicit = payload.top_k if "top_k" in payload.model_fields_set else None
@@ -2261,11 +2232,11 @@ async def _proxy_to_external_provider(
def _resolve_openai_cloud_client(body: OpenAIContainerRequest) -> ExternalProviderClient:
"""
- Decrypt the API key + validate the base URL points at OpenAI cloud,
- then build an ExternalProviderClient for the three container CRUD
- endpoints below. The shell tool only exists on api.openai.com, so
- rejecting non-cloud bases up front prevents confusing 404s on
- ollama / llama.cpp / vLLM / custom presets.
+ Decrypt the API key + validate the base URL points at OpenAI cloud, then
+ build an ExternalProviderClient for the three container CRUD endpoints
+ below. The shell tool only exists on api.openai.com, so rejecting non-cloud
+ bases up front prevents confusing 404s on ollama / llama.cpp / vLLM /
+ custom presets.
"""
base_url = body.provider_base_url or get_base_url("openai")
if not base_url or "api.openai.com" not in base_url:
@@ -2337,9 +2308,9 @@ async def list_openai_containers(
event = "openai_container_list.transport_error",
log = logger,
)
- # OpenAI keeps expired containers in /v1/containers indefinitely
- # with status="expired" — they're effectively dead but still
- # listed. Hide them so the picker only shows usable containers.
+ # OpenAI keeps expired containers in /v1/containers indefinitely with
+ # status="expired" -- dead but still listed. Hide them so the picker
+ # only shows usable containers.
return ListOpenAIContainersResponse(
containers = [
_summarize_container(c)
@@ -2442,35 +2413,35 @@ async def openai_chat_completions(
"""
OpenAI-compatible chat completions endpoint.
- Supports multimodal messages: ``content`` may be a plain string or a
- list of content parts (``text`` / ``image_url``).
+ Supports multimodal messages: ``content`` may be a plain string or a list
+ of content parts (``text`` / ``image_url``).
Non-streaming (default): returns a single ChatCompletion JSON object.
Streaming: returns SSE chunks matching OpenAI's format.
- ``stream`` defaults to ``false`` to match OpenAI's spec; clients opt
- into SSE by sending ``stream: true``.
+ ``stream`` defaults to ``false`` per OpenAI's spec; clients opt into SSE by
+ sending ``stream: true``.
- Automatically routes to the correct backend:
+ Routes to the correct backend automatically:
- GGUF models → llama-server via LlamaCppBackend
- Other models → Unsloth/transformers via InferenceBackend
"""
# ── External provider routing ────────────────────────────────
- # encrypted_api_key is optional — local providers (llama.cpp / vLLM / Ollama) may run without auth.
+ # encrypted_api_key is optional -- local providers (llama.cpp / vLLM / Ollama) may run without auth.
if payload.provider_id or payload.provider_type:
return await _proxy_to_external_provider(payload, request)
llama_backend = get_llama_cpp_backend()
using_gguf = llama_backend.is_loaded
- # OpenAI-SDK clients send ``chat_template_kwargs`` via ``extra_body``,
- # which the SDK spreads into the request body at the top level. Studio's
+ # OpenAI-SDK clients send ``chat_template_kwargs`` via ``extra_body``, which
+ # the SDK spreads into the request body at the top level. Studio's
# ChatCompletionRequest has ``extra="allow"`` so pydantic stashes them in
- # ``model_extra``, but the typed ``payload.enable_thinking`` path is what
- # downstream generators actually consume. Lift ``enable_thinking`` from
- # the extra-body chat_template_kwargs onto the typed field so clients
- # that only know the OpenAI shape (data_designer recipe runs, etc.)
- # can still control the reasoning preamble.
+ # ``model_extra``, but downstream generators consume the typed
+ # ``payload.enable_thinking``. Lift ``enable_thinking`` from the extra-body
+ # chat_template_kwargs onto the typed field so clients that only know the
+ # OpenAI shape (data_designer recipe runs, etc.) can still control the
+ # reasoning preamble.
_extra = getattr(payload, "model_extra", None)
if payload.enable_thinking is None and isinstance(_extra, dict):
_tpl_kw = _extra.get("chat_template_kwargs")
@@ -2492,7 +2463,7 @@ async def openai_chat_completions(
model_name = backend.active_model_name or payload.model
# ── Audio TTS path: auto-route to audio generation ────
- # (Whisper is ASR not TTS — handled below in audio input path)
+ # (Whisper is ASR not TTS -- handled below in audio input path)
model_info = backend.models.get(backend.active_model_name, {})
if model_info.get("is_audio") and model_info.get("audio_type") != "whisper":
return await generate_audio(payload, request)
@@ -2620,21 +2591,19 @@ async def openai_chat_completions(
# ── Standard OpenAI function-calling pass-through (GGUF only) ────
# When a client (opencode / Claude Code via OpenAI compat / Cursor /
# Continue / ...) sends standard OpenAI `tools` without Studio's
- # `enable_tools` shorthand, forward the request to llama-server
- # verbatim so structured `tool_calls` flow back to the client. This
- # branch runs BEFORE `_extract_content_parts` because that helper is
- # unaware of `role="tool"` messages and assistant messages that only
- # carry `tool_calls` (content=None) — both of which are valid in
- # multi-turn client-side tool loops.
+ # `enable_tools` shorthand, forward to llama-server verbatim so structured
+ # `tool_calls` flow back. Runs BEFORE `_extract_content_parts` because that
+ # helper is unaware of `role="tool"` messages and assistant messages that
+ # only carry `tool_calls` (content=None) -- both valid in multi-turn
+ # client-side tool loops.
_has_tool_messages = any(m.role == "tool" or m.tool_calls for m in payload.messages)
# Route guided-decoding requests through the verbatim passthrough so
- # ``response_format`` (JSON schema) actually reaches llama-server and
- # the model's GBNF-constrained output comes back unmodified. The
- # non-passthrough GGUF path below calls ``generate_chat_completion``
- # which has no response_format kwarg, so the schema gets silently
- # dropped and data_designer falls back to free-form sampling. Guided
- # decoding does not require ``supports_tools`` - the grammar machinery
- # is independent of tool-call parsing.
+ # ``response_format`` (JSON schema) reaches llama-server and the model's
+ # GBNF-constrained output comes back unmodified. The non-passthrough GGUF
+ # path below calls ``generate_chat_completion`` which has no response_format
+ # kwarg, so the schema gets silently dropped and data_designer falls back to
+ # free-form sampling. Guided decoding does not require ``supports_tools`` --
+ # the grammar machinery is independent of tool-call parsing.
_has_response_format = _extract_response_format(payload) is not None
_tools_passthrough = llama_backend.supports_tools and (
(payload.tools and len(payload.tools) > 0) or _has_tool_messages
@@ -2650,10 +2619,10 @@ async def openai_chat_completions(
detail = "Audio input is not supported for GGUF chat models yet.",
)
- # Preserve the vision guard that would otherwise run in the
- # non-passthrough path below: text-only tool-capable GGUFs
- # should return a clear 400 here rather than forwarding the
- # image to llama-server and surfacing an opaque upstream error.
+ # Preserve the vision guard from the non-passthrough path below:
+ # text-only tool-capable GGUFs should return a clear 400 here rather
+ # than forwarding the image to llama-server and surfacing an opaque
+ # upstream error.
if not llama_backend.is_vision and (
payload.image_base64
or any(
@@ -2670,8 +2639,8 @@ async def openai_chat_completions(
cancel_event = threading.Event()
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
# `stream` defaults to False on ChatCompletionRequest (OpenAI spec
- # parity). Naive curl / .NET / System.Text.Json clients omitting
- # the field used to get SSE here and choke on deserialization (#5047).
+ # parity). Naive curl / .NET / System.Text.Json clients omitting the
+ # field used to get SSE here and choke on deserialization (#5047).
if payload.stream:
return await _openai_passthrough_stream(
request,
@@ -2717,12 +2686,11 @@ async def openai_chat_completions(
# ── Tool-calling path (agentic loop) ──────────────────
# `_effective_enable_tools` lets `unsloth run --enable-tools/--disable-tools`
- # hard-override the per-request value. Without a CLI override, falls
- # back to `payload.enable_tools` (existing behavior). `mcp_enabled=true`
- # also opens the tool loop so MCP-only callers do not have to flip a
- # second flag, BUT must still honor a CLI `--disable-tools` policy --
- # checking the raw policy here keeps `mcp_enabled` from re-enabling
- # tools that the operator explicitly forbade.
+ # hard-override the per-request value, else falls back to
+ # `payload.enable_tools`. `mcp_enabled=true` also opens the tool loop so
+ # MCP-only callers needn't flip a second flag, BUT must still honor a
+ # CLI `--disable-tools` policy -- checking the raw policy here keeps
+ # `mcp_enabled` from re-enabling tools the operator explicitly forbade.
from state.tool_policy import get_tool_policy as _get_tool_policy_g
_cli_policy = _get_tool_policy_g()
@@ -2746,12 +2714,11 @@ async def openai_chat_completions(
if _mcp_allowed:
tools_to_use = tools_to_use + await get_enabled_mcp_tools()
- # Skip the tool loop when no tool actually survived, so the
- # safetensors loop's "empty = allow all" semantic cannot reach
- # built-in tools the caller did not opt into. Existing callers
- # who omit enabled_tools still get ALL_TOOLS here, so this
- # only suppresses the loop when discovery + opt-in left it
- # genuinely empty.
+ # Skip the tool loop when no tool survived, so the safetensors
+ # loop's "empty = allow all" semantic can't reach built-in tools
+ # the caller didn't opt into. Callers who omit enabled_tools still
+ # get ALL_TOOLS here, so this only suppresses the loop when
+ # discovery + opt-in left it genuinely empty.
if not tools_to_use:
use_tools = False
@@ -2764,8 +2731,8 @@ async def openai_chat_completions(
_date_line = f"The current date is {_date.today().isoformat()}."
- # Small models (<9B) struggle with multi-step search plans,
- # so simplify the web tips to avoid plan-then-stall behavior.
+ # Small models (<9B) struggle with multi-step search plans, so
+ # simplify the web tips to avoid plan-then-stall behavior.
_model_size_b = _extract_model_size_b(model_name)
_is_small_model = _model_size_b is not None and _model_size_b < 9
@@ -2809,7 +2776,7 @@ async def openai_chat_completions(
if _nudge:
_nudge += _tool_action_nudge(_has_artifact)
- # Append nudge to system prompt (preserve user's prompt)
+ # Append nudge to system prompt (preserve the user's prompt)
if system_prompt:
system_prompt = system_prompt.rstrip() + "\n\n" + _nudge
else:
@@ -2869,8 +2836,8 @@ async def openai_chat_completions(
)
yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
- # Iterate the synchronous generator in a thread so
- # the event loop stays free for disconnect detection.
+ # Iterate the sync generator in a thread so the event loop
+ # stays free for disconnect detection.
gen = gguf_generate_with_tools()
prev_text = ""
_stream_usage = None
@@ -2887,14 +2854,14 @@ async def openai_chat_completions(
break
if event["type"] == "status":
- # Empty status marks an iteration boundary
- # in the GGUF tool loop (e.g. after a
- # re-prompt). Reset the cumulative cursor
- # so the next assistant turn streams cleanly.
+ # Empty status marks an iteration boundary in the
+ # GGUF tool loop (e.g. after a re-prompt). Reset the
+ # cumulative cursor so the next assistant turn
+ # streams cleanly.
if not event["text"]:
prev_text = ""
- # Emit tool status as a custom SSE event
- # (including empty ones to clear UI badges)
+ # Emit tool status as a custom SSE event (including
+ # empty ones to clear UI badges)
status_data = json.dumps(
{
"type": "tool_status",
@@ -2915,10 +2882,9 @@ async def openai_chat_completions(
_stream_timings = event.get("timings")
continue
- # "content" type -- cumulative text
- # Sanitize the full cumulative then diff against
- # the last sanitized snapshot so cross-chunk XML
- # tags are handled correctly.
+ # "content" type -- cumulative text. Sanitize the full
+ # cumulative then diff against the last sanitized
+ # snapshot so cross-chunk XML tags are handled correctly.
raw_cumulative = event.get("text", "")
clean_cumulative = _TOOL_XML_RE.sub("", raw_cumulative)
new_text = clean_cumulative[len(prev_text) :]
@@ -2950,7 +2916,7 @@ async def openai_chat_completions(
],
)
yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
- # Usage chunk (OpenAI-standard: choices=[], usage populated)
+ # Usage chunk (OpenAI standard: choices=[], usage populated)
if _stream_usage or _stream_timings:
usage_obj = CompletionUsage(
prompt_tokens = (_stream_usage or {}).get("prompt_tokens", 0),
@@ -3038,8 +3004,8 @@ async def openai_chat_completions(
)
yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
- # Iterate the synchronous generator in a thread so
- # the event loop stays free for disconnect detection.
+ # Iterate the sync generator in a thread so the event loop
+ # stays free for disconnect detection.
gen = gguf_generate()
prev_text = ""
_stream_usage = None
@@ -3053,7 +3019,7 @@ async def openai_chat_completions(
cumulative = await asyncio.to_thread(next, gen, _gguf_sentinel)
if cumulative is _gguf_sentinel:
break
- # Capture server metadata for final usage chunk
+ # Capture server metadata for the final usage chunk
if isinstance(cumulative, dict):
if cumulative.get("type") == "metadata":
_stream_usage = cumulative.get("usage")
@@ -3094,7 +3060,7 @@ async def openai_chat_completions(
],
)
yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
- # Usage chunk (OpenAI-standard: choices=[], usage populated)
+ # Usage chunk (OpenAI standard: choices=[], usage populated)
if _stream_usage or _stream_timings:
usage_obj = CompletionUsage(
prompt_tokens = (_stream_usage or {}).get("prompt_tokens", 0),
@@ -3213,10 +3179,10 @@ async def openai_chat_completions(
created = int(time.time())
# ── Safetensors tool-calling path ─────────────────────────
- # Mirrors the GGUF agentic loop's event shape. Disabled for
- # vision turns (untested overlap with image render slot) and
- # for gpt-oss (Harmony uses dedicated channels, not <tool_call>
- # XML -- gpt-oss tools still work via the GGUF path).
+ # Mirrors the GGUF agentic loop's event shape. Disabled for vision turns
+ # (untested overlap with image render slot) and for gpt-oss (Harmony uses
+ # dedicated channels, not <tool_call> XML -- gpt-oss tools still work via
+ # the GGUF path).
_sf_is_gptoss = False
try:
_sf_is_gptoss = bool(hasattr(backend, "_is_gpt_oss_model") and backend._is_gpt_oss_model())
@@ -3258,8 +3224,8 @@ async def openai_chat_completions(
_sf_tools_to_use = _sf_tools_to_use + await get_enabled_mcp_tools()
# Mirror the GGUF path: refuse to enter the tool loop when nothing
- # survived, so a model-emitted built-in call cannot piggy-back on
- # the empty allow-list.
+ # survived, so a model-emitted built-in call can't piggy-back on the
+ # empty allow-list.
if not _sf_tools_to_use:
_sf_use_tools = False
@@ -3474,8 +3440,8 @@ async def openai_chat_completions(
raise
except Exception:
backend.reset_generation_state()
- # Generic wire message; full trace stays in the log
- # (CWE-209: transformers/torch errors may leak paths).
+ # Generic wire message; full trace stays in the log (CWE-209:
+ # transformers/torch errors may leak paths).
logger.exception("safetensors tool stream error")
error_chunk = {
"error": {
@@ -3547,8 +3513,8 @@ async def openai_chat_completions(
max_new_tokens = payload.max_tokens or 2048,
repetition_penalty = payload.repetition_penalty,
)
- # Forward reasoning kwargs; the worker/template wrapper peels off
- # any the template doesn't accept.
+ # Forward reasoning kwargs; the worker/template wrapper peels off any the
+ # template doesn't accept.
if payload.enable_thinking is not None:
gen_kwargs["enable_thinking"] = payload.enable_thinking
if payload.reasoning_effort is not None:
@@ -3599,12 +3565,12 @@ async def openai_chat_completions(
yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
prev_text = ""
- # Run sync generator in thread pool to avoid blocking
- # the event loop. Critical for compare mode: two SSE
- # requests arrive concurrently but the orchestrator
- # serializes them via _gen_lock. Without run_in_executor
- # the second request's blocking lock acquisition would
- # freeze the entire event loop, stalling both streams.
+ # Run the sync generator in a thread pool to avoid blocking the
+ # event loop. Critical for compare mode: two SSE requests arrive
+ # concurrently but the orchestrator serializes them via
+ # _gen_lock; without run_in_executor the second request's
+ # blocking lock acquisition would freeze the entire event loop,
+ # stalling both streams.
_DONE = object() # sentinel for generator exhaustion
loop = asyncio.get_event_loop()
gen = generate()
@@ -3613,8 +3579,8 @@ async def openai_chat_completions(
backend.reset_generation_state()
break
# next(gen, _DONE) returns _DONE instead of raising
- # StopIteration — StopIteration cannot propagate
- # through asyncio futures (Python limitation).
+ # StopIteration -- StopIteration can't propagate through
+ # asyncio futures (Python limitation).
cumulative = await loop.run_in_executor(None, next, gen, _DONE)
if cumulative is _DONE:
break
@@ -3750,8 +3716,8 @@ async def serve_sandbox_file(
"""
Serve image files created by Python tool execution.
- Accepts auth via Authorization header OR ?token= query param
- (needed because <img src> cannot send custom headers).
+ Accepts auth via Authorization header OR ?token= query param (needed
+ because <img src> cannot send custom headers).
"""
from fastapi.responses import FileResponse
@@ -3863,8 +3829,8 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
"""
OpenAI-compatible text completions endpoint (non-chat).
- Transparently proxies to the running llama-server's ``/v1/completions``.
- Only available when a GGUF model is loaded.
+ Proxies to the running llama-server's ``/v1/completions``. Only available
+ when a GGUF model is loaded.
"""
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
@@ -3880,15 +3846,14 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
if is_stream:
async def _stream():
- # Manual httpx client/response lifecycle AND explicit
- # aiter_bytes() iterator close — see _anthropic_passthrough_stream
- # for the full rationale. Saving `bytes_iter = resp.aiter_bytes()`
- # and `await bytes_iter.aclose()` in the finally block is the
- # part that matters for avoiding the Python 3.13 + httpcore
- # 1.0.x "Exception ignored in: <async_generator>" / anyio
- # cancel-scope trace: an anonymous async for leaves the
- # iterator unclosed, so Python's asyncgen GC finalizer runs
- # cleanup on a later pass in a different asyncio task.
+ # Manual httpx client/response lifecycle AND explicit aiter_bytes()
+ # iterator close -- see _anthropic_passthrough_stream for the full
+ # rationale. Saving `bytes_iter = resp.aiter_bytes()` and `await
+ # bytes_iter.aclose()` in finally is what avoids the Python 3.13 +
+ # httpcore 1.0.x "Exception ignored in: <async_generator>" / anyio
+ # cancel-scope trace: an anonymous async for leaves the iterator
+ # unclosed, so the asyncgen GC finalizer runs cleanup later in a
+ # different asyncio task.
client = httpx.AsyncClient(timeout = 600)
resp = None
bytes_iter = None
@@ -3937,10 +3902,10 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
"""
OpenAI-compatible embeddings endpoint.
- Transparently proxies to the running llama-server's ``/v1/embeddings``.
- Only available when a GGUF model is loaded.
- Note: the loaded model must support pooling; otherwise llama-server
- will return an error (expected).
+ Proxies to the running llama-server's ``/v1/embeddings``. Only available
+ when a GGUF model is loaded.
+ Note: the loaded model must support pooling, else llama-server returns an
+ error (expected).
"""
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
@@ -3981,9 +3946,9 @@ def _translate_responses_tools_to_chat(tools: Optional[list[dict]]) -> Optional[
"parameters": {...}, "strict": true}}
Only ``type=="function"`` entries are forwarded. Built-in Responses tools
- (``web_search``, ``file_search``, ``mcp``, ...) are dropped because
- llama-server does not implement them server-side; keeping them in the
- request would produce an opaque upstream 400.
+ (``web_search``, ``file_search``, ``mcp``, ...) are dropped: llama-server
+ doesn't implement them server-side, so keeping them would produce an opaque
+ upstream 400.
"""
if not tools:
return None
@@ -4010,8 +3975,8 @@ def _translate_responses_tool_choice_to_chat(tool_choice: Any) -> Any:
"""Translate a Responses-shape ``tool_choice`` to the Chat Completions shape.
String values (``"auto"``/``"none"``/``"required"``) pass through unchanged.
- The Responses forcing object ``{"type": "function", "name": "X"}`` is
- converted to Chat Completions' ``{"type": "function", "function": {"name": "X"}}``.
+ The Responses forcing object ``{"type": "function", "name": "X"}`` becomes
+ Chat Completions' ``{"type": "function", "function": {"name": "X"}}``.
Unknown / built-in tool choices are forwarded as-is; llama-server ignores
what it doesn't recognise.
"""
@@ -4046,28 +4011,26 @@ def _responses_message_text(content: Union[str, list]) -> str:
def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
- """Convert a ResponsesRequest's ``input`` into Chat-format ``ChatMessage`` list.
+ """Convert a ResponsesRequest's ``input`` into a Chat-format ``ChatMessage`` list.
Handles the three input item shapes allowed by the Responses API:
- - ``ResponsesInputMessage`` — regular chat messages (text or multimodal).
- - ``ResponsesFunctionCallInputItem`` — a prior assistant tool call replayed
- on a follow-up turn. Converted into an assistant message carrying a
+ - ``ResponsesInputMessage`` -- regular chat messages (text or multimodal).
+ - ``ResponsesFunctionCallInputItem`` -- a prior assistant tool call
+ replayed on a follow-up turn. Becomes an assistant message carrying a
Chat Completions ``tool_calls`` entry keyed by ``call_id``.
- - ``ResponsesFunctionCallOutputInputItem`` — a tool result the client is
- returning. Converted into a ``role="tool"`` message with ``tool_call_id``
- set to the originating ``call_id`` so llama-server can reconcile the
- call with its result.
-
- System / developer content is collected from ``instructions`` *and* from
- any ``role="system"`` / ``role="developer"`` entries in ``input``, then
- merged into a single ``role="system"`` message placed at the top of the
- returned list. This satisfies strict chat templates (harmony / gpt-oss,
- Qwen3, ...) whose Jinja raises ``"System message must be at the
- beginning."`` when more than one system message is present or when a
- system message appears after a user turn — the exact pattern the OpenAI
- Codex CLI hits, since Codex sets ``instructions`` *and* also sends a
- developer message in ``input``.
+ - ``ResponsesFunctionCallOutputInputItem`` -- a tool result the client is
+ returning. Becomes a ``role="tool"`` message with ``tool_call_id`` set to
+ the originating ``call_id`` so llama-server can reconcile call with result.
+
+ System / developer content is collected from ``instructions`` *and* any
+ ``role="system"`` / ``role="developer"`` entries in ``input``, then merged
+ into a single top-of-list ``role="system"`` message. This satisfies strict
+ chat templates (harmony / gpt-oss, Qwen3, ...) whose Jinja raises
+ ``"System message must be at the beginning."`` when more than one system
+ message is present or a system message follows a user turn -- the exact
+ pattern the OpenAI Codex CLI hits, since Codex sets ``instructions`` *and*
+ also sends a developer message in ``input``.
"""
system_parts: list[str] = []
messages: list[ChatMessage] = []
@@ -4105,8 +4068,8 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
continue
if isinstance(item, ResponsesFunctionCallOutputInputItem):
- # Chat Completions `role="tool"` requires a string content; if a
- # Responses client sends a content-array output, serialize it.
+ # Chat Completions `role="tool"` requires string content; serialize
+ # a Responses content-array output.
output = item.output
if not isinstance(output, str):
output = json.dumps(output)
@@ -4120,13 +4083,13 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
continue
if isinstance(item, ResponsesUnknownInputItem):
- # Reasoning items and any other unmodelled top-level Responses
- # item types are silently dropped — llama-server-backed GGUFs
- # cannot consume them and our lenient validation let them in so
- # unrelated turns don't 422.
+ # Reasoning items and other unmodelled top-level Responses item
+ # types are silently dropped -- llama-server-backed GGUFs can't
+ # consume them; lenient validation lets them in so unrelated turns
+ # don't 422.
continue
- # ResponsesInputMessage — hoist system/developer to the top, merge.
+ # ResponsesInputMessage -- hoist system/developer to the top, merge.
if item.role in ("system", "developer"):
hoisted = _responses_message_text(item.content)
if hoisted:
@@ -4139,16 +4102,16 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
# Assistant-replay turns come back as content = [output_text, ...].
# Chat Completions' assistant role expects a plain string, not a
- # multimodal content array, so flatten output_text (and any stray
- # input_text / unknown text) to a single string.
+ # multimodal array, so flatten output_text (and any stray input_text /
+ # unknown text) to a single string.
if item.role == "assistant":
text = _responses_message_text(item.content)
if text:
messages.append(ChatMessage(role = "assistant", content = text))
continue
- # User (and any other remaining roles) — keep multimodal when
- # present, drop unknown content parts silently.
+ # User (and any other remaining roles) -- keep multimodal when present,
+ # drop unknown content parts silently.
parts: list = []
for part in item.content:
if isinstance(part, (ResponsesInputTextPart, ResponsesOutputTextPart)):
@@ -4162,9 +4125,8 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
)
# ResponsesUnknownContentPart and anything else: drop.
if parts:
- # Collapse single-text-part content to a plain string so roles
- # that reject multimodal arrays (e.g. legacy templates) still
- # accept the message.
+ # Collapse single-text-part content to a plain string so roles that
+ # reject multimodal arrays (e.g. legacy templates) still accept it.
if len(parts) == 1 and isinstance(parts[0], TextContentPart):
messages.append(ChatMessage(role = item.role, content = parts[0].text))
else:
@@ -4183,8 +4145,7 @@ def _build_chat_request(
Tools and ``tool_choice`` are translated from the flat Responses shape to
the nested Chat Completions shape here so the existing #5099
- ``/v1/chat/completions`` client-side pass-through picks them up without
- further modification.
+ ``/v1/chat/completions`` client-side pass-through picks them up unchanged.
"""
chat_kwargs: dict = dict(
model = payload.model,
@@ -4207,11 +4168,11 @@ def _build_chat_request(
chat_kwargs["tool_choice"] = chat_tool_choice
req = ChatCompletionRequest(**chat_kwargs)
- # `parallel_tool_calls` is not a first-class field on ChatCompletionRequest,
+ # `parallel_tool_calls` isn't a first-class field on ChatCompletionRequest,
# but the model allows extras and _build_openai_passthrough_body forwards
- # only explicitly-known fields. Llama-server does not currently implement
- # parallel_tool_calls semantics, so we accept-and-ignore it on the
- # Responses side to avoid breaking SDK clients that always send it.
+ # only known fields. Llama-server doesn't implement parallel_tool_calls
+ # semantics, so accept-and-ignore it on the Responses side to avoid breaking
+ # SDK clients that always send it.
return req
@@ -4219,9 +4180,8 @@ def _chat_tool_calls_to_responses_output(tool_calls: list[dict]) -> list[dict]:
"""Map Chat Completions ``tool_calls`` into Responses ``function_call`` output items.
The Chat Completions id (``call_xxx``) is the shared correlation key across
- turns in the OpenAI Responses API — it is stored as ``call_id`` on the
- output item and must be echoed back by the client as
- ``function_call_output.call_id`` on the next turn.
+ turns in the Responses API -- stored as ``call_id`` on the output item and
+ echoed back by the client as ``function_call_output.call_id`` next turn.
"""
items: list[dict] = []
for tc in tool_calls:
@@ -4246,7 +4206,7 @@ async def _responses_non_streaming(
chat_req = _build_chat_request(payload, messages, stream = False)
result = await openai_chat_completions(chat_req, request)
- # openai_chat_completions returns a JSONResponse for non-streaming
+ # openai_chat_completions returns a JSONResponse for non-streaming.
if isinstance(result, JSONResponse):
body = json.loads(result.body.decode())
elif isinstance(result, Response):
@@ -4269,10 +4229,9 @@ async def _responses_non_streaming(
resp_id = f"resp_{uuid.uuid4().hex[:12]}"
# Responses API emits each tool call as its own top-level output item,
- # alongside an optional assistant text message. Emit the text message
- # only when the model actually produced content, so clients that expect
- # a pure tool-call turn (finish_reason="tool_calls") don't see a spurious
- # empty message item.
+ # plus an optional assistant text message. Emit the text message only when
+ # the model produced content, so clients expecting a pure tool-call turn
+ # (finish_reason="tool_calls") don't see a spurious empty message item.
output_items: list[dict] = []
if text:
msg_id = f"msg_{uuid.uuid4().hex[:12]}"
@@ -4311,24 +4270,23 @@ async def _responses_stream(
"""Handle a streaming Responses API call, emitting named SSE events.
For GGUF models the request goes directly to llama-server's
- ``/v1/chat/completions`` endpoint from inside the StreamingResponse
- child task — a single httpx lifecycle, a single async generator.
- Wrapping the existing ``openai_chat_completions`` pass-through (which
- already does its own httpx lifecycle) stacks two generators: Python
- 3.13 + httpcore 1.0.x then loses the close-propagation chain on the
- innermost ``HTTP11ConnectionByteStream`` at asyncgen finalisation,
- tripping "Attempted to exit cancel scope in a different task" /
- "async generator ignored GeneratorExit". The direct path avoids that
- altogether. Non-GGUF falls back to the wrapper (which doesn't use
- httpx, so the issue doesn't apply).
+ ``/v1/chat/completions`` from inside the StreamingResponse child task -- one
+ httpx lifecycle, one async generator. Wrapping the existing
+ ``openai_chat_completions`` pass-through (which has its own httpx lifecycle)
+ stacks two generators: Python 3.13 + httpcore 1.0.x then loses the
+ close-propagation chain on the innermost ``HTTP11ConnectionByteStream`` at
+ asyncgen finalisation, tripping "Attempted to exit cancel scope in a
+ different task" / "async generator ignored GeneratorExit". The direct path
+ avoids that. Non-GGUF falls back to the wrapper (which doesn't use httpx, so
+ the issue doesn't apply).
Text deltas arrive as ``response.output_text.delta`` on a single
``message`` output item at ``output_index=0``. Each tool call from
``delta.tool_calls[]`` is promoted to its own top-level ``function_call``
- output item (one per distinct ``tool_calls[].index``), and relayed as
+ output item (one per distinct ``tool_calls[].index``) and relayed as
``response.function_call_arguments.delta`` / ``.done`` events so clients
- (Codex, OpenAI Python SDK) can reconstruct the call incrementally and
- reply with a ``function_call_output`` item on the next turn.
+ (Codex, OpenAI Python SDK) can reconstruct the call incrementally and reply
+ with a ``function_call_output`` item next turn.
"""
resp_id = f"resp_{uuid.uuid4().hex[:12]}"
msg_id = f"msg_{uuid.uuid4().hex[:12]}"
@@ -4338,13 +4296,12 @@ async def _responses_stream(
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
- # The direct pass-through is GGUF-only. Non-GGUF /v1/responses
- # streaming isn't a Codex-compatible path today and wrapping the
- # transformers backend's streaming generator here would re-
- # introduce the double-layer asyncgen close pattern that produces
- # "Attempted to exit cancel scope in a different task" on Python
- # 3.13. Surface a typed 400 so the client sees a useful error
- # instead of a dangling stream.
+ # The direct pass-through is GGUF-only. Non-GGUF /v1/responses streaming
+ # isn't a Codex-compatible path today, and wrapping the transformers
+ # backend's streaming generator here would re-introduce the
+ # double-layer asyncgen close pattern that produces "Attempted to exit
+ # cancel scope in a different task" on Python 3.13. Surface a typed 400
+ # so the client sees a useful error instead of a dangling stream.
raise HTTPException(
status_code = 400,
detail = (
@@ -4371,8 +4328,8 @@ async def _responses_stream(
full_text = ""
input_tokens = 0
output_tokens = 0
- # Per-tool-call state keyed by the Chat Completions `tool_calls[].index`
- # which stays stable across chunks for the same call. Values are:
+ # Per-tool-call state keyed by Chat Completions `tool_calls[].index`,
+ # stable across chunks for the same call. Values:
# {output_index, item_id, call_id, name, arguments, opened}
tool_call_state: dict[int, dict] = {}
# Text message lives at output_index 0; tool calls claim 1, 2, ...
@@ -4426,11 +4383,11 @@ async def _responses_stream(
yield f"event: response.content_part.added\ndata: {json.dumps({'type': 'response.content_part.added', 'item_id': msg_id, 'output_index': 0, 'content_index': 0, 'part': content_part})}\n\n"
# ── Direct httpx lifecycle to llama-server ──
- # Full same-task open + close, identical pattern to
- # _openai_passthrough_stream and _anthropic_passthrough_stream:
- # no `async with`, explicit aclose of lines_iter BEFORE resp /
- # client so the innermost httpcore byte stream is finalised in
- # this task (not via Python's asyncgen GC in a sibling task).
+ # Full same-task open + close, same pattern as
+ # _openai_passthrough_stream and _anthropic_passthrough_stream: no
+ # `async with`, explicit aclose of lines_iter BEFORE resp / client so
+ # the innermost httpcore byte stream is finalised in this task (not via
+ # the asyncgen GC in a sibling task).
client = httpx.AsyncClient(timeout = 600)
resp = None
lines_iter = None
@@ -4496,7 +4453,7 @@ async def _responses_stream(
st = tool_call_state.get(idx)
fn = tc.get("function") or {}
if st is None:
- # First chunk for this tool call — allocate an
+ # First chunk for this tool call -- allocate an
# output_index and emit output_item.added.
st = {
"output_index": next_output_index,
@@ -4509,8 +4466,8 @@ async def _responses_stream(
next_output_index += 1
tool_call_state[idx] = st
else:
- # Later chunks sometimes carry the id/name only
- # once; merge when present.
+ # Later chunks sometimes carry id/name only once; merge
+ # when present.
if tc.get("id") and not st["call_id"]:
st["call_id"] = tc["id"]
if fn.get("name") and not st["name"]:
@@ -4543,9 +4500,9 @@ async def _responses_stream(
}
yield f"event: response.function_call_arguments.delta\ndata: {json.dumps(args_delta_event)}\n\n"
elif arg_delta:
- # Buffer the args until we can open the item
- # (id/name arrive in the same chunk as the first
- # arg delta for some models — but if not, stash).
+ # Buffer args until we can open the item (some models
+ # send id/name in the same chunk as the first arg delta;
+ # if not, stash).
st["arguments"] += arg_delta
usage = chunk_data.get("usage")
@@ -4572,8 +4529,8 @@ async def _responses_stream(
# ── Closing events for tool calls ──
for st in sorted(tool_call_state.values(), key = lambda s: s["output_index"]):
- # If id/name never arrived (malformed upstream), synthesise so
- # the client still sees a coherent frame sequence.
+ # If id/name never arrived (malformed upstream), synthesise so the
+ # client still sees a coherent frame sequence.
if not st["opened"]:
if not st["call_id"]:
st["call_id"] = f"call_{uuid.uuid4().hex[:12]}"
@@ -4676,10 +4633,9 @@ async def openai_responses(
"""
OpenAI Responses API endpoint.
- Accepts the Responses-format request, converts it to a
- ChatCompletionRequest internally, and returns a response
- matching the OpenAI Responses API schema (output array,
- input_tokens/output_tokens, named SSE events for streaming).
+ Accepts a Responses-format request, converts it to a ChatCompletionRequest
+ internally, and returns a response matching the Responses API schema
+ (output array, input_tokens/output_tokens, named SSE events for streaming).
"""
messages = _normalise_responses_input(payload)
if not messages:
@@ -4713,9 +4669,9 @@ def _anthropic_requested_studio_tools(tools: Optional[list]) -> set[str]:
# Client tools always carry input_schema; server tools never do.
if td.get("input_schema") is not None:
continue
- # Anthropic dispatches server tools by `type` (not by bare `name`);
- # matching name too would let a malformed client tool like
- # `{"name": "python"}` silently flip into server-execution mode.
+ # Anthropic dispatches server tools by `type`, not bare `name`; matching
+ # name too would let a malformed client tool like `{"name": "python"}`
+ # silently flip into server-execution mode.
type_ = td.get("type")
if isinstance(type_, str) and type_ in _STUDIO_ANTHROPIC_TOOL_ALIASES:
requested.add(_STUDIO_ANTHROPIC_TOOL_ALIASES[type_])
@@ -4737,19 +4693,18 @@ def _select_anthropic_server_tools(
def _normalize_anthropic_openai_images(openai_messages: list[dict], is_vision: bool) -> bool:
- """Enforce the vision guard on translated Anthropic messages and
- normalize any ``image_url`` parts with base64 data URLs to PNG.
+ """Enforce the vision guard on translated Anthropic messages and normalize
+ any base64-data-URL ``image_url`` parts to PNG.
llama-server's stb_image only handles a few formats (JPEG/PNG/BMP/…);
- Anthropic clients commonly send JPEG or WebP, and Claude Code sends
- WebP. Re-encoding everything to PNG mirrors the behavior of
- `_openai_messages_for_passthrough` / the GGUF branch of
- `/v1/chat/completions` so the two endpoints agree.
-
- Mutates ``openai_messages`` in place. Returns ``True`` when any
- image part was seen (so the caller can skip a second scan). Raises
- HTTPException(400) when images are present but the active model is
- not a vision model, or when an image cannot be decoded.
+ Anthropic clients commonly send JPEG or WebP, and Claude Code sends WebP.
+ Re-encoding everything to PNG mirrors `_openai_messages_for_passthrough` /
+ the GGUF branch of `/v1/chat/completions` so the two endpoints agree.
+
+ Mutates ``openai_messages`` in place. Returns ``True`` when any image part
+ was seen (so the caller can skip a second scan). Raises HTTPException(400)
+ when images are present but the active model isn't a vision model, or when
+ an image cannot be decoded.
"""
from PIL import Image
@@ -4815,10 +4770,10 @@ async def anthropic_messages(
"""
Anthropic-compatible Messages API endpoint.
- Translates Anthropic message format to internal OpenAI format, runs
- through the existing agentic tool loop when tools are provided, and
- returns responses in Anthropic Messages API format (streaming SSE or
- non-streaming JSON).
+ Translates Anthropic message format to internal OpenAI format, runs through
+ the existing agentic tool loop when tools are provided, and returns
+ responses in Anthropic Messages API format (streaming SSE or non-streaming
+ JSON).
"""
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
@@ -4837,18 +4792,17 @@ async def anthropic_messages(
)
# Strip synthetic provider-side builtin tool history (web_search,
# web_fetch, code_execution, image_generation cards tagged with
- # _server_tool or extra_content.google.native_part) before handing
- # off to local llama-server. The local /v1/chat/completions and
- # GGUF passthrough builders apply the same strip; without it an
- # Anthropic /v1/messages caller replaying a prior provider-side
- # tool_use forwards fake builtin tool history to a backend that
- # has no matching function declarations.
+ # _server_tool or extra_content.google.native_part) before handing off to
+ # local llama-server. The local /v1/chat/completions and GGUF passthrough
+ # builders apply the same strip; without it an Anthropic /v1/messages caller
+ # replaying a prior provider-side tool_use forwards fake builtin tool
+ # history to a backend with no matching function declarations.
openai_messages = _strip_provider_synthetic_tool_history(
_drop_empty_assistant_sentinels(openai_messages)
)
- # Enforce vision guard + re-encode embedded images to PNG so the
- # Anthropic endpoint matches the behavior of /v1/chat/completions.
+ # Enforce vision guard + re-encode embedded images to PNG so the Anthropic
+ # endpoint matches /v1/chat/completions.
_has_image = _normalize_anthropic_openai_images(openai_messages, llama_backend.is_vision)
temperature = payload.temperature if payload.temperature is not None else 0.6
@@ -4861,9 +4815,8 @@ async def anthropic_messages(
presence_penalty = payload.presence_penalty if payload.presence_penalty is not None else 0.0
stop = payload.stop_sequences or None
- # Translate Anthropic tool_choice to OpenAI format for forwarding to
- # llama-server. Falls back to "auto" when unset or unrecognized, which
- # matches the prior hardcoded behavior.
+ # Translate Anthropic tool_choice to OpenAI format for llama-server. Falls
+ # back to "auto" when unset or unrecognized (prior hardcoded behavior).
openai_tool_choice = anthropic_tool_choice_to_openai(payload.tool_choice)
if openai_tool_choice is None:
openai_tool_choice = "auto"
@@ -4875,17 +4828,17 @@ async def anthropic_messages(
# 1. enable_tools=true → server-side execution of built-in tools (Unsloth shorthand)
# 2. tools=[...] only → client-side pass-through (standard Anthropic behavior)
# 3. neither → plain chat
- # Server-side agentic loop doesn't support multimodal input — matches
+ # The server-side agentic loop doesn't support multimodal input -- matches
# the `not image_b64` gate in /v1/chat/completions.
requested_studio_tools = _anthropic_requested_studio_tools(payload.tools)
- # Reject malformed client tools at the boundary. AnthropicTool was
- # relaxed to Optional[name]/Optional[input_schema] for server tools,
- # so the converter silently drops incomplete entries — surface them
- # as 400. A `type` field marks a server-tool declaration per spec
- # (unrecognized server tools are accepted as no-ops); anything else
- # without input_schema or name is malformed and must not be allowed
- # to silently flip execution mode or disable tool calling.
+ # Reject malformed client tools at the boundary. AnthropicTool was relaxed
+ # to Optional[name]/Optional[input_schema] for server tools, so the
+ # converter silently drops incomplete entries -- surface them as 400. A
+ # `type` field marks a server-tool declaration per spec (unrecognized server
+ # tools are accepted as no-ops); anything else without input_schema or name
+ # is malformed and must not be allowed to silently flip execution mode or
+ # disable tool calling.
for tool in payload.tools or []:
td = tool if isinstance(tool, dict) else tool.model_dump()
name, type_, schema = td.get("name"), td.get("type"), td.get("input_schema")
@@ -4900,17 +4853,17 @@ async def anthropic_messages(
detail = "Client tool is missing required field 'name'.",
)
- # Detect client tools from the raw payload (presence of input_schema)
- # so the mixed-mode check below isn't fooled by a name collision with
- # a server-tool alias that the post-filter would silently drop.
+ # Detect client tools from the raw payload (presence of input_schema) so the
+ # mixed-mode check below isn't fooled by a name collision with a server-tool
+ # alias that the post-filter would silently drop.
_has_client_tool = any(
(t if isinstance(t, dict) else t.model_dump()).get("input_schema") is not None
for t in payload.tools or []
)
- # The server-tool agentic loop executes tools in-process and cannot
- # relay unknown client functions back to the caller, so mixed requests
- # would silently drop the client tools. Reject explicitly instead.
+ # The server-tool agentic loop executes tools in-process and can't relay
+ # unknown client functions back to the caller, so mixed requests would
+ # silently drop the client tools. Reject explicitly instead.
if requested_studio_tools and _has_client_tool:
raise HTTPException(
status_code = 400,
@@ -4927,9 +4880,9 @@ async def anthropic_messages(
if tool.get("function", {}).get("name") not in requested_studio_tools
]
- # An Anthropic server-tool declaration implies server-tool mode, but
- # only when tools aren't explicitly disabled (CLI --disable-tools or
- # per-request enable_tools=false). Explicit False always wins.
+ # An Anthropic server-tool declaration implies server-tool mode, but only
+ # when tools aren't explicitly disabled (CLI --disable-tools or per-request
+ # enable_tools=false). Explicit False always wins.
_enable = _effective_enable_tools(payload)
server_tools = (
(_enable or (_enable is None and bool(requested_studio_tools)))
@@ -4991,7 +4944,7 @@ async def anthropic_messages(
payload.enabled_tools,
)
- # Build tool-use system prompt nudge (same logic as /chat/completions)
+ # Build tool-use system prompt nudge (same as /chat/completions)
_tool_names = {t["function"]["name"] for t in openai_tools}
_has_web = "web_search" in _tool_names
_has_code = "python" in _tool_names or "terminal" in _tool_names
@@ -5205,15 +5158,14 @@ async def _anthropic_tool_non_streaming(run_gen, message_id, model_name):
"""Non-streaming response for the tool-calling path.
Builds ``content_blocks`` in generation order (text → tool_use → text →
- tool_use → ...), mirroring the streaming emitter's behavior. Deltas
- within a single synthesis turn are merged into the trailing text block;
- tool_use blocks interrupt the text sequence and open a new text block on
- the next content event.
+ tool_use → ...), mirroring the streaming emitter. Deltas within one
+ synthesis turn merge into the trailing text block; tool_use blocks interrupt
+ the text sequence and open a new text block on the next content event.
``prev_text`` is reset on ``tool_end`` because
``generate_chat_completion_with_tools`` yields cumulative content *per
- turn* — the first content event of turn N+1 must diff against an empty
- baseline, not against turn N's final length.
+ turn* -- the first content event of turn N+1 must diff against an empty
+ baseline, not turn N's final length.
"""
content_blocks: list = []
tool_blocks_by_id: dict[str, AnthropicResponseToolUseBlock] = {}
@@ -5344,20 +5296,20 @@ def _build_passthrough_payload(
if min_p is not None:
body["min_p"] = min_p
if repetition_penalty is not None:
- # llama-server's field is "repeat_penalty", not "repetition_penalty"
+ # llama-server's field is "repeat_penalty", not "repetition_penalty".
body["repeat_penalty"] = repetition_penalty
if presence_penalty is not None:
body["presence_penalty"] = presence_penalty
if response_format is not None:
- # llama-server applies a GBNF grammar derived from the JSON schema
- # when response_format is present. Field is documented flat at the
- # request root (tools/server/README.md), which is also what the
- # OpenAI SDK produces by spreading extra_body into the body top.
+ # llama-server applies a GBNF grammar derived from the JSON schema when
+ # response_format is present. The field is documented flat at the
+ # request root (tools/server/README.md), which is also what the OpenAI
+ # SDK produces by spreading extra_body into the body top.
body["response_format"] = response_format
if chat_template_kwargs is not None:
- # Propagate reasoning / template overrides (e.g. enable_thinking)
- # so llama-server renders the Jinja template in the mode the caller
- # asked for instead of whatever default the model was loaded with.
+ # Propagate reasoning / template overrides (e.g. enable_thinking) so
+ # llama-server renders the Jinja template in the caller's mode instead
+ # of the model's load-time default.
body["chat_template_kwargs"] = chat_template_kwargs
return body
@@ -5383,7 +5335,7 @@ async def _anthropic_passthrough_stream(
cancel_id = None,
):
"""Streaming client-side pass-through: forward tools to llama-server and
- translate its streaming response to Anthropic SSE without executing anything."""
+ translate its stream to Anthropic SSE without executing anything."""
target_url = f"{llama_backend.base_url}/v1/chat/completions"
body = _build_passthrough_payload(
openai_messages,
@@ -5401,8 +5353,8 @@ async def _anthropic_passthrough_stream(
backend_ctx = llama_backend.context_length,
)
- # cancel_id mirrors the OpenAI passthrough so a per-run cancel POST
- # works without the caller having to know the local message_id.
+ # cancel_id mirrors the OpenAI passthrough so a per-run cancel POST works
+ # without the caller knowing the local message_id.
_tracker = _TrackedCancel(cancel_event, cancel_id, session_id, message_id)
_tracker.__enter__()
@@ -5412,32 +5364,28 @@ async def _anthropic_passthrough_stream(
yield line
# Manage the httpx client, response, AND the aiter_lines() async
- # generator MANUALLY — no `async with`, no anonymous iterator.
+ # generator MANUALLY -- no `async with`, no anonymous iterator.
#
# On Python 3.13 + httpcore 1.0.x, `async for raw_line in
- # resp.aiter_lines():` creates an anonymous async generator. When
- # the loop exits via `break` (or the generator is orphaned when a
- # client disconnects mid-stream), Python's `async for` protocol
- # does NOT auto-close the iterator the way a sync `for` loop
- # would. The iterator remains reachable only from the current
- # coroutine frame; once `_stream()` returns, the frame is GC'd
- # and the iterator becomes unreachable. Python's asyncgen
- # finalizer hook then runs its aclose() on a LATER GC pass in a
- # DIFFERENT asyncio task, where httpcore's
- # `HTTP11ConnectionByteStream.aclose()` enters
- # `anyio.CancelScope.__exit__` with a mismatched task and prints
- # `RuntimeError: Attempted to exit cancel scope in a different
- # task` / `RuntimeError: async generator ignored GeneratorExit`
- # as "Exception ignored in:" unraisable warnings.
+ # resp.aiter_lines():` creates an anonymous async generator. When the
+ # loop exits via `break` (or the generator is orphaned by a mid-stream
+ # client disconnect), `async for` does NOT auto-close the iterator like
+ # a sync `for` would. The iterator stays reachable only from the current
+ # coroutine frame; once `_stream()` returns, the frame is GC'd and the
+ # iterator becomes unreachable. The asyncgen finalizer then runs aclose()
+ # on a LATER GC pass in a DIFFERENT asyncio task, where httpcore's
+ # `HTTP11ConnectionByteStream.aclose()` enters `anyio.CancelScope.__exit__`
+ # with a mismatched task and prints `RuntimeError: Attempted to exit
+ # cancel scope in a different task` / `RuntimeError: async generator
+ # ignored GeneratorExit` as "Exception ignored in:" unraisable warnings.
#
- # The fix: save `resp.aiter_lines()` as `lines_iter`, and in the
- # finally block explicitly `await lines_iter.aclose()` BEFORE
- # `resp.aclose()` / `client.aclose()`. This closes the iterator
- # inside our own task's event loop, so the internal httpcore
- # byte-stream is cleaned up before Python's asyncgen finalizer
- # has anything orphaned to finalize. Each aclose is wrapped in
- # `try: ... except Exception: pass` so anyio cleanup noise from
- # nested aclose paths can't bubble out.
+ # Fix: save `resp.aiter_lines()` as `lines_iter`, and in finally
+ # explicitly `await lines_iter.aclose()` BEFORE `resp.aclose()` /
+ # `client.aclose()`. This closes the iterator in our own task's event
+ # loop, cleaning up the httpcore byte-stream before the asyncgen
+ # finalizer has anything orphaned to finalize. Each aclose is wrapped in
+ # `try: ... except Exception: pass` so nested anyio cleanup noise can't
+ # bubble out.
client = httpx.AsyncClient(
timeout = 600,
limits = httpx.Limits(max_keepalive_connections = 0),
@@ -5449,10 +5397,10 @@ async def _anthropic_passthrough_stream(
req = client.build_request("POST", target_url, json = body)
resp = await client.send(req, stream = True)
- # See _openai_passthrough_stream for rationale: aiter_lines()
- # blocks during llama-server prefill, so the in-loop cancel
- # check is unreachable until the first SSE chunk arrives.
- # The watcher closes `resp` on cancel, raising in aiter_lines.
+ # See _openai_passthrough_stream for rationale: aiter_lines() blocks
+ # during llama-server prefill, so the in-loop cancel check is
+ # unreachable until the first SSE chunk arrives. The watcher closes
+ # `resp` on cancel, raising in aiter_lines.
cancel_watcher = asyncio.create_task(_await_cancel_then_close(cancel_event, resp))
lines_iter = resp.aiter_lines()
async for raw_line in lines_iter:
@@ -5629,19 +5577,18 @@ _LOCAL_SERVER_BUILTIN_TOOL_NAMES = frozenset(
def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
- """Drop synthetic provider-side tool_calls + matching role=tool replies
- on the local-backend (llama-server / GGUF) dispatch path.
+ """Drop synthetic provider-side tool_calls + matching role=tool replies on
+ the local-backend (llama-server / GGUF) dispatch path.
A Gemini chat that ran code_execution / image_generation persists the
- server-side tool card into thread history as an assistant tool_calls
- entry tagged with ``args._server_tool`` (or a Gemini
- ``args.google.native_part`` payload) plus a follow-up role=tool reply.
- When the user switches the SAME thread to a local GGUF model, those
- synthetic tool_calls are not real user functions, llama-server has no
- matching declaration, and Gemini-only ``extra_content`` /
- ``native_part`` payloads are meaningless. Forward only ordinary user
- function calls; strip the matched role=tool replies too so the
- backend does not see an orphan tool_call_id.
+ server-side tool card into history as an assistant tool_calls entry tagged
+ with ``args._server_tool`` (or a Gemini ``args.google.native_part`` payload)
+ plus a follow-up role=tool reply. When the user switches the SAME thread to
+ a local GGUF model, those synthetic tool_calls aren't real user functions,
+ llama-server has no matching declaration, and Gemini-only ``extra_content``
+ / ``native_part`` payloads are meaningless. Forward only ordinary user
+ function calls; strip the matched role=tool replies too so the backend never
+ sees an orphan tool_call_id.
"""
dropped_ids: set[str] = set()
sanitized_assistant: list[dict] = []
@@ -5653,12 +5600,10 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
if not isinstance(tool_calls, list) or not tool_calls:
# Plain text Gemini reply: still strip message-level
# `extra_content` (carries `google.thought_signature` replay
- # metadata) so a text-only Gemini turn switched to a local
- # GGUF backend does not leak Gemini-only fields to
- # llama-server. ChatMessage previously did not have
- # `extra_content`, so the field was implicitly dropped --
- # round-22 added it to ChatMessage, which is what made this
- # leak possible.
+ # metadata) so a text-only Gemini turn switched to a local GGUF
+ # backend doesn't leak Gemini-only fields to llama-server.
+ # ChatMessage didn't used to have `extra_content` (implicitly
+ # dropped); round-22 added it, which made this leak possible.
if "extra_content" in m:
m = {k: v for k, v in m.items() if k != "extra_content"}
sanitized_assistant.append(m)
@@ -5694,14 +5639,14 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
if isinstance(tc_id, str) and tc_id:
dropped_ids.add(tc_id)
continue
- # Strip Gemini-only `extra_content` on real user tool_calls
- # too — llama-server has no use for it and may pass it
- # through to the model unchanged.
+ # Strip Gemini-only `extra_content` on real user tool_calls too --
+ # llama-server has no use for it and may pass it to the model
+ # unchanged.
if "extra_content" in tc:
tc = {k: v for k, v in tc.items() if k != "extra_content"}
cleaned.append(tc)
- # Drop top-level message-level `extra_content` (Gemini
- # thoughtSignature replay metadata) on local dispatch.
+ # Drop message-level `extra_content` (Gemini thoughtSignature replay
+ # metadata) on local dispatch.
m_clean = {k: v for k, v in m.items() if k != "extra_content"}
if cleaned:
m_clean["tool_calls"] = cleaned
@@ -5729,17 +5674,16 @@ def _openai_messages_for_passthrough(payload) -> list[dict]:
"""Build OpenAI-format message dicts for the /v1/chat/completions
passthrough path.
- Messages from ``payload.messages`` are dumped through Pydantic (dropping
- unset optional fields) so they are already in standard OpenAI format
- — including ``role="tool"`` tool-result messages and assistant messages
- that carry structured ``tool_calls``. Content-parts images already in
- the message list are left untouched.
+ ``payload.messages`` are dumped through Pydantic (dropping unset optional
+ fields), so they're already standard OpenAI format -- including
+ ``role="tool"`` tool-result messages and assistant messages carrying
+ structured ``tool_calls``. Content-parts images already in the list are
+ left untouched.
When a client uses Studio's legacy ``image_base64`` top-level field, the
image is re-encoded to PNG (llama-server's stb_image has limited format
- support) and spliced into the last user message as an OpenAI
- ``image_url`` content part so vision + function-calling requests work
- transparently.
+ support) and spliced into the last user message as an OpenAI ``image_url``
+ content part so vision + function-calling requests work transparently.
"""
messages = _strip_provider_synthetic_tool_history(
_drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in payload.messages])
@@ -5787,9 +5731,9 @@ def _openai_messages_for_passthrough(payload) -> list[dict]:
def _openai_messages_for_gguf_chat(payload, is_vision: bool) -> tuple[list[dict], bool]:
"""Build llama-server messages for the standard GGUF chat path.
- llama-server accepts OpenAI multimodal content parts directly. Preserve
- all per-turn ``image_url`` parts so multi-image chat history keeps each
- image attached to its original turn.
+ llama-server accepts OpenAI multimodal content parts directly. Preserve all
+ per-turn ``image_url`` parts so multi-image chat history keeps each image
+ attached to its original turn.
"""
messages = _strip_provider_synthetic_tool_history(
_drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in payload.messages])
@@ -5827,10 +5771,10 @@ def _openai_messages_for_gguf_chat(payload, is_vision: bool) -> tuple[list[dict]
def _extract_response_format(payload):
"""Return the ``response_format`` field on an incoming ChatCompletionRequest
- (or None). The model is declared with ``extra="allow"`` so pydantic stashes
- unknown top-level fields in ``model_extra``; OpenAI-SDK clients spread
- ``extra_body`` into the request body top level, which is where guided-
- decoding recipes park their JSON-schema response_format.
+ (or None). The model uses ``extra="allow"`` so pydantic stashes unknown
+ top-level fields in ``model_extra``; OpenAI-SDK clients spread ``extra_body``
+ into the request body top level, where guided-decoding recipes park their
+ JSON-schema response_format.
"""
extra = getattr(payload, "model_extra", None)
if not isinstance(extra, dict):
@@ -5842,15 +5786,15 @@ def _extract_response_format(payload):
def _build_openai_passthrough_body(payload, backend_ctx = None) -> dict:
"""Assemble the llama-server request body from a ChatCompletionRequest.
- Only explicitly-known OpenAI / llama-server fields are forwarded so that
- Studio-specific extensions (``enable_tools``, ``enabled_tools``,
- ``session_id``, ...) never leak to the backend.
+ Only known OpenAI / llama-server fields are forwarded, so Studio-specific
+ extensions (``enable_tools``, ``enabled_tools``, ``session_id``, ...) never
+ leak to the backend.
"""
messages = _openai_messages_for_passthrough(payload)
tool_choice = payload.tool_choice if payload.tool_choice is not None else "auto"
- # When the caller asked for a specific reasoning mode, forward it to
- # llama-server via chat_template_kwargs so the Jinja template renders
- # with (or without) the reasoning preamble.
+ # When the caller asked for a specific reasoning mode, forward it via
+ # chat_template_kwargs so the Jinja template renders with (or without) the
+ # reasoning preamble.
tpl_kwargs = None
if payload.enable_thinking is not None:
tpl_kwargs = {"enable_thinking": bool(payload.enable_thinking)}
@@ -5879,10 +5823,10 @@ async def _openai_passthrough_stream(
"""Streaming client-side pass-through for /v1/chat/completions.
Forwards the client's OpenAI function-calling request to llama-server and
- relays the SSE stream back verbatim. This preserves llama-server's
- native response ``id``, ``finish_reason`` (including ``"tool_calls"``),
- ``delta.tool_calls``, and the trailing ``usage`` chunk so the client
- observes a standard OpenAI response.
+ relays the SSE stream back verbatim, preserving llama-server's native
+ response ``id``, ``finish_reason`` (including ``"tool_calls"``),
+ ``delta.tool_calls``, and the trailing ``usage`` chunk so the client sees a
+ standard OpenAI response.
"""
target_url = f"{llama_backend.base_url}/v1/chat/completions"
body = _build_openai_passthrough_body(payload, backend_ctx = llama_backend.context_length)
@@ -5891,14 +5835,13 @@ async def _openai_passthrough_stream(
_tracker = _TrackedCancel(cancel_event, *_cancel_keys)
_tracker.__enter__()
- # Outer guard: asyncio.CancelledError at `await client.send(...)` is
- # a BaseException that bypasses `except httpx.RequestError`; without
- # this the tracker leaks. The generator's finally only runs once
- # iteration starts.
+ # Outer guard: asyncio.CancelledError at `await client.send(...)` is a
+ # BaseException that bypasses `except httpx.RequestError`; without this the
+ # tracker leaks. The generator's finally only runs once iteration starts.
try:
- # Dispatch BEFORE returning StreamingResponse so transport errors
- # and non-200 upstream statuses surface as real HTTP errors --
- # OpenAI SDKs rely on status codes to raise APIError/BadRequestError.
+ # Dispatch BEFORE returning StreamingResponse so transport errors and
+ # non-200 upstream statuses surface as real HTTP errors -- OpenAI SDKs
+ # rely on status codes to raise APIError/BadRequestError.
client = httpx.AsyncClient(
timeout = 600,
limits = httpx.Limits(max_keepalive_connections = 0),
@@ -5908,7 +5851,7 @@ async def _openai_passthrough_stream(
req = client.build_request("POST", target_url, json = body)
resp = await client.send(req, stream = True)
except httpx.RequestError as e:
- # llama-server subprocess crashed / still starting / unreachable.
+ # llama-server subprocess crashed / starting / unreachable.
logger.error("openai passthrough stream: upstream unreachable: %s", e)
if resp is not None:
try:
@@ -5948,16 +5891,15 @@ async def _openai_passthrough_stream(
async def _stream():
# Same httpx lifecycle pattern as _anthropic_passthrough_stream:
- # save resp.aiter_lines() so the finally block can aclose() it
- # on our task. See that function for full rationale.
+ # save resp.aiter_lines() so the finally block can aclose() it on
+ # our task. See that function for full rationale.
lines_iter = None
# During llama-server prefill, `aiter_lines()` blocks until the
- # first SSE chunk arrives. The in-loop `cancel_event` check
- # cannot fire until then, which is the exact proxy/Colab
- # scenario the cancel POST is meant to recover from. Run a
- # tiny watcher that closes `resp` as soon as cancel fires,
- # unblocking the iterator with a RemoteProtocolError caught
- # in the except clause below.
+ # first SSE chunk arrives. The in-loop `cancel_event` check can't
+ # fire until then -- the exact proxy/Colab scenario the cancel POST
+ # recovers from. Run a tiny watcher that closes `resp` as soon as
+ # cancel fires, unblocking the iterator with a RemoteProtocolError
+ # caught in the except clause below.
cancel_watcher = asyncio.create_task(_await_cancel_then_close(cancel_event, resp))
try:
lines_iter = resp.aiter_lines()
@@ -5977,12 +5919,12 @@ async def _openai_passthrough_stream(
if raw_line[6:].strip() == "[DONE]":
break
except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError):
- # Watcher closed resp on cancel. Emit nothing extra; the
- # client either initiated the cancel or already disconnected.
+ # Watcher closed resp on cancel. Emit nothing extra; the client
+ # initiated the cancel or already disconnected.
if not cancel_event.is_set():
raise
except Exception as e:
- # 200 headers are already flushed; errors must be in the SSE body.
+ # 200 headers already flushed; errors must go in the SSE body.
logger.error("openai passthrough stream error: %s", e)
err = {
"error": {
@@ -6029,10 +5971,9 @@ async def _openai_passthrough_stream(
async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
"""Non-streaming client-side pass-through for /v1/chat/completions.
- Returns llama-server's JSON response verbatim (via JSONResponse) so the
- client sees the native response ``id``, ``finish_reason`` (including
- ``"tool_calls"``), structured ``tool_calls``, and accurate ``usage``
- token counts.
+ Returns llama-server's JSON response verbatim so the client sees the native
+ response ``id``, ``finish_reason`` (including ``"tool_calls"``), structured
+ ``tool_calls``, and accurate ``usage`` token counts.
"""
target_url = f"{llama_backend.base_url}/v1/chat/completions"
body = _build_openai_passthrough_body(payload, backend_ctx = llama_backend.context_length)
@@ -6041,9 +5982,9 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
async with httpx.AsyncClient() as client:
resp = await client.post(target_url, json = body, timeout = 600)
except httpx.RequestError as e:
- # llama-server subprocess crashed / still starting / unreachable.
- # Surface the same friendly message the sync chat path emits so
- # operators don't see a bare 500 with no diagnostic.
+ # llama-server subprocess crashed / starting / unreachable. Surface the
+ # same friendly message the sync chat path emits so operators don't see
+ # a bare 500 with no diagnostic.
logger.error("openai passthrough non-streaming: upstream unreachable: %s", e)
raise HTTPException(
status_code = 502,
@@ -6056,12 +5997,11 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
detail = f"llama-server error: {resp.text[:500]}",
)
- # Guided-decoding fence wrap. llama-server returns raw JSON that matches
- # the schema (no surrounding markdown) because the GBNF grammar only
- # emits the JSON object itself. data_designer's llm-structured parser
- # looks for a ```json ... ``` markdown fence and discards unfenced
- # output, which collapses a 100%-valid guided-decoding run to 0/N.
- # Wrap each choice's content in the expected fence when the caller
+ # Guided-decoding fence wrap. llama-server returns raw JSON matching the
+ # schema (no markdown) since the GBNF grammar emits only the JSON object.
+ # data_designer's llm-structured parser looks for a ```json ... ``` fence
+ # and discards unfenced output, collapsing a 100%-valid guided-decoding run
+ # to 0/N. Wrap each choice's content in the expected fence when the caller
# asked for guided decoding, leaving already-fenced content alone.
if _extract_response_format(payload) is not None:
try:
@@ -6084,15 +6024,14 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
if changed:
return JSONResponse(content = data)
except Exception as exc:
- # Wrap is best-effort; fall through to the verbatim body if
- # the response is not JSON-shaped or the structure is unusual.
+ # Wrap is best-effort; fall through to the verbatim body if the
+ # response isn't JSON-shaped or the structure is unusual.
logger.warning(
"response_format fence wrap skipped: %s",
exc,
)
- # Pass the upstream body through as raw bytes — skips a redundant
- # parse+re-serialize round-trip and keeps the response truly
- # verbatim (matches the docstring). Status is guaranteed 200 by
- # the check above.
+ # Pass the upstream body through as raw bytes -- skips a redundant
+ # parse+re-serialize round-trip and keeps the response truly verbatim
+ # (matches the docstring). Status is guaranteed 200 by the check above.
return Response(content = resp.content, media_type = "application/json")
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index bf8550f5839..1d8f73eb884 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -34,9 +34,9 @@ router = APIRouter()
def _looks_like_command(value: str) -> bool:
- """Whitespace is a one-way signal: a URL can't hold an unencoded space, so a
- value with whitespace is definitely a command. No whitespace proves nothing
- (a lone token may be a single-arg command or a scheme-less URL)."""
+ """Whitespace is a one-way signal: a URL can't hold an unencoded space, so
+ a value with whitespace is definitely a command. No whitespace proves
+ nothing (a lone token may be a single-arg command or a scheme-less URL)."""
return any(ch.isspace() for ch in value)
@@ -46,8 +46,8 @@ def _validate_url(url: str) -> str:
raise HTTPException(status_code = 400, detail = "url must not be empty")
# When stdio is enabled on this host, a non-HTTP value is a local command.
# Reuse this field so stdio servers ride the existing CRUD/storage with no
- # schema change. A lone token (example.com, /usr/bin/srv) is ambiguous, so we
- # keep the existing behaviour and treat any non-HTTP value as a command here.
+ # schema change. A lone token (example.com, /usr/bin/srv) is ambiguous, so
+ # keep existing behaviour and treat any non-HTTP value as a command here.
if stdio_mcp_enabled() and is_stdio(trimmed):
try:
parts = parse_stdio_command(trimmed)
@@ -63,7 +63,7 @@ def _validate_url(url: str) -> str:
raise HTTPException(status_code = 400, detail = "command must not be empty")
if "://" in parts[0]:
# A URL-scheme first token is a mistyped URL, not a command. Reject
- # it cleanly instead of exec-ing it (mirrors the frontend check).
+ # cleanly instead of exec-ing it (mirrors the frontend check).
raise HTTPException(
status_code = 400,
detail = "Enter an http(s):// URL, or a local command whose "
@@ -87,7 +87,7 @@ def _validate_url(url: str) -> str:
def _normalize_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
- """Trim header names, drop empties, coerce values to str. None if nothing left."""
+ """Trim header names, drop empties, coerce values to str; None if empty."""
if not headers:
return None
out: dict[str, str] = {}
@@ -126,7 +126,7 @@ async def create_mcp_server(
url = _validate_url(payload.url)
headers = _normalize_headers(payload.headers)
# OAuth is HTTP-only; force it off for stdio commands so a stale flag can't
- # push the probe onto the 305s OAuth timeout. Backend is the enforcer.
+ # push the probe onto the 305s OAuth timeout. Backend enforces this.
use_oauth = payload.use_oauth and not is_stdio(url)
server_id = uuid.uuid4().hex[:16]
@@ -182,7 +182,7 @@ async def update_mcp_server(
if not changes:
raise HTTPException(status_code = 400, detail = "No fields to update")
# headers == HTTP headers (remote) or env vars (stdio). On a transport-type
- # switch with no new headers, drop the old ones so env secrets are not
+ # switch with no new headers, drop the old ones so env secrets aren't
# re-sent as HTTP headers (or vice versa).
if (
"url" in changes
@@ -190,9 +190,9 @@ async def update_mcp_server(
and "headers_json" not in changes
):
changes["headers_json"] = None
- # Clear persisted OAuth tokens when the URL changes or OAuth is
- # disabled; fastmcp keys tokens by URL and would otherwise let a
- # re-pointed server silently inherit the old account's credentials.
+ # Clear persisted OAuth tokens when the URL changes or OAuth is disabled;
+ # fastmcp keys tokens by URL and would otherwise let a re-pointed server
+ # silently inherit the old account's credentials.
if bool(old.get("use_oauth")) and (
("url" in changes and changes["url"] != old["url"]) or changes.get("use_oauth") is False
):
@@ -248,8 +248,8 @@ async def test_mcp_server(
payload: McpServerTestRequest, current_subject: str = Depends(get_current_subject)
):
# URL/header validation must surface as 400 like create/update so the
- # frontend's create-form pre-flight gets the same error semantics as
- # the actual save call. Only catch transport/timeout errors below.
+ # frontend's create-form pre-flight gets the same error semantics as the
+ # save call. Only catch transport/timeout errors below.
url = _validate_url(payload.url)
headers = _normalize_headers(payload.headers)
try:
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 3871f579af9..319330d428e 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Model Management API routes
-"""
+"""Model management API routes."""
import hashlib
import json
@@ -28,14 +26,13 @@ def _is_valid_repo_id(repo_id: str) -> bool:
def _safe_is_dir(path) -> bool:
- """``Path.is_dir()`` that returns ``False`` instead of raising.
-
- On Python >= 3.12 ``is_dir()``'s ``os.stat`` only suppresses
- "not found"-class errors and now propagates ``PermissionError``
- (EACCES); on Python <= 3.11 it returned ``False``. The folder-scan
- endpoints probe well-known system locations (e.g. a root-owned,
- mode-700 ``/usr/share/ollama/.ollama/models``) and must treat an
- un-stat-able path as "not a directory", never 500.
+ """``Path.is_dir()`` returning ``False`` instead of raising.
+
+ Python >= 3.12's ``is_dir()`` propagates ``PermissionError``
+ (EACCES); <= 3.11 returned ``False``. Folder-scan endpoints probe
+ system locations (e.g. root-owned mode-700
+ ``/usr/share/ollama/.ollama/models``) and must treat an un-stat-able
+ path as "not a directory", never 500.
"""
try:
return Path(path).is_dir()
@@ -43,7 +40,7 @@ def _safe_is_dir(path) -> bool:
return False
-# Add backend directory to path
+# Add backend dir to path
backend_path = Path(__file__).parent.parent.parent
if str(backend_path) not in sys.path:
sys.path.insert(0, str(backend_path))
@@ -79,7 +76,7 @@ try:
resolve_export_dir,
)
except ImportError:
- # Fallback: try to import from parent directory
+ # Fallback: import from parent directory
parent_backend = backend_path.parent / "backend"
if str(parent_backend) not in sys.path:
sys.path.insert(0, str(parent_backend))
@@ -167,15 +164,14 @@ def _resolve_hf_cache_dir() -> Path:
def _is_model_directory(d: Path) -> bool:
"""Return ``True`` when *d* looks like a model directory.
- A model directory must have **both** a config file (``config.json`` or
- ``adapter_config.json``) **and** actual model weight files. Both
- conditions are required: a bare directory with only loose ``.gguf``
- files (no config) might be a mixed collection, and a ``config.json``
- alone (no weights) is not a model directory.
+ Requires **both** a config (``config.json`` or
+ ``adapter_config.json``) **and** weight files: loose ``.gguf`` files
+ without config may be a mixed collection, and config without weights
+ is not a model dir.
Excludes ``mmproj`` GGUF files (vision projectors) and non-weight
- ``.bin`` files (``tokenizer.bin``, ``vocab.bin``, etc.) from the
- weight check to avoid false positives.
+ ``.bin`` files (``tokenizer.bin``, ``vocab.bin``, etc.) to avoid
+ false positives.
"""
def _is_weight_file(f: Path) -> bool:
@@ -239,8 +235,8 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
or any(child.glob("*.gguf"))
)
except OSError:
- # Skip individual children that are unreadable (permissions, broken
- # symlinks, etc.) rather than failing the entire scan.
+ # Skip unreadable children (permissions, broken symlinks)
+ # rather than failing the whole scan.
continue
if not has_model_files:
continue
@@ -257,7 +253,7 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
updated_at = updated_at,
),
)
- # Also scan for standalone .gguf files directly in the models directory
+ # Also scan standalone .gguf files in the models directory
if limit is None or len(found) < limit:
for gguf_file in models_dir.glob("*.gguf"):
if limit is not None and len(found) >= limit:
@@ -315,16 +311,16 @@ def _scan_hf_cache(cache_dir: Path) -> List[LocalModelInfo]:
def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
"""Scan an LM Studio models directory for model files.
- LM Studio uses a ``publisher/model-name`` folder structure containing
- GGUF files, or standalone GGUF files at the top level.
+ LM Studio uses a ``publisher/model-name`` folder structure with GGUF
+ files, or standalone GGUF files at the top level.
"""
if not lm_dir.exists() or not lm_dir.is_dir():
return []
- # If the directory itself is a model directory (has config AND weight
- # files), it is not an LM Studio publisher structure -- return it as a
- # single model entry. We cannot skip it silently because this function
- # is the only scanner called for default LM Studio roots.
+ # If lm_dir is itself a model directory (config AND weights), it's
+ # not an LM Studio publisher structure -- return it as a single
+ # entry. Can't skip it silently: this is the only scanner called for
+ # default LM Studio roots.
if _is_model_directory(lm_dir):
try:
updated_at = lm_dir.stat().st_mtime
@@ -360,9 +356,9 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
)
continue
- # If the child directory itself looks like a model directory
- # (has config AND weight files), surface it directly instead
- # of descending into it as a publisher.
+ # If the child looks like a model directory (config AND
+ # weights), surface it directly instead of descending into
+ # it as a publisher.
if _is_model_directory(child):
try:
updated_at = child.stat().st_mtime
@@ -379,7 +375,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
)
continue
- # child is a publisher directory -- scan its sub-directories
+ # child is a publisher directory -- scan its subdirectories
for model_dir in child.iterdir():
try:
if model_dir.is_dir():
@@ -430,11 +426,11 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:
"""Return a writable directory for Ollama ``.gguf`` symlinks.
- Prefers ``<ollama_dir>/.studio_links/`` so the links sit next to the
- blobs they point at. Falls back to a per-ollama-dir namespace under
- Studio's own cache when the models directory is read-only (common
- for system installs under ``/usr/share/ollama`` or ``/var/lib/ollama``)
- so we still surface Ollama models in those environments.
+ Prefers ``<ollama_dir>/.studio_links/`` so links sit next to their
+ blobs. Falls back to a per-ollama-dir namespace under Studio's cache
+ when the models dir is read-only (common for system installs under
+ ``/usr/share/ollama`` or ``/var/lib/ollama``) so Ollama models still
+ surface there.
"""
from utils.paths.storage_roots import cache_root
@@ -449,9 +445,8 @@ def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:
e,
)
- # Fallback: namespace by a hash of the ollama_dir so two different
- # Ollama roots don't collide. This is a cache path, not a security
- # boundary.
+ # Fallback: namespace by a hash of ollama_dir so two Ollama roots
+ # don't collide. Cache path, not a security boundary.
try:
digest = hashlib.sha256(str(ollama_dir.resolve()).encode()).hexdigest()[:12]
except OSError:
@@ -472,34 +467,29 @@ def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:
def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[LocalModelInfo]:
"""Scan an Ollama models directory for downloaded models.
- Ollama stores models in a content-addressable layout::
+ Ollama uses a content-addressable layout::
<ollama_dir>/manifests/<host>/<namespace>/<model>/<tag>
<ollama_dir>/blobs/sha256-...
- The default host is ``registry.ollama.ai`` with namespace
- ``library`` (official models), but users can pull from custom
- namespaces (``mradermacher/llama3``) or entirely different hosts
- (``hf.co/org/repo:tag``). We iterate all manifest files via
- ``rglob`` so every layout depth is discovered.
-
- Each manifest is JSON with a ``layers`` array. The layer with
- ``mediaType == "application/vnd.ollama.image.model"`` contains the
- GGUF weights. Vision models also have a projector layer
- (``application/vnd.ollama.image.projector``). We read the config
- layer to extract family/size info.
-
- Since Ollama blobs lack a ``.gguf`` extension (which the GGUF
- loading pipeline requires), we create ``.gguf``-named links
- pointing at the blobs so the existing ``detect_gguf_model`` and
- ``llama-server -m`` paths work unchanged. Each model gets its
- own subdirectory under the links dir (keyed by a short hash of
- the manifest path) so that ``detect_mmproj_file`` only sees the
- projector for *that* model. Links are created as symlinks when
- possible, falling back to hardlinks (Windows without Developer
- Mode) as a last resort. The link dir lives under
- ``<ollama_dir>/.studio_links/`` when writable, otherwise under
- Studio's own cache directory.
+ Default host is ``registry.ollama.ai`` namespace ``library``
+ (official), but users can pull from custom namespaces
+ (``mradermacher/llama3``) or other hosts (``hf.co/org/repo:tag``).
+ We ``rglob`` all manifest files so every layout depth is found.
+
+ Each manifest is JSON with a ``layers`` array. The
+ ``application/vnd.ollama.image.model`` layer holds the GGUF weights;
+ vision models add an ``application/vnd.ollama.image.projector``
+ layer. We read the config layer for family/size info.
+
+ Ollama blobs lack the ``.gguf`` extension the loading pipeline
+ requires, so we create ``.gguf``-named links to them so
+ ``detect_gguf_model`` and ``llama-server -m`` work unchanged. Each
+ model gets its own subdir under the links dir (keyed by a short hash
+ of the manifest path) so ``detect_mmproj_file`` only sees that
+ model's projector. Links are symlinks when possible, falling back to
+ hardlinks (Windows without Developer Mode). The link dir is
+ ``<ollama_dir>/.studio_links/`` when writable, else Studio's cache.
"""
manifests_root = ollama_dir / "manifests"
if not manifests_root.is_dir():
@@ -518,10 +508,9 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Loca
def _make_link(link_dir: Path, link_name: str, target: Path) -> Optional[str]:
"""Create a .gguf-named link to an Ollama blob.
- Tries symlink first, then hardlink (works on Windows without
- Developer Mode when target is on the same filesystem). Skips
- the model if neither works -- a full file copy of a multi-GB
- GGUF inside a synchronous API request would block the backend.
+ Tries symlink, then hardlink (Windows without Developer Mode,
+ same filesystem). Skips the model if neither works -- a full
+ multi-GB copy in a sync API request would block the backend.
Idempotent: skips recreation when a valid link already exists.
"""
@@ -529,9 +518,9 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Loca
link_path = link_dir / link_name
resolved = target.resolve()
- # Skip if the link already points at the exact same blob.
- # Only use samefile -- size-based checks can reuse stale links
- # after `ollama pull` updates a tag to a same-sized blob.
+ # Skip if the link already points at the same blob. Use samefile
+ # only -- size checks can reuse stale links after `ollama pull`
+ # updates a tag to a same-sized blob.
try:
if link_path.exists() and os.path.samefile(str(link_path), str(resolved)):
return str(link_path)
@@ -700,9 +689,9 @@ async def list_local_models(
hf_default = hf_default_cache_dir()
lm_dirs = lmstudio_model_dirs()
- # Validate models_dir against an allowlist of trusted directories.
- # Only the trusted Path objects are used for filesystem access -- the
- # user-supplied string is only used for matching, never for path construction.
+ # Validate models_dir against an allowlist of trusted dirs. Only the
+ # trusted Path objects are used for FS access; the user string is
+ # only used for matching, never for path construction.
allowed_roots: list[Path] = [Path("./models").resolve(), hf_cache_dir]
if legacy_hf.is_dir():
allowed_roots.append(legacy_hf)
@@ -719,7 +708,7 @@ async def list_local_models(
for root in allowed_roots:
root_str = os.path.realpath(str(root))
if requested == root_str or requested.startswith(root_str + os.sep):
- models_root = root # Use the trusted root, not the user-supplied path
+ models_root = root # trusted root, not the user-supplied path
break
if models_root is None:
raise HTTPException(
@@ -734,7 +723,7 @@ async def list_local_models(
if legacy_hf.is_dir() and legacy_hf.resolve() != hf_cache_dir.resolve():
local_models += _scan_hf_cache(legacy_hf)
- # Scan HF system default cache (may differ when env vars are overridden)
+ # Scan HF system default cache (may differ under env overrides)
if (
hf_default.is_dir()
and hf_default.resolve() != hf_cache_dir.resolve()
@@ -746,7 +735,7 @@ async def list_local_models(
for lm_dir in lm_dirs:
local_models += _scan_lmstudio_dir(lm_dir)
- # Scan user-added custom folders (cap per-folder to avoid unbounded scans)
+ # Scan user-added custom folders (per-folder cap)
from storage.studio_db import list_scan_folders
_MAX_MODELS_PER_FOLDER = 200
@@ -758,9 +747,9 @@ async def list_local_models(
for folder in custom_folders:
folder_path = Path(folder["path"])
try:
- # Ollama scanner creates .studio_links/ with .gguf symlinks.
- # Filter those from the generic scanners to avoid duplicates
- # and leaking internal paths into the UI.
+ # Ollama scanner creates .studio_links/ with .gguf
+ # symlinks. Filter those from generic scanners to avoid
+ # duplicates and leaking internal paths into the UI.
_generic = [
m
for m in (
@@ -781,10 +770,10 @@ async def list_local_models(
continue
local_models += [m.model_copy(update = {"source": "custom"}) for m in custom_models]
- # Deduplicate models, but always keep custom folder entries so they
- # appear in the "Custom Folders" UI section even when the same model
- # also exists in the HF cache or default models directory. Use a
- # (id, source) key for custom entries to avoid collisions.
+ # Deduplicate, but always keep custom folder entries so they show
+ # in the "Custom Folders" UI section even when the same model is
+ # also in the HF cache or default models dir. Custom entries use
+ # an (id, source) key to avoid collisions.
deduped: dict[str, LocalModelInfo] = {}
for model in local_models:
key = f"{model.id}\x00custom" if model.source == "custom" else model.id
@@ -855,11 +844,10 @@ async def remove_scan_folder_endpoint(
async def get_recommended_folders(current_subject: str = Depends(get_current_subject)):
"""Return well-known model directories that exist on this machine.
- Lightweight alternative to ``browse-folders`` for showing quick-pick
- chips without the overhead of enumerating a directory tree. Returns
- paths that actually exist on disk (HF cache, LM Studio, Ollama,
- ``~/models``, etc.) so the frontend can offer them as one-click
- "Recommended" shortcuts in the Custom Folders section.
+ Lightweight alternative to ``browse-folders`` for quick-pick chips
+ without enumerating a directory tree. Returns paths that exist on
+ disk (HF cache, LM Studio, Ollama, ``~/models``, etc.) for the
+ frontend's one-click "Recommended" shortcuts.
"""
from utils.paths.storage_roots import lmstudio_model_dirs
@@ -900,26 +888,25 @@ async def get_recommended_folders(current_subject: str = Depends(get_current_sub
return {"folders": folders}
-# Heuristic ceiling on how many children to stat when checking whether a
-# directory "looks like" it contains models. Keeps the browser snappy
-# even when a directory has thousands of unrelated entries.
+# Max children to stat when checking if a directory "looks like" it
+# holds models. Keeps the browser snappy on dirs with thousands of
+# unrelated entries.
_BROWSE_MODEL_HINT_PROBE = 64
-# Hard cap on how many subdirectory entries we send back. Pointing the
-# browser at something like ``/usr/lib`` or ``/proc`` must not stat-storm
-# the process or send tens of thousands of rows to the client.
+# Hard cap on subdirectory entries returned. Browsing ``/usr/lib`` or
+# ``/proc`` must not stat-storm the process or send tens of thousands of
+# rows to the client.
_BROWSE_ENTRY_CAP = 2000
def _count_model_files(directory: Path, cap: int = 200) -> int:
"""Count GGUF/safetensors files immediately inside *directory*.
- Used to surface a count-hint on the response so the UI can tell
- users that a leaf directory (no subdirs, only weights) is a valid
- "Use this folder" target.
-
- Bounded by *visited entries*, not by *match count*: in directories
- with many non-model files (or many subdirectories) the scan still
- stops after ``cap`` entries so a UI hint never costs more than a
- bounded directory walk.
+
+ Surfaces a count-hint so the UI can mark a leaf directory (no
+ subdirs, only weights) as a valid "Use this folder" target.
+
+ Bounded by *visited entries*, not match count: the scan stops after
+ ``cap`` entries even in dirs full of non-model files/subdirs, so a UI
+ hint never costs more than a bounded directory walk.
"""
n = 0
visited = 0
@@ -945,10 +932,10 @@ def _count_model_files(directory: Path, cap: int = 200) -> int:
def _has_direct_model_signal(directory: Path) -> bool:
- """Return True if *directory* has an immediate child that signals
- it holds a model: a GGUF/safetensors/config.json file, or a
- `models--*` subdir (HF hub cache). Bounded by
- ``_BROWSE_MODEL_HINT_PROBE`` to stay fast."""
+ """Return True if *directory* has an immediate child signalling a
+ model: a GGUF/safetensors/config.json file, or a `models--*` subdir
+ (HF hub cache). Bounded by ``_BROWSE_MODEL_HINT_PROBE`` to stay
+ fast."""
try:
it = directory.iterdir()
except OSError:
@@ -975,23 +962,22 @@ def _has_direct_model_signal(directory: Path) -> bool:
def _looks_like_model_dir(directory: Path) -> bool:
- """Bounded heuristic used by the folder browser to flag directories
- worth exploring. False negatives are fine; the real scanner is
+ """Bounded heuristic to flag directories worth exploring in the
+ folder browser. False negatives are fine; the real scanner is
authoritative.
Three signals, cheapest first:
- 1. Directory name itself: ``models--*`` is the HuggingFace hub cache
- layout (``blobs``/``refs``/``snapshots`` children wouldn't match
- the file-level probes below).
- 2. An immediate child is a weight file or config (handled by
+ 1. Directory name ``models--*`` (HuggingFace hub cache layout; its
+ ``blobs``/``refs``/``snapshots`` children wouldn't match the
+ file-level probes below).
+ 2. An immediate child is a weight file or config (via
:func:`_has_direct_model_signal`).
- 3. A grandchild has a direct signal -- this catches the
- ``publisher/model/weights.gguf`` layout used by LM Studio and
- Ollama. We probe at most the first
- ``_BROWSE_MODEL_HINT_PROBE`` child directories, each of which is
- checked with a bounded :func:`_has_direct_model_signal` call,
- so the total cost stays O(PROBE^2) worst-case.
+ 3. A grandchild has a direct signal -- catches the
+ ``publisher/model/weights.gguf`` layout of LM Studio and Ollama.
+ Probes at most the first ``_BROWSE_MODEL_HINT_PROBE`` child dirs,
+ each via a bounded :func:`_has_direct_model_signal`, so total cost
+ is O(PROBE^2) worst-case.
"""
if directory.name.startswith("models--"):
return True
@@ -1011,7 +997,7 @@ def _looks_like_model_dir(directory: Path) -> bool:
continue
except OSError:
continue
- # Fast name check first
+ # Fast name check first.
if child.name.startswith("models--"):
return True
if _has_direct_model_signal(child):
@@ -1022,16 +1008,15 @@ def _looks_like_model_dir(directory: Path) -> bool:
def _build_browse_allowlist() -> list[Path]:
- """Return the list of root directories the folder browser is allowed
- to walk. The same list is used to seed the sidebar suggestion chips,
- so chip targets are always reachable.
-
- Roots include the current user's HOME, the resolved HF cache dirs,
- Studio's own outputs/exports/studio root, registered scan folders,
- and well-known third-party local-LLM dirs (LM Studio, Ollama,
- `~/models`). Each is added only if it currently resolves to a real
- directory, so we never produce a "dead" sandbox boundary the user
- can't navigate into.
+ """Return the root directories the folder browser may walk. The same
+ list seeds the sidebar suggestion chips, so chip targets are always
+ reachable.
+
+ Roots: the user's HOME, resolved HF cache dirs, Studio's
+ outputs/exports/studio root, registered scan folders, and well-known
+ third-party local-LLM dirs (LM Studio, Ollama, `~/models`). Each is
+ added only if it resolves to a real directory, so we never produce a
+ "dead" sandbox boundary.
"""
from utils.paths import (
hf_default_cache_dir,
@@ -1100,9 +1085,8 @@ def _build_browse_allowlist() -> list[Path]:
def _is_path_inside_allowlist(target: Path, allowed_roots: list[Path]) -> bool:
- """Return True if *target* equals or is a descendant of any allowed
- root. The comparison uses ``os.path.realpath`` so symlinks cannot be
- used to escape the sandbox.
+ """Return True if *target* equals or descends from any allowed root.
+ Uses ``os.path.realpath`` so symlinks can't escape the sandbox.
"""
try:
target_real = os.path.realpath(str(target))
@@ -1262,30 +1246,28 @@ async def browse_folders(
"""
List immediate subdirectories of *path* for the Custom Folders picker.
- The frontend uses this to render a modal folder browser without needing
- a native OS dialog (Studio is served over HTTP, so the browser can't
- reveal absolute paths on the host). The endpoint is read-only and does
- not create, move, or delete anything. It simply enumerates visible
- subdirectories so the user can click their way to a folder and hand
- the resulting string back to POST `/api/models/scan-folders`.
+ Lets the frontend render a modal folder browser without a native OS
+ dialog (Studio is served over HTTP, so the browser can't reveal host
+ paths). Read-only: it only enumerates visible subdirectories so the
+ user can click to a folder and hand the string back to POST
+ `/api/models/scan-folders`.
- Sandbox: requests are bounded to the allowlist returned by
+ Sandbox: bounded to the allowlist from
:func:`_build_browse_allowlist` (HOME, HF cache, Studio dirs,
- registered scan folders, well-known model dirs). Paths outside the
- allowlist return 403 so users cannot probe ``/etc``, ``/proc``,
- ``/root`` (when not HOME), or other sensitive system locations
- even if the server process can read them. Symlinks are resolved
- via ``os.path.realpath`` before the check, so symlink traversal
- cannot escape the sandbox either.
-
- Sorting: directories that look like they hold models come first, then
- plain directories, then hidden entries (if `show_hidden=true`).
+ registered scan folders, well-known model dirs). Paths outside it
+ return 403 so users can't probe ``/etc``, ``/proc``, ``/root`` (when
+ not HOME), or other sensitive locations even if the process can read
+ them. Symlinks are resolved via ``os.path.realpath`` first, so
+ traversal can't escape the sandbox.
+
+ Sorting: model-bearing dirs first, then plain dirs, then hidden
+ entries (if `show_hidden=true`).
"""
from utils.paths import hf_default_cache_dir, well_known_model_dirs
from storage.studio_db import list_scan_folders
- # Build the allowlist once -- both the sandbox check below and the
- # suggestion chips use the same set, so chips are always navigable.
+ # Build the allowlist once -- the sandbox check and suggestion chips
+ # share it, so chips are always navigable.
allowed_roots = _build_browse_allowlist()
try:
@@ -1301,7 +1283,7 @@ async def browse_folders(
raise
# Enumerate immediate subdirectories with a bounded cap so a stray
- # query against ``/usr/lib`` or ``/proc`` can't stat-storm the process.
+ # query against ``/usr/lib`` or ``/proc`` can't stat-storm us.
entries: list[BrowseEntry] = []
truncated = False
visited = 0
@@ -1321,13 +1303,12 @@ async def browse_folders(
try:
for child in it:
- # Bound by *visited entries*, not by *appended entries*: in
- # directories full of files (or hidden subdirs when
- # ``show_hidden=False``) the cap on ``len(entries)`` would
- # never trigger and we'd still stat every child. Counting
- # visits keeps the worst-case work to ``_BROWSE_ENTRY_CAP``
- # iterdir/is_dir calls regardless of how many of them
- # survive the filters below.
+ # Bound by *visited*, not *appended*: in dirs full of files
+ # (or hidden subdirs when ``show_hidden=False``) a cap on
+ # ``len(entries)`` would never trigger and we'd stat every
+ # child. Counting visits caps worst-case work at
+ # ``_BROWSE_ENTRY_CAP`` iterdir/is_dir calls regardless of
+ # how many survive the filters below.
visited += 1
if visited > _BROWSE_ENTRY_CAP:
truncated = True
@@ -1366,10 +1347,10 @@ async def browse_folders(
entries.sort(key = _sort_key)
- # Parent is None at the filesystem root (`p.parent == p`) AND when
- # the parent would step outside the sandbox -- otherwise the up-row
- # would 403 on click. Users can still hop to other allowed roots
- # via the suggestion chips below.
+ # Parent is None at the filesystem root (`p.parent == p`) and when
+ # the parent would leave the sandbox -- otherwise the up-row would
+ # 403 on click. Users can still hop to other allowed roots via the
+ # suggestion chips below.
parent: Optional[str]
if target.parent == target or not _is_path_inside_allowlist(target.parent, allowed_roots):
parent = None
@@ -1393,27 +1374,25 @@ async def browse_folders(
seen_sug.add(resolved)
suggestions.append(resolved)
- # Home always comes first -- it's the safe fallback when everything
- # else is cold.
+ # Home first -- the safe fallback when everything else is cold.
_add_sug(Path.home())
# The HF cache root the process is actually using.
try:
_add_sug(hf_default_cache_dir())
except Exception:
pass
- # Already-registered scan folders (what the user has curated).
+ # Already-registered scan folders (user-curated).
try:
for folder in list_scan_folders():
_add_sug(Path(folder.get("path", "")))
except Exception as exc:
logger.debug("browse-folders: could not load scan folders: %s", exc)
- # Directories commonly used by other local-LLM tools: LM Studio
- # (`~/.lmstudio/models` + legacy `~/.cache/lm-studio/models` +
- # user-configured downloadsFolder from LM Studio's settings.json),
- # Ollama (`~/.ollama/models` + common system paths + OLLAMA_MODELS
- # env var), and generic user-choice spots (`~/models`, `~/Models`).
- # Each helper only returns paths that currently exist so we never
- # show dead chips.
+ # Dirs used by other local-LLM tools: LM Studio
+ # (`~/.lmstudio/models` + legacy `~/.cache/lm-studio/models` + LM
+ # Studio settings.json downloadsFolder), Ollama (`~/.ollama/models`
+ # + common system paths + OLLAMA_MODELS env var), and generic spots
+ # (`~/models`, `~/Models`). Each helper returns only existing paths
+ # so we never show dead chips.
try:
for p in well_known_model_dirs():
_add_sug(p)
@@ -1441,18 +1420,12 @@ def _looks_like_mlx_repo(model_id: str) -> bool:
@router.get("/list")
async def list_models(current_subject: str = Depends(get_current_subject)):
- """
- List available models (default models and loaded models).
-
- This endpoint returns the default models and any currently loaded models.
- """
+ """List available models: default plus currently loaded."""
try:
inference_backend = get_inference_backend()
- # Get default models
default_models = inference_backend.default_models
- # Get loaded models
loaded_models = []
for model_name, model_data in inference_backend.models.items():
_is_vision = model_data.get("is_vision", False)
@@ -1470,7 +1443,7 @@ async def list_models(current_subject: str = Depends(get_current_subject)):
)
loaded_models.append(model_info)
- # Include active GGUF model (loaded via llama-server)
+ # Include active GGUF model (loaded via llama-server).
from routes.inference import get_llama_cpp_backend
llama_backend = get_llama_cpp_backend()
@@ -1486,12 +1459,11 @@ async def list_models(current_subject: str = Depends(get_current_subject)):
)
)
- # Combine default and loaded models
+ # Combine default and loaded models.
all_models = []
seen_ids = set()
- # Prefer loaded entries for duplicate ids so runtime flags
- # (is_mlx, is_vision, is_audio, ...) are not lost.
+ # Prefer loaded entries for duplicate ids so runtime flags survive.
loaded_by_id = {model_info.id: model_info for model_info in loaded_models}
# Add default models
@@ -1506,7 +1478,7 @@ async def list_models(current_subject: str = Depends(get_current_subject)):
all_models.append(model_info)
seen_ids.add(model_id)
- # Add loaded models
+ # Add loaded models.
for model_info in loaded_models:
if model_info.id not in seen_ids:
all_models.append(model_info)
@@ -1525,7 +1497,7 @@ async def list_models(current_subject: str = Depends(get_current_subject)):
def _get_max_position_embeddings(config) -> Optional[int]:
- """Extract max_position_embeddings from a model config, checking text_config fallback."""
+ """Extract max_position_embeddings from a config, with text_config fallback."""
if hasattr(config, "max_position_embeddings"):
return config.max_position_embeddings
if hasattr(config, "text_config") and hasattr(config.text_config, "max_position_embeddings"):
@@ -1534,7 +1506,7 @@ def _get_max_position_embeddings(config) -> Optional[int]:
def _get_model_size_bytes(model_name: str, hf_token: Optional[str] = None) -> Optional[int]:
- """Get total size of model weight files from HF Hub."""
+ """Total size of model weight files from HF Hub."""
try:
from huggingface_hub import HfApi
@@ -1562,11 +1534,7 @@ async def get_model_config(
hf_token: Optional[str] = Query(None),
current_subject: str = Depends(get_current_subject),
):
- """
- Get configuration for a specific model.
-
- This endpoint wraps the backend load_model_defaults function.
- """
+ """Get configuration for a specific model (wraps load_model_defaults)."""
try:
if not is_local_path(model_name):
resolved = resolve_cached_repo_id_case(model_name)
@@ -1581,15 +1549,14 @@ async def get_model_config(
logger.info(f"Getting model config for: {model_name}")
from utils.models.model_config import detect_audio_type
- # Load model defaults from backend
config_dict = load_model_defaults(model_name)
- # Detect model capabilities (pass HF token for gated models)
+ # Detect capabilities (pass HF token for gated models).
is_vision = is_vision_model(model_name, hf_token = hf_token)
is_embedding = is_embedding_model(model_name, hf_token = hf_token)
audio_type = detect_audio_type(model_name, hf_token = hf_token)
- # Check if it's a LoRA adapter
+ # Check if it's a LoRA adapter.
is_lora = False
base_model = None
max_position_embeddings = None
@@ -1601,7 +1568,7 @@ async def get_model_config(
except Exception:
pass
- # Fallback: try AutoConfig directly if not found yet
+ # Fallback: try AutoConfig directly if not found yet.
if max_position_embeddings is None:
try:
from transformers import AutoConfig as _AutoConfig
@@ -1653,18 +1620,17 @@ async def scan_loras(
),
current_subject: str = Depends(get_current_subject),
):
- """
- Scan for trained LoRA adapters and exported models.
+ """Scan for trained LoRA adapters and exported models.
- Returns both training outputs (from outputs_dir) and exported models
- (from exports_dir) in a single list, distinguished by source field.
+ Returns training outputs (outputs_dir) and exported models
+ (exports_dir) in one list, distinguished by the source field.
"""
try:
resolved_outputs_dir = str(resolve_output_dir(outputs_dir))
resolved_exports_dir = str(resolve_export_dir(exports_dir))
lora_list = []
- # Scan training outputs
+ # Scan training outputs.
trained_models = scan_trained_models(outputs_dir = resolved_outputs_dir)
for display_name, model_path, model_type in trained_models:
base_model = get_base_model_from_checkpoint(model_path)
@@ -1712,7 +1678,7 @@ def _is_path_under(path: Path, root: Path) -> bool:
def _is_path_under_lexically(path: Path, root: Path) -> bool:
- """Check containment without resolving the final path's symlink target."""
+ """Check containment without resolving the final path's symlink."""
try:
absolute_path = Path(os.path.abspath(str(path)))
absolute_root = Path(os.path.abspath(str(root)))
@@ -1744,10 +1710,10 @@ def _loading_model_matches_deleted_path(loading_model: object, deleted_path: Pat
def _prune_empty_parents(start: Path, stop_at: Path) -> None:
- """Remove empty ancestor directories of ``start`` up to (but not including) ``stop_at``.
+ """Remove empty ancestors of ``start`` up to (not including) ``stop_at``.
- Used after deleting a model checkpoint so the enclosing run directory does
- not linger as an empty entry in scan results.
+ Used after deleting a checkpoint so the enclosing run dir doesn't
+ linger as an empty entry in scan results.
"""
try:
stop_resolved = stop_at.resolve()
@@ -1799,8 +1765,8 @@ async def delete_finetuned_model(
):
"""Delete a Studio-trained or exported model from disk.
- Only paths under Studio's outputs/exports roots are accepted. Exported
- GGUF entries can delete one quantization variant at a time.
+ Only paths under Studio's outputs/exports roots are accepted.
+ Exported GGUF entries can delete one quant variant at a time.
"""
if source not in {"training", "exported"}:
raise HTTPException(
@@ -2126,18 +2092,16 @@ async def get_gguf_variants(
hf_token: Optional[str] = Query(None, description = "HuggingFace token for private repos"),
current_subject: str = Depends(get_current_subject),
):
- """
- List available GGUF quantization variants for a HuggingFace repo
- or a local directory (e.g. LM Studio model folder).
+ """List GGUF quantization variants for a HuggingFace repo or local
+ directory (e.g. LM Studio model folder).
- Returns all available quantization variants (Q4_K_M, Q8_0, BF16, etc.)
- with file sizes, whether the model supports vision, and the recommended
- default variant.
+ Returns all variants (Q4_K_M, Q8_0, BF16, etc.) with file sizes,
+ whether the model supports vision, and the recommended default.
"""
try:
from utils.models.model_config import is_local_path, list_local_gguf_variants
- # Local directory path (e.g. LM Studio models) — scan filesystem
+ # Local directory path (e.g. LM Studio models) — scan filesystem.
if is_local_path(repo_id):
variants, has_vision = list_local_gguf_variants(repo_id)
@@ -2160,26 +2124,25 @@ async def get_gguf_variants(
default_variant = default_variant,
)
- # Remote HuggingFace repo — query HF API
+ # Remote HuggingFace repo — query HF API.
variants, has_vision = list_gguf_variants(repo_id, hf_token = hf_token)
- # Determine default variant
+ # Determine default variant.
filenames = [v.filename for v in variants]
best = _pick_best_gguf(filenames)
default_variant = _extract_quant_label(best) if best else None
- # Check which variants are fully downloaded in the HF cache.
- # For split GGUFs, ALL shards must be present -- sum cached bytes
- # per variant and compare against the expected total.
- # HF cache dir uses the exact case from the repo_id at download time,
- # which may differ from the canonical HF repo_id, so do a
- # case-insensitive match.
+ # Which variants are fully downloaded in the HF cache. For split
+ # GGUFs, ALL shards must be present -- sum cached bytes per
+ # variant vs. the expected total. The HF cache dir uses the
+ # repo_id casing from download time, which may differ from the
+ # canonical repo_id, so match case-insensitively.
cached_bytes_by_quant: dict[str, int] = {}
try:
import re as _re
from huggingface_hub import constants as hf_constants
- # Sanitize repo_id: must be "owner/name" with safe chars only
+ # Sanitize repo_id: "owner/name" with safe chars only.
if not _is_valid_repo_id(repo_id):
raise ValueError(f"Invalid repo_id format: {repo_id}")
@@ -2203,7 +2166,7 @@ async def get_gguf_variants(
cached = cached_bytes_by_quant.get(variant.quant, 0)
if cached == 0 or variant.size_bytes == 0:
return False
- # Allow small rounding tolerance (symlinks vs real sizes)
+ # Small rounding tolerance (symlinks vs real sizes).
return cached >= variant.size_bytes * 0.99
return GgufVariantsResponse(
@@ -2236,10 +2199,10 @@ async def get_gguf_download_progress(
expected_bytes: int = Query(0, description = "Expected total download size in bytes"),
current_subject: str = Depends(get_current_subject),
):
- """Return download progress by checking cached GGUF files for a specific variant.
+ """Download progress from cached GGUF files for a specific variant.
- Tracks completed shard downloads in snapshots and in-progress downloads
- in the blobs directory (incomplete files).
+ Tracks completed shards in snapshots and in-progress (.incomplete)
+ downloads in the blobs directory.
"""
try:
if not _is_valid_repo_id(repo_id):
@@ -2258,12 +2221,12 @@ async def get_gguf_download_progress(
in_progress_bytes = 0
for entry in cache_dir.iterdir():
if entry.name.lower() == target:
- # Count completed .gguf files matching this variant in snapshots
+ # Completed .gguf files for this variant in snapshots.
for f in _iter_gguf_paths(entry):
fname = f.name.lower().replace("-", "").replace("_", "")
if not variant_lower or variant_lower in fname:
downloaded_bytes += f.stat().st_size
- # Check blobs for in-progress downloads (.incomplete files)
+ # In-progress downloads (.incomplete) in blobs.
blobs_dir = entry / "blobs"
if blobs_dir.is_dir():
for f in blobs_dir.iterdir():
@@ -2273,7 +2236,7 @@ async def get_gguf_download_progress(
total_progress_bytes = downloaded_bytes + in_progress_bytes
progress = min(total_progress_bytes / expected_bytes, 0.99) if expected_bytes > 0 else 0
- # Only report 1.0 when all bytes are in completed files (not in-progress)
+ # Report 1.0 only when all bytes are in completed files.
if expected_bytes > 0 and downloaded_bytes >= expected_bytes:
progress = 1.0
return {
@@ -2288,9 +2251,9 @@ async def get_gguf_download_progress(
def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
"""Pick the most useful on-disk path for a HF cache repo.
- Prefers the most-recent snapshot dir (what `from_pretrained` actually
- points at). Falls back to the cache repo root. Returns the resolved
- realpath so symlinks under snapshots/ are followed back to blobs/.
+ Prefers the most-recent snapshot dir (what `from_pretrained` points
+ at), falling back to the cache repo root. Returns the resolved
+ realpath so symlinks under snapshots/ follow back to blobs/.
"""
try:
snapshots_dir = repo_dir / "snapshots"
@@ -2312,11 +2275,10 @@ async def get_download_progress(
"""Return download progress for any HuggingFace model repo.
Checks the local HF cache for completed blobs and in-progress
- (.incomplete) downloads. Uses the HF API to determine the expected
- total size on the first call, then caches it for subsequent polls.
- Also returns ``cache_path``: the realpath of the snapshot directory
- (or the cache repo root if no snapshot exists yet) so the UI can
- show users where the weights actually live on disk.
+ (.incomplete) downloads. Gets the expected total size from the HF API
+ on the first call, then caches it for later polls. Also returns
+ ``cache_path``: the realpath of the snapshot dir (or cache repo root
+ if no snapshot yet) so the UI can show where weights live on disk.
"""
_empty = {
"downloaded_bytes": 0,
@@ -2356,10 +2318,10 @@ async def get_download_progress(
if downloaded_bytes == 0:
return {**_empty, "cache_path": cache_path}
- # Get expected size from HF API (cached per repo_id)
+ # Expected size from HF API (cached per repo_id).
expected_bytes = _get_repo_size_cached(repo_id)
if expected_bytes <= 0:
- # Cannot determine total; report bytes only, no percentage
+ # Total unknown; report bytes only, no percentage.
return {
"downloaded_bytes": downloaded_bytes,
"expected_bytes": 0,
@@ -2367,11 +2329,10 @@ async def get_download_progress(
"cache_path": cache_path,
}
- # Use 95% threshold for completion (blob deduplication can make
- # completed_bytes differ slightly from expected_bytes).
- # Do NOT use "no .incomplete files" as a completion signal --
- # HF downloads files sequentially, so between files there are
- # no .incomplete files even though the download is far from done.
+ # 95% completion threshold (blob dedup can make completed_bytes
+ # differ slightly from expected_bytes). Do NOT treat "no
+ # .incomplete files" as done -- HF downloads sequentially, so
+ # between files none exist even though it's far from finished.
if completed_bytes >= expected_bytes * 0.95:
progress = 1.0
else:
@@ -2406,14 +2367,14 @@ def _get_repo_size_cached(repo_id: str) -> int:
def _all_hf_cache_scans():
- """Return scan_cache_dir results for the active, legacy, and default HF caches."""
+ """scan_cache_dir results for the active, legacy, and default HF caches."""
from huggingface_hub import scan_cache_dir
from utils.paths import legacy_hf_cache_dir, hf_default_cache_dir
scans = [scan_cache_dir()]
seen: set[str] = set()
try:
- # Resolve the active cache dir so we can dedup
+ # Resolve the active cache dir for deduplication.
from huggingface_hub.constants import HF_HUB_CACHE
seen.add(str(Path(HF_HUB_CACHE).resolve()))
except Exception:
@@ -2435,14 +2396,14 @@ def _is_gguf_filename(name: str) -> bool:
def _is_mmproj_filename(name: str) -> bool:
- """Match GGUF vision-adapter (mmproj) files. Kept consistent with
+ """Match GGUF vision-adapter (mmproj) files. Consistent with
``utils.models.model_config._is_mmproj``."""
return "mmproj" in name.lower()
def _is_main_gguf_filename(name: str) -> bool:
- """A GGUF file that is a primary weight artifact, not an mmproj
- vision adapter."""
+ """A GGUF file that is a primary weight, not an mmproj vision
+ adapter."""
return _is_gguf_filename(name) and not _is_mmproj_filename(name)
@@ -2453,17 +2414,16 @@ def _iter_gguf_paths(root: Path):
def _repo_gguf_size_bytes(repo_info) -> int:
- """Return the total on-disk size of primary GGUF weight files across
- all revisions, excluding mmproj vision-adapter files.
+ """Total on-disk size of primary GGUF weight files across all
+ revisions, excluding mmproj vision-adapter files.
Hugging Face hardlinks blobs shared between revisions, so this
- deduplicates by blob path (or, as a fallback, by revision commit
- hash + filename) to avoid double-counting the same bytes. Files
- with an unknown size (``size_on_disk is None``, e.g. a partial or
- interrupted download) are treated as zero bytes. mmproj files are
- excluded so that repos whose only ``.gguf`` artifact is a vision
- adapter are not classified as GGUF repos: the variant selector
- filters mmproj out and would otherwise show zero pickable variants.
+ deduplicates by blob path (or revision commit hash + filename as a
+ fallback) to avoid double-counting. Unknown sizes (``size_on_disk is
+ None``, e.g. a partial download) count as zero. mmproj files are
+ excluded so repos whose only ``.gguf`` artifact is a vision adapter
+ aren't classed as GGUF repos: the variant selector filters mmproj
+ out and would otherwise show zero pickable variants.
"""
unique_blobs: dict[str, int] = {}
for revision in repo_info.revisions:
@@ -2480,9 +2440,9 @@ def _repo_gguf_size_bytes(repo_info) -> int:
def _repo_has_gguf_files(repo_info) -> bool:
- """Return True when any revision in a cached repo contains a
- primary GGUF weight file. Repos whose only ``.gguf`` artifact is
- an mmproj vision adapter are not treated as GGUF here."""
+ """True when any revision in a cached repo has a primary GGUF weight
+ file. Repos whose only ``.gguf`` artifact is an mmproj vision adapter
+ are not treated as GGUF here."""
return _repo_gguf_size_bytes(repo_info) > 0
@@ -2576,14 +2536,14 @@ async def delete_cached_model(
):
"""Delete a cached model repo (or a specific GGUF variant) from the HF cache.
- When *variant* is provided, only the GGUF files matching that quant label
- are removed (e.g. ``UD-Q4_K_XL``). Otherwise the entire repo is deleted.
- Refuses if the model is currently loaded for inference.
+ With *variant*, only GGUF files matching that quant label are removed
+ (e.g. ``UD-Q4_K_XL``); otherwise the whole repo is deleted. Refuses
+ if the model is currently loaded for inference.
"""
if not _is_valid_repo_id(repo_id):
raise HTTPException(status_code = 400, detail = "Invalid repo_id format")
- # Check if model is currently loaded
+ # Refuse if the model is currently loaded.
try:
from routes.inference import get_llama_cpp_backend
llama_backend = get_llama_cpp_backend()
@@ -2641,7 +2601,7 @@ async def delete_cached_model(
quant = _extract_quant_label(f.file_name)
if quant.lower() != variant.lower():
continue
- # Delete the blob (actual data) and the snapshot symlink
+ # Delete the blob (data) and the snapshot symlink.
try:
blob = Path(f.blob_path)
snap = Path(f.file_path)
@@ -2700,8 +2660,7 @@ async def list_checkpoints(
),
current_subject: str = Depends(get_current_subject),
):
- """
- List available checkpoints in the outputs directory.
+ """List checkpoints in the outputs directory.
Scans the outputs folder for training runs and their checkpoints.
"""
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 5dd70383300..c78739be848 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -4,12 +4,12 @@
"""
API routes for external LLM provider management.
-Provides endpoints for:
- - Discovering available provider types (registry)
+Endpoints:
+ - Discover available provider types (registry)
- CRUD for saved provider configurations (no API keys stored)
- - Fetching the RSA public key for API key encryption
- - Testing provider connectivity
- - Listing models from a provider
+ - Fetch the RSA public key for API key encryption
+ - Test provider connectivity
+ - List models from a provider
"""
import uuid
@@ -54,11 +54,10 @@ router = APIRouter()
async def get_public_key(current_subject: str = Depends(get_current_subject)):
"""Return the RSA public key PEM for client-side API key encryption.
- The ``fingerprint`` field is a short SHA256 of the PEM and is meant
- purely for diagnostics — a mismatch between what the frontend
- captured at encrypt time and what the server reports here is a
- clear signal that the keypair rotated mid-flight (e.g. the server
- re-ran ``init_key_pair`` for any reason).
+ The ``fingerprint`` field is a short SHA256 of the PEM, for diagnostics: a
+ mismatch between what the frontend captured at encrypt time and what the
+ server reports here signals the keypair rotated mid-flight (e.g. the server
+ re-ran ``init_key_pair``).
"""
return {
"public_key": get_public_key_pem(),
@@ -80,10 +79,10 @@ async def list_registry(current_subject: str = Depends(get_current_subject)):
@router.get("/pricing")
async def get_pricing_snapshot(current_subject: str = Depends(get_current_subject)):
- """Static per-MTok pricing table the frontend uses to convert
- upstream usage chunks into a per-turn USD cost. See
- ``core/inference/pricing.py`` for sourcing notes; values reflect
- the published prices as of the file's last update."""
+ """Static per-MTok pricing table the frontend uses to convert upstream
+ usage chunks into a per-turn USD cost. See ``core/inference/pricing.py``
+ for sourcing notes; values reflect the published prices as of the file's
+ last update."""
return pricing_snapshot()
@@ -196,7 +195,7 @@ async def test_provider(
Test connectivity to an external provider.
Makes a lightweight GET /models call to verify the API key works.
- The encrypted_api_key is decrypted server-side and never stored.
+ encrypted_api_key is decrypted server-side and never stored.
"""
info = get_provider_info(payload.provider_type)
if info is None:
@@ -267,7 +266,7 @@ async def list_provider_models(
"""
List models available from an external provider.
- The encrypted_api_key is decrypted server-side and never stored.
+ encrypted_api_key is decrypted server-side and never stored.
"""
info = get_provider_info(payload.provider_type)
if info is None:
@@ -308,16 +307,15 @@ async def list_provider_models(
try:
models = await client.list_models()
- # Registry-level model-id filters are scoped to the canonical
- # native Gemini base. A custom Gemini OAI-compatible proxy
- # (LiteLLM, deployment gateway) returns IDs like
- # `google/gemini-2.5-flash`, `gemini/gemini-2.5-flash`, or
- # team-prefixed deployment aliases; the native allowlist regex
- # would strip those out and leave the picker empty even though
- # the chat path now routes them via the OAI-compatible
- # dispatcher (the same gate ExternalProviderClient applies for
- # request building). Match the host check here so the model
- # list and chat dispatch agree on what counts as "native".
+ # Registry-level model-id filters are scoped to the canonical native
+ # Gemini base. A custom Gemini OAI-compatible proxy (LiteLLM, deployment
+ # gateway) returns IDs like `google/gemini-2.5-flash`,
+ # `gemini/gemini-2.5-flash`, or team-prefixed deployment aliases; the
+ # native allowlist regex would strip those and leave the picker empty,
+ # even though the chat path routes them via the OAI-compatible
+ # dispatcher (the same gate ExternalProviderClient applies for request
+ # building). Match the host check here so the model list and chat
+ # dispatch agree on what counts as "native".
apply_registry_model_filters = True
if payload.provider_type == "gemini":
try:
@@ -344,11 +342,10 @@ async def list_provider_models(
denylist = info.get("model_id_denylist")
if denylist is not None:
models = [m for m in models if not denylist.search(m.get("id", ""))]
- # Apply an optional cap after filtering so registry entries with a
- # large remote catalog (e.g. HF Inference Providers) can stay
- # picker-sized. No popularity sort happens server-side, so this is
- # "first N matches" — pair with default_models for any must-have
- # flagship ids.
+ # Optional cap after filtering so registry entries with a large remote
+ # catalog (e.g. HF Inference Providers) stay picker-sized. No
+ # server-side popularity sort, so this is "first N matches" — pair with
+ # default_models for any must-have flagship ids.
limit = info.get("model_id_limit")
if isinstance(limit, int) and limit > 0:
models = models[:limit]
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index d62e0209b01..7ce086e5b20 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -16,13 +16,12 @@ import asyncio
from datetime import datetime
import uuid as _uuid
-# Add backend directory to path
-# The backend code should be in the same directory structure
+# Add backend directory to path (same directory structure).
backend_path = Path(__file__).parent.parent.parent
if str(backend_path) not in sys.path:
sys.path.insert(0, str(backend_path))
-# Import backend functions
+# Import backend functions.
try:
from core.training import get_training_backend
from core.training.resume import (
@@ -34,7 +33,7 @@ try:
from utils.models.model_config import load_model_defaults
from utils.paths import resolve_dataset_path
except ImportError:
- # Fallback: try to import from parent directory
+ # Fallback: import from the parent directory.
parent_backend = backend_path.parent / "backend"
if str(parent_backend) not in sys.path:
sys.path.insert(0, str(parent_backend))
@@ -95,10 +94,9 @@ def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset"
@router.get("/hardware")
async def get_hardware_utilization(current_subject: str = Depends(get_current_subject)):
"""
- Get a live snapshot of GPU hardware utilization.
+ Live snapshot of GPU hardware utilization for the active backend.
- Designed to be polled by the frontend during training.
- Returns live GPU memory usage information for the active backend.
+ Polled by the frontend during training.
"""
from utils.hardware import get_gpu_utilization
return get_gpu_utilization()
@@ -117,8 +115,8 @@ async def start_training(
"""
Start a training job.
- This endpoint initiates training in the background and returns immediately.
- Use the /status endpoint to check training progress.
+ Initiates training in the background and returns immediately. Use /status
+ to check progress.
"""
try:
logger.info(f"Starting training job with model: {request.model_name}")
@@ -129,7 +127,7 @@ async def start_training(
backend = get_training_backend()
- # Check if training is already active (before mutating any state)
+ # Check if training is already active (before mutating state).
if backend.is_training_active():
existing_job_id: Optional[str] = getattr(backend, "current_job_id", "")
return TrainingJobResponse(
@@ -142,11 +140,11 @@ async def start_training(
error = "Training already active",
)
- # Generate job ID — passed into start_training() which sets it on the
- # backend only after confirming the old pump thread is dead.
+ # Job ID — passed to start_training(), which sets it on the backend only
+ # after confirming the old pump thread is dead.
job_id = f"job_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{_uuid.uuid4().hex[:8]}"
- # Validate dataset paths if provided
+ # Validate dataset paths if provided.
if request.local_datasets:
request.local_datasets = _validate_local_dataset_paths(
request.local_datasets, "Local dataset"
@@ -178,7 +176,7 @@ async def start_training(
)
request.resume_from_checkpoint = resume_checkpoint
- # Convert request to kwargs for backend
+ # Convert request to backend kwargs.
training_kwargs = {
"model_name": request.model_name,
"training_type": request.training_type,
@@ -242,8 +240,8 @@ async def start_training(
}
# Training page has no trust_remote_code toggle — the value comes from
- # YAML model defaults applied when the user selects a model. As a safety
- # net, consult the YAML directly so models that need it always get it.
+ # YAML model defaults on model select. As a safety net, consult the YAML
+ # directly so models that need it always get it.
if not training_kwargs["trust_remote_code"]:
model_defaults = load_model_defaults(request.model_name)
yaml_trust = model_defaults.get("training", {}).get("trust_remote_code", False)
@@ -252,7 +250,7 @@ async def start_training(
training_kwargs["trust_remote_code"] = True
# Free GPU memory: shut down any running inference/export subprocesses
- # before training starts (they'd compete for VRAM otherwise)
+ # before training (they'd compete for VRAM otherwise).
try:
from core.inference import get_inference_backend
inf_backend = get_inference_backend()
@@ -279,7 +277,7 @@ async def start_training(
except Exception as e:
logger.warning("Could not shut down export subprocess: %s", e)
- # start_training now spawns a subprocess (non-blocking)
+ # start_training spawns a subprocess (non-blocking).
success = backend.start_training(job_id = job_id, **training_kwargs)
if not success:
@@ -334,7 +332,6 @@ async def stop_training(
status = "idle", message = "No training job is currently running"
)
- # Call backend stop method
backend.stop_training(save = body.save)
return TrainingStopResponse(
@@ -354,16 +351,14 @@ async def stop_training(
@router.post("/reset")
async def reset_training(current_subject: str = Depends(get_current_subject)):
- """
- Reset training state so the user can return to configuration.
- """
+ """Reset training state so the user can return to configuration."""
try:
backend = get_training_backend()
is_active = backend.is_training_active()
if is_active:
if backend._cancel_requested:
- # Cancel (save=False) was requested — force-terminate so we can reset immediately
+ # Cancel (save=False) requested — force-terminate to reset immediately.
logger.info("Force-terminating subprocess for immediate reset (cancel path)")
backend.force_terminate()
else:
@@ -460,7 +455,7 @@ async def get_training_status(current_subject: str = Depends(get_current_subject
if output_dir:
details["output_dir"] = output_dir
- # Build metric history for chart recovery after SSE reconnection
+ # Metric history for chart recovery after SSE reconnection.
metric_history = None
if backend.step_history:
metric_history = {
@@ -540,16 +535,15 @@ async def stream_training_progress(
request: Request, current_subject: str = Depends(get_current_subject)
):
"""
- Stream training progress updates using Server-Sent Events (SSE).
-
- This endpoint provides real-time updates on training progress.
- Supports reconnection via the SSE spec:
- - Sends `id:` with each event so the browser tracks position.
- - Sends `retry:` to control reconnection interval.
- - Sends named `event:` types (progress, heartbeat, complete, error).
- - Reads `Last-Event-ID` header on reconnect to replay missed steps.
+ Stream training progress via Server-Sent Events (SSE).
+
+ Real-time progress with reconnection support per the SSE spec:
+ - `id:` per event so the browser tracks position.
+ - `retry:` to control reconnection interval.
+ - Named `event:` types (progress, heartbeat, complete, error).
+ - Reads `Last-Event-ID` on reconnect to replay missed steps.
"""
- # Read Last-Event-ID header for reconnection resume
+ # Read Last-Event-ID header for reconnection resume.
last_event_id = request.headers.get("last-event-id")
resume_from_step: Optional[int] = None
if last_event_id is not None:
@@ -580,7 +574,7 @@ async def stream_training_progress(
else:
progress_percent = float(step) / float(total) * 100.0 if total > 0 else 0.0
- # Get actual values from progress object if available
+ # Pull values from the progress object if available.
elapsed_seconds = getattr(progress, "elapsed_seconds", None) if progress else None
eta_seconds = getattr(progress, "eta_seconds", None) if progress else None
grad_norm = grad_norm_override
@@ -622,7 +616,7 @@ async def stream_training_progress(
return "\n".join(lines)
# ── Retry directive ──────────────────────────────────────
- # Tell the browser to reconnect after 3 seconds if the connection drops
+ # Reconnect after 3 seconds if the connection drops.
yield "retry: 3000\n\n"
# ── Replay missed steps on reconnect ─────────────────────
@@ -707,7 +701,7 @@ async def stream_training_progress(
# ── Live polling loop ────────────────────────────────────
last_step = resume_from_step if resume_from_step is not None else -1
no_update_count = 0
- max_no_updates = 1800 # Timeout after 30 minutes (large models need time for compilation)
+ max_no_updates = 1800 # Timeout after 30 min (large models need compile time)
while backend.is_training_active():
try:
@@ -721,7 +715,7 @@ async def stream_training_progress(
)
current_epoch = getattr(tp_inner, "epoch", None) if tp_inner else None
- # Only send if step changed
+ # Only send if the step changed.
if current_step != last_step:
progress_payload = build_progress(
current_step,
@@ -740,7 +734,7 @@ async def stream_training_progress(
no_update_count = 0
else:
no_update_count += 1
- # Send heartbeat every 10 seconds
+ # Heartbeat every 10 seconds.
if no_update_count % 10 == 0:
heartbeat_payload = build_progress(
current_step,
@@ -756,11 +750,11 @@ async def stream_training_progress(
event_id = current_step,
)
else:
- # No steps yet, but training is active (model loading, etc.)
+ # No steps yet, but training is active (model loading, etc.).
no_update_count += 1
if no_update_count % 5 == 0:
- # Pull total_steps and status from trainer so
- # the frontend can show "Tokenizing…" etc.
+ # Pull total_steps + status from trainer so the frontend
+ # can show "Tokenizing…" etc.
tp_prep = getattr(
getattr(backend, "trainer", None),
"training_progress",
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 5cfc1822f7a..b9f271b4bee 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -1,9 +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
-"""
-Run script for Unsloth UI Backend.
-Works independently and can be moved to any directory.
+"""Run script for Unsloth UI Backend.
+
+Self-contained; can be moved to any directory.
"""
import os
@@ -11,10 +11,10 @@ import sys
from pathlib import Path
from typing import Optional
-# Suppress annoying C-level dependency warnings globally (e.g. SwigPyPacked)
+# Suppress C-level dependency warnings globally (e.g. SwigPyPacked).
os.environ["PYTHONWARNINGS"] = "ignore"
-# Add the backend directory to Python path early so local modules are importable
+# Add the backend dir to sys.path early so local modules import.
backend_dir = Path(__file__).parent
if str(backend_dir) not in sys.path:
sys.path.insert(0, str(backend_dir))
@@ -27,8 +27,8 @@ except ValueError as exc:
configured = os.environ.get("UNSLOTH_CPU_THREADS")
raise SystemExit(f"Error: Invalid UNSLOTH_CPU_THREADS value {configured!r}: {exc}") from None
-# Fix for Anaconda/conda-forge Python: seed platform._sys_version_cache before
-# any library imports that trigger attrs -> rich -> structlog -> platform crash.
+# Anaconda/conda-forge Python: seed platform._sys_version_cache before
+# imports that trigger attrs -> rich -> structlog -> platform crash.
# See: https://github.com/python/cpython/issues/102396
import _platform_compat # noqa: F401
@@ -39,18 +39,17 @@ logger = get_logger(__name__)
def _resolve_external_ip() -> str:
- """
- Resolve the machine's external IP address.
+ """Resolve the machine's external IP address.
- Tries (in order):
- 1. GCE metadata server (instant, works on Google Cloud VMs)
- 2. ifconfig.me (works anywhere with internet)
+ Tries, in order:
+ 1. GCE metadata server (instant on Google Cloud VMs)
+ 2. ifconfig.me (anywhere with internet)
3. LAN IP via UDP socket trick (fallback)
"""
import urllib.request
import socket
- # 1. Try GCE metadata server (responds in <10ms on GCE, times out fast elsewhere)
+ # 1. GCE metadata server (<10ms on GCE, times out fast elsewhere).
try:
req = urllib.request.Request(
"http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip",
@@ -63,7 +62,7 @@ def _resolve_external_ip() -> str:
except Exception:
pass
- # 2. Try public IP service
+ # 2. Public IP service.
try:
with urllib.request.urlopen("https://ifconfig.me", timeout = 3) as resp:
ip = resp.read().decode().strip()
@@ -84,9 +83,10 @@ def _resolve_external_ip() -> str:
def _install_uvicorn_startup_log_rewrite(bind_host: str, display_host: str) -> None:
- """Rewrite Uvicorn's startup log line: swap wildcard bind for the
- externally-reachable address, replace the CTRL+C suffix with our Mac-aware
- stop hint, and rename the prefix to "Unsloth Studio running on"."""
+ """Rewrite Uvicorn's startup log line: swap the wildcard bind for the
+ externally-reachable address, replace the CTRL+C suffix with our
+ Mac-aware stop hint, and rename the prefix to "Unsloth Studio running
+ on"."""
import logging
import re
@@ -137,7 +137,7 @@ def _local_port_open(
port: int,
timeout: float = 1.0,
) -> bool:
- """Return True iff a TCP connection to (host, port) succeeds within timeout."""
+ """True iff a TCP connection to (host, port) succeeds within timeout."""
import socket
try:
with socket.create_connection((host, port), timeout = timeout):
@@ -147,8 +147,8 @@ def _local_port_open(
def _working_local_url(port: int) -> "str | None":
- """Return a working loopback URL on this machine, or None if neither
- 127.0.0.1 nor ::1 responds. Used as a fallback when external reachability fails."""
+ """A working loopback URL on this machine, or None if neither
+ 127.0.0.1 nor ::1 responds. Fallback when external reachability fails."""
if _local_port_open("127.0.0.1", port):
return f"http://127.0.0.1:{port}"
if _local_port_open("::1", port):
@@ -157,13 +157,12 @@ def _working_local_url(port: int) -> "str | None":
def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":
- """Return the IPv4 loopback URL when localhost will not reach 127.0.0.1.
+ """Return the IPv4 loopback URL when localhost won't reach 127.0.0.1.
- Local Studio intentionally binds to 127.0.0.1. On hosts where localhost
- resolves to IPv6 only (::1), a browser pointed at http://localhost:<port>
- fails -- or worse, reaches a different process listening on ::1 -- even
- though http://127.0.0.1:<port> works. Return the IPv4 URL so the caller can
- tell the user which address to open.
+ Local Studio binds to 127.0.0.1. Where localhost resolves to IPv6
+ only (::1), http://localhost:<port> fails -- or worse, hits a
+ different process on ::1 -- even though http://127.0.0.1:<port> works.
+ Return the IPv4 URL so the caller can tell the user what to open.
"""
import socket
@@ -172,7 +171,7 @@ def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":
ipv4_url = f"http://127.0.0.1:{port}"
- # Only warn once Studio is confirmed answering on the IPv4 loopback.
+ # Only warn once Studio is confirmed answering on IPv4 loopback.
if _working_local_url(port) != ipv4_url:
return None
@@ -194,11 +193,11 @@ def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":
if host == "::1":
has_ipv6_loopback = True
- # A successful connection to ::1 is NOT evidence that Studio is reachable
- # there: Studio binds 127.0.0.1 only, so anything answering on ::1 is a
- # different process -- which is exactly when the user must be steered to
- # 127.0.0.1. Dual-stack localhost is fine (browsers fall back to 127.0.0.1
- # when ::1 refuses), so only the IPv6-only case strands the user.
+ # A connection to ::1 is NOT evidence Studio is reachable there:
+ # Studio binds 127.0.0.1 only, so anything on ::1 is a different
+ # process -- exactly when to steer the user to 127.0.0.1. Dual-stack
+ # localhost is fine (browsers fall back to 127.0.0.1 when ::1
+ # refuses), so only the IPv6-only case strands the user.
if has_ipv6_loopback and not has_ipv4_loopback:
return ipv4_url
return None
@@ -231,11 +230,11 @@ def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:
def _verify_global_reachability(display_host: str, port: int) -> None:
- """Probe check-host.net to confirm display_host:port is reachable from the
- public internet. Synchronous so the caller can render output between the
- banner URL section and the trailing stop hint. Bounded at ~15s; failures
- are swallowed (the verifier failing is not Studio failing). Only meaningful
- when bound to a wildcard host."""
+ """Probe check-host.net to confirm display_host:port is reachable
+ from the public internet. Synchronous so the caller can render output
+ between the banner URL section and the trailing stop hint. Bounded at
+ ~15s; failures are swallowed (verifier failing != Studio failing).
+ Only meaningful when bound to a wildcard host."""
import ipaddress
import json
import time
@@ -256,7 +255,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
url = f"http://{display_host}:{port}"
- # Private / loopback / link-local addresses are not globally routable.
+ # Private/loopback/link-local addresses aren't globally routable.
try:
addr = ipaddress.ip_address(display_host)
if addr.is_loopback or addr.is_private or addr.is_link_local:
@@ -304,7 +303,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
continue
if results and all(v is not None for v in results.values()):
break
- # Two decisive nodes is enough; stop polling early.
+ # Two decisive nodes is enough; stop early.
decisive = [
v
for v in results.values()
@@ -373,7 +372,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
f"{dim} then open http://localhost:{port}/ in your browser.{reset}",
flush = True,
)
- # Only offer the local URL if loopback actually answers.
+ # Only offer the local URL if loopback answers.
local_url = _working_local_url(port)
if local_url:
print(
@@ -388,7 +387,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
flush = True,
)
except urllib.error.URLError:
- # Outbound HTTPS blocked; skip silently.
+ # Outbound HTTPS blocked; skip.
pass
except Exception:
pass
@@ -397,16 +396,16 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
def _emit_startup_output(host: str, port: int, display_host: str) -> None:
"""Print the access banner plus any post-startup warnings.
- Extracted from ``_run`` so the banner/warning wiring is unit-testable. The
- ``localhost``-to-::1 mismatch warning and the wildcard reachability check
- are mutually exclusive (the mismatch helper returns None for any non
- 127.0.0.1 bind, and wildcard binds are never 127.0.0.1), so the trailing
- stop hint is emitted exactly once.
+ Extracted from ``_run`` so the banner/warning wiring is testable. The
+ ``localhost``-to-::1 mismatch warning and the wildcard reachability
+ check are mutually exclusive (the mismatch helper returns None for any
+ non-127.0.0.1 bind, and wildcard binds are never 127.0.0.1), so the
+ trailing stop hint is emitted exactly once.
"""
wildcard_bind = host in ("0.0.0.0", "::")
localhost_mismatch_url = _localhost_ipv6_mismatch_url(host, port)
- # For wildcard binds, run the reachability check between the URL section
- # and the stop hint so the stop hint stays last on screen.
+ # For wildcard binds, run the reachability check between the URL
+ # section and the stop hint so the stop hint stays last.
print_studio_access_banner(
port = port,
bind_host = host,
@@ -422,12 +421,11 @@ def _emit_startup_output(host: str, port: int, display_host: str) -> None:
def _get_pid_on_port(port: int) -> "tuple[int, str] | None":
- """Return (pid, process_name) of the process listening on *port*, or None.
-
- Uses psutil when available. Falls back gracefully to None so callers
- can still report the port conflict without process details.
+ """Return (pid, process_name) listening on *port*, or None.
- Works on Windows, macOS, and Linux wherever psutil is installed.
+ Uses psutil when available, falling back to None so callers can still
+ report the conflict without process details. Works on Windows, macOS,
+ and Linux wherever psutil is installed.
"""
try:
import psutil
@@ -444,7 +442,7 @@ def _get_pid_on_port(port: int) -> "tuple[int, str] | None":
except (psutil.NoSuchProcess, psutil.AccessDenied):
return (conn.pid, "<unknown>")
except (psutil.AccessDenied, OSError) as e:
- # psutil.net_connections() needs elevated privileges on some platforms
+ # net_connections() needs elevated privileges on some platforms.
logger.debug("Failed to scan network connections for port %s: %s", port, e)
return None
@@ -452,19 +450,17 @@ def _get_pid_on_port(port: int) -> "tuple[int, str] | None":
def _is_port_free(host: str, port: int) -> bool:
"""Check if a port is available for binding.
- When *host* is ``0.0.0.0`` (wildcard), we also check whether anything
- is already listening on ``127.0.0.1`` (and ``::1`` when IPv6 is
- available). An SSH tunnel or similar process may hold the loopback
- address while our wildcard bind still succeeds, making Unsloth Studio
- unreachable via ``localhost``.
+ When *host* is ``0.0.0.0`` (wildcard), also check whether anything is
+ already listening on ``127.0.0.1`` (and ``::1`` when IPv6 exists). An
+ SSH tunnel may hold the loopback address while our wildcard bind
+ succeeds, making Studio unreachable via ``localhost``.
Works on Windows, macOS, and Linux.
"""
import socket
- # 1. Can we bind to the requested address?
- # Use getaddrinfo so both IPv4 ("0.0.0.0") and IPv6 ("::") hosts
- # resolve to the correct address family automatically.
+ # 1. Can we bind to the requested address? getaddrinfo resolves both
+ # IPv4 ("0.0.0.0") and IPv6 ("::") to the right address family.
try:
addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
family, socktype, proto, _, sockaddr = addr_info[0]
@@ -474,9 +470,9 @@ def _is_port_free(host: str, port: int) -> bool:
except OSError:
return False
- # 2. When binding to all interfaces, verify that localhost is not
- # already claimed by another process (e.g. an SSH -L tunnel).
- # We attempt a TCP connect -- if it succeeds something is listening.
+ # 2. When binding to all interfaces, verify localhost isn't already
+ # claimed by another process (e.g. an SSH -L tunnel). A successful
+ # TCP connect means something is listening.
if host in ("0.0.0.0", "::"):
for loopback, family in [
("127.0.0.1", socket.AF_INET),
@@ -486,10 +482,10 @@ def _is_port_free(host: str, port: int) -> bool:
with socket.socket(family, socket.SOCK_STREAM) as s:
s.settimeout(1)
if s.connect_ex((loopback, port)) == 0:
- # Connection succeeded -- port is taken on loopback
+ # Port is taken on loopback.
return False
except OSError:
- # IPv6 disabled or other OS-level restriction -- skip
+ # IPv6 disabled or other OS-level restriction -- skip.
continue
return True
@@ -500,7 +496,7 @@ def _find_free_port(
start: int,
max_attempts: int = 20,
) -> int:
- """Find a free port starting from `start`, trying up to max_attempts ports."""
+ """Find a free port from `start`, trying up to max_attempts ports."""
for offset in range(max_attempts):
candidate = start + offset
if _is_port_free(host, candidate):
@@ -514,7 +510,7 @@ _PID_FILE = _studio_root() / "studio.pid"
# Direct backend launches bypass the CLI's env re-export; do it here for
# real custom roots so unsloth-zoo's import-time LLAMA_CPP_DEFAULT_DIR
-# picks up the custom build. Skip for legacy-default to avoid flipping
+# picks up the custom build. Skip legacy-default to avoid flipping
# default-mode installs into env-override.
try:
_LEGACY_STUDIO_ROOT = (Path.home() / ".unsloth" / "studio").resolve()
@@ -552,20 +548,20 @@ def _remove_pid_file():
def _graceful_shutdown(server = None):
- """Explicitly shut down all subprocess backends and the uvicorn server.
+ """Shut down all subprocess backends and the uvicorn server.
- Called from signal handlers to ensure child processes are cleaned up
- before the parent exits. This is critical on Windows where atexit
- handlers are unreliable after Ctrl+C.
+ Called from signal handlers to clean up child processes before the
+ parent exits. Critical on Windows where atexit handlers are
+ unreliable after Ctrl+C.
"""
_remove_pid_file()
logger.info("Graceful shutdown initiated — cleaning up subprocesses...")
- # 1. Shut down uvicorn server (releases the listening socket)
+ # 1. Shut down uvicorn (releases the listening socket).
if server is not None:
server.should_exit = True
- # 2. Clean up inference subprocess (if instantiated)
+ # 2. Clean up inference subprocess (if instantiated).
try:
from core.inference.orchestrator import _inference_backend
if _inference_backend is not None:
@@ -573,7 +569,7 @@ def _graceful_shutdown(server = None):
except Exception as e:
logger.warning("Error shutting down inference subprocess: %s", e)
- # 3. Clean up export subprocess (if instantiated)
+ # 3. Clean up export subprocess (if instantiated).
try:
from core.export.orchestrator import _export_backend
if _export_backend is not None:
@@ -581,7 +577,7 @@ def _graceful_shutdown(server = None):
except Exception as e:
logger.warning("Error shutting down export subprocess: %s", e)
- # 4. Clean up training subprocess (if active)
+ # 4. Clean up training subprocess (if active).
try:
from core.training.training import _training_backend
if _training_backend is not None:
@@ -589,7 +585,7 @@ def _graceful_shutdown(server = None):
except Exception as e:
logger.warning("Error shutting down training subprocess: %s", e)
- # 5. Kill llama-server subprocess (if loaded)
+ # 5. Kill llama-server subprocess (if loaded).
try:
from routes.inference import _llama_cpp_backend
if _llama_cpp_backend is not None:
@@ -601,10 +597,10 @@ def _graceful_shutdown(server = None):
# The uvicorn server instance -- set by run_server(), used by callers
-# that need to tell the server to exit (e.g. signal handlers).
+# that tell the server to exit (e.g. signal handlers).
_server = None
-# Shutdown event -- used to wake the main loop on signal
+# Shutdown event -- wakes the main loop on signal.
_shutdown_event = None
@@ -615,8 +611,8 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":
"""Yield `studio/frontend/dist` paths to try when the default is missing.
Covers PATH-shadowed binaries whose __file__ resolves into a
- site-packages tree that never received a vite build (e.g. plain
- `pip install unsloth` from PyPI).
+ site-packages tree with no vite build (e.g. plain `pip install
+ unsloth` from PyPI).
"""
import ast
import re
@@ -642,9 +638,9 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":
src = finder.read_text(encoding = "utf-8")
except OSError:
continue
- # Tolerate single- or multi-line dict literals; [^}]* still
- # rejects nested dicts, which the setuptools template never
- # emits for editable installs.
+ # Tolerate single- or multi-line dict literals; [^}]*
+ # still rejects nested dicts, which the setuptools
+ # template never emits for editable installs.
m = re.search(r"^MAPPING\s*(?::[^=]*)?=\s*(\{[^}]*\})", src, re.M | re.S)
if not m:
continue
@@ -652,8 +648,8 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":
mapping = ast.literal_eval(m.group(1))
except (SyntaxError, ValueError):
continue
- # Defensive: literal_eval can return a set / list / None if the
- # matched literal is not a dict (regex captures `{...}`).
+ # Defensive: literal_eval can return a set/list/None if
+ # the matched `{...}` literal isn't a dict.
if not isinstance(mapping, dict):
continue
studio_pkg = mapping.get("studio")
@@ -663,10 +659,10 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":
def _resolve_frontend_path(frontend_path: Path) -> tuple[Optional[Path], list[Path]]:
- """Pick a frontend dir that actually contains `index.html`.
+ """Pick a frontend dir that contains `index.html`.
Returns (chosen, attempted). `chosen` is None if nothing servable was
- found; `attempted` is the full ordered list for diagnostics.
+ found; `attempted` is the ordered list for diagnostics.
"""
attempted: list[Path] = []
seen: set[Path] = set()
@@ -706,25 +702,25 @@ def run_server(
port: Port to bind to (auto-increments if in use)
frontend_path: Path to frontend build directory (optional)
silent: Suppress startup messages
- api_only: Run API server only, no frontend serving (for Tauri desktop app)
- llama_parallel_slots: Number of parallel slots for llama-server
+ api_only: API server only, no frontend (for Tauri desktop app)
+ llama_parallel_slots: parallel slots for llama-server
Note:
- Signal handlers are NOT registered here so that embedders
- (e.g. Colab notebooks) keep their own interrupt semantics.
- Standalone callers should register handlers after calling this.
+ Signal handlers are NOT registered here so embedders (e.g. Colab
+ notebooks) keep their own interrupt semantics. Standalone callers
+ should register handlers after calling this.
"""
global _server, _shutdown_event
- # On Windows the default console encoding (cp1252) cannot encode emoji.
- # Reconfigure stdout to UTF-8 so startup messages do not crash the server.
+ # Windows console encoding (cp1252) can't encode emoji. Reconfigure
+ # stdout to UTF-8 so startup messages don't crash the server.
if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding = "utf-8", errors = "replace")
except Exception:
pass
- # Set env var BEFORE importing main so CORS middleware picks it up
+ # Set env var BEFORE importing main so CORS middleware picks it up.
if api_only:
os.environ["UNSLOTH_API_ONLY"] = "1"
@@ -739,10 +735,10 @@ def run_server(
from main import app, setup_frontend, _IS_COLAB
from utils.paths import ensure_studio_directories
- # Create all standard directories on startup
+ # Create all standard directories on startup.
ensure_studio_directories()
- # Auto-find free port if requested port is in use
+ # Auto-find a free port if the requested one is in use.
if not _is_port_free(host, port):
original_port = port
blocker = _get_pid_on_port(port)
@@ -760,14 +756,14 @@ def run_server(
print("=" * 50)
print("")
- # Setup frontend if path provided (skip in api-only mode).
- # Falls back through alternate locations if the default lacks a built
- # dist; errors out loudly rather than silently serving 404 on `/`.
+ # Setup frontend if path provided (skip in api-only mode). Falls back
+ # through alternate locations if the default lacks a built dist;
+ # errors loudly rather than serving 404 on `/`.
if frontend_path and not api_only:
chosen, attempted = _resolve_frontend_path(Path(frontend_path))
if chosen is not None and setup_frontend(app, chosen):
if not silent:
- # Resolve so logs always show an absolute path for support.
+ # Resolve so logs show an absolute path for support.
try:
display = chosen.resolve()
except OSError:
@@ -779,8 +775,8 @@ def run_server(
or os.environ.get("STUDIO_HOME")
or str(Path.home() / ".unsloth" / "studio")
)
- # Windows ships the user-facing shim at $STUDIO_HOME/bin/unsloth.exe
- # (a hardlink to the venv exe); Linux/macOS use the venv binary
+ # Windows ships the shim at $STUDIO_HOME/bin/unsloth.exe (a
+ # hardlink to the venv exe); Linux/macOS use the venv binary
# at $STUDIO_HOME/unsloth_studio/bin/unsloth.
home = Path(home_str).expanduser()
if sys.platform == "win32":
@@ -803,7 +799,7 @@ def run_server(
" - reinstall: curl -fsSL https://unsloth.ai/install.sh | sh"
)
- # Resolve once; shared by the log rewrite and the banner.
+ # Resolve once; shared by the log rewrite and banner.
display_host = _resolve_external_ip() if host == "0.0.0.0" else host
_install_uvicorn_startup_log_rewrite(host, display_host)
@@ -825,11 +821,11 @@ def run_server(
access_log = False,
server_header = False,
)
- # Only in Colab: trust X-Forwarded-* from Colab's reverse proxy so the app
- # sees the real https origin. forwarded_allow_ips="*" is fine inside Colab's
- # single-user sandbox, but would be an unwanted security relaxation for a
- # normal local/standalone Studio, so leave uvicorn's safe defaults
- # (forwarded headers trusted from loopback only) in place there.
+ # Colab only: trust X-Forwarded-* from Colab's reverse proxy so the
+ # app sees the real https origin. forwarded_allow_ips="*" is fine in
+ # Colab's single-user sandbox but an unwanted relaxation for a normal
+ # local/standalone Studio, so leave uvicorn's safe defaults
+ # (forwarded headers trusted from loopback only) elsewhere.
if _IS_COLAB:
config_kwargs["proxy_headers"] = True
config_kwargs["forwarded_allow_ips"] = "*"
@@ -837,17 +833,16 @@ def run_server(
_server = _ReadyServer(config)
_shutdown_event = Event()
- # Expose the actual bound port so request-handling code can build
- # loopback URLs that point at the real backend, not whatever port a
- # reverse proxy or tunnel exposed in the request URL. Only publish
- # an explicit value when we know the concrete port; for ephemeral
- # binds (port==0) leave it unset and let request handlers fall back
- # to the ASGI request scope or request.base_url.
+ # Expose the actual bound port so request handlers build loopback
+ # URLs pointing at the real backend, not whatever port a proxy/tunnel
+ # exposed in the request URL. Only publish a concrete port; for
+ # ephemeral binds (port==0) leave it unset so handlers fall back to
+ # the ASGI request scope or request.base_url.
app.state.server_port = port if port and port > 0 else None
app.state.llama_parallel_slots = llama_parallel_slots
- # Expose a shutdown callable via app.state before the server can accept
- # requests so /api/shutdown is available as soon as readiness is published.
+ # Expose a shutdown callable via app.state before the server accepts
+ # requests so /api/shutdown is ready as soon as readiness publishes.
def _trigger_shutdown():
_graceful_shutdown(_server)
if _shutdown_event is not None:
@@ -855,11 +850,10 @@ def run_server(
app.state.trigger_shutdown = _trigger_shutdown
- # Run server in a daemon thread.
- # Use an explicit new_event_loop() + run_until_complete() instead of
- # asyncio.run() to avoid nest_asyncio's global patches to asyncio.run
- # interfering when called from a thread while Colab/IPython already has
- # a running loop on the main thread.
+ # Run server in a daemon thread. Use explicit new_event_loop() +
+ # run_until_complete() rather than asyncio.run() so nest_asyncio's
+ # global patches to asyncio.run don't interfere when called from a
+ # thread while Colab/IPython already runs a loop on the main thread.
def _run():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
@@ -876,9 +870,9 @@ def run_server(
thread = Thread(target = _run, daemon = True)
thread.start()
- # Wait until uvicorn has completed lifespan startup and bound sockets, or
- # until the server exits/fails before startup. This intentionally has no
- # correctness deadline: a slow but live startup should remain in progress.
+ # Wait until uvicorn finishes lifespan startup and binds sockets, or
+ # until the server exits/fails before startup. No correctness
+ # deadline: a slow but live startup should remain in progress.
try:
while not ready_event.is_set():
if startup_failed.is_set() or not thread.is_alive():
@@ -898,8 +892,8 @@ def run_server(
atexit.register(_remove_pid_file)
- # Output port for Tauri to parse when in api-only mode. Emit only after
- # uvicorn sockets are bound and FastAPI lifespan/startup has completed.
+ # Output port for Tauri to parse in api-only mode. Emit only after
+ # uvicorn sockets are bound and FastAPI startup completed.
if api_only:
print(f"TAURI_PORT={port}", flush = True)
@@ -909,13 +903,13 @@ def run_server(
return app
-# For direct execution (also invoked by CLI via os.execvp / subprocess)
+# For direct execution (also invoked by CLI via os.execvp / subprocess).
if __name__ == "__main__":
import argparse
import signal
import traceback
- # Ensure stderr can handle Unicode on Windows (tracebacks with non-ASCII paths)
+ # Ensure stderr handles Unicode on Windows (non-ASCII path tracebacks).
if sys.platform == "win32" and hasattr(sys.stderr, "reconfigure"):
try:
sys.stderr.reconfigure(encoding = "utf-8", errors = "replace")
@@ -942,7 +936,7 @@ if __name__ == "__main__":
help = "API server only, no frontend (for Tauri)",
)
# Mirror unsloth_cli/commands/studio.py's _PARALLEL_*. Default 1
- # applies only to direct backend launches; `unsloth studio run`
+ # applies to direct backend launches only; `unsloth studio run`
# always passes its own value (4) explicitly.
_PARALLEL_MIN = 1
_PARALLEL_MAX = 64
@@ -985,7 +979,7 @@ if __name__ == "__main__":
sys.stderr.flush()
sys.exit(1)
- # Signal handler -- ensures subprocess cleanup on Ctrl+C
+ # Signal handler -- ensures subprocess cleanup on Ctrl+C.
def _signal_handler(signum, frame):
_graceful_shutdown(_server)
_shutdown_event.set()
@@ -993,13 +987,13 @@ if __name__ == "__main__":
signal.signal(signal.SIGINT, _signal_handler)
signal.signal(signal.SIGTERM, _signal_handler)
- # On Windows, some terminals send SIGBREAK for Ctrl+C / Ctrl+Break
+ # On Windows, some terminals send SIGBREAK for Ctrl+C / Ctrl+Break.
if hasattr(signal, "SIGBREAK"):
signal.signal(signal.SIGBREAK, _signal_handler)
# Keep running until shutdown signal.
# NOTE: Event.wait() without a timeout blocks at the C level on Linux,
- # which prevents Python from delivering SIGINT (Ctrl+C). Using a
- # short timeout in a loop lets the interpreter process pending signals.
+ # preventing Python from delivering SIGINT (Ctrl+C). A short timeout
+ # in a loop lets the interpreter process pending signals.
while not _shutdown_event.is_set():
_shutdown_event.wait(timeout = 1)
diff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.py
index 2bda4357ba3..08ceae1b595 100644
--- a/studio/backend/startup_banner.py
+++ b/studio/backend/startup_banner.py
@@ -3,7 +3,7 @@
"""Terminal banner for Studio startup.
-Stdlib only — safe to import without the rest of the backend (no structlog/uvicorn).
+Stdlib only — safe to import without the rest of the backend.
"""
from __future__ import annotations
@@ -34,7 +34,7 @@ def print_port_in_use_notice(original_port: int, new_port: int) -> None:
def print_studio_stop_hint() -> None:
- """Print the trailing stop hint + closing divider. Separate from the main
+ """Print the trailing stop hint + closing divider. Separate from the
banner so callers can interleave content (e.g. a reachability check)."""
use_color = stdout_supports_color()
dim = "\033[38;5;245m"
@@ -67,7 +67,7 @@ def print_studio_access_banner(
display_host: str,
include_stop_hint: bool = True,
) -> None:
- """Pretty-print URLs after the server is listening. Set
+ """Pretty-print URLs once the server is listening. Set
``include_stop_hint=False`` to omit the trailing stop block; pair with
:func:`print_studio_stop_hint` after inserting your own content."""
use_color = stdout_supports_color()
@@ -96,8 +96,8 @@ def print_studio_access_banner(
listen_all = bind_host in ("0.0.0.0", "::")
loopback_bind = bind_host in ("127.0.0.1", "localhost", "::1")
- # Use loopback URL only when the server is reachable on loopback;
- # otherwise show the actual bound address.
+ # Use the loopback URL only when reachable on loopback; otherwise show
+ # the actual bound address.
primary_url = loopback_url if listen_all or loopback_bind else external_url
tip_url = alt_local if listen_all or loopback_bind else external_url
api_base = primary_url
diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.py
index 9dd90a58bbf..bbd7186ed40 100644
--- a/studio/backend/storage/mcp_servers_db.py
+++ b/studio/backend/storage/mcp_servers_db.py
@@ -28,7 +28,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
)
"""
)
- # use_oauth was added after the first release; backfill for pre-existing DBs.
+ # use_oauth added after the first release; backfill for pre-existing DBs.
cols = {r["name"] for r in conn.execute("PRAGMA table_info(mcp_servers)").fetchall()}
if "use_oauth" not in cols:
conn.execute("ALTER TABLE mcp_servers ADD COLUMN use_oauth INTEGER NOT NULL DEFAULT 0")
diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.py
index 3c6056fb8d4..e58133090d5 100644
--- a/studio/backend/storage/providers_db.py
+++ b/studio/backend/storage/providers_db.py
@@ -4,8 +4,8 @@
"""
SQLite storage for external LLM provider configurations.
-Follows the same pattern as studio_db.py — module-level functions,
-raw sqlite3, WAL mode, per-function connections.
+Same pattern as studio_db.py: module-level functions, raw sqlite3, WAL
+mode, per-function connections.
NOTE: API keys are NOT stored here. They live only in the browser
(localStorage) and are sent encrypted per-request.
@@ -26,7 +26,7 @@ _schema_ready = False
def _ensure_schema(conn: sqlite3.Connection) -> None:
- """Create the llm_providers table if it doesn't exist. Called once per process."""
+ """Create the llm_providers table if absent. Called once per process."""
conn.execute("PRAGMA journal_mode=WAL")
conn.execute(
"""
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 5f0d6449d5d..d3900387d4a 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -4,8 +4,8 @@
"""
SQLite storage for training run history and metrics.
-Follows the same pattern as auth/storage.py — module-level functions,
-raw sqlite3, per-function connections. Enhancements over auth:
+Same pattern as auth/storage.py — module-level functions, raw sqlite3,
+per-function connections. Enhancements over auth:
- WAL mode for concurrent read/write access
- PRAGMA foreign_keys = ON for CASCADE deletes
"""
@@ -34,8 +34,8 @@ def _denied_path_prefixes() -> list[str]:
if system == "Linux":
return ["/proc", "/sys", "/dev", "/etc", "/boot", "/run"]
if system == "Darwin":
- # realpath() resolves /etc -> /private/etc, /tmp -> /private/tmp on macOS,
- # so include the /private variants to avoid bypasses.
+ # realpath() resolves /etc -> /private/etc, /tmp -> /private/tmp on
+ # macOS, so include the /private variants to avoid bypasses.
return [
"/System",
"/Library",
@@ -174,9 +174,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_metrics_run_id ON training_metrics(run_id)")
- # Use COLLATE NOCASE on Windows so C:\Models and c:\models dedup via the
- # UNIQUE constraint. On Linux/macOS (case-sensitive FS) keep the default
- # BINARY collation so /Models and /models remain distinct.
+ # COLLATE NOCASE on Windows so C:\Models and c:\models dedup via the
+ # UNIQUE constraint. On Linux/macOS (case-sensitive FS) keep the default
+ # BINARY collation so /Models and /models stay distinct.
collation = "COLLATE NOCASE" if platform.system() == "Windows" else ""
conn.execute(
f"""
@@ -287,15 +287,14 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
)
"""
)
- # Server-side import ledger so a studio.db wipe correctly re-triggers
- # the legacy Dexie import. The previous boolean localStorage sentinel
- # (`unsloth_chat_legacy_imported_to_studio_db`) is non-recoverable:
- # if studio.db is recreated while the browser keeps the flag, legacy
- # Dexie threads are silently hidden from the sidebar. The ledger
- # lives inside studio.db so it disappears together with the data it
- # is supposed to track, which is the recovery the boolean lacked.
- # Keyed by legacy thread id; per-thread is sufficient because Dexie
- # is read-only after this PR (a thread's message set does not grow).
+ # Server-side import ledger so a studio.db wipe re-triggers the legacy
+ # Dexie import. The old boolean localStorage sentinel
+ # (`unsloth_chat_legacy_imported_to_studio_db`) was non-recoverable: if
+ # studio.db is recreated while the browser keeps the flag, legacy Dexie
+ # threads are silently hidden from the sidebar. The ledger lives inside
+ # studio.db so it disappears with the data it tracks -- the recovery the
+ # boolean lacked. Keyed by legacy thread id; per-thread suffices because
+ # Dexie is read-only after this PR (a thread's message set doesn't grow).
conn.execute(
"""
CREATE TABLE IF NOT EXISTS chat_legacy_imports (
@@ -313,7 +312,7 @@ def get_connection() -> sqlite3.Connection:
ensure_dir(db_path.parent)
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
- # foreign_keys is session-scoped, must be set per connection
+ # foreign_keys is session-scoped; set per connection
conn.execute("PRAGMA foreign_keys=ON")
if not _schema_ready:
with _schema_lock:
@@ -701,9 +700,9 @@ def add_scan_folder(path: str) -> dict:
if not os.access(normalized, os.R_OK | os.X_OK):
raise ValueError("Path is not readable")
- # On Windows, use normcase for denylist comparison but store the
- # original-cased path so downstream consumers see the native
- # drive-letter casing the user expects (e.g. C:\Models, not c:\models).
+ # On Windows, normcase for the denylist comparison but store the
+ # original-cased path so downstream consumers see the native drive-letter
+ # casing the user expects (e.g. C:\Models, not c:\models).
is_win = platform.system() == "Windows"
check = os.path.normcase(normalized) if is_win else normalized
for prefix in _denied_path_prefixes():
@@ -713,8 +712,8 @@ def add_scan_folder(path: str) -> dict:
conn = get_connection()
try:
now = datetime.now(timezone.utc).isoformat()
- # On Windows, use case-insensitive lookup so C:\Models and c:\models
- # dedup correctly while preserving the originally-stored casing.
+ # On Windows, case-insensitive lookup so C:\Models and c:\models dedup
+ # while preserving the originally-stored casing.
if is_win:
existing = conn.execute(
"SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE",
@@ -735,8 +734,8 @@ def add_scan_folder(path: str) -> dict:
conn.commit()
except sqlite3.IntegrityError:
pass # duplicate -- fall through to SELECT
- # Use the same collation as the pre-check so we find the row even
- # when a concurrent writer stored it with different casing (Windows).
+ # Same collation as the pre-check so we find the row even when a
+ # concurrent writer stored it with different casing (Windows).
fallback_sql = (
"SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE"
if is_win
@@ -1408,8 +1407,8 @@ def _deep_merge_settings(current: dict[str, Any], updates: dict[str, Any]) -> di
def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:
- """Atomic read-merge-write under BEGIN IMMEDIATE so two concurrent writers
- cannot drop one another's updates."""
+ """Atomic read-merge-write under BEGIN IMMEDIATE so concurrent writers
+ cannot drop each other's updates."""
if not updates:
return list_chat_settings()
conn = get_connection()
@@ -1457,8 +1456,8 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:
def list_chat_legacy_imports() -> list[str]:
"""Return the legacy_thread_id of every thread already imported.
- Cheap: scans a single small PK-only table. The frontend stuffs the
- result into a Set before walking Dexie, so the diff is O(|Dexie|).
+ Cheap: scans one small PK-only table. The frontend puts the result in a
+ Set before walking Dexie, so the diff is O(|Dexie|).
"""
conn = get_connection()
try:
@@ -1472,13 +1471,13 @@ def upsert_chat_legacy_imports(legacy_thread_ids: list[str]) -> tuple[int, int]:
"""Mark each given legacy thread id as imported. Idempotent.
Returns (accepted, inserted):
- - accepted: number of non-empty deduped input ids
- - inserted: number of rows that were actually new (not already in ledger)
+ - accepted: count of non-empty deduped input ids
+ - inserted: count of rows that were actually new (not already in ledger)
ON CONFLICT DO NOTHING keeps the existing imported_at when an id is
- recorded twice. INSERT...RETURNING reports only the rows that were
- actually inserted, so callers can distinguish first-time imports
- from idempotent re-runs without an extra SELECT.
+ recorded twice. INSERT...RETURNING reports only newly-inserted rows, so
+ callers distinguish first-time imports from idempotent re-runs without an
+ extra SELECT.
"""
ids = list(dict.fromkeys(tid for tid in legacy_thread_ids if tid))
if not ids:
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 6aa6d314c1f..d903e045146 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -7,19 +7,19 @@ Shared pytest configuration for the backend test suite.
Responsibilities:
1. Put the backend root on sys.path so `from models.inference import ...`
(and similar flat imports) resolve in test modules — mirrors how the
- app itself is launched.
+ app is launched.
2. Provide a hybrid ``studio_server`` session fixture for end-to-end tests
- (see ``test_studio_api.py``). The fixture supports two invocation modes:
+ (see ``test_studio_api.py``), supporting two invocation modes:
a. **External server.** If ``UNSLOTH_E2E_BASE_URL`` is set, tests point
- at an already-running Studio instance. ``UNSLOTH_E2E_API_KEY`` must
- also be set. This is the fast-iteration mode: start the server once
- with ``unsloth studio run ...``, then run pytest against it many
- times with no per-run GGUF load cost.
+ at an already-running Studio instance (``UNSLOTH_E2E_API_KEY`` must
+ also be set). Fast-iteration mode: start the server once with
+ ``unsloth studio run ...``, then run pytest against it many times with
+ no per-run GGUF load cost.
- b. **Fixture-managed server.** Otherwise, the fixture launches a fresh
- server via ``_start_server`` and tears it down at session end. This
- is the one-shot mode for CI or a clean-slate verification run.
+ b. **Fixture-managed server.** Otherwise the fixture launches a fresh
+ server via ``_start_server`` and tears it down at session end. One-shot
+ mode for CI or a clean-slate verification run.
The model / variant for mode (b) come from ``--unsloth-model`` /
``--unsloth-gguf-variant`` pytest options, then ``UNSLOTH_E2E_MODEL`` /
@@ -80,16 +80,16 @@ def studio_server(request):
Resolution order:
- 1. If ``UNSLOTH_E2E_BASE_URL`` is set → point at that server,
- require ``UNSLOTH_E2E_API_KEY`` alongside (skip if missing).
- 2. Otherwise → start a fresh ``unsloth studio run`` subprocess via
- the existing ``_start_server`` helper in ``test_studio_api.py``
- and tear it down on session teardown.
+ 1. If ``UNSLOTH_E2E_BASE_URL`` is set → point at that server, requiring
+ ``UNSLOTH_E2E_API_KEY`` alongside (skip if missing).
+ 2. Otherwise → start a fresh ``unsloth studio run`` subprocess via the
+ ``_start_server`` helper in ``test_studio_api.py`` and tear it down on
+ session teardown.
- Session-scoped so the expensive GGUF load happens at most once per
- pytest invocation. Lazily instantiated — tests that don't request
- the fixture (e.g. the unit tests in ``test_anthropic_messages.py``
- or ``test_help_output``) do not trigger server startup.
+ Session-scoped so the expensive GGUF load happens at most once per pytest
+ invocation. Lazy — tests that don't request the fixture (e.g. the unit
+ tests in ``test_anthropic_messages.py`` or ``test_help_output``) don't
+ trigger server startup.
"""
external_url = os.environ.get("UNSLOTH_E2E_BASE_URL")
if external_url:
@@ -103,9 +103,9 @@ def studio_server(request):
yield external_url, api_key
return
- # Lazy import: pytest has already loaded test_studio_api into
- # sys.modules by the time any test requests this fixture, so this
- # is a cache hit, not a re-execution.
+ # Lazy import: pytest has already loaded test_studio_api into sys.modules
+ # by the time any test requests this fixture, so this is a cache hit, not
+ # a re-execution.
import test_studio_api as _e2e
model = (
diff --git a/studio/backend/tests/test_anthropic_cache_ttl.py b/studio/backend/tests/test_anthropic_cache_ttl.py
index e5d806e3c27..895c5985460 100644
--- a/studio/backend/tests/test_anthropic_cache_ttl.py
+++ b/studio/backend/tests/test_anthropic_cache_ttl.py
@@ -1,18 +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
-"""Unit tests for the prompt_cache_ttl threading on the Anthropic path.
+"""Unit tests for prompt_cache_ttl threading on the Anthropic path.
Anthropic accepts an optional ``ttl`` on each ``cache_control`` marker:
-the default is the 5-minute ephemeral pool; ``ttl:"1h"`` writes into
-the 1-hour pool instead. The 1h pool is the right pick when
-conversations span multiple short bursts more than 5 minutes apart --
-1h writes are billed at 2x base input vs 1.25x for 5m, but reads stay
-at 0.1x for both, so one extra read pays off the premium.
-
-These tests pin the outbound body shape: when prompt_cache_ttl="1h"
-both cache_control markers carry ``ttl:"1h"``; default omits the field
-entirely so the 5m pool is used; garbage values are silently dropped.
+default is the 5-minute ephemeral pool; ``ttl:"1h"`` writes into the
+1-hour pool. The 1h pool fits conversations spanning short bursts more
+than 5 minutes apart -- 1h writes bill at 2x base input vs 1.25x for 5m,
+but reads stay at 0.1x for both, so one extra read pays the premium.
+
+These tests pin the outbound body shape: prompt_cache_ttl="1h" puts
+``ttl:"1h"`` on both markers; default omits the field (5m pool); garbage
+values are silently dropped.
"""
import asyncio
@@ -128,13 +127,12 @@ def test_1h_ttl_writes_into_1h_pool(monkeypatch):
def test_1h_ttl_does_not_send_extended_cache_ttl_beta_header(monkeypatch):
- # The `extended-cache-ttl-2025-04-11` beta header that originally
- # gated 1h cache TTL has been promoted to GA: verified live against
- # api.anthropic.com on 2026-05-22 -- a request with
- # `cache_control:{type:"ephemeral", ttl:"1h"}` and NO beta header
- # returns 200 and populates `ephemeral_1h_input_tokens`. Pin the
- # contract so we don't reintroduce the gate by accident; a future
- # regression that re-adds the header would surface here.
+ # The `extended-cache-ttl-2025-04-11` beta header that originally gated
+ # 1h cache TTL is now GA: verified live against api.anthropic.com on
+ # 2026-05-22 -- a request with `cache_control:{type:"ephemeral",
+ # ttl:"1h"}` and NO beta header returns 200 and populates
+ # `ephemeral_1h_input_tokens`. Pin the contract so a regression that
+ # re-adds the header surfaces here.
captured = _capture(monkeypatch, ttl = "1h")
beta = captured["headers"].get("anthropic-beta", "")
assert "extended-cache-ttl-2025-04-11" not in beta, beta
@@ -156,7 +154,7 @@ def test_unknown_ttl_silently_dropped(monkeypatch, bogus):
assert len(ccs) == 2, ccs
for cc in ccs:
# Bogus TTLs must NOT round-trip; marker stays at the default
- # (no `ttl` key, which means the 5m pool upstream).
+ # (no `ttl` key = 5m pool upstream).
assert cc == {"type": "ephemeral"}, cc
diff --git a/studio/backend/tests/test_anthropic_citations.py b/studio/backend/tests/test_anthropic_citations.py
index ab5ba10b56c..c6104f2425a 100644
--- a/studio/backend/tests/test_anthropic_citations.py
+++ b/studio/backend/tests/test_anthropic_citations.py
@@ -3,11 +3,10 @@
"""Tests for Anthropic ``citations_delta`` handling in the streaming proxy.
-Verifies the proxy injects inline ``[N]`` markers after cited text,
-dedupes by type-specific anchor (char_location, page_location,
-content_block_location, search_result_location), forwards a synthetic
-``document_citations`` tool_event at message_stop, and stays inert when
-no citations_delta events fire. See
+Verifies the proxy injects inline ``[N]`` markers after cited text, dedupes by
+type-specific anchor (char_location, page_location, content_block_location,
+search_result_location), forwards a synthetic ``document_citations`` tool_event
+at message_stop, and stays inert when no citations_delta events fire. See
https://platform.claude.com/docs/en/build-with-claude/citations
"""
diff --git a/studio/backend/tests/test_anthropic_citations_edge.py b/studio/backend/tests/test_anthropic_citations_edge.py
index 6b106008470..f89e5ebda83 100644
--- a/studio/backend/tests/test_anthropic_citations_edge.py
+++ b/studio/backend/tests/test_anthropic_citations_edge.py
@@ -50,10 +50,9 @@ def _capture(
messages: list[dict] | None = None,
captured_body: dict | None = None,
) -> list[str]:
- """Drive ``stream_chat_completion`` against a mocked Anthropic
- response and return the SSE lines. Pass ``captured_body`` to also
- capture the outgoing request body for assertions on the translated
- Anthropic shape.
+ """Drive ``stream_chat_completion`` against a mocked Anthropic response
+ and return the SSE lines. Pass ``captured_body`` to also capture the
+ outgoing request body for assertions on the translated Anthropic shape.
"""
def handler(request: httpx.Request) -> httpx.Response:
@@ -147,8 +146,8 @@ def _joined(lines: list[str]) -> str:
def _citation_payload(body: str) -> dict:
- """Pull the ``document_citations`` synthetic tool_event from the
- SSE body and return its payload. Raises if absent."""
+ """Return the ``document_citations`` synthetic tool_event payload from
+ the SSE body. Raises if absent."""
assert "document_citations" in body, body
for line in body.splitlines():
if not line.startswith("data: "):
@@ -167,8 +166,8 @@ def _citation_payload(body: str) -> dict:
def test_citation_with_no_preceding_text_still_emits_marker(monkeypatch):
- """citations_delta before any text_delta must not crash; marker
- lands at the start of the block."""
+ """citations_delta before any text_delta must not crash; marker lands
+ at the start of the block."""
cit = {
"type": "char_location",
"document_index": 0,
@@ -195,8 +194,8 @@ def test_citation_with_no_preceding_text_still_emits_marker(monkeypatch):
def test_citations_delta_with_non_dict_citation_is_ignored(monkeypatch):
- """Non-dict ``delta.citation`` must not crash, emit a marker, or
- poison the document_citations list."""
+ """Non-dict ``delta.citation`` must not crash, emit a marker, or poison
+ the document_citations list."""
lines = _capture(
monkeypatch,
[
@@ -220,8 +219,8 @@ def test_citations_delta_with_non_dict_citation_is_ignored(monkeypatch):
def test_citations_delta_with_missing_citation_field_is_ignored(monkeypatch):
- """Missing ``citation`` field is treated like a non-dict citation:
- skip without crashing."""
+ """Missing ``citation`` field is treated like a non-dict citation: skip
+ without crashing."""
lines = _capture(
monkeypatch,
[
@@ -245,8 +244,8 @@ def test_citations_delta_with_missing_citation_field_is_ignored(monkeypatch):
def test_char_location_with_reversed_indices_does_not_crash(monkeypatch):
- """Malformed char_location with reversed indices must not crash;
- the dedup key accepts any int pair and still surfaces a footnote."""
+ """Malformed char_location with reversed indices must not crash; the
+ dedup key accepts any int pair and still surfaces a footnote."""
cit = {
"type": "char_location",
"document_index": 0,
@@ -275,8 +274,8 @@ def test_char_location_with_reversed_indices_does_not_crash(monkeypatch):
def test_page_location_missing_document_index_does_not_crash(monkeypatch):
- """page_location missing ``document_index`` still produces a
- footnote; dedup key falls back to ``None`` for the missing field."""
+ """page_location missing ``document_index`` still produces a footnote;
+ dedup key falls back to ``None`` for the missing field."""
cit = {
"type": "page_location",
"document_title": "Untitled PDF",
@@ -303,8 +302,8 @@ def test_page_location_missing_document_index_does_not_crash(monkeypatch):
def test_content_block_location_with_non_int_block_index_does_not_crash(monkeypatch):
- """content_block_location with string block indices must not crash;
- dedup key tolerates non-int values."""
+ """content_block_location with string block indices must not crash; dedup
+ key tolerates non-int values."""
cit = {
"type": "content_block_location",
"document_index": 0,
@@ -332,8 +331,8 @@ def test_content_block_location_with_non_int_block_index_does_not_crash(monkeypa
def test_unknown_citation_type_falls_back_to_stringified_key(monkeypatch):
- """Unknown citation ``type`` (forward-compat) still dedupes:
- identical ones collapse, differing ones get distinct numbers."""
+ """Unknown citation ``type`` (forward-compat) still dedupes: identical
+ ones collapse, differing ones get distinct numbers."""
cit_a = {
"type": "future_shape_location",
"anchor": "abc",
@@ -369,8 +368,8 @@ def test_unknown_citation_type_falls_back_to_stringified_key(monkeypatch):
def test_mixed_citation_types_same_document_get_distinct_keys(monkeypatch):
- """char_location and page_location on the same document_index are
- distinct shapes; dedup key uses citation type as its first slot."""
+ """char_location and page_location on the same document_index are distinct
+ shapes; dedup key uses citation type as its first slot."""
cit_char = {
"type": "char_location",
"document_index": 0,
@@ -406,9 +405,9 @@ def test_mixed_citation_types_same_document_get_distinct_keys(monkeypatch):
def test_cited_text_is_preserved_in_synthetic_event(monkeypatch):
- """``cited_text`` must survive into the synthetic event so the
- Sources panel can render it as a tooltip. Anthropic does not bill
- cited_text against output tokens, so preserving it is free."""
+ """``cited_text`` must survive into the synthetic event so the Sources
+ panel can render it as a tooltip. Anthropic does not bill cited_text
+ against output tokens, so preserving it is free."""
cit = {
"type": "char_location",
"document_index": 0,
@@ -435,8 +434,8 @@ def test_cited_text_is_preserved_in_synthetic_event(monkeypatch):
def test_internal_key_field_never_leaks_to_client(monkeypatch):
- """The internal ``_key`` dedup sentinel must be stripped before
- the synthetic event is forwarded; it is not an Anthropic field."""
+ """The internal ``_key`` dedup sentinel must be stripped before the
+ synthetic event is forwarded; it is not an Anthropic field."""
cit = {
"type": "char_location",
"document_index": 0,
@@ -465,8 +464,8 @@ def test_internal_key_field_never_leaks_to_client(monkeypatch):
def test_citation_across_multiple_content_blocks_numbers_continue(monkeypatch):
- """Footnote numbering is per-message, not per-content-block:
- citations across separate blocks emit [1] then [2]."""
+ """Footnote numbering is per-message, not per-content-block: citations
+ across separate blocks emit [1] then [2]."""
cit_a = {
"type": "char_location",
"document_index": 0,
@@ -509,9 +508,9 @@ def test_citation_across_multiple_content_blocks_numbers_continue(monkeypatch):
def test_inline_marker_lands_after_text_run(monkeypatch):
- """Inline ``[N]`` must land AFTER the cited text run: Anthropic
- streams text then citation, so the proxy emits ``"...green.[1]"``
- not ``"[1]green"``."""
+ """Inline ``[N]`` must land AFTER the cited text run: Anthropic streams
+ text then citation, so the proxy emits ``"...green.[1]"`` not
+ ``"[1]green"``."""
cit = {
"type": "char_location",
"document_index": 0,
@@ -541,8 +540,8 @@ def test_inline_marker_lands_after_text_run(monkeypatch):
def test_no_synthetic_event_when_only_text_deltas(monkeypatch):
- """No citations_delta means no synthetic ``document_citations``
- event; Sources panel relies on absence to suppress the section."""
+ """No citations_delta means no synthetic ``document_citations`` event;
+ Sources panel relies on absence to suppress the section."""
lines = _capture(
monkeypatch,
[
@@ -561,9 +560,9 @@ def test_no_synthetic_event_when_only_text_deltas(monkeypatch):
def test_input_document_translation_enables_citations(monkeypatch):
- """``input_document`` must translate to an Anthropic ``document``
- block carrying ``citations: {enabled: true}`` (both base64 and url
- source branches) so upstream emits citations_delta."""
+ """``input_document`` must translate to an Anthropic ``document`` block
+ carrying ``citations: {enabled: true}`` (both base64 and url source
+ branches) so upstream emits citations_delta."""
captured_b64: dict = {}
_capture(
monkeypatch,
@@ -631,8 +630,8 @@ def test_input_document_translation_enables_citations(monkeypatch):
def test_cited_text_truncated_in_synthetic_event(monkeypatch):
- """``cited_text`` is capped server-side so multi-KB spans do not
- balloon the SSE payload."""
+ """``cited_text`` is capped server-side so multi-KB spans don't balloon
+ the SSE payload."""
from core.inference.external_provider import _CITED_TEXT_MAX_LEN
long_quote = "x" * (_CITED_TEXT_MAX_LEN + 4000)
diff --git a/studio/backend/tests/test_anthropic_code_execution.py b/studio/backend/tests/test_anthropic_code_execution.py
index dd2f2eef6cf..cc0fb21deb1 100644
--- a/studio/backend/tests/test_anthropic_code_execution.py
+++ b/studio/backend/tests/test_anthropic_code_execution.py
@@ -6,20 +6,18 @@ Unit tests for Anthropic's server-side `code_execution_20250825` tool
translation in `_stream_anthropic`.
Covers:
-- Request body: when ``enabled_tools=["code_execution"]``, the outbound
- ``tools`` array carries ``{"type": "code_execution_20250825", "name":
- "code_execution"}`` and the ``anthropic-beta`` header includes
- ``code-execution-2025-08-25``.
-- Combined request: ``enabled_tools=["web_search", "code_execution"]``
- sends both tool entries; the beta header still merges the code-exec
- flag onto whatever the registry contributed.
-- SSE translation: a `bash_code_execution` server_tool_use +
+- Request body: ``enabled_tools=["code_execution"]`` puts ``{"type":
+ "code_execution_20250825", "name": "code_execution"}`` in the outbound
+ ``tools`` and ``code-execution-2025-08-25`` in the ``anthropic-beta``
+ header.
+- Combined: ``["web_search", "code_execution"]`` sends both tool entries;
+ the beta header merges the code-exec flag onto the registry's.
+- SSE: a `bash_code_execution` server_tool_use +
`bash_code_execution_tool_result` pair emits one tool_start and one
- tool_end ``_toolEvent`` chunk with the expected arguments and result.
-- SSE translation: a `text_editor_code_execution` create + result emits
- a tool_start with ``kind="text_editor"`` + parsed args, and tool_end
- with ``"Created"`` (or ``"Updated"``) based on the ``is_file_update``
- flag.
+ tool_end ``_toolEvent`` chunk with the expected args and result.
+- SSE: a `text_editor_code_execution` create + result emits a tool_start
+ with ``kind="text_editor"`` + parsed args, and tool_end with
+ ``"Created"`` (or ``"Updated"``) per the ``is_file_update`` flag.
- Error path: a ``bash_code_execution_tool_result_error`` with
``error_code="container_expired"`` renders as ``"Error:
container_expired"`` in the tool_end ``result``.
@@ -116,13 +114,13 @@ def test_code_execution_tool_appended_to_request_body(monkeypatch):
body = captured["body"]
tools = body.get("tools") or []
- # Opus 4.7 gets the newer date-pinned variant (`_20260120`) that
- # supports REPL state persistence + programmatic tool calling.
+ # Opus 4.7 gets the newer date-pinned variant (`_20260120`) with REPL
+ # state persistence + programmatic tool calling.
assert {"type": "code_execution_20260120", "name": "code_execution"} in tools
# No web_search entry when only code_execution is enabled.
assert all("web_search" not in (t.get("type") or "") for t in tools)
- # Beta header still carries the documented flag; both `_20250825`
- # and `_20260120` are unlocked by the same header per upstream docs.
+ # Beta header still carries the flag; both `_20250825` and `_20260120`
+ # are unlocked by the same header per upstream docs.
beta_header = captured["headers"].get("anthropic-beta", "")
assert "code-execution-2025-08-25" in beta_header
@@ -193,11 +191,11 @@ def test_no_code_execution_tool_when_pill_off(monkeypatch):
_drive(run())
tools = captured["body"].get("tools") or []
- # Pill off -- neither the legacy nor the new code_execution variant
- # may appear on the wire.
+ # Pill off -- neither the legacy nor new code_execution variant may
+ # appear on the wire.
assert all("code_execution" not in (t.get("type") or "") for t in tools)
- # Beta header must NOT mention code-execution when the tool isn't on
- # -- that flag is opt-in only.
+ # Beta header must NOT mention code-execution when the tool is off --
+ # that flag is opt-in only.
assert "code-execution-2025-08-25" not in captured["headers"].get("anthropic-beta", "")
@@ -270,8 +268,8 @@ def test_bash_code_execution_emits_tool_start_and_end(monkeypatch):
assert start["type"] == "tool_start"
assert start["tool_name"] == "code_execution"
assert start["tool_call_id"] == "srvtoolu_1"
- # `_server_tool: True` marks this as a provider-side synthetic
- # tool card for the frontend's history serializer.
+ # `_server_tool: True` marks a provider-side synthetic tool card for
+ # the frontend's history serializer.
assert start["arguments"] == {"kind": "bash", "command": "ls -la", "_server_tool": True}
assert end["type"] == "tool_end"
diff --git a/studio/backend/tests/test_anthropic_compaction.py b/studio/backend/tests/test_anthropic_compaction.py
index 6da752eac4a..5047a93979d 100644
--- a/studio/backend/tests/test_anthropic_compaction.py
+++ b/studio/backend/tests/test_anthropic_compaction.py
@@ -4,15 +4,15 @@
"""Unit tests for Anthropic server-side context compaction wiring.
Compaction is a beta feature (header ``compact-2026-01-12``) gated to
-Opus 4.6, Opus 4.7, Sonnet 4.6, and Mythos preview. When enabled,
-Studio attaches ``context_management.edits[{type:"compact_20260112",
-trigger:{type:"input_tokens", value:N}}]`` to the outbound body. The
-minimum upstream-accepted threshold is 50k tokens; lower values are
-clamped to 50k so the request doesn't 400.
-
-These tests pin: the body shape per model, the beta header merge with
-the existing code-execution beta, threshold clamping, and silent no-op
-on unsupported models.
+Opus 4.6, Opus 4.7, Sonnet 4.6, and Mythos preview. When enabled, Studio
+attaches ``context_management.edits[{type:"compact_20260112",
+trigger:{type:"input_tokens", value:N}}]`` to the outbound body. Minimum
+upstream threshold is 50k tokens; lower values are clamped to 50k so the
+request doesn't 400.
+
+These tests pin: body shape per model, the beta header merge with the
+code-execution beta, threshold clamping, and silent no-op on unsupported
+models.
"""
import asyncio
@@ -168,10 +168,9 @@ def test_omitted_threshold_no_body_field(monkeypatch):
def test_chat_completion_request_accepts_sub_50k_compaction_threshold():
- # Codex P1 caught that ge=50_000 on the field caused FastAPI to
- # 422 the request before the in-helper clamp could fire. The
- # schema must accept any positive int and let _stream_anthropic
- # clamp upward.
+ # Codex P1 caught that ge=50_000 on the field made FastAPI 422 the
+ # request before the in-helper clamp could fire. The schema must
+ # accept any positive int and let _stream_anthropic clamp upward.
from models.inference import ChatCompletionRequest
req = ChatCompletionRequest.model_validate(
@@ -209,13 +208,12 @@ def test_chat_completion_request_accepts_sub_50k_compaction_threshold():
def test_message_delta_iterations_array_aggregates_compaction_tokens(monkeypatch, capsys):
# When Anthropic compacts mid-stream, the SSE message_delta usage
- # payload carries `iterations: [{type:"compaction", ...}, ...]`.
- # The top-level input_tokens / output_tokens only account for the
- # `message` iteration, so the cost surface needs the compaction
- # totals exposed separately. The stream helper folds them into
- # last_usage as `compaction_input_tokens` / `compaction_output_tokens`
- # and surfaces them in the closing summary log so an operator can
- # eyeball "did compaction cost us 180k tokens this turn?".
+ # carries `iterations: [{type:"compaction", ...}, ...]`. The top-level
+ # input_tokens / output_tokens only cover the `message` iteration, so
+ # compaction totals need to be exposed separately. The stream helper
+ # folds them into last_usage as `compaction_input_tokens` /
+ # `compaction_output_tokens` and surfaces them in the closing summary
+ # log so an operator can see "did compaction cost us 180k tokens?".
def http_handler(request: httpx.Request) -> httpx.Response:
body = (
@@ -258,8 +256,8 @@ def test_message_delta_iterations_array_aggregates_compaction_tokens(monkeypatch
_drive(run())
- # structlog renders the closing summary through the stdlib bridge,
- # which lands on stdout. Capture and check the rendered line.
+ # structlog renders the closing summary via the stdlib bridge onto
+ # stdout. Capture and check the rendered line.
out = capsys.readouterr().out
summary = next(
(line for line in out.splitlines() if "Anthropic stream complete" in line),
@@ -271,8 +269,8 @@ def test_message_delta_iterations_array_aggregates_compaction_tokens(monkeypatch
def test_message_delta_no_iterations_leaves_compaction_keys_unset(monkeypatch, capsys):
# Re-applying a previous compaction block does NOT emit a fresh
- # iterations array. The helper must not invent compaction keys
- # in that case (would otherwise double-bill).
+ # iterations array. The helper must not invent compaction keys then
+ # (would otherwise double-bill).
def http_handler(request: httpx.Request) -> httpx.Response:
body = (
b"event: message_delta\n"
@@ -331,19 +329,17 @@ def _async_collect(agen):
def test_compaction_block_emitted_as_tool_event(monkeypatch):
- # Codex P1: once context_management is enabled and Anthropic runs
- # compaction during a turn, the response carries a
- # `{type:"compaction", content:"<summary>"}` block. The translator
- # must surface it so the chat-adapter can persist it onto the
- # assistant message; otherwise the next turn loses the state and
- # Anthropic re-compacts from scratch.
+ # Codex P1: once context_management is enabled and Anthropic compacts
+ # during a turn, the response carries a `{type:"compaction",
+ # content:"<summary>"}` block. The translator must surface it so the
+ # chat-adapter persists it onto the assistant message; otherwise the
+ # next turn loses the state and Anthropic re-compacts from scratch.
def http_handler(request: httpx.Request) -> httpx.Response:
- # Anthropic ships compaction blocks as a content_block_start
- # with `type:"compaction"`, then either includes the summary
- # on that start event AND/OR streams it via text_delta events
- # on the same block index. Test the streamed-delta path since
- # it's the harder case.
+ # Anthropic ships compaction blocks as a content_block_start with
+ # `type:"compaction"`, then includes the summary on that start
+ # event AND/OR streams it via text_delta events on the same block
+ # index. Test the streamed-delta path since it's the harder case.
body = (
b"event: message_start\n"
b'data: {"type":"message_start","message":{"usage":{}}}\n\n'
@@ -411,8 +407,8 @@ def test_compaction_block_emitted_as_tool_event(monkeypatch):
except json.JSONDecodeError:
continue
# tool_event payloads ride inside chat.completion.chunk.choices[0].delta.content
- # as a JSON-encoded string. The simpler path: look for the
- # marker substring anywhere in the chunk.
+ # as a JSON-encoded string. Simpler: look for the marker substring
+ # anywhere in the chunk.
if "compaction_block" in raw:
events.append(raw)
assert events, f"no compaction_block tool event found in {lines}"
@@ -445,10 +441,10 @@ def test_compaction_block_emitted_as_tool_event(monkeypatch):
def test_compaction_block_round_trips_through_outbound_messages(monkeypatch):
- # Once the prior turn persisted a compaction block onto the
- # assistant message, the next turn's outbound body must forward
- # the {type:"compaction", content:"..."} block to Anthropic
- # verbatim so the API recognises the existing state.
+ # Once the prior turn persisted a compaction block onto the assistant
+ # message, the next turn's outbound body must forward the
+ # {type:"compaction", content:"..."} block to Anthropic verbatim so the
+ # API recognises the existing state.
captured: dict = {}
def http_handler(request: httpx.Request) -> httpx.Response:
@@ -527,10 +523,10 @@ def test_compaction_content_part_accepted_by_chat_message_schema():
def test_build_external_messages_passes_compaction_for_anthropic_only():
- # Compaction is an Anthropic-only synthetic content part. The
- # builder MUST gate it on provider_type=="anthropic"; every other
- # provider would 400 on the unknown content type via generic
- # /chat/completions passthrough (Codex P1 follow-up).
+ # Compaction is an Anthropic-only synthetic content part. The builder
+ # MUST gate it on provider_type=="anthropic"; every other provider
+ # would 400 on the unknown content type via generic /chat/completions
+ # passthrough (Codex P1 follow-up).
from models.inference import ChatMessage
from routes.inference import _build_external_messages
@@ -554,7 +550,7 @@ def test_build_external_messages_passes_compaction_for_anthropic_only():
def test_build_external_messages_strips_compaction_for_non_anthropic_providers():
# Provider switch (or reused history) hands compaction blocks to a
- # non-Anthropic provider. Those land on generic /chat/completions
+ # non-Anthropic provider, landing on generic /chat/completions
# passthrough where the unknown content type fails the upstream
# validator. Builder must strip the part for every non-anthropic
# provider, including OpenAI/DeepSeek/Mistral/Gemini/Kimi/OpenRouter.
diff --git a/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
index 94a1ca4e2cd..da0c0941ca7 100644
--- a/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
+++ b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
@@ -3,9 +3,9 @@
"""Tests for Anthropic fast-mode wiring and streaming refusal handling.
-fast_mode=True on Opus 4.6/4.7 attaches the ``fast-mode-2026-02-01``
-beta header and sets ``speed: "fast"``; unsupported models drop both.
-Streaming ``stop_reason: "refusal"`` surfaces a user notice before the
+fast_mode=True on Opus 4.6/4.7 attaches the ``fast-mode-2026-02-01`` beta
+header and sets ``speed: "fast"``; unsupported models drop both. Streaming
+``stop_reason: "refusal"`` surfaces a user notice before the
``content_filter`` finish chunk.
https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
"""
@@ -63,7 +63,7 @@ def _capture(
sse: bytes = b"",
**kwargs,
) -> tuple[dict, list[str]]:
- """Install a MockTransport, drive one streamed call, return body+lines."""
+ """Install a MockTransport, drive one streamed call; return body+lines."""
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
@@ -157,12 +157,12 @@ def test_refusal_emits_user_facing_notice_and_content_filter_finish(monkeypatch)
def test_refusal_emits_tool_event_for_chat_adapter_drop(monkeypatch):
"""Refused turns emit an out-of-band `_toolEvent` that the chat-adapter
- latches into assistant `metadata.custom.anthropicRefusal`, driving
- the next-request prune. Tool event (not text) prevents spoofing.
+ latches into assistant `metadata.custom.anthropicRefusal`, driving the
+ next-request prune. Tool event (not text) prevents spoofing.
"""
_, lines = _capture(monkeypatch, sse = _refusal_sse())
body = "\n".join(lines)
assert '"_toolEvent": {"type": "anthropic_refusal"}' in body, body
- # Visible refusal text must not embed a sentinel that could spoof
- # a context reset if echoed by another assistant message.
+ # Visible refusal text must not embed a sentinel that could spoof a
+ # context reset if echoed by another assistant message.
assert "studio:anthropic-refusal" not in body, body
diff --git a/studio/backend/tests/test_anthropic_fast_mode_edge.py b/studio/backend/tests/test_anthropic_fast_mode_edge.py
index 116f58f7f2d..dd69d775909 100644
--- a/studio/backend/tests/test_anthropic_fast_mode_edge.py
+++ b/studio/backend/tests/test_anthropic_fast_mode_edge.py
@@ -1,12 +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
-"""Edge-case coverage for the Anthropic fast-mode + refusal wiring.
+"""Edge-case coverage for Anthropic fast-mode + refusal wiring.
-Complements ``test_anthropic_fast_mode_and_refusal.py`` (happy path)
-with dated snapshots, strict opt-in (future Opus families do not
-auto-enable), multi-beta header merging, refusal stream ordering, and
-the non-destruction guarantee for unset/None fast_mode.
+Complements ``test_anthropic_fast_mode_and_refusal.py`` (happy path) with
+dated snapshots, strict opt-in (future Opus families do not auto-enable),
+multi-beta header merging, refusal stream ordering, and the
+non-destruction guarantee for unset/None fast_mode.
"""
import asyncio
@@ -128,7 +128,7 @@ def test_fast_mode_attaches_on_dated_opus_4_6_snapshot(monkeypatch):
# ──────────────────────────── strict opt-in semantics ────────────────────────────
def test_fast_mode_does_not_auto_enable_on_future_opus_4_8(monkeypatch):
- """Future ``claude-opus-4-8`` must not auto-enable; opt-in per family."""
+ """Future ``claude-opus-4-8`` must not auto-enable; per-family opt-in."""
cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-8")
assert "speed" not in cap["body"], cap["body"]
assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
@@ -248,7 +248,7 @@ def test_fast_mode_unset_is_byte_identical_to_omitted(monkeypatch):
_drive(run())
assert cap_none["body"] == captured["body"], (cap_none["body"], captured["body"])
- # Headers can vary by httpx-injected fields (host, connection); compare
+ # Headers vary by httpx-injected fields (host, connection); compare
# the load-bearing ones.
for key in ("anthropic-version", "x-api-key", "content-type"):
assert cap_none["headers"].get(key) == captured["headers"].get(key), key
@@ -323,8 +323,7 @@ def test_refusal_chunk_is_proper_openai_delta_shape(monkeypatch):
assert notice_chunk is not None, lines
choice = notice_chunk["choices"][0]
assert "delta" in choice and "content" in choice["delta"], notice_chunk
- # Must NOT carry a finish_reason itself -- that comes on the next
- # chunk.
+ # Must NOT carry a finish_reason itself -- that comes on the next chunk.
assert choice.get("finish_reason") in (None,), notice_chunk
# Refusal text is plain-spoken; no embedded sentinel.
assert "studio:anthropic-refusal" not in choice["delta"]["content"]
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index ee19a96bcad..c55ccbaaefd 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -2,7 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""
-Tests for the Anthropic Messages API schemas and translation layer.
+Tests for Anthropic Messages API schemas and translation layer.
No running server or GPU required.
"""
@@ -1187,14 +1187,14 @@ class TestAnthropicRequestedStudioTools:
def test_bare_name_without_type_is_not_treated_as_server_tool(self):
# Anthropic dispatches server tools by `type`; bare-name matching
- # would let a malformed client tool (e.g. user forgot input_schema)
- # silently flip the request into server-execution mode.
+ # would let a malformed client tool (missing input_schema) silently
+ # flip the request into server-execution mode.
tools = [{"name": "python"}]
assert _anthropic_requested_studio_tools(tools) == set()
def test_client_tool_named_python_is_not_misclassified(self):
- # input_schema is the client-tool discriminator; presence of it
- # must prevent the name from being treated as a Studio alias.
+ # input_schema is the client-tool discriminator; its presence must
+ # prevent the name from being treated as a Studio alias.
tools = [
{
"name": "python",
@@ -1239,8 +1239,8 @@ class _ToolPathCalled(Exception):
def _mock_backend(monkeypatch, **overrides):
"""Install a minimal stub backend on routes.inference.
- Generation methods raise sentinel exceptions so the caller can assert
- which path the route entered.
+ Generation methods raise sentinels so the caller can assert which path
+ the route entered.
"""
import routes.inference as inf_mod
@@ -1299,10 +1299,10 @@ class TestAnthropicMessagesToolRouting:
assert "Mixing Anthropic server tools" in exc.value.detail
def test_mixed_rejected_when_client_tool_name_collides_with_server_alias(self, monkeypatch):
- # Regression: a client tool sharing a name with a mapped server
- # tool (e.g. user defines their own "web_search") must still
- # trigger the mixed-mode 400 — the post-name filter would
- # otherwise drop the client tool and silently route to server-only.
+ # Regression: a client tool sharing a name with a mapped server tool
+ # (e.g. a custom "web_search") must still trigger the mixed-mode 400;
+ # otherwise the post-name filter drops the client tool and silently
+ # routes to server-only.
_mock_backend(monkeypatch)
payload = _basic_payload(
tools = [
@@ -1329,10 +1329,10 @@ class TestAnthropicMessagesToolRouting:
def test_client_tool_missing_name_rejected_with_400(self, monkeypatch):
# Regression: AnthropicTool.name was relaxed to Optional for server
- # tools, so a client-tool payload that has input_schema but omits
- # `name` (e.g. typo) now parses successfully but would be silently
- # dropped by anthropic_tools_to_openai, leaving the request with
- # tool calling disabled. Reject at the boundary instead.
+ # tools, so a client-tool payload with input_schema but no `name`
+ # (typo) now parses but would be silently dropped by
+ # anthropic_tools_to_openai, leaving tool calling disabled. Reject at
+ # the boundary instead.
_mock_backend(monkeypatch)
payload = _basic_payload(
tools = [{"input_schema": {"type": "object"}}],
@@ -1346,7 +1346,7 @@ class TestAnthropicMessagesToolRouting:
def test_client_tool_empty_name_rejected_with_400(self, monkeypatch):
# Same silent-disable class as missing-name: `name: ""` passes the
# isinstance check but is dropped by anthropic_tools_to_openai's
- # `if not name` guard. Reject at the boundary so the typo surfaces.
+ # `if not name` guard. Reject at the boundary so the typo shows.
_mock_backend(monkeypatch)
payload = _basic_payload(
tools = [{"name": "", "input_schema": {"type": "object"}}],
@@ -1358,10 +1358,10 @@ class TestAnthropicMessagesToolRouting:
assert "name" in exc.value.detail
def test_alias_named_client_tool_without_schema_rejected_with_400(self, monkeypatch):
- # Regression: a typo'd client tool whose name happens to collide
- # with a Studio alias (e.g. user meant a custom "python" tool but
- # forgot input_schema) must surface a 400, not silently switch
- # the request into Studio's built-in python execution.
+ # Regression: a typo'd client tool whose name collides with a Studio
+ # alias (e.g. a custom "python" tool missing input_schema) must
+ # surface a 400, not silently switch into Studio's built-in python
+ # execution.
_mock_backend(monkeypatch)
payload = _basic_payload(tools = [{"name": "python"}])
@@ -1380,9 +1380,8 @@ class TestAnthropicMessagesToolRouting:
_drive(anthropic_messages(payload, request = None, current_subject = "t"))
def test_disable_tools_policy_overrides_server_tool_alias(self, monkeypatch):
- # CLI `unsloth run --disable-tools` sets policy=False. A request
- # carrying a Studio server-tool alias must NOT enter the agentic
- # loop in that configuration.
+ # CLI `unsloth run --disable-tools` sets policy=False. A request with
+ # a Studio server-tool alias must NOT enter the agentic loop then.
_mock_backend(monkeypatch)
set_tool_policy(False)
payload = _basic_payload(
diff --git a/studio/backend/tests/test_anthropic_thinking_translation.py b/studio/backend/tests/test_anthropic_thinking_translation.py
index 14f261ae6ba..144de166f25 100644
--- a/studio/backend/tests/test_anthropic_thinking_translation.py
+++ b/studio/backend/tests/test_anthropic_thinking_translation.py
@@ -2,23 +2,19 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Unit tests for the Anthropic extended-thinking translation in
-external_provider.
+Unit tests for the Anthropic extended-thinking translation in external_provider.
Covers:
- Adaptive-mode request body nests effort under
- ``output_config: {effort: "<level>"}`` per the Messages API
- reference (a top-level ``effort`` field 400s with
- "effort: Extra inputs are not permitted").
-- Streaming SSE: ``content_block_delta`` with
- ``delta.type == "thinking_delta"`` is translated into inline
- ``<think>...</think>`` chat-completion chunks so the frontend's
- reasoning-panel pipeline lifts it correctly.
-- The ``<think>`` tag closes when the first ``text_delta`` arrives,
- on ``content_block_stop``, on ``message_delta``, or on
- ``message_stop``.
-- Thinking is paired with ``temperature=1`` and no ``top_p`` /
- ``top_k`` on the wire (Anthropic extended-thinking contract).
+ ``output_config: {effort: "<level>"}`` per the Messages API reference (a
+ top-level ``effort`` field 400s with "effort: Extra inputs are not permitted").
+- Streaming SSE: ``content_block_delta`` with ``delta.type == "thinking_delta"``
+ is translated into inline ``<think>...</think>`` chat-completion chunks so the
+ frontend's reasoning-panel pipeline lifts it correctly.
+- The ``<think>`` tag closes when the first ``text_delta`` arrives, on
+ ``content_block_stop``, on ``message_delta``, or on ``message_stop``.
+- Thinking is paired with ``temperature=1`` and no ``top_p`` / ``top_k`` on the
+ wire (Anthropic extended-thinking contract).
"""
import asyncio
@@ -113,9 +109,8 @@ def test_adaptive_thinking_body_uses_output_config_effort_shape(monkeypatch):
# display=summarized is set explicitly so Opus 4.7 (which defaults to
# "omitted") still emits thinking_delta events for the reasoning panel.
assert body["thinking"] == {"type": "adaptive", "display": "summarized"}
- # Documented shape: effort is nested under output_config.
- # A top-level `effort` field produces a 400:
- # "effort: Extra inputs are not permitted".
+ # Documented shape: effort is nested under output_config. A top-level
+ # `effort` field produces a 400: "effort: Extra inputs are not permitted".
assert body["output_config"] == {"effort": "medium"}
assert "effort" not in body
# Extended-thinking contract: temperature=1, no top_p / top_k.
@@ -258,10 +253,10 @@ def test_manual_thinking_body_uses_budget_tokens_on_4_5(monkeypatch):
body = captured["body"]
assert body["thinking"] == {"type": "enabled", "budget_tokens": 4096}
# max_tokens must be strictly greater than budget_tokens; we shipped 1024
- # and budget is 4096, so the wrapper should bump max_tokens.
+ # and budget is 4096, so the wrapper must bump max_tokens.
assert body["max_tokens"] > body["thinking"]["budget_tokens"]
- # Manual-thinking path does not use output_config / effort — those are
- # the adaptive-mode controls (Claude 4.6 / 4.7).
+ # Manual-thinking path does not use output_config / effort — those are the
+ # adaptive-mode controls (Claude 4.6 / 4.7).
assert "effort" not in body
assert "output_config" not in body
@@ -338,8 +333,8 @@ def test_thinking_delta_wrapped_in_think_tags(monkeypatch):
if isinstance(p, dict) and p["choices"][0]["delta"]
)
- # Reasoning text should be wrapped in <think>...</think>, followed by the
- # answer text, and the stream should terminate with [DONE].
+ # Reasoning text is wrapped in <think>...</think>, then the answer text, and
+ # the stream terminates with [DONE].
assert "<think>First I plan.</think>" in combined
assert combined.endswith("Answer.")
# signature_delta is intentionally dropped — no leaked signature text.
@@ -350,9 +345,9 @@ def test_thinking_delta_wrapped_in_think_tags(monkeypatch):
def test_thinking_only_turn_closes_tag_without_text_delta(monkeypatch):
"""display=omitted on Claude 4.7 emits a signature_delta and no text.
- The <think> open is still triggered by the (synthetic) thinking_delta;
- we want content_block_stop to close it cleanly so the tag never leaks
- into the next chunk."""
+ The <think> open is still triggered by the (synthetic) thinking_delta; we
+ want content_block_stop to close it cleanly so the tag never leaks into the
+ next chunk."""
def handler(request: httpx.Request) -> httpx.Response:
events = [
diff --git a/studio/backend/tests/test_anthropic_tool_versions.py b/studio/backend/tests/test_anthropic_tool_versions.py
index 8f5d3f7f461..f9ff448f66d 100644
--- a/studio/backend/tests/test_anthropic_tool_versions.py
+++ b/studio/backend/tests/test_anthropic_tool_versions.py
@@ -7,13 +7,12 @@ helpers in ``core.inference.external_provider``.
Anthropic ships date-pinned tool versions per model family. The newer
``_20260209`` web_search / web_fetch and ``_20260120`` code_execution
-variants only run on a subset of models; sending them to an older
-model returns a 400 from upstream, and sending the older
-``_20250305`` / ``_20250910`` / ``_20250825`` variants to a newer
-model misses dynamic filtering and the free-when-paired pricing. The
-helpers below decide which version goes out per model; this test pins
-the dispatch matrix so future model launches keep working without
-silently regressing the newer-version path.
+variants only run on a subset of models; sending them to an older model
+returns a 400 from upstream, and sending the older ``_20250305`` /
+``_20250910`` / ``_20250825`` variants to a newer model misses dynamic
+filtering and the free-when-paired pricing. The helpers below pick the
+version per model; this test pins the dispatch matrix so future model
+launches keep working without regressing the newer-version path.
Covers:
- ``_anthropic_web_search_version`` / ``_anthropic_web_fetch_version``
@@ -23,10 +22,10 @@ Covers:
- ``_anthropic_code_execution_version`` picks ``_20260120`` for the
Opus 4.5+ / Sonnet 4.5+ / Opus 4.7 / Sonnet 4.6 family and falls back
to ``_20250825`` everywhere else (Haiku 4.5, 4.1, 4.0).
-- ``_stream_anthropic`` body integration: when ``enabled_tools=
- ["web_search", "code_execution"]`` is set on Opus 4.7, the outbound
- body carries the newer pinned versions; the same payload on Haiku
- 4.5 falls back to the legacy versions.
+- ``_stream_anthropic`` body integration: with ``enabled_tools=
+ ["web_search", "code_execution"]`` on Opus 4.7, the outbound body
+ carries the newer pinned versions; the same payload on Haiku 4.5 falls
+ back to the legacy versions.
- The ``anthropic-beta: code-execution-2025-08-25`` header is sent
unchanged for both code-execution variants (no header rev needed).
"""
@@ -165,9 +164,9 @@ def test_outbound_body_uses_new_versions_on_opus_4_7(monkeypatch):
assert "code_execution_20260120" in tool_types
assert "web_search_20250305" not in tool_types
assert "code_execution_20250825" not in tool_types
- # Beta header for code execution stays on the existing flag for
- # both _20250825 and _20260120; the API uses one header to gate
- # the feature, not the date.
+ # Beta header for code execution stays on the existing flag for both
+ # _20250825 and _20260120; the API gates the feature by one header, not
+ # the date.
assert "code-execution-2025-08-25" in captured["headers"].get("anthropic-beta", "")
diff --git a/studio/backend/tests/test_anthropic_web_fetch.py b/studio/backend/tests/test_anthropic_web_fetch.py
index 7d754872cd9..542048ebd4c 100644
--- a/studio/backend/tests/test_anthropic_web_fetch.py
+++ b/studio/backend/tests/test_anthropic_web_fetch.py
@@ -1,12 +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
-"""
-Unit tests for Anthropic's `web_fetch_20250910` / `web_fetch_20260209`
+"""Unit tests for Anthropic's `web_fetch_20250910` / `web_fetch_20260209`
translation in ``_stream_anthropic``. Covers request body emission
-(version picked by ``_anthropic_web_fetch_version``: ``_20260209`` for
-Opus 4.6/4.7 + Sonnet 4.6, ``_20250910`` otherwise), combined tool
-requests, off-by-default behavior, and SSE translation of success and
+(version from ``_anthropic_web_fetch_version``: ``_20260209`` for Opus
+4.6/4.7 + Sonnet 4.6, else ``_20250910``), combined tool requests,
+off-by-default behavior, and SSE translation of success and
``url_not_accessible`` error paths into ``tool_start`` / ``tool_end``.
"""
@@ -103,7 +102,7 @@ def test_web_fetch_tool_appended_to_request_body(monkeypatch):
body = captured["body"]
tools = body.get("tools") or []
- # claude-opus-4-7 routes web_fetch to _20260209 (dynamic filtering).
+ # claude-opus-4-7 routes web_fetch to _20260209.
assert {"type": "web_fetch_20260209", "name": "web_fetch", "max_uses": 5} in tools
# web_fetch is GA; no beta header is required.
assert "web-fetch" not in captured["headers"].get("anthropic-beta", "")
@@ -140,13 +139,13 @@ def test_web_fetch_combined_with_web_search_and_code_execution(monkeypatch):
tools = captured["body"].get("tools") or []
tool_types = [t.get("type") for t in tools]
- # claude-opus-4-7 routes web_search and web_fetch to _20260209
- # and code_execution to _20260120 (per PR 5679 dispatch).
+ # claude-opus-4-7 routes web_search/web_fetch to _20260209 and
+ # code_execution to _20260120 (per PR 5679 dispatch).
assert "web_search_20260209" in tool_types, tool_types
assert "web_fetch_20260209" in tool_types, tool_types
assert "code_execution_20260120" in tool_types, tool_types
- # Code-execution still adds its beta flag; web_fetch must not
- # have accidentally stripped it.
+ # Code-execution still adds its beta flag; web_fetch must not have
+ # stripped it.
assert "code-execution-2025-08-25" in captured["headers"].get("anthropic-beta", "")
@@ -263,8 +262,8 @@ def test_web_fetch_success_emits_tool_start_and_end(monkeypatch):
assert start["type"] == "tool_start"
assert start["tool_name"] == "web_fetch"
assert start["tool_call_id"] == "srvtoolu_wf1"
- # `_server_tool: True` marks this as a provider-side synthetic
- # tool card for the frontend's history serializer.
+ # `_server_tool: True` marks this a provider-side synthetic tool card
+ # for the frontend's history serializer.
assert start["arguments"] == {"url": "https://example.com/article", "_server_tool": True}
assert end["type"] == "tool_end"
assert end["tool_call_id"] == "srvtoolu_wf1"
@@ -345,9 +344,10 @@ def test_web_fetch_error_renders_error_code(monkeypatch):
def _finish_reasons(lines: list[str]) -> list:
- """Return non-null finish_reason fields from each chat.completion.chunk.
- Mid-stream content deltas carry ``finish_reason: None`` and are skipped
- (the refusal path emits a notice delta before the content_filter chunk)."""
+ """Non-null finish_reason fields from each chat.completion.chunk.
+ Mid-stream content deltas carry ``finish_reason: None`` and are
+ skipped (refusal emits a notice delta before the content_filter
+ chunk)."""
out: list = []
for line in lines:
if not line.startswith("data:"):
@@ -369,12 +369,12 @@ def _finish_reasons(lines: list[str]) -> list:
def test_pause_turn_does_not_emit_finish_reason_chunk(monkeypatch):
- # `pause_turn` is what Anthropic emits when a long server-tool turn
- # (typically web_search / web_fetch) pauses and will resume on the
- # next request. Treating it as finish_reason="stop" makes the
- # OpenAI-formatted client truncate the rendered assistant message.
- # The adapter must skip the chunk so the stream ends cleanly with
- # [DONE] and no terminal finish_reason.
+ # Anthropic emits `pause_turn` when a long server-tool turn
+ # (typically web_search / web_fetch) pauses and resumes on the next
+ # request. Mapping it to finish_reason="stop" makes the
+ # OpenAI-formatted client truncate the assistant message. The adapter
+ # must skip the chunk so the stream ends cleanly with [DONE] and no
+ # terminal finish_reason.
sse_events = [
{"type": "message_start", "message": {"usage": {}}},
{
@@ -408,15 +408,14 @@ def test_pause_turn_does_not_emit_finish_reason_chunk(monkeypatch):
)
lines = _drive(run())
- # No finish_reason chunk for pause_turn -- the only completion
- # signal is the [DONE] line.
+ # No finish_reason chunk for pause_turn -- only [DONE] signals
+ # completion.
assert _finish_reasons(lines) == [], lines
assert any(line.strip() == "data: [DONE]" for line in lines), lines
def test_end_turn_still_emits_stop_finish_reason(monkeypatch):
- # Sanity: the pause_turn -> None mapping must not regress normal
- # end_turn handling.
+ # Sanity: pause_turn -> None mapping must not regress end_turn.
sse_events = [
{"type": "message_start", "message": {"usage": {}}},
{
@@ -489,12 +488,11 @@ def test_refusal_maps_to_content_filter(monkeypatch):
def test_web_fetch_titleless_document_falls_back_to_url(monkeypatch):
- # Anthropic may omit `document.title` on pages where the HTML
- # provides nothing usable. Without a fallback the formatter would
- # emit `URL: ...\nSnippet: ...` only, and the frontend's
- # parseSourcesFromResult skips entries that lack a `Title:` line,
- # so the source pill silently disappears. Verify the formatter
- # mirrors the web_search behaviour and falls back to the URL.
+ # Anthropic may omit `document.title` when the HTML has nothing
+ # usable. Without a fallback the formatter emits `URL: ...\nSnippet:
+ # ...` only, and the frontend's parseSourcesFromResult skips entries
+ # lacking a `Title:` line, so the source pill disappears. Verify the
+ # formatter mirrors web_search and falls back to the URL.
sse_events = [
{"type": "message_start", "message": {"usage": {}}},
{
diff --git a/studio/backend/tests/test_audio_token_detection.py b/studio/backend/tests/test_audio_token_detection.py
index bf1217b231a..02d47905192 100644
--- a/studio/backend/tests/test_audio_token_detection.py
+++ b/studio/backend/tests/test_audio_token_detection.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
-"""Tests for tokenizer-based audio_type detection patterns, covering both
-Gemma 3n (<audio_soft_token>) and Gemma 4 (<|audio|>) audio-input tokens."""
+"""Tests for tokenizer-based audio_type detection, covering Gemma 3n
+(<audio_soft_token>) and Gemma 4 (<|audio|>) audio-input tokens."""
from __future__ import annotations
@@ -10,8 +10,7 @@ from utils.models.model_config import _AUDIO_TOKEN_PATTERNS, is_audio_input_type
def _classify(tokens: list[str]) -> str | None:
- """Mirror _detect_audio_from_tokenizer._check_token_patterns: first match
- in dict order wins."""
+ """Mirror _check_token_patterns: first match in dict order wins."""
for audio_type, check in _AUDIO_TOKEN_PATTERNS.items():
if check(tokens):
return audio_type
diff --git a/studio/backend/tests/test_browse_folders_route.py b/studio/backend/tests/test_browse_folders_route.py
index 19a83987d3a..3a607e6b103 100644
--- a/studio/backend/tests/test_browse_folders_route.py
+++ b/studio/backend/tests/test_browse_folders_route.py
@@ -9,8 +9,7 @@ from pathlib import Path
import pytest
from fastapi import HTTPException
-# Keep this test runnable in lightweight environments where optional logging
-# deps are not installed.
+# Keep runnable in lightweight environments lacking optional logging deps.
if "structlog" not in sys.modules:
class _DummyLogger:
diff --git a/studio/backend/tests/test_cache_case_resolution.py b/studio/backend/tests/test_cache_case_resolution.py
index 60963b4f7dc..50340bda633 100644
--- a/studio/backend/tests/test_cache_case_resolution.py
+++ b/studio/backend/tests/test_cache_case_resolution.py
@@ -111,10 +111,10 @@ def test_resolve_cached_repo_id_case_late_cache_population(tmp_path, monkeypatch
first = resolve_cached_repo_id_case("org/model")
assert first == "org/model"
- # Simulate cache being populated after first miss (e.g. another code path/download).
+ # Cache populated after first miss (e.g. another code path/download).
_mk_cache_repo(tmp_path, "Org/Model")
second = resolve_cached_repo_id_case("org/model")
- # Desired behavior: second lookup should pick up the now-existing variant.
+ # Second lookup should pick up the now-existing variant.
assert second == "Org/Model"
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 980de216db9..0274d5b4da1 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -7,8 +7,8 @@ import types
from pathlib import Path
from types import SimpleNamespace
-# Keep this test runnable in lightweight environments where optional logging
-# deps are not installed.
+# Keep this test runnable in lightweight environments without optional
+# logging deps.
if "structlog" not in sys.modules:
class _DummyLogger:
@@ -212,7 +212,7 @@ def test_list_cached_models_skips_non_suffix_repo_when_gguf_files_exist(monkeypa
def test_list_cached_gguf_includes_mixed_repo_with_gguf_and_safetensors(monkeypatch, tmp_path):
"""Mirror of the _skips_ test: the mixed repo should still surface in
- cached-gguf so the picker can show it as a GGUF download."""
+ cached-gguf so the picker shows it as a GGUF download."""
mixed = _repo(
"Org/MixedRepo",
[
@@ -241,8 +241,8 @@ def test_list_cached_gguf_includes_mixed_repo_with_gguf_and_safetensors(monkeypa
def test_list_cached_gguf_handles_none_size_on_disk(monkeypatch, tmp_path):
"""A partial/interrupted GGUF download has ``size_on_disk = None``. The
- route must treat the unknown bytes as zero instead of raising TypeError
- out of ``sum()`` and wiping the entire response."""
+ route must treat unknown bytes as zero instead of raising TypeError from
+ ``sum()`` and wiping the whole response."""
partial = _repo(
"Org/PartialDownload",
[_file("Q4_K_M.gguf", None), _file("Q6_K.gguf", 5_000)],
@@ -268,7 +268,7 @@ def test_list_cached_gguf_handles_none_size_on_disk(monkeypatch, tmp_path):
def test_list_cached_gguf_skips_malformed_repo_without_wiping_response(monkeypatch, tmp_path):
"""One repo raising during classification must not poison the response
- for every other repo in the scan."""
+ for the other repos in the scan."""
class _ExplodingRepo:
repo_id = "Org/Broken"
@@ -303,9 +303,9 @@ def test_list_cached_gguf_skips_malformed_repo_without_wiping_response(monkeypat
def test_list_cached_gguf_skips_repo_with_only_mmproj_gguf(monkeypatch, tmp_path):
- """A repo whose only ``.gguf`` artifact is an mmproj vision adapter
- must not be classified as a GGUF repo: the variant selector filters
- mmproj out and the picker would otherwise show zero variants."""
+ """A repo whose only ``.gguf`` artifact is an mmproj vision adapter must
+ not be classified as a GGUF repo: the variant selector filters mmproj
+ out and the picker would otherwise show zero variants."""
mmproj_only = _repo(
"Org/MmprojOnly",
[
@@ -327,9 +327,9 @@ def test_list_cached_gguf_skips_repo_with_only_mmproj_gguf(monkeypatch, tmp_path
def test_list_cached_models_includes_repo_with_only_mmproj_gguf(monkeypatch, tmp_path):
- """Mirror of the cached-gguf skip: a safetensors repo with an
- auxiliary mmproj vision adapter must still surface in cached-models
- so the user can load it as a normal model."""
+ """Mirror of the cached-gguf skip: a safetensors repo with an auxiliary
+ mmproj vision adapter must still surface in cached-models so the user
+ can load it as a normal model."""
mmproj_aux = _repo(
"Org/MmprojAux",
[
@@ -351,10 +351,10 @@ def test_list_cached_models_includes_repo_with_only_mmproj_gguf(monkeypatch, tmp
def test_list_cached_gguf_includes_vision_repo_with_main_gguf_and_mmproj(monkeypatch, tmp_path):
- """A vision-capable GGUF repo (main weight + mmproj adapter) is still
- a GGUF repo. The reported size is the main weight size; mmproj is
- excluded from the GGUF-size accounting because it is filtered out at
- classification time."""
+ """A vision-capable GGUF repo (main weight + mmproj adapter) is still a
+ GGUF repo. Reported size is the main weight size; mmproj is excluded
+ from GGUF-size accounting since it is filtered out at classification
+ time."""
vision_repo = _repo(
"Org/VisionGguf",
[
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index b79f8f8119b..92cac1a50d4 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -30,9 +30,9 @@ def _reset_studio_db(
def workspace_projects_home(tmp_path):
"""Projects root outside the platform delete denylist.
- tmp_path resolves under /private/tmp on macOS, which the workspace
- delete guard refuses by design. Linux/Windows tmp is not denied and is
- used as-is; only the denied case falls back to a home subdir.
+ tmp_path resolves under /private/tmp on macOS, which the workspace delete
+ guard refuses by design. Linux/Windows tmp is not denied and is used as-is;
+ only the denied case falls back to a home subdir.
"""
candidate = tmp_path / "Projects"
resolved = str(candidate.resolve())
@@ -367,8 +367,8 @@ def test_legacy_imports_dedups_input(tmp_path, monkeypatch):
accepted, inserted = studio_db.upsert_chat_legacy_imports(
["x", "x", "y", "x"],
)
- # accepted is the deduped non-empty input size; inserted is the rows
- # actually new in the ledger after ON CONFLICT DO NOTHING.
+ # accepted is the deduped non-empty input size; inserted is the rows newly
+ # added to the ledger after ON CONFLICT DO NOTHING.
assert accepted == 2
assert inserted == 2
assert set(studio_db.list_chat_legacy_imports()) == {"x", "y"}
diff --git a/studio/backend/tests/test_cleanup_cancelled_checkpoints.py b/studio/backend/tests/test_cleanup_cancelled_checkpoints.py
index 3bb60336eb0..138cda30d45 100644
--- a/studio/backend/tests/test_cleanup_cancelled_checkpoints.py
+++ b/studio/backend/tests/test_cleanup_cancelled_checkpoints.py
@@ -16,11 +16,11 @@ if str(_BACKEND_ROOT) not in sys.path:
@pytest.fixture
def outputs_setup(tmp_path, monkeypatch):
- """Point outputs_root() at a temp dir so cleanup is allowed to run on it.
+ """Point outputs_root() at a temp dir so cleanup may run on it.
The training module binds ``outputs_root`` at import time
- (``from utils.paths import outputs_root``), so we have to patch
- the symbol on the importer module, not on storage_roots.
+ (``from utils.paths import outputs_root``), so patch the symbol on the
+ importer module, not on storage_roots.
"""
from core.training import training as training_mod
@@ -36,8 +36,8 @@ def _mk_dir(parent: Path, name: str) -> Path:
def test_completed_checkpoints_are_preserved(outputs_setup):
- """The big regression: prior to this fix, every completed
- checkpoint-N/ was rmtree'd on Cancel, destroying resume points."""
+ """The big regression: before this fix, every completed checkpoint-N/
+ was rmtree'd on Cancel, destroying resume points."""
from core.training.training import _cleanup_cancelled_checkpoints
out = outputs_setup / "run-1"
diff --git a/studio/backend/tests/test_cpu_threads.py b/studio/backend/tests/test_cpu_threads.py
index b51d2bfb7d2..2930c9f0818 100644
--- a/studio/backend/tests/test_cpu_threads.py
+++ b/studio/backend/tests/test_cpu_threads.py
@@ -116,8 +116,8 @@ def _ast_line_of_platform_compat_import(source: str) -> int:
raise AssertionError("_platform_compat import not found")
-# AST-based ordering: configure_cpu_threads() must precede _platform_compat
-# in both run.py and main.py. Robust to formatting / line shifts.
+# AST ordering: configure_cpu_threads() must precede _platform_compat in both
+# run.py and main.py. Robust to formatting / line shifts.
@pytest.mark.parametrize("entry_point", [_RUN_PY, _MAIN_PY])
def test_cpu_thread_configuration_runs_before_backend_imports(entry_point):
source = entry_point.read_text()
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index 219d64145ff..9d80c718cbc 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -239,7 +239,7 @@ def test_consume_refresh_token_second_call_returns_none():
def test_consume_refresh_token_concurrent_only_one_succeeds(tmp_path, monkeypatch):
- """64-thread pile-up against one token; DELETE RETURNING permits one winner."""
+ """64-thread pile-up on one token; DELETE RETURNING permits one winner."""
seed_user()
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
@@ -254,7 +254,7 @@ def test_consume_refresh_token_concurrent_only_one_succeeds(tmp_path, monkeypatc
try:
return storage.consume_refresh_token(raw)
except sqlite3.OperationalError:
- # "database is locked" under heavy contention; treat as losing the race.
+ # "database is locked" under contention; treat as losing the race.
return None
with ThreadPoolExecutor(max_workers = workers) as pool:
@@ -293,9 +293,9 @@ def test_desktop_session_uses_real_admin_identity_for_api_keys():
def test_local_recipe_token_authenticates_as_admin_for_desktop_user(loaded_local_model):
- # _inject_local_providers mints an internal sk-unsloth-* API key (not a
- # forwarded JWT). The unified API-key path validates as the real admin
- # user regardless of whether the incoming session was desktop or web.
+ # _inject_local_providers mints an internal sk-unsloth-* API key (not
+ # a forwarded JWT). The unified API-key path validates as the real
+ # admin user whether the incoming session was desktop or web.
from auth.authentication import create_access_token, get_current_subject
seed_user(must_change_password = True)
@@ -318,8 +318,8 @@ def test_local_recipe_token_authenticates_as_admin_for_desktop_user(loaded_local
def test_local_recipe_token_authenticates_as_admin_for_web_user(loaded_local_model):
- # Mirror of the desktop variant: API-key issuance is identical for web
- # and desktop incoming tokens; auth via get_current_subject works the same.
+ # Mirror of the desktop variant: API-key issuance is identical for
+ # web and desktop tokens; get_current_subject works the same.
from auth.authentication import create_access_token, get_current_subject
seed_user(must_change_password = False)
diff --git a/studio/backend/tests/test_detect_mmproj_file.py b/studio/backend/tests/test_detect_mmproj_file.py
index 9487db1e5b1..64dd8ebd90e 100644
--- a/studio/backend/tests/test_detect_mmproj_file.py
+++ b/studio/backend/tests/test_detect_mmproj_file.py
@@ -46,7 +46,7 @@ def test_returns_none_when_no_mmproj(tmp_path: Path):
def test_single_matching_family_mmproj_picked(tmp_path: Path):
- """Single same-family projector: returned (historical behaviour)."""
+ """Single same-family projector is returned (historical behaviour)."""
model = _touch(tmp_path / "Qwen3.5-9B-Q4_K_M.gguf")
mmproj = _touch(tmp_path / "Qwen3.5-9B-BF16-mmproj.gguf")
assert detect_mmproj_file(str(model)) == str(mmproj.resolve())
diff --git a/studio/backend/tests/test_export_log_cursor.py b/studio/backend/tests/test_export_log_cursor.py
index 253922ce745..25f276b0f50 100644
--- a/studio/backend/tests/test_export_log_cursor.py
+++ b/studio/backend/tests/test_export_log_cursor.py
@@ -4,24 +4,21 @@
"""
Regression tests for the export log ring-buffer cursor semantics.
-Context: the live export log SSE stream has a race where the frontend
-opens the SSE connection AFTER the POST that starts the export. Any
-lines the worker subprocess emits during the gap between POST and SSE
-connect get buffered with seqs 1..k, and then the SSE default cursor
-`get_current_log_seq()` returns k -- so lines 1..k are forever
-unreachable to that client.
-
-Fix: `clear_logs()` snapshots the pre-run seq into `_run_start_seq`
-(exposed via `get_run_start_seq()`), and `routes/export.py` defaults
-the SSE cursor to that snapshot instead of the current seq. Every line
-appended during the current run has seq strictly greater than the
-snapshot, so the client sees the full run regardless of when it
-connects.
-
-These tests exercise the orchestrator-side contract only (no
-subprocess, no FastAPI, no frontend). The routes-level integration
-with get_run_start_seq() is a one-line edit covered by manual testing
-and the frontend build.
+Context: the live export log SSE stream has a race where the frontend opens
+the SSE connection AFTER the POST that starts the export. Lines the worker
+emits in the gap between POST and SSE connect get buffered with seqs 1..k,
+and the SSE default cursor `get_current_log_seq()` returns k -- so lines
+1..k are forever unreachable to that client.
+
+Fix: `clear_logs()` snapshots the pre-run seq into `_run_start_seq` (exposed
+via `get_run_start_seq()`), and `routes/export.py` defaults the SSE cursor
+to that snapshot instead of the current seq. Every line appended during the
+run has seq strictly greater than the snapshot, so the client sees the full
+run regardless of when it connects.
+
+These tests exercise the orchestrator-side contract only (no subprocess,
+FastAPI, or frontend). The routes-level integration with get_run_start_seq()
+is a one-line edit covered by manual testing and the frontend build.
"""
from __future__ import annotations
@@ -39,21 +36,17 @@ _BACKEND_DIR = Path(__file__).resolve().parent.parent
if str(_BACKEND_DIR) not in sys.path:
sys.path.insert(0, str(_BACKEND_DIR))
-# ExportOrchestrator imports structlog and a few heavy modules at the
-# top of orchestrator.py. Stub the ones we don't need in these unit
-# tests so the import succeeds on machines without the full studio
-# venv.
+# orchestrator.py imports structlog and a few heavy modules at the top. Stub
+# the ones we don't need so the import succeeds without the full studio venv.
_loggers_stub = types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
-# structlog is only used for a module-level import; a bare stub is
-# enough because we never call into it in these tests.
+# structlog is only a module-level import here; a bare stub suffices.
sys.modules.setdefault("structlog", types.ModuleType("structlog"))
-# utils.paths.outputs_root is only called inside scan_checkpoints which
-# we don't hit in these tests. Provide a stub module so the top-level
-# import in orchestrator.py resolves.
+# utils.paths.outputs_root is only called inside scan_checkpoints, which we
+# don't hit; stub it so orchestrator.py's top-level import resolves.
_utils_pkg = types.ModuleType("utils")
_utils_pkg.__path__ = [] # mark as package
_utils_paths_stub = types.ModuleType("utils.paths")
@@ -84,14 +77,14 @@ def _append(
def test_run_start_seq_is_zero_before_any_logs(orchestrator) -> None:
- """A brand-new orchestrator must report run_start_seq == 0 so a
- first SSE connection picks up every line from seq 1 onward."""
+ """New orchestrator must report run_start_seq == 0 so a first SSE
+ connection picks up every line from seq 1 onward."""
assert orchestrator.get_run_start_seq() == 0
def test_clear_logs_snapshots_current_seq(orchestrator) -> None:
- """clear_logs() must capture _log_seq BEFORE clearing the buffer,
- so subsequent runs can anchor their SSE cursor at the snapshot."""
+ """clear_logs() must capture _log_seq BEFORE clearing the buffer, so
+ subsequent runs can anchor their SSE cursor at the snapshot."""
_append(orchestrator, "old run line 1")
_append(orchestrator, "old run line 2")
_append(orchestrator, "old run line 3")
@@ -109,13 +102,12 @@ def test_clear_logs_snapshots_current_seq(orchestrator) -> None:
def test_sse_default_cursor_catches_all_current_run_lines(orchestrator) -> None:
- """Simulate the POST-then-SSE race: worker starts emitting lines
- immediately after clear_logs(), SSE connects several lines later.
- Using get_run_start_seq() as the default cursor MUST return every
- line emitted since clear_logs() ran.
+ """Simulate the POST-then-SSE race: worker emits lines right after
+ clear_logs(), SSE connects several lines later. get_run_start_seq() as
+ the default cursor MUST return every line emitted since clear_logs().
- Pre-fix, the SSE defaulted to get_current_log_seq() at connect
- time, which would return the last-seen seq and miss lines N+1..M.
+ Pre-fix, the SSE defaulted to get_current_log_seq() at connect time,
+ returning the last-seen seq and missing lines N+1..M.
"""
# Previous run leaves some buffered lines.
_append(orchestrator, "previous run line A")
@@ -130,8 +122,7 @@ def test_sse_default_cursor_catches_all_current_run_lines(orchestrator) -> None:
_append(orchestrator, "Loading checkpoint: /foo/bar")
_append(orchestrator, "Starting export...")
- # SSE connects now and asks "give me everything after the run
- # start cursor".
+ # SSE connects and asks for everything after the run start cursor.
entries, new_cursor = orchestrator.get_logs_since(run_start)
# All three early lines must be present. Pre-fix this was [].
@@ -145,9 +136,9 @@ def test_sse_default_cursor_catches_all_current_run_lines(orchestrator) -> None:
def test_sse_default_cursor_excludes_previous_run(orchestrator) -> None:
- """After clear_logs(), lines from the PREVIOUS run must not leak
- into the new run's SSE stream. Pre-fix this worked correctly
- (clear_logs cleared the deque); the fix must preserve it.
+ """After clear_logs(), PREVIOUS-run lines must not leak into the new
+ run's SSE stream. Pre-fix this worked (clear_logs cleared the deque);
+ the fix must preserve it.
"""
_append(orchestrator, "previous run line 1")
_append(orchestrator, "previous run line 2")
@@ -164,10 +155,9 @@ def test_sse_default_cursor_excludes_previous_run(orchestrator) -> None:
def test_clear_logs_twice_advances_run_start(orchestrator) -> None:
- """Back-to-back clear_logs() calls (e.g. cleanup -> load ->
- export in the same dialog session) must each re-anchor run_start
- at the current seq, so successive runs each start with a fresh
- low-water mark."""
+ """Back-to-back clear_logs() calls (e.g. cleanup -> load -> export in one
+ dialog session) must each re-anchor run_start at the current seq, so
+ successive runs each start with a fresh low-water mark."""
_append(orchestrator, "run 1 line a")
_append(orchestrator, "run 1 line b")
diff --git a/studio/backend/tests/test_external_provider_usage_chunk.py b/studio/backend/tests/test_external_provider_usage_chunk.py
index afeb26e9e9e..f462e1c8e97 100644
--- a/studio/backend/tests/test_external_provider_usage_chunk.py
+++ b/studio/backend/tests/test_external_provider_usage_chunk.py
@@ -2,14 +2,14 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Unit tests for the prompt-cache accounting chunk emitted by the external-
-provider streaming proxy.
+Unit tests for the prompt-cache accounting chunk emitted by the
+external-provider streaming proxy.
-The streaming Anthropic + OpenAI Responses paths now emit one extra
+The streaming Anthropic + OpenAI Responses paths emit one extra
``include_usage``-style SSE chunk (``choices: []`` with a populated
``usage`` block) just before ``[DONE]`` / after the final
-``finish_reason`` chunk. This lets clients surface cache savings
-without scraping the structlog stream.
+``finish_reason`` chunk, so clients see cache savings without scraping
+the structlog stream.
Covers:
- Helper alone: shape for Anthropic / OpenAI usage payloads, missing
@@ -20,8 +20,8 @@ Covers:
- OpenAI Responses stream: ``response.completed.usage`` with
``input_tokens_details.cached_tokens`` produces the expected usage
chunk after the ``stop`` finish_reason chunk.
-- OpenAI Responses ``response.incomplete`` also emits the usage chunk
- so length-truncated turns still report cached tokens.
+- OpenAI Responses ``response.incomplete`` also emits the chunk so
+ length-truncated turns still report cached tokens.
"""
import asyncio
@@ -57,9 +57,9 @@ def test_build_usage_chunk_anthropic_shape():
assert payload["object"] == "chat.completion.chunk"
assert payload["choices"] == []
usage = payload["usage"]
- # Anthropic's input_tokens excludes cache buckets; prompt_tokens
- # must add all three input components together so downstream
- # context / cost displays see the real prompt size.
+ # Anthropic's input_tokens excludes cache buckets; prompt_tokens must
+ # sum all three input components so downstream context/cost displays
+ # see the real prompt size.
assert usage["prompt_tokens"] == 8 + 1367 + 18901
assert usage["completion_tokens"] == 862
assert usage["total_tokens"] == 8 + 1367 + 18901 + 862
@@ -92,9 +92,8 @@ def test_build_usage_chunk_openai_shape():
def test_build_usage_chunk_missing_fields_default_to_zero():
- # OpenAI Responses can return a usage object without
- # input_tokens_details when prompt caching is unused; the helper
- # should still emit a chunk with cached_tokens=0.
+ # OpenAI Responses can omit input_tokens_details when prompt caching is
+ # unused; the helper should still emit a chunk with cached_tokens=0.
line = _build_usage_chunk(
"chatcmpl-z",
"openai",
@@ -107,7 +106,7 @@ def test_build_usage_chunk_missing_fields_default_to_zero():
def test_build_usage_chunk_returns_none_when_all_zero():
# If upstream errored before any usage event, suppress the chunk to
- # avoid surfacing a misleading "0 tokens" line.
+ # avoid a misleading "0 tokens" line.
assert _build_usage_chunk("id", "anthropic", {}) is None
assert _build_usage_chunk("id", "anthropic", None) is None
assert _build_usage_chunk("id", "openai", {}) is None
diff --git a/studio/backend/tests/test_frontend_resolution.py b/studio/backend/tests/test_frontend_resolution.py
index 3cdc755f7f6..7224ee7a04e 100644
--- a/studio/backend/tests/test_frontend_resolution.py
+++ b/studio/backend/tests/test_frontend_resolution.py
@@ -3,9 +3,8 @@
"""Tests for the frontend-dist resolver in studio/backend/run.py.
-Loads only the relevant helpers via importlib so the test does not pull in
-uvicorn / FastAPI / unsloth's full dependency tree. Pairs with the AST-style
-test_host_defaults.py.
+Loads only the relevant helpers via importlib to avoid pulling in
+uvicorn / FastAPI / unsloth's deps. Pairs with AST-style test_host_defaults.py.
"""
import ast
@@ -19,7 +18,7 @@ _REPO_STUDIO_DIR = _RUN_PY.parent.parent # studio/
def _load_helpers_only():
- """Import just the resolver helpers from run.py without executing the
+ """Import just the resolver helpers from run.py, skipping the
server-side imports (uvicorn, structlog, etc.)."""
source = _RUN_PY.read_text(encoding = "utf-8")
tree = ast.parse(source)
@@ -91,7 +90,7 @@ def test_resolver_falls_back_to_studio_home_site_packages(tmp_path, monkeypatch)
def test_resolver_falls_back_via_editable_pth(tmp_path, monkeypatch):
"""Simulates a `--local` install: dedicated venv with an editable .pth
- pointing at a cloned repo that owns the built dist."""
+ pointing at a cloned repo owning the built dist."""
studio_home = tmp_path / "studio_home"
sp = studio_home / "unsloth_studio" / "lib" / "python3.13" / "site-packages"
sp.mkdir(parents = True)
@@ -100,7 +99,7 @@ def test_resolver_falls_back_via_editable_pth(tmp_path, monkeypatch):
repo_dist = repo_studio / "frontend" / "dist"
repo_dist.mkdir(parents = True)
(repo_dist / "index.html").write_text("<!doctype html>", encoding = "utf-8")
- # Minimal `__editable___pkg_finder.py` carrying a MAPPING dict that
+ # Minimal `__editable___pkg_finder.py` with the MAPPING dict that
# setuptools' editable install generator writes.
finder = sp / "__editable___unsloth_0_0_0_finder.py"
finder.write_text(
@@ -127,7 +126,7 @@ def test_iter_candidates_handles_missing_studio_home(tmp_path, monkeypatch):
def test_resolver_falls_back_to_windows_layout_site_packages(tmp_path, monkeypatch):
"""Pins the `Lib/site-packages` (capital L) Windows venv layout
- alongside the POSIX `lib/python*/site-packages` path."""
+ alongside the POSIX `lib/python*/site-packages`."""
studio_home = tmp_path / "studio_home"
sp_dist = (
studio_home / "unsloth_studio" / "Lib" / "site-packages" / "studio" / "frontend" / "dist"
@@ -143,20 +142,19 @@ def test_resolver_falls_back_to_windows_layout_site_packages(tmp_path, monkeypat
def test_resolver_does_not_crash_on_non_dict_mapping_literal(tmp_path, monkeypatch):
- """A finder file whose MAPPING value is a set / list / non-dict literal
- (theoretically possible if the regex matched a brace-delimited literal
- that ast.literal_eval can parse) must not AttributeError. The resolver
- should skip that finder and keep probing."""
+ """A finder whose MAPPING value is a set/list/non-dict literal (possible
+ if the regex matched a brace-delimited literal ast.literal_eval can parse)
+ must not AttributeError. The resolver should skip it and keep probing."""
studio_home = tmp_path / "studio_home"
sp = studio_home / "unsloth_studio" / "lib" / "python3.13" / "site-packages"
sp.mkdir(parents = True)
- # Bad finder: set literal, not a dict. ast.literal_eval parses it as set;
- # any .get() call on it would raise AttributeError.
+ # Bad finder: set literal, not a dict. literal_eval parses it as a set,
+ # so any .get() call on it would raise AttributeError.
(sp / "__editable___bad_0_0_0_finder.py").write_text(
"MAPPING: dict[str, str] = {'studio', 'unsloth', 'unsloth_cli'}\n",
encoding = "utf-8",
)
- # Good finder that should still be discovered after the bad one is skipped.
+ # Good finder, still discovered after the bad one is skipped.
repo_root = tmp_path / "clone"
repo_dist = repo_root / "studio" / "frontend" / "dist"
repo_dist.mkdir(parents = True)
@@ -174,9 +172,8 @@ def test_resolver_does_not_crash_on_non_dict_mapping_literal(tmp_path, monkeypat
def test_resolver_handles_multiline_mapping_dict(tmp_path, monkeypatch):
- """A future setuptools / black reformat that wraps the MAPPING dict
- across multiple lines must still parse and resolve. Locks in the
- `[^}]*` + re.DOTALL behaviour."""
+ """A future setuptools/black reformat wrapping the MAPPING dict across
+ multiple lines must still parse and resolve. Locks in `[^}]*` + re.DOTALL."""
studio_home = tmp_path / "studio_home"
sp = studio_home / "unsloth_studio" / "lib" / "python3.13" / "site-packages"
sp.mkdir(parents = True)
@@ -204,8 +201,8 @@ def test_resolver_handles_multiline_mapping_dict(tmp_path, monkeypatch):
def test_systemexit_message_contains_actionable_fixes(tmp_path, monkeypatch):
"""The user-facing recovery message is a contract: it must surface the
- attempted paths and every concrete fix. Pin its structure so a future
- refactor doesn't drop one."""
+ attempted paths and every concrete fix. Pin its structure so a refactor
+ doesn't drop one."""
import os
import sys
diff --git a/studio/backend/tests/test_gemini_provider.py b/studio/backend/tests/test_gemini_provider.py
index 01ef2e16fd9..85ceb04d278 100644
--- a/studio/backend/tests/test_gemini_provider.py
+++ b/studio/backend/tests/test_gemini_provider.py
@@ -24,9 +24,9 @@ Gemini does NOT speak OpenAI Chat Completions on its primary endpoint
(delta.content for text, delta.tool_calls for functionCall,
_toolEvent for image_b64/web_search, usage block before [DONE])
-These tests pin the outbound body shape AND the inbound translation
-using httpx.MockTransport (no live network). Mirrors the structure of
-test_anthropic_cache_ttl.py and test_openai_image_generation.py.
+These tests pin the outbound body shape AND the inbound translation via
+httpx.MockTransport (no live network). Mirrors test_anthropic_cache_ttl.py
+and test_openai_image_generation.py.
"""
import asyncio
@@ -44,10 +44,9 @@ _active_mock_clients: list[httpx.AsyncClient] = []
def _drive(coro):
- # Create a fresh loop per drive so tests don't share asyncio state.
- # Close mocked clients + shutdown async-generators inside this loop
- # so Python 3.13 doesn't emit the
- # `Response.aiter_*.aclose was never awaited` warning on GC.
+ # Fresh loop per drive so tests don't share asyncio state. Close mocked
+ # clients + shutdown async-generators inside this loop so Python 3.13
+ # doesn't emit `Response.aiter_*.aclose was never awaited` on GC.
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(coro)
@@ -75,8 +74,8 @@ def _make_gemini_client(
def _mock_http(monkeypatch, handler):
mock_client = httpx.AsyncClient(transport = httpx.MockTransport(handler))
monkeypatch.setattr(ep_mod, "_http_client", mock_client)
- # `_drive` will aclose this at the end of the run inside the same
- # event loop so we do not leak an unawaited aclose() coroutine.
+ # `_drive` acloses this at end of run inside the same event loop, so we
+ # don't leak an unawaited aclose() coroutine.
_active_mock_clients.append(mock_client)
@@ -98,7 +97,7 @@ def _capture_body(monkeypatch, **kwargs) -> dict:
captured["headers"] = dict(request.headers)
captured["url"] = str(request.url)
captured["method"] = request.method
- # Minimal valid Gemini stream so the helper can complete.
+ # Minimal valid Gemini stream so the helper completes.
return httpx.Response(
200,
content = _gemini_sse(
@@ -262,7 +261,7 @@ def test_presence_penalty_forwarded_to_generation_config(monkeypatch):
captured = _capture_body(monkeypatch, presence_penalty = 0.7)
assert captured["body"]["generationConfig"]["presencePenalty"] == 0.7
- # And the default of zero is omitted, matching top_k semantics.
+ # Default zero is omitted, matching top_k semantics.
captured = _capture_body(monkeypatch, presence_penalty = 0.0)
assert "presencePenalty" not in captured["body"]["generationConfig"]
@@ -282,7 +281,7 @@ def test_gemini25_flash_thinking_disabled_sets_budget_zero(monkeypatch):
def test_gemini3_flash_thinking_disabled_uses_minimal_level(monkeypatch):
- """Gemini 3 Flash migrated to thinkingLevel; "off" maps to minimal
+ """Gemini 3 Flash uses thinkingLevel; "off" maps to minimal
(Gemini 3 cannot turn thinking fully off)."""
captured = _capture_body(
monkeypatch,
@@ -306,8 +305,8 @@ def test_gemini25_pro_thinking_disabled_uses_small_budget(monkeypatch):
def test_gemini3_pro_thinking_disabled_uses_low_level(monkeypatch):
- """Gemini 3 Pro uses thinkingLevel and rejects 'minimal' (Pro tier),
- so 'off' coerces to 'low' (lowest the API accepts)."""
+ """Gemini 3 Pro uses thinkingLevel and rejects 'minimal' (Pro tier), so
+ 'off' coerces to 'low' (lowest the API accepts)."""
for model in (
"gemini-3.1-pro-preview",
"gemini-3-pro-preview",
@@ -402,16 +401,16 @@ def test_gemini3_flash_effort_none_maps_to_minimal(monkeypatch):
def test_thinking_default_omits_thinking_config(monkeypatch):
- """When neither knob is supplied, thinkingConfig is omitted entirely
- (Google's server-side default applies)."""
+ """When neither knob is supplied, thinkingConfig is omitted (Google's
+ server-side default applies)."""
captured = _capture_body(monkeypatch, model = "gemini-3.5-flash")
gc = captured["body"]["generationConfig"]
assert "thinkingConfig" not in gc, gc
def test_nano_banana_alias_routes_through_image_modalities(monkeypatch):
- """`nano-banana-pro-preview` is an alias for the Pro image model and
- must set responseModalities=[TEXT,IMAGE] when the Images pill is on
+ """`nano-banana-pro-preview` aliases the Pro image model; must set
+ responseModalities=[TEXT,IMAGE] when the Images pill is on
(enabled_tools includes "image_generation")."""
captured = _capture_body(
monkeypatch,
@@ -423,12 +422,11 @@ def test_nano_banana_alias_routes_through_image_modalities(monkeypatch):
def test_image_capable_model_without_image_pill_stays_text_only(monkeypatch):
- """When the Images pill is off (enabled_tools has no
- image_generation), an image-capable model id (gemini-2.5-flash-image)
- must force responseModalities=["TEXT"]. Google's image models
- default to text+image when responseModalities is omitted, so
- omitting it would silently bill image output the UI says is
- disabled."""
+ """When the Images pill is off (no image_generation in enabled_tools), an
+ image-capable model id (gemini-2.5-flash-image) must force
+ responseModalities=["TEXT"]. Google's image models default to text+image
+ when responseModalities is omitted, so omitting it would silently bill
+ image output the UI says is disabled."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash-image",
@@ -439,9 +437,9 @@ def test_image_capable_model_without_image_pill_stays_text_only(monkeypatch):
def test_image_models_skip_thinking_config(monkeypatch):
- """Image-tier ids do not benefit from a visible thinking knob and
- must NOT forward thinkingConfig even when stale UI state still
- sends `reasoning_effort` or `enable_thinking=False`."""
+ """Image-tier ids have no visible thinking knob and must NOT forward
+ thinkingConfig even when stale UI state still sends `reasoning_effort` or
+ `enable_thinking=False`."""
for model in (
"gemini-2.5-flash-image",
"gemini-3.1-flash-image-preview",
@@ -462,8 +460,8 @@ def test_image_models_skip_thinking_config(monkeypatch):
def test_image_models_drop_code_execution(monkeypatch):
"""All image-tier ids reject `tools: [{codeExecution: {}}]`; drop
silently. (Gemini 3 image models DO accept googleSearch -- see
- test_gemini3_image_models_allow_google_search; older image models
- drop everything.)"""
+ test_gemini3_image_models_allow_google_search; older ones drop
+ everything.)"""
for model in (
"gemini-2.5-flash-image",
"gemini-3.1-flash-image-preview",
@@ -481,9 +479,8 @@ def test_image_models_drop_code_execution(monkeypatch):
def test_gemini_35_pro_uses_thinking_level(monkeypatch):
- """`gemini-3.5-pro` is part of the Gemini 3 family and uses
- thinkingLevel (not thinkingBudget). "Off" maps to "low" because Pro
- tier rejects "minimal"."""
+ """`gemini-3.5-pro` is Gemini 3 family and uses thinkingLevel (not
+ thinkingBudget). "Off" maps to "low" since Pro tier rejects "minimal"."""
captured = _capture_body(
monkeypatch,
model = "gemini-3.5-pro",
@@ -525,9 +522,9 @@ def test_legacy_image_models_block_google_search(monkeypatch):
def test_legacy_openai_base_url_normalized(monkeypatch):
- """Saved Gemini providers carrying the legacy `/v1beta/openai` base
- (from the pre-PR OpenAI-compat plumbing) now point at the native
- endpoint without the user re-saving the connection."""
+ """Saved Gemini providers with the legacy `/v1beta/openai` base (from
+ pre-PR OpenAI-compat plumbing) now point at the native endpoint without
+ the user re-saving the connection."""
client = ExternalProviderClient(
provider_type = "gemini",
base_url = "https://generativelanguage.googleapis.com/v1beta/openai",
@@ -538,7 +535,7 @@ def test_legacy_openai_base_url_normalized(monkeypatch):
def test_finish_reason_swaps_to_tool_calls_when_function_call_emitted(monkeypatch):
"""Gemini emits finishReason="STOP" even for pure functionCall turns;
- surface as `tool_calls` so OAI clients trigger tool execution."""
+ surface as `tool_calls` so OAI clients run the tool."""
sse = [
{
"candidates": [
@@ -563,7 +560,7 @@ def test_finish_reason_swaps_to_tool_calls_when_function_call_emitted(monkeypatc
def test_thought_signature_round_trips_into_gemini_function_call(monkeypatch):
"""An assistant tool_call carrying `extra_content.google.thought_signature`
- must echo the value back as a sibling of the Gemini functionCall part."""
+ must echo it back as a sibling of the Gemini functionCall part."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -600,8 +597,8 @@ def test_thought_signature_round_trips_into_gemini_function_call(monkeypatch):
def test_thought_signature_emitted_in_tool_call_delta(monkeypatch):
- """A Gemini functionCall part with `thoughtSignature` must surface
- that signature on the outbound OpenAI tool_calls delta via
+ """A Gemini functionCall part with `thoughtSignature` must surface it on
+ the outbound OpenAI tool_calls delta via
`extra_content.google.thought_signature`."""
sse = [
{
@@ -637,10 +634,10 @@ def test_thought_signature_emitted_in_tool_call_delta(monkeypatch):
def test_image_models_suppress_phantom_web_search_card(monkeypatch):
- """When the image guard filters googleSearch out of the outbound
- request, the inbound stream must NOT emit web_search tool_start /
- tool_end (otherwise the UI shows a misleading 'Search complete'
- card on a turn where Gemini never actually searched)."""
+ """When the image guard filters googleSearch out of the request, the
+ inbound stream must NOT emit web_search tool_start / tool_end (else the UI
+ shows a misleading 'Search complete' card on a turn Gemini never
+ searched)."""
sse = [
{
"candidates": [
@@ -669,10 +666,10 @@ def test_image_models_suppress_phantom_web_search_card(monkeypatch):
def test_image_generation_tool_on_image_model_drops_text_tools(monkeypatch):
"""`enabled_tools=["image_generation", "web_search", "code_execution"]`
- on a Gemini IMAGE model flips responseModalities to TEXT+IMAGE; in
- that mode codeExecution must NOT be forwarded (Gemini rejects text
- code tools alongside image responseModalities). Older image
- families also drop googleSearch."""
+ on a Gemini IMAGE model flips responseModalities to TEXT+IMAGE; in that
+ mode codeExecution must NOT be forwarded (Gemini rejects text code tools
+ alongside image responseModalities). Older image families also drop
+ googleSearch."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash-image",
@@ -687,8 +684,8 @@ def test_image_generation_tool_on_image_model_drops_text_tools(monkeypatch):
def test_prompt_feedback_block_reason_surfaces_as_error(monkeypatch):
- """`promptFeedback.blockReason` with zero candidates must produce
- an error chunk, not a silent empty assistant reply."""
+ """`promptFeedback.blockReason` with zero candidates must produce an error
+ chunk, not a silent empty assistant reply."""
sse = [
{
"promptFeedback": {"blockReason": "SAFETY"},
@@ -701,10 +698,10 @@ def test_prompt_feedback_block_reason_surfaces_as_error(monkeypatch):
def test_usage_chunk_includes_thoughts_tokens(monkeypatch):
- """`thoughtsTokenCount` is the hidden-reasoning slice of output;
- roll it into `output_tokens` AND surface it on
- `output_tokens_details.reasoning_tokens` so total_tokens reflects
- the full billable spend."""
+ """`thoughtsTokenCount` is the hidden-reasoning slice of output; roll it
+ into `output_tokens` AND surface it on
+ `output_tokens_details.reasoning_tokens` so total_tokens reflects the full
+ billable spend."""
sse = [
{
"candidates": [
@@ -918,16 +915,16 @@ def test_tool_message_translates_to_function_response_part(monkeypatch):
]
captured = _capture_body(monkeypatch, messages = messages)
contents = captured["body"]["contents"]
- # Last turn must be a functionResponse part (Gemini wraps it as a
- # role=user turn carrying the result).
+ # Last turn must be a functionResponse part (Gemini wraps it as a role=user
+ # turn carrying the result).
last = contents[-1]
assert last["role"] == "user", last
fr = last["parts"][0].get("functionResponse")
assert fr is not None, last
assert fr["name"] == "get_weather"
assert fr["response"] == {"temp_c": 18, "summary": "Sunny"}
- # And the assistant turn carries the original functionCall so the
- # model sees the round-trip context.
+ # And the assistant turn carries the original functionCall so the model
+ # sees the round-trip context.
assistant_turn = [c for c in contents if c["role"] == "model"][0]
fc_part = next(
(p for p in assistant_turn["parts"] if "functionCall" in p),
@@ -940,8 +937,8 @@ def test_tool_message_translates_to_function_response_part(monkeypatch):
def test_parallel_function_calls_get_distinct_tool_call_indices(monkeypatch):
"""Each emitted functionCall in one assistant turn needs its own
- tool_calls[*].index. Hardcoding index=0 collapses parallel calls
- onto a single slot in OpenAI-style reassemblers."""
+ tool_calls[*].index. Hardcoding index=0 collapses parallel calls onto one
+ slot in OpenAI-style reassemblers."""
sse = [
{
"candidates": [
@@ -1117,8 +1114,8 @@ def test_code_execution_parts_translate_to_code_execution_tool_events(monkeypatc
assert code_starts[0]["arguments"]["code"] == "print(2+2)"
assert code_starts[0]["arguments"]["language"] == "python"
assert len(code_ends) == 1, tool_events
- # tool_start and tool_end must share the same tool_call_id so the
- # frontend pairs them onto a single CodeExecutionToolUI block.
+ # tool_start and tool_end must share a tool_call_id so the frontend pairs
+ # them onto one CodeExecutionToolUI block.
assert code_starts[0]["tool_call_id"] == code_ends[0]["tool_call_id"]
@@ -1360,8 +1357,8 @@ def test_grounding_metadata_surfaces_as_tool_end_citations(monkeypatch):
def test_custom_gemini_proxy_base_url_not_rewritten():
- """Only the Google-hosted /v1beta/openai base is normalized; a
- custom gateway whose path ends in /openai must be left alone."""
+ """Only the Google-hosted /v1beta/openai base is normalized; a custom
+ gateway whose path ends in /openai must be left alone."""
client = ExternalProviderClient(
provider_type = "gemini",
base_url = "https://proxy.example.com/team/openai",
@@ -1371,10 +1368,9 @@ def test_custom_gemini_proxy_base_url_not_rewritten():
def test_custom_gemini_proxy_uses_openai_dispatch():
- """Any non-Google Gemini base (LiteLLM, custom OpenAI-compat
- routers) must route through the OpenAI-compatible forwarder, not
- the native translator. Auth uses Authorization: Bearer ..., not
- x-goog-api-key."""
+ """Any non-Google Gemini base (LiteLLM, custom OpenAI-compat routers) must
+ route through the OpenAI-compatible forwarder, not the native translator.
+ Auth uses Authorization: Bearer ..., not x-goog-api-key."""
for base in (
"https://proxy.example.com/team/openai",
"https://proxy.example.com/v1",
@@ -1405,8 +1401,8 @@ def test_google_hosted_gemini_still_uses_native_dispatch():
def test_invalid_gemini_model_id_rejected_before_request(monkeypatch):
"""Path-traversal model ids must be rejected before the URL is
- interpolated so the configured API key isn't sent to unintended
- Gemini endpoints."""
+ interpolated, so the configured API key isn't sent to unintended Gemini
+ endpoints."""
captured: list[httpx.Request] = []
@@ -1442,17 +1438,16 @@ def test_invalid_gemini_model_id_rejected_before_request(monkeypatch):
def test_top_k_omitted_when_not_explicit_default_for_gemini(monkeypatch):
- """top_k=None means "use provider default"; helper must not emit
- `topK` in generationConfig when the caller didn't pass it."""
+ """top_k=None means "use provider default"; helper must not emit `topK` in
+ generationConfig when the caller didn't pass it."""
captured = _capture_body(monkeypatch, top_k = None)
assert "topK" not in captured["body"]["generationConfig"], captured["body"]
def test_text_model_image_generation_tool_silently_dropped(monkeypatch):
- """A stale `enabled_tools=["image_generation"]` on a text-only
- Gemini model (e.g. gemini-2.5-flash) must NOT switch the request
- into image mode -- Google's API 400s on responseModalities for
- text models."""
+ """A stale `enabled_tools=["image_generation"]` on a text-only Gemini
+ model (e.g. gemini-2.5-flash) must NOT switch the request into image mode
+ -- Google's API 400s on responseModalities for text models."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash",
@@ -1464,8 +1459,8 @@ def test_text_model_image_generation_tool_silently_dropped(monkeypatch):
def test_empty_text_part_with_thought_signature_emits_extra_content(monkeypatch):
"""Gemini 3 can ship a content-free fragment whose only payload is
- `thoughtSignature`. The translator must still surface that signature
- on a delta.extra_content envelope so the next turn can replay it."""
+ `thoughtSignature`. The translator must still surface it on a
+ delta.extra_content envelope so the next turn can replay it."""
sse = [
{
"candidates": [
@@ -1499,9 +1494,9 @@ def test_empty_text_part_with_thought_signature_emits_extra_content(monkeypatch)
def test_enable_prompt_caching_false_string_coerces_to_bool():
- """Pre-PR the field was Optional[bool]; widening to Union[bool,str]
- must preserve historical coercion so callers sending `"false"`
- still opt out of caching."""
+ """Pre-PR the field was Optional[bool]; widening to Union[bool,str] must
+ preserve historical coercion so callers sending `"false"` still opt out of
+ caching."""
from models.inference import ChatCompletionRequest
msg = {"role": "user", "content": "hi"}
@@ -1545,10 +1540,9 @@ def test_legacy_google_openai_base_url_is_rewritten():
def test_remote_image_url_downloads_and_inlines_as_base64(monkeypatch):
- """Round 14: arbitrary public HTTPS image URLs cannot be sent as
- Gemini fileData (that path is reserved for Files API URIs and
- YouTube). The translator must fetch the bytes server-side and
- inline them as base64 inlineData."""
+ """Round 14: arbitrary public HTTPS image URLs cannot be sent as Gemini
+ fileData (reserved for Files API URIs and YouTube). The translator must
+ fetch the bytes server-side and inline them as base64 inlineData."""
image_bytes = b"FAKEPNGBYTES"
async def fake_fetch(
@@ -1586,10 +1580,9 @@ def test_remote_image_url_downloads_and_inlines_as_base64(monkeypatch):
def test_remote_image_url_dropped_when_fetch_returns_none(monkeypatch):
- """Round 15: if the SSRF guard rejects the URL (private host,
- non-https, oversize, non-image), the helper returns None and the
- image part is silently dropped instead of forwarding raw bytes
- or a fileData fallback."""
+ """Round 15: if the SSRF guard rejects the URL (private host, non-https,
+ oversize, non-image), the helper returns None and the image part is
+ silently dropped, not forwarded as raw bytes or a fileData fallback."""
async def fake_fetch_reject(
url,
@@ -1628,8 +1621,8 @@ def test_safe_fetch_image_rejects_non_https():
def test_safe_fetch_image_rejects_loopback_ip_literal():
- """SSRF guard: refuse loopback / private IP literals before any
- network call."""
+ """SSRF guard: refuse loopback / private IP literals before any network
+ call."""
for url in (
"https://127.0.0.1/x.png",
"https://[::1]/x.png",
@@ -1658,9 +1651,9 @@ def test_safe_fetch_image_rejects_resolved_private_host(monkeypatch):
def test_youtube_and_files_api_uris_stay_as_file_data(monkeypatch):
- """Round 14: YouTube URLs and generativelanguage.googleapis.com
- Files API URIs are the documented `fileData.fileUri` paths and
- must NOT be downloaded; arbitrary public URLs do get fetched."""
+ """Round 14: YouTube URLs and generativelanguage.googleapis.com Files API
+ URIs are the documented `fileData.fileUri` paths and must NOT be
+ downloaded; arbitrary public URLs do get fetched."""
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
@@ -1730,8 +1723,8 @@ def test_youtube_and_files_api_uris_stay_as_file_data(monkeypatch):
def test_tool_use_prompt_tokens_added_to_input_tokens(monkeypatch):
- """`toolUsePromptTokenCount` must roll into the OpenAI prompt
- total -- otherwise tool turns silently undercount input tokens."""
+ """`toolUsePromptTokenCount` must roll into the OpenAI prompt total --
+ else tool turns silently undercount input tokens."""
sse = [
{
"candidates": [
@@ -1763,8 +1756,9 @@ def test_tool_use_prompt_tokens_added_to_input_tokens(monkeypatch):
def test_usage_chunk_reasoning_tokens_surfaced(monkeypatch):
- """thoughtsTokenCount must surface as completion_tokens_details.
- reasoning_tokens in the emitted OpenAI usage chunk."""
+ """thoughtsTokenCount must surface as
+ completion_tokens_details.reasoning_tokens in the emitted OpenAI usage
+ chunk."""
sse = [
{
"candidates": [
@@ -1794,8 +1788,8 @@ def test_usage_chunk_reasoning_tokens_surfaced(monkeypatch):
def test_prompt_block_pairs_web_search_tool_end(monkeypatch):
"""When `promptFeedback.blockReason` triggers after the synthetic
- web_search tool_start, the helper must emit a matching tool_end so
- the UI does not leave a "searching..." spinner stuck on screen."""
+ web_search tool_start, the helper must emit a matching tool_end so the UI
+ doesn't leave a "searching..." spinner stuck on screen."""
sse = [
{"promptFeedback": {"blockReason": "SAFETY"}},
]
@@ -1817,9 +1811,9 @@ def test_prompt_block_pairs_web_search_tool_end(monkeypatch):
def test_code_execution_tool_events_stow_native_part(monkeypatch):
- """executableCode / codeExecutionResult must round-trip native ids
- and thoughtSignature in google.native_part so follow-up turns can
- replay Gemini's required history shape."""
+ """executableCode / codeExecutionResult must round-trip native ids and
+ thoughtSignature in google.native_part so follow-up turns can replay
+ Gemini's required history shape."""
sse = [
{
"candidates": [
@@ -1870,7 +1864,7 @@ def test_code_execution_tool_events_stow_native_part(monkeypatch):
assert code_start is not None, starts
assert code_start["tool_call_id"] == "code_a", code_start
native = code_start["arguments"]["google"]["native_part"]
- # Round 21: native_part now uses an ordered `parts` list so per-part
+ # Round 21: native_part uses an ordered `parts` list so per-part
# `thoughtSignature` survives a frontend merge of executableCode +
# codeExecutionResult into one tool-call card.
start_parts = native["parts"]
@@ -1884,8 +1878,8 @@ def test_code_execution_tool_events_stow_native_part(monkeypatch):
def test_inline_image_tool_end_carries_thought_signature(monkeypatch):
- """Inline image parts with thoughtSignature must persist it on the
- emitted tool_end so Gemini 3 image editing can echo it back."""
+ """Inline image parts with thoughtSignature must persist it on the emitted
+ tool_end so Gemini 3 image editing can echo it back."""
sse = [
{
"candidates": [
@@ -1921,11 +1915,11 @@ def test_inline_image_tool_end_carries_thought_signature(monkeypatch):
image_ends = [e for e in tool_events if e.get("type") == "tool_end" and e.get("image_b64")]
assert image_ends, tool_events
assert image_ends[0]["google"]["thought_signature"] == "SIG-IMG"
- # Multi-turn image edit must replay the original inlineData part with
- # its thoughtSignature; the outbound translator reads
- # google.native_part.parts[].inlineData, so stow it on the tool_end
- # too. Round 21 changed native_part to an ordered parts list so a
- # per-part signature stays attached to inlineData only.
+ # Multi-turn image edit must replay the original inlineData part with its
+ # thoughtSignature; the outbound translator reads
+ # google.native_part.parts[].inlineData, so stow it on the tool_end too.
+ # Round 21 made native_part an ordered parts list so a per-part signature
+ # stays attached to inlineData only.
native = image_ends[0]["google"]["native_part"]
image_parts = native["parts"]
assert image_parts[0]["inlineData"]["mimeType"] == "image/png"
@@ -1934,10 +1928,9 @@ def test_inline_image_tool_end_carries_thought_signature(monkeypatch):
def test_code_execution_plot_attaches_inline_image_native_part(monkeypatch):
- """A code_execution turn that returns a matplotlib plot must stow
- the plot's inlineData on the secondary tool_end so the follow-up
- turn can replay the image alongside executableCode and
- codeExecutionResult."""
+ """A code_execution turn that returns a matplotlib plot must stow the
+ plot's inlineData on the secondary tool_end so the follow-up turn can
+ replay the image alongside executableCode and codeExecutionResult."""
plot_data = base64.b64encode(b"PLOT").decode()
sse = [
{
@@ -1987,11 +1980,11 @@ def test_code_execution_plot_attaches_inline_image_native_part(monkeypatch):
code_ends = [
e for e in tool_events if e.get("type") == "tool_end" and e.get("tool_call_id") == "code_a"
]
- # Two tool_end events on the same id: one for codeExecutionResult,
- # one merging in the inlineData plot. The plot one must carry the
- # native inlineData under google.native_part so the frontend
- # tool_end merge union joins it with the prior executableCode and
- # codeExecutionResult parts on the same card.
+ # Two tool_end events on the same id: one for codeExecutionResult, one
+ # merging in the inlineData plot. The plot one must carry the native
+ # inlineData under google.native_part so the frontend tool_end merge union
+ # joins it with the prior executableCode and codeExecutionResult parts on
+ # the same card.
assert len(code_ends) == 2, code_ends
image_end = next(
(e for e in code_ends if "__IMAGES__:" in (e.get("result") or "")),
@@ -2005,8 +1998,8 @@ def test_code_execution_plot_attaches_inline_image_native_part(monkeypatch):
def test_text_chunk_carries_thought_signature(monkeypatch):
- """Text parts with thoughtSignature surface it on delta.extra_content
- so frontend persistence can replay it on the follow-up turn."""
+ """Text parts with thoughtSignature surface it on delta.extra_content so
+ frontend persistence can replay it on the follow-up turn."""
sse = [
{
"candidates": [
@@ -2040,8 +2033,8 @@ def test_text_chunk_carries_thought_signature(monkeypatch):
def test_openai_tools_translated_into_function_declarations(monkeypatch):
- """Standard ChatCompletionRequest.tools must be forwarded into
- Gemini's tools[].functionDeclarations envelope."""
+ """Standard ChatCompletionRequest.tools must be forwarded into Gemini's
+ tools[].functionDeclarations envelope."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -2093,11 +2086,10 @@ def test_tool_choice_auto_maps_to_function_calling_mode_auto(monkeypatch):
def test_code_exec_inline_image_attaches_to_code_execution_card(monkeypatch):
- """A codeExecution sandbox plot (matplotlib) ships as an inline
- image part right after the codeExecutionResult. Instead of spawning
- a separate empty image_generation card, attach to the same
- code_execution tool_end via the `__IMAGES__:` marker the chat
- adapter already understands."""
+ """A codeExecution sandbox plot (matplotlib) ships as an inline image part
+ right after the codeExecutionResult. Instead of a separate empty
+ image_generation card, attach to the same code_execution tool_end via the
+ `__IMAGES__:` marker the chat adapter already understands."""
sse = [
{
"candidates": [
@@ -2164,9 +2156,9 @@ def test_code_exec_inline_image_attaches_to_code_execution_card(monkeypatch):
def test_code_execution_tool_call_replays_native_executable_code(monkeypatch):
"""An assistant tool_call with toolName=code_execution and
- extra_content.google.native_part containing the originally-emitted
- `executableCode` + `codeExecutionResult` must round-trip as native
- Gemini parts (not a generic functionCall) on the next turn."""
+ extra_content.google.native_part holding the originally-emitted
+ `executableCode` + `codeExecutionResult` must round-trip as native Gemini
+ parts (not a generic functionCall) on the next turn."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -2220,10 +2212,9 @@ def test_code_execution_tool_call_replays_native_executable_code(monkeypatch):
def test_image_generation_tool_call_replays_native_inline_data(monkeypatch):
"""An assistant tool_call with toolName=image_generation and
- extra_content.google.native_part.inlineData must replay the prior
- image as a native Gemini inlineData part (not a generic
- functionCall) so multi-turn image editing keeps the image
- context."""
+ extra_content.google.native_part.inlineData must replay the prior image as
+ a native Gemini inlineData part (not a generic functionCall) so multi-turn
+ image editing keeps the image context."""
pixel = base64.b64encode(b"PNG").decode()
captured = _capture_body(
monkeypatch,
@@ -2273,11 +2264,11 @@ def test_image_generation_tool_call_replays_native_inline_data(monkeypatch):
def test_assistant_text_thought_signature_replays_on_outbound_text_part(monkeypatch):
- """Assistant text with extra_content.google.thought_signature must
- attach `thoughtSignature` to the LAST text part of the replayed
- Gemini history. Gemini 3 strict function-calling rejects history
- that drops returned signatures, so the frontend stows the latest
- signed-text signature and the backend pins it on the next turn."""
+ """Assistant text with extra_content.google.thought_signature must attach
+ `thoughtSignature` to the LAST text part of the replayed Gemini history.
+ Gemini 3 strict function-calling rejects history that drops returned
+ signatures, so the frontend stows the latest signed-text signature and the
+ backend pins it on the next turn."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -2303,10 +2294,10 @@ def test_assistant_text_thought_signature_replays_on_outbound_text_part(monkeypa
def test_function_declarations_strip_openai_only_schema_keys(monkeypatch):
- """OpenAI strict tools commonly include `additionalProperties`,
- `$schema`, `$defs`, `strict`, etc. Gemini's Schema rejects those
- with INVALID_ARGUMENT, so the translator must strip them while
- keeping properties.<field>.type intact."""
+ """OpenAI strict tools commonly include `additionalProperties`, `$schema`,
+ `$defs`, `strict`, etc. Gemini's Schema rejects those with
+ INVALID_ARGUMENT, so the translator must strip them while keeping
+ properties.<field>.type intact."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -2349,12 +2340,12 @@ def test_function_declarations_strip_openai_only_schema_keys(monkeypatch):
def test_function_declarations_inline_local_refs_into_gemini_schema(monkeypatch):
- """Round 25: Pydantic-generated tool schemas hoist nested object
- shapes into `$defs` and reference them with `{"$ref": "#/$defs/..."}`.
- Gemini's OpenAPI subset has no $ref, so a naive allowlist sanitizer
- drops the reference and reduces the nested property to `{}`, losing
- its type, fields, and required keys. The sanitizer must resolve
- local `#/...` pointers and inline the referenced schema."""
+ """Round 25: Pydantic-generated tool schemas hoist nested object shapes
+ into `$defs` and reference them with `{"$ref": "#/$defs/..."}`. Gemini's
+ OpenAPI subset has no $ref, so a naive allowlist sanitizer drops the
+ reference and reduces the nested property to `{}`, losing its type, fields,
+ and required keys. The sanitizer must resolve local `#/...` pointers and
+ inline the referenced schema."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -2401,9 +2392,8 @@ def test_function_declarations_inline_local_refs_into_gemini_schema(monkeypatch)
def test_function_declarations_inline_local_refs_in_anyof_and_items(monkeypatch):
- """The recursive inliner must reach through `anyOf` branches and
- `items` (array element schemas) as well, not just top-level
- property refs."""
+ """The recursive inliner must reach through `anyOf` branches and `items`
+ (array element schemas), not just top-level property refs."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -2446,8 +2436,8 @@ def test_function_declarations_inline_local_refs_in_anyof_and_items(monkeypatch)
params = decls[0]["parameters"]
primary = params["properties"]["primary"]
# anyOf with single non-null branch + null collapses to inline +
- # nullable: true, and the inlined branch must contain the resolved
- # Address shape.
+ # nullable: true; the inlined branch must contain the resolved Address
+ # shape.
assert primary.get("nullable") is True
assert primary.get("type") == "object"
assert primary.get("properties", {}).get("zip", {}).get("type") == "string"
@@ -2458,9 +2448,9 @@ def test_function_declarations_inline_local_refs_in_anyof_and_items(monkeypatch)
def test_function_declarations_self_referential_schema_terminates(monkeypatch):
- """Self-referential / cyclic JSON Schemas (a `Node` that contains
- `children: [Node]`) must not infinite-loop. The inliner tracks the
- set of refs in flight and short-circuits to `{}` on a cycle."""
+ """Self-referential / cyclic JSON Schemas (a `Node` with `children:
+ [Node]`) must not infinite-loop. The inliner tracks the set of refs in
+ flight and short-circuits to `{}` on a cycle."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -2503,10 +2493,10 @@ def test_function_declarations_self_referential_schema_terminates(monkeypatch):
def test_gemini_native_skips_orphan_function_response_for_dropped_builtin(monkeypatch):
"""Round 26: when the assistant-side synthetic web_search/web_fetch
- tool_call is dropped from native Gemini history, the matching
- role="tool" follow-up must also be dropped. Otherwise the outbound
- body carries an orphan functionResponse with no preceding
- functionCall, which 400s the Gemini turn."""
+ tool_call is dropped from native Gemini history, the matching role="tool"
+ follow-up must also be dropped. Otherwise the outbound body carries an
+ orphan functionResponse with no preceding functionCall, which 400s the
+ Gemini turn."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -2556,12 +2546,12 @@ def test_gemini_native_skips_orphan_function_response_for_dropped_builtin(monkey
def test_gemini_native_skips_orphan_function_response_for_native_part_replay(monkeypatch):
- """Round 26: code_execution / image_generation tool_calls are
- replayed as Gemini-native executableCode / codeExecutionResult /
- inlineData parts. The matching role="tool" follow-up must NOT then
- be emitted as a functionResponse named code_execution -- there is
- no declared user function with that name, and Gemini's history
- rules already attribute the result to the native parts above."""
+ """Round 26: code_execution / image_generation tool_calls are replayed as
+ Gemini-native executableCode / codeExecutionResult / inlineData parts. The
+ matching role="tool" follow-up must NOT then be emitted as a
+ functionResponse named code_execution -- there is no declared user
+ function with that name, and Gemini's history rules already attribute the
+ result to the native parts above."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -2622,17 +2612,16 @@ def test_gemini_native_skips_orphan_function_response_for_native_part_replay(mon
def test_gemini_native_part_falls_back_to_args_google(monkeypatch):
- """Round 27: a direct OpenAI-compat API caller (or imported third-
- party thread) cannot use Studio's non-standard
- `tool_calls[].extra_content` field, so the native_part payload
- round-trips through `function.arguments` as
- `{"google": {"native_part": {...}}}`. The synthetic-builtin
- detector recognizes that location, but the replay branch was only
- reading from `tc.extra_content.google.native_part`. Result: the
- round-25 guard saw a synthetic builtin with no _native_part and
- dropped the entire assistant turn, losing the prior code/image
- context. The translator must fall back to args.google.native_part
- and still emit the native executableCode / inlineData parts."""
+ """Round 27: a direct OpenAI-compat API caller (or imported third-party
+ thread) cannot use Studio's non-standard `tool_calls[].extra_content`
+ field, so the native_part payload round-trips through `function.arguments`
+ as `{"google": {"native_part": {...}}}`. The synthetic-builtin detector
+ recognizes that location, but the replay branch was only reading from
+ `tc.extra_content.google.native_part`. Result: the round-25 guard saw a
+ synthetic builtin with no _native_part and dropped the entire assistant
+ turn, losing the prior code/image context. The translator must fall back
+ to args.google.native_part and still emit the native executableCode /
+ inlineData parts."""
import json as _json
captured = _capture_body(
@@ -2682,11 +2671,11 @@ def test_gemini_native_part_falls_back_to_args_google(monkeypatch):
def test_gemini_native_skips_synthetic_server_builtin_replay(monkeypatch):
"""Round 25: Marked server-side builtin tool_calls (web_search /
- web_fetch with `_server_tool` or `args.google.native_part`) must
- not fall through to the generic Gemini `functionCall` replay path
- when no replayable native part exists. Without this guard the
- outbound body contains a fake `functionCall` whose name is not a
- declared user function, and the Gemini turn 400s."""
+ web_fetch with `_server_tool` or `args.google.native_part`) must not fall
+ through to the generic Gemini `functionCall` replay path when no replayable
+ native part exists. Without this guard the outbound body contains a fake
+ `functionCall` whose name isn't a declared user function, and the Gemini
+ turn 400s."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -2736,10 +2725,10 @@ def test_gemini_native_skips_synthetic_server_builtin_replay(monkeypatch):
def test_chat_message_extra_content_round_trips_through_validation():
- """Round 9: ChatMessage was missing `extra_content`, so Pydantic
- discarded the field during request validation and the text-part
- signature replay path read nothing. The field must survive
- model_validate and pass through _build_external_messages."""
+ """Round 9: ChatMessage was missing `extra_content`, so Pydantic discarded
+ it during request validation and the text-part signature replay path read
+ nothing. The field must survive model_validate and pass through
+ _build_external_messages."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -2774,16 +2763,16 @@ def test_chat_message_extra_content_round_trips_through_validation():
assistant_out = built[1]
assert assistant_out["extra_content"] == {"google": {"thought_signature": "SIG-TEXT"}}
# Non-Gemini providers must NOT receive extra_content; Google's
- # thought_signature field is unknown to OpenAI / Mistral / etc.
+ # thought_signature is unknown to OpenAI / Mistral / etc.
built_openai = _build_external_messages(
req.messages,
supports_vision = True,
provider_type = "openai",
)
assert "extra_content" not in built_openai[1], built_openai[1]
- # Custom non-Google Gemini bases (LiteLLM / OAI-compat gateways)
- # also must not receive Gemini-only extra_content because the
- # backend dispatches them through /chat/completions.
+ # Custom non-Google Gemini bases (LiteLLM / OAI-compat gateways) also must
+ # not receive Gemini-only extra_content -- the backend dispatches them
+ # through /chat/completions.
built_custom = _build_external_messages(
req.messages,
supports_vision = True,
@@ -2794,11 +2783,10 @@ def test_chat_message_extra_content_round_trips_through_validation():
def test_parallel_tool_results_group_into_one_user_block(monkeypatch):
- """Round 14: Gemini docs show parallel functionResponses grouped
- in a single subsequent user content with multiple
- functionResponse parts. Consecutive OpenAI role="tool" messages
- must merge into one Gemini user block, not split into separate
- user turns."""
+ """Round 14: Gemini docs group parallel functionResponses in a single
+ subsequent user content with multiple functionResponse parts. Consecutive
+ OpenAI role="tool" messages must merge into one Gemini user block, not
+ split into separate user turns."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -2850,10 +2838,9 @@ def test_parallel_tool_results_group_into_one_user_block(monkeypatch):
def test_function_schema_nullable_type_array_flattens(monkeypatch):
- """Round 14: OpenAI strict tools commonly use
- `"type": ["string", "null"]` for optional fields. Gemini's
- OpenAPI-style Schema rejects union types and expects
- `"type": "string"` with `"nullable": true`. The sanitizer must
+ """Round 14: OpenAI strict tools commonly use `"type": ["string", "null"]`
+ for optional fields. Gemini's OpenAPI-style Schema rejects union types and
+ expects `"type": "string"` with `"nullable": true`. The sanitizer must
translate the union form."""
captured = _capture_body(
monkeypatch,
@@ -2886,12 +2873,11 @@ def test_function_schema_nullable_type_array_flattens(monkeypatch):
def test_image_picker_model_with_search_off_pill_strips_text_tools(monkeypatch):
- """Round 11: image-tier model id rejects text-only tools and
- thinkingConfig at the model level regardless of whether the Images
- pill is on. Selecting gemini-2.5-flash-image + enabled_tools=
- ["web_search"] with no image_generation must NOT forward
- googleSearch or thinkingConfig (Gemini 400s on text tools for
- legacy image ids)."""
+ """Round 11: image-tier model ids reject text-only tools and
+ thinkingConfig at the model level regardless of the Images pill. Selecting
+ gemini-2.5-flash-image + enabled_tools=["web_search"] with no
+ image_generation must NOT forward googleSearch or thinkingConfig (Gemini
+ 400s on text tools for legacy image ids)."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash-image",
@@ -2904,7 +2890,7 @@ def test_image_picker_model_with_search_off_pill_strips_text_tools(monkeypatch):
def test_image_models_drop_function_declarations(monkeypatch):
- """Image-mode requests cannot mix tools with responseModalities so
+ """Image-mode requests cannot mix tools with responseModalities, so
user-supplied function declarations must be dropped."""
captured = _capture_body(
monkeypatch,
@@ -2923,18 +2909,17 @@ def test_image_models_drop_function_declarations(monkeypatch):
def test_safe_fetch_image_rejects_malformed_bracketed_url():
"""Round 17: bracketed IPv6 garbage like `https://[bad/x.png` makes
- urlparse raise ValueError. The fetch helper must catch it and drop
- the image rather than crashing the request mid-build."""
+ urlparse raise ValueError. The fetch helper must catch it and drop the
+ image rather than crashing the request mid-build."""
res = _drive(ep_mod._safe_fetch_image_for_gemini("https://[bad/x.png", "image/png"))
assert res is None
def test_safe_fetch_image_pins_validated_ip_no_hostname_in_request(monkeypatch):
- """Round 17: the fetch helper must pin the validated IP into the
- outgoing request URL (with a Host header carrying the original
- hostname). A second hostname-style getaddrinfo after the validate
- step would be a DNS-rebinding gap, so we assert the urllib opener
- is called with an IP-rewritten URL."""
+ """Round 17: the fetch helper must pin the validated IP into the outgoing
+ request URL (with a Host header carrying the original hostname). A second
+ hostname-style getaddrinfo after validate would be a DNS-rebinding gap, so
+ we assert the urllib opener is called with an IP-rewritten URL."""
import socket
captured: dict = {"requests": []}
@@ -2990,7 +2975,7 @@ def test_safe_fetch_image_pins_validated_ip_no_hostname_in_request(monkeypatch):
res = _drive(ep_mod._safe_fetch_image_for_gemini("https://cdn.example.com/x.png", "image/png"))
assert res is not None
assert res[0] == "image/png"
- # The outgoing URL must use the pinned IP literal, not the hostname.
+ # Outgoing URL must use the pinned IP literal, not the hostname.
assert any("8.8.8.8" in r["url"] for r in captured["requests"]), captured
assert all("cdn.example.com" not in r["url"] for r in captured["requests"]), captured
# Host header still carries the original hostname for vhost/SNI.
@@ -2998,8 +2983,8 @@ def test_safe_fetch_image_pins_validated_ip_no_hostname_in_request(monkeypatch):
def test_safe_fetch_image_redirect_to_private_host_rejected(monkeypatch):
- """Round 17: each redirect hop must re-validate the new host. A
- public hop that redirects to an internal address must be dropped."""
+ """Round 17: each redirect hop must re-validate the new host. A public hop
+ that redirects to an internal address must be dropped."""
import socket
import urllib.error
@@ -3052,11 +3037,11 @@ def test_safe_fetch_image_redirect_to_private_host_rejected(monkeypatch):
def test_files_api_substring_url_not_misclassified_as_filedata(monkeypatch):
- """Round 17: a CDN URL whose path/query merely contains the Files
- API substring must NOT be sent as `fileData.fileUri`; it must be
- routed through the safe-fetch path. Previously the substring check
- `"generativelanguage.googleapis.com/" in url.lower()` matched any
- URL carrying that text anywhere."""
+ """Round 17: a CDN URL whose path/query merely contains the Files API
+ substring must NOT be sent as `fileData.fileUri`; route it through the
+ safe-fetch path. The old substring check
+ `"generativelanguage.googleapis.com/" in url.lower()` matched any URL
+ carrying that text anywhere."""
captured_outbound: dict = {}
fetch_calls: list[str] = []
@@ -3109,8 +3094,8 @@ def test_files_api_substring_url_not_misclassified_as_filedata(monkeypatch):
{
"type": "image_url",
"image_url": {
- # Looks like a Files API URL in the path
- # but the host is an attacker CDN.
+ # Files-API-looking path, but host is an
+ # attacker CDN.
"url": "https://evil.example/path/generativelanguage.googleapis.com/v1beta/files/abc.png",
},
},
@@ -3142,10 +3127,10 @@ def test_files_api_substring_url_not_misclassified_as_filedata(monkeypatch):
def test_function_schema_anyof_null_variant_flattens_to_nullable(monkeypatch):
- """Round 17: OpenAI/Pydantic emit `anyOf: [{X}, {"type":"null"}]`
- for Optional[X]. Gemini's OpenAPI subset rejects `"type":"null"`
- inside anyOf. The sanitizer must collapse a singleton-plus-null
- union back to the non-null branch with `nullable: true`."""
+ """Round 17: OpenAI/Pydantic emit `anyOf: [{X}, {"type":"null"}]` for
+ Optional[X]. Gemini's OpenAPI subset rejects `"type":"null"` inside anyOf.
+ The sanitizer must collapse a singleton-plus-null union back to the
+ non-null branch with `nullable: true`."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -3188,10 +3173,10 @@ def test_function_schema_anyof_null_variant_flattens_to_nullable(monkeypatch):
def test_legacy_gemini3_pro_medium_coerced_to_high(monkeypatch):
- """Round 17: legacy `gemini-3-pro*` (including `-preview`, shut down
- 2026-03-09) only accepted low/high. 3.1+ Pro added medium. The
- backend must coerce medium → high for the legacy model so stale UI
- state does not 400 the request."""
+ """Round 17: legacy `gemini-3-pro*` (incl. `-preview`, shut down
+ 2026-03-09) only accepted low/high. 3.1+ Pro added medium. The backend
+ must coerce medium → high for the legacy model so stale UI state doesn't
+ 400 the request."""
captured = _capture_body(
monkeypatch,
model = "gemini-3-pro-preview",
@@ -3201,8 +3186,8 @@ def test_legacy_gemini3_pro_medium_coerced_to_high(monkeypatch):
def test_gemini_3_1_pro_medium_passes_through(monkeypatch):
- """Round 17 regression: 3.1+ Pro accepts medium; coercion must NOT
- apply when the model id is gemini-3.1-pro*."""
+ """Round 17 regression: 3.1+ Pro accepts medium; coercion must NOT apply
+ when the model id is gemini-3.1-pro*."""
captured = _capture_body(
monkeypatch,
model = "gemini-3.1-pro-preview",
@@ -3214,8 +3199,8 @@ def test_gemini_3_1_pro_medium_passes_through(monkeypatch):
def test_tool_calls_extra_content_stripped_for_non_native_gemini():
"""Round 17: per-tool-call `extra_content` (Gemini thoughtSignature
carrier) must not leak through `_build_external_messages` to
- non-native-Gemini providers; OpenAI / Anthropic / custom Gemini
- OAI-compat gateways would 400 on the unknown key."""
+ non-native-Gemini providers; OpenAI / Anthropic / custom Gemini OAI-compat
+ gateways would 400 on the unknown key."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -3241,8 +3226,8 @@ def test_tool_calls_extra_content_stripped_for_non_native_gemini():
}
req = ChatCompletionRequest.model_validate(payload)
- # Non-native providers (openai, custom Gemini OAI-compat proxy)
- # must have extra_content stripped from the tool_call entry.
+ # Non-native providers (openai, custom Gemini OAI-compat proxy) must have
+ # extra_content stripped from the tool_call entry.
for provider_type, base_url in [
("openai", None),
("gemini", "https://litellm.example/v1"),
@@ -3269,11 +3254,10 @@ def test_tool_calls_extra_content_stripped_for_non_native_gemini():
def test_user_function_named_with_server_tool_arg_not_dropped(monkeypatch):
- """Round 17: the OpenAI Responses translator must NOT drop a user
- function whose JSON arguments happen to contain `_server_tool:
- true` UNLESS the function name is also one of the canonical
- builtin names. Otherwise a user schema with an `_server_tool` field
- becomes invisible to the model."""
+ """Round 17: the OpenAI Responses translator must NOT drop a user function
+ whose JSON arguments contain `_server_tool: true` UNLESS the function name
+ is also a canonical builtin name. Otherwise a user schema with an
+ `_server_tool` field becomes invisible to the model."""
captured: dict = {"input_items": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3331,15 +3315,14 @@ def test_user_function_named_with_server_tool_arg_not_dropped(monkeypatch):
items = captured["input_items"] or []
fn_calls = [i for i in items if i.get("type") == "function_call"]
fn_outs = [i for i in items if i.get("type") == "function_call_output"]
- # User function call must survive (matching call + output).
+ # User function call must survive (call + output).
assert any(c.get("name") == "user_function" for c in fn_calls), items
assert len(fn_outs) == 1, items
def test_builtin_named_with_server_tool_marker_dropped(monkeypatch):
- """Round 17 control: a builtin (web_search) tagged with
- `_server_tool: true` continues to be filtered from outbound
- history."""
+ """Round 17 control: a builtin (web_search) tagged with `_server_tool:
+ true` continues to be filtered from outbound history."""
captured: dict = {"input_items": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3395,10 +3378,10 @@ def test_builtin_named_with_server_tool_marker_dropped(monkeypatch):
def test_gemini_tool_choice_none_disables_hosted_builtins(monkeypatch):
- """Round 18: `tool_choice="none"` must drop hosted Google Search /
- code execution from the outbound Gemini body, not just user
- function declarations. Otherwise an API client that opted out of
- tool use still triggers grounded search (privacy + billing)."""
+ """Round 18: `tool_choice="none"` must drop hosted Google Search / code
+ execution from the Gemini body, not just user function declarations.
+ Otherwise an API client that opted out of tool use still triggers grounded
+ search (privacy + billing)."""
captured = _capture_body(
monkeypatch,
enabled_tools = ["web_search", "code_execution"],
@@ -3408,8 +3391,8 @@ def test_gemini_tool_choice_none_disables_hosted_builtins(monkeypatch):
def test_gemini_tool_choice_none_disables_function_declarations(monkeypatch):
- """Round 18: `tool_choice="none"` must drop user function
- declarations as well as hosted builtins from the Gemini body."""
+ """Round 18: `tool_choice="none"` must drop user function declarations as
+ well as hosted builtins from the Gemini body."""
captured = _capture_body(
monkeypatch,
tool_choice = "none",
@@ -3424,10 +3407,9 @@ def test_gemini_tool_choice_none_disables_function_declarations(monkeypatch):
def test_schema_anyof_multitype_with_null_keeps_anyof_and_nullable(monkeypatch):
- """Round 18: multi-branch unions with null (e.g.
- `Union[str, int, None]`) must keep the slim anyOf without the null
- branch and add `nullable: true`; Gemini rejects
- `{"type":"null"}` inside anyOf."""
+ """Round 18: multi-branch unions with null (e.g. `Union[str, int, None]`)
+ must keep the slim anyOf without the null branch and add `nullable: true`;
+ Gemini rejects `{"type":"null"}` inside anyOf."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -3464,9 +3446,9 @@ def test_schema_anyof_multitype_with_null_keeps_anyof_and_nullable(monkeypatch):
def test_safe_fetch_image_redirect_malformed_url_no_crash(monkeypatch):
- """Round 18: when the upstream 302 Location is a malformed
- bracketed-IPv6 URL, the helper must return None instead of letting
- a urlparse ValueError abort the chat stream."""
+ """Round 18: when the upstream 302 Location is a malformed bracketed-IPv6
+ URL, the helper must return None instead of letting a urlparse ValueError
+ abort the chat stream."""
import socket
import urllib.error
@@ -3508,17 +3490,17 @@ def test_safe_fetch_image_redirect_malformed_url_no_crash(monkeypatch):
def test_safe_fetch_image_malformed_port_no_crash():
- """Round 18: a URL with a non-numeric port (`https://h:bad/x.png`)
- must not raise; urlparse's port property lazily ValueErrors."""
+ """Round 18: a URL with a non-numeric port (`https://h:bad/x.png`) must
+ not raise; urlparse's port property lazily ValueErrors."""
res = _drive(ep_mod._safe_fetch_image_for_gemini("https://example.com:bad/x.png", "image/png"))
assert res is None
def test_safe_fetch_image_missing_content_type_uses_fallback(monkeypatch):
- """Round 18: when the server returns image bytes but no
- Content-Type header, the helper must use the caller-provided
- fallback MIME (guessed from URL extension) instead of dropping the
- image as `non-image content-type=<none>`."""
+ """Round 18: when the server returns image bytes but no Content-Type
+ header, the helper must use the caller-provided fallback MIME (guessed from
+ URL extension) instead of dropping the image as `non-image
+ content-type=<none>`."""
import socket
original_getaddrinfo = socket.getaddrinfo
@@ -3569,11 +3551,11 @@ def test_safe_fetch_image_missing_content_type_uses_fallback(monkeypatch):
def test_anthropic_translates_openai_tool_calls_into_tool_use_blocks(monkeypatch):
- """Round 18: an assistant turn with OpenAI-style top-level
- `tool_calls` must be translated into Anthropic native
- `{type:"tool_use", id, name, input}` content blocks before being
- forwarded. The OpenAI `role="tool"` follow-up must become a
- `role:"user"` message with a `tool_result` content block."""
+ """Round 18: an assistant turn with OpenAI-style top-level `tool_calls`
+ must be translated into Anthropic native `{type:"tool_use", id, name,
+ input}` content blocks before forwarding. The OpenAI `role="tool"`
+ follow-up must become a `role:"user"` message with a `tool_result`
+ block."""
captured: dict = {"messages": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3631,8 +3613,8 @@ def test_anthropic_translates_openai_tool_calls_into_tool_use_blocks(monkeypatch
msgs = captured["messages"] or []
# No top-level tool_calls should remain.
assert all("tool_calls" not in m for m in msgs), msgs
- # The assistant turn must now have content blocks including a
- # tool_use block.
+ # The assistant turn must now have content blocks including a tool_use
+ # block.
asst = [m for m in msgs if m.get("role") == "assistant"]
assert asst and isinstance(asst[0]["content"], list), asst
tool_uses = [b for b in asst[0]["content"] if b.get("type") == "tool_use"]
@@ -3651,10 +3633,10 @@ def test_anthropic_translates_openai_tool_calls_into_tool_use_blocks(monkeypatch
def test_unmarked_user_web_search_function_survives_serialization():
- """Round 18: a user-defined function literally named `web_search`
- with NO `_server_tool` marker must survive `_build_external_messages`
- when forwarded to a non-native provider; only marked synthetic
- builtin cards may be dropped."""
+ """Round 18: a user-defined function literally named `web_search` with NO
+ `_server_tool` marker must survive `_build_external_messages` when
+ forwarded to a non-native provider; only marked synthetic builtin cards may
+ be dropped."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -3692,11 +3674,11 @@ def test_unmarked_user_web_search_function_survives_serialization():
def test_marked_server_builtin_dropped_from_build_external_messages():
- """Round 18: when a Gemini-native turn carrying a marked
- `image_generation` server-tool card is forwarded to OpenAI / a
- custom Gemini OAI-compat proxy, the tool_call must be dropped, not
- just have its extra_content stripped. Forwarding an orphan
- `image_generation` tool_call would 400 the receiving API."""
+ """Round 18: when a Gemini-native turn carrying a marked `image_generation`
+ server-tool card is forwarded to OpenAI / a custom Gemini OAI-compat proxy,
+ the tool_call must be dropped, not just have its extra_content stripped.
+ Forwarding an orphan `image_generation` tool_call would 400 the receiving
+ API."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -3722,8 +3704,8 @@ def test_marked_server_builtin_dropped_from_build_external_messages():
"stream": True,
}
req = ChatCompletionRequest.model_validate(payload)
- # Non-native providers: marked builtin tool_call must be dropped
- # AND if it was the only payload, the whole message disappears.
+ # Non-native providers: marked builtin tool_call must be dropped, and if it
+ # was the only payload, the whole message disappears.
for provider_type, base_url in [
("openai", None),
("gemini", "https://litellm.example/v1"),
@@ -3752,9 +3734,9 @@ def test_marked_server_builtin_dropped_from_build_external_messages():
def test_openai_responses_tool_choice_none_drops_hosted_tools(monkeypatch):
- """Round 18: `tool_choice="none"` must also drop hosted OpenAI
- Responses builtins (web_search, code execution shell, image
- generation), not just user function tools."""
+ """Round 18: `tool_choice="none"` must also drop hosted OpenAI Responses
+ builtins (web_search, code execution shell, image generation), not just
+ user function tools."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3791,9 +3773,9 @@ def test_openai_responses_tool_choice_none_drops_hosted_tools(monkeypatch):
def test_anthropic_tool_choice_none_drops_hosted_tools(monkeypatch):
- """Round 19: tool_choice="none" must opt out of Anthropic hosted
- builtins (web_search, web_fetch, code_execution) just like it does
- for Gemini and OpenAI Responses."""
+ """Round 19: tool_choice="none" must opt out of Anthropic hosted builtins
+ (web_search, web_fetch, code_execution) like it does for Gemini and OpenAI
+ Responses."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3830,9 +3812,9 @@ def test_anthropic_tool_choice_none_drops_hosted_tools(monkeypatch):
def test_openrouter_tool_choice_none_drops_web_plugin(monkeypatch):
- """Round 19: tool_choice="none" must drop the OpenRouter web
- plugin so a request that opted out of tool use does not still
- trigger hosted web search."""
+ """Round 19: tool_choice="none" must drop the OpenRouter web plugin so a
+ request that opted out of tool use doesn't still trigger hosted web
+ search."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -3869,10 +3851,9 @@ def test_openrouter_tool_choice_none_drops_web_plugin(monkeypatch):
def test_kimi_tool_choice_none_skips_web_search_helper(monkeypatch):
- """Round 19: when tool_choice="none" plus enabled_tools=
- ["web_search"] on Kimi, the dispatcher must NOT route into
- `_stream_kimi_web_search`. Falling through to the generic OAI-
- compat path is the expected behavior."""
+ """Round 19: when tool_choice="none" plus enabled_tools=["web_search"] on
+ Kimi, the dispatcher must NOT route into `_stream_kimi_web_search`. Falling
+ through to the generic OAI-compat path is expected."""
routed_to_helper = {"called": False}
real_helper = ExternalProviderClient._stream_kimi_web_search
@@ -3926,10 +3907,9 @@ def test_kimi_tool_choice_none_skips_web_search_helper(monkeypatch):
def test_user_code_execution_function_not_dropped():
- """Round 19: a user-declared function literally named
- `code_execution` with normal `code` arguments must survive
- `_build_external_messages` -- round 17's shape heuristic dropped
- it, which broke function-calling round-trips."""
+ """Round 19: a user-declared function literally named `code_execution` with
+ normal `code` arguments must survive `_build_external_messages` -- round
+ 17's shape heuristic dropped it, breaking function-calling round-trips."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -3967,10 +3947,10 @@ def test_user_code_execution_function_not_dropped():
def test_native_part_code_execution_treated_as_server_side():
- """Round 19: a Gemini `code_execution` card persists its replay
- payload at `args.google.native_part` (no `_server_tool` marker on
- pre-PR cards). The backend filter must still drop it for non-native
- providers because it is a synthetic card, not a real user function."""
+ """Round 19: a Gemini `code_execution` card persists its replay payload at
+ `args.google.native_part` (no `_server_tool` marker on pre-PR cards). The
+ backend filter must still drop it for non-native providers because it's a
+ synthetic card, not a real user function."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -4017,9 +3997,9 @@ def test_native_part_code_execution_treated_as_server_side():
def test_remote_image_fetch_attempt_cap_includes_failures(monkeypatch):
- """Round 19: the per-request image fetch count cap must count
- ATTEMPTS, not just successes. Otherwise a request with 100
- failing/slow URLs runs 100 fetches each up to the 15s timeout."""
+ """Round 19: the per-request image fetch count cap must count ATTEMPTS,
+ not just successes. Otherwise a request with 100 failing/slow URLs runs 100
+ fetches each up to the 15s timeout."""
fetch_calls: list[str] = []
async def fake_fetch(
@@ -4091,10 +4071,9 @@ def test_remote_image_fetch_attempt_cap_includes_failures(monkeypatch):
def test_orphan_function_call_output_dropped_when_call_skipped(monkeypatch):
- """Round 19: when a marked server-side builtin `function_call` is
- dropped from OpenAI Responses input items, the matching role=tool
- follow-up must also be dropped to avoid an orphan
- `function_call_output`."""
+ """Round 19: when a marked server-side builtin `function_call` is dropped
+ from OpenAI Responses input items, the matching role=tool follow-up must
+ also be dropped to avoid an orphan `function_call_output`."""
captured: dict = {"input_items": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -4157,10 +4136,10 @@ def test_orphan_function_call_output_dropped_when_call_skipped(monkeypatch):
def test_schema_multitype_union_with_null_preserves_anyof(monkeypatch):
- """Round 19: a JSON Schema `"type": ["string","integer","null"]`
- must be sanitized to anyOf:[{string},{integer}] + nullable:true.
- Flattening to just `{"type":"string"}` silently drops the integer
- branch and changes the function contract."""
+ """Round 19: a JSON Schema `"type": ["string","integer","null"]` must be
+ sanitized to anyOf:[{string},{integer}] + nullable:true. Flattening to just
+ `{"type":"string"}` silently drops the integer branch and changes the
+ function contract."""
captured = _capture_body(
monkeypatch,
tools = [
@@ -4193,8 +4172,7 @@ def test_schema_multitype_union_with_null_preserves_anyof(monkeypatch):
def test_invalid_gemini_model_rejected_before_image_fetch(monkeypatch):
"""Round 19: invalid Gemini model IDs are rejected at the top of
- `_stream_gemini`, BEFORE any user-controlled remote image fetch
- runs."""
+ `_stream_gemini`, BEFORE any user-controlled remote image fetch runs."""
fetch_calls: list[str] = []
async def fake_fetch(
@@ -4244,11 +4222,10 @@ def test_invalid_gemini_model_rejected_before_image_fetch(monkeypatch):
def test_empty_assistant_turn_skipped_after_synthetic_tool_calls_dropped():
- """Round 20: when `_filter_tool_calls` drops every synthetic
- server-builtin tool_call on an empty-content assistant turn, the
- whole message must be skipped. Forwarding
- `{"role":"assistant","content":""}` is rejected by several
- providers as an empty assistant turn."""
+ """Round 20: when `_filter_tool_calls` drops every synthetic server-builtin
+ tool_call on an empty-content assistant turn, the whole message must be
+ skipped. Several providers reject `{"role":"assistant","content":""}` as an
+ empty assistant turn."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -4284,16 +4261,16 @@ def test_empty_assistant_turn_skipped_after_synthetic_tool_calls_dropped():
provider_type = provider_type,
base_url = base_url,
)
- # The empty assistant turn (only a synthetic builtin) must
- # NOT appear in the output at all.
+ # The empty assistant turn (only a synthetic builtin) must NOT appear
+ # in the output at all.
assert result == [], (provider_type, result)
def test_role_tool_dropped_when_matching_synthetic_call_filtered():
- """Round 20: `_build_external_messages` drops the matching role=
- tool follow-up when its tool_call was a synthetic builtin that
- `_filter_tool_calls` removed. Otherwise the receiving provider
- sees an orphan tool_result with no tool_call."""
+ """Round 20: `_build_external_messages` drops the matching role=tool
+ follow-up when its tool_call was a synthetic builtin that
+ `_filter_tool_calls` removed. Otherwise the receiving provider sees an
+ orphan tool_result with no tool_call."""
from models.inference import ChatCompletionRequest
from routes.inference import _build_external_messages
@@ -4338,10 +4315,9 @@ def test_role_tool_dropped_when_matching_synthetic_call_filtered():
def test_openrouter_no_synthetic_web_search_event_on_tool_choice_none(monkeypatch):
- """Round 20: OpenRouter dispatcher must not emit synthetic
- web_search tool_start / tool_end events when tool_choice="none";
- otherwise the chat UI shows a search card for a search that
- never happened."""
+ """Round 20: OpenRouter dispatcher must not emit synthetic web_search
+ tool_start / tool_end events when tool_choice="none"; otherwise the chat UI
+ shows a search card for a search that never happened."""
captured_events: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
@@ -4377,10 +4353,9 @@ def test_openrouter_no_synthetic_web_search_event_on_tool_choice_none(monkeypatc
obj = json.loads(payload)
except Exception:
continue
- # Backend emits synthetic tool events as a top-level
- # `_toolEvent` on the SSE payload (not nested inside
- # `delta`). Read both shapes so a future format change
- # cannot mask this regression.
+ # Backend emits synthetic tool events as a top-level `_toolEvent`
+ # on the SSE payload (not nested inside `delta`). Read both shapes
+ # so a future format change can't mask this regression.
evt = obj.get("_toolEvent")
if isinstance(evt, dict):
captured_events.append(evt)
@@ -4398,9 +4373,9 @@ def test_openrouter_no_synthetic_web_search_event_on_tool_choice_none(monkeypatc
def test_anthropic_role_tool_list_content_translates_to_tool_result(monkeypatch):
"""Round 20: an OpenAI-shape role=tool message with list content
- (`content=[{"type":"text","text":"result"}]`) must be translated
- into Anthropic's native tool_result block, not forwarded as an
- invalid role=tool message."""
+ (`content=[{"type":"text","text":"result"}]`) must be translated into
+ Anthropic's native tool_result block, not forwarded as an invalid role=tool
+ message."""
captured: dict = {"messages": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -4468,9 +4443,9 @@ def test_anthropic_role_tool_list_content_translates_to_tool_result(monkeypatch)
def test_data_url_non_image_mime_dropped(monkeypatch):
- """Round 20: a `data:text/html;base64,...` image_url must be
- dropped from the outbound Gemini body, not forwarded as
- `inlineData.mimeType="text/html"` which Gemini rejects."""
+ """Round 20: a `data:text/html;base64,...` image_url must be dropped from
+ the Gemini body, not forwarded as `inlineData.mimeType="text/html"` which
+ Gemini rejects."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -4493,8 +4468,8 @@ def test_data_url_non_image_mime_dropped(monkeypatch):
def test_youtube_filedata_uses_video_mime(monkeypatch):
- """Round 20: YouTube `fileData.fileUri` must declare a video
- mimeType, not `image/jpeg` guessed from the URL path."""
+ """Round 20: YouTube `fileData.fileUri` must declare a video mimeType, not
+ `image/jpeg` guessed from the URL path."""
captured = _capture_body(
monkeypatch,
messages = [
@@ -4519,12 +4494,11 @@ def test_youtube_filedata_uses_video_mime(monkeypatch):
def test_openai_responses_assistant_text_serialized_before_function_call(monkeypatch):
- """Round 20: in OpenAI Responses history, the assistant's
- visible text for a turn that ALSO emitted a function_call must
- serialize BEFORE the function_call item, matching the prior
- response.output sequence. Otherwise function_call_output (the
- role=tool follow-up) appears to follow an unrelated assistant
- message."""
+ """Round 20: in OpenAI Responses history, the assistant's visible text for
+ a turn that ALSO emitted a function_call must serialize BEFORE the
+ function_call item, matching the prior response.output sequence. Otherwise
+ function_call_output (the role=tool follow-up) appears to follow an
+ unrelated assistant message."""
captured: dict = {"input_items": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -4593,9 +4567,9 @@ def test_openai_responses_assistant_text_serialized_before_function_call(monkeyp
def test_gemini_tool_choice_none_disables_image_generation(monkeypatch):
"""Round 21: `tool_choice="none"` must also flip the implicit
image-generation hosted tool off on image-tier models. Otherwise
- `responseModalities=["TEXT","IMAGE"]` still rides on the outbound
- body and the provider can generate (and bill for) image output
- despite the explicit OpenAI tool opt-out."""
+ `responseModalities=["TEXT","IMAGE"]` still rides on the body and the
+ provider can generate (and bill for) image output despite the explicit
+ OpenAI tool opt-out."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash-image",
@@ -4608,11 +4582,11 @@ def test_gemini_tool_choice_none_disables_image_generation(monkeypatch):
def test_gemini_forced_function_tool_choice_drops_hosted_builtins(monkeypatch):
"""Round 21: forced-function `tool_choice` (e.g.
- `{"type":"function","function":{"name":"lookup"}}`) must suppress
- hosted Google Search / code execution. Gemini's toolConfig only
- constrains function declarations, not hosted tools, so leaving
- `googleSearch`/`codeExecution` in `tools[]` lets them fire despite
- the caller pinning a specific user function."""
+ `{"type":"function","function":{"name":"lookup"}}`) must suppress hosted
+ Google Search / code execution. Gemini's toolConfig only constrains
+ function declarations, not hosted tools, so leaving
+ `googleSearch`/`codeExecution` in `tools[]` lets them fire despite the
+ caller pinning a specific user function."""
captured = _capture_body(
monkeypatch,
enabled_tools = ["web_search", "code_execution"],
@@ -4636,8 +4610,8 @@ def test_gemini_forced_function_tool_choice_drops_hosted_builtins(monkeypatch):
def test_gemini_forced_function_tool_choice_drops_image_generation(monkeypatch):
- """Round 21: forced-function `tool_choice` must also flip the
- implicit image-generation hosted tool off on image-tier models."""
+ """Round 21: forced-function `tool_choice` must also flip the implicit
+ image-generation hosted tool off on image-tier models."""
captured = _capture_body(
monkeypatch,
model = "gemini-2.5-flash-image",
@@ -4659,9 +4633,9 @@ def test_gemini_forced_function_tool_choice_drops_image_generation(monkeypatch):
def test_gemini_code_execution_native_part_list_replays_per_part_signatures(monkeypatch):
"""Round 21: merged code-execution history must replay per-part
- `thoughtSignature`s, not fan one top-level signature across every
- native subpart. Gemini 3 strict validators reject a signature
- placed on the wrong part."""
+ `thoughtSignature`s, not fan one top-level signature across every native
+ subpart. Gemini 3 strict validators reject a signature on the wrong
+ part."""
history = [
{"role": "user", "content": "plot 1+1"},
{
@@ -4711,7 +4685,7 @@ def test_gemini_code_execution_native_part_list_replays_per_part_signatures(monk
]
captured = _capture_body(monkeypatch, messages = history)
contents = captured["body"]["contents"]
- # Locate the assistant turn replayed as native code-exec parts.
+ # Find the assistant turn replayed as native code-exec parts.
assistant_turn = next(c for c in contents if c["role"] == "model")
parts = assistant_turn["parts"]
exec_parts = [p for p in parts if "executableCode" in p]
@@ -4723,11 +4697,11 @@ def test_gemini_code_execution_native_part_list_replays_per_part_signatures(monk
def test_gemini_code_execution_legacy_merged_signature_only_on_executable(monkeypatch):
- """Round 21: backward compatibility for pre-round-21 persisted
- history that stored merged `native_part` as a single object plus a
- top-level `thoughtSignature`. The replay branch must attach that
- signature only to `executableCode` (where Gemini 3 emits it), not
- fan it across `codeExecutionResult` / `inlineData`."""
+ """Round 21: backward compat for pre-round-21 persisted history that stored
+ merged `native_part` as a single object plus a top-level
+ `thoughtSignature`. The replay branch must attach that signature only to
+ `executableCode` (where Gemini 3 emits it), not fan it across
+ `codeExecutionResult` / `inlineData`."""
history = [
{"role": "user", "content": "plot 1+1"},
{
@@ -4779,10 +4753,10 @@ def test_gemini_code_execution_legacy_merged_signature_only_on_executable(monkey
def test_gemini_role_tool_list_content_flattens_to_result_text(monkeypatch):
- """Round 21: OpenAI-shape role=tool messages may carry list content
- like `[{"type":"text","text":"result"}]`. Forwarding those parts
- verbatim into `functionResponse.response.result` yields a list of
- content-part objects instead of the actual tool output text."""
+ """Round 21: OpenAI-shape role=tool messages may carry list content like
+ `[{"type":"text","text":"result"}]`. Forwarding those parts verbatim into
+ `functionResponse.response.result` yields a list of content-part objects
+ instead of the actual tool output text."""
history = [
{"role": "user", "content": "look up"},
{
@@ -4825,7 +4799,7 @@ def test_safe_fetch_image_threads_per_request_byte_budget(monkeypatch):
"""Round 21: the aggregate per-request byte cap must be passed into
`_safe_fetch_image_for_gemini` so an oversize URL is refused via
Content-Length (short-circuit) rather than fully downloaded then
- discarded after the fact."""
+ discarded."""
import socket
captured: dict = {"reads": 0, "content_length_seen": None}
@@ -4889,10 +4863,10 @@ def test_safe_fetch_image_threads_per_request_byte_budget(monkeypatch):
def test_openai_chat_delta_type_includes_tool_calls_and_extra_content():
"""Round 21: the frontend `OpenAIChatDelta` interface must expose
- `tool_calls` and `extra_content` so TypeScript callers can consume
- the Gemini-native stream fields without `any` casts. This test is
- a static-string assertion against the .ts source; mirrors how other
- frontend wire-contract tests are pinned from the backend suite."""
+ `tool_calls` and `extra_content` so TypeScript callers can consume the
+ Gemini-native stream fields without `any` casts. A static-string assertion
+ against the .ts source; mirrors how other frontend wire-contract tests are
+ pinned from the backend suite."""
import os
here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -4905,11 +4879,11 @@ def test_openai_chat_delta_type_includes_tool_calls_and_extra_content():
def test_anthropic_forced_function_tool_choice_drops_hosted_tools(monkeypatch):
- """Round 22: forced-function tool_choice must suppress Anthropic
- hosted builtins the same way it does for Gemini. Pinning a user
- function (`tool_choice={"type":"function","function":{"name":...}}`)
- while also passing `enabled_tools=["web_search","web_fetch",
- "code_execution"]` should not still fire those server-side."""
+ """Round 22: forced-function tool_choice must suppress Anthropic hosted
+ builtins like it does for Gemini. Pinning a user function
+ (`tool_choice={"type":"function","function":{"name":...}}`) while passing
+ `enabled_tools=["web_search","web_fetch","code_execution"]` should not still
+ fire those server-side."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -4945,8 +4919,8 @@ def test_anthropic_forced_function_tool_choice_drops_hosted_tools(monkeypatch):
_drive(run())
body = captured["body"] or {}
- # No hosted tools should be in the body — only the caller's user-
- # function declarations (which this test doesn't pass any of).
+ # No hosted tools in the body — only the caller's user-function
+ # declarations (none passed here).
tools = body.get("tools") or []
hosted_tool_names = {"web_search", "web_fetch", "code_execution"}
for tool in tools:
@@ -4954,9 +4928,9 @@ def test_anthropic_forced_function_tool_choice_drops_hosted_tools(monkeypatch):
def test_openrouter_forced_function_tool_choice_drops_web_plugin(monkeypatch):
- """Round 22: forced-function tool_choice must drop the OpenRouter
- web plugin too — caller pinned a user function, OpenRouter must not
- still attach the hosted web-search plugin."""
+ """Round 22: forced-function tool_choice must drop the OpenRouter web
+ plugin too — caller pinned a user function, so OpenRouter must not attach
+ the hosted web-search plugin."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -4996,10 +4970,10 @@ def test_openrouter_forced_function_tool_choice_drops_web_plugin(monkeypatch):
def test_kimi_forced_function_tool_choice_skips_web_search_helper(monkeypatch):
- """Round 22: forced-function tool_choice plus enabled_tools=
- ["web_search"] on Kimi must NOT route into `_stream_kimi_web_search`.
- Caller pinned a user function; hosted $web_search should be
- suppressed for the same privacy/billing reason."""
+ """Round 22: forced-function tool_choice plus enabled_tools=["web_search"]
+ on Kimi must NOT route into `_stream_kimi_web_search`. Caller pinned a user
+ function; hosted $web_search should be suppressed for the same
+ privacy/billing reason."""
routed_to_helper = {"called": False}
async def fake_helper(self, *args, **kwargs): # noqa: ARG001
@@ -5048,11 +5022,10 @@ def test_kimi_forced_function_tool_choice_skips_web_search_helper(monkeypatch):
def test_openai_responses_forced_function_tool_choice_drops_hosted_tools(monkeypatch):
- """Round 23: forced-function tool_choice on the OpenAI Responses
- path must suppress hosted builtins (web_search, shell,
- image_generation) the same way it does for Gemini / Anthropic /
- OpenRouter / Kimi. User-defined function tools still flow through
- so the pinned function can resolve."""
+ """Round 23: forced-function tool_choice on the OpenAI Responses path must
+ suppress hosted builtins (web_search, shell, image_generation) like it does
+ for Gemini / Anthropic / OpenRouter / Kimi. User-defined function tools
+ still flow through so the pinned function can resolve."""
captured: dict = {"body": None}
def handler(request: httpx.Request) -> httpx.Response:
@@ -5101,12 +5074,12 @@ def test_openai_responses_forced_function_tool_choice_drops_hosted_tools(monkeyp
hosted_types = {"web_search", "shell", "image_generation"}
hosted_seen = {t.get("type") for t in tools if isinstance(t, dict)}
assert not (hosted_seen & hosted_types), body
- # The user function declaration must still be present so the pin
- # has something to target.
+ # The user function declaration must still be present so the pin has a
+ # target.
user_function_seen = any(isinstance(t, dict) and t.get("type") == "function" for t in tools)
assert user_function_seen, body
- # And the forced-function tool_choice must be forwarded in Responses
- # shape: `{type:"function", name:"..."}`.
+ # And the forced-function tool_choice must be forwarded in Responses shape:
+ # `{type:"function", name:"..."}`.
tc = body.get("tool_choice")
assert isinstance(tc, dict) and tc.get("type") == "function", body
assert tc.get("name") == "lookup_record", body
@@ -5114,10 +5087,10 @@ def test_openai_responses_forced_function_tool_choice_drops_hosted_tools(monkeyp
def test_strip_provider_synthetic_tool_history_drops_text_only_extra_content():
"""Round 24: a plain text Gemini reply (no tool_calls) carrying
- `extra_content.google.thought_signature` must still have that
- metadata stripped before being forwarded to a local llama-server
- backend. Without this, switching a Gemini thread mid-stream to a
- local GGUF model leaks Gemini-only fields to llama-server."""
+ `extra_content.google.thought_signature` must still have that metadata
+ stripped before being forwarded to a local llama-server backend. Without
+ it, switching a Gemini thread mid-stream to a local GGUF model leaks
+ Gemini-only fields to llama-server."""
from routes.inference import _strip_provider_synthetic_tool_history
messages = [
@@ -5139,10 +5112,10 @@ def test_strip_provider_synthetic_tool_history_drops_text_only_extra_content():
def test_validate_and_resolve_host_blocks_shared_address_space():
"""Round 24 SSRF P1: 100.64.0.0/10 carrier-grade NAT addresses are
- `is_private=False` AND `is_global=False` per Python's ipaddress
- docs. The previous denylist (is_private/loopback/link_local/etc.)
- missed them. Adding `not ip.is_global` as the primary gate covers
- all non-public ranges, current and future."""
+ `is_private=False` AND `is_global=False` per Python's ipaddress docs. The
+ old denylist (is_private/loopback/link_local/etc.) missed them. Adding `not
+ ip.is_global` as the primary gate covers all non-public ranges, current and
+ future."""
import socket as _socket
from core.inference import tools as _tools
@@ -5171,13 +5144,12 @@ def test_validate_and_resolve_host_blocks_shared_address_space():
def test_gemini_custom_oai_compat_base_skips_native_allowlist():
- """Round 24: a custom Gemini OAI-compatible base (LiteLLM/proxy)
- must NOT have its model list filtered through the native Gemini
- allowlist regex. A LiteLLM gateway returning
- `["google/gemini-2.5-flash", "my-team/gemini", "gemini-2.5-flash"]`
- should be passed through; the native filter would strip the
- prefixed IDs even though the chat dispatch routes them via the
- OpenAI-compatible client."""
+ """Round 24: a custom Gemini OAI-compatible base (LiteLLM/proxy) must NOT
+ have its model list filtered through the native Gemini allowlist regex. A
+ LiteLLM gateway returning
+ `["google/gemini-2.5-flash", "my-team/gemini", "gemini-2.5-flash"]` should
+ pass through; the native filter would strip the prefixed IDs even though
+ chat dispatch routes them via the OpenAI-compatible client."""
import asyncio as _asyncio
from routes import providers as _providers
@@ -5213,18 +5185,18 @@ def test_gemini_custom_oai_compat_base_skips_native_allowlist():
finally:
_providers.ExternalProviderClient = orig
ids = {m.id for m in result}
- # All three IDs survive — the native allowlist was bypassed.
+ # All three IDs survive — native allowlist bypassed.
assert "google/gemini-2.5-flash" in ids, ids
assert "my-team/gemini" in ids, ids
assert "gemini-2.5-flash" in ids, ids
def test_strip_provider_synthetic_tool_history_drops_synthetic_only():
- """Round 22: switching a thread from native Gemini (code_execution
- / image_generation tool_cards in history) to a local GGUF backend
- must strip the synthetic tool_calls + matching role=tool replies
- before llama-server sees them. Real user-function tool_calls and
- their matching tool replies must survive."""
+ """Round 22: switching a thread from native Gemini (code_execution /
+ image_generation tool_cards in history) to a local GGUF backend must strip
+ the synthetic tool_calls + matching role=tool replies before llama-server
+ sees them. Real user-function tool_calls and their matching tool replies
+ must survive."""
from routes.inference import _strip_provider_synthetic_tool_history
messages = [
@@ -5282,9 +5254,9 @@ def test_strip_provider_synthetic_tool_history_drops_synthetic_only():
def test_strip_provider_synthetic_tool_history_drops_empty_assistant():
- """If every tool_call was synthetic and the assistant turn had no
- content, the entire turn must be dropped (llama-server rejects
- empty assistant messages with no tool_calls)."""
+ """If every tool_call was synthetic and the assistant turn had no content,
+ the entire turn must be dropped (llama-server rejects empty assistant
+ messages with no tool_calls)."""
from routes.inference import _strip_provider_synthetic_tool_history
messages = [
@@ -5323,18 +5295,17 @@ def test_strip_provider_synthetic_tool_history_drops_empty_assistant():
]
out = _strip_provider_synthetic_tool_history(messages)
roles = [m.get("role") for m in out]
- # The synthetic assistant + its tool reply are both gone; only the
- # two user turns survive.
+ # Synthetic assistant + its tool reply are both gone; only the two user
+ # turns survive.
assert roles == ["user", "user"], out
def test_openrouter_no_synthetic_web_search_event_on_forced_function_tool_choice(monkeypatch):
- """Round 22 sibling of the round-20 `tool_choice='none'` test: when
- the caller forces a specific function via `tool_choice={"type":
- "function", ...}` AND passes `enabled_tools=["web_search"]`, the
- OpenRouter path must NOT synthesize a fake `web_search` tool card.
- The plugin was not attached upstream so the UI must not see a
- server-tool card."""
+ """Round 22 sibling of the round-20 `tool_choice='none'` test: when the
+ caller forces a specific function via `tool_choice={"type":"function", ...}`
+ AND passes `enabled_tools=["web_search"]`, the OpenRouter path must NOT
+ synthesize a fake `web_search` tool card. The plugin wasn't attached
+ upstream, so the UI must not see a server-tool card."""
captured_events: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
diff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.py
index 08f22edb181..d3d43877202 100644
--- a/studio/backend/tests/test_gguf_metadata.py
+++ b/studio/backend/tests/test_gguf_metadata.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
-"""Tests for :mod:`utils.models.gguf_metadata`. Synthesise small GGUF
-headers in tmp dirs so we never depend on real model files."""
+"""Tests for :mod:`utils.models.gguf_metadata`. Synthesise small GGUF headers
+in tmp dirs so we never depend on real model files."""
from __future__ import annotations
@@ -140,7 +140,7 @@ def test_metadata_is_cached(tmp_path: Path):
)
first = read_gguf_general_metadata(str(p))
assert first == {"general.basename": "First"}
- # Force size change so the (path, mtime, size) key invalidates.
+ # Change size so the (path, mtime, size) cache key invalidates.
_write_synthetic_gguf(
tmp_path / "model.gguf",
{"general.basename": "Second", "general.organization": "X"},
diff --git a/studio/backend/tests/test_gguf_reload_inheritance.py b/studio/backend/tests/test_gguf_reload_inheritance.py
index 1a663725d99..500bfc2d4c7 100644
--- a/studio/backend/tests/test_gguf_reload_inheritance.py
+++ b/studio/backend/tests/test_gguf_reload_inheritance.py
@@ -3,11 +3,10 @@
"""Backend contract for the GGUF reload duplicate-load guard.
-``LlamaCppBackend._already_in_target_state`` is the in-process
-short-circuit that prevents a serialised duplicate /load from killing
-the just-spawned llama-server. These tests pin the local-file
-identity, the HF-mode hf_variant fallback, and the ``extra_args``
-None-vs-[] inherit semantics so the guard cannot silently regress.
+``LlamaCppBackend._already_in_target_state`` is the in-process short-circuit
+preventing a serialised duplicate /load from killing the just-spawned
+llama-server. Pins local-file identity, the HF-mode hf_variant fallback, and
+``extra_args`` None-vs-[] inherit semantics so the guard cannot regress.
"""
from __future__ import annotations
diff --git a/studio/backend/tests/test_gguf_routing.py b/studio/backend/tests/test_gguf_routing.py
index 1b299cba193..c640218943d 100644
--- a/studio/backend/tests/test_gguf_routing.py
+++ b/studio/backend/tests/test_gguf_routing.py
@@ -4,10 +4,9 @@
"""
Tests for GGUF routing in detect_gguf_model.
-Regression test for the bug where a .gguf file temporarily appears
-inaccessible on Windows during llama-server process teardown, causing
-is_file() to return False and the model to be routed to the transformers
-backend instead of llama-server.
+Regression test: on Windows a .gguf file can briefly appear inaccessible
+during llama-server teardown, making is_file() return False and routing
+the model to the transformers backend instead of llama-server.
"""
import sys
@@ -16,7 +15,7 @@ import types
from pathlib import Path
from unittest.mock import patch
-# Stub structlog before importing backend modules (mirrors other tests in this suite)
+# Stub structlog before importing backend modules (as in other suite tests)
if "structlog" not in sys.modules:
class _DummyLogger:
@@ -44,10 +43,10 @@ def test_detects_gguf_file_normally(tmp_path):
def test_detects_gguf_when_stat_raises_oserror(tmp_path):
"""
- Regression: on Windows, both is_file() and exists() call stat() internally.
- During the brief lock window after llama-server is killed, stat() raises
- OSError, causing both to return False. detect_gguf_model must still route
- to llama-server based on the file extension alone.
+ Regression: on Windows both is_file() and exists() call stat() internally.
+ In the brief lock window after llama-server is killed, stat() raises
+ OSError so both return False. detect_gguf_model must still route to
+ llama-server based on the file extension alone.
"""
gguf = tmp_path / "gpt-oss-20b-MXFP4.gguf"
gguf.write_bytes(b"")
diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.py
index 90020efe437..cb26330ed05 100644
--- a/studio/backend/tests/test_gpu_selection.py
+++ b/studio/backend/tests/test_gpu_selection.py
@@ -181,7 +181,7 @@ class TestVisibleGpuUtilization(_GpuCacheResetMixin, unittest.TestCase):
self.assertAlmostEqual(result["devices"][1]["memory_total_gb"], 29.3, places = 1)
def test_uuid_parent_visibility_falls_back_to_torch(self):
- """UUID/MIG masks should fall through nvidia to torch fallback and
+ """UUID/MIG masks fall through nvidia to the torch fallback and
still report visible devices using relative ordinals."""
fake_torch_devices = [
{
@@ -1338,7 +1338,7 @@ class TestEstimateFp16ModelSizeBytesPrefersLocalWeights(unittest.TestCase):
self.assertEqual(src, "weight_bytes")
def test_equal_local_and_config_keeps_config_label(self):
- # why: tie-breaker is "local must be strictly larger" so an exact
+ # Tie-breaker is "local must be strictly larger", so an exact
# match keeps the config-derived path.
same = 8 * (1 << 30)
bytes_, src = self._run(
diff --git a/studio/backend/tests/test_gpu_selection_sandbox.py b/studio/backend/tests/test_gpu_selection_sandbox.py
index 073f8d94371..733933271bd 100644
--- a/studio/backend/tests/test_gpu_selection_sandbox.py
+++ b/studio/backend/tests/test_gpu_selection_sandbox.py
@@ -2,9 +2,9 @@
"""
Sandbox test for multi-GPU selection logic.
-Tests the core GPU selection, memory estimation, and device_map logic
-in an isolated environment. Can be run on Linux, macOS, and Windows
-without requiring actual GPUs -- all hardware calls are mocked.
+Tests GPU selection, memory estimation, and device_map logic in
+isolation. Runs on Linux, macOS, and Windows without real GPUs -- all
+hardware calls are mocked.
Usage:
python -m pytest studio/backend/tests/test_gpu_selection_sandbox.py -v
@@ -18,7 +18,7 @@ import unittest
from pathlib import Path
from unittest.mock import patch, MagicMock
-# Ensure backend is on sys.path
+# Ensure backend is on sys.path.
_backend_root = Path(__file__).resolve().parent.parent
if str(_backend_root) not in sys.path:
sys.path.insert(0, str(_backend_root))
@@ -33,7 +33,7 @@ def _make_fake_config(
num_key_value_heads = 8,
tie_word_embeddings = False,
):
- """Create a fake HF config-like object for estimation tests."""
+ """Fake HF config-like object for estimation tests."""
from types import SimpleNamespace
return SimpleNamespace(
vocab_size = vocab_size,
@@ -47,7 +47,7 @@ def _make_fake_config(
class TestEstimateFP16ModelSizeFromConfig(unittest.TestCase):
- """Test the config-based model size estimation."""
+ """Config-based model size estimation."""
def test_llama_8b_size_reasonable(self):
from utils.hardware.hardware import _estimate_fp16_model_size_bytes_from_config
@@ -90,7 +90,7 @@ class TestEstimateFP16ModelSizeFromConfig(unittest.TestCase):
from utils.hardware.hardware import _estimate_fp16_model_size_bytes_from_config
from types import SimpleNamespace
- config = SimpleNamespace(vocab_size = 32000) # Missing most fields
+ config = SimpleNamespace(vocab_size = 32000) # most fields missing
size = _estimate_fp16_model_size_bytes_from_config(config)
self.assertIsNone(size)
@@ -117,7 +117,7 @@ class TestEstimateFP16ModelSizeFromConfig(unittest.TestCase):
class TestEstimateRequiredModelMemory(unittest.TestCase):
- """Test memory requirement estimation."""
+ """Memory requirement estimation."""
def test_inference_fp16_uses_1_3x(self):
from utils.hardware.hardware import estimate_required_model_memory_gb
@@ -189,10 +189,10 @@ class TestEstimateRequiredModelMemory(unittest.TestCase):
class TestAutoSelectGpuIds(unittest.TestCase):
- """Test automatic GPU selection based on model size and free memory."""
+ """Automatic GPU selection by model size and free memory."""
def _make_utilization(self, devices):
- """Create a fake utilization response."""
+ """Fake utilization response."""
return {
"available": True,
"devices": [
@@ -304,7 +304,7 @@ class TestAutoSelectGpuIds(unittest.TestCase):
class TestGetDeviceMap(unittest.TestCase):
- """Test device_map string generation."""
+ """device_map string generation."""
def test_single_gpu_returns_sequential(self):
from utils.hardware.hardware import get_device_map
@@ -341,7 +341,7 @@ class TestGetDeviceMap(unittest.TestCase):
class TestResolveRequestedGpuIds(unittest.TestCase):
- """Test GPU ID validation."""
+ """GPU ID validation."""
def test_none_returns_parent_visible(self):
from utils.hardware.hardware import resolve_requested_gpu_ids
@@ -390,7 +390,7 @@ class TestResolveRequestedGpuIds(unittest.TestCase):
class TestApplyGpuIds(unittest.TestCase):
- """Test CUDA_VISIBLE_DEVICES environment variable setting."""
+ """CUDA_VISIBLE_DEVICES environment variable setting."""
def test_apply_list(self):
from utils.hardware.hardware import apply_gpu_ids
@@ -407,10 +407,10 @@ class TestApplyGpuIds(unittest.TestCase):
class TestMultiGpuOverheadAccounting(unittest.TestCase):
- """Test that multi-GPU overhead is applied correctly.
+ """Multi-GPU overhead is applied correctly.
- The first GPU should keep its full free memory, and only
- additional GPUs should have the overhead factor applied.
+ The first GPU keeps its full free memory; the overhead factor applies
+ only to additional GPUs.
"""
def _make_utilization(self, devices):
diff --git a/studio/backend/tests/test_host_defaults.py b/studio/backend/tests/test_host_defaults.py
index 02bb54df56f..c66385721e3 100644
--- a/studio/backend/tests/test_host_defaults.py
+++ b/studio/backend/tests/test_host_defaults.py
@@ -35,10 +35,10 @@ def _parse_function_param_defaults(source: str, func_name: str) -> dict:
def _parse_argparse_add_argument_default(source: str, option_name: str):
- """Return the 'default' kwarg value for add_argument(option_name, ...) in *source*.
+ """Return the 'default' kwarg for add_argument(option_name, ...) in *source*.
- Walks the entire module so the call can live in __main__ or in a helper
- function — only handles ast.Constant defaults.
+ Walks the whole module so the call may live in __main__ or a helper;
+ only handles ast.Constant defaults.
"""
tree = ast.parse(source)
for node in ast.walk(tree):
@@ -59,12 +59,12 @@ def _parse_argparse_add_argument_default(source: str, option_name: str):
def test_run_server_default_host_is_loopback():
- """run_server() parameter default for 'host' must be 127.0.0.1, not 0.0.0.0.
+ """run_server() 'host' default must be 127.0.0.1, not 0.0.0.0.
- Binding to 0.0.0.0 by default exposes the service on all network
- interfaces, contradicting the documented "privacy first / 100% local"
- guarantee. Loopback (127.0.0.1) is the least-permissive default;
- users who need network access can pass -H 0.0.0.0 explicitly.
+ Binding to 0.0.0.0 by default exposes the service on all interfaces,
+ contradicting the "privacy first / 100% local" guarantee. Loopback
+ (127.0.0.1) is the least-permissive default; users who need network
+ access can pass -H 0.0.0.0 explicitly.
"""
source = _RUN_PY.read_text()
defaults = _parse_function_param_defaults(source, "run_server")
@@ -81,7 +81,7 @@ def test_argparse_default_host_is_loopback():
"""argparse --host add_argument default must be 127.0.0.1.
When run.py is invoked directly (python run.py), the argparse default
- should match the function default so direct execution is equally safe.
+ must match the function default so direct execution is equally safe.
"""
source = _RUN_PY.read_text()
host_default = _parse_argparse_add_argument_default(source, "--host")
diff --git a/studio/backend/tests/test_index_bootstrap_origin.py b/studio/backend/tests/test_index_bootstrap_origin.py
index b36e3fceddd..85b785ee109 100644
--- a/studio/backend/tests/test_index_bootstrap_origin.py
+++ b/studio/backend/tests/test_index_bootstrap_origin.py
@@ -61,8 +61,8 @@ def test_is_same_origin_request_port_mismatch_is_cross_origin():
def test_is_same_origin_request_https_default_port_stripped_on_origin():
- """RFC 6454 strips default ports on Origin; Starlette's netloc may still
- carry ``:443``. Canonicalise both sides so this stays same-origin.
+ """RFC 6454 strips default ports on Origin; Starlette netloc may keep
+ ``:443``. Canonicalise both sides so this stays same-origin.
"""
from main import _is_same_origin_request
@@ -109,7 +109,7 @@ def test_is_same_origin_request_null_origin_is_cross_origin():
def test_is_same_origin_request_unparseable_origin_is_cross_origin():
- """Garbage values without a host fall to cross-origin; a malformed header
+ """Hostless garbage falls to cross-origin; a malformed header
must not leak the bootstrap.
"""
from main import _is_same_origin_request
@@ -120,8 +120,7 @@ def test_is_same_origin_request_unparseable_origin_is_cross_origin():
def test_is_same_origin_request_userinfo_in_netloc_ignored():
"""``user:pass@host:port`` netlocs (RFC 3986) must compare equal to the
- credentials-less Origin.
- """
+ credentials-less Origin."""
from main import _is_same_origin_request
req = _build_request("user:[email protected]:80", origin = "http://example.com")
diff --git a/studio/backend/tests/test_index_bootstrap_origin_extra.py b/studio/backend/tests/test_index_bootstrap_origin_extra.py
index 71fdbad930b..feda88c14c5 100644
--- a/studio/backend/tests/test_index_bootstrap_origin_extra.py
+++ b/studio/backend/tests/test_index_bootstrap_origin_extra.py
@@ -2,9 +2,9 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Extra edge-case coverage for the bootstrap-pw cross-origin gate.
-Companion to ``test_index_bootstrap_origin.py``: IPv6 netlocs, opaque
-origins (``data:``, ``blob:``), comma-joined multi-Origin headers, and
-the ``localhost`` vs ``127.0.0.1`` distinct-origin rule.
+Companion to ``test_index_bootstrap_origin.py``: IPv6 netlocs, opaque origins
+(``data:``, ``blob:``), comma-joined multi-Origin headers, and the
+``localhost`` vs ``127.0.0.1`` distinct-origin rule.
"""
from unittest.mock import MagicMock
@@ -28,7 +28,7 @@ def _build_request(
def test_is_same_origin_request_ipv6_loopback_same_origin():
"""Studio supports ``-H ::1`` binds; netloc is ``[::1]:8902``. Bare
``partition(":")`` mis-parses the bracketed form and would refuse the
- bootstrap on legitimate same-origin nav.
+ bootstrap on legitimate same-origin navigation.
"""
from main import _is_same_origin_request
@@ -88,9 +88,7 @@ def test_is_same_origin_request_ipv6_userinfo_stripped():
def test_is_same_origin_request_data_url_origin_is_cross_origin():
- """``data:`` URLs are opaque origins (HTML living standard); no host,
- never same-origin.
- """
+ """``data:`` URLs are opaque origins (HTML living standard); no host, never same-origin."""
from main import _is_same_origin_request
req = _build_request("127.0.0.1:8902", origin = "data:text/html,<script>alert(1)</script>")
@@ -98,9 +96,7 @@ def test_is_same_origin_request_data_url_origin_is_cross_origin():
def test_is_same_origin_request_blob_url_origin_is_cross_origin():
- """``blob:`` URLs carry the inner origin only in non-canonical form; the
- canonical comparison rejects them.
- """
+ """``blob:`` URLs carry the inner origin only in non-canonical form; the canonical comparison rejects them."""
from main import _is_same_origin_request
req = _build_request("127.0.0.1:8902", origin = "blob:http://127.0.0.1:8902/uuid")
@@ -108,8 +104,8 @@ def test_is_same_origin_request_blob_url_origin_is_cross_origin():
def test_is_same_origin_request_file_url_origin_is_cross_origin():
- """``file://`` pages usually send ``Origin: null``; historical engines
- sent ``Origin: file://``. Neither is same-origin vs an http listener.
+ """``file://`` pages usually send ``Origin: null``; older engines sent
+ ``Origin: file://``. Neither is same-origin vs an http listener.
"""
from main import _is_same_origin_request
@@ -121,8 +117,8 @@ def test_is_same_origin_request_file_url_origin_is_cross_origin():
def test_is_same_origin_request_comma_joined_origins_cross_origin():
- """Starlette concatenates repeated headers with ``, ``; the canonical
- parser can't safely split this, so it falls to cross-origin.
+ """Starlette joins repeated headers with ``, ``; the canonical parser can't
+ safely split this, so it falls to cross-origin.
"""
from main import _is_same_origin_request
@@ -137,8 +133,8 @@ def test_is_same_origin_request_comma_joined_origins_cross_origin():
def test_is_same_origin_request_localhost_vs_127_is_cross_origin():
- """Browsers treat ``localhost`` and ``127.0.0.1`` as distinct origins;
- the canonical comparison must not DNS-collapse them.
+ """Browsers treat ``localhost`` and ``127.0.0.1`` as distinct origins; the
+ canonical comparison must not DNS-collapse them.
"""
from main import _is_same_origin_request
@@ -157,7 +153,7 @@ def test_is_same_origin_request_127_vs_localhost_is_cross_origin():
def test_is_same_origin_request_malformed_ipv6_bracket_is_cross_origin():
"""``urlparse`` raises ``ValueError('Invalid IPv6 URL')`` on unclosed
- brackets (CVE-2024-11168 hardening). The gate must swallow and fall to
+ brackets (CVE-2024-11168 hardening). The gate must swallow it and fall to
cross-origin rather than 500 the SPA handler.
"""
from main import _is_same_origin_request
@@ -184,8 +180,8 @@ def test_is_same_origin_request_bracket_with_trailing_garbage_is_cross_origin():
def test_is_same_origin_request_empty_origin_header_is_cross_origin():
- """Explicit empty ``Origin:`` is not a valid serialised origin and must
- not be conflated with a missing header; cross-origin, bootstrap withheld.
+ """Explicit empty ``Origin:`` is not a valid serialised origin and must not
+ be conflated with a missing header; cross-origin, bootstrap withheld.
"""
from main import _is_same_origin_request
diff --git a/studio/backend/tests/test_inference_model_validation.py b/studio/backend/tests/test_inference_model_validation.py
index faf5a67873e..dddf5c8052b 100644
--- a/studio/backend/tests/test_inference_model_validation.py
+++ b/studio/backend/tests/test_inference_model_validation.py
@@ -170,16 +170,15 @@ def test_walkback_does_not_cross_user_turn():
]
)
last = req.messages[-1].tool_call_id
- # The walkback must NOT pick old_call because a user turn intervenes;
- # falls back to synth.
+ # Walkback must NOT pick old_call across a user turn; falls back to synth.
assert last is not None
assert last != "old_call"
assert last.startswith("call_")
def test_walkback_skips_explicitly_consumed_tool_call_id():
- """Sibling tool result with an explicit id must reserve its assistant
- slot so a follow-up missing-id result picks the OTHER tool call."""
+ """An explicit-id tool result reserves its assistant slot so a
+ follow-up missing-id result picks the OTHER tool call."""
req = _req(
[
{
diff --git a/studio/backend/tests/test_kv_cache_estimation.py b/studio/backend/tests/test_kv_cache_estimation.py
index 001b5f1beee..cd679b0bf11 100644
--- a/studio/backend/tests/test_kv_cache_estimation.py
+++ b/studio/backend/tests/test_kv_cache_estimation.py
@@ -7,8 +7,7 @@ Covers the GGUF metadata parser, _can_estimate_kv gate, all 5 estimation
paths (MLA, Hybrid Mamba, Sliding Window, Standard GQA, Legacy), KV cache
quantization, edge cases, and lifecycle (init/unload/reparse).
-Requires no GPU, network, or external libraries beyond pytest.
-Cross-platform: Linux, macOS, Windows, WSL.
+No GPU, network, or libraries beyond pytest. Cross-platform.
"""
import io
@@ -21,8 +20,8 @@ from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_native_context_length.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_native_context_length.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -38,11 +37,10 @@ sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
sys.modules.setdefault("structlog", _structlog_stub)
-# httpx -- only stub when the real library isn't installed. Stubbing
-# unconditionally would shadow ``HTTPError`` / ``Response`` etc. that
-# ``huggingface_hub.errors`` imports at module load time, which causes
-# the transformers introspection tier to silently return None inside
-# the test process.
+# httpx -- only stub when the real library isn't installed. Stubbing
+# unconditionally shadows ``HTTPError`` / ``Response`` etc. that
+# ``huggingface_hub.errors`` imports at load time, making the transformers
+# introspection tier silently return None in the test process.
try:
import httpx as _httpx_real # noqa: F401
except ImportError:
@@ -84,9 +82,9 @@ from core.inference.llama_cpp import LlamaCppBackend
def _make_gguf_bytes(arch: str, kv_pairs: dict) -> bytes:
- """Build a minimal GGUF v3 binary blob with the given KV metadata.
+ """Build a minimal GGUF v3 blob with the given KV metadata.
- Supports the scalar and simple array metadata used by the parser.
+ Supports the scalar and simple array metadata the parser uses.
"""
buf = io.BytesIO()
# Header: magic, version, tensor_count, kv_count
@@ -134,9 +132,8 @@ def _backend_from_gguf(
) -> LlamaCppBackend:
"""Create a LlamaCppBackend with parsed GGUF metadata from given fields.
- `general` lets a test inject extra `general.*` metadata (used to
- verify the dynamic SWA resolver picks up source-repo hints from
- GGUFs that ship them).
+ `general` injects extra `general.*` metadata, to verify the dynamic
+ SWA resolver picks up source-repo hints from GGUFs that ship them.
"""
kv = {"general.architecture": arch}
for k, v in (general or {}).items():
@@ -163,7 +160,7 @@ def _backend_from_gguf(
class TestGGUFParserNewFields:
- """Verify that architecture-aware fields are correctly parsed."""
+ """Architecture-aware fields are parsed correctly."""
@pytest.mark.parametrize(
"field,gguf_key,value",
@@ -217,9 +214,9 @@ class TestGGUFParserNewFields:
)
# Per-layer KV head count is preserved exactly...
assert b._n_kv_heads_by_layer == [8, 8, 8, 8, 8, 2]
- # ...and mirrored into the scalar field as a conservative max so
- # non-SWA estimator paths and any caller using
- # `n_kv = self._n_kv_heads or ...` get a safe upper bound.
+ # ...and mirrored into the scalar field as a conservative max, so
+ # non-SWA paths and callers using `n_kv = self._n_kv_heads or ...`
+ # get a safe upper bound.
assert b._n_kv_heads == 8
assert b._sliding_window_pattern == [True, True, True, True, True, False]
@@ -270,7 +267,7 @@ class TestArchSwaPatternDefaults:
assert b._sliding_window_pattern is None
def test_explicit_pattern_overrides_arch_default(self):
- # Period=6 is the gemma3 default; the explicit array must win.
+ # gemma3 default is period=6; the explicit array must win.
b = _backend_from_gguf(
"gemma3",
{
@@ -310,8 +307,8 @@ class TestArchSwaPatternDefaults:
"arch", ["llama", "qwen2", "qwen3", "mistral", "mistral3", "glm4", "llama4"]
)
def test_non_swa_arch_uses_full_attention_path(self, arch):
- # Pure-GQA arches: GGUF has no sliding_window, no synthetic
- # pattern, estimator hits Path 4.
+ # Pure-GQA arches: no sliding_window, no synthetic pattern,
+ # estimator hits Path 4.
b = _backend_from_gguf(
arch,
{
@@ -340,7 +337,7 @@ class TestArchSwaPatternDefaults:
"embedding_length": 5376,
}
with_default = _backend_from_gguf("gemma3", common)
- # Arch not in the table -> legacy 1/4 path.
+ # Arch not in table -> legacy 1/4 path.
without_default = _backend_from_gguf("totallymadeupv7", common)
kv_default = with_default._estimate_kv_cache_bytes(131072, "f16")
@@ -430,7 +427,7 @@ class TestDynamicSwaResolver:
def test_period_from_layer_types_finds_smallest_period(self):
from core.inference.llama_cpp import _period_from_layer_types
- # gemma3 (1 global per 6), gpt-oss (alternating), gemma3n (1 per 5).
+ # gemma3 (1 global/6), gpt-oss (alternating), gemma3n (1/5).
assert _period_from_layer_types((["sliding_attention"] * 5 + ["full_attention"]) * 4) == 6
assert _period_from_layer_types(["sliding_attention", "full_attention"] * 12) == 2
assert _period_from_layer_types((["sliding_attention"] * 4 + ["full_attention"]) * 7) == 5
@@ -481,14 +478,14 @@ class TestDynamicSwaResolver:
def test_disk_cache_takes_precedence_over_bootstrap(self, monkeypatch, tmp_path):
self._isolate_cache(monkeypatch, tmp_path)
- # Override bootstrap=6 with a cached period=3.
+ # Cached period=3 overrides bootstrap=6.
with open(tmp_path / "swa_cache.json", "w") as f:
json.dump({"gemma3": 3}, f)
b = _backend_from_gguf("gemma3", dict(_SWA_FIELDS, block_count = 18))
assert b._sliding_window_pattern == [(i + 1) % 3 != 0 for i in range(18)]
def test_disk_cache_supports_array_entries(self, monkeypatch, tmp_path):
- # Aperiodic mask gets tiled across n_layers.
+ # Aperiodic mask is tiled across n_layers.
self._isolate_cache(monkeypatch, tmp_path)
mask = [True, False, True, True, False, True, False, False]
with open(tmp_path / "swa_cache.json", "w") as f:
@@ -556,7 +553,7 @@ class TestDynamicSwaResolver:
from core.inference import llama_cpp as lc
monkeypatch.setattr(lc, "_fetch_swa_entry_from_hf", lambda repo_id: None)
- # Force the failure into the Tier 3 path; bypass Tier 2.5.
+ # Force failure into Tier 3; bypass Tier 2.5.
monkeypatch.setattr(lc, "_resolve_swa_entry_from_transformers", lambda arch: None)
b = _backend_from_gguf(
"newmodel",
@@ -639,7 +636,7 @@ class TestTransformersIntrospection:
assert _resolve_swa_entry_from_transformers("totally-fake-arch-xyz") is None
def test_full_resolver_uses_transformers_before_hf_fetch(self, monkeypatch, tmp_path):
- # With bootstrap empty, Tier 2.5 must answer before Tier 3 fires.
+ # Bootstrap empty: Tier 2.5 must answer before Tier 3 fires.
self._isolate_cache(monkeypatch, tmp_path)
from core.inference import llama_cpp as lc
@@ -660,10 +657,10 @@ class TestTransformersIntrospection:
class TestGGUFParserReset:
- """Verify that fields are properly reset between parses."""
+ """Fields are reset between parses."""
def test_reset_between_parses(self):
- # First parse with all fields
+ # First parse: all fields set
b = _backend_from_gguf(
"arch1",
{
@@ -685,7 +682,7 @@ class TestGGUFParserReset:
assert b._kv_value_length_swa == 64
assert b._ssm_inner_size == 4096
- # Second parse without those fields -- they should be None
+ # Second parse without those fields -- they must be None
kv = {"general.architecture": "arch2", "arch2.block_count": 64}
import tempfile, os
@@ -713,7 +710,7 @@ class TestGGUFParserReset:
class TestCanEstimateKV:
- """Verify gate logic for all field combinations."""
+ """Gate logic for all field combinations."""
def test_no_layers_returns_false(self):
b = LlamaCppBackend()
@@ -729,7 +726,7 @@ class TestCanEstimateKV:
assert b._can_estimate_kv()
def test_key_length_alone_insufficient(self):
- """key_length without value_length should NOT be enough."""
+ """key_length without value_length is NOT enough."""
b = LlamaCppBackend()
b._n_layers = 32
b._kv_key_length = 128
@@ -799,33 +796,33 @@ class TestMLAEstimation:
assert b._estimate_kv_cache_bytes(163840, "f16") == expected
def test_mla_ignores_value_length(self):
- """MLA should NOT add value_length -- V is reconstructed from the latent."""
+ """MLA must NOT add value_length -- V is reconstructed from the latent."""
b = self._mla_backend()
result = b._estimate_kv_cache_bytes(1000, "f16")
- # Should be n_layers * ctx * 1 * key_len(576) * 2
+ # n_layers * ctx * 1 * key_len(576) * 2
expected = 61 * 1000 * 1 * 576 * 2
assert result == expected
def test_mla_fallback_when_no_key_length(self):
- """If key_length is missing, fallback to kv_lora_rank + key_length_mla."""
+ """No key_length: fall back to kv_lora_rank + key_length_mla."""
b = self._mla_backend(_kv_key_length = None)
- # _key_length_mla=192 in default, so rope_dim=192
+ # default _key_length_mla=192, so rope_dim=192
result = b._estimate_kv_cache_bytes(1000, "f16")
expected = 61 * 1000 * 1 * (512 + 192) * 2 # 704
assert result == expected
def test_mla_fallback_no_key_length_mla(self):
- """If both key_length and key_length_mla are missing, fallback to +64."""
+ """No key_length and no key_length_mla: fall back to +64."""
b = self._mla_backend(_kv_key_length = None, _key_length_mla = None)
result = b._estimate_kv_cache_bytes(1000, "f16")
expected = 61 * 1000 * 1 * (512 + 64) * 2 # 576
assert result == expected
def test_mla_defaults_n_kv_to_1_when_heads_absent(self):
- """MLA should use n_kv=1 even if n_kv_heads is None (not n_heads)."""
+ """MLA uses n_kv=1 even if n_kv_heads is None (not n_heads)."""
b = self._mla_backend(_n_kv_heads = None) # n_heads=128 still set
result = b._estimate_kv_cache_bytes(1000, "f16")
- # Should use n_kv_mla=1, NOT n_heads=128
+ # Uses n_kv_mla=1, NOT n_heads=128
expected = 61 * 1000 * 1 * 576 * 2
assert result == expected
@@ -883,14 +880,14 @@ class TestHybridMambaEstimation:
assert b._estimate_kv_cache_bytes(262144, "f16") == expected
def test_hybrid_without_explicit_dims(self):
- """Fallback to head_dim when key_length/value_length are missing."""
+ """Fall back to head_dim when key_length/value_length are missing."""
b = self._hybrid_backend(_kv_key_length = None, _kv_value_length = None)
head_dim = 5120 // 24 # 213
expected = 16 * 4096 * 4 * 2 * head_dim * 2
assert b._estimate_kv_cache_bytes(4096, "f16") == expected
def test_fai_zero_safety(self):
- """full_attention_interval=0 should not cause ZeroDivisionError."""
+ """full_attention_interval=0 must not ZeroDivisionError."""
b = self._hybrid_backend(_full_attention_interval = 0)
result = b._estimate_kv_cache_bytes(4096, "f16")
# fai=0 -> n_attn = n_layers (all layers)
@@ -978,7 +975,7 @@ class TestSlidingWindowEstimation:
assert b._estimate_kv_cache_bytes(ctx, "f16") == expected(ctx)
def test_ctx_smaller_than_window(self):
- """When context < 2 * sliding_window, SWA cache caps at ctx."""
+ """When ctx < 2 * sliding_window, SWA cache caps at ctx."""
b = self._swa_backend(_sliding_window = 8192)
n_global = max(1, 62 // 4) # 15
n_swa = 62 - n_global # 47
@@ -1031,11 +1028,11 @@ class TestStandardGQAEstimation:
assert b._estimate_kv_cache_bytes(4096, "f16") == expected
def test_differs_from_legacy(self):
- """GQA path should differ from legacy when key_length != embed//n_heads."""
+ """GQA path differs from legacy when key_length != embed//n_heads."""
b = self._gqa_backend()
head_dim = 1024 // 16 # 64
gqa_result = b._estimate_kv_cache_bytes(4096, "f16")
- # Legacy would use: 2 * 8 * 64 * 28 * 4096 * 2
+ # Legacy: 2 * 8 * 64 * 28 * 4096 * 2
legacy_result = int(2 * 8 * head_dim * 28 * 4096 * 2)
# GQA: 28 * 4096 * 8 * (128+128) * 2 -- uses actual key_length=128
assert gqa_result != legacy_result
@@ -1077,7 +1074,7 @@ class TestLegacyEstimation:
assert b._estimate_kv_cache_bytes(4096, "f16") == expected
def test_legacy_identical_to_old_formula(self):
- """Confirm legacy path produces the same result as the pre-PR formula."""
+ """Legacy path matches the pre-PR formula."""
b = self._legacy_backend()
n_layers = 32
n_kv_heads = 8
@@ -1097,7 +1094,7 @@ class TestPathPriority:
"""Confirm: MLA > Hybrid Mamba > SWA > GQA > Legacy."""
def test_mla_takes_priority_over_all(self):
- """If kv_lora_rank is set, MLA path is used even if other fields are present."""
+ """If kv_lora_rank is set, MLA path wins even with other fields present."""
b = LlamaCppBackend()
b._n_layers = 61
b._n_kv_heads = 1
@@ -1132,9 +1129,9 @@ class TestPathPriority:
assert b._estimate_kv_cache_bytes(1000, "f16") == expected_hybrid
def test_all_paths_produce_different_values(self):
- """With carefully chosen params, each path should yield a distinct value."""
- # Use embedding_length=768 so legacy head_dim (768//16=48) differs from
- # key_length (256), and MLA key_len (256) != legacy K+V (2*48=96).
+ """With chosen params, each path yields a distinct value."""
+ # embedding_length=768 so legacy head_dim (768//16=48) != key_length
+ # (256), and MLA key_len (256) != legacy K+V (2*48=96).
params = {
"_n_layers": 40,
"_n_kv_heads": 4,
@@ -1191,7 +1188,7 @@ class TestPathPriority:
class TestQuantization:
- """Verify all supported cache_type_kv values produce correct scaling."""
+ """All supported cache_type_kv values scale correctly."""
@pytest.mark.parametrize(
"cache_type,expected_bpe",
@@ -1332,7 +1329,7 @@ class TestServerFlags:
b = self._swa_backend()
ctx = 32_768
flagged = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
- # With swa_full, every layer caches n_ctx -- equals path 4 sizing.
+ # swa_full: every layer caches n_ctx -- equals path 4 sizing.
kv_per_token = 4 * (256 + 256) * 2 # n_kv_heads * (k+v) * f16
expected = 26 * ctx * kv_per_token
assert flagged == expected
@@ -1366,10 +1363,9 @@ class TestServerFlags:
assert with_cp > b._estimate_kv_cache_bytes(8192, "f16")
# ── --parallel + --kv-unified ──────────────────────────────────
- # Empirically verified against llama-server: non-SWA caches partition
- # n_ctx across slots (total memory constant); SWA layers are the only
- # portion that scales with --parallel. --kv-unified is currently a
- # no-op for memory math (kept for API forward-compat).
+ # Verified against llama-server: non-SWA caches partition n_ctx across
+ # slots (total memory constant); only SWA layers scale with --parallel.
+ # --kv-unified is a no-op for memory math (kept for API forward-compat).
def test_gqa_kv_constant_across_parallel(self):
b = self._gqa_backend()
@@ -1394,7 +1390,7 @@ class TestServerFlags:
b = self._swa_backend()
ctx = 8192
baseline = b._estimate_kv_cache_bytes(ctx, "f16")
- # Decompose baseline by walking the same loop the estimator does.
+ # Decompose baseline by walking the estimator's own loop.
swa = b._sliding_window
per_token_global = 4 * (256 + 256) * 2 # n_kv * (k+v) * f16
per_token_swa = 4 * (256 + 256) * 2 # k_swa/val_swa fall back
@@ -1409,10 +1405,10 @@ class TestServerFlags:
)
# Sanity: parallel=1 reproduces baseline exactly
assert global_bytes + swa_bytes_per_slot == baseline
- # Only SWA portion scales by parallel
+ # Only the SWA portion scales by parallel
for slots in (1, 2, 3, 4):
scaled = b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = slots, kv_unified = False)
- # SWA cells get clamped to per_slot_ctx when ctx/slots < 2*swa
+ # SWA cells clamp to per_slot_ctx when ctx/slots < 2*swa
per_slot_ctx = max(1, ctx // slots)
cells = min(ctx, 2 * swa, per_slot_ctx)
swa_bps = sum(
@@ -1452,7 +1448,7 @@ class TestServerFlags:
ctx = 8192
baseline = b._estimate_kv_cache_bytes(ctx, "f16")
flagged = b._estimate_kv_cache_bytes(ctx, "f16", ctx_checkpoints = 4)
- # 22 SWA layers * 4 checkpoints * 512 cells * 4 heads * (256+256) * 2 bytes
+ # 22 SWA layers * 4 cps * 512 cells * 4 heads * (256+256) * 2 bytes
n_swa_layers = sum(1 for f in [True, True, True, True, True, False] * 4 + [True, True] if f)
per_layer = 4 * 512 * 4 * (256 + 256) * 2
assert flagged == baseline + n_swa_layers * per_layer
@@ -1470,7 +1466,7 @@ class TestServerFlags:
def test_ctx_checkpoints_compose_with_n_parallel(self):
# Only the SWA + checkpoint portion scales by n_parallel; the
- # global-layer portion stays constant.
+ # global-layer portion is constant.
b = self._swa_backend()
ctx = 8192
swa = b._sliding_window
@@ -1493,7 +1489,7 @@ class TestServerFlags:
def test_fit_returns_requested_when_kv_off_gpu(self):
b = self._gqa_backend()
- # Tiny VRAM budget -- normally would force a reduction.
+ # Tiny VRAM budget -- would normally force a reduction.
fitted = b._fit_context_to_vram(
requested_ctx = 32_768,
available_mib = 1,
@@ -1515,8 +1511,8 @@ class TestServerFlags:
assert fitted < 32_768
def test_fit_mtp_engaged_returns_smaller_or_equal_context(self):
- # MTP-engaged budget is 0.85 of available; non-MTP is 0.90.
- # On a tight budget the MTP path must yield <= the non-MTP path.
+ # MTP budget is 0.85 of available, non-MTP is 0.90; on a tight
+ # budget MTP must yield <= non-MTP.
b = self._gqa_backend()
common = dict(
requested_ctx = 32_768,
@@ -1529,7 +1525,7 @@ class TestServerFlags:
assert mtp <= baseline
def test_fit_mtp_engaged_unchanged_when_kv_off_gpu(self):
- # kv_on_gpu=False short-circuits the fit; mtp_engaged is irrelevant.
+ # kv_on_gpu=False short-circuits the fit; mtp_engaged irrelevant.
b = self._gqa_backend()
fitted = b._fit_context_to_vram(
requested_ctx = 32_768,
@@ -1548,7 +1544,7 @@ class TestServerFlags:
kv_default = b._estimate_kv_cache_bytes(ctx, "f16")
kv_full = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
assert kv_full > kv_default
- # Budget = model + kv_default (rounded up) -- swa_full should not fit.
+ # Budget = model + kv_default (rounded up) -- swa_full must not fit.
budget_mib = (1024 * 1024 + kv_default) / (1024 * 1024) / 0.90 + 1
fitted_default = b._fit_context_to_vram(
requested_ctx = ctx,
@@ -1573,16 +1569,16 @@ class TestServerFlags:
class TestParallelSWAScaling:
- """Verifies the per-layer-type scaling rule against the closed form
- measured from llama-server. Empirical formula on Gemma-3 270m at
- ctx=8192: total_kv = 24 + parallel * 15 (MiB).
+ """Per-layer-type scaling rule vs the closed form measured from
+ llama-server. Empirical formula on Gemma-3 270m at ctx=8192:
+ total_kv = 24 + parallel * 15 (MiB).
Rule (verified vs ``llama-server`` log on real GGUFs):
* non-SWA layers: total cells = n_ctx, partitioned across slots,
memory CONSTANT in n_parallel.
* SWA layers: per-slot cells = 2 * sliding_window (clamped at
n_ctx and at per_slot_ctx); memory LINEAR in n_parallel.
- * --kv-unified is a no-op for memory math; both modes yield the
+ * --kv-unified is a no-op for memory math; both modes give the
same total in measured cases.
"""
@@ -1703,7 +1699,7 @@ class TestParallelSWAScaling:
def test_swa_per_slot_clamped_when_ctx_lt_slots_x_2window(self):
# ctx=4096 / slots=8 -> per_slot_ctx=512, but 2*sliding=1024.
- # SWA cells should clamp at per_slot_ctx (512), not 2*sliding.
+ # SWA cells clamp at per_slot_ctx (512), not 2*sliding.
b = self._swa_backend()
ctx = 4096
per_slot_ctx_at_8 = ctx // 8
@@ -1719,8 +1715,8 @@ class TestParallelSWAScaling:
assert b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = 8) == expected
def test_swa_full_does_not_scale_under_parallel(self):
- # swa_full forces every layer to n_ctx; result is the all-global
- # GQA-style total, which is constant in parallel.
+ # swa_full forces every layer to n_ctx -> all-global GQA-style
+ # total, constant in parallel.
b = self._swa_backend()
ctx = 8192
baseline = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
@@ -1732,8 +1728,8 @@ class TestParallelSWAScaling:
# ── kv_unified: no-op for memory math ──────────────────────────
def test_kv_unified_is_no_op_for_memory_math(self):
- # Both unified=True and unified=False must produce the same
- # total bytes for every backend type and every parallel value.
+ # unified=True and unified=False must give the same total bytes
+ # for every backend type and parallel value.
backends = [
("gqa", self._gqa_backend()),
("swa", self._swa_backend()),
@@ -1761,9 +1757,8 @@ class TestParallelSWAScaling:
b._kv_key_length = 256
b._kv_value_length = 256
b._sliding_window = 512
- # 5-period [swa,swa,swa,swa,full] * 3 + [swa,swa,swa]: mirrors the
- # bootstrap-resolved pattern for gemma3 (period 6) on an 18-layer
- # model (15 SWA, 3 global).
+ # Mirrors the bootstrap-resolved gemma3 pattern (period 6) on an
+ # 18-layer model: 15 SWA, 3 global.
b._sliding_window_pattern = [(i + 1) % 6 != 0 for i in range(18)]
n_global = 3
n_swa = 15
@@ -1784,13 +1779,13 @@ class TestParallelSWAScaling:
class TestSharedKVLayers:
"""``<arch>.attention.shared_kv_layers`` reduces the layer count that
- actually allocates KV. The trailing ``shared_kv_layers`` blocks reuse
- earlier caches (Gemma 3n: 35 layers, 15 shared -> 20 allocate; Gemma 4
- same field). Unset on every other arch -> no behavioural change."""
+ allocates KV. The trailing ``shared_kv_layers`` blocks reuse earlier
+ caches (Gemma 3n: 35 layers, 15 shared -> 20 allocate; Gemma 4 same
+ field). Unset on every other arch -> no behavioural change."""
def _gemma3n_backend(self, **overrides):
- # Mirrors google/gemma-3n-E4B-it: 35 layers, 15 shared,
- # SWA window 1024, period 5 (4 sliding + 1 full repeating).
+ # Mirrors google/gemma-3n-E4B-it: 35 layers, 15 shared, SWA window
+ # 1024, period 5 (4 sliding + 1 full repeating).
defaults = {
"_n_layers": 35,
"_n_kv_heads": 4,
@@ -1873,9 +1868,8 @@ class TestSharedKVLayers:
def test_path3_pattern_loops_only_unshared_layers(self):
b = self._gemma3n_backend()
ctx = 8192
- # First 20 layers contribute; layers 20..34 are skipped.
- # Pattern: [s,s,s,s,F] repeated. In layers 0..19:
- # sliding: 16, full: 4
+ # First 20 layers contribute; layers 20..34 skipped. Pattern
+ # [s,s,s,s,F] repeated -> in layers 0..19: sliding 16, full 4.
sliding_in_unshared = sum(b._sliding_window_pattern[:20])
full_in_unshared = 20 - sliding_in_unshared
assert sliding_in_unshared == 16
@@ -1890,7 +1884,7 @@ class TestSharedKVLayers:
with_shared = b._estimate_kv_cache_bytes(8192, "f16")
b._shared_kv_layers = 0
without_shared = b._estimate_kv_cache_bytes(8192, "f16")
- # 20/35 = 0.571 of the work; expect ~43% reduction.
+ # 20/35 = 0.571 of the work; ~43% reduction.
ratio = with_shared / without_shared
assert 0.5 < ratio < 0.65
@@ -1898,8 +1892,8 @@ class TestSharedKVLayers:
b = self._gemma3n_backend()
ctx = 8192
flagged = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
- # Every unshared layer caches n_ctx; equals path-4-style sizing
- # over only the 20 unshared layers.
+ # Every unshared layer caches n_ctx -> path-4-style sizing over
+ # only the 20 unshared layers.
kv_per = 4 * (256 + 256) * 2
assert flagged == 20 * ctx * kv_per
@@ -1917,15 +1911,15 @@ class TestSharedKVLayers:
assert b._estimate_kv_cache_bytes(ctx, "f16") == expected
def test_shared_floors_at_one_layer(self):
- # Pathological: shared >= n_layers should not zero out the cache.
+ # Pathological: shared >= n_layers must not zero out the cache.
b = self._gqa_backend(_shared_kv_layers = 99)
ctx = 4096
kv_per = 8 * (128 + 128) * 2
assert b._estimate_kv_cache_bytes(ctx, "f16") == 1 * ctx * kv_per
def test_composes_with_n_parallel(self):
- # Only the SWA portion of the unshared layers scales by n_parallel;
- # the global portion stays constant.
+ # Only the SWA portion of unshared layers scales by n_parallel;
+ # the global portion is constant.
b = self._gemma3n_backend()
ctx = 8192
swa = b._sliding_window
@@ -1946,7 +1940,7 @@ class TestSharedKVLayers:
ctx = 8192
baseline = b._estimate_kv_cache_bytes(ctx, "f16")
with_cp = b._estimate_kv_cache_bytes(ctx, "f16", ctx_checkpoints = 4)
- # Checkpoints only count over UNSHARED SWA layers (16 of them).
+ # Checkpoints count only over UNSHARED SWA layers (16 of them).
sliding_in_unshared = sum(b._sliding_window_pattern[:20])
per_cp_layer = 4 * 1024 * 4 * (256 + 256) * 2 # cps * swa * heads * (k+v) * bpe
assert with_cp == baseline + sliding_in_unshared * per_cp_layer
@@ -2017,7 +2011,7 @@ class TestLifecycle:
assert b._n_kv_heads_by_layer is None
def test_end_to_end_synthetic_mla(self):
- """Full round-trip: write GGUF -> parse -> estimate."""
+ """Round-trip: write GGUF -> parse -> estimate."""
b = _backend_from_gguf(
"deepseek2",
{
@@ -2075,8 +2069,8 @@ class TestLifecycle:
)
assert b._can_estimate_kv()
result = b._estimate_kv_cache_bytes(131072, "f16")
- # gemma3 -> period 6 from the bootstrap table, SWA cache
- # double-buffered to 2 * sliding_window cells.
+ # gemma3 -> period 6 from bootstrap; SWA cache double-buffered to
+ # 2 * sliding_window cells.
period = 6
kv_per = 16 * 256 * 2
expected = 0
@@ -2104,13 +2098,13 @@ class TestLifecycle:
)
assert b._can_estimate_kv()
assert b._shared_kv_layers == 15
- # Bootstrap table for gemma3n_text -> period 5; the resolver
- # synthesises a 35-entry bool array. The first 20 entries
- # (n_layers - shared) are the only ones that allocate KV.
+ # Bootstrap for gemma3n_text -> period 5; resolver synthesises a
+ # 35-entry bool array. Only the first 20 (n_layers - shared)
+ # allocate KV.
result = b._estimate_kv_cache_bytes(8192, "f16")
assert result > 0
- # Sanity: setting shared back to 0 must produce a strictly larger
- # estimate (more layers allocate).
+ # Sanity: shared back to 0 -> strictly larger estimate (more
+ # layers allocate).
b._shared_kv_layers = 0
unshared = b._estimate_kv_cache_bytes(8192, "f16")
assert unshared > result
diff --git a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
index f887f7747c4..8fca27dfe18 100644
--- a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
+++ b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
@@ -1,11 +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
-"""Validates that the installer correctly resolves lemonade ROCm prebuilt assets.
+"""Validates that the installer resolves lemonade ROCm prebuilt assets.
-Uses a faked HostInfo so no AMD GPU is needed. Network calls to the lemonade
-GitHub API are stubbed out so the suite runs without internet access and is
-not subject to rate limits.
+Uses a faked HostInfo so no AMD GPU is needed. The lemonade GitHub API calls
+are stubbed so the suite runs offline and isn't subject to rate limits.
"""
from __future__ import annotations
@@ -33,7 +32,7 @@ if resolve_lemonade_rocm_choice is None or _LEMONADE_GFX_FAMILIES is None:
@pytest.fixture(autouse = True)
def _clear_lemonade_release_cache():
"""Prevent cross-test pollution of the lemonade release lru_cache when
- future tests vary the fetch_json mock return value."""
+ tests vary the fetch_json mock return value."""
_cache = getattr(_mod, "_fetch_lemonade_release_cached", None)
if _cache is not None and hasattr(_cache, "cache_clear"):
_cache.cache_clear()
@@ -157,10 +156,9 @@ direct_upstream_release_plan = getattr(_mod, "direct_upstream_release_plan", Non
def _stub_unsloth_release(release_tag: str = "b9022") -> dict:
- # Minimal payload that parse_direct_linux_release_bundle accepts. It
- # requires at least one `app-{label}-linux-x64*.tar.gz` asset for the
- # bundle to be recognised; we ship a bare CPU one so the planner has a
- # baseline non-ROCm attempt to fall through to.
+ # Minimal payload parse_direct_linux_release_bundle accepts. It needs at
+ # least one `app-{label}-linux-x64*.tar.gz` asset to recognise the bundle;
+ # we ship a bare CPU one so the planner has a baseline non-ROCm fallback.
asset_name = f"app-{release_tag}-linux-x64.tar.gz"
return {
"tag_name": release_tag,
@@ -255,9 +253,8 @@ def test_lemonade_release_api_url_pinned_tag():
def test_lemonade_release_api_url_encodes_tag():
- """Unexpected slashes / hashes in the tag must be URL-encoded so the URL
- cannot be reshaped (defence in depth -- tags should already be sanitised
- upstream)."""
+ """Slashes / hashes in the tag must be URL-encoded so the URL can't be
+ reshaped (defence in depth -- tags should already be sanitised upstream)."""
url = _mod._lemonade_release_api_for("b1260/../latest")
assert "/releases/tags/b1260%2F..%2Flatest" in url
assert "//latest" not in url.split("/releases/tags/", 1)[1]
@@ -272,9 +269,9 @@ def test_lemonade_resolver_skipped_by_opt_out_env(monkeypatch):
def test_lemonade_resolver_rejects_non_github_url(monkeypatch):
- """If the GitHub API response somehow contained an off-host download URL,
- the resolver must refuse to use it (lemonade assets are not in the
- approved-hash manifest)."""
+ """If the GitHub API response contained an off-host download URL, the
+ resolver must refuse it (lemonade assets aren't in the approved-hash
+ manifest)."""
bad_release = {
"tag_name": _STUB_TAG,
"assets": [
@@ -298,7 +295,7 @@ def test_lemonade_resolver_rejects_http_scheme():
def test_lemonade_resolver_accepts_github_cdn():
- # Real GitHub release CDN URLs carry the /github-production-release-asset- prefix.
+ # Real GitHub release CDN URLs carry the /github-production-release-asset- prefix
assert _mod._is_trusted_github_release_url(
"https://objects.githubusercontent.com/github-production-release-asset-abc123/456/789?token=x",
"lemonade-sdk/llamacpp-rocm",
@@ -306,7 +303,7 @@ def test_lemonade_resolver_accepts_github_cdn():
def test_lemonade_resolver_rejects_arbitrary_cdn_path():
- # A CDN URL without the release-asset path prefix must be rejected.
+ # A CDN URL without the release-asset path prefix must be rejected
assert not _mod._is_trusted_github_release_url(
"https://objects.githubusercontent.com/abc/def",
"lemonade-sdk/llamacpp-rocm",
@@ -348,7 +345,7 @@ def test_lemonade_runtime_patterns_include_hip_runtime():
Lemonade ZIPs carry transitive deps (libamd_comgr, libLLVM, libclang-cpp,
...) whose names change across ROCm releases. A broad ``lib*.so*`` glob
- avoids having to enumerate every transitive dependency by name.
+ avoids enumerating every transitive dependency by name.
"""
from install_llama_prebuilt import runtime_patterns_for_choice, AssetChoice
@@ -362,7 +359,7 @@ def test_lemonade_runtime_patterns_include_hip_runtime():
)
pats = runtime_patterns_for_choice(choice)
# The broad glob must be present so every .so in the lemonade bundle
- # (including transitive deps added in future ROCm releases) gets overlaid.
+ # (including future transitive deps) gets overlaid.
assert "lib*.so*" in pats, f"'lib*.so*' missing from linux-rocm patterns: {pats}"
@@ -374,9 +371,9 @@ _pick_rocm_gfx_target = getattr(_mod, "_pick_rocm_gfx_target", None)
reason = "_pick_rocm_gfx_target not present on this branch",
)
def test_pick_rocm_gfx_target_honors_cuda_visible_devices(monkeypatch):
- """AMD HIP honours CUDA_VISIBLE_DEVICES identically to HIP_VISIBLE_DEVICES;
- on a gfx1151 + gfx1100 mixed host, CUDA_VISIBLE_DEVICES=1 must select gfx1100."""
- # Two GPUs; rocminfo reports each token twice (as in the real tool output).
+ """AMD HIP honours CUDA_VISIBLE_DEVICES like HIP_VISIBLE_DEVICES; on a
+ gfx1151 + gfx1100 mixed host, CUDA_VISIBLE_DEVICES=1 must select gfx1100."""
+ # Two GPUs; rocminfo reports each token twice (as in real tool output).
probe_out = "gfx1151\ngfx1151\ngfx1100\ngfx1100"
monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
@@ -405,7 +402,7 @@ def test_pick_rocm_gfx_target_same_arch_multi_gpu(monkeypatch):
"""Regression: [gfx1100, gfx1100, gfx1151] with HIP_VISIBLE_DEVICES=2 must
return gfx1151, not fall back to GPU 0 due to dict.fromkeys collapsing the
two gfx1100 entries into one and making index 2 out of range."""
- # Simulate rocminfo output for 3 GPUs (2x gfx1100 dGPU + 1x gfx1151 APU).
+ # rocminfo output for 3 GPUs (2x gfx1100 dGPU + 1x gfx1151 APU).
# Each GPU gets its own Agent section with a few token mentions.
probe_out = (
"***\nAgent 1\n***\n gfx1100 some info\n gfx1100\n"
diff --git a/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py b/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
index 255c04a9565..215936bd207 100644
--- a/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
+++ b/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
@@ -5,17 +5,14 @@
``LlamaCppBackend.load_model``.
The preflight used to compare the repo's total GGUF download size against
-free disk without accounting for bytes already present in the Hugging
-Face cache. That made re-loading a cached large model (e.g.
-``unsloth/MiniMax-M2.7-GGUF`` at 131 GB) fail cold whenever free disk was
-below the full weight footprint, even though nothing needed
-downloading.
+free disk without accounting for bytes already in the Hugging Face cache.
+That made re-loading a cached large model (e.g. ``unsloth/MiniMax-M2.7-GGUF``
+at 131 GB) fail cold whenever free disk was below the full weight footprint,
+even though nothing needed downloading.
These tests exercise the preflight arithmetic in isolation by driving
``get_paths_info`` and ``try_to_load_from_cache`` through ``mock.patch``.
-No network, GPU, or subprocess use.
-
-Cross-platform: Linux, macOS, Windows, WSL.
+No network, GPU, or subprocess use. Cross-platform: Linux, macOS, Windows, WSL.
"""
from __future__ import annotations
@@ -29,8 +26,8 @@ from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable external deps before importing the module under
+# test. Same pattern as test_kv_cache_estimation.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -99,11 +96,11 @@ def _preflight(
hf_repo = "unsloth/Example-GGUF",
hf_token = None,
):
- """Run the preflight arithmetic as written in llama_cpp.py and return
- the decision outcome as a dict.
+ """Run the preflight arithmetic as in llama_cpp.py; return the decision
+ outcome as a dict.
``repo_files``: list of (filename, remote_bytes).
- ``cached_files``: dict {filename: on_disk_bytes} for files already in cache.
+ ``cached_files``: dict {filename: on_disk_bytes} for files already cached.
``free_bytes``: value returned by shutil.disk_usage(cache_dir).free.
"""
import os
@@ -112,22 +109,21 @@ def _preflight(
path_infos = [_FakePathInfo(name, size) for name, size in repo_files]
with tempfile.TemporaryDirectory() as tmp:
- # Create SPARSE files for the cached ones so os.path.exists /
- # os.path.getsize pass without actually allocating bytes on disk.
- # This is critical when simulating multi-GB models.
+ # SPARSE files for the cached ones so os.path.exists / os.path.getsize
+ # pass without allocating bytes on disk -- critical for multi-GB models.
cache_paths = {}
for name, sz in cached_files.items():
p = Path(tmp) / name.replace("/", "_")
with open(p, "wb") as fh:
if sz > 0:
- fh.truncate(sz) # sparse allocation: no data blocks written
+ fh.truncate(sz) # sparse: no data blocks written
cache_paths[name] = str(p)
def fake_try_to_load_from_cache(repo_id, filename):
return cache_paths.get(filename)
- # Mirror the same variable names and control flow as the real code
- # so behavioral drift is caught immediately.
+ # Mirror the real code's variable names and control flow so behavioral
+ # drift is caught immediately.
total_bytes = sum((p.size or 0) for p in path_infos)
already_cached_bytes = 0
for p in path_infos:
@@ -189,8 +185,8 @@ class TestCacheAwarePreflight:
assert out["would_raise_disk_error"] is False
def test_partial_cache_insufficient_disk_for_rest_still_raises(self):
- """Two of four shards cached; remaining 70 GB still bigger than
- free disk -> preflight correctly wants to raise."""
+ """Two of four shards cached; remaining 70 GB still exceeds free
+ disk -> preflight correctly wants to raise."""
shards = [(f"UD-Q4_K_XL/shard-{i}.gguf", 35 * GIB) for i in range(4)]
cached = {
shards[0][0]: shards[0][1],
@@ -217,8 +213,8 @@ class TestCacheAwarePreflight:
assert out["would_raise_disk_error"] is False
def test_incomplete_cached_blob_is_not_credited(self):
- """A partial file on disk (e.g. interrupted download) is not
- counted as cached -- we still require bytes for it."""
+ """A partial file on disk (e.g. interrupted download) isn't counted
+ as cached -- we still require bytes for it."""
shards = [("UD-Q4_K_XL/shard-0.gguf", 40 * GIB)]
partial = {"UD-Q4_K_XL/shard-0.gguf": 10 * GIB}
out = _preflight(
@@ -231,7 +227,7 @@ class TestCacheAwarePreflight:
assert out["would_raise_disk_error"] is False
def test_zero_size_path_infos_do_not_crash(self):
- """A path_info with size=0 should not be credited or break the
+ """A path_info with size=0 must not be credited or break the
arithmetic."""
shards = [("mmproj.gguf", 0), ("UD-Q4_K_XL/shard-0.gguf", 40 * GIB)]
out = _preflight(
diff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.py
index ee8d54443a7..ec66411bfd8 100644
--- a/studio/backend/tests/test_llama_cpp_context_fit.py
+++ b/studio/backend/tests/test_llama_cpp_context_fit.py
@@ -5,26 +5,24 @@
Guards two regressions in ``LlamaCppBackend.load_model``:
-1. **Auto mode on weights-exceed-VRAM** (``n_ctx == 0``): when the model
- weights alone exceed 90% of every GPU subset's free memory, the
- auto-pick loop used to exit without matching, leaving
- ``effective_ctx`` at the model's native context (e.g. 196608 for
- MiniMax-M2.7). The intended default per Studio's UI spec is 4096 so
- the slider lands on a usable value; the user can still drag higher
- and trigger ``--fit on`` with a warning.
+1. **Auto mode on weights-exceed-VRAM** (``n_ctx == 0``): when weights
+ alone exceed 90% of every GPU subset's free memory, the auto-pick loop
+ used to exit without matching, leaving ``effective_ctx`` at the native
+ context (e.g. 196608 for MiniMax-M2.7). Studio's UI spec wants 4096 so
+ the slider lands on a usable value; the user can still drag higher and
+ trigger ``--fit on`` with a warning.
2. **Explicit ctx silently shrunk when KV overflows**: with fittable
- weights but a requested ctx whose KV cache pushes total memory over
- 90% of VRAM, the old code binary-searched a smaller ctx and emitted
- ``-c <capped> -ngl -1`` without informing the caller. The UI had
- already surfaced its "might be slower" warning and expects the user's
- explicit ctx to be honored with ``--fit on`` flexing ``-ngl`` instead.
+ weights but a ctx whose KV cache pushes total memory over 90% of VRAM,
+ the old code binary-searched a smaller ctx and emitted ``-c <capped>
+ -ngl -1`` without telling the caller. The UI already showed its "might
+ be slower" warning and expects the explicit ctx honored with ``--fit
+ on`` flexing ``-ngl`` instead.
-Tests avoid GPU probing, subprocess spawning, and GGUF I/O by driving the
+Avoids GPU probing, subprocess spawning, and GGUF I/O by driving the
post-metadata decision block directly against a stubbed instance.
-Requires no GPU, network, or external libraries beyond pytest.
-Cross-platform: Linux, macOS, Windows, WSL.
+No GPU, network, or libraries beyond pytest. Cross-platform.
"""
from __future__ import annotations
@@ -36,8 +34,8 @@ from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -103,8 +101,8 @@ def _make_backend(
kv_key_length = 128,
kv_value_length = 128,
):
- """Create a LlamaCppBackend instance with GGUF metadata fields set and
- the helpers used by the decision block stubbed out."""
+ """LlamaCppBackend with GGUF metadata fields set and the decision
+ block's helpers stubbed out."""
inst = LlamaCppBackend.__new__(LlamaCppBackend)
inst._context_length = native_ctx
inst._n_layers = n_layers
@@ -136,8 +134,8 @@ def _drive(
):
"""Drive the post-metadata portion of load_model with stubbed inputs.
- Mirrors the decision block at llama_cpp.py:1137-1296 so we can assert
- the command that would be built, without subprocesses or GPU probes.
+ Mirrors the decision block at llama_cpp.py:1137-1296 to assert the
+ command that would be built, without subprocesses or GPU probes.
"""
inst = _make_backend(native_ctx = native_ctx)
model_size = int(model_gib * GIB)
@@ -154,9 +152,8 @@ def _drive(
inst._can_estimate_kv = lambda: can_estimate_kv
context_length = inst._context_length
- # Use the production helper instead of reimplementing the conditional
- # locally; reimplementing makes the test pass for the test's own logic
- # rather than production's, and silent drift won't be caught.
+ # Use the production helper, not a local reimplementation: a local copy
+ # would test the test's own logic, not production's, and hide drift.
ctx_override = parse_ctx_override(extra_args)
requested_ctx = resolve_requested_ctx(extra_args, n_ctx)
@@ -267,8 +264,8 @@ class TestAutoModeWeightsExceedVRAM:
assert plan["c_arg"] == FALLBACK_CTX
assert plan["use_fit"] is True
assert plan["gpu_indices"] is None
- # UI slider ceiling stays at native: user can still drag higher
- # and get the "might be slower" path.
+ # UI slider ceiling stays at native: user can drag higher and get
+ # the "might be slower" path.
assert plan["max_available_ctx"] == 196608
def test_multi_gpu_all_subsets_fail(self):
@@ -304,9 +301,8 @@ class TestExplicitCtxRespectsUser:
"""``n_ctx > 0`` must never be silently shrunk."""
def test_fittable_weights_oversized_kv(self):
- # 8 GB weights + 131k ctx KV on 24 GB VRAM.
- # Budget = 21.6 GB, KV at 131k >> 13.6 GB remaining, so
- # _select_gpus flips use_fit=True.
+ # 8 GB weights + 131k ctx KV on 24 GB VRAM. Budget = 21.6 GB, KV
+ # at 131k >> 13.6 GB remaining, so _select_gpus flips use_fit=True.
plan = _drive(
n_ctx = 131072,
model_gib = 8,
@@ -350,7 +346,7 @@ class TestExplicitCtxRespectsUser:
assert plan["use_fit"] is True
def test_explicit_below_floor_honored(self):
- # 2048 is below --fit-ctx default; still honored since user set it.
+ # 2048 is below --fit-ctx default; honored since user set it.
plan = _drive(
n_ctx = 2048,
model_gib = 8,
@@ -451,8 +447,8 @@ class TestTightFitPinsToGPU:
"""Models that fit at 91-95% of free VRAM must use the GPU."""
def test_rtx_4090_qwen_24gb_class(self):
- # noahterbest's #5106 log: 20.8 GB model on 22805 MiB free
- # GPU, ctx=4096 -> ~94% utilization, ~1.4 GiB headroom.
+ # noahterbest's #5106 log: 20.8 GB model on 22805 MiB free GPU,
+ # ctx=4096 -> ~94% utilization, ~1.4 GiB headroom.
plan = _drive(
n_ctx = 0,
model_gib = 20.8,
@@ -495,9 +491,9 @@ class TestTightFitPinsToGPU:
@pytest.mark.parametrize("platform_tag", ["linux", "windows", "mac", "rocm"])
def test_identical_decision_across_platforms(platform_tag):
- """The decision function takes ``[(gpu_idx, free_mib), ...]`` regardless
- of how upstream (nvidia-smi / nvidia-smi.exe / Metal / rocm-smi) produced
- it. Identical inputs must yield identical plans."""
+ """The decision takes ``[(gpu_idx, free_mib), ...]`` regardless of the
+ source (nvidia-smi / nvidia-smi.exe / Metal / rocm-smi). Identical
+ inputs must yield identical plans."""
plan_a = _drive(n_ctx = 0, model_gib = 8, gpus = [(0, 24_000)])
plan_b = _drive(n_ctx = 0, model_gib = 8, gpus = [(0, 24_000)])
assert plan_a == plan_b, platform_tag
@@ -525,8 +521,8 @@ class TestClassifyGpuOffload:
assert inst._classify_gpu_offload(True, [(0, 22805)]) is True
def test_cpu_only_buffer_returns_false(self):
- # llama-server printed buffer lines but only CPU buffers --
- # this is the silent CPU fallback symptom we want to catch.
+ # Buffer lines printed but only CPU buffers -- the silent CPU
+ # fallback symptom we want to catch.
inst = self._backend(
[
"load_tensors: CPU_Mapped model buffer size = 21000.0 MiB",
@@ -555,8 +551,7 @@ class TestClassifyGpuOffload:
assert inst._classify_gpu_offload(False, []) is None
def test_user_did_not_intend_gpu_returns_none(self):
- # Studio called start_llama_server without expecting GPU use;
- # don't warn.
+ # Studio called start_llama_server without expecting GPU; don't warn.
inst = self._backend(
[
"load_tensors: CPU_Mapped model buffer size = 21000.0 MiB",
diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.py
index c7dd111ee3a..25bcf851b4e 100644
--- a/studio/backend/tests/test_llama_cpp_freshness.py
+++ b/studio/backend/tests/test_llama_cpp_freshness.py
@@ -3,8 +3,8 @@
"""Tests for the llama.cpp prebuilt freshness check.
-Pins the marker parser, the disk+memory cache, the stale decision
-matrix, and fail-open behaviour on missing data.
+Pins the marker parser, disk+memory cache, stale-decision matrix, and
+fail-open behaviour on missing data.
"""
from __future__ import annotations
@@ -57,7 +57,7 @@ def _write_marker(install_dir: Path, **overrides) -> Path:
def _fake_binary(install_dir: Path, *, layout: str = "cmake") -> Path:
- """Stub llama-server under one of the supported install layouts."""
+ """Stub llama-server under a supported install layout."""
if layout == "cmake":
bin_dir = install_dir / "build" / "bin"
bin_name = "llama-server"
@@ -77,7 +77,7 @@ def _fake_binary(install_dir: Path, *, layout: str = "cmake") -> Path:
@pytest.fixture(autouse = True)
def _reset(monkeypatch, tmp_path):
- # Isolate disk cache per-test; never touch the user's real cache.
+ # Isolate disk cache per-test; never touch the real cache.
monkeypatch.setattr(fr, "_cache_dir", lambda: tmp_path / ".freshness")
fr.reset_caches()
yield
@@ -107,8 +107,8 @@ def test_read_install_marker_finds_root_layout(tmp_path):
def test_read_install_marker_finds_windows_cmake_layout(tmp_path):
- # Windows cmake puts the .exe under build/bin/Release/, so the
- # marker is four levels above the binary.
+ # Windows cmake puts the .exe under build/bin/Release/, so the marker
+ # is four levels above the binary.
install_dir = tmp_path / "llama.cpp"
_write_marker(install_dir, tag = "b8888")
bin_path = _fake_binary(install_dir, layout = "windows")
@@ -121,8 +121,8 @@ def test_read_install_marker_finds_windows_cmake_layout(tmp_path):
def test_read_install_marker_carries_published_repo_dynamically(tmp_path, repo):
# The freshness check queries whichever release repo the marker
# records, so CUDA Linux (unslothai), CPU Linux x86_64 / macOS
- # (ggml-org), and ROCm source-build (unslothai upstream label)
- # all surface the right "latest" tag.
+ # (ggml-org), and ROCm source-build all surface the right "latest"
+ # tag.
install_dir = tmp_path / "llama.cpp"
_write_marker(install_dir, tag = "b9000", published_repo = repo)
bin_path = _fake_binary(install_dir, layout = "cmake")
diff --git a/studio/backend/tests/test_llama_cpp_load_progress.py b/studio/backend/tests/test_llama_cpp_load_progress.py
index f95d8bf1a46..dcbe16be505 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress.py
@@ -4,18 +4,17 @@
"""Tests for ``LlamaCppBackend.load_progress()``.
The chat settings flow and the training overlay both show a generic
-"Starting model..." spinner during the window after a GGUF download
-finishes and before llama-server reports healthy. For small models
-that window is a second or two and nobody notices. For large MoE GGUFs
-(MiniMax-M2.7, Qwen3.5-397B-A17B, etc.) the llama-server process spends
-minutes in kernel state D, paging tens or hundreds of GB of shards
-into the page cache. The UI has no way to show a real progress bar,
-rate, or ETA during that window.
-
-``load_progress()`` samples ``/proc/<pid>/status VmRSS`` (what the
-kernel has actually paged in) against the total shard file size on
-disk, so the frontend can render a real bar plus rate/ETA. This
-module pins that contract:
+"Starting model..." spinner in the window after a GGUF download finishes
+and before llama-server reports healthy. For small models that window is a
+second or two and nobody notices. For large MoE GGUFs (MiniMax-M2.7,
+Qwen3.5-397B-A17B, etc.) llama-server spends minutes in kernel state D,
+paging tens or hundreds of GB of shards into the page cache. The UI has no
+way to show a real progress bar, rate, or ETA during that window.
+
+``load_progress()`` samples ``/proc/<pid>/status VmRSS`` (what the kernel
+actually paged in) against the total shard file size on disk, so the
+frontend can render a real bar plus rate/ETA. This module pins that
+contract:
* returns ``None`` when no load is in flight
* returns ``{"phase": "mmap", ...}`` while the subprocess is alive
@@ -27,10 +26,9 @@ module pins that contract:
* ``bytes_loaded`` is VmRSS in bytes, capped by total, rounded
* ``fraction`` is clamped to 0..1 and rounded to 4 decimal places
-Linux-only via ``/proc``. On platforms without ``/proc`` the method
-returns ``None`` instead of raising.
-Cross-platform test: skips cleanly on macOS / Windows if ``/proc`` is
-not available.
+Linux-only via ``/proc``; without ``/proc`` the method returns ``None``
+instead of raising. Cross-platform test: skips cleanly on macOS / Windows
+when ``/proc`` is unavailable.
"""
from __future__ import annotations
@@ -45,8 +43,8 @@ from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -106,7 +104,7 @@ def _make_instance():
class _FakeProc:
- """Minimal stand-in for subprocess.Popen that just carries a pid."""
+ """Minimal stand-in for subprocess.Popen carrying just a pid."""
def __init__(self, pid: int):
self.pid = pid
@@ -188,7 +186,7 @@ class TestLoadProgressSingleShard:
class TestLoadProgressMultiShard:
- """Shard-aware total: for ``*-00001-of-00004.gguf`` primaries the
+ """Shard-aware total: for ``*-00001-of-00004.gguf`` primaries, the
method sums sibling files with the same prefix."""
def test_sharded_total_aggregates_siblings(self, tmp_path):
@@ -197,7 +195,7 @@ class TestLoadProgressMultiShard:
tmp_path / f"model-{i:05d}-of-00004.gguf",
size_bytes = 20 * 1024**3,
)
- # Drop an unrelated .gguf in the same folder -- must not be counted.
+ # An unrelated .gguf in the same folder -- must not be counted.
_write_sparse_file(tmp_path / "mmproj-BF16.gguf", 2 * 1024**3)
inst = _make_instance()
diff --git a/studio/backend/tests/test_llama_cpp_load_progress_live.py b/studio/backend/tests/test_llama_cpp_load_progress_live.py
index 44a8f00834d..ce9dd509bf5 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress_live.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress_live.py
@@ -4,17 +4,15 @@
"""Live, no-mock integration test for ``LlamaCppBackend.load_progress()``.
The companion files (``test_llama_cpp_load_progress.py`` and
-``test_llama_cpp_load_progress_matrix.py``) patch ``builtins.open`` to
-feed synthetic VmRSS values. This file is the opposite: it uses **real**
-subprocesses, **real** file sizes, and the **real** ``/proc``
-interface. It is the sanity check that the contract we keep in the
-mocked tests still maps to what the kernel actually returns on a live
-Linux system.
-
-Why both: the mocked tests can be fooled by a buggy implementation that
-parses ``/proc`` output in a format the kernel no longer uses, or that
-makes assumptions about ``Path.stat()`` vs ``os.path.getsize``. This
-file hits the real APIs so any format drift gets caught.
+``test_llama_cpp_load_progress_matrix.py``) patch ``builtins.open`` to feed
+synthetic VmRSS values. This file is the opposite: it uses **real**
+subprocesses, **real** file sizes, and the **real** ``/proc`` interface,
+checking that the contract from the mocked tests still maps to what the kernel
+returns on a live Linux system.
+
+Why both: the mocked tests can be fooled by an implementation that parses
+``/proc`` in a format the kernel no longer uses, or assumes ``Path.stat()`` vs
+``os.path.getsize``. This file hits the real APIs so format drift gets caught.
Skipped cleanly on non-Linux (no ``/proc``).
"""
@@ -31,8 +29,8 @@ from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
-# Same stubs as the matrix file (keep self-contained so the file can be
-# run standalone as well as via the full suite).
+# Same stubs as the matrix file (self-contained so this file runs standalone
+# and via the full suite).
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -88,8 +86,8 @@ def _make_backend(
def test_live_rss_matches_kernel_vmrss(tmp_path):
- """Spawn a real child, let it allocate real bytes, confirm
- ``bytes_loaded`` tracks the kernel's VmRSS within a sane tolerance."""
+ """Spawn a real child, let it allocate real bytes, confirm ``bytes_loaded``
+ tracks the kernel's VmRSS within a sane tolerance."""
# Child that allocates ~100 MB of zero'd bytes and then idles.
script = tmp_path / "burn.py"
script.write_text(
@@ -112,7 +110,7 @@ def test_live_rss_matches_kernel_vmrss(tmp_path):
ready = proc.stdout.readline()
assert ready.strip() == b"ready"
- # Create a fake 200 MB sparse gguf so bytes_total is concrete.
+ # Fake 200 MB sparse gguf so bytes_total is concrete.
gguf = tmp_path / "model.gguf"
with open(gguf, "wb") as f:
f.truncate(200 * 1024 * 1024)
@@ -123,8 +121,8 @@ def test_live_rss_matches_kernel_vmrss(tmp_path):
assert out is not None, "load_progress returned None for live pid"
assert out["phase"] == "mmap"
assert out["bytes_total"] == 200 * 1024 * 1024
- # VmRSS for the Python child includes the interpreter + the 100MB
- # buffer, so a realistic floor is 50 MB and ceiling is 200 MB.
+ # VmRSS for the Python child includes the interpreter + 100MB buffer,
+ # so a realistic floor is 50 MB and ceiling is 200 MB.
assert (
out["bytes_loaded"] >= 50 * 1024 * 1024
), f"bytes_loaded unexpectedly low: {out['bytes_loaded']}"
@@ -153,8 +151,8 @@ def test_live_ready_phase_when_healthy(tmp_path):
def test_live_dead_pid_returns_none(tmp_path):
- """A recently-dead pid may linger in /proc for ms; use a clearly
- invalid id so the read reliably fails."""
+ """A recently-dead pid may linger in /proc for ms; use a clearly invalid id
+ so the read reliably fails."""
gguf = tmp_path / "m.gguf"
gguf.touch()
@@ -164,8 +162,8 @@ def test_live_dead_pid_returns_none(tmp_path):
def test_live_shard_aggregation_counts_real_files(tmp_path):
- """With 4 real sibling shards on disk, ``bytes_total`` equals their
- summed size to the byte."""
+ """With 4 real sibling shards on disk, ``bytes_total`` equals their summed
+ size to the byte."""
shard_size = 7 * 1024 * 1024 # 7 MB each
for i in range(1, 5):
f = tmp_path / f"model-{i:05d}-of-00004.gguf"
@@ -186,8 +184,8 @@ def test_live_shard_aggregation_counts_real_files(tmp_path):
def test_live_repeated_polling_stays_sane(tmp_path):
- """Sampling the same backend 20 times should not raise or produce
- non-numeric output, even under normal kernel RSS jitter."""
+ """Sampling the same backend 20 times must not raise or produce non-numeric
+ output, even under normal kernel RSS jitter."""
gguf = tmp_path / "m.gguf"
with open(gguf, "wb") as f:
f.truncate(500 * 1024 * 1024)
diff --git a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py b/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
index a88450ec0b5..1a698d3613d 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
@@ -3,29 +3,29 @@
"""Extended test matrix for ``LlamaCppBackend.load_progress()``.
-Companion to ``test_llama_cpp_load_progress.py`` (which pins the basic
-contract). This file widens coverage to the edge cases that bit users
-or were hypothesized to bite them on cross-platform installs:
+Companion to ``test_llama_cpp_load_progress.py`` (basic contract). Widens
+coverage to edge cases that bit (or were thought to bite) cross-platform
+installs:
- * Platform matrix — macOS/Windows simulation via ``/proc`` absence.
+ * Platform matrix — macOS/Windows via ``/proc`` absence.
* ``VmRSS`` parsing — tab vs space delimiter, missing line, malformed
integer.
* Filesystem edges — HF-cache symlinks, broken symlinks, nonexistent
paths, relative paths.
- * Shard aggregation — partial multi-shard downloads where some shards
- are still ``.incomplete``, two shard series in the same dir,
+ * Shard aggregation — partial multi-shard downloads with some shards
+ still ``.incomplete``, two shard series in one dir,
``mmproj-*.gguf`` sibling exclusion for non-sharded primaries,
single-file models.
- * Lifecycle races — process set before ``_gguf_path`` is assigned,
- process dead mid-sample, ``_healthy`` flipped to True.
- * Concurrent sampling — 10 threads × 50 iterations against a single
- backend, hitting real ``/proc`` (no mocks — see the note in
+ * Lifecycle races — process set before ``_gguf_path``, process dead
+ mid-sample, ``_healthy`` flipped to True.
+ * Concurrent sampling — 10 threads × 50 iterations against one
+ backend, hitting real ``/proc`` (no mocks — see
``TestConcurrentSampling`` for why).
* Fraction bounds — capped at 1.0 when RSS exceeds total; 0.0 when
total is zero.
-All tests are Linux-only in practice (we stub ``/proc`` where needed).
-The stable subset runs in well under a second.
+Linux-only in practice (``/proc`` stubbed where needed). The stable
+subset runs in well under a second.
"""
from __future__ import annotations
@@ -41,8 +41,8 @@ from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_llama_cpp_load_progress.py.
+# Stub heavy/unavailable deps before importing the module under test.
+# Same pattern as test_llama_cpp_load_progress.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -113,7 +113,7 @@ def _sparse(path, size):
def _fake_proc_reader(rss_kb):
- """Return an ``open()`` replacement that fakes /proc reads with a VmRSS line."""
+ """An ``open()`` replacement faking /proc reads with a VmRSS line."""
def fake_open(path, *args, **kwargs):
if str(path).startswith("/proc/"):
@@ -129,8 +129,8 @@ def _fake_proc_reader(rss_kb):
class TestPlatformMatrix:
- """The method is Linux-first via /proc. On macOS/Windows it must
- degrade to None rather than crash."""
+ """Linux-first via /proc. On macOS/Windows must degrade to None
+ rather than crash."""
def test_linux_live_proc_is_self_pid(self, tmp_path):
"""Self-pid /proc read uses the real kernel interface."""
@@ -144,7 +144,7 @@ class TestPlatformMatrix:
assert out is not None
assert out["phase"] == "mmap"
assert out["bytes_total"] == 1 * 1024**3
- # Our Python process has some RSS -- just sanity-check positive.
+ # Our process has some RSS -- sanity-check it's positive.
assert out["bytes_loaded"] > 0
def test_macos_no_proc_returns_none(self, tmp_path):
@@ -199,7 +199,7 @@ class TestVmRSSParsing:
assert out["bytes_loaded"] == 2 * 1024**3
def test_space_separated_fallback(self, tmp_path):
- """Some kernels emit single-space rather than tab."""
+ """Some kernels emit a single space, not a tab."""
gguf = tmp_path / "m.gguf"
_sparse(gguf, 4 * 1024**3)
inst = _make()
@@ -235,8 +235,8 @@ class TestVmRSSParsing:
assert out["fraction"] == 0.0
def test_malformed_vmrss_value(self, tmp_path):
- """Non-integer VmRSS value should be treated as if the line were
- absent (early ValueError caught)."""
+ """Non-integer VmRSS is treated like an absent line (ValueError
+ caught)."""
gguf = tmp_path / "m.gguf"
_sparse(gguf, 1 * 1024**3)
inst = _make()
@@ -250,7 +250,7 @@ class TestVmRSSParsing:
with patch("builtins.open", side_effect = fake_open):
out = inst.load_progress()
- # The implementation catches ValueError on int() and returns None.
+ # int() ValueError is caught and returns None.
assert out is None
@@ -262,7 +262,7 @@ class TestVmRSSParsing:
class TestFilesystemEdges:
def test_symlink_primary_follows_to_blob(self, tmp_path):
"""HF cache stores blobs under blobs/ and symlinks them from
- snapshots/. The method must follow the symlink."""
+ snapshots/. Must follow the symlink."""
blob = tmp_path / "blob"
_sparse(blob, 12 * 1024**3)
snap = tmp_path / "snap"
@@ -300,7 +300,7 @@ class TestFilesystemEdges:
def test_relative_gguf_path(self, tmp_path):
"""Relative paths shouldn't crash; behaviour depends on CWD but
- the method must not raise."""
+ must not raise."""
cwd = os.getcwd()
try:
os.chdir(tmp_path)
@@ -323,11 +323,11 @@ class TestFilesystemEdges:
class TestShardAggregation:
def test_partial_multi_shard_download(self, tmp_path):
- """Primary present but shards 2..N still downloading as
- ``.incomplete``. Sums only the fully-arrived ``.gguf`` files."""
+ """Primary present but shards 2..N still ``.incomplete``. Sums
+ only the fully-arrived ``.gguf`` files."""
_sparse(tmp_path / "m-00001-of-00004.gguf", 30 * 1024**3)
_sparse(tmp_path / "m-00002-of-00004.gguf", 30 * 1024**3)
- # 3 and 4 still downloading as .incomplete
+ # 3 and 4 still downloading as .incomplete.
_sparse(tmp_path / "m-00003-of-00004.gguf.incomplete", 5 * 1024**3)
inst = _make()
inst._process = _Proc(os.getpid())
@@ -337,8 +337,8 @@ class TestShardAggregation:
assert out["bytes_total"] == 60 * 1024**3 # only the .gguf siblings
def test_two_shard_series_in_same_dir(self, tmp_path):
- """Defensive: if two quant series share a dir, prefix filter
- only sums siblings of the chosen primary."""
+ """Defensive: when two quant series share a dir, the prefix
+ filter sums only siblings of the chosen primary."""
for i in range(1, 3):
_sparse(tmp_path / f"m_q4-{i:05d}-of-00002.gguf", 10 * 1024**3)
_sparse(tmp_path / f"m_q8-{i:05d}-of-00002.gguf", 20 * 1024**3)
@@ -351,7 +351,7 @@ class TestShardAggregation:
def test_mmproj_sibling_not_counted(self, tmp_path):
"""Vision models drop an ``mmproj-*.gguf`` alongside. For a
- single-file (non-sharded) primary we only count the primary."""
+ single-file (non-sharded) primary, count only the primary."""
_sparse(tmp_path / "m.gguf", 8 * 1024**3)
_sparse(tmp_path / "mmproj-BF16.gguf", 2 * 1024**3)
inst = _make()
@@ -359,7 +359,7 @@ class TestShardAggregation:
inst._gguf_path = str(tmp_path / "m.gguf")
with patch("builtins.open", side_effect = _fake_proc_reader(0)):
out = inst.load_progress()
- # Non-sharded primary: only the primary is counted.
+ # Non-sharded: only the primary is counted.
assert out["bytes_total"] == 8 * 1024**3
def test_single_file_model(self, tmp_path):
@@ -381,7 +381,7 @@ class TestShardAggregation:
class TestLifecycleRaces:
def test_process_set_but_gguf_path_not_yet(self, tmp_path):
- """Moment between Popen and self._gguf_path=model_path."""
+ """Window between Popen and self._gguf_path=model_path."""
inst = _make()
inst._process = _Proc(os.getpid())
inst._gguf_path = None
@@ -418,14 +418,13 @@ class TestLifecycleRaces:
class TestConcurrentSampling:
def test_parallel_invocations_never_raise(self, tmp_path):
- """Many concurrent samplers hitting the same backend must not raise.
-
- We intentionally do NOT patch ``builtins.open`` here because
- ``unittest.mock.patch`` is not thread-safe: interleaved
- enter/exit across threads can leak a Mock into ``builtins.open``
- and poison every subsequent test in the session. Instead, we
- let each thread hit the real ``/proc/self/status`` of the test
- process, which is exactly the code path that matters in prod.
+ """Many concurrent samplers on one backend must not raise.
+
+ We do NOT patch ``builtins.open`` here: ``unittest.mock.patch``
+ is not thread-safe -- interleaved enter/exit across threads can
+ leak a Mock into ``builtins.open`` and poison later tests.
+ Instead each thread hits the real ``/proc/self/status``, the
+ code path that matters in prod.
"""
_sparse(tmp_path / "m.gguf", 1 * 1024**3)
inst = _make()
diff --git a/studio/backend/tests/test_llama_cpp_max_context_threshold.py b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
index aa0198892f5..30131991ae5 100644
--- a/studio/backend/tests/test_llama_cpp_max_context_threshold.py
+++ b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
@@ -3,22 +3,20 @@
"""Tests for the ``max_context_length`` warning-threshold semantics.
-``/api/inference/status.max_context_length`` is what the ctx slider in
-the chat settings sheet reads to decide when to render the "Exceeds
-estimated VRAM capacity. The model may use system RAM." warning:
+The ctx slider in the chat settings sheet reads
+``/api/inference/status.max_context_length`` to decide when to render the
+"Exceeds estimated VRAM capacity. The model may use system RAM." warning:
ctxDisplayValue > ggufMaxContextLength → show warning
-For models whose weights fit on some GPU subset, the warning threshold
-is the largest ctx that fits fully in VRAM (the binary-search cap from
-``_fit_context_to_vram``). For models whose weights exceed 90% of every
-GPU subset's free memory, the warning must fire as soon as the user
-drags above the 4096 spec default (otherwise a user loading e.g.
-MiniMax-M2.7 on a 97 GB GPU sees a slider up to 196608 with no
-indication that any value above 4096 will trigger ``--fit on`` and
-degrade performance).
+When weights fit on some GPU subset, the threshold is the largest ctx that
+fits fully in VRAM (the binary-search cap from ``_fit_context_to_vram``).
+When weights exceed 90% of every GPU subset's free memory, the warning must
+fire as soon as the user drags above the 4096 spec default (otherwise loading
+e.g. MiniMax-M2.7 on a 97 GB GPU shows a slider up to 196608 with no hint that
+any value above 4096 triggers ``--fit on`` and degrades performance).
-These tests pin both cases. No GPU probing, no subprocess, no GGUF I/O.
+These tests pin both cases. No GPU probing, subprocess, or GGUF I/O.
Cross-platform: Linux, macOS, Windows, WSL.
"""
@@ -31,8 +29,8 @@ from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -115,9 +113,8 @@ def _compute_max_available_ctx(
gpus,
kv_per_token_bytes = 325_000,
):
- """Run the ceiling-probe block from load_model and return the final
- ``max_available_ctx`` value the backend would assign to
- ``_max_context_length``.
+ """Run load_model's ceiling-probe block and return the final
+ ``max_available_ctx`` the backend would assign to ``_max_context_length``.
"""
inst = _make_backend(native_ctx = native_ctx)
model_size = int(model_gib * GIB)
@@ -163,8 +160,8 @@ def _compute_max_available_ctx(
class TestMaxContextLengthForWeightsExceedVRAM:
- """The UI ``max_context_length`` threshold must fall back to 4096 so
- the warning fires as soon as the user drags above the spec default.
+ """UI ``max_context_length`` must fall back to 4096 so the warning fires
+ as soon as the user drags above the spec default.
"""
def test_minimax_like(self):
@@ -186,8 +183,8 @@ class TestMaxContextLengthForWeightsExceedVRAM:
assert got == 4096
def test_native_below_fallback_is_preserved(self):
- """If the model's native ctx is itself smaller than 4096, do not
- advertise a larger value than the model supports."""
+ """If native ctx is itself below 4096, don't advertise a larger value
+ than the model supports."""
got = _compute_max_available_ctx(
native_ctx = 2048,
model_gib = 200,
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index 9e7944913a8..fc21c48b76d 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -187,9 +187,9 @@ def _mtp_backend(**overrides):
backend._requested_n_ctx = 8192
backend._cache_type_kv = None
backend._speculative_type = "draft-mtp"
- # Default fixture simulates Auto having auto-promoted to draft-mtp.
- # Individual tests override _requested_spec_mode when they want a
- # forced mode or the user---spec-type-extra-args path.
+ # Fixture simulates Auto having auto-promoted to draft-mtp. Tests
+ # override _requested_spec_mode for a forced mode or the
+ # user---spec-type-extra-args path.
backend._requested_spec_mode = "auto"
backend._chat_template_override = None
backend._is_vision = False
@@ -239,11 +239,10 @@ def test_already_in_target_state_matches_when_request_uses_default_for_mtp_model
def test_already_in_target_state_auto_request_matches_auto_backend_for_non_mtp_model():
- # Under the requested-mode round-trip model, Auto requested against an
- # Auto-recorded backend matches regardless of model name. The underlying
- # resolved emission (--spec-default vs draft-mtp) is handled by the
- # backend's own load path and reflected in _speculative_type; the
- # short-circuit comparison only cares whether the *intent* changed.
+ # In the requested-mode round-trip model, Auto-vs-Auto matches regardless
+ # of model name. The resolved emission (--spec-default vs draft-mtp) is
+ # handled by the load path and reflected in _speculative_type; the
+ # short-circuit only cares whether the *intent* changed.
backend = _mtp_backend(
_model_identifier = "unsloth/Qwen3.6-27B-GGUF",
_speculative_type = "default",
@@ -404,10 +403,10 @@ def test_already_in_target_state_vision_mtp_default_matches():
def test_already_in_target_state_vision_off_matches_vision_backend():
# Vision loads silently drop speculative decoding at the route level
- # (_request_matches_loaded_settings overrides req to "off"). At the
- # llama_cpp.py level, _already_in_target_state compares canonical
- # requested modes; a vision backend recorded with _requested_spec_mode
- # = "off" matches a req of "off" or None+vision.
+ # (_request_matches_loaded_settings overrides req to "off"). In
+ # llama_cpp.py, _already_in_target_state compares canonical requested
+ # modes; a vision backend recorded with _requested_spec_mode = "off"
+ # matches a req of "off" or None+vision.
backend = _mtp_backend(
_model_identifier = "unsloth/Qwen3-VL-4B-Instruct-GGUF",
_is_vision = True,
@@ -616,9 +615,8 @@ def test_probe_detects_legacy_ngram_mod_flavor(tmp_path):
@_NEEDS_BASH
def test_probe_ignores_removal_stub_descriptions(tmp_path):
- # Post-rename binary: legacy flags are present but with
- # "argument has been removed" descriptions; must not be detected
- # as legacy.
+ # Post-rename binary: legacy flags present but with "argument has been
+ # removed" descriptions; must not be detected as legacy.
fake = _make_fake_llama_server(tmp_path / "llama-server", _POST_RENAME_HELP)
_clear_caps_cache()
caps = LlamaCppBackend.probe_server_capabilities(str(fake))
@@ -784,16 +782,15 @@ def test_already_in_target_state_draft_n_max_ignored_when_not_mtp():
)
-# Sub-3B MTP gate -- tiny dense models regress with the MTP draft
-# head, so load_model falls back to ngram-mod (when the binary supports
-# it) instead of draft-mtp. The reload-skip mirror must follow the
-# same fallback so a sub-3B reload-with-default does not bounce a
-# correctly-configured ngram-mod / off backend.
+# Sub-3B MTP gate -- tiny dense models regress with the MTP draft head, so
+# load_model falls back to ngram-mod (when the binary supports it) instead of
+# draft-mtp. The reload-skip mirror must follow the same fallback so a sub-3B
+# reload-with-default doesn't bounce a correctly-configured ngram-mod/off backend.
def _patch_probe(monkeypatch, ngram_supported):
- """Force probe_server_capabilities to a deterministic result so
- tests don't depend on whatever llama-server happens to be on PATH."""
+ """Force probe_server_capabilities to a deterministic result so tests
+ don't depend on whatever llama-server is on PATH."""
fake = {
"found": True,
"mtp_token": "draft-mtp",
@@ -815,8 +812,8 @@ def _patch_probe(monkeypatch, ngram_supported):
def test_already_in_target_state_sub_3b_falls_back_to_ngram_mod_when_supported(monkeypatch):
- # 0.8B MTP request -- load_model would have promoted to ngram-mod
- # (no MTP head); reload check must match a ngram-mod backend.
+ # 0.8B MTP request -- load_model would have promoted to ngram-mod (no MTP
+ # head); reload check must match a ngram-mod backend.
_patch_probe(monkeypatch, ngram_supported = True)
backend = _mtp_backend(
_model_identifier = "unsloth/Qwen3.5-0.8B-MTP-GGUF",
@@ -888,8 +885,8 @@ def test_already_in_target_state_4b_mtp_request_promotes_as_before(monkeypatch):
def test_already_in_target_state_2b_falls_back_to_ngram_below_threshold(monkeypatch):
- # 2.0B is below the 3B threshold -> ngram-mod fallback, not
- # draft-mtp. Clean-bench shows 2B regresses with draft-mtp.
+ # 2.0B is below the 3B threshold -> ngram-mod fallback, not draft-mtp.
+ # Clean-bench shows 2B regresses with draft-mtp.
_patch_probe(monkeypatch, ngram_supported = True)
backend = _mtp_backend(
_model_identifier = "unsloth/Qwen3.5-2B-MTP-GGUF",
@@ -1023,9 +1020,9 @@ def _resolver_backend(
def _flags_dict(flags):
- """Parse the spec-flag list into a small {flag: value} dict; collapses
- repeated flags by keeping the last (only --spec-type can repeat and
- never does in our resolver)."""
+ """Parse the spec-flag list into a {flag: value} dict; collapses repeated
+ flags by keeping the last (only --spec-type can repeat, and never does
+ in our resolver)."""
out = {}
i = 0
while i < len(flags):
@@ -1125,8 +1122,8 @@ def test_build_speculative_flags_user_extra_args_owns_spec_type(monkeypatch):
gpus = True,
binary = "/fake/llama-server",
)
- # No flags emitted by the resolver -- the user's extra_args carries
- # the --spec-type, and the resolver records requested_spec_mode = None.
+ # Resolver emits nothing -- the user's extra_args carries the --spec-type,
+ # and the resolver records requested_spec_mode = None.
assert flags == []
assert backend.requested_spec_mode is None
assert backend.speculative_type is None
@@ -1179,7 +1176,7 @@ def test_build_speculative_flags_mtp_token_missing_logs_and_skips(monkeypatch):
binary = "/fake/llama-server",
)
assert "--spec-type" not in flags
- # _speculative_type stays None (resolved emission was none), but
- # _requested_spec_mode still reflects the user's choice.
+ # _speculative_type stays None (resolved emission was none); the user's
+ # choice is still reflected in _requested_spec_mode.
assert backend.requested_spec_mode == "mtp"
assert backend.speculative_type is None
diff --git a/studio/backend/tests/test_llama_cpp_no_context_shift.py b/studio/backend/tests/test_llama_cpp_no_context_shift.py
index b9f25faf889..312adea83e4 100644
--- a/studio/backend/tests/test_llama_cpp_no_context_shift.py
+++ b/studio/backend/tests/test_llama_cpp_no_context_shift.py
@@ -3,17 +3,15 @@
"""``--no-context-shift`` launch-flag contract.
-When llama-server runs with its default context-shift behavior, the UI
-has no way to tell the user that the KV cache has been rotated --
-earlier turns silently vanish from the conversation. The Studio
-backend always passes ``--no-context-shift`` so the server returns a
+With llama-server's default context-shift behavior, the UI cannot tell the user
+the KV cache was rotated -- earlier turns silently vanish from the conversation.
+The Studio backend always passes ``--no-context-shift`` so the server returns a
clean error instead, and the chat adapter can point the user at the
``Context Length`` input in the settings panel.
-This file is a static read of the launch command: we ask
-``LlamaCppBackend`` to assemble its ``cmd`` list and assert the flag
-is always present. Testing via the real subprocess would require an
-actual GGUF on disk, which is out of scope for the fast test suite.
+This file statically reads the launch command: we ask ``LlamaCppBackend`` to
+assemble its ``cmd`` list and assert the flag is present. Testing via the real
+subprocess would need an actual GGUF on disk, out of scope for the fast suite.
"""
from __future__ import annotations
@@ -68,11 +66,10 @@ from core.inference import llama_cpp as llama_cpp_module
def _load_model_source() -> str:
"""Return the source of ``LlamaCppBackend.load_model``.
- Using ``inspect.getsource`` instead of reading the file directly
- scopes the assertions to the function that actually launches
- llama-server, so neither the presence check nor the location check
- can be fooled by a stray occurrence of ``"--no-context-shift"``
- elsewhere in the module.
+ Using ``inspect.getsource`` instead of reading the file scopes the assertions
+ to the function that launches llama-server, so neither the presence nor the
+ location check can be fooled by a stray ``"--no-context-shift"`` elsewhere in
+ the module.
"""
return inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
@@ -80,10 +77,9 @@ def _load_model_source() -> str:
def test_no_context_shift_is_in_load_model():
"""The flag is part of the static launch-command template.
- We check the source of ``load_model`` rather than mocking the whole
- call chain (GPU probing, GGUF stat, etc.): the flag is written as
- a literal in one place and any regression has to delete it, which
- a text search will catch.
+ We check the source of ``load_model`` rather than mocking the whole call
+ chain (GPU probing, GGUF stat, etc.): the flag is a literal in one place and
+ any regression must delete it, which a text search catches.
"""
assert '"--no-context-shift"' in _load_model_source(), (
"llama-server must be launched with --no-context-shift so the "
@@ -93,21 +89,20 @@ def test_no_context_shift_is_in_load_model():
def test_flag_sits_inside_the_base_cmd_list():
- """Pin the flag's location so a future refactor can't accidentally
- move it into a branch that only fires on some code paths.
-
- We slice from ``cmd = [`` to the first ``]`` at the same indent.
- Using ``inspect.getsource`` means the function lives in its own
- string and there are no siblings to worry about, so a plain
- bracket search would also work -- anchoring on the trailing indent
- just keeps the slice from wandering into a later expression if the
- opening literal ever grows an in-line comment trailing it.
+ """Pin the flag's location so a refactor can't move it into a branch that
+ only fires on some code paths.
+
+ We slice from ``cmd = [`` to the first ``]`` at the same indent. Since
+ ``inspect.getsource`` gives the function its own string with no siblings, a
+ plain bracket search would also work -- anchoring on the trailing indent just
+ keeps the slice from wandering into a later expression if the opening literal
+ ever grows a trailing in-line comment.
"""
source = _load_model_source()
start = source.find("cmd = [")
assert start >= 0, "could not find the base cmd = [...] block"
- # Find the first line containing only ``]`` (possibly indented).
- # Works for any indentation style the formatter picks.
+ # Find the first line containing only ``]`` (possibly indented); works for
+ # any indentation style the formatter picks.
rest = source[start:]
end_rel = -1
for line_start, line in _iter_lines_with_offset(rest):
@@ -124,7 +119,7 @@ def test_flag_sits_inside_the_base_cmd_list():
"conditional branch -- otherwise some code paths would still "
"run with silent context shift enabled."
)
- # Also pin that it is next to -c / --ctx so the grouping makes sense.
+ # Also pin that it sits next to -c / --ctx so the grouping makes sense.
assert '"-c"' in block
assert '"--flash-attn"' in block
diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
index 202fd36c868..8d88a61ae3d 100644
--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py
+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
@@ -4,10 +4,10 @@
"""Tests for LlamaCppBackend._classify_llama_start_failure.
When llama-server exits before becoming healthy, load_model turns its
-captured stdout/stderr into a user-facing reason. A diffusion / image
-GGUF (FLUX, Qwen-Image, ...) is a valid file with plenty of memory, so
-the generic "invalid file or out of memory" message is actively
-misleading (issue #5842). These tests pin the classification.
+captured stdout/stderr into a user-facing reason. A diffusion/image GGUF
+(FLUX, Qwen-Image, ...) is a valid file with plenty of memory, so the
+generic "invalid file or out of memory" message is misleading (issue
+#5842). These tests pin the classification.
"""
from __future__ import annotations
@@ -22,8 +22,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
-# Match the stubbing pattern in sibling tests so the module imports in a
-# lightweight env without fastapi.
+# Match sibling tests' stubbing so the module imports in a lightweight
+# env without fastapi.
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.py
index bcf2eb16835..d787107d392 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py
@@ -3,10 +3,10 @@
"""Tests for LlamaCppBackend._wait_for_health resilience.
-The probe loop must swallow transient httpx errors and fall through to
-the subprocess.poll() branch so a crashed llama-server surfaces a
-structured "exited with code X" log instead of bubbling an opaque
-exception up to the /api/inference/load route.
+The probe loop must swallow transient httpx errors and fall through to the
+subprocess.poll() branch so a crashed llama-server surfaces a structured
+"exited with code X" log instead of bubbling an opaque exception up to the
+/api/inference/load route.
"""
from __future__ import annotations
@@ -22,8 +22,7 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
-# Match the stubbing pattern in sibling tests so the module imports in
-# a lightweight env without fastapi.
+# Mirror sibling tests' stubbing so the module imports without fastapi.
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
@@ -33,11 +32,10 @@ import httpx # noqa: E402
from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
-# Sibling tests in this directory install lightweight httpx stubs via
-# sys.modules.setdefault. When collected together, our `httpx` symbol
-# may be one of those stubs, which lacks `get`. Ensure the production
-# code finds a working `httpx.get` and the standard exception types
-# regardless of collection order by adding the missing attributes.
+# Sibling tests install lightweight httpx stubs via sys.modules.setdefault.
+# When collected together, our `httpx` may be such a stub lacking `get`. Add
+# the missing attributes so production code finds a working `httpx.get` and
+# the standard exception types regardless of collection order.
if not hasattr(httpx, "get"):
httpx.get = None # placeholder; every test below monkeypatches it
for _exc_name in (
@@ -52,9 +50,9 @@ for _exc_name in (
def _make_backend(port: int = 12345) -> LlamaCppBackend:
- """Build a barebones LlamaCppBackend instance with only the
- attributes _wait_for_health touches. Bypasses __init__ so we do not
- pull in the full subprocess + logging stack."""
+ """Barebones LlamaCppBackend with only the attributes
+ _wait_for_health touches. Bypasses __init__ to avoid the full
+ subprocess + logging stack."""
b = LlamaCppBackend.__new__(LlamaCppBackend)
b._port = port
b._stdout_thread = None
@@ -72,14 +70,12 @@ class TestWaitForHealthResilience:
assert b._wait_for_health(timeout = 1.0, interval = 0.01) is True
def test_read_error_loops_to_subprocess_poll(self, monkeypatch):
- """WinError 10054 maps to httpx.ReadError. The loop must swallow
- it and the next iteration must detect the dead subprocess via
- poll() != None, returning False with a structured exit-code log
- instead of bubbling the ReadError."""
+ """WinError 10054 maps to httpx.ReadError. The loop must swallow it;
+ the next iteration detects the dead subprocess via poll() != None and
+ returns False with a structured exit-code log, not the ReadError."""
b = _make_backend()
- # First iteration: process alive (so we reach the httpx probe).
- # Second iteration: process has exited (so we hit the structured
- # exit-code branch and return False).
+ # Iter 1: process alive (reach the httpx probe).
+ # Iter 2: process exited (hit the exit-code branch, return False).
b._process.poll.side_effect = [None, 1]
b._process.returncode = 1
b._stdout_lines = ["llama-server: ggml-cuda.dll failed to load"]
@@ -89,12 +85,12 @@ class TestWaitForHealthResilience:
monkeypatch.setattr(httpx, "get", raise_read_error)
assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
- # Both iterations of the loop ran -- the ReadError did not bubble.
+ # Both loop iterations ran -- the ReadError did not bubble.
assert b._process.poll.call_count >= 2
def test_remote_protocol_error_also_swallowed(self, monkeypatch):
- """Partial / malformed response on the probe (server crashed
- mid-headers) raises RemoteProtocolError -- also non-fatal."""
+ """A partial/malformed probe response (server crashed mid-headers)
+ raises RemoteProtocolError -- also non-fatal."""
b = _make_backend()
b._process.poll.side_effect = [None, -1]
b._process.returncode = -1
@@ -121,8 +117,8 @@ class TestWaitForHealthResilience:
assert b._process.poll.call_count >= 2
def test_connect_error_swallowed_until_success(self, monkeypatch):
- """Sanity: existing ConnectError swallowing still works -- the
- loop retries until llama-server eventually answers 200."""
+ """Sanity: existing ConnectError swallowing still works -- the loop
+ retries until llama-server answers 200."""
b = _make_backend()
b._process.poll.return_value = None
calls = {"n": 0}
@@ -139,8 +135,8 @@ class TestWaitForHealthResilience:
assert calls["n"] >= 3
def test_dead_process_before_probe_returns_false(self, monkeypatch):
- """If poll() != None on entry, _wait_for_health must return
- False immediately without calling httpx at all."""
+ """poll() != None on entry: _wait_for_health returns False
+ immediately without calling httpx."""
b = _make_backend()
b._process.poll.return_value = 137
b._process.returncode = 137
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
index 125b13782ab..51835536071 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
@@ -3,9 +3,9 @@
"""``_wait_for_vram_settle`` helper contract.
-Pins the bounded poll over ``_get_gpu_free_memory`` that bridges the
-kill -> spawn VRAM-reclaim window. Patches ``_get_gpu_free_memory``;
-no real llama-server or nvidia-smi involved.
+Pins the bounded poll over ``_get_gpu_free_memory`` bridging the kill -> spawn
+VRAM-reclaim window. Patches ``_get_gpu_free_memory``; no real llama-server or
+nvidia-smi involved.
"""
from __future__ import annotations
@@ -20,8 +20,8 @@ import pytest
# ---------------------------------------------------------------------------
-# Same external-dep stubs as the other llama_cpp tests so this module
-# imports cleanly without httpx / structlog / loggers installed.
+# Same external-dep stubs as the other llama_cpp tests so this module imports
+# without httpx / structlog / loggers installed.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
@@ -34,8 +34,8 @@ sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
sys.modules.setdefault("structlog", _structlog_stub)
-# Ensure get_logger is set even if a previous test module already
-# inserted a bare ``structlog`` stub via ``setdefault``.
+# Set get_logger even if a prior test inserted a bare ``structlog`` stub
+# via ``setdefault``.
if not hasattr(sys.modules["structlog"], "get_logger"):
sys.modules["structlog"].get_logger = _structlog_stub.get_logger
@@ -74,8 +74,8 @@ def _patch_probe(samples):
"""Patch ``_get_gpu_free_memory`` to yield ``samples`` in order.
Each entry is a list[(idx, free_mib)], a callable, or an exception
- (instance or class). Calls past the end repeat the last entry so
- tests can assert "stopped polling" via the call count.
+ (instance or class). Calls past the end repeat the last entry so tests
+ can assert "stopped polling" via the call count.
"""
state = {"i": 0, "calls": 0}
@@ -112,8 +112,8 @@ def _kw(**extra):
def test_cold_start_returns_immediately_without_probing():
- """Default ``since_kill=0.0`` is cold-start: no kill recorded,
- helper short-circuits without ever invoking the probe."""
+ """Default ``since_kill=0.0`` is cold-start: no kill recorded, so the
+ helper short-circuits without invoking the probe."""
ctx, state = _patch_probe([[(0, 10000)], [(0, 10000)]])
with ctx:
start = time.monotonic()
@@ -154,8 +154,8 @@ def test_first_probe_raises_returns_without_polling():
def test_two_consecutive_samples_within_tolerance_settles():
- """The reclaim ramp from 10000 → 11500 → 11550: third sample within
- 256 MiB of the second so the helper returns after exactly three probes."""
+ """Reclaim ramp 10000 → 11500 → 11550: third sample within 256 MiB of
+ the second, so the helper returns after exactly three probes."""
ctx, state = _patch_probe(
[
[(0, 10000)],
@@ -168,7 +168,7 @@ def test_two_consecutive_samples_within_tolerance_settles():
LlamaCppBackend._wait_for_vram_settle(**_kw(max_wait = 2.0, interval = 0.05))
elapsed = time.monotonic() - start
assert state["calls"] == 3
- # interval * 2 sleeps = 0.10; allow generous slack for scheduler jitter.
+ # interval * 2 sleeps = 0.10; allow slack for scheduler jitter.
assert elapsed < 1.0
@@ -199,7 +199,7 @@ def test_max_wait_respected_when_never_settles():
start = time.monotonic()
LlamaCppBackend._wait_for_vram_settle(**_kw(max_wait = 0.5, interval = 0.1))
elapsed = time.monotonic() - start
- # We must stop near max_wait, not run forever. Generous upper bound for CI.
+ # Must stop near max_wait, not run forever. Generous upper bound for CI.
assert 0.3 <= elapsed < 2.0, f"helper ignored max_wait: elapsed={elapsed:.3f}s"
@@ -217,8 +217,8 @@ def test_max_wait_respected_when_probe_is_slow():
**_kw(max_wait = 0.4, interval = 0.25),
)
elapsed = time.monotonic() - start
- # First probe (0.30 s) + at most one short clipped sleep + bail.
- # Hard cap well below the old behaviour of 0.30 + 0.25 + 0.30 = 0.85.
+ # First probe (0.30 s) + at most one clipped sleep + bail.
+ # Hard cap well below the old 0.30 + 0.25 + 0.30 = 0.85.
assert elapsed < 0.85, f"helper exceeded the deadline due to slow probes: {elapsed:.3f}s"
@@ -264,8 +264,8 @@ def test_tolerance_two_percent_for_large_cards():
def test_load_model_calls_helper_outside_lock_and_uses_last_kill_timestamp():
- """Pin the call site: outside Phase 3 lock, gated on the timestamp,
- no ``had_live_process`` in-band flag regression. Mirrors the
+ """Pin the call site: outside Phase 3 lock, gated on the timestamp, no
+ ``had_live_process`` in-band flag regression. Mirrors the
``inspect.getsource`` pattern from ``test_llama_cpp_no_context_shift``.
"""
import inspect
@@ -274,11 +274,11 @@ def test_load_model_calls_helper_outside_lock_and_uses_last_kill_timestamp():
assert "_wait_for_vram_settle" in src
assert "since_kill" in src
assert "self._last_kill_monotonic" in src
- # Must be invoked before Phase 3's broad lock so /unload, /cancel,
- # /status are not blocked during the wait.
+ # Must run before Phase 3's broad lock so /unload, /cancel, /status
+ # are not blocked during the wait.
assert src.index("_wait_for_vram_settle") < src.index("# ── Phase 3:")
- # An in-band ``had_live_process`` flag would silently regress the
- # frontend /unload+/load Apply path; use the timestamp instead.
+ # An in-band ``had_live_process`` flag would regress the frontend
+ # /unload+/load Apply path; use the timestamp instead.
assert "had_live_process" not in src
diff --git a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
index a5c9d2255fb..4fa7d2f8e61 100644
--- a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
+++ b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
@@ -4,9 +4,9 @@
"""Tests for the Windows pip-nvidia DLL dir resolver.
Studio installs torch with bundled CUDA wheels (nvidia-cuda-runtime-cu13,
-nvidia-cublas-cu13, etc.) and the prebuilt llama-server.exe must find
-those DLLs at runtime to load CUDA. Mirrors the Linux LD_LIBRARY_PATH
-block. See unslothai/unsloth#5106.
+nvidia-cublas-cu13, etc.) and the prebuilt llama-server.exe must find those
+DLLs at runtime to load CUDA. Mirrors the Linux LD_LIBRARY_PATH block.
+See unslothai/unsloth#5106.
"""
from __future__ import annotations
@@ -61,7 +61,7 @@ from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
def _make_nvidia_layout(prefix: Path, pkgs_with_layout: dict[str, str]):
"""Build a fake <prefix>/Lib/site-packages/nvidia/<pkg>/{bin|Library/bin}
- tree with a stub DLL inside each leaf so isdir() picks them up."""
+ tree with a stub DLL in each leaf so isdir() picks them up."""
nv = prefix / "Lib" / "site-packages" / "nvidia"
for pkg, layout in pkgs_with_layout.items():
if layout == "bin":
@@ -124,9 +124,8 @@ class TestWindowsPipNvidiaDllDirs:
assert len(result) == 4
def test_does_not_walk_outside_known_paths(self, tmp_path):
- # Only nvidia/<pkg>/{bin,Library/bin} and torch/lib are picked
- # up. Unrelated site-packages contents (numpy, scipy, ...) must
- # be ignored.
+ # Only nvidia/<pkg>/{bin,Library/bin} and torch/lib are picked up.
+ # Unrelated site-packages contents (numpy, scipy, ...) are ignored.
site = tmp_path / "Lib" / "site-packages"
(site / "numpy").mkdir(parents = True)
(site / "scipy" / "linalg").mkdir(parents = True)
@@ -135,9 +134,9 @@ class TestWindowsPipNvidiaDllDirs:
def test_picks_up_torch_lib(self, tmp_path):
# PyTorch's Windows CUDA wheel bundles cudart64_X.dll /
- # cublas64_X.dll directly under Lib/site-packages/torch/lib/
- # instead of as separate nvidia-* wheels. Without this, users
- # on torch-bundled-CUDA installs still hit #5106.
+ # cublas64_X.dll directly under Lib/site-packages/torch/lib/ rather
+ # than as separate nvidia-* wheels. Without this, torch-bundled-CUDA
+ # installs still hit #5106.
torch_lib = tmp_path / "Lib" / "site-packages" / "torch" / "lib"
torch_lib.mkdir(parents = True)
(torch_lib / "cudart64_12.dll").write_bytes(b"")
@@ -146,8 +145,7 @@ class TestWindowsPipNvidiaDllDirs:
assert Path(result[0]) == torch_lib
def test_torch_lib_combined_with_nvidia_wheels(self, tmp_path):
- # Both modular nvidia-* wheels and torch/lib are returned when
- # present together.
+ # Both modular nvidia-* wheels and torch/lib are returned together.
_make_nvidia_layout(
tmp_path,
{
@@ -165,8 +163,7 @@ class TestWindowsPipNvidiaDllDirs:
assert any(Path(p) == torch_lib for p in result)
def test_torch_lib_must_be_a_directory(self, tmp_path):
- # If torch/lib exists as a file (broken install), it is
- # ignored, not returned.
+ # If torch/lib exists as a file (broken install), it is ignored.
site = tmp_path / "Lib" / "site-packages" / "torch"
site.mkdir(parents = True)
(site / "lib").write_bytes(b"not a dir")
@@ -176,24 +173,22 @@ class TestWindowsPipNvidiaDllDirs:
def test_skips_non_directories(self, tmp_path):
nv = tmp_path / "Lib" / "site-packages" / "nvidia"
(nv / "cuda_runtime").mkdir(parents = True)
- # Create a regular file at the path where 'bin' would normally be a dir
+ # Regular file where 'bin' would normally be a dir
(nv / "cuda_runtime" / "bin").write_bytes(b"not a dir")
result = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(tmp_path))
assert result == []
def test_missing_prefix_does_not_raise(self):
- # If sys.prefix points to a path that doesn't exist (unusual,
- # but possible during test setup), the resolver must just
- # return [] rather than raising.
+ # If sys.prefix points to a nonexistent path (unusual but possible
+ # during test setup), the resolver must return [], not raise.
result = LlamaCppBackend._windows_pip_nvidia_dll_dirs("/this/path/does/not/exist/anywhere")
assert result == []
def test_picks_up_cu13_bin_x86_64_layout(self, tmp_path):
- # Current ``nvidia-cuda-runtime`` 13.x and ``nvidia-cublas``
- # 13.x Windows wheels ship DLLs under
- # ``nvidia/cu13/bin/x86_64/`` instead of ``nvidia/<pkg>/bin/``.
- # Without this, users on the new CUDA 13 wheel generation hit
- # the original #5106 failure mode.
+ # Current ``nvidia-cuda-runtime`` 13.x and ``nvidia-cublas`` 13.x
+ # Windows wheels ship DLLs under ``nvidia/cu13/bin/x86_64/`` instead
+ # of ``nvidia/<pkg>/bin/``. Without this, the new CUDA 13 wheel
+ # generation hits the original #5106 failure mode.
dll_dir = tmp_path / "Lib" / "site-packages" / "nvidia" / "cu13" / "bin" / "x86_64"
dll_dir.mkdir(parents = True)
for name in ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"):
@@ -203,7 +198,7 @@ class TestWindowsPipNvidiaDllDirs:
def test_picks_up_bin_x64_layout(self, tmp_path):
# Some repackaged wheels use ``bin/x64`` (Windows-x64 convention)
- # instead of ``bin/x86_64`` (NVIDIA-internal convention).
+ # rather than ``bin/x86_64`` (NVIDIA-internal convention).
dll_dir = tmp_path / "Lib" / "site-packages" / "nvidia" / "cu13" / "bin" / "x64"
dll_dir.mkdir(parents = True)
(dll_dir / "cudart64_13.dll").write_bytes(b"")
@@ -211,9 +206,8 @@ class TestWindowsPipNvidiaDllDirs:
assert str(dll_dir) in result
def test_mixed_cu12_and_cu13_layouts(self, tmp_path):
- # A venv could have both the modular cu12 wheels (legacy) and
- # the unsuffixed cu13 wheel installed side by side. Both must
- # be reachable.
+ # A venv could have both the modular cu12 wheels (legacy) and the
+ # unsuffixed cu13 wheel side by side. Both must be reachable.
site = tmp_path / "Lib" / "site-packages"
cu12_bin = site / "nvidia" / "cuda_runtime" / "bin"
cu13_arch = site / "nvidia" / "cu13" / "bin" / "x86_64"
@@ -225,10 +219,10 @@ class TestWindowsPipNvidiaDllDirs:
assert cu13_arch in result_set
def test_glob_meta_in_prefix_is_safe(self, tmp_path):
- # Windows usernames / install paths can contain ``[`` or ``]``.
- # A glob-based resolver would interpret these as a character
- # class and silently return [] even when DLL dirs exist. The
- # iterdir-based implementation must work on such paths.
+ # Windows usernames / install paths can contain ``[`` or ``]``. A
+ # glob-based resolver would read these as a character class and
+ # return [] even when DLL dirs exist. The iterdir-based
+ # implementation must work on such paths.
prefix = tmp_path / "studio_[gpu]_install"
dll_dir = prefix / "Lib" / "site-packages" / "nvidia" / "cuda_runtime" / "bin"
dll_dir.mkdir(parents = True)
@@ -237,18 +231,17 @@ class TestWindowsPipNvidiaDllDirs:
assert str(dll_dir) in result, f"bracket-prefixed path returned empty: {result}"
def test_arch_subdir_listed_before_parent_bin(self, tmp_path):
- # When both ``nvidia/<pkg>/bin/`` and
- # ``nvidia/<pkg>/bin/x86_64/`` exist, the arch-specific subdir
- # must be listed first so Windows DLL search picks up the
- # cudart64_X.dll location even if the parent ``bin`` is empty.
+ # When both ``nvidia/<pkg>/bin/`` and ``nvidia/<pkg>/bin/x86_64/``
+ # exist, the arch-specific subdir must be listed first so the Windows
+ # DLL search finds cudart64_X.dll even if the parent ``bin`` is empty.
site = tmp_path / "Lib" / "site-packages"
outer_bin = site / "nvidia" / "cu13" / "bin"
arch_bin = outer_bin / "x86_64"
arch_bin.mkdir(parents = True)
(arch_bin / "cudart64_13.dll").write_bytes(b"")
result = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(tmp_path))
- # outer_bin exists as a directory (it contains arch_bin); the
- # arch-specific subdir should come first in the list.
+ # outer_bin exists as a dir (it holds arch_bin); the arch-specific
+ # subdir should come first in the list.
result_paths = [Path(p) for p in result]
assert arch_bin in result_paths
assert outer_bin in result_paths
diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.py
index 2c7362a9ff1..60d4fb0bc38 100644
--- a/studio/backend/tests/test_llama_server_args.py
+++ b/studio/backend/tests/test_llama_server_args.py
@@ -4,8 +4,8 @@
"""Unit tests for the llama-server pass-through args validator.
The validator is the boundary between user CLI/HTTP input and the
-llama-server subprocess. These tests pin denylist behaviour so it
-doesn't quietly regress when new managed flags are added.
+llama-server subprocess. These tests pin denylist behaviour so it doesn't
+regress when new managed flags are added.
"""
from __future__ import annotations
@@ -16,10 +16,10 @@ from pathlib import Path
import pytest
-# Load llama_server_args.py directly so this test doesn't drag in the
-# full backend chain (fastapi / structlog / loggers / utils.hardware)
-# via core/inference/__init__.py. The validator is intentionally
-# dependency-free and unit-tests should reflect that.
+# Load llama_server_args.py directly so this test doesn't drag in the full
+# backend chain (fastapi / structlog / loggers / utils.hardware) via
+# core/inference/__init__.py. The validator is intentionally dependency-free
+# and unit tests should reflect that.
_LSA_PATH = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_server_args.py"
_spec = importlib.util.spec_from_file_location("_lsa_test_only", _LSA_PATH)
_lsa = importlib.util.module_from_spec(_spec)
@@ -72,10 +72,10 @@ validate_extra_args = _lsa.validate_extra_args
# Reasoning controls
["--reasoning-format", "deepseek"],
["-rea", "auto"],
- # Soft-managed: user-supplied flags last-wins-override Studio's
- # auto-set version. --parallel / -np / --n-parallel are NOT
- # here -- they're hard-denied (KV-cache + slot count would
- # desync). Use `unsloth studio run --parallel N` instead.
+ # Soft-managed: user flags last-wins-override Studio's auto-set
+ # version. --parallel / -np / --n-parallel are NOT here -- they're
+ # hard-denied (KV-cache + slot count would desync). Use
+ # `unsloth studio run --parallel N` instead.
["-c", "131072"],
["--ctx-size", "8192"],
["--flash-attn", "off"],
@@ -124,8 +124,8 @@ def test_non_flag_token_passes_through():
"-np",
"--parallel",
"--n-parallel",
- # Model identity (every alias; bumping llama.cpp must keep
- # every form rejected, not just the long).
+ # Model identity (every alias; bumping llama.cpp must keep every
+ # form rejected, not just the long one).
"-m",
"--model",
"-mu",
@@ -173,8 +173,8 @@ def test_non_flag_token_passes_through():
"--models-max",
"--models-autoload",
"--no-models-autoload",
- # Server-mode flips: --embedding / --rerank would restrict
- # llama-server to those endpoints and break Studio's chat hop.
+ # Server-mode flips: --embedding / --rerank restrict llama-server to
+ # those endpoints and break Studio's chat hop.
"--embedding",
"--embeddings",
"--rerank",
@@ -191,16 +191,16 @@ def test_denylist_rejects_all_aliases(denied):
@pytest.mark.parametrize(
"args,offending",
[
- # Pass-through --parallel would last-wins-override the real
- # slot count while Studio's KV-cache fit + llama_parallel_slots
- # stay at the typer value -- plan vs. process disagree.
+ # Pass-through --parallel would last-wins-override the real slot
+ # count while Studio's KV-cache fit + llama_parallel_slots stay at
+ # the typer value -- plan vs. process disagree.
(["--parallel", "8"], "--parallel"),
(["--parallel=8"], "--parallel"),
(["--n-parallel", "16"], "--n-parallel"),
(["--n-parallel=16"], "--n-parallel"),
(["-np", "32"], "-np"),
- # Attached short form: Click clusters it CLI-side; HTTP /load
- # with `["-np8"]` must still resolve to managed.
+ # Attached short form: Click clusters it CLI-side; HTTP /load with
+ # `["-np8"]` must still resolve to managed.
(["-np8"], "-np"),
(["-np64"], "-np"),
# Out-of-range values that would bypass the typer 1..64 guard.
@@ -227,8 +227,8 @@ def test_denylist_rejects_equals_form():
[" --parallel", "--parallel ", "\t--parallel", " -np", "-np \n", "-np\t"],
)
def test_denylist_rejects_whitespace_padded_forms(padded):
- # `_flag_name` trims whitespace before lookup; otherwise a trailing
- # space could slip a managed flag past the boundary.
+ # `_flag_name` trims whitespace before lookup; else a trailing space
+ # could slip a managed flag past the boundary.
with pytest.raises(ValueError, match = "parallel|np"):
validate_extra_args([padded, "8"])
@@ -238,15 +238,15 @@ def test_denylist_rejects_whitespace_padded_forms(padded):
["-np8x", "-np-1foo", "-np+1bar", "-np9zzz"],
)
def test_denylist_rejects_np_with_digit_prefix_and_junk(attached):
- # Backend `_flag_name` must classify the same forms the CLI
- # rewriter expands, else HTTP /load could smuggle `-np8x` through.
+ # Backend `_flag_name` must classify the same forms the CLI rewriter
+ # expands, else HTTP /load could smuggle `-np8x` through.
with pytest.raises(ValueError, match = "np"):
validate_extra_args([attached])
def test_denylist_rejects_short_form_when_long_is_denied():
- # `-m` is the short form of --model; rejecting only the long
- # form would leave a trivial bypass.
+ # `-m` is the short form of --model; rejecting only the long form
+ # would leave a trivial bypass.
with pytest.raises(ValueError, match = "-m"):
validate_extra_args(["-m", "/some/other/path.gguf"])
diff --git a/studio/backend/tests/test_log_filter_no_truncation.py b/studio/backend/tests/test_log_filter_no_truncation.py
index d9a6e2bc4ac..52ffa2ba32d 100644
--- a/studio/backend/tests/test_log_filter_no_truncation.py
+++ b/studio/backend/tests/test_log_filter_no_truncation.py
@@ -4,9 +4,9 @@
"""
Regression tests for loggers.handlers.filter_sensitive_data.
-Pins two properties: (1) long strings with commas/slashes pass through
-unchanged (the base64-truncation heuristic from PR #5246 was too aggressive),
-and (2) native-path lease redaction still fires for both inline and dict-key forms.
+Pins two properties: (1) long strings with commas/slashes pass through unchanged
+(the base64-truncation heuristic from PR #5246 was too aggressive), and
+(2) native-path lease redaction still fires for inline and dict-key forms.
"""
from loggers.handlers import filter_sensitive_data
diff --git a/studio/backend/tests/test_login_rate_limit.py b/studio/backend/tests/test_login_rate_limit.py
index 1b084cf4361..6f2d2c7d94e 100644
--- a/studio/backend/tests/test_login_rate_limit.py
+++ b/studio/backend/tests/test_login_rate_limit.py
@@ -4,11 +4,11 @@
"""Tests for the per-(ip, username) login rate limiter.
Covers:
- - bucket key composition is (client-ip, username.lower())
- - X-Forwarded-For is honoured only when UNSLOTH_STUDIO_TRUST_FORWARDED is set
+ - bucket key is (client-ip, username.lower())
+ - X-Forwarded-For honoured only when UNSLOTH_STUDIO_TRUST_FORWARDED is set
- 429 detail body does NOT leak the client IP
- - One username failing does not lock out a different user from the same IP
- - One IP failing does not lock out the same user from a different IP
+ - One username failing doesn't lock out a different user from the same IP
+ - One IP failing doesn't lock out the same user from a different IP
"""
import os
@@ -69,8 +69,8 @@ class TestClientIp:
"127.0.0.1",
{"x-forwarded-for": "198.51.100.7, 10.0.0.1"},
)
- # The proxy header could be spoofed; without the opt-in we
- # only trust the direct connection.
+ # Proxy header can be spoofed; without the opt-in, trust only the
+ # direct connection.
assert _client_ip(req) == "127.0.0.1"
def test_honours_first_xff_when_trust_on(self, env_trust_proxy):
@@ -123,8 +123,8 @@ class TestClientIp:
def test_forwarded_isolates_first_element(self, env_trust_proxy):
from routes.auth import _client_ip
- # Multi-element Forwarded must pick the first element only,
- # otherwise suffix variations create attacker-controlled buckets.
+ # Multi-element Forwarded must pick the first element only, else suffix
+ # variations create attacker-controlled buckets.
req = _FakeRequest(
"127.0.0.1",
{"forwarded": "for=198.51.100.42, for=10.0.0.1;proto=https"},
@@ -155,7 +155,7 @@ class TestBucketKeyAndBlocking:
for _ in range(_LOGIN_MAX_FAILS):
_record_login_failure(_bucket_key(req, "alice"))
assert _login_blocked(_bucket_key(req, "alice")) > 0
- # bob's account from the same IP is unaffected by alice's typos.
+ # bob's account from the same IP is unaffected by alice's typos
assert _login_blocked(_bucket_key(req, "bob")) == 0
def test_record_per_ip_isolates_other_ips(self, env_no_proxy):
@@ -189,8 +189,8 @@ class TestBucketKeyAndBlocking:
req = _FakeRequest("203.0.113.10")
for idx in range(5):
auth_routes._record_login_failure(auth_routes._unknown_user_key(req))
- # Different "username" each attempt would not have throttled
- # under per-(ip,username) only; the IP aggregate must.
+ # A different "username" each attempt wouldn't throttle under
+ # per-(ip,username) only; the IP aggregate must.
# The next missing-user attempt is blocked.
assert auth_routes._login_blocked(auth_routes._unknown_user_key(req)) > 0
@@ -202,8 +202,8 @@ class TestBucketKeyAndBlocking:
unknown_key = auth_routes._unknown_user_key(req)
for _ in range(20):
auth_routes._record_login_failure(unknown_key)
- # Account bucket cardinality stays at exactly one sentinel entry
- # for this IP regardless of how many distinct usernames sprayed.
+ # Account bucket cardinality stays at exactly one sentinel entry for
+ # this IP regardless of how many distinct usernames sprayed.
ip_keys = [k for k in auth_routes._LOGIN_BUCKETS if k[0] == "203.0.113.11"]
assert len(ip_keys) == 1
assert ip_keys[0][1].startswith("\x00")
@@ -216,7 +216,7 @@ class TestBucketKeyAndBlocking:
req = _FakeRequest("203.0.113.12")
for idx in range(50):
auth_routes._record_login_failure((req.client.host, f"user-{idx}"))
- # Hard cap respected; further keys do not allocate.
+ # Hard cap respected; further keys don't allocate.
assert len(auth_routes._LOGIN_BUCKETS) <= 10
@@ -249,7 +249,7 @@ class TestLogin429Body:
def test_429_detail_does_not_leak_ip(self, env_no_proxy, login_client):
from routes.auth import _LOGIN_MAX_FAILS
- # Drive 6 failures from the same client IP / username.
+ # Drive 6 failures from the same client IP / username
for _ in range(_LOGIN_MAX_FAILS):
r = login_client.post(
"/api/auth/login",
@@ -262,8 +262,8 @@ class TestLogin429Body:
)
assert r.status_code == 429
detail = r.json()["detail"]
- # The 429 body must not interpolate the source IP.
+ # The 429 body must not interpolate the source IP
assert "127.0.0.1" not in detail
assert "Too many" in detail
- # Retry-After header is still set for clients.
+ # Retry-After header is still set for clients
assert "Retry-After" in r.headers
diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.py
index 0d263d7630a..9def1619d78 100644
--- a/studio/backend/tests/test_mcp_servers.py
+++ b/studio/backend/tests/test_mcp_servers.py
@@ -151,8 +151,8 @@ def test_execute_tool_disabled_server(tmp_path, monkeypatch):
def test_mcp_specs_skip_invalid_openai_function_names():
- """OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; tools whose
- names contain '.', '/', spaces, etc. would 400 the whole request."""
+ """OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; names with '.',
+ '/', spaces, etc. would 400 the whole request."""
from core.inference.tools import _mcp_specs_for_server
server = {"id": "srv", "display_name": "S"}
@@ -178,7 +178,7 @@ def test_mcp_specs_skip_empty_tool_name():
def test_mcp_specs_drops_duplicate_names():
"""Same tool name twice from one MCP server -> OpenAI rejects the
- request as 'duplicates'. Drop the duplicate before forwarding."""
+ request as 'duplicates'. Drop duplicates before forwarding."""
from core.inference.tools import _mcp_specs_for_server
server = {"id": "srv", "display_name": "S"}
@@ -188,8 +188,8 @@ def test_mcp_specs_drops_duplicate_names():
def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
- """cancel_event already set before the call -> immediate Error: cancelled
- without making a network round-trip."""
+ """cancel_event set before the call -> immediate Error: cancelled, no
+ network round-trip."""
import threading
from core.inference import mcp_client
@@ -203,7 +203,7 @@ def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
async def call_tool(self, name, args):
import asyncio as _asyncio
- await _asyncio.sleep(30) # never finishes within the test
+ await _asyncio.sleep(30) # never finishes during the test
monkeypatch.setattr(mcp_client, "_client", lambda *a, **kw: _StubClient())
@@ -221,8 +221,8 @@ def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
def test_clear_oauth_tokens_async_no_op_safe(tmp_path, monkeypatch):
- """clear_oauth_tokens_async on a URL with no stored token must not raise --
- the delete + update handlers call it best-effort regardless of prior state."""
+ """clear_oauth_tokens_async on a URL with no stored token must not raise;
+ the delete + update handlers call it best-effort regardless of state."""
import asyncio
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
@@ -233,7 +233,7 @@ def test_clear_oauth_tokens_async_no_op_safe(tmp_path, monkeypatch):
def test_delete_server_calls_oauth_cleanup_when_oauth_was_on(tmp_path, monkeypatch):
- """delete_mcp_server route helper should invoke clear_oauth_tokens_async
+ """delete_mcp_server route helper must call clear_oauth_tokens_async
when the deleted row had use_oauth=true."""
import asyncio
@@ -255,7 +255,7 @@ def test_delete_server_calls_oauth_cleanup_when_oauth_was_on(tmp_path, monkeypat
calls.append(url)
monkeypatch.setattr(mcp_client, "clear_oauth_tokens_async", fake_clear)
- # Re-import the route's binding through the module so the patch is seen.
+ # Patch the route's module binding too so it's seen.
import routes.mcp_servers as routes_mcp
monkeypatch.setattr(routes_mcp, "clear_oauth_tokens_async", fake_clear)
@@ -292,7 +292,7 @@ def test_delete_server_skips_oauth_cleanup_when_oauth_off(tmp_path, monkeypatch)
def test_update_server_clears_oauth_on_url_change(tmp_path, monkeypatch):
"""Changing the URL on an OAuth server must drop the old URL's tokens
- so the new URL doesn't silently inherit credentials."""
+ so the new URL doesn't inherit credentials."""
import asyncio
_reset_db(tmp_path, monkeypatch)
@@ -381,7 +381,7 @@ def test_changes_from_payload_rejects_null_use_oauth():
def test_test_endpoint_surfaces_url_validation_as_400(tmp_path, monkeypatch):
"""POST /api/mcp/servers/test must 400 on invalid URL like create/update;
- previously the same input returned 200 with {"ok": false}."""
+ it previously returned 200 with {"ok": false}."""
import asyncio
_reset_db(tmp_path, monkeypatch)
@@ -399,9 +399,9 @@ def test_test_endpoint_surfaces_url_validation_as_400(tmp_path, monkeypatch):
def test_tool_xml_parser_handles_hyphenated_parameter_names():
- """MCP tool schemas commonly use hyphenated property names like
+ """MCP tool schemas often use hyphenated property names like
`issue-number` / `repo-name`; the XML parser's `<parameter=\\w+>` regex
- dropped those keys. Verify hyphenated parameter names round-trip."""
+ dropped those keys. Verify hyphenated names round-trip."""
from core.inference.tool_call_parser import parse_tool_calls_from_text
import json as _json
@@ -428,9 +428,9 @@ def test_tool_healing_strip_handles_hyphenated_function_names():
def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
- """When the model emits a tool call not in the per-request tool list
- the GGUF agentic loop must refuse to dispatch -- mirroring the
- safetensors path. Previously execute_tool ran the call regardless."""
+ """When the model emits a tool call not in the per-request tool list,
+ the GGUF agentic loop must refuse to dispatch (mirroring the
+ safetensors path). execute_tool previously ran the call regardless."""
from core.inference import tools as tools_mod
captured: list[str] = []
@@ -441,8 +441,8 @@ def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
monkeypatch.setattr(tools_mod, "execute_tool", fake_execute)
- # Re-create the allow-list check inline so we can unit-test the
- # behavior without spinning up llama-server.
+ # Re-create the allow-list check inline to unit-test the behavior
+ # without spinning up llama-server.
def _gate(tools_advertised, called_name, args):
allowed = {
(t.get("function") or {}).get("name")
@@ -472,9 +472,9 @@ def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
def test_call_tool_sync_short_circuits_on_pre_set_cancel(monkeypatch):
- """cancel_event set BEFORE call_tool_sync runs -> no HTTP request
- is made. Previously the call task was created before the cancel
- check, opening a transport that the watcher then had to cancel."""
+ """cancel_event set BEFORE call_tool_sync runs -> no HTTP request made.
+ The call task was previously created before the cancel check, opening a
+ transport that the watcher then had to cancel."""
from core.inference import mcp_client
opened: list[str] = []
@@ -510,9 +510,9 @@ def test_call_tool_sync_short_circuits_on_pre_set_cancel(monkeypatch):
def test_clear_oauth_tokens_swallows_constructor_errors(tmp_path, monkeypatch):
- """clear_oauth_tokens_async is best-effort; an OAuth constructor
- failure (e.g. missing fastmcp.client.auth) must not bubble out into
- a 500 from the delete / update routes."""
+ """clear_oauth_tokens_async is best-effort; an OAuth constructor failure
+ (e.g. missing fastmcp.client.auth) must not bubble into a 500 from the
+ delete / update routes."""
import asyncio
from core.inference import mcp_client
@@ -535,8 +535,8 @@ def test_clear_oauth_tokens_swallows_constructor_errors(tmp_path, monkeypatch):
def test_tool_xml_parser_handles_hyphenated_function_names():
"""MCP tool names are advertised as `mcp__srv__list-issues` (the regex
- fix allows '-'); the XML tool-call parser must parse them too,
- otherwise the model can call the tool but Studio cannot dispatch."""
+ fix allows '-'); the XML tool-call parser must parse them too, else the
+ model can call the tool but Studio cannot dispatch."""
from core.inference.tool_call_parser import parse_tool_calls_from_text
calls = parse_tool_calls_from_text(
@@ -552,7 +552,7 @@ def test_tool_xml_parser_handles_hyphenated_function_names():
def test_tool_xml_strip_handles_hyphenated_function_names():
"""routes/inference.py:_TOOL_XML_RE must strip a `<function=name-with-dash>`
- block; otherwise hyphenated MCP tool-call XML leaks into chat history."""
+ block; else hyphenated MCP tool-call XML leaks into chat history."""
import re as _re
from pathlib import Path
@@ -570,11 +570,10 @@ def test_tool_xml_strip_handles_hyphenated_function_names():
def test_safetensors_agentic_empty_allowlist_still_means_allow_all():
- """Document existing contract: at the safetensors_agentic layer,
- tools=[] is still treated as "no constraint" (so existing callers
- work unchanged). The real fix for the MCP-only-no-discovery case
- lives at the route level in inference.py, which refuses to enter
- use_tools when the resolved tool list is empty."""
+ """Document the contract: at the safetensors_agentic layer, tools=[] is
+ still "no constraint" (existing callers work unchanged). The real fix
+ for the MCP-only-no-discovery case lives at the route level in
+ inference.py, which refuses use_tools when the resolved list is empty."""
import threading
from core.inference.safetensors_agentic import run_safetensors_tool_loop
diff --git a/studio/backend/tests/test_mcp_stdio_improvements.py b/studio/backend/tests/test_mcp_stdio_improvements.py
index 515e39d5b69..bec4f9393e5 100644
--- a/studio/backend/tests/test_mcp_stdio_improvements.py
+++ b/studio/backend/tests/test_mcp_stdio_improvements.py
@@ -1,8 +1,8 @@
"""Tests for the proposed PR #5863 improvements.
Covers: _client() self-gating + keep_alive, OAuth normalised off for stdio
-(create + update), env/header dropped on a transport-type switch, and the
-backend rejecting a command whose first token is a URL scheme.
+(create + update), env/header dropped on a transport-type switch, and rejecting
+a command whose first token is a URL scheme.
Run from studio/backend: python -m pytest tests/test_mcp_stdio_improvements.py -q
"""
@@ -41,7 +41,7 @@ def test_client_refuses_stdio_when_disabled(monkeypatch):
def test_client_builds_stdio_when_enabled_without_spawning(monkeypatch):
_enable(monkeypatch)
# Constructing the Client must not spawn the subprocess (spawn happens on
- # __aenter__); we only assert it builds.
+ # __aenter__); only assert it builds.
client = mcp_client._client("npx -y server /tmp", {"K": "v"})
assert client is not None
@@ -122,7 +122,7 @@ def test_switch_stdio_to_http_drops_env(tmp_path, monkeypatch):
"s1", McpServerUpdate(url = "https://remote/mcp"), current_subject = "u"
)
)
- # the stdio env must NOT survive as HTTP headers on the remote endpoint
+ # stdio env must NOT survive as HTTP headers on the remote endpoint
assert resp.headers == {}
assert mcp_servers_db.get_server("s1")["headers_json"] is None
@@ -161,7 +161,7 @@ def test_same_transport_edit_keeps_headers(tmp_path, monkeypatch):
url = "npx server",
headers_json = '{"API_KEY": "secret"}',
)
- # editing only the display name (still stdio) must not wipe env vars
+ # editing only the display name (still stdio) must keep env vars
resp = asyncio.run(
routes_mcp.update_mcp_server("s1", McpServerUpdate(display_name = "B"), current_subject = "u")
)
@@ -183,13 +183,13 @@ def test_validate_url_rejects_url_scheme_command_when_enabled(monkeypatch):
def test_validate_url_allows_url_in_argument(monkeypatch):
from routes.mcp_servers import _validate_url
_enable(monkeypatch)
- # :// inside an ARGUMENT (not the first token) is still a valid command
+ # :// inside an ARGUMENT (not the first token) is a valid command
assert _validate_url("npx server --url https://x/mcp") == ("npx server --url https://x/mcp")
# ── P6: Data Recipe stdio path obeys the same host gate ─────────────
-# build_mcp_providers needs the data_designer plugin, which is only installed in
-# the Studio test job; skip there rather than fail the core matrix.
+# build_mcp_providers needs the data_designer plugin, installed only in the
+# Studio test job; skip there rather than fail the core matrix.
_STDIO_RECIPE = {
"mcp_providers": [
@@ -209,7 +209,7 @@ def test_data_recipe_skips_stdio_when_disabled(monkeypatch):
_disable(monkeypatch)
from core.data_recipe.service import build_mcp_providers
- # gate off -> the stdio provider is dropped (no subprocess can be spawned)
+ # gate off -> the stdio provider is dropped (no subprocess spawned)
assert build_mcp_providers(_STDIO_RECIPE) == []
diff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.py
index 277306836b4..d744c07b14e 100644
--- a/studio/backend/tests/test_mcp_stdio_pr5863.py
+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py
@@ -2,10 +2,10 @@
Covers the pure helpers (is_stdio / parse_stdio_command / stdio_mcp_enabled /
probe_timeout), the route-level _validate_url gate, and - most importantly -
-that the UNSLOTH_STUDIO_ALLOW_STDIO_MCP gate blocks the stdio transport at all
-five enforcement points (create, update, test, refresh, discovery, execute)
-when disabled, and reaches it when enabled. The transport (_client) is stubbed
-so no real subprocess is spawned; a recorder asserts whether it was reached.
+that the UNSLOTH_STUDIO_ALLOW_STDIO_MCP gate blocks the stdio transport at
+every enforcement point (create, update, test, refresh, discovery, execute)
+when disabled and reaches it when enabled. The transport (_client) is stubbed
+so no real subprocess spawns; a recorder asserts whether it was reached.
Run from studio/backend: python -m pytest tests/test_mcp_stdio_pr5863.py -q
"""
@@ -57,7 +57,7 @@ class _FakeResult:
class _RecordingClient:
- """Stands in for fastmcp.Client; records that the transport was opened."""
+ """Stand-in for fastmcp.Client; records that the transport was opened."""
def __init__(self, url, headers, use_oauth, recorder):
recorder.append({"url": url, "headers": headers, "use_oauth": use_oauth})
@@ -78,7 +78,7 @@ class _RecordingClient:
@pytest.fixture
def transport(monkeypatch):
"""Patch mcp_client._client with a recorder. Returns the recorder list;
- empty == the stdio transport was never reached."""
+ empty == stdio transport never reached."""
recorder = []
monkeypatch.setattr(
mcp_client,
@@ -156,8 +156,8 @@ def test_parse_unclosed_quote_raises_valueerror():
def test_parse_windows_strips_wrapping_quotes(monkeypatch):
- # gemini "medium": posix=False keeps backslash paths but also the wrapping
- # quotes; the PR strips a matched pair so argv[0] reaches the OS clean.
+ # gemini "medium": posix=False keeps backslash paths but also the
+ # wrapping quotes; the PR strips a matched pair so argv[0] is clean.
monkeypatch.setattr(sys, "platform", "win32")
parts = mcp_client.parse_stdio_command(r'"C:\Program Files\node\node.exe" server.js')
assert parts[0] == r"C:\Program Files\node\node.exe"
@@ -214,8 +214,8 @@ def test_validate_url_gate_off_rejects_stdio(monkeypatch):
def test_validate_url_gate_off_message_depends_on_whitespace(monkeypatch):
- # The message names a command only when the value has whitespace, and never
- # says "desktop app only" (self-hosted hosts can opt in via the env var).
+ # The message names a command only when the value has whitespace, and
+ # never says "desktop app only" (self-hosted can opt in via the env var).
_disable(monkeypatch)
from routes.mcp_servers import _validate_url
@@ -242,8 +242,8 @@ def test_validate_url_gate_on_accepts_stdio(monkeypatch):
assert _validate_url("https://x/mcp") == "https://x/mcp"
# url-bearing argument accepted as a command
assert _validate_url("npx server --url https://x/mcp") == ("npx server --url https://x/mcp")
- # A lone token is ambiguous; keep the prior behaviour and accept it as a
- # command rather than guessing it's a URL (no regression for single binaries).
+ # A lone token is ambiguous; accept it as a command rather than
+ # guessing it's a URL (no regression for single binaries).
assert _validate_url("/usr/local/bin/my-mcp-server") == "/usr/local/bin/my-mcp-server"
assert _validate_url("mcp-server-sqlite") == "mcp-server-sqlite"
# empty / unparseable still rejected
@@ -284,7 +284,7 @@ def test_update_http_to_stdio_blocked_when_off(tmp_path, monkeypatch):
_reset_db(tmp_path, monkeypatch)
_disable(monkeypatch)
mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")
- # editing url -> stdio command must 400 (http->stdio edit bypass closed)
+ # editing url -> stdio command must 400 (http->stdio bypass closed)
with pytest.raises(HTTPException) as exc:
asyncio.run(
routes_mcp.update_mcp_server(
@@ -321,7 +321,7 @@ def test_refresh_route_gate(tmp_path, monkeypatch, transport):
import routes.mcp_servers as routes_mcp
_reset_db(tmp_path, monkeypatch)
- # a stdio row as if carried over from a desktop DB
+ # a stdio row, as if carried over from a desktop DB
mcp_servers_db.create_server(id = "stdio1", display_name = "FS", url = "npx server")
_disable(monkeypatch)
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 2d6efa9f8b5..2ff7acfbd06 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -109,8 +109,8 @@ class TestMaxBodyMiddleware:
assert "too large" in r.json()["detail"].lower()
def test_chunked_upload_over_cap_rejected(self, main_module):
- # Regression: declared-Content-Length-only check could be bypassed
- # by chunked transfer-encoding.
+ # Regression: declared-Content-Length-only check could be bypassed by
+ # chunked transfer-encoding.
app = _make_protected_app(1024, main_module)
c = TestClient(app)
@@ -282,13 +282,13 @@ class TestSecurityHeadersMiddleware:
def test_img_src_allows_google_favicons(self, main_module):
# sources.tsx fetches https://www.google.com/s2/favicons?... ; without
- # this allowlist entry citation favicons fall back to gray initials.
+ # this allowlist entry, citation favicons fall back to gray initials.
csp = main_module._build_csp()
img_directive = next(
chunk.strip() for chunk in csp.split(";") if chunk.strip().startswith("img-src ")
)
- # Tokenise and compare with `==` so CodeQL's URL-substring rule does
- # not read directive-string `in` membership as URL sanitisation.
+ # Tokenise and compare with `==` so CodeQL's URL-substring rule
+ # doesn't read directive-string `in` membership as URL sanitisation.
img_sources = img_directive.split()
assert any(src == "https://www.google.com" for src in img_sources)
# Pre-existing favicon CDNs stay allowed.
@@ -332,9 +332,9 @@ def health_app(tmp_path, monkeypatch):
class TestHealthAuthGate:
- # Launcher / frontend bootstrap fields are available unauth so the Tauri
- # watchdog can re-adopt a sibling backend and the SPA can detect chat-only
- # mode before any token exists. Version / device_type still require a bearer.
+ # Launcher / frontend bootstrap fields are unauth so the Tauri watchdog can
+ # re-adopt a sibling backend and the SPA can detect chat-only mode before
+ # any token exists. Version / device_type still require a bearer.
LAUNCHER_BITS = (
"service",
"studio_root_id",
@@ -361,7 +361,7 @@ class TestHealthAuthGate:
assert forbidden not in body
def test_invalid_bearer_returns_launcher_bits_only(self, health_app):
- # Regression: calling the async dep without await made any Bearer header pass.
+ # Regression: calling the async dep without await let any Bearer header pass.
c = TestClient(health_app)
r = c.get(
"/api/health",
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 49afab048d8..9871965ce8f 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -159,10 +159,9 @@ def test_mlx_inference_vlm_lora_uses_unsloth_loader_without_native_adapter_rewri
assert isinstance(backend._tokenizer, _DummyTokenizer)
-# Regression: MLXInferenceBackend.generate_chat_response must accept the
-# four template kwargs (tools / enable_thinking / reasoning_effort /
-# preserve_thinking) so the route layer can forward what the user
-# toggled in the UI. The previous signature raised
+# Regression: generate_chat_response must accept the four template kwargs
+# (tools / enable_thinking / reasoning_effort / preserve_thinking) so the route
+# layer can forward UI toggles. The old signature raised
# "got an unexpected keyword argument 'tools'" on Mac.
@@ -184,8 +183,8 @@ def test_mlx_generate_chat_response_accepts_template_kwargs():
def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
- """The Mac text path must route through apply_chat_template_for_
- generation so reasoning / tool kwargs reach the tokenizer."""
+ """Mac text path must route through apply_chat_template_for_generation so
+ reasoning / tool kwargs reach the tokenizer."""
_install_fake_mlx(monkeypatch)
from core.inference.mlx_inference import MLXInferenceBackend
@@ -203,9 +202,8 @@ def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
raising = True,
)
- # mlx_lm.stream_generate yields response objects with .token; make a
- # one-token generator so _generate_text returns without touching the
- # real stack.
+ # mlx_lm.stream_generate yields response objects with .token; use a
+ # one-token generator so _generate_text returns without the real stack.
import types as _types
mlx_lm_pkg = _types.ModuleType("mlx_lm")
@@ -250,7 +248,7 @@ def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
)
)
assert out == ["hi"]
- # The kwargs the user toggled must reach the chat-template helper.
+ # The toggled kwargs must reach the chat-template helper.
assert captured["kwargs"]["tools"] == [{"function": {"name": "web_search"}}]
assert captured["kwargs"]["enable_thinking"] is True
assert captured["kwargs"]["reasoning_effort"] == "medium"
diff --git a/studio/backend/tests/test_multimodal_document.py b/studio/backend/tests/test_multimodal_document.py
index b2986f2c3a4..29926299cef 100644
--- a/studio/backend/tests/test_multimodal_document.py
+++ b/studio/backend/tests/test_multimodal_document.py
@@ -3,17 +3,16 @@
"""Tests for PDF / document attachment translation on external providers.
-Studio introduces a normalised `input_document` content part on
-ChatCompletionRequest so the frontend doesn't have to know the
-per-provider attachment shape:
+Studio adds a normalised `input_document` content part on
+ChatCompletionRequest so the frontend needn't know the per-provider
+attachment shape:
-- Anthropic: translates to `{type:"document", source:{type:"base64"|"url", ...}}`
-- OpenAI Responses: translates to `{type:"input_file", file_data|file_url, filename?}`
+- Anthropic: `{type:"document", source:{type:"base64"|"url", ...}}`
+- OpenAI Responses: `{type:"input_file", file_data|file_url, filename?}`
-These tests pin the translation shape on both paths for base64 data
-URIs and remote URLs, with optional filename metadata, and confirm
-unknown / empty document parts are dropped without breaking the
-request.
+Pins the translation shape on both paths for base64 data URIs and remote
+URLs (with optional filename), and confirms unknown / empty document
+parts are dropped without breaking the request.
"""
import asyncio
@@ -87,9 +86,8 @@ _PDF_DATA_URI = f"data:application/pdf;base64,{_TINY_PDF_B64}"
def _strip_cache(p: dict) -> dict:
# Studio's prompt-cache wiring attaches cache_control:{type:ephemeral}
- # to the tail block of the last user message; strip it before
- # comparing the document core fields so this test stays focused
- # on the translation, not the caching layer.
+ # to the tail block of the last user message; strip it so this test
+ # focuses on translation, not the caching layer.
return {k: v for k, v in p.items() if k != "cache_control"}
@@ -117,7 +115,7 @@ def test_anthropic_base64_pdf_becomes_document_block(monkeypatch):
types = [p.get("type") for p in parts]
assert "document" in types, parts
doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
- # citations: {enabled: true} opts into Anthropic's natural-citation
+ # citations:{enabled:true} opts into Anthropic's natural-citation
# pipeline; without it the citations_delta handler is a no-op.
assert doc == {
"type": "document",
@@ -179,9 +177,9 @@ def test_anthropic_empty_document_part_is_dropped(monkeypatch):
def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):
- # If the ONLY part in a user message is an unparseable input_document,
- # the helper must NOT append an empty-content message to the outbound
- # body (Anthropic 400s on "at least one block is required").
+ # If the ONLY part is an unparseable input_document, the helper must
+ # NOT append an empty-content message (Anthropic 400s on "at least
+ # one block is required").
captured = _capture(
monkeypatch,
provider = "anthropic",
@@ -192,14 +190,14 @@ def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):
],
)
msgs = captured["body"]["messages"]
- # The empty-content message must be skipped; only the second remains.
+ # Empty-content message skipped; only the second remains.
assert len(msgs) == 1, msgs
def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):
- # Codex P2: `data:application/pdf;base64,` with no payload (or
- # whitespace-only) would create an empty `source.data` that
- # Anthropic 400s on. Must be filtered before the wire.
+ # Codex P2: `data:application/pdf;base64,` with no (or whitespace-only)
+ # payload would make an empty `source.data` that Anthropic 400s on.
+ # Must be filtered before the wire.
captured = _capture(
monkeypatch,
provider = "anthropic",
@@ -228,12 +226,11 @@ def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):
def test_anthropic_empty_data_uri_falls_back_to_file_url(monkeypatch):
- # Codex P2 follow-up: my previous fix added the empty-data-URI ->
- # file_url fallback to the OpenAI side but missed the Anthropic
- # side, where the empty-payload branch did `continue` and discarded
- # an otherwise-valid file_url on the same part. Mirror the OpenAI
- # behavior so a malformed inline payload + remote URL still
- # attaches.
+ # Codex P2 follow-up: the empty-data-URI -> file_url fallback was on
+ # the OpenAI side but missing on Anthropic, where the empty-payload
+ # branch did `continue` and discarded a valid file_url on the same
+ # part. Mirror OpenAI so a malformed inline payload + remote URL
+ # still attaches.
captured = _capture(
monkeypatch,
provider = "anthropic",
@@ -255,7 +252,7 @@ def test_anthropic_empty_data_uri_falls_back_to_file_url(monkeypatch):
)
parts = captured["body"]["messages"][0]["content"]
doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
- # base64 source MUST NOT have landed on the wire; URL source survived.
+ # base64 source MUST NOT reach the wire; URL source survives.
assert doc == {
"type": "document",
"source": {"type": "url", "url": "https://example.com/doc.pdf"},
@@ -344,11 +341,10 @@ def test_openai_url_pdf_becomes_input_file(monkeypatch):
def test_openai_empty_data_uri_falls_back_to_file_url(monkeypatch):
- # Codex P2 follow-up: an empty `data:application/pdf;base64,`
- # payload was being preferred over a perfectly valid `file_url`
- # in the same part, sending `file_data=""` to OpenAI and 400ing
- # the whole turn. The translator must treat empty data URIs as
- # missing and recover via file_url.
+ # Codex P2 follow-up: an empty `data:application/pdf;base64,` payload
+ # was preferred over a valid `file_url` in the same part, sending
+ # `file_data=""` and 400ing the turn. The translator must treat empty
+ # data URIs as missing and recover via file_url.
captured = _capture(
monkeypatch,
provider = "openai",
@@ -370,7 +366,7 @@ def test_openai_empty_data_uri_falls_back_to_file_url(monkeypatch):
)
parts = captured["body"]["input"][0]["content"]
fileblk = next(p for p in parts if p.get("type") == "input_file")
- # file_data MUST NOT be on the wire; file_url survives.
+ # file_data MUST NOT reach the wire; file_url survives.
assert "file_data" not in fileblk, fileblk
assert fileblk["file_url"] == "https://example.com/doc.pdf"
assert fileblk["filename"] == "doc.pdf"
@@ -402,8 +398,8 @@ def test_openai_whitespace_only_data_uri_falls_back_to_file_url(monkeypatch):
def test_openai_empty_data_uri_without_fallback_is_dropped(monkeypatch):
- # If the only signal is an empty data URI (no file_url), the
- # whole part is skipped rather than sent as `file_data=""`.
+ # Only signal is an empty data URI (no file_url): skip the whole part
+ # rather than send `file_data=""`.
captured = _capture(
monkeypatch,
provider = "openai",
@@ -449,12 +445,11 @@ def test_openai_empty_document_part_is_dropped(monkeypatch):
# ── Pydantic schema + builder pass-through ──────────────────────────
#
-# The translation tests above call the external-provider client directly
-# with hand-built dicts, which bypasses BOTH ChatCompletionRequest's
-# discriminated Union AND routes/inference._build_external_messages. The
-# tests below close that gap: parse an input_document part through the
-# real request schema, run the builder, and assert the part survives to
-# the dict the client would receive.
+# The translation tests above call the client directly with hand-built
+# dicts, bypassing both ChatCompletionRequest's discriminated Union and
+# routes/inference._build_external_messages. The tests below close that
+# gap: parse an input_document part through the real schema, run the
+# builder, and assert the part survives to the dict the client receives.
def test_chat_message_accepts_input_document_part():
@@ -482,10 +477,9 @@ def test_chat_message_accepts_input_document_part():
def test_build_external_messages_passes_input_document_for_anthropic_and_openai():
- # Both providers' stream helpers have explicit input_document
- # translation logic (Anthropic -> {type:"document"}, OpenAI
- # Responses -> {type:"input_file"}), so the part round-trips
- # through the builder unchanged on those routes.
+ # Both providers' stream helpers translate input_document (Anthropic ->
+ # {type:"document"}, OpenAI Responses -> {type:"input_file"}), so the
+ # part round-trips through the builder unchanged on those routes.
from models.inference import ChatMessage
from routes.inference import _build_external_messages
@@ -518,10 +512,10 @@ def test_build_external_messages_passes_input_document_for_anthropic_and_openai(
def test_build_external_messages_strips_input_document_for_unmapped_providers():
# Codex P1 follow-up: gemini / mistral / kimi / openrouter / deepseek
- # / custom go through generic /chat/completions passthrough that
- # forwards `messages` verbatim. Handing them an `input_document`
- # part fails the upstream validator. Builder must strip the part
- # for every provider whose stream helper doesn't translate it.
+ # / custom use generic /chat/completions passthrough that forwards
+ # `messages` verbatim, so an `input_document` part fails the upstream
+ # validator. The builder must strip it for any provider whose stream
+ # helper doesn't translate it.
from models.inference import ChatMessage
from routes.inference import _build_external_messages
@@ -551,8 +545,8 @@ def test_build_external_messages_strips_input_document_for_unmapped_providers():
def test_build_external_messages_strips_input_document_when_provider_type_unknown():
- # Defensive: legacy callers that don't pass provider_type must
- # not leak the part to an unknown destination.
+ # Defensive: legacy callers without provider_type must not leak the
+ # part to an unknown destination.
from models.inference import ChatMessage
from routes.inference import _build_external_messages
diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.py
index 01c05d3ec64..0290bb13088 100644
--- a/studio/backend/tests/test_native_context_length.py
+++ b/studio/backend/tests/test_native_context_length.py
@@ -3,11 +3,11 @@
"""Tests for the native_context_length feature (PR #4746).
-Verifies that the new `native_context_length` property on LlamaCppBackend
-and the corresponding Pydantic model fields work correctly. The raw GGUF
-`_context_length` must never be overwritten by VRAM-capping logic.
+Verifies the `native_context_length` property on LlamaCppBackend and the
+matching Pydantic fields. The raw GGUF `_context_length` must never be
+overwritten by VRAM-capping logic.
-Requires no GPU, network, or external libraries beyond pytest and pydantic.
+Needs no GPU, network, or libraries beyond pytest and pydantic.
"""
import io
@@ -21,8 +21,8 @@ from unittest.mock import patch
import pytest
# ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
# ---------------------------------------------------------------------------
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -38,7 +38,7 @@ sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
sys.modules.setdefault("structlog", _structlog_stub)
-# httpx -- stub only the names referenced at import / class-definition time
+# httpx -- stub only names referenced at import / class-definition time
_httpx_stub = _types.ModuleType("httpx")
for _exc_name in (
"ConnectError",
@@ -227,7 +227,7 @@ class TestContextValueSeparation:
def test_all_equal_when_uncapped(self, backend):
"""All three equal when no VRAM constraint."""
backend._context_length = 8192
- # No effective or max set -- properties fall back to _context_length
+ # No effective/max set -- properties fall back to _context_length.
assert backend.native_context_length == 8192
assert backend.max_context_length == 8192
assert backend.context_length == 8192
@@ -241,16 +241,16 @@ class TestContextValueSeparation:
backend._embedding_length = 4096
original = backend._context_length
- # Simulate a very small VRAM budget that forces capping
+ # Tiny VRAM budget forces capping.
result = backend._fit_context_to_vram(
requested_ctx = 131072,
available_mib = 512, # very small
model_size_bytes = 0,
)
- # _fit_context_to_vram returns the capped value, not modifying _context_length
+ # Returns the capped value without modifying _context_length.
assert backend._context_length == original
assert backend.native_context_length == original
- # The returned capped value should be <= requested
+ # Capped value must be <= requested.
assert result <= 131072
def test_native_gt_context_when_capped(self, backend):
@@ -370,7 +370,7 @@ class TestRouteCompleteness:
start = self._source.find(f"{class_name}(", idx)
if start == -1:
break
- # Find matching closing paren (simple depth counter)
+ # Find the matching closing paren via a depth counter.
depth = 0
end = start
for i, ch in enumerate(self._source[start:], start):
@@ -401,8 +401,8 @@ class TestRouteCompleteness:
"""Non-GGUF LoadResponse blocks do not set native_context_length (defaults to None)."""
blocks = self._find_construction_blocks("LoadResponse")
non_gguf = [b for b in blocks if "is_gguf = True" not in b and "is_gguf=True" not in b]
- # Non-GGUF paths should not reference native_context_length
- # (Pydantic defaults it to None, so not setting it is correct)
+ # Non-GGUF paths shouldn't reference native_context_length
+ # (Pydantic defaults it to None, so omitting it is correct).
for block in non_gguf:
assert (
"native_context_length" not in block
@@ -476,7 +476,7 @@ class TestNativeContextEdgeCases:
backend._read_gguf_metadata(path)
assert backend.native_context_length == 131072
- # Simulate VRAM capping by setting effective and max
+ # Simulate VRAM capping via effective and max.
backend._effective_context_length = 16384
backend._max_context_length = 32768
assert backend.native_context_length == 131072
diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.py
index df7652a590f..2856bb7cada 100644
--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py
+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py
@@ -3,27 +3,25 @@
"""Regression tests for the offline GGUF cache fallback path (#5505).
-Three failure modes hit users when ``huggingface.co`` is unreachable
-but the requested GGUF repo is fully cached locally:
-
-* ``list_gguf_variants`` raised through ``HTTPException(500)`` so the
- variant dropdown sat empty.
-* ``detect_gguf_model_remote`` returned ``None`` so a GGUF-only repo
- was misrouted into the transformers/Unsloth backend (on macOS this
- surfaced as a hardware error).
-* ``_download_gguf`` fell back to a synthetic ``{repo}-{variant}.gguf``
- name that did not exist in cache when the in-repo filename did not
- echo the repo name (e.g. ``unsloth/Qwen3.6-27B-MTP-GGUF`` ships
+Three failure modes hit users when ``huggingface.co`` is unreachable but the
+requested GGUF repo is fully cached locally:
+
+* ``list_gguf_variants`` raised ``HTTPException(500)`` so the variant
+ dropdown sat empty.
+* ``detect_gguf_model_remote`` returned ``None`` so a GGUF-only repo was
+ misrouted into the transformers/Unsloth backend (a hardware error on macOS).
+* ``_download_gguf`` fell back to a synthetic ``{repo}-{variant}.gguf`` name
+ absent from cache when the in-repo filename did not echo the repo name
+ (e.g. ``unsloth/Qwen3.6-27B-MTP-GGUF`` ships
``Qwen3.6-27B-UD-Q4_K_XL.gguf`` with no ``MTP`` token).
-Two follow-up regressions covered here:
+Two follow-up regressions also covered:
-* P1 #1: the cache-side variant filter must match the snapshot-relative
- path, not just the basename, so subdir layouts like
- ``BF16/foo.gguf`` are findable.
-* P1 #2: the DNS auto-detect must scope ``HF_HUB_OFFLINE`` to one load
- via try/finally so a transient resolver hiccup cannot lock the
- long-lived ``LlamaCppBackend`` singleton offline forever.
+* P1 #1: the cache-side variant filter must match the snapshot-relative path,
+ not just the basename, so subdir layouts like ``BF16/foo.gguf`` are findable.
+* P1 #2: the DNS auto-detect must scope ``HF_HUB_OFFLINE`` to one load via
+ try/finally so a transient resolver hiccup cannot lock the long-lived
+ ``LlamaCppBackend`` singleton offline forever.
No GPU, no network, no subprocess. Linux, macOS, Windows compatible.
"""
@@ -44,8 +42,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
-# Stub heavy/unavailable external deps before importing the modules
-# under test (same pattern as other studio backend tests).
+# Stub heavy/unavailable external deps before importing the modules under
+# test (same pattern as other studio backend tests).
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
@@ -182,7 +180,7 @@ class TestIterHfCacheSnapshots:
def test_repo_id_match_is_case_insensitive(self, hf_cache):
_build_cache(hf_cache, "unsloth/Foo-GGUF", {"Foo-Q4_K_M.gguf": 1})
- # Lookup with a different casing of the org/name still resolves
+ # Lookup with different org/name casing still resolves
out = list(_iter_hf_cache_snapshots("UNSLOTH/foo-gguf"))
assert len(out) == 1
@@ -272,9 +270,9 @@ class TestDetectGgufFromCache:
def test_subdir_only_quant_resolves(self, hf_cache):
"""P1 #1 regression: ``BF16/foo.gguf`` (quant only in directory).
- Before the fix, the offline cache scan matched on basename and
- missed this layout, falling through to the synthetic
- ``{repo}-{variant}.gguf`` heuristic."""
+ The pre-fix cache scan matched on basename, missing this layout
+ and falling through to the synthetic ``{repo}-{variant}.gguf``
+ heuristic."""
_build_cache(
hf_cache,
"unsloth/gpt-oss-20b-BF16",
@@ -316,7 +314,7 @@ class TestDetectGgufModelRemoteOffline:
assert out == "a-Q4_K_M.gguf"
def test_repository_not_found_does_not_consult_cache(self, hf_cache, clean_offline_env):
- # Cache has a file but the API explicitly says repo is gone.
+ # Cache has a file but the API says the repo is gone.
_build_cache(hf_cache, "unsloth/a", {"a-Q4_K_M.gguf": 1})
class RepositoryNotFoundError(Exception):
@@ -442,9 +440,9 @@ class TestHfOfflineIfDnsDead:
class TestExtractQuantLabelSubdir:
- """``_extract_quant_label`` must consider the parent directories when
- the basename has no quant token. Subdir layouts like ``BF16/foo.gguf``
- are documented in this codebase and surface through the cache scan."""
+ """``_extract_quant_label`` must consider parent directories when the
+ basename has no quant token. Subdir layouts like ``BF16/foo.gguf`` are
+ documented here and surface through the cache scan."""
def test_quant_in_basename_unchanged(self):
assert _extract_quant_label("BF16/foo-BF16.gguf") == "BF16"
@@ -457,17 +455,15 @@ class TestExtractQuantLabelSubdir:
assert _extract_quant_label("UD-Q4_K_XL/weight.gguf") == "UD-Q4_K_XL"
def test_deeper_nesting_picks_nearest_quant_dir(self):
- # When multiple parent segments could match, prefer the one closest
- # to the file (innermost). This matches how repos like
- # ``models/MXFP4_MOE/foo.gguf`` are laid out.
+ # When multiple parent segments match, prefer the innermost (closest
+ # to the file), matching repos like ``models/MXFP4_MOE/foo.gguf``.
assert _extract_quant_label("models/MXFP4_MOE/foo.gguf") == "MXFP4_MOE"
class TestDownloadMmprojOfflineCacheFallback:
- """``LlamaCppBackend._download_mmproj`` must resolve cached mmproj
- GGUFs offline, same shape as ``_download_gguf``. Without this the
- offline vision GGUF load path returns ``None`` even when the mmproj
- is present in cache."""
+ """``LlamaCppBackend._download_mmproj`` must resolve cached mmproj GGUFs
+ offline, same shape as ``_download_gguf``. Without this the offline vision
+ GGUF load path returns ``None`` even when the mmproj is cached."""
def test_cache_lookup_returns_cached_mmproj_when_list_repo_files_fails(self, hf_cache):
_build_cache(
@@ -559,7 +555,7 @@ class TestDownloadMmprojOfflineCacheFallback:
class TestListLocalGgufVariantsSubdir:
"""Subdir layouts like ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf`` must
- produce distinct quant labels, not collapse on basename."""
+ yield distinct quant labels, not collapse on basename."""
def test_two_subdir_variants_do_not_collapse(self, tmp_path):
from utils.models.model_config import list_local_gguf_variants
@@ -642,8 +638,8 @@ class TestListGgufVariantsPermanentErrors:
class TestDetectGgufFromCacheExcludesMmproj:
- """A partial cache with only a vision projector must not route the
- projector as the main model."""
+ """A partial cache with only a vision projector must not route it as
+ the main model."""
def test_mmproj_only_returns_none(self, hf_cache):
from utils.models.model_config import _detect_gguf_from_hf_cache
@@ -672,7 +668,7 @@ class TestDetectGgufFromCacheExcludesMmproj:
class TestProbeDnsDeadNoGlobalTimeoutMutation:
"""``_probe_dns_dead`` must not change ``socket.setdefaulttimeout``
- process-wide -- concurrent sockets without explicit timeout would
+ process-wide -- concurrent sockets without an explicit timeout would
inherit it for the probe window."""
def test_default_timeout_unchanged_when_dns_up(self, monkeypatch):
@@ -694,7 +690,7 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:
try:
_probe_dns_dead("example.invalid", timeout = 0.5)
finally:
- # Restore exact state regardless of any test-side mutation.
+ # Restore exact state regardless of test-side mutation.
original_set(prev)
assert set_calls == [], (
@@ -717,8 +713,8 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:
class TestWaitForHealthRetriesOnReadError:
"""A TCP RST mid-read while llama-server is still binding the port
- (Windows: WinError 10054) must not abort the health-poll loop --
- that masks a legitimate 'still warming up' state as a fatal load."""
+ (Windows: WinError 10054) must not abort the health-poll loop -- that
+ masks a legitimate 'still warming up' state as a fatal load."""
def test_read_error_then_success(self, monkeypatch):
import httpx
diff --git a/studio/backend/tests/test_offline_inference_parent.py b/studio/backend/tests/test_offline_inference_parent.py
index fbb0aa89990..71331220d6f 100644
--- a/studio/backend/tests/test_offline_inference_parent.py
+++ b/studio/backend/tests/test_offline_inference_parent.py
@@ -140,7 +140,7 @@ class TestLoraDetectOffline:
monkeypatch.setenv("HF_HUB_OFFLINE", "1")
# Studio catches Exception broadly; pin that the call still happens
- # (so cached LoRAs aren't missed) and returns fast via mock.
+ # (so cached LoRAs aren't missed) and returns fast via the mock.
class _OfflineModeIsEnabled(Exception):
pass
diff --git a/studio/backend/tests/test_openai_citation_markers.py b/studio/backend/tests/test_openai_citation_markers.py
index ccc17be3293..dafcffc8bd2 100644
--- a/studio/backend/tests/test_openai_citation_markers.py
+++ b/studio/backend/tests/test_openai_citation_markers.py
@@ -4,8 +4,8 @@
"""Tests for the OpenAI Responses-API citation marker rewriter.
The stream interleaves text deltas with ``\\ue200cite\\ue202SOURCE_ID\\ue201``
-markers. The rewriter resolves each to `[N](URL)` when the annotation has
-arrived and drops it otherwise; the URL list still flows to Sources via
+markers. The rewriter resolves each to `[N](URL)` once the annotation arrives
+and drops it otherwise; the URL list still flows to Sources via
`_record_url_citation`.
Reference: https://developers.openai.com/api/docs/guides/citation-formatting
@@ -58,8 +58,7 @@ def test_marker_rewritten_to_link_when_annotation_known():
def test_unknown_source_marker_dropped_silently():
text = f"Foo {_marker('turn9view9')} bar."
out = _replace_openai_citation_markers(text, [])
- # Marker stripped, no garbled "E202" glyph leaks through, and the
- # surrounding text stays intact.
+ # Marker stripped, no garbled "E202" glyph leaks, surrounding text intact.
assert not _has_marker_codepoints(out)
assert "E202" not in out
assert "turn9view9" not in out
@@ -67,8 +66,8 @@ def test_unknown_source_marker_dropped_silently():
def test_multiple_concatenated_markers_resolved_in_order():
- """Real-world wire shape: a string of markers butted up against each other
- after a sentence, as in the user-reported bug."""
+ """Real-world wire shape: markers butted together after a sentence,
+ as in the user-reported bug."""
markers = "".join(_marker(f"turn{i}view{j}") for i, j in [(1, 0), (1, 1), (3, 0)])
text = f"All animals ranked. {markers}"
citations = [
@@ -150,8 +149,8 @@ def test_multiple_source_id_aliases_resolve_to_same_url():
},
]
out = _replace_openai_citation_markers(text, citations)
- # All three aliases collapse onto citation [1] -- the URL is the
- # same so it would be misleading to show three different numbers.
+ # All three aliases collapse onto citation [1] -- same URL, so showing
+ # three different numbers would mislead.
assert out.count("[[1]](https://example.com/paris)") == 3
assert not _has_marker_codepoints(out)
@@ -176,7 +175,7 @@ def test_source_ids_list_and_legacy_source_id_both_resolve():
# ---------------------------------------------------------------------------
# _rewrite_citation_markers_partial: deferred-annotation tests. OpenAI emits
-# url_citation annotations on a subsequent SSE event; this helper reports
+# url_citation annotations on a later SSE event; this helper reports
# `has_unresolved` so the stream loop defers emission. See PR #5713 audit.
# ---------------------------------------------------------------------------
@@ -216,15 +215,15 @@ def test_partial_resolves_after_late_annotation():
def test_partial_multi_source_partial_resolution_keeps_marker_pending():
"""Any unresolved token in a multi-source marker leaves the whole marker
verbatim with ``unresolved`` True; defer until every id resolves or
- end-of-stream forces a flush (dropping unresolved tokens then)."""
+ end-of-stream forces a flush (dropping unresolved tokens)."""
cite = f"{CITE_START}cite{CITE_DELIM}known{CITE_DELIM}locator{CITE_STOP}"
text = f"Pre {cite} post."
citations = [{"source_id": "known", "url": "https://example.com/y"}]
out, unresolved = _rewrite_citation_markers_partial(text, citations)
assert unresolved is True
assert cite in out
- # End-of-stream force flush: drop the unresolved token, keep the
- # resolved link. The streamer routes pending segments through
+ # End-of-stream force flush: drop the unresolved token, keep the resolved
+ # link. The streamer routes pending segments through
# `_replace_openai_citation_markers` at force=True for this.
forced = _replace_openai_citation_markers(out, citations)
assert "[[1]](https://example.com/y)" in forced
diff --git a/studio/backend/tests/test_openai_citation_markers_edge.py b/studio/backend/tests/test_openai_citation_markers_edge.py
index e8d0be62463..f44975ce332 100644
--- a/studio/backend/tests/test_openai_citation_markers_edge.py
+++ b/studio/backend/tests/test_openai_citation_markers_edge.py
@@ -13,8 +13,8 @@ Reference: https://developers.openai.com/api/docs/guides/citation-formatting
import importlib
-# Streaming integration is exercised by ``_simulate_delta_stream`` further
-# down, mirroring the head/buffer/flush dance from ``_stream_openai_responses``.
+# Streaming is exercised by ``_simulate_delta_stream`` below, mirroring the
+# head/buffer/flush dance from ``_stream_openai_responses``.
_module = importlib.import_module("core.inference.external_provider")
_replace_openai_citation_markers = _module._replace_openai_citation_markers
_split_pending_citation_tail = _module._split_pending_citation_tail
@@ -27,7 +27,7 @@ CITE_DELIM = ""
def _marker(*source_ids: str, locator: str | None = None) -> str:
"""Build a ``\\ue200cite\\ue202<sid>[\\ue202<sid>...][\\ue202<loc>]\\ue201``
- marker. Accepts one or many ``source_ids`` plus an optional ``locator``."""
+ marker from one or more ``source_ids`` plus an optional ``locator``."""
payload = f"{CITE_START}cite{CITE_DELIM}" + CITE_DELIM.join(source_ids)
if locator:
payload = f"{payload}{CITE_DELIM}{locator}"
@@ -39,7 +39,7 @@ def _no_private_use(text: str) -> bool:
# Harness mirroring the head/pending-tail/flush dance in
-# `_stream_openai_responses`, so streaming tests skip the httpx mock.
+# `_stream_openai_responses` so streaming tests skip the httpx mock.
def _simulate_delta_stream(
deltas: list[str],
citations: list[dict],
@@ -56,8 +56,8 @@ def _simulate_delta_stream(
if head:
emitted.append(head)
if flush and pending:
- # Mirror `_flush_pending_marker_tail`: drop the tail entirely if no
- # closing stop byte arrived; the literal ``cite<sid>`` would leak otherwise.
+ # Mirror `_flush_pending_marker_tail`: drop the tail if no closing stop
+ # byte arrived; the literal ``cite<sid>`` would leak otherwise.
if CITE_STOP not in pending:
rendered = ""
else:
@@ -79,7 +79,7 @@ def _simulate_delta_stream(
def test_multi_source_marker_all_resolve():
"""\\ue200cite\\ue202id1\\ue202id2\\ue202id3\\ue201 expands to three links
- when every id is known. Earlier regex captured only id1 and dropped id2/id3."""
+ when every id is known. Earlier regex captured only id1."""
text = f"All three: {_marker('id1', 'id2', 'id3')}"
citations = [
{"source_id": "id1", "url": "https://example.com/1"},
@@ -136,14 +136,14 @@ def test_marker_with_range_locator():
def test_marker_split_in_source_id():
- """Delta-1 ends mid-source-id (``\\ue200cite\\ue202tu``), delta-2 starts
- with the rest (``rn0view0\\ue201``). The buffer stitches the halves
- back together so they resolve to one link instead of leaking."""
+ """Delta-1 ends mid-source-id (``\\ue200cite\\ue202tu``), delta-2 has the
+ rest (``rn0view0\\ue201``). The buffer stitches the halves so they resolve
+ to one link instead of leaking."""
full = f"See {_marker('turn0view0')} now."
# Cut right after the second delim + "tu" inside the source id.
cut = full.index("tu", full.index(CITE_START)) + len("tu")
d1, d2 = full[:cut], full[cut:]
- # Sanity check: delta-1 actually contains a partial marker.
+ # Sanity: delta-1 contains a partial marker.
assert CITE_START in d1 and CITE_STOP not in d1
assert CITE_STOP in d2
citations = [{"source_id": "turn0view0", "url": "https://x"}]
@@ -153,8 +153,8 @@ def test_marker_split_in_source_id():
def test_marker_split_at_start_byte():
- """Split exactly after the opening ``\\ue200`` byte; the buffer must
- hold the lone open byte until the rest arrives."""
+ """Split right after the opening ``\\ue200`` byte; the buffer must hold the
+ lone open byte until the rest arrives."""
full = f"Text {_marker('sid')} done"
cut = full.index(CITE_START) + 1 # right AFTER the open byte
d1, d2 = full[:cut], full[cut:]
@@ -167,7 +167,7 @@ def test_marker_split_at_start_byte():
def test_marker_split_across_three_deltas():
"""Worst case: marker chopped into three pieces across three deltas."""
full = f"A {_marker('threesplit')} B"
- # cut at two points inside the marker
+ # Cut at two points inside the marker.
open_pos = full.index(CITE_START)
stop_pos = full.index(CITE_STOP)
cut1 = open_pos + 4
@@ -206,21 +206,20 @@ def test_split_marker_unknown_source_is_dropped_cleanly():
def test_unterminated_marker_at_stream_end_dropped_on_flush():
- """Stream ends mid-marker (e.g. response.incomplete); the tail is
- flushed with private-use bytes stripped, no `E202` text leaks."""
+ """Stream ends mid-marker (e.g. response.incomplete); the flushed tail
+ strips private-use bytes, no `E202` text leaks."""
deltas = ["Some text ", f"{CITE_START}citetu", "rn0view0"] # no STOP ever
out = _simulate_delta_stream(deltas, [], flush = True)
assert _no_private_use(out)
assert "E200" not in out and "E202" not in out
- # Surrounding prose stays; we don't assert exact marker remainder.
+ # Surrounding prose stays; don't assert exact marker remainder.
assert "Some text " in out
def test_flush_resolves_marker_when_late_annotation_arrives():
- """Marker in a delta, matching annotation arrives later (on
- response.output_text.annotation.added after the final delta). The
- rewriter reads ``all_url_citations`` LIVE at flush, so the buffered
- marker still resolves."""
+ """Marker in a delta; the matching annotation arrives later (on
+ response.output_text.annotation.added after the final delta). The rewriter
+ reads ``all_url_citations`` LIVE at flush, so the buffered marker resolves."""
deltas = ["Look ", f"{CITE_START}cite{CITE_DELIM}late_sid"]
pending = ""
citations: list[dict] = []
@@ -291,8 +290,8 @@ def test_rewriter_idempotent_on_marker_free_text():
def test_only_marker_no_surrounding_text():
- """A delta that is JUST a marker (no prose) still renders correctly;
- used to leak without the empty-string short-circuit in the split helper."""
+ """A delta that is JUST a marker (no prose) renders correctly; it leaked
+ before the empty-string short-circuit in the split helper."""
text = _marker("solo")
citations = [{"source_id": "solo", "url": "https://solo.example"}]
out = _replace_openai_citation_markers(text, citations)
@@ -311,15 +310,15 @@ def test_back_to_back_markers_with_no_separator():
def test_split_helper_buffers_only_after_last_open_byte():
- """A complete marker followed by an unterminated one: head includes
- the complete marker, buffer holds only the trailing partial."""
+ """Complete marker followed by an unterminated one: head includes the
+ complete marker, buffer holds only the trailing partial."""
complete = _marker("done")
partial = f"{CITE_START}cite{CITE_DELIM}half" # no STOP
text = f"pre {complete} mid {partial}"
head, tail = _split_pending_citation_tail(text)
assert head == f"pre {complete} mid "
assert tail == partial
- # And the head, once rewritten, drops every private-use byte.
+ # Head, once rewritten, drops every private-use byte.
rewritten = _replace_openai_citation_markers(head, [{"source_id": "done", "url": "https://d"}])
assert rewritten == "pre [[1]](https://d) mid "
@@ -355,7 +354,7 @@ def test_unknown_marker_does_not_perturb_citation_indexing():
{"source_id": "real_b", "url": "https://example.com/b"},
]
out = _replace_openai_citation_markers(text, citations)
- # real_a is index 1; unknown does not take a slot.
+ # real_a is index 1; unknown takes no slot.
assert "[[1]](https://example.com/a)" in out
assert "[[2]](https://example.com/b)" in out
assert _no_private_use(out)
@@ -368,8 +367,8 @@ def test_unknown_marker_does_not_perturb_citation_indexing():
def test_unterminated_marker_does_not_leak_cite_residue():
- """Stream ends mid-marker: drop the whole tail rather than strip
- codepoints and leave ``cite<sid>`` behind."""
+ """Stream ends mid-marker: drop the whole tail rather than strip codepoints
+ and leave ``cite<sid>`` behind."""
half = f"Hi there {CITE_START}cite{CITE_DELIM}turn0view0"
out = _simulate_delta_stream([half], [], flush = True)
# Prose before the marker stays; no private-use bytes or cite residue.
diff --git a/studio/backend/tests/test_openai_code_execution.py b/studio/backend/tests/test_openai_code_execution.py
index d4f814856b8..e1b66b40505 100644
--- a/studio/backend/tests/test_openai_code_execution.py
+++ b/studio/backend/tests/test_openai_code_execution.py
@@ -6,23 +6,22 @@ Unit tests for OpenAI's server-side `shell` tool translation in
`_stream_openai_responses`.
Covers:
-- Request body: ``enabled_tools=["code_execution"]`` on the OpenAI
- cloud base_url appends ``{"type": "shell", "environment": {"type":
+- Request body: ``enabled_tools=["code_execution"]`` on the OpenAI cloud
+ base_url appends ``{"type": "shell", "environment": {"type":
"container_auto"}}`` to ``tools``.
-- Container reuse: when ``openai_code_exec_container_id`` is provided,
- the outgoing ``environment.type`` flips to ``"container_reference"``
- and the id propagates.
-- Cloud guard: code_execution on a non-cloud base_url (e.g. a local
- OpenAI-compat preset / ollama / llama.cpp / vLLM) does NOT add the
- shell tool, preventing a guaranteed 400 from those servers.
+- Container reuse: with ``openai_code_exec_container_id``, the outgoing
+ ``environment.type`` flips to ``"container_reference"`` and the id
+ propagates.
+- Cloud guard: code_execution on a non-cloud base_url (local
+ OpenAI-compat / ollama / llama.cpp / vLLM) does NOT add the shell tool,
+ avoiding a guaranteed 400 from those servers.
- SSE translation: a `shell_call` + `shell_call_output` pair emits one
``_toolEvent`` `tool_start` (`tool_name="code_execution"`,
- `arguments.kind="bash"`) and one `tool_end` whose `result` contains
- the joined stdout from the shell_call_output entries.
-- Container surfacing: container_id captured from
+ `arguments.kind="bash"`) and one `tool_end` whose `result` is the
+ joined stdout from the shell_call_output entries.
+- Container surfacing: container_id from
`response.completed.container_id` is emitted as a synthetic
- `container_ready` `_toolEvent` (only when it differs from the
- inbound id).
+ `container_ready` `_toolEvent` (only when it differs from the inbound id).
- Stale-container handling: 400 with "container expired" body emits a
`container_invalidated` event before propagating the error.
"""
@@ -192,8 +191,8 @@ def test_shell_tool_refused_for_non_cloud_base_url(monkeypatch):
_drive(run())
tools = captured["body"].get("tools") or []
- # Shell tool must NOT leak to local OpenAI-compat servers — those
- # 400 on the unknown tool type.
+ # Shell tool must NOT leak to local OpenAI-compat servers — they 400
+ # on the unknown tool type.
assert all(t.get("type") != "shell" for t in tools)
@@ -266,10 +265,9 @@ def test_shell_call_emits_tool_start_and_end(monkeypatch):
assert len(ends) == 1
assert starts[0]["tool_name"] == "code_execution"
assert starts[0]["tool_call_id"] == "scall_1"
- # `_server_tool: True` is the synthetic-builtin marker the
- # backend stamps onto every provider-side tool_start so the
- # frontend serializer can distinguish hosted tools from
- # user-declared functions on history replay.
+ # `_server_tool: True` marks a synthetic builtin: stamped onto every
+ # provider-side tool_start so the frontend serializer can tell hosted
+ # tools from user-declared functions on history replay.
assert starts[0]["arguments"] == {"kind": "bash", "command": "ls -la", "_server_tool": True}
assert ends[0]["tool_call_id"] == "scall_1"
assert "total 24" in ends[0]["result"]
@@ -395,21 +393,21 @@ def test_stale_container_emits_invalidated(monkeypatch):
def test_expired_container_triggers_transparent_retry(monkeypatch):
"""When OpenAI 400s with 'Container is expired' on a request that
carried container_reference, the streamer retries once with the
- container field stripped. The user never sees an error line — only
- container_invalidated, then the normal stream from the retry.
+ container field stripped. The user sees only container_invalidated,
+ then the normal stream from the retry — never an error line.
"""
calls: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content.decode("utf-8"))
calls.append(body)
- # Find the shell tool entry to inspect environment.type.
+ # Inspect the shell tool's environment.type.
shell_env_type = None
for tool in body.get("tools", []) or []:
if tool.get("type") == "shell":
shell_env_type = tool.get("environment", {}).get("type")
break
- # First call carries container_reference -> 400 expired.
+ # First call has container_reference -> 400 expired.
# Retry omits container -> normal SSE stream.
if shell_env_type == "container_reference":
return httpx.Response(
@@ -424,8 +422,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
).encode("utf-8"),
headers = {"content-type": "application/json"},
)
- # Successful retry: minimal SSE — a completed response with a
- # fresh container_id so container_ready latches.
+ # Successful retry: minimal SSE — completed response with a fresh
+ # container_id so container_ready latches.
sse = _openai_sse(
[
{
@@ -461,8 +459,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
lines = _drive(run())
events = _tool_events(lines)
- # Two outbound HTTP calls were made: the expired-container attempt
- # then the retry without the container field.
+ # Two outbound calls: the expired-container attempt, then the retry
+ # without the container field.
assert len(calls) == 2
shell_types = []
for body in calls:
@@ -471,14 +469,14 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
shell_types.append(tool.get("environment", {}).get("type"))
assert shell_types == ["container_reference", "container_auto"]
- # container_invalidated emitted (frontend will null its stored id).
+ # container_invalidated emitted (frontend nulls its stored id).
assert any(e.get("type") == "container_invalidated" for e in events)
# container_ready emitted from the retry stream with the fresh id.
assert any(
e.get("type") == "container_ready" and e.get("container_id") == "cntr_fresh_111"
for e in events
)
- # CRUCIALLY: no SSE error line surfaced to the chat — only completion.
+ # CRUCIALLY: no SSE error line surfaced to the chat.
error_lines = [
line
for line in lines
@@ -488,8 +486,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
def test_expired_container_retries_only_once(monkeypatch):
- """If the retry ALSO fails (any 4xx, expired or otherwise), the
- error is surfaced normally — no infinite retry loop.
+ """If the retry ALSO fails (any 4xx), the error surfaces normally —
+ no infinite retry loop.
"""
call_count = {"n": 0}
@@ -528,8 +526,7 @@ def test_expired_container_retries_only_once(monkeypatch):
lines = _drive(run())
- # Exactly two calls (first + one retry). Third would mean an
- # infinite loop.
+ # Exactly two calls (first + one retry); a third would be a loop.
assert call_count["n"] == 2
# The second failure surfaces normally as an error SSE line.
error_lines = [line for line in lines if '"error"' in line and "_toolEvent" not in line]
diff --git a/studio/backend/tests/test_openai_compaction.py b/studio/backend/tests/test_openai_compaction.py
index f0599952c68..c7de0a9aedc 100644
--- a/studio/backend/tests/test_openai_compaction.py
+++ b/studio/backend/tests/test_openai_compaction.py
@@ -4,14 +4,13 @@
"""Unit tests for OpenAI Responses API context_management wiring.
OpenAI's Responses API supports server-side compaction via
-``context_management: [{type:"compaction", compact_threshold:N}]``.
-There is no beta header and no dated version pin; the threshold is
-silently accepted and the API runs the compaction step when the
-rendered prompt crosses it.
-
-These tests pin: the body shape when threshold is set on cloud OpenAI,
-the silent no-op when the base URL is non-cloud, and the
-omitted-threshold pass-through.
+``context_management: [{type:"compaction", compact_threshold:N}]``. No
+beta header, no dated version pin; the threshold is silently accepted and
+compaction runs when the rendered prompt crosses it.
+
+These pin: the body shape when threshold is set on cloud OpenAI, the
+silent no-op on non-cloud base URLs, and the omitted-threshold
+pass-through.
"""
import asyncio
@@ -32,8 +31,7 @@ def _capture(monkeypatch, *, base_url: str, threshold) -> dict:
def handler(request: httpx.Request) -> httpx.Response:
captured["body"] = json.loads(request.content.decode("utf-8"))
- # Send an empty Responses-shaped SSE stream so the helper exits
- # cleanly.
+ # Empty Responses-shaped SSE stream so the helper exits cleanly.
return httpx.Response(
200,
content = (
@@ -88,8 +86,8 @@ def test_cloud_openai_sets_compaction_block(monkeypatch):
def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
- # Studio doesn't clamp the OpenAI side -- the API accepts whatever
- # the caller sends, so a small probe like 60k still goes through.
+ # Studio doesn't clamp the OpenAI side -- the API accepts whatever the
+ # caller sends, so a small probe like 60k still goes through.
captured = _capture(
monkeypatch,
base_url = "https://api.openai.com/v1",
@@ -105,8 +103,8 @@ def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
def test_non_cloud_base_silently_drops_compaction(monkeypatch):
# ollama / llama.cpp / "custom" presets collapse to provider="openai"
- # but don't implement context_management. Sending the field would
- # 400 those servers, so it must NOT appear on the wire.
+ # but lack context_management. Sending the field would 400 them, so it
+ # must NOT appear on the wire.
captured = _capture(
monkeypatch,
base_url = "http://127.0.0.1:11434/v1",
@@ -120,9 +118,9 @@ def test_non_cloud_base_silently_drops_compaction(monkeypatch):
def test_azure_openai_base_url_carries_compaction_block(monkeypatch):
# Azure OpenAI Foundry exposes the same /v1/responses extensions
- # (context_management, prompt_cache_retention, container shell)
- # under a *.openai.azure.com base URL. Treat it as cloud so the
- # compaction field actually reaches the API.
+ # (context_management, prompt_cache_retention, container shell) under
+ # a *.openai.azure.com base URL. Treat it as cloud so the compaction
+ # field reaches the API.
captured = _capture(
monkeypatch,
base_url = "https://my-resource.openai.azure.com/openai/v1",
@@ -132,14 +130,14 @@ def test_azure_openai_base_url_carries_compaction_block(monkeypatch):
{"type": "compaction", "compact_threshold": 200_000}
]
# Sibling Azure-cloud extension: prompt_cache_retention should also
- # be set so caching works the same way on Azure deployments.
+ # be set so caching works the same on Azure deployments.
assert captured["body"].get("prompt_cache_retention") == "24h"
def test_azure_openai_mixed_case_base_url_matches(monkeypatch):
- # The match is case-insensitive so URLs copy-pasted from the Azure
- # portal (which sometimes capitalise the resource name) still get
- # the cloud-only fields.
+ # Case-insensitive match so URLs copy-pasted from the Azure portal
+ # (which sometimes capitalise the resource name) still get the
+ # cloud-only fields.
captured = _capture(
monkeypatch,
base_url = "https://My-Resource.OpenAI.Azure.Com/openai/v1",
@@ -151,12 +149,11 @@ def test_azure_openai_mixed_case_base_url_matches(monkeypatch):
def test_cloud_gate_uses_hostname_not_substring(monkeypatch):
- # CodeQL py/incomplete-url-substring-sanitization: an attacker who
- # controls the configured base_url could embed `api.openai.com` or
- # `.openai.azure.com` as part of a path or a subdomain on an
- # arbitrary host to slip the cloud-only request body fields to a
- # server they control. The hostname-anchored helper must reject
- # both shapes.
+ # CodeQL py/incomplete-url-substring-sanitization: an attacker
+ # controlling base_url could embed `api.openai.com` or
+ # `.openai.azure.com` in a path or subdomain on an arbitrary host to
+ # slip cloud-only body fields to their own server. The
+ # hostname-anchored helper must reject both shapes.
for evil in [
"https://evil.com/api.openai.com/v1",
"https://api.openai.com.attacker.com/v1",
@@ -188,19 +185,17 @@ def test_omitted_threshold_no_body_field(monkeypatch):
def test_chat_completion_request_accepts_any_positive_compaction_threshold():
- # Codex follow-up: the field is documented as a no-op for non-cloud
- # OpenAI bases and every non-OpenAI provider, so a cross-provider
- # schema floor would 422 perfectly valid Anthropic / ollama /
- # llama.cpp requests that happen to carry the field. Keep schema
- # floor at ge=1 (any positive int) and rely on per-provider
- # helpers (_stream_openai_responses / _stream_anthropic) to
- # enforce or clamp the real floor.
+ # Codex follow-up: the field is a no-op for non-cloud OpenAI bases and
+ # every non-OpenAI provider, so a cross-provider schema floor would
+ # 422 valid Anthropic / ollama / llama.cpp requests carrying it. Keep
+ # the schema floor at ge=1 (any positive int) and let per-provider
+ # helpers (_stream_openai_responses / _stream_anthropic) enforce or
+ # clamp the real floor.
import pytest as _pytest
from models.inference import ChatCompletionRequest
- # Non-positive values still rejected so blank-string posts don't
- # sneak through.
+ # Non-positive values rejected so blank-string posts don't sneak in.
with _pytest.raises(Exception):
ChatCompletionRequest.model_validate(
{
@@ -211,10 +206,10 @@ def test_chat_completion_request_accepts_any_positive_compaction_threshold():
)
# Any positive int passes schema validation, including values that
- # would be no-ops on the OpenAI cloud path. This is intentional --
- # the OpenAI helper drops the field on non-cloud bases and
- # forwards-as-is on cloud bases; if the value is below the model's
- # effective floor, the upstream API surfaces the error.
+ # are no-ops on the OpenAI cloud path. Intentional -- the OpenAI
+ # helper drops the field on non-cloud bases and forwards as-is on
+ # cloud bases; if it's below the model's effective floor, the upstream
+ # API surfaces the error.
for v in (1, 5_000, 9_999, 10_000, 200_000):
req = ChatCompletionRequest.model_validate(
{
diff --git a/studio/backend/tests/test_openai_container_crud.py b/studio/backend/tests/test_openai_container_crud.py
index 48acf97e1f7..e0604527fd2 100644
--- a/studio/backend/tests/test_openai_container_crud.py
+++ b/studio/backend/tests/test_openai_container_crud.py
@@ -4,11 +4,11 @@
"""Unit tests for the /v1/containers CRUD client methods.
Covers:
-- All three calls (list / create / delete) send
- ``OpenAI-Beta: containers=v1``. Without it, OpenAI silently no-ops
- the DELETE while still returning 200 ``{"deleted": true}``.
-- ``delete_openai_container`` raises when the response body does not
- report ``{"deleted": true}``, even on a 2xx response.
+- list / create / delete all send ``OpenAI-Beta: containers=v1``. Without
+ it, OpenAI silently no-ops the DELETE but still returns 200
+ ``{"deleted": true}``.
+- ``delete_openai_container`` raises when the body omits
+ ``{"deleted": true}``, even on a 2xx response.
"""
from __future__ import annotations
@@ -28,11 +28,10 @@ def _drive(coro):
def _mock_http_client(monkeypatch, handler):
- """Wire `handler` for both the shared `_http_client` AND any
- per-call `httpx.AsyncClient(...)` instances. delete_openai_container
- intentionally creates a fresh AsyncClient (see comment in
- external_provider.delete_openai_container) so the test must
- also intercept that constructor."""
+ """Wire `handler` for the shared `_http_client` AND any per-call
+ `httpx.AsyncClient(...)`. delete_openai_container creates a fresh
+ AsyncClient (see external_provider.delete_openai_container), so we
+ must also intercept that constructor."""
transport = httpx.MockTransport(handler)
monkeypatch.setattr(ep_mod, "_http_client", httpx.AsyncClient(transport = transport))
real_async_client = httpx.AsyncClient
@@ -110,13 +109,12 @@ def test_delete_sends_openai_beta_header_and_accepts_confirmation(monkeypatch):
def test_delete_raises_when_response_lacks_deleted_true(monkeypatch):
"""OpenAI returns 200 ``{"deleted": true}`` even when the request is
- silently rejected (e.g. before we started sending OpenAI-Beta).
- Defensive guard: when the body omits ``deleted: true``, surface it
- as an error so the UI can report the failure instead of falsely
- reporting success."""
+ silently rejected (e.g. before we sent OpenAI-Beta). Guard: when the
+ body omits ``deleted: true``, surface an error so the UI reports the
+ failure instead of false success."""
def handler(request: httpx.Request) -> httpx.Response:
- # 200 but no deleted flag — simulate an unexpected payload shape.
+ # 200 but no deleted flag — unexpected payload shape.
return httpx.Response(200, json = {"id": "cntr_x", "object": "container"})
_mock_http_client(monkeypatch, handler)
@@ -159,10 +157,9 @@ def test_delete_propagates_openai_4xx(monkeypatch):
def test_list_route_filters_expired_containers(monkeypatch):
- """OpenAI keeps containers in /v1/containers indefinitely with
- status="expired" after their idle TTL passes — they can't be
- used but still show up. The list route must drop them so the
- picker only surfaces usable containers."""
+ """OpenAI keeps containers in /v1/containers with status="expired"
+ after their idle TTL passes — unusable but still listed. The list
+ route must drop them so the picker shows only usable containers."""
from routes import inference as inf_mod
from models.inference import OpenAIContainerRequest
diff --git a/studio/backend/tests/test_openai_image_generation.py b/studio/backend/tests/test_openai_image_generation.py
index f5dee2561a3..39cf672dc1f 100644
--- a/studio/backend/tests/test_openai_image_generation.py
+++ b/studio/backend/tests/test_openai_image_generation.py
@@ -4,17 +4,16 @@
"""Unit tests for OpenAI Responses API image_generation tool wiring.
The image_generation tool is a server-side Responses-API tool:
-``{type: "image_generation"}`` in the request's tools array, and the
-result comes back as an ``image_generation_call`` output item carrying
-the base64 image on ``result``. Studio translates the output item
-into ``_toolEvent`` chunks (``tool_start`` with `kind:"image"`,
-``tool_end`` with ``image_b64`` + ``image_mime``) so the chat adapter
-can render the image inline.
-
-These tests pin: the tool is added to the outbound body only when the
-caller asks for it on a cloud OpenAI base; the SSE output_item.done
-for ``image_generation_call`` produces the expected _toolEvent chunks;
-non-cloud bases drop the tool silently.
+``{type: "image_generation"}`` in the request's tools array; the result
+returns as an ``image_generation_call`` output item carrying the base64 image
+on ``result``. Studio translates that item into ``_toolEvent`` chunks
+(``tool_start`` with `kind:"image"`, ``tool_end`` with ``image_b64`` +
+``image_mime``) so the chat adapter renders the image inline.
+
+These tests pin: the tool is added to the outbound body only when the caller
+asks for it on a cloud OpenAI base; the SSE output_item.done for
+``image_generation_call`` produces the expected _toolEvent chunks; non-cloud
+bases drop the tool silently.
"""
import asyncio
@@ -75,8 +74,8 @@ def _capture_body(monkeypatch, *, base_url: str, enabled_tools) -> dict:
def _collect_tool_events(monkeypatch) -> list[dict]:
- """Drive a Responses stream that emits one image_generation_call done
- event and return the parsed _toolEvent chunks."""
+ """Drive a Responses stream with one image_generation_call done event and
+ return the parsed _toolEvent chunks."""
sse = (
b"event: response.output_item.done\n"
@@ -207,8 +206,8 @@ def test_image_generation_done_emits_tool_event_chunks(monkeypatch):
ends = [e for e in image_events if e.get("type") == "tool_end"]
assert len(starts) == 1, image_events
assert len(ends) == 1, image_events
- # `_server_tool: True` marks this as a provider-side synthetic
- # tool card on the frontend's history serializer.
+ # `_server_tool: True` marks this as a provider-side synthetic tool card
+ # for the frontend's history serializer.
assert starts[0]["arguments"] == {
"kind": "image",
"prompt": "A photorealistic cat sitting",
diff --git a/studio/backend/tests/test_openai_responses_translation.py b/studio/backend/tests/test_openai_responses_translation.py
index 95e9b2d63cd..19d4959aa19 100644
--- a/studio/backend/tests/test_openai_responses_translation.py
+++ b/studio/backend/tests/test_openai_responses_translation.py
@@ -5,14 +5,14 @@
Unit tests for the OpenAI `/v1/responses` translation in external_provider.
Covers:
-- Request body shape: system messages collapse into `instructions`, user/
- assistant messages go into `input`, sampling knobs Responses does not
- support (presence_penalty, top_k) are not forwarded.
-- SSE translation: `response.output_text.delta` events become OpenAI Chat
- Completions chunks, `response.completed` emits a `finish_reason: stop`
- chunk, the stream terminates with `data: [DONE]`.
-- Image parts in user content are rewritten from Chat Completions
- `{type: image_url, image_url: {url}}` into Responses
+- Request body shape: system messages collapse into `instructions`,
+ user/assistant messages go into `input`, and unsupported sampling knobs
+ (presence_penalty, top_k) are not forwarded.
+- SSE translation: `response.output_text.delta` → Chat Completions chunks,
+ `response.completed` → a `finish_reason: stop` chunk, stream ends with
+ `data: [DONE]`.
+- Image parts rewritten from Chat Completions
+ `{type: image_url, image_url: {url}}` to Responses
`{type: input_image, image_url: <url>}`.
"""
@@ -101,9 +101,9 @@ def test_responses_request_body_uses_input_and_instructions(monkeypatch):
assert body["input"] == [{"role": "user", "content": "Hi"}]
assert body["max_output_tokens"] == 512
assert body["stream"] is True
- # Responses API on reasoning-class models (gpt-5.x / o3 / gpt-4.5 — the
- # only OpenAI ids the registry allowlist exposes) rejects these as
- # `Unsupported parameter`. Make sure we never silently forward them.
+ # Responses API on reasoning-class models (gpt-5.x / o3 / gpt-4.5 — the only
+ # OpenAI ids the registry allowlist exposes) rejects these as `Unsupported
+ # parameter`. Never silently forward them.
assert "temperature" not in body
assert "top_p" not in body
assert "presence_penalty" not in body
@@ -213,11 +213,11 @@ def test_responses_sse_translates_to_chat_completions_chunks(monkeypatch):
def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypatch):
- """Round 12: caller-supplied function tools forwarded into /v1/responses
- must have their `function_call` output items translated back into Chat
- Completions delta.tool_calls, and the terminal chunk must emit
- finish_reason="tool_calls" so the frontend's accumulator runs the
- function instead of seeing finish_reason="stop"."""
+ """Round 12: function tools forwarded into /v1/responses must have their
+ `function_call` output items translated back into Chat Completions
+ delta.tool_calls, and the terminal chunk must emit
+ finish_reason="tool_calls" (not "stop") so the frontend's accumulator runs
+ the function."""
def handler(request: httpx.Request) -> httpx.Response:
events = [
@@ -288,7 +288,7 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat
assert tc["id"] == "call_xyz"
assert tc["function"]["name"] == "get_weather"
assert tc["function"]["arguments"] == '{"city":"SF"}'
- # Final chunk reports tool_calls instead of stop.
+ # Final chunk reports tool_calls, not stop.
terminal = next(
p
for p in payloads
@@ -301,8 +301,8 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat
def test_responses_parallel_function_calls_get_distinct_indices(monkeypatch):
"""Round 13: parallel function_call items must land on distinct
- delta.tool_calls[].index slots so index-keyed clients don't
- collapse the second call into the first."""
+ delta.tool_calls[].index slots so index-keyed clients don't collapse the
+ second call into the first."""
def handler(request: httpx.Request) -> httpx.Response:
events = [
@@ -388,10 +388,10 @@ def test_responses_parallel_function_calls_get_distinct_indices(monkeypatch):
def test_responses_follow_up_tool_result_uses_function_call_output_items(monkeypatch):
- """Round 13: a second turn after a Responses function call must
- serialize the tool_calls history and tool result as Responses
- `function_call` / `function_call_output` input items, not as
- Chat Completions role="tool" content."""
+ """Round 13: a second turn after a Responses function call must serialize
+ the tool_calls history and tool result as Responses `function_call` /
+ `function_call_output` input items, not Chat Completions role="tool"
+ content."""
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 7d488ae4c93..b9f086a4b90 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -10,8 +10,7 @@ Covers:
with `content: None` + `tool_calls`.
- ChatCompletionRequest carries unknown fields via `extra="allow"`.
- anthropic_tool_choice_to_openai() covers all four Anthropic shapes.
-- _build_passthrough_payload() honors a caller-supplied tool_choice and
- defaults to "auto" when unset.
+- _build_passthrough_payload() honors a caller tool_choice, defaults to "auto".
- _friendly_error() maps httpx transport errors to a "Lost connection"
message so passthrough failures are legible instead of bare 500s.
@@ -120,8 +119,8 @@ class TestChatMessageToolRoles:
ChatMessage(role = "function", content = "x")
def test_content_absent_on_assistant_tool_call_defaults_to_none(self):
- # Assistant messages that carry only tool_calls are the one
- # documented case where `content=None` is permitted.
+ # Assistant messages carrying only tool_calls are the one documented
+ # case where `content=None` is permitted.
msg = ChatMessage(
role = "assistant",
tool_calls = [
@@ -136,9 +135,9 @@ class TestChatMessageToolRoles:
def test_tool_role_missing_tool_call_id_left_for_request_validator(self):
# Per-message: missing tool_call_id is now allowed at this layer.
- # ChatCompletionRequest's walkback fills it in from the prior
- # assistant tool_calls; see test_inference_model_validation.py for
- # the resolution coverage.
+ # ChatCompletionRequest's walkback fills it from the prior assistant
+ # tool_calls; see test_inference_model_validation.py for resolution
+ # coverage.
msg = ChatMessage(role = "tool", content = '{"temperature": 72}')
assert msg.tool_call_id is None
assert msg.content == '{"temperature": 72}'
@@ -173,7 +172,7 @@ class TestChatMessageToolRoles:
assert "content" in str(exc_info.value)
def test_assistant_without_content_or_tool_calls_tolerated(self):
- # Stop-button leaves an empty assistant turn; tolerate so replay round-trips.
+ # Stop-button leaves an empty assistant turn; tolerate for replay.
msg = ChatMessage(role = "assistant")
assert msg.content is None
assert msg.tool_calls is None
@@ -280,9 +279,8 @@ class TestChatCompletionRequestToolFields:
assert req.stop is None
def test_extra_fields_accepted(self):
- # `frequency_penalty`, `seed`, `response_format` are not yet
- # explicitly declared but must survive Pydantic parsing now that
- # extra="allow" is set.
+ # `frequency_penalty`, `seed`, `response_format` aren't explicitly
+ # declared but must survive Pydantic parsing now that extra="allow".
req = self._make(
frequency_penalty = 0.5,
seed = 42,
@@ -306,24 +304,22 @@ class TestChatCompletionRequestToolFields:
def test_stream_defaults_false_matching_openai_spec(self):
# OpenAI's /v1/chat/completions spec defaults `stream` to false.
- # Studio previously defaulted to true, which broke naive curl
- # clients (and .NET / System.Text.Json SDKs per #5047) that omit
- # `stream` -- they expect a JSON blob, got SSE.
- # Pin the corrected default so it can't silently regress.
+ # Studio previously defaulted to true, breaking naive curl clients
+ # (and .NET / System.Text.Json SDKs per #5047) that omit `stream`:
+ # they expect a JSON blob, got SSE. Pin the corrected default so it
+ # can't silently regress.
req = self._make()
assert req.stream is False
def test_post_without_stream_field_decodes_to_stream_false_over_http(self, monkeypatch):
# Wire-level guard for the same default: a POST body that omits
- # `stream` entirely (the exact shape naive curl / .NET clients
- # send) must deserialise into stream=False *and* the response
- # must be `application/json`, never `text/event-stream`.
- # Mounts the real `routes.inference.router` so this catches
- # regressions in middleware/aliasing on the actual endpoint
- # (e.g. someone adding a request layer that injects stream=True
- # before pydantic builds the model). Backends are bypassed by
- # routing through `provider_type` and stubbing the external
- # provider proxy.
+ # `stream` (the exact shape naive curl / .NET clients send) must
+ # deserialise into stream=False *and* return `application/json`, never
+ # `text/event-stream`. Mounts the real `routes.inference.router` so
+ # this catches middleware/aliasing regressions on the actual endpoint
+ # (e.g. a request layer that injects stream=True before pydantic builds
+ # the model). Backends are bypassed via `provider_type` + a stubbed
+ # external provider proxy.
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -487,12 +483,12 @@ class TestBuildPassthroughPayloadToolChoice:
class TestFriendlyErrorHttpx:
"""The async pass-through helpers talk to llama-server via httpx.
- When the subprocess is down, httpx raises RequestError subclasses
- whose string form (``"All connection attempts failed"``, ``"[Errno 111]
- Connection refused"``, ...) does NOT contain the substring
- ``"Lost connection to llama-server"`` the sync path uses, so the
- previous substring-only `_friendly_error` returned a useless generic
- message. These tests pin the new isinstance-based mapping.
+ When the subprocess is down, httpx raises RequestError subclasses whose
+ string form (``"All connection attempts failed"``, ``"[Errno 111]
+ Connection refused"``, ...) lacks the ``"Lost connection to llama-server"``
+ substring the sync path uses, so the old substring-only `_friendly_error`
+ returned a useless generic message. These tests pin the new
+ isinstance-based mapping.
"""
def _req(self):
@@ -515,9 +511,8 @@ class TestFriendlyErrorHttpx:
assert "Lost connection" in _friendly_error(exc)
def test_non_httpx_unchanged(self):
- # Non-httpx exceptions still fall through to the existing substring
- # heuristics — a context-size message must still produce the
- # "Message too long" path.
+ # Non-httpx exceptions still fall through to the substring heuristics
+ # — a context-size message must still produce "Message too long".
ctx_msg = "request (4096 tokens) exceeds the available context size (2048 tokens)"
assert "Message too long" in _friendly_error(ValueError(ctx_msg))
@@ -543,7 +538,7 @@ class TestDropEmptyAssistantSentinels:
assert out == [{"role": "user", "content": "hi"}, {"role": "user", "content": "again"}]
def test_drops_assistant_with_no_content_key(self):
- # exclude_none=True strips the content key entirely; filter must catch this.
+ # exclude_none=True strips the content key entirely; filter must catch it.
msgs = [
{"role": "user", "content": "hi"},
{"role": "assistant"},
@@ -658,8 +653,8 @@ class TestGgufVisionMessages:
assert len(messages[2]["content"]) == 2
assert isinstance(messages[1]["content"], str)
- # Legacy top-level image_base64 must be ignored when any message-level
- # image already exists; otherwise turn 2 ends up with two image parts.
+ # Legacy top-level image_base64 must be ignored when a message-level
+ # image exists; otherwise turn 2 ends up with two image parts.
for msg in messages:
content = msg.get("content")
if isinstance(content, list):
diff --git a/studio/backend/tests/test_openai_tool_result_fallbacks.py b/studio/backend/tests/test_openai_tool_result_fallbacks.py
index 7c033bc3488..5ea812441fb 100644
--- a/studio/backend/tests/test_openai_tool_result_fallbacks.py
+++ b/studio/backend/tests/test_openai_tool_result_fallbacks.py
@@ -3,8 +3,8 @@
"""Regression tests for OpenAI Responses tool-result rendering.
-Covers two bug classes: empty web_search cards (per-card result seeded
-with "Searching: <query>") and orphan shell_call cards (bundled-output
+Two bug classes: empty web_search cards (per-card result seeded with
+"Searching: <query>") and orphan shell_call cards (bundled-output
fallback + final flush at response.completed / response.incomplete).
"""
@@ -137,8 +137,8 @@ def test_web_search_each_call_carries_its_own_query_as_result(monkeypatch):
def test_web_search_last_call_overwritten_with_citations(monkeypatch):
- """Last call still gets the aggregated citation list; earlier calls
- keep their per-call `Searching:` text."""
+ """Last call gets the aggregated citations; earlier calls keep their
+ per-call `Searching:` text."""
sse_events = [
{
"type": "response.output_item.done",
@@ -170,12 +170,12 @@ def test_web_search_last_call_overwritten_with_citations(monkeypatch):
events = _tool_events(lines)
ends = [e for e in events if e["type"] == "tool_end"]
by_id: dict = {}
- # Keep the LAST tool_end per id (the citation overwrite for ws_2).
+ # Keep the LAST tool_end per id (citation overwrite for ws_2).
for e in ends:
by_id[e["tool_call_id"]] = e
# First call keeps its own query.
assert by_id["ws_1"]["result"] == "Searching: first query"
- # Last call gets overwritten with the citation block.
+ # Last call overwritten with the citation block.
assert "Title: Example A" in by_id["ws_2"]["result"]
assert "URL: https://example.com/a" in by_id["ws_2"]["result"]
diff --git a/studio/backend/tests/test_pricing.py b/studio/backend/tests/test_pricing.py
index d669747b1a7..8cd7796f142 100644
--- a/studio/backend/tests/test_pricing.py
+++ b/studio/backend/tests/test_pricing.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
-"""Unit tests for the per-session cost calculator. Verifies math
-against ``core/inference/pricing.py`` and graceful degradation."""
+"""Unit tests for the per-session cost calculator: math against
+``core/inference/pricing.py`` plus graceful degradation."""
import math
@@ -462,12 +462,12 @@ def test_snapshot_contains_provider_buckets_and_multipliers():
# ── longest-prefix match: dated mini variant must not collide with the
-# shorter family prefix. ──
+# shorter family prefix ──
def test_longest_prefix_match_wins_for_dated_mini_snapshot():
- """`gpt-5.4-mini-2026-...` must inherit the mini rate, not the
- shorter `gpt-5.4` rate (longest prefix wins)."""
+ """`gpt-5.4-mini-2026-...` inherits the mini rate, not the shorter
+ `gpt-5.4` rate (longest prefix wins)."""
out = calculate_cost(
"openai",
"gpt-5.4-mini-2026-04-23",
@@ -493,7 +493,7 @@ def test_longest_prefix_match_wins_for_dated_pro_snapshot():
def test_openai_chat_style_usage_keys_priced_correctly():
- """Chat-style envelope (`prompt_tokens` / `completion_tokens`) must
+ """Chat-style envelope (`prompt_tokens`/`completion_tokens`) must
produce a non-zero cost (previously silently zeroed)."""
out = calculate_cost(
"openai",
@@ -577,7 +577,7 @@ def test_openai_chat_style_prompt_tokens_keeps_cache_read_semantics():
def test_openai_chat_style_envelope_reads_cache_from_prompt_tokens_details():
"""Chat-style envelope ships cached under prompt_tokens_details;
- calculator must honour both this and input_tokens_details."""
+ calculator must honour both that and input_tokens_details."""
base = OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
raw = calculate_cost(
"openai",
diff --git a/studio/backend/tests/test_pricing_edge.py b/studio/backend/tests/test_pricing_edge.py
index 5818b42e8ac..4197d8c9f0a 100644
--- a/studio/backend/tests/test_pricing_edge.py
+++ b/studio/backend/tests/test_pricing_edge.py
@@ -30,8 +30,8 @@ def _isclose(
def test_prefix_match_requires_dash_boundary_opus_variant():
- # `claude-opus-4-15` must not inherit `claude-opus-4-1` pricing;
- # next char must be `-` or end-of-string.
+ # `claude-opus-4-15` must not inherit `claude-opus-4-1` pricing; the next
+ # char must be `-` or end-of-string.
assert _lookup("anthropic", "claude-opus-4-15") is None
out = calculate_cost(
"anthropic",
@@ -55,8 +55,8 @@ def test_prefix_match_requires_dash_boundary_gpt_variant():
def test_prefix_match_requires_dash_boundary_pro_lookalike():
- # `gpt-5.5-prod` must fall through `gpt-5.5-pro` (6x overcharge)
- # and land on the canonical `gpt-5.5` row.
+ # `gpt-5.5-prod` must fall through `gpt-5.5-pro` (6x overcharge) and land on
+ # the canonical `gpt-5.5` row.
prices = _lookup("openai", "gpt-5.5-prod")
assert prices is not None
assert (
@@ -81,7 +81,7 @@ def test_prefix_match_still_resolves_legit_dated_snapshots():
assert out["priced"] is True
assert _isclose(out["input_usd"], 0.75)
- # And Anthropic dated snapshot still resolves to canonical row.
+ # Anthropic dated snapshot still resolves to the canonical row.
out = calculate_cost(
"anthropic",
"claude-opus-4-7-20260414",
@@ -95,7 +95,7 @@ def test_prefix_match_still_resolves_legit_dated_snapshots():
def test_explicit_zero_input_tokens_wins_over_stale_prompt_tokens():
- # Input-side mirror of the output zero precedence test.
+ # Input-side mirror of the output zero-precedence test.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -110,7 +110,7 @@ def test_explicit_zero_input_tokens_wins_over_stale_prompt_tokens():
def test_none_input_tokens_falls_through_to_prompt_tokens():
- # `None` is "key present but unset"; chat-style mirror wins.
+ # `None` means "key present but unset"; chat-style mirror wins.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -176,8 +176,8 @@ def test_negative_prompt_tokens_chat_style_clamp():
def test_anthropic_chat_cache_read_exceeds_prompt_no_negative_billable():
- # cache_read > prompt_tokens clamps uncached_input at 0; billable
- # still reflects cache buckets (we charge for what we got).
+ # cache_read > prompt_tokens clamps uncached_input at 0; billable still
+ # reflects cache buckets (we charge for what we got).
out = calculate_cost(
"anthropic",
"claude-opus-4-7",
@@ -216,8 +216,8 @@ def test_openai_raw_cached_tokens_exceeds_input_clamp_non_cached():
def test_openai_long_context_triggers_on_cache_creation_inflated_billable():
- # cache_creation pushes billable past 272k -> long-context tier
- # must fire to avoid undercounting.
+ # cache_creation pushes billable past 272k -> long-context tier must fire to
+ # avoid undercounting.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -272,8 +272,8 @@ def test_openai_chat_envelope_long_context_parity_with_raw():
def test_cache_creation_as_int_does_not_crash():
- # Proxies sometimes fold cache_creation to an int; tolerate it
- # and fall back to the 5m default.
+ # Proxies sometimes fold cache_creation to an int; tolerate it and fall back
+ # to the 5m default.
base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
out = calculate_cost(
"anthropic",
@@ -363,16 +363,16 @@ def test_empty_usage_dict_zero_bill():
def test_anthropic_prompt_tokens_details_fallback_when_native_key_missing():
- """Chat-style envelope without `cache_read_input_tokens` but with
- mirrored `prompt_tokens_details.cached_tokens` should still apply
- the cache_read discount."""
+ """Chat-style envelope without `cache_read_input_tokens` but with mirrored
+ `prompt_tokens_details.cached_tokens` should still apply the cache_read
+ discount."""
r = calculate_cost(
provider = "anthropic",
model = "claude-opus-4-7",
usage = {
"prompt_tokens": 1_000_000,
"completion_tokens": 0,
- # Only the mirrored shape (no native key).
+ # Mirrored shape only (no native key).
"prompt_tokens_details": {"cached_tokens": 1_000_000},
"cache_creation_input_tokens": 0,
},
@@ -383,8 +383,8 @@ def test_anthropic_prompt_tokens_details_fallback_when_native_key_missing():
def test_anthropic_native_key_takes_precedence_over_mirrored():
- """When both native and mirrored cache-read fields are present,
- the native Anthropic field wins (mirror is fallback-only)."""
+ """When both native and mirrored cache-read fields are present, the native
+ Anthropic field wins (mirror is fallback-only)."""
r = calculate_cost(
provider = "anthropic",
model = "claude-opus-4-7",
@@ -403,8 +403,8 @@ def test_anthropic_native_key_takes_precedence_over_mirrored():
def test_anthropic_native_zero_takes_precedence_over_mirrored():
- """Explicit `cache_read_input_tokens: 0` is authoritative; a stale
- mirrored block from a proxy must not inflate cache_read past it."""
+ """Explicit `cache_read_input_tokens: 0` is authoritative; a stale mirrored
+ block from a proxy must not inflate cache_read past it."""
r = calculate_cost(
provider = "anthropic",
model = "claude-opus-4-7",
@@ -429,8 +429,8 @@ def test_anthropic_native_zero_takes_precedence_over_mirrored():
def test_build_usage_chunk_forwards_anthropic_cache_creation_breakdown():
- """Chat-style envelope must carry the 5m/1h cache-write breakdown
- so downstream cost calc applies the 2x 1h premium."""
+ """Chat-style envelope must carry the 5m/1h cache-write breakdown so
+ downstream cost calc applies the 2x 1h premium."""
import json
from core.inference.external_provider import _build_usage_chunk
diff --git a/studio/backend/tests/test_providers_api.py b/studio/backend/tests/test_providers_api.py
index 88df886b6cf..f343cef635f 100644
--- a/studio/backend/tests/test_providers_api.py
+++ b/studio/backend/tests/test_providers_api.py
@@ -4,13 +4,13 @@
"""
Integration tests for the external providers API.
-Requires a running Unsloth Studio server. Configure via environment variables:
+Requires a running Unsloth Studio server. Configure via env vars:
export STUDIO_TEST_URL="http://localhost:8888" # default
export STUDIO_TEST_USER="unsloth" # default
export STUDIO_TEST_PASSWORD="..." # required — see .bootstrap_password
- # Provider API keys — any left unset will have their tests automatically skipped
+ # Provider API keys — tests skip when their key is unset
export OPENAI_API_KEY="sk-..."
export MISTRAL_API_KEY="..."
export GOOGLE_API_KEY="..."
@@ -38,15 +38,14 @@ BASE_URL = os.getenv("STUDIO_TEST_URL", "http://localhost:8000")
USERNAME = os.getenv("STUDIO_TEST_USER", "unsloth")
PASSWORD = os.getenv("STUDIO_TEST_PASSWORD", "")
-# These tests require a live Studio server reachable at BASE_URL with a known
-# bootstrap password. Skip the whole module when that environment is missing
-# (e.g. on CI runners) so pytest discovery does not error out.
+# Skip the whole module when no live Studio server / bootstrap password is
+# available (e.g. on CI) so pytest discovery does not error out.
pytestmark = pytest.mark.skipif(
not PASSWORD,
reason = "Integration test requires a running Studio server; set STUDIO_TEST_PASSWORD to enable.",
)
-# Map provider_type → (env var name, model to use for inference test)
+# provider_type → (env var name, model for inference test)
_PROVIDER_CONFIGS: dict[str, tuple[str, str]] = {
"openai": ("OPENAI_API_KEY", "gpt-4o-mini"),
"mistral": ("MISTRAL_API_KEY", "mistral-small-2506"),
@@ -74,10 +73,10 @@ def _url(path: str) -> str:
def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:
"""
- Read a streaming SSE response and return (assembled_text, saw_done).
+ Read an SSE response, return (assembled_text, saw_done).
- Each chunk is a JSON object with choices[0].delta.content.
- The stream ends with `data: [DONE]`.
+ Each chunk is JSON with choices[0].delta.content; stream ends with
+ `data: [DONE]`.
"""
reply_parts: list[str] = []
saw_done = False
@@ -93,7 +92,7 @@ def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:
break
try:
chunk = json.loads(data)
- # Handle both error payloads and normal chunks
+ # Handle error payloads and normal chunks
if "error" in chunk:
raise RuntimeError(f"Provider error in stream: {chunk['error']}")
delta = chunk.get("choices", [{}])[0].get("delta", {})
@@ -114,13 +113,12 @@ def auth_headers() -> dict[str, str]:
"""
Log in once per session and return auth headers.
- On a fresh Studio install the bootstrap password triggers a forced password
- change (must_change_password=True). Any subsequent API call using that token
- returns 403 "Password change required". This fixture detects that state,
- automatically completes the change-password flow, and re-logs in so all other
- tests get a fully usable token.
+ On a fresh install the bootstrap password forces a change
+ (must_change_password=True); calls with that token return 403 "Password
+ change required". This fixture detects that, auto-completes the change, and
+ re-logs in so other tests get a usable token.
- The new password used during auto-change is:
+ The auto-change new password is:
STUDIO_TEST_NEW_PASSWORD (env var, optional)
or PASSWORD + "-test" (derived default)
@@ -142,8 +140,8 @@ def auth_headers() -> dict[str, str]:
assert token, "access_token is empty"
if body.get("must_change_password"):
- # Bootstrap token is restricted — only /api/auth/change-password works with it.
- # Auto-complete the forced change so the rest of the tests get a full token.
+ # Bootstrap token only works with /api/auth/change-password; auto-complete
+ # the forced change so the rest of the tests get a full token.
new_password = os.getenv("STUDIO_TEST_NEW_PASSWORD") or f"{PASSWORD}-test"
change_resp = requests.post(
_url("/api/auth/change-password"),
@@ -176,11 +174,11 @@ def public_key_pem(auth_headers: dict[str, str]) -> str:
@pytest.fixture(scope = "session")
def vision_image_data_url() -> str:
"""
- Download the sloth image once per session and return it as a base64 data URI.
+ Download the sloth image once per session as a base64 data URI.
- Using a data URI instead of a remote URL ensures every provider receives
- the image inline — Gemini's OpenAI-compatible layer does not fetch external
- HTTP URLs, so raw image_url links silently produce empty replies for Gemini.
+ A data URI sends the image inline to every provider; Gemini's
+ OpenAI-compatible layer does not fetch external HTTP URLs, so raw image_url
+ links silently produce empty Gemini replies.
"""
resp = requests.get(_VISION_IMAGE_URL, timeout = 30)
resp.raise_for_status()
@@ -192,10 +190,10 @@ def vision_image_data_url() -> str:
@pytest.fixture(scope = "session")
def encrypt_key(public_key_pem: str):
"""
- Return a callable encrypt_key(plaintext: str) -> str (base64 RSA-OAEP ciphertext).
- Uses the backend's RSA public key — mirrors what the frontend does.
+ Return encrypt_key(plaintext: str) -> str (base64 RSA-OAEP ciphertext).
+ Uses the backend's RSA public key — mirrors the frontend.
"""
- # Decode PEM → load RSA public key
+ # Load RSA public key from PEM
pem_bytes = public_key_pem.encode("utf-8")
rsa_pub = serialization.load_pem_public_key(pem_bytes)
@@ -298,8 +296,8 @@ class TestRegistry:
class TestProviderCRUD:
"""
- These tests run sequentially within the class and share state via class variables.
- They create, read, update, and delete a single test provider config.
+ Run sequentially, sharing state via class variables. Create, read, update,
+ and delete a single test provider config.
"""
_created_id: str = ""
@@ -356,7 +354,7 @@ class TestProviderCRUD:
)
assert resp.status_code == 204, f"Delete failed ({resp.status_code}): {resp.text}"
- # Confirm gone from list
+ # Confirm gone
list_resp = requests.get(_url("/api/providers/"), headers = auth_headers, timeout = 10)
ids = [p["id"] for p in list_resp.json()]
assert TestProviderCRUD._created_id not in ids, "Deleted provider still in list"
@@ -366,7 +364,7 @@ class TestProviderCRUD:
# ── TestProviderInference ────────────────────────────────────────────
-# Build parametrize list: (provider_type, model, api_key) for configured providers only
+# Parametrize (provider_type, model, api_key) for configured providers
_INFERENCE_PARAMS = [
pytest.param(
ptype,
@@ -384,8 +382,8 @@ _INFERENCE_PARAMS = [
class TestProviderInference:
"""
- Live inference tests — one parametrized set per provider.
- Each test is automatically skipped when the provider's API key env var is not set.
+ Live inference tests, one parametrized set per provider. Each is skipped
+ when the provider's API key env var is unset.
"""
@pytest.mark.parametrize("provider_type,model,api_key", _INFERENCE_PARAMS)
@@ -475,7 +473,7 @@ class TestProviderInference:
# ── TestVisionInference ─────────────────────────────────────────────
-# Sloth photo — used to test vision routing across providers
+# Sloth photo for testing vision routing across providers
_VISION_IMAGE_URL = "https://www.travelexcellence.com/images/where-to-see-sloths-in-costa-rica.jpg"
_VISION_PARAMS = [
@@ -496,8 +494,8 @@ _VISION_PARAMS = [
class TestVisionInference:
"""
- Send a 1×1 white PNG alongside a text question to each vision-capable provider.
- Verifies that image content parts survive the proxy and the provider replies.
+ Send a 1×1 white PNG plus a text question to each vision-capable provider.
+ Verifies image content parts survive the proxy and the provider replies.
"""
@pytest.mark.parametrize("provider_type,model,api_key", _VISION_PARAMS)
@@ -559,9 +557,9 @@ class TestLocalInferenceUnaffected:
"""
POST /v1/chat/completions without provider fields must not return 422 or 500.
- 200 = a local model is loaded and responded.
- 503 = no model loaded (expected in test environment — that's fine).
- Any other 4xx/5xx (except 503) = regression in request handling.
+ 200 = local model loaded and responded.
+ 503 = no model loaded (expected in test env — fine).
+ Any other 4xx/5xx (except 503) = request-handling regression.
"""
resp = requests.post(
_url("/v1/chat/completions"),
diff --git a/studio/backend/tests/test_pytorch_mirror.py b/studio/backend/tests/test_pytorch_mirror.py
index 5844f209b64..f1574fb31ec 100644
--- a/studio/backend/tests/test_pytorch_mirror.py
+++ b/studio/backend/tests/test_pytorch_mirror.py
@@ -19,8 +19,8 @@ OFFICIAL_URL = "https://download.pytorch.org/whl"
def _reload_whl_base(monkeypatch, mirror_value = None):
- """(Re-)import install_python_stack with a controlled env and return _PYTORCH_WHL_BASE."""
- # Remove cached module so the module-level assignment re-executes
+ """(Re-)import install_python_stack with a controlled env, return _PYTORCH_WHL_BASE."""
+ # Drop cached module so the module-level assignment re-executes
sys.modules.pop("install_python_stack", None)
if mirror_value is None:
@@ -28,7 +28,7 @@ def _reload_whl_base(monkeypatch, mirror_value = None):
else:
monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", mirror_value)
- # Temporarily add the script's directory to sys.path for import
+ # Add the script's directory to sys.path for import
script_dir = str(_INSTALL_SCRIPT.parent)
monkeypatch.syspath_prepend(script_dir)
diff --git a/studio/backend/tests/test_recommended_folders_permission.py b/studio/backend/tests/test_recommended_folders_permission.py
index 659c3b547df..ffe8c65ac0f 100644
--- a/studio/backend/tests/test_recommended_folders_permission.py
+++ b/studio/backend/tests/test_recommended_folders_permission.py
@@ -6,17 +6,16 @@ Regression test for the /recommended-folders (and /browse-folders) 500
caused by an unreadable model directory, e.g. a stock root-owned
``ollama`` install at ``/usr/share/ollama/.ollama/models``.
-Root cause: the folder-scan helpers in ``routes.models`` probed candidate
-paths with a bare ``Path(p).is_dir()``. On Python <= 3.11 that returned
-``False`` for an unreadable path; on Python >= 3.12 ``is_dir()`` propagates
+Root cause: ``routes.models`` folder-scan helpers probed candidates with a
+bare ``Path(p).is_dir()``. On Python <= 3.11 that returned ``False`` for an
+unreadable path; on Python >= 3.12 ``is_dir()`` propagates
``PermissionError`` (EACCES), so the endpoint 500-ed through the whole
-middleware stack instead of just skipping the directory. The probes now go
-through the module-level ``_safe_is_dir`` helper.
+middleware stack instead of skipping the directory. Probes now go through
+the module-level ``_safe_is_dir`` helper.
-``routes.models`` pulls the full backend dependency tree (fastapi,
-structlog, the models package, ...), so rather than stand up the app we
-extract the real ``_safe_is_dir`` definition from the source file and
-exercise that exact function in isolation. The test therefore stays
+``routes.models`` pulls the full backend dep tree (fastapi, structlog, the
+models package, ...), so rather than stand up the app we extract the real
+``_safe_is_dir`` from the source file and exercise it in isolation —
dependency-free while still running the shipped code.
Run:
@@ -36,7 +35,7 @@ _models_src = _backend_root / "routes" / "models.py"
def _load_safe_is_dir():
"""Return the real ``_safe_is_dir`` from routes/models.py without
- importing the (heavily dependency-laden) module."""
+ importing the dependency-laden module."""
tree = ast.parse(_models_src.read_text())
fn = next(
node
@@ -51,8 +50,8 @@ def _load_safe_is_dir():
safe_is_dir = _load_safe_is_dir()
-# Permission bits are bypassed for the superuser, so the chmod-000 setup
-# below would not actually deny access when running as root.
+# The superuser bypasses permission bits, so the chmod-000 setup below
+# would not deny access when running as root.
_skip_as_root = pytest.mark.skipif(
hasattr(os, "geteuid") and os.geteuid() == 0,
reason = "root bypasses filesystem permission bits",
@@ -60,8 +59,8 @@ _skip_as_root = pytest.mark.skipif(
def test_helper_exists_in_source():
- # Guards against a refactor silently dropping the helper the fix
- # depends on (the extractor would then raise StopIteration).
+ # Guard against a refactor silently dropping the helper the fix needs
+ # (the extractor would then raise StopIteration).
assert callable(safe_is_dir)
@@ -83,8 +82,8 @@ def test_file_is_false(tmp_path):
def test_mode000_dir_itself_is_still_a_dir(tmp_path):
"""A mode-000 directory is still stat-able via its (traversable)
parent, so _safe_is_dir reports True without raising. Filtering out
- dirs we cannot actually *read* is the caller's separate
- os.access(R_OK|X_OK) check, not this helper's job."""
+ dirs we can't *read* is the caller's separate os.access(R_OK|X_OK)
+ check, not this helper's job."""
locked = tmp_path / "locked"
locked.mkdir()
os.chmod(locked, 0o000)
@@ -96,8 +95,8 @@ def test_mode000_dir_itself_is_still_a_dir(tmp_path):
@_skip_as_root
def test_path_under_unreadable_parent_returns_false_not_raises(tmp_path):
- """The exact production scenario: stat()-ing a child of a mode-700
- system directory, e.g. ``/usr/share/ollama/.ollama/models``."""
+ """The production scenario: stat()-ing a child of a mode-700 system
+ directory, e.g. ``/usr/share/ollama/.ollama/models``."""
parent = tmp_path / "ollama"
parent.mkdir()
os.chmod(parent, 0o000)
@@ -113,8 +112,8 @@ def test_path_under_unreadable_parent_returns_false_not_raises(tmp_path):
reason = "is_dir() only propagates PermissionError on Python >= 3.12",
)
def test_demonstrates_the_underlying_stdlib_regression(tmp_path):
- """Documents *why* _safe_is_dir exists: the old bare pattern raises
- on the interpreters Studio ships on (3.12+)."""
+ """Documents *why* _safe_is_dir exists: the old bare pattern raises on
+ the interpreters Studio ships on (3.12+)."""
parent = tmp_path / "ollama"
parent.mkdir()
os.chmod(parent, 0o000)
diff --git a/studio/backend/tests/test_responses_api.py b/studio/backend/tests/test_responses_api.py
index c0ec876ad00..6ef874bd988 100644
--- a/studio/backend/tests/test_responses_api.py
+++ b/studio/backend/tests/test_responses_api.py
@@ -2,9 +2,9 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""
-Tests for the OpenAI Responses API schemas and input normalisation.
-These tests do NOT require a running server or GPU -- they validate
-the Pydantic models and the _normalise_responses_input helper.
+Tests for OpenAI Responses API schemas and input normalisation.
+No running server or GPU required -- validates the Pydantic models and
+the _normalise_responses_input helper.
"""
import sys
@@ -12,7 +12,7 @@ import os
import json
import re
-# Ensure backend is on path
+# Ensure backend is on path.
_backend = os.path.join(os.path.dirname(__file__), "..")
sys.path.insert(0, _backend)
@@ -34,33 +34,32 @@ from models.inference import (
# ── _normalise_responses_input: copied from routes/inference.py ──
-# We cannot import routes.inference directly because routes/__init__.py
-# pulls in heavy dependencies (structlog/twisted/torch). This is a
-# direct copy of the function for testing purposes.
+# Can't import routes.inference directly: routes/__init__.py pulls in
+# heavy deps (structlog/twisted/torch). This is a direct copy for tests.
def _normalise_responses_input(payload: ResponsesRequest) -> list:
- """Convert a ResponsesRequest into a list of ChatMessage for the completions backend."""
+ """Convert a ResponsesRequest into ChatMessages for the completions backend."""
messages = []
- # System / developer instructions
+ # System / developer instructions.
if payload.instructions:
messages.append(ChatMessage(role = "system", content = payload.instructions))
- # Simple string input
+ # Simple string input.
if isinstance(payload.input, str):
if payload.input:
messages.append(ChatMessage(role = "user", content = payload.input))
return messages
- # List of ResponsesInputMessage
+ # List of ResponsesInputMessage.
for msg in payload.input:
role = "system" if msg.role == "developer" else msg.role
if isinstance(msg.content, str):
messages.append(ChatMessage(role = role, content = msg.content))
else:
- # Convert Responses content parts -> Chat content parts
+ # Convert Responses content parts -> Chat content parts.
parts = []
for part in msg.content:
if isinstance(part, ResponsesInputTextPart):
@@ -130,7 +129,7 @@ class TestResponsesRequest:
assert req.instructions == "You are a helpful assistant."
def test_extra_fields_accepted(self):
- """OpenAI SDK may send fields we don't model -- extra='allow' should pass."""
+ """OpenAI SDK may send unmodeled fields -- extra='allow' must pass."""
req = ResponsesRequest(
input = "test",
tools = [{"type": "web_search_preview"}],
@@ -167,7 +166,7 @@ class TestResponsesRequest:
class TestResponsesResponse:
- """Validate response models serialise correctly."""
+ """Response models serialise correctly."""
def test_basic_response(self):
resp = ResponsesResponse(
@@ -224,7 +223,7 @@ class TestResponsesResponse:
class TestNormaliseResponsesInput:
- """Test _normalise_responses_input converts Responses input to ChatMessages."""
+ """_normalise_responses_input converts Responses input to ChatMessages."""
def test_string_input(self):
payload = ResponsesRequest(input = "Hello world")
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index 146d6017d00..c182e3d6d0c 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -6,19 +6,19 @@ Tests for the OpenAI /v1/responses client-side function-calling pass-through.
Covers:
- ResponsesRequest accepts Responses-shape `tools`, `tool_choice`,
- `parallel_tool_calls`, and the `function_call` / `function_call_output`
- input items used for multi-turn tool loops.
-- _translate_responses_tools_to_chat() converts the flat Responses tool
- shape to the nested Chat Completions shape, drops non-function built-in
- tools, and returns None for empty lists.
-- _translate_responses_tool_choice_to_chat() passes string choices through
- and converts {type:function,name:X} to Chat Completions' nested shape.
-- _normalise_responses_input() maps function_call_output items to
+ `parallel_tool_calls`, and `function_call` / `function_call_output`
+ input items for multi-turn tool loops.
+- _translate_responses_tools_to_chat(): flat Responses tool shape ->
+ nested Chat Completions shape, drops non-function built-in tools,
+ returns None for empty lists.
+- _translate_responses_tool_choice_to_chat(): passes string choices
+ through, converts {type:function,name:X} to the nested shape.
+- _normalise_responses_input(): maps function_call_output items to
role="tool" ChatMessages with tool_call_id, and function_call items to
assistant messages with tool_calls.
-- _chat_tool_calls_to_responses_output() preserves call_id and drops
+- _chat_tool_calls_to_responses_output(): keeps call_id, drops
non-function tool calls.
-- ResponsesOutputFunctionCall and ResponsesResponse round-trip tool-call
+- ResponsesOutputFunctionCall / ResponsesResponse round-trip tool-call
outputs without losing fields.
No running server or GPU required.
@@ -104,9 +104,9 @@ class TestResponsesRequestTools:
assert req.parallel_tool_calls is True
def test_builtin_tool_type_passes_validation(self):
- """Non-function built-in tools (web_search, file_search, mcp, ...) must
- not raise at request validation so SDKs that default to them don't
- fail on Studio; they are filtered out during translation."""
+ """Non-function built-in tools (web_search, file_search, mcp, ...)
+ must not raise at validation so SDKs that default to them don't
+ fail on Studio; they're filtered out during translation."""
req = ResponsesRequest(
input = "hi",
tools = [{"type": "web_search_preview"}],
@@ -249,8 +249,8 @@ class TestToolChoiceTranslation:
) == {"type": "function", "function": {"name": "get_weather"}}
def test_already_chat_nested_shape_passes_through(self):
- """If a client happens to send the Chat Completions nested shape,
- we don't double-wrap it."""
+ """A client sending the Chat Completions nested shape isn't
+ double-wrapped."""
already_nested = {"type": "function", "function": {"name": "get_weather"}}
assert _translate_responses_tool_choice_to_chat(already_nested) == already_nested
@@ -297,10 +297,10 @@ class TestNormaliseResponsesInputWithTools:
def test_instructions_plus_developer_message_are_merged(self):
"""Codex CLI sends `instructions` (system prompt) AND a developer
- message in `input`. Strict chat templates (harmony / gpt-oss, Qwen3,
- ...) raise "System message must be at the beginning" when two
- separate system-role messages appear, so we must emit exactly one
- merged system message at the top.
+ message in `input`. Strict chat templates (harmony / gpt-oss,
+ Qwen3, ...) raise "System message must be at the beginning" on two
+ separate system-role messages, so we emit exactly one merged
+ system message at the top.
"""
payload = ResponsesRequest(
instructions = "Base instructions.",
@@ -314,14 +314,14 @@ class TestNormaliseResponsesInputWithTools:
assert len(system_roles) == 1
assert "Base instructions." in system_roles[0].content
assert "Developer override." in system_roles[0].content
- # System must be the very first message for strict templates.
+ # System must be the first message for strict templates.
assert msgs[0].role == "system"
assert msgs[1].role == "user"
def test_developer_message_after_user_is_still_hoisted(self):
- """Multi-turn conversations where a developer message appears after
- user turns must still produce a single leading system message, not
- a mid-conversation system that strict templates reject."""
+ """A developer message appearing after user turns must still
+ produce a single leading system message, not a mid-conversation
+ system that strict templates reject."""
payload = ResponsesRequest(
input = [
{"role": "user", "content": "Hello"},
@@ -486,8 +486,8 @@ class TestCodexStyleRequestShapes:
"""Regression tests for the request shapes OpenAI Codex CLI sends."""
def test_assistant_replay_output_text_accepted(self):
- """Codex replays prior assistant turns with `output_text` content.
- Before, this triggered a 422 on every turn after the first."""
+ """Codex replays prior assistant turns with `output_text` content;
+ this used to 422 on every turn after the first."""
req = ResponsesRequest(
input = [
{"role": "user", "content": "Hi"},
@@ -514,7 +514,7 @@ class TestCodexStyleRequestShapes:
def test_reasoning_item_accepted_as_unknown(self):
"""`reasoning` items replayed from prior o-series turns must not
- fail validation — Codex preserves them in multi-turn."""
+ fail validation — Codex keeps them in multi-turn."""
req = ResponsesRequest(
input = [
{"role": "user", "content": "Hi"},
@@ -532,7 +532,7 @@ class TestCodexStyleRequestShapes:
def test_unknown_content_part_type_accepted(self):
"""Unknown content-part types (e.g. future input_audio) validate as
- ResponsesUnknownContentPart so the whole request doesn't 422."""
+ ResponsesUnknownContentPart so the request doesn't 422."""
req = ResponsesRequest(
input = [
{
@@ -596,15 +596,15 @@ class TestCodexStyleRequestShapes:
],
)
msgs = _normalise_responses_input(payload)
- # Single leading merged system; no mid-conversation system.
+ # One leading merged system; no mid-conversation system.
assert msgs[0].role == "system"
assert sum(1 for m in msgs if m.role == "system") == 1
assert "Base instructions." in msgs[0].content
assert "Dev override." in msgs[0].content
roles = [m.role for m in msgs[1:]]
- # Reasoning item is dropped. Order: user, assistant(tool_calls),
- # tool, assistant(text), user.
+ # Reasoning dropped. Order: user, assistant(tool_calls), tool,
+ # assistant(text), user.
assert roles == ["user", "assistant", "tool", "assistant", "user"]
assert msgs[2].tool_calls is not None
assert msgs[3].role == "tool"
@@ -612,9 +612,9 @@ class TestCodexStyleRequestShapes:
assert msgs[4].content == "It's 20°C."
def test_single_output_text_part_flattens_to_string(self):
- """ChatMessage assistant role prefers plain string content — tests
- confirm we don't forward a single-part array that would otherwise
- force legacy chat templates into multimodal handling."""
+ """ChatMessage assistant role prefers plain string content — we
+ don't forward a single-part array that would force legacy chat
+ templates into multimodal handling."""
payload = ResponsesRequest(
input = [
{
@@ -630,9 +630,9 @@ class TestCodexStyleRequestShapes:
class TestTranslatedMessagesValidate:
- """Verify that the messages produced by _normalise_responses_input
- satisfy ChatMessage's role-shape validator so the downstream /v1/chat/
- completions pass-through does not reject them."""
+ """Messages from _normalise_responses_input satisfy ChatMessage's
+ role-shape validator so the downstream /v1/chat/completions
+ pass-through doesn't reject them."""
def test_round_trip_multi_turn(self):
payload = ResponsesRequest(
@@ -654,6 +654,6 @@ class TestTranslatedMessagesValidate:
)
msgs = _normalise_responses_input(payload)
for m in msgs:
- # Constructing a fresh ChatMessage from the dump round-trips the
- # role-shape validator — the key invariant for the passthrough.
+ # Building a fresh ChatMessage from the dump round-trips the
+ # role-shape validator — the passthrough's key invariant.
ChatMessage(**m.model_dump(exclude_none = True))
diff --git a/studio/backend/tests/test_rocm_oom_guard.py b/studio/backend/tests/test_rocm_oom_guard.py
index d27ee83f1d7..6b2c6aa84fc 100644
--- a/studio/backend/tests/test_rocm_oom_guard.py
+++ b/studio/backend/tests/test_rocm_oom_guard.py
@@ -3,16 +3,16 @@
"""Unit tests for _rocm_classify_unified_memory (ROCm OOM-guard classifier).
-Covers the three classification paths:
+Three classification paths:
Path 1 – canonical gcnArchName attribute present.
Path 2 – gcnArchName absent, alternate-spelling attribute present.
Path 3 – ALL arch attrs absent; falls back to device-name substring match.
-Regression for: Strix Halo (gfx1151) misclassified as discrete on AMD SDK /
-Radeon wheels that populate props.name = "Radeon 8060S Graphics" but do NOT
-set any gcnArchName attribute. Without the 8060s/8050s name patterns the
-fallback returned is_unified=False, applying the 0.90 fraction instead of
-0.80 and leaving only ~12.8 GiB OS headroom on a 128 GiB unified-memory pool.
+Regression: Strix Halo (gfx1151) misclassified as discrete on AMD SDK / Radeon
+wheels that set props.name = "Radeon 8060S Graphics" but no gcnArchName attr.
+Without the 8060s/8050s name patterns the fallback returned is_unified=False,
+applying 0.90 instead of 0.80 and leaving only ~12.8 GiB OS headroom on a
+128 GiB unified-memory pool.
"""
from __future__ import annotations
@@ -62,7 +62,7 @@ class TestCanonicalGcnArchName:
assert is_unified is True
def test_canonical_attr_wins_over_name(self) -> None:
- """Arch attr takes priority; device name should be ignored."""
+ """Arch attr takes priority; device name is ignored."""
# Discrete arch, but name looks like a unified SKU — arch must win.
props = _props(gcnArchName = "gfx1100", name = "Radeon 890M")
gcn, is_unified = _rocm_classify_unified_memory(props)
@@ -97,7 +97,7 @@ class TestAlternateSpellingFallback:
assert is_unified is False
def test_first_non_empty_attr_wins(self) -> None:
- """When multiple alternate attrs are present the first non-empty one wins."""
+ """With multiple alternate attrs, the first non-empty one wins."""
props = _props(gcn_arch_name = "gfx1151", arch_name = "gfx1100", name = "irrelevant")
gcn, is_unified = _rocm_classify_unified_memory(props)
assert gcn == "gfx1151"
@@ -147,7 +147,7 @@ class TestDeviceNameFallback:
"Radeon RX 6900 XT",
"Radeon Pro W7900",
"AMD Instinct MI300X",
- # Names that contain superficially similar substrings but are discrete
+ # Superficially similar substrings but discrete
"Radeon RX 580",
"Radeon VII",
],
@@ -161,7 +161,7 @@ class TestDeviceNameFallback:
), f"discrete device {device_name!r} should NOT be classified as unified-memory"
def test_empty_name_returns_false(self) -> None:
- """Completely absent name must not crash and must default to discrete."""
+ """Absent name must not crash and must default to discrete."""
props = _props() # no 'name' attr at all
gcn, is_unified = _rocm_classify_unified_memory(props)
assert gcn == ""
diff --git a/studio/backend/tests/test_safetensors_capability_advertise.py b/studio/backend/tests/test_safetensors_capability_advertise.py
index 5e3d2cc9d1f..1e40f376f32 100644
--- a/studio/backend/tests/test_safetensors_capability_advertise.py
+++ b/studio/backend/tests/test_safetensors_capability_advertise.py
@@ -2,9 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Capability advertisement contract: classifier honesty, worker→
-orchestrator IPC hop, and route-layer end-to-end. Pure helpers + fakes;
-no torch / transformers import.
+Capability advertisement contract: classifier honesty, worker→orchestrator
+IPC hop, route-layer end-to-end. Pure helpers + fakes; no torch/transformers.
"""
from __future__ import annotations
@@ -116,7 +115,7 @@ def test_detect_safetensors_features_none_template_returns_all_false():
def test_detect_safetensors_features_gptoss_disables_tools():
- """gpt-oss Harmony: tools intentionally off even if template marks it."""
+ """gpt-oss Harmony: tools off even if template marks it."""
from routes.inference import _detect_safetensors_features
backend = MagicMock()
@@ -129,11 +128,10 @@ def test_detect_safetensors_features_gptoss_disables_tools():
assert flags["supports_tools"] is False
-# Llama-3 / Mistral templates advertise tool handling but the model emits
-# tool calls in <|python_tag|> / [TOOL_CALLS] format -- not the
-# <tool_call> / <function= our parser understands. The route helper must
-# refuse to flip supports_tools=True for those families so the UI does
-# not enable a pill the agentic loop cannot honour.
+# Llama-3 / Mistral templates advertise tools but emit calls in
+# <|python_tag|> / [TOOL_CALLS] format -- not the <tool_call> / <function=
+# our parser understands. The route helper must not flip supports_tools=True
+# for those families, else the UI enables a pill the agentic loop can't honour.
LLAMA3_TEMPLATE = """
{%- if tools %}
@@ -207,10 +205,10 @@ def test_detect_safetensors_features_function_xml_format_keeps_tools_on():
assert flags["supports_tools"] is True
-# Qwen3.5 family pins -- the live GGUF + safetensors templates fetched
-# from the unsloth/Qwen3.5-0.8B(-GGUF) repos both wrap tool calls as
-# ``<tool_call>\n<function=name>...``. Capture a faithful slice so the
-# classifier never silently regresses for this family.
+# Qwen3.5 family pins -- the live GGUF + safetensors templates from the
+# unsloth/Qwen3.5-0.8B(-GGUF) repos both wrap tool calls as
+# ``<tool_call>\n<function=name>...``. Faithful slice so the classifier
+# never silently regresses for this family.
QWEN35_TOOL_INSTRUCTION = (
"{%- if tools %}\n"
@@ -234,7 +232,7 @@ QWEN35_TOOL_INSTRUCTION = (
def test_detect_safetensors_features_qwen35_keeps_tools_on():
- """unsloth/Qwen3.5-0.8B family must surface tools+reasoning enabled."""
+ """unsloth/Qwen3.5-0.8B family must surface tools+reasoning on."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Qwen3.5-0.8B")
@@ -248,7 +246,7 @@ def test_detect_safetensors_features_qwen35_keeps_tools_on():
def test_orchestrator_mirrors_chat_template_info_into_models_dict():
- """Worker → orchestrator must copy chat_template_info verbatim."""
+ """Worker → orchestrator copies chat_template_info verbatim."""
from core.inference.orchestrator import InferenceOrchestrator
orch = InferenceOrchestrator.__new__(InferenceOrchestrator)
@@ -274,7 +272,7 @@ def test_orchestrator_mirrors_chat_template_info_into_models_dict():
},
}
- # Replay orchestrator.load_model's mirror block verbatim.
+ # Replay orchestrator.load_model's mirror block.
orch.active_model_name = model_info["identifier"]
orch.models[orch.active_model_name] = {
"is_vision": model_info.get("is_vision", False),
@@ -386,7 +384,7 @@ def test_worker_load_reply_payload_includes_chat_template_info():
def test_worker_load_reply_payload_survives_missing_template():
- """Tokenizer with no chat_template still produces a valid reply."""
+ """Tokenizer with no chat_template still yields a valid reply."""
class _StubBackend:
def __init__(self):
@@ -421,7 +419,7 @@ def test_worker_load_reply_payload_survives_missing_template():
def test_route_layer_emits_supports_tools_true_for_qwen3_safetensors():
- """End-to-end: Qwen3 safetensors flips supports_tools=True."""
+ """E2E: Qwen3 safetensors flips supports_tools=True."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index ff5653c7425..526ea2d19fc 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -4,27 +4,26 @@
"""
Tests for the safetensors agentic tool loop.
-Covers the shared ``tool_call_parser`` helpers and the cumulative-text
-state machine inside ``safetensors_agentic.run_safetensors_tool_loop``.
-The loop is exercised with hand-crafted fake single-turn generators so
-no model load is needed; the tests run in CI under a few seconds.
+Covers the shared ``tool_call_parser`` helpers and the cumulative-text state
+machine in ``safetensors_agentic.run_safetensors_tool_loop``. The loop runs
+against hand-crafted fake single-turn generators, so no model load is needed;
+the tests finish in CI within a few seconds.
-Edge cases under coverage:
+Edge cases covered:
* Plain answers (no tool calls) flush full content.
* Single ``<tool_call>{json}</tool_call>`` triggers the tool and re-enters.
* Single ``<function=name>...`` XML form triggers the same path.
* Truncated unclosed ``<tool_call>`` is still parsed.
* Tool result is fed back as ``role=tool`` for the next iteration.
-* Bad JSON inside ``<tool_call>`` does not raise and (when healed) is
- routed as a ``{"query": ...}`` web search call.
-* Duplicate tool calls produce a synthetic "do not repeat" result the
- second time.
+* Bad JSON inside ``<tool_call>`` does not raise and (when healed) routes as a
+ ``{"query": ...}`` web search call.
+* Duplicate tool calls produce a synthetic "do not repeat" result the 2nd time.
* ``__IMAGES__`` sentinel is stripped before the model sees the result.
-* Tool execution errors are tagged so the model gets a nudge but the
- loop keeps streaming.
+* Tool execution errors are tagged so the model gets a nudge but the loop keeps
+ streaming.
* Cancel is honoured between iterations.
-* ``max_tool_iterations`` cap is respected and a final-answer attempt
- closes the stream cleanly.
+* ``max_tool_iterations`` cap is respected and a final-answer attempt closes the
+ stream cleanly.
"""
import threading
@@ -64,7 +63,7 @@ class TestParser:
assert "hello" in tc["function"]["arguments"]
def test_json_tool_call_unclosed(self):
- # No </tool_call>; balanced-brace extractor must still close.
+ # No </tool_call>; balanced-brace extractor must still close it.
text = '<tool_call>{"name":"python","arguments":{"code":"print(1)"}}'
result = parse_tool_calls_from_text(text)
assert len(result) == 1
@@ -86,9 +85,9 @@ class TestParser:
assert "ls -la" in result[0]["function"]["arguments"]
def test_code_with_embedded_xml(self):
- # A code parameter contains the literal </parameter>. Must not
- # truncate the value because the parser uses end-of-body as the
- # only boundary for single-parameter calls.
+ # A code parameter contains the literal </parameter>. Must not truncate
+ # the value: the parser uses end-of-body as the only boundary for
+ # single-parameter calls.
text = (
"<function=python><parameter=code>html = '<a></a>'\n"
"print('hi')</parameter></function>"
@@ -121,7 +120,7 @@ class TestParser:
def test_bad_json_does_not_raise(self):
text = "<tool_call>{not valid json}</tool_call>"
result = parse_tool_calls_from_text(text)
- # Bad JSON is silently dropped; caller can fall back to text.
+ # Bad JSON is dropped silently; caller can fall back to text.
assert result == []
def test_has_tool_signal(self):
@@ -147,7 +146,7 @@ class TestParser:
def test_strip_markup_unclosed_final(self):
text = "before <tool_call>{partial"
- # With final=True the trailing run is dropped.
+ # final=True drops the trailing run.
assert strip_tool_markup(text, final = True) == "before"
# Without final=True the unclosed run is preserved.
assert "partial" in strip_tool_markup(text)
@@ -220,8 +219,7 @@ def _make_loop(
):
"""Build a configured loop with a multi-turn fake generator.
- ``turns`` is a list of chunk-lists; iteration N yields chunks from
- ``turns[N]``.
+ ``turns`` is a list of chunk-lists; iteration N yields chunks from ``turns[N]``.
"""
turn_iter = iter(turns)
@@ -260,7 +258,7 @@ class TestLoopBasic:
contents = [e for e in events if e["type"] == "content"]
statuses = [e for e in events if e["type"] == "status"]
assert contents, "expected at least one content event"
- # Final cumulative content should contain the answer.
+ # Final cumulative content must contain the answer.
final_text = contents[-1]["text"]
assert "Hello world!" in final_text
assert statuses and statuses[-1]["text"] == ""
@@ -284,7 +282,7 @@ class TestLoopBasic:
assert "tool_start" in kinds
assert "tool_end" in kinds
- # Tool was actually called with the parsed arguments.
+ # Tool was called with the parsed arguments.
assert exec_fn.calls == [("web_search", {"query": "weather"})]
tool_start = next(e for e in events if e["type"] == "tool_start")
@@ -402,8 +400,8 @@ class TestLoopBasic:
def test_truncated_unclosed_tool_call(self):
loop, exec_fn = _make_loop(
turns = [
- # No </tool_call>; balanced-brace parser must still
- # succeed because the JSON itself is balanced.
+ # No </tool_call>; balanced-brace parser still succeeds because
+ # the JSON itself is balanced.
['<tool_call>{"name":"web_search","arguments":{"query":"x"}}'],
["done"],
],
@@ -413,14 +411,13 @@ class TestLoopBasic:
assert exec_fn.calls == [("web_search", {"query": "x"})]
def test_bad_json_healed_to_query(self):
- # Tool call with non-JSON string arguments. With auto_heal_tool_calls
- # the string is routed as {"query": ...}.
+ # Tool call with non-JSON string arguments. With auto_heal_tool_calls,
+ # the string routes as {"query": ...}.
loop, exec_fn = _make_loop(
turns = [
- # JSON inside the tool call is well-formed; the
- # ``arguments`` is a string that is not itself valid
- # JSON for ``_coerce_arguments`` to parse, so the
- # heal path runs.
+ # JSON inside the tool call is well-formed, but ``arguments`` is
+ # a string that ``_coerce_arguments`` cannot parse as JSON, so
+ # the heal path runs.
['<tool_call>{"name":"web_search","arguments":"hello world"}</tool_call>'],
["ok"],
],
@@ -433,9 +430,8 @@ class TestLoopBasic:
class TestLoopBehaviour:
def test_duplicate_tool_call_synthetic_result(self):
- # Two identical successful calls in a row: the second is short-
- # circuited with a "do not repeat" message and execute_tool is
- # called only once.
+ # Two identical successful calls in a row: the second is short-circuited
+ # with a "do not repeat" message and execute_tool runs only once.
loop, exec_fn = _make_loop(
turns = [
['<tool_call>{"name":"web_search","arguments":{"query":"x"}}</tool_call>'],
@@ -452,9 +448,9 @@ class TestLoopBehaviour:
assert "do not repeat" in tool_end_events[1]["result"].lower()
def test_image_sentinel_stripped_from_model_feed(self):
- # The tool result has a frontend image sentinel that should be
- # stripped before being fed back into the next turn, BUT the
- # tool_end event still carries the raw result for the UI.
+ # The tool result's frontend image sentinel must be stripped before
+ # being fed into the next turn, BUT the tool_end event still carries the
+ # raw result for the UI.
loop, exec_fn = _make_loop(
turns = [
['<tool_call>{"name":"python","arguments":{"code":"plot()"}}</tool_call>'],
@@ -490,7 +486,7 @@ class TestLoopBehaviour:
auto_heal_tool_calls = True,
)
)
- # Model's second turn must not see "__IMAGES__".
+ # The model's second turn must not see "__IMAGES__".
assert len(captured) >= 2
tool_msgs = [m for m in captured[1] if m.get("role") == "tool"]
assert tool_msgs, "no tool message reached the model"
@@ -539,7 +535,7 @@ class TestLoopBehaviour:
events = _collect_events(loop)
tool_end = next(e for e in events if e["type"] == "tool_end")
assert tool_end["result"].startswith("Error")
- # The loop must still produce a content event after the failure.
+ # The loop must still emit a content event after the failure.
contents = [e for e in events if e["type"] == "content"]
assert contents
@@ -560,8 +556,8 @@ class TestLoopControl:
def test_cancel_event_breaks_loop(self):
cancel = threading.Event()
cancel.set()
- # Even with a fake stream that emits tool calls, the loop must
- # bail before invoking execute_tool when cancel is set.
+ # Even with a fake stream that emits tool calls, the loop must bail
+ # before invoking execute_tool when cancel is set.
exec_fn = FakeExecuteTool([])
events = list(
run_safetensors_tool_loop(
@@ -578,8 +574,8 @@ class TestLoopControl:
assert exec_fn.calls == []
def test_max_iterations_caps_loop(self):
- # The loop should stop after max_tool_iterations even if the
- # model keeps asking for tools, then emit a final-attempt round.
+ # The loop stops after max_tool_iterations even if the model keeps
+ # asking for tools, then emits a final-attempt round.
loop, exec_fn = _make_loop(
turns = [
# : tool call (executes once)
@@ -592,13 +588,13 @@ class TestLoopControl:
)
events = _collect_events(loop)
contents = [e for e in events if e["type"] == "content"]
- # Final content must include the final answer.
+ # Final content must contain the final answer.
assert contents and "final answer" in contents[-1]["text"]
class TestStatusFormatting:
def test_status_for_known_tools(self):
- # Use the private helper directly to verify status formatting.
+ # Call the private helper directly to verify status formatting.
assert (
safetensors_agentic._status_for_tool("web_search", {"query": "abc"}) == "Searching: abc"
)
@@ -617,10 +613,10 @@ class TestStatusFormatting:
class TestProseMentioningToolCall:
def test_assistant_prose_with_literal_tool_call_text_survives(self):
- # Regression: if the assistant text legitimately mentions
- # ``<tool_call>`` as a literal string and the parser finds no
- # actual call, the loop must surface the full content instead
- # of silently stripping everything past the literal marker.
+ # Regression: if assistant text legitimately mentions ``<tool_call>`` as
+ # a literal string and the parser finds no actual call, the loop must
+ # surface the full content instead of stripping everything past the
+ # literal marker.
loop, exec_fn = _make_loop(
turns = [
# : a real tool call so the loop moves to
@@ -640,9 +636,9 @@ class TestProseMentioningToolCall:
), f"prose mentioning <tool_call> should not be truncated; got {final!r}"
def test_tool_result_with_tool_call_text_does_not_retrigger(self):
- # Tool result text contains the literal ``<tool_call>`` string.
- # The loop must only parse the MODEL output, not the tool
- # result, so we should see exactly one call.
+ # Tool result text contains the literal ``<tool_call>`` string. The loop
+ # must parse only the MODEL output, not the tool result, so we see
+ # exactly one call.
loop, exec_fn = _make_loop(
turns = [
['<tool_call>{"name":"web_search","arguments":{"query":"x"}}</tool_call>'],
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 92fee2e8e53..1841d084b9e 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -117,7 +117,7 @@ class TestUntrustedHostBlock:
)
def test_dynamic_url_not_statically_blocked(self):
- # Static AST cannot resolve runtime URLs; bash blocklist is the fallback.
+ # Static AST can't resolve runtime URLs; bash blocklist is the fallback.
_ok('import requests; url = "https://example.com/"; requests.get(url)')
@@ -225,8 +225,8 @@ class TestUploadDenylist:
class TestSandboxEnvIsolation:
"""The sandbox subprocess env is built from a whitelist, not by stripping.
- Confirm every credential-shaped parent var is absent regardless of how the
- operator's process is configured. Covers Linux/macOS/WSL/Windows shapes.
+ Confirm every credential-shaped parent var is absent regardless of the
+ operator's process config. Covers Linux/macOS/WSL/Windows shapes.
"""
_SECRET_KEYS = (
@@ -313,8 +313,8 @@ class TestSandboxEnvIsolation:
def test_term_is_dumb(self, tmp_path):
from core.inference.tools import _build_safe_env
- # Prevents the sandbox from re-using the operator's TERM (e.g. xterm-256color)
- # which could trigger color-escape parsing in downstream tools.
+ # Avoid re-using the operator's TERM (e.g. xterm-256color) that
+ # could trigger color-escape parsing in downstream tools.
env = _build_safe_env(str(tmp_path))
assert env["TERM"] == "dumb"
@@ -348,9 +348,9 @@ class TestMaxBodyDefault:
class TestBashBlocklistPosition:
"""The blocklist must fire at command position only.
- Pre-fix the per-token loop fired on any token, so `grep -r curl .`
+ Pre-fix, the per-token loop fired on any token, so `grep -r curl .`
and `echo source` were rejected. The position-anchored regex plus a
- shlex-aware command-position-only token check is sufficient.
+ shlex-aware command-position-only token check fixes this.
"""
@staticmethod
@@ -366,8 +366,7 @@ class TestBashBlocklistPosition:
assert self._find()("echo source the data") == set()
def test_cat_with_word_source_allowed(self):
- # The 'source' word is an argument to echo; not blocked.
- # `echo` itself isn't blocked. Only legit allowed tokens here.
+ # 'source' is an argument to echo, and echo isn't blocked either.
assert self._find()("cat README.md && echo source") == set()
assert "source" not in self._find()("cat README.md && echo source")
assert "echo" not in self._find()("cat README.md && echo source")
@@ -397,14 +396,14 @@ class TestBashBlocklistPosition:
assert "wget" in self._find()("cd /tmp && wget https://bad")
def test_split_quotes_obfuscation_blocked(self):
- # shlex collapses 'r''m' -> 'rm' as a single token at command position.
+ # shlex collapses 'r''m' -> 'rm' at command position.
assert "rm" in self._find()("r''m -rf /")
def test_path_prefixed_command_blocked(self):
assert "sudo" in self._find()("/usr/bin/sudo whoami")
def test_nested_bash_c_blocked(self):
- # Recursion into the nested command string still catches command-position curl.
+ # Recursion into the nested command string catches command-position curl.
assert "curl" in self._find()("bash -c 'curl https://x'")
def test_subshell_command_blocked(self):
@@ -465,9 +464,9 @@ class TestBashBlocklistPosition:
class TestHfUploadImportGate:
- """HfApi-style upload-method blocking should require an HF import in
- scope; otherwise paramiko / boto3 / internal SDKs with the same
- method names hit a false positive."""
+ """HfApi-style upload-method blocking requires an HF import in scope;
+ otherwise paramiko / boto3 / internal SDKs with the same method names
+ false-positive."""
def test_paramiko_upload_file_allowed_without_hf_import(self):
_ok("import paramiko; sftp=None; sftp.upload_file('a','b')")
@@ -476,14 +475,14 @@ class TestHfUploadImportGate:
_ok("client=None; client.create_commit(Repo='x')")
def test_hf_api_upload_safe_path_allowed(self):
- # Sandbox-local relative path -- the call shape we want to permit.
+ # Sandbox-local relative path -- the permitted call shape.
_ok("from huggingface_hub import HfApi; HfApi().upload_file('a','b','c')")
def test_hf_upload_file_fq_safe_path_allowed(self):
_ok("import huggingface_hub; huggingface_hub.upload_file('a','b','c')")
def test_dynamic_builtin_import_safe_path_allowed(self):
- # `__import__('huggingface_hub')` puts HF in scope; relative-literal path is safe.
+ # `__import__('huggingface_hub')` puts HF in scope; relative literal is safe.
_ok("hf=__import__('huggingface_hub'); hf.HfApi().upload_file('a','b','c')")
def test_dynamic_importlib_safe_path_allowed(self):
@@ -499,8 +498,8 @@ class TestHfUploadImportGate:
)
def test_hf_bare_name_upload_safe_path_allowed(self):
- # `from huggingface_hub import upload_file` then bare `upload_file(...)`
- # with a sandbox-local relative-path literal is allowed.
+ # Bare `upload_file(...)` (imported from huggingface_hub) with a
+ # sandbox-local relative-path literal is allowed.
_ok(
"from huggingface_hub import upload_file;"
" upload_file(path_or_fileobj='x', path_in_repo='x', repo_id='r')"
@@ -519,15 +518,15 @@ class TestHfUploadImportGate:
)
def test_bare_name_upload_file_without_hf_import_allowed(self):
- # No HF import -- local helper named upload_file should pass.
+ # No HF import -- local helper named upload_file passes.
_ok("def upload_file(*a, **k):\n pass\nupload_file('x', 'y', 'z')")
class TestHfUploadSandboxLocalPaths:
- """The HF upload gate must only allow uploads of files that already live in
- the sandbox workdir. Absolute paths, `..` traversal, home expansion, and
- Windows drive letters are rejected because the LLM can use them to lift
- secrets from outside the sandbox."""
+ """The HF upload gate allows only files already in the sandbox workdir.
+ Absolute paths, `..` traversal, home expansion, and Windows drive
+ letters are rejected — the LLM could use them to lift secrets from
+ outside the sandbox."""
def test_relative_literal_allowed(self):
_ok(
@@ -621,8 +620,8 @@ class TestHfUploadSandboxLocalPaths:
)
def test_dynamic_variable_path_blocked(self):
- # A non-literal expression could resolve to any path at runtime;
- # the static checker cannot prove safety, so block.
+ # A non-literal expr could resolve to any path at runtime; the
+ # static checker can't prove safety, so block.
_blocked(
"import huggingface_hub, os\n"
"p = os.path.join('outputs', 'x.bin')\n"
@@ -674,11 +673,11 @@ class TestHfUploadSandboxLocalPaths:
class TestHfUploadEnvAndSecretLeakBlock:
- """The HF upload gate must reject any positional / keyword arg sourced from
- `os.environ` / `os.getenv` / subprocess env reads. Even though
- `_build_safe_env` strips HF_TOKEN/WANDB/AWS upfront for the sandbox shell,
- a Python script can still reach the parent process env if it bypasses the
- safe-env wrapper at the source -- so block statically."""
+ """The HF upload gate rejects any positional / keyword arg sourced from
+ `os.environ` / `os.getenv` / subprocess env reads. `_build_safe_env`
+ strips HF_TOKEN/WANDB/AWS for the sandbox shell, but a Python script
+ can still reach the parent env if it bypasses the safe-env wrapper at
+ the source -- so block statically."""
def test_path_from_os_environ_subscript_blocked(self):
_blocked(
@@ -756,7 +755,7 @@ class TestHfUploadEnvAndSecretLeakBlock:
)
def test_env_dict_unpacked_via_environ_attr_blocked(self):
- # `os.environ` as a bare reference (passed somewhere it gets serialized).
+ # Bare `os.environ` reference (passed somewhere it gets serialized).
_blocked(
"import huggingface_hub, os\n"
"huggingface_hub.upload_file(path_or_fileobj=str(os.environ),"
@@ -765,8 +764,8 @@ class TestHfUploadEnvAndSecretLeakBlock:
)
def test_repo_id_from_env_also_blocked(self):
- # Even non-path args must not source env vars -- an attacker could
- # encode secrets in repo_id or path_in_repo.
+ # Non-path args must not source env vars either -- an attacker
+ # could encode secrets in repo_id or path_in_repo.
_blocked(
"import huggingface_hub, os\n"
'huggingface_hub.upload_file(path_or_fileobj="x.bin",'
diff --git a/studio/backend/tests/test_studio_api.py b/studio/backend/tests/test_studio_api.py
index 70a103a2f86..c40729d9a87 100644
--- a/studio/backend/tests/test_studio_api.py
+++ b/studio/backend/tests/test_studio_api.py
@@ -4,9 +4,9 @@
"""
End-to-end tests for Unsloth Studio's HTTP API surface.
-Covers the OpenAI-compatible and Anthropic-compatible endpoints exposed
-by the server that ``unsloth studio run`` boots, plus API key
-authentication and the CLI's ``--help`` output:
+Covers the OpenAI- and Anthropic-compatible endpoints exposed by the
+server that ``unsloth studio run`` boots, plus API key authentication and
+the CLI's ``--help`` output:
1. curl -- basic chat completions (non-streaming)
2. curl -- streaming chat completions
@@ -38,14 +38,14 @@ Usage:
export UNSLOTH_E2E_API_KEY=sk-unsloth-... # from the server banner
pytest tests/test_studio_api.py -v
- # Pytest mode, fixture-managed server — pytest launches and tears
- # down the server itself. One-shot verification, CI-friendly.
+ # Pytest mode, fixture-managed server — pytest launches and tears down
+ # the server itself. One-shot verification, CI-friendly.
pytest tests/test_studio_api.py -v \\
--unsloth-model unsloth/Qwen3-1.7B-GGUF \\
--unsloth-gguf-variant UD-Q4_K_XL
-The ``base_url`` / ``api_key`` parameters on the test functions resolve
-via the ``studio_server`` session fixture in ``conftest.py``.
+The ``base_url`` / ``api_key`` parameters on the test functions resolve via
+the ``studio_server`` session fixture in ``conftest.py``.
Requires a GPU and ~2 GB of disk for the GGUF download.
"""
@@ -233,10 +233,10 @@ def test_openai_sdk(base_url: str, api_key: str):
def test_curl_with_tools(base_url: str, api_key: str):
"""Example 4: chat completion with tool calling enabled.
- Note: when ``enable_tools`` is set the server always returns SSE
- streaming regardless of the ``stream`` flag, so we parse SSE chunks.
- The model may or may not produce visible content -- tool orchestration
- can intercept the response -- so we only assert the endpoint succeeds.
+ When ``enable_tools`` is set the server always returns SSE streaming
+ regardless of the ``stream`` flag, so we parse SSE chunks. The model may
+ not produce visible content (tool orchestration can intercept the
+ response), so we only assert the endpoint succeeds.
"""
status, chunks = _stream_http(
f"{base_url}/v1/chat/completions",
@@ -268,16 +268,16 @@ def test_curl_with_tools(base_url: str, api_key: str):
# ── Standard OpenAI function-calling pass-through tests ─────────────
#
# Regression coverage for unslothai/unsloth#4999: Studio's
-# /v1/chat/completions used to silently strip standard OpenAI `tools`
-# and `tool_choice` fields, so clients (opencode, Claude Code, Cursor,
-# Continue, ...) could never get structured tool_calls back. These
-# tests exercise the client-side pass-through path that forwards those
-# fields to llama-server verbatim.
+# /v1/chat/completions used to silently strip standard OpenAI `tools` and
+# `tool_choice` fields, so clients (opencode, Claude Code, Cursor,
+# Continue, ...) never got structured tool_calls back. These tests exercise
+# the client-side pass-through path that forwards those fields to
+# llama-server verbatim.
#
-# They require a tool-capable GGUF (``supports_tools=True`` — e.g.
-# Qwen3, Qwen2.5-Coder, Llama-3.1-Instruct). The default test model
-# ``unsloth/Qwen3-1.7B-GGUF`` advertises tool support via its chat
-# template metadata.
+# They require a tool-capable GGUF (``supports_tools=True`` — e.g. Qwen3,
+# Qwen2.5-Coder, Llama-3.1-Instruct). The default test model
+# ``unsloth/Qwen3-1.7B-GGUF`` advertises tool support via its chat template
+# metadata.
_WEATHER_TOOL = {
"type": "function",
@@ -301,9 +301,9 @@ _WEATHER_TOOL = {
def _collect_streamed_tool_calls(chunks: list[dict]) -> list[dict]:
"""Reassemble OpenAI streaming delta.tool_calls into full tool calls.
- OpenAI streams partial tool calls across chunks — the first chunk for
- a given index carries ``id`` + ``function.name``, and subsequent
- chunks append fragments to ``function.arguments``.
+ OpenAI streams partial tool calls across chunks — the first chunk for a
+ given index carries ``id`` + ``function.name``, and later chunks append
+ fragments to ``function.arguments``.
"""
by_index: dict[int, dict] = {}
for c in chunks:
@@ -346,8 +346,8 @@ def _final_finish_reason(chunks: list[dict]) -> str | None:
def test_openai_tools_nonstream(base_url: str, api_key: str):
"""Standard OpenAI function calling, non-streaming, tool_choice='required'.
- Regression: before the fix, Studio silently stripped `tools` and the
- model returned plain text with finish_reason='stop'. After the fix,
+ Regression: before the fix, Studio stripped `tools` and the model
+ returned plain text with finish_reason='stop'. After the fix,
llama-server's response is forwarded verbatim so the client sees
finish_reason='tool_calls' with a structured tool_calls array and
non-zero usage.prompt_tokens.
@@ -428,9 +428,9 @@ def test_openai_tools_multiturn(base_url: str, api_key: str):
messages and assistant messages carrying tool_calls are accepted.
Regression: before the fix, ChatMessage.role was restricted to
- {system,user,assistant} and rejected role='tool' at the Pydantic
- validation stage. This test sends a full round trip so the model
- receives the simulated tool result and responds with final text.
+ {system,user,assistant} and rejected role='tool' at Pydantic
+ validation. This test sends a full round trip so the model receives the
+ simulated tool result and responds with final text.
"""
status, text = _http(
"POST",
@@ -467,7 +467,7 @@ def test_openai_tools_multiturn(base_url: str, api_key: str):
assert status == 200, f"Expected 200, got {status}: {text[:500]}"
data = json.loads(text)
msg = data["choices"][0]["message"]
- # The model should respond with text now that it has the tool result
+ # The model should respond with text now it has the tool result
content = msg.get("content") or ""
assert len(content) > 0 or msg.get(
"tool_calls"
@@ -701,9 +701,9 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
"""Anthropic Messages API: ``tool_choice: {"type": "any"}`` must be
honored (forwarded as OpenAI ``tool_choice: "required"`` to
llama-server). Regression for the secondary fix bundled with #4999 —
- previously this field was accepted on the request model but silently
- dropped with a warning log, so the model was free to answer from
- memory instead of using the tool.
+ previously this field was accepted on the request model but dropped with
+ a warning log, so the model could answer from memory instead of using
+ the tool.
"""
status, events = _stream_anthropic_http(
f"{base_url}/v1/messages",
@@ -711,7 +711,7 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
"model": "default",
"max_tokens": 256,
"messages": [
- # A question the model could easily answer from memory if
+ # A question the model could answer from memory if
# tool_choice were not enforced.
{
"role": "user",
@@ -740,7 +740,7 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
assert status == 200, f"Expected 200, got {status}"
assert len(events) > 0, "No SSE events received"
- # With tool_choice=any, stop_reason must be tool_use (not end_turn)
+ # With tool_choice=any, stop_reason must be tool_use, not end_turn
stop_reason = None
for etype, data in events:
if etype == "message_delta":
@@ -870,7 +870,7 @@ def main():
failed += 1
print(f" ERROR {fn.__name__}: {type(exc).__name__}: {exc}")
- # ── 1. Test --help (no server needed) ────────────────────────────
+ # ── 1. --help (no server needed) ────────────────────────────
print("\n[1/16] Testing --help output")
run_test(test_help_output)
diff --git a/studio/backend/tests/test_studio_train_validation.py b/studio/backend/tests/test_studio_train_validation.py
index 6df491610b8..ed33c07689f 100644
--- a/studio/backend/tests/test_studio_train_validation.py
+++ b/studio/backend/tests/test_studio_train_validation.py
@@ -24,7 +24,7 @@ from models.training import (
def _check_field(field_name: str, value):
- """Run the field validator without constructing a full TrainingStartRequest."""
+ """Run the field validator without building a full TrainingStartRequest."""
from models.training import TrainingStartRequest
schema_field = TrainingStartRequest.model_fields[field_name]
@@ -87,7 +87,7 @@ class TestVisionImageSizeCap:
@pytest.mark.parametrize("value", [True, False])
def test_bool_error_says_integer_not_range(self, value):
- # Regression guard: bools must say "integer or null", not "in [256, 2048]".
+ # Regression guard: bools say "integer or null", not "in [256, 2048]".
with pytest.raises(ValidationError) as exc:
_check_field("vision_image_size", value)
assert "integer or null" in str(exc.value)
@@ -95,7 +95,7 @@ class TestVisionImageSizeCap:
@pytest.mark.parametrize("value", ["++512", "--256", "+-+512", "+", "-"])
def test_multi_sign_string_says_integer_not_raw(self, value):
# Regression guard: multi-sign strings must not leak int()'s raw
- # "invalid literal" message; precise contract is "integer or null".
+ # "invalid literal" message; contract is "integer or null".
with pytest.raises(ValidationError) as exc:
_check_field("vision_image_size", value)
assert "integer or null" in str(exc.value)
diff --git a/studio/backend/tests/test_tool_policy_gates.py b/studio/backend/tests/test_tool_policy_gates.py
index 01f6bbbc3f2..fad121a4a10 100644
--- a/studio/backend/tests/test_tool_policy_gates.py
+++ b/studio/backend/tests/test_tool_policy_gates.py
@@ -2,8 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""
-Tests for `_effective_enable_tools` -- the helper that folds the
-process-level `tool_policy` over a request's `enable_tools` field.
+Tests for `_effective_enable_tools` -- folds the process-level `tool_policy`
+over a request's `enable_tools` field.
Truth table (policy x payload.enable_tools -> effective):
policy=None + payload=None -> None
diff --git a/studio/backend/tests/test_tool_xml_strip.py b/studio/backend/tests/test_tool_xml_strip.py
index 857302d5438..6cc01f25953 100644
--- a/studio/backend/tests/test_tool_xml_strip.py
+++ b/studio/backend/tests/test_tool_xml_strip.py
@@ -1,9 +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
-"""Tests for `_TOOL_XML_RE` (routes/inference.py) -- strips tool-call
-XML that leaks past the speculative buffer in core/inference/llama_cpp.py
-when the open/close pair is split across the visible/DRAIN boundary.
+"""Tests for `_TOOL_XML_RE` (routes/inference.py) -- strips tool-call XML that
+leaks past the speculative buffer in core/inference/llama_cpp.py when the
+open/close pair is split across the visible/DRAIN boundary.
"""
from __future__ import annotations
@@ -134,7 +134,7 @@ def test_strips_tail_only_parameter_orphan_no_trailing_ws():
def test_preserves_mid_string_parameter_in_code_sample():
- # Tail-anchor on `</parameter>` is required so doc/example prose survives.
+ # Tail-anchor on `</parameter>` so doc/example prose survives.
text = (
"Here is the Qwen tool-call format:\n"
"```xml\n"
@@ -207,8 +207,8 @@ def test_real_world_sweep_leaks_get_stripped(leak):
# ── Real-world tail-only </parameter> from gdpval sweep ──────────
-# All end-anchored: outer </function></tool_call> truncated by EOS,
-# inner <parameter=...> open DRAINED, leaving bare </parameter> tail.
+# All end-anchored: outer </function></tool_call> truncated by EOS, inner
+# <parameter=...> open DRAINED, leaving bare </parameter> tail.
GDPVAL_PARAMETER_LEAKS = [
# Qwen3.5-27B Q8_0 / worldbank s00
"the page contains image data and the text is not readable.\n</parameter>\n\n",
diff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.py
index edc47c705e6..5b7b70eefe2 100644
--- a/studio/backend/tests/test_training_worker_flash_attn.py
+++ b/studio/backend/tests/test_training_worker_flash_attn.py
@@ -221,7 +221,7 @@ def test_mamba_ssm_path_preserves_wheel_first_install_args(monkeypatch):
def _force_missing_fla_imports(monkeypatch):
- """Make fla.modules / fla.ops.gated_delta_rule imports raise ImportError."""
+ """Force fla.modules / fla.ops imports to raise ImportError."""
real_import = builtins.__import__
def fake_import(name, *a, **kw):
@@ -267,8 +267,8 @@ def test_flash_linear_attention_skips_for_unrelated_models(monkeypatch):
def test_flash_linear_attention_skips_for_ssm_only_models(monkeypatch):
- # Nemotron-H / Falcon-H1 / Granite-H / LFM2 take the mamba_ssm path
- # and never call FLA's gated_delta_rule kernels.
+ # Nemotron-H / Falcon-H1 / Granite-H / LFM2 take the mamba_ssm path,
+ # never FLA's gated_delta_rule kernels.
run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
monkeypatch.setattr(worker._sp, "run", run_mock)
@@ -289,7 +289,7 @@ def test_flash_linear_attention_matches_full_qwen3_family(monkeypatch):
monkeypatch.setattr(worker._sp, "run", run_mock)
_force_missing_fla_imports(monkeypatch)
monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
- # Hermetic discovery: pretend installed transformers ships all the Qwen GDN families.
+ # Hermetic discovery: pretend transformers ships all Qwen GDN families.
monkeypatch.setattr(
worker,
"_discover_fla_model_types",
@@ -370,9 +370,9 @@ def test_flash_linear_attention_install_includes_einops(monkeypatch):
args = run_mock.call_args[0][0]
assert "--no-deps" in args
- # einops is declared by fla-core; packaging and triton are pulled in
- # because fla/utils.py imports them at module load but neither is
- # declared in fla-core's METADATA (an upstream FLA gap).
+ # einops is declared by fla-core; packaging and triton are added
+ # because fla/utils.py imports them at load but neither is in
+ # fla-core's METADATA (an upstream FLA gap).
assert "einops" in args
assert "packaging" in args
assert "triton" in args
@@ -389,8 +389,8 @@ def test_flash_linear_attention_logs_post_install_import_failure(monkeypatch):
def fake_importable():
import_calls["count"] += 1
- # First call (pre-install probe) -> False so we attempt install.
- # Second call (post-install verify) -> still False.
+ # Pre-install probe -> False (attempt install); post-install
+ # verify -> still False.
return False
monkeypatch.setattr(worker, "_flash_linear_attention_importable", fake_importable)
@@ -433,13 +433,13 @@ def test_tilelang_backend_pins_only_binary(monkeypatch):
run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
monkeypatch.setattr(worker._sp, "run", run_mock)
monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
- # Need to bypass the post-install probe too.
+ # Bypass the post-install probe too.
probe_calls = {"count": 0}
def fake_probe():
probe_calls["count"] += 1
- # First probe (pre-install): False so install runs.
- # Second probe (post-install): True so success branch taken.
+ # Pre-install probe: False (install runs); post-install: True
+ # (success branch taken).
return probe_calls["count"] > 1
monkeypatch.setattr(worker, "_tilelang_importable", fake_probe)
@@ -492,13 +492,13 @@ def test_tilelang_backend_reinstalls_when_tvm_ffi_is_broken(monkeypatch):
"""Repair path issues TWO pip calls:
Call 1 (repair): `--force-reinstall --no-deps apache-tvm-ffi==0.1.9`
- — surgically downgrades the broken package only. `--no-deps` here
- is REQUIRED to prevent --force-reinstall from cascading through
- apache-tvm-ffi's dep graph and replacing torch / the CUDA stack.
+ — downgrades only the broken package. `--no-deps` is REQUIRED so
+ --force-reinstall doesn't cascade through apache-tvm-ffi's dep
+ graph and replace torch / the CUDA stack.
Call 2 (install): plain `apache-tvm-ffi==0.1.9 tilelang==0.1.8`
— resolves missing transitive deps (z3-solver, ml-dtypes) without
- --force-reinstall, so it never replaces already-correct packages.
+ --force-reinstall, so it never replaces correct packages.
"""
monkeypatch.delenv(worker._TILELANG_SKIP_ENV, raising = False)
monkeypatch.setattr(worker.shutil, "which", lambda name: "/usr/bin/uv")
@@ -515,14 +515,14 @@ def test_tilelang_backend_reinstalls_when_tvm_ffi_is_broken(monkeypatch):
assert run_mock.call_count == 2
repair_args, install_args = (call[0][0] for call in run_mock.call_args_list)
- # Repair: --force-reinstall --no-deps, apache-tvm-ffi ONLY (no tilelang).
+ # Repair: --force-reinstall --no-deps, apache-tvm-ffi ONLY.
assert "--force-reinstall" in repair_args
assert "--no-deps" in repair_args, "Repair MUST use --no-deps to avoid replacing torch / CUDA"
assert "--only-binary=:all:" in repair_args
assert f"apache-tvm-ffi=={worker._APACHE_TVM_FFI_PACKAGE_VERSION}" in repair_args
assert all("tilelang" not in a for a in repair_args), "Repair MUST only touch apache-tvm-ffi"
- # Install: regular dep-resolving install, NO --force-reinstall.
+ # Install: regular dep-resolving install, no --force-reinstall.
assert "--force-reinstall" not in install_args
assert "--no-deps" not in install_args
assert "--only-binary=:all:" in install_args
@@ -573,7 +573,7 @@ def test_tilelang_backend_swallows_install_timeout(monkeypatch):
statuses: list[str] = []
monkeypatch.setattr(worker, "_send_status", lambda queue, msg: statuses.append(msg))
- # Should not raise.
+ # Must not raise.
worker._ensure_tilelang_backend(
event_queue = [],
model_name = "unsloth/Qwen3.5-2B",
@@ -588,7 +588,7 @@ def test_tilelang_backend_skipped_for_ssm_models(monkeypatch):
monkeypatch.setattr(worker._sp, "run", run_mock)
# Nemotron-H / Falcon-H1 / Granite-H take the mamba_ssm path, not FLA's
- # gated_delta_rule -> tilelang has no effect on them.
+ # gated_delta_rule -> tilelang doesn't affect them.
for name in (
"tiiuae/Falcon-H1-0.5B-Instruct",
"nvidia/Nemotron-H-8B-Base",
@@ -635,25 +635,24 @@ def test_tilelang_backend_swallows_install_failure(monkeypatch):
# ───────────────────────────────────────────────────────────────────
# Runtime hook on `is_flash_linear_attention_available` /
-# `is_causal_conv1d_available`. These are the primary gate in
-# normal operation; the substring tests above cover the
+# `is_causal_conv1d_available` — the primary gate in normal operation.
+# The substring tests above cover the
# UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 fallback.
# ───────────────────────────────────────────────────────────────────
class _FakeQueue(list):
- """List with `.put` so worker._send_status can send into it during tests."""
+ """List with `.put` so worker._send_status can send into it in tests."""
def put(self, item):
self.append(item)
def _make_fake_gate(initial_return: bool):
- """Build a callable that mimics transformers' lru_cache-decorated gates.
+ """Callable mimicking transformers' lru_cache-decorated gates.
- Tracks call count and exposes a `cache_clear` attribute. The return
- value can be flipped to mimic install-then-True behaviour by setting
- `.next_return`.
+ Tracks call count and exposes `cache_clear`. Flip `.next_return` to
+ mimic install-then-True behaviour.
"""
class Gate:
@@ -707,7 +706,7 @@ def test_hook_installs_when_gate_returns_false(monkeypatch):
from transformers.utils import import_utils as _iu
- # Both gates are now wrapped. Call them — the hook should drive the install.
+ # Both gates wrapped; calling them should drive the install.
assert _iu.is_flash_linear_attention_available() is True
fla_install.assert_called_once()
tile_install.assert_called_once()
@@ -716,9 +715,9 @@ def test_hook_installs_when_gate_returns_false(monkeypatch):
def test_hook_skips_install_when_gate_already_true(monkeypatch):
- """When both gates are already True AND tilelang is healthy, the hook
- must do zero install work. (Tilelang repair on the already-True path
- is covered by test_hook_runs_tilelang_repair_when_fla_already_true.)
+ """Both gates already True AND tilelang healthy -> zero install work.
+ (Tilelang repair on the already-True path is covered by
+ test_hook_runs_tilelang_repair_when_fla_already_true.)
"""
fla_gate = _make_fake_gate(initial_return = True)
conv_gate = _make_fake_gate(initial_return = True)
@@ -730,9 +729,8 @@ def test_hook_skips_install_when_gate_already_true(monkeypatch):
monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", fla_install)
monkeypatch.setattr(worker, "_ensure_tilelang_backend_unconditional", tile_install)
monkeypatch.setattr(worker, "_install_package_wheel_first", conv_install)
- # Tilelang healthy so the post_available path is a no-op (otherwise
- # it would call tile_install, which is correct behaviour but
- # outside the scope of this test).
+ # Tilelang healthy -> post_available path is a no-op (otherwise it
+ # would call tile_install, correct but out of scope here).
monkeypatch.setattr(worker, "_tilelang_importable", lambda: True)
monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.9")
monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
@@ -776,7 +774,7 @@ def test_hook_idempotent_on_repeat_call(monkeypatch):
# First call: hook fires.
_iu.is_flash_linear_attention_available()
- # Subsequent calls: must not re-trigger the installer.
+ # Later calls: must not re-trigger the installer.
_iu.is_flash_linear_attention_available()
_iu.is_flash_linear_attention_available()
assert fla_install.call_count == 1
@@ -800,7 +798,7 @@ def test_hook_handles_install_failure_gracefully(monkeypatch):
from transformers.utils import import_utils as _iu
- # Must not raise; returns False so transformers falls back to torch loop.
+ # Must not raise; returns False so transformers uses the torch loop.
assert _iu.is_flash_linear_attention_available() is False
@@ -817,7 +815,7 @@ def test_hook_can_be_disabled_via_env(monkeypatch):
from transformers.utils import import_utils as _iu
- # Hook should NOT have been installed; gates remain the fakes.
+ # Hook not installed; gates remain the fakes.
assert _iu.is_flash_linear_attention_available is fla_gate
assert _iu.is_causal_conv1d_available is conv_gate
fla_install.assert_not_called()
@@ -837,21 +835,21 @@ def test_hook_clears_lru_cache_before_first_check(monkeypatch):
from transformers.utils import import_utils as _iu
_iu.is_flash_linear_attention_available()
- # The wrapper called cache_clear at least once before delegating.
+ # Wrapper called cache_clear at least once before delegating.
assert fla_gate.cache_clear_count >= 1
def test_hook_rewrites_previously_imported_module_bindings(monkeypatch):
"""Modeling files bind `is_flash_linear_attention_available` locally
via `from ... import is_X`. Reassigning the attribute on
- transformers.utils.import_utils alone does NOT reach those local
- bindings. The hook installer sweeps sys.modules and rebinds them.
+ transformers.utils.import_utils alone misses those local bindings;
+ the hook installer sweeps sys.modules and rebinds them.
"""
fla_gate = _make_fake_gate(initial_return = False)
conv_gate = _make_fake_gate(initial_return = True)
_patch_iu_gates(monkeypatch, fla_gate, conv_gate)
- # Create a fake modeling module that did `from ... import is_flash_linear_attention_available`.
+ # Fake modeling module that did `from ... import is_flash_linear_attention_available`.
fake_mod = sys.modules.setdefault(
"_test_fake_modeling_qwen35", type(sys)("_test_fake_modeling_qwen35")
)
@@ -868,9 +866,9 @@ def test_hook_rewrites_previously_imported_module_bindings(monkeypatch):
worker._install_fast_path_hooks(event_queue = _FakeQueue(), model_name = "unsloth/Qwen3.5-2B")
- # The fake module's local binding has been rewritten to the wrapper.
+ # The fake module's local binding is rewritten to the wrapper.
assert fake_mod.is_flash_linear_attention_available is not fla_gate
- # Calling through the fake module's reference triggers the install.
+ # Calling through the fake module's reference triggers install.
assert fake_mod.is_flash_linear_attention_available() is True
del sys.modules["_test_fake_modeling_qwen35"]
@@ -894,7 +892,7 @@ def test_hook_skips_when_import_utils_unavailable(monkeypatch):
def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):
- """Hook disabled -> legacy gate falls back to auto-discovered model types."""
+ """Hook disabled -> legacy gate falls back to auto-discovered types."""
install_mock = mock.Mock()
monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", install_mock)
monkeypatch.setattr(worker, "_discover_fla_model_types", lambda: frozenset({"qwen3_5"}))
@@ -921,8 +919,8 @@ def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):
def test_hook_does_not_install_tilelang_for_model_outside_allowlist(monkeypatch):
- """A model whose name is not in the auto-discovered FLA allowlist calls
- is_flash_linear_attention_available but should NOT get tilelang."""
+ """A model not in the auto-discovered FLA allowlist calls
+ is_flash_linear_attention_available but must NOT get tilelang."""
fla_gate = _make_fake_gate(initial_return = False)
conv_gate = _make_fake_gate(initial_return = True)
_patch_iu_gates(monkeypatch, fla_gate, conv_gate)
@@ -939,7 +937,7 @@ def test_hook_does_not_install_tilelang_for_model_outside_allowlist(monkeypatch)
monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
# Hermetize the auto-discovered set so the test stays valid as new
# transformers releases add FLA-using model_types (eg olmo_hybrid in
- # 5.4.0). The semantic under test is "outside-allowlist -> no tilelang".
+ # 5.4.0). Test semantic: "outside-allowlist -> no tilelang".
monkeypatch.setattr(
worker,
"_discover_fla_model_types",
@@ -986,7 +984,7 @@ def test_hook_does_install_tilelang_for_qwen35(monkeypatch):
def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
"""Finding #2: the broken-tvm-ffi repair must use --no-deps on the
- forced step so --force-reinstall does not cascade through
+ forced step so --force-reinstall doesn't cascade through
apache-tvm-ffi's dep graph and pull a different torch wheel.
"""
monkeypatch.delenv(worker._TILELANG_SKIP_ENV, raising = False)
@@ -1000,9 +998,9 @@ def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
assert run_mock.call_count == 2
repair_args = run_mock.call_args_list[0][0][0]
- # The forced step MUST be --no-deps so torch / CUDA stack is untouched.
+ # Forced step MUST be --no-deps so torch / CUDA stack is untouched.
assert "--force-reinstall" in repair_args and "--no-deps" in repair_args
- # And it touches ONLY apache-tvm-ffi, not tilelang / torch.
+ # Touches ONLY apache-tvm-ffi, not tilelang / torch.
assert all("tilelang" not in a for a in repair_args)
assert all("torch" not in a for a in repair_args)
@@ -1010,25 +1008,24 @@ def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
def test_hook_trusts_installer_bool_not_metadata(monkeypatch):
"""Finding #3: if pip exits 0 but deep imports fail, the installer
returns False; the hook must propagate False even if the underlying
- `original()` gate (which only checks metadata) returns True after
- pip succeeds.
+ `original()` gate (metadata-only) returns True after pip succeeds.
- Setup mirrors the real bug:
- 1. Pre-install: gate=False (FLA not present) → wrapper triggers install.
+ Mirrors the real bug:
+ 1. Pre-install: gate=False (FLA absent) → wrapper triggers install.
2. Installer's `_flash_linear_attention_importable` post-probe fails,
- so the installer returns False. (pip exited 0 but `import fla.modules`
- raised because of a missing transitive dep.)
- 3. Post-install: gate would return True (metadata check sees fla-core
- version) — but the wrapper must IGNORE that and use the installer's
- False so transformers takes the torch fallback.
+ so it returns False. (pip exited 0 but `import fla.modules` raised
+ due to a missing transitive dep.)
+ 3. Post-install: gate would return True (metadata sees fla-core) — but
+ the wrapper must IGNORE that and use the installer's False so
+ transformers takes the torch fallback.
"""
# Gate flips True after install (simulating "metadata sees fla").
fla_gate = _make_fake_gate(initial_return = False)
conv_gate = _make_fake_gate(initial_return = True)
_patch_iu_gates(monkeypatch, fla_gate, conv_gate)
- # Installer "succeeds" at pip, AND flips the gate to True (metadata
- # sees fla post-install), BUT returns False (deep import broken).
+ # Installer "succeeds" at pip and flips the gate to True (metadata
+ # sees fla post-install), but returns False (deep import broken).
def _bad_install(eq):
fla_gate.next_return = True # metadata says yes after pip
return False # but deep import is broken
@@ -1051,9 +1048,9 @@ def test_hook_trusts_installer_bool_not_metadata(monkeypatch):
def test_rebind_does_not_trigger_module_getattr(monkeypatch):
- """Finding #5: the rebind sweep must use __dict__, not getattr(),
- to avoid invoking transformers' lazy module __getattr__ which spits
- out hundreds of "Accessing X from .models..." warnings.
+ """Finding #5: the rebind sweep must use __dict__, not getattr(), to
+ avoid invoking transformers' lazy module __getattr__ which spits out
+ hundreds of "Accessing X from .models..." warnings.
"""
original = object()
replacement = object()
@@ -1068,8 +1065,8 @@ def test_rebind_does_not_trigger_module_getattr(monkeypatch):
lazy = _GetattrTripwire("_lazy_test_module")
sys.modules["_lazy_test_module"] = lazy
try:
- # No module-level binding to `is_flash_linear_attention_available`
- # in __dict__, so the sweep must NOT trip the tripwire.
+ # No `is_flash_linear_attention_available` in __dict__, so the
+ # sweep must NOT trip the tripwire.
worker._rebind_in_already_imported_modules(
attr_name = "is_flash_linear_attention_available",
old_obj = original,
@@ -1085,7 +1082,7 @@ def test_rebind_does_not_trigger_module_getattr(monkeypatch):
def test_hook_skips_tilelang_when_fla_install_is_skipped(monkeypatch):
"""Finding #6: env-skipped FLA returns False from
_ensure_flash_linear_attention_unconditional; tilelang must NOT
- install in that case.
+ install then.
"""
fla_gate = _make_fake_gate(initial_return = False)
conv_gate = _make_fake_gate(initial_return = True)
@@ -1107,9 +1104,9 @@ def test_hook_skips_tilelang_when_fla_install_is_skipped(monkeypatch):
def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
- """Finding #7: when FLA is already importable (gate returns True at
- first probe) but tilelang is missing or apache-tvm-ffi is on the
- broken list, the post-available action must still run tilelang.
+ """Finding #7: when FLA is already importable (gate True at first
+ probe) but tilelang is missing or apache-tvm-ffi is on the broken
+ list, the post-available action must still run tilelang.
"""
fla_gate = _make_fake_gate(initial_return = True)
conv_gate = _make_fake_gate(initial_return = True)
@@ -1120,7 +1117,7 @@ def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", fla_install)
monkeypatch.setattr(worker, "_ensure_tilelang_backend_unconditional", tile_install)
monkeypatch.setattr(worker, "_install_package_wheel_first", mock.Mock(return_value = True))
- # tilelang missing AND tvm-ffi is on broken list — both trigger repair.
+ # tilelang missing AND tvm-ffi on broken list — both trigger repair.
monkeypatch.setattr(worker, "_tilelang_importable", lambda: False)
monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.11")
monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
@@ -1130,19 +1127,19 @@ def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
from transformers.utils import import_utils as _iu
_iu.is_flash_linear_attention_available()
- # FLA install was NOT needed; tilelang repair WAS still triggered.
+ # FLA install NOT needed; tilelang repair still triggered.
fla_install.assert_not_called()
tile_install.assert_called_once()
def test_fla_installer_force_reinstalls_when_older_version_present(monkeypatch):
- """Finding #8: when an older `flash-linear-attention` is importable
- but below the pin, the installer must force a reinstall (not no-op).
+ """Finding #8: an older `flash-linear-attention` that is importable
+ but below the pin must force a reinstall (not no-op).
"""
monkeypatch.delenv(worker._FLA_SKIP_ENV, raising = False)
monkeypatch.setattr(worker.shutil, "which", lambda name: "/usr/bin/uv")
monkeypatch.setattr(worker, "_installed_torch_version_tuple", lambda: (2, 9))
- # Importable but stale (current() reports False even though importable() is True).
+ # Importable but stale (current()=False though importable()=True).
monkeypatch.setattr(worker, "_flash_linear_attention_importable", lambda: True)
monkeypatch.setattr(worker, "_flash_linear_attention_current", lambda **kw: False)
run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
@@ -1162,22 +1159,22 @@ def test_fla_installer_force_reinstalls_when_older_version_present(monkeypatch):
def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():
"""Finding #4: SSM modeling files use `lazy_load_kernel("causal-conv1d")`
- and never call `is_causal_conv1d_available()`, so the hook would not
- fire for them. The orchestrator must always run the eager
- substring installer regardless of hook mode.
+ and never call `is_causal_conv1d_available()`, so the hook won't fire
+ for them. The orchestrator must always run the eager substring
+ installer regardless of hook mode.
- This test reads the worker source rather than running the full
- orchestrator (which requires a configured training config). It
- asserts the eager install is OUTSIDE the if/else hook branch.
+ Reads the worker source rather than running the full orchestrator
+ (which needs a configured training config), asserting the eager
+ install is OUTSIDE the if/else hook branch.
"""
import inspect
src = inspect.getsource(worker.run_training_process)
- # Find the orchestration block.
+ # Orchestration block.
assert "_ensure_causal_conv1d_fast_path(event_queue, model_name)" in src
assert "_install_fast_path_hooks(event_queue, model_name)" in src
- # The eager causal_conv1d call must appear BEFORE the hook-mode if/else,
- # not nested inside the `if _FAST_PATH_HOOKS_SKIP_ENV` branch.
+ # Eager causal_conv1d call must come BEFORE the hook-mode if/else, not
+ # nested inside the `if _FAST_PATH_HOOKS_SKIP_ENV` branch.
eager_pos = src.find("_ensure_causal_conv1d_fast_path(event_queue, model_name)")
skip_check_pos = src.find('os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1"')
assert eager_pos < skip_check_pos, (
@@ -1189,17 +1186,17 @@ def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():
# ───────────────────────────────────────────────────────────────────
# HIP / ROCm regression coverage (h34v3nzc0dex Strix Halo report).
-# tilelang 0.1.8 has no HIP GEMM backend; FLA's TileLang dispatch
-# crashes mid-backward on AMD with "Unsupported target for gemm: hip".
-# The fix: skip the install on HIP-built torch AND setdefault
-# FLA_TILELANG=0 so already-installed tilelang doesn't get used either.
+# tilelang 0.1.8 has no HIP GEMM backend; FLA's TileLang dispatch crashes
+# mid-backward on AMD with "Unsupported target for gemm: hip". Fix: skip
+# install on HIP-built torch AND setdefault FLA_TILELANG=0 so an
+# already-installed tilelang isn't used either.
# ───────────────────────────────────────────────────────────────────
def test_tilelang_platform_unsupported_on_hip_torch(monkeypatch):
- """Strix Halo / MI300 with ROCm torch: linux + x86_64 looks
- identical to a CUDA box at the OS level, so the platform check
- must consult torch.version.hip explicitly.
+ """Strix Halo / MI300 with ROCm torch: linux + x86_64 looks identical
+ to a CUDA box at the OS level, so the platform check must consult
+ torch.version.hip explicitly.
"""
monkeypatch.setattr(worker, "_torch_has_hip", lambda: True)
assert worker._tilelang_platform_supported() is False
@@ -1220,9 +1217,9 @@ def test_tilelang_install_skipped_on_hip_torch(monkeypatch):
def test_install_fast_path_hooks_sets_fla_tilelang_zero_on_hip(monkeypatch):
- """When HIP torch is detected, hook installer must set
- FLA_TILELANG=0 (via setdefault — respects user override) so any
- PRE-EXISTING tilelang install isn't used by FLA's dispatcher.
+ """On HIP torch, the hook installer must setdefault FLA_TILELANG=0
+ (respecting user override) so a PRE-EXISTING tilelang install isn't
+ used by FLA's dispatcher.
"""
import os as _os
@@ -1239,8 +1236,8 @@ def test_install_fast_path_hooks_sets_fla_tilelang_zero_on_hip(monkeypatch):
def test_install_fast_path_hooks_respects_user_fla_tilelang_override(monkeypatch):
- """If the user explicitly set FLA_TILELANG (even on HIP), don't
- overwrite — they may know they have a HIP-aware tilelang fork.
+ """If the user set FLA_TILELANG (even on HIP), don't overwrite — they
+ may have a HIP-aware tilelang fork.
"""
import os as _os
@@ -1278,7 +1275,7 @@ def test_install_fast_path_hooks_does_not_set_fla_tilelang_on_cuda(monkeypatch):
def _make_fake_transformers_tree(tmp_path, fla_types: list[str], non_fla_types: list[str]):
- """Lay out a tmp dir as `transformers/models/{type}/modeling_{type}.py`."""
+ """Lay out tmp dir as `transformers/models/{type}/modeling_{type}.py`."""
pkg = tmp_path / "transformers"
models = pkg / "models"
models.mkdir(parents = True)
@@ -1341,7 +1338,7 @@ def test_discover_fla_model_types_caches_across_calls(tmp_path, monkeypatch):
second = worker._discover_fla_model_types()
assert first == second
- assert read_calls[0] == after_first # cache hit: no extra disk reads
+ assert read_calls[0] == after_first # cache hit: no extra reads
def test_discover_fla_model_types_handles_missing_transformers(monkeypatch):
@@ -1382,7 +1379,7 @@ def test_discover_fla_model_types_handles_unreadable_file(tmp_path, monkeypatch)
monkeypatch.setattr(_Path, "read_text", boom_read)
result = worker._discover_fla_model_types()
- assert result == frozenset() # unreadable file simply doesn't contribute
+ assert result == frozenset() # unreadable file doesn't contribute
def test_model_wants_tilelang_handles_real_repo_names(monkeypatch):
@@ -1425,20 +1422,19 @@ def test_model_wants_tilelang_normalizes_separators(monkeypatch):
# ────────────────────────────────────────────────────────────────────
# HIP source-build gcc-install-dir coverage (h34v3nzc0dex Strix Halo).
-# Ubuntu 24.04 ships gcc-14's runtime dir without /usr/include/c++/14,
-# so ROCm clang-20 picks it and fails with 'cstdlib' file not found
-# when building causal-conv1d (or any other HIP source fallback).
-# _hipcc_gcc_install_dir() finds a gcc dir that has both halves; the
+# Ubuntu 24.04 ships gcc-14's runtime dir without /usr/include/c++/14, so
+# ROCm clang-20 picks it and fails with 'cstdlib' file not found when
+# building causal-conv1d (or any HIP source fallback).
+# _hipcc_gcc_install_dir() finds a gcc dir with both halves; the
# _install_package_wheel_first HIP branch passes it to clang via
-# HIPCC_COMPILE_FLAGS_APPEND. Parallel to bbf004c's setup.sh fix for
-# the llama.cpp HIP build (PR #5301).
+# HIPCC_COMPILE_FLAGS_APPEND. Parallel to bbf004c's setup.sh fix for the
+# llama.cpp HIP build (PR #5301).
# ────────────────────────────────────────────────────────────────────
def _isdir_for_layout(*existing: str):
- """Return an os.path.isdir replacement that only treats the given
- absolute paths as directories. Lets a test simulate exactly which
- gcc runtime dirs and C++ header dirs exist on the host."""
+ """os.path.isdir replacement treating only the given absolute paths as
+ directories, to simulate which gcc runtime / C++ header dirs exist."""
valid = set(existing)
def fake_isdir(path: str) -> bool:
@@ -1449,7 +1445,7 @@ def _isdir_for_layout(*existing: str):
def test_hipcc_gcc_install_dir_picks_highest_with_headers(monkeypatch):
"""gcc-14 has runtime but no /usr/include/c++/14; loop falls through
- to gcc-13 which has both. This is the exact Ubuntu 24.04 layout."""
+ to gcc-13 which has both. The exact Ubuntu 24.04 layout."""
monkeypatch.setattr(sys, "platform", "linux")
import platform as _platform
@@ -1485,8 +1481,8 @@ def test_hipcc_gcc_install_dir_picks_14_when_headers_exist(monkeypatch):
def test_hipcc_gcc_install_dir_returns_none_when_no_match(monkeypatch):
- """No gcc dir has both halves → return None and skip the env injection
- rather than guessing wrong and surfacing a confusing build failure."""
+ """No gcc dir has both halves → return None and skip env injection
+ rather than guessing wrong and causing a confusing build failure."""
monkeypatch.setattr(sys, "platform", "linux")
import platform as _platform
@@ -1516,10 +1512,9 @@ def test_hipcc_gcc_install_dir_returns_none_on_non_x86_64(monkeypatch):
def _make_hip_install_env(monkeypatch, *, gcc_dir: str | None):
- """Common scaffolding for tests that exercise the HIP source-build
- branch of _install_package_wheel_first end-to-end. The package isn't
- installed yet, no prebuilt wheel exists, hipcc is on PATH, and the
- fake env reports an HIP torch."""
+ """Scaffolding for end-to-end tests of the HIP source-build branch of
+ _install_package_wheel_first: package not installed, no prebuilt
+ wheel, hipcc on PATH, fake env reports HIP torch."""
monkeypatch.setattr(builtins, "__import__", _missing_module_import("causal_conv1d"))
monkeypatch.setattr(
worker,
@@ -1574,8 +1569,8 @@ def test_install_injects_gcc_install_dir_on_hip_source_build(monkeypatch):
def test_install_appends_to_existing_hipcc_compile_flags(monkeypatch):
- """User has HIPCC_COMPILE_FLAGS_APPEND='-O3 -DFOO' set → final value
- keeps the user's flags AND adds --gcc-install-dir at the end."""
+ """User has HIPCC_COMPILE_FLAGS_APPEND='-O3 -DFOO' → final value keeps
+ the user's flags AND appends --gcc-install-dir."""
monkeypatch.setenv("HIPCC_COMPILE_FLAGS_APPEND", "-O3 -DFOO")
_make_hip_install_env(monkeypatch, gcc_dir = "/usr/lib/gcc/x86_64-linux-gnu/13")
@@ -1636,9 +1631,9 @@ def test_install_respects_user_gcc_install_dir(monkeypatch):
release_base_url = "https://example.com",
)
- # subprocess.run was invoked without env override (the user already
- # set HIPCC_COMPILE_FLAGS_APPEND with --gcc-install-dir, so we left
- # the env alone — the existing value is inherited normally).
+ # subprocess.run invoked without env override (user already set
+ # HIPCC_COMPILE_FLAGS_APPEND with --gcc-install-dir, so we left the
+ # env alone — the existing value is inherited).
assert captured == {"_called": "yes_no_env"}
@@ -1660,7 +1655,7 @@ def test_install_does_not_inject_env_on_cuda(monkeypatch):
monkeypatch.setattr(worker, "direct_wheel_url", lambda **kw: None)
monkeypatch.setattr(worker.shutil, "which", lambda name: None)
monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
- # If _hipcc_gcc_install_dir were called on CUDA we'd want to know.
+ # _hipcc_gcc_install_dir must not be called on CUDA.
monkeypatch.setattr(
worker,
"_hipcc_gcc_install_dir",
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index ff5e1f13810..c8d6a4fd100 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -10,9 +10,8 @@ from unittest.mock import patch
# ---------------------------------------------------------------------------
-# We need to be able to import the module under test. The studio backend
-# uses relative-style imports (``from utils.…``), so we add the backend
-# directory to *sys.path* if it is not already there.
+# The studio backend uses relative-style imports (``from utils.…``), so
+# add the backend directory to *sys.path* if not already present.
# ---------------------------------------------------------------------------
import sys
@@ -20,8 +19,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
-# Stub the custom logger before importing the module under test so it
-# doesn't fail on the ``from loggers import get_logger`` line.
+# Stub the custom logger before import so ``from loggers import
+# get_logger`` doesn't fail.
import types as _types
_loggers_stub = _types.ModuleType("loggers")
@@ -90,7 +89,7 @@ class TestResolveBaseModel:
(tmp_path / "config.json").write_text(json.dumps(config_cfg))
result = _resolve_base_model(str(tmp_path))
- # Should fall through, not return the self-referencing path
+ # Falls through; does not return the self-referencing path.
assert result == str(tmp_path)
def test_no_config_files(self, tmp_path: Path):
@@ -174,7 +173,7 @@ class TestNeedsTransformers5:
def test_llama_does_not_need_v5(self):
"""Standard models should not trigger v5."""
- # Patch network call to avoid real fetch
+ # Patch network call to avoid a real fetch.
with patch(
"utils.transformers_version._check_tokenizer_config_needs_v5",
return_value = False,
@@ -182,13 +181,13 @@ class TestNeedsTransformers5:
assert needs_transformers_5("meta-llama/Llama-3-8B") is False
def test_local_checkpoint_resolved_via_config(self, tmp_path: Path):
- """A local checkpoint with config.json pointing to Qwen3.5 should need v5."""
+ """Local checkpoint with config.json pointing to Qwen3.5 needs v5."""
config_cfg = {"model_name": "Qwen/Qwen3.5-9B"}
(tmp_path / "config.json").write_text(json.dumps(config_cfg))
- # _resolve_base_model is called by ensure_transformers_version,
- # but needs_transformers_5 just does substring matching.
- # We test the full resolution chain here:
+ # ensure_transformers_version calls _resolve_base_model, but
+ # needs_transformers_5 just does substring matching. Test the
+ # full resolution chain here.
resolved = _resolve_base_model(str(tmp_path))
assert needs_transformers_5(resolved) is True
@@ -230,7 +229,7 @@ class TestCheckConfigNeeds550:
def test_no_config_json(self, tmp_path: Path):
"""Missing config.json should return False (fail-open)."""
- # Patch network call to avoid real fetch
+ # Patch network call to avoid a real fetch.
with patch("urllib.request.urlopen") as mock_urlopen:
mock_urlopen.side_effect = Exception("no network")
assert _check_config_needs_550(str(tmp_path)) is False
@@ -311,8 +310,8 @@ class TestGetTransformersTier:
assert get_transformers_tier("meta-llama/Llama-3-8B") == "default"
def test_550_checked_before_530(self):
- """Ensure 5.5.0 is checked first — a model matching both should get 550."""
- # This shouldn't happen in practice, but verifies priority
+ """5.5.0 is checked first — a model matching both gets 550."""
+ # Shouldn't happen in practice, but verifies priority.
assert get_transformers_tier("gemma-4-model") == "550"
def test_needs_transformers_5_compat(self):
diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.py
index bdb1cd2ce89..765235bd32d 100644
--- a/studio/backend/tests/test_utils.py
+++ b/studio/backend/tests/test_utils.py
@@ -4,13 +4,13 @@
"""
Tests for utils/hardware and utils/utils — device detection, GPU memory, error formatting.
-These tests are designed to pass on ANY platform:
+Designed to pass on ANY platform:
• NVIDIA GPU (CUDA backend, requires torch)
• Apple Silicon (MLX backend, requires mlx)
• CPU-only (no GPU at all)
-No ML framework is imported at the top level.
-Tests that need torch/mlx internals for mocking are skipped when unavailable.
+No ML framework is imported at the top level; tests needing torch/mlx
+internals for mocking are skipped when unavailable.
Run with:
cd studio/backend
@@ -189,10 +189,9 @@ class TestGetGpuMemoryInfo:
assert "backend" in get_gpu_memory_info()
def test_backend_matches_device(self):
- # The backend field uses _backend_label, which swaps "cuda" for
- # "rocm" when running on an AMD host (IS_ROCM=True) so the UI
- # can render the correct label. On CUDA / XPU / MLX / CPU hosts
- # it is equivalent to `get_device().value`.
+ # backend uses _backend_label, which swaps "cuda" for "rocm" on
+ # AMD hosts (IS_ROCM=True) for the UI label. On CUDA/XPU/MLX/CPU
+ # hosts it equals `get_device().value`.
from utils.hardware.hardware import _backend_label
result = get_gpu_memory_info()
assert result["backend"] == _backend_label(get_device())
diff --git a/studio/backend/tests/test_vision_cache.py b/studio/backend/tests/test_vision_cache.py
index 78f88fd7ea1..0df474b586f 100644
--- a/studio/backend/tests/test_vision_cache.py
+++ b/studio/backend/tests/test_vision_cache.py
@@ -3,14 +3,13 @@
"""Tests for is_vision_model() caching behaviour.
-The vision detection cache (``_vision_detection_cache``) mirrors the existing
-``_audio_detection_cache`` pattern used by ``detect_audio_type()``. These
-tests verify that:
+``_vision_detection_cache`` mirrors the ``_audio_detection_cache``
+pattern used by ``detect_audio_type()``. These tests verify:
-* Repeated calls for the same model hit the cache (no redundant work).
+* Repeated calls for the same model hit the cache.
* Different models each trigger their own detection.
* Both True and False results are cached.
-* The subprocess path (transformers 5.x models) is also cached.
+* The subprocess path (transformers 5.x models) is cached.
* Exceptions that fall back to False are cached.
"""
@@ -62,8 +61,7 @@ class TestVisionCacheHitMiss:
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_second_call_uses_cache(self, mock_uncached):
- """Calling is_vision_model() twice for the same model should invoke
- the uncached function only once."""
+ """Two calls for the same model invoke the uncached fn once."""
assert is_vision_model("org/my-vlm") is True
assert is_vision_model("org/my-vlm") is True
mock_uncached.assert_called_once_with("org/my-vlm", None)
@@ -101,15 +99,15 @@ class TestVisionCacheStoresFalse:
class TestVisionCacheSubprocessPath:
- """Models needing transformers 5.x go through _is_vision_model_subprocess.
- The cache should prevent the subprocess from being spawned more than once
- per model per process."""
+ """transformers 5.x models go through _is_vision_model_subprocess.
+ The cache should spawn the subprocess at most once per model per
+ process."""
@patch("utils.models.model_config._is_vision_model_subprocess", return_value = True)
@patch("utils.transformers_version.needs_transformers_5", return_value = True)
def test_subprocess_called_once_with_cache(self, mock_needs_t5, mock_subprocess):
- """Subprocess should only fire on the first call; second is cached."""
- # First call: goes through uncached → subprocess
+ """Subprocess fires only on the first call; second is cached."""
+ # First call: uncached → subprocess
assert is_vision_model("unsloth/Qwen3.5-2B") is True
# Second call: cache hit, no subprocess
assert is_vision_model("unsloth/Qwen3.5-2B") is True
@@ -136,10 +134,9 @@ class TestVisionCacheSubprocessPath:
class TestVisionCacheOnException:
- """When detection raises an exception, _is_vision_model_uncached
- distinguishes permanent failures (cached as False) from transient
- failures (returned as None, not cached so the next call can retry).
- Verify both contracts."""
+ """On exception, _is_vision_model_uncached distinguishes permanent
+ failures (cached as False) from transient ones (returned as None,
+ not cached, so the next call retries). Verify both contracts."""
@patch(
"utils.models.model_config.load_model_config",
@@ -148,13 +145,12 @@ class TestVisionCacheOnException:
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
def test_permanent_exception_result_cached(self, mock_needs_t5, mock_load_config):
"""A permanent failure (ValueError / RepositoryNotFoundError /
- GatedRepoError / JSONDecodeError) should be caught, return False,
- and that False should be cached so subsequent calls don't retry.
+ GatedRepoError / JSONDecodeError) is caught, returns False, and
+ that False is cached so subsequent calls don't retry.
- ValueError is used here because it's the simplest of the
- code-path's cacheable exception types and does not require an
- import of huggingface_hub errors (whose module path varies
- across versions)."""
+ ValueError is used as the simplest cacheable exception type that
+ avoids importing huggingface_hub errors (whose module path
+ varies across versions)."""
# First call: load_model_config raises -> except branch -> False.
assert is_vision_model("broken/model") is False
# Second call: cache hit, load_model_config not called again.
@@ -167,17 +163,15 @@ class TestVisionCacheOnException:
)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
def test_transient_exception_not_cached(self, mock_needs_t5, mock_load_config):
- """A transient failure (OSError, timeouts) should return None from
- _is_vision_model_uncached, surface as False to the caller, and
- NOT be cached, so the next call retries detection. This matches
- the documented behaviour on _vision_detection_cache:
- 'transient failures (network errors, timeouts) are NOT cached so
- they can be retried.'"""
- # First call: load_model_config raises OSError -> uncached None
- # -> caller returns False without caching.
+ """A transient failure (OSError, timeouts) returns None from
+ _is_vision_model_uncached, surfaces as False to the caller, and
+ is NOT cached, so the next call retries. Matches the documented
+ _vision_detection_cache behaviour: 'transient failures (network
+ errors, timeouts) are NOT cached so they can be retried.'"""
+ # First call: OSError -> uncached None -> caller returns False,
+ # no caching.
assert is_vision_model("broken/model") is False
- # Second call: cache miss again, load_model_config called a
- # second time.
+ # Second call: cache miss again, load_model_config called twice.
assert is_vision_model("broken/model") is False
assert mock_load_config.call_count == 2
@@ -188,7 +182,7 @@ class TestVisionCacheOnException:
class TestVisionCacheDirectPath:
- """For models that do NOT need transformers 5.x, the detection goes through
+ """Models that do NOT need transformers 5.x detect via
load_model_config directly. The cache must work the same way."""
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@@ -214,7 +208,7 @@ class TestVisionCacheDirectPath:
cfg.architectures = ["LlamaForCausalLM"]
mock_load_config.return_value = cfg
- # LlamaForCausalLM doesn't end with VLM suffixes, no vision_config, etc.
+ # No VLM suffix, no vision_config, etc.
assert is_vision_model("meta-llama/Llama-3-8B") is False
assert is_vision_model("meta-llama/Llama-3-8B") is False
mock_load_config.assert_called_once()
@@ -290,15 +284,14 @@ class TestVisionCacheDirectPath:
class TestVisionCacheTokenHandling:
- """The cache is keyed on (model_name, hf_token).
- Different tokens for the same model should trigger separate detections
- to handle gated models correctly."""
+ """The cache is keyed on (model_name, hf_token). Different tokens
+ for the same model trigger separate detections for gated models."""
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_different_tokens_trigger_new_detection(self, mock_uncached):
- """Calls with different tokens should trigger separate detections to
- handle gated models correctly (e.g. unauthenticated probe → False,
- then authenticated call should re-check)."""
+ """Different tokens trigger separate detections for gated models
+ (e.g. unauthenticated probe → False, then authenticated
+ re-check)."""
assert is_vision_model("gated/model", hf_token = "token-a") is True
assert is_vision_model("gated/model", hf_token = "token-b") is True
assert mock_uncached.call_count == 2
diff --git a/studio/backend/tests/test_vram_estimation.py b/studio/backend/tests/test_vram_estimation.py
index 65964908d72..2def8738e26 100644
--- a/studio/backend/tests/test_vram_estimation.py
+++ b/studio/backend/tests/test_vram_estimation.py
@@ -531,7 +531,7 @@ class TestQuantizationSkips(unittest.TestCase):
)
def test_vlm_prefix_skip_module_does_not_match_text_alias(self):
- # vision_tower-prefixed skips must not shadow text aliases sharing the
+ # vision_tower-prefixed skips must not shadow text aliases with the
# same suffix.
baseline = replace(QUANT_SKIP_STRUCTURED, quantization_skip_modules = [])
vlm_skip = replace(
@@ -995,9 +995,9 @@ class TestParallelDenseMoE(unittest.TestCase):
+ with_parallel.num_experts * with_parallel.hidden_size
)
dense_only = with_parallel.hidden_size * with_parallel.intermediate_size * 3
- # why: under gemma4 enable_moe_block, the layer's `self.experts` is a
- # sibling of `self.mlp`; the `text.layers.<i>.mlp` aggregate must
- # cover the dense path only, with experts in their own aggregate.
+ # why: under gemma4 enable_moe_block, `self.experts` is a sibling of
+ # `self.mlp`; the `text.layers.<i>.mlp` aggregate covers the dense path
+ # only, with experts in their own aggregate.
self.assertEqual(elements["text.layers.0.mlp"], dense_only)
self.assertEqual(elements["text.layers.0.experts"], moe_only)
@@ -1148,9 +1148,9 @@ class TestPerLayerInputAccounting(unittest.TestCase):
def test_per_layer_input_modules_count_quantizable_block(self):
with_ple = self._arch()
without_ple = replace(with_ple, hidden_size_per_layer_input = 0)
- # The PLE block adds: model_projection (hd*nl*pli), per_layer_input_gate
- # (hd*pli per layer) + per_layer_projection (pli*hd per layer) as
- # quantizable text linears.
+ # PLE block adds these quantizable text linears: model_projection
+ # (hd*nl*pli), per_layer_input_gate (hd*pli per layer),
+ # per_layer_projection (pli*hd per layer).
n_layers = with_ple.num_hidden_layers
hd = with_ple.hidden_size
pli = with_ple.hidden_size_per_layer_input
@@ -1161,10 +1161,10 @@ class TestPerLayerInputAccounting(unittest.TestCase):
self.assertGreaterEqual(delta, expected_quantizable_extra)
def test_all_linear_lora_excludes_per_layer_input_modules(self):
- # why: Unsloth's get_peft_regex requires module names to contain a
- # component tag (mlp/attn/...); PLE module names (per_layer_input_gate,
- # per_layer_projection, per_layer_model_projection) lack any tag, so
- # all-linear training does NOT attach LoRA to them.
+ # why: Unsloth's get_peft_regex requires a component tag (mlp/attn/...)
+ # in module names; PLE names (per_layer_input_gate, per_layer_projection,
+ # per_layer_model_projection) lack one, so all-linear does NOT attach
+ # LoRA to them.
arch = self._arch()
without_ple = replace(arch, hidden_size_per_layer_input = 0)
self.assertEqual(
@@ -1234,11 +1234,10 @@ class TestExpertsSkipGranularity(unittest.TestCase):
bytes_skip_experts = compute_model_weights_bytes(skip_experts, "qlora", True)
bytes_skip_mlp = compute_model_weights_bytes(skip_full_mlp, "qlora", True)
# why: under gemma4 enable_moe_block, `self.experts` is a sibling of
- # `self.mlp`; skipping `model.layers.0.mlp` should cover only the
- # dense MLP, while `model.layers.0.mlp.experts` covers the routed
- # experts. Routed experts have far more params than the dense MLP,
- # so skipping experts must add more bytes than skipping the dense
- # path.
+ # `self.mlp`; skipping `model.layers.0.mlp` covers only the dense MLP,
+ # while `model.layers.0.mlp.experts` covers the routed experts. Routed
+ # experts have far more params than the dense MLP, so skipping experts
+ # must add more bytes than skipping the dense path.
self.assertGreater(bytes_skip_experts, bytes_no_skip)
self.assertGreater(bytes_skip_mlp, bytes_no_skip)
self.assertGreater(bytes_skip_experts, bytes_skip_mlp)
@@ -1485,8 +1484,8 @@ class TestPerLayerInputSkipAlias(unittest.TestCase):
)
arch_with = extract_arch_config(self._hf(["model.layers.0"]))
- # The text.layers.0 aggregate must include the PLE per-layer modules,
- # so the same skip on a config without PLE produces a smaller value.
+ # text.layers.0 aggregate includes the PLE per-layer modules, so the
+ # same skip on a no-PLE config produces a smaller value.
arch_without = extract_arch_config(
SimpleNamespace(
text_config = SimpleNamespace(
@@ -1558,7 +1557,7 @@ class TestSharedExpertVariants(unittest.TestCase):
arch_separate = extract_arch_config(self._hf(shared_expert_intermediate_size = 64))
arch_implicit = extract_arch_config(self._hf(n_shared_experts = 1))
# Different shared sizes (64 vs default moe_intermediate_size=128) must
- # produce different MoE element counts.
+ # give different MoE element counts.
self.assertNotEqual(
_compute_moe_mlp_elements(arch_separate),
_compute_moe_mlp_elements(arch_implicit),
@@ -1567,7 +1566,7 @@ class TestSharedExpertVariants(unittest.TestCase):
def test_shared_expert_gate_counted_only_for_qwen_style(self):
from utils.hardware.vram_estimation import _compute_moe_mlp_elements
- # Qwen-style: shared_expert_intermediate_size set -> shared_expert_gate counted.
+ # Qwen-style: shared_expert_intermediate_size set -> gate counted.
qwen_arch = extract_arch_config(self._hf(shared_expert_intermediate_size = 64))
hd = qwen_arch.hidden_size
ms = qwen_arch.moe_intermediate_size
@@ -1624,8 +1623,8 @@ class TestSharedExpertActivation(unittest.TestCase):
)
def test_shared_expert_plus_dense_block_compose(self):
- # gemma4 enable_moe_block with hypothetical shared expert: dense + routed
- # + shared all live per layer; mlp_size should sum all three terms.
+ # gemma4 enable_moe_block with a hypothetical shared expert: dense +
+ # routed + shared all live per layer; mlp_size sums all three.
from utils.hardware.vram_estimation import _layer_qkv_mlp_sizes
arch = self._make(
@@ -1773,7 +1772,7 @@ class TestSparseMoeSkipAliases(unittest.TestCase):
shared_expert_intermediate_size = 32,
)
)
- # shared_expert delta only -- routed mlp.experts is NOT skipped.
+ # shared_expert delta only -- routed mlp.experts NOT skipped.
delta = _compute_skipped_quantizable_elements(arch)
self.assertGreater(delta, 0)
full_layer = extract_arch_config(
@@ -1944,10 +1943,10 @@ class TestErnieMoEListConfig(unittest.TestCase):
moe_intermediate_size = [1536, 512],
)
)
- # why: ERNIE 4.5 VL MoE encodes [text_routed, vision_routed]; the
- # second element is the vision-routed expert width, not the shared
- # expert width. Shared experts are sized from the text-routed width
- # (= moe_intermediate_size[0]) when moe_num_shared_experts is set.
+ # why: ERNIE 4.5 VL MoE encodes [text_routed, vision_routed]; element 1
+ # is the vision-routed width, not the shared-expert width. Shared
+ # experts size from the text-routed width (moe_intermediate_size[0])
+ # when moe_num_shared_experts is set.
self.assertEqual(arch.moe_intermediate_size, 1536)
self.assertIsNone(arch.shared_expert_intermediate_size)
self.assertEqual(arch.n_shared_experts, 0)
@@ -2070,7 +2069,7 @@ class TestMultimodalFullModelBytes(unittest.TestCase):
load_in_4bit = True,
)
self.assertEqual(metadata.get("estimation_mode"), "detailed")
- # model_weights_gb must reflect the extra non-text bytes (>5 GB
+ # model_weights_gb must reflect the extra non-text bytes (>5 GB,
# since text-only arch_fp16 is small for these dims).
self.assertGreater(metadata["vram_breakdown"]["model_weights_gb"], 5.0)
diff --git a/studio/backend/tests/test_windows_gpu_detection_mock.py b/studio/backend/tests/test_windows_gpu_detection_mock.py
index bc887f8cc5a..3a82541a311 100644
--- a/studio/backend/tests/test_windows_gpu_detection_mock.py
+++ b/studio/backend/tests/test_windows_gpu_detection_mock.py
@@ -3,12 +3,12 @@
"""Windows GPU-detection regression test on a synthetic layout.
-The bug (#5106): on Windows without a system CUDA toolkit, the prebuilt
-llama-server.exe could not LoadLibrary cudart64_X / cublas64_X /
+Bug (#5106): on Windows without a system CUDA toolkit, the prebuilt
+llama-server.exe couldn't LoadLibrary cudart64_X / cublas64_X /
cublasLt64_X, so ggml-cuda.dll's static import on cublas64_X.dll failed
and the model fell back to CPU even when nvidia-smi reported the GPU.
-The fix:
+Fix:
* #5322 overlays upstream's paired cudart bundle into
install_dir/build/bin/Release/ next to llama-server.exe.
* #5324 prepends pip-installed nvidia/<pkg>/{bin,bin/x86_64,Library/
@@ -34,13 +34,12 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
-# Stub heavy deps only if they actually fail to import -- unconditional
-# stubs would shadow the real module for sibling tests in this dir.
-# Use try-import rather than find_spec: loggers/__init__.py re-exports
-# handlers.get_logger, which does `from fastapi import Request,
-# Response` at module load. find_spec("loggers") returns a spec even
-# without fastapi, but the import then raises. CI has fastapi, so this
-# is dev-machine ergonomics only.
+# Stub heavy deps only if they fail to import -- unconditional stubs
+# would shadow the real module for sibling tests here. Use try-import,
+# not find_spec: loggers/__init__.py re-exports handlers.get_logger,
+# which does `from fastapi import Request, Response` at load. find_spec
+# returns a spec even without fastapi, but the import then raises. CI has
+# fastapi, so this is dev-machine ergonomics only.
import importlib as _importlib # noqa: E402
@@ -100,7 +99,7 @@ from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
# Upstream b9103 cudart bundle: exactly these three DLLs per CUDA major,
-# no executables, no subdirectories. Verified by direct unzip.
+# no executables or subdirectories. Verified by direct unzip.
REAL_UPSTREAM_CUDART_BUNDLE = {
"12.4": ("cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll"),
"13.1": ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"),
@@ -133,15 +132,15 @@ REAL_PIP_NVIDIA_WHEEL_LAYOUTS = {
def _populate_studio_venv(prefix: Path) -> None:
"""Lay out fake nvidia + torch wheels in <prefix>/Lib/site-packages
- matching the real win_amd64 wheel layouts. Contents are stub bytes;
- only directory structure matters."""
+ matching real win_amd64 layouts. Contents are stub bytes; only
+ directory structure matters."""
site = prefix / "Lib" / "site-packages"
for rel, dlls in REAL_PIP_NVIDIA_WHEEL_LAYOUTS.items():
d = site / Path(rel)
d.mkdir(parents = True, exist_ok = True)
for name in dlls:
(d / name).write_bytes(b"PE-stub")
- # install_python_stack always installs torch alongside nvidia.
+ # install_python_stack always installs torch beside nvidia.
(site / "torch" / "lib").mkdir(parents = True, exist_ok = True)
for fn in ("c10.dll", "torch.dll", "torch_cpu.dll", "torch_python.dll"):
(site / "torch" / "lib" / fn).write_bytes(b"PE-stub")
@@ -149,7 +148,7 @@ def _populate_studio_venv(prefix: Path) -> None:
def _populate_studio_install(install_dir: Path, runtime: str = "13.1") -> None:
"""Lay out install_dir/build/bin/Release/ as #5322 leaves it: main
- archive payload + paired cudart bundle overlay."""
+ archive payload + cudart bundle overlay."""
rel = install_dir / "build" / "bin" / "Release"
rel.mkdir(parents = True, exist_ok = True)
for fn in (
@@ -163,7 +162,7 @@ def _populate_studio_install(install_dir: Path, runtime: str = "13.1") -> None:
"mtmd.dll",
):
(rel / fn).write_bytes(b"PE-stub")
- # The cudart overlay #5322 contributes.
+ # The cudart overlay from #5322.
for fn in REAL_UPSTREAM_CUDART_BUNDLE[runtime]:
(rel / fn).write_bytes(b"PE-stub")
@@ -173,15 +172,15 @@ def _build_path_dirs_like_start_llama_server(
prefix: Path,
cuda_path: str = "",
) -> list[str]:
- """Path-friendly wrapper around LlamaCppBackend._build_windows_path_dirs.
- Asserting against the staticmethod (not a hand-copy) is the point:
- if the win32 PATH order drops _windows_pip_nvidia_dll_dirs, tests fail."""
+ """Path-friendly wrapper around _build_windows_path_dirs. Asserting
+ against the real staticmethod (not a hand-copy) is the point: if the
+ win32 PATH order drops _windows_pip_nvidia_dll_dirs, tests fail."""
return LlamaCppBackend._build_windows_path_dirs(str(binary_dir), str(prefix), cuda_path)
def _mock_nvidia_smi_run(fake_output: str, returncode: int = 0) -> "mock._patch":
"""Patch subprocess.run so the nvidia-smi probe returns fake_output;
- other subprocess.run calls pass through."""
+ other calls pass through."""
real_run = subprocess.run
def fake_run(cmd, *args, **kwargs):
@@ -199,11 +198,11 @@ def _mock_nvidia_smi_run(fake_output: str, returncode: int = 0) -> "mock._patch"
# --------------------------------------------------------------------- #
class TestWindowsGpuDetectionAfter5106Fix:
"""End-to-end #5106 fix on a synthetic Windows layout. nvidia-smi
- mocked; resolver, PATH builder and install layout exercised live."""
+ mocked; resolver, PATH builder, and install layout run live."""
def test_nvidia_smi_probe_reports_synthetic_gpu(self, monkeypatch):
"""Probe parses CSV output and returns (index, free_mib)."""
- # Clear inherited masks so the synthetic CSV is not filtered.
+ # Clear inherited masks so the synthetic CSV isn't filtered.
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
monkeypatch.delenv("NVIDIA_VISIBLE_DEVICES", raising = False)
# The #5106 reporter's exact reproducer: RTX 4090, 22805 MiB.
@@ -222,7 +221,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
def test_windows_install_dir_has_all_three_cudart_dlls(self, tmp_path):
"""All three bundle DLLs must land in install_dir/build/bin/
- Release; missing any one breaks ggml-cuda.dll's PE import chain."""
+ Release; any missing one breaks ggml-cuda.dll's PE import chain."""
install = tmp_path / "studio_install"
_populate_studio_install(install, runtime = "13.1")
rel = install / "build" / "bin" / "Release"
@@ -232,8 +231,8 @@ class TestWindowsGpuDetectionAfter5106Fix:
assert (rel / "ggml-cuda.dll").exists()
def test_resolver_finds_real_pypi_wheel_layouts(self, tmp_path):
- """Resolver must pick up every real-world wheel layout:
- nvidia/<pkg>/bin, nvidia/<pkg>/bin/x86_64, torch/lib."""
+ """Resolver must pick up every wheel layout: nvidia/<pkg>/bin,
+ nvidia/<pkg>/bin/x86_64, torch/lib."""
prefix = tmp_path / "studio_venv"
_populate_studio_venv(prefix)
out = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(prefix))
@@ -249,8 +248,8 @@ class TestWindowsGpuDetectionAfter5106Fix:
def test_path_assembly_makes_cudart_reachable_without_toolkit(self, tmp_path):
"""The #5106 scenario: GPU detected, pip nvidia wheels present,
- no system CUDA toolkit. cudart must be reachable from PATH, and
- from BOTH binary_dir (#5322) and a pip nvidia dir (#5324)."""
+ no system CUDA toolkit. cudart must be reachable from PATH via
+ BOTH binary_dir (#5322) and a pip nvidia dir (#5324)."""
prefix = tmp_path / "studio_venv"
install = tmp_path / "studio_install"
_populate_studio_venv(prefix)
@@ -278,7 +277,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
), f"#5324's pip nvidia dir not contributing cudart: {cudart_locations}"
def test_cublas_and_cublasLt_also_reachable(self, tmp_path):
- """ggml-cuda imports cublas64; cublas64 imports cublasLt64. All
+ """ggml-cuda imports cublas64, which imports cublasLt64. All
three must resolve or LoadLibrary returns NULL."""
prefix = tmp_path / "studio_venv"
install = tmp_path / "studio_install"
@@ -293,7 +292,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
)
def test_no_pip_nvidia_wheels_still_works_via_install_dir(self, tmp_path):
- """No pip nvidia wheels (CPU-only torch / unsloth run standalone):
+ """No pip nvidia wheels (CPU-only torch / standalone unsloth):
cudart still resolves via #5322's binary_dir drop."""
prefix = tmp_path / "bare_venv"
prefix.mkdir()
@@ -309,7 +308,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
def test_no_install_dir_still_works_via_pip_wheels(self, tmp_path):
"""Pre-#5322 install (binary_dir lacks cudart): #5324's pip
- wheel directories on PATH still resolve cudart."""
+ wheel dirs on PATH still resolve cudart."""
prefix = tmp_path / "studio_venv"
_populate_studio_venv(prefix)
install = tmp_path / "studio_install_pre5322"
@@ -339,9 +338,9 @@ class TestWindowsGpuDetectionAfter5106Fix:
assert cublas_reachable, "cublas unreachable on cudart-less install"
def test_pre_pr_scenario_would_have_failed(self, tmp_path):
- """Negative control: pre-#5322 + pre-#5324 world leaves cudart
+ """Negative control: pre-#5322 + pre-#5324 leaves cudart
unreachable -- the original failure mode. Confirms the test
- actually catches a regression."""
+ catches a regression."""
prefix = tmp_path / "studio_venv"
_populate_studio_venv(prefix)
install = tmp_path / "pre_pr_install"
@@ -349,7 +348,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
rel.mkdir(parents = True)
for fn in ("llama-server.exe", "llama.dll", "ggml-cuda.dll"):
(rel / fn).write_bytes(b"PE-stub")
- # Pre-PR PATH: binary_dir only. No pip nvidia dirs, no toolkit.
+ # Pre-PR PATH: binary_dir only, no pip nvidia dirs, no toolkit.
pre_pr_path_dirs = [str(rel)]
cudart_reachable_pre = any(
(Path(d) / "cudart64_12.dll").exists() or (Path(d) / "cudart64_13.dll").exists()
@@ -362,9 +361,9 @@ class TestWindowsGpuDetectionAfter5106Fix:
class TestWindowsSysPlatformMocked:
- """Confirm the win32 branch in start_llama_server is what we test
- (not the linux fallback). Patches sys.platform and re-runs the
- branch-selecting helper."""
+ """Confirm we test the win32 branch in start_llama_server, not the
+ linux fallback. Patches sys.platform and re-runs the branch-selecting
+ helper."""
def test_sys_platform_win32_uses_pip_nvidia_resolver(self, monkeypatch, tmp_path):
monkeypatch.setattr(sys, "platform", "win32")
diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.py
index 9d01b40add4..4e582ae926e 100644
--- a/studio/backend/utils/cache_cleanup.py
+++ b/studio/backend/utils/cache_cleanup.py
@@ -4,11 +4,11 @@
"""
Utility for cleaning up the Unsloth compiled cache directory.
-The unsloth_compiled_cache is created by unsloth_zoo/compiler.py during
-FastModel.from_pretrained() and contains model-type-specific compiled Python
-files. It should be selectively cleared between model loads to avoid stale
-artefacts, while preserving model-agnostic components (like Trainers) needed
-by spawned subprocesses.
+unsloth_compiled_cache is created by unsloth_zoo/compiler.py during
+FastModel.from_pretrained() and holds model-type-specific compiled Python files.
+Clear it selectively between model loads to avoid stale artefacts, while
+preserving model-agnostic components (like Trainers) needed by spawned
+subprocesses.
"""
import shutil
@@ -38,9 +38,8 @@ def get_existing_cache_dirs() -> List[Path]:
def register_compiled_cache_on_path() -> None:
"""Add all existing compiled-cache directories to sys.path and PYTHONPATH.
- This ensures spawned workers (on platforms using the 'spawn' start method,
- i.e. Windows and macOS) can import dynamically compiled modules such as
- UnslothSFTTrainer.
+ Ensures spawned workers (on 'spawn'-start platforms, i.e. Windows and macOS)
+ can import dynamically compiled modules such as UnslothSFTTrainer.
"""
import os
import sys
@@ -48,8 +47,8 @@ def register_compiled_cache_on_path() -> None:
pypath = os.environ.get("PYTHONPATH", "")
pypath_entries = [p for p in pypath.split(os.pathsep) if p]
- # Iterate in reverse so that earlier _CACHE_DIRS entries (higher priority)
- # are inserted last and therefore end up first in sys.path / PYTHONPATH.
+ # Iterate in reverse so earlier _CACHE_DIRS entries (higher priority) are
+ # inserted last and thus end up first in sys.path / PYTHONPATH.
for cache_dir in reversed(get_existing_cache_dirs()):
resolved = str(cache_dir.resolve())
if resolved not in sys.path:
@@ -65,7 +64,7 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
Remove compiled files from the cache directory (idempotent).
Args:
- preserve_patterns: A list of glob patterns for files to keep
+ preserve_patterns: glob patterns for files to keep
(e.g., ["Unsloth*Trainer.py"]). If None or empty,
the entire cache directory is deleted (legacy behavior).
"""
@@ -80,7 +79,7 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
for item in cache_dir.iterdir():
if item.is_file():
- # Check if the file matches any of the patterns we want to keep
+ # Keep the file if it matches any preserve pattern
preserve = any(item.match(pattern) for pattern in preserve_patterns)
if not preserve:
try:
@@ -92,6 +91,6 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
# Always clear __pycache__ and other subdirectories
shutil.rmtree(item, ignore_errors = True)
else:
- # Legacy behavior: nuke the entire directory
+ # Legacy behavior: remove the entire directory
logger.info(f"Removing unsloth compiled cache: {cache_dir}")
shutil.rmtree(cache_dir, ignore_errors = True)
diff --git a/studio/backend/utils/cpu_threads.py b/studio/backend/utils/cpu_threads.py
index 922f95ce558..5cf2ff1ce23 100644
--- a/studio/backend/utils/cpu_threads.py
+++ b/studio/backend/utils/cpu_threads.py
@@ -18,9 +18,9 @@ _THREAD_POOL_ENV_VARS = (
def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> None:
"""Apply ``UNSLOTH_CPU_THREADS`` to native CPU pools when configured.
- This must run before importing libraries that initialize an OpenMP or
- BLAS thread pool. Library-specific variables are left untouched so users
- can override a single runtime independently.
+ Must run before importing libraries that initialize an OpenMP or BLAS
+ thread pool. Library-specific variables are left untouched so users can
+ override a single runtime independently.
"""
environ = os.environ if env is None else env
configured = environ.get("UNSLOTH_CPU_THREADS", "").strip()
diff --git a/studio/backend/utils/datasets/__init__.py b/studio/backend/utils/datasets/__init__.py
index 7988b09972a..3ecb0854780 100644
--- a/studio/backend/utils/datasets/__init__.py
+++ b/studio/backend/utils/datasets/__init__.py
@@ -2,10 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Dataset utilities package.
-
-This package provides utilities for dataset format detection, conversion,
-and processing for LLM and VLM fine-tuning workflows.
+Dataset utilities for LLM/VLM fine-tuning: format detection, conversion,
+and processing.
Modules:
- format_detection: Detect dataset formats (Alpaca, ShareGPT, ChatML)
@@ -62,8 +60,7 @@ from .model_mappings import (
is_gpt_oss_model_name,
)
-# Legacy imports from the original dataset_utils.py for backward compatibility
-# These functions have not yet been refactored into separate modules
+# Legacy imports from dataset_utils.py (not yet refactored) for backward compat
from .dataset_utils import (
check_dataset_format,
format_and_template_dataset,
diff --git a/studio/backend/utils/datasets/chat_templates.py b/studio/backend/utils/datasets/chat_templates.py
index cfdd811853a..4b8ee93e9c6 100644
--- a/studio/backend/utils/datasets/chat_templates.py
+++ b/studio/backend/utils/datasets/chat_templates.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
-"""
-Chat template application utilities for dataset processing.
+"""Chat template utilities for dataset processing.
-This module contains functions for applying chat templates to datasets
-and generating dataset info summaries.
+Apply chat templates to datasets and generate dataset info summaries.
"""
from .format_detection import detect_dataset_format, detect_multimodal_dataset, detect_custom_format_heuristic
@@ -47,29 +45,27 @@ def _chat_template_kwargs() -> dict:
def get_tokenizer_chat_template(tokenizer, model_name):
"""
- Gets appropriate chat template for tokenizer based on model.
- Uses Unsloth's get_chat_template if model is in the mapper.
+ Get the chat template for a tokenizer based on the model.
+ Uses Unsloth's get_chat_template if the model is in the mapper.
Args:
tokenizer: HuggingFace tokenizer
model_name: Model class name (e.g., "Gemma3ForCausalLM")
Returns:
- tokenizer: Tokenizer with appropriate chat template applied
+ tokenizer: Tokenizer with the chat template applied
"""
try:
from unsloth.chat_templates import get_chat_template
except ImportError:
- # Unsloth not available, return tokenizer as-is
+ # Unsloth not available; return tokenizer as-is.
return tokenizer
- # Normalize model_name to lowercase for matching
model_name_lower = model_name.lower()
- # Check if model matches any template in mapper
matched_template = None
- # Direct match in MODEL_TO_TEMPLATE_MAPPER
+ # Direct match in MODEL_TO_TEMPLATE_MAPPER.
if model_name_lower in MODEL_TO_TEMPLATE_MAPPER:
matched_template = MODEL_TO_TEMPLATE_MAPPER[model_name_lower]
logger.info(f"📝 Applying Unsloth chat template: {matched_template}")
@@ -83,7 +79,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
logger.info(f"⚠️ Failed to apply Unsloth template '{matched_template}': {e}")
logger.info(f" Falling back to tokenizer's default chat template")
else:
- # Check if tokenizer actually has a chat_template set
+ # Check whether the tokenizer has a chat_template set.
has_chat_template = (
hasattr(tokenizer, 'chat_template')
and tokenizer.chat_template is not None
@@ -91,7 +87,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
if has_chat_template:
logger.info(f"📝 Using tokenizer's own chat template (no Unsloth template match)")
else:
- # Base model with no chat template — apply default ChatML
+ # Base model with no chat template — apply default ChatML.
logger.info(f"📝 No chat template found — applying default ChatML template (base model)")
try:
tokenizer = get_chat_template(
@@ -107,9 +103,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
def get_dataset_info_summary(dataset_info):
- """
- Returns a human-readable summary for UI display.
- """
+ """Return a human-readable summary for UI display."""
detected_format = dataset_info["detected_format"]
final_format = dataset_info["final_format"]
@@ -147,14 +141,14 @@ def apply_chat_template_to_dataset(
progress_callback = None,
):
"""
- Applies chat template to dataset based on its format.
+ Apply the chat template to a dataset based on its format.
Args:
dataset_info: Output from format_dataset() with metadata
tokenizer: Tokenizer with chat template
custom_prompt_template: Optional string template for custom formatting
- add_eos_token: If True, appends tokenizer.eos_token to each text
- remove_bos_prefix: If True, removes '<bos>' prefix (for Gemma, etc.)
+ add_eos_token: If True, append tokenizer.eos_token to each text
+ remove_bos_prefix: If True, remove '<bos>' prefix (Gemma, etc.)
custom_format_mapping: Dict mapping custom columns to standard format
batch_size: Batch size for processing
num_proc: Number of processes
@@ -170,7 +164,7 @@ def apply_chat_template_to_dataset(
warnings = list(dataset_info.get("warnings", []))
errors = []
- # Get EOS token if needed
+ # Get EOS token if needed.
eos_token = ""
if add_eos_token:
if hasattr(tokenizer, 'eos_token') and tokenizer.eos_token:
@@ -180,9 +174,9 @@ def apply_chat_template_to_dataset(
# CUSTOM FORMAT MAPPING (for non-standard datasets)
if final_format == "unknown":
- # Try auto-detection if no custom mapping provided
+ # Auto-detect if no custom mapping was provided.
if custom_format_mapping is None and auto_detect_mapping:
- # Check if format_dataset already tried and failed
+ # Skip if format_dataset already tried and failed.
if not dataset_info.get("auto_detection_attempted", False):
custom_format_mapping = detect_custom_format_heuristic(dataset)
if custom_format_mapping:
@@ -196,7 +190,7 @@ def apply_chat_template_to_dataset(
"errors": errors
}
else:
- # Already failed once in format_dataset, don't retry
+ # Already failed once in format_dataset; don't retry.
errors.append(
"Format remains unknown after detection attempts. "
"Please provide custom_format_mapping to specify column roles manually."
@@ -216,7 +210,7 @@ def apply_chat_template_to_dataset(
conversations = []
num_examples = len(examples[list(examples.keys())[0]])
- # Only preserve unmapped columns if auto-detected
+ # Preserve unmapped columns only if auto-detected.
preserved_columns = {}
if not is_user_provided:
all_columns = set(examples.keys())
@@ -236,10 +230,10 @@ def apply_chat_template_to_dataset(
content = examples[col_name][i]
if is_user_provided:
- # User explicitly mapped - include even if empty
+ # User-mapped: include even if empty.
convo.append({"role": role, "content": str(content) if content else ""})
else:
- # Auto-detected - skip empty
+ # Auto-detected: skip empty.
if content and str(content).strip():
convo.append({"role": role, "content": str(content)})
@@ -252,7 +246,7 @@ def apply_chat_template_to_dataset(
try:
dataset = dataset.map(_apply_custom_mapping, batched = True, batch_size = batch_size)
- # Update to use conversations format
+ # Switch to conversations format.
final_format = "chatml_conversations"
chat_column = "conversations"
is_standardized = True
@@ -269,8 +263,8 @@ def apply_chat_template_to_dataset(
# ALPACA FORMAT
if final_format == "alpaca":
- # Set alpaca chat template on tokenizer for saving (if not already set)
- # This ensures the template is saved with the model for inference
+ # Set alpaca chat template on the tokenizer (if unset) so it's
+ # saved with the model for inference.
if not (hasattr(tokenizer, 'chat_template') and tokenizer.chat_template):
try:
from unsloth.chat_templates import get_chat_template
@@ -283,7 +277,7 @@ def apply_chat_template_to_dataset(
except Exception as e:
logger.info(f"⚠️ Could not set alpaca template on tokenizer: {e}")
- # Use custom template if provided
+ # Use custom template if provided.
def _format_alpaca_custom(examples):
texts = []
for i in range(len(examples["instruction"])):
@@ -349,7 +343,7 @@ def apply_chat_template_to_dataset(
if not is_standardized:
warnings.append("Dataset may not be fully standardized")
- # Apply Unsloth chat template if model matches
+ # Apply Unsloth chat template if the model matches.
if model_name:
tokenizer = get_tokenizer_chat_template(tokenizer, model_name)
@@ -398,7 +392,7 @@ def apply_chat_template_to_dataset(
dataset_map_kwargs['num_proc'] = num_proc
dataset_map_kwargs['desc'] = f"Applying chat template to {final_format}"
- # Monitor tqdm progress from dataset.map() and relay to callback
+ # Monitor tqdm progress from dataset.map() and relay it.
_tqdm_monitor_stop = None
if progress_callback and not _is_torch_iterable:
import threading
diff --git a/studio/backend/utils/datasets/data_collators.py b/studio/backend/utils/datasets/data_collators.py
index 2955ec90233..5f249b32f91 100644
--- a/studio/backend/utils/datasets/data_collators.py
+++ b/studio/backend/utils/datasets/data_collators.py
@@ -4,8 +4,7 @@
"""
Data collators for dataset processing.
-This module contains custom data collators for training,
-particularly for VLM/OCR processing.
+Custom training collators, particularly for VLM/OCR processing.
"""
from dataclasses import dataclass
@@ -20,9 +19,9 @@ class DataCollatorSpeechSeq2SeqWithPadding:
"""
Data collator for Whisper speech-to-text training.
- Pads input features (audio) and label sequences (text) separately,
- masks padding in labels with -100, and strips leading BOS token.
- Mirrors the collator from the Whisper.ipynb notebook.
+ Pads audio input features and text labels separately, masks label padding
+ with -100, and strips the leading BOS token. Mirrors the Whisper.ipynb
+ notebook collator.
"""
processor: Any
@@ -71,7 +70,7 @@ class DeepSeekOCRDataCollator:
"""
from PIL import Image
- # Extract messages and images
+ # Extract messages and images.
all_messages = []
all_images = []
@@ -79,7 +78,7 @@ class DeepSeekOCRDataCollator:
messages = sample["messages"]
all_messages.append(messages)
- # Extract PIL images from content
+ # Extract PIL images from content.
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
@@ -89,9 +88,9 @@ class DeepSeekOCRDataCollator:
if img is not None and hasattr(img, "size"): # PIL Image
all_images.append(img)
- # Process with the VL processor
+ # Process with the VL processor.
try:
- # Qwen2VL style processing
+ # Qwen2VL-style processing.
texts = [
self.processor.apply_chat_template(
msgs, tokenize = False, add_generation_prompt = False
@@ -99,7 +98,7 @@ class DeepSeekOCRDataCollator:
for msgs in all_messages
]
- # Process with images
+ # Process with images.
inputs = self.processor(
text = texts,
images = all_images if all_images else None,
@@ -109,10 +108,10 @@ class DeepSeekOCRDataCollator:
max_length = self.max_length,
)
- # Create labels (mask input, keep output)
+ # Create labels (mask input, keep output).
labels = inputs["input_ids"].clone()
- # Simple masking: mask padding tokens
+ # Mask padding tokens.
labels[labels == self.processor.tokenizer.pad_token_id] = self.ignore_index
inputs["labels"] = labels
@@ -138,7 +137,7 @@ class VLMDataCollator:
processor: Any
max_length: int = 2048
ignore_index: int = -100
- mask_input_tokens: bool = True # Whether to mask user tokens in labels
+ mask_input_tokens: bool = True # Mask user tokens in labels
def __call__(self, batch: List[dict]) -> dict:
"""
@@ -151,7 +150,7 @@ class VLMDataCollator:
messages = sample.get("messages", [])
all_messages.append(messages)
- # Extract images
+ # Extract images.
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
@@ -161,13 +160,13 @@ class VLMDataCollator:
if img is not None:
all_images.append(img)
- # Apply chat template
+ # Apply chat template.
texts = [
self.processor.apply_chat_template(msgs, tokenize = False, add_generation_prompt = False)
for msgs in all_messages
]
- # Process inputs
+ # Process inputs.
inputs = self.processor(
text = texts,
images = all_images if all_images else None,
@@ -177,10 +176,10 @@ class VLMDataCollator:
max_length = self.max_length,
)
- # Create labels
+ # Create labels.
labels = inputs["input_ids"].clone()
- # Mask padding
+ # Mask padding.
if hasattr(self.processor, "tokenizer"):
pad_token_id = self.processor.tokenizer.pad_token_id
else:
diff --git a/studio/backend/utils/datasets/dataset_none_detect.py b/studio/backend/utils/datasets/dataset_none_detect.py
index e48e153fb84..354fd360d36 100644
--- a/studio/backend/utils/datasets/dataset_none_detect.py
+++ b/studio/backend/utils/datasets/dataset_none_detect.py
@@ -1,8 +1,8 @@
"""
dataset_none_detect.py
-Detect None/empty content turns in conversation datasets.
-Reports findings without modifying data.
+Detect None/empty content turns in conversation datasets. Reports findings
+without modifying data.
Usage:
from .dataset_none_detect import scan_dataset, print_report
@@ -18,8 +18,8 @@ Supported formats (via FORMAT_REGISTRY):
sharegpt conversations from/value per turn
gptoss messages (alias: gpt-oss) role/content; has a developer turn
-Any role/content chat template matches the chatml entry, so new templates need
-no change; add a FORMAT_REGISTRY entry only for a genuinely new column/turn shape.
+Any role/content chat template matches chatml, so new templates need no change;
+add a FORMAT_REGISTRY entry only for a genuinely new column/turn shape.
"""
from datasets import Dataset
@@ -31,7 +31,7 @@ from datasets import Dataset
# Candidate column names for conversational datasets, checked in priority order.
CONVERSATION_COLUMNS = ("messages", "conversations", "texts")
-# Minimum turn key sets that identify a column as conversational (not e.g. messages=[{"id":1}]).
+# Minimum turn key sets identifying a column as conversational (not e.g. messages=[{"id":1}]).
_CHAT_KEY_SETS = (frozenset({"role", "content"}), frozenset({"from", "value"}))
@@ -39,13 +39,13 @@ def _probe_conversation(dataset: Dataset, candidates = None):
"""
Probe a dataset for its conversation column and turn structure.
- candidates - iterable of column names to try, in priority order.
+ candidates - column names to try, in priority order.
Defaults to CONVERSATION_COLUMNS when None.
Returns a dict with:
- column - name of the conversation column found
- turn_keys - set of keys present in the first turn dict
- roles - set of all role values seen across the first few samples
+ column - conversation column found
+ turn_keys - keys present in the first turn dict
+ roles - all role values seen across the first few samples
Returns None if no conversation column is found.
"""
@@ -53,12 +53,12 @@ def _probe_conversation(dataset: Dataset, candidates = None):
candidates = CONVERSATION_COLUMNS
columns = set(dataset.column_names)
# Remember the first all-corrupt candidate, but keep probing: a later column
- # may be healthy and should win (e.g. bad messages, good conversations).
+ # may be healthy and win (e.g. bad messages, good conversations).
all_corrupt_fallback = None
for col in candidates:
if col not in columns:
continue
- # Scan up to 100 rows - row 0 alone may be empty or malformed.
+ # Scan up to 100 rows - row 0 alone may be empty/malformed.
first = None
for i in range(min(len(dataset), 100)):
sample = dataset[i][col]
@@ -71,9 +71,9 @@ def _probe_conversation(dataset: Dataset, candidates = None):
break
if first is None:
# No usable dict turn in 100 rows. Record an all_corrupt fallback,
- # marking it plausible only if we saw turn-shaped data (a None cell or
- # a list holding a dict/None turn); scalars and list-of-strings must
- # not look like chatml. Upgrade a non-plausible fallback when a later
+ # plausible only if we saw turn-shaped data (a None cell or a list
+ # holding a dict/None turn); scalars and list-of-strings must not
+ # look like chatml. Upgrade a non-plausible fallback when a later
# candidate is plausible, so probe order keeps the best match.
if all_corrupt_fallback is None or not all_corrupt_fallback.get("has_plausible_turns"):
has_plausible_turns = False
@@ -86,8 +86,8 @@ def _probe_conversation(dataset: Dataset, candidates = None):
# not chat: leave it for "unknown format", matching
# format_detection.py.
if isinstance(cell, list):
- # Plausible only if the list holds a dict/None turn; empty
- # lists and list-of-strings are not chat data.
+ # Plausible only if the list holds a dict/None turn;
+ # empty lists and list-of-strings are not chat data.
if any(t is None or isinstance(t, dict) for t in cell):
has_plausible_turns = True
break
@@ -112,11 +112,11 @@ def _probe_conversation(dataset: Dataset, candidates = None):
r = t.get("role") or t.get("from")
if r:
roles.add(str(r))
- # Column lacks a full chat key pair. If it still has a conversational key
- # (role/from/content/value) it is a corrupt-but-real chat column, so save
- # a plausible fallback for find_none_chatml to flag. Pure metadata (e.g.
- # [{"id":1}]) is not plausible, so a later real-but-corrupt column (e.g.
- # conversations=None) can still win.
+ # Column lacks a full chat key pair. If it has a conversational key
+ # (role/from/content/value) it is a corrupt-but-real chat column, so
+ # save a plausible fallback for find_none_chatml to flag. Pure metadata
+ # (e.g. [{"id":1}]) is not plausible, so a later real-but-corrupt column
+ # (e.g. conversations=None) can still win.
_CONV_KEYS = {"role", "from", "content", "value"}
if not any(keys <= turn_keys for keys in _CHAT_KEY_SETS):
schema_less_plausible = bool(turn_keys & _CONV_KEYS)
@@ -143,7 +143,7 @@ def is_none_or_empty(value) -> bool:
if value is None:
return True
if isinstance(value, str):
- # Treat zero-width/BOM chars (U+FEFF/200B/200C/200D/2060) as empty too;
+ # Treat zero-width/BOM chars (U+FEFF/200B/200C/200D/2060) as empty;
# they render invisibly. Two-pass strip (ws, invisibles, ws) catches
# mixed cases like "\u200b \u200b".
stripped = value.strip().strip("\ufeff\u200b\u200c\u200d\u2060").strip()
@@ -156,7 +156,7 @@ def is_none_or_empty(value) -> bool:
# exists (an image-only turn is valid).
if len(value) == 0:
return True
- # No dict blocks at all (e.g. [None], [' ']) -> malformed/empty.
+ # No dict blocks (e.g. [None], [' ']) -> malformed/empty.
dict_blocks = [item for item in value if isinstance(item, dict)]
if not dict_blocks:
return True
@@ -190,7 +190,7 @@ def _classify_empty(value) -> str:
if len(value) == 0:
return "empty_list"
return "empty_vlm_content"
- return "valid" # should not reach here if is_none_or_empty was True
+ return "valid" # unreachable if is_none_or_empty was True
# ---------------------------------------------------------------------------
@@ -201,7 +201,7 @@ def _classify_empty(value) -> str:
def find_none_alpaca(dataset: Dataset) -> dict:
"""
Scan alpaca dataset for None/empty instruction or output fields.
- Returns stats dict with a detailed 'findings' list.
+ Returns a stats dict with a detailed 'findings' list.
"""
stats = {
"total_rows": len(dataset),
@@ -242,8 +242,8 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
Scan chatml/sharegpt/gptoss dataset for turns with None/empty content.
Auto-detects the conversation column if col=None.
- Returns a stats dict that includes a complete 'findings' list - one entry
- per bad turn with row_index, turn_index, role, value_type, and raw_value.
+ Returns a stats dict with a complete 'findings' list - one entry per bad
+ turn with row_index, turn_index, role, value_type, and raw_value.
"""
if col is None:
# Reuse _probe_conversation so the all_corrupt path is handled here too.
@@ -292,7 +292,7 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
continue
if len(conversation) == 0:
- # Zero-turn conversation: flag so it does not scan as clean.
+ # Zero-turn conversation: flag so it doesn't scan as clean.
stats["bad_row_indices"].append(i)
stats["rows_with_none_turns"] += 1
stats["total_none_turns"] += 1
@@ -340,8 +340,8 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
role = r
else:
role = str(r)
- # Pick the content key: from+value -> value (ShareGPT, even if role is
- # also set); role -> content (or value); from only -> value (None when
+ # Pick the content key: from+value -> value (ShareGPT, even if role
+ # is set); role -> content (or value); from only -> value (None when
# missing, so it is flagged); neither -> content then value.
if "from" in turn and "value" in turn:
content = turn.get("value")
@@ -388,7 +388,7 @@ def find_none_sharegpt(dataset: Dataset, col: str = None) -> dict:
"""ShareGPT uses 'from'/'value' keys - same scan logic handles both."""
if col is None:
# ShareGPT lives in 'conversations'; probe only that column so a corrupt
- # one is still scanned, not replaced by a healthy 'messages' (P1 fix).
+ # one is still scanned, not replaced by healthy 'messages' (P1 fix).
conv_info = _probe_conversation(dataset, candidates = ("conversations",))
if conv_info is None:
raise ValueError(
@@ -403,7 +403,7 @@ def find_none_gptoss(dataset: Dataset, col: str = None) -> dict:
"""gptoss: role/content plus optional thinking/tool_calls. Only content checked."""
if col is None:
# gptoss lives in 'messages': target it whenever present (even if
- # corrupt), and fall back to 'conversations' only if 'messages' is absent.
+ # corrupt); fall back to 'conversations' only if 'messages' is absent.
if "messages" in dataset.column_names:
conv_info = _probe_conversation(dataset, candidates = ("messages",))
else:
@@ -420,7 +420,7 @@ def find_none_gptoss(dataset: Dataset, col: str = None) -> dict:
# ---------------------------------------------------------------------------
# Format registry - first match wins; detect_format() auto-scales.
# Each entry: name (label/--format value), match(dataset, conv_info) -> bool,
-# scan (find_none_* function). Put specific formats before generalisations
+# scan (find_none_* function). Put specific formats before general ones
# (gptoss before chatml, since gptoss is chatml with a 'developer' role).
# To add a format: write find_none_<name>() (or reuse find_none_chatml) and
# append an entry; detect_format(), --format, and scan_dataset() pick it up.
@@ -460,7 +460,7 @@ FORMAT_REGISTRY = [
and (
{"role", "content"} <= conv["turn_keys"]
# all_corrupt: column found but every row malformed; require
- # has_plausible_turns so scalar/string columns are not chatml.
+ # has_plausible_turns so scalar/string columns aren't chatml.
or (conv.get("all_corrupt") and conv.get("has_plausible_turns"))
)
),
@@ -479,7 +479,7 @@ def detect_format(dataset: Dataset) -> str:
"""
Auto-detect dataset format by probing columns and turn structure.
- Returns one of the format names in FORMAT_REGISTRY, or 'unknown'.
+ Returns a format name from FORMAT_REGISTRY, or 'unknown'.
Walks the registry in order; first match wins.
"""
conv_info = _probe_conversation(dataset)
@@ -507,7 +507,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
# Reject a DatasetDict / IterableDatasetDict (load_dataset without split):
# its column_names is a split map and would yield a confusing "unknown
# format". Check both (IterableDatasetDict is not a DatasetDict subclass);
- # import locally so this module never hard-requires those symbols.
+ # import locally so this module never hard-requires them.
_dict_types = []
try:
from datasets import DatasetDict as _DatasetDict
@@ -526,7 +526,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
"Pass dataset[<split>] or use load_dataset(..., split='train')."
)
# Streaming IterableDataset has no len()/column_names; give a clear error
- # instead of a confusing TypeError downstream.
+ # instead of a confusing downstream TypeError.
try:
from datasets import IterableDataset as _IterableDataset
if isinstance(dataset, _IterableDataset):
@@ -555,8 +555,8 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
if entry["match"](dataset, conv_info):
fmt = entry["name"]
break
- # No format matched: return clean stats (format="unknown") rather than
- # raise, so callers can branch on stats["format"].
+ # No format matched: return clean stats (format="unknown") instead of
+ # raising, so callers can branch on stats["format"].
if fmt == "unknown":
return {
"format": "unknown",
@@ -567,7 +567,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
scanner = get_scanner(fmt)
if scanner is None:
raise ValueError(f"Unknown or unsupported format: '{fmt}'")
- # Column forwarding: on auto-detect pass the probed column (already the best
+ # Column forwarding: on auto-detect pass the probed column (the best
# choice). On an explicit format let that scanner pick its own column, so
# e.g. fmt='sharegpt' always scans 'conversations', not 'messages' (P1 fix);
# gptoss has its own messages-first rule. alpaca never takes a column.
@@ -620,7 +620,7 @@ def _print_summary_header(stats: dict, fmt: str) -> bool:
if rows_all:
print(f" Rows ALL bad: {rows_all} (every turn is None/empty)")
- # Rows with no Nones - compute the count directly instead of allocating a
+ # Rows with no Nones - compute the count directly rather than allocating a
# full set of row indices, which OOMs on large (10M+ row) datasets.
bad_indices = set(stats.get("bad_row_indices", []))
clean_count = total - len(bad_indices)
@@ -696,8 +696,8 @@ def show_row(
print(f" Row {ri}")
print(f"{'=' * 64}")
- # Print non-conversation columns. For alpaca, skip the fields the
- # alpaca block below prints with status markers (avoid double render).
+ # Print non-conversation columns. For alpaca, skip fields the alpaca
+ # block below prints with status markers (avoid double render).
_ALPACA_FIELDS = {"instruction", "input", "output"}
for key in dataset.column_names:
if key == col:
@@ -732,7 +732,7 @@ def show_row(
c = t.get("value")
else:
c = t.get("content") if "content" in t else t.get("value")
- # Mirror scanner logic: tool_calls exemption is assistant-only;
+ # Mirror scanner: tool_calls exemption is assistant-only;
# other roles with empty content + tool_calls are still bad.
r = t.get("role") if t.get("role") is not None else t.get("from")
if is_none_or_empty(c) and not (str(r) == "assistant" and t.get("tool_calls")):
@@ -743,7 +743,7 @@ def show_row(
print(f" {col}: {len(conversation)} turns ({none_count} None)")
print(f" {'-' * 60}")
for i, turn in enumerate(conversation):
- # Non-dict turn - can't extract role or content normally.
+ # Non-dict turn - can't extract role/content normally.
if not isinstance(turn, dict):
label = "None" if turn is None else "invalid_type"
print(f" [{i:>3d}] {'unknown':<12s} [{label}] << NONE")
diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.py
index 792e0ea9bc4..03387e5331d 100644
--- a/studio/backend/utils/datasets/dataset_utils.py
+++ b/studio/backend/utils/datasets/dataset_utils.py
@@ -4,12 +4,12 @@
"""
Dataset utilities for format detection, conversion, and template application.
-This module provides the main entry points for dataset processing:
-- check_dataset_format: Lightweight check if manual mapping is needed (for frontend)
-- format_dataset: Detects and normalizes dataset formats
-- format_and_template_dataset: End-to-end processing with chat template application
+Main entry points for dataset processing:
+- check_dataset_format: lightweight check if manual mapping is needed (frontend)
+- format_dataset: detects and normalizes dataset formats
+- format_and_template_dataset: end-to-end processing with chat template
-All internal utilities have been moved to separate modules:
+Internal utilities live in separate modules:
- format_detection: detect_dataset_format, detect_multimodal_dataset, etc.
- format_conversion: standardize_chat_format, convert_chatml_to_alpaca, etc.
- chat_templates: apply_chat_template_to_dataset, get_tokenizer_chat_template, etc.
@@ -54,8 +54,8 @@ def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
"""
Lightweight format check without processing - for frontend validation.
- Use this to quickly determine if user needs to manually map columns
- before calling the full format_and_template_dataset().
+ Quickly determines if the user must manually map columns before the full
+ format_and_template_dataset().
Args:
dataset: HuggingFace dataset
@@ -121,7 +121,7 @@ def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
}
if is_audio:
- # Audio dataset — require manual mapping only when columns can't be auto-detected
+ # Audio dataset — require manual mapping only when columns aren't auto-detected
detected_audio = multimodal_info.get("detected_audio_column")
detected_text = multimodal_info.get("detected_text_column")
needs_mapping = not detected_audio or not detected_text
@@ -211,9 +211,9 @@ def _apply_user_mapping(
Apply user-provided column mapping to convert dataset to conversations format.
Accepts chatml (user/assistant/system), sharegpt (human/gpt/system), and
- alpaca (instruction/input/output) role names — all normalised to chatml output.
+ alpaca (instruction/input/output) role names — all normalised to chatml.
- If the mapping contains ``__``-prefixed metadata keys (from the conversion
+ If the mapping has ``__``-prefixed metadata keys (from the conversion
advisor), routes to template-based conversion instead of simple role mapping.
Returns:
@@ -262,7 +262,7 @@ def _apply_user_mapping(
def _extract_column_value(val, col: str, label_mapping: dict) -> str:
"""Extract a string value from a column, handling complex types and label mapping."""
- # Handle complex types (dicts, lists) — extract useful text instead of raw repr
+ # Complex types (dicts, lists): extract useful text instead of raw repr
if isinstance(val, dict):
# Common pattern: {"text": [...]} in QA datasets
if "text" in val:
@@ -291,10 +291,9 @@ def _apply_template_mapping(
"""
Apply advisor-driven mapping for non-conversational datasets.
- Groups columns by their assigned role (user/assistant), concatenates
- values within each role into a single message, and injects an optional
- system prompt. Label mapping is applied to convert integer labels
- to human-readable strings.
+ Groups columns by assigned role (user/assistant), concatenates values
+ within each role into one message, and injects an optional system prompt.
+ Label mapping converts integer labels to human-readable strings.
Returns:
Dataset with single 'conversations' column
@@ -327,7 +326,7 @@ def _apply_template_mapping(
if system_prompt:
convo.append({"role": "system", "content": system_prompt})
- # User message: concatenate all user-role column values
+ # User message: concatenate user-role column values
user_parts = []
for col in role_groups["user"]:
if col in examples:
@@ -335,7 +334,7 @@ def _apply_template_mapping(
if user_parts:
convo.append({"role": "user", "content": "\n".join(user_parts)})
- # Assistant message: concatenate all assistant-role column values
+ # Assistant message: concatenate assistant-role column values
asst_parts = []
for col in role_groups["assistant"]:
if col in examples:
@@ -433,7 +432,7 @@ def format_dataset(
"final_format": final format after processing,
"chat_column": column name with chat data,
"is_standardized": whether role names are standardized,
- "requires_manual_mapping": True if format detection failed and user must map columns,
+ "requires_manual_mapping": True if detection failed and user must map columns,
"warnings": list of warning messages
}
"""
@@ -455,7 +454,7 @@ def format_dataset(
"warnings": [notice.message for notice in raw_result.notices],
}
- # If user provided explicit mapping, skip detection and apply in the requested format
+ # If user provided explicit mapping, skip detection and apply it
if custom_format_mapping:
try:
if format_type == "alpaca":
@@ -465,8 +464,8 @@ def format_dataset(
final_format = "alpaca"
chat_column = None
else:
- # auto / chatml / sharegpt / conversational — all produce chatml conversations
- # (sharegpt is always standardized to role/content internally)
+ # auto / chatml / sharegpt / conversational all produce chatml
+ # conversations (sharegpt standardized to role/content internally)
mapped_dataset = _apply_user_mapping(dataset, custom_format_mapping, batch_size)
final_format = "chatml_conversations"
chat_column = "conversations"
@@ -577,11 +576,11 @@ def format_dataset(
"warnings": warnings,
}
- # Unknown - try standardization, if fails pass as is
+ # Unknown - try standardization, pass as-is on failure
else:
warnings.append(f"Unknown format detected. Keys found: {detected['sample_keys']}")
- # NEW: Try heuristic detection
+ # Try heuristic detection
if auto_detect_custom:
custom_mapping = detect_custom_format_heuristic(dataset)
if custom_mapping:
@@ -853,8 +852,8 @@ def format_and_template_dataset(
progress_callback = None,
):
"""
- Convenience function that combines format_dataset and apply_chat_template_to_dataset.
- Perfect for UI workflows - one function does everything!
+ Combines format_dataset and apply_chat_template_to_dataset. Convenient for
+ UI workflows: one function does everything.
Returns:
dict: {
@@ -862,7 +861,7 @@ def format_and_template_dataset(
"detected_format": Original format,
"final_format": Format after processing,
"success": Whether template application succeeded,
- "requires_manual_mapping": True if format detection failed and user must map columns,
+ "requires_manual_mapping": True if detection failed and user must map columns,
"warnings": List of warnings,
"errors": List of errors,
"summary": Human-readable summary
@@ -876,7 +875,7 @@ def format_and_template_dataset(
multimodal_info = detect_multimodal_dataset(dataset)
- # NEW: If user provided explicit mapping for VLM, use it directly
+ # If user provided explicit mapping for VLM, use it directly
if custom_format_mapping:
# Expect mapping like: {"image_col": "image", "caption_col": "text"}
user_vlm_image_column = None
@@ -916,15 +915,15 @@ def format_and_template_dataset(
"errors": [],
}
except Exception as e:
- # User mapping failed — fall back to auto-detection instead
- # of giving up (handles stale cached mappings gracefully)
+ # User mapping failed — fall back to auto-detection rather
+ # than give up (handles stale cached mappings gracefully)
warnings.append(
f"User VLM mapping (image='{user_vlm_image_column}', "
f"text='{user_vlm_text_column}') failed: {e} — "
f"falling back to auto-detection"
)
logger.info(f"⚠️ User VLM mapping failed, falling back to auto-detection...")
- custom_format_mapping = None # clear so auto-detection runs below
+ custom_format_mapping = None # so auto-detection runs below
else:
errors.append(
f"Invalid VLM mapping: need 'image' and 'text' roles. Got: {custom_format_mapping}"
@@ -967,7 +966,7 @@ def format_and_template_dataset(
"errors": errors,
}
- # Handle ShareGPT/ChatML + image column (e.g. ShareGPT4V, LLaVA-style)
+ # ShareGPT/ChatML + image column (e.g. ShareGPT4V, LLaVA-style)
elif vlm_structure["format"] == "sharegpt_with_images":
try:
dataset = convert_sharegpt_with_images_to_vlm_format(
@@ -1087,7 +1086,7 @@ def format_and_template_dataset(
"errors": errors,
}
- # LLM FLOW (Existing code)
+ # LLM FLOW
else:
# Step 1: Format the dataset
n_rows = len(dataset) if hasattr(dataset, "__len__") else None
@@ -1127,7 +1126,7 @@ def format_and_template_dataset(
progress_callback(
status_message = f"Applying chat template to {detected} ({n_rows:,} rows)..."
)
- # Gemma emits a leading <bos> that must be stripped for text-only chatml/sharegpt.
+ # Gemma emits a leading <bos>, stripped for text-only chatml/sharegpt.
is_alpaca = format_type == "alpaca" or (
format_type == "auto" and dataset_info["detected_format"] == "alpaca"
)
@@ -1156,7 +1155,7 @@ def format_and_template_dataset(
all_errors = template_result.get("errors", [])
# If format_dataset returned "unknown" but apply_chat_template rescued
- # it via heuristic detection, update final_format to reflect reality.
+ # it via heuristic detection, update final_format accordingly.
final_format = dataset_info["final_format"]
requires_manual = dataset_info.get("requires_manual_mapping", False)
if final_format == "unknown" and template_result["success"]:
@@ -1170,7 +1169,7 @@ def format_and_template_dataset(
"detected_format": dataset_info["detected_format"],
"final_format": final_format,
"chat_column": dataset_info.get("chat_column"),
- "is_vlm": False, # This is LLM flow
+ "is_vlm": False, # LLM flow
"success": template_result["success"],
"requires_manual_mapping": requires_manual,
"warnings": all_warnings,
diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.py
index 5433d3115c6..09521e160ce 100644
--- a/studio/backend/utils/datasets/format_conversion.py
+++ b/studio/backend/utils/datasets/format_conversion.py
@@ -2,10 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""
-Format conversion utilities for dataset processing.
-
-This module contains functions for converting between dataset formats
-(Alpaca, ShareGPT, ChatML) and standardizing chat formats.
+Dataset format conversion: convert between Alpaca, ShareGPT, and ChatML,
+and standardize chat formats.
"""
import os
@@ -36,14 +34,14 @@ def standardize_chat_format(
num_proc = None,
):
"""
- Our own standardization function that handles BOTH messages and conversations.
- Converts non-standard role names and keys to standard format.
+ Standardize BOTH messages and conversations: map non-standard role
+ names and keys to the standard format.
"""
import collections
import itertools
from datasets import IterableDataset
- # Check if vision tokenizer is used
+ # Detect a vision tokenizer
is_vlm = False
if tokenizer is not None:
if hasattr(tokenizer, "image_processor") or hasattr(tokenizer, "tokenizer"):
@@ -51,7 +49,7 @@ def standardize_chat_format(
column_names = set(next(iter(dataset)).keys())
- # Check for both 'conversations' and 'messages'
+ # Find the chat column
chat_column = None
if "conversations" in column_names:
chat_column = "conversations"
@@ -69,7 +67,7 @@ def standardize_chat_format(
for message in example[chat_column]:
for key, value in message.items():
if type(value) is not str:
- continue # Skip non-string values
+ continue # Skip non-strings
uniques[key].append(value)
if len(uniques.keys()) != 2:
@@ -79,7 +77,7 @@ def standardize_chat_format(
length_first = len(set(uniques[keys[0]]))
length_second = len(set(uniques[keys[1]]))
- # Determine which is role and which is content
+ # Fewer unique values => role; the other => content
if length_first < length_second:
role_key = keys[0]
content_key = keys[1]
@@ -102,18 +100,15 @@ def standardize_chat_format(
for convo in convos:
new_convo = []
for message in convo:
- # Get original role and content
original_role = message.get(role_key, "")
original_content = message.get(content_key, "")
- # Map to standard role name
standard_role = aliases_mapping.get(original_role, original_role)
- # Handle VLM format
if is_vlm:
original_content = [{"type": "text", "text": original_content}]
- # Create dict with EXPLICIT ORDER
+ # Keep EXPLICIT key order
new_message = {"role": standard_role, "content": original_content}
new_convo.append(new_message)
@@ -146,8 +141,7 @@ def convert_chatml_to_alpaca(
num_proc = None,
):
"""
- Converts ChatML format (messages OR conversations) to Alpaca format.
- Handles both standardized and ShareGPT formats.
+ Convert ChatML (messages OR conversations) to Alpaca format.
Supports:
- "messages" or "conversations" column
@@ -160,7 +154,7 @@ def convert_chatml_to_alpaca(
_is_torch_iterable = False
def _convert(examples):
- # Auto-detect which column name is used
+ # Auto-detect the column name
chatml_data = (
examples.get("messages") or examples.get("conversations") or examples.get("texts")
)
@@ -177,20 +171,20 @@ def convert_chatml_to_alpaca(
output = ""
for msg in convo:
- # Handle both standard and ShareGPT formats
+ # Standard and ShareGPT key names
role = msg.get("role") or msg.get("from")
content = msg.get("content") or msg.get("value")
- # Get first user message as instruction
+ # First user message -> instruction
if role in ["user", "human", "input"] and not instruction:
instruction = content
- # Get first assistant message as output
+ # First assistant message -> output
elif role in ["assistant", "gpt", "output"] and not output:
output = content
break # Stop after first assistant response
instructions.append(instruction)
- inputs.append("") # Alpaca typically has empty input
+ inputs.append("") # Alpaca input usually empty
outputs.append(output)
return {"instruction": instructions, "input": inputs, "output": outputs}
@@ -220,9 +214,9 @@ def convert_alpaca_to_chatml(
num_proc = None,
):
"""
- Converts Alpaca format to ChatML format.
+ Convert Alpaca format to ChatML format.
- Output format: Uses 'conversations' column with standard 'role'/'content' structure.
+ Output: 'conversations' column with standard 'role'/'content' dicts.
"""
try:
from torch.utils.data import IterableDataset
@@ -238,13 +232,12 @@ def convert_alpaca_to_chatml(
input_text = examples.get("input", [""] * len(examples["instruction"]))[i]
output = examples["output"][i]
- # Combine instruction and input (if exists) for user message
+ # User message = instruction + input (if any)
if input_text and input_text.strip():
user_content = f"{instruction}\n\n{input_text}".strip()
else:
user_content = instruction
- # Build conversation in standard ChatML format
convo = [
{"role": "user", "content": user_content},
{"role": "assistant", "content": output},
@@ -294,17 +287,17 @@ def convert_to_vlm_format(
progress_callback = None,
):
"""
- Converts simple {image, text} format to VLM messages format.
+ Convert simple {image, text} format to VLM messages format.
Returns a LIST, not a HuggingFace Dataset (to preserve PIL Images).
- For URL-based image datasets, runs a 200-sample parallel probe first to
- estimate download speed and failure rate, then reports time estimate or
- warning through progress_callback before proceeding with the full conversion.
+ For URL-based image datasets, runs a 200-sample parallel probe first
+ to estimate download speed and failure rate, reporting a time
+ estimate or warning via progress_callback before the full conversion.
Args:
- progress_callback: Optional callable(status_message=str) to report
- progress to the training overlay.
+ progress_callback: Optional callable(status_message=str) to
+ report progress to the training overlay.
Returns:
list: List of dicts with 'messages' field
@@ -313,11 +306,11 @@ def convert_to_vlm_format(
from .vlm_processing import generate_smart_vlm_instruction
def _notify(msg):
- """Send status update to the training overlay if callback is available."""
+ """Send a status update to the training overlay if callback set."""
if progress_callback:
progress_callback(status_message = msg)
- # Generate smart instruction if not provided
+ # Generate a smart instruction if none provided
if instruction is None:
instruction_info = generate_smart_vlm_instruction(
dataset,
@@ -342,7 +335,7 @@ def convert_to_vlm_format(
def _convert_single_sample(sample):
"""Convert a single sample to VLM format."""
- # Get image (might be PIL Image, local path, URL, or bare filename)
+ # Image may be a PIL Image, local path, URL, or bare filename
image_data = sample[image_column]
if isinstance(image_data, str):
@@ -363,19 +356,18 @@ def convert_to_vlm_format(
else:
image_data = Image.open(image_data).convert("RGB")
- # Get text (if list of strings, pick a random one — e.g. multiple captions)
+ # Text: if a list (e.g. multiple captions), pick one at random
text_data = sample[text_column]
if isinstance(text_data, list) and len(text_data) > 0:
import random
text_data = random.choice(text_data)
- # Get instruction (static or dynamic)
+ # Instruction: static or dynamic
if uses_dynamic and instruction_column:
current_instruction = sample[instruction_column]
else:
current_instruction = instruction
- # Build VLM messages - simple structure
messages = [
{
"role": "user",
@@ -387,16 +379,15 @@ def convert_to_vlm_format(
{"role": "assistant", "content": [{"type": "text", "text": text_data}]},
]
- # Return dict with messages
return {"messages": messages}
total = len(dataset)
first_image = next(iter(dataset))[image_column]
has_urls = isinstance(first_image, str) and first_image.startswith(("http://", "https://"))
- # ── Bare-filename detection: images stored as filenames (e.g. "img_001.png")
- # that don't exist locally. Build a basename→repo_path lookup so we can
- # resolve them via hf_hub_download during conversion.
+ # ── Bare-filename detection: images stored as filenames (e.g.
+ # "img_001.png") not present locally. Build a basename→repo_path
+ # lookup to resolve them via hf_hub_download during conversion.
_image_lookup = None
_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff")
if (
@@ -431,7 +422,7 @@ def convert_to_vlm_format(
logger.info(f"⚠️ Failed to build HF repo image lookup: {e}")
_image_lookup = None
- # ── URL probe: 200 samples with parallel workers to estimate speed + failure rate ──
+ # ── URL probe: 200 parallel samples to estimate speed + failure rate ──
PROBE_SIZE = 200
MAX_FAIL_RATE = 0.3
@@ -468,7 +459,7 @@ def convert_to_vlm_format(
f"{fail_rate:.0%} of the first {PROBE_SIZE} image URLs failed to download ({probe_fail}/{probe_total})",
"Images are external URLs, not embedded in the dataset",
]
- # Try LLM-friendly warning
+ # LLM-friendly warning
friendly = None
try:
from .llm_assist import llm_generate_dataset_warning
@@ -490,7 +481,7 @@ def convert_to_vlm_format(
_notify(msg)
raise ValueError(msg)
- # Estimate total time for remaining samples
+ # Estimate time for remaining samples
remaining = total - PROBE_SIZE
estimated_seconds = remaining / throughput if throughput > 0 else 0
eta_str = _format_eta(estimated_seconds)
@@ -546,7 +537,7 @@ def convert_to_vlm_format(
converted_list.extend(r for r in batch_results if r is not None)
- # Progress update every batch
+ # Per-batch progress update
elapsed = time.time() - start_time
done = batch_end
rate = done / elapsed if elapsed > 0 else 0
@@ -558,7 +549,7 @@ def convert_to_vlm_format(
)
_notify(progress_msg)
else:
- # Sequential conversion for local/embedded images (fast, no I/O bottleneck)
+ # Sequential conversion for local/embedded images (no I/O bottleneck)
pbar = tqdm(dataset, total = total, desc = "Converting VLM samples", unit = "sample")
for sample in pbar:
try:
@@ -576,7 +567,7 @@ def convert_to_vlm_format(
logger.info(
f"⚠️ Skipped {failed_count}/{total} ({fail_rate:.0%}) samples with broken/unreachable images"
)
- # For datasets that skipped the probe (small URL datasets), check fail rate now
+ # Small URL datasets skip the probe; check fail rate here
if has_urls and fail_rate >= MAX_FAIL_RATE:
issues = [
f"{fail_rate:.0%} of images failed to download ({failed_count}/{total})",
@@ -629,7 +620,7 @@ def convert_to_vlm_format(
logger.info(f"✅ Converted {len(converted_list)}/{total} samples")
_notify(f"Converted {len(converted_list):,}/{total:,} images successfully")
- # Return list, NOT Dataset
+ # Return list, NOT a Dataset
return converted_list
@@ -641,8 +632,8 @@ def convert_sharegpt_with_images_to_vlm_format(
progress_callback = None,
):
"""
- Converts ShareGPT/ChatML datasets that have a separate image column and
- ``<image>`` placeholders inside the conversation text.
+ Convert ShareGPT/ChatML datasets with a separate image column and
+ ``<image>`` placeholders in the conversation text.
Example input::
@@ -672,7 +663,7 @@ def convert_sharegpt_with_images_to_vlm_format(
if progress_callback:
progress_callback(status_message = msg)
- # ── Resolve image loading strategy (same 3-tier as convert_to_vlm_format) ──
+ # ── Resolve image loading (same 3-tier as convert_to_vlm_format) ──
total = len(dataset)
first_image = next(iter(dataset))[image_column]
@@ -696,7 +687,7 @@ def convert_sharegpt_with_images_to_vlm_format(
for f in repo_files
if any(f.lower().endswith(ext) for ext in _IMAGE_EXTS)
}
- # Also add the full relative paths as keys (for paths like "sam/images/sa_545504.jpg")
+ # Also key by full relative path (e.g. "sam/images/sa_545504.jpg")
for f in repo_files:
if any(f.lower().endswith(ext) for ext in _IMAGE_EXTS):
_image_lookup[f] = f
@@ -714,7 +705,7 @@ def convert_sharegpt_with_images_to_vlm_format(
_image_lookup = None
def _resolve_image(image_data):
- """Resolve image data to a PIL Image object."""
+ """Resolve image data to a PIL Image."""
if hasattr(image_data, "size") and hasattr(image_data, "mode"):
return image_data # Already PIL
if isinstance(image_data, str):
@@ -742,7 +733,7 @@ def convert_sharegpt_with_images_to_vlm_format(
raise ValueError(f"Cannot resolve image: {type(image_data)}")
def _convert_single_sample(sample):
- """Convert a single ShareGPT+image sample to standard VLM format."""
+ """Convert one ShareGPT+image sample to standard VLM format."""
pil_image = _resolve_image(sample[image_column])
conversation = sample[messages_column]
@@ -752,7 +743,7 @@ def convert_sharegpt_with_images_to_vlm_format(
role = _ROLE_MAP.get(role_raw.lower(), role_raw.lower())
text = msg.get("value") or msg.get("content") or ""
- # Split on <image> to interleave text and image content blocks
+ # Interleave text and image blocks around <image>
if "<image>" in text:
parts = text.split("<image>")
content = []
@@ -762,7 +753,7 @@ def convert_sharegpt_with_images_to_vlm_format(
content.append({"type": "text", "text": part})
if i < len(parts) - 1:
content.append({"type": "image", "image": pil_image})
- # If <image> was the entire text, content might just be the image
+ # If text was only <image>, content is just the image
if not content:
content.append({"type": "image", "image": pil_image})
else:
@@ -804,7 +795,7 @@ def convert_sharegpt_with_images_to_vlm_format(
def convert_llava_to_vlm_format(dataset):
"""
- Converts Llava format to standard VLM format.
+ Convert Llava format to standard VLM format.
Llava format:
- messages: [{'content': [{'type': 'image', 'index': 0}, {'type': 'text', 'text': '...'}]}]
@@ -818,23 +809,22 @@ def convert_llava_to_vlm_format(dataset):
logger.info(f"🔄 Converting {len(dataset)} samples from Llava format to standard VLM format...")
def _convert_single_sample(sample):
- """Convert a single llava sample to standard VLM format."""
+ """Convert one llava sample to standard VLM format."""
messages = sample["messages"]
images = sample.get("images", [])
- # Process each message
new_messages = []
for msg in messages:
new_content = []
for item in msg["content"]:
if item["type"] == "image":
- # Replace index with actual PIL image
+ # Replace index with the actual PIL image
if "index" in item and item["index"] is not None:
img_idx = item["index"]
if img_idx < len(images):
pil_image = images[img_idx]
- # Ensure it's PIL
+ # Ensure PIL
if isinstance(pil_image, str):
pil_image = Image.open(pil_image).convert("RGB")
@@ -845,7 +835,7 @@ def convert_llava_to_vlm_format(dataset):
}
)
else:
- # No index, try to use first image
+ # No index: use the first image
if len(images) > 0:
pil_image = images[0]
if isinstance(pil_image, str):
@@ -854,14 +844,12 @@ def convert_llava_to_vlm_format(dataset):
new_content.append({"type": "image", "image": pil_image})
elif item["type"] == "text":
- # Keep text as-is (only type + text)
new_content.append({"type": "text", "text": item.get("text", "")})
new_messages.append({"role": msg["role"], "content": new_content})
return {"messages": new_messages}
- # Convert using list comprehension
converted_list = [_convert_single_sample(sample) for sample in dataset]
logger.info(f"✅ Converted {len(converted_list)} samples")
diff --git a/studio/backend/utils/datasets/format_detection.py b/studio/backend/utils/datasets/format_detection.py
index 829838064a1..72f8f48cf75 100644
--- a/studio/backend/utils/datasets/format_detection.py
+++ b/studio/backend/utils/datasets/format_detection.py
@@ -1,11 +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
-"""
-Format detection utilities for dataset processing.
+"""Format detection utilities for dataset processing.
-This module contains functions for detecting dataset formats (Alpaca, ShareGPT, ChatML),
-detecting multimodal/VLM dataset structures, and heuristic-based column mapping.
+Detects dataset formats (Alpaca, ShareGPT, ChatML), multimodal/VLM
+structures, and heuristic column mapping.
"""
import re
@@ -17,8 +16,7 @@ def _keyword_in_column(keyword: str, col_name: str) -> bool:
def detect_dataset_format(dataset):
- """
- Detects dataset format by inspecting structure.
+ """Detect dataset format by inspecting structure.
Returns:
dict: {
@@ -30,7 +28,7 @@ def detect_dataset_format(dataset):
"""
column_names = set(next(iter(dataset)).keys())
- # Check for Alpaca
+ # Alpaca
alpaca_columns = {"instruction", "output"}
if alpaca_columns.issubset(column_names):
return {
@@ -40,7 +38,7 @@ def detect_dataset_format(dataset):
"sample_keys": [],
}
- # Check for chat-based formats (messages or conversations)
+ # Chat-based formats (messages or conversations)
chat_column = None
if "messages" in column_names:
chat_column = "messages"
@@ -50,7 +48,7 @@ def detect_dataset_format(dataset):
chat_column = "texts"
if chat_column:
- # Inspect the structure to determine if ShareGPT or ChatML
+ # Inspect structure: ShareGPT or ChatML?
try:
sample = next(iter(dataset))
chat_data = sample[chat_column]
@@ -77,7 +75,7 @@ def detect_dataset_format(dataset):
"sample_keys": list(msg_keys),
}
- # Unknown structure but has chat column
+ # Has chat column but unknown structure
else:
return {
"format": "unknown",
@@ -104,8 +102,7 @@ def detect_dataset_format(dataset):
def detect_custom_format_heuristic(dataset):
- """
- Smart detection with priority scoring.
+ """Detection with priority scoring.
Strategy for ambiguous keywords like 'task':
1. Detect assistant first (unambiguous)
@@ -159,7 +156,7 @@ def detect_custom_format_heuristic(dataset):
"persona",
"role",
"template",
- "task", # Also in system
+ "task", # also a system keyword
]
# Metadata columns to ignore
@@ -197,7 +194,7 @@ def detect_custom_format_heuristic(dataset):
}
def has_keyword(col_name, keywords):
- """Check if any keyword appears in column name."""
+ """True if any keyword appears in the column name."""
col_lower = col_name.lower()
col_normalized = col_lower.replace("_", "").replace("-", "").replace(" ", "")
@@ -207,7 +204,7 @@ def detect_custom_format_heuristic(dataset):
return False
def is_metadata(col_name):
- """Check if column is likely metadata."""
+ """True if the column is likely metadata."""
col_lower = col_name.lower()
if col_lower in metadata_exact_match:
@@ -229,7 +226,7 @@ def detect_custom_format_heuristic(dataset):
return False
def get_priority_score(col_name):
- """Calculate priority score based on column name patterns."""
+ """Priority score from column-name patterns."""
col_lower = col_name.lower()
score = 0
@@ -240,7 +237,7 @@ def detect_custom_format_heuristic(dataset):
return score
def get_content_length(col_name):
- """Get average content length for this column."""
+ """Average content length for this column."""
try:
if col_name in sample and sample[col_name]:
content = str(sample[col_name])
@@ -250,7 +247,7 @@ def detect_custom_format_heuristic(dataset):
return 0
def score_column(col_name, keywords, role_type, num_candidates):
- """Score a column for how likely it is to be a particular role."""
+ """Score how likely a column is to be a given role."""
if not has_keyword(col_name, keywords):
return 0
@@ -260,7 +257,7 @@ def detect_custom_format_heuristic(dataset):
# Penalize ambiguous keywords when scoring for user
if role_type == "user":
col_lower = col_name.lower()
- # If column is ONLY "task" (or task_xxx), give it lower priority for user role
+ # ONLY "task" (or task_xxx): lower priority for user role
if "task" in col_lower and not any(kw in col_lower for kw in user_words_high_priority):
score -= 15 # Significant penalty so other user columns win
@@ -289,10 +286,10 @@ def detect_custom_format_heuristic(dataset):
return score
- # Filter out metadata columns
+ # Drop metadata columns
content_columns = [col for col in all_columns if not is_metadata(col)]
- # Count candidates first
+ # Count candidates
assistant_potential = [col for col in content_columns if has_keyword(col, assistant_words)]
user_potential = [col for col in content_columns if has_keyword(col, user_words)]
@@ -332,7 +329,7 @@ def detect_custom_format_heuristic(dataset):
system_col = None
for col in remaining_columns:
if has_keyword(col, system_words):
- # Found a system match in remaining columns
+ # System match found
mapping[col] = "system"
system_col = col
break
@@ -344,17 +341,17 @@ def detect_custom_format_heuristic(dataset):
if len(remaining_columns) >= 1:
remaining_col = remaining_columns[0]
- # If no strong keyword match, decide based on what's missing
+ # No strong keyword match: decide by what's missing
if not has_keyword(remaining_col, user_words + assistant_words):
mapping[remaining_col] = "system"
elif user_col is None:
- # No user column yet, assign this as user
+ # No user column yet: assign this as user
mapping[remaining_col] = "user"
else:
- # Already have user + assistant, treat as system context
+ # Already have user + assistant: treat as system context
mapping[remaining_col] = "system"
- # VALIDATION: Ensure we have at least user + assistant
+ # Ensure we have at least user + assistant
has_user = any(role == "user" for role in mapping.values())
has_assistant = any(role == "assistant" for role in mapping.values())
@@ -372,12 +369,11 @@ def detect_custom_format_heuristic(dataset):
def detect_multimodal_dataset(dataset):
- """
- Detects if dataset contains multimodal data (images and/or audio).
+ """Detect multimodal data (images and/or audio) in a dataset.
- Two-pass approach for each modality:
- 1. Column-name heuristic (fast): checks for keywords.
- 2. Value-type inspection (reliable): checks actual sample values.
+ Two passes per modality:
+ 1. Column-name heuristic (fast): keyword match.
+ 2. Value-type inspection (reliable): check actual sample values.
Returns:
dict: {
@@ -393,7 +389,7 @@ def detect_multimodal_dataset(dataset):
sample = next(iter(dataset))
column_names = list(sample.keys())
- # Keywords that indicate image data
+ # Image keywords
image_keywords = [
"image",
"img",
@@ -414,7 +410,7 @@ def detect_multimodal_dataset(dataset):
"filename",
]
- # Keywords that indicate audio data
+ # Audio keywords
audio_keywords = ["audio", "speech", "wav", "waveform", "sound"]
multimodal_columns = []
@@ -422,8 +418,8 @@ def detect_multimodal_dataset(dataset):
modality_types = set()
# ── Image detection ─────────────────────────────────────
- # Pass 1: column-name heuristic (word-boundary match to avoid
- # false positives like 'pic' in 'topic')
+ # Pass 1: column-name heuristic (word-boundary match avoids false
+ # positives like 'pic' in 'topic')
for col_name in column_names:
for keyword in image_keywords:
if _keyword_in_column(keyword, col_name):
@@ -460,13 +456,13 @@ def detect_multimodal_dataset(dataset):
audio_columns.append(col_name)
modality_types.add("audio")
- # Filter out columns that are actually audio from the image list
- # (e.g. a column named "audio" with {"bytes", "path"} could match _is_image_value)
+ # Drop audio columns from the image list (e.g. a column named "audio"
+ # with {"bytes", "path"} could match _is_image_value)
if audio_columns:
audio_set = set(audio_columns)
multimodal_columns = [c for c in multimodal_columns if c not in audio_set]
- # Detect text column for audio datasets
+ # Text column for audio datasets
detected_text_col = None
if audio_columns:
text_keywords = ["text", "sentence", "transcript", "transcription", "label"]
@@ -477,7 +473,7 @@ def detect_multimodal_dataset(dataset):
is_audio = len(audio_columns) > 0
- # Detect speaker_id column for TTS datasets (CSM, Orpheus, Spark)
+ # speaker_id column for TTS datasets (CSM, Orpheus, Spark)
detected_speaker_col = None
if audio_columns:
speaker_keywords = ["source", "speaker", "speaker_id"]
@@ -511,14 +507,13 @@ def _is_image_value(value) -> bool:
except ImportError:
pass
- # HF datasets Image feature stores decoded images as PIL or dicts with
- # {"bytes": b"...", "path": "..."} when not yet decoded.
+ # HF Image feature: decoded as PIL, or {"bytes", "path"} when undecoded.
# Exclude audio dicts (decoded audio has "array" + "sampling_rate").
if isinstance(value, dict):
if "array" in value and "sampling_rate" in value:
- return False # This is audio, not image
+ return False # audio, not image
if "bytes" in value and "path" in value:
- # Check path extension to exclude audio files
+ # Use path extension to exclude audio files
path = value.get("path") or ""
if isinstance(path, str) and any(
path.lower().endswith(ext) for ext in _AUDIO_EXTENSIONS
@@ -539,7 +534,7 @@ def _is_image_value(value) -> bool:
lower.split("?")[0].endswith(ext) for ext in _IMAGE_EXTS
):
return True
- # Image file path (relative or absolute path ending in image extension)
+ # Image file path (relative or absolute)
if any(lower.endswith(ext) for ext in _IMAGE_EXTS):
return True
@@ -564,11 +559,11 @@ def _is_audio_value(value) -> bool:
if value is None:
return False
- # HF datasets Audio feature: decoded → {"array": np.ndarray, "sampling_rate": int}
+ # HF Audio feature: decoded → {"array": np.ndarray, "sampling_rate": int}
if isinstance(value, dict):
if "array" in value and "sampling_rate" in value:
return True
- # Undecoded/streaming → {"bytes": b"...", "path": "some.wav"}
+ # Undecoded/streaming → {"bytes", "path": "some.wav"}
if "bytes" in value or "path" in value:
path = value.get("path") or ""
if isinstance(path, str) and any(
@@ -602,9 +597,8 @@ def _has_image_header(data: bytes) -> bool:
def detect_vlm_dataset_structure(dataset):
- """
- Detects if VLM dataset is:
- - Standard VLM messages format (image objects in content)
+ """Detect which VLM dataset shape this is:
+ - Standard VLM messages (image objects in content)
- Llava format (image indices + separate images column)
- Simple format needing conversion (image + text columns)
"""
@@ -621,7 +615,7 @@ def detect_vlm_dataset_structure(dataset):
column_names = set(sample.keys())
- # Check if has messages column
+ # Has messages column?
if "messages" in column_names:
messages = sample["messages"]
@@ -632,7 +626,7 @@ def detect_vlm_dataset_structure(dataset):
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "type" in content[0]:
- # Check for llava format
+ # Llava format?
has_index = any(
"index" in item for item in content if isinstance(item, dict)
)
@@ -660,8 +654,8 @@ def detect_vlm_dataset_structure(dataset):
"text_column": None,
}
- # Check for ShareGPT/ChatML conversations with <image> placeholder + companion image column
- # (e.g. Lin-Chen/ShareGPT4V, LLaVA-style datasets)
+ # ShareGPT/ChatML conversations with <image> placeholder + companion
+ # image column (e.g. Lin-Chen/ShareGPT4V, LLaVA-style datasets)
for chat_col in ("conversations", "messages"):
if chat_col not in column_names:
continue
@@ -671,11 +665,11 @@ def detect_vlm_dataset_structure(dataset):
first_msg = chat_data[0]
if not isinstance(first_msg, dict):
continue
- # Detect ShareGPT (from/value) or ChatML (role/content) keys
+ # ShareGPT (from/value) or ChatML (role/content) keys
msg_text = first_msg.get("value") or first_msg.get("content")
if not isinstance(msg_text, str):
continue
- # Check for <image> placeholder anywhere in the conversation
+ # <image> placeholder anywhere in the conversation?
has_image_placeholder = any(
"<image>" in str(m.get("value", "") or m.get("content", ""))
for m in chat_data
@@ -700,9 +694,7 @@ def detect_vlm_dataset_structure(dataset):
"messages_column": chat_col,
}
- # Find image and text columns using metadata filtering
-
- # Define metadata patterns to EXCLUDE
+ # Find image and text columns, filtering out metadata patterns
metadata_patterns = {
"suffixes": [
"_id",
@@ -726,7 +718,7 @@ def detect_vlm_dataset_structure(dataset):
],
}
- # Image-related keywords
+ # Image keywords
image_keywords = [
"image",
"img",
@@ -739,7 +731,7 @@ def detect_vlm_dataset_structure(dataset):
"filename",
]
- # Text-related keywords
+ # Text keywords
text_keywords = [
"text",
"caption",
@@ -752,14 +744,14 @@ def detect_vlm_dataset_structure(dataset):
]
def is_metadata_column(col_name):
- """Check if column name looks like metadata."""
+ """True if the column name looks like metadata."""
col_lower = col_name.lower()
- # Check suffixes
+ # Suffixes
if any(col_lower.endswith(suffix) for suffix in metadata_patterns["suffixes"]):
return True
- # Check prefixes
+ # Prefixes
if any(col_lower.startswith(prefix) for prefix in metadata_patterns["prefixes"]):
return True
@@ -767,16 +759,16 @@ def detect_vlm_dataset_structure(dataset):
def _score_image_candidate(col, sample_value):
"""Score a candidate image column by how resolvable its value is."""
- # PIL Image object (highest priority - already loaded)
+ # PIL Image object (already loaded -> highest)
if hasattr(sample_value, "size") and hasattr(sample_value, "mode"):
return 100
- # Dict with image data (bytes/path from HF Image feature)
+ # Dict with bytes/path from HF Image feature
if isinstance(sample_value, dict) and ("bytes" in sample_value or "path" in sample_value):
return 75
if isinstance(sample_value, str):
- # URL strings
+ # URL
if sample_value.startswith(("http://", "https://")):
return 70 if not is_metadata_column(col) else 55
# Bare file path
@@ -787,8 +779,8 @@ def detect_vlm_dataset_structure(dataset):
return 0
def _probe_image_candidate(col, sample_value):
- """Quick probe to check if an image candidate is actually reachable.
- Returns True if likely valid, False if definitely broken."""
+ """Probe whether an image candidate is reachable.
+ True if likely valid, False if definitely broken."""
import os
# PIL / dict — already loaded, always valid
@@ -799,7 +791,7 @@ def detect_vlm_dataset_structure(dataset):
if not sample_value.startswith(("http://", "https://")):
return os.path.exists(sample_value) # bare filenames return False here, that's OK
- # URL — quick HEAD request with short timeout
+ # URL — quick HEAD with short timeout
try:
import urllib.request
@@ -810,8 +802,8 @@ def detect_vlm_dataset_structure(dataset):
return False
def find_image_column():
- """Find image column by keyword match + value-based fallback.
- When multiple candidates exist, probes them to find one that works."""
+ """Find image column by keyword match + value-based fallback,
+ probing candidates to find one that works."""
candidates = []
# Pass 1: keyword-matched columns
@@ -822,8 +814,8 @@ def detect_vlm_dataset_structure(dataset):
if score > 0:
candidates.append((col, score))
- # Pass 2: value-based fallback — find columns with image URLs/paths
- # even if the column name doesn't match image keywords
+ # Pass 2: value-based fallback — columns with image URLs/paths
+ # even if the name doesn't match image keywords
already = {c[0] for c in candidates}
for col in column_names:
if col in already:
@@ -831,7 +823,7 @@ def detect_vlm_dataset_structure(dataset):
sample_value = sample[col]
if _is_image_value(sample_value):
score = _score_image_candidate(col, sample_value)
- # Slightly penalise non-keyword columns so keyword matches win on ties
+ # Penalise non-keyword columns so keyword matches win on ties
candidates.append((col, max(score - 5, 1)))
if not candidates:
@@ -839,48 +831,47 @@ def detect_vlm_dataset_structure(dataset):
candidates.sort(key = lambda x: x[1], reverse = True)
- # Single candidate or top candidate is PIL/dict — no probing needed
+ # Single candidate or top is PIL/dict — no probing needed
if len(candidates) == 1 or candidates[0][1] >= 75:
return candidates[0][0]
- # Multiple string-based candidates — probe to find one that actually works
+ # Multiple string candidates — probe for one that works
for col, score in candidates:
sample_value = sample[col]
if _probe_image_candidate(col, sample_value):
return col
- # Nothing probed successfully — return highest-scored anyway and let
- # conversion handle the error (it may still resolve via hf_hub_download)
+ # None probed OK — return highest-scored and let conversion handle
+ # the error (it may still resolve via hf_hub_download)
return candidates[0][0]
def find_text_column():
- """Find text column by filtering out metadata and checking keywords."""
+ """Find text column: skip metadata, match keywords."""
candidates = []
for col in column_names:
- # Skip metadata columns
if is_metadata_column(col):
continue
- # Check if contains text keywords (word-boundary match)
+ # Text keyword (word-boundary match)
if any(_keyword_in_column(keyword, col) for keyword in text_keywords):
# Verify it's actually text
sample_value = sample[col]
if isinstance(sample_value, str) and len(sample_value) > 0:
- # Longer text = higher priority (likely content, not just a label)
- priority = min(len(sample_value), 1000) # Cap at 1000
+ # Longer text = higher priority (content, not a label)
+ priority = min(len(sample_value), 1000) # cap at 1000
candidates.append((col, priority))
elif (
isinstance(sample_value, list)
and len(sample_value) > 0
and isinstance(sample_value[0], str)
):
- # List of strings (e.g. captions list) — lower priority than plain strings
+ # List of strings (e.g. captions) — lower priority than plain str
priority = min(len(sample_value[0]), 1000) // 2
candidates.append((col, priority))
- # Return highest priority candidate
+ # Highest-priority candidate
if candidates:
candidates.sort(key = lambda x: x[1], reverse = True)
return candidates[0][0]
diff --git a/studio/backend/utils/datasets/llm_assist.py b/studio/backend/utils/datasets/llm_assist.py
index 10004ce3dbe..d6bb0dc91d0 100644
--- a/studio/backend/utils/datasets/llm_assist.py
+++ b/studio/backend/utils/datasets/llm_assist.py
@@ -4,13 +4,13 @@
"""
LLM-assisted dataset analysis using an ephemeral GGUF helper model.
-Complements heuristic-based detection in format_detection.py and
-vlm_processing.py. Only invoked when heuristics are uncertain.
+Complements heuristic detection in format_detection.py and vlm_processing.py.
+Only invoked when heuristics are uncertain.
Architecture:
- Instantiates LlamaCppBackend, loads model, runs completion(s), unloads.
- Not kept warm — VRAM is freed immediately after use.
- - Gracefully degrades: returns None when unavailable (no binary, OOM, disabled).
+ - Degrades gracefully: returns None when unavailable (no binary, OOM, disabled).
"""
import json
@@ -35,20 +35,19 @@ README_MAX_CHARS = 1500
def _strip_think_tags(text: str) -> str:
"""Strip <think>...</think> reasoning blocks emitted by some models.
- If the model places its actual answer OUTSIDE the think block, we
- discard the think block and keep the rest. If the entire response
- is INSIDE a think block (nothing useful outside), we extract and
- return the inner content instead of discarding everything.
+ If the answer is OUTSIDE the think block, discard the block and keep the
+ rest. If the entire response is INSIDE a think block (nothing useful
+ outside), return the inner content instead of discarding everything.
"""
if "<think>" not in text:
return text
- # Try stripping think blocks — keep content outside them
+ # Strip think blocks — keep content outside them
stripped = re.sub(r"<think>.*?</think>\s*", "", text, flags = re.DOTALL).strip()
if stripped:
return stripped
- # Everything was inside <think> tags — extract the inner content of the last block
+ # Everything was inside <think> tags — return the last block's inner content
matches = re.findall(r"<think>(.*?)</think>", text, flags = re.DOTALL)
if matches:
return matches[-1].strip()
@@ -60,9 +59,9 @@ def precache_helper_gguf():
"""
Pre-download the helper GGUF to HF cache.
- Called on FastAPI startup in a background thread so subsequent
+ Called on FastAPI startup in a background thread so later
``_run_with_helper()`` calls skip the download and only pay for
- llama-server startup. No-op if already cached or disabled.
+ llama-server startup. No-op if already cached or disabled.
"""
if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):
return
@@ -82,7 +81,7 @@ def precache_helper_gguf():
files = api.list_repo_files(repo, repo_type = "model")
gguf_files = [f for f in files if f.endswith(".gguf")]
- # Find all GGUF files matching the variant (may be split into shards)
+ # All GGUF files matching the variant (may be split into shards)
variant_lower = variant.lower().replace("-", "_")
matching = sorted(f for f in gguf_files if variant_lower in f.lower().replace("-", "_"))
@@ -150,7 +149,7 @@ def _run_with_helper(prompt: str, max_tokens: int = 256) -> Optional[str]:
):
if isinstance(chunk, dict):
continue # skip metadata events
- cumulative = chunk # cumulative — last value is full text
+ cumulative = chunk # cumulative; last value is full text
result = cumulative.strip()
result = _strip_think_tags(result)
@@ -181,8 +180,8 @@ def llm_generate_vlm_instruction(
"""
Ask a helper LLM to generate a task-specific VLM instruction.
- Called when heuristic instruction generation returns low confidence
- or falls back to generic.
+ Called when heuristic instruction generation returns low confidence or
+ falls back to generic.
Args:
column_names: Column names in the dataset.
@@ -218,9 +217,9 @@ def llm_generate_vlm_instruction(
if not result:
return None
- # Clean up: strip quotes, ensure it's a single sentence
+ # Strip quotes; ensure a single sentence
instruction = result.strip().strip('"').strip("'").strip()
- # Reject obviously bad outputs (too short, too long, or multi-line)
+ # Reject bad outputs (too short, too long, or multi-line)
if len(instruction) < 10 or len(instruction) > 200 or "\n" in instruction:
logger.warning(f"Helper model returned unusable instruction: {instruction!r}")
return None
@@ -243,8 +242,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Option
samples: 3-5 sample rows with values truncated to 200 chars.
Returns:
- Dict mapping column_name → role ("user"|"assistant"|"system"|"metadata"),
- or None on failure.
+ Dict mapping column_name → role ("user"|"assistant"|"system"|"metadata"), or None.
"""
formatted = ""
for i, row in enumerate(samples[:5], 1):
@@ -281,7 +279,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Option
try:
mapping = json.loads(text)
except json.JSONDecodeError:
- # Try to find JSON object in the response
+ # Find a JSON object in the response
import re
match = re.search(r"\{[^}]+\}", text)
if match:
@@ -324,7 +322,7 @@ def llm_generate_dataset_warning(
column_names: Optional[list[str]] = None,
) -> Optional[str]:
"""
- Ask the helper LLM to turn technical dataset issues into a user-friendly warning.
+ Ask the helper LLM to turn technical dataset issues into a friendly warning.
Works for all modalities (text, vision, audio).
@@ -359,7 +357,7 @@ def llm_generate_dataset_warning(
return None
warning = result.strip()
- # Reject obviously bad outputs
+ # Reject bad outputs
if len(warning) < 10 or len(warning) > 500:
return None
@@ -489,7 +487,7 @@ def _run_multi_pass_advisor(
"""
Multi-pass LLM analysis: classify → convert → validate.
- Keeps model loaded across all passes. Returns combined result dict or None.
+ Keeps the model loaded across passes. Returns combined result dict or None.
"""
if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):
return None
@@ -619,7 +617,7 @@ def _run_multi_pass_advisor(
logger.warning(f"Advisor Pass 1 failed to produce JSON: {raw1[:200]}")
return None
- # If dataset is already conversational, skip passes 2-3
+ # Already conversational: skip passes 2-3
if pass1.get("is_conversational") and not pass1.get("needs_conversion"):
return {
"success": True,
@@ -724,7 +722,7 @@ def _run_multi_pass_advisor(
column_roles = pass2.get("column_roles", {})
label_map = pass2.get("label_mapping") or {} # may be null
- # Validate: must have at least one user AND one assistant
+ # Must have at least one user AND one assistant
roles_present = set(column_roles.values())
if "user" not in roles_present or "assistant" not in roles_present:
logger.warning(f"Pass 2 sanity fail: missing user or assistant role: {column_roles}")
@@ -739,7 +737,7 @@ def _run_multi_pass_advisor(
logger.info("Pass 3: Generating system prompt...")
t3 = time.monotonic()
- # Format label mapping info for the prompt
+ # Format label mapping for the prompt
label_info = ""
if label_map:
for col, mapping in label_map.items():
@@ -782,12 +780,12 @@ def _run_multi_pass_advisor(
)
if raw3:
- # Pass 3 returns raw text, not JSON — clean it up
+ # Pass 3 returns raw text, not JSON — clean it
cleaned = raw3.strip().strip('"').strip("'").strip()
if len(cleaned) >= 20 and cleaned.lower() not in ("null", "none", ""):
sys_prompt = cleaned
- # Build suggested_mapping (column → role, for the frontend dropdowns)
+ # Build suggested_mapping (column → role) for the frontend dropdowns
suggested_mapping = {}
for col, role in column_roles.items():
if col in columns and role in ("user", "assistant", "system"):
@@ -855,7 +853,7 @@ def llm_conversion_advisor(
if dataset_name and "/" in dataset_name:
dataset_card, dataset_metadata = fetch_hf_dataset_card(dataset_name, hf_token)
- # Try multi-pass advisor
+ # Try the multi-pass advisor
result = _run_multi_pass_advisor(
columns = column_names,
samples = samples,
diff --git a/studio/backend/utils/datasets/model_mappings.py b/studio/backend/utils/datasets/model_mappings.py
index eb2e5482c9a..b550dc81bd8 100644
--- a/studio/backend/utils/datasets/model_mappings.py
+++ b/studio/backend/utils/datasets/model_mappings.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
-"""
-Model and template mappings for dataset processing.
+"""Model and template mappings for dataset processing.
-This module contains the mapping dictionaries that associate model names
-with their corresponding chat templates and response markers.
+Maps model names to their chat templates and response markers.
"""
TEMPLATE_TO_MODEL_MAPPER = {
@@ -445,8 +443,8 @@ for key, values in TEMPLATE_TO_MODEL_MAPPER.items():
def is_gpt_oss_model_name(name: str) -> bool:
"""Name-based check for gpt-oss / harmony models.
- Used by both the in-process backend and the parent-process
- orchestrator to detect harmony models without an IPC round-trip.
+ Used by the in-process backend and the parent orchestrator to detect
+ harmony models without an IPC round-trip.
"""
name = (name or "").lower()
if not name:
diff --git a/studio/backend/utils/datasets/vlm_processing.py b/studio/backend/utils/datasets/vlm_processing.py
index a0f1fd9f993..4919b8884d0 100644
--- a/studio/backend/utils/datasets/vlm_processing.py
+++ b/studio/backend/utils/datasets/vlm_processing.py
@@ -4,8 +4,8 @@
"""
VLM (Vision-Language Model) processing utilities.
-This module contains functions for generating smart instructions
-for VLM datasets based on content analysis and heuristics.
+Generates smart instructions for VLM datasets via content analysis and
+heuristics.
"""
import re
@@ -19,19 +19,19 @@ def generate_smart_vlm_instruction(
dataset_name = None,
):
"""
- Generate smart, context-aware instruction for VLM datasets using heuristics.
+ Generate a smart, context-aware instruction for VLM datasets via heuristics.
Strategy:
- 1. Check for explicit question/instruction columns → use that
+ 1. Explicit question/instruction column → use that
2. Infer from text column name + sample content
3. Analyze dataset name for task hints
- 4. Fall back to generic instruction
+ 4. Generic fallback
Returns:
dict: {
"instruction": str or None, # None means use column content
"instruction_type": "explicit" | "inferred" | "generic",
- "uses_dynamic_instruction": bool, # True if instruction varies per sample
+ "uses_dynamic_instruction": bool, # True if it varies per sample
"confidence": float, # 0.0 to 1.0
}
"""
@@ -39,16 +39,16 @@ def generate_smart_vlm_instruction(
sample = next(iter(dataset))
# ===== LEVEL 1: Explicit Instruction Columns =====
- # Check for columns that contain per-sample instructions
+ # Columns that hold per-sample instructions
question_columns = ["question", "query", "prompt", "instruction", "user_prompt"]
for col in question_columns:
if col in column_names:
- # Check if this column has varied content (not just empty/same)
+ # Use it only if it has non-empty content
sample_content = sample[col]
if sample_content and str(sample_content).strip():
return {
- "instruction": None, # Signal to use column content
+ "instruction": None, # use column content
"instruction_column": col,
"instruction_type": "explicit",
"uses_dynamic_instruction": True,
@@ -58,7 +58,7 @@ def generate_smart_vlm_instruction(
# ===== LEVEL 2: Infer from Column Names + Content =====
text_col_lower = text_column.lower()
- # Sample the text content to detect patterns
+ # Sample text content for pattern detection
text_sample = str(sample.get(text_column, ""))[:500] # First 500 chars
# Task-specific keywords and their instructions
@@ -122,24 +122,24 @@ def generate_smart_vlm_instruction(
},
}
- # Check column name matches
+ # Score each task by column/dataset name and content matches
best_match = None
best_score = 0.0
for task_name, task_info in task_patterns.items():
score = 0.0
- # Check column name
+ # Column name
if any(keyword in text_col_lower for keyword in task_info["keywords"]):
score += 0.5
- # Check dataset name if provided
+ # Dataset name if provided
if dataset_name and any(
keyword in dataset_name.lower() for keyword in task_info["keywords"]
):
score += 0.3
- # Check content patterns
+ # Content patterns
for pattern in task_info["content_hints"]:
if re.search(pattern, text_sample, re.IGNORECASE):
score += 0.4
@@ -162,7 +162,6 @@ def generate_smart_vlm_instruction(
if dataset_name:
name_lower = dataset_name.lower()
- # Common dataset name patterns
if "vqa" in name_lower or "question" in name_lower:
return {
"instruction": "Answer the question about this image.",
diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.py
index 400b5dd0660..7ccba6315e1 100644
--- a/studio/backend/utils/hardware/__init__.py
+++ b/studio/backend/utils/hardware/__init__.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Hardware detection and GPU utilities
-"""
+"""Hardware detection and GPU utilities."""
from . import hardware as _hardware
from .hardware import (
@@ -86,8 +84,8 @@ __all__ = [
def __getattr__(name: str):
- """Resolve IS_ROCM at access time so callers always see the live value
- after detect_hardware() runs (it flips the flag in hardware.py)."""
+ """Resolve IS_ROCM at access time so callers see the live value after
+ detect_hardware() runs (it flips the flag in hardware.py)."""
if name == "IS_ROCM":
return getattr(_hardware, "IS_ROCM")
raise AttributeError(name)
diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.py
index 04b9494a29d..41ee9f3fbeb 100644
--- a/studio/backend/utils/hardware/amd.py
+++ b/studio/backend/utils/hardware/amd.py
@@ -3,9 +3,8 @@
"""AMD GPU monitoring via amd-smi.
-Mirrors the nvidia.py module structure so hardware.py can swap backends
-based on IS_ROCM. All functions return the same dict shapes as their
-nvidia.py counterparts.
+Mirrors nvidia.py so hardware.py can swap backends based on IS_ROCM.
+All functions return the same dict shapes as their nvidia.py counterparts.
"""
import json
@@ -23,20 +22,20 @@ from utils.subprocess_compat import windows_hidden_subprocess_kwargs
logger = get_logger(__name__)
-# amd-smi on Windows must initialise the full ROCm runtime on first call, which
-# can take 15-25 s on cold hardware. Linux is consistently < 2 s.
+# amd-smi on Windows initialises the full ROCm runtime on first call, which
+# can take 15-25 s on cold hardware. Linux is consistently < 2 s.
_AMD_SMI_DEFAULT_TIMEOUT = 30 if platform.system() == "Windows" else 10
# Circuit breaker: stop calling amd-smi after this many consecutive failures.
# On Windows, each failed call spawns a process that may show a UAC/DiskPart
-# elevation prompt. Once we know amd-smi doesn't work we stop polling it.
+# elevation prompt. Once we know amd-smi doesn't work, stop polling it.
_AMD_SMI_FAILURE_LIMIT = 3
_amd_smi_consecutive_failures = 0
_amd_smi_disabled = False
def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optional[Any]:
- """Run amd-smi with the given arguments and return parsed JSON, or None."""
+ """Run amd-smi with the given args and return parsed JSON, or None."""
global _amd_smi_consecutive_failures, _amd_smi_disabled
if _amd_smi_disabled:
return None
@@ -52,7 +51,7 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
except (OSError, subprocess.TimeoutExpired) as e:
if isinstance(e, FileNotFoundError):
# amd-smi ships with Adrenalin, not the HIP SDK -- absence is
- # expected on HIP SDK-only Windows setups. Log at debug only.
+ # expected on HIP SDK-only Windows setups. Log at debug only.
logger.debug("amd-smi not found (not in PATH): %s", e)
else:
logger.warning("amd-smi query failed: %s", e)
@@ -75,9 +74,9 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
_amd_smi_disabled = True
return None
if not result.stdout.strip():
- # amd-smi exited successfully but produced no output (e.g. no GPUs
- # visible on this query, or a version that emits nothing for --json).
- # This is not a tool failure, so don't count against the circuit breaker.
+ # amd-smi exited 0 but produced no output (e.g. no GPUs visible on
+ # this query, or a version that emits nothing for --json). Not a tool
+ # failure, so don't count against the circuit breaker.
logger.debug("amd-smi exited 0 but returned no output")
return None
_amd_smi_consecutive_failures = 0 # reset on success
@@ -89,7 +88,7 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
def _parse_numeric(value: Any) -> Optional[float]:
- """Extract a numeric value from amd-smi output (may be str, int, float, or dict)."""
+ """Extract a numeric value from amd-smi output (str, int, float, or dict)."""
if value is None:
return None
# Newer amd-smi versions emit {"value": 10, "unit": "W"}
@@ -114,9 +113,8 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
"""Parse a memory value from amd-smi output and return MB.
Handles bare numbers (assumed MB -- the amd-smi convention on every
- version we have seen), dict-shaped values with explicit units
- (``{"value": 192, "unit": "GiB"}`` on newer releases), and plain
- strings like ``"8192 MiB"``.
+ version seen), dict values with explicit units (``{"value": 192,
+ "unit": "GiB"}`` on newer releases), and strings like ``"8192 MiB"``.
"""
unit = ""
raw_value = value
@@ -134,8 +132,8 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
if num is None:
return None
- # Unit conversion -- GPU tools (including amd-smi) use binary units even
- # when labeling them "GB" or "MB", so treat GB/GiB and MB/MiB the same.
+ # Unit conversion -- GPU tools (incl. amd-smi) use binary units even when
+ # labeled "GB" or "MB", so treat GB/GiB and MB/MiB the same.
if "gib" in unit or "gb" in unit:
return num * 1024
if "mib" in unit or "mb" in unit:
@@ -146,27 +144,27 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
# Plain bytes
return num / (1024 * 1024)
- # No explicit unit -- default to MB, which is the amd-smi convention
- # for bare numeric values. A previous heuristic assumed values above
- # ~10M were bytes, but that misclassifies small VRAM allocations
- # (e.g. 5 MB = 5,242,880 reported without a unit) as ~5 TB. Modern
- # amd-smi always ships explicit units, so the heuristic branch only
- # fired for legacy output where MB was already the convention.
+ # No explicit unit -- default to MB, the amd-smi convention for bare
+ # numeric values. A previous heuristic assumed values above ~10M were
+ # bytes, but that misclassifies small VRAM allocations (e.g. 5 MB =
+ # 5,242,880 reported without a unit) as ~5 TB. Modern amd-smi always
+ # ships explicit units, so the heuristic only fired for legacy output
+ # where MB was already the convention.
return num
def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
"""Extract standardized metrics from a single GPU's amd-smi data."""
- # amd-smi metric output structure varies by version; try common paths
+ # Output structure varies by version; try common paths
usage = gpu_data.get("usage", gpu_data.get("gpu_activity", {}))
if isinstance(usage, dict):
gpu_util = _parse_numeric(usage.get("gfx_activity", usage.get("gpu_use_percent")))
else:
gpu_util = _parse_numeric(usage)
- # Temperature -- try multiple keys in priority order.
- # dict.get() returns "N/A" strings rather than falling through,
- # so we must try each key and check if it parses to a real number.
+ # Temperature -- try keys in priority order. dict.get() returns "N/A"
+ # strings rather than falling through, so try each key and check it
+ # parses to a real number.
temp_data = gpu_data.get("temperature", {})
temp = None
if isinstance(temp_data, dict):
@@ -191,10 +189,10 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
power_draw = None
power_limit = None
- # VRAM -- unit-aware parsing to handle varying amd-smi output formats.
- # Newer amd-smi versions may return {"value": 192, "unit": "GiB"}.
- # Newer amd-smi uses "mem_usage" with "total_vram" / "used_vram" keys;
- # older versions use "vram" or "fb_memory_usage" with "used" / "total".
+ # VRAM -- unit-aware parsing for varying amd-smi output formats.
+ # Newer versions may return {"value": 192, "unit": "GiB"} and use
+ # "mem_usage" with "total_vram" / "used_vram" keys; older versions use
+ # "vram" or "fb_memory_usage" with "used" / "total".
vram_data = gpu_data.get(
"mem_usage",
gpu_data.get("vram", gpu_data.get("fb_memory_usage", {})),
@@ -239,11 +237,10 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
def _has_real_metrics(metrics: dict[str, Any]) -> bool:
"""Return True when ``metrics`` contains at least one non-None value.
- ``amd-smi`` can return a zero-exit JSON envelope that is missing every
- expected field (error response, unsupported card, hipless container).
- In that case ``_extract_gpu_metrics`` produces a dict where every value
- is ``None`` -- callers must surface this as ``available: False`` rather
- than ``available: True`` with empty data.
+ ``amd-smi`` can return a zero-exit JSON envelope missing every expected
+ field (error response, unsupported card, hipless container). Then
+ ``_extract_gpu_metrics`` produces an all-``None`` dict -- callers must
+ surface this as ``available: False``, not ``available: True`` with empty data.
"""
return any(value is not None for value in metrics.values())
@@ -255,9 +252,9 @@ def get_physical_gpu_count() -> Optional[int]:
return None
if isinstance(data, list):
return len(data)
- # Some versions return a dict with a "gpu" / "gpus" key. Guard the
- # .get() access with an isinstance check so a malformed scalar /
- # string response from amd-smi cannot raise AttributeError.
+ # Some versions return a dict with a "gpu" / "gpus" key. Guard .get()
+ # with isinstance so a malformed scalar/string response cannot raise
+ # AttributeError.
if not isinstance(data, dict):
return None
gpus = data.get("gpu", data.get("gpus", []))
@@ -267,12 +264,12 @@ def get_physical_gpu_count() -> Optional[int]:
def _first_visible_amd_gpu_id() -> Optional[str]:
- """Return the physical AMD GPU id that should be treated as 'primary'.
+ """Return the physical AMD GPU id treated as 'primary'.
Honours HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES
- in that order (HIP respects all three). Returns ``"0"`` when none are
- set, and ``None`` when the env var explicitly narrows to zero GPUs
- ("" or "-1"), so callers can short-circuit to "available: False".
+ in that order (HIP respects all three). Returns ``"0"`` when none are set,
+ and ``None`` when the env var narrows to zero GPUs ("" or "-1"), so callers
+ can short-circuit to "available: False".
"""
for env_name in (
"HIP_VISIBLE_DEVICES",
@@ -285,11 +282,10 @@ def _first_visible_amd_gpu_id() -> Optional[str]:
raw = raw.strip()
if raw == "" or raw == "-1":
return None
- # Filter out empty tokens after splitting. This tolerates minor
- # typos like ``HIP_VISIBLE_DEVICES=",1"`` (leading comma, user
- # clearly meant to narrow to device 1) while still falling
- # through to the next env var when every token is empty
- # (e.g. ``,,,``).
+ # Drop empty tokens after splitting. Tolerates minor typos like
+ # ``HIP_VISIBLE_DEVICES=",1"`` (leading comma, clearly meant device 1)
+ # while still falling through to the next env var when every token is
+ # empty (e.g. ``,,,``).
tokens = [t.strip() for t in raw.split(",") if t.strip()]
if tokens:
return tokens[0]
@@ -320,10 +316,9 @@ def get_primary_gpu_utilization() -> dict[str, Any]:
metrics = _extract_gpu_metrics(gpu_data)
if not _has_real_metrics(metrics):
- # amd-smi returned a JSON envelope with no usable fields (error
- # response or unsupported card). Surface as unavailable rather
- # than available-with-empty-data so the UI does not render a
- # ghost device.
+ # JSON envelope with no usable fields (error response or unsupported
+ # card). Surface as unavailable rather than available-with-empty-data
+ # so the UI does not render a ghost device.
return {"available": False}
metrics["available"] = True
return metrics
@@ -352,11 +347,10 @@ def get_visible_gpu_utilization(
"index_kind": "physical",
}
- # Extract a device list from amd-smi's envelope. Newer versions return
- # a JSON array directly, older versions return a dict with a "gpus" /
- # "gpu" key wrapping the list. Guard non-dict / non-list envelopes
- # (scalar / string fallbacks from malformed output) so the .get()
- # access cannot raise AttributeError on an unexpected shape.
+ # Extract a device list from amd-smi's envelope. Newer versions return a
+ # JSON array directly; older versions wrap the list in a dict under
+ # "gpus" / "gpu". Guard non-dict / non-list envelopes (scalar/string
+ # fallbacks from malformed output) so .get() cannot raise AttributeError.
if isinstance(data, list):
gpu_list = data
elif isinstance(data, dict):
@@ -369,17 +363,15 @@ def get_visible_gpu_utilization(
devices = []
for fallback_idx, gpu_data in enumerate(gpu_list):
- # Skip non-dict entries defensively: if amd-smi ever ships a
- # scalar inside its "gpus" array (observed on some malformed
- # output), _extract_gpu_metrics would raise AttributeError on
- # the first .get() call.
+ # Skip non-dict entries: a scalar inside the "gpus" array (seen on
+ # some malformed output) would make _extract_gpu_metrics raise
+ # AttributeError on the first .get() call.
if not isinstance(gpu_data, dict):
continue
- # Use AMD-reported GPU ID when available, fall back to enumeration
- # index. Newer amd-smi versions wrap scalars as ``{"value": 0,
- # "unit": "none"}``, so route raw_id through ``_parse_numeric``
- # which already handles bare ints, floats, strings, and that
- # dict shape uniformly.
+ # Use AMD-reported GPU ID when available, else the enumeration index.
+ # Newer amd-smi wraps scalars as ``{"value": 0, "unit": "none"}``, so
+ # route raw_id through ``_parse_numeric`` which handles bare ints,
+ # floats, strings, and that dict shape uniformly.
raw_id = gpu_data.get("gpu", gpu_data.get("gpu_id", gpu_data.get("id", fallback_idx)))
parsed_id = _parse_numeric(raw_id)
if parsed_id is None:
@@ -403,10 +395,9 @@ def get_visible_gpu_utilization(
continue
metrics = _extract_gpu_metrics(gpu_data)
if not _has_real_metrics(metrics):
- # Skip ghost entries: an amd-smi response that decodes to a
- # dict but contains no usable fields (error envelope, etc.)
- # would otherwise show up as a device row with all-None
- # numbers in the UI.
+ # Skip ghost entries: a dict response with no usable fields
+ # (error envelope, etc.) would otherwise show up as a device row
+ # with all-None numbers in the UI.
continue
metrics["index"] = idx
metrics["index_kind"] = "physical"
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 3f2823302a2..df3fbac47a6 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -39,7 +39,7 @@ logger = get_logger(__name__)
class DeviceType(str, Enum):
- """Supported compute backends. Inherits from str so it serializes cleanly in JSON."""
+ """Supported compute backends. str subclass for clean JSON serialization."""
CUDA = "cuda"
XPU = "xpu"
@@ -57,14 +57,11 @@ IS_ROCM: bool = False # True when running on AMD ROCm (HIP) -- routes GPU monit
def _backend_label(device: DeviceType) -> str:
"""Return the user-facing backend name for API responses.
- Internally we still represent ROCm hosts as ``DeviceType.CUDA`` because
- ROCm torch sets ``torch.cuda.is_available() = True`` and reuses the whole
- ``torch.cuda.*`` API surface, so branching on ``DeviceType`` stays
- consistent with the rest of the codebase. For the JSON responses served
- to the Studio frontend and other clients, however, "cuda" is misleading
- on an AMD machine. This helper swaps the label to ``"rocm"`` when the
- module-level ``IS_ROCM`` flag is set so the UI can render the correct
- backend name without every caller having to duplicate the check.
+ ROCm hosts stay ``DeviceType.CUDA`` internally (ROCm torch sets
+ ``torch.cuda.is_available() = True`` and reuses ``torch.cuda.*``), so
+ branching on ``DeviceType`` stays consistent. But "cuda" is misleading
+ in JSON responses on an AMD machine, so this swaps the label to
+ ``"rocm"`` when ``IS_ROCM`` is set, sparing callers the check.
"""
if IS_ROCM and device == DeviceType.CUDA:
return "rocm"
@@ -75,12 +72,12 @@ def _backend_label(device: DeviceType) -> str:
def is_apple_silicon() -> bool:
- """Check if running on Apple Silicon hardware (pure platform check, no ML imports)."""
+ """True on Apple Silicon (pure platform check, no ML imports)."""
return platform.system() == "Darwin" and platform.machine() == "arm64"
def _has_torch() -> bool:
- """Check if PyTorch is importable."""
+ """True if PyTorch is importable."""
try:
import torch
return True
@@ -89,7 +86,7 @@ def _has_torch() -> bool:
def _has_mlx() -> bool:
- """Check if MLX is importable."""
+ """True if MLX is importable."""
try:
import mlx.core
return True
@@ -99,10 +96,9 @@ def _has_mlx() -> bool:
def detect_hardware() -> DeviceType:
"""
- Detect the best available compute device and set the module-level DEVICE global.
+ Detect the best compute device and set the module-level DEVICE global.
- Should be called exactly once during FastAPI lifespan startup.
- Safe to call multiple times (idempotent).
+ Call once at FastAPI lifespan startup; idempotent.
Detection order:
1. CUDA (NVIDIA GPU, requires torch)
@@ -121,10 +117,10 @@ def detect_hardware() -> DeviceType:
CHAT_ONLY = False
device_name = torch.cuda.get_device_properties(0).name
- # Distinguish AMD ROCm (HIP) from NVIDIA CUDA for display purposes.
+ # Distinguish AMD ROCm (HIP) from NVIDIA CUDA for display only;
# DeviceType stays CUDA since torch.cuda.* works on ROCm via HIP.
- # AMD's repo.radeon.com SDK wheels (e.g. 2.9.0+rocmsdk20251116) do
- # not set torch.version.hip, so fall back to checking __version__.
+ # AMD's repo.radeon.com SDK wheels (e.g. 2.9.0+rocmsdk20251116)
+ # don't set torch.version.hip, so fall back to __version__.
_hip_ver = getattr(torch.version, "hip", None)
if _hip_ver is not None or "rocm" in torch.__version__.lower():
IS_ROCM = True
@@ -148,9 +144,9 @@ def detect_hardware() -> DeviceType:
if is_apple_silicon() and _has_mlx():
DEVICE = DeviceType.MLX
CHAT_ONLY = False
- # platform.processor() runs `uname -p` which returns "i386" on most
- # universal2 / Rosetta-shaped Python builds even on native arm64.
- # platform.machine() is "arm64" once is_apple_silicon() has gated us.
+ # platform.processor() (`uname -p`) returns "i386" on most
+ # universal2 / Rosetta Python builds even on native arm64.
+ # platform.machine() is "arm64" once is_apple_silicon() gated us.
chip = platform.machine() or "arm64"
print(f"Hardware detected: MLX — Apple Silicon ({chip})")
return DEVICE
@@ -166,8 +162,8 @@ def detect_hardware() -> DeviceType:
def get_device() -> DeviceType:
"""
- Return the detected device. Auto-detects if detect_hardware() hasn't been called yet.
- Prefer calling detect_hardware() explicitly at startup instead.
+ Return the detected device, auto-detecting if detect_hardware() hasn't run.
+ Prefer calling detect_hardware() explicitly at startup.
"""
global DEVICE
if DEVICE is None:
@@ -178,7 +174,7 @@ def get_device() -> DeviceType:
def clear_gpu_cache():
"""
Clear GPU memory cache for the current device.
- Safe to call on any platform — no-ops gracefully.
+ Safe on any platform — no-ops gracefully.
"""
gc.collect()
@@ -195,15 +191,15 @@ def clear_gpu_cache():
torch.xpu.synchronize()
torch.xpu.empty_cache()
elif device == DeviceType.MLX:
- # MLX manages memory automatically; no explicit cache clear needed.
- # mlx.core has no empty_cache equivalent — gc.collect() above is enough.
+ # MLX manages memory automatically; no empty_cache equivalent,
+ # so the gc.collect() above is enough.
pass
def get_gpu_memory_info() -> Dict[str, Any]:
"""
- Get GPU memory information.
- Supports CUDA (NVIDIA), MLX (Apple Silicon), and CPU-only environments.
+ Get GPU memory info.
+ Supports CUDA (NVIDIA), MLX (Apple Silicon), and CPU-only.
"""
device = get_device()
@@ -275,8 +271,8 @@ def get_gpu_memory_info() -> Dict[str, Any]:
import mlx.core as mx
import psutil
- # MLX uses unified memory. Total = system RAM. GPU memory used
- # comes from IORegistry's AGXAccelerator (system-wide, no sudo).
+ # MLX uses unified memory: total = system RAM, GPU used comes
+ # from IORegistry's AGXAccelerator (system-wide, no sudo).
total = psutil.virtual_memory().total
agx = _read_apple_gpu_stats()
allocated = agx.get("vram_used_bytes", 0) if agx else 0
@@ -284,7 +280,7 @@ def get_gpu_memory_info() -> Dict[str, Any]:
try:
info = mx.device_info()
# See detect_hardware(): platform.processor() can return "i386"
- # on native arm64 Python builds, so prefer machine() as fallback.
+ # on native arm64 builds, so prefer machine() as fallback.
gpu_name = info.get("device_name") or platform.machine() or "arm64"
except Exception:
gpu_name = platform.machine() or "arm64"
@@ -352,13 +348,11 @@ def get_gpu_summary() -> Dict[str, Any]:
def get_package_versions() -> Dict[str, Optional[str]]:
"""
- Return the installed versions of key ML packages.
+ Return installed versions of key ML packages.
- Uses importlib.metadata (stdlib) so no subprocess is needed.
- CUDA version comes from torch.version.cuda.
-
- Returns dict with keys: unsloth, torch, transformers, cuda.
- Missing packages yield None.
+ Uses importlib.metadata (stdlib), no subprocess. CUDA version from
+ torch.version.cuda. Returns dict keyed unsloth/torch/transformers/cuda;
+ missing packages yield None.
"""
packages = ("unsloth", "torch", "transformers")
versions: Dict[str, Optional[str]] = {}
@@ -418,8 +412,8 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]
# torch uses 0-based ordinals relative to CUDA_VISIBLE_DEVICES
props = mod.get_device_properties(ordinal)
total_bytes = props.total_memory
- # Prefer mem_get_info (reports system-wide usage, not just this
- # process) so auto-selection accounts for other GPU consumers.
+ # Prefer mem_get_info (system-wide usage, not just this process)
+ # so auto-selection accounts for other GPU consumers.
if hasattr(mod, "mem_get_info"):
free_bytes, total_bytes = mod.mem_get_info(ordinal)
used_bytes = total_bytes - free_bytes
@@ -443,9 +437,9 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]
def _smi_query(func_name: str, *args, **kwargs) -> Optional[Dict[str, Any]]:
- """Run a query against the appropriate SMI backend (amd-smi or nvidia-smi).
+ """Query the appropriate SMI backend (amd-smi or nvidia-smi).
- Returns the result dict if available, or None on failure/unavailability.
+ Returns the result dict if available, else None.
"""
if IS_ROCM:
backend_name = "amd-smi"
@@ -474,8 +468,8 @@ def _smi_query(func_name: str, *args, **kwargs) -> Optional[Dict[str, Any]]:
def _read_apple_gpu_stats() -> Dict[str, Any]:
"""Query macOS IORegistry for AGX (Apple GPU) live stats. No sudo needed.
- Returns dict with utilization_pct, vram_used_bytes (system-wide GPU memory).
- Returns empty dict on failure.
+ Returns dict with utilization_pct, vram_used_bytes (system-wide GPU
+ memory), or empty dict on failure.
"""
try:
result = subprocess.run(
@@ -574,7 +568,7 @@ def _rocm_windows_perf_counter_gpu_util_pct() -> Optional[float]:
def _rocm_linux_sysfs_vram_gb() -> tuple[Optional[float], Optional[float]]:
"""Query system-wide AMD GPU VRAM via Linux DRM sysfs.
- Reads /sys/class/drm/card*/device/mem_info_vram_* which the kernel
+ Reads /sys/class/drm/card*/device/mem_info_vram_*, which the kernel
updates in real-time across all processes. No tools required.
Returns (used_gb, total_gb) or (None, None) on failure.
"""
@@ -597,8 +591,8 @@ def _rocm_linux_sysfs_vram_gb() -> tuple[Optional[float], Optional[float]]:
def _rocm_windows_perf_counter_vram_gb() -> tuple[Optional[float], Optional[float]]:
"""Query system-wide dedicated GPU VRAM via Windows Performance Counters.
- Uses the same data source as Task Manager so it reflects cross-process
- usage accurately. Works for any GPU vendor without amd-smi or nvidia-smi.
+ Same data source as Task Manager, so cross-process usage is accurate.
+ Works for any GPU vendor without amd-smi or nvidia-smi.
Returns (used_gb, total_gb) or (None, None) on failure.
"""
if platform.system() != "Windows":
@@ -640,10 +634,10 @@ def get_gpu_utilization() -> Dict[str, Any]:
# Fix unified-memory VRAM on AMD iGPUs (Strix Halo etc.)
_reconcile_primary_rocm_unified_memory(result, _get_parent_visible_gpu_spec())
return result
- # SMI tool unavailable or returned no usable data. On Windows, query
+ # SMI tool unavailable or returned nothing usable. On Windows, query
# the Performance Counter API (same source as Task Manager) for
# system-wide dedicated VRAM — covers cross-process usage that
- # torch.cuda.mem_get_info cannot see from the Studio server process.
+ # torch.cuda.mem_get_info can't see from the Studio server process.
if IS_ROCM and platform.system() == "Windows":
_win_used, _win_total = _rocm_windows_perf_counter_vram_gb()
if _win_used is not None and _win_total is not None:
@@ -705,8 +699,8 @@ def get_gpu_utilization() -> Dict[str, Any]:
"power_utilization_pct": None,
}
- # MLX path: single _read_apple_gpu_stats() call carries both VRAM-used
- # bytes and GPU utilization %. psutil for unified-memory total is cheap.
+ # MLX path: one _read_apple_gpu_stats() call carries both VRAM-used bytes
+ # and GPU utilization %. psutil for unified-memory total is cheap.
if device == DeviceType.MLX:
try:
import psutil
@@ -772,8 +766,8 @@ def _apply_unified_memory_correction(
"""Per-device reconciliation: when torch reports a larger memory total
than amd-smi, overwrite the smi VRAM fields in place.
- Used by both the multi-device and primary-device reconciliation helpers
- so the two endpoints stay in sync on AMD iGPUs with unified memory.
+ Used by both the multi-device and primary-device reconcilers so the two
+ endpoints stay in sync on AMD iGPUs with unified memory.
"""
torch_total_gb = torch_info["total_gb"]
smi_total_gb = device_metrics.get("vram_total_gb") or 0.0
@@ -798,7 +792,7 @@ def _reconcile_rocm_unified_memory(utilization: Dict[str, Any], device_indices:
amd-smi reports only the dedicated slice (~512 MB); torch sees the full
GTT pool (~128 GB). When torch total > smi total, overwrite per-device
- VRAM fields so GPU selection uses the real available memory.
+ VRAM fields so GPU selection uses real available memory.
"""
torch_devices = _torch_get_per_device_info(device_indices)
if not torch_devices:
@@ -820,10 +814,9 @@ def _reconcile_primary_rocm_unified_memory(
# No visibility env var set: torch ordinal 0 is the primary device.
primary_idx = [0]
elif len(numeric_ids) == 0:
- # Empty mask (HIP_VISIBLE_DEVICES="" or "-1"): no GPU is visible to
- # this process. Querying torch device 0 would raise a RuntimeError or
- # return stale/wrong data, so bail out rather than writing bad values
- # into the utilization dict.
+ # Empty mask (HIP_VISIBLE_DEVICES="" or "-1"): no GPU visible to this
+ # process. Querying torch device 0 would raise or return stale data,
+ # so bail rather than write bad values into the utilization dict.
return
else:
primary_idx = [int(numeric_ids[0])]
@@ -942,14 +935,14 @@ _visible_gpu_count: Optional[int] = None
def _get_parent_visible_gpu_spec() -> Dict[str, Any]:
- # ROCm uses HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES in addition to
- # CUDA_VISIBLE_DEVICES (which HIP also respects). Check ROCm-specific
- # env vars first so multi-GPU AMD setups are handled correctly.
- # Use explicit None checks (not `or`) so empty string "" is honoured
- # as "no visible GPUs" rather than falling through to CUDA_VISIBLE_DEVICES.
+ # ROCm uses HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES on top of
+ # CUDA_VISIBLE_DEVICES (which HIP also respects). Check ROCm env vars
+ # first for multi-GPU AMD setups. Use explicit None checks (not `or`)
+ # so empty string "" is honoured as "no visible GPUs" rather than
+ # falling through to CUDA_VISIBLE_DEVICES.
cuda_visible = None
# Prefer ROCm masks only on a ROCm host, or when no CUDA mask is set, so a
- # stale HIP_VISIBLE_DEVICES on an NVIDIA host can't override CUDA_VISIBLE_DEVICES.
+ # stale HIP_VISIBLE_DEVICES on NVIDIA can't override CUDA_VISIBLE_DEVICES.
_is_rocm_spec = IS_ROCM or (
"CUDA_VISIBLE_DEVICES" not in os.environ
and ("HIP_VISIBLE_DEVICES" in os.environ or "ROCR_VISIBLE_DEVICES" in os.environ)
@@ -1027,7 +1020,7 @@ def resolve_requested_gpu_ids(gpu_ids: Optional[list[int]]) -> list[int]:
f"Parent-visible GPUs: {parent_visible_ids}"
)
- # Reject negative IDs unconditionally.
+ # Reject negative IDs.
negative_ids = [gpu_id for gpu_id in requested_ids if gpu_id < 0]
if negative_ids:
raise ValueError(
@@ -1035,12 +1028,11 @@ def resolve_requested_gpu_ids(gpu_ids: Optional[list[int]]) -> list[int]:
f"Rejected IDs: {negative_ids}. Parent-visible GPUs: {parent_visible_ids}"
)
- # Only enforce the physical upper bound when we have a reliable count
- # from nvidia-smi. When the count comes from torch, it reflects visible
- # devices (filtered by CUDA_VISIBLE_DEVICES), not the physical total,
- # so high physical indices like 3 would be falsely rejected on a
- # CUDA_VISIBLE_DEVICES="2,3" machine that reports device_count()=2.
- # The parent-visible check below is authoritative in all cases.
+ # Only enforce the physical upper bound when the count is reliable
+ # (from nvidia-smi). A torch count reflects visible devices (filtered by
+ # CUDA_VISIBLE_DEVICES), not the physical total, so e.g. index 3 would be
+ # falsely rejected on a CUDA_VISIBLE_DEVICES="2,3" host reporting
+ # device_count()=2. The parent-visible check below is always authoritative.
if physical_gpu_count > 0 and parent_visible_ids:
max_parent_id = max(parent_visible_ids)
if physical_gpu_count > max_parent_id:
@@ -1123,13 +1115,13 @@ def _load_config_for_gpu_estimate(model_name: str, hf_token: Optional[str] = Non
def _determine_attention_impl_for_gpu_estimate(config) -> str:
- # torch.distributed is incomplete on Windows ROCm — torch._C is a C
- # extension (not a package), so Python cannot import the submodule
- # torch._C._distributed_c10d that torch.distributed depends on.
- # Inject an empty stub into sys.modules BEFORE importing torch.distributed
- # so the import succeeds, then patch the missing process-group helpers.
+ # torch.distributed is incomplete on Windows ROCm: torch._C is a C
+ # extension (not a package), so the submodule torch._C._distributed_c10d
+ # that torch.distributed depends on can't be imported. Inject an empty
+ # stub into sys.modules BEFORE importing torch.distributed so the import
+ # succeeds, then patch the missing process-group helpers.
if sys.platform == "win32" and IS_ROCM:
- # Dummy class for any name torch.distributed tries to import from these stubs
+ # Dummy for any name torch.distributed imports from these stubs
class _Dummy:
pass
@@ -1177,11 +1169,11 @@ def _determine_attention_impl_for_gpu_estimate(config) -> str:
from unsloth.models._utils import resolve_attention_implementation
from transformers import AutoModel, AutoModelForCausalLM
- # why: resolve_attention_implementation calls _set_attn_impl which writes
+ # why: resolve_attention_implementation calls _set_attn_impl, which writes
# _attn_implementation onto the config; PreTrainedConfig's setter walks
# `sub_configs` and propagates to nested text_config / sub-configs, so a
- # shallow copy still mutates those shared inner objects on the cached
- # config returned by _load_config_for_gpu_estimate. Deepcopy isolates them.
+ # shallow copy would still mutate those shared inner objects on the cached
+ # config from _load_config_for_gpu_estimate. Deepcopy isolates them.
config_copy = copy.deepcopy(config)
model_class = None
@@ -1357,15 +1349,15 @@ def estimate_required_model_memory_gb(
config
)
except Exception as e:
- # Log at debug: on Windows ROCm the torch.distributed stub does
- # not implement Store, so this fires on every estimate call.
- # It is expected and non-actionable -- eager is the safe fallback.
+ # Debug-level: on Windows ROCm the torch.distributed stub lacks
+ # Store, so this fires every estimate call. Expected and
+ # non-actionable -- eager is the safe fallback.
logger.debug(
"Could not resolve attention implementation for '%s': %s",
estimate_model,
e,
)
- # why: if we cannot prove flash attention is usable, charge the
+ # why: if flash attention can't be proven usable, charge the
# quadratic non-flash activation path so GPU selection stays
# conservative.
vram_config.attention_implementation = "eager"
@@ -1374,14 +1366,14 @@ def estimate_required_model_memory_gb(
if arch is not None:
breakdown = estimate_training_vram(arch, vram_config)
# why: extract_arch_config only sees text_config; safetensors include
- # vision/audio tower bytes that the text-arch fp16 total misses.
+ # vision/audio tower bytes the text-arch fp16 total misses.
arch_fp16_bytes = compute_total_params(arch) * 2
extra_bytes = max(0, int(model_size_bytes) - arch_fp16_bytes)
if extra_bytes > 0:
breakdown.model_weights += extra_bytes
if training_method == "full":
# why: full fine-tuning makes the extra (vision/audio) params
- # trainable; optimizer + gradient bytes scale with them too.
+ # trainable; optimizer + gradient bytes scale with them.
extra_params = extra_bytes // 2
breakdown.optimizer_states += compute_optimizer_bytes(
extra_params,
@@ -1460,9 +1452,8 @@ def auto_select_gpu_ids(
return None, metadata
if required_gb is None:
- # Cannot estimate model size -- fall back to all visible GPUs
- # rather than risk loading on a single GPU that may not have
- # enough memory.
+ # Cannot estimate model size -- fall back to all visible GPUs rather
+ # than risk loading on a single GPU that may lack memory.
parent_ids = get_parent_visible_gpu_ids()
metadata["selection_mode"] = "fallback_all"
metadata["selected_gpu_ids"] = parent_ids
@@ -1500,17 +1491,16 @@ def auto_select_gpu_ids(
free_by_index = {item["index"]: item["free_gb"] for item in ranked}
selected: list[int] = []
usable_gb = 0.0
- # Multi-GPU sharding has overhead from inter-GPU communication (NCCL
- # all-reduce, PCIe/NVLink transfers, synchronization barriers), so each
- # additional GPU contributes less than its raw free memory. The first GPU
- # keeps its full capacity (no cross-device overhead). 0.85 was calibrated
- # empirically on 2-8 GPU setups with NVLink and PCIe topologies -- the
- # 15% discount accounts for NCCL buffers (~2-5% of VRAM), pipeline bubble
- # overhead, and memory fragmentation from non-uniform shard sizes.
+ # Multi-GPU sharding has inter-GPU communication overhead (NCCL
+ # all-reduce, PCIe/NVLink transfers, sync barriers), so each extra GPU
+ # contributes less than its raw free memory; the first GPU keeps full
+ # capacity. 0.85 was calibrated empirically on 2-8 GPU NVLink/PCIe
+ # setups -- the 15% discount covers NCCL buffers (~2-5% of VRAM),
+ # pipeline bubble overhead, and fragmentation from non-uniform shards.
multi_gpu_overhead = 0.85
# Per-GPU check: activations don't shard, so each GPU needs its weight
- # shard + full activation cost. Use precomputed min_per_gpu_N values.
+ # shard + full activation cost. Uses precomputed min_per_gpu_N values.
vram_breakdown = estimate_metadata.get("vram_breakdown", {})
for candidate in ranked:
@@ -1547,7 +1537,7 @@ def auto_select_gpu_ids(
)
return selected, metadata
- # Use only GPUs with verified VRAM data (from gpu_candidates, not raw devices)
+ # Use only GPUs with verified VRAM data (gpu_candidates, not raw devices)
fallback_all = [c["index"] for c in gpu_candidates] if gpu_candidates else parent_ids
metadata["selection_mode"] = "fallback_all"
if ranked:
@@ -1586,18 +1576,17 @@ def prepare_gpu_selection(
"""Resolve which physical GPUs to use for a model load.
GPU selection modes:
- - **Explicit** (``gpu_ids=[5, 6, 7]``): the caller chooses exact GPUs.
- All listed GPUs are used and the model is sharded across them via
- ``device_map="balanced"``, regardless of whether the model would fit
- on fewer GPUs. IDs are validated against the parent-visible set.
- - **Auto** (``gpu_ids=None`` or ``[]``): ``auto_select_gpu_ids`` estimates
- VRAM requirements and picks the *minimum* number of GPUs needed,
- preferring GPUs with the most free memory.
-
- The returned ``gpu_ids`` list is later passed to ``get_device_map()`` which
- maps it to a Hugging Face ``device_map`` string, and to ``apply_gpu_ids()``
- in the worker subprocess which narrows ``CUDA_VISIBLE_DEVICES`` before any
- torch/CUDA initialisation.
+ - **Explicit** (``gpu_ids=[5, 6, 7]``): caller chooses exact GPUs.
+ All listed GPUs are used and the model is sharded via
+ ``device_map="balanced"``, even if it would fit on fewer. IDs are
+ validated against the parent-visible set.
+ - **Auto** (``gpu_ids=None`` or ``[]``): ``auto_select_gpu_ids``
+ estimates VRAM needs and picks the *minimum* GPUs needed,
+ preferring those with the most free memory.
+
+ The returned ``gpu_ids`` is later passed to ``get_device_map()`` (maps it
+ to a Hugging Face ``device_map`` string) and to ``apply_gpu_ids()`` in the
+ worker subprocess (narrows ``CUDA_VISIBLE_DEVICES`` before torch/CUDA init).
"""
if gpu_ids and get_device() != DeviceType.CUDA:
raise ValueError(
@@ -1633,8 +1622,7 @@ def get_physical_gpu_count() -> int:
Return the number of physical GPUs on the machine.
Uses ``nvidia-smi -L`` on NVIDIA (unaffected by CUDA_VISIBLE_DEVICES),
- with a torch-based fallback for AMD ROCm and Intel XPU.
- Result is cached after the first call.
+ with a torch fallback for AMD ROCm and Intel XPU. Cached after first call.
"""
global _physical_gpu_count
if _physical_gpu_count is not None:
@@ -1676,10 +1664,10 @@ def get_physical_gpu_count() -> int:
def _backend_visible_devices_env() -> Optional[str]:
"""Return the raw visibility env string that applies to this backend.
- On ROCm, HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES take precedence
- over CUDA_VISIBLE_DEVICES; the helper mirrors the resolution logic in
- ``_get_parent_visible_gpu_spec`` so ``backend_cuda_visible_devices``
- reports the value that is actually narrowing the visible device set.
+ On ROCm, HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES take precedence over
+ CUDA_VISIBLE_DEVICES; this mirrors ``_get_parent_visible_gpu_spec`` so
+ ``backend_cuda_visible_devices`` reports the value actually narrowing the
+ visible device set.
"""
if IS_ROCM:
return _get_parent_visible_gpu_spec().get("raw")
@@ -1706,7 +1694,7 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
except Exception as e:
logger.warning("Backend GPU visibility query failed: %s", e)
- # Torch fallback (AMD ROCm, Intel XPU, nvidia-smi missing/failed)
+ # Torch fallback (AMD ROCm, Intel XPU, nvidia-smi missing/failed).
# When parent_visible_ids is empty (UUID/MIG mask), enumerate by
# torch ordinal so the UI still shows devices.
if parent_visible_ids:
@@ -1789,15 +1777,15 @@ def get_visible_gpu_count() -> int:
Return the number of GPUs visible to this process.
Respects ``CUDA_VISIBLE_DEVICES`` -- if set, only those GPUs count.
- Falls back to physical count if the env var is unset or torch is
- unavailable. Result is cached after the first call.
+ Falls back to physical count if unset or torch is unavailable.
+ Cached after the first call.
"""
global _visible_gpu_count
if _visible_gpu_count is not None:
return _visible_gpu_count
- # Use _get_parent_visible_gpu_spec() which already handles
- # HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES on ROCm.
+ # _get_parent_visible_gpu_spec() already handles HIP_VISIBLE_DEVICES /
+ # ROCR_VISIBLE_DEVICES on ROCm.
visible_spec = _get_parent_visible_gpu_spec()
if visible_spec["raw"] is not None:
raw = visible_spec["raw"].strip()
@@ -1809,7 +1797,7 @@ def get_visible_gpu_count() -> int:
_visible_gpu_count = len([x for x in raw.split(",") if x.strip()])
return _visible_gpu_count
- # No visibility env var set -- try torch, fall back to physical count
+ # No visibility env var set -- try torch, else physical count
try:
import torch
if get_device() == DeviceType.XPU and hasattr(torch, "xpu"):
@@ -1826,9 +1814,9 @@ def apply_gpu_ids(gpu_ids) -> None:
if gpu_ids is None:
return
- # Empty list means "no GPUs visible" -- treat the same as None
- # (inherit parent) to avoid setting CUDA_VISIBLE_DEVICES="" which
- # disables CUDA entirely and crashes downstream torch calls.
+ # Empty list means "no GPUs visible" -- treat like None (inherit parent)
+ # to avoid setting CUDA_VISIBLE_DEVICES="", which disables CUDA entirely
+ # and crashes downstream torch calls.
if isinstance(gpu_ids, (list, tuple)) and len(gpu_ids) == 0:
return
@@ -1841,22 +1829,21 @@ def apply_gpu_ids(gpu_ids) -> None:
os.environ["CUDA_VISIBLE_DEVICES"] = value
# Keep ROCm visibility env vars in sync so _get_parent_visible_gpu_spec()
- # picks up the narrowed set on AMD systems. Workers can call
- # apply_gpu_ids() before detect_hardware() runs (so IS_ROCM is still
- # its default False), so also mirror the selection whenever the
- # parent process already set a ROCm visibility variable -- that
- # way a downstream ROCm process inherits the narrowed mask even
- # before Studio's hardware detection has classified the host.
- # Final fallback: probe torch.version.hip so AMD workers without
- # HIP_VISIBLE_DEVICES still get the correct ROCm visibility mask.
+ # picks up the narrowed set on AMD. Workers may call apply_gpu_ids()
+ # before detect_hardware() runs (IS_ROCM still default False), so also
+ # mirror the selection whenever the parent already set a ROCm visibility
+ # var -- a downstream ROCm process then inherits the narrowed mask before
+ # hardware detection classifies the host. Final fallback: probe
+ # torch.version.hip so AMD workers without HIP_VISIBLE_DEVICES still get
+ # the correct ROCm visibility mask.
_inherits_rocm_visibility = (
"HIP_VISIBLE_DEVICES" in os.environ or "ROCR_VISIBLE_DEVICES" in os.environ
)
_is_rocm = IS_ROCM or _inherits_rocm_visibility
if not _is_rocm:
# torch.version.hip is a non-empty string on ROCm, None on CUDA.
- # AMD SDK / Radeon ROCm wheels can leave torch.version.hip unset but
- # still encode "rocm" in torch.__version__, matching detect_hardware().
+ # AMD SDK / Radeon ROCm wheels may leave it unset but still encode
+ # "rocm" in torch.__version__ (matching detect_hardware()).
# Broad except: a probe failure must never crash a training worker.
try:
import torch as _torch
@@ -1886,22 +1873,21 @@ def get_device_map(gpu_ids: Optional[list[int]] = None) -> str:
Returns ``"balanced"`` (shard evenly across GPUs) when:
- ``gpu_ids`` explicitly lists >1 GPU, **or**
- ``CUDA_VISIBLE_DEVICES`` uses UUID/MIG identifiers (non-numeric) and
- more than one GPU is visible (fallback: we cannot resolve numeric IDs,
- so we assume the caller intends multi-GPU).
+ >1 GPU is visible (fallback: numeric IDs unresolvable, so assume
+ multi-GPU is intended).
- Returns ``"sequential"`` (single device) in all other cases, including
- non-CUDA backends (CPU, MLX).
+ Returns ``"sequential"`` (single device) otherwise, including non-CUDA
+ backends (CPU, MLX).
- Callers should use ``prepare_gpu_selection()`` upstream to determine the
- ``gpu_ids`` list -- that function handles the smart auto-selection of the
- minimum number of GPUs needed for a given model.
+ Use ``prepare_gpu_selection()`` upstream to determine ``gpu_ids`` -- it
+ handles auto-selecting the minimum GPUs needed for a model.
"""
device = get_device()
if device == DeviceType.CUDA:
multi_gpu = gpu_ids is not None and len(gpu_ids) > 1
if not multi_gpu:
- # UUID/MIG masks cannot be split into numeric IDs, so if multiple
+ # UUID/MIG masks can't be split into numeric IDs, so if multiple
# GPUs are visible we assume multi-GPU sharding is intended.
parent_visible_spec = _get_parent_visible_gpu_spec()
if parent_visible_spec["numeric_ids"] is None and get_visible_gpu_count() > 1:
@@ -1944,18 +1930,14 @@ def safe_num_proc(desired: Optional[int] = None) -> int:
"""
Return a safe ``num_proc`` for ``dataset.map()`` calls.
- On Windows, always returns 1 because Python uses ``spawn`` instead of
- ``fork`` for multiprocessing -- the overhead of re-importing torch,
- transformers, unsloth etc. per worker is typically slower than
- single-process for normal dataset sizes.
-
- On multi-GPU machines (where multiple GPUs are *visible* to this
- process) the NVIDIA driver spawns extra background threads, making
- ``os.fork()`` prone to deadlocks when many workers are created.
- This helper caps ``num_proc`` to 4 on such machines.
+ On Windows always returns 1: Python uses ``spawn`` not ``fork``, so
+ re-importing torch/transformers/unsloth per worker is typically slower
+ than single-process for normal dataset sizes.
- When ``CUDA_VISIBLE_DEVICES`` restricts to a single GPU, the cap
- does not apply.
+ On multi-GPU machines (multiple GPUs *visible* to this process) the
+ NVIDIA driver spawns extra background threads, making ``os.fork()``
+ deadlock-prone with many workers, so this caps ``num_proc`` to 4.
+ The cap does not apply when ``CUDA_VISIBLE_DEVICES`` restricts to one GPU.
Args:
desired: The num_proc you *want*. If None, auto-computes from
@@ -1964,9 +1946,8 @@ def safe_num_proc(desired: Optional[int] = None) -> int:
Returns:
A safe integer ≥ 1.
"""
- # Windows and macOS use 'spawn' for multiprocessing -- the overhead of
- # re-importing torch/transformers/unsloth per worker is typically slower
- # than single-process.
+ # Windows/macOS use 'spawn'; re-importing torch/transformers/unsloth per
+ # worker is typically slower than single-process.
if sys.platform in ("win32", "darwin"):
return 1
@@ -1989,9 +1970,8 @@ def safe_thread_num_proc(desired: Optional[int] = None) -> int:
"""
Return a safe worker count for ``ThreadPoolExecutor`` calls.
- Unlike ``safe_num_proc()``, this does NOT cap to 1 on macOS/Windows.
- Threads share the parent process address space and are unaffected by
- the ``spawn`` vs ``fork`` distinction.
+ Unlike ``safe_num_proc()``, does NOT cap to 1 on macOS/Windows: threads
+ share the parent address space, unaffected by ``spawn`` vs ``fork``.
Args:
desired: The thread count you *want*. If None, auto-computes
@@ -2010,9 +1990,9 @@ def dataset_map_num_proc(desired: Optional[int] = None) -> Optional[int]:
"""
Return a safe ``num_proc`` for ``Dataset.map()`` and ``Dataset.filter()``.
- Returns ``None`` on spawn-based platforms (Windows, macOS) because
- ``datasets`` treats ``num_proc=1`` as multiprocessing (creates ``Pool(1)``).
- Only ``num_proc=None`` guarantees in-process execution.
+ Returns ``None`` on spawn platforms (Windows, macOS) because ``datasets``
+ treats ``num_proc=1`` as multiprocessing (creates ``Pool(1)``); only
+ ``num_proc=None`` guarantees in-process execution.
"""
if sys.platform in ("win32", "darwin"):
return None
diff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.py
index 6cead61f08f..b8f307df9ed 100644
--- a/studio/backend/utils/hardware/nvidia.py
+++ b/studio/backend/utils/hardware/nvidia.py
@@ -110,9 +110,9 @@ def get_primary_gpu_utilization() -> dict[str, Any]:
def get_visible_gpu_utilization(
parent_visible_ids: Optional[list[int]], parent_cuda_visible_devices: Optional[str] = None
) -> dict[str, Any]:
- # When parent_visible_ids is None (UUID/MIG mask), we cannot safely
- # map nvidia-smi rows to the process's visible devices. Return empty
- # instead of exposing all physical GPUs.
+ # parent_visible_ids None (UUID/MIG mask): can't safely map
+ # nvidia-smi rows to visible devices. Return empty rather than
+ # exposing all physical GPUs.
if parent_visible_ids is None:
return {
"available": False,
@@ -196,8 +196,8 @@ def get_visible_gpu_utilization(
def get_backend_visible_gpu_info(
parent_visible_ids: Optional[list[int]], backend_cuda_visible_devices: Optional[str]
) -> dict[str, Any]:
- # When parent_visible_ids is None (UUID/MIG mask), we cannot safely
- # map nvidia-smi rows to the process's visible devices.
+ # parent_visible_ids None (UUID/MIG mask): can't safely map
+ # nvidia-smi rows to visible devices.
if parent_visible_ids is None:
return {
"available": False,
@@ -249,7 +249,7 @@ def get_backend_visible_gpu_info(
continue
if visible_ordinals is not None and idx not in visible_ordinals:
continue
- # Use split with limit to handle GPU names containing commas
+ # Rejoin in case the GPU name contains commas
name = parts[1] if len(parts) == 3 else ", ".join(parts[1:-1])
try:
mem_total_mb = int(parts[-1])
diff --git a/studio/backend/utils/hardware/vram_estimation.py b/studio/backend/utils/hardware/vram_estimation.py
index ddc39733e33..51903e0c97c 100644
--- a/studio/backend/utils/hardware/vram_estimation.py
+++ b/studio/backend/utils/hardware/vram_estimation.py
@@ -59,8 +59,8 @@ OPTIMIZER_BYTES_PER_PARAM: Dict[str, int] = {
}
# (full_ft_multiplier, lora_multiplier) — fraction of num_layers.
-# LoRA: frozen base layers skip activation storage, but you always need
-# at least ~1 layer in flight during backprop recomputation.
+# LoRA: frozen base layers skip activation storage, but ~1 layer is always
+# in flight during backprop recomputation.
GC_LAYER_MULTIPLIERS = {
"none": (None, None),
"true": (2.0, 1.0),
@@ -125,8 +125,7 @@ class VramBreakdown:
gradients: int
activations: int
cuda_overhead: int
- # Equals `activations`; retained for backward compatibility with
- # consumers that read this field.
+ # Equals `activations`; kept for backward compat with field consumers.
activations_computed: int = 0
@property
@@ -141,10 +140,10 @@ class VramBreakdown:
)
def min_gpu_vram(self, n_gpus: int) -> int:
- """Minimum VRAM a single GPU needs: its shard + non-shardable costs.
+ """Min VRAM one GPU needs: its shard + non-shardable costs.
- Weights/LoRA/optimizer/gradients shard across GPUs.
- Activations do NOT shard (the GPU running a layer holds them).
+ Weights/LoRA/optimizer/gradients shard across GPUs; activations do
+ NOT (the GPU running a layer holds them).
"""
shardable = self.model_weights + self.lora_adapters + self.optimizer_states + self.gradients
per_gpu_fixed = self.activations + self.cuda_overhead
@@ -163,7 +162,7 @@ class VramBreakdown:
def _first_scalar(value):
- # why: ERNIE MoE configs ship moe_intermediate_size / moe_num_experts as
+ # ERNIE MoE ships moe_intermediate_size / moe_num_experts as
# [routed, shared] lists; downstream arithmetic needs the routed scalar.
if isinstance(value, (list, tuple)):
return value[0] if value else None
@@ -171,8 +170,8 @@ def _first_scalar(value):
def _max_scalar(value):
- # why: Hunyuan-V1-MoE moe_topk can be a per-layer list; activation
- # accounting uses the max top-k as a conservative upper bound.
+ # Hunyuan-V1-MoE moe_topk can be a per-layer list; activation accounting
+ # uses max top-k as a conservative upper bound.
if isinstance(value, (list, tuple)):
items = [v for v in value if v is not None]
return max(items) if items else None
@@ -181,8 +180,8 @@ def _max_scalar(value):
def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
"""Layer indices that use dense MLP instead of MoE. Position matters."""
- # why: transformers Exaone-MoE / Laguna / Hy_v3 / GLM-MoE-DSA / GLM4-MoE-Lite /
- # Ernie4_5_VL_MoE prefer per-position `mlp_layer_types` over the prefix-style
+ # Exaone-MoE / Laguna / Hy_v3 / GLM-MoE-DSA / GLM4-MoE-Lite / Ernie4_5_VL_MoE
+ # prefer per-position `mlp_layer_types` over prefix-style
# `first_k_dense_replace` and may omit `decoder_sparse_step` entirely.
layer_types = getattr(text_config, "mlp_layer_types", None)
if layer_types:
@@ -190,7 +189,7 @@ def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
i for i, t in enumerate(layer_types[:total_layers]) if str(t).lower() == "dense"
)
- # why: Llama4TextConfig.__init__ auto-populates self.moe_layers from
+ # Llama4TextConfig.__init__ auto-populates self.moe_layers from
# interleave_moe_layer_step; Llama4TextDecoderLayer dispatches via
# `layer_idx in config.moe_layers` (modeling_llama4.py).
llama4_moe_layers = getattr(text_config, "moe_layers", None)
@@ -198,9 +197,9 @@ def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
moe_indices = {int(i) for i in llama4_moe_layers}
return tuple(i for i in range(total_layers) if i not in moe_indices)
- # why: transformers ERNIE 4.5 MoE / ERNIE 4.5 VL MoE declare MoE layers
- # via moe_layer_start_index / moe_layer_end_index / moe_layer_interval;
- # the model's per-layer guard is `(layer_idx + 1) % interval == 0` with
+ # ERNIE 4.5 MoE / ERNIE 4.5 VL MoE declare MoE layers via
+ # moe_layer_start_index / moe_layer_end_index / moe_layer_interval; the
+ # per-layer guard is `(layer_idx + 1) % interval == 0` with
# start <= layer_idx <= end (modeling_ernie4_5_moe.py).
moe_start = getattr(text_config, "moe_layer_start_index", None)
moe_interval = getattr(text_config, "moe_layer_interval", None)
@@ -261,8 +260,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
num_kv_heads = getattr(text_config, "num_key_value_heads", num_heads)
- # why: DBRX places its MoE attrs on the DbrxFFNConfig sub-config; probe
- # ffn_config as a secondary source so DBRX is not misclassified as dense.
+ # DBRX places its MoE attrs on the DbrxFFNConfig sub-config; probe
+ # ffn_config as a secondary source so DBRX isn't misclassified as dense.
ffn_config = getattr(text_config, "ffn_config", None)
def _moe_attr(name):
@@ -286,8 +285,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
if moe_intermediate_raw is None:
moe_intermediate_raw = _moe_attr("ffn_hidden_size")
moe_intermediate = _first_scalar(moe_intermediate_raw)
- # why: Exaone-MoE / ERNIE families alias num_shared_experts /
- # moe_num_shared_experts to the canonical n_shared_experts.
+ # Exaone-MoE / ERNIE alias num_shared_experts / moe_num_shared_experts
+ # to the canonical n_shared_experts.
n_shared_experts = (
_first_scalar(_moe_attr("n_shared_experts"))
or _first_scalar(_moe_attr("num_shared_experts"))
@@ -297,9 +296,9 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
shared_expert_intermediate_size = _moe_attr("shared_expert_intermediate_size")
if shared_expert_intermediate_size and n_shared_experts == 0:
n_shared_experts = 1
- # why: DBRX exposes moe_top_k, Hunyuan-V1-MoE exposes moe_topk (which can
- # be a per-layer list); _max_scalar normalizes list values to the worst
- # case so int(...) below cannot crash on the canonical attribute_map path.
+ # DBRX exposes moe_top_k; Hunyuan-V1-MoE exposes moe_topk (can be a
+ # per-layer list). _max_scalar normalizes lists to the worst case so
+ # int(...) below cannot crash on the canonical attribute_map path.
num_experts_per_tok = (
_max_scalar(_moe_attr("num_experts_per_tok"))
or _max_scalar(_moe_attr("top_k_experts"))
@@ -313,9 +312,9 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
dense_layer_indices = _compute_dense_layer_indices(text_config, num_layers)
num_dense_layers = len(dense_layer_indices)
- # why: Llama4 dense layers use intermediate_size_mlp; routed and shared
- # experts use intermediate_size. Llama4TextMoe builds one shared_expert
- # per MoE layer (modeling_llama4.py).
+ # Llama4 dense layers use intermediate_size_mlp; routed/shared experts use
+ # intermediate_size. Llama4TextMoe builds one shared_expert per MoE layer
+ # (modeling_llama4.py).
intermediate_size_mlp_raw = _first_scalar(_moe_attr("intermediate_size_mlp"))
dense_intermediate_size = (
int(intermediate_size_mlp_raw) if intermediate_size_mlp_raw is not None else None
@@ -386,8 +385,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
def _targets_all_linear(target_modules) -> bool:
- # why: peft LoraConfig accepts target_modules="all-linear" as a bare
- # string; iterating a string yields chars and never matches the set.
+ # peft LoraConfig accepts target_modules="all-linear" as a bare string;
+ # iterating a string yields chars and never matches the set.
if isinstance(target_modules, str):
target_modules = [target_modules]
normalized = {str(module).lower().replace("_", "-") for module in target_modules}
@@ -425,10 +424,9 @@ def _is_kv_shared_layer(arch: ModelArchConfig, layer_idx: int) -> bool:
if arch.num_kv_shared_layers <= 0:
return False
first_shared = arch.num_hidden_layers - arch.num_kv_shared_layers
- # why: transformers Gemma4 (modeling_gemma4.py:1031, modular_gemma4.py:863)
- # uses the same `> 0` guard so a fully-shared config raises during model
- # construction; matching upstream avoids producing a detailed estimate
- # for a shape the actual model code rejects.
+ # Gemma4 (modeling_gemma4.py:1031, modular_gemma4.py:863) uses the same
+ # `> 0` guard so a fully-shared config raises at model construction;
+ # matching upstream avoids estimating a shape the model code rejects.
return layer_idx >= first_shared > 0
@@ -439,9 +437,9 @@ def _is_dense_mlp_layer(arch: ModelArchConfig, layer_idx: int) -> bool:
def _per_layer_input_quantizable(arch: ModelArchConfig) -> int:
- # why: Gemma4 PLE block adds per_layer_model_projection (single Linear),
+ # Gemma4 PLE block adds per_layer_model_projection (single Linear),
# per_layer_input_gate (per layer), and per_layer_projection (per layer);
- # see transformers gemma4/modular_gemma4.py:1077-1083 and :1247-1253.
+ # see gemma4/modular_gemma4.py:1077-1083 and :1247-1253.
pli = arch.hidden_size_per_layer_input
if pli <= 0:
return 0
@@ -460,10 +458,10 @@ def _per_layer_input_norm_elements(arch: ModelArchConfig) -> int:
def _per_layer_input_lora_params(arch: ModelArchConfig, r: int, target_modules) -> int:
- # why: Unsloth's get_peft_regex (unsloth_zoo/peft_utils.py) requires module
- # names to contain a component tag (mlp/attn/...); PLE module names lack
- # any tag, so all-linear training does NOT attach LoRA to them. Only count
- # PLE LoRA when the user explicitly names PLE modules.
+ # Unsloth's get_peft_regex (unsloth_zoo/peft_utils.py) requires module
+ # names to contain a component tag (mlp/attn/...); PLE names lack any tag,
+ # so all-linear does NOT attach LoRA to them. Only count PLE LoRA when the
+ # user explicitly names PLE modules.
pli = arch.hidden_size_per_layer_input
if pli <= 0:
return 0
@@ -543,17 +541,17 @@ def _module_path_matches(skip_module: str, alias: str) -> bool:
if alias_parts[0] == "layers":
return skip_parts == alias_parts
if len(skip_parts) <= len(alias_parts):
- # why: transformers BNB quantizer suffix-matches short skip entries
- # like ["q_proj"] / ["lm_head"] against full module paths, so a skip
- # shorter than the alias is a tail match.
+ # BNB quantizer suffix-matches short skip entries like ["q_proj"] /
+ # ["lm_head"] against full paths, so a skip shorter than the alias is
+ # a tail match.
return alias_parts[-len(skip_parts) :] == skip_parts
if skip_parts[-len(alias_parts) :] != alias_parts:
return False
prefix_parts = skip_parts[: len(skip_parts) - len(alias_parts)]
if not prefix_parts:
return True
- # why: bound the prefix to known text-tower roots so VLM skip names like
- # vision_tower.model.layers.<i>.self_attn.q_proj do not shadow the text
+ # Bound the prefix to known text-tower roots so VLM skip names like
+ # vision_tower.model.layers.<i>.self_attn.q_proj don't shadow the text
# alias model.layers.<i>.self_attn.q_proj.
return ".".join(prefix_parts) in _SKIP_MODULE_TEXT_PREFIXES
@@ -587,9 +585,9 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
mlp_dims = {name: dim for name, dim in dims.items() if name in MLP_TARGET_MODULES}
if is_mla:
- # why: _text_linear_dims uses (hd, hd) for q/o; MLA actually splits
- # into q_a/q_b/kv_a/kv_b, so emit a single self_attn aggregate at
- # the authoritative MLA per-layer total.
+ # _text_linear_dims uses (hd, hd) for q/o; MLA splits into
+ # q_a/q_b/kv_a/kv_b, so emit a single self_attn aggregate at the
+ # authoritative MLA per-layer total.
layer_modules["self_attn"] = _compute_attn_elements(arch)
else:
for name, (in_dim, out_dim) in attn_dims.items():
@@ -607,17 +605,17 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
layer_modules["mlp.experts"] = _compute_routed_moe_elements(arch)
shared_moe = _compute_shared_moe_elements(arch)
if shared_moe:
- # why: Qwen3.5-MoE exposes shared expert as
- # mlp.shared_expert; Exaone-MoE/Laguna/GLM-style configs use
- # mlp.shared_experts. Register both names so child-path
- # llm_int8_skip_modules entries match the right shared block.
+ # Qwen3.5-MoE exposes shared expert as mlp.shared_expert;
+ # Exaone-MoE/Laguna/GLM-style use mlp.shared_experts.
+ # Register both names so child-path llm_int8_skip_modules
+ # entries match the right shared block.
layer_modules["mlp.shared_expert"] = shared_moe
if arch.moe_has_dense_mlp:
- # why: enable_moe_block runs the dense MLP and the MoE
- # experts in parallel; register both for skip matching.
- # Non-structured _text_linear_dims returns mlp_size from
- # _get_mlp_size which prefers moe_intermediate_size, so
- # rebuild dense dims from arch.intermediate_size directly.
+ # enable_moe_block runs the dense MLP and MoE experts in
+ # parallel; register both for skip matching. Non-structured
+ # _text_linear_dims returns mlp_size from _get_mlp_size
+ # (prefers moe_intermediate_size), so rebuild dense dims
+ # from arch.intermediate_size directly.
if _uses_structured_layer_shapes(arch):
dense_dims = mlp_dims
else:
@@ -640,8 +638,8 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
)
if pli > 0:
- # why: register PLE per-layer linears so llm_int8_skip_modules
- # entries like model.layers.0.per_layer_input_gate match.
+ # Register PLE per-layer linears so llm_int8_skip_modules entries
+ # like model.layers.0.per_layer_input_gate match.
layer_modules["per_layer_input_gate"] = hd_global * pli
layer_modules["per_layer_projection"] = pli * hd_global
@@ -650,10 +648,10 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
for name, value in layer_modules.items()
if name == "self_attn" or name.startswith("self_attn.")
)
- # why: gemma4 enable_moe_block puts routed experts at the sibling
+ # gemma4 enable_moe_block puts routed experts at the sibling
# layers.<i>.experts attribute, not under self.mlp; the layer's "mlp"
# aggregate must reflect only the dense MLP path so a skip module
- # `model.layers.0.mlp` does not over-skip into the experts block.
+ # `model.layers.0.mlp` doesn't over-skip into the experts block.
is_sibling_experts = bool(arch.moe_has_dense_mlp)
mlp_total = sum(
value
@@ -683,11 +681,11 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
elements[canonical] = value
_add_module_aliases(aliases, canonical, canonical.removeprefix("text."))
if name == "mlp.experts" and arch.moe_has_dense_mlp:
- # why: gemma4 enable_moe_block exposes routed experts at
+ # gemma4 enable_moe_block exposes routed experts at
# layers.<i>.experts (sibling of self.mlp), not under mlp.
_add_module_aliases(aliases, canonical, f"layers.{layer_idx}.experts")
elif name == "mlp.shared_expert":
- # why: Exaone-MoE / Laguna / GLM-style configs use the plural
+ # Exaone-MoE / Laguna / GLM-style use the plural
# `shared_experts` attribute name; register both spellings.
_add_module_aliases(
aliases,
@@ -733,8 +731,8 @@ def _get_mlp_size(arch: ModelArchConfig) -> int:
def _dense_mlp_size(arch: ModelArchConfig) -> int:
- # why: Llama4 dense layers use intermediate_size_mlp; routed/shared
- # experts use intermediate_size. Other configs leave the field None.
+ # Llama4 dense layers use intermediate_size_mlp; routed/shared experts use
+ # intermediate_size. Other configs leave the field None.
return arch.dense_intermediate_size or arch.intermediate_size
@@ -764,7 +762,7 @@ def _compute_dense_mlp_elements(arch: ModelArchConfig) -> int:
def _shared_expert_size(arch: ModelArchConfig) -> int:
- # why: Qwen3.5-MoE shared expert has its own intermediate_size (default 512)
+ # Qwen3.5-MoE shared expert has its own intermediate_size (default 512)
# distinct from moe_intermediate_size; fall back to routed mlp_size for
# families that share it (deepseek-style configs).
return arch.shared_expert_intermediate_size or _get_mlp_size(arch)
@@ -782,10 +780,10 @@ def _compute_shared_moe_elements(arch: ModelArchConfig) -> int:
hd = arch.hidden_size
shared_size = _shared_expert_size(arch)
total = hd * shared_size * 3 * arch.n_shared_experts
- # why: only Qwen2-MoE / Qwen3.5-MoE define a shared_expert_gate Linear
- # (hidden_size→1); other families (Exaone-MoE, HY-V3, GLM4-MoE-Lite, Laguna)
- # have shared_experts without a gate. shared_expert_intermediate_size is the
- # Qwen-style discriminator.
+ # Only Qwen2-MoE / Qwen3.5-MoE define a shared_expert_gate Linear
+ # (hidden_size->1); other families (Exaone-MoE, HY-V3, GLM4-MoE-Lite,
+ # Laguna) have shared_experts without a gate.
+ # shared_expert_intermediate_size is the Qwen-style discriminator.
if arch.shared_expert_intermediate_size:
total += arch.n_shared_experts * hd
return total
@@ -824,8 +822,8 @@ def _compute_layer_elements(arch: ModelArchConfig):
n_moe = n_layers - n_dense
moe_mlp_total = _compute_moe_mlp_elements(arch) * n_moe
if arch.moe_has_dense_mlp:
- # why: enable_moe_block runs dense MLP and MoE experts in
- # parallel; count dense for every layer alongside MoE.
+ # enable_moe_block runs dense MLP and MoE experts in parallel;
+ # count dense for every layer alongside MoE.
mlp_total = sum(per_layer_dense_mlp) + moe_mlp_total
else:
dense_only_total = sum(
@@ -958,11 +956,10 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
if n_experts > 1:
n_dense = arch.num_dense_layers
n_moe = n_layers - n_dense
- # why: peft "all-linear" attaches LoRA to nn.Linear only;
- # routed experts are nn.Parameter and need explicit
- # gate_proj/up_proj/down_proj naming via Unsloth's
- # get_moe_target_parameters. Shared experts are nn.Linear and
- # are picked up by get_peft_regex.
+ # peft "all-linear" attaches LoRA to nn.Linear only; routed experts
+ # are nn.Parameter and need explicit gate_proj/up_proj/down_proj
+ # naming via Unsloth's get_moe_target_parameters. Shared experts are
+ # nn.Linear, picked up by get_peft_regex.
routed_moe = (
0
if all_linear
@@ -983,7 +980,7 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
)
moe_mlp = routed_moe + shared_moe
if arch.moe_has_dense_mlp:
- # why: parallel dense MLP coexists with MoE on every layer.
+ # Parallel dense MLP coexists with MoE on every layer.
mlp_total = structured_dense_mlp + moe_mlp * n_moe
else:
dense_only = sum(
@@ -999,7 +996,7 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
attn_total = _lora_attn_elements(arch, r, selected_modules) * n_layers
n_dense = arch.num_dense_layers
n_moe = n_layers - n_dense
- # why: routed and shared experts may use different intermediate sizes
+ # Routed and shared experts may use different intermediate sizes
# (Qwen3.5-MoE: routed mlp_size != shared_expert_intermediate_size).
# See structured branch for the all-linear exclusion rationale; only
# routed (nn.Parameter) experts are excluded under all-linear.
@@ -1064,7 +1061,7 @@ def compute_gradient_bytes(trainable_params: int) -> int:
def _is_linear_attention(attention_implementation: Optional[str]) -> bool:
- # why: PyTorch SDPA dispatches to flash/memory-efficient O(n) backends; only
+ # PyTorch SDPA dispatches to flash/memory-efficient O(n) backends; only
# eager (and other non-flash impls) need the quadratic correction.
return attention_implementation in LINEAR_ATTENTION_IMPLS
@@ -1081,16 +1078,16 @@ def _layer_qkv_mlp_sizes(arch: ModelArchConfig, layer_idx: int) -> tuple:
is_moe_layer = n_experts > 1 and not _is_dense_mlp_layer(arch, layer_idx)
if _uses_structured_layer_shapes(arch):
q_size, kv_size, _has_k, _has_v = _layer_attention_dims(arch, layer_idx)
- # why: KV-shared layers (Gemma4/Gemma3n) drop k_proj/v_proj WEIGHTS but
- # the donor layer's K/V tensors stay alive across the shared range, so
- # activation memory still pays for kv_size; only the weight path uses
+ # KV-shared layers (Gemma4/Gemma3n) drop k_proj/v_proj WEIGHTS but the
+ # donor layer's K/V tensors stay alive across the shared range, so
+ # activation memory still pays kv_size; only the weight path uses
# has_k/has_v.
layer_type = _layer_types(arch)[layer_idx]
use_alt_attention = arch.attention_k_eq_v and layer_type != "sliding_attention"
kv_count = 1 if use_alt_attention else 2
qkv_size = q_size + kv_size * kv_count
if is_moe_layer:
- # why: each token routes through `num_experts_per_tok` experts; their
+ # Each token routes through `num_experts_per_tok` experts; their
# gate/up/down intermediates are all live during MLP forward.
mlp_size = _get_mlp_size(arch) * arch.num_experts_per_tok
if arch.n_shared_experts:
@@ -1119,9 +1116,9 @@ def _per_layer_activation_bytes(
activation_qkv = seq_len * batch_size * qkv_size
residual_memory = (seq_len * batch_size) * 2
activation_mlp = seq_len * batch_size * (mlp_size + mlp_size)
- # why: per_layer_input_gate (hd-sized) and per_layer_projection (pli-sized)
- # outputs materialize once per decoder layer when hidden_size_per_layer_input
- # is set; see gemma4/modular_gemma4.py:1141-1145.
+ # per_layer_input_gate (hd-sized) and per_layer_projection (pli-sized)
+ # outputs materialize once per decoder layer when
+ # hidden_size_per_layer_input is set; see gemma4/modular_gemma4.py:1141-1145.
pli = arch.hidden_size_per_layer_input
activation_ple = seq_len * batch_size * (arch.hidden_size + pli) if pli > 0 else 0
return int((activation_qkv + residual_memory + activation_mlp + activation_ple) * 2 * 1.25)
@@ -1154,8 +1151,8 @@ def compute_activation_bytes(
)
linear_bytes = int(max_layer_bytes * effective_layers)
- # why: gemma4 per_layer_model_projection runs once outside the per-decoder
- # loop and materializes a [B, S, L, PLI] tensor; see modular_gemma4.py:1247.
+ # gemma4 per_layer_model_projection runs once outside the per-decoder loop
+ # and materializes a [B, S, L, PLI] tensor; see modular_gemma4.py:1247.
pli = arch.hidden_size_per_layer_input
if pli > 0:
linear_bytes += int(seq_len * batch_size * n_layers * pli * 2 * 1.25)
diff --git a/studio/backend/utils/inference/inference_config.py b/studio/backend/utils/inference/inference_config.py
index e07bc62cfdf..87e2aac833c 100644
--- a/studio/backend/utils/inference/inference_config.py
+++ b/studio/backend/utils/inference/inference_config.py
@@ -4,9 +4,9 @@
"""
Inference configuration loading utilities.
-This module provides functions to load inference parameters (temperature, top_p, top_k, min_p)
-from model YAML configuration files, with fallback to default.yaml.
-Includes family-based lookup from inference_defaults.json for GGUF models.
+Loads inference parameters (temperature, top_p, top_k, min_p) from model YAML
+configs, falling back to default.yaml. Includes family-based lookup from
+inference_defaults.json for GGUF models.
"""
from pathlib import Path
@@ -51,8 +51,8 @@ def get_family_inference_params(model_id: str) -> Dict[str, Any]:
"""
Look up recommended inference parameters by model family.
- Extracts the model family from the identifier (e.g. "unsloth/Qwen3.5-9B-GGUF" -> "qwen3.5")
- and returns the matching parameters from inference_defaults.json.
+ Extracts the family from the identifier (e.g. "unsloth/Qwen3.5-9B-GGUF" ->
+ "qwen3.5") and returns the matching params from inference_defaults.json.
Args:
model_id: Model identifier (e.g. "unsloth/Qwen3.5-9B-GGUF")
@@ -65,12 +65,12 @@ def get_family_inference_params(model_id: str) -> Dict[str, Any]:
if not _FAMILY_PATTERNS or not _FAMILY_DEFAULTS:
return {}
- # Normalize: lowercase, strip org prefix
+ # Normalize: lowercase, strip org prefix.
normalized = model_id.lower()
if "/" in normalized:
normalized = normalized.split("/", 1)[1]
- # Match against patterns (ordered longest-match-first in the JSON)
+ # Match patterns (ordered longest-match-first in the JSON).
for pattern in _FAMILY_PATTERNS:
if pattern in normalized:
params = _FAMILY_DEFAULTS.get(pattern, {})
@@ -87,14 +87,13 @@ def _has_specific_yaml(model_identifier: str) -> bool:
script_dir = Path(__file__).parent.parent.parent
defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
- # Check the mapping
+ # Check the mapping.
if model_identifier.lower() in _REVERSE_MODEL_MAPPING:
return True
- # For local filesystem paths (e.g. C:\Users\...\model on Windows),
- # normalize backslashes so Path().parts splits correctly on POSIX/WSL,
- # then try matching the last 1-2 path components against the registry
- # (mirrors the logic in load_model_defaults).
+ # For local paths (e.g. C:\Users\...\model on Windows), normalize backslashes
+ # so Path().parts splits correctly on POSIX/WSL, then match the last 1-2 path
+ # components against the registry (mirrors load_model_defaults).
_is_local = is_local_path(model_identifier)
_normalized = normalize_path(model_identifier) if _is_local else model_identifier
@@ -109,9 +108,8 @@ def _has_specific_yaml(model_identifier: str) -> bool:
else:
_lookup = model_identifier
- # Check for exact filename match (basename for local paths to avoid
- # passing absolute paths into rglob which raises
- # "Non-relative patterns are unsupported" on Windows).
+ # Exact filename match (basename for local paths; passing absolute paths to
+ # rglob raises "Non-relative patterns are unsupported" on Windows).
model_filename = _lookup.replace("/", "_") + ".yaml"
for config_path in defaults_dir.rglob(model_filename):
if config_path.is_file():
@@ -125,15 +123,15 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
Load inference configuration parameters for a model.
Priority chain:
- 1. Model-specific YAML (if it exists and has inference params)
- 2. Family-based defaults from inference_defaults.json
- 3. default.yaml fallback
+ 1. Model-specific YAML (if it exists and has inference params).
+ 2. Family-based defaults from inference_defaults.json.
+ 3. default.yaml fallback.
Args:
model_identifier: Model identifier (e.g., "unsloth/llama-3-8b-bnb-4bit")
Returns:
- Dictionary containing inference parameters:
+ Dict of inference parameters:
{
"temperature": float,
"top_p": float,
@@ -141,10 +139,10 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
"min_p": float
}
"""
- # Load model defaults to get inference parameters
+ # Model defaults for inference parameters.
model_defaults = load_model_defaults(model_identifier)
- # Load default.yaml for fallback values
+ # default.yaml for fallback values.
script_dir = Path(__file__).parent.parent.parent
defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
default_config_path = defaults_dir / "default.yaml"
@@ -158,18 +156,18 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
except Exception as e:
logger.warning(f"Failed to load default.yaml: {e}")
- # Family-based defaults from inference_defaults.json
+ # Family-based defaults from inference_defaults.json.
family_params = get_family_inference_params(model_identifier)
model_inference = model_defaults.get("inference", {})
- # If the model has its own YAML config, those values take priority over family defaults.
- # If it only fell back to default.yaml, family defaults take priority.
+ # Model's own YAML beats family defaults; if it only fell back to
+ # default.yaml, family defaults win.
has_own_yaml = _has_specific_yaml(model_identifier)
def _get_param(key, hardcoded_default):
if has_own_yaml:
- # Model-specific YAML wins, then family fills gaps, then default.yaml
+ # Model-specific YAML wins, then family fills gaps, then default.yaml.
val = model_inference.get(key)
if val is not None and isinstance(val, (int, float)):
return val
@@ -177,7 +175,7 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
return family_params[key]
return default_inference.get(key, hardcoded_default)
else:
- # No model-specific YAML: family wins, then default.yaml
+ # No model-specific YAML: family wins, then default.yaml.
if key in family_params:
return family_params[key]
return default_inference.get(key, hardcoded_default)
diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.py
index f0e642a38e9..3635969c73b 100644
--- a/studio/backend/utils/llama_cpp_freshness.py
+++ b/studio/backend/utils/llama_cpp_freshness.py
@@ -45,7 +45,7 @@ def _cache_dir() -> Path:
def read_install_marker(binary_path: Optional[str]) -> Optional[dict]:
"""Walk up from binary_path to find UNSLOTH_PREBUILT_INFO.json.
- None means no marker (source build / custom path) or invalid JSON."""
+ None = no marker (source build / custom path) or invalid JSON."""
if not binary_path:
return None
cached = _marker_cache.get(binary_path)
diff --git a/studio/backend/utils/models/checkpoints.py b/studio/backend/utils/models/checkpoints.py
index 99770ce7a65..80312af0f74 100644
--- a/studio/backend/utils/models/checkpoints.py
+++ b/studio/backend/utils/models/checkpoints.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Checkpoint scanning utilities for discovering training runs and their checkpoints.
-"""
+"""Checkpoint scanning utilities for discovering training runs and checkpoints."""
import json
import structlog
@@ -17,7 +15,7 @@ logger = get_logger(__name__)
def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:
"""
- Read the training loss from a checkpoint's trainer_state.json.
+ Read training loss from a checkpoint's trainer_state.json.
Returns the loss from the last log_history entry, or None if unavailable.
"""
@@ -91,8 +89,8 @@ def scan_checkpoints(
except Exception:
pass
- # Fallback: extract base model name from folder name
- # e.g. "unsloth_Llama-3.2-3B-Instruct_1771227800" → "unsloth/Llama-3.2-3B-Instruct"
+ # Fallback: extract base model name from the folder name, e.g.
+ # "unsloth_Llama-3.2-3B-Instruct_1771227800" → "unsloth/Llama-3.2-3B-Instruct"
if not metadata.get("base_model"):
parts = item.name.rsplit("_", 1)
if len(parts) == 2 and parts[1].isdigit():
@@ -103,13 +101,13 @@ def scan_checkpoints(
else:
metadata["base_model"] = name_part
- # This is a valid training run
+ # Valid training run.
checkpoints = []
- # Placeholder for the main adapter — loss filled from last checkpoint below
+ # Main adapter placeholder — loss filled from the last checkpoint below.
checkpoints.append((item.name, str(item), None))
- # Scan for intermediate checkpoints (checkpoint-N subdirs)
+ # Scan for intermediate checkpoints (checkpoint-N subdirs).
for sub in sorted(item.iterdir()):
if not sub.is_dir() or not sub.name.startswith("checkpoint-"):
continue
@@ -119,7 +117,7 @@ def scan_checkpoints(
loss = _read_checkpoint_loss(sub)
checkpoints.append((sub.name, str(sub), loss))
- # Assign the last checkpoint's loss to the main adapter entry
+ # Assign the last checkpoint's loss to the main adapter entry.
if len(checkpoints) > 1:
last_checkpoint_loss = checkpoints[-1][2]
checkpoints[0] = (
diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.py
index 32618773b7d..a2912cc8433 100644
--- a/studio/backend/utils/models/gguf_metadata.py
+++ b/studio/backend/utils/models/gguf_metadata.py
@@ -1,10 +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
-"""Free-function ``general.*`` reader for GGUF headers, used by
-``detect_mmproj_file`` to pair weights and projectors via
-``general.base_model.0.repo_url``. ~30 ms per file, cached by
-(path, mtime, size)."""
+"""``general.*`` reader for GGUF headers, used by ``detect_mmproj_file`` to
+pair weights and projectors via ``general.base_model.0.repo_url``. ~30 ms
+per file, cached by (path, mtime, size)."""
from __future__ import annotations
@@ -65,9 +64,9 @@ def _cache_key(path: str) -> Optional[_CacheKey]:
def read_gguf_general_metadata(path: str) -> Optional[Dict[str, str]]:
- """Return ``general.*`` strings from a GGUF header, or ``None`` if
- the file is missing, unreadable, or not a GGUF. ``{}`` means the
- file is valid but carries none of the wanted keys."""
+ """Return ``general.*`` strings from a GGUF header, or ``None`` if the
+ file is missing, unreadable, or not a GGUF. ``{}`` means valid but
+ carrying none of the wanted keys."""
key = _cache_key(path)
if key is None:
return None
@@ -156,9 +155,9 @@ _FIXED_VTYPE_SIZES: Dict[int, int] = {
def _skip_gguf_value(f, vtype: int) -> bool:
- """Advance past one GGUF value. ``f.seek(.., 1)`` past EOF is legal
- on a regular file so truncation is detected on the next read; we
- only return False for unknown types or sanity-bound overflow."""
+ """Advance past one GGUF value. ``f.seek(.., 1)`` past EOF is legal on a
+ regular file, so truncation is caught on the next read; return False only
+ for unknown types or sanity-bound overflow."""
if vtype == 8: # STRING
slen_bytes = f.read(8)
if len(slen_bytes) < 8:
@@ -265,9 +264,9 @@ def _read_gguf_bool(path: str, wanted_key: str) -> Optional[bool]:
def read_mmproj_audio_capability(path: str) -> Optional[bool]:
- """``clip.has_audio_encoder`` from an mmproj GGUF (e.g. Gemma 4's gemma4ua):
- ``True``/``False`` if present, ``None`` if absent / unreadable. Flags
- audio-input models independently of tokenizer token names."""
+ """``clip.has_audio_encoder`` from an mmproj GGUF (e.g. Gemma 4's
+ gemma4ua): ``True``/``False`` if present, ``None`` if absent/unreadable.
+ Flags audio-input models independently of tokenizer token names."""
return _read_gguf_bool(path, "clip.has_audio_encoder")
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 2947bab3d39..abddd073679 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Model and LoRA configuration handling
-"""
+"""Model and LoRA configuration handling."""
from dataclasses import dataclass
from typing import Optional, Dict, Any
@@ -58,7 +56,7 @@ def _env_offline() -> bool:
import re as _re
_MODEL_SIZE_RE = _re.compile(r"(?:^|[-_/])(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)
-# MoE active-parameter pattern: matches "A3B", "A3.5B", etc.
+# MoE active-parameter pattern: "A3B", "A3.5B", etc.
_ACTIVE_SIZE_RE = _re.compile(r"(?:^|[-_/])a(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)
@@ -66,8 +64,8 @@ def extract_model_size_b(model_id: str) -> float | None:
"""Extract model size in billions from a model identifier.
Prefers MoE active-parameter notation (e.g. ``A3B`` in
- ``Qwen3.5-35B-A3B``) over the total parameter count.
- Handles both ``B`` (billions) and ``M`` (millions) suffixes.
+ ``Qwen3.5-35B-A3B``) over total params. Handles ``B`` (billions)
+ and ``M`` (millions) suffixes.
"""
mid = (model_id or "").lower()
active = _ACTIVE_SIZE_RE.search(mid)
@@ -81,9 +79,9 @@ def extract_model_size_b(model_id: str) -> float | None:
return val / 1000.0 if size.group(2).lower() == "m" else val
-# Model name mapping: maps all equivalent model names to their canonical YAML config file
-# Format: "canonical_model_name.yaml": [list of all equivalent model names]
-# Based on the model mapper provided - canonical filename is based on the first model name in the mapper
+# Maps equivalent model names to their canonical YAML config file.
+# Format: "canonical_model_name.yaml": [equivalent model names].
+# Canonical filename derives from the first model name in each list.
MODEL_NAME_MAPPING = {
# ── Embedding models ──
"unsloth_all-MiniLM-L6-v2.yaml": [
@@ -457,7 +455,7 @@ MODEL_NAME_MAPPING = {
],
}
-# Reverse mapping for quick lookup: model_name -> canonical_filename
+# Reverse lookup: model_name -> canonical_filename
_REVERSE_MODEL_MAPPING = {}
for canonical_file, model_names in MODEL_NAME_MAPPING.items():
for model_name in model_names:
@@ -470,19 +468,17 @@ def load_model_config(
token: Optional[str] = None,
trust_remote_code: bool = True,
):
- """
- Load model config with optional authentication control.
- """
+ """Load model config with optional authentication control."""
from transformers import AutoConfig
if token:
- # Explicit token provided - use it
+ # Explicit token provided
return AutoConfig.from_pretrained(
model_name, trust_remote_code = trust_remote_code, token = token
)
if not use_auth:
- # Load without any authentication (for public model checks)
+ # No authentication (for public model checks)
with without_hf_auth():
return AutoConfig.from_pretrained(
model_name,
@@ -490,7 +486,7 @@ def load_model_config(
token = None,
)
- # Use default authentication (cached tokens)
+ # Default authentication (cached tokens)
return AutoConfig.from_pretrained(
model_name,
trust_remote_code = trust_remote_code,
@@ -588,8 +584,8 @@ _VISION_CHECK_INLINE_HELPERS = (
" )\n"
)
-# Inline script executed in a subprocess with transformers 5.x activated.
-# Receives model_name and token via argv, prints JSON result to stdout.
+# Subprocess script run with transformers 5.x active. Takes model_name and
+# token via argv, prints JSON result to stdout.
_VISION_CHECK_SCRIPT = (
r"""
import sys, os, json
@@ -636,10 +632,10 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)
with .venv_t5/ prepended to sys.path so AutoConfig recognizes newer
architectures (glm4_moe_lite, etc.).
- Returns True/False for definitive results, or None for transient failures
- (timeouts, subprocess errors) so callers can decide whether to cache
- the result. Subprocess failures are treated as transient because they
- can be caused by temporary HF/auth/network issues.
+ Returns True/False for definitive results, or None for transient
+ failures (timeouts, subprocess errors) so callers can decide whether
+ to cache. Subprocess failures are treated as transient since they may
+ stem from temporary HF/auth/network issues.
"""
token_arg = hf_token or ""
@@ -699,7 +695,7 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)
def _token_fingerprint(token: Optional[str]) -> Optional[str]:
- """Return a SHA256 digest of the token for use as a cache key.
+ """SHA256 digest of the token for use as a cache key.
Avoids storing the raw bearer token in process memory as a dict key.
"""
@@ -708,26 +704,26 @@ def _token_fingerprint(token: Optional[str]) -> Optional[str]:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
-# Cache vision detection results per session to avoid repeated subprocess spawns.
-# Keyed by (normalized_model_name, token_fingerprint) to handle gated models correctly.
-# Only definitive results (True/False from successful detection) are cached;
-# transient failures (network errors, timeouts) are NOT cached so they can be retried.
+# Cache vision detection per session to avoid repeated subprocess spawns.
+# Keyed by (normalized_model_name, token_fingerprint) to handle gated models.
+# Only definitive results are cached; transient failures (network, timeouts)
+# are NOT cached so they can be retried.
_vision_detection_cache: Dict[Tuple[str, Optional[str]], bool] = {}
_vision_cache_lock = threading.Lock()
def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
"""
- Detect vision-language models (VLMs) by checking architecture in config.
+ Detect vision-language models (VLMs) via architecture in config.
Works for fine-tuned models since they inherit the base architecture.
For models that require transformers 5.x (e.g. GLM-4.7-Flash), the check
runs in a subprocess with .venv_t5/ activated -- same pattern as the
training and inference workers.
- Results are cached per (model_name, token_fingerprint) for the lifetime of
- the process to avoid repeated subprocess spawns and HuggingFace API calls.
- Transient failures are not cached so they can be retried on the next call.
+ Results are cached per (model_name, token_fingerprint) for the process
+ lifetime to avoid repeated subprocess spawns and HuggingFace API calls.
+ Transient failures are not cached so they can be retried.
Args:
model_name: Model identifier (HF repo or local path)
@@ -749,21 +745,21 @@ def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
resolved_name = model_name
cache_key = (resolved_name, _token_fingerprint(hf_token))
- # Lock-free fast path for cache hits. Uses a sentinel to distinguish
- # "key not found" from "value is False" in a single atomic dict.get() call.
+ # Lock-free fast path for cache hits. Sentinel distinguishes "key not
+ # found" from "value is False" in a single atomic dict.get() call.
_MISS = object()
cached = _vision_detection_cache.get(cache_key, _MISS)
if cached is not _MISS:
return cached
# Compute outside the lock to avoid serializing long-running detection
- # (subprocess spawns with 60s timeout, HF API calls) across all models.
- # The tradeoff: two concurrent calls for the same uncached model may
- # both run detection, but they produce the same result and the second
- # write is a benign no-op.
+ # (60s-timeout subprocess spawns, HF API calls) across all models.
+ # Tradeoff: two concurrent calls for the same uncached model may both
+ # run detection, but produce the same result and the second write is a
+ # benign no-op.
result = _is_vision_model_uncached(resolved_name, hf_token)
- # Only cache definitive results; None means a transient failure occurred
- # and we should retry on the next call instead of locking in a wrong answer.
+ # Only cache definitive results; None means a transient failure, so
+ # retry on the next call instead of locking in a wrong answer.
if result is not None:
with _vision_cache_lock:
_vision_detection_cache[cache_key] = result
@@ -774,13 +770,12 @@ def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -> Optional[bool]:
"""Uncached vision model detection -- called by is_vision_model().
- Returns True/False for definitive results, or None when detection failed
- due to a transient error (network, timeout, subprocess failure) so the
- caller knows not to cache the result.
+ Returns True/False for definitive results, or None on transient errors
+ (network, timeout, subprocess failure) so the caller knows not to cache.
Do not call directly; use is_vision_model() instead.
"""
- # Models that need transformers 5.x must be checked in a subprocess
+ # Models needing transformers 5.x must be checked in a subprocess
# because AutoConfig in the main process (transformers 4.57.x) doesn't
# recognize their architectures.
from utils.transformers_version import needs_transformers_5
@@ -798,7 +793,7 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
try:
config = load_model_config(model_name, use_auth = True, token = hf_token)
- # Exclude audio-only models that share ForConditionalGeneration suffix
+ # Exclude audio-only models sharing the ForConditionalGeneration suffix
# (e.g. CsmForConditionalGeneration, WhisperForConditionalGeneration)
model_type = getattr(config, "model_type", None)
if model_type in _AUDIO_ONLY_MODEL_TYPES:
@@ -818,8 +813,8 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
except Exception as e:
logger.warning(f"Could not determine if {model_name} is vision model: {e}")
- # Permanent failures (model not found, gated, bad config) should be
- # cached as False. Transient failures (network, timeout) should not.
+ # Permanent failures (not found, gated, bad config) cache as False;
+ # transient failures (network, timeout) should not.
try:
from huggingface_hub.errors import RepositoryNotFoundError, GatedRepoError
except ImportError:
@@ -841,10 +836,10 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
VALID_AUDIO_TYPES = ("snac", "csm", "bicodec", "dac", "whisper", "audio_vlm")
-# Cache detection results per session to avoid repeated API calls
+# Cache detection per session to avoid repeated API calls
_audio_detection_cache: Dict[str, Optional[str]] = {}
-# Tokenizer token patterns → audio_type (all 6 types detected from tokenizer_config.json)
+# Tokenizer token patterns → audio_type (all 6 types from tokenizer_config.json)
_AUDIO_TOKEN_PATTERNS = {
"csm": lambda tokens: "<|AUDIO|>" in tokens and "<|audio_eos|>" in tokens,
"whisper": lambda tokens: "<|startoftranscript|>" in tokens,
@@ -863,10 +858,10 @@ _AUDIO_TOKEN_PATTERNS = {
def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:
"""
- Dynamically detect if a model is an audio model and return its type.
+ Detect if a model is an audio model and return its type.
- Fully dynamic — works for any model, not just known ones.
- Uses tokenizer_config.json special tokens to detect all 6 audio types.
+ Works for any model, not just known ones. Uses tokenizer_config.json
+ special tokens to detect all 6 audio types.
Returns: audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper', 'audio_vlm') or None.
"""
@@ -882,10 +877,10 @@ def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Option
def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:
- """Detect audio type from tokenizer special tokens (for LLM-based audio models).
+ """Detect audio type from tokenizer special tokens (LLM-based audio models).
- First checks local HF cache, then fetches tokenizer_config.json from HuggingFace.
- Checks added_tokens_decoder for distinctive patterns.
+ Checks local HF cache first, then fetches tokenizer_config.json from
+ HuggingFace. Examines added_tokens_decoder for distinctive patterns.
"""
def _check_token_patterns(tok_config: dict) -> Optional[str]:
@@ -898,7 +893,7 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None
return audio_type
return None
- # 1) Check local HF cache first (works for gated/offline models)
+ # 1) Local HF cache first (works for gated/offline models)
try:
repo_dir = get_cache_path(model_name)
if repo_dir is not None and repo_dir.exists():
@@ -924,7 +919,7 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None
import os
paths_to_try = ["tokenizer_config.json", "LLM/tokenizer_config.json"]
- # Use provided token, or fall back to env
+ # Use provided token, else env
token = hf_token or os.environ.get("HF_TOKEN")
headers = {}
if token:
@@ -994,7 +989,7 @@ _MODEL_FAMILY_TOKENS: tuple[str, ...] = (
)
-# Word-bounded match: any letter on either side disqualifies. Stops
+# Word-bounded match: a letter on either side disqualifies. Stops
# ``phi`` matching ``sapphire``, ``yi`` matching ``tiny``, etc.
_FAMILY_TOKEN_RE_CACHE: Dict[str, "_re.Pattern[str]"] = {}
@@ -1022,8 +1017,8 @@ def _detect_family_token(filename: str) -> Optional[str]:
def mmproj_matches_model_family(model_path: str, mmproj_path: str) -> bool:
- """Defense-in-depth guard for the launcher: True unless both filenames
- carry recognised family tokens that disagree."""
+ """Launcher guard: True unless both filenames carry recognised family
+ tokens that disagree."""
model_fam = _detect_family_token(Path(model_path).name)
mmproj_fam = _detect_family_token(Path(mmproj_path).name)
if model_fam is None or mmproj_fam is None:
@@ -1116,7 +1111,7 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optional
continue
if resolved in seen_resolved:
continue
- # Prefer ``general.type=='mmproj'``; fall back to filename.
+ # Prefer ``general.type=='mmproj'``, else filename.
meta = read_gguf_general_metadata(str(resolved))
by_meta = is_mmproj_by_metadata(meta)
if by_meta is True or (by_meta is None and _is_mmproj(f.name)):
@@ -1211,12 +1206,10 @@ def detect_gguf_model(path: str) -> Optional[str]:
return None
-# Preferred GGUF quantization levels, in descending priority.
-# Q4_K_M is a good default: small, fast, acceptable quality.
-# UD (Unsloth Dynamic) variants are always preferred over standard quants
-# because they provide better quality per bit. If the repo has no UD variants
-# (e.g., bartowski repos), the standard quants are used as fallback.
-# Ordered by best size/quality tradeoff, not raw quality.
+# Preferred GGUF quant levels, descending priority. Q4_K_M is a good default
+# (small, fast, acceptable quality). UD (Unsloth Dynamic) variants beat
+# standard quants on quality per bit; repos without UD (e.g. bartowski) fall
+# back to standard quants. Ordered by size/quality tradeoff, not raw quality.
_GGUF_QUANT_PREFERENCE = [
# UD variants (best quality per bit) -- Q4 is the sweet spot
"UD-Q4_K_XL",
@@ -1263,8 +1256,7 @@ def _pick_best_gguf(filenames: list[str]) -> Optional[str]:
"""
Pick the best GGUF file from a list of filenames.
- Prefers quantization levels in _GGUF_QUANT_PREFERENCE order.
- Falls back to the first .gguf file found.
+ Prefers quant levels in _GGUF_QUANT_PREFERENCE order; else the first .gguf.
"""
gguf_files = [f for f in filenames if f.lower().endswith(".gguf")]
if not gguf_files:
@@ -1291,7 +1283,7 @@ class GgufVariantInfo:
def _extract_quant_label(filename: str) -> str:
"""
- Extract quantization label like Q4_K_M, IQ4_XS, BF16 from a GGUF filename.
+ Extract quant label like Q4_K_M, IQ4_XS, BF16 from a GGUF filename.
Examples:
"gemma-3-4b-it-Q4_K_M.gguf" → "Q4_K_M"
@@ -1318,8 +1310,8 @@ def _extract_quant_label(filename: str) -> str:
)
match = re.search(quant_re, stem, re.IGNORECASE)
# Subdir layouts like ``BF16/foo.gguf`` keep the quant in the directory,
- # not the basename. Look at the parent dirs too so the variant label
- # matches the snapshot-relative path produced elsewhere.
+ # not the basename. Check parent dirs too so the label matches the
+ # snapshot-relative path produced elsewhere.
if not match and "/" in filename:
parents = filename.rsplit("/", 1)[0]
for segment in reversed(parents.split("/")):
@@ -1330,16 +1322,16 @@ def _extract_quant_label(filename: str) -> str:
if match:
prefix = match.group(1) or ""
return f"{prefix}{match.group(2)}"
- # Fallback: last segment after hyphen
+ # Fallback: last hyphen-separated segment
return stem.split("-")[-1]
def _iter_hf_cache_snapshots(repo_id: str):
"""Yield HF cache snapshot dirs for *repo_id*, newest first.
- Empty generator if HF_HUB_CACHE is missing, the repo isn't cached,
- or has no snapshots. Repo name match is case-insensitive to handle
- casing drift between download time and lookup.
+ Empty if HF_HUB_CACHE is missing, the repo isn't cached, or has no
+ snapshots. Repo name match is case-insensitive to handle casing drift
+ between download time and lookup.
"""
try:
from huggingface_hub import constants as hf_constants
@@ -1389,8 +1381,8 @@ def list_gguf_variants(
"""
List all GGUF quantization variants in a HuggingFace repo.
- Separates main model files from mmproj (vision projection) files.
- The presence of mmproj files indicates a vision-capable model.
+ Separates main model files from mmproj (vision projection) files;
+ mmproj presence indicates a vision-capable model.
Returns:
(variants, has_vision): list of non-mmproj GGUF variants + vision flag.
@@ -1406,9 +1398,9 @@ def list_gguf_variants(
try:
info = hf_model_info(repo_id, token = hf_token, files_metadata = True)
except Exception as e:
- # Permanent errors (deleted/gated/bad revision) must surface to
- # the caller; serving stale cache here would mask the real cause.
- # Matches the early-return in ``detect_gguf_model_remote``.
+ # Permanent errors (deleted/gated/bad revision) must surface to the
+ # caller; serving stale cache would mask the real cause. Matches the
+ # early-return in ``detect_gguf_model_remote``.
if type(e).__name__ in (
"RepositoryNotFoundError",
"GatedRepoError",
@@ -1438,7 +1430,7 @@ def list_gguf_variants(
continue
size = sibling.size or 0
- # mmproj files are vision projection models, not main model files
+ # mmproj files are vision projections, not main model files
if "mmproj" in fname.lower():
has_vision = True
continue
@@ -1457,9 +1449,8 @@ def list_gguf_variants(
)
)
- # Sort by size descending (largest = best quality first).
- # Recommended pinning and OOM demotion are handled client-side
- # where GPU VRAM info is available.
+ # Sort by size descending (largest = best quality first). Recommended
+ # pinning and OOM demotion happen client-side where GPU VRAM info exists.
variants.sort(key = lambda v: -v.size_bytes)
return variants, has_vision
@@ -1468,11 +1459,10 @@ def list_gguf_variants(
def _resolve_gguf_dir(p: Path) -> Optional[Path]:
"""Resolve a path to the directory containing GGUF variants.
- If *p* is already a directory, returns it directly. If *p* is a ``.gguf``
- file whose parent directory has model metadata (``config.json`` or
- ``adapter_config.json``), returns the parent -- all GGUFs in that
- directory belong to the same model. Returns ``None`` for loose standalone
- GGUFs (no config) to avoid cross-wiring unrelated models.
+ Directory *p* returns directly. A ``.gguf`` file whose parent dir has
+ model metadata (``config.json`` or ``adapter_config.json``) returns the
+ parent -- all GGUFs there belong to the same model. Returns ``None`` for
+ loose standalone GGUFs (no config) to avoid cross-wiring unrelated models.
"""
if p.is_dir():
return p
@@ -1490,9 +1480,9 @@ def _resolve_gguf_dir(p: Path) -> Optional[Path]:
def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], bool]:
"""List GGUF quantization variants in a local directory.
- Mirrors :func:`list_gguf_variants` but reads from the filesystem
- instead of the HuggingFace API. Aggregates shard sizes by quant
- label so that split GGUFs appear as a single variant.
+ Mirrors :func:`list_gguf_variants` but reads the filesystem instead of
+ the HuggingFace API. Aggregates shard sizes by quant label so split
+ GGUFs appear as a single variant.
Returns:
(variants, has_vision): list of non-mmproj GGUF variants + vision flag.
@@ -1505,10 +1495,10 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
quant_first_file: dict[str, str] = {}
has_vision = False
- # Recurse so variant-specific subdirectories (e.g. ``BF16/...gguf``
- # used by some HF GGUF repos for the largest quants) are picked up.
- # Filenames in the result preserve the relative subpath so that
- # ``_find_local_gguf_by_variant`` can locate the file again.
+ # Recurse so variant-specific subdirs (e.g. ``BF16/...gguf`` used by
+ # some HF GGUF repos for the largest quants) are picked up. Result
+ # filenames keep the relative subpath so ``_find_local_gguf_by_variant``
+ # can locate the file again.
for f in sorted(_iter_gguf_files(p, recursive = True)):
if _is_mmproj(f.name):
has_vision = True
@@ -1517,8 +1507,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
size = f.stat().st_size
except OSError:
size = 0
- # Pass the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``
- # produce distinct quant labels instead of collapsing on basename.
+ # Use the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``
+ # get distinct quant labels instead of collapsing on basename.
rel = f.relative_to(p).as_posix()
quant = _extract_quant_label(rel)
quant_totals[quant] = quant_totals.get(quant, 0) + size
@@ -1540,8 +1530,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
"""Find the GGUF file in *directory* matching a quantization *variant*.
- For sharded GGUFs (multiple files with the same quant label), returns
- the first shard (sorted by name) which is what ``llama-server -m`` expects.
+ For sharded GGUFs (multiple files sharing a quant label), returns the
+ first shard (sorted by name), which is what ``llama-server -m`` expects.
Returns the resolved absolute path, or ``None`` if no match.
"""
@@ -1549,10 +1539,10 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
if p is None:
return None
- # Recurse into subdirectories so variants stored under a quant-named
- # subdir (e.g. ``BF16/foo-BF16-00001-of-00002.gguf``) are found.
- # Match against the relative path so the quant label can come from
- # the directory name when the basename omits it.
+ # Recurse so variants under a quant-named subdir (e.g.
+ # ``BF16/foo-BF16-00001-of-00002.gguf``) are found. Match the relative
+ # path so the quant label can come from the dir name when the basename
+ # omits it.
matches = sorted(
f
for f in _iter_gguf_files(p, recursive = True)
@@ -1566,8 +1556,8 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
def _detect_gguf_from_hf_cache(repo_id: str) -> Optional[str]:
"""Best GGUF filename for *repo_id* from the local HF cache, or None.
- Excludes mmproj (vision projector) files so a partial cache that
- only has the projector cannot route the projector as the main model.
+ Excludes mmproj (vision projector) files so a partial cache holding only
+ the projector cannot route it as the main model.
"""
for snap in _iter_hf_cache_snapshots(repo_id):
rel_files = [
@@ -1586,16 +1576,15 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Op
Returns the filename of the best GGUF file in the repo, or None.
- Retries on transient HF Hub failures (network hiccups, 5xx, slow
- cold-start of the API). Without retry, a single transient failure
- here returns None silently and the caller treats the repo as
- non-GGUF -- which on Apple Silicon (Mac UI route) means falling
- through to the MLX backend, which then fails opening a non-existent
- config.json on the GGUF-only repo. Three attempts with 1s/2s/4s
- backoff covers the typical free-runner HF Hub flakiness.
+ Retries on transient HF Hub failures (network hiccups, 5xx, slow API
+ cold-start). Without retry, a single transient failure returns None
+ silently and the caller treats the repo as non-GGUF -- which on Apple
+ Silicon (Mac UI route) falls through to the MLX backend, which then
+ fails opening a non-existent config.json on the GGUF-only repo. Three
+ attempts with 1s/2s/4s backoff covers typical free-runner HF Hub flakiness.
- When offline, falls back to the local HF cache so a downloaded
- repo is still routed to llama-server (not MLX/Unsloth).
+ When offline, falls back to the local HF cache so a downloaded repo is
+ still routed to llama-server (not MLX/Unsloth).
"""
import time
from huggingface_hub import model_info as hf_model_info
@@ -1613,7 +1602,7 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Op
return _pick_best_gguf(repo_files)
except Exception as e:
last_err = e
- # 404 / RepoNotFound is permanent -- don't waste attempts.
+ # 404 / RepoNotFound is permanent -- don't retry.
err_name = type(e).__name__
if err_name in (
"RepositoryNotFoundError",
@@ -1660,20 +1649,20 @@ def download_gguf_file(
return local_path
-# Cache embedding detection results per session to avoid repeated HF API calls
+# Cache embedding detection per session to avoid repeated HF API calls
_embedding_detection_cache: Dict[tuple, bool] = {}
def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
"""
- Detect embedding/sentence-transformer models using HuggingFace model metadata.
+ Detect embedding/sentence-transformer models via HuggingFace metadata.
- Uses a belt-and-suspenders approach combining three signals:
+ Combines three signals:
1. "sentence-transformers" in model tags
2. "feature-extraction" in model tags
3. pipeline_tag is "sentence-similarity" or "feature-extraction"
- This catches all known embedding models including those like gte-modernbert
+ Catches all known embedding models, including ones like gte-modernbert
whose library_name is "transformers" rather than "sentence-transformers".
Args:
@@ -1681,8 +1670,8 @@ def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
hf_token: Optional HF token for accessing gated/private models
Returns:
- True if the model is an embedding model, False otherwise.
- Defaults to False for local paths or on errors.
+ True if embedding model, else False. Defaults to False for local
+ paths or on errors.
"""
cache_key = (model_name, hf_token)
if cache_key in _embedding_detection_cache:
@@ -1774,8 +1763,8 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[st
Scan outputs folder for trained Studio models.
Returns:
- List of tuples: [(display_name, model_path, model_type), ...]
- model_type is "lora" for adapter runs and "merged" for full finetunes.
+ List of [(display_name, model_path, model_type), ...].
+ model_type is "lora" for adapter runs, "merged" for full finetunes.
"""
trained_models = []
outputs_path = resolve_output_dir(outputs_dir)
@@ -1796,7 +1785,7 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[st
trained_models.append((display_name, model_path, model_type))
logger.debug("Found trained model: %s (%s)", display_name, model_type)
- # Sort by modification time (newest first)
+ # Sort by mtime, newest first
trained_models.sort(key = lambda x: Path(x[1]).stat().st_mtime, reverse = True)
logger.info(
@@ -1822,7 +1811,7 @@ def scan_exported_models(
- Flat: {name}-finetune-gguf/ (GGUF exports)
Returns:
- List of tuples: [(display_name, model_path, export_type, base_model), ...]
+ List of [(display_name, model_path, export_type, base_model), ...].
export_type: "lora" | "merged" | "gguf"
"""
results = []
@@ -1836,8 +1825,8 @@ def scan_exported_models(
if not run_dir.is_dir():
continue
- # Check for flat GGUF export (e.g. exports/gemma-3-4b-it-finetune-gguf/)
- # Filter out mmproj (vision projection) files — they aren't loadable as main models
+ # Flat GGUF export (e.g. exports/gemma-3-4b-it-finetune-gguf/).
+ # Skip mmproj (vision projection) files — not loadable as main models.
gguf_files = [f for f in _iter_gguf_files(run_dir) if not _is_mmproj(f.name)]
if gguf_files:
base_model = None
@@ -1850,7 +1839,7 @@ def scan_exported_models(
pass
display_name = run_dir.name
- model_path = str(gguf_files[0]) # path to the .gguf file
+ model_path = str(gguf_files[0]) # the .gguf file
results.append((display_name, model_path, "gguf", base_model))
logger.debug(f"Found GGUF export: {display_name}")
continue
@@ -1889,8 +1878,8 @@ def scan_exported_models(
elif has_gguf:
export_type = "gguf"
gguf_list = list(_iter_gguf_files(checkpoint_dir))
- # Check checkpoint_dir first, then fall back to parent run_dir
- # (export.py writes metadata to the top-level export directory)
+ # Check checkpoint_dir first, then parent run_dir
+ # (export.py writes metadata to the top-level export dir)
for meta_dir in (checkpoint_dir, run_dir):
export_meta = meta_dir / "export_metadata.json"
try:
@@ -1910,7 +1899,7 @@ def scan_exported_models(
else:
continue
- # Fallback: read base model from the original training run's
+ # Fallback: read base model from the training run's
# adapter_config.json in ./outputs/{run_name}/
if not base_model:
outputs_adapter_cfg = resolve_output_dir(run_dir.name) / "adapter_config.json"
@@ -2012,7 +2001,7 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:
if not _looks_like_lora_adapter(lora_path_obj):
return None
- # Try adapter_config.json first
+ # adapter_config.json first
adapter_config_path = lora_path_obj / "adapter_config.json"
if adapter_config_path.exists():
with open(adapter_config_path, "r") as f:
@@ -2043,7 +2032,7 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:
# Format: unsloth_Meta-Llama-3.1-8B-Instruct-bnb-4bit_timestamp
dir_name = lora_path_obj.name
if dir_name.startswith("unsloth_"):
- # Remove timestamp suffix (usually _1234567890)
+ # Drop timestamp suffix (usually _1234567890)
parts = dir_name.split("_")
# Reconstruct model name
if len(parts) >= 2:
@@ -2072,21 +2061,21 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
model_name: Model identifier (e.g., "unsloth/Meta-Llama-3.1-8B-bnb-4bit")
Returns:
- Dictionary with default parameters from YAML file, or empty dict if not found
+ Dict of default parameters from the YAML file, or empty dict if none.
- The function looks for a YAML file in configs/model_defaults/ (including subfolders)
- based on the model name or its aliases from MODEL_NAME_MAPPING.
- If no specific file exists, it falls back to default.yaml.
+ Looks for a YAML in configs/model_defaults/ (including subfolders) by the
+ model name or its aliases from MODEL_NAME_MAPPING, else falls back to
+ default.yaml.
"""
try:
- # Get the script directory to locate configs
+ # Locate configs relative to the script dir
script_dir = Path(__file__).parent.parent.parent
defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
- # First, check if model is in the mapping
+ # Check the mapping first
if model_name.lower() in _REVERSE_MODEL_MAPPING:
canonical_file = _REVERSE_MODEL_MAPPING[model_name.lower()]
- # Search in subfolders and root
+ # Search subfolders and root
for config_path in defaults_dir.rglob(canonical_file):
if config_path.is_file():
with open(config_path, "r", encoding = "utf-8") as f:
@@ -2094,10 +2083,9 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
logger.info(f"Loaded model defaults from {config_path} (via mapping)")
return config
- # If model_name is a local path (e.g. /home/.../Spark-TTS-0.5B/LLM from
- # adapter_config.json, or C:\Users\...\model on Windows), try matching
- # the last 1-2 path components against the registry
- # (e.g. "Spark-TTS-0.5B/LLM").
+ # For local paths (e.g. /home/.../Spark-TTS-0.5B/LLM from
+ # adapter_config.json, or C:\Users\...\model on Windows), match the
+ # last 1-2 path components against the registry (e.g. "Spark-TTS-0.5B/LLM").
_is_local_path = is_local_path(model_name)
# Normalize Windows backslash paths so Path().parts splits correctly
# on POSIX/WSL hosts (pathlib treats backslashes as literals on Linux).
@@ -2118,13 +2106,13 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
)
return config
- # Try exact model name match (for backward compatibility).
- # For local filesystem paths, use only the directory basename to
- # avoid passing absolute paths (e.g. C:\...) into rglob which
- # raises "Non-relative patterns are unsupported" on Windows.
+ # Exact model name match (backward compatibility). For local paths,
+ # use only the dir basename to avoid passing absolute paths (e.g.
+ # C:\...) into rglob, which raises "Non-relative patterns are
+ # unsupported" on Windows.
_lookup_name = Path(_normalized).name if _is_local_path else model_name
model_filename = _lookup_name.replace("/", "_") + ".yaml"
- # Search in subfolders and root
+ # Search subfolders and root
for config_path in defaults_dir.rglob(model_filename):
if config_path.is_file():
with open(config_path, "r", encoding = "utf-8") as f:
@@ -2150,17 +2138,17 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
@dataclass
class ModelConfig:
- """Configuration for a model to load"""
+ """Configuration for a model to load."""
identifier: str # Clean model identifier (org/name or path)
display_name: str # Original UI display name
path: str # Normalized filesystem path
- is_local: bool # Is this a local file vs HF model?
- is_cached: bool # Is this already in HF cache?
- is_vision: bool # Is this a vision model?
- is_lora: bool # Is this a lora adapter?
- is_gguf: bool = False # Is this a GGUF model?
- is_audio: bool = False # Is this a TTS audio model?
+ is_local: bool # Local file vs HF model?
+ is_cached: bool # Already in HF cache?
+ is_vision: bool # Vision model?
+ is_lora: bool # LoRA adapter?
+ is_gguf: bool = False # GGUF model?
+ is_audio: bool = False # TTS audio model?
audio_type: Optional[str] = None # Audio codec type: 'snac', 'csm', 'bicodec', 'dac'
has_audio_input: bool = False # Accepts audio input (ASR/speech understanding)
gguf_file: Optional[str] = None # Full path to the .gguf file (local mode)
@@ -2180,7 +2168,7 @@ class ModelConfig:
"""
Create ModelConfig from a local LoRA adapter path.
- Automatically detects the base model from adapter config.
+ Auto-detects the base model from adapter config.
Args:
lora_path: Path to LoRA adapter (e.g., "./outputs/unsloth_Meta-Llama-3.1_.../")
@@ -2196,27 +2184,23 @@ class ModelConfig:
logger.error(f"LoRA path does not exist: {lora_path}")
return None
- # Get base model
base_model = get_base_model_from_lora(lora_path)
if not base_model:
logger.error(f"Could not determine base model for LoRA: {lora_path}")
return None
- # Check if base model is vision
is_vision = is_vision_model(base_model, hf_token = hf_token)
-
- # Check if base model is audio
audio_type = detect_audio_type(base_model, hf_token = hf_token)
display_name = lora_path_obj.name
- identifier = lora_path # Use path as identifier for local LoRAs
+ identifier = lora_path # path as identifier for local LoRAs
return cls(
identifier = identifier,
display_name = display_name,
path = lora_path,
is_local = True,
- is_cached = True, # Local LoRAs are always "cached"
+ is_cached = True, # local LoRAs are always "cached"
is_vision = is_vision,
is_lora = True,
is_audio = audio_type is not None and audio_type != "audio_vlm",
@@ -2241,7 +2225,7 @@ class ModelConfig:
Create ModelConfig from a clean model identifier.
For FastAPI routes where the frontend sends sanitized model paths.
- No Gradio dropdown parsing - expects clean identifiers like:
+ No Gradio dropdown parsing; expects clean identifiers like:
- "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"
- "./outputs/my_lora_adapter"
- "/absolute/path/to/model"
@@ -2250,9 +2234,9 @@ class ModelConfig:
model_id: Clean model identifier (HF repo name or local path)
hf_token: Optional HF token for vision detection on gated models
is_lora: Whether this is a LoRA adapter
- gguf_variant: Optional GGUF quantization variant (e.g. "Q4_K_M").
- For remote GGUF repos, specifies which quant to load via -hf.
- If None, auto-selects using _pick_best_gguf().
+ gguf_variant: Optional GGUF quant variant (e.g. "Q4_K_M"). For
+ remote GGUF repos, sets which quant to load via -hf. If None,
+ auto-selects via _pick_best_gguf().
Returns:
ModelConfig or None if configuration cannot be created
@@ -2269,8 +2253,9 @@ class ModelConfig:
identifier = f"unsloth/{identifier}"
path = identifier
- # Preserve requested casing, but if a case-variant already exists in local HF cache,
- # reuse that exact repo_id spelling to avoid one-time re-downloads after #2592.
+ # Preserve requested casing, but if a case-variant already exists in
+ # local HF cache, reuse that exact repo_id spelling to avoid one-time
+ # re-downloads after #2592.
if not is_local:
resolved_identifier = resolve_cached_repo_id_case(identifier)
if resolved_identifier != identifier:
@@ -2292,12 +2277,12 @@ class ModelConfig:
display_name = Path(gguf_file).stem
logger.info(f"Detected local GGUF model: {gguf_file}")
- # Detect vision: check if base model is vision, then look for mmproj
+ # Vision: check base model, then look for mmproj
mmproj_file = None
gguf_is_vision = False
gguf_dir = Path(gguf_file).parent
- # Determine if this is a vision model from export metadata
+ # Is this a vision model, per export metadata?
base_is_vision = False
meta_path = gguf_dir / "export_metadata.json"
if meta_path.exists():
@@ -2310,15 +2295,12 @@ class ModelConfig:
except Exception as e:
logger.debug(f"Could not read export metadata: {e}")
- # If vision (or mmproj happens to exist), find the mmproj
- # file. The recursive variant scan in
- # ``_find_local_gguf_by_variant`` may have returned a
- # weight file inside a quant-named subdir (e.g.
- # ``.../BF16/foo.gguf``) while ``mmproj-*.gguf`` lives
- # at the snapshot root. Pass ``search_root=path`` so
- # ``detect_mmproj_file`` walks up to the snapshot root
- # instead of seeing only the weight file's immediate
- # parent.
+ # Find the mmproj file. The recursive variant scan in
+ # ``_find_local_gguf_by_variant`` may have returned a weight
+ # file inside a quant-named subdir (e.g. ``.../BF16/foo.gguf``)
+ # while ``mmproj-*.gguf`` lives at the snapshot root. Pass
+ # ``search_root=path`` so ``detect_mmproj_file`` walks up to
+ # the snapshot root instead of only the weight's parent.
mmproj_file = detect_mmproj_file(gguf_file, search_root = path)
if mmproj_file:
gguf_is_vision = True
@@ -2339,11 +2321,11 @@ class ModelConfig:
gguf_mmproj_file = mmproj_file,
)
else:
- # Check if the HF repo contains GGUF files
+ # Does the HF repo contain GGUF files?
gguf_filename = detect_gguf_model_remote(identifier, hf_token = hf_token)
if gguf_filename:
- # Preflight: verify llama-server binary exists BEFORE user waits
- # for a multi-GB download that llama-server handles natively
+ # Preflight: verify llama-server binary exists BEFORE the user
+ # waits for a multi-GB download llama-server handles natively
from core.inference.llama_cpp import LlamaCppBackend
if not LlamaCppBackend._find_llama_server_binary():
@@ -2352,7 +2334,7 @@ class ModelConfig:
"Run setup.sh to build it, or set LLAMA_SERVER_PATH."
)
- # Use list_gguf_variants() to detect vision & resolve variant
+ # list_gguf_variants() detects vision & resolves the variant
variants, has_vision = list_gguf_variants(identifier, hf_token = hf_token)
variant = gguf_variant
if not variant:
@@ -2383,7 +2365,7 @@ class ModelConfig:
gguf_variant = variant,
)
- # Auto-detect LoRA for local paths (check adapter_config.json on disk)
+ # Auto-detect LoRA for local paths (adapter_config.json on disk)
if not is_lora and is_local:
detected_base = (
get_base_model_from_lora(path) if _looks_like_lora_adapter(Path(path)) else None
@@ -2406,7 +2388,7 @@ class ModelConfig:
except Exception as e:
logger.debug(f"Could not check remote LoRA status for '{identifier}': {e}")
- # API may have failed; adapter_config.json may still be cached.
+ # API may have failed; adapter_config.json could still be cached.
if not is_lora:
for snap in _iter_hf_cache_snapshots(identifier):
if (snap / "adapter_config.json").is_file():
@@ -2421,7 +2403,7 @@ class ModelConfig:
# Local LoRA: read adapter_config.json from disk
base_model = get_base_model_from_lora(path)
else:
- # Remote LoRA: download adapter_config.json from HF
+ # Remote LoRA: fetch adapter_config.json from HF
try:
from huggingface_hub import hf_hub_download
@@ -2473,7 +2455,7 @@ class ModelConfig:
is_lora: bool = False,
) -> Optional["ModelConfig"]:
"""
- Create a universal ModelConfig from UI dropdown/search selections.
+ Create a ModelConfig from UI dropdown/search selections.
Handles base models and LoRA adapters.
"""
selected = None
@@ -2487,7 +2469,7 @@ class ModelConfig:
display_name = selected
- # Use the correct 'local_models' parameter to resolve display names
+ # Resolve display names via the 'local_models' parameter
if " (Active)" in selected or " (Ready)" in selected:
clean_display_name = selected.replace(" (Active)", "").replace(" (Ready)", "")
if local_models:
@@ -2496,7 +2478,7 @@ class ModelConfig:
selected = local_path
break
- # Clean all UI status indicators to get the final identifier
+ # Strip all UI status indicators to get the final identifier
identifier = selected
for status in UI_STATUS_INDICATORS:
identifier = identifier.replace(status, "")
@@ -2516,23 +2498,23 @@ class ModelConfig:
identifier = resolved_identifier
path = resolved_identifier
- # --- Logic for Base Model and Vision Detection ---
+ # --- Base Model and Vision Detection ---
base_model = None
is_vision = False
if is_lora:
- # For a LoRA, we MUST find its base model.
+ # A LoRA MUST have a base model.
base_model = get_base_model_from_lora(path)
if not base_model:
logger.warning(
f"Could not determine base model for LoRA '{path}'. Cannot create config."
)
- return None # Cannot proceed without a base model
+ return None # cannot proceed without a base model
- # A LoRA's vision capability is determined by its base model.
+ # A LoRA's vision capability comes from its base model.
is_vision = is_vision_model(base_model, hf_token = hf_token)
else:
- # For a base model, just check its own vision status.
+ # Base model: check its own vision status.
is_vision = is_vision_model(identifier, hf_token = hf_token)
from utils.paths import is_model_cached
@@ -2547,5 +2529,5 @@ class ModelConfig:
is_cached = is_cached,
is_vision = is_vision,
is_lora = is_lora,
- base_model = base_model, # This will be None for base models, and populated for LoRAs
+ base_model = base_model, # None for base models, set for LoRAs
)
diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.py
index eba7a9de6cd..8805308829a 100644
--- a/studio/backend/utils/paths/__init__.py
+++ b/studio/backend/utils/paths/__init__.py
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""
-Path utilities for model and dataset handling
-"""
+"""Path utilities for model and dataset handling."""
from .path_utils import (
normalize_path,
@@ -46,8 +44,8 @@ from .storage_roots import (
resolve_dataset_path,
)
-# Re-export shim: name-load the project-path helpers so the import-hoist
-# safety net sees them used here, not just listed in __all__ as strings.
+# Re-export shim: reference the project-path helpers by name so the
+# import-hoist safety net sees them used, not just named in __all__.
_REEXPORTED = (documents_root, project_workspaces_root)
__all__ = [
diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.py
index 22c6c46ee16..a065250154a 100644
--- a/studio/backend/utils/paths/path_utils.py
+++ b/studio/backend/utils/paths/path_utils.py
@@ -17,7 +17,7 @@ logger = get_logger(__name__)
# Per-process cache to avoid repeated cache-dir scans for the same identifier.
_CACHE_CASE_RESOLUTION_MEMO: dict[str, str] = {}
-# Lightweight instrumentation counters for operational visibility.
+# Instrumentation counters for operational visibility.
_CACHE_CASE_RESOLUTION_STATS: dict[str, int] = {
"calls": 0,
"memo_hits": 0,
@@ -63,8 +63,7 @@ def normalize_path(path: str) -> str:
# Handle Windows drive letters (C:\\ or c:\\)
if len(path) >= 3 and path[1] == ":" and path[2] in ("\\", "/"):
- # Only map to /mnt/<drive>/ when running under WSL;
- # on native Windows the drive letter must be preserved.
+ # Map to /mnt/<drive>/ only under WSL; native Windows keeps the drive letter.
if _IS_WSL:
drive = path[0].lower()
rest = path[3:].replace("\\", "/")
@@ -86,7 +85,7 @@ def is_local_path(path: str) -> bool:
if not path:
return False
- # If it exists on disk, treat as local (covers relative paths like "outputs/foo").
+ # Exists on disk → local (covers relative paths like "outputs/foo").
try:
if Path(normalize_path(path)).expanduser().exists():
return True
@@ -122,7 +121,7 @@ def is_model_cached(model_name: str) -> bool:
if not cache_path:
return False
- # Check for actual model files
+ # Check for model files
for suffix in [".safetensors", ".bin", ".json"]:
if list(cache_path.rglob(f"*{suffix}")):
return True
@@ -146,9 +145,9 @@ def _hf_hub_cache_dir() -> Path:
def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
"""Resolve repo_id to the exact casing already present in local HF cache.
- Policy: prefer the requested/canonical repo_id, but if a case-variant already
- exists in local HF cache, reuse that exact cached spelling. This avoids
- duplicate downloads while preserving user intent whenever possible.
+ Policy: prefer the requested/canonical repo_id, but reuse a case-variant's
+ exact cached spelling if one already exists in local HF cache. Avoids
+ duplicate downloads while preserving user intent where possible.
"""
_CACHE_CASE_RESOLUTION_STATS["calls"] += 1
@@ -163,8 +162,8 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
expected_dir = f"models--{model_name.replace('/', '--')}"
- # Always check the exact-case path first so a newly-appeared exact match
- # wins over any previously memoized variant.
+ # Check the exact-case path first so a newly-appeared exact match wins over
+ # any previously memoized variant.
exact_path = cache_dir / expected_dir
if exact_path.is_dir():
if use_memo:
@@ -172,8 +171,8 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
_CACHE_CASE_RESOLUTION_STATS["exact_hits"] += 1
return model_name
- # Validate memoized entries still exist on disk before returning them.
- # This prevents stale results when cache dirs are deleted/recreated.
+ # Validate memoized entries still exist on disk before returning them,
+ # preventing stale results when cache dirs are deleted/recreated.
if use_memo:
cached = _CACHE_CASE_RESOLUTION_MEMO.get(model_name)
if cached is not None:
@@ -181,7 +180,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
if cached_path.is_dir():
_CACHE_CASE_RESOLUTION_STATS["memo_hits"] += 1
return cached
- # Stale entry -- drop it and re-scan below.
+ # Stale entry -- drop it and re-scan below
_CACHE_CASE_RESOLUTION_MEMO.pop(model_name, None)
expected_lower = expected_dir.lower()
@@ -200,7 +199,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
candidates.append(repo_part.replace("--", "/"))
if candidates:
- # Deterministic tie-break if multiple case variants coexist.
+ # Deterministic tie-break if multiple case variants coexist
resolved = sorted(candidates)[0]
if len(candidates) > 1:
_CACHE_CASE_RESOLUTION_STATS["tie_breaks"] += 1
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index b254c20f97e..de88a0bf311 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -11,9 +11,9 @@ import tempfile
def _infer_studio_home_from_venv() -> Path | None:
- """Return parent dir of sys.prefix as STUDIO_HOME if running from an
+ """Return parent of sys.prefix as STUDIO_HOME when running from an
installer-managed unsloth_studio venv. Sentinel-gated (share/studio.conf
- or bin shim) so a developer venv named unsloth_studio is not misidentified.
+ or bin shim) so a dev venv named unsloth_studio isn't misidentified.
"""
try:
prefix = Path(sys.prefix).resolve()
@@ -38,8 +38,8 @@ def studio_root() -> Path:
"""Studio install root.
Priority: UNSLOTH_STUDIO_HOME, then STUDIO_HOME alias, then sys.prefix
- inference, then legacy ~/.unsloth/studio. UNSLOTH_STUDIO_HOME wins when
- both are set (the more specific signal beats the generic alias).
+ inference, then legacy ~/.unsloth/studio. UNSLOTH_STUDIO_HOME wins if
+ both are set (specific signal beats generic alias).
"""
override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()
if not override:
@@ -56,7 +56,7 @@ def studio_root() -> Path:
def cache_root() -> Path:
- """Central cache directory for all studio downloads (models, datasets, etc.)."""
+ """Central cache dir for all studio downloads (models, datasets, etc.)."""
return studio_root() / "cache"
@@ -158,16 +158,15 @@ def ensure_dir(path: Path) -> Path:
def legacy_hf_cache_dir() -> Path:
- """Old Unsloth-specific HF hub cache, kept for backward-compat scanning."""
+ """Old Unsloth-specific HF hub cache, kept for backward-compat scans."""
return cache_root() / "huggingface" / "hub"
def hf_default_cache_dir() -> Path:
- """Return the platform default HuggingFace hub cache (ignoring env overrides).
+ """Platform default HuggingFace hub cache (ignoring env overrides).
- This is the location HF uses when no ``HF_HUB_CACHE`` / ``HF_HOME``
- env var is set. We scan it so that models a user downloaded *before*
- installing Unsloth Studio are still discovered.
+ Where HF caches when no ``HF_HUB_CACHE`` / ``HF_HOME`` is set. Scanned
+ so models downloaded *before* installing Unsloth Studio are discovered.
"""
return Path.home() / ".cache" / "huggingface" / "hub"
@@ -183,7 +182,7 @@ def lmstudio_model_dirs() -> list[Path]:
seen.add(resolved)
dirs.append(p)
- # 1. Check LM Studio settings.json for custom downloads folder
+ # 1. LM Studio settings.json custom downloads folder
settings_path = Path.home() / ".lmstudio" / "settings.json"
if settings_path.is_file():
try:
@@ -207,17 +206,17 @@ def lmstudio_model_dirs() -> list[Path]:
def well_known_model_dirs() -> list[Path]:
"""Return directories commonly used by other local LLM tools.
- Used by the folder browser to offer quick-pick chips. Returns only
- paths that exist on disk, so the UI never shows dead chips. Order
- reflects a rough "likelihood the user has models here" -- LM Studio
- and Ollama first, then the generic fallbacks.
+ Backs the folder browser's quick-pick chips. Returns only paths that
+ exist on disk, so the UI never shows dead chips. Order reflects rough
+ likelihood of models being there -- LM Studio and Ollama first, then
+ generic fallbacks.
"""
candidates: list[Path] = []
# LM Studio (reuses the logic above, including settings.json override)
candidates.extend(lmstudio_model_dirs())
- # Ollama -- both the user-level and common system-wide install paths
+ # Ollama -- user-level and common system-wide install paths
# (https://github.com/ollama/ollama/issues/733).
ollama_env = os.environ.get("OLLAMA_MODELS")
if ollama_env:
@@ -229,7 +228,7 @@ def well_known_model_dirs() -> list[Path]:
# HF hub cache root (separate from the explicit HF cache chip)
candidates.append(Path.home() / ".cache" / "huggingface" / "hub")
- # Generic "my models" spots users tend to drop things into
+ # Generic "my models" spots users drop things into
for name in ("models", "Models"):
candidates.append(Path.home() / name)
@@ -253,14 +252,12 @@ def _setup_cache_env() -> None:
"""Set cache environment variables for HuggingFace, uv, and vLLM.
Respects the standard HF cache resolution chain: explicit ``HF_HOME``
- / ``HF_HUB_CACHE`` env vars take priority, then ``XDG_CACHE_HOME``,
- then the platform default (``~/.cache/huggingface``). The legacy
- Unsloth cache is still *scanned* for models but is never set as the
- active download target.
-
- Only sets variables that are not already set by the user, so
- explicit overrides (e.g. HF_HOME=/data/hf) are respected.
- Works on Linux, macOS, and Windows.
+ / ``HF_HUB_CACHE`` win, then ``XDG_CACHE_HOME``, then the platform
+ default (``~/.cache/huggingface``). The legacy Unsloth cache is still
+ *scanned* for models but never set as the active download target.
+
+ Only sets variables not already set by the user, so explicit overrides
+ (e.g. HF_HOME=/data/hf) are respected. Works on Linux, macOS, Windows.
"""
root = cache_root()
xdg_cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")).expanduser()
@@ -327,8 +324,8 @@ def resolve_under_root(
) -> Path:
"""Resolve ``path_value`` and assert the result is under ``root``.
- Absolutes are accepted only if already contained (so internal pre-resolved
- paths re-enter idempotently); user-facing schemas reject absolutes upstream.
+ Absolutes are accepted only if already contained (so pre-resolved
+ internal paths re-enter idempotently); schemas reject absolutes upstream.
"""
if not path_value or not str(path_value).strip():
return root
diff --git a/studio/backend/utils/studio_version.py b/studio/backend/utils/studio_version.py
index e59439a2cc6..98c48fe45c0 100644
--- a/studio/backend/utils/studio_version.py
+++ b/studio/backend/utils/studio_version.py
@@ -74,8 +74,8 @@ def _exact_git_studio_tag(repo_root: Path) -> str | None:
def get_studio_version(repo_root: Path | None = None) -> str:
"""Return the installed Studio release tag for display, or ``dev``.
- This value is intentionally separate from the PyPI ``unsloth`` package
- version used by update checks. It never performs network requests.
+ Intentionally separate from the PyPI ``unsloth`` package version used by
+ update checks. Never performs network requests.
"""
resolved_repo_root = repo_root or _repo_root()
diff --git a/studio/backend/utils/subprocess_compat.py b/studio/backend/utils/subprocess_compat.py
index bedf8cf2e6c..b7fe906e916 100644
--- a/studio/backend/utils/subprocess_compat.py
+++ b/studio/backend/utils/subprocess_compat.py
@@ -10,8 +10,8 @@ import sys
def windows_hidden_subprocess_kwargs() -> dict[str, object]:
"""Return Windows-only subprocess kwargs that suppress console windows.
- On non-Windows platforms returns an empty dict so callers can always
- unpack the result into ``subprocess.run`` / ``subprocess.Popen`` via
+ Returns an empty dict off Windows so callers can always unpack it into
+ ``subprocess.run`` / ``subprocess.Popen`` via
``**windows_hidden_subprocess_kwargs()``.
"""
if sys.platform != "win32":
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 16f964d628e..7c1bc361b66 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -4,26 +4,24 @@
"""
Automatic transformers version switching.
-Some newer model architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,
-tiny_qwen3_moe) require transformers>=5.3.0, while Gemma 4 models require
-transformers>=5.5.0. Everything else needs the default 4.57.x that ships
-with Unsloth.
+Some newer architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,
+tiny_qwen3_moe) need transformers>=5.3.0; Gemma 4 needs >=5.5.0. Everything
+else uses the default 4.57.x that ships with Unsloth.
-Two separate target directories are maintained:
+Two target directories:
- .venv_t5_530/ — transformers 5.3.0 (Ministral-3, GLM, Qwen3 MoE, etc.)
- .venv_t5_550/ — transformers 5.5.0 (Gemma 4)
-When loading a LoRA adapter with a custom name, we resolve the base model from
-``adapter_config.json`` and check *that* against the model list.
+For a custom-named LoRA adapter, the base model is resolved from
+``adapter_config.json`` and checked against the model list.
Strategy:
- Training and inference run in subprocesses that activate the correct version
- via sys.path (prepending the appropriate .venv_t5_*/ directory). See:
- - core/training/worker.py
- - core/inference/worker.py
+ Training and inference run in subprocesses that activate the right version
+ via sys.path (prepending the appropriate .venv_t5_*/ dir). See
+ core/training/worker.py and core/inference/worker.py.
- For export (still in-process), ensure_transformers_version() does a lightweight
- sys.path swap using the same directories pre-installed by setup.sh.
+ For export (in-process), ensure_transformers_version() does a lightweight
+ sys.path swap using the same setup.sh-installed directories.
"""
import importlib
@@ -57,8 +55,7 @@ def _env_offline() -> bool:
# Detection
# ---------------------------------------------------------------------------
-# Lowercase substrings — if ANY appears anywhere in the lowered model name,
-# we need transformers 5.3.0.
+# Lowercase substrings — any match in the lowered model name needs transformers 5.3.0.
TRANSFORMERS_5_MODEL_SUBSTRINGS: tuple[str, ...] = (
"ministral-3-", # Ministral-3-{3,8,14}B-{Instruct,Reasoning,Base}-2512
"glm-4.7-flash", # GLM-4.7-Flash
@@ -85,15 +82,15 @@ _TRANSFORMERS_550_MODEL_TYPES: set[str] = {
"gemma4",
}
-# Tokenizer classes that only exist in transformers>=5.x
+# Tokenizer classes that only exist in transformers>=5.x.
_TRANSFORMERS_5_TOKENIZER_CLASSES: set[str] = {
"TokenizersBackend",
}
-# Cache for dynamic tokenizer_config.json lookups to avoid repeated fetches
+# Cache for dynamic tokenizer_config.json lookups (avoids repeated fetches).
_tokenizer_class_cache: dict[str, bool] = {}
-# Cache for dynamic config.json lookups (architecture/model_type checks)
+# Cache for dynamic config.json lookups (architecture/model_type checks).
_config_needs_550_cache: dict[str, bool] = {}
# Versions
@@ -116,12 +113,10 @@ _VENV_T5_DIR = _VENV_T5_550_DIR
def activate_transformers_for_subprocess(model_name: str) -> None:
"""Activate the correct transformers version in a subprocess worker.
- Call this BEFORE any ML imports. Resolves LoRA adapters to their base
- model, determines the required tier, and prepends the appropriate
- ``.venv_t5_*`` directory to ``sys.path``. Also propagates the path
- via ``PYTHONPATH`` for child processes (e.g. GGUF converter).
-
- Used by training, inference, and export workers.
+ Call BEFORE any ML imports. Resolves LoRA adapters to their base model,
+ determines the required tier, prepends the appropriate ``.venv_t5_*`` dir to
+ ``sys.path``, and propagates it via ``PYTHONPATH`` for child processes
+ (e.g. GGUF converter). Used by training, inference, and export workers.
"""
resolved = _resolve_base_model(model_name)
tier = get_transformers_tier(resolved)
@@ -155,11 +150,10 @@ def activate_transformers_for_subprocess(model_name: str) -> None:
def _resolve_base_model(model_name: str) -> str:
"""If *model_name* points to a LoRA adapter, return its base model.
- Checks for ``adapter_config.json`` locally first. Only calls the heavier
- ``get_base_model_from_lora`` for paths that are actual local directories
- (avoids noisy warnings for plain HF model IDs).
-
- Returns the original *model_name* unchanged if it is not a LoRA adapter.
+ Checks ``adapter_config.json`` locally first. Only calls the heavier
+ ``get_base_model_from_lora`` for real local directories (avoids noisy
+ warnings for plain HF model IDs). Returns *model_name* unchanged if not a
+ LoRA adapter.
"""
# --- Fast local check ---------------------------------------------------
local_path = Path(model_name)
@@ -221,11 +215,11 @@ def _resolve_base_model(model_name: str) -> str:
def _check_tokenizer_config_needs_v5(model_name: str) -> bool:
- """Fetch tokenizer_config.json from HuggingFace and check if the
- tokenizer_class requires transformers 5.x.
+ """True if the model's tokenizer_class requires transformers 5.x.
- Results are cached in ``_tokenizer_class_cache`` to avoid repeated fetches.
- Returns False on any network/parse error (fail-open to default version).
+ Checks local tokenizer_config.json, else fetches from HuggingFace. Cached in
+ ``_tokenizer_class_cache``. Returns False on any network/parse error
+ (fail-open to default version).
"""
if model_name in _tokenizer_class_cache:
return _tokenizer_class_cache[model_name]
@@ -280,12 +274,11 @@ def _check_tokenizer_config_needs_v5(model_name: str) -> bool:
def _check_config_needs_550(model_name: str) -> bool:
- """Check ``config.json`` for architectures or model_type that require
- transformers 5.5.0 (e.g. Gemma 4).
+ """True if ``config.json`` has architectures/model_type needing transformers
+ 5.5.0 (e.g. Gemma 4).
- Checks locally first, then falls back to fetching from HuggingFace.
- Results are cached in ``_config_needs_550_cache``.
- Returns False on any error (fail-open to lower tier).
+ Checks locally first, else fetches from HuggingFace. Cached in
+ ``_config_needs_550_cache``. Returns False on any error (fail-open to lower tier).
"""
if model_name in _config_needs_550_cache:
return _config_needs_550_cache[model_name]
@@ -352,10 +345,8 @@ def _check_config_needs_550(model_name: str) -> bool:
def get_transformers_tier(model_name: str) -> str:
"""Return the transformers tier required for *model_name*.
- Returns ``"550"`` for models needing transformers 5.5.0 (e.g. Gemma 4),
- ``"530"`` for models needing transformers 5.3.0 (e.g. Ministral-3, Qwen3 MoE),
- or ``"default"`` for everything else (4.57.x).
-
+ ``"550"`` for transformers 5.5.0 (e.g. Gemma 4), ``"530"`` for 5.3.0
+ (e.g. Ministral-3, Qwen3 MoE), or ``"default"`` for everything else (4.57.x).
The 5.5.0 check runs first, then 5.3.0.
"""
lowered = model_name.lower()
@@ -407,9 +398,9 @@ _PURGE_PREFIXES = (
"accelerate",
"auto_gptq",
# NOTE: bitsandbytes is intentionally EXCLUDED — it registers torch custom
- # operators at import time via torch.library.define(). Those registrations
- # live in torch's global operator registry which survives module purge.
- # Re-importing bitsandbytes after purge → duplicate registration → crash.
+ # operators at import via torch.library.define() into torch's global
+ # registry, which survives module purge. Re-importing it after purge →
+ # duplicate registration → crash.
# Our own modules that import from transformers at module level
# (e.g. model_config.py: `from transformers import AutoConfig`)
"utils.models",
@@ -462,15 +453,15 @@ def _venv_dir_is_valid(venv_dir: str, packages: tuple[str, ...]) -> bool:
pkg_name = parts[0]
pkg_version = parts[1] if len(parts) > 1 else None
pkg_name_norm = pkg_name.replace("-", "_")
- # Check directory exists
+ # Directory must exist.
if not any(
(Path(venv_dir) / d).is_dir() for d in (pkg_name_norm, pkg_name_norm.replace("_", "-"))
):
return False
- # For unpinned packages, existence is enough
+ # Unpinned packages: existence is enough.
if pkg_version is None:
continue
- # Check version via .dist-info metadata
+ # Check version via .dist-info metadata.
dist_info_found = False
for di in Path(venv_dir).glob(f"{pkg_name_norm}-*.dist-info"):
metadata = di / "METADATA"
@@ -504,7 +495,7 @@ def _venv_t5_is_valid() -> bool:
def _install_to_dir(pkg: str, target_dir: str) -> bool:
"""Install a single package into *target_dir*, preferring uv then pip."""
- # Try uv first (faster) if already on PATH -- do NOT install uv at runtime
+ # Try uv first (faster) if on PATH -- do NOT install uv at runtime.
if shutil.which("uv"):
result = subprocess.run(
[
@@ -529,7 +520,7 @@ def _install_to_dir(pkg: str, target_dir: str) -> bool:
return True
logger.warning("uv install of %s failed, falling back to pip", pkg)
- # Fallback to pip
+ # Fallback to pip.
result = subprocess.run(
[
sys.executable,
@@ -621,13 +612,13 @@ def ensure_transformers_version(model_name: str) -> None:
• Need 5.3.0 → prepend .venv_t5_530/ to sys.path, purge modules.
• Need 4.x → remove all .venv_t5_*/ from sys.path, purge modules.
- For LoRA adapters with custom names, the base model is resolved from
+ For custom-named LoRA adapters, the base model is resolved from
``adapter_config.json`` before checking.
- NOTE: Training and inference use subprocess isolation instead of this
- function. This is only used by the export path (routes/export.py).
+ NOTE: Training and inference use subprocess isolation instead. Used only by
+ the export path (routes/export.py).
"""
- # Resolve LoRA adapters to their base model for accurate detection
+ # Resolve LoRA adapters to their base model for accurate detection.
resolved = _resolve_base_model(model_name)
tier = get_transformers_tier(resolved)
@@ -666,10 +657,10 @@ def ensure_transformers_version(model_name: str) -> None:
model_name,
)
return
- # Different 5.x → need to switch (e.g. 5.3.0 loaded but need 5.5.0)
+ # Different 5.x → must switch (e.g. 5.3.0 loaded but need 5.5.0).
in_memory_major = int(in_memory.split(".")[0])
if in_memory_major == target_major and venv_dir is None:
- # Both are default (4.x) — close enough
+ # Both are default (4.x) — close enough.
logger.info(
"transformers %s already loaded — correct for '%s'",
in_memory,
@@ -679,7 +670,7 @@ def ensure_transformers_version(model_name: str) -> None:
# --- Switch version -----------------------------------------------------
if venv_dir is not None:
- # First remove any other 5.x venv from sys.path
+ # First remove any other 5.x venv from sys.path.
_deactivate_5x()
if not ensure_fn():
raise RuntimeError(
diff --git a/studio/backend/utils/update_status.py b/studio/backend/utils/update_status.py
index 9b71ff31a01..ad9dabcf363 100644
--- a/studio/backend/utils/update_status.py
+++ b/studio/backend/utils/update_status.py
@@ -3,9 +3,8 @@
"""Web update status helpers for browser-served Unsloth Studio.
-This module is intentionally side-effect light: no network work happens at
-import time or from /api/health. The PyPI check is lazy, cached, and only used
-for normal PyPI-managed installs.
+Side-effect light: no network work at import time or from /api/health.
+The PyPI check is lazy, cached, and only for PyPI-managed installs.
"""
from __future__ import annotations
@@ -66,9 +65,9 @@ def reset_update_status_cache() -> None:
def detect_install_source() -> str:
"""Return a coarse install source without exposing local paths.
- Sources are intentionally conservative. PEP 610 local/vcs metadata wins.
- Legacy source installs are treated as local only when package files resolve
- outside site-packages/dist-packages and under a Git checkout.
+ Conservative: PEP 610 local/vcs metadata wins. Legacy source
+ installs count as local only when package files resolve outside
+ site-packages/dist-packages and under a Git checkout.
"""
try:
dist = distribution(PACKAGE_NAME)
diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.py
index 7a7774be40e..c51fc267f21 100644
--- a/studio/backend/utils/utils.py
+++ b/studio/backend/utils/utils.py
@@ -77,14 +77,14 @@ def log_and_http_error(
@contextmanager
def without_hf_auth():
"""
- Context manager to temporarily disable HuggingFace authentication.
+ Temporarily disable HuggingFace authentication.
Usage:
with without_hf_auth():
# Code that should run without cached tokens
model_info(model_name, token=None)
"""
- # Save environment variables
+ # Save and clear env vars
saved_env = {}
env_vars = ["HF_TOKEN", "HUGGINGFACE_HUB_TOKEN", "HF_HOME"]
for var in env_vars:
@@ -92,11 +92,10 @@ def without_hf_auth():
saved_env[var] = os.environ[var]
del os.environ[var]
- # Save disable flag
saved_disable = os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN")
os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
- # Move token files temporarily
+ # Move token files aside temporarily
token_files = []
token_locations = [
Path.home() / ".cache" / "huggingface" / "token",
@@ -121,7 +120,7 @@ def without_hf_auth():
except Exception as e:
logger.error(f"Failed to restore token {original}: {e}")
- # Restore environment
+ # Restore env
for var, value in saved_env.items():
os.environ[var] = value
@@ -133,14 +132,11 @@ def without_hf_auth():
def format_error_message(error: Exception, model_name: str) -> str:
"""
- Format user-friendly error messages for common issues.
+ Format a user-friendly error message for common load issues.
Args:
error: The exception that occurred
model_name: Name of the model being loaded
-
- Returns:
- User-friendly error string
"""
error_str = str(error).lower()
model_short = model_name.split("/")[-1] if "/" in model_name else model_name
@@ -171,5 +167,4 @@ def format_error_message(error: Exception, model_name: str) -> str:
)
return f"Not enough {device_label} memory to load '{model_short}'. Try a smaller model or free memory."
- # Generic fallback
return str(error)
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index cca30bfd44d..59632963b76 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -27,12 +27,12 @@ def has_blackwell_gpu() -> bool:
"""Return True if any visible NVIDIA GPU has compute capability >= 10.0
(Blackwell: sm_100, sm_120, sm_121, ...).
- Dao-AILab does not publish prebuilt flash-attention wheels for these
- architectures, and the older-arch wheels fail to load on Blackwell, so
- callers use this gate to skip the flash-attn install/upgrade path.
+ Dao-AILab publishes no prebuilt flash-attention wheels for these archs,
+ and older-arch wheels fail to load on Blackwell, so callers use this gate
+ to skip the flash-attn install/upgrade path.
- Result is cached for the process lifetime since GPU hardware does not
- change. Tests that mock subprocess/nvidia-smi must call
+ Cached for the process lifetime since GPU hardware doesn't change. Tests
+ that mock subprocess/nvidia-smi must call
``has_blackwell_gpu.cache_clear()`` before each invocation.
"""
exe = shutil.which("nvidia-smi")
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index 09953843f0c..80e5257c8d0 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -89,9 +89,9 @@ def env_int(
return value
-# Prefer "latest" over "master" -- "master" bypasses the prebuilt resolver
+# Prefer "latest" over "master": "master" bypasses the prebuilt resolver
# (no matching GitHub release), forces a source build, and causes HTTP 422
-# errors. Only use "master" temporarily when the latest release is missing
+# errors. Use "master" only temporarily when the latest release lacks
# support for a new model architecture.
DEFAULT_LLAMA_TAG = os.environ.get("UNSLOTH_LLAMA_TAG", "latest")
# Default published repo for prebuilt release resolution. Linux uses
@@ -113,21 +113,19 @@ LEMONADE_ROCM_RELEASES_API = f"https://api.github.com/repos/{LEMONADE_ROCM_REPO}
def _lemonade_release_api_for(llama_tag: str) -> str:
- """Return the GitHub API URL for the lemonade release that matches a
- requested llama.cpp tag.
-
- When llama_tag is unset or "latest", point at /releases/latest. When the
- caller has pinned a specific tag (e.g. "b1260"), point at the same tag in
- lemonade. Lemonade tracks `ggml-org/llama.cpp` build tags (e.g. "b1260")
- but is NOT guaranteed to publish every upstream build -- lemonade may be
- several builds behind ggml-org. Pinning to a specific tag that lemonade
- skipped will produce a 404 and the caller falls through to the upstream
- tarball; that is intentional so pinned installs stay reproducible.
- Do NOT pass a `unslothai/llama.cpp` fork tag -- the fork uses its own
- namespace and will always 404 against lemonade.
-
- The tag is URL-encoded with `safe=""` so an unexpected slash / hash / query
- character cannot reshape the URL.
+ """Return the GitHub API URL for the lemonade release matching a llama.cpp tag.
+
+ When llama_tag is unset or "latest", point at /releases/latest. When
+ pinned (e.g. "b1260"), point at the same tag in lemonade. Lemonade
+ tracks `ggml-org/llama.cpp` build tags but is NOT guaranteed to publish
+ every upstream build -- it may be several builds behind. Pinning a tag
+ lemonade skipped produces a 404 and the caller falls through to the
+ upstream tarball; intentional so pinned installs stay reproducible.
+ Do NOT pass a `unslothai/llama.cpp` fork tag -- the fork's namespace
+ always 404s against lemonade.
+
+ The tag is URL-encoded with `safe=""` so a stray slash / hash / query
+ char cannot reshape the URL.
"""
normalized = (llama_tag or "").strip()
if not normalized or normalized.lower() == "latest":
@@ -162,25 +160,25 @@ DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS = env_int(
2,
minimum = 1,
)
-# Deeper macOS-only walk-back: upstream can ship a run of prebuilts built for a
-# newer macOS than the host, only caught at validate time, so an older host must
-# skip the whole run. Free on new hosts (first plan validates, extras unused).
+# Deeper macOS-only walk-back: upstream can ship a run of prebuilts built for
+# a newer macOS than the host, caught only at validate time, so an older host
+# must skip the whole run. Free on new hosts (first plan validates).
DEFAULT_MAX_MACOS_RELEASE_FALLBACKS = env_int(
"UNSLOTH_LLAMA_MAX_MACOS_RELEASE_FALLBACKS",
16,
minimum = 1,
)
# Deterministic macOS pin. At b9428 ggml-org's macOS runner moved to macOS 26
-# (Tahoe), so b9428+ prebuilts only load on macOS 26+. b9415 is the last build
-# stamped below 26 (arm64 minos 14, x64 minos 13.3); loads on macOS 13.3/14/15/26.
+# (Tahoe), so b9428+ prebuilts load only on macOS 26+. b9415 is the last build
+# stamped below 26 (arm64 minos 14, x64 minos 13.3); loads on 13.3/14/15/26.
_PINNED_MACOS_FALLBACK_TAG = "b9415"
_PINNED_MACOS_LATEST_FLOOR = (26, 0)
FORCE_COMPILE_DEFAULT_REF = os.environ.get("UNSLOTH_LLAMA_FORCE_COMPILE_REF", "master")
# sm_103 (B300 / GB300 Blackwell Ultra) is not built natively but runs on the
# bundled base compute_100 PTX, which the driver JIT-compiles forward to sm_103.
-# It is listed in every bundle that ships the sm_100 build (the "newer" and
-# "portable" classes) so those hosts get a prebuilt instead of a source compile.
+# Listed in every bundle that ships the sm_100 build (the "newer" and
+# "portable" classes) so those hosts get a prebuilt, not a source compile.
DIRECT_LINUX_BUNDLE_PROFILES: dict[str, dict[str, Any]] = {
"cuda12-older": {
"runtime_line": "cuda12",
@@ -234,18 +232,18 @@ DIRECT_LINUX_BUNDLE_PROFILES: dict[str, dict[str, Any]] = {
# Lowest CUDA major we ship prebuilts for, and the highest major we probe for
# installed runtime libraries. Detection and runtime-line derivation are
-# generated per major so a new toolkit (cuda14, ...) needs no code change while
-# llama.cpp keeps the cudart64_<major>.dll / libcudart.so.<major> naming.
+# generated per major so a new toolkit (cuda14, ...) needs no code change as
+# long as llama.cpp keeps the cudart64_<major>.dll / libcudart.so.<major> naming.
_MIN_CUDA_MAJOR = 12
_MAX_PROBE_CUDA_MAJOR = 19
# Last ggml-org release whose Windows win-cuda-13 build is still sub-13.3
# (cuda-13.1, b9360, 2026-05-27). Upstream bumped win-cuda-13 to 13.3 at b9365
# and now ships only cuda-12.4 + cuda-13.3. cuda-12.4 predates Blackwell (ggml
-# compiles sm_120 only at toolkit >= 12.8), so a Blackwell host on a 13.0/13.1/13.2
-# driver is gated off 13.3 and would drop to a CPU-only 12.4 build. b9360 is
-# immutable, so we pin its cuda-13.1 build (plus paired cudart) as a GPU
-# fallback for exactly those hosts. See unslothai/unsloth#5887.
+# compiles sm_120 only at toolkit >= 12.8), so a Blackwell host on a
+# 13.0/13.1/13.2 driver is gated off 13.3 and would drop to CPU-only 12.4.
+# b9360 is immutable, so we pin its cuda-13.1 build (plus paired cudart) as a
+# GPU fallback for exactly those hosts. See unslothai/unsloth#5887.
_PINNED_BLACKWELL_FALLBACK_TAG = "b9360"
_PINNED_BLACKWELL_FALLBACK_RUNTIME = "13.1"
# Floor at 13.0: b9360 ships native sm_120a SASS (no PTX/JIT) and a bundled
@@ -255,15 +253,15 @@ _PINNED_BLACKWELL_DRIVER_FLOOR = (13, 0)
_BLACKWELL_MIN_SM = 120
# ggml compiles Blackwell sm_120 only at toolkit >= 12.8, so an in-release
# windows-cuda build at or above this already covers Blackwell and makes the
-# older pinned 13.1 fallback unnecessary (cuda-12.4 is below it).
+# pinned 13.1 fallback unnecessary (cuda-12.4 is below it).
_BLACKWELL_MIN_TOOLKIT = (12, 8)
_PINNED_BLACKWELL_LLAMA_SHA256 = "31ddb8b42d7ab4a47cab8c48c397519f580ca502df7e73f3ab396eacc16c8e8d"
_PINNED_BLACKWELL_CUDART_SHA256 = "f96935e7e385e3b2d0189239077c10fe8fd7e95690fea4afec455b1b6c7e3f18"
def _cuda_runtime_lines_for_major(major: int) -> list[str]:
- """Runtime lines a driver of this CUDA major can use, newest major first
- down to the minimum we ship. A driver runs its own major and any older one
+ """Runtime lines a driver of this CUDA major can use, newest first down to
+ the minimum we ship. A driver runs its own major and any older one
(backward compatibility)."""
return [f"cuda{m}" for m in range(major, _MIN_CUDA_MAJOR - 1, -1)]
@@ -272,7 +270,7 @@ def _resolve_linux_bundle_profile(bundle_profile: str) -> "dict[str, Any] | None
"""Profile (runtime line + sm coverage) for a linux-x64-cuda<major>-<class>
bundle. Known majors use their published coverage; an unknown future major
reuses the newest known major's coverage for the same class as a forward
- default, with the post-build GPU smoke test as the backstop."""
+ default, with the post-build GPU smoke test as backstop."""
known = DIRECT_LINUX_BUNDLE_PROFILES.get(bundle_profile)
if known is not None:
return known
@@ -325,8 +323,8 @@ class AssetChoice:
url: str
source_label: str
# Paired runtime archive (Windows CUDA cudart bundle). When set,
- # install_from_archives also downloads it and overlays its DLLs on
- # top of the main install. See unslothai/unsloth#5106.
+ # install_from_archives also downloads it and overlays its DLLs on top
+ # of the main install. See unslothai/unsloth#5106.
runtime_name: str | None = None
runtime_url: str | None = None
runtime_sha256: str | None = None
@@ -553,14 +551,13 @@ def is_github_api_url(url: str | None) -> bool:
def is_retryable_url_error(exc: Exception) -> bool:
if isinstance(exc, urllib.error.HTTPError):
- # GitHub returns 403 (not the standard 429) when the API rate
- # limit is hit. Anonymous calls share a 60-req/hour bucket per
- # runner IP, which CI fleets can exhaust trivially. Treat 403
- # against api.github.com as retryable so we get one or two
- # backoff cycles before the source-build fallback fires; honour
- # Retry-After / X-RateLimit-Reset in sleep_backoff for accurate
- # waits. Real 403s on other hosts (private artefact downloads,
- # auth failures) stay non-retryable.
+ # GitHub returns 403 (not 429) when the API rate limit is hit.
+ # Anonymous calls share a 60-req/hour bucket per runner IP, which
+ # CI fleets exhaust trivially. Treat 403 against api.github.com as
+ # retryable so we get a backoff cycle or two before the source-build
+ # fallback fires; sleep_backoff honours Retry-After /
+ # X-RateLimit-Reset for accurate waits. Real 403s on other hosts
+ # (private artefact downloads, auth failures) stay non-retryable.
if exc.code == 403:
return is_github_api_url(getattr(exc, "url", None))
return exc.code in RETRYABLE_HTTP_STATUS
@@ -579,9 +576,9 @@ _RATE_LIMIT_WAIT_CAP_SECONDS = 60.0
def _http_error_retry_delay(exc: Exception) -> float | None:
"""Extract a recommended wait from rate-limit headers on a 403/429.
- Returns None when no header is present or the indicated wait is
- longer than _RATE_LIMIT_WAIT_CAP_SECONDS (in which case the caller
- should not block on it -- the source-build fallback is faster).
+ Returns None when no header is present or the wait exceeds
+ _RATE_LIMIT_WAIT_CAP_SECONDS (the caller should not block then -- the
+ source-build fallback is faster).
"""
if not isinstance(exc, urllib.error.HTTPError):
return None
@@ -790,12 +787,12 @@ def refs_match(candidate_ref: str | None, requested_ref: str | None) -> bool:
def checkout_friendly_ref(ref_kind: str | None, ref: str | None) -> str | None:
- """Normalize a source ref to a form that ``git clone --branch`` accepts.
+ """Normalize a source ref to a form ``git clone --branch`` accepts.
- Fully qualified branch refs like ``refs/heads/main`` are stripped to
- ``main``; tag refs like ``refs/tags/b8508`` are stripped to ``b8508``.
- Pull refs like ``refs/pull/123/head`` are left as-is since they are
- always fetched explicitly rather than cloned with ``--branch``.
+ Fully qualified branch refs (``refs/heads/main``) are stripped to
+ ``main``; tag refs (``refs/tags/b8508``) to ``b8508``. Pull refs
+ (``refs/pull/123/head``) are left as-is since they are fetched
+ explicitly rather than cloned with ``--branch``.
"""
if not isinstance(ref, str) or not ref:
return ref
@@ -845,8 +842,8 @@ def _published_windows_cuda_runtime(
"""Highest cuda-<major>.<minor> published upstream that `driver` can run by
default CUDA compatibility, i.e. (major, minor) <= driver. None if nothing
qualifies. Gating on the driver (not just the major) keeps a 13.3 build off
- a driver that only advertises 13.1, where it would otherwise rely on the
- unguaranteed minor-version-compatibility path."""
+ a 13.1-only driver, where it would rely on the unguaranteed
+ minor-version-compatibility path."""
if driver is None:
return None
best: int | None = None
@@ -1361,8 +1358,8 @@ def direct_linux_release_plan(
attempts: list[AssetChoice] = []
if host.has_usable_nvidia:
# Prefer the cudart major Studio loads at runtime (torch's bundled
- # libcudart), not the newest detected on disk. Without this a stray
- # cuda13 runtime outranks the torch cuda12 the binary links against.
+ # libcudart), not the newest on disk. Otherwise a stray cuda13
+ # runtime outranks the torch cuda12 the binary links against.
torch_preference = detect_torch_cuda_runtime_preference(host)
selection = linux_cuda_choice_from_release(
host,
@@ -1375,14 +1372,13 @@ def direct_linux_release_plan(
if host.has_rocm and not host.has_usable_nvidia:
# Per-GPU lemonade prebuilts ship the ROCm runtime libs alongside
# llama.cpp, so they install cleanly even on hosts (e.g. gfx1151
- # Strix Halo) that the upstream combined-ROCm tarball doesn't cover.
- # The "ubuntu" label is lemonade's asset naming convention only --
- # the binary is a manylinux-style glibc build that runs on Arch,
- # Fedora, openSUSE, etc. as long as the host glibc is recent enough.
- # Do NOT append the CPU asset for ROCm-only hosts: if lemonade fails
- # validation we want validate_prebuilt_attempts to raise PrebuiltFallback
- # so the caller triggers the HIP source build, not silently install a
- # CPU-only binary.
+ # Strix Halo) the upstream combined-ROCm tarball doesn't cover.
+ # "ubuntu" is lemonade's asset naming convention only -- the binary
+ # is a manylinux-style glibc build that runs on Arch, Fedora,
+ # openSUSE, etc. with a recent-enough glibc. Do NOT append the CPU
+ # asset for ROCm-only hosts: if lemonade fails validation we want
+ # validate_prebuilt_attempts to raise PrebuiltFallback so the caller
+ # triggers the HIP source build, not silently install a CPU binary.
lemonade_choice = resolve_lemonade_rocm_choice(
host, "ubuntu", "linux-rocm", llama_tag = requested_tag
)
@@ -1405,9 +1401,9 @@ def direct_linux_release_plan(
):
approved_checksums = load_approved_release_checksums(repo, bundle.release_tag)
# Require exact source provenance for branch/pull/commit releases.
- # Mirrors validated_checksums_for_bundle so incomplete metadata
- # fails closed instead of degrading to the legacy branch-as-tag
- # source hydration path that this PR is meant to eliminate.
+ # Mirrors validated_checksums_for_bundle so incomplete metadata fails
+ # closed instead of degrading to the legacy branch-as-tag source
+ # hydration path this PR eliminates.
if (
not approved_checksums.source_commit
or exact_source_archive_hash(approved_checksums) is None
@@ -1455,7 +1451,7 @@ def direct_upstream_release_plan(
)
)
# Blackwell on a 13.1/13.2 driver: prefer the pinned cuda-13.1 GPU
- # build over the CPU-only cuda-12.4 the in-release gating leaves.
+ # build over the CPU-only cuda-12.4 left by in-release gating.
pinned = _pinned_windows_cuda_fallback(host, attempts)
if pinned is not None:
attempts.insert(0, pinned)
@@ -1493,9 +1489,9 @@ def direct_upstream_release_plan(
)
elif host.is_windows and host.is_arm64:
# Upstream ggml-org/llama.cpp ships llama-bNNNN-bin-win-cpu-arm64.zip
- # (visible in the b9334 release manifest). Without this branch the
- # selector returned 0 attempts and the installer fell back to a
- # source build on every Windows ARM64 host.
+ # (in the b9334 release manifest). Without this branch the selector
+ # returned 0 attempts and fell back to a source build on every
+ # Windows ARM64 host.
cpu_asset = f"llama-{release_tag}-bin-win-cpu-arm64.zip"
cpu_url = assets.get(cpu_asset)
if cpu_url:
@@ -1553,10 +1549,10 @@ def direct_upstream_release_plan(
)
elif host.is_linux and host.is_arm64 and not host.has_usable_nvidia:
# Upstream ggml-org/llama.cpp ships llama-bNNNN-bin-ubuntu-arm64.tar.gz
- # (visible in the b9334 release manifest). Without this branch the
- # selector returned 0 attempts and the installer fell back to a
- # source build on every Linux ARM64 host (DGX Spark, Ampere
- # Altra, GitHub-hosted ubuntu-24.04-arm runners, etc.).
+ # (in the b9334 release manifest). Without this branch the selector
+ # returned 0 attempts and fell back to a source build on every Linux
+ # ARM64 host (DGX Spark, Ampere Altra, GitHub ubuntu-24.04-arm
+ # runners, etc.).
asset_name = f"llama-{release_tag}-bin-ubuntu-arm64.tar.gz"
asset_url = assets.get(asset_name)
if asset_url:
@@ -1586,9 +1582,9 @@ def direct_upstream_release_plan(
def pinned_macos_release_tag(host: HostInfo, repo: str) -> str | None:
- """Pin b9415 (the last upstream macOS build that loads below macOS 26) for a
- known pre-26 host on ggml-org upstream; return None to keep latest selection.
- The unslothai/llama.cpp fork ships its own prebuilts (arm64 minos 14, x64
+ """Pin b9415 (last upstream macOS build that loads below macOS 26) for a
+ known pre-26 host on ggml-org upstream; None keeps latest selection. The
+ unslothai/llama.cpp fork ships its own prebuilts (arm64 minos 14, x64
minos 13.3) and needs no pin, so this is a no-op there and for macOS 26+,
unknown version, non-macOS."""
if repo != UPSTREAM_REPO:
@@ -1614,9 +1610,9 @@ def resolve_simple_install_release_plans(
repo = published_repo or DEFAULT_PUBLISHED_REPO
requested_tag = normalized_requested_llama_tag(llama_tag)
# The unslothai/llama.cpp fork ships only linux-x64 bundles. An arm64 Linux
- # host with a GPU (GH200/GB200/DGX Spark) routes here; it must not install an
- # x64 binary, so fall back to a source build that targets the GPU rather than
- # selecting the wrong arch (or silently dropping to a CPU arm64 build).
+ # host with a GPU (GH200/GB200/DGX Spark) routes here; it must not install
+ # an x64 binary, so fall back to a GPU-targeting source build rather than
+ # the wrong arch (or silently dropping to a CPU arm64 build).
if host.is_linux and not host.is_x86_64 and repo == DEFAULT_PUBLISHED_REPO:
raise PrebuiltFallback(
f"{repo} ships only linux-x64 prebuilts; "
@@ -1625,7 +1621,7 @@ def resolve_simple_install_release_plans(
allow_older_release_fallback = requested_tag == "latest" and not published_release_tag
# macOS: pin the last upstream build that loads on a pre-26 host instead of
# fetching the latest (macOS 26 only) build and walking back release by
- # release. No-op on macOS 26+, unknown version, non-macOS, and the fork.
+ # release. No-op on macOS 26+, unknown version, non-macOS, the fork.
if allow_older_release_fallback:
pinned_macos = pinned_macos_release_tag(host, repo)
if pinned_macos is not None:
@@ -1940,8 +1936,8 @@ def parse_published_release_bundle(
if not manifest_url:
return None
- # Mixed repos are filtered by an explicit release-side manifest rather than
- # by release tag or asset filename conventions.
+ # Mixed repos are filtered by an explicit release-side manifest, not by
+ # release tag or asset filename conventions.
manifest_bytes = download_bytes(
manifest_url,
timeout = 30,
@@ -2393,9 +2389,9 @@ def validated_checksums_for_bundle(
raise PrebuiltFallback(
"published manifest checksum did not match the approved checksum asset"
)
- # Accept bundles that carry only an exact-commit source archive
- # (e.g. llama.cpp-source-commit-<sha>.tar.gz) without requiring the
- # legacy llama.cpp-source-<upstream_tag>.tar.gz entry.
+ # Accept bundles carrying only an exact-commit source archive
+ # (llama.cpp-source-commit-<sha>.tar.gz) without requiring the legacy
+ # llama.cpp-source-<upstream_tag>.tar.gz entry.
if exact_source_archive_hash(checksums) is None:
require_approved_source_hash(checksums, bundle.upstream_tag)
return checksums
@@ -2531,23 +2527,22 @@ def resolve_requested_llama_tag(
Resolution order:
1. Concrete tag (e.g. "b8508") -- returned as-is.
- 2. "latest" with published_repo -- resolve the latest usable Unsloth
- published release bundle and return its upstream_tag. This is the
- preferred version that matches the published prebuilt metadata.
- 3. "latest" without published_repo or if (2) fails -- query the upstream
- ggml-org/llama.cpp repo. This may return a newer, untested tag.
-
- The Unsloth repo is preferred because its releases are pinned to specific
- upstream tags that have been validated with Unsloth Studio. Using the
- upstream bleeding-edge tag risks API/ABI incompatibilities.
+ 2. "latest" with published_repo -- the latest usable Unsloth published
+ bundle's upstream_tag (matches the published prebuilt metadata).
+ 3. "latest" without published_repo, or if (2) fails -- query upstream
+ ggml-org/llama.cpp. May return a newer, untested tag.
+
+ The Unsloth repo is preferred because its releases are pinned to upstream
+ tags validated with Unsloth Studio; the upstream bleeding-edge tag risks
+ API/ABI incompatibilities.
"""
normalized_requested = normalized_requested_llama_tag(requested_tag)
if normalized_requested != "latest":
return normalized_requested
# Prefer the Unsloth release repo tag (tested/approved) over bleeding-edge
- # upstream. For example, unslothai/llama.cpp may publish b8508 while
- # ggml-org/llama.cpp latest is b8514. The source-build fallback should
- # compile the same version the prebuilt path would have installed.
+ # upstream. E.g. unslothai/llama.cpp may publish b8508 while ggml-org
+ # latest is b8514. The source-build fallback should compile the same
+ # version the prebuilt path would have installed.
if published_repo:
try:
return resolve_published_release(
@@ -2557,7 +2552,7 @@ def resolve_requested_llama_tag(
).bundle.upstream_tag
except Exception:
pass
- # Fall back to upstream ggml-org latest release tag
+ # Fall back to the upstream ggml-org latest release tag
return latest_upstream_release_tag()
@@ -2704,38 +2699,38 @@ def _pick_rocm_gfx_target(out: str) -> str | None:
A bare first-match picked the wrong device on mixed APU + dGPU hosts
(e.g. Strix Halo gfx1151 + discrete RX 7900 gfx1100). Respect
HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES so the
- asset matches what HIP actually runs on. Falls back to the first GPU when
- no env var is set.
+ asset matches what HIP runs on; falls back to the first GPU with no env
+ var set.
rocminfo / hipinfo print the same gfx token multiple times per GPU (Name,
- ISA, marketing-name). We first try to split the output on per-GPU section
- headers (rocminfo: "Agent N" blocks, hipinfo: "device#N" entries) and take
- exactly one gfx token per section. This gives the correct per-GPU list even
- on same-arch multi-GPU hosts (e.g. two RX 7900 XTX cards) where global
- dict.fromkeys dedup would collapse both cards to a single entry and make
- HIP_VISIBLE_DEVICES=1 point out of range.
+ ISA, marketing-name). We first split the output on per-GPU section headers
+ (rocminfo: "Agent N" blocks, hipinfo: "device#N" entries) and take exactly
+ one gfx token per section -- this gives the correct per-GPU list even on
+ same-arch multi-GPU hosts (e.g. two RX 7900 XTX) where global dict.fromkeys
+ dedup would collapse both to one entry and make HIP_VISIBLE_DEVICES=1 point
+ out of range.
Falls back to insertion-order dedup when the output has no recognisable
section markers (flat gfx-string inputs, unit-test stubs, etc.).
Empty / "-1" env values mean no AMD GPU is visible to HIP: return None.
"""
- # Try to build a per-GPU token list by splitting on section boundaries.
- # rocminfo sections are introduced by "Agent N" lines (optionally between
- # rows of asterisks). hipinfo sections start with "device#N".
+ # Build a per-GPU token list by splitting on section boundaries. rocminfo
+ # sections start with "Agent N" lines (optionally between rows of
+ # asterisks); hipinfo sections with "device#N".
_sections = re.split(
r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bdevice\s*#\s*\d+\b",
out,
)
if len(_sections) > 1:
- # Section-based: one gfx token per GPU section preserves physical order.
+ # One gfx token per GPU section preserves physical order.
_tokens: list[str] = []
for _sec in _sections[1:]:
_m = re.search(r"gfx[1-9][0-9a-z]{2,3}", _sec.lower())
if _m:
_tokens.append(_m.group(0))
else:
- # Fallback: insertion-order dedup (handles flat strings / unknown formats).
+ # Fallback: insertion-order dedup (flat strings / unknown formats).
_raw = re.findall(r"gfx[1-9][0-9a-z]{2,3}", out.lower())
_tokens = list(dict.fromkeys(_raw))
@@ -2751,7 +2746,7 @@ def _pick_rocm_gfx_target(out: str) -> str | None:
break
if _vis_raw is not None:
_vis = _vis_raw.strip()
- # Empty or "-1" means "no AMD GPU visible" (matches the rest of Studio).
+ # Empty or "-1" means "no AMD GPU visible" (matches the rest of Studio)
if _vis == "" or _vis == "-1":
return None
_first = _vis.split(",")[0].strip()
@@ -2783,11 +2778,10 @@ def detect_host() -> HostInfo:
has_physical_nvidia = False
has_usable_nvidia = False
if nvidia_smi:
- # Require `nvidia-smi -L` to actually list a GPU before treating the
- # host as NVIDIA. The banner text "NVIDIA-SMI ..." is printed even
- # when the command fails to communicate with the driver (e.g. stale
- # container leftovers), which would otherwise misclassify an AMD
- # ROCm host as NVIDIA and short-circuit the ROCm path.
+ # Require `nvidia-smi -L` to list a GPU before treating the host as
+ # NVIDIA. The "NVIDIA-SMI ..." banner prints even when the command
+ # can't reach the driver (e.g. stale container leftovers), which
+ # would misclassify an AMD ROCm host as NVIDIA and skip the ROCm path.
try:
listing = run_capture([nvidia_smi, "-L"], timeout = 20)
gpu_lines = [line for line in listing.stdout.splitlines() if line.startswith("GPU ")]
@@ -2800,9 +2794,9 @@ def detect_host() -> HostInfo:
try:
result = run_capture([nvidia_smi], timeout = 20)
merged = "\n".join(part for part in (result.stdout, result.stderr) if part)
- # Newer NVIDIA drivers (e.g. 610.x on Windows) print
- # "CUDA UMD Version: X.Y" instead of the legacy
- # "CUDA Version: X.Y"; accept both spellings.
+ # Newer NVIDIA drivers (e.g. 610.x on Windows) print "CUDA UMD
+ # Version: X.Y" instead of the legacy "CUDA Version: X.Y"; accept
+ # both spellings.
cuda_match = re.search(
r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)",
merged,
@@ -2845,10 +2839,10 @@ def detect_host() -> HostInfo:
if visible_gpu_rows:
has_usable_nvidia = True
- # Older nvidia-smi versions (pre -L support) hit the
- # except in the first try block but still succeed here,
- # leaving has_physical_nvidia unset. Mirror the -L path
- # so downstream diagnostics on line ~4390 still run.
+ # Older nvidia-smi (pre -L support) hits the except in the
+ # first try block but still succeeds here, leaving
+ # has_physical_nvidia unset. Mirror the -L path so downstream
+ # diagnostics on line ~4390 still run.
if not has_physical_nvidia:
has_physical_nvidia = True
elif visible_device_tokens == []:
@@ -2870,10 +2864,10 @@ def detect_host() -> HostInfo:
rocm_gfx_target: str | None = None
if is_linux:
for _cmd, _check in (
- # rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
- # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
- # "gfx11-generic" or "gfx9-4-generic" which only have 1-2 digits before
- # the dash and must not be treated as a real GPU.
+ # rocminfo: a real gfx GPU id (3-4 chars, nonzero first digit).
+ # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines
+ # ("gfx11-generic", "gfx9-4-generic") with only 1-2 digits before
+ # the dash, which must not be treated as a real GPU.
(
["rocminfo"],
lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
@@ -2893,14 +2887,13 @@ def detect_host() -> HostInfo:
rocm_gfx_target = _pick_rocm_gfx_target(_result.stdout)
break
elif is_windows:
- # Windows: prefer active probes that validate GPU presence.
- # hipinfo / amd-smi are often NOT on PATH -- the HIP SDK installer
- # sets HIP_PATH / ROCM_PATH but does not always add the bin dir to
- # the system PATH. Mirror setup.ps1's fallback: check the env-var
- # bin dirs before giving up so that `has_rocm` is not silently False
- # on machines where the PATH is not yet updated.
+ # Windows: prefer active probes that validate GPU presence. hipinfo /
+ # amd-smi are often NOT on PATH -- the HIP SDK installer sets HIP_PATH
+ # / ROCM_PATH but doesn't always add the bin dir to PATH. Mirror
+ # setup.ps1's fallback: check the env-var bin dirs before giving up so
+ # `has_rocm` isn't silently False when PATH isn't updated yet.
def _resolve_exe(name: str) -> str | None:
- """Return full path to `name`, checking PATH then HIP_PATH/ROCM_PATH bin."""
+ """Full path to `name`, checking PATH then HIP_PATH/ROCM_PATH bin."""
found = shutil.which(name)
if found:
return found
@@ -2929,8 +2922,8 @@ def detect_host() -> HostInfo:
# hipinfo reports "gcnArchName: gfx1100" -- extract if present
rocm_gfx_target = _pick_rocm_gfx_target(_result.stdout)
break
- # Note: amdhip64.dll presence alone is NOT treated as GPU evidence
- # since the HIP SDK can be installed without an AMD GPU.
+ # Note: amdhip64.dll presence alone is NOT GPU evidence -- the HIP SDK
+ # can be installed without an AMD GPU.
return HostInfo(
system = system,
@@ -2955,7 +2948,7 @@ def detect_host() -> HostInfo:
def _normalize_forwarded_gfx(value: str | None) -> str | None:
"""Extract a single gfx token from a forwarded --rocm-gfx / env value.
setup.sh/setup.ps1 already picked the active GPU, so take the token as-is
- without re-applying visible-device selection. Ignore anything malformed."""
+ without re-applying visible-device selection. Ignore malformed input."""
if not value:
return None
m = re.search(r"gfx[1-9][0-9a-z]{2,3}", value.lower())
@@ -2971,8 +2964,8 @@ def _apply_host_overrides(
) -> HostInfo:
"""Fold setup.sh/setup.ps1's forwarded detection into the host profile.
A forwarded gfx (--rocm-gfx or UNSLOTH_ROCM_GFX_ARCH) is authoritative and
- implies ROCm: the installer's own hipinfo/amd-smi probe can miss the arch on
- amd-smi-only hosts or when setup inferred it from the GPU name, leaving
+ implies ROCm: the installer's own hipinfo/amd-smi probe can miss the arch
+ on amd-smi-only hosts or when setup inferred it from the GPU name, leaving
rocm_gfx_target None and no lemonade prebuilt selected. force_cpu is the
opposite explicit signal (arm64 Linux GPU host whose source build failed):
drop GPU attributes so the CPU prebuilt for this OS/arch is selected."""
@@ -3014,7 +3007,7 @@ def compatible_linux_runtime_lines(host: HostInfo) -> list[str]:
def windows_runtime_line_info() -> dict[str, tuple[str, ...]]:
# Generated per CUDA major (newest first) so a new toolkit is detected
- # without a code change while the cudart64_<major>.dll naming holds.
+ # without code changes while the cudart64_<major>.dll naming holds.
return {
f"cuda{m}": (
f"cudart64_{m}*.dll",
@@ -3041,7 +3034,7 @@ def compatible_windows_runtime_lines(host: HostInfo) -> list[str]:
if not host.driver_cuda_version:
return []
major, minor = host.driver_cuda_version
- # cuda12 prebuilts need a 12.4+ driver; cuda13+ any minor of the major.
+ # cuda12 prebuilts need a 12.4+ driver; cuda13+ any minor.
if major < _MIN_CUDA_MAJOR or (major == _MIN_CUDA_MAJOR and minor < 4):
return []
return _cuda_runtime_lines_for_major(major)
@@ -3181,8 +3174,8 @@ def windows_cuda_attempts(
runtime_order.extend(
runtime_line for runtime_line in normal_runtime_lines if runtime_line not in runtime_order
)
- # Keep every driver-compatible line reachable as a fallback, so a line gated
- # out by the driver version still drops to an older major (cuda13 -> cuda12).
+ # Keep every driver-compatible line reachable as a fallback, so a line
+ # gated out by driver version still drops to an older major (cuda13->cuda12).
runtime_order.extend(
runtime_line
for runtime_line in compatible_runtime_lines
@@ -3201,7 +3194,7 @@ def windows_cuda_attempts(
for runtime_line in runtime_order:
major = int(runtime_line.removeprefix("cuda"))
# Track whatever minor llama.cpp actually ships for this major
- # (cuda13 -> 13.1, 13.3, ...). Skip the line when the release has no
+ # (cuda13 -> 13.1, 13.3, ...). Skip the line when the release lacks a
# matching asset instead of guessing a now-missing name.
runtime = _published_windows_cuda_runtime(upstream_assets, major, host.driver_cuda_version)
if runtime is None:
@@ -3222,10 +3215,10 @@ def windows_cuda_attempts(
+ ",".join(windows_cuda_upstream_asset_names(llama_tag, runtime))
)
continue
- # Pair the cudart bundle when upstream ships it. Without this
- # the binary needs a system CUDA toolkit on PATH at runtime
- # (#5106). Only pair when the selected main archive is the
- # binary archive, not the cudart archive itself.
+ # Pair the cudart bundle when upstream ships it; otherwise the binary
+ # needs a system CUDA toolkit on PATH at runtime (#5106). Only pair
+ # when the selected main archive is the binary archive, not the cudart
+ # archive itself.
runtime_archive_name: str | None = None
runtime_archive_url: str | None = None
if selected_name.startswith("llama-"):
@@ -3264,8 +3257,8 @@ def windows_cuda_attempts(
def _windows_cuda_attempt_covers_blackwell(attempt: AssetChoice) -> bool:
- """True if an in-release windows-cuda attempt is built with a toolkit that
- covers Blackwell sm_120 (>= 12.8), read from its asset name's CUDA minor."""
+ """True if an in-release windows-cuda attempt's toolkit covers Blackwell
+ sm_120 (>= 12.8), read from its asset name's CUDA minor."""
if attempt.install_kind != "windows-cuda":
return False
m = re.search(r"-bin-win-cuda-(\d+)\.(\d+)-x64\.zip$", attempt.name)
@@ -3276,16 +3269,16 @@ def _pinned_windows_cuda_fallback(
host: HostInfo, existing_cuda_attempts: list[AssetChoice]
) -> AssetChoice | None:
"""Pinned GPU fallback for a Blackwell host the in-release build gates off.
- Upstream stopped publishing a sub-13.3 Windows cuda13 build after b9360, and
- cuda-12.4 cannot offload sm_120, so a 13.1/13.2 driver would land on CPU.
- b9360's cuda-13.1 build is immutable and runs on those drivers. Returns None
- (dormant) whenever the in-release selection already offers a Blackwell-capable
- build (toolkit >= 12.8, e.g. a runnable cuda13/cuda14), so it self-disables
- once upstream ships a driver-runnable build again.
-
- The b9360 binary reuses the current release's source tree and convert scripts
- and is recorded via binary_release_tag, the same binary/source split used for
- the lemonade prebuilt."""
+ Upstream stopped publishing a sub-13.3 Windows cuda13 build after b9360,
+ and cuda-12.4 cannot offload sm_120, so a 13.1/13.2 driver would land on
+ CPU. b9360's cuda-13.1 build is immutable and runs on those drivers.
+ Returns None (dormant) whenever the in-release selection already offers a
+ Blackwell-capable build (toolkit >= 12.8, e.g. a runnable cuda13/cuda14),
+ so it self-disables once upstream ships a driver-runnable build again.
+
+ The b9360 binary reuses the current release's source tree and convert
+ scripts and is recorded via binary_release_tag, the same binary/source
+ split used for the lemonade prebuilt."""
if not (host.is_windows and host.is_x86_64 and host.has_usable_nvidia):
return None
driver = host.driver_cuda_version
@@ -3327,8 +3320,8 @@ def _pinned_windows_cuda_fallback(
def _augment_checksums_with_pin(
checksums: ApprovedReleaseChecksums, pin: AssetChoice
) -> ApprovedReleaseChecksums:
- """Add the pin's own verified hashes to a copy of the approved checksums so
- apply_approved_hashes keeps it on the published path (b9360 is not in the
+ """Add the pin's verified hashes to a copy of the approved checksums so
+ apply_approved_hashes keeps it on the published path (b9360 isn't in the
release manifest)."""
artifacts = dict(checksums.artifacts)
if pin.expected_sha256:
@@ -3352,7 +3345,7 @@ def _with_pinned_windows_cuda_fallback(
host: HostInfo, attempts: list[AssetChoice], checksums: ApprovedReleaseChecksums
) -> tuple[list[AssetChoice], ApprovedReleaseChecksums]:
"""Insert the Blackwell pin ahead of the Windows CUDA attempts and keep it
- through apply_approved_hashes, or return the inputs unchanged when dormant.
+ through apply_approved_hashes, or return inputs unchanged when dormant.
Gives the published install path the same GPU fallback as the simple path."""
pin = _pinned_windows_cuda_fallback(host, attempts)
if pin is None:
@@ -3369,7 +3362,7 @@ def published_windows_cuda_attempts(
selection_log = list(release.selection_log) + list(selection_preamble)
# Seed the runtime-line ordering from the real published windows-cuda minors
# (their names encode the minor), so a future CUDA major published here is
- # ordered too instead of a hardcoded cuda12/cuda13 pair. Keys mirror the
+ # ordered too rather than a hardcoded cuda12/cuda13 pair. Keys mirror the
# upstream naming so windows_cuda_attempts can match them; fall back to the
# long-standing default when the release lists no windows-cuda asset.
published_minors: list[str] = []
@@ -3414,8 +3407,8 @@ def published_windows_cuda_attempts(
if not asset_url:
continue
am = re.search(r"-bin-win-cuda-(\d+)\.(\d+)-x64\.zip$", artifact.asset_name)
- # Gate the real published minor against the driver, so a published
- # windows-cuda artifact can never bypass the driver-version gate.
+ # Gate the published minor against the driver so it can never
+ # bypass the driver-version gate.
if (
am is not None
and host.driver_cuda_version is not None
@@ -3516,9 +3509,9 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
"""Return (major, minor) of the installed ROCm runtime, or None.
Best-effort read from /opt/rocm/.info/version, amd-smi version, and
- hipconfig --version. Used to pick a compatible upstream llama.cpp
- ROCm prebuilt rather than always taking the numerically newest one
- (which can be newer than the host runtime).
+ hipconfig --version. Used to pick a compatible upstream llama.cpp ROCm
+ prebuilt rather than the numerically newest one (which can be newer than
+ the host runtime).
"""
rocm_root = os.environ.get("ROCM_PATH") or "/opt/rocm"
for path in (
@@ -3528,9 +3521,9 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
try:
with open(path) as fh:
parts = fh.read().strip().split("-")[0].split(".")
- # Explicit length guard avoids relying on the broad except
- # below to swallow IndexError when the version file contains
- # a single component (e.g. "6\n" on a partial install).
+ # Explicit length guard so we don't rely on the broad except
+ # below to swallow IndexError when the version file has a single
+ # component (e.g. "6\n" on a partial install).
if len(parts) >= 2:
return int(parts[0]), int(parts[1])
except Exception:
@@ -3571,8 +3564,8 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
# Distro package-manager fallbacks. Mirrors install.sh::get_torch_index_url
# and _detect_rocm_version() in install_python_stack.py so package-managed
- # ROCm hosts without /opt/rocm/.info/version still report a usable version
- # and the <= host version filter in resolve_upstream_asset_choice picks
+ # ROCm hosts without /opt/rocm/.info/version still report a usable version,
+ # letting the <= host version filter in resolve_upstream_asset_choice pick
# the correct upstream prebuilt instead of the newest-regardless fallback.
for _cmd in (
["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
@@ -3594,7 +3587,7 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
if _result.returncode != 0 or not _result.stdout.strip():
continue
_raw = _result.stdout.strip()
- # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
+ # dpkg can prepend an epoch ("1:6.3.0-1"); strip it first.
_raw = re.sub(r"^\d+:", "", _raw)
_m = re.match(r"(\d+)[.-](\d+)", _raw)
if _m:
@@ -3603,7 +3596,7 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
# Map detected gfx IDs to lemonade-sdk asset family suffixes.
-# More-specific prefixes must come before shorter ones (e.g. gfx1151 before gfx110).
+# More-specific prefixes must precede shorter ones (e.g. gfx1151 before gfx110).
_LEMONADE_GFX_FAMILIES: list[tuple[str, str]] = [
("gfx1151", "gfx1151"),
("gfx1150", "gfx1150"),
@@ -3627,9 +3620,8 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
Accepts:
https://github.com/{expected_repo}/releases/download/...
https://objects.githubusercontent.com/... (GitHub's release CDN)
- Anything else (including http://, raw.githubusercontent.com, gist, etc.)
- is rejected so a malicious API response cannot redirect downloads to an
- attacker-chosen host.
+ Anything else (http://, raw.githubusercontent.com, gist, etc.) is rejected
+ so a malicious API response can't redirect downloads to an attacker host.
"""
if not isinstance(url, str) or not url:
return False
@@ -3642,8 +3634,8 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
host = (parsed.netloc or "").lower()
if host == "objects.githubusercontent.com":
# GitHub's release CDN. Restrict to release-asset paths so a tampered
- # API response pointing at an arbitrary CDN object is still rejected.
- # Real release asset URLs carry the "/github-production-release-asset-"
+ # API response pointing at an arbitrary CDN object is rejected. Real
+ # release asset URLs carry the "/github-production-release-asset-"
# prefix; gist / raw / avatar CDN paths do not.
return parsed.path.startswith("/github-production-release-asset-")
if host == "github.com":
@@ -3655,12 +3647,12 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
def _fetch_lemonade_release_cached(api_url: str, llama_tag: str) -> "dict | None":
"""Cached wrapper around fetch_json for lemonade release lookups.
- resolve_lemonade_rocm_choice() is called twice per install (once from the
- direct planner, once from resolve_upstream_asset_choice) with identical
- arguments. Without memoisation, each install hits api.github.com twice,
- doubling the rate-limit failure surface on busy CI runners. Cache is
- process-scoped; tests that need to vary fetch_json's return value across
- invocations should call cache_clear().
+ resolve_lemonade_rocm_choice() is called twice per install (direct planner
+ + resolve_upstream_asset_choice) with identical arguments. Without
+ memoisation each install hits api.github.com twice, doubling the
+ rate-limit failure surface on busy CI runners. Cache is process-scoped;
+ tests that vary fetch_json's return value across calls should call
+ cache_clear().
"""
try:
return fetch_json(api_url)
@@ -3686,23 +3678,21 @@ def resolve_lemonade_rocm_choice(
os_prefix: lemonade's asset filename label, NOT a host-distro filter.
Pass "ubuntu" for any Linux host (Arch, Fedora, openSUSE,
- Debian, ...) -- lemonade only publishes one Linux variant
- and it is a manylinux-style glibc build that runs on any
- distro with a recent-enough glibc. Pass "windows" for
- Windows hosts.
+ Debian, ...) -- lemonade publishes one Linux variant, a
+ manylinux-style glibc build that runs on any distro with a
+ recent-enough glibc. Pass "windows" for Windows hosts.
install_kind: "linux-rocm" or "windows-hip"
llama_tag: the requested upstream llama.cpp tag ("latest" or a pinned
- release like "b1260"). When pinned, the resolver fetches
- the matching lemonade release. When the pinned tag is not
- published by lemonade we skip silently (and the caller
- falls through to upstream) rather than drift to whatever
- lemonade ships as latest.
+ release like "b1260"). When pinned, fetch the matching
+ lemonade release; if lemonade hasn't published that tag, skip
+ silently (caller falls through to upstream) rather than drift
+ to whatever lemonade ships as latest.
"""
if not host.rocm_gfx_target:
return None
# Opt-out for users who want the upstream HIP build path only -- lemonade
- # binaries are downloaded without entries in the approved-hash manifest, so
- # the integrity gate is functional validation only.
+ # binaries lack approved-hash manifest entries, so their integrity gate is
+ # functional validation only.
if os.environ.get("UNSLOTH_DISABLE_LEMONADE_ROCM", "").strip().lower() in (
"1",
"true",
@@ -3735,7 +3725,7 @@ def resolve_lemonade_rocm_choice(
return None
asset_url = assets[asset_name]
if not asset_url:
- # release_asset_map defaults to "" when an asset row is missing
+ # release_asset_map defaults to "" when an asset row lacks
# browser_download_url; skip cleanly instead of letting
# download_file("") raise a less obvious error downstream.
log(
@@ -3744,9 +3734,9 @@ def resolve_lemonade_rocm_choice(
)
return None
# Defence in depth: lemonade browser_download_url should be on github.com
- # or githubusercontent.com. A compromised GitHub API response that
- # redirects to an attacker-chosen host would otherwise be honoured
- # silently (lemonade assets are not in the approved-hash manifest).
+ # or githubusercontent.com. A compromised GitHub API response redirecting
+ # to an attacker host would otherwise be honoured silently (lemonade
+ # assets are not in the approved-hash manifest).
if not _is_trusted_github_release_url(asset_url, LEMONADE_ROCM_REPO):
log(
f"{LEMONADE_ROCM_REPO}@{release_tag} asset {asset_name!r} points "
@@ -3754,9 +3744,9 @@ def resolve_lemonade_rocm_choice(
"lemonade prebuilt"
)
return None
- # Note: lemonade tags Linux assets with "ubuntu" but the binary is a
- # generic glibc build that runs on any distro (Arch, Fedora, ...), so
- # this attempt is selected for all Linux ROCm hosts, not just Ubuntu.
+ # Note: lemonade tags Linux assets "ubuntu" but the binary is a generic
+ # glibc build that runs on any distro (Arch, Fedora, ...), so this attempt
+ # is selected for all Linux ROCm hosts, not just Ubuntu.
log(
f"AMD GPU {host.rocm_gfx_target!r} ({gfx_family}) -- "
f"trying lemonade-sdk ROCm prebuilt {asset_name} "
@@ -3782,28 +3772,27 @@ def resolve_lemonade_rocm_choice(
def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice:
upstream_assets = github_release_assets(UPSTREAM_REPO, llama_tag)
if host.is_linux and host.is_x86_64:
- # AMD ROCm: try upstream ROCm prebuilt first, then fall back to source build.
- # Source build (via setup.sh) compiles with -DGGML_HIP=ON and auto-detects
- # the exact GPU target via rocminfo, which is more reliable for consumer
- # GPUs (e.g. gfx1151) that may not be in the prebuilt.
+ # AMD ROCm: try upstream ROCm prebuilt first, then a source build. The
+ # source build (via setup.sh) compiles with -DGGML_HIP=ON and
+ # auto-detects the exact GPU target via rocminfo, more reliable for
+ # consumer GPUs (e.g. gfx1151) that may not be in the prebuilt.
if host.has_rocm and not host.has_usable_nvidia:
- # Try lemonade-sdk per-GPU prebuilt first: these are built against
- # specific gfx targets and bundle all required ROCm runtime libs.
+ # Try lemonade-sdk per-GPU prebuilt first: built against specific
+ # gfx targets and bundle all required ROCm runtime libs.
lemonade_choice = resolve_lemonade_rocm_choice(
host, "ubuntu", "linux-rocm", llama_tag = llama_tag
)
if lemonade_choice is not None:
return lemonade_choice
- # Fall back to upstream combined ROCm tarball.
- # Scan upstream assets for any rocm-<version> prebuilt. When the
- # host ROCm runtime version is known, pick the newest candidate
- # whose major.minor is <= host version -- otherwise a ROCm 6.4
- # host would download the rocm-7.2 tarball, fail preflight, and
- # fall back to a source build even though a compatible 6.4
- # prebuilt exists. If no compatible candidate matches (e.g. host
- # runtime is older than every published prebuilt), fall back to
- # the numerically newest so we at least try something.
+ # Fall back to the upstream combined ROCm tarball. Scan for any
+ # rocm-<version> prebuilt; when the host ROCm version is known,
+ # pick the newest candidate whose major.minor is <= host version
+ # -- otherwise a ROCm 6.4 host downloads the rocm-7.2 tarball,
+ # fails preflight, and source-builds even though a 6.4 prebuilt
+ # exists. If none is compatible (host older than every published
+ # prebuilt), fall back to the numerically newest so we try
+ # something.
_rocm_pattern = re.compile(
rf"llama-{re.escape(llama_tag)}-bin-ubuntu-rocm-([0-9]+(?:\.[0-9]+)*)-x64\.tar\.gz"
)
@@ -3822,10 +3811,10 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
item for item in rocm_candidates if item[0][:2] <= _host_rocm_version
]
if rocm_candidates and not _compatible:
- # Fall back to the newest candidate so a source build is
- # not forced when the host runtime is older than every
- # published prebuilt: preflight will still catch a true
- # incompatibility and trigger a fallback.
+ # Fall back to the newest candidate so we don't force a source
+ # build when the host runtime is older than every published
+ # prebuilt: preflight still catches a true incompatibility and
+ # triggers a fallback.
_compatible = rocm_candidates[:1]
if _compatible:
rocm_name = _compatible[0][1]
@@ -3848,7 +3837,7 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
source_label = "upstream",
install_kind = "linux-rocm",
)
- # No ROCm prebuilt available -- fall back to source build
+ # No ROCm prebuilt available -- fall back to a source build
raise PrebuiltFallback(
"AMD ROCm detected but no upstream ROCm prebuilt found; "
"falling back to source build with HIP support"
@@ -3978,12 +3967,11 @@ def resolve_release_asset_choice(
published_choice: AssetChoice | None = None
if host.is_windows and host.is_x86_64:
- # AMD Windows hosts should prefer a hash-approved published
- # Windows HIP bundle when one exists, but otherwise fall through
- # to resolve_asset_choice() so the upstream HIP prebuilt is
- # tried before the CPU fallback. Hard-pinning the published
- # windows-cpu bundle here would make the new HIP path
- # unreachable.
+ # AMD Windows hosts prefer a hash-approved published Windows HIP
+ # bundle when one exists, otherwise fall through to
+ # resolve_asset_choice() so the upstream HIP prebuilt is tried before
+ # the CPU fallback. Hard-pinning the published windows-cpu bundle here
+ # would make the HIP path unreachable.
if host.has_rocm:
published_choice = published_asset_choice_for_kind(release, "windows-hip")
else:
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 5ff8e8572bc..0cff45daefa 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -5,9 +5,8 @@
"""Cross-platform Python dependency installer for Unsloth Studio.
-Called by both setup.sh (Linux / WSL) and setup.ps1 (Windows) after the
-virtual environment is already activated. Expects `pip` and `python` on
-PATH to point at the venv.
+Called by setup.sh (Linux/WSL) and setup.ps1 (Windows) after the venv is
+activated. Expects `pip` and `python` on PATH to point at the venv.
"""
from __future__ import annotations
@@ -42,11 +41,10 @@ IS_MAC_INTEL = IS_MACOS and platform.machine() == "x86_64"
IS_MAC_ARM = IS_MACOS and platform.machine() == "arm64"
IS_LINUX = sys.platform.startswith("linux")
# torchcodec ships wheels only for manylinux_2_28_x86_64,
-# macosx_12_0_arm64, and win_amd64 (visible in the 0.10.0 PyPI page).
-# Trying to install it on any other host fails the whole
-# extras-no-deps step. `unsloth studio update` does not have a
-# --no-torch flag, so on these hosts the audio extras must be
-# filtered out independent of the NO_TORCH env var.
+# macosx_12_0_arm64, and win_amd64 (per the 0.10.0 PyPI page). Installing
+# on any other host fails the whole extras-no-deps step. `unsloth studio
+# update` has no --no-torch flag, so on these hosts the audio extras must
+# be filtered out regardless of the NO_TORCH env var.
PLATFORM_LACKS_TORCHCODEC_WHEEL = (
(IS_LINUX and platform.machine() in {"aarch64", "arm64"})
or (IS_WINDOWS and platform.machine().lower() in {"arm64", "aarch64"})
@@ -54,8 +52,8 @@ PLATFORM_LACKS_TORCHCODEC_WHEEL = (
)
# ── ROCm / AMD GPU support ─────────────────────────────────────────────────────
-# Mapping from detected ROCm (major, minor) to the best PyTorch wheel tag on
-# download.pytorch.org. Entries are checked newest-first (>=).
+# Detected ROCm (major, minor) -> best PyTorch wheel tag on
+# download.pytorch.org. Checked newest-first (>=).
_ROCM_TORCH_INDEX: dict[tuple[int, int], str] = {
(7, 2): "rocm7.2", # torch 2.11.0
(7, 1): "rocm7.1", # torch 2.10.0
@@ -85,15 +83,15 @@ _PYTORCH_WHL_BASE = (
os.environ.get("UNSLOTH_PYTORCH_MIRROR") or "https://download.pytorch.org/whl"
).rstrip("/")
-# AMD Windows ROCm wheels — repo.amd.com (arch-specific pip index)
+# AMD Windows ROCm wheels — repo.amd.com (arch-specific pip index).
# Format: https://repo.amd.com/rocm/whl/{arch_family}/
-# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped / mirror installs.
+# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped/mirror installs.
_ROCM_WINDOWS_INDEX_BASE = (
os.environ.get("UNSLOTH_ROCM_WINDOWS_MIRROR") or "https://repo.amd.com/rocm/whl"
).rstrip("/")
-# Maps gfx arch → AMD index arch-family suffix.
-# Each family is a separate pip index on repo.amd.com.
+# gfx arch → AMD index arch-family suffix; each family is a separate
+# pip index on repo.amd.com.
_GFX_TO_AMD_INDEX_ARCH: dict[str, str] = {
"gfx1201": "gfx120X-all",
"gfx1200": "gfx120X-all", # RDNA 4
@@ -122,9 +120,9 @@ _BNB_ROCM_PRERELEASE_URLS: dict[str, str] = {
"bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_aarch64.whl"
),
# Windows ROCm wheel — ships libbitsandbytes_rocm{VER}.dll.
- # BNB auto-detects HIP version from torch.version.hip, which does not always
- # match the DLL suffix in this prerelease wheel (e.g. torch 7.13 with a rocm72
- # DLL). We scan the installed wheel for the actual DLL name and set
+ # BNB auto-detects HIP version from torch.version.hip, which may not match
+ # the DLL suffix in this prerelease wheel (e.g. torch 7.13 with a rocm72
+ # DLL). We scan the installed wheel for the real DLL name and set
# BNB_ROCM_VERSION accordingly in _install_bnb_windows_rocm() and worker.py.
"win_amd64": (
"https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
@@ -136,8 +134,8 @@ _BNB_ROCM_PYPI_FALLBACK = "bitsandbytes>=0.49.1"
def _bnb_rocm_prerelease_url() -> str | None:
- """Return the continuous-release_main bnb wheel URL for the current
- architecture, or None when no pre-release wheel is available.
+ """Return the continuous-release_main bnb wheel URL for the current arch,
+ or None when no pre-release wheel is available.
"""
arch = platform.machine().lower()
arch = {"amd64": "x86_64", "arm64": "aarch64"}.get(arch, arch)
@@ -155,9 +153,9 @@ def _detect_rocm_version() -> tuple[int, int] | None:
try:
with open(path) as fh:
parts = fh.read().strip().split("-")[0].split(".")
- # Explicit length guard avoids relying on the broad except
- # below to swallow IndexError when the version file contains
- # a single component (e.g. "6\n" on a partial install).
+ # Explicit length guard so we don't rely on the broad except
+ # below to swallow IndexError when the version file has a
+ # single component (e.g. "6\n" on a partial install).
if len(parts) >= 2:
return int(parts[0]), int(parts[1])
except Exception:
@@ -201,11 +199,10 @@ def _detect_rocm_version() -> tuple[int, int] | None:
pass
# Distro package-manager fallbacks. Package-managed ROCm installs can
- # expose GPUs via rocminfo / amd-smi but still lack /opt/rocm/.info/version
- # and hipconfig, so probe dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE)
- # for the rocm-core package version. Matches the chain in
- # install.sh::get_torch_index_url so `unsloth studio update` behaves
- # the same as a fresh `curl | sh` install.
+ # expose GPUs via rocminfo/amd-smi but lack /opt/rocm/.info/version and
+ # hipconfig, so probe dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE)
+ # for the rocm-core version. Matches install.sh::get_torch_index_url so
+ # `unsloth studio update` behaves like a fresh `curl | sh` install.
for cmd in (
["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
@@ -236,9 +233,9 @@ def _detect_rocm_version() -> tuple[int, int] | None:
def _pick_visible_index(num_tokens: int) -> int:
- """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an integer
- index into a list of length num_tokens. Returns 0 (first GPU) for
- unset, empty, '-1', UUID-style, or out-of-range values."""
+ """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an index into a
+ list of length num_tokens. Returns 0 (first GPU) for unset, empty, '-1',
+ UUID-style, or out-of-range values."""
for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
_val = os.environ.get(_env)
if _val is None:
@@ -260,14 +257,14 @@ def _pick_visible_index(num_tokens: int) -> int:
def _detect_windows_gfx_arch() -> str | None:
"""Return the gcnArchName on Windows (e.g. 'gfx1200'), or None.
- Probe order matches the PowerShell installer: env-var override first,
- then hipinfo (PATH or HIP_PATH / ROCM_PATH bin), then amd-smi. Without
- the amd-smi fallback, runtime-only AMD installs without hipinfo on PATH
+ Probe order matches the PowerShell installer: env-var override, then
+ hipinfo (PATH or HIP_PATH/ROCM_PATH bin), then amd-smi. Without the
+ amd-smi fallback, runtime-only AMD installs lacking hipinfo on PATH
return early and `studio update` cannot repair a CPU-only venv.
- On multi-GPU hosts, all detected gfx tokens are deduplicated (preserving
- enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES selects
- which one to install for. The first GPU is used when no env var is set.
+ On multi-GPU hosts, detected gfx tokens are deduplicated (preserving
+ enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES picks
+ which to install for. The first GPU is used when no env var is set.
"""
# 1. Explicit override (matches PowerShell installer's env-var path).
_override = os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
@@ -277,8 +274,8 @@ def _detect_windows_gfx_arch() -> str | None:
def _dedup_pick(tokens: list[str]) -> "str | None":
if not tokens:
return None
- # Index into the full (ordered) list first so HIP_VISIBLE_DEVICES
- # correctly addresses GPU N on mixed-arch hosts, then return that arch.
+ # Index into the full ordered list so HIP_VISIBLE_DEVICES addresses
+ # GPU N on mixed-arch hosts, then return that arch.
return tokens[_pick_visible_index(len(tokens))]
# 2. hipinfo via PATH, then HIP_PATH\bin / ROCM_PATH\bin.
@@ -301,8 +298,8 @@ def _detect_windows_gfx_arch() -> str | None:
)
if result.returncode == 0:
text = result.stdout.decode(errors = "replace")
- # findall picks every gcnArchName line so multi-GPU hosts
- # are enumerable and HIP_VISIBLE_DEVICES selects correctly.
+ # findall gets every gcnArchName line so multi-GPU hosts are
+ # enumerable and HIP_VISIBLE_DEVICES selects correctly.
_tokens = [
t.strip().lower() for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
]
@@ -353,10 +350,10 @@ def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:
def _detect_bnb_rocm_dll_ver() -> str | None:
"""Scan the installed bitsandbytes package for libbitsandbytes_rocm{VER}.dll.
- Returns the version suffix string (e.g. ``"72"``, ``"713"``) or ``None``
- if bitsandbytes is not installed or no ROCm DLL is found. Does NOT import
- bitsandbytes — uses importlib.util.find_spec so it is safe to call before
- BNB is imported.
+ Returns the version suffix (e.g. ``"72"``, ``"713"``) or ``None`` if
+ bitsandbytes is not installed or no ROCm DLL is found. Does NOT import
+ bitsandbytes — uses importlib.util.find_spec, so it is safe to call
+ before BNB is imported.
"""
import importlib.util
@@ -369,9 +366,9 @@ def _detect_bnb_rocm_dll_ver() -> str | None:
m = re.search(r"libbitsandbytes_rocm(\d+)\.dll", os.path.basename(dll))
if m:
all_vers.append(m.group(1))
- # Pick the highest numeric suffix so that e.g. "713" wins over "72" when
- # both variants are present in the wheel. Filesystem glob order is not
- # guaranteed, so always sort rather than stopping at the first match.
+ # Pick the highest numeric suffix so e.g. "713" wins over "72" when both
+ # variants are present. Glob order is not guaranteed, so always sort
+ # rather than stopping at the first match.
return max(all_vers, key = lambda v: int(v)) if all_vers else None
@@ -380,8 +377,8 @@ def _has_rocm_gpu() -> bool:
for cmd, check_fn in (
# rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
# gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
- # "gfx11-generic" or "gfx9-4-generic" which only have 1-2 digits before
- # the dash and must not be treated as a real GPU.
+ # "gfx11-generic"/"gfx9-4-generic" with only 1-2 digits before the dash,
+ # which must not be treated as a real GPU.
(
["rocminfo"],
lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
@@ -410,9 +407,8 @@ def _has_rocm_gpu() -> bool:
return True
# sysfs KFD topology fallback (Linux only) -- matches install.sh's
# runtime-only detection. On minimal package-managed installs (no
- # rocminfo / no amd-smi GUI tools), the kernel exposes AMD GPUs via
- # /sys/class/kfd so `studio update` can still detect the GPU and
- # repair the venv.
+ # rocminfo / no amd-smi tools), the kernel exposes AMD GPUs via
+ # /sys/class/kfd so `studio update` can still detect and repair.
if sys.platform != "win32":
try:
kfd_nodes = "/sys/class/kfd/kfd/topology/nodes"
@@ -450,12 +446,11 @@ def _has_usable_nvidia_gpu() -> bool:
def _detect_amd_gfx_codes() -> list[str]:
- """Return the list of AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
+ """Return the AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
- Probes rocminfo first, then falls back to ``amd-smi list`` and
- ``amd-smi static --asic`` for runtime-only Radeon hosts that ship
- amd-smi but no rocminfo. Returns an empty list when no probe yields
- a gfx target.
+ Probes rocminfo, then falls back to ``amd-smi list`` and ``amd-smi
+ static --asic`` for runtime-only Radeon hosts that ship amd-smi but no
+ rocminfo. Returns an empty list when no probe yields a gfx target.
"""
def _extract(text: str) -> list[str]:
@@ -495,13 +490,13 @@ def _install_bnb_windows_rocm() -> bool:
"""Install the AMD Windows BNB prerelease wheel. Returns True on success.
The continuous-release wheel is intentionally mismatched: the filename
- encodes version 1.33.7.preview (parsed as 1.33.7rc0 by PEP 440) while the
- wheel metadata reports 0.50.0.dev0. uv rejects this filename/metadata
- mismatch -- and bypassing it with UV_SKIP_WHEEL_FILENAME_CHECK still leaves
- uv mangling the bitsandbytes install. Per the AMD install guide
+ encodes 1.33.7.preview (parsed as 1.33.7rc0 by PEP 440) while the wheel
+ metadata reports 0.50.0.dev0. uv rejects this filename/metadata mismatch,
+ and bypassing it with UV_SKIP_WHEEL_FILENAME_CHECK still leaves uv mangling
+ the bitsandbytes install. Per the AMD install guide
(https://unsloth.ai/docs/get-started/install/amd/amd-hackathon) the wheel
- must be installed with plain pip, not uv, so we force pip here
- (force_pip=True). plain pip performs no wheel filename/metadata check.
+ must be installed with plain pip, not uv, so we force pip (force_pip=True);
+ plain pip performs no wheel filename/metadata check.
"""
_bnb_win_url = _BNB_ROCM_PRERELEASE_URLS.get("win_amd64")
if _bnb_win_url is None:
@@ -517,13 +512,12 @@ def _install_bnb_windows_rocm() -> bool:
)
if not _ok:
return False
- # After install: detect the actual ROCm DLL suffix shipped in the wheel and
- # set BNB_ROCM_VERSION so bitsandbytes loads the correct DLL regardless of
- # what torch.version.hip reports. The wheel may ship an older suffix (e.g.
- # "72") while torch reports a newer HIP version (e.g. 7.13); the env var
- # override ensures bitsandbytes does not fail looking for a non-existent DLL.
- # The worker subprocess inherits this env var automatically.
- # Fall back to "72" if detection fails (e.g. install was a no-op / dry-run).
+ # After install: detect the actual ROCm DLL suffix in the wheel and set
+ # BNB_ROCM_VERSION so bitsandbytes loads the correct DLL regardless of what
+ # torch.version.hip reports. The wheel may ship an older suffix (e.g. "72")
+ # while torch reports a newer HIP version (e.g. 7.13); the override stops
+ # bitsandbytes from failing on a non-existent DLL. The worker subprocess
+ # inherits this env var. Fall back to "72" if detection fails (no-op/dry-run).
if "BNB_ROCM_VERSION" not in os.environ:
_ver = _detect_bnb_rocm_dll_ver() or "72"
os.environ["BNB_ROCM_VERSION"] = _ver
@@ -540,9 +534,9 @@ def _ensure_rocm_torch() -> None:
Uses pip_install() to respect uv, constraints, and --python targeting.
"""
global _rocm_windows_torch_installed
- # setup.ps1 sets this when it already installed AMD wheels; skip the probe
- # only when torch is actually importable as ROCm. If the venv was wiped
- # between runs, the stale env-var would suppress a needed reinstall.
+ # setup.ps1 sets this after installing AMD wheels; skip the probe only when
+ # torch is actually importable as ROCm. If the venv was wiped between runs,
+ # the stale env-var would suppress a needed reinstall.
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
_torch_ok = False
try:
@@ -566,9 +560,9 @@ def _ensure_rocm_torch() -> None:
pass
if _torch_ok:
_rocm_windows_torch_installed = True
- # setup.ps1 already installed ROCm torch, but we still need to install
- # the AMD Windows BNB wheel here -- the PyPI bitsandbytes wheel ships
- # only CUDA DLLs and will fail to load on ROCm.
+ # setup.ps1 already installed ROCm torch, but we still need the AMD
+ # Windows BNB wheel here -- the PyPI bitsandbytes wheel ships only
+ # CUDA DLLs and fails to load on ROCm.
_install_bnb_windows_rocm()
return
# torch was wiped between runs; fall through to the full install path
@@ -619,14 +613,14 @@ def _ensure_rocm_torch() -> None:
"torchaudio",
constrain = False,
)
- # ROCm torch is installed (or already was); flag it so later install
- # phases do not overwrite it with the generic CPU torch wheel. BNB is
- # a separate dependency -- a BNB install failure must NOT roll the
- # torch ROCm install back.
+ # ROCm torch is installed (or already was); flag it so later phases
+ # do not overwrite it with the generic CPU torch wheel. BNB is a
+ # separate dependency -- a BNB install failure must NOT roll back the
+ # torch ROCm install.
_rocm_windows_torch_installed = True
# Always install AMD Windows bitsandbytes -- the PyPI wheel ships only
- # CUDA DLLs and will fail to load on ROCm. Install even when torch was
- # already a ROCm build so that `studio update` repairs a broken bnb.
+ # CUDA DLLs and fails on ROCm. Install even when torch was already a
+ # ROCm build so `studio update` repairs a broken bnb.
if not _install_bnb_windows_rocm():
print(
" Warning: AMD Windows bitsandbytes install failed; "
@@ -637,16 +631,15 @@ def _ensure_rocm_torch() -> None:
# ── Linux x86_64 only: PyTorch ROCm wheels are not published for aarch64 ──
if platform.machine().lower() not in {"x86_64", "amd64"}:
return
- # NVIDIA takes precedence on mixed hosts -- but only if an actual GPU is usable
+ # NVIDIA takes precedence on mixed hosts -- but only if a GPU is usable
if _has_usable_nvidia_gpu():
return
- # Rely on _has_rocm_gpu() (rocminfo / amd-smi GPU data rows) as the
- # authoritative "is this actually an AMD ROCm host?" signal. The old
- # gate required /opt/rocm or hipcc to exist, which breaks on
- # runtime-only ROCm installs (package-managed minimal installs,
- # Radeon software) that ship amd-smi/rocminfo without /opt/rocm or
- # hipcc, and leaves `unsloth studio update` unable to repair a
- # CPU-only venv on those systems.
+ # Use _has_rocm_gpu() (rocminfo / amd-smi GPU data rows) as the
+ # authoritative "is this an AMD ROCm host?" signal. The old gate required
+ # /opt/rocm or hipcc to exist, which breaks runtime-only ROCm installs
+ # (minimal package-managed installs, Radeon software) that ship
+ # amd-smi/rocminfo without /opt/rocm or hipcc, leaving `unsloth studio
+ # update` unable to repair a CPU-only venv on those systems.
if not _has_rocm_gpu():
return # no AMD GPU visible
@@ -655,9 +648,9 @@ def _ensure_rocm_torch() -> None:
print(" ROCm detected but version unreadable -- skipping torch reinstall")
return
- # Probe whether torch already links against HIP (ROCm is already working).
- # Do NOT skip for CUDA-only builds since they are unusable on AMD-only
- # hosts (the NVIDIA check above already handled mixed AMD+NVIDIA setups).
+ # Probe whether torch already links against HIP (ROCm already working).
+ # Do NOT skip for CUDA-only builds: they are unusable on AMD-only hosts
+ # (the NVIDIA check above already handled mixed AMD+NVIDIA setups).
try:
probe = subprocess.run(
[
@@ -667,7 +660,7 @@ def _ensure_rocm_torch() -> None:
"import torch; "
"hip=getattr(torch.version,'hip','') or ''; "
"ver=getattr(torch,'__version__','').lower(); "
- # Print the HIP version when present (back-compat), else
+ # Print the HIP version when present (back-compat), else a
# "rocm" sentinel when only torch.__version__ flags ROCm
# (AMD SDK / Radeon wheels). Empty string = CPU/CUDA.
"print(hip if hip else ('rocm' if 'rocm' in ver else ''))"
@@ -689,10 +682,9 @@ def _ensure_rocm_torch() -> None:
# in torch._grouped_mm. AMD's per-gfx repo ships torch 2.11.0+rocm7.13.0
# with the real fix, so route those hosts there instead of the generic
# pytorch.org rocm7.1 wheel. Mirrors install.sh's Strix override.
- # On mixed hosts (Strix iGPU + non-Strix dGPU), only route to the AMD
- # per-gfx index when the GPU HIP will actually run on is the Strix one --
- # otherwise the dGPU would get an incompatible wheel. Use HIP_VISIBLE_DEVICES
- # to determine the runtime target.
+ # On mixed hosts (Strix iGPU + non-Strix dGPU), route to the AMD per-gfx
+ # index only when HIP's runtime GPU is the Strix one -- else the dGPU gets
+ # an incompatible wheel. Use HIP_VISIBLE_DEVICES for the runtime target.
_strix_override_url: "str | None" = None
_strix_override_pkgs: "tuple[str, str, str] | None" = None
if ver < (7, 2):
@@ -700,10 +692,9 @@ def _ensure_rocm_torch() -> None:
_strix_gfx = {"gfx1151", "gfx1150"}
_detected_strix = _strix_gfx.intersection(gfx_codes)
if _detected_strix:
- # Pick the runtime-visible GPU. If HIP_VISIBLE_DEVICES selects a
- # specific index into gfx_codes, use that gfx; else default to the
- # first listed GPU. Skip the override unless the resolved GPU is
- # Strix.
+ # Pick the runtime-visible GPU: use the HIP_VISIBLE_DEVICES index
+ # into gfx_codes, else default to the first GPU. Skip the override
+ # unless the resolved GPU is Strix.
_runtime_gfx = gfx_codes[_pick_visible_index(len(gfx_codes))] if gfx_codes else None
if _runtime_gfx in _strix_gfx:
_selected_gfx = _runtime_gfx
@@ -715,10 +706,10 @@ def _ensure_rocm_torch() -> None:
"torch>=2.11.0,<2.12.0",
# Pin torchvision/torchaudio to the 2.11.x-compatible range.
# The install uses --index-url (exclusive, no PyPI fallback),
- # so bare unversioned names risk resolving a build from AMD's
- # index that targets a different torch major (e.g. 0.27 built
- # against torch 2.12), which would fail at runtime with an
- # ABI/version mismatch. Matches _ROCM_TORCH_CONSTRAINT["rocm7.2"].
+ # so bare unversioned names risk resolving an AMD-index build
+ # targeting a different torch major (e.g. 0.27 built against
+ # torch 2.12), which fails at runtime with an ABI/version
+ # mismatch. Matches _ROCM_TORCH_CONSTRAINT["rocm7.2"].
"torchvision>=0.26.0,<0.27.0",
"torchaudio>=2.11.0,<2.12.0",
)
@@ -740,8 +731,8 @@ def _ensure_rocm_torch() -> None:
# Strix override on ROCm 7.1 must fire even when has_hip_torch is True --
# an existing torch with `torch.version.hip == "7.1"` is exactly the broken
- # combo the override is meant to repair, so skipping it leaves users on
- # the known _grouped_mm segfault.
+ # combo the override repairs, so skipping it leaves users on the known
+ # _grouped_mm segfault.
if _strix_override_url is not None and _strix_override_pkgs is not None:
index_url = _strix_override_url
_torch_pkg, _vision_pkg, _audio_pkg = _strix_override_pkgs
@@ -790,10 +781,9 @@ def _ensure_rocm_torch() -> None:
rocm_torch_ready = True
# Install bitsandbytes only when torch links against ROCm. Prefers the
- # continuous-release_main wheel (bnb PR #1887 4-bit GEMV fix) and falls
- # back to PyPI when the pre-release wheel cannot be installed. Use pip for
- # the pre-release wheel because uv rejects the wheel's filename/metadata
- # version mismatch.
+ # continuous-release_main wheel (bnb PR #1887 4-bit GEMV fix), falling back
+ # to PyPI when the pre-release wheel won't install. Use pip for the
+ # pre-release wheel because uv rejects its filename/metadata version mismatch.
if rocm_torch_ready:
_bnb_url = _bnb_rocm_prerelease_url()
_bnb_installed = False
@@ -871,10 +861,9 @@ def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
def _infer_no_torch() -> bool:
"""Determine whether to run in no-torch (GGUF-only) mode.
- Checks UNSLOTH_NO_TORCH env var first. When unset, falls back to
- platform detection so that Intel Macs automatically use GGUF-only
- mode even when invoked from ``unsloth studio update`` (which does
- not inject the env var).
+ Checks UNSLOTH_NO_TORCH first. When unset, falls back to platform
+ detection so Intel Macs use GGUF-only mode even when invoked from
+ ``unsloth studio update`` (which does not inject the env var).
"""
env = os.environ.get("UNSLOTH_NO_TORCH")
if env is not None:
@@ -886,15 +875,15 @@ NO_TORCH = _infer_no_torch()
# -- Verbosity control ----------------------------------------------------------
-# By default the installer shows a minimal progress bar (one line, in-place).
-# Set UNSLOTH_VERBOSE=1 in the environment to restore full per-step output:
+# By default the installer shows a minimal in-place one-line progress bar.
+# Set UNSLOTH_VERBOSE=1 to restore full per-step output:
# CLI: unsloth studio setup --verbose
# Linux/Mac: UNSLOTH_VERBOSE=1 ./studio/setup.sh
# Windows: $env:UNSLOTH_VERBOSE="1" ; .\studio\setup.ps1
VERBOSE: bool = os.environ.get("UNSLOTH_VERBOSE", "0") == "1"
-# Progress bar state -- updated by _progress() as each install step runs.
-# Update _TOTAL here if you add or remove install steps in install_python_stack().
+# Progress bar state -- updated by _progress() per install step.
+# Update _TOTAL if you add/remove steps in install_python_stack().
_STEP: int = 0
_TOTAL: int = 0 # set at runtime in install_python_stack() based on platform
@@ -908,16 +897,15 @@ LOCAL_DD_UNSTRUCTURED_PLUGIN = (
)
LOCAL_DD_GITHUB_PLUGIN = SCRIPT_DIR / "backend" / "plugins" / "data-designer-github-repo-seed"
-# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides file).
+# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides).
_MLX_OVERRIDES = SINGLE_ENV / "overrides-darwin-arm64.txt"
if IS_MAC_ARM and _MLX_OVERRIDES.is_file():
os.environ.setdefault("UV_OVERRIDE", str(_MLX_OVERRIDES))
# -- Unicode-safe printing ---------------------------------------------
-# On Windows the default console encoding can be a legacy code page
-# (e.g. CP1252) that cannot represent Unicode glyphs such as ✅ or ❌.
-# _safe_print() gracefully degrades to ASCII equivalents so the
-# installer never crashes just because of a status glyph.
+# On Windows the console encoding may be a legacy code page (e.g. CP1252)
+# that cannot represent glyphs like ✅ or ❌. _safe_print() degrades to ASCII
+# equivalents so the installer never crashes over a status glyph.
_UNICODE_TO_ASCII: dict[str, str] = {
"\u2705": "[OK]", # ✅
@@ -934,11 +922,11 @@ def _safe_print(*args: object, **kwargs: object) -> None:
except OSError:
return
except UnicodeEncodeError:
- # Stringify, then swap emoji for ASCII equivalents
+ # Stringify, then swap emoji for ASCII equivalents.
text = " ".join(str(a) for a in args)
for uni, ascii_alt in _UNICODE_TO_ASCII.items():
text = text.replace(uni, ascii_alt)
- # Final fallback: replace any remaining unencodable chars
+ # Final fallback: replace any remaining unencodable chars.
print(
text.encode(sys.stdout.encoding or "ascii", errors = "replace").decode(
sys.stdout.encoding or "ascii", errors = "replace"
@@ -1065,16 +1053,14 @@ def run(
WINDOWS_SKIP_PACKAGES = {"open_spiel", "triton_kernels"}
# Packages to skip when torch is unavailable (Intel Mac GGUF-only mode).
-# These packages either *are* torch extensions or have unconditional
-# ``Requires-Dist: torch`` in their published metadata, so installing
-# them would pull torch back into the environment. ``librosa`` also
-# lives in this set even though it does not itself require torch:
-# upstream ``llvmlite`` dropped its macOS x86_64 wheel between 0.42.0
-# and 0.46.0+ (see https://pypi.org/project/llvmlite/0.47.0/#files --
-# only macosx_arm64 / manylinux / win_amd64 remain), so on Intel Mac
-# the librosa -> numba -> llvmlite chain triggers a from-source build
-# that fails inside CI and on the host without LLVM 14/15 headers.
-# Tracked separately in unslothai/unsloth#5046.
+# These either *are* torch extensions or have unconditional
+# ``Requires-Dist: torch``, so installing them would pull torch back in.
+# ``librosa`` is here too despite not requiring torch: upstream ``llvmlite``
+# dropped its macOS x86_64 wheel between 0.42.0 and 0.46.0+ (see
+# https://pypi.org/project/llvmlite/0.47.0/#files -- only
+# macosx_arm64 / manylinux / win_amd64 remain), so on Intel Mac the
+# librosa -> numba -> llvmlite chain triggers a from-source build that fails
+# in CI and on hosts without LLVM 14/15 headers. Tracked in unslothai/unsloth#5046.
NO_TORCH_SKIP_PACKAGES = {
"torch-stoi",
"timm",
@@ -1238,14 +1224,14 @@ def _build_uv_cmd(args: tuple[str, ...]) -> list[str]:
cmd = ["uv", "pip", "install"]
if UV_NEEDS_SYSTEM:
cmd.append("--system")
- # Always pass --python so uv targets the correct environment.
- # Without this, uv can ignore an activated venv and install into
- # the system Python (observed on Colab and similar environments).
+ # Always pass --python so uv targets the right environment. Without it, uv
+ # can ignore an activated venv and install into the system Python (seen on
+ # Colab and similar).
cmd.extend(["--python", sys.executable])
cmd.extend(_translate_pip_args_for_uv(args))
- # Torch is pre-installed by install.sh/setup.ps1. Do not add
- # --torch-backend by default -- it can cause solver dead-ends on
- # CPU-only machines. Callers that need it can set UV_TORCH_BACKEND.
+ # Torch is pre-installed by install.sh/setup.ps1. Do not add
+ # --torch-backend by default -- it can cause solver dead-ends on CPU-only
+ # machines. Callers that need it can set UV_TORCH_BACKEND.
_tb = os.environ.get("UV_TORCH_BACKEND", "")
if _tb:
cmd.append(f"--torch-backend={_tb}")
@@ -1259,7 +1245,7 @@ def pip_install_try(
force_pip: bool = False,
) -> bool:
"""Like pip_install but returns False on failure instead of exiting.
- For optional installs with a follow-up fallback.
+ For optional installs that have a follow-up fallback.
"""
constraint_args_pip: list[str] = []
constraint_args_uv: list[str] = []
@@ -1384,14 +1370,14 @@ def install_python_stack() -> int:
global USE_UV, _STEP, _TOTAL
_STEP = 0
- # When called from install.sh (which already installed unsloth into the venv),
- # SKIP_STUDIO_BASE=1 is set to avoid redundant reinstallation of base packages.
- # When called from "unsloth studio update", it is NOT set so base packages
- # (unsloth + unsloth-zoo) are always reinstalled to pick up new versions.
+ # install.sh (which already installed unsloth) sets SKIP_STUDIO_BASE=1 to
+ # avoid reinstalling base packages. "unsloth studio update" does NOT set it,
+ # so base packages (unsloth + unsloth-zoo) are reinstalled to pick up new
+ # versions.
skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"
- # When --package is used, install a different package name (for testing)
+ # --package installs a different package name (for testing).
package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")
- # When --local is used, overlay a local repo checkout after updating deps
+ # --local overlays a local repo checkout after updating deps.
local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")
base_total = 10 if IS_WINDOWS else 11
if IS_MACOS:
@@ -1402,11 +1388,11 @@ def install_python_stack() -> int:
base_total += 2 # flash-attn (line 1620) + ROCm torch final (line 1705) -- Linux only
_TOTAL = (base_total - 1) if skip_base else base_total
- # 1. Try to use uv for faster installs (must happen before pip upgrade
- # because uv venvs don't include pip by default)
+ # 1. Try uv for faster installs (before pip upgrade -- uv venvs don't
+ # include pip by default).
USE_UV = _bootstrap_uv()
- # 2. Ensure pip is available (uv venvs created by install.sh don't include pip)
+ # 2. Ensure pip is available (uv venvs from install.sh omit pip).
_progress("pip bootstrap")
if USE_UV:
run(
@@ -1421,9 +1407,8 @@ def install_python_stack() -> int:
],
)
else:
- # pip may not exist yet (uv-created venvs omit it). Try ensurepip
- # first, then upgrade. Only fall back to a direct upgrade when pip
- # is already present.
+ # pip may not exist yet (uv-created venvs omit it). Try ensurepip,
+ # then upgrade. Direct upgrade only when pip is already present.
_has_pip = (
subprocess.run(
[sys.executable, "-m", "pip", "--version"],
@@ -1464,8 +1449,8 @@ def install_python_stack() -> int:
pass
elif NO_TORCH:
# No-torch update path: install unsloth + unsloth-zoo with --no-deps
- # (current PyPI metadata still declares torch as a hard dep), then
- # runtime deps with --no-deps (avoids transitive torch).
+ # (PyPI metadata still declares torch as a hard dep), then runtime deps
+ # with --no-deps (avoids transitive torch).
_progress("base packages (no torch)")
pip_install(
f"Updating {package_name} + unsloth-zoo (no-torch mode)",
@@ -1478,11 +1463,10 @@ def install_python_stack() -> int:
package_name,
"unsloth-zoo",
)
- # Resolve pydantic WITH deps so pip pins pydantic-core to the
- # exact version pydantic's metadata declares. Under --no-deps
- # alone pip picks the latest of each and trips pydantic's
- # _ensure_pydantic_core_version check. Transitive deps are
- # torch-free.
+ # Resolve pydantic WITH deps so pip pins pydantic-core to the exact
+ # version pydantic's metadata declares. Under --no-deps pip picks the
+ # latest of each and trips pydantic's _ensure_pydantic_core_version
+ # check. Transitive deps are torch-free.
pip_install(
"Installing pydantic (with deps for compatible core)",
"--no-cache-dir",
@@ -1514,9 +1498,8 @@ def install_python_stack() -> int:
constrain = False,
)
elif local_repo:
- # Local dev install: update deps from base.txt, then overlay the
- # local checkout as an editable install (--no-deps so torch is
- # never re-resolved).
+ # Local dev install: update deps from base.txt, then overlay the local
+ # checkout as an editable install (--no-deps so torch is not re-resolved).
_progress("base packages")
pip_install(
"Updating base packages",
@@ -1546,7 +1529,7 @@ def install_python_stack() -> int:
constrain = False,
)
elif package_name != "unsloth":
- # Custom package name (for testing), install directly
+ # Custom package name (for testing): install directly.
_progress("base packages")
pip_install(
f"Installing {package_name}",
@@ -1554,9 +1537,9 @@ def install_python_stack() -> int:
package_name,
)
else:
- # Update path: upgrade only unsloth + unsloth-zoo while preserving
- # existing torch/CUDA installations. Torch is pre-installed by
- # install.sh / setup.ps1; --upgrade-package targets only base pkgs.
+ # Update path: upgrade only unsloth + unsloth-zoo, preserving existing
+ # torch/CUDA installs. Torch is pre-installed by install.sh/setup.ps1;
+ # --upgrade-package targets only base pkgs.
_progress("base packages")
pip_install(
"Updating base packages",
@@ -1569,16 +1552,16 @@ def install_python_stack() -> int:
)
# 2b. AMD ROCm: reinstall torch with HIP wheels if the host has ROCm but the
- # venv received CPU-only torch (common when pip resolves torch from PyPI).
- # Must come immediately after base packages so torch is present for inspection.
+ # venv got CPU-only torch (common when pip resolves torch from PyPI).
+ # Must follow base packages so torch is present for inspection.
if not IS_MACOS and not NO_TORCH:
_progress("ROCm torch check")
_ensure_rocm_torch()
- # Windows + AMD GPU: if ROCm torch was not installed (wrong Python version
- # or unknown ROCm version), warn the user.
+ # Windows + AMD GPU: warn if ROCm torch was not installed (wrong Python
+ # version or unknown ROCm version).
if IS_WINDOWS and not NO_TORCH and not _has_usable_nvidia_gpu():
- # Validate actual AMD GPU presence (not just tool existence)
+ # Validate actual AMD GPU presence (not just tool existence).
import re as _re_win
def _win_amd_smi_has_gpu(stdout: str) -> bool:
@@ -1632,9 +1615,9 @@ def install_python_stack() -> int:
req = REQ_ROOT / "extras-no-deps.txt",
)
- # 4. Overrides (torchao, transformers) -- force-reinstall
- # Skip entirely when torch is unavailable (e.g. Intel Mac GGUF-only mode)
- # because overrides.txt contains torchao which requires torch.
+ # 4. Overrides (torchao, transformers) -- force-reinstall.
+ # Skip when torch is unavailable (e.g. Intel Mac GGUF-only mode):
+ # overrides.txt contains torchao, which requires torch.
if NO_TORCH:
_progress("dependency overrides (skipped, no torch)")
else:
@@ -1642,8 +1625,8 @@ def install_python_stack() -> int:
_override_extra_args: tuple[str, ...] = ()
if _rocm_windows_torch_installed:
# torchao in overrides.txt declares torch as a dependency; without
- # --no-deps uv would resolve and install CPU torch from PyPI,
- # overwriting the AMD ROCm wheels we just installed.
+ # --no-deps uv would install CPU torch from PyPI, overwriting the
+ # AMD ROCm wheels we just installed.
_override_extra_args = ("--no-deps",)
pip_install(
"Installing dependency overrides",
@@ -1653,8 +1636,8 @@ def install_python_stack() -> int:
req = REQ_ROOT / "overrides.txt",
)
- # 5. Triton kernels (no-deps, from source)
- # Skip on Windows (no support) and macOS (no support).
+ # 5. Triton kernels (no-deps, from source). Skip on Windows and macOS
+ # (no support).
if not IS_WINDOWS and not IS_MACOS:
_progress("triton kernels")
pip_install(
@@ -1745,11 +1728,10 @@ def install_python_stack() -> int:
[sys.executable, str(SINGLE_ENV / "patch_metadata.py")],
)
- # 13. AMD ROCm: final torch repair. Multiple install steps above can
- # pull in CUDA torch from PyPI (base packages, extras, overrides,
- # studio deps, etc.). Running the repair as the very last step
- # ensures ROCm torch is in place at runtime, regardless of which
- # intermediate step clobbered it.
+ # 13. AMD ROCm: final torch repair. Several steps above can pull in CUDA
+ # torch from PyPI (base packages, extras, overrides, studio deps, etc.).
+ # Running the repair last ensures ROCm torch is in place at runtime,
+ # whichever intermediate step clobbered it.
if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:
_progress("ROCm torch (final)")
_ensure_rocm_torch()