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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Reduce and tighten code comments and docstrings repo-wide (#6095)
Daniel Han187144d4e74a
diff --git a/scripts/check_frontend_dep_removal.py b/scripts/check_frontend_dep_removal.pyindex 3ec4e9037fe..b95c4ca7f6d 100644--- a/scripts/check_frontend_dep_removal.py+++ b/scripts/check_frontend_dep_removal.py@@ -43,7 +43,7 @@ DEP_FIELDS = ("optionalDependencies",)-# Sources where seeing a package name does NOT count as usage.+# Files where seeing a package name does NOT count as usage.EXPECTED_NOISE_FILES = {"studio/frontend/package.json","studio/frontend/package-lock.json",@@ -51,17 +51,15 @@ EXPECTED_NOISE_FILES = {"studio/backend/core/data_recipe/oxc-validator/package-lock.json",}-# Only quoted-string occurrences in these file types can be module specifiers.+# File types where a quoted string can be a module specifier.JS_LIKE_EXT = re.compile(r"\.(ts|tsx|js|jsx|mjs|cjs|html|htm|css|scss|sass|json|jsonc)$")-# Files where JS-syntactic import patterns (static/dynamic/require/re-export)-# could be a real module reference. Markdown gets a separate gate (.mdx is+# Files where JS import patterns could be a real module reference (.mdx is# real ESM; .md code fences are not).SCRIPT_LIKE_EXT = re.compile(r"\.(ts|tsx|js|jsx|mjs|cjs|mdx)$")STYLE_EXT = re.compile(r"\.(css|scss|sass)$")HTML_EXT = re.compile(r"\.(html|htm)$")TS_LIKE_EXT = re.compile(r"\.(ts|tsx|mts|cts|mdx)$")-# Files where a removed package's CLI binary could be invoked (npx, bunx,-# yarn dlx, pnpm exec, or a bare `pkg --flag` shell call).+# Files where a removed package's CLI binary could be invoked.COMMAND_LIKE_EXT = re.compile(r"(\.(ya?ml|sh|ps1|bat)$|(^|/)Dockerfile[^/]*$)")GREP_INCLUDES = [@@ -102,7 +100,7 @@ GREP_EXCLUDES = ["--exclude-dir=venv",]-# A pip-installed playwright reference is the PyPI package, not npm.+# A pip-installed playwright ref is the PyPI package, not npm.PIP_PLAYWRIGHT = re.compile(r"(pip\s+install\s+['\"]?playwright"r"|python\s+-m\s+playwright"@@ -153,9 +151,8 @@ def all_decl_names(pkg: dict) -> set[str]:def _resolve_install_path(parent_path: str, name: str, pkgs: dict) -> str | None:- """Walk up the nested node_modules chain from `parent_path` to find- where `name` actually resolves. Mirrors Node module resolution.- """+ """Walk up the nested node_modules chain from `parent_path` to find where+ `name` resolves, mirroring Node module resolution."""parts = parent_path.split("/node_modules/")for i in range(len(parts), 0, -1):prefix = "/node_modules/".join(parts[:i])@@ -168,11 +165,8 @@ def _resolve_install_path(parent_path: str, name: str, pkgs: dict) -> str | Nonedef _deps_of(meta: dict) -> dict:- """Deps npm actually installs. Optional peers are skipped: npm only- installs them when another package declares the same dep, so for the- purpose of "is this package still reachable" they cannot keep a- removed top-level dep alive on their own.- """+ """Deps npm actually installs. Optional peers are skipped: they can't keep+ a removed top-level dep reachable on their own."""out = {}for field in ("dependencies", "optionalDependencies"):out.update(meta.get(field) or {})@@ -185,10 +179,8 @@ def _deps_of(meta: dict) -> dict:def reachable_from_head(head_pkg: dict, lock: dict) -> set[str]:- """BFS the lockfile dep graph starting from `head_pkg`'s top-level- declared deps. Returns the set of lockfile install paths that survive.- Stale lockfile entries (orphaned by the new package.json) are excluded.- """+ """BFS the lockfile dep graph from `head_pkg`'s top-level deps. Returns the+ surviving install paths, excluding stale (orphaned) lockfile entries."""pkgs = lock.get("packages", {})if not pkgs:return set()@@ -215,23 +207,17 @@ def reachable_from_head(head_pkg: dict, lock: dict) -> set[str]:def classify(pkg: str, file: str, content: str) -> str | None:"""Return why `content` references `pkg`, or None.- `content` may span multiple lines (for multi-line imports/exports);- each pattern uses re.DOTALL where it matters. The bare-spec- regexes use a word-boundary check on the package name so that- `foobar` does not match `foo`.-- File-type gating: JS-syntactic patterns only fire on .ts/.tsx/.js/.jsx/- .mjs/.cjs/.mdx files, so an `import x from "pkg"` snippet inside a- Python test fixture or a Markdown code block is not mistaken for a- real npm usage. CSS patterns only fire on .css/.scss/.sass. HTML- patterns only fire on .html/.htm.+ `content` may span multiple lines (multi-line imports/exports use re.DOTALL).+ Bare-spec regexes word-boundary the package name so `foobar` doesn't match+ `foo`. File-type gating restricts JS patterns to .ts/.tsx/.js/.jsx/.mjs/+ .cjs/.mdx, CSS to .css/.scss/.sass, HTML to .html/.htm, so a snippet inside+ a Python fixture or Markdown code block isn't mistaken for real npm usage."""if file in EXPECTED_NOISE_FILES:return Noneesc = re.escape(pkg)- # Subpath gate: after the package name, the next char must be either- # the closing quote, `/`, or end-of-string. Prevents foo matching foobar.+ # Subpath gate: pkg must be followed by quote, `/`, or end-of-string.sub = r"(?:/[^'\"`]*)?"flags_dotall = re.DOTALL | re.MULTILINE@@ -241,30 +227,22 @@ def classify(pkg: str, file: str, content: str) -> str | None:is_html = bool(HTML_EXT.search(file))is_ts = bool(TS_LIKE_EXT.search(file))- # If the file is none of script / style / html / json (which is the- # quoted-string fallback surface) and is not an mdx file, no classify- # rule applies. This is what gates out Python fixtures, Markdown code- # blocks, shell snippets, etc.+ # Gate out Python fixtures, Markdown code blocks, shell snippets, etc.is_json = file.endswith(".json") or file.endswith(".jsonc")if not (is_script or is_style or is_html or is_json):return None- # CSS @import is checked first so it does not collide with the- # side-effect-import regex below.+ # CSS @import first so it doesn't collide with side-effect-import below.if is_style and re.search(rf"@import\s+['\"]{esc}{sub}['\"]", content):return "css_import"- # Static imports: handle multi-line `import { ... } from "pkg"` by- # allowing arbitrary content (newlines included) between `import`- # and `from`. The non-greedy match plus the required `from` keeps- # this scoped to a single statement.+ # Static imports, including multi-line `import { ... } from "pkg"`.if is_script and re.search(rf"(?<!@)\bimport\b[^;'\"]*?\bfrom\s+['\"]{esc}{sub}['\"]",content,flags_dotall,):return "static_import"- # Side-effect import: `import "pkg"` (no `from`). The negative- # lookbehind rules out CSS `@import` lines.+ # Side-effect import `import "pkg"` (no `from`); lookbehind rules out @import.if is_script and re.search(rf"(?<!@)\bimport\s+['\"]{esc}{sub}['\"]", content):return "side_effect_import"# Dynamic import: `import("pkg")` and `await import("pkg")`.@@ -273,17 +251,15 @@ def classify(pkg: str, file: str, content: str) -> str | None:# require / require.resolveif is_script and re.search(rf"\brequire(?:\.resolve)?\(\s*['\"]{esc}{sub}['\"]\s*\)", content):return "require"- # Re-exports: `export * from "pkg"`, `export { x } from "pkg"`,- # `export type { Foo } from "pkg"`. Multi-line supported.+ # Re-exports: `export * from`, `export { x } from`, `export type { Foo } from`.if is_script and re.search(rf"\bexport\b[^;'\"]*?\bfrom\s+['\"]{esc}{sub}['\"]",content,flags_dotall,):return "re_export"- # HTML script / link. Match the package name as a complete path- # segment bounded by a quote / `#` / `?` or a subpath `/`, so- # `/node_modules/foo-extra/...` is NOT treated as usage of `foo`.+ # HTML script / link. Match pkg as a complete path segment so+ # `/node_modules/foo-extra/...` is not treated as usage of `foo`.html_pkg = rf"{esc}(?:/[^'\"#?]*)?(?=['\"#?])"if is_html and re.search(rf"<script[^>]*src\s*=\s*['\"][^'\"]*/{html_pkg}", content):return "html_script"@@ -295,8 +271,7 @@ def classify(pkg: str, file: str, content: str) -> str | None:# new URL("pkg/...", import.meta.url)if is_script and re.search(rf"\bnew\s+URL\(\s*['\"]{esc}{sub}['\"]", content):return "new_url"- # CSS url(...). Accept quoted ("pkg/x") AND unquoted (pkg/x) variants,- # bounded by a path-segment lookahead so `pkg-extra` does not match.+ # CSS url(...), quoted and unquoted, bounded so `pkg-extra` doesn't match.if is_style and re.search(rf"\burl\(\s*['\"]?(?:[^)'\"\s]+/)?{esc}(?:/[^)'\"`]*)?['\"]?\s*\)",content,@@ -309,20 +284,18 @@ def classify(pkg: str, file: str, content: str) -> str | None:if is_script and re.search(rf"@import\(\s*['\"]{esc}{sub}['\"]\s*\)", content):return "jsdoc_import"# Bare quoted-string fallback (config plugin lists, vite aliases,- # tsconfig paths, biome config plugin arrays, shadcn registries).+ # tsconfig paths, biome plugin arrays, shadcn registries).if not JS_LIKE_EXT.search(file):return None- # Boundary: pkg must be followed by `'`, `"`, or `/` to avoid- # matching `foo` inside `foobar`.+ # pkg must be followed by `'`, `"`, or `/` so `foo` doesn't match `foobar`.if re.search(rf"['\"]{esc}(?:['\"]|/)", content):return "string_literal"return Nonedef lockfile_root_sync(head_pkg: dict, head_lock: dict) -> list[str]:- """Return a list of warnings if package-lock.json's <root> dep map- disagrees with package.json (i.e., npm install was not re-run).- """+ """Warn if package-lock.json's <root> dep map disagrees with package.json+ (i.e. npm install was not re-run)."""warnings = []if not head_lock:return warnings@@ -350,10 +323,8 @@ def lockfile_root_sync(head_pkg: dict, head_lock: dict) -> list[str]:def types_orphan_warnings(head_pkg: dict) -> list[str]:- """Flag @types/<X> deps where <X> is no longer declared anywhere- in package.json. Removing X without also dropping @types/X leaves- dangling type packages.- """+ """Flag @types/<X> deps where <X> is no longer declared in package.json,+ which leaves dangling type packages."""decl = set()for f in DEP_FIELDS:decl.update((head_pkg.get(f) or {}).keys())@@ -361,9 +332,7 @@ def types_orphan_warnings(head_pkg: dict) -> list[str]:for name in decl:if not name.startswith("@types/"):continue- # @types/foo provides types for `foo`- # @types/foo-bar provides types for `foo-bar`- # @types/scope__pkg provides types for `@scope/pkg`+ # @types/scope__pkg provides types for @scope/pkg.target = name[len("@types/") :]if "__" in target:scope, sub = target.split("__", 1)@@ -386,8 +355,7 @@ _PKG_JSON_SKIP_KEYS = {"bundledDependencies",}-# Top-level fields whose contents are never package references. We walk-# everything else recursively.+# Top-level fields whose contents are never package references._PKG_JSON_OPAQUE_KEYS = {"browserslist", # browser queries"keywords", # free-form strings@@ -429,20 +397,12 @@ _PKG_JSON_OPAQUE_KEYS = {def package_json_extra_refs(pkg: dict, target: str) -> list[str]:- """Walk every key/value in package.json EXCEPT the dep declaration- blocks, and return citations for string values or dict keys that- equal `target` (or `target/subpath`).-- Catches the patterns the public dep-checker tools commonly miss:- - `overrides` / `resolutions` / `pnpm.overrides` keys- - `pnpm.patchedDependencies` keys- - `peerDependenciesMeta` keys- - `prettier`: "@my/prettier-config"- - `eslintConfig.extends`: ["..."] / "..."- - `stylelint.extends` / `stylelint.plugins`- - `babel.presets` / `babel.plugins`- - `jest.preset` / `jest.setupFiles` / `jest.transform`- - `commitlint.extends`, `renovate.extends`, `remarkConfig.plugins`+ """Walk package.json (except dep declaration blocks) and return citations+ for string values or dict keys equal to `target` (or `target/subpath`).++ Catches refs that public dep-checkers commonly miss: overrides/resolutions/+ pnpm.overrides keys, pnpm.patchedDependencies, peerDependenciesMeta,+ prettier, eslintConfig.extends, stylelint, babel, jest, commitlint, etc."""target_sub = target + "/"cites: list[str] = []@@ -453,14 +413,11 @@ def package_json_extra_refs(pkg: dict, target: str) -> list[str]:def walk(obj: object, path: str) -> None:if isinstance(obj, dict):for k, v in obj.items():- # Skip top-level dep declaration fields entirely.if path == "" and k in _PKG_JSON_SKIP_KEYS:continue- # Top-level fields whose contents are never package refs.if path == "" and k in _PKG_JSON_OPAQUE_KEYS:continue- # Inside `overrides` / `resolutions` / etc., the KEY itself- # is a package reference.+ # Inside overrides/resolutions/etc., the KEY is a package ref.if matches(k):cites.append(f"{path}.{k}" if path else k)walk(v, f"{path}.{k}" if path else k)@@ -476,9 +433,8 @@ def package_json_extra_refs(pkg: dict, target: str) -> list[str]:def build_bin_to_pkg(head_lock: dict) -> dict[str, str]:- """Map a binary name (e.g. 'vite', 'tsc', 'eslint') to the package- that provides it. Built from each lockfile entry's `bin` field.- """+ """Map a binary name (e.g. 'vite', 'eslint') to its providing package,+ from each lockfile entry's `bin` field."""out: dict[str, str] = {}if not head_lock:return out@@ -497,42 +453,29 @@ def build_bin_to_pkg(head_lock: dict) -> dict[str, str]:_SCRIPT_TOKENIZE = re.compile(r"\s*(?:&&|\|\||;|\|(?!\|))\s*")-# Wrappers that delegate to a real CLI in the same shell word list.-# After stripping env prefixes and (optionally) `npx`/`pnpm exec`/`yarn dlx`/-# `bunx`, if the leading token is one of these we advance past the-# wrapper's own flags and any further env-prefix tokens, then re-check.-# `cross-env` is the common one; `dotenv-cli` / `dotenvx` use `--` as a-# separator. Wrappers that operate on named npm-scripts (concurrently,-# npm-run-all, run-s, run-p, wireit, turbo, nx) intentionally aren't-# here -- they reference script names, not bin names, so the real bin-# is in the *target* script's chunk which we already tokenize.+# Wrappers that delegate to a real CLI in the same shell word list; we skip+# past them and their flags to find the wrapped bin. Script-name wrappers+# (concurrently, npm-run-all, turbo, nx) are excluded: they reference script+# names, so the real bin lives in the target script's chunk we already tokenize._SCRIPT_WRAPPERS = {"cross-env", "dotenv", "dotenvx", "env-cmd"}_ENV_PREFIX_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")def _next_real_bin(words: list[str], idx: int) -> str | None:- """Walk `words` from `idx`, peeling env-prefix tokens, the leading- package-manager runner (`npx`, `pnpm exec`, etc.), and the known- wrapper bins. Return the next token that looks like the real CLI- binary, or None if the chunk has nothing to look up.-- Recursion depth is bounded by the chunk's word count, so the loop- cannot run away on a pathological wrapper chain.- """+ """Walk `words` from `idx`, peeling env-prefix tokens, the package-manager+ runner (npx, pnpm exec, etc.), and known wrapper bins. Return the next+ real CLI binary, or None. Bounded by the chunk's word count."""seen_wrappers: set[str] = set()while idx < len(words):- # 1. env-prefix run: `FOO=bar BAZ="a b" cmd ...`. shlex has- # already collapsed quoted values into one word, so this- # tokenizer is safe for them.+ # 1. env-prefix run `FOO=bar BAZ="a b" cmd ...` (shlex pre-collapsed).while idx < len(words) and _ENV_PREFIX_RE.match(words[idx]):idx += 1if idx >= len(words):return Nonefirst = words[idx]- # 2. Package-manager runner: `npx <pkg> args`, `pnpm exec <pkg>`,- # `yarn dlx <pkg>`, `bunx <pkg>`. Strip and continue (so the- # wrapped command goes through the same unwrap loop).+ # 2. Package-manager runner (npx/pnpm exec/yarn dlx/bunx): strip and+ # continue so the wrapped command re-enters the unwrap loop.if first in {"npx", "pnpx", "bunx"} and idx + 1 < len(words):idx += 1continue@@ -540,21 +483,17 @@ def _next_real_bin(words: list[str], idx: int) -> str | None:idx += 2continue- # 3. Wrapper bin (cross-env, dotenv, etc.). Skip the wrapper's- # own flags and any subsequent env-prefix tokens, then re-loop.+ # 3. Wrapper bin (cross-env, dotenv): skip its flags and env prefixes.bin_token = first.removeprefix("./node_modules/.bin/").removeprefix("node_modules/.bin/")if bin_token in _SCRIPT_WRAPPERS and bin_token not in seen_wrappers:seen_wrappers.add(bin_token)idx += 1- # cross-env / env-cmd: no flags; just more env-prefix tokens.- # dotenv / dotenvx: skip `-e <file>` style flags and the- # optional `--` separator before the wrapped command.+ # dotenv/dotenvx use `-e <file>` flags and an optional `--`.while idx < len(words):tok = words[idx]if tok.startswith("-") and tok != "--":idx += 1- # `-e .env` style: also skip the flag's argument- # when it does not look like another flag.+ # `-e .env`: also skip the flag's argument.if (idx < len(words)and not words[idx].startswith("-")@@ -572,18 +511,12 @@ def _next_real_bin(words: list[str], idx: int) -> str | None:def scripts_bin_refs(head_pkg: dict, bin_to_pkg: dict[str, str]) -> dict[str, list[str]]:- """Return `{package_name: ['scripts.X: cmd', ...]}` listing every- package referenced via its bin name in package.json scripts.-- Each script value is split on shell separators (`&&`, `||`, `;`,- `|`). Within each chunk, `_next_real_bin()` unwraps env prefixes,- package-manager runners (`npx` / `pnpm exec` / `yarn dlx` / `bunx`),- and wrapper bins like `cross-env` / `dotenv` so that- `cross-env CI=1 biome check` correctly credits `biome` to its- declaring package.-- Tokenization uses shlex.split so quoted env values- (`FOO="a b" biome`) survive unbroken.+ """Return `{package_name: ['scripts.X: cmd', ...]}` for every package+ referenced via its bin name in package.json scripts.++ Each script is split on shell separators; `_next_real_bin()` unwraps env+ prefixes, package-manager runners, and wrapper bins so `cross-env CI=1+ biome check` credits `biome`. Uses shlex.split so quoted env values survive."""import shlex@@ -599,7 +532,7 @@ def scripts_bin_refs(head_pkg: dict, bin_to_pkg: dict[str, str]) -> dict[str, litry:words = shlex.split(chunk, posix = True)except ValueError:- # Unbalanced quotes -- fall back to plain split.+ # Unbalanced quotes: fall back to plain split.words = chunk.split()if not words:continue@@ -613,11 +546,8 @@ def scripts_bin_refs(head_pkg: dict, bin_to_pkg: dict[str, str]) -> dict[str, lidef tsconfig_compiler_types_refs() -> set[str]:- """Read studio/frontend/tsconfig*.json and return the set of- package names referenced in compilerOptions.types arrays. These are- implicitly loaded by tsc and count as a real use even though they- have no explicit import.- """+ """Return package names in tsconfig*.json compilerOptions.types arrays.+ These are implicitly loaded by tsc and count as real uses."""out: set[str] = set()base = REPO_ROOT / "studio/frontend"for name in ("tsconfig.json", "tsconfig.app.json", "tsconfig.node.json"):@@ -635,26 +565,16 @@ def tsconfig_compiler_types_refs() -> set[str]:for t in types:if not isinstance(t, str):continue- # `vite/client` resolves to `vite` package.+ # `vite/client` resolves to the `vite` package.pkg = t.split("/", 1)[0] if not t.startswith("@") else "/".join(t.split("/", 2)[:2])out.add(pkg)return outdef enumerate_dep_usage(head_pkg: dict, head_lock: dict) -> dict[str, list]:- """For every declared dep, classify whether it appears used. Returns- a dict with these categories:- - used: has at least one detected usage in src/,- config files, scripts.bin, package.json- field refs, or tsconfig types- - unused: no detected usage anywhere- - type_pkg_kept: @types/X where X is still declared- - type_pkg_orphan: @types/X where X is no longer declared- (or X is removed) -- candidate for removal-- Each entry is the package name. The categorisation is opinionated;- `unused` is a CANDIDATE list, not a guarantee. The caller should- verify before deletion.+ """For every declared dep, classify usage into a dict of package-name lists:+ used, unused, type_pkg_kept (@types/X with X declared), type_pkg_orphan+ (@types/X with X gone). `unused` is a CANDIDATE list; verify before deletion."""decl = all_decl_names(head_pkg)bin_to_pkg = build_bin_to_pkg(head_lock) if head_lock else {}@@ -683,11 +603,8 @@ def enumerate_dep_usage(head_pkg: dict, head_lock: dict) -> dict[str, list]:# Real-source-usage checkhits = find_usage(name)used = bool(hits)- # CLI usage in shell / workflow / Dockerfile surfaces. Skip for- # `@types/*` packages because they never expose a CLI binary and- # the unscoped-tail bin name candidate would scan workflow files- # for the bare runtime name (a removed `@types/foo` would look- # for invocations of `foo`).+ # CLI usage in shell/workflow/Dockerfile. Skipped for @types/* (no CLI+ # binary; the bare-name bin candidate would false-match the runtime).if not used and not name.startswith("@types/") and find_command_usage(name):used = True# Bin scripts@@ -707,28 +624,15 @@ def enumerate_dep_usage(head_pkg: dict, head_lock: dict) -> dict[str, list]:def find_imports_without_decl(head_pkg: dict) -> list[tuple[str, int, str]]:- """Reverse check: find bare-specifier imports in studio/frontend/src- that don't correspond to any declared package.json dep. Catches the- case where someone adds an import but forgets the dep declaration.- Returns (file, line, spec) tuples.-- Match shapes covered:- import "pkg"- import Foo from "pkg"- import { Foo } from "pkg"- import type { Foo } from "pkg"- const x = require("pkg")- const x = await import("pkg")+ """Reverse check: find bare-specifier imports in studio/frontend/src with+ no matching package.json dep (import added but dep declaration forgotten).+ Covers import/require/dynamic-import shapes. Returns (file, line, spec)."""decl = set()for f in DEP_FIELDS:decl.update((head_pkg.get(f) or {}).keys())- # Also: anything tsconfig path-aliases (just '@/...' here) is internal.- # The capture group is the specifier; the leading alternation accepts- # any of: `from "..."`, bare side-effect `import "..."`,- # `import("..."), or `require("...")`. We exclude relative paths and- # the `@/` alias prefix by requiring the first char of the specifier- # to be neither `.` nor `/`.+ # Exclude relative paths and the `@/` alias by requiring the specifier's+ # first char to be neither `.` nor `/`. Capture group is the specifier.pattern = (r"(?:\bfrom\s+|"r"\bimport\s+(?:\(\s*)?|"@@ -754,7 +658,7 @@ def find_imports_without_decl(head_pkg: dict) -> list[tuple[str, int, str]]:file, ln, content = m.group(1), int(m.group(2)), m.group(3)for spec_match in re.finditer(pattern, content):spec = spec_match.group(1)- # Resolve to package name (strip subpath)+ # Resolve to package name (strip subpath).if spec.startswith("@"):parts = spec.split("/", 2)pkg_name = "/".join(parts[:2]) if len(parts) >= 2 else spec@@ -762,7 +666,7 @@ def find_imports_without_decl(head_pkg: dict) -> list[tuple[str, int, str]]:pkg_name = spec.split("/", 1)[0]if pkg_name in decl:continue- # Internal aliases like '@/foo' or starts with builtin names+ # Internal aliases like '@/foo' or builtin names.if pkg_name == "@":continueif pkg_name in {@@ -807,11 +711,10 @@ def _read_file(path: str) -> list[str]:def find_usage(pkg: str) -> list[Hit]:- """Return real usages of `pkg`. Filters pip-playwright separately.+ """Return real usages of `pkg` (pip-playwright filtered separately).- For each filename returned by grep, also feed a multi-line window- around the matching line into classify() so multi-line imports- (`import {\n a\n} from "pkg"`) get picked up.+ For each grep hit, also feed a multi-line window into classify() so+ multi-line imports get picked up."""rows = grep_repo(re.escape(pkg))hits = []@@ -822,10 +725,8 @@ def find_usage(pkg: str) -> list[Hit]:# Try the single-line classify first.kind = classify(pkg, file, content)if not kind:- # Multi-line window: a generous 25 lines above + the line +- # 25 below so Prettier's one-import-per-line formatting for- # 12-20+ named imports still includes the `import` keyword- # in the same window as the `from "pkg"` clause.+ # Multi-line window (25 lines each side) so Prettier's+ # one-import-per-line formatting still pairs `import` with `from`.lines = _read_file(file)lo = max(0, lineno - 26)hi = min(len(lines), lineno + 25)@@ -841,28 +742,21 @@ def find_usage(pkg: str) -> list[Hit]:def _candidate_bin_names(pkg: str) -> set[str]:- """Names a removed package's CLI could be invoked under in shell- scripts and workflow files. Most npm CLIs use the package name- (`vite`, `eslint`, `playwright`); scoped CLI packages commonly- expose an unscoped binary name (`@biomejs/biome` -> `biome`).- """+ """Bin names a removed package's CLI could be invoked under. Most npm CLIs+ use the package name; scoped ones expose an unscoped bin (@biomejs/biome ->+ biome)."""return {pkg, pkg.rsplit("/", 1)[-1]}def find_command_usage(pkg: str) -> list[Hit]:- """Find package CLI invocations in shell / workflow / Dockerfile- surfaces: `npx pkg`, `bunx pkg`, `pnpm exec pkg`, `yarn dlx pkg`,- or a bare `pkg --flag`. Returns Hit("command_bin").-- Detection is bounded to COMMAND_LIKE_EXT files so a JS string that- happens to contain `npx foo` inside a TS test fixture is not- mistaken for a real invocation.+ """Find package CLI invocations in shell/workflow/Dockerfile surfaces (npx,+ bunx, pnpm exec, yarn dlx, or bare `pkg --flag`). Bounded to+ COMMAND_LIKE_EXT so `npx foo` in a TS fixture isn't mistaken for real use."""bins = sorted(_candidate_bin_names(pkg), key = len, reverse = True)esc_bins = "|".join(re.escape(b) for b in bins)- # grep ERE pattern (POSIX classes for whitespace/word boundaries).- # Build without f-strings to avoid f-string-vs-{} confusion with the- # POSIX `[[:space:]]` literals and trailing `})}` boundary class.+ # grep ERE pattern. Built without f-strings to avoid clashing with the+ # POSIX `[[:space:]]` literals.grep_pat = (r"(^|[[:space:]:;&|(\[])"r"(npx[[:space:]]+|pnpm[[:space:]]+exec[[:space:]]+"@@ -894,10 +788,8 @@ def find_command_usage(pkg: str) -> list[Hit]:def types_target_name(pkg: str) -> str | None:- """Strip `@types/` prefix and decode the npm scope-encoding so the- return value matches the runtime package name. `@types/foo` -> `foo`,- `@types/foo__bar` -> `@foo/bar`. Returns None for non-@types packages.- """+ """Strip `@types/` and decode scope-encoding to the runtime package name+ (`@types/foo__bar` -> `@foo/bar`). None for non-@types packages."""if not pkg.startswith("@types/"):return Nonetarget = pkg[len("@types/") :]@@ -908,11 +800,8 @@ def types_target_name(pkg: str) -> str | None:def find_types_runtime_usage(pkg: str, tsc_types: set[str]) -> list[Hit]:- """For a removed `@types/X`, find usages of `X` itself: explicit- `/// <reference types="X" />`, `tsconfig.compilerOptions.types: ["X"]`,- and runtime `import "X"` shapes. The whole point of `@types/X` is to- type one of those; if any are present, the type package must stay.- """+ """For a removed `@types/X`, find usages of `X` itself (triple-slash+ reference, tsconfig types, runtime import). If any exist, @types/X stays."""target = types_target_name(pkg)if target is None:return []@@ -997,10 +886,9 @@ def main() -> int:return 2head_lock = read_pkg_file(head_lock_path)- # Base lockfile is best-effort. We use it only to recover the- # bin -> package mapping for packages the PR is removing -- so a- # `scripts.biome:check` cite still fires when `@biomejs/biome` is- # being dropped and the head lockfile no longer has it.+ # Base lockfile is best-effort: only used to recover the bin -> package+ # mapping for packages the PR removes, so a scripts.biome cite still fires+ # when @biomejs/biome is dropped from the head lockfile.if args.base_lock:base_lock_path = Path(args.base_lock)base_lock = read_pkg_file(base_lock_path) if base_lock_path.exists() else {}@@ -1011,9 +899,8 @@ def main() -> int:head_names = all_decl_names(head_pkg)removed = sorted(base_names - head_names)- # All hygiene checks compute up front so they can run on both the- # removal-present and removal-empty paths (so `--strict` actually- # fails when only hygiene issues exist).+ # Hygiene checks compute up front so they run on both the removal-present+ # and removal-empty paths (so --strict fails on hygiene-only issues).sync_warns = lockfile_root_sync(head_pkg, head_lock)types_warns = types_orphan_warnings(head_pkg)missing_imports = find_imports_without_decl(head_pkg)@@ -1074,12 +961,9 @@ def main() -> int:print()reachable_paths = reachable_from_head(head_pkg, head_lock) if head_lock else set()- # bin -> package map: start from the head lockfile, then layer the- # base lockfile's entries on top for packages this PR is removing.- # A correct removal updates the head lockfile to drop node_modules/foo,- # so build_bin_to_pkg(head_lock) loses the mapping; we recover it- # from the base lockfile so `scripts.biome:check` still flags as a- # usage when `@biomejs/biome` is being dropped.+ # bin -> package map from the head lockfile, layering base-lockfile entries+ # for removed packages so scripts.biome still flags when @biomejs/biome is+ # dropped (head lockfile no longer maps it).bin_to_pkg = build_bin_to_pkg(head_lock) if head_lock else {}base_bin_to_pkg = build_bin_to_pkg(base_lock) if base_lock else {}removed_set = set(removed)@@ -1091,9 +975,8 @@ def main() -> int:def reachable_install_paths(name: str) -> tuple[str | None, list[str]]:"""Return (top_level_path, nested_paths). top_level is what bare- `import "name"` from src/ actually resolves to; nested copies are- only visible inside the parent package that nested them.- """+ `import "name"` resolves to; nested copies are only visible inside+ their parent package."""top = f"node_modules/{name}"top_path = top if top in reachable_paths else Nonenested = sorted(@@ -1106,8 +989,7 @@ def main() -> int:hits = find_usage(name)# CLI invocations in shell scripts / workflows / Dockerfiles.hits.extend(find_command_usage(name))- # @types/X is "used" if X is referenced as a type or as a- # runtime import elsewhere in the repo.+ # @types/X is "used" if X is referenced as a type or runtime import.hits.extend(find_types_runtime_usage(name, tsc_types))for cite in script_refs.get(name, []):hits.append(Hit("studio/frontend/package.json", 0, "script_bin", cite))@@ -1115,9 +997,8 @@ def main() -> int:hits.append(Hit("studio/frontend/package.json", 0, "pkg_json_field", cite))top, nested = reachable_install_paths(name)importable_top_level = top is not None- # Source imports of bare specifier `name` resolve ONLY to top-level- # node_modules/<name>. Nested copies under another package are- # invisible to src/ files.+ # Bare specifier `name` resolves ONLY to top-level node_modules/<name>;+ # nested copies are invisible to src/ files.if hits and not importable_top_level:status = "FAIL"elif hits and importable_top_level:diff --git a/scripts/check_new_install_scripts.py b/scripts/check_new_install_scripts.pyindex 2beaada0bf2..604d9b9f90c 100644--- a/scripts/check_new_install_scripts.py+++ b/scripts/check_new_install_scripts.py@@ -4,33 +4,18 @@"""Diff two `package-lock.json` files and flag NEW install-script deps.-A package with `"hasInstallScript": true` runs `preinstall` / `install` /-`postinstall` lifecycle hooks every time `npm ci` lays it down. Every-npm supply-chain compromise of the last 18 months (Shai-Hulud,-TanStack, axios-style, ArmorCode hijacks) leveraged exactly this lever:-the attacker publishes a new malicious version of a dep we already-trust, and the post-install hook runs the next time CI installs.--This scanner refuses to allow a newly-introduced install-script dep to-land without a maintainer eyeball on the lifecycle script body.-Existing install-script deps are NOT re-flagged -- if `node-gyp` has-been in the lockfile since day one, it's not part of this PR's threat-model. Only new entries are surfaced.--Supports lockfileVersion 1 (`dependencies` key, recursive), 2 and 3-(flat `packages` key with `node_modules/<a>/node_modules/<b>` nesting-for transitive entries). For each NEW install-script package we-attempt a stdlib-only fetch of-`https://registry.npmjs.org/<name>/<version>` to recover the actual-postinstall command body. If the network is blocked we still emit the-finding -- the lifecycle command body is informational, not-load-bearing.--Exit codes-==========- 0 no newly-added install-script deps- 1 one or more newly-added install-script deps; listed on stderr- 2 internal error (missing lockfile, malformed JSON, etc.)+A `"hasInstallScript": true` package runs preinstall/install/postinstall+hooks on every `npm ci` -- the lever behind recent npm supply-chain+compromises (attacker publishes a malicious version of a trusted dep).+This refuses to land a newly-introduced install-script dep without a+maintainer eyeball; pre-existing ones are not re-flagged.++Supports lockfileVersion 1 (recursive `dependencies`) and 2/3 (flat+`packages` with `node_modules/.../node_modules/...` nesting). For each+new entry we best-effort fetch the registry metadata to recover the+postinstall command body; the finding is still emitted if unreachable.++Exit codes: 0 = none; 1 = one or more (on stderr); 2 = internal error."""from __future__ import annotations@@ -68,21 +53,14 @@ class Finding:)-# ─────────────────────────────────────────────────────────────────────# Lockfile parsing.-# ─────────────────────────────────────────────────────────────────────def _strip_nm_prefix(key: str) -> str:- """Convert a v2/v3 `packages` key into a bare package name.-- `node_modules/foo` -> `foo`; `node_modules/foo/node_modules/bar` ->- `bar`. The empty key (`""`) is the project root and returns "".- """+ """Convert a v2/v3 `packages` key into a bare package name (leaf after last `node_modules/`)."""if not key:return ""- # Use the LAST `node_modules/` segment so transitives map to their- # leaf name, matching how npm install resolves a postinstall.+ # LAST node_modules/ segment so transitives map to their leaf name.marker = "node_modules/"idx = key.rfind(marker)if idx == -1:@@ -91,14 +69,9 @@ def _strip_nm_prefix(key: str) -> str:def _collect_install_script_entries(lock: dict) -> dict[str, str]:- """Walk a parsed lockfile and return {package_name: version} for- every entry with `hasInstallScript: true` (v2/v3) OR a- non-empty `scripts.preinstall|install|postinstall` (v1).-- The same package may appear at multiple versions in a single- lockfile (de-duplicated copies under different parents); we key by- `name@version` so we don't lose either copy. Returns a dict keyed- by `name@version` -> the same string for convenience.+ """Return {name@version: name} for entries with hasInstallScript (v2/v3) or a lifecycle script (v1).++ Keyed by name@version so dup copies at different versions aren't lost."""seen: dict[str, str] = {}version = lock.get("lockfileVersion")@@ -118,10 +91,7 @@ def _collect_install_script_entries(lock: dict) -> dict[str, str]:ver = entry.get("version") or "<unversioned>"seen[f"{name}@{ver}"] = name- # v1 also embeds a `dependencies` tree; v2/v3 carry both for- # backwards-compat but `packages` is canonical for them. For v1- # there is no `hasInstallScript` flag, so look for a non-empty- # `scripts.preinstall|install|postinstall` directly.+ # v1 has no hasInstallScript flag; detect lifecycle scripts directly.def _walk_v1(deps: dict, depth: int = 0) -> None:if depth > 64 or not isinstance(deps, dict):return@@ -133,8 +103,6 @@ def _collect_install_script_entries(lock: dict) -> dict[str, str]:isinstance(scripts, dict) and scripts.get(hook)for hook in ("preinstall", "install", "postinstall"))- # v1 also sets `requires` only on the parent, no flag, so- # the lifecycle-script presence is the only signal.if lifecycle:ver = entry.get("version") or "<unversioned>"seen[f"{name}@{ver}"] = name@@ -155,19 +123,11 @@ def _load_lockfile(path: Path) -> dict:raise ValueError(f"{path}: not valid JSON: {exc}") from exc-# ─────────────────────────────────────────────────────────────────────# Registry lookup for the postinstall command body (best-effort).-# ─────────────────────────────────────────────────────────────────────def _fetch_registry_scripts(name: str, version: str) -> dict[str, str] | None:- """Return {hook: command} for any of preinstall / install /- postinstall published in the registry metadata for this name@ver.-- Returns None on any error (network blocked, 404, malformed JSON).- Never raises; the caller treats absence as "could not enrich, emit- finding anyway".- """+ """Return {hook: command} for lifecycle hooks in registry metadata; None on any error (never raises)."""safe_name = urllib.parse.quote(name, safe = "@/")url = f"{REGISTRY_BASE}{safe_name}/{urllib.parse.quote(version)}"try:@@ -190,9 +150,7 @@ def _fetch_registry_scripts(name: str, version: str) -> dict[str, str] | None:return keep or None-# ─────────────────────────────────────────────────────────────────────# Diff.-# ─────────────────────────────────────────────────────────────────────def diff_new_install_scripts(base_lock: dict, head_lock: dict) -> list[Finding]:@@ -203,7 +161,6 @@ def diff_new_install_scripts(base_lock: dict, head_lock: dict) -> list[Finding]:if key in base:continue # pre-existing install-script dep; not in scopename = head[key]- # key is "name@version"; rsplit("@", 1) handles scoped names.version = key[len(name) + 1 :] if key.startswith(name + "@") else "<unversioned>"scripts = _fetch_registry_scripts(name, version)if scripts:@@ -226,9 +183,7 @@ def diff_new_install_scripts(base_lock: dict, head_lock: dict) -> list[Finding]:return findings-# ─────────────────────────────────────────────────────────────────────# CLI.-# ─────────────────────────────────────────────────────────────────────def main(argv: list[str] | None = None) -> int:diff --git a/scripts/enforce_kwargs_spacing.py b/scripts/enforce_kwargs_spacing.pyindex fdef950d7f5..dc4a6d68217 100755--- a/scripts/enforce_kwargs_spacing.py+++ b/scripts/enforce_kwargs_spacing.py@@ -20,13 +20,8 @@ from pathlib import Pathdef _atomic_write_text(path: Path, data: str, encoding: str) -> None:- """Write ``data`` to ``path`` atomically.-- Stages a tmp file in the same directory (so it's on the same- filesystem as the destination), fsyncs, then `os.replace`s into- place. A crash mid-write therefore leaves either the previous- content or the fully new content -- never a truncated source file.- """+ """Write ``data`` to ``path`` atomically via same-dir tmp + fsync + os.replace,+ so a crash mid-write leaves either the old or full new content, never a truncation."""dirpath = str(path.parent) or "."fd, tmp_path = tempfile.mkstemp(prefix=".kwargs_fix.", dir=dirpath)try:@@ -142,7 +137,7 @@ def remove_redundant_passes(text: str) -> tuple[str, bool]:lines[start] = segment if segment.strip() else ""continue- # Defensive fall-back for unexpected multi-line 'pass'.+ # Fall-back for unexpected multi-line 'pass'.prefix = lines[start][: node.col_offset]lines[start] = prefix if prefix.strip() else ""for idx in range(start + 1, end):@@ -164,15 +159,12 @@ def remove_redundant_passes(text: str) -> tuple[str, bool]:def remove_blank_after_short_import(text: str) -> tuple[str, bool]:- """Drop blank line(s) after an import block in a *small* nested suite.-- Inside an indented suite of <= 3 statements (function/try/if/with/etc., never- module level), when a run of consecutive ``import`` / ``from ... import``- statements is directly followed -- across one or more blank lines and nothing- else -- by another statement in the same suite, remove those blank lines so- the import sits next to the code that uses it. A comment in the gap blocks the- rule. Removing blank lines never changes the AST, so this is always- semantics-preserving.+ """Drop blank line(s) after an import block in a small nested suite.++ In an indented suite of <= 3 statements (never module level), when consecutive+ imports are followed across blank lines (nothing else) by another statement,+ remove those blanks. A comment in the gap blocks the rule. Removing blank lines+ never changes the AST."""try:tree = ast.parse(text)@@ -226,12 +218,11 @@ _DEF_MIN_PARAMS_FOR_MULTILINE = 3 # signatures with < this many params stay onedef _def_specs_by_line(tree: ast.AST) -> dict[int, tuple[int, bool]]:- """Map the line of each def keyword to (param count, has-any-default).+ """Map each def keyword line to (param count, has-any-default).- One def per line, so the line is a stable key. ``*`` / ``/`` markers are not- parameters and are not counted. A default exists if any positional default- is present or any keyword-only default is not ``None`` (a ``None`` entry in- ``kw_defaults`` means a required keyword-only arg).+ ``*`` / ``/`` markers aren't counted. A default exists if any positional default+ is present or any keyword-only default is not ``None`` (``None`` in ``kw_defaults``+ means a required keyword-only arg)."""out: dict[int, tuple[int, bool]] = {}for node in ast.walk(tree):@@ -250,20 +241,12 @@ def _def_specs_by_line(tree: ast.AST) -> dict[int, tuple[int, bool]]:def normalize_def_trailing_comma(text: str) -> tuple[str, bool]:- """Force a def / async-def signature one-per-line iff it has >= 3 parameters- AND at least one default value; otherwise keep it collapsible.-- Rationale: signatures with defaults read better one parameter per line, but- only once they are non-trivial (< 3 params always stay on one line). A- signature with >= 3 params and a default gets a magic trailing comma added- (ruff then wraps it one-per-line regardless of length); every other- signature has its trailing comma stripped so ruff collapses it onto one line- when it fits (and wraps a genuinely long one by length alone).-- Function-definition parameter lists only, never call sites or collection- literals. Parameter counts and defaults come from the AST. Run BEFORE ruff- format. Adding or removing a def trailing comma never changes the AST, which- is re-checked before returning.+ """Force a def signature one-per-line iff >= 3 params AND a default; else collapsible.++ A qualifying signature gets a magic trailing comma added (ruff wraps it+ one-per-line); every other signature has its trailing comma stripped so ruff+ collapses it when it fits. Def parameter lists only, never call sites or+ collection literals. Run BEFORE ruff format. Never changes the AST (re-checked)."""try:tree = ast.parse(text)@@ -332,12 +315,10 @@ def normalize_def_trailing_comma(text: str) -> tuple[str, bool]:def _split_string_token(s: str) -> tuple[str, str, str] | None:- """Split a string literal's source into (prefix, quote, body).+ """Split a string literal source into (prefix, quote, body).- ``prefix`` is the letters before the opening quote (``r``/``f``/``b``/``u``- in any case/order), ``quote`` is the opening delimiter (``'``, ``"``,- ``'''`` or ``\"\"\"``) and ``body`` is everything between the delimiters.- Returns ``None`` if ``s`` is not a recognizable string literal.+ ``prefix`` is the letters before the opening quote, ``quote`` the delimiter,+ ``body`` everything between. ``None`` if not a recognizable string literal."""i = 0while i < len(s) and s[i] not in ("'", '"'):@@ -393,15 +374,12 @@ def _string_pieces(def _merge_string_run(pieces: list[tuple[str, str]]) -> str | None:"""Merge a run of adjacent string pieces into one literal's source text.- ``pieces`` is a list of ``(kind, raw_source)`` where kind is ``"str"`` or- ``"f"``. Rules: bytes are left side-by-side (return ``None``); a run with no- f-string merges plain/raw/unicode pieces sharing one prefix+quote by simple- body concatenation; a run mixing an f-string with at least one plain string- (and no bytes, no raw) folds into a single f-string -- f pieces keep their- bodies verbatim and plain pieces have their braces escaped (``{`` -> ``{{``).- Runs of only f-strings are left side-by-side. The caller re-checks the file- AST and drops the change if it differs, so any subtle case (e.g. ``\\N{...}``)- that this would mis-handle is caught and skipped.+ ``pieces`` is ``(kind, raw_source)`` with kind ``"str"`` or ``"f"``. Bytes are+ left side-by-side (``None``); a run with no f-string merges plain/raw/unicode+ sharing one prefix+quote by body concatenation; a run mixing an f-string with a+ plain string (no bytes, no raw) folds into one f-string with plain braces escaped.+ Runs of only f-strings are left alone. Caller re-checks the AST and drops a+ differing change, so subtle cases are caught."""parsed = []for kind, raw in pieces:@@ -455,13 +433,10 @@ def _fold_collapses() -> bool:"""Whether an f-string fold at ``row[c0:c1]`` -> ``merged`` is safe to apply.- Only ``assert`` statements wrap awkwardly when a message is folded: ruff- parenthesizes the *condition* once ``assert cond, msg`` no longer fits on one- line. For every other construct (call argument, ``raise``, assignment, ...) a- folded long message wraps acceptably, so the fold is always allowed. For an- ``assert`` the fold is allowed only when the statement is already one physical- line, or its estimated one-line length after folding fits the line length;- otherwise the message is left side-by-side.+ Only ``assert`` wraps awkwardly when a message folds (ruff parenthesizes the+ condition once it no longer fits one line); every other construct wraps+ acceptably so is always allowed. An ``assert`` fold is allowed only if already+ one line, or its estimated folded one-line length fits the line length."""stmt = _enclosing_stmt(tree, row)if not isinstance(stmt, ast.Assert):@@ -483,15 +458,12 @@ def _fold_collapses(def merge_adjacent_string_literals(text: str) -> tuple[str, bool]:- """Merge a run of adjacent string literals on ONE physical line into a single- literal (the ``"a" "b"`` form ruff emits when it collapses an implicit- concatenation). Plain/raw/unicode runs merge by concatenation; a run mixing- an f-string with a plain string folds into one f-string (plain parts' braces- escaped) -- but only when the statement still fits on one line, so a long- message is left side-by-side rather than forcing the statement to re-wrap.- Runs of only f-strings, and bytes, are left side-by-side. The whole file's AST- is re-checked and the change is dropped if it would differ, so the transform- can never change meaning.+ """Merge adjacent string literals on ONE physical line into a single literal.++ Plain/raw/unicode runs merge by concatenation; an f-string + plain string folds+ into one f-string (plain braces escaped) only while the statement still fits one+ line. Runs of only f-strings, and bytes, are left side-by-side. The file AST is+ re-checked and a differing change dropped, so meaning never changes."""try:toks = list(tokenize.generate_tokens(io.StringIO(text).readline))@@ -552,17 +524,11 @@ def merge_adjacent_string_literals(text: str) -> tuple[str, bool]:def collapse_short_asserts(text: str) -> tuple[str, bool]:"""Collapse a multi-line ``assert`` onto one line when it would fit.- An ``assert`` is often kept multi-line only by a magic trailing comma inside- a collection / call / tuple-message (``assert x == {\"a\": 1,}`` written- across lines). When the whole statement's estimated one-line length fits the- line length, strip those trailing commas (the comma before a ``)`` / ``]`` /- ``}``) so ruff joins it back onto one line on the following format pass.-- Run BEFORE ruff format. Skips any assert that contains a comment (a comment- forces ruff to keep it multi-line, which would oscillate). Stripping a- trailing comma is non-semantic except for a one-element tuple ``(x,)``; the- file AST is re-checked and any assert whose strip would change it is left- alone.+ When the statement's estimated one-line length fits, strip the magic trailing+ commas (comma before a closer) holding it open so ruff rejoins it. Run BEFORE+ ruff format. Skips asserts with a comment (would oscillate). Stripping is+ non-semantic except for a one-element tuple; AST is re-checked and changing+ asserts left alone."""try:tree = ast.parse(text)diff --git a/scripts/lint_workflow_triggers.py b/scripts/lint_workflow_triggers.pyindex 34868b7d685..0688f6c65c9 100644--- a/scripts/lint_workflow_triggers.py+++ b/scripts/lint_workflow_triggers.py@@ -4,37 +4,19 @@"""Refuse dangerous GitHub Actions trigger patterns at PR time.-Two patterns are banned outright, both of which powered the TanStack-GHSA-g7cv-rxg3-hmpx supply-chain compromise:--1. `pull_request_target` -- runs a fork's workflow YAML against the- BASE repository's secrets and permissions. The fork can inject- arbitrary code into the base context. The TanStack worm used this- to land base-context execution from a fork PR. There is essentially- no safe use of this trigger for a public open-source project;- `pull_request` is the safe alternative.--2. `workflow_run` chained to a PR-triggered workflow -- carries the- same trust boundary problem one hop later. If a PR-triggered- workflow can poison artifacts/caches and a `workflow_run` trigger- fires off the result with elevated permissions, the attacker still- reaches the trusted context.--3. Shared cache keys between PR-triggered workflows and publish /- release / push-triggered workflows. The TanStack worm poisoned the- Actions cache from a fork PR and the legitimate release workflow- then restored the poisoned cache. Cache keys must be partitioned- so that nothing a PR can write is ever read by a workflow that- holds secrets.--Exit codes-==========-- 0 no findings- 1 one or more findings; stderr lists each with file path--Run from repo root:- python3 scripts/lint_workflow_triggers.py+Bans patterns behind the TanStack GHSA-g7cv-rxg3-hmpx compromise:++1. `pull_request_target` -- runs a fork's workflow against the base+ repo's secrets/permissions; use `pull_request` instead.+2. `workflow_run` chained to a PR-triggered workflow -- same trust+ boundary problem one hop later (poisoned artifacts/caches run with+ elevated permissions).+3. Cache keys shared between PR-triggered and publish/release/push+ workflows -- a fork PR could poison a cache the publish workflow+ restores. Partition the key namespaces.++Exit codes: 0 = no findings, 1 = findings (listed on stderr).+Run from repo root: python3 scripts/lint_workflow_triggers.py"""from __future__ import annotationsdiff --git a/scripts/lockfile_supply_chain_audit.py b/scripts/lockfile_supply_chain_audit.pyindex 5b503dcffe9..66b48c094d2 100644--- a/scripts/lockfile_supply_chain_audit.py+++ b/scripts/lockfile_supply_chain_audit.py@@ -5,64 +5,21 @@"""Lockfile supply-chain audit for the Studio frontend and Tauri shell.Runs BEFORE `npm ci` / `cargo fetch` in CI. Refuses to proceed when a-lockfile contains patterns that indicate the kind of supply-chain-injection seen in the npm Shai-Hulud waves and the cargo-crates.io brand-squat attempts.--What it checks-==============--studio/frontend/package-lock.json (lockfileVersion 2 or 3):-- 1. `resolved` URL origin. Every entry must resolve through- `https://registry.npmjs.org/`. Direct GitHub-hosted dependencies- (`git+ssh://`, `git+https://`, `github:owner/repo#sha`,- `file:`, `http://`) are refused -- npm's TanStack incident used- exactly this vector to land an unaudited GitHub commit hash as- an optional dependency.-- 2. `integrity` field presence. Every non-workspace entry must carry- an `integrity` SHA. A missing integrity means the registry can- swap the tarball after lockfile generation and CI will not- notice.-- 3. Known IOC strings. A hardcoded set of indicator-of-compromise- substrings is grepped across the entire lockfile body (file- names, dependency keys, URLs). The list is updated as new- campaigns surface. Catching one means the local install was- about to pull a publicly-known malicious release.--studio/src-tauri/Cargo.lock:-- 4. `source` field origin. Every entry with a `source` must point at- `registry+https://github.com/rust-lang/crates.io-index`. Direct- git sources (`git+https://...`) and `path+...` for cross-crate- paths warrant manual review and are flagged.-- 5. Known cargo IOC strings. Same idea as (3), separate list.--Exit codes-==========-- 0 no findings, or an opt-out env var (UNSLOTH_LOCKFILE_AUDIT_SKIP)- is set to a justification string (>=5 chars, not '1'/'true'/etc).- A value like '1' or 'true' is now REJECTED loudly and the audit- runs normally- 1 one or more findings; stderr lists them with file path and line- number where derivable- 2 internal error (missing dependency, malformed JSON, etc.)--Operational stance-==================--This scanner only PARSES the lockfiles -- it never executes anything-in them, never resolves anything against the network. Safe to run-ahead of every `npm ci`. The IOC list is short by design; this-complements (not replaces) `npm audit`, OSV-Scanner, and the-advisory-DB pipeline in `.github/workflows/security-audit.yml`. The-shape of the catch is "we refuse to proceed because the lockfile-itself is shaped wrong", which fires before any third-party install-script gets a chance to run on the runner.+lockfile contains patterns indicating supply-chain injection (npm+Shai-Hulud waves, cargo crates.io brand-squats).++Checks package-lock.json (lockfileVersion 2/3): `resolved` URL must be+the npm registry (direct git/github/file refs are the injection vector);+`integrity` SHA must be present; known IOC substrings grepped from the+body. Checks Cargo.lock: `source` must be the crates.io registry index;+known cargo IOC substrings.++Exit codes: 0 = clean (or skip env var set to a justification >=5 chars,+not '1'/'true'); 1 = findings; 2 = internal error.++Only PARSES the lockfiles, never executes or networks. Complements (not+replaces) `npm audit` / OSV-Scanner / the advisory-DB pipeline. Fires+before any third-party install script runs on the runner."""from __future__ import annotations@@ -77,14 +34,9 @@ from pathlib import PathREPO_ROOT = Path(__file__).resolve().parents[1]-# ─────────────────────────────────────────────────────────────────────-# Known IOC strings (case-sensitive substring match).-# ─────────────────────────────────────────────────────────────────────-#-# Keep these short and FACTUAL. Each entry is tied to a public advisory-# and is the literal string an attacker would have to embed for the-# attack to work. Adding speculative or generic patterns here would-# generate false positives on dependency upgrades.+# Known IOC strings (case-sensitive substring match). Each is tied to a+# public advisory; speculative/generic patterns would false-positive on+# upgrades.NPM_IOC_STRINGS: tuple[str, ...] = (# Shai-Hulud TanStack wave -- May 11, 2026 (GHSA-g7cv-rxg3-hmpx)."router_init.js",@@ -328,36 +280,22 @@ BLOCKED_NPM_VERSIONS: dict[str, set[str]] = {}CARGO_IOC_STRINGS: tuple[str, ...] = (- # Reserved for future cargo-side incidents. Empty by default --- # `source` origin check below catches the structural pattern.+ # Empty by default; the `source` origin check catches the structural+ # pattern. Reserved for future cargo-side incidents.)-# ─────────────────────────────────────────────────────────────────────# Allowed lockfile origins.-# ─────────────────────────────────────────────────────────────────────NPM_REGISTRY_PREFIX = "https://registry.npmjs.org/"--# Tarballs are also fetched from this mirror on some GH Actions cached-# runs (npm rewrites the resolved URL on cache hit). Allow either.NPM_REGISTRY_PREFIXES_ALLOWED: tuple[str, ...] = (NPM_REGISTRY_PREFIX,)CARGO_REGISTRY_SOURCE = "registry+https://github.com/rust-lang/crates.io-index"-# ─────────────────────────────────────────────────────────────────────-# Cargo non-registry source allowlist.-# ─────────────────────────────────────────────────────────────────────-#-# Each entry is `(crate_name, exact_source_string)`. The crate must-# match by name AND the source must match the full pinned-SHA string-# verbatim. Bumping the commit SHA forces a re-review here: the-# scanner fires until the new SHA is appended.-#-# Studio's Tauri shell pulls `fix-path-env` directly from-# tauri-apps/fix-path-env-rs because the crate is not published to-# crates.io. The pinned commit (c4c45d5) was reviewed at the time it-# landed; future bumps need explicit approval.+# Cargo non-registry source allowlist: `(crate_name, exact_source_string)`.+# Both must match verbatim; bumping the pinned SHA forces a re-review.+# Studio's Tauri shell pulls `fix-path-env` from git because it is not+# published to crates.io; commit c4c45d5 was reviewed when it landed.CARGO_SOURCE_ALLOWLIST: tuple[tuple[str, str], ...] = (("fix-path-env",@@ -367,11 +305,6 @@ CARGO_SOURCE_ALLOWLIST: tuple[tuple[str, str], ...] = ()-# ─────────────────────────────────────────────────────────────────────-# Finding container.-# ─────────────────────────────────────────────────────────────────────--class Finding:__slots__ = ("path", "package", "kind", "detail")@@ -390,27 +323,19 @@ class Finding:def _gha_escape(text: str) -> str:- """Escape a string for use in a GitHub Actions `::warning::` /- `::error::` workflow command message. GH Actions truncates- annotation messages at the first newline unless `\\n` is- escaped as `%0A`; carriage returns and the percent sign need- matching escapes per the workflow-commands spec. Order matters:- `%` must be replaced first so the subsequent `%0A` / `%0D`- sequences are not double-encoded.+ """Escape a string for a GH Actions `::warning::`/`::error::` message.++ GH Actions truncates at the first newline unless `\\n`/`\\r` are+ escaped as `%0A`/`%0D`. `%` must be replaced first to avoid+ double-encoding the subsequent escapes."""return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")-# ─────────────────────────────────────────────────────────────────────-# package-lock.json audit.-# ─────────────────────────────────────────────────────────────────────--def audit_npm_lockfile(path: Path) -> list[Finding]:findings: list[Finding] = []if not path.exists():- # A missing requested lockfile is a config error, not a clean- # audit; surface it so a deleted default cannot pass silently.+ # Missing lockfile is a config error, not a clean audit.findings.append(Finding(path = str(path),@@ -427,8 +352,7 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:try:raw = path.read_text(encoding = "utf-8")except OSError as exc:- # Permission denied, is-a-directory, broken-pipe etc. -- surface- # as a finding instead of crashing CI with a raw traceback.+ # Surface as a finding instead of crashing CI with a traceback.findings.append(Finding(path = str(path),@@ -464,9 +388,7 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:packages = lock.get("packages") or {}for key, entry in packages.items():- # The empty key "" is the project root; workspace entries use- # keys like "node_modules/foo" or "studio/frontend/sub-pkg".- # Skip the project root (it has no `resolved`).+ # Empty key "" is the project root (no `resolved`); skip it.if key == "":continueif entry.get("link"):@@ -474,12 +396,8 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:continueresolved = entry.get("resolved")- # Entries living inside another package's `node_modules/`- # tree are bundled fold-ins -- the parent's tarball ships- # their source verbatim and the parent's `integrity` covers- # the whole subtree. npm represents them in lockfileVersion 3- # as nested entries with no `resolved` and no `integrity` of- # their own. Treat them as transparent to this audit.+ # Entries nested in another package's node_modules are bundled+ # fold-ins covered by the parent's integrity; treat as transparent.nested = key.count("/node_modules/") >= 1# 1. resolved-URL origin.@@ -545,12 +463,10 @@ def audit_npm_lockfile(path: Path) -> list[Finding]:))- # 4. Known IOC strings: scan the raw file body so we hit fields the- # structural pass above doesn't enumerate (scripts, optional- # dependencies, etc.). Cheap and complete.+ # 4. Known IOC strings: scan the raw body to catch fields the+ # structural pass doesn't enumerate (scripts, optional deps, etc.).for ioc in NPM_IOC_STRINGS:if ioc in raw:- # Best-effort line number lookup.line_no = _first_line_containing(raw, ioc)findings.append(Finding(@@ -575,14 +491,7 @@ def _first_line_containing(text: str, needle: str) -> int | None:return None-# ─────────────────────────────────────────────────────────────────────-# Cargo.lock audit.-# ─────────────────────────────────────────────────────────────────────---# Cargo.lock is TOML; parse with stdlib tomllib (Python 3.11+). The-# studio's Tauri shell already requires a modern toolchain so this is-# always available where CI runs.+# Cargo.lock is TOML; parsed with stdlib tomllib (Python 3.11+)._PACKAGE_HEADER = re.compile(r"^\[\[package\]\]\s*$")@@ -706,24 +615,15 @@ def audit_cargo_lockfile(path: Path) -> list[Finding]:return findings-# ─────────────────────────────────────────────────────────────────────-# CLI.-# ─────────────────────────────────────────────────────────────────────--# Finding kinds split into BLOCKING vs ADVISORY for the default run mode.-# Blocking findings come from public supply-chain attack indicators (a-# version we know is malicious, a string an attacker would have to embed-# for an attack to work). Advisory findings are structural lockfile-# anomalies (missing integrity, non-default registry, etc.) -- they-# WARN the maintainer but do not block merges. Pass --strict to make-# every finding blocking (PR-5479-style behavior for opt-in adopters).+# Blocking = public attack indicators (known-malicious version, IOC+# string). Advisory = structural anomalies that warn but don't block.+# --strict makes every finding blocking.BLOCKING_KINDS: frozenset[str] = frozenset({"blocked-known-malicious","known-ioc-string",- # Internal-failure kinds: a structurally broken lockfile MIGHT- # be hiding a real attack, so we keep these blocking too.+ # A structurally broken lockfile might hide a real attack."malformed-lockfile","missing-lockfile","unreadable-lockfile",@@ -779,15 +679,9 @@ def main(argv: list[str] | None = None) -> int:)args = parser.parse_args(argv)- # SF4: require a real justification (e.g. JIRA ticket id) for the- # skip env var. Treat the trivially-set values ("1", "true", "yes",- # "on", empty) as INVALID -- they look like accidental flips and- # silently bypassed the supply-chain audit. A valid value is a- # non-empty string >=5 chars after stripping that does not match- # any of the boolean-shaped tokens above. An invalid value emits a- # loud GitHub Actions warning to stderr and FALLS THROUGH to run- # the audit normally (fail-safe). A valid value emits a warning- # naming the reason and skips with rc=0 (compat).+ # Require a real justification (>=5 chars, not a boolean-shaped token)+ # for the skip env var. An invalid value warns and falls through to+ # run the audit (fail-safe); a valid one warns and skips with rc=0._skip_raw = os.environ.get("UNSLOTH_LOCKFILE_AUDIT_SKIP")if _skip_raw is not None:_skip = _skip_raw.strip()@@ -809,8 +703,7 @@ def main(argv: list[str] | None = None) -> int:return 0root = Path(args.root).resolve()- # Explicit --npm-lockfile/--cargo-lockfile scopes the scan to those- # paths; defaults apply only to the no-args CI invocation.+ # Explicit flags scope the scan; defaults apply only to no-args CI._user_explicit = args.npm_lockfile is not None or args.cargo_lockfile is not Noneif _user_explicit:npm_paths = [root / p for p in (args.npm_lockfile or ())]@@ -835,11 +728,9 @@ def main(argv: list[str] | None = None) -> int:)return 0- # Split findings into blocking (known-malicious / IOC / structurally- # broken) and advisory (everything else, e.g. missing integrity on a- # registry-published tarball). In default mode advisory findings are- # printed but do not change the exit code; --strict treats every- # finding as blocking.+ # Split into blocking (known-malicious / IOC / structurally broken)+ # and advisory (everything else). Default mode prints advisories+ # without changing the exit code; --strict makes all blocking.blocking = [f for f in all_findings if f.kind in BLOCKING_KINDS]advisory = [f for f in all_findings if f.kind not in BLOCKING_KINDS]@@ -854,12 +745,8 @@ def main(argv: list[str] | None = None) -> int:file = sys.stderr,)for f in advisory:- # Surface in GitHub Actions UI as a warning annotation when run- # under Actions; harmless prefix elsewhere. GH Actions- # truncates annotation messages at the first newline unless- # newlines are escaped as `%0A`, so the full multi-line- # Finding (kind + path + package + detail) only renders in- # the UI after _gha_escape collapses it onto one line.+ # GH Actions warning annotation; _gha_escape collapses the+ # multi-line Finding onto one line so it renders fully in the UI.print(f"::warning::{_gha_escape(str(f))}", file = sys.stderr)print(file = sys.stderr)@@ -876,9 +763,7 @@ def main(argv: list[str] | None = None) -> int:file = sys.stderr,)for f in blocking:- # Same %-encoding rationale as the advisory branch above: the- # GH Actions annotation is truncated at the first newline- # unless the message is escaped.+ # Same %-encoding rationale as the advisory branch above.print(f"::error::{_gha_escape(str(f))}", file = sys.stderr)print(file = sys.stderr)print(diff --git a/scripts/notebook_to_python.py b/scripts/notebook_to_python.pyindex cc9dc0acda0..4b64123d6a6 100644--- a/scripts/notebook_to_python.py+++ b/scripts/notebook_to_python.py@@ -22,19 +22,14 @@ import urllib.parsefrom pathlib import Path-# Hosts we are willing to fetch raw notebook JSON from. Anything else-# is rejected before `urlopen` so a typoed / hostile URL cannot pull-# code from arbitrary infrastructure.+# Allowlist of hosts for raw notebook fetches; anything else rejected before urlopen._ALLOWED_NOTEBOOK_HOSTS = {"raw.githubusercontent.com","gist.githubusercontent.com",}-# Shell metacharacters that imply the cell's `!cmd` line cannot be-# parsed as a flat argv. If any of these appears, `shlex.split` would-# either fail or, worse, silently strip the operator -- so we keep-# `shell=True` for that command and emit a review marker.+# Metacharacters that mean a `!cmd` line can't be a flat argv -> keep shell=True + review marker._SHELL_METACHARS_RE = re.compile(r"\$\(|`|\|\||\||&&|>>?|<<?|\*|\?|;")@@ -46,12 +41,8 @@ def needs_fstring(cmd: str) -> bool:def github_blob_to_raw(url: str) -> str:"""Convert GitHub blob URL to raw URL."""- # https://github.com/user/repo/blob/branch/path- # -> https://raw.githubusercontent.com/user/repo/branch/path- # Compare the parsed host exactly (not as a substring) so a URL- # like https://attacker.example.com/github.com/blob/... does NOT- # get rewritten to a github raw URL. Closes CodeQL alert- # py/incomplete-url-substring-sanitization.+ # github.com/user/repo/blob/branch/path -> raw.githubusercontent.com/user/repo/branch/path+ # Exact host match (not substring) so attacker.example.com/github.com/blob/... is not rewritten.parsed = urllib.parse.urlparse(url)if parsed.netloc != "github.com" or "/blob/" not in parsed.path:return url@@ -63,18 +54,12 @@ def github_blob_to_raw(url: str) -> str:def download_notebook(url: str) -> tuple[str, str]:"""Download notebook from URL. Returns (content, filename)."""- # Convert blob URL to raw if neededraw_url = github_blob_to_raw(url)- # Extract filename from URLparsed = urllib.parse.urlparse(raw_url)filename = os.path.basename(urllib.parse.unquote(parsed.path))- # Host allowlist. Refuse to fetch from anywhere the campaign IOC- # tables flag (or just anywhere we don't recognise). The blob->raw- # conversion above only emits `raw.githubusercontent.com`, so a- # rejection here means the caller hand-typed a URL pointing- # somewhere we don't trust.+ # Host allowlist: refuse to fetch from anything we don't recognise.host = parsed.hostnameif host not in _ALLOWED_NOTEBOOK_HOSTS:raise ValueError(@@ -82,7 +67,6 @@ def download_notebook(url: str) -> tuple[str, str]:f"{sorted(_ALLOWED_NOTEBOOK_HOSTS)}")- # Downloadprint(f"Downloading {url}...")with urllib.request.urlopen(raw_url, timeout = 60) as response:content = response.read().decode("utf-8")@@ -97,29 +81,18 @@ def is_url(path: str) -> bool:def replace_colab_paths(source: str) -> str:"""Replace Colab-specific /content/ paths with current working directory."""- # Replace /content/ with f-string using _WORKING_DIRsource = source.replace('"/content/', 'f"{_WORKING_DIR}/')source = source.replace("'/content/", "f'{_WORKING_DIR}/")return sourcedef _emit_shell_command(indent: str, full_cmd: str, *, allow_shell: bool) -> list[str]:- """Render a `!cmd` notebook line as one or more Python statements.-- When the command body is f-string-interpolated, contains shell- metacharacters, or spans multiple lines, falling back to- `shell=True` is the only correct option -- `shlex.split` would- either drop operators or fail outright. We surface that with a- `# WARNING: shell=True; reviewed for hostile input` comment so a- reviewer cannot miss it.-- Otherwise we emit `subprocess.run(shlex.split(cmd), shell=False)`- so the converted script is not a re-injection vector if the- notebook ever interpolates user-controlled data.-- `allow_shell` defaults to True at the CLI for backwards- compatibility. Setting it to False makes `shell=True` emission a- hard error (no surprise behaviour).+ """Render a `!cmd` notebook line as Python statements.++ f-string interpolation, shell metacharacters, or multiline force+ shell=True (shlex.split would drop operators), flagged with a+ WARNING comment. Otherwise emit shell=False argv form. allow_shell+ False makes shell=True emission a hard error."""needs_f = needs_fstring(full_cmd)has_meta = bool(_SHELL_METACHARS_RE.search(full_cmd))@@ -144,7 +117,6 @@ def _emit_shell_command(indent: str, full_cmd: str, *, allow_shell: bool) -> lisstmt = f"{indent}subprocess.run({f_prefix}{full_cmd!r}, shell=True)"return [warn, stmt]- # Shell-safe argv form.return [f"{indent}subprocess.run(shlex.split({full_cmd!r}), shell=False)"]@@ -159,12 +131,10 @@ def convert_cell_to_python(source: str, *, allow_shell: bool = True) -> str:stripped = line.strip()indent = line[: len(line) - len(line.lstrip())]- # Skip %%captureif stripped.startswith("%%capture"):i += 1continue- # Handle %%file magicif stripped.startswith("%%file "):filename = stripped[7:].strip()file_lines = []@@ -178,7 +148,6 @@ def convert_cell_to_python(source: str, *, allow_shell: bool = True) -> str:result.append(f'{indent} _f.write("""{file_content}""")')continue- # Handle ! shell commandsif stripped.startswith("!"):cmd_lines = [stripped[1:]]while cmd_lines[-1].rstrip().endswith("\\") and i + 1 < len(lines):@@ -308,21 +277,16 @@ def convert_notebook_to_script(content = f.read()source_name = source- # Generate output filenameoutput_filename = filename.replace(".ipynb", ".py")- # Clean up filenameoutput_filename = output_filename.replace("(", "").replace(")", "").replace("-", "_")- # Add output directory if specifiedif output_dir:output_path = os.path.join(output_dir, output_filename)else:output_path = output_filename- # Convertscript = convert_notebook(content, source_name, allow_shell = allow_shell)- # Write outputwith open(output_path, "w", encoding = "utf-8") as f:f.write(script)@@ -349,11 +313,7 @@ Examples:)parser.add_argument("notebooks", nargs = "+", help = "Notebook files or URLs to convert.")parser.add_argument("-o", "--output", dest = "output_dir", default = ".", help = "Output directory.")- # Default True for backwards compatibility: existing Colab notebooks- # routinely use pipes / redirection / interpolation in `!cmd` lines- # and the converted script needs to keep working. Operators who- # convert untrusted notebooks should pass --no-allow-shell to force- # a hard error on every metacharacter-bearing cell.+ # Default True for backwards compat; pass --no-allow-shell for untrusted notebooks.parser.add_argument("--allow-shell",dest = "allow_shell",@@ -371,14 +331,9 @@ Examples:args = parser.parse_args()- # Create output directory if neededos.makedirs(args.output_dir, exist_ok = True)- # SF2: track per-notebook failures so a CI invocation that converts- # 10 notebooks but silently fails on 3 is no longer reported as- # success. Each failure is collected and the loop continues so the- # caller sees the full set; final exit status is 1 if anything- # failed.+ # Track per-notebook failures; continue the loop and exit 1 if any failed.failures: list[tuple[str, str]] = []ok = 0total = len(args.notebooks)diff --git a/scripts/notebook_validator.py b/scripts/notebook_validator.pyindex 74bfaa8d41b..c1be7a63a40 100644--- a/scripts/notebook_validator.py+++ b/scripts/notebook_validator.py@@ -49,12 +49,9 @@ from typing import Any, Iterable, Iteratordef _atomic_write_bytes(path: pathlib.Path, data: bytes) -> None:- """Atomic write helper. See `scripts/scan_packages.py::update_req_file`.-- A crash between `mkstemp` and `os.replace` leaves the prior file- untouched, so a half-downloaded PyPI metadata cache file cannot- poison subsequent runs of the validator.- """+ """Atomic write (see scripts/scan_packages.py::update_req_file). A crash+ between mkstemp and os.replace leaves the prior file intact, so a+ half-downloaded cache file can't poison later runs."""path.parent.mkdir(parents = True, exist_ok = True)dirpath = str(path.parent) or "."fd, tmp_path = tempfile.mkstemp(prefix = ".nb_val.", dir = dirpath)@@ -81,12 +78,10 @@ COLAB_PIP_FREEZE_URL = ()COLAB_FALLBACK_FILE = DATA_DIR / "colab_pip_freeze.gpu.txt"-# Oracle files we snapshot from googlecolab/backend-info. The diff-# subcommand fetches each, compares against the committed snapshot,-# and surfaces NEW / REMOVED / CHANGED entries so upstream Colab base-# image rotations land in CI within ~24h instead of when a notebook-# breaks. Every rule in this validator that resolves against the-# Colab preinstall (R-INST-002/003/004/005) gets earlier signal.+# Oracle files snapshotted from googlecolab/backend-info. The colab-diff+# subcommand surfaces NEW/REMOVED/CHANGED entries so upstream Colab base+# image rotations land in CI within ~24h, giving R-INST-002/003/004/005+# earlier signal.COLAB_ORACLE_FILES: dict[str, str] = {"pip-freeze.gpu.txt": "colab_pip_freeze.gpu.txt","apt-list-gpu.txt": "colab_apt_list.gpu.txt",@@ -145,9 +140,8 @@ class Finding:def iter_notebooks(notebooks_dir: pathlib.Path, include_templates: bool = False) -> Iterator[pathlib.Path]:- """Yield user-facing .ipynb files under nb/ and kaggle/. Pass- include_templates=True to also walk original_template/ (used by the- convert subcommand which doesn't lint install cells)."""+ """Yield user-facing .ipynb files under nb/ and kaggle/.+ include_templates=True also walks original_template/ (for convert)."""subs = ("nb", "kaggle")if include_templates:subs = ("nb", "kaggle", "original_template")@@ -198,11 +192,8 @@ def install_cells(nb: dict[str, Any]) -> list[tuple[int, str]]:return out-# Notebook target environment. The Colab oracle (pip-freeze.gpu.txt) only-# applies to notebooks that actually run on Colab; AMD-Dev-Cloud,-# Kaggle, HuggingFace-Course, and DGX-Spark notebooks have their own-# preinstalled environments and the Colab-vs-cell rules are not-# applicable to them.+# Colab oracle only applies to notebooks that run on Colab; AMD, Kaggle,+# DGX-Spark have their own preinstalls and the Colab-vs-cell rules don't apply.def target_environment(notebook_name: str) -> str:parts = pathlib.PurePath(notebook_name).partsbase = parts[-1] if parts else notebook_name@@ -466,19 +457,12 @@ def constraint_satisfied(version: str, ops: list[tuple[str, str]]) -> bool:def resolved_set(install_cell: str, colab: dict[str, str]) -> dict[str, str]:- """Merge install-cell explicit constraints with Colab pip-freeze. Cell- wins.-- Resolution order per package, when more than one form is present:- 1. Exact `==V` pin in any install line (definitive).- 2. Upper-bound `<=V` constraint (pip picks the highest- allowed; that's V).- 3. Colab pip-freeze fallback.-- The lower-bound `>=V` is intentionally NOT reflected here — a `>=V`- by itself doesn't change the resolved version when a higher- Colab-preinstalled version is already in scope. (R-INST-003 calls- `_install_cell_lower_bound` separately to model that case.)+ """Merge install-cell constraints with Colab pip-freeze (cell wins).++ Resolution order per package: (1) exact `==V` pin, (2) upper-bound `<=V`+ (pip picks the highest allowed = V), (3) Colab fallback. Lower-bound `>=V`+ is intentionally NOT reflected (it doesn't lower an already-higher Colab+ version); R-INST-003 models that via `_install_cell_lower_bound`."""out = dict(colab)pinned: set[str] = set()@@ -543,8 +527,7 @@ def rule_inst_002_no_deps_transitive(v = explicit_pin(sp)if v is None:continue- # Check transitive constraints on a curated short list of pkgs we- # care about (transformers/peft/trl/accelerate/torchao/torchcodec).+ # Check transitive constraints on a curated short list of pkgs.for target in ("tokenizers","torchao",@@ -575,10 +558,9 @@ def rule_inst_002_no_deps_transitive(def _install_cell_lower_bound(install_cell: str, target: str) -> str | None:- """Return the highest LOWER bound that any install line places on `target`,- or None if no constraint is present. Treats `==V` as both lower and upper.- Used by R-INST-003: a `pip install torchao>=0.16.0` line is enough to- satisfy a `torchao>=0.16.0` floor even though it's not a `==` pin."""+ """Return the highest lower bound any install line places on `target`+ (treating `==V` as both bounds), or None. Used by R-INST-003 so a+ `torchao>=0.16.0` line satisfies the floor without a `==` pin."""best: str | None = Nonefor inv in iter_pip_invocations(install_cell):for raw in inv.packages:@@ -652,20 +634,17 @@ def rule_inst_004_torchcodec_torch(def rule_inst_005_transformers_tokenizers(install_cell: str, colab: dict[str, str], file: str, cell_idx: int) -> list[Finding]:- """Fires only when transformers is installed with `--no-deps`. Without- `--no-deps`, pip resolves the correct tokenizers transitively, so the- rule would be a false positive (this is the case for older notebooks- that pin `transformers==4.51.3` but rely on pip's transitive resolver).- The rule targets the exact pattern PR #261b / #264 fixed:- `pip install --no-deps transformers==X` next to a Colab preinstall- `tokenizers` outside transformers's window."""+ """Fires only when transformers is installed with `--no-deps` (otherwise+ pip resolves tokenizers transitively and flagging would be a false+ positive). Targets the PR #261b/#264 pattern: `--no-deps transformers==X`+ next to a Colab `tokenizers` outside transformers's window."""findings: list[Finding] = []res = resolved_set(install_cell, colab)tf = res.get("transformers")tok = res.get("tokenizers")if not tf or tok is None:return findings- # Find the install line that pins transformers and check for --no-deps.+ # Find the transformers pin and check for --no-deps.transformers_line_no_deps = Falsefor inv in iter_pip_invocations(install_cell):for raw in inv.packages:@@ -724,11 +703,9 @@ def rule_inst_006_double_bang(install_cell: str, file: str, cell_idx: int) -> liclass _APIScanner(ast.NodeVisitor):"""Scan user-facing code cells for known deprecated patterns. R-API-001- (`for_training`/`for_inference`) is intentionally absent: those helpers- are still part of the live unsloth surface as of 2026-05; PR #221 removed- the calls cosmetically from Vision notebooks but did not deprecate the- methods. R-API-004 (live API surface diff) catches actual removals- dynamically without us hand-coding them."""+ (`for_training`/`for_inference`) is intentionally absent: those helpers are+ still live as of 2026-05 (PR #221 removed them cosmetically, not as a+ deprecation). R-API-004 catches actual removals dynamically."""def __init__(self, file: str, cell_idx: int):self.file = file@@ -736,14 +713,10 @@ class _APIScanner(ast.NodeVisitor):self.findings: list[Finding] = []def visit_Call(self, node: ast.Call) -> None:- # SFTConfig with suboptimal optim (R-API-003).- # NOTE: PR #221 also stripped `gradient_checkpointing` /- # `gradient_checkpointing_kwargs` from a handful of vision notebooks,- # but those kwargs are still accepted by live TRL (verified against- # trl==0.25.1 in the unsloth workspace) so removing them was- # cosmetic, not a deprecation. We do NOT flag them. R-API-004 (live- # API surface diff in the api subcommand) is the right way to catch- # actual TRL signature drift.+ # SFTConfig with suboptimal optim (R-API-003).+ # NOTE: PR #221 also stripped gradient_checkpointing kwargs from some+ # vision notebooks, but they're still accepted by live TRL (trl==0.25.1)+ # so that was cosmetic. We don't flag them; R-API-004 catches real drift.if isinstance(node.func, ast.Name) and node.func.id == "SFTConfig":for kw in node.keywords:if (@@ -799,13 +772,9 @@ POLICY_CLAUSES_DEFAULT = [def extract_policy_clauses(update_script: pathlib.Path) -> list[tuple[str, re.Pattern[str], Any]]:- """Best-effort: scan update_all_notebooks.py for canonical phrases used by- multiple templates. Falls back to POLICY_CLAUSES_DEFAULT.-- Today we use POLICY_CLAUSES_DEFAULT directly; the regex form is- intentionally permissive so a template-side reword (e.g. comment changes)- doesn't cause false positives. New clauses become 1-line PRs to this list.- """+ """Best-effort scan of update_all_notebooks.py for canonical phrases;+ falls back to POLICY_CLAUSES_DEFAULT (which we use directly today). The+ permissive regexes avoid false positives on template rewords."""return list(POLICY_CLAUSES_DEFAULT)@@ -868,14 +837,9 @@ def cmd_drift(args: argparse.Namespace) -> int:check = False,capture_output = True,)- # SF3: the restore MUST run even on SystemExit / KeyboardInterrupt /- # segfault-propagated exception, otherwise the user's working tree- # silently stays rolled back into the stash. A bare try/finally- # (NOT try/except/finally) preserves the original exception and- # still runs the cleanup. The pre-existing try/except around- # `subprocess.run` of the updater is folded inside the new outer- # try so its early returns still happen, but the stash pop is- # protected.+ # The restore MUST run even on SystemExit/KeyboardInterrupt, else the+ # working tree stays rolled back into the stash. A bare try/finally keeps+ # the original exception while still running the cleanup (stash pop).findings: list[Finding] = []rc: inttry:@@ -920,8 +884,7 @@ def cmd_drift(args: argparse.Namespace) -> int:)rc = 0 if not findings else 1finally:- # Restore the working tree. Both commands MUST run regardless of- # how the try block exited (including SystemExit/KeyboardInterrupt).+ # Restore the working tree (both commands run regardless of exit path).subprocess.run(["git", "-C", str(nbdir), "checkout", "."],check = False,@@ -1004,19 +967,16 @@ def cmd_lint(args: argparse.Namespace) -> int:continuerel = str(path.relative_to(nbdir))env = target_environment(rel)- # The Colab oracle is the source of truth ONLY for Colab notebooks.- # Other targets (amd / kaggle / dgx_spark) have their own runtime- # preinstall sets that aren't tracked here yet, so we apply the- # environment-agnostic rules and skip the Colab-specific ones.+ # Colab oracle applies only to Colab notebooks; other targets get the+ # environment-agnostic rules only (their preinstalls aren't tracked).oracle = colab if env == "colab" else {}cells = install_cells(nb)- # Per-cell rules: forbid-pattern checks scoped to a single line.+ # Per-cell forbid-pattern checks.for idx, cell in cells:findings += rule_inst_001_git_plus(cell, rel, idx)findings += rule_inst_006_double_bang(cell, rel, idx)- # Whole-notebook rules: a notebook's install steps are sometimes split- # across multiple cells (initial install + post-install bumps). Merge- # all install cells before resolving compat against Colab.+ # Whole-notebook rules: install steps may span multiple cells, so merge+ # before resolving compat against Colab.merged = "\n".join(c for _, c in cells)if env == "colab" and merged:first_cell = cells[0][0] if cells else None@@ -1147,8 +1107,7 @@ def _parse_apt_lines(text: str) -> dict[str, str]:def _parse_os_lines(text: str) -> dict[str, str]:- """Free-form `<tool> <version>` lines. Skip comments. The key is the- first token lower-cased; the value is the rest of the line."""+ """Free-form `<tool> <version>` lines -> {tool_lower: rest}."""out: dict[str, str] = {}for line in text.splitlines():line = line.strip()@@ -1185,10 +1144,9 @@ def _diff_oracle(def cmd_colab_diff(args: argparse.Namespace) -> int:- """Fetch every Colab oracle file in COLAB_ORACLE_FILES, diff against- the committed snapshot, and print NEW / REMOVED / CHANGED. Advisory- by default (rc=0); --strict promotes any diff to rc=1 so the daily- cron can fail loudly when upstream rotates."""+ """Diff each Colab oracle file against its committed snapshot and print+ NEW/REMOVED/CHANGED. Advisory (rc=0) by default; --strict makes any diff+ rc=1 so the daily cron fails loudly on upstream rotation."""snapshot_dir = pathlib.Path(args.snapshot_dir).resolve()any_diff = Falsefor upstream_name, snapshot_name in COLAB_ORACLE_FILES.items():diff --git a/scripts/run_ruff_format.py b/scripts/run_ruff_format.pyindex 2f0a6c6bba1..817565eddf7 100755--- a/scripts/run_ruff_format.py+++ b/scripts/run_ruff_format.py@@ -19,10 +19,8 @@ def main(argv: list[str]) -> int:spacing_script = HERE / "enforce_kwargs_spacing.py"- # Pre-ruff: normalize def-signature trailing commas (>=3 params with a- # default -> one-per-line; everything else collapsible) and strip the magic- # comma from a short multi-line assert, so ruff wraps signatures accordingly- # and joins the assert back onto one line.+ # Pre-ruff: normalize def-signature magic commas and strip the magic comma+ # from short multi-line asserts so ruff wraps/joins accordingly.pre_cmd = [sys.executable, str(spacing_script), "--pre", *files]pre_proc = subprocess.run(pre_cmd)if pre_proc.returncode != 0:diff --git a/scripts/scan_npm_packages.py b/scripts/scan_npm_packages.pyindex 14a3cd65602..fe90afa7e69 100644--- a/scripts/scan_npm_packages.py+++ b/scripts/scan_npm_packages.py@@ -7,73 +7,32 @@"""scan_npm_packages.py -- npm-side content scanner.-Counterpart to scripts/scan_packages.py for the pip ecosystem. Reads+npm counterpart to scripts/scan_packages.py. Readsstudio/frontend/package-lock.json, downloads each resolved tarballDIRECTLY from registry.npmjs.org (never via `npm install` -- no-lifecycle scripts ever run), verifies the lockfile integrity hash,-unpacks each tarball into a sandboxed temp dir behind size / count /-path-escape / symlink guards, and pattern-scans the extracted file-contents for the signatures common to npm supply-chain attacks:-- - Lifecycle (preinstall / install / postinstall / prepare) scripts- in any package.json that fetch + execute external code.- - C2 / exfiltration hosts (getsession.org, AWS IMDS endpoints,- Kubernetes ServiceAccount token paths, GitHub Actions OIDC,- HashiCorp Vault endpoints).- - Credential-stealing references (~/.npmrc, ~/.aws/credentials,- GITHUB_TOKEN / NPM_TOKEN in JS sources).- - Known IOC filenames from public advisories- (router_init.js, tanstack_runner.js, router_runtime.js).- - Obfuscation shapes (large single JS in package root with a low- whitespace ratio + Function/eval against a base64-decoded blob).--Safety stance-=============--This script ingests attacker-controlled archives. Every parse path-assumes the worst:-- 1. Downloads ONLY from `registry.npmjs.org`. Any tarball URL with a- different hostname is refused without fetching.- 2. Tarball download is size-capped (HARD_MAX_TARBALL_BYTES default- 64 MiB). HEAD-style probe via the Content-Length response header- plus a chunked read that aborts on overflow.+lifecycle scripts run), verifies the lockfile integrity hash, unpacks+each into a sandboxed temp dir behind size/count/path-escape/symlink+guards, and pattern-scans extracted contents for npm supply-chain+attack signatures: malicious lifecycle scripts, C2 / exfil hosts,+credential-stealing references, known IOC filenames, and obfuscation+shapes.++Safety stance (ingests attacker-controlled archives; assumes worst):+ 1. Downloads ONLY from registry.npmjs.org; other hosts refused.+ 2. Tarball download size-capped via Content-Length probe + chunked+ read that aborts on overflow.3. SHA-512 integrity verified against the lockfile entry BEFORE the- tarball is even opened. A mismatch aborts that package -- the- scanner does not "fall back" to the registry-published hash.- 4. tar extraction goes through `safe_extract`:- - rejects symbolic links (`SYMTYPE`, `LNKTYPE`)- - rejects absolute paths, `..` traversal, paths outside the- extract root after resolution- - rejects character / block / FIFO devices- - per-file uncompressed size cap (HARD_MAX_FILE_BYTES, default- 8 MiB) AND cumulative cap (HARD_MAX_TOTAL_BYTES, default- 128 MiB) AND member-count cap (HARD_MAX_MEMBERS, default- 50_000)- - tar reads happen via `tarfile.open(mode='r|gz')` streaming- so an oversized file is detected before write- 5. NOTHING from the extracted tree is ever executed. Files are read- as raw bytes, decoded with `errors='replace'`, and grepped. We- never call `node`, `eval`, `compile`, `subprocess.run`,- `os.system`, or anything that would touch the tarball's- declared scripts.- 6. Tempdir is created with `tempfile.mkdtemp(prefix='npm-scan-')`,- fully resolved with .resolve(), and registered with atexit to be- wiped on every termination path.- 7. Stdlib only. No third-party deps -- adding one would itself be a- supply-chain liability.--Exit codes-==========-- 0 no findings of severity HIGH or higher- 1 one or more HIGH/CRITICAL findings (or pre-scan structural- anomalies -- non-registry resolved URL, missing integrity)- 2 internal error (lockfile missing, integrity mismatch on- download, malformed tarball, etc.)--The script is meant to be run in CI on every PR that touches-package-lock.json and on a nightly schedule.+ tarball is opened; mismatch aborts that package (no fallback).+ 4. tar extraction via `safe_extract`: rejects symlinks, absolute /+ `..` paths, device files; enforces per-file, cumulative, and+ member-count caps; streams (`r|gz`) so oversize is caught early.+ 5. NOTHING extracted is executed -- files are read as bytes and+ grepped only.+ 6. Tempdir resolved and atexit-wiped on every termination path.+ 7. Stdlib only (a dep would be a supply-chain liability itself).++Exit codes: 0 = no HIGH+ findings; 1 = HIGH/CRITICAL or pre-scan+structural anomaly; 2 = internal error. Run in CI per-PR and nightly."""from __future__ import annotations@@ -565,12 +524,9 @@ CRED_HOST_NEEDS_CONTEXT: tuple[tuple[str, str], ...] = (),)-# Credentials a frontend package should NEVER need to read. Bare-# substring match is too noisy (object-treeify ships a `docker` dev-# script that mounts ~/.npmrc -- legitimate dev tooling, never run-# at install time). We instead surface these only when they appear-# inside a LIFECYCLE script (preinstall / install / postinstall /-# prepare), which is the only path that runs automatically on+# Credentials a frontend package should never read. Bare substring+# match is too noisy (legit dev tooling mounts ~/.npmrc), so we flag+# these only inside lifecycle scripts -- the only auto-run path on# `npm ci`. See `scan_package_json` below.CRED_PATH_SUBSTRINGS: tuple[tuple[str, str], ...] = (("/.npmrc", "npm credentials file"),@@ -603,9 +559,8 @@ _JS_FETCH_EVAL = re.compile(""",)-# `process.env.GITHUB_TOKEN` / `NPM_TOKEN` / `AWS_*` access in-# top-level / install-time code is suspicious. We also catch-# `os.environ["GITHUB_TOKEN"]` for the rare Python-in-npm postinstall.+# Token env access in install-time code; also catches os.environ[...]+# for the rare Python-in-npm postinstall._JS_ENV_TOKEN = re.compile(r"""(process\.env\.|os\.environ\[?['"])(?:GITHUB_TOKEN | GH_TOKEN | NPM_TOKEN | NODE_AUTH_TOKEN@@ -616,11 +571,9 @@ _JS_ENV_TOKEN = re.compile(re.VERBOSE,)-# Suspicious lifecycle-script payloads. Anything in a package.json-# `scripts` field that wgets/curls an external resource and executes-# it. We do NOT block ALL curl/wget in scripts (some legit packages-# fetch test fixtures into devDependencies), but we DO block the-# fetch+exec chain.+# Lifecycle-script fetch+exec chain: curl/wget an external resource+# and run it. Bare curl/wget is allowed (legit fixture fetches); only+# the fetch+exec chain is blocked._LIFECYCLE_FETCH_EXEC = re.compile(r"""(?xs)(?:curl|wget|fetch|http\.get|axios\.get)\s+ # fetch verb@@ -634,9 +587,8 @@ _LIFECYCLE_FETCH_EXEC = re.compile(""",)-# Obfuscation: large JS file that is mostly one line of base64-ish-# blob with a Function() / eval() bookend. Tuned against the-# router_init.js shape (2.3 MB obfuscated single-blob).+# Obfuscation: large single-line base64-ish blob behind Function()/+# eval(). Tuned against the router_init.js shape (2.3 MB blob)._OBFUSC_BLOB = re.compile(r"""(?xs)(?:Function|eval)\s*\(\s*['"`]?@@ -653,11 +605,9 @@ _OBFUSC_BLOB = re.compile(def parse_lockfile(path: Path) -> tuple[list[PackageEntry], list[Finding]]:"""Return (entries, structural_findings).- Structural findings here are HIGH-severity refusals that should- short-circuit the scan -- a lockfile with non-registry resolved- URLs is itself a finding (covered by scripts/lockfile_supply_chain- _audit.py in detail; we surface a summary here so this scanner is- standalone-runnable).+ Structural findings are HIGH-severity refusals that short-circuit+ the scan (e.g. non-registry resolved URLs). A summary is surfaced+ here so this scanner is standalone-runnable."""entries: list[PackageEntry] = []findings: list[Finding] = []@@ -701,9 +651,8 @@ def parse_lockfile(path: Path) -> tuple[list[PackageEntry], list[Finding]]:resolved = entry.get("resolved")if not resolved:continue- # Strict registry origin check. lockfile_supply_chain_audit- # already catches this; double-defend here so this scanner- # cannot be tricked into fetching from an attacker-chosen URL.+ # Strict registry origin check so this scanner can't be tricked+ # into fetching from an attacker-chosen URL.parsed = urllib.parse.urlparse(resolved)if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:findings.append(@@ -775,16 +724,12 @@ def download_tarball(timeout: float = HARD_HTTP_TIMEOUT_S,max_bytes: int = HARD_MAX_TARBALL_BYTES,) -> tuple[Path, str | None]:- """Stream-download entry.resolved to dest. Verify SRI integrity.+ """Stream-download entry.resolved to dest and verify SRI integrity.- Returns (downloaded_path, error_or_none). On any error the- returned path may not exist. Network access is restricted to- https://{ALLOWED_DOWNLOAD_HOST}/ -- the caller passes a Request- we already validated.+ Returns (downloaded_path, error_or_none); on error the path may not+ exist. Network access is restricted to ALLOWED_DOWNLOAD_HOST."""- # Re-assert hostname; the entry was validated at parse time but a- # defence-in-depth check here means a future refactor cannot- # accidentally bypass it.+ # Re-assert hostname (defence-in-depth against a future refactor).parsed = urllib.parse.urlparse(entry.resolved)if parsed.scheme != "https" or parsed.hostname != ALLOWED_DOWNLOAD_HOST:return dest, (f"refused download from non-allowlisted URL {entry.resolved!r}")@@ -873,8 +818,7 @@ def safe_extract(total = 0count = 0try:- # Open in streaming mode so we never seek backwards in the- # input. `r|gz` rejects malformed gzip frames immediately.+ # Streaming mode (no backward seeks); `r|gz` rejects bad gzip.with tarfile.open(tarball_path, mode = "r|gz") as tf:for member in tf:count += 1@@ -889,9 +833,8 @@ def safe_extract(return f"refused link member {name!r} (sym/lnk)"if member.isdev() or member.isfifo():return f"refused special member {name!r}"- # Cumulative cap is checked against DECLARED size up- # front to short-circuit obvious bombs without reading- # the body.+ # Check declared size up front to short-circuit bombs+ # without reading the body.declared = max(member.size, 0)if declared > HARD_MAX_BINARY_FILE_BYTES:return (@@ -903,9 +846,8 @@ def safe_extract(f"cumulative bytes {total + declared} > cap "f"{max_total_bytes} at {name!r}")- # Strip leading "package/" -- the npm convention. We do- # NOT trust npm to be right, so we explicitly resolve- # the destination and refuse anything that escapes.+ # Resolve destination and refuse anything escaping root+ # (don't trust the npm "package/" convention).dest = extract_root / nameif not _is_within(extract_root, dest):return f"refused escape: {name!r} resolved outside root"@@ -919,10 +861,8 @@ def safe_extract(src = tf.extractfile(member)if src is None:continue- # Sniff first 16 bytes to classify text vs binary.- # Text-cap members get the tight 16 MiB limit; binary- # members (executables, .node, .wasm, native libs)- # get the generous binary cap. We bound BOTH cases.+ # Sniff first 16 bytes to classify text vs binary;+ # each gets its own cap (both are bounded).header = src.read(16)is_binary = _looks_binary(name, header)file_cap = HARD_MAX_BINARY_FILE_BYTES if is_binary else HARD_MAX_TEXT_FILE_BYTES@@ -941,8 +881,7 @@ def safe_extract(f"({'binary' if is_binary else 'text'})")total += len(data)- # Write with restrictive mode (rw-r--r--) so even if- # someone runs the extract dir nothing is executable.+ # Restrictive mode (rw-r--r--): nothing executable.with open(dest, "wb") as out:out.write(data)os.chmod(dest, 0o644)@@ -1008,10 +947,8 @@ def scan_package_json(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:),))- # Credential file paths inside a lifecycle script are- # exfiltration prep -- npm runs these scripts automatically- # on `npm ci`. Manual `scripts.*` entries (like a `docker`- # dev script) are out of scope: npm does not run them.+ # Cred file paths in a lifecycle script are exfil prep (npm+ # auto-runs these on `npm ci`); manual scripts are out of scope.for path_substr, why in CRED_PATH_SUBSTRINGS:if path_substr in body:findings.append(@@ -1071,20 +1008,12 @@ def scan_package_json(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:def _host_in_outbound_context(text: str, host: str) -> bool:- """True if `host` appears in a way consistent with an outbound call.-- A bare `"169.254.169.254"` array literal (defensive blocklist) is- safe; a `fetch("http://169.254.169.254/...")` is not. The signal- is co-occurrence with either an HTTP URL scheme or a fetch verb- within a short window.-- A defensive blocklist looks like:- const CLOUD_METADATA_IPS = ["169.254.169.254", "169.254.170.2"];- An exfil call looks like:- fetch("http://169.254.169.254/latest/meta-data/...")- http.request({ host: "169.254.169.254", path: "/..." })+ """True if `host` appears consistent with an outbound call.++ A bare array literal (defensive blocklist) is safe; co-occurrence+ with an HTTP URL scheme or a fetch verb in a short window is not."""- # Esc for use in a regex (IPs contain dots).+ # Escape for regex (IPs contain dots).host_re = re.escape(host)# 1. URL form: http://host or https://host or //host/ or //host"url_form = re.compile(@@ -1127,8 +1056,7 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:))- # Credential surfaces. Tier 1: hosts with no legitimate use,- # bare substring is enough.+ # Cred surfaces, tier 1: hosts with no legit use; bare substring.for needle, why in CRED_HOST_ALWAYS_BAD:if needle in text:findings.append(@@ -1145,8 +1073,8 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:))- # Credential surfaces. Tier 2: hosts that do appear in defensive- # code; require co-occurrence with a fetch verb or URL prefix.+ # Cred surfaces, tier 2: hosts that appear in defensive code too;+ # require co-occurrence with a fetch verb or URL prefix.for needle, why in CRED_HOST_NEEDS_CONTEXT:if needle in text and _host_in_outbound_context(text, needle):findings.append(@@ -1164,11 +1092,8 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:))- # Credential PATHS are deliberately not scanned here; they have- # too high a false-positive rate at file scope (defensive code,- # docker mounts, AWS SDK docs strings). `scan_package_json`- # catches the malicious case -- credential paths inside a- # lifecycle script run automatically on `npm ci`.+ # Credential PATHS aren't scanned here (too many FPs at file+ # scope); scan_package_json catches them inside lifecycle scripts.# JS-specific regex.if _JS_FETCH_EVAL.search(text):@@ -1211,9 +1136,8 @@ def scan_text_blob(pkg: PackageEntry, rel: str, text: str) -> list[Finding]:return findings-# Filename suffix decides which scanners run. We deliberately treat-# *.cjs/*.mjs/*.ts the same as *.js -- attackers use whichever-# extension the consumer's bundler / loader resolves.+# Filename suffix decides which scanners run; .cjs/.mjs/.ts are+# treated like .js (attackers use whichever the loader resolves)._TEXT_SUFFIXES = (".js",".mjs",@@ -1241,12 +1165,9 @@ def scan_extracted_tree(pkg: PackageEntry, root: Path) -> list[Finding]:rel = path.relative_to(root).as_posix()lower = rel.lower()if not lower.endswith(_TEXT_SUFFIXES):- # Skip native binaries entirely -- regex over compiled- # machine code is just noise (false positives in WASM- # opcodes, .node BSS segments, image pixel data). Use- # content-magic detection so extensionless executables- # (eg `package/biome`) and versioned shared libraries- # are also skipped.+ # Skip native binaries (regex over machine code is noise);+ # content-magic detection also skips extensionless+ # executables and versioned shared libraries.try:if path.stat().st_size > HARD_MAX_TEXT_FILE_BYTES:continue@@ -1288,12 +1209,12 @@ def scan_extracted_tree(pkg: PackageEntry, root: Path) -> list[Finding]:def scan_one(pkg: PackageEntry, workspace: Path) -> tuple[list[Finding], str | None]:- """Download + extract + scan a single package. Cleans up its dir.+ """Download + extract + scan a single package; cleans up its dir.Returns (findings, error). `error` is non-None only on hard- failures (download error, integrity mismatch, malformed tarball);- on a clean run with findings the error is None and the caller- decides exit code based on severity.+ failures (download, integrity mismatch, malformed tarball); on a+ clean run with findings, error is None and the caller decides the+ exit code from severity."""pkg_dir = workspace / f"{pkg.name.replace('/', '_')}-{pkg.version}"pkg_dir.mkdir(parents = True, exist_ok = True)diff --git a/scripts/scan_packages.py b/scripts/scan_packages.pyindex d753a17e496..861b35617bb 100644--- a/scripts/scan_packages.py+++ b/scripts/scan_packages.py@@ -56,27 +56,22 @@ from dataclasses import dataclass, fieldfrom pathlib import Path-# ---------------------------------------------------------------------------# Severity-# ---------------------------------------------------------------------------CRITICAL = "CRITICAL"HIGH = "HIGH"MEDIUM = "MEDIUM"SEVERITY_ORDER = {CRITICAL: 0, HIGH: 1, MEDIUM: 2}-# Hard pin-blocks for publicly confirmed malicious PyPI versions.-# Source: Socket.dev 2026-05-12 disclosure (Mini Shai-Hulud May-12 wave) and-# earlier Semgrep / Endor reports for the `lightning` entries.+# Hard pin-blocks for confirmed malicious PyPI versions (Socket.dev 2026-05-12+# Mini Shai-Hulud wave; earlier Semgrep/Endor reports for `lightning`).BLOCKED_PYPI_VERSIONS: dict[str, set[str]] = {"guardrails-ai": {"0.10.1"},"mistralai": {"2.4.6"},"lightning": {"2.6.2", "2.6.3"},}-# ---------------------------------------------------------------------------# Pattern definitions-# ---------------------------------------------------------------------------# Subprocess / OS exec patternsRE_SUBPROCESS = re.compile(@@ -312,10 +307,8 @@ RE_C2_POLLING = re.compile(re.DOTALL,)-# Developer-tool persistence hooks. The PyTorch Lightning 2.6.x compromise-# planted SessionStart hooks into Claude Code, VS Code tasks, and Cursor-# settings so the payload re-attached on every editor open. Catches any-# package writing into a known dev-tool config that supports auto-run.+# Developer-tool persistence hooks. Lightning 2.6.x planted SessionStart hooks+# into Claude Code / VS Code / Cursor so the payload re-attached on editor open.RE_DEV_TOOL_HIJACK = re.compile(r"\.claude/settings\.json"r"|\.cursor/.*hooks"@@ -326,9 +319,8 @@ RE_DEV_TOOL_HIJACK = re.compile(r"|\bautomator\b.*\.workflow\b",)-# Hard-coded credential / API-token regexes embedded in source. Packages-# that ship regexes for OTHER people's secrets are nearly always-# stealers (litellm 1.82.7, elementary-data 0.23.3, Shai-Hulud).+# Hard-coded credential / API-token regexes embedded in source. Packages that+# ship regexes for OTHER people's secrets are nearly always stealers.RE_TOKEN_REGEX = re.compile(r"\bgh[psoru]_[A-Za-z0-9_]{20,}" # GitHub PAT/OAuth/etc.r"|\bgithub_pat_[A-Za-z0-9_]{20,}"@@ -342,20 +334,16 @@ RE_TOKEN_REGEX = re.compile(r"|\bglpat-[0-9A-Za-z_-]{20,}", # GitLab PAT)-# Mini Shai-Hulud May-12 2026 wave indicators. The dropper artifact name-# `transformers.pyz` is high-confidence (no legit PyPI package ships a `.pyz`-# named after `transformers`); the host + slogans are CRITICAL.+# Mini Shai-Hulud May-12 2026 wave indicators. `transformers.pyz` dropper name+# is high-confidence; the host + slogans are CRITICAL.RE_MAY12_IOC = re.compile(r"(git-tanstack\.com|/tmp/transformers\.pyz|transformers\.pyz"r"|With Love TeamPCP|We've been online over 2 hours)",re.IGNORECASE,)-# JavaScript-side obfuscation. The npm chalk/debug compromise and the-# Lightning router_runtime.js use the same minifier-style hex-var name-# pattern; a bundle full of `_0x1f2e3d` identifiers is a near-universal-# tell for a malicious npm payload (and very rare in legit minified code-# that ships in PyPI wheels).+# JavaScript-side obfuscation. A bundle full of `_0x1f2e3d` hex-var identifiers+# is a near-universal tell for a malicious npm payload, rare in legit wheels.RE_JS_OBFUSCATION = re.compile(r"_0x[a-f0-9]{4,6}\s*=\s*function"r"|var\s+_0x[a-f0-9]{4,6}\b"@@ -363,9 +351,8 @@ RE_JS_OBFUSCATION = re.compile(r"|String\.fromCharCode\s*\(\s*\d+\s*(?:,\s*\d+\s*){10,}\)",)-# Web3 / wallet-hijack pattern. The Qix npm phish overrode fetch /-# XMLHttpRequest and attached a `window.ethereum` listener that-# Levenshtein-swapped recipient addresses on the way to the network.+# Web3 / wallet-hijack pattern. The Qix npm phish overrode fetch/XMLHttpRequest+# and swapped recipient addresses via a `window.ethereum` listener.RE_WEB3_HIJACK = re.compile(r"\bwindow\.ethereum\b"r"|\bweb3\.eth\.\w+\s*\("@@ -374,11 +361,9 @@ RE_WEB3_HIJACK = re.compile(r"|TronWeb|solanaWeb3",)-# Self-propagating supply-chain worms (Shai-Hulud, ForceMemo) plant-# their own GitHub workflow in every repo they can reach, and lean on-# trufflehog/gitleaks for credential discovery. The combo of any of-# these strings inside a *package payload* is overwhelming evidence of-# repo-takeover intent.+# Self-propagating worms (Shai-Hulud, ForceMemo) plant their own GitHub workflow+# in every repo they reach and use trufflehog/gitleaks for credential discovery.+# Any of these strings in a package payload is strong repo-takeover evidence.RE_WORKFLOW_INJECT = re.compile(r"\.github/workflows/[^\"\']*\.ya?ml"r"|\btrufflehog\b|\bgitleaks\b"@@ -388,9 +373,8 @@ RE_WORKFLOW_INJECT = re.compile(re.IGNORECASE | re.DOTALL,)-# Shell-side patterns specific to install.sh / postinstall scripts that-# pipe remote code into a shell. `curl ... | sh` and friends are the-# canonical npm postinstall dropper.+# install.sh / postinstall scripts piping remote code into a shell.+# `curl ... | sh` is the canonical npm postinstall dropper.RE_SHELL_DROPPER = re.compile(r"\bcurl\b[^\n|]*\|\s*(?:sh|bash|zsh)\b"r"|\bwget\b[^\n|]*-O-\s*\|\s*(?:sh|bash|zsh)\b"@@ -400,9 +384,6 @@ RE_SHELL_DROPPER = re.compile()-# ----------------------------------------------------------------------------# Finding dataclass-# ---------------------------------------------------------------------------@dataclassclass Finding:severity: str@@ -412,9 +393,7 @@ class Finding:evidence: str = ""-# ---------------------------------------------------------------------------# Checkers-# ---------------------------------------------------------------------------def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:@@ -425,7 +404,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:"""findings = []- # Only care about .pth files that have import lines (executable)+ # Only .pth files with import lines are executableimport_lines = [line for line in content.splitlines() if RE_PTH_IMPORT.match(line)]if not import_lines:return findings # Pure path entries, inert@@ -470,7 +449,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:))- # Large base64 blob (special handling for blob size)+ # Large base64 blobif RE_LARGE_BLOB.search(content):blob = RE_LARGE_BLOB.search(content).group()findings.append(@@ -483,7 +462,7 @@ def check_pth_file(content: str, filename: str, package: str) -> list[Finding]:))- # Catch-all: any import line at all in .pth (if nothing else triggered)+ # Catch-all: any import line in .pth if nothing else triggeredif not findings and import_lines:evidence = "\n".join(import_lines[:5])if len(import_lines) > 5:@@ -521,7 +500,7 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:is_setup = basename in ("setup.py", "setup.cfg")is_init = basename == "__init__.py"- # Pre-compute all pattern matches+ # Pre-compute pattern matcheshas_network = bool(RE_NETWORK.search(content))has_subprocess = bool(RE_SUBPROCESS.search(content))has_base64 = bool(RE_BASE64.search(content))@@ -546,9 +525,7 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:has_c2_polling = bool(RE_C2_POLLING.search(content))has_may12_ioc = bool(RE_MAY12_IOC.search(content))- # ---------------------------------------------------------------# CRITICAL: combination patterns that strongly indicate malice- # ---------------------------------------------------------------# base64 decode + subprocess execution (staged payload)if has_base64 and has_subprocess:@@ -740,9 +717,7 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:))- # ---------------------------------------------------------------# HIGH: single strong signals or weaker combinations- # ---------------------------------------------------------------# Obfuscated payload: base64 + exec/eval + large blobif has_base64 and has_exec_eval and has_blob:@@ -879,9 +854,7 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:))- # ---------------------------------------------------------------# MEDIUM: standalone signals (informational, may be legitimate)- # ---------------------------------------------------------------# base64 + exec/eval without blobif has_base64 and has_exec_eval and not has_blob:@@ -978,23 +951,18 @@ def _extract_evidence(return " | ".join(matches) if matches else ""-# ---------------------------------------------------------------------------# Non-Python checkers-# ----------------------------------------------------------------------------# Several recent PyPI compromises (PyTorch Lightning 2.6.x, ForceMemo)-# carried the active payload in a bundled .js / .sh / workflow yaml so-# the Python imports looked clean on first glance. These checkers scan-# those file types when they appear inside a Python wheel/sdist.+# Recent PyPI compromises (Lightning 2.6.x, ForceMemo) carried the payload in a+# bundled .js / .sh / workflow yaml so the Python imports looked clean. These+# checkers scan those file types when they appear inside a wheel/sdist.def check_js_file(content: str, filename: str, package: str) -> list[Finding]:"""Run JS-side checks. Triggered by .js / .mjs / .cjs / .ts."""findings = []- # A JS file *inside a Python wheel* that's larger than 100 KB is- # itself anomalous (legit Python packages don't ship hand-written- # JS bundles). Combined with ANY of the other JS heuristics it is- # CRITICAL; standalone it is HIGH.+ # A >100 KB JS file inside a Python wheel is anomalous: CRITICAL combined+ # with any other JS heuristic, HIGH standalone.is_large = len(content) > 100 * 1024has_obf = bool(RE_JS_OBFUSCATION.search(content))has_web3 = bool(RE_WEB3_HIJACK.search(content))@@ -1119,10 +1087,8 @@ def check_shell_file(content: str, filename: str, package: str) -> list[Finding]def check_workflow_file(content: str, filename: str, package: str) -> list[Finding]:"""Run GitHub-Actions workflow checks. Triggered by .github/workflows/*.yml."""findings = []- # A GitHub workflow file inside a *PyPI package* is itself- # suspicious (Shai-Hulud's whole MO is to plant `shai-hulud.yml`- # in every repo it can write to). Anything matching the workflow- # injection signature gets flagged CRITICAL.+ # A workflow file inside a PyPI package is suspicious (Shai-Hulud plants+ # `shai-hulud.yml` everywhere); injection-signature matches are CRITICAL.if RE_WORKFLOW_INJECT.search(content):findings.append(Finding(@@ -1166,15 +1132,11 @@ def check_workflow_file(content: str, filename: str, package: str) -> list[Findireturn findings-# ---------------------------------------------------------------------------# Archive handling-# ---------------------------------------------------------------------------# Tarbomb caps, mirrored from scripts/scan_npm_packages.py::safe_extract.-# Refuses zip-of-death / tar-of-death archives so a hostile sdist or-# wheel cannot exhaust memory or fill the temp dir before content-# scanning even starts. Keep these constants in sync with the npm side;-# we duplicate rather than import to keep `scan_packages.py` standalone.+# Refuses zip/tar-of-death so a hostile archive cannot exhaust memory before+# scanning. Keep in sync with the npm side; duplicated to stay standalone.HARD_MAX_FILE_BYTES = 64 * 1024 * 1024 # 64 MiB per memberHARD_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB cumulativeHARD_MAX_MEMBERS = 50_000 # entries per archive@@ -1183,11 +1145,8 @@ HARD_MAX_MEMBERS = 50_000 # entries per archivedef _refuse_unsafe_member_name(name: str) -> str | None:"""Return a refusal reason for a member name, or None if safe.- Mirrors `scan_npm_packages.py::safe_extract` semantics: no absolute- paths, no `..` traversal segments. The caller is responsible for- checking the resolved path lands inside the extract root, but for- iter_archive_files we never write to disk so the name-shape check- plus the in-memory size cap is sufficient.+ Mirrors `safe_extract`: no absolute paths, no `..` traversal. We never write+ to disk, so the name-shape check plus the in-memory size cap is sufficient."""if name.startswith("/") or ".." in Path(name).parts:return f"unsafe member name {name!r}"@@ -1197,9 +1156,8 @@ def _refuse_unsafe_member_name(name: str) -> str | None:def iter_archive_files(archive_path: str):"""Yield (filename, text_content) for every file in a wheel/sdist.- Streams members with size + count caps applied at the member level- so a tarbomb / zipbomb cannot blow up the scanner's memory budget.- On cap breach we emit a `[WARN]` log and short-circuit the archive.+ Streams members with per-member size + count caps so a tarbomb/zipbomb can't+ blow the memory budget. On cap breach, emits a `[WARN]` and short-circuits."""path = Path(archive_path)@@ -1225,7 +1183,7 @@ def iter_archive_files(archive_path: str):file = sys.stderr,)continue- # Declared (uncompressed) size cap.+ # Declared (uncompressed) size capif info.file_size > HARD_MAX_FILE_BYTES:print(f" [WARN] {path.name}: skipped {info.filename!r} "@@ -1262,9 +1220,8 @@ def iter_archive_files(archive_path: str):file = sys.stderr,)return- # Refuse symlinks / hardlinks / devices outright -- the- # scanner never writes them anyway, but tar parsers- # have historically dereferenced them on extract.+ # Refuse symlinks/hardlinks/devices: tar parsers have+ # historically dereferenced them on extract.if member.issym() or member.islnk():print(f" [WARN] {path.name}: refused link member " f"{member.name!r}",@@ -1305,8 +1262,7 @@ def iter_archive_files(archive_path: str):f = tf.extractfile(member)if f is None:continue- # Bound the read so a tar header that lies about- # size cannot OOM us.+ # Bound the read: a tar header may lie about sizedata = f.read(HARD_MAX_FILE_BYTES + 1)if len(data) > HARD_MAX_FILE_BYTES:print(@@ -1327,11 +1283,9 @@ def iter_archive_files(archive_path: str):def scan_archive(archive_path: str, package: str) -> list[Finding]:"""Scan all files in an archive for malicious patterns.- A corrupted archive container (truncated wheel, bad gzip header,- etc.) used to be silently skipped by an ``except Exception: continue``- inside ``iter_archive_files``. Per the silent-failure hardening- (SF1) it now emits a CRITICAL ``archive_corrupted`` finding so the- main loop counts and surfaces it rather than reporting "0 findings".+ A corrupted archive container (truncated wheel, bad gzip header, etc.) emits+ a CRITICAL ``archive_corrupted`` finding rather than being silently skipped+ and reported as "0 findings" (silent-failure hardening SF1)."""findings: list[Finding] = []try:@@ -1342,22 +1296,17 @@ def scan_archive(archive_path: str, package: str) -> list[Finding]:elif lower.endswith(".py"):findings.extend(check_py_file(content, filename, package))elif lower.endswith((".js", ".mjs", ".cjs", ".ts")):- # Lightning 2.6.x hid its real payload in a 14.8 MB- # router_runtime.js inside a Python wheel. Without this- # branch we'd have only seen the small Python loader.+ # Lightning 2.6.x hid its payload in a 14.8 MB router_runtime.js;+ # without this branch we'd only see the small Python loader.findings.extend(check_js_file(content, filename, package))elif lower.endswith((".sh", ".bash")):findings.extend(check_shell_file(content, filename, package))elif "/.github/workflows/" in lower and lower.endswith((".yml", ".yaml")):- # Shai-Hulud / ForceMemo plant their own GHA workflow.- # A workflow file inside a *PyPI package* is on its own- # already a yellow flag; pattern-match the worm signatures.+ # Shai-Hulud/ForceMemo plant their own GHA workflowfindings.extend(check_workflow_file(content, filename, package))except (zipfile.BadZipFile, tarfile.TarError, EOFError, OSError) as exc:- # The archive cannot be opened or is structurally broken. A- # benign wheel/sdist always opens; a malformed one is either a- # transport corruption (treat as scan failure) or a deliberate- # attempt to bypass scanners that swallow archive errors.+ # Archive cannot be opened / is structurally broken: either transport+ # corruption or a deliberate attempt to bypass error-swallowing scanners.findings.append(Finding(CRITICAL,@@ -1370,9 +1319,7 @@ def scan_archive(archive_path: str, package: str) -> list[Finding]:return findings-# ---------------------------------------------------------------------------# Download packages-# ---------------------------------------------------------------------------_RE_PYPI_SPEC_VERSION = re.compile(r"==\s*([A-Za-z0-9_.\-+!]+)")@@ -1382,10 +1329,8 @@ def _check_blocked_pypi_versions(specs: list[str]) -> tuple[list[str], list[Find"""Filter ``specs`` against ``BLOCKED_PYPI_VERSIONS``.Returns ``(safe_specs, findings)``. Each blocked spec emits a CRITICAL- ``Finding`` and is removed from the returned spec list so the caller- never fetches the malicious tarball. Specs without an ``==X.Y.Z`` pin- pass through unchanged -- pip will resolve them at download time and- the existing scanners will catch the payload via the IOC regexes.+ ``Finding`` and is dropped so the malicious tarball is never fetched. Specs+ without an ``==X.Y.Z`` pin pass through; the IOC regexes catch them later."""safe: list[str] = []findings: list[Finding] = []@@ -1407,7 +1352,7 @@ def _check_blocked_pypi_versions(specs: list[str]) -> tuple[list[str], list[Findf"{name}=={version} is on the BLOCKED_PYPI_VERSIONS list",))- # Drop the spec; do not download.+ # Drop the spec; do not downloadcontinuesafe.append(spec)return safe, findings@@ -1416,14 +1361,11 @@ def _check_blocked_pypi_versions(specs: list[str]) -> tuple[list[str], list[Finddef _pip_download_env() -> dict[str, str]:"""Return a scrubbed environment for invoking `pip download`.- Hostile shells / CI configs can override the index with PIP_INDEX_URL,- PIP_EXTRA_INDEX_URL, or a user `pip.conf`. We strip every PIP_*- override and route the resolver explicitly at PyPI. PIP_CONFIG_FILE- is forced to /dev/null so a stray ~/.pip/pip.conf with an- extra-index-url cannot bypass the pin.+ Strips every PIP_* override and forces the resolver at PyPI; PIP_CONFIG_FILE+ is /dev/null so a stray pip.conf extra-index-url cannot bypass the pin."""env = {**os.environ}- # Drop any user override.+ # Drop any user overridefor key in [k for k in env if k.startswith("PIP_")]:env.pop(key, None)env["PIP_INDEX_URL"] = "https://pypi.org/simple"@@ -1433,10 +1375,8 @@ def _pip_download_env() -> dict[str, str]:return env-# Pip resolver flags shared by both download branches. Pinning the-# index URL on the CLI is belt + braces with the env scrub above.-# `--no-build-isolation` is deliberately NOT set; we never invoke-# setup.py at all because of `--only-binary :all:`.+# Pip resolver flags shared by both download branches. CLI index-URL pin is+# belt + braces with the env scrub; `--only-binary :all:` avoids running setup.py._PIP_DOWNLOAD_PIN_FLAGS = ["--index-url","https://pypi.org/simple",@@ -1445,9 +1385,8 @@ _PIP_DOWNLOAD_PIN_FLAGS = []-# Strip any character that could escape `dest` via `os.path.join`. This-# is the last line of defence before `pkg_dir = os.path.join(dest, ...)`-# so a spec like `../../etc/foo==1.0` cannot land outside the temp tree.+# Strip characters that could escape `dest` via `os.path.join`, so a spec like+# `../../etc/foo==1.0` cannot land outside the temp tree._RE_PKG_NAME_SANITIZE = re.compile(r"[^A-Za-z0-9._-]")@@ -1459,27 +1398,21 @@ def download_packages() -> tuple[list[tuple[str, str]], list[str]]:"""Download packages to dest using pip download. NEVER installs.- Returns ``(results, download_errors)`` where ``results`` is a list of- ``(spec_or_name, filepath)`` for every downloaded archive and- ``download_errors`` is a list of one-line transport-failure summaries.- A non-empty ``download_errors`` MUST cause the caller to exit non-zero- even if no findings were produced; a silent ``0 findings, scan- incomplete`` is the bug class this return-shape was widened to fix.-- When with_deps=True, downloads the full transitive dependency tree- in a single pip invocation (all archives land in one flat dir).- When with_deps=False (default), downloads each spec individually- with --no-deps.+ Returns ``(results, download_errors)``: ``results`` is ``(spec_or_name,+ filepath)`` per archive; ``download_errors`` is one-line transport-failure+ summaries. A non-empty ``download_errors`` MUST make the caller exit+ non-zero so a partial scan can't masquerade as "0 findings, all clean".++ with_deps=True downloads the full transitive tree in one pip call (flat dir);+ with_deps=False (default) downloads each spec individually with --no-deps."""results: list[tuple[str, str]] = []download_errors: list[str] = []env = _pip_download_env()if with_deps:- # Single pip download call for all specs + their transitive deps.- # `--only-binary :all:` refuses sdists so we never execute a- # setup.py just to learn dependency metadata; combined with the- # scrubbed env, pip is wired hard at pypi.org.+ # Single pip download for all specs + transitive deps. `--only-binary+ # :all:` refuses sdists so we never execute setup.py for metadata.os.makedirs(dest, exist_ok = True)cmd = [sys.executable,@@ -1495,7 +1428,7 @@ def download_packages(cmd,capture_output = True,text = True,- timeout = 600, # transitive resolution can be slow+ timeout = 600, # transitive resolution is slowenv = env,)if proc.returncode != 0:@@ -1511,14 +1444,12 @@ def download_packages(for fname in sorted(os.listdir(dest)):fpath = os.path.join(dest, fname)if os.path.isfile(fpath):- # Derive package name from filenamepkg_name = fname.split("-")[0].replace("_", "-").lower()results.append((pkg_name, fpath))else:for spec in specs:raw_name = _extract_pkg_name(spec)- # Sanitize before joining into `dest` so a hostile spec- # cannot path-traverse out of the destination directory.+ # Sanitize before joining into `dest` to prevent path traversalsafe_name = _RE_PKG_NAME_SANITIZE.sub("_", raw_name) or "_pkg"pkg_dir = os.path.join(dest, safe_name)os.makedirs(pkg_dir, exist_ok = True)@@ -1552,7 +1483,6 @@ def download_packages(download_errors.append(msg)continue- # Find downloaded file(s)for fname in os.listdir(pkg_dir):fpath = os.path.join(pkg_dir, fname)if os.path.isfile(fpath):@@ -1560,9 +1490,7 @@ def download_packages(return results, download_errors-# ---------------------------------------------------------------------------# Parse requirements files-# ---------------------------------------------------------------------------_RE_NAME = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?)")@@ -1591,7 +1519,7 @@ def parse_requirements(req_files: list[str]) -> list[dict]:if not line or line.startswith("#") or line.startswith("-"):continueis_git = line.startswith("git+") or "git+" in line.split("#")[0]- # Strip inline comments and environment markers for spec+ # Strip inline comments and env markersspec = line.split("#")[0].strip()spec = spec.split(";")[0].strip()if not spec:@@ -1624,7 +1552,7 @@ def get_downloaded_version(archive_path: str) -> str | None:parts = basename[:-4].split("-")if len(parts) >= 2:return parts[1]- # Sdist: name-version.tar.gz / .tar.bz2 / .zip+ # Sdist: name-version.<ext>for ext in (".tar.gz", ".tar.bz2", ".tar.xz", ".tar", ".zip"):if basename.endswith(ext):stem = basename[: -len(ext)]@@ -1634,9 +1562,7 @@ def get_downloaded_version(archive_path: str) -> str | None:return None-# ---------------------------------------------------------------------------# Display-# ---------------------------------------------------------------------------def severity_color(sev: str) -> str:@@ -1652,7 +1578,6 @@ def print_findings(findings: list[Finding]) -> None:print("\n All clean. No suspicious patterns found.")return- # Sort by severityfindings.sort(key = lambda f: SEVERITY_ORDER.get(f.severity, 99))print(f"\n {'=' * 72}")@@ -1682,9 +1607,7 @@ def print_findings(findings: list[Finding]) -> None:print(f" Summary: {', '.join(parts)}")-# ---------------------------------------------------------------------------# PyPI version queries and --fix logic-# ---------------------------------------------------------------------------def version_sort_key(v: str) -> tuple:@@ -1708,15 +1631,13 @@ def version_sort_key(v: str) -> tuple:base = v_clean[0]suffix = v[len(base) :]- # Parse numeric partsparts = []for seg in base.split("."):try:parts.append(int(seg))except ValueError:parts.append(0)- # Pad to at least 3 parts- while len(parts) < 3:+ while len(parts) < 3: # pad to at least 3 partsparts.append(0)# Suffix ordering: dev < alpha < beta < rc < (none) < post@@ -1732,7 +1653,7 @@ def version_sort_key(v: str) -> tuple:elif suffix_lower.startswith("post"):suffix_rank = 1else:- suffix_rank = 0 # stable release+ suffix_rank = 0 # stablereturn (epoch, tuple(parts), suffix_rank, suffix)@@ -1772,11 +1693,10 @@ def find_safe_version(print(f" [WARN] No versions found on PyPI for {name}", file = sys.stderr)return None- # Find index of bad versiontry:bad_idx = versions.index(bad_ver)except ValueError:- # bad_ver might have been resolved to a different string; search by sort key+ # bad_ver may resolve to a different string; search by sort keybad_key = version_sort_key(bad_ver)bad_idx = Nonefor i, v in enumerate(versions):@@ -1820,7 +1740,6 @@ def find_safe_version(print(f" {ver} -- CRITICAL finding(s), skipping")break- # Clean up scan dir for this versionshutil.rmtree(scan_dir, ignore_errors = True)if clean:@@ -1850,8 +1769,7 @@ def update_req_line(raw_line: str, safe_ver: str, old_ver: str | None) -> str:code_part, marker = code_part.split(";", 1)marker = ";" + marker- # Replace version specifier- # Match patterns like ==1.2.3, >=1.2, ~=1.0, <=2.0, !=1.1, or bare name+ # Replace version specifier (==1.2.3, >=1.2, ~=1.0, !=1.1, or bare name)rewritten = re.sub(r"([A-Za-z0-9._-]+)\s*(?:[><=!~]=?[^;#,\s]*(?:\s*,\s*[><=!~]=?[^;#,\s]*)*)?",lambda m: f"{m.group(1)}=={safe_ver}",@@ -1870,12 +1788,8 @@ def update_req_file(filepath: str, updates: dict[int, str]) -> None:updates: {line_num (1-indexed): new_line_text}- Writes atomically: stage in a sibling tmp file on the same- filesystem, fsync, then `os.replace` over the original. A SIGKILL- or power loss mid-write therefore either leaves the original- intact or leaves the fully new file -- never a half-written- requirements file (which would silently re-introduce a malicious- pin).+ Writes atomically (sibling tmp file, fsync, os.replace) so a crash mid-write+ never leaves a half-written file that re-introduces a malicious pin."""with open(filepath) as f:lines = f.readlines()@@ -1883,8 +1797,7 @@ def update_req_file(filepath: str, updates: dict[int, str]) -> None:for line_num, new_text in updates.items():idx = line_num - 1if 0 <= idx < len(lines):- # Preserve original line ending- ending = "\n" if lines[idx].endswith("\n") else ""+ ending = "\n" if lines[idx].endswith("\n") else "" # preserve line endinglines[idx] = new_text + endingdirpath = os.path.dirname(os.path.abspath(filepath)) or "."@@ -1909,7 +1822,7 @@ def update_req_file(filepath: str, updates: dict[int, str]) -> None:def _run_fix(critical_pkgs: set[str], entries: list[dict], max_search: int) -> None:"""Run the --fix flow: find safe versions, update requirements files."""- # Map package names to their entries for source tracking+ # Map package names to entries for source trackingpkg_entries: dict[str, list[dict]] = {}for e in entries:norm = e["name"].lower().replace("-", "_").replace(".", "_")@@ -1931,8 +1844,7 @@ def _run_fix(critical_pkgs: set[str], entries: list[dict], max_search: int) -> Nchanges_summary.append(f" SKIP {pkg_name} (git URL)")continue- # Get the currently resolved version- # Try to extract from the spec (e.g. name==1.2.3)+ # Resolved version: try to extract from the spec (name==1.2.3)current_ver = Nonefor e in related:spec = e["spec"]@@ -1947,7 +1859,6 @@ def _run_fix(critical_pkgs: set[str], entries: list[dict], max_search: int) -> Ndownloaded = download_packages([pkg_name], dl_dir)if downloaded:current_ver = get_downloaded_version(downloaded[0][1])- # Delete resolution download immediatelyshutil.rmtree(dl_dir, ignore_errors = True)if not current_ver:@@ -1986,7 +1897,6 @@ def _run_fix(critical_pkgs: set[str], entries: list[dict], max_search: int) -> Nfor filepath, updates in file_updates.items():update_req_file(filepath, updates)- # Print summaryprint(f"\n {'=' * 72}")print(f" FIX SUMMARY")print(f" {'=' * 72}")@@ -1995,9 +1905,7 @@ def _run_fix(critical_pkgs: set[str], entries: list[dict], max_search: int) -> Nprint(f"\n Re-run without --fix to verify the scan is clean.")-# ---------------------------------------------------------------------------# Directory scanning-# ---------------------------------------------------------------------------def _find_requirements_files(root: str) -> list[str]:@@ -2014,7 +1922,7 @@ def _find_requirements_files(root: str) -> list[str]:skip_dirs = {"__pycache__", "node_modules", "venv", ".venv", "site-packages"}results = []for dirpath, dirnames, filenames in os.walk(root):- # Skip hidden dirs and known non-requirement dirs+ # Skip hidden and known non-requirement dirsdirnames[:] = [dfor d in dirnames@@ -2024,18 +1932,15 @@ def _find_requirements_files(root: str) -> list[str]:for fname in sorted(filenames):if not fname.endswith(".txt"):continue- # Match requirements*.txt anywhereif fnmatch.fnmatch(fname.lower(), "requirements*.txt"):results.append(os.path.join(dirpath, fname))- # Match *.txt inside a directory named "requirements"+ # *.txt inside a directory named "requirements"elif dirname == "requirements":results.append(os.path.join(dirpath, fname))return sorted(results)-# ---------------------------------------------------------------------------# Main-# ---------------------------------------------------------------------------def main() -> int:@@ -2134,7 +2039,7 @@ def main() -> int:all_findings: list[Finding] = []- # Hard pin-block: refuse to download known-malicious PyPI versions.+ # Hard pin-block: refuse to download known-malicious PyPI versionsspecs, blocked_findings = _check_blocked_pypi_versions(specs)all_findings.extend(blocked_findings)@@ -2172,10 +2077,8 @@ def main() -> int:)_run_fix(critical_pkgs, entries, args.max_search)- # Surface any pip-download failures BEFORE the scan-result exit code so- # an empty / partial download cannot mask itself as "0 findings, all- # clean". This is item (4) of the silent-failure hardening: an- # unresolvable spec or PyPI timeout used to print to stderr and exit 0.+ # Surface pip-download failures BEFORE the exit code so a partial download+ # can't masquerade as "0 findings, all clean" (silent-failure hardening 4).if download_errors:print(f"\n {'=' * 72}\n"diff --git a/scripts/stamp_studio_release.py b/scripts/stamp_studio_release.pyindex a3c8712a6e3..7dab35ea8a8 100644--- a/scripts/stamp_studio_release.py+++ b/scripts/stamp_studio_release.py@@ -22,11 +22,8 @@ def _atomic_write_text(data: str,encoding: str = "utf-8",) -> None:- """Atomic version of ``Path.write_text``.-- A crash or signal mid-write leaves the prior file intact; the- Studio build never reads a partial ``_studio_release_build.py``.- """+ """Atomic ``Path.write_text``: a crash mid-write leaves the prior file+ intact, so the build never reads a partial ``_studio_release_build.py``."""dirpath = str(path.parent) or "."path.parent.mkdir(parents = True, exist_ok = True)fd, tmp_path = tempfile.mkstemp(prefix = ".stamp_studio.", dir = dirpath)diff --git a/scripts/verify_comment_only_diff.py b/scripts/verify_comment_only_diff.pyindex b661f76859c..23d06b85dfa 100644--- a/scripts/verify_comment_only_diff.py+++ b/scripts/verify_comment_only_diff.py@@ -57,9 +57,7 @@ def _git_show(rev: str, path: str) -> str:def _strip_docstrings(tree: ast.AST) -> ast.AST:- """Remove every string-literal docstring (Module / FunctionDef /- AsyncFunctionDef / ClassDef). Empty body becomes ``pass`` so- ast.unparse stays valid."""+ """Remove docstrings; empty bodies become ``pass`` so unparse stays valid."""for node in ast.walk(tree):if isinstance(node,@@ -87,9 +85,8 @@ def _normalize_py(src: str) -> str:def _strip_shell_comments(s: str) -> str:- """Strip pure-comment lines and inline trailing comments from a shell- snippet, then collapse runs of blank lines. Heuristic only: leaves a- line untouched if it has an odd quote count (open string)."""+ """Strip shell comments and collapse blank lines. Heuristic: skips lines+ with an odd quote count (open string)."""out = []for line in s.splitlines():stripped = line.lstrip()@@ -116,9 +113,7 @@ def _strip_shell_comments(s: str) -> str:def _normalize_yaml_run_strings(obj: Any) -> Any:- """Walk the parsed YAML object; for any multi-line string (i.e. a- ``run: |`` script body), strip shell comments. Returns a normalised- copy."""+ """Strip shell comments from any multi-line string (``run: |`` body)."""if isinstance(obj, dict):return {k: _normalize_yaml_run_strings(v) for k, v in obj.items()}if isinstance(obj, list):diff --git a/scripts/verify_import_hoist.py b/scripts/verify_import_hoist.pyindex 6f5b452f3c1..b8cb0573fe2 100644--- a/scripts/verify_import_hoist.py+++ b/scripts/verify_import_hoist.py@@ -122,16 +122,13 @@ class _Builder(ast.NodeVisitor):def __init__(self):self.module = Scope("module", "<module>", None)- self.uses: list[tuple[Scope, str, int]] = [] # (scope, name, lineno) hard loads- self.soft_uses: list[tuple[Scope, str, int]] = [] # annotations: count as "used"- # but never as "unresolved"- # (forward refs / string annos)+ self.uses: list[tuple[Scope, str, int]] = [] # hard loads+ # annotations: count as "used" but never as "unresolved" (forward refs)+ self.soft_uses: list[tuple[Scope, str, int]] = []def _visit_annotation(self, node, scope: Scope) -> None:- """Annotation context: with `from __future__ import annotations` these are- never evaluated (strings), and even otherwise they routinely contain forward- references. Record contained names as SOFT uses so an import used only in an- annotation still counts as used, but a forward-ref name is never 'unresolved'."""+ """Record annotation names as SOFT uses: an import used only in an annotation+ counts as used, but a forward-ref name is never 'unresolved'."""if node is None:returnfor n in ast.walk(node):@@ -189,7 +186,7 @@ class _Builder(ast.NodeVisitor):child = Scope("function", f"{scope.qualname}.{node.name}", scope)self._bind_type_params(node, child)self._bind_args(node.args, child)- # arg + return annotations: soft uses (may be strings / forward refs)+ # arg + return annotations: soft usesfor a in self._all_args(node.args):self._visit_annotation(a.annotation, child)self._visit_annotation(getattr(node, "returns", None), child)@@ -355,7 +352,7 @@ class _Builder(ast.NodeVisitor):if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):child = Scope("comp", f"{scope.qualname}.<comp>", scope)for i, gen in enumerate(node.generators):- # first iterable is evaluated in the enclosing scope+ # first iterable evaluates in the enclosing scopeself._visit_expr(gen.iter, scope if i == 0 else child)self._bind_targets(child, gen.target)for cond in gen.ifs:@@ -394,9 +391,8 @@ def _any_star(scope: Scope) -> bool:def _resolve(scope: Scope, name: str):- """LEGB resolution. Returns (status, bindings) where status in+ """LEGB resolution. Returns (status, bindings); status in{'local','import','other','builtin','star','unresolved'}."""- # global / nonlocal redirectionstart = scopeif name in scope.globals:chain = [_module_of(scope)]@@ -441,7 +437,7 @@ def _legb_chain(scope: Scope) -> list[Scope]:chain = [scope]p = scope.parentwhile p is not None:- if p.kind != "class" or p.parent is None: # module-level class never happens; keep module+ if p.kind != "class" or p.parent is None: # skip class scopes, keep moduleif p.kind != "class":chain.append(p)p = p.parent@@ -455,7 +451,7 @@ def _analyze(src: str):tree = ast.parse(src)b = _Builder()b.run(tree)- # Per-scope: unresolved load names, and import targets it resolves to.+ # Per-scope: unresolved load names + import targets it resolves to.unresolved: dict[str, set[str]] = {}targets_by_scope: dict[str, set[str]] = {}target_by_use: dict[tuple[str, str], set[str]] = {}@@ -467,7 +463,7 @@ def _analyze(src: str):tids = {bd.target for bd in binds if bd.target}targets_by_scope.setdefault(scope.qualname, set()).update(tids)target_by_use.setdefault((scope.qualname, name), set()).update(tids)- # soft uses (annotations): only contribute to "used", never to "unresolved"+ # soft uses (annotations): contribute to "used" only, never "unresolved"for scope, name, _ln in b.soft_uses:status, binds = _resolve(scope, name)if status == "import":@@ -495,7 +491,7 @@ def _analyze(src: str):x.kind not in ("import", "importfrom") for x in bs):ambiguous.setdefault(scope.qualname, set()).add(n)- # scope tree isn't stored; rebuild via uses is hard. We approximate with module only.+ # scope tree isn't stored; approximate with module only.walk_scopes(module)return {@@ -524,14 +520,9 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]Blocker signals (precise, no relocation false-positives):UNRESOLVED-NEW - a load became undefined (dangling alias / removed import).- NEW-UNUSED-HOIST - a module-level import added by THIS change is resolved by- NO load. A correct hoist always wires its new import to a- reference; if the alias was left un-normalized OR renamed- to the wrong name, the hoisted import ends up unused. This- single signal catches BOTH user-described failure modes and- does NOT fire for code merely relocated to another file- (that removes the import, it doesn't add an unused one).- TARGET-CHANGED - the same (scope, name) load resolves to a different import+ NEW-UNUSED-HOIST - a module-level import added by this change is resolved by+ NO load (un-normalized alias or wrong rename target).+ TARGET-CHANGED - same (scope, name) load resolves to a different importtarget before vs after (a same-name re-point)."""a = _analyze(before_src)@@ -566,14 +557,13 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]))- # 2. HOISTED-IMPORT-UNUSED (the core botched-hoist / wrong-rename signal)- # A module-level import in AFTER that NO load resolves to, and which was- # either newly added by this change OR was actually used before. Excludes:- # - relocation (the import is REMOVED, so it's not in after at all)- # - stable pre-existing re-exports (unused before AND after, not newly added)+ # 2. HOISTED-IMPORT-UNUSED (core botched-hoist / wrong-rename signal)+ # A module-level import in AFTER that NO load resolves to, that was either+ # newly added by this change OR actually used before. Excludes relocation+ # (import removed) and stable pre-existing re-exports.for n, tids in b["module_import_targets"].items():if tids & after_used:- continue # resolved by something -> fine+ continue # resolved -> finenewly_added = bool(tids - before_module_targets)was_used_before = bool(tids & before_used)if newly_added or was_used_before:@@ -619,8 +609,7 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]findings.append(("WARN", f"{path}: AMBIGUOUS-BIND '{n}' import+non-import in {scope}"))# 6. TARGET-MISSING (informational): a scope stopped resolving to an import- # target. Real bugs are already covered above; remaining cases are code- # relocated to another file (e.g. a moved helper). Shown for transparency.+ # target. Real bugs are covered above; remaining cases are relocated code.for scope, tbefore in a["targets_by_scope"].items():tafter = b["targets_by_scope"].get(scope, set())for t in sorted(tbefore - tafter):@@ -667,13 +656,13 @@ _SELF_TESTS = {"BLOCKER",),"local_var_clash": (- # _b renamed to b, but b is a LOCAL variable in f -> import silently unused+ # _b renamed to b, but b is a LOCAL var in f -> import silently unused"def f(b):\n import re as _b\n return _b.compile(b)\n","import re\ndef f(b):\n return b.compile(b)\n", # 'b' is the param, not the module"BLOCKER",),"substring_safe": (- # correct _copy->copy rename while a config_copy var exists: NO false positive+ # correct _copy->copy rename while config_copy var exists: NO false positive"def f(config):\n"" import copy as _copy\n"" config_copy = _copy.deepcopy(config)\n"@@ -728,10 +717,9 @@ def _pyflakes_undefined(path: str) -> set[str] | None:def audit_files(paths: list[str]) -> int:- """Single-version robustness audit. For every file: confirm the analyzer does- not crash, then cross-check its 'unresolved' names against pyflakes. Any name- the resolver flags that pyflakes does NOT call undefined is a tool FALSE- POSITIVE (a resolver gap to fix)."""+ """Single-version robustness audit: confirm the analyzer doesn't crash, then+ cross-check its 'unresolved' names against pyflakes. A name the resolver flags+ that pyflakes accepts is a tool false positive."""n_files = n_err = n_fp = n_syntax = 0fp_detail: dict[str, set[str]] = {}err_detail: dict[str, str] = {}diff --git a/studio/backend/_platform_compat.py b/studio/backend/_platform_compat.pyindex 37bf5e3fb53..013667d5cae 100644--- a/studio/backend/_platform_compat.py+++ b/studio/backend/_platform_compat.py@@ -5,16 +5,15 @@Compatibility shim for Anaconda/conda-forge Python builds.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).+'3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'. The regex in+platform._sys_version() can't parse this and raises ValueError (cpython#102396,+closed as "not planned").We seed platform._sys_version_cache so the stdlib parser never sees the badstring, fixing the import chain:structlog -> rich.pretty -> attrs._compat -> platform.python_implementation()-Import before any library that may trigger that chain. Idempotent (no-op if the-cache is already seeded or there are no pipes).+Import before any library that may trigger that chain. Idempotent."""import platform@@ -23,14 +22,13 @@ import sysdef _seed_sys_version_cache() -> None:- """One-shot cache prime: parse a cleaned sys.version and seed the cache."""+ """Parse a cleaned sys.version and seed the cache once."""raw = sys.version# Strip paired |...| segments (Anaconda, conda-forge metadata)cleaned = re.sub(r"\s*\|[^|]*\|\s*", " ", raw).strip()- # Format B: "ver (build) | label | (build_dup) \n[compiler]" leaves two- # consecutive (...) groups after pipe-strip; drop the second.+ # Pipe-strip can leave two consecutive (...) groups; drop the second.cleaned = re.sub(r"(\([^)]*\))\s+\([^)]*\)", r"\1", cleaned)if "|" in cleaned:@@ -43,7 +41,6 @@ def _seed_sys_version_cache() -> None:if cleaned == raw:return # Nothing to fix- # Parse the cleaned string through the real stdlib parsertry:result = platform._sys_version(cleaned)except ValueError:diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex 6509cb68250..9dd56489eb1 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -156,15 +156,7 @@ async def get_current_subject_allow_password_change(async def _get_current_subject(credentials: HTTPAuthorizationCredentials, *, allow_password_change: bool) -> str:- """- FastAPI dependency: validate the JWT and return the subject.-- Use as a dependency on protected routes, e.g.:-- @router.get("/secure")- async def secure_endpoint(current_subject: str = Depends(get_current_subject)):- ...- """+ """FastAPI dependency: validate the JWT and return the subject. Use on protected routes."""token = credentials.credentials# --- API key path (sk-unsloth-...) ---diff --git a/studio/backend/auth/hashing.py b/studio/backend/auth/hashing.pyindex 873381db045..0a1b0c15beb 100644--- a/studio/backend/auth/hashing.py+++ b/studio/backend/auth/hashing.py@@ -23,7 +23,7 @@ def hash_password(password: str, salt: str | None = None) -> Tuple[str, str]:"sha256",password.encode("utf-8"),salt.encode("utf-8"),- 100_000, # 100k iterations+ 100_000,)return salt, dk.hex()diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.pyindex 42e2de74509..fa5b9855131 100644--- a/studio/backend/auth/storage.py+++ b/studio/backend/auth/storage.py@@ -26,30 +26,29 @@ _bootstrap_password: Optional[str] = Nonedef generate_bootstrap_password() -> str:"""Generate a 4-word diceware passphrase and persist it to disk.- Written to ``_BOOTSTRAP_PW_PATH`` so it survives restarts (the DB only- stores the *hash*). Later calls / restarts return the persisted value.+ Persisted (the DB stores only the hash) so it survives restarts; later+ calls return the persisted value."""global _bootstrap_password- # 1. Already cached in this process?+ # Cached in this process?if _bootstrap_password is not None:return _bootstrap_password- # 2. Already persisted from a previous run?+ # Persisted from a previous run?if _BOOTSTRAP_PW_PATH.is_file():_bootstrap_password = _BOOTSTRAP_PW_PATH.read_text().strip()if _bootstrap_password:return _bootstrap_password- # 3. First-ever startup — generate a fresh passphrase.+ # First startup: generate a fresh passphrase.import diceware_bootstrap_password = diceware.get_passphrase(options = diceware.handle_options(args = ["-n", "4", "-d", "", "-c"]))- # Persist so the *same* passphrase is reused if the server restarts- # before the user changes the password.+ # Persist so the same passphrase survives restarts until password change.ensure_dir(_BOOTSTRAP_PW_PATH.parent)_BOOTSTRAP_PW_PATH.write_text(_bootstrap_password)try:@@ -87,17 +86,10 @@ def clear_bootstrap_password() -> None:def _hash_token(token: str) -> str:"""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.+ Plain SHA-256 is intentional: refresh tokens are 384-bit random strings, so+ a slow KDF adds no security while costing per-refresh latency. API keys use+ the separate ``_pbkdf2_api_key`` helper, only to satisfy CodeQL's+ ``py/weak-sensitive-data-hashing`` query, not for crypto reasons."""return hashlib.sha256(token.encode("utf-8")).hexdigest()@@ -182,9 +174,8 @@ _api_key_pbkdf2_salt_cache: Optional[bytes] = Nonedef _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 ``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).+ Hex-encoded 32-byte random value in ``app_secrets``. Regenerated only when+ the row is missing (fresh install, or operator deleted it)."""global _api_key_pbkdf2_salt_cacheif _api_key_pbkdf2_salt_cache is not None:@@ -226,18 +217,10 @@ _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.- 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.+ For API-key storage ONLY, not refresh tokens. The slow KDF is only to+ appease CodeQL's ``py/weak-sensitive-data-hashing`` query, not a crypto+ requirement (API keys are random 128-bit tokens). The salt lives in+ ``app_secrets`` so dumping ``api_keys`` alone can't derive hashes."""salt = _get_or_create_api_key_pbkdf2_salt()dk = hashlib.pbkdf2_hmac(@@ -502,7 +485,7 @@ def verify_refresh_token(token: str) -> Optional[Tuple[str, bool]]:token_hash = _hash_token(token)conn = get_connection()try:- # Clean up any expired tokens while we're here+ # Opportunistically clean up expired tokensconn.execute("DELETE FROM refresh_tokens WHERE expires_at < ?",(datetime.now(timezone.utc).isoformat(),),diff --git a/studio/backend/colab.py b/studio/backend/colab.pyindex 1f618a34abb..ba46c52a6a6 100644--- a/studio/backend/colab.py+++ b/studio/backend/colab.py@@ -8,8 +8,7 @@ Colab helpers for Unsloth Studio. Uses Colab's built-in proxy.from pathlib import Pathimport sys-# Anaconda/conda-forge Python: seed platform._sys_version_cache before any-# import that triggers attrs -> rich -> structlog -> platform crash.+# Seed platform._sys_version_cache before attrs->rich->structlog->platform crash on conda Python.# See: https://github.com/python/cpython/issues/102396_backend_dir = str(Path(__file__).parent)if _backend_dir not in sys.path:@@ -41,7 +40,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)- # Valid Colab proxy URL starts with https:// and embeds the port.+ # Valid proxy URL is 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:@@ -59,16 +58,13 @@ 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. Pass it from ``_show_and_embed`` to- avoid a second ``eval_js`` round-trip.+ *_url* is an optional pre-fetched proxy URL; pass it to avoid a second eval_js round-trip."""from IPython.display import display, HTMLurl = _url if _url is not None else get_colab_url(port)- # Truncated display URL. try/except so an unexpected URL shape never- # prevents the link from rendering.+ # Truncated display URL; try/except so an odd URL shape still renders the link.try:port_prefix = f"{port}-"idx = url.index(port_prefix)@@ -77,7 +73,7 @@ def show_link(port: int = 8888, *, _url: "str | None" = None):except (ValueError, IndexError):short_url = url- # Plain-text line so the URL is visible even if HTML display fails.+ # Plain-text line so the URL shows even if HTML display fails.logger.info(f"🌐 Unsloth Studio URL: {url}")html = f"""@@ -120,10 +116,8 @@ 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 (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.+ Fetches the proxy URL once (registering the port), then renders header bar ++ iframe. Falls back to serve_kernel_port_as_iframe if IPython HTML is unavailable."""url = get_colab_url(port)logger.info(f"🌐 Unsloth Studio URL: {url}")@@ -162,7 +156,7 @@ def _show_and_embed(port: int):"""))except Exception:- # Fallback: Colab's built-in helper (less control, but always works)+ # Fallback: Colab's built-in helper.try:from google.colab import output as colab_outputcolab_output.serve_kernel_port_as_iframe(port, height = 900, width = "100%")@@ -182,9 +176,8 @@ def start(port: int = 8888):logger.info("🦥 Starting Unsloth Studio...")- # --- Fast path: Studio is already running (cell re-run) ---- # Re-launching would collide on the port or silently shift to a new one.- # Just re-show the link and iframe instead.+ # Fast path: Studio already running (cell re-run). Re-launching would collide on+ # the port, so just re-show the link and iframe.if _is_studio_healthy(port):logger.info(f" Studio is already running on port {port} — reusing existing server.")_show_and_embed(port)@@ -217,16 +210,14 @@ def start(port: int = 8888):logger.error(f"❌ Unsloth Studio failed to start: {exc}")return- # 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.+ # run_server auto-increments the port if in use; read back the bound port so the+ # proxy URL and iframe point at the right place.actual_port: int = getattr(getattr(app, "state", None), "server_port", None) or portlogger.info(f" Server started on port {actual_port}!")- # 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.+ # Poll health endpoint before showing the link — avoids the race where ready_event+ # fires but the process hasn't finished binding.import urllib.requestserver_ready = False@@ -247,9 +238,8 @@ def start(port: int = 8888):_show_and_embed(actual_port)- # 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.+ # Keep kernel alive so the daemon server thread runs; handle KeyboardInterrupt+ # cleanly so interrupting the cell gives a readable message.try:for _ in range(10000):time.sleep(300)diff --git a/studio/backend/core/__init__.py b/studio/backend/core/__init__.pyindex 5400ef0d352..30ecb27f810 100644--- a/studio/backend/core/__init__.py+++ b/studio/backend/core/__init__.py@@ -12,8 +12,8 @@ torch) before the version-activation code runs.import sysfrom pathlib import Path-# 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").+# Add backend dir to sys.path so bare "from utils.*" imports work when core+# is imported as a package._backend_dir = str(Path(__file__).resolve().parent.parent)if _backend_dir not in sys.path:sys.path.insert(0, _backend_dir)diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.pyindex 4a62004bac1..6336954bd51 100644--- a/studio/backend/core/_torchao_stub.py+++ b/studio/backend/core/_torchao_stub.py@@ -3,17 +3,11 @@"""Shared torchao Windows-ROCm import stub.-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. `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.--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+torchao (pulled in by transformers.quantizers) imports distributed_c10d.py+unconditionally, which crashes on Windows ROCm because the RCCL backend+(torch._C._distributed_c10d) is absent. Stubbing torchao short-circuits its+import chain; _StubSubpackageFinder handles any depth of torchao.xxx.yyy.+Worker subprocesses call install_torchao_windows_rocm_stub() before importingtransformers / unsloth_zoo."""@@ -27,12 +21,9 @@ import importlib.machinery_STUB_SENTINEL = object()-# 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.+# Metaclass for stub types so isinstance(x, StubClass) returns False instead of+# raising TypeError -- peft's lora/torchao.py does isinstance() against torchao+# types, which fails if those names resolve to stub modules rather than types.class _StubTypeMeta(type):def __instancecheck__(cls, instance):return False@@ -70,8 +61,7 @@ def _make_mod_stub(mod_name):):if attr.startswith("__"):raise AttributeError(attr)- # Return a stub CLASS (not a module) so isinstance(x, attr) returns- # False instead of raising TypeError.+ # Return a stub CLASS (not module) so isinstance() returns False, not TypeError.child = _make_stub_type(f"{_n}.{attr}")setattr(_m, attr, child)return child@@ -113,14 +103,12 @@ 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 (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.+ No-op elsewhere (incl. Windows CUDA, where torchao is real). Must run before+ importing 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 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.+ # Gate on the active torch runtime, not env-var presence -- HIP_PATH/ROCM_PATH+ # persist after reverting to a CUDA wheel. Some ROCm wheels lack+ # torch.version.hip but still encode "rocm" in __version__, so accept either._is_win32_rocm = Falseif sys.platform == "win32":try:@@ -133,8 +121,7 @@ def install_torchao_windows_rocm_stub() -> None:except Exception:passif _is_win32_rocm:- # Register the finder only on Windows ROCm -- elsewhere no stub modules- # are seeded, so appending would be pure accumulation.+ # Register the finder only on Windows ROCm.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/__init__.py b/studio/backend/core/data_recipe/__init__.pyindex 239e406300b..ebc27983757 100644--- a/studio/backend/core/data_recipe/__init__.py+++ b/studio/backend/core/data_recipe/__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-"""-Data Recipe core (DataDesigner wrapper + job runner).-"""+"""Data Recipe core (DataDesigner wrapper + job runner)."""from .jobs import JobManager, get_job_managerdiff --git a/studio/backend/core/data_recipe/huggingface.py b/studio/backend/core/data_recipe/huggingface.pyindex 3012fed1ea5..7a1219b2c32 100644--- a/studio/backend/core/data_recipe/huggingface.py+++ b/studio/backend/core/data_recipe/huggingface.py@@ -95,8 +95,7 @@ def publish_recipe_dataset(tags = None,)card.text = card.text.replace(_DATA_DESIGNER_FOOTER, _UNSLOTH_STUDIO_FOOTER)- # Data Designer drops the explicit token when pushing the dataset- # card, so push it ourselves to keep auth request-local.+ # Data Designer drops the explicit token, so push the card 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.pyindex 71c2b7468f9..32523e469e0 100644--- a/studio/backend/core/data_recipe/jobs/manager.py+++ b/studio/backend/core/data_recipe/jobs/manager.py@@ -132,10 +132,9 @@ class JobManager:) -> str:"""Spawn the job subprocess (one at a time, no cap).- ``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 on terminal state so the key's live window is- no longer than the run.+ ``internal_api_key_id`` is a workflow-scoped sk-unsloth-* key row id+ minted by the route layer; revoked 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@@ -537,15 +536,14 @@ 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 expires on- its own after 24h, so a missed revoke is a latency concern, not a- correctness one.+ Best-effort: failures are swallowed. The key expires after 24h, so a+ missed revoke is a latency, not correctness, concern."""key_id = getattr(job, "internal_api_key_id", None)if not key_id:returntry:- from auth import storage # deferred: avoids circular import+ from auth import storage # deferred: avoid circular importstorage.revoke_internal_api_key(int(key_id))except Exception:passdiff --git a/studio/backend/core/data_recipe/jobs/parse.py b/studio/backend/core/data_recipe/jobs/parse.pyindex e37d7064ed8..3be830d0e4c 100644--- a/studio/backend/core/data_recipe/jobs/parse.py+++ b/studio/backend/core/data_recipe/jobs/parse.py@@ -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; reset on entering the next stage.+ # Usage summary is a short block; reset on the next stage.job._in_usage_summary = Falseif 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.pyindex 6dd4db59730..c30606b2d12 100644--- a/studio/backend/core/data_recipe/jobs/types.py+++ b/studio/backend/core/data_recipe/jobs/types.py@@ -90,9 +90,8 @@ class Job:progress_columns_total: int | None = Nonesource_progress_estimated_total: int | None = Nonecompleted_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 ends so the key's window matches the- # run rather than its 24h TTL.+ # Id of the internal sk-unsloth-* API key minted for a local-model workflow.+ # Revoked when the job ends so the key's window matches the run, not its 24h TTL.internal_api_key_id: int | None = None_current_usage_model: str | None = None_in_usage_summary: bool = Falsediff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.pyindex 27d08e90fe0..4073288cb3e 100644--- a/studio/backend/core/data_recipe/jobs/worker.py+++ b/studio/backend/core/data_recipe/jobs/worker.py@@ -76,7 +76,7 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any])"""Subprocess entrypoint. Sends events to `event_queue`."""import os- os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports+ os.environ["PYTHONWARNINGS"] = "ignore" # suppress C-level warnings before importsimport warningsfrom loggers.config import LogConfig@@ -112,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 __init__. Attach the queue- # logger to `data_designer` directly so parser events survive root resets.+ # DataDesigner resets root logging in __init__; attach the queue handler+ # to the named loggers directly so parser events survive.handler = _QueueLogHandler(event_queue)handler.setLevel(logging.INFO)for logger_name in (diff --git a/studio/backend/core/data_recipe/local_callable_validators.py b/studio/backend/core/data_recipe/local_callable_validators.pyindex a40261fa92f..fbe847f9ced 100644--- a/studio/backend/core/data_recipe/local_callable_validators.py+++ b/studio/backend/core/data_recipe/local_callable_validators.py@@ -184,7 +184,7 @@ def _build_oxc_validation_function(lang: str, validation_mode: str, code_shape:normalized_code_shape = code_shape if code_shape in _OXC_CODE_SHAPES else "auto"def _validator(df):- import pandas as pd # imported lazily for local callable runtime+ import pandas as pd # lazy import for local callable runtimerow_count = int(len(df.index))if row_count == 0:diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex addbe8f8486..9d8ca5cfcc1 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -167,10 +167,8 @@ def _validate_recipe_runtime_support(recipe: dict[str, Any], model_providers: lidef 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 build them only when this host allows it (desktop /- # explicit opt-in). Otherwise 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).from core.inference.mcp_client import stdio_mcp_enabledstdio_allowed = stdio_mcp_enabled()@@ -283,9 +281,8 @@ def create_data_designer(recipe: dict[str, Any], *, artifact_path: str | None =model_providers = build_model_providers(recipe)_validate_recipe_runtime_support(recipe, model_providers)- # DataDesigner requires at least one model provider in its registry even- # when the pipeline has no LLM columns. Supply a lightweight stub so- # sampler/expression-only recipes can run without a real provider.+ # DataDesigner requires >=1 model provider even with no LLM columns; stub+ # one so sampler/expression-only recipes 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__.pyindex db9d1b352c0..f7241cd925b 100644--- a/studio/backend/core/export/__init__.py+++ b/studio/backend/core/export/__init__.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-"""-Export submodule - Model export operations+"""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.+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."""from .orchestrator import ExportOrchestrator, get_export_backenddiff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex aaae8002fcb..d5a3de06df3 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -1,7 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-# backend/export.py"""Export backend - exports models in various formats."""import glob@@ -44,10 +43,8 @@ def _is_wsl():def _apply_wsl_sudo_patch():"""On WSL, monkey-patch do_we_need_sudo() to return False.- 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.+ WSL lacks passwordless sudo and do_we_need_sudo()'s `sudo apt-get update`+ hangs on a stdin password; setup.sh pre-installs the build deps anyway."""if not _is_wsl():return@@ -108,18 +105,15 @@ class ExportBackend:try:logger.info("Starting memory cleanup...")- # Unload all inference-backend modelsmodel_names = list(self.inference_backend.models.keys())for model_name in model_names:self.inference_backend.unload_model(model_name)- # Clear current export stateself.current_model = Noneself.current_tokenizer = Noneself.current_checkpoint = Noneself._audio_type = None- # Clear GPU cache (handles gc + backend-specific cleanup)clear_gpu_cache()logger.info("Memory cleanup completed successfully")@@ -156,7 +150,6 @@ class ExportBackend:try:logger.info(f"Loading checkpoint: {checkpoint_path}")- # Cleanup existing models firstself.cleanup_memory()checkpoint_path_obj = Path(checkpoint_path)@@ -171,11 +164,9 @@ class ExportBackend:model_id = base_model or checkpoint_path- # Detect audio type and visionself._audio_type = detect_audio_type(model_id)self.is_vision = not self._audio_type and is_vision_model(model_id)- # Load model based on typeif self._audio_type == "csm":from unsloth import FastModelfrom transformers import CsmForConditionalGeneration@@ -255,7 +246,6 @@ class ExportBackend:trust_remote_code = trust_remote_code,)- # Detect PEFT / LoRA modelif _IS_MLX:# MLX doesn't use PeftModel — detect LoRA via adapter_config.jsonself.is_peft = adapter_config.exists()@@ -345,7 +335,6 @@ class ExportBackend:else:save_method = "merged_16bit"- # Save locally if requestedif save_directory:save_directory = str(resolve_export_dir(save_directory))logger.info(f"Saving merged model locally to: {save_directory}")@@ -366,7 +355,6 @@ class ExportBackend:logger.info(f"Model saved successfully to {save_directory}")output_path = str(Path(save_directory).resolve())- # Push to hub if requestedif push_to_hub:if not repo_id or not hf_token:return (@@ -447,7 +435,6 @@ class ExportBackend:output_path: Optional[str] = Nonetry:- # Save locally if requestedif save_directory:save_directory = str(resolve_export_dir(save_directory))logger.info(f"Saving base model locally to: {save_directory}")@@ -470,7 +457,6 @@ class ExportBackend:logger.info(f"Model saved successfully to {save_directory}")output_path = str(Path(save_directory).resolve())- # Push to hub if requestedif push_to_hub:if not repo_id or not hf_token:return (@@ -519,7 +505,6 @@ class ExportBackend:)username = repo_id.split("/")[0]- # Build and push model cardcontent = MODEL_CARD.format(username = username,base_model = base_model,@@ -530,7 +515,6 @@ class ExportBackend:card = ModelCard(content)card.push_to_hub(repo_id, token = hf_token, commit_message = "Unsloth Model Card")- # Upload filesif save_directory:hf_api.upload_folder(folder_path = save_directory,@@ -583,10 +567,8 @@ class ExportBackend:# unsloth expects lowercase quant methodquant_method = quantization_method.lower()- # Pin convert_hf_to_gguf.py to the same llama.cpp ref as the- # llama-quantize binary (Studio installs at a tagged ref via- # setup.sh) so it can't drift past the pinned binary's gguf API.- # Set before both branches; hub-only export has save_directory == "".+ # Pin convert_hf_to_gguf.py to setup.sh's tagged llama.cpp ref so it+ # can't drift past the pinned llama-quantize binary's gguf API.global _LLAMA_CPP_SCRIPTS_WARNING_EMITTEDtry:from unsloth_zoo.llama_cpp import (@@ -605,12 +587,10 @@ class ExportBackend:)_LLAMA_CPP_SCRIPTS_WARNING_EMITTED = True- # Save locally if requestedif save_directory:save_directory = str(resolve_export_dir(save_directory))- # Use absolute path so unsloth's relative-path internals- # (check_llama_cpp, use_local_gguf, _download_convert_hf_to_gguf)- # resolve against the repo root cwd, NOT the export directory.+ # Absolute path so unsloth's relative-path internals 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}")@@ -619,15 +599,11 @@ class ExportBackend:# 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 relative to cwd- # (repo root), so we diff afterwards and relocate.+ # convert_to_gguf writes output relative to cwd (repo root);+ # snapshot existing .gguf so we can diff and relocate afterwards.cwd = os.getcwd()pre_existing_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf")))- # 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,@@ -635,18 +611,14 @@ class ExportBackend:quantization_method = quant_method,)- # Relocate GGUF artifacts into the export directory.- # convert_to_gguf writes .gguf to cwd (repo root) because- # --outfile is a relative path like "model.Q4_K_M.gguf".+ # Relocate the .gguf that convert_to_gguf wrote to cwd (repo root).new_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf"))) - pre_existing_ggufsfor 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 from subdirs into abs_save_dir.- # save_pretrained_gguf may create subdirs (e.g. model_gguf/)- # named differently from model_save_path.+ # Flatten any .gguf from subdirs (e.g. model_gguf/) into abs_save_dir.for sub in list(Path(abs_save_dir).iterdir()):if not sub.is_dir():continue@@ -654,13 +626,11 @@ 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 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 dir in outputs/. Relocate- # any GGUFs from there and clean it up.+ # For non-PEFT models, save_pretrained_gguf leaves a *_gguf dir at+ # the checkpoint path; relocate its GGUFs and clean it up.if self.current_checkpoint:ckpt = Path(self.current_checkpoint)gguf_dir = ckpt.parent / f"{ckpt.name}_gguf"@@ -680,7 +650,6 @@ class ExportBackend:# Write export metadata so the Chat page can identify the base modelself._write_export_metadata(abs_save_dir)- # 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",@@ -689,7 +658,6 @@ class ExportBackend:)output_path = str(Path(abs_save_dir).resolve())- # Push to hub if requestedif push_to_hub:if not repo_id or not hf_token:return (@@ -743,7 +711,6 @@ class ExportBackend:output_path: Optional[str] = Nonetry:- # Save locally if requestedif save_directory:save_directory = str(resolve_export_dir(save_directory))logger.info(f"Saving LoRA adapter locally to: {save_directory}")@@ -759,7 +726,6 @@ class ExportBackend:logger.info(f"Adapter saved successfully to {save_directory}")output_path = str(Path(save_directory).resolve())- # Push to hub if requestedif push_to_hub:if not repo_id or not hf_token:return (diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.pyindex 49c1af8822b..20158d18918 100644--- a/studio/backend/core/export/orchestrator.py+++ b/studio/backend/core/export/orchestrator.py@@ -28,9 +28,7 @@ logger = get_logger(__name__)_CTX = mp.get_context("spawn")-# 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.+# Max log lines kept per orchestrator (live log panel scrollback); ~1 MB worst-case._LOG_BUFFER_MAXLEN = 4000@@ -44,13 +42,10 @@ class ExportOrchestrator:"""def __init__(self):- # Subprocess state.self._proc: Optional[mp.Process] = Noneself._cmd_queue: Any = Noneself._resp_queue: Any = None- # Serializes export ops (load_checkpoint, export_*, cleanup) so- # concurrent HTTP requests can't interleave commands on the- # subprocess queue.+ # Serializes export ops so concurrent HTTP requests can't interleave commands.self._lock = threading.Lock()# Local state mirrors (updated from subprocess responses).@@ -58,25 +53,15 @@ class ExportOrchestrator:self.is_vision: bool = Falseself.is_peft: bool = False- # ── Live log capture ─────────────────────────────────────- # Thread-safe ring buffer of log lines from the worker- # subprocess. Powers the GET /api/export/logs/stream SSE- # endpoint the export dialog consumes.+ # Thread-safe ring buffer of worker log lines; powers the export logs SSE endpoint.self._log_buffer: Deque[Dict[str, Any]] = deque(maxlen = _LOG_BUFFER_MAXLEN)self._log_lock = threading.Lock()- # Monotonic sequence number. Never reset across operations, so- # SSE clients can use it as a stable cursor even if clear_logs()- # runs mid-session.+ # Monotonic seq, never reset, so SSE clients have a stable cursor across clear_logs().self._log_seq: int = 0- # 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.+ # _log_seq snapshot at the current run's start; SSE defaults its cursor here so a+ # late-connecting client still sees the full run. Current run has seq > this.self._run_start_seq: int = 0- # 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.+ # True while an export op runs; SSE ends the stream 1s after this flips False.self._export_active: bool = Falseatexit.register(self._cleanup)@@ -87,12 +72,7 @@ class ExportOrchestrator:# ------------------------------------------------------------------def _append_log(self, entry: Dict[str, Any]) -> None:- """Append a worker-subprocess log line to the buffer.-- Entries look like {"type": "log", "stream": "stdout"|"stderr",- "line": "...", "ts": ...}. Each gets a monotonic seq number so- SSE clients can cursor through new lines.- """+ """Append a worker log line to the buffer, stamped with a monotonic seq."""line = entry.get("line")if not line:return@@ -108,17 +88,10 @@ class ExportOrchestrator:)def clear_logs(self) -> None:- """Drop buffered log lines from a previous operation.-- Called at the start of each export op so the UI shows only the- 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).+ """Drop buffered log lines from a previous op so the UI shows only this run.- 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())``.+ The seq counter is NOT reset (clients keep a stable cursor); the current seq+ is snapshotted into ``_run_start_seq`` to anchor the SSE default cursor."""with self._log_lock:self._log_buffer.clear()@@ -138,12 +111,7 @@ class ExportOrchestrator:return self._log_seqdef get_run_start_seq(self) -> int:- """Return the seq captured at the start of the current run.-- The SSE endpoint uses this as the default cursor so a client- connecting AFTER the worker started emitting still sees every- line from the current run.- """+ """Return the seq captured at the current run's start (SSE default cursor)."""with self._log_lock:return self._run_start_seq@@ -187,22 +155,19 @@ class ExportOrchestrator:self._proc = Nonereturn- # 1. Drain stale responses.self._drain_queue()- # 2. Send shutdown command.try:self._cmd_queue.put({"type": "shutdown"})except (OSError, ValueError):pass- # 3. Wait for graceful shutdown.try:self._proc.join(timeout = timeout)except Exception:pass- # 4. Force kill if still alive.+ # 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:@@ -272,7 +237,6 @@ class ExportOrchestrator:resp = self._read_resp(timeout = min(remaining, 2.0))if resp is None:- # Check subprocess health.if not self._ensure_subprocess_alive():raise RuntimeError("Export subprocess crashed during wait")continue@@ -294,9 +258,7 @@ class ExportOrchestrator:if rtype == "status":message = resp.get("message", "")logger.info("Export subprocess status: %s", message)- # Surface status 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 for high-level progress.if message:self._append_log({@@ -477,13 +439,10 @@ 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.+ """Send an export command and wait for the result.- 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.+ Returns ``(success, message, output_path)``. ``output_path`` is the on-disk+ dir the worker wrote to (None if it only pushed to Hub or failed pre-write)."""with self._lock:if not self._ensure_subprocess_alive():@@ -517,7 +476,6 @@ class ExportOrchestrator:"""Cleanup export-related models from memory."""with self._lock:if not self._ensure_subprocess_alive():- # No subprocess — clear local state.self.current_checkpoint = Noneself.is_vision = Falseself.is_peft = Falsediff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex a517d6d7b1d..fb2a8930146 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -1,16 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Export subprocess entry point.--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.+"""Export subprocess entry point.-The subprocess stays alive while a model is loaded, accepting commands-(load, export_merged, export_base, export_gguf, export_lora, cleanup,-shutdown) via mp.Queue.+Each export session runs in a persistent subprocess (mp spawn), giving a clean+interpreter with no stale module state, which solves transformers version+switching. The subprocess stays alive while a model is loaded, accepting commands+(load, export_*, cleanup, shutdown) via mp.Queue.Pattern follows core/inference/worker.py and core/training/worker.py."""@@ -31,40 +27,31 @@ from typing import Anylogger = get_logger(__name__)-# 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.+# 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 (imports, model resolution, loading bars) is+# suppressed in the UI; _handle_export() opens it when export work starts. The+# orchestrator spawns a fresh subprocess per checkpoint load, resetting this.+# Dropped lines are still echoed to the saved fds so the server log keeps them._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 and any child it spawns is forwarded to the parent via resp_queue- as {"type": "log", ...} messages.+ """Redirect fds 1 and 2 through pipes so every line printed by this worker+ and any child it spawns is forwarded to the parent via resp_queue as+ {"type": "log", ...} messages.Must run BEFORE LogConfig.setup_logging and any ML imports, else libraryhandlers 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 the full subprocess output, even while- ``_log_forward_gate`` is closed.+ Lines are also echoed back to the original fds so the server console keeps+ the full 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- # works, just no live log streaming.+ # dup failed; give up quietly (export still works, no live streaming).returntry:@@ -86,13 +73,11 @@ def _setup_log_capture(resp_queue: Any) -> None:passreturn- # Close the write ends we just dup2'd (fds 1 and 2 are now the real- # write ends).+ # Close the write ends we just dup2'd (fds 1 and 2 are the real write ends).os.close(w_out)os.close(w_err)- # Replace 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 on fds 1 and 2.try:sys.stdout = os.fdopen(1, "w", buffering = 1, encoding = "utf-8", errors = "replace")sys.stderr = os.fdopen(2, "w", buffering = 1, encoding = "utf-8", errors = "replace")@@ -110,8 +95,7 @@ def _setup_log_capture(resp_queue: Any) -> None:continueif not chunk:break- # Echo to the original fd so the server console keeps the- # full output.+ # Echo to the original fd so the server console keeps the full output.try:os.write(echo_fd, chunk)except OSError:@@ -131,9 +115,8 @@ def _setup_log_capture(resp_queue: Any) -> None:if not line:continueif not _log_forward_gate.is_set():- # Gate closed (bootstrap) -- 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 above; drop the+ # line so the export dialog skips import noise.continuetry:resp_queue.put_nowait(@@ -145,8 +128,7 @@ 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; drop the line rather than crash the thread.passif buf and _log_forward_gate.is_set():try:@@ -179,7 +161,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 sys.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)@@ -265,11 +247,9 @@ 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 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 export progress in the live+ # log panel. Stays open for the rest of this subprocess's life; the+ # orchestrator spawns a fresh subprocess per checkpoint load, resetting it._log_forward_gate.set()output_path: Any = None@@ -370,23 +350,16 @@ 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 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 (powers the live log stream)._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 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["PYTHONWARNINGS"] = "ignore" # suppress C-level warnings before imports+ # Unbuffered output from child Python (e.g. GGUF converter) so prints surface live.os.environ["PYTHONUNBUFFERED"] = "1"- # tqdm defaults to a 10-second mininterval when stdout is not a tty- # (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.+ # tqdm defaults to a 10s mininterval when stdout isn't a tty (we redirected+ # fd 1/2 to a pipe), making multi-step bars look frozen; force frequent flushes.os.environ.setdefault("TQDM_MININTERVAL", "0.5")import warnings@@ -430,10 +403,8 @@ 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: RCCL backend absent). No-op off Windows ROCm. Must run- # before importing transformers / unsloth_zoo.+ # See core/_torchao_stub.py: torchao crashes on Windows ROCm (RCCL absent).+ # No-op off Windows ROCm. Must run before importing transformers / unsloth_zoo.from core._torchao_stub import install_torchao_windows_rocm_stubinstall_torchao_windows_rocm_stub()@@ -509,7 +480,7 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> Nonetry: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/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex b6262d99742..e7de4a53128 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -81,9 +81,7 @@ 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 buffers so nested blockquotes get the right ">" depth.self._bq_stack: list[list[str]] = []# ------------------------------------------------------------------@@ -116,10 +114,7 @@ class _MarkdownRenderer(HTMLParser):prefixed.append(">")return "\n".join(prefixed)- # ------------------------------------------------------------------- # Table helpers -- flush open cells/rows so HTML with omitted optional- # end tags (</td>, </tr>) does not lose data.- # ------------------------------------------------------------------+ # Table helpers: flush open cells/rows so omitted </td>/</tr> don't lose data.def _finish_cell(self) -> None:if not self._in_cell:return@@ -142,10 +137,7 @@ class _MarkdownRenderer(HTMLParser):self._current_row = []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 content in <a> stays single-line.def _finish_link(self) -> None:text = re.sub(r"\s+", " ", "".join(self._link_text_parts)).strip()href = self._link_href or ""@@ -234,22 +226,19 @@ class _MarkdownRenderer(HTMLParser):self._emit("\n\n")elif tag == "tr":- # Flush any open cell/row from a previous row that omitted its- # optional </td> or </tr> end tags.+ # Flush open cell/row from a prior row that omitted </td>/</tr>.self._finish_cell()self._finish_row()elif tag in ("th", "td"):- # Flush any open cell (handles omitted </td>/<th>).- self._finish_cell()+ self._finish_cell() # handles omitted </td>/</th>self._cell_parts = []self._in_cell = Trueif tag == "th":self._row_has_th = Trueelif tag == "img":- # Skip images -- keeps page text focused on readable content and- # avoids data-URI amplification.+ # Skip images: keeps text readable, avoids data-URI amplification.returndef handle_endtag(self, tag: str) -> None:@@ -310,7 +299,7 @@ class _MarkdownRenderer(HTMLParser):self._finish_row()elif tag == "table":- # Flush any remaining row (handles omitted </tr>).+ # Flush remaining row (handles omitted </tr>).self._finish_cell()self._finish_row()self._in_table = False@@ -331,9 +320,7 @@ class _MarkdownRenderer(HTMLParser):return# Collapse all whitespace (including newlines) per HTML rules.text = re.sub(r"\s+", " ", data)- # Suppress whitespace-only text nodes between table structural elements- # (source indentation) so leading spaces don't break Markdown table- # row alignment.+ # Suppress whitespace-only nodes between table elements (source indentation).if self._in_table and not self._in_cell and not text.strip():returnself._emit(text)@@ -348,18 +335,10 @@ class _MarkdownRenderer(HTMLParser):returnself._emit(html.unescape(f"&#{name};"))- # ------------------------------------------------------------------# Flush pending buffers (handles truncated HTML from capped fetches)- # ------------------------------------------------------------------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).- """+ """Flush open side-buffers into ``_out`` after close(), recovering truncated HTML."""# Flush innermost buffers first so their content propagates outward.-if self._in_link:self._finish_link()@@ -388,15 +367,9 @@ class _MarkdownRenderer(HTMLParser):self._out.append("\n\n" + prefixed + "\n\n")-# ------------------------------------------------------------------# Post-processing-# ------------------------------------------------------------------def _cleanup(text: str) -> str:- """Normalize whitespace and blank lines in the final output.-- Preserves content inside fenced code blocks verbatim so intentional blank- lines in ``<pre>`` content are not collapsed.- """+ """Normalize whitespace and blank lines, preserving fenced code blocks verbatim."""lines = text.split("\n")out: list[str] = []in_fence = False@@ -411,7 +384,6 @@ def _cleanup(text: str) -> str:continueif in_fence:- # Preserve code block content exactly as-is.out.append(line)continue@@ -427,15 +399,11 @@ def _cleanup(text: str) -> str:return "\n".join(out).strip()-# ------------------------------------------------------------------# Public API-# ------------------------------------------------------------------def html_to_markdown(source_html: str) -> str:- """Convert an HTML string to Markdown.+ """Convert HTML to Markdown (headings, links, emphasis, lists, tables, blockquotes, code, entities).- Handles headings, links, bold/italic, ordered/unordered lists, tables,- blockquotes, code blocks, and HTML entities. ``<script>``, ``<style>``,- and ``<head>`` sections are stripped entirely.+ ``<script>``, ``<style>``, and ``<head>`` are stripped entirely."""# Normalize line endings before parsing.source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.pyindex ce5f5c220fb..c1f1c6b81e6 100644--- a/studio/backend/core/inference/anthropic_compat.py+++ b/studio/backend/core/inference/anthropic_compat.py@@ -75,8 +75,7 @@ def anthropic_messages_to_openai(continueif role == "assistant":- # Assistant content carries text + tool_use; images aren't- # part of Anthropic's assistant content model.+ # Assistant content: text + tool_use only (no images in Anthropic's model).text_parts: list[str] = []tool_calls: list[dict] = []for block in content:@@ -104,9 +103,7 @@ def anthropic_messages_to_openai(continueif role == "user":- # Ordered part list to preserve text/image interleaving (e.g.- # [text, image, text, image]). tool_result blocks become their- # own OpenAI "tool" role messages.+ # Ordered parts preserve text/image interleaving; tool_result -> own "tool" messages.user_parts: list[dict] = []has_image = Falsetool_results: list[dict] = []@@ -137,8 +134,7 @@ 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- # text-only callers keep their simple shape.+ # No images: collapse text parts to a plain string.text = "\n".join(p["text"] for p in user_parts)if text:result.append({"role": "user", "content": text})@@ -317,11 +313,9 @@ class AnthropicStreamEmitter:return self._tool_arguments_delta(args)events = []- # Close current text block if open.if self._text_block_open:events.append(self._close_block())- # Defensive: if a different tool_start arrives while a tool_use- # block is open, close the stale block before starting another.+ # Defensive: close a stale open tool_use block before starting another.elif self._open_tool_call_id is not None:events.append(self._close_block())self._open_tool_call_id = Nonediff --git a/studio/backend/core/inference/audio_codecs.py b/studio/backend/core/inference/audio_codecs.pyindex c6d87d44f00..93c7da72cbb 100644--- a/studio/backend/core/inference/audio_codecs.py+++ b/studio/backend/core/inference/audio_codecs.py@@ -90,8 +90,8 @@ class AudioCodecManager:import osimport sys- # Clone SparkAudio/Spark-TTS for the sparktts package (same as- # training; the HF model repos don't contain it)+ # Clone SparkAudio/Spark-TTS for the sparktts package (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):@@ -127,9 +127,8 @@ class AudioCodecManager:import osimport sys- # 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.+ # Clone OuteTTS (the pip package has problematic deps; we remove+ # 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 +147,7 @@ class AudioCodecManager:env = child_env_without_native_path_secret(),**_windows_hidden_subprocess_kwargs(),)- # Remove files pulling in heavy / incompatible deps (matches- # notebook: gguf_model.py under models/, others under outetts/)+ # Remove files pulling in heavy / incompatible depsremove_paths = [os.path.join(outetts_pkg, "models", "gguf_model.py"),os.path.join(outetts_pkg, "interface.py"),@@ -178,13 +176,10 @@ class AudioCodecManager:# ── Decoders ─────────────────────────────────────────────────def decode_snac(self, generated_ids: torch.Tensor, device: str) -> Tuple[bytes, int]:- """- Decode SNAC tokens (Orpheus) into WAV bytes.-- 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.+ """Decode SNAC tokens (Orpheus) into WAV bytes.+ 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)."""# Find START_OF_SPEECH token (128257)@@ -229,16 +224,13 @@ class AudioCodecManager:return _numpy_to_wav_bytes(waveform, 24000), 24000def decode_csm(self, audio_values: torch.Tensor) -> Tuple[bytes, int]:- """- Decode CSM output (already a waveform from model.generate(output_audio=True)).- Returns (wav_bytes, 24000).- """+ """Decode CSM output (already a waveform). Returns (wav_bytes, 24000)."""waveform = audio_values[0].to(torch.float32).cpu().numpy()return _numpy_to_wav_bytes(waveform, 24000), 24000def decode_bicodec(self, generated_text: str, device: str) -> Tuple[bytes, int]:- """- Decode BiCodec tokens (Spark-TTS) from generated text.+ """Decode BiCodec tokens (Spark-TTS) from generated text.+Extracts bicodec_semantic_N and bicodec_global_N tokens via regex.Returns (wav_bytes, sample_rate)."""@@ -256,8 +248,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);+ # pad with zeros or truncate.GLOBAL_TOKEN_NUM = 32if global_matches:raw = [int(t) for t in global_matches]@@ -279,8 +271,8 @@ class AudioCodecManager:return _numpy_to_wav_bytes(wav_np, sr), srdef decode_dac(self, generated_text: str, device: str) -> Tuple[bytes, int]:- """- Decode DAC tokens (OuteTTS) from generated text.+ """Decode DAC tokens (OuteTTS) from generated text.+Extracts c1_N and c2_N codec code tokens via regex.Returns (wav_bytes, 24000)."""diff --git a/studio/backend/core/inference/defaults.py b/studio/backend/core/inference/defaults.pyindex f14c03dad2b..b64605e16fc 100644--- a/studio/backend/core/inference/defaults.py+++ b/studio/backend/core/inference/defaults.py@@ -49,7 +49,7 @@ DEFAULT_MODELS_STANDARD = [def get_default_models() -> list[str]:- hw.get_device() # ensure detect_hardware() has run+ hw.get_device() # ensures detect_hardware() has runif hw.CHAT_ONLY:return list(DEFAULT_MODELS_GGUF)return list(DEFAULT_MODELS_STANDARD)diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 3132ad6f860..a7d44b992da 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -19,36 +19,25 @@ from urllib.parse import urlparseimport httpximport structlog-# 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.+# structlog so INFO diagnostics reach the backend's JSON log stream (the+# stdlib root logger defaults to WARNING with no handlers). It accepts the+# existing printf-style positional args.logger = structlog.get_logger(__name__)-# 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 is set-# to a non-default value. Authoritative ref ("Sampling parameters removed"):+# Claude 4.7 (Opus/Sonnet/Haiku) removed temperature/top_p/top_k — the API+# 400s "<param> is deprecated for this model" on a non-default value. 3.x and+# 4.5/4.6 still accept them, so match the 4-7 line strictly. Ref:# 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 -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 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). 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).+ Anchored to the URL host so a path/subdomain like+ ``https://api.openai.com.attacker.com/v1`` can't bypass it (CodeQL+ py/incomplete-url-substring-sanitization). Scopes cloud-only Responses-API+ extensions that 400 on non-cloud OAI-compat servers (ollama/llama.cpp/vLLM).+ Azure Foundry resources live at ``<resource>.openai.azure.com``; the leading+ dot on `endswith` stops `openai.azure.com` apex from matching."""if not base_url:return False@@ -263,14 +252,12 @@ def _anthropic_thinking_spec(model: str) -> Optional[_AnthropicThinkingSpec]:return None-# Anthropic ships date-pinned tool versions per model family. Per the-# 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). 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 ships date-pinned tool versions per model family: the newer+# `_20260209`/`_20260120` variants only run on recent models (400 "tool not+# supported" elsewhere), and old versions on a new model miss dynamic+# filtering and free-with-search pricing. Pick the newest combo the model+# accepts, else the GA `_20250305`/`_20250910`/`_20250825` defaults. Ref:+# https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference_ANTHROPIC_NEW_WEB_PREFIXES = ("claude-opus-4-7","claude-opus-4-6",@@ -315,12 +302,10 @@ def _anthropic_code_execution_version(model: str) -> str:_ANTHROPIC_CODE_EXECUTION_BETA = "code-execution-2025-08-25"-# Anthropic server-side context compaction (beta as of compact-2026-01-12).-# 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 server-side context compaction (beta compact-2026-01-12), supported+# on Opus 4.6/4.7, Sonnet 4.6 and Mythos Preview. Same beta header for all; the+# dated `compact_20260112` type lives in body `context_management.edits`. Models+# outside the prefix list are silently ignored so we don't 400 upstream._ANTHROPIC_COMPACTION_PREFIXES = ("claude-opus-4-7","claude-opus-4-6",@@ -1490,12 +1475,8 @@ class ExternalProviderClient:first_args = _json.loads(first_args_raw)except Exception:first_args = {}- # 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.+ # Args are an opaque receipt (`{"search_result":..., "usage":{"total_tokens":N}}`),+ # not a query — Kimi runs the search server-side and bakes results into context.logger.info("Kimi $web_search: %d tool_call(s), args[0]=%s",len(search_calls),@@ -1516,13 +1497,8 @@ class ExternalProviderClient:"arguments": first_args if isinstance(first_args, dict) else {},})- # 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.+ # The search already ran server-side, so emit tool_end now — otherwise the+ # UI card sits in "running" through the whole second-call answer.yield _build_kimi_tool_end(_synthetic_chunk, tool_call_id, [])# ---- Second call: echo the tool_calls back and stream answer ----@@ -1542,14 +1518,10 @@ class ExternalProviderClient:]followup_body = dict(body)followup_body["messages"] = list(messages) + [assistant_msg] + tool_msgs- # 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.+ # Request a final `usage` block (OAI-compat streams omit it otherwise) so+ # we can see prompt_tokens jump when search context is injected.followup_body["stream_options"] = {"include_usage": True}- # Keep the tool 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.+ # Keep the tool on the second call so the model can search again mid-turn.try:async with _http_client.stream(@@ -1571,10 +1543,8 @@ class ExternalProviderClient:returnlines_gen = response.aiter_lines().__aiter__()- # 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.+ # Latch final usage; a big prompt_tokens is evidence the server+ # injected search results into context.last_usage: Optional[dict[str, Any]] = Noneannotation_shapes: set[str] = set()try:@@ -1596,11 +1566,9 @@ class ExternalProviderClient:usage = parsed.get("usage")if isinstance(usage, dict):last_usage = usage- # Scan annotations only for diagnostics —- # Kimi today doesn't emit url_citation, but- # 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.+ # Scan annotations for diagnostics only; Kimi+ # doesn't emit url_citation today, but a future+ # version's type name would show in the log.for choice in parsed.get("choices") or []:if not isinstance(choice, dict):continue@@ -1733,12 +1701,8 @@ 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:"..."}- # shape the API expects. See+ # Round-trip a prior turn's compaction block back onto this+ # assistant message so Anthropic skips re-compaction. Ref:# https://platform.claude.com/docs/en/build-with-claude/compactionsummary = part.get("content") or ""if isinstance(summary, str) and summary:@@ -1772,20 +1736,13 @@ class ExternalProviderClient:})elif part.get("type") == "input_document":- # `input_document` is Studio's normalised content type- # 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.+ # Studio's normalised PDF/doc type (file_data data-URI or+ # file_url) -> Anthropic's native `document` block.url = part.get("file_url") or ""data_uri = part.get("file_data") or ""title = part.get("filename")- # Treat 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.+ # Treat a "data:" URI with no base64 payload as missing so+ # the file_url branch can take over (matches OpenAI side).data_uri_valid = Falseb64data = ""header = ""@@ -1923,12 +1880,9 @@ class ExternalProviderClient:continuefiltered.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 be set —- # including the thinking-mode override below, which used to force- # temperature=1.+ # Claude 4.7 removed temperature/top_p/top_k entirely (400 "deprecated+ # for this model"). Latch the match and reuse it wherever those are set,+ # including the thinking-mode override below that used to force temp=1.sampling_removed = bool(_ANTHROPIC_4_7_SAMPLING_REMOVED.match(model))body: dict[str, Any] = {@@ -1941,14 +1895,11 @@ class ExternalProviderClient:body["temperature"] = temperatureif 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. 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.+ # Anthropic caches a prefix only with a cache_control marker. Treat None+ # as True (frontend default); pass False to opt out.prompt_caching_enabled = enable_prompt_caching is not False- # Optional 1h cache TTL is GA 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 (no beta header). 1h writes cost 2x vs 5m's+ # 1.25x but reads are 0.1x for both, so 1h wins after one extra hit.cache_marker: dict[str, Any] = {"type": "ephemeral"}if prompt_cache_ttl in ("5m", "1h"):cache_marker["ttl"] = prompt_cache_ttl@@ -1967,14 +1918,10 @@ class ExternalProviderClient:body["system"] = systemif 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- # 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).+ # Second breakpoint on the latest message so turn N+1 rehydrates+ # through turn N from cache. Covers the case where the system prompt+ # is below Anthropic's ~1024-token cache floor. (Max 4 breakpoints;+ # we use 2: system + tail.)last_msg = filtered[-1]content = last_msg.get("content")if isinstance(content, str):@@ -1986,10 +1933,8 @@ class ExternalProviderClient:}]elif isinstance(content, list) and content:- # Don't mutate the caller's list. Rebuild the tail with- # cache_control on the final block so an upstream image-bearing- # turn still cleanly slots into the cache as part of the- # conversational prefix.+ # Rebuild the tail (don't mutate the caller's list) with+ # cache_control on the final block.head = list(content[:-1])tail = content[-1]if isinstance(tail, dict):@@ -2002,10 +1947,8 @@ class ExternalProviderClient:thinking_spec.efforts if thinking_spec else ("none", "low", "medium", "high"))effort = reasoning_effort if reasoning_effort in allowed_efforts else None- # Claude 4.6 Opus/Sonnet accept top-tier adaptive effort as "max" only;- # "xhigh" is rejected (supported on Claude 4.7). Map our shared "xhigh"- # to "max" for 4.6 outbound requests while still accepting both in- # ``allowed_efforts`` for persisted / cross-provider UI state.+ # Claude 4.6 takes top-tier adaptive effort as "max" only ("xhigh" is+ # 4.7-only), so map "xhigh" -> "max" for 4.6 outbound requests.if effort == "xhigh" and model.startswith(("claude-opus-4-6", "claude-sonnet-4-6")):effort = "max"if effort is None:@@ -2018,30 +1961,20 @@ 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:- # "temperature and top_p cannot both be specified for this- # model. Please use only one."- # 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.+ # 4.5/4.6 require temperature=1 with thinking and forbid top_p in the+ # same request; 4.7 removed temperature entirely (any value 400s), so+ # skip the override there.if not sampling_removed:body["temperature"] = 1body.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 is harmless.+ # Force display="summarized": it defaults to "omitted" on Opus 4.7,+ # which emits an empty thinking block and leaves the panel blank.+ # Harmless no-op on 4.6.body["thinking"] = {"type": "adaptive", "display": "summarized"}- # 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:+ # Adaptive effort lives under `output_config.effort`, not top-level+ # (top-level 400s "Extra inputs are not permitted"). Allowed:+ # low|medium|high|xhigh|max. See# https://platform.claude.com/docs/en/api/messagesbody["output_config"] = {"effort": effort}elif thinking_spec and thinking_spec.kind == "manual":@@ -2099,10 +2032,9 @@ class ExternalProviderClient:)body["tools"] = anthropic_tools- # Anthropic server-side code execution — see+ # Anthropic server-side code execution (date-pinned type per model, both+ # unlocked by the same beta header set below). See# https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool- # Date-pinned tool type per model; both unlock via the same- # `code-execution-2025-08-25` beta header set below.code_execution_enabled = bool(_anthropic_hosted_builtins_allowedand enabled_tools@@ -2282,14 +2214,9 @@ class ExternalProviderClient:# 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- # glance. generated_files_count is interesting for the- # future Files API PR — when bash creates files inside- # the container, they show up as file_id entries on- # bash_code_execution_result.content, and v1 drops- # them. Track the count so we know how often it would- # have mattered.+ # Surfaced in the final log line. generated_files_count tracks+ # file_id entries on bash_code_execution_result.content that v1+ # drops, to gauge how often the future Files API PR would matter.code_execution_generated_files = 0# Container id captured from `message_start.message.container.id`# when code_execution is enabled. Emit a `container_ready`@@ -2298,12 +2225,9 @@ class ExternalProviderClient:# from the inbound id — no churn on reuse.latched_container_id: Optional[str] = Nonecontainer_id_emitted = False- # 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 surface in the "stream complete" log so- # prompt caching can be verified per-request without opening the- # Anthropic dashboard.+ # Cache usage from message_start (cache_creation/read_input_tokens)+ # and message_delta (output_tokens), logged on stream complete so+ # caching is verifiable per-request without the dashboard.last_usage: dict[str, Any] = {}def _content_chunk(text: str) -> str:@@ -2464,11 +2388,8 @@ class ExternalProviderClient:key = event_type or "<unknown>"event_counts[key] = event_counts.get(key, 0) + 1- # 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.+ # Merge input-side usage from message_start with+ # message_delta's output_tokens into last_usage.if event_type == "message_start":start_usage = (event.get("message") or {}).get("usage")if isinstance(start_usage, dict):@@ -2544,12 +2465,9 @@ 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 ordering matches the- # web_search path.+ # Code-exec result content arrives whole on the+ # start event; finalize on content_block_stop to+ # match the web_search ordering.tool_use_id = content_block.get("tool_use_id", "")inner = content_block.get("content") or {}current_code_exec_result = {@@ -2615,13 +2533,9 @@ 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- # 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_json carrying tool inputs (web_search+ # query, code-exec command, etc.); route to+ # whichever buffer is open.partial = delta.get("partial_json", "")if current_server_tool_use is not None:current_server_tool_use["buffer"] += partial@@ -2711,13 +2625,9 @@ class ExternalProviderClient:)current_code_exec_use = Noneelif 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.+ # End of a compaction block: emit a synthetic+ # tool_event so the chat-adapter persists it onto+ # the assistant message for next-turn round-trip.compaction_blocks_seen += 1yield _emit_tool_event({@@ -2787,14 +2697,8 @@ class ExternalProviderClient:)current_web_fetch_use = Noneelif 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 the+ # source pill and emit tool_end.tool_use_id = current_web_fetch_result["tool_use_id"]result_text = _format_web_fetch_result(current_web_fetch_result["inner"]@@ -2835,14 +2739,10 @@ class ExternalProviderClient:if c_in or c_out:last_usage["compaction_input_tokens"] = c_inlast_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 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.+ # Container id is on message_delta.delta.container+ # (not message_start; not provisioned yet there).+ # Emit container_ready only when it differs from the+ # inbound id so reuse doesn't re-write it every turn.delta_obj = event.get("delta") or {}container_obj = delta_obj.get("container")if isinstance(container_obj, dict) and latched_container_id is None:@@ -2946,20 +2846,15 @@ class ExternalProviderClient:await lines_gen.aclose() # now safe — aclose() is a no-opraisefinally:- # 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.+ # Per-event-type counts + web_search summary for triage.web_search_requested = bool(enabled_tools and "web_search" in enabled_tools)web_search_invocations = len(web_search_calls)total_results = sum(len(sc.get("results") or []) for sc in web_search_calls.values())queries = [sc["query"] for sc in web_search_calls.values() if sc.get("query")]- # cache_read_input_tokens > 0 on turn N proves the- # 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.+ # cache_read_input_tokens > 0 proves the cache_control marker+ # works (turn 1 shows cache_creation instead).code_execution_invocations = len(code_execution_calls)code_execution_results = sum(1 for c in code_execution_calls.values() if c.get("result") is not None@@ -3088,12 +2983,9 @@ class ExternalProviderClient:"""import json as _json- # 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._-]+`.+ # Validate the user-controlled model id first: `../cachedContents/x` is+ # path traversal, and rejecting early avoids attacker-triggered outbound+ # image fetches on a doomed request. Catalog ids match `[A-Za-z0-9._-]+`.if not re.fullmatch(r"[A-Za-z0-9._-]+", model):yield _error_sse_line(400,@@ -3160,11 +3052,9 @@ 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.+ # Reject non-image data URLs (e.g. data:text/html);+ # they'd 400 the request as inlineData. Mirrors the+ # remote-fetch path's Content-Type check.if not media_type.startswith("image/"):logger.info("Gemini inlineData: refusing non-image data URL media_type=%s",@@ -3199,10 +3089,9 @@ 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.+ # YouTube; everything else is downloaded and inlined.+ # Parse host explicitly so e.g.+ # https://evil.com/youtube.com/x isn't mis-detected.try:_parsed_image_url = urlparse(url)except (ValueError, UnicodeError):@@ -3472,12 +3361,9 @@ class ExternalProviderClient:fc_part["thoughtSignature"] = sigparts.append(fc_part)if role == "tool":- # 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.+ # Drop the follow-up if its assistant-side tool_call was dropped+ # or already replayed as native parts; else it would be an+ # orphan/duplicate functionResponse._tc_id_for_skip = msg.get("tool_call_id")if (isinstance(_tc_id_for_skip, str)@@ -3496,13 +3382,8 @@ class ExternalProviderClient:tool_name = tool_call_names[tc_id]response_payload: Anyif isinstance(content, list):- # OpenAI tool messages may carry list-form content- # (`[{"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.+ # Flatten list-form tool content to text so the+ # functionResponse result matches the string-content path._flat_parts: list[str] = []for _cpart in content:if (@@ -3540,12 +3421,8 @@ class ExternalProviderClient: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 in the next turn. Merge consecutive- # functionResponse-only user blocks so realistic parallel tool- # loops round-trip correctly.+ # Merge consecutive functionResponse-only user blocks: Gemini+ # wants parallel tool responses grouped into one user turn.if (role == "tool"and contents@@ -3581,21 +3458,14 @@ class ExternalProviderClient: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 supports it -- a stale- # `enabled_tools=["image_generation"]` on a text model is silently- # treated as a regular turn.+ # Nano Banana image generation: only image-capable models (id contains+ # `-image`/`nano-banana`) accept responseModalities=["TEXT","IMAGE"];+ # text models 400 on it, so a stale image_generation pill is ignored.# https://ai.google.dev/gemini-api/docs/image-generationmodel_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 user-function pin) still flips- # `responseModalities=["TEXT","IMAGE"]` on image-tier models and bills- # for image output.+ # tool_choice="none"/forced-function also suppresses implicit image+ # generation, else an explicit opt-out still bills for image output._tool_choice_disabled = (isinstance(tool_choice, str) and tool_choice.strip().lower() == "none")@@ -3606,14 +3476,9 @@ 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 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-tier models reject text-only tools and thinkingConfig regardless+ # of the pill (model-level constraint); the pill only controls image+ # output. Decouple the two so Images-off + Code/Search-on doesn't 400.image_tool_requested = bool(_hosted_builtins_allowed and enabled_tools and "image_generation" in enabled_tools)@@ -3748,13 +3613,12 @@ class ExternalProviderClient:and code_execution_allowed):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.+ # OpenAI function declarations -> Gemini functionDeclarations+ # (https://ai.google.dev/gemini-api/docs/function-calling#step_1). Gemini's+ # Schema accepts only the OpenAPI 3.0 subset; OpenAI strict tools include+ # keys (additionalProperties, $schema, $defs, ...) that 400 as+ # INVALID_ARGUMENT, so strip recursively. Ref:+ # https://ai.google.dev/api/caching#Schema_GEMINI_ALLOWED_SCHEMA_KEYS = frozenset({"type",@@ -3804,27 +3668,16 @@ class ExternalProviderClient:root: Optional[dict[str, Any]] = None,_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 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.+ # Recursively filter to Gemini's OpenAPI 3.0 subset (drop non-allowlist+ # keys) and translate JSON Schema `type:[X,"null"]` into+ # `type:X` + `nullable:true`.if root is None and isinstance(node, dict):root = nodeif _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.+ # Inline `$ref` targets (Gemini's subset has no $ref), with local+ # siblings overriding and a cycle guard._ref = node.get("$ref")if isinstance(_ref, str):if _ref in _seen_refs:@@ -4042,11 +3895,8 @@ class ExternalProviderClient:# 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. 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.+ # Keyed on whether `googleSearch` was actually forwarded (not caller+ # intent) so image-mode turns don't show a phantom "search complete".web_search_active = any("googleSearch" in t for t in tools_array)web_search_tool_id = "gemini_web_search"web_search_tool_started = False@@ -4128,12 +3978,9 @@ class ExternalProviderClient: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 (zero candidates ++ # promptFeedback.blockReason): surface as an error so the+ # client doesn't see an empty successful response.prompt_feedback = event.get("promptFeedback")if isinstance(prompt_feedback, dict) and prompt_feedback.get("blockReason"):block_reason = str(prompt_feedback.get("blockReason"))@@ -4241,13 +4088,9 @@ class ExternalProviderClient:if fc_id in emitted_function_call_ids:continueemitted_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 one slot if this is- # hardcoded to 0, breaking- # parallel/multi-tool turns.+ # Each functionCall needs its own+ # tool_calls[*].index, else index-based+ # consumers collapse parallel calls.tc_index = len(emitted_function_call_ids) - 1tool_call_delta: dict[str, Any] = {"index": tc_index,@@ -4258,14 +4101,9 @@ class ExternalProviderClient:"arguments": _json.dumps(fc_args),},}- # Gemini 3 function-calling: the- # 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.+ # Gemini 3 requires the part-level+ # thoughtSignature echoed next turn; stow+ # it on extra_content.google for replay.thought_sig = part.get("thoughtSignature") or part.get("thought_signature")@@ -4527,11 +4365,8 @@ 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 needs no provider-specific ordering- # knowledge.+ # End-of-stream order: web_search tool_end -> finish_reason ->+ # usage -> [DONE], matching the Anthropic/OpenAI helpers.if web_search_active and web_search_tool_started and not web_search_tool_ended:blocks: list[str] = []for cit in web_search_citations:@@ -4551,10 +4386,8 @@ class ExternalProviderClient:web_search_tool_ended = Trueif final_finish_reason:- # OpenAI clients trigger tool execution when- # finish_reason="tool_calls". Gemini emits "STOP" even- # for a pure functionCall request, so override after the- # fact to match the OAI contract.+ # Gemini emits "STOP" even for a pure functionCall turn;+ # override to "tool_calls" so OAI clients run the tool.if emitted_any_function_call and final_finish_reason == "stop":final_finish_reason = "tool_calls"finish_chunk = {@@ -4598,9 +4431,7 @@ 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() is a no-op.await response.aclose()await lines_gen.aclose()@@ -4712,12 +4543,9 @@ 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.+ # Responses uses item-shape history: each assistant call is a+ # `function_call` item and each role="tool" follow-up a+ # `function_call_output` keyed by call_id (Chat Completions shape 400s).if role == "tool":_call_id = msg.get("tool_call_id") or ""# If the matching assistant `function_call` was a server-side@@ -4743,21 +4571,12 @@ class ExternalProviderClient:)continue- # 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.+ # Translate assistant tool_calls into `function_call` items, skipping+ # server-side builtin cards (builtin name + `_server_tool` marker)._tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else Noneif 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 place tool output after an- # unrelated assistant message and confuse multi-turn function- # calling.+ # Emit assistant text before its function_call items to preserve+ # the original response.output ordering.if isinstance(content, str) and content:input_items.append({"role": "assistant", "content": content})elif isinstance(content, list):@@ -4872,23 +4691,13 @@ class ExternalProviderClient:{"type": "image_generation_call", "id": call_id})elif part_type == "input_document":- # OpenAI Responses accepts PDFs / docs as- # `{type:"input_file", file_data:"data:application/pdf;base64,..."}`- # or `{type:"input_file", file_url:"https://..."}`,- # with optional `filename`. See+ # Map Studio's `input_document` onto Responses' `input_file`.# https://developers.openai.com/api/docs/guides/images-vision- # 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 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.+ # Treat a "data:" URI with no base64 payload as missing+ # (else file_data="" 400s) and fall back to file_url.file_data_valid = bool(isinstance(file_data, str)and file_data@@ -4960,15 +4769,10 @@ class ExternalProviderClient:breakinput_items[insert_at:insert_at] = openai_replay_items- # 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 /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.+ # gpt-5.x / o3 / gpt-4.5 reject temperature/top_p (400 "Unsupported+ # parameter"); the openai allowlist scopes the picker to these families,+ # so never forward sampling knobs.+ del temperature, top_p # accepted for API symmetry, not forwarded.body: dict[str, Any] = {"model": model,@@ -4978,11 +4782,8 @@ class ExternalProviderClient:if previous_response_id:body["previous_response_id"] = previous_response_id# `summary: "auto"` is what makes /v1/responses emit reasoning summary- # events — without it 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.+ # events; without it the reasoning panel stays blank. Pair it with any+ # explicit effort except "none".summary_unsupported = bool(_OPENAI_REASONING_SUMMARY_UNSUPPORTED.match(model.strip().lower()))@@ -5162,10 +4963,8 @@ class ExternalProviderClient:return attempt_bodydef _is_openai_container_expired_error(error_text: str) -> bool:- """Match the substring patterns OpenAI uses for expired / missing- code-exec containers. No official error code exists in the public- docs, so substring-match a small set.- """+ """Substring-match OpenAI's expired/missing code-exec container errors+ (no official error code exists)."""lowered = error_text.lower()if "container" not in lowered:return False@@ -5331,14 +5130,9 @@ 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 info beyond- "succeeded".- """+ """Render `shell_call_output.output` (stdout/stderr/outcome+ per entry) as the preformatted text CodeExecutionToolUI+ shows; append return_code/(timeout) only when informative."""if not isinstance(output, list):return ""parts: list[str] = []@@ -5366,14 +5160,10 @@ class ExternalProviderClient:return "\n--- next command ---\n".join(parts) if parts else "(no output)"def _record_url_citation(payload: dict[str, Any]) -> None:- """Append a url_citation 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 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."""+ """Append a url_citation, deduped by URL: collect every+ source_id alias onto the entry's ``source_ids`` so the+ rewriter can resolve any alias. The id lives under+ source_id/id/locator across API revisions."""if payload.get("type") != "url_citation":returnurl = payload.get("url", "")@@ -5665,15 +5455,10 @@ class ExternalProviderClient:yield _chunk_with_text(summary_text)reasoning_emitted = Trueelif item.get("type") == "web_search_call":- # 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 "Searching: <query>" label.- # Citations are aggregated separately and the- # *last* call's result is overwritten at- # response.completed with the citation list- # (so source-pill extraction at message tail- # surfaces them once).+ # done carries the query; emit tool_start ++ # tool_end here. Citations are aggregated and+ # the last call's result is overwritten at+ # response.completed.item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")action = item.get("action")query = (@@ -5699,13 +5484,10 @@ 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 carries a- # single `command`. Multiple commands in one- # shell_call are joined with newlines so they- # still render as one card.+ # Join the action.commands array into one+ # newline-separated string (the card renderer,+ # shared with Anthropic bash, wants a single+ # `command`).item_id = item.get("id", "") or (f"sc_{len(shell_calls)}")action = item.get("action") or {}commands = (@@ -5874,12 +5656,9 @@ 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 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.+ # Flush any unterminated citation tail; by now all+ # annotations are recorded, else private-use bytes+ # are stripped.if pending_marker_tail:flushed = _flush_pending_marker_tail(pending_marker_tail)pending_marker_tail = ""@@ -5888,8 +5667,7 @@ class ExternalProviderClient:yield _chunk_with_text("</think>")reasoning_open = Falseyield _chunk_with_text(flushed)- # Force-drain any segment still awaiting an- # annotation; lingering codepoints drop.+ # Force-drain segments still awaiting an annotation.tail_flushed = _drain_pending_segments(force = True,)@@ -5901,12 +5679,9 @@ class ExternalProviderClient:if reasoning_open:yield _chunk_with_text("</think>")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 scan both. Emit `container_ready` only- # when the value differs from the inbound one — no- # churn on reuse.+ # Scan response.container_id and response.container.id+ # (docs don't pin the field); emit container_ready+ # only when it differs from the inbound id.response_obj = event.get("response") or {}if isinstance(response_obj, dict):probe_id = response_obj.get("container_id")@@ -5932,10 +5707,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.+ # Overwrite the last web_search card with the+ # citation list (the extractor flatMaps cards).if web_search_calls and all_url_citations:last_id = list(web_search_calls.keys())[-1]blocks: list[str] = []@@ -6018,12 +5791,7 @@ class ExternalProviderClient:if reasoning_open:yield _chunk_with_text("</think>")reasoning_open = False- # Same backfill as response.completed — apply- # 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.+ # Same citation backfill as response.completed.if web_search_calls and all_url_citations:last_id = list(web_search_calls.keys())[-1]blocks = []@@ -6096,22 +5864,16 @@ class ExternalProviderClient:await lines_gen.aclose()raisefinally:- # 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?+ # Per-turn tool summary for triage.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)queries = [sc["query"] for sc in web_search_calls.values() if sc.get("query")]- # 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 at+ # On /v1/responses cached tokens live at# usage.input_tokens_details.cached_tokens (not- # prompt_tokens_details, the /v1/chat/completions shape).+ # prompt_tokens_details, the chat/completions shape).cached_input_tokens = Noneif isinstance(last_usage, dict):details = last_usage.get("input_tokens_details")@@ -6212,15 +5974,11 @@ class ExternalProviderClient:return response.json()async def list_models(self) -> list[dict[str, Any]]:- """- Call GET /models on the provider to discover available models.-- Returns model dicts with at least 'id' and optionally 'created',- 'owned_by', etc.+ """GET /models to discover available models.- All supported providers expose a /models endpoint:- - OpenAI-compatible: standard {"data": [...]} response- - Anthropic: https://api.anthropic.com/v1/models — same {"data": [...]} shape+ Returns dicts with at least 'id'. All providers expose /models with the+ OpenAI {"data": [...]} shape (Anthropic included:+ https://api.anthropic.com/v1/models)."""try:response = await _http_client.get(@@ -6230,7 +5988,6 @@ class ExternalProviderClient:)response.raise_for_status()data = response.json()- # OpenAI format: {"data": [{"id": "...", ...}, ...]}# Some local servers (Ollama with no models) return data: null.models: list[dict[str, Any]] = []if isinstance(data, dict):@@ -6239,10 +5996,8 @@ class ExternalProviderClient:models = [model for model in raw_models if isinstance(model, dict)]if not models and self.provider_type == "ollama":models = await self._list_ollama_native_models()- # Gemini's native /v1beta/models returns- # {"models": [{"name": "models/gemini-2.5-flash", ...}]}- # -- repackage into the OpenAI-compatible shape the rest of Studio- # expects so dynamic model discovery works.+ # Gemini's native /v1beta/models uses a different shape; repackage+ # into the OpenAI-compatible one Studio expects.if not models and self.provider_type == "gemini":models = self._parse_gemini_models(data)return models@@ -6252,17 +6007,9 @@ class ExternalProviderClient:@staticmethoddef _parse_gemini_models(payload: Any) -> list[dict[str, Any]]:- """Translate Gemini's native /v1beta/models payload to OpenAI shape.-- Native response:- {"models": [{"name": "models/gemini-2.5-flash",- "baseModelId": "gemini-2.5-flash",- "displayName": "Gemini 2.5 Flash",- "supportedGenerationMethods": [...]}]}-- We only keep entries that advertise ``generateContent`` /- ``streamGenerateContent`` so the picker doesn't surface embedding-only- models the chat path can't drive.+ """Translate Gemini's native /v1beta/models payload to OpenAI shape,+ keeping only entries advertising generateContent / streamGenerateContent+ so embedding-only models don't reach the chat picker."""if not isinstance(payload, dict):return []@@ -6349,29 +6096,16 @@ class ExternalProviderClient:raisedef _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 doesn't actually remove the container- (verified 2026-05-15). The header is required for list / create / delete- to behave consistently.- """+ """Auth headers plus the required ``OpenAI-Beta: containers=v1`` opt-in;+ without it DELETE silently no-ops (returns deleted:true but keeps the+ container, verified 2026-05-15)."""headers = self._auth_headers()headers["OpenAI-Beta"] = "containers=v1"return headersasync def list_openai_containers(self) -> list[dict[str, Any]]:- """- 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.-- 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.+ """GET /v1/containers; returns raw container records (the route reshapes+ them). Only valid against api.openai.com (caller guards is_openai_cloud)."""response = await _http_client.get(f"{self.base_url}/containers",@@ -6412,17 +6146,11 @@ class ExternalProviderClient:return response.json()async def delete_openai_container(self, container_id: str) -> None:- """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 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.+ """DELETE /v1/containers/{id}. 404s surface as HTTPError.- 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.+ Uses a fresh httpx client (shared-pool DELETEs returned deleted:true but+ left the container alive). Also verifies the body reports deleted:true,+ since OpenAI 2xx-returns that even when silently rejecting the request."""url = f"{self.base_url}/containers/{container_id}"headers = self._container_headers()@@ -6513,35 +6241,17 @@ def _build_usage_chunk("""Build an OpenAI ``include_usage``-style SSE chunk carrying upstreamprompt-cache accounting back to the client.- Studio captured ``cache_creation_input_tokens`` /- ``cache_read_input_tokens`` (Anthropic) and- ``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 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``).+ Emits the standard chunk shape (``choices: []`` + ``usage`` block) so+ ``stream_options={"include_usage": true}`` clients keep working, plus the+ Anthropic-native counts as extra keys:+ usage.prompt_tokens_details.cached_tokens (both providers)+ usage.cache_creation_input_tokens (Anthropic-only)+ usage.cache_read_input_tokens (Anthropic-only)++ Anthropic's ``input_tokens`` excludes the cache buckets, so prompt_tokens+ sums all three (OpenAI Responses already folds cached tokens in).++ Returns ``None`` when there are no usage numbers to report."""if not isinstance(last_usage, dict):return Nonediff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 0cef6c41ff2..c44db7485d5 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -36,23 +36,13 @@ logger = get_logger(__name__)class HarmonyTextStreamer:"""Streaming text decoder for the gpt-oss harmony channel protocol.- 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 harmony- markup is visible, then uses stateful incremental parsing:-- - ``<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`` for drop-in use in ``generate_stream``.+ gpt-oss emits multi-channel output via ``<|channel|>analysis<|message|>...``+ / ``<|channel|>final<|message|>...``. Plain skip_special_tokens streaming+ glues channel names to content. This decodes with skip_special_tokens=False+ and parses statefully: emit ``<think>`` on first analysis, stream analysis,+ emit ``</think>`` on first final, stream final. Tracking per-channel lengths+ avoids the delta-on-transformed bug where wrapping tags shift position.+ Same put/end/iterator interface as TextIteratorStreamer."""import re as _re@@ -87,9 +77,7 @@ class HarmonyTextStreamer:self._analysis_emitted: int = 0 # chars of analysis content emittedself._final_emitted: int = 0 # chars of final content emitted- # ------------------------------------------------------------------# put / end — called from the generation thread- # ------------------------------------------------------------------def put(self, value):"""Receive new token IDs from model.generate()."""@@ -104,7 +92,7 @@ class HarmonyTextStreamer:ids = [value]if self._is_first_put and self.skip_prompt:- # First call is 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@@ -112,20 +100,20 @@ class HarmonyTextStreamer:self._token_ids.extend(ids)- # Decode only the generated part (after the prompt)+ # Decode only the generated part (after the prompt).gen_ids = self._token_ids[self._prompt_len :]raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)self._process_incremental(raw)def end(self):"""Signal generation is complete."""- # Final decode to capture remaining content+ # Final decode to capture remaining content.gen_ids = self._token_ids[self._prompt_len :]if gen_ids:raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)self._process_incremental(raw)- # Close any open think tags+ # Close any open think tags.if self._emitted_think_open and not self._emitted_think_close:self._queue.put("</think>")self._emitted_think_close = True@@ -133,9 +121,7 @@ class HarmonyTextStreamer:self._stop = Trueself._queue.put(None) # sentinel- # ------------------------------------------------------------------# Iterator interface — consumed by the streaming loop- # ------------------------------------------------------------------def __iter__(self):return self@@ -153,33 +139,19 @@ class HarmonyTextStreamer:raise StopIterationreturn val- # ------------------------------------------------------------------# Stateful incremental harmony protocol parsing- # ------------------------------------------------------------------def _process_incremental(self, raw: str) -> None:- """Parse harmony channels and emit per-channel deltas.-- 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- """- # raw has <|channel|> but no complete channel+message pair yet:- # buffer silently, don't emit partial channel names as text.+ """Parse harmony channels and emit per-channel deltas (tracked by length, not whole-text diff)."""+ # If raw has <|channel|> but no complete channel+message pair yet, buffer.has_channel_token = "<|channel|>" in rawmatches = list(self._HARMONY_RE.finditer(raw))if has_channel_token and not matches:- # Partial harmony markup still building — wait for more tokens+ # Partial harmony markup still building — wait for more tokens.returnif not has_channel_token and not matches:- # No harmony protocol (shouldn't happen for gpt-oss) — emit nothingreturnfor m in matches:@@ -221,11 +193,9 @@ class InferenceBackend:self.device = get_device().valueself._audio_codec_manager = AudioCodecManager()- # _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.+ # _generation_lock serializes model.generate(). Plain Lock (NOT RLock):+ # RLock reentrancy would let concurrent compare-mode requests race on+ # the GPU. Acquired by the background generation thread, not the event-loop.import threadingself._generation_lock = threading.Lock()@@ -313,14 +283,13 @@ class InferenceBackend:from unsloth import FastModelif config.is_lora and config.base_model:- # 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/).+ # LoRA adapter: base_model is .../Spark-TTS-0.5B/LLM;+ # BiCodec weights live in the parent dir.base_path = config.base_modelif os.path.isdir(base_path):abs_repo_path = os.path.abspath(os.path.dirname(base_path))else:- # base_model is an HF ID — download it+ # base_model is an HF ID — download it.from huggingface_hub import snapshot_downloadlocal_dir = base_path.split("/")[-1]@@ -463,17 +432,14 @@ class InferenceBackend: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). If so, load the real processor from- # the base model.+ # FastVisionModel may return a raw tokenizer instead of a+ # Processor for some models (e.g. Gemma-3); load the real one.from transformers import ProcessorMixinif not (isinstance(processor, ProcessorMixin) or hasattr(processor, "image_processor")):- # LoRA adapters: use the base model. Local merged exports:- # read export_metadata.json for the original base model.+ # LoRA adapters: use base model. Local merged exports: read base from export_metadata.json.processor_source = config.base_model if config.is_lora else config.identifierif not config.is_lora and config.is_local:_meta_path = Path(config.path) / "export_metadata.json"@@ -557,9 +523,8 @@ class InferenceBackend:clear_gpu_cache()- # 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.+ # Drop stale compiled cache for the next model. On spawn platforms,+ # preserve trainer files so concurrent dataset.map() workers can import them.import sys as _sysfrom utils.cache_cleanup import clear_unsloth_compiled_cache@@ -593,9 +558,8 @@ class InferenceBackend:self.models[base_model_name]["model"] = unwrapped_base_modelmodel = unwrapped_base_model- # 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.+ # model.unload() can leave a peft_config; removing it avoids+ # "multiple adapters" warnings on the next from_pretrained().if hasattr(model, "peft_config"):del model.peft_config@@ -701,8 +665,7 @@ class InferenceBackend:return Falsedef set_active_adapter(self, base_model_name: str, adapter_name: str) -> bool:- """Set the active adapter for generation (replaces the flawed- 'enable_adapter')."""+ """Set the active adapter for generation."""model = self.models[base_model_name].get("model")try:logger.info(f"Setting active adapter to: '{adapter_name}'")@@ -715,16 +678,11 @@ class InferenceBackend:return Falsedef _apply_adapter_state(self, use_adapter: Optional[Union[bool, str]]) -> None:- """Apply adapter state before generation. Must hold _generation_lock.-- 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.+ """Apply adapter state before generation (must hold _generation_lock).- Args:- use_adapter: None = no change, False = disable (base model),- True = enable current adapter, str = enable specific adapter.+ Toggles PEFT enable/disable_adapter_layers (non-destructive, no reload).+ use_adapter: None = no change, False = base model, True = current adapter,+ str = named adapter."""if use_adapter is None:return@@ -739,7 +697,7 @@ class InferenceBackend:returnif use_adapter is False:- # Disable LoRA layers → base model output+ # Disable LoRA layers -> base model output.if isinstance(model, (PeftModel, PeftModelForCausalLM)):logger.info(f"Compare mode: disabling adapters on '{base}' for base model generation"@@ -749,7 +707,7 @@ class InferenceBackend:logger.info(f"Compare mode: model '{base}' is not a PeftModel, already base")elif use_adapter is True:- # Re-enable LoRA layers → adapter output+ # Re-enable LoRA layers -> adapter output.if isinstance(model, (PeftModel, PeftModelForCausalLM)):logger.info(f"Compare mode: enabling adapters on '{base}' for LoRA generation")model.base_model.enable_adapter_layers()@@ -757,7 +715,7 @@ class InferenceBackend:logger.warning("use_adapter=true but model is not a PeftModel")elif isinstance(use_adapter, str):- # Enable adapters and set the named one active+ # 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()@@ -773,14 +731,9 @@ class InferenceBackend:) -> Generator[str, None, None]:"""Thread-safe generation with optional adapter toggling.- The adapter toggle + model.generate() are serialized by _generation_lock- 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.- **gen_kwargs: Forwarded to generate_chat_response.+ Adapter toggle + model.generate() are serialized by _generation_lock in+ the background thread, avoiding the RLock-reentrant race when two async+ SSE handlers share one event-loop thread. use_adapter: see _apply_adapter_state."""yield from self._generate_chat_response_inner(cancel_event = cancel_event, _adapter_state = use_adapter, **gen_kwargs@@ -870,14 +823,11 @@ class InferenceBackend:reasoning_effort: Optional[str] = None,preserve_thinking: Optional[bool] = None,) -> Generator[str, None, None]:- """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 them- (Qwen3, Llama 3.1+, gpt-oss harmony, ...) advertise the tool schemas- and reasoning controls to the model.+ """Generate response for text or vision models (lock held by background thread).++ ``tools`` / ``enable_thinking`` / ``reasoning_effort`` / ``preserve_thinking``+ are forwarded into ``apply_chat_template`` so templates that understand them+ (Qwen3, Llama 3.1+, gpt-oss harmony) advertise tool schemas / reasoning controls."""yield from self._generate_chat_response_inner(messages = messages,@@ -927,15 +877,13 @@ class InferenceBackend:model_info = self.models[self.active_model_name]is_vision = model_info.get("is_vision", False)tokenizer = model_info.get("tokenizer") or model_info.get("processor")- # Unwrap processor → raw tokenizer for VLMs on the text path+ # Unwrap processor -> raw tokenizer for VLMs on the text path.tokenizer = getattr(tokenizer, "tokenizer", tokenizer)top_k = self._normalize_top_k(top_k)if is_vision and image:- # 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).+ # Verify the stored processor can handle images; FastVisionModel may+ # return a raw tokenizer instead of a ProcessorMixin (e.g. Gemma-3).from transformers import ProcessorMixinprocessor = model_info.get("processor")@@ -963,10 +911,9 @@ class InferenceBackend:f"falling back to text-only generation (image will be ignored).")- # Text path: training-pipeline approach. Messages are already in- # ChatML format from eval.py.+ # Text path: 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,@@ -980,7 +927,6 @@ class InferenceBackend:f"Applying chat template '{template_name}' for {self.active_model_name}")- # Sets the correct template on the tokenizertokenizer = get_chat_template(tokenizer,chat_template = template_name,@@ -992,7 +938,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}] + messageselse:diff --git a/studio/backend/core/inference/key_exchange.py b/studio/backend/core/inference/key_exchange.pyindex ddc726751db..15ebf0e4c0e 100644--- a/studio/backend/core/inference/key_exchange.py+++ b/studio/backend/core/inference/key_exchange.py@@ -36,9 +36,7 @@ def init_key_pair() -> None:"""Generate an RSA-2048 key pair. Called once at server startup."""global _private_key, _public_key_pem, _public_key_fingerprintif _private_key is not None:- # 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.+ # Re-entry invalidates in-flight ciphertext from the old public key; log loudly.logger.warning("init_key_pair called again — replacing existing RSA keypair ""(previous fingerprint=%s). Any frontend that cached the old "@@ -111,9 +109,8 @@ def decrypt_api_key(encrypted_b64: str) -> str:),)except Exception as exc:- # 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.+ # Log state to distinguish key mismatch from padding/algo mismatch or+ # corrupted bytes. RSA-2048 ciphertext 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.pyindex e2b2533d2ec..4d4ae57afe8 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.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-"""-llama-server inference backend for GGUF models.+"""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@@ -79,17 +78,13 @@ _INTENT_SIGNAL = re.compile()_MAX_REPROMPTS = 3-# 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 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 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.+# Without max_tokens, llama-server defaults n_predict = n_ctx (up to 262144 for+# Qwen3.5), causing many-minute zombie decodes when cancel fails.+# t_max_predict_ms is a wall-clock backstop but per the llama.cpp README only+# fires after a newline, so we keep a token cap as the front-line limiter.+# The cap is the effective context length when known, else this floor. 4096 was+# too low: Qwen3 / gpt-oss reasoning traces and max_tokens-omitting OpenAI-API+# callers (langchain, llama-index, curl) got truncated mid-sentence._DEFAULT_MAX_TOKENS_FLOOR = 32768_DEFAULT_T_MAX_PREDICT_MS = 600_000 # 10 min_REPROMPT_MAX_CHARS = 2000@@ -123,8 +118,8 @@ _SWA_CACHE_LOCK = threading.Lock()def _probe_dns_dead(host: str = "huggingface.co", timeout: float = 2.0) -> bool:- """Quick DNS check on a daemon thread, so concurrent sockets in the- same process aren't affected by socket.setdefaulttimeout."""+ """Quick DNS check on a daemon thread, so concurrent sockets aren't+ affected by socket.setdefaulttimeout."""result: list[Optional[bool]] = [None]def _probe() -> None:@@ -143,9 +138,9 @@ def _probe_dns_dead(host: str = "huggingface.co", timeout: float = 2.0) -> bool:@contextlib.contextmanagerdef _hf_offline_if_dns_dead():- """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."""+ """Set HF_HUB_OFFLINE for this block only when DNS to huggingface.co fails;+ restores env on exit so a transient hiccup can't quarantine the process.+ No-op if the user already set it."""if "HF_HUB_OFFLINE" in os.environ:yield Falsereturn@@ -200,8 +195,7 @@ 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, else None."""if not layer_types:return Noneis_swa = ["full" not in str(t).lower() for t in layer_types]@@ -368,7 +362,6 @@ def _hf_repo_from_url(url: Optional[str]) -> Optional[str]:# 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_breturn extract_model_size_b(model_id)@@ -589,8 +582,7 @@ def _backfill_usage_from_timings(usage, timings):class LlamaCppBackend:- """- Manages a llama-server subprocess for GGUF model inference.+ """Manages a llama-server subprocess for GGUF model inference.Lifecycle:1. load_model() — start llama-server with the GGUF file@@ -622,11 +614,10 @@ class LlamaCppBackend:self._cache_type_kv: Optional[str] = Noneself._reasoning_default: bool = Trueself._speculative_type: Optional[str] = None- # 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, not the resolved internal flag set (auto on a 27B MTP- # GGUF resolves to draft-mtp but the dropdown still reads "Auto").+ # 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, not the resolved+ # flag set (auto on a 27B MTP GGUF resolves to draft-mtp but reads "Auto").self._requested_spec_mode: Optional[str] = None# User --spec-draft-n-max override (None = platform default).self._spec_draft_n_max: Optional[int] = None@@ -654,14 +645,13 @@ class LlamaCppBackend:# MTP head count (llama.cpp #22673); >0 enables --spec-type draft-mtp.self._nextn_predict_layers: Optional[int] = Noneself._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).- # ``_extra_args_source`` records the (model_identifier, hf_variant)- # the stored args came from so the route can refuse cross-model- # inheritance.+ # 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.self._extra_args: Optional[List[str]] = Noneself._extra_args_source: Optional[tuple[str, Optional[str]]] = Noneself._requested_n_ctx: int = 0@@ -742,12 +732,10 @@ class LlamaCppBackend:def max_context_length(self) -> Optional[int]:"""Return the largest context that fits on this hardware at load time.- 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.+ The UI's "safe zone" warning threshold: the ``_fit_context_to_vram``+ binary-search cap for the best GPU subset, or the 4096 fallback if the+ weights exceed 90% of every subset. The slider ceiling is+ ``native_context_length``; dragging above this triggers the warning."""return self._max_context_length or self._context_length@@ -759,16 +747,11 @@ class LlamaCppBackend:def load_progress(self) -> Optional[dict]:"""Return live model-load progress, or None if not loading.- 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.-- 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).+ During warm-up llama-server mmaps weight shards into page cache before+ pushing layers to VRAM, a window where status only reports ``loading``+ and the UI spinner looks stuck for minutes on large MoEs. Samples+ ``/proc/<pid>/status VmRSS`` against the sum of GGUF shard sizes for a+ real progress bar. Returns ``None`` when no load is in flight.Shape::@@ -779,8 +762,7 @@ class LlamaCppBackend:"fraction": float, # bytes_loaded / bytes_total, 0..1}- Linux-only for now; returns ``None`` where ``/proc/<pid>/status``- is unavailable (macOS/Windows would need a different API).+ Linux-only; returns ``None`` where ``/proc/<pid>/status`` is unavailable."""proc = self._processif proc is None:@@ -799,8 +781,7 @@ class LlamaCppBackend:bytes_total += primary.stat().st_sizeexcept OSError:pass- # Extra shards share the primary's prefix before the shard- # index (e.g. ``-00001-of-00004.gguf``).+ # Extra shards share the primary's prefix before the shard index.try:parent = primary.parentstem = primary.name@@ -1209,10 +1190,9 @@ class LlamaCppBackend:@staticmethoddef _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.*; gcnArchName suffix is- stripped."""+ GGML_CUDA_ENABLE_UNIFIED_MEMORY lets llama.cpp use shared system RAM.+ False elsewhere (the env hurts discrete GPUs). ROCm reuses torch.cuda.*;+ gcnArchName suffix is stripped."""try:import torch@@ -1266,11 +1246,9 @@ class LlamaCppBackend:cvd = os.environ.get("CUDA_VISIBLE_DEVICES")if cvd is not None:try:- # `if x.strip()` filters trailing-comma masks like- # "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.+ # `if x.strip()` filters trailing-comma masks ("0,1,").+ # Empty mask (CVD="") yields an empty set -> all GPUs+ # filtered out, per codebase convention.allowed = set(int(x.strip()) for x in cvd.split(",") if x.strip())except ValueError:pass@@ -1283,8 +1261,7 @@ class LlamaCppBackend:if allowed is not None and idx not in allowed:continuegpus.append((idx, free_mib))- # Match the docstring's sort-by-id guarantee; nvidia-smi- # output is usually sorted but driver order isn't guaranteed.+ # Match the docstring's sort-by-id guarantee (driver order isn't).gpus.sort(key = lambda g: g[0])if gpus:return gpus@@ -1299,19 +1276,14 @@ class LlamaCppBackend:return []if not hasattr(torch.cuda, "mem_get_info"):return []- # 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.+ # torch.cuda enumerates GPUs RELATIVE to the visibility mask. We+ # feed these IDs back into the subprocess as CVD, so visible ordinals+ # must be translated to physical indices first; otherwise CVD=2,3+ # gets rewritten to 0,1 and targets the wrong GPUs.physical_ids: Optional[list[int]] = None- # 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.+ # Match utils/hardware/hardware.py::_get_parent_visible_gpu_spec:+ # treat an empty mask (HIP_VISIBLE_DEVICES="") as "no GPUs" rather+ # than falling through. ``or`` would coerce "" to the wrong source.if getattr(torch.version, "hip", None) is not None:hip_v = os.environ.get("HIP_VISIBLE_DEVICES")rocr_v = os.environ.get("ROCR_VISIBLE_DEVICES")@@ -1326,9 +1298,8 @@ class LlamaCppBackend:cvd = os.environ.get("CUDA_VISIBLE_DEVICES")if cvd is not None:try:- # Empty mask (CVD="") yields an empty list so the loop- # produces no GPUs, consistent with the nvidia-smi path- # and utils/hardware/hardware.py.+ # Empty mask (CVD="") yields an empty list -> no GPUs,+ # consistent with the nvidia-smi path.physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]except ValueError:physical_ids = None@@ -1361,16 +1332,14 @@ class LlamaCppBackend:"""Poll ``_get_gpu_free_memory`` until free VRAM stabilises.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.+ sampling free memory in the kill-to-spawn window reads artificially low+ and pushes GPU selection toward needless CPU offload (the Apply-reload+ OOM bare-shell launches never see).++ Short-circuits on cold start, stale kill (older than+ ``_VRAM_SETTLE_WINDOW_S``), CPU-only hosts, probe exceptions, and GPU-set+ changes. ``max_wait`` bounds wall-clock time so a wedged ``nvidia-smi``+ can't extend the reload."""now = time.monotonic()if since_kill <= 0.0:@@ -1406,8 +1375,7 @@ class LlamaCppBackend:stable = Falsebreakprev_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.per_gpu_tol = max(tolerance_mib, int(max(free, prev_free) * 0.02))if abs(free - prev_free) >= per_gpu_tol:stable = False@@ -1418,34 +1386,25 @@ class LlamaCppBackend:# 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.+ # buffers; 0.90 dropped 91-94% fits to CPU offload (#5106)._GPU_PIN_VRAM_FRACTION = 0.95@staticmethoddef _windows_pip_nvidia_dll_dirs(prefix: str) -> list[str]:"""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 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 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)."""+ ``cudart64_X.dll`` / ``cublas64_X.dll`` without a system CUDA toolkit.+ Mirrors the Linux ``nvidia/cu*/lib`` LD_LIBRARY_PATH block, covering the+ Windows wheel layouts seen in the wild:+ * ``nvidia/<pkg>/bin`` -- legacy modular wheels.+ * ``nvidia/<pkg>/bin/x86_64`` and ``.../bin/x64`` -- CUDA 13 layout+ for unsuffixed packages (#5106).+ * ``nvidia/<pkg>/Library/bin`` (and arch subdirs) -- conda repacks.+ * ``torch/lib`` -- PyTorch's CUDA-bundled wheel can ship+ ``cudart64_*.dll`` here; mirrors install_llama_prebuilt.py.++ Walks with ``Path.iterdir`` not ``glob.glob`` so it's safe against+ Windows paths containing ``[`` or ``]`` (valid in usernames)."""site_packages = Path(prefix) / "Lib" / "site-packages"out: list[str] = []seen: set[str] = set()@@ -1464,8 +1423,8 @@ class LlamaCppBackend:for pkg_dir in nvidia_root.iterdir():if not pkg_dir.is_dir():continue- # Order matters: arch-specific subdirs first so the explicit- # cudart64_X.dll location wins over an empty sibling ``bin``.+ # 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",@@ -1480,11 +1439,9 @@ class LlamaCppBackend:@staticmethoddef _build_windows_path_dirs(binary_dir: str, prefix: str, cuda_path: str) -> list[str]:- """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 the- production logic, not a hand-copy. #5106."""+ """Ordered PATH entries prepended so llama-server.exe resolves cudart /+ cublas DLLs: binary_dir, pip nvidia wheels, CUDA_PATH/bin, .../bin/x64.+ Extracted so test_windows_gpu_detection_mock tests the real logic. #5106."""path_dirs = [binary_dir]path_dirs.extend(LlamaCppBackend._windows_pip_nvidia_dll_dirs(prefix))if cuda_path:@@ -1547,10 +1504,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 suffices (K-only cache)+ # MLA: kv_lora_rank suffices (K-only cache).if self._kv_lora_rank is not None:return True- # New-style: need 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).@@ -1585,20 +1542,14 @@ class LlamaCppBackend:5. Legacy -- fallback using embed // n_headsServer-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- 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.+ swa_full -- ``--swa-full``: force SWA layers to cache full+ ``n_ctx`` (collapses path 3 to path 4 for them).+ n_parallel -- ``--parallel`` slots: non-SWA layers stay constant+ (cells split across slots), SWA layers scale linearly.+ kv_unified -- ``--kv-unified`` (default on): no-op for memory math;+ kept for API forward-compat.+ ctx_checkpoints -- ``--ctx-checkpoints`` (PR #15293): N SWA snapshots+ per slot, one sliding-window of state per SWA layer.Returns 0 if metadata is insufficient."""@@ -1606,9 +1557,8 @@ class LlamaCppBackend:return 0n_layers = self._n_layers # type: ignore[assignment]- # 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.+ # Gemma 3n / Gemma 4 reuse earlier KV in the last ``shared_kv_layers``+ # blocks (no cache). Floor at 1 so a bad GGUF can't zero out KV.shared = self._shared_kv_layers or 0n_layers_kv = max(1, n_layers - shared)n_kv = self._n_kv_heads or self._n_heads or 1 # type: ignore[assignment]@@ -1629,11 +1579,10 @@ class LlamaCppBackend:slots = max(1, n_parallel)# Path 1: MLA (DeepSeek-V2/V3, GLM-4.7, GLM-5, Kimi-K2.5)- # 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 128x's.+ # One compressed KV latent per token/layer (shared across heads); V is+ # reconstructed from it, no separate V cache. key_length = kv_lora_rank+ # + rope_dim. 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 128x's.if self._kv_lora_rank is not None:n_kv_mla = self._n_kv_heads or 1rope_dim = self._key_length_mla or 64@@ -1644,7 +1593,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; rest are Mamba (no KV cache).+ # Only 1 in N layers is attention; the 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_intervaln_attn = -(-n_layers // fai) if fai > 0 else n_layers # ceiling division@@ -1654,18 +1603,14 @@ 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 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 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.+ # Pattern filled 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 split across slots -> CONSTANT.+ # * SWA layers: per-slot cells = 2*sliding_window (capped at n_ctx+ # and per_slot_ctx) -> grows LINEARLY in slots.+ # --swa-full forces full n_ctx for SWA layers; --ctx-checkpoints N adds+ # N snapshots per SWA layer per slot.if (self._sliding_window is not Noneand self._sliding_window > 0@@ -1674,11 +1619,9 @@ class LlamaCppBackend:):swa = self._sliding_windowper_slot_ctx = max(1, n_ctx // slots)- # ``--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-full caches full context like non-SWA (per-slot cells =+ # per_slot_ctx, collapsing to constant n_ctx total); otherwise SWA+ # caches 2*sliding_window per slot, clamped at 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_lenval_len_swa = self._kv_value_length_swa or val_len@@ -1686,8 +1629,8 @@ class LlamaCppBackend:global_bytes = 0.0 # constant across slotsswa_bytes_per_slot = 0.0 # multiplied by slotscheckpoint_extra_per_slot = 0.0- # Only layers that allocate their own KV; 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 = (@@ -1748,20 +1691,15 @@ class LlamaCppBackend:"""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.-- ``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- 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 a slower partial-offload path.+ ``_GPU_PIN_VRAM_FRACTION`` on purpose (over-promising context OOMs at+ runtime). If the weights alone don't fit, returns ``requested_ctx``.++ ``kv_on_gpu`` mirrors ``--kv-offload`` (default on); when False the KV+ cache lives in CPU RAM and 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 buffers, else tight tiers (e.g. 32 GB) spill to a slower path."""if not self._can_estimate_kv():logger.debug(@@ -1792,8 +1730,7 @@ class LlamaCppBackend:if model_footprint + kv <= budget_bytes:return requested_ctx- # Weights alone exceed budget -- reducing ctx can't help. Return- # requested_ctx unchanged; --fit will handle VRAM management.+ # Weights alone exceed budget -- reducing ctx can't help; --fit handles it.if model_footprint >= budget_bytes:logger.debug("Model footprint exceeds GPU budget before KV cache",@@ -1886,16 +1823,13 @@ class LlamaCppBackend:# ── Stdout drain (prevents pipe deadlock on Windows) ─────────def _drain_stdout(self):- """- Read subprocess stdout lines in a background thread.-- Prevents a pipe-buffer deadlock on Windows (default buffer ~4 KB):- without draining, llama-server blocks on writes and never becomes- healthy.+ """Read subprocess stdout lines in a background thread.+ Prevents a pipe-buffer deadlock on Windows (~4 KB buffer): 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 output even if the crash- predates the drain-thread join in ``_wait_for_health``.+ post-mortem has the full output even if the crash predates the+ drain-thread join in ``_wait_for_health``."""try:for line in self._process.stdout:@@ -1912,7 +1846,7 @@ class LlamaCppBackend:# Log file closed under us; tee silently.passexcept (ValueError, OSError):- # Pipe closed -- process terminating+ # Pipe closed -- process terminating.pass# GGUF KV type sizes for fast skipping@@ -2486,13 +2420,13 @@ class LlamaCppBackend:# ── Lifecycle ─────────────────────────────────────────────────# GGUF ``general.architecture`` values for diffusion / image models.- # llama.cpp proper has no such architectures, so loading one as a chat- # model dies with "unknown model architecture: '<arch>'". These match- # 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 a substring) so a chat arch merely containing a- # short token like "wan"/"sd1" (e.g. "taiwan") isn't misrouted to Images.+ # llama.cpp has no such architectures, so loading one as a chat model dies+ # with "unknown model architecture: '<arch>'". These match the patched+ # stable-diffusion.cpp / ComfyUI-GGUF enums. Unsloth publishes FLUX and+ # Qwen-Image GGUFs under+ # https://huggingface.co/collections/unsloth/unsloth-diffusion-ggufs.+ # Matched exactly (not a substring) so a chat arch containing "wan"/"sd1"+ # (e.g. "taiwan") isn't misrouted to Images._DIFFUSION_ARCHES = frozenset(("qwen_image",@@ -2517,12 +2451,10 @@ class LlamaCppBackend:"""Explain *why* llama-server failed to start, from its output.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.+ "invalid GGUF or out of memory" message. Worst case: a diffusion GGUF+ loaded as a chat model -- valid file, plenty of memory, but llama.cpp+ has no such architecture, so the user is told to free memory that was+ never the problem (#5842). Pick the most specific message we can."""lowered = (output or "").lower()@@ -2606,25 +2538,19 @@ class LlamaCppBackend:n_parallel: int = 1,extra_args: Optional[List[str]] = None,) -> bool:- """- Start llama-server with a GGUF model.+ """Start llama-server with a GGUF model.Two modes:- 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``+ - HF: ``hf_repo="...-GGUF", hf_variant="Q4_K_M"`` → uses ``-hf``- In HF mode, llama-server handles download, caching, and auto-loading- mmproj files for vision models.-- Returns True if the server started and health check passed.+ Returns True if the server started and the health check passed."""# Serialise the whole load so concurrent /load calls never leave two- # llama-server processes alive (#5401 / #5161). Doesn't block- # /unload, /status, /load-progress.+ # llama-server processes alive (#5401 / #5161). Doesn't block /unload.with self._serial_load_lock:- # 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.+ # Duplicate /load that raced past the route check: do nothing if the+ # live server already satisfies this request.if self._already_in_target_state(gguf_path = gguf_path,model_identifier = model_identifier,@@ -2721,13 +2647,12 @@ class LlamaCppBackend:else:raise ValueError("Either gguf_path or hf_repo must be provided")- # Set identifier early so _read_gguf_metadata can use it for DeepSeek detection+ # Set identifier early so _read_gguf_metadata can use it (DeepSeek).self._model_identifier = model_identifier- # Read GGUF metadata (context_length, chat_template); fast, header only+ # Read GGUF metadata (context_length, chat_template); header-only.self._read_gguf_metadata(model_path)- # Check cancel after downloadif self._cancel_event.is_set():logger.info("Load cancelled after download phase")return False@@ -2779,12 +2704,10 @@ class LlamaCppBackend:# 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, 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 /+ # Will MTP engage on this load? If so, auto-fit reserves+ # extra VRAM for the draft model. Mirrors+ # _build_speculative_flags' resolver: forced mtp / mtp+ngram+ # always engage; auto only on an MTP GGUF >= 3B; ngram /# ngram-simple / off never engage MTP._mtp_canonical = _canonicalize_spec_mode(speculative_type)_mtp_effective = _mtp_canonical or "auto"@@ -2805,16 +2728,13 @@ class LlamaCppBackend:))- # Auto-cap context to fit GPU VRAM and select GPUs.- # Two policies by 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.- #- # 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.+ # Auto-cap context to fit GPU VRAM and select GPUs. Two+ # policies by whether the user set n_ctx:+ # Explicit n_ctx: honor it. Try the full context with+ # _select_gpus (as many GPUs as needed); cap only if it+ # doesn't fit on any combination.+ # Auto n_ctx=0 (native): prefer fewer GPUs with reduced+ # context, since multi-GPU is slower.gpu_indices, use_fit = None, Trueexplicit_ctx = requested_ctx > 0@@ -2846,21 +2766,15 @@ class LlamaCppBackend:if best_cap > 0:max_available_ctx = best_capelse:- # Weights exceed 90% of every GPU subset's free- # 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.+ # Weights exceed 90% of every GPU subset, so no+ # context fits. Anchor the UI "safe zone" at 4096+ # so the slider warns above the fallback.max_available_ctx = min(4096, native_ctx_for_cap)if explicit_ctx:# 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 should have- # surfaced the "might be slower" warning before a- # ctx above the fit ceiling was submitted.+ # pin GPUs and skip --fit; else ship -c <ctx> --fit+ # on and let llama-server flex -ngl (CPU offload).requested_total = model_size + self._estimate_kv_cache_bytes(effective_ctx, cache_type_kv, n_parallel = n_parallel)@@ -2893,9 +2807,8 @@ class LlamaCppBackend:breakelse:# 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 --fit on: a model overflowing+ # at 131k may pin fine with a 4096 KV (#5106).effective_ctx = min(4096, effective_ctx)if effective_ctx > 0:for n_gpus in range(1, len(ranked) + 1):@@ -2913,18 +2826,16 @@ class LlamaCppBackend:breakelif gpus:- # 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).+ # Can't estimate KV -- file-size-only check; keep the+ # ceiling at native context (already the default).logger.debug("Falling back to file-size-only GPU selection",model_size_gb = round(model_size / (1024**3), 2),)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 flexes -ngl at runtime.+ # Weights don't fit on any subset; default UI to 4096+ # so the slider isn't on an unusable native ctx.effective_ctx = min(4096, effective_ctx) if effective_ctx > 0 else 4096if effective_ctx < original_ctx:@@ -3036,29 +2947,8 @@ class LlamaCppBackend:else:self._cache_type_kv = None- # 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- # gpt-oss-120b code refactor | 181 t/s | 446 t/s | 2.5x- # 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- #- # Params from llama.cpp server README:- # --spec-ngram-mod-n-match 24 (lookup length)- # --spec-ngram-mod-n-min 48 --spec-ngram-mod-n-max 64- # (MoEs need long drafts; dense models can reduce these)- # ref: https://github.com/ggml-org/llama.cpp/blob/master/docs/speculative.md- # ref: https://github.com/ggml-org/llama.cpp/pull/19164- # 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.+ # Speculative decoding. See _build_speculative_flags for the+ # mode resolution, benchmarks, and llama.cpp references.spec_flags = self._build_speculative_flags(speculative_type = speculative_type,spec_draft_n_max = spec_draft_n_max,@@ -3097,9 +2987,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- # below 9B (0.8B, 2B, 4B) disable thinking by default; 9B+- # enable it. Always-on templates ignore the kwarg, so skip.+ # Default thinking mode for reasoning models. Qwen3.5/3.6 below+ # 9B 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 = Truemid = (model_identifier or "").lower()@@ -3132,10 +3022,9 @@ class LlamaCppBackend:else:self._api_key = None- # 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().+ # User pass-through args go last so llama.cpp's last-wins parsing+ # lets the user override Studio's auto-set flags. Already+ # validated by the route 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)}")@@ -3147,7 +3036,7 @@ class LlamaCppBackend:_log_cmd[_ki] = "<redacted>"logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")- # Set library paths so llama-server finds its shared libs and CUDA DLLs+ # Library paths so llama-server finds its shared libs and CUDA DLLs.import osimport sys@@ -3170,14 +3059,11 @@ class LlamaCppBackend:existing_path = env.get("PATH", "")env["PATH"] = ";".join(path_dirs) + ";" + existing_path- # ROCm: the llama.cpp prebuilt bundles its own rocblas.dll- # 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.+ # ROCm: the prebuilt bundles rocblas.dll but NOT the Tensile+ # kernel files (rocblas/library/*.dat + *.hsaco); the DLL+ # searches <binary_dir>/rocblas/library/ which doesn't exist+ # -> silent crash on the first GEMM. ROCBLAS_TENSILE_LIBPATH+ # repoints that search at the ROCm install._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")@@ -3191,10 +3077,9 @@ class LlamaCppBackend: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- # links against libcudart.so.13 / libcublas.so.13 which- # live here, not in /usr/local/cuda.+ # Pip-installed nvidia CUDA runtime libs. The prebuilt+ # binary links libcudart.so.13 / libcublas.so.13 which live+ # here, not in /usr/local/cuda.import glob as _globfor _nv_pattern in [@@ -3246,10 +3131,9 @@ class LlamaCppBackend:new_ld = ":".join(lib_dirs)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 inherited.+ # Pin to selected GPU(s). On ROCm, narrowing only+ # CUDA_VISIBLE_DEVICES leaves an AMD child seeing the full+ # HIP/ROCR set, so set those too.if gpu_indices is not None:pinned = ",".join(str(i) for i in gpu_indices)env["CUDA_VISIBLE_DEVICES"] = pinned@@ -3261,18 +3145,14 @@ class LlamaCppBackend:except Exception as e:logger.debug("Failed to set ROCm visibility env vars for child: %s", e)- # Defensive kill: if a concurrent load slipped past Phase 1- # (its `self._process` was None then) and already stored a- # Popen handle here, drop that orphan before we overwrite the- # reference. See issue #5161.+ # Defensive kill: drop an orphan Popen a concurrent load may+ # have stored before we overwrite the reference (#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 kept the last- # 50 lines. Path lives under the studio home alongside other- # Studio logs.+ # post-mortem has the full trail even when the parent only kept+ # the last 50 lines. Path is under the studio home.self._llama_log_fh = Nonetry:log_dir = _swa_cache_path().parent / "logs" / "llama-server"@@ -3306,10 +3186,9 @@ class LlamaCppBackend:)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 ``model_path``- # is what llama-server actually mmap's. Downstream consumers- # (load_progress, log lines, etc.) need the real on-disk path.+ # Store the resolved on-disk path, not the caller's kwarg: in+ # HF mode gguf_path is None and ``model_path`` is what+ # llama-server mmap's, which downstream consumers need.self._gguf_path = model_pathself._hf_repo = hf_repo# For local GGUF files, extract variant from filename if absent@@ -3326,9 +3205,8 @@ class LlamaCppBackend:self._is_vision = effective_is_visionself._model_identifier = model_identifier- # 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.+ # Store the effective (possibly capped) context separately; do+ # NOT overwrite _context_length (the native length for display).self._effective_context_length = (effective_ctx if effective_ctx > 0 else self._context_length)@@ -3349,11 +3227,10 @@ 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 start+ # can't poison the next inheritance check. None keeps prior, []+ # clears, list sets. Source records hf_variant for the route's+ # same_source check.if extra_args is not None:self._extra_args = list(extra_args)self._extra_args_source = (model_identifier, hf_variant)@@ -3454,6 +3331,10 @@ class LlamaCppBackend:gpt-oss-120b code refactor | 181 t/s | 446 t/s | 2.5xQwen3-235B offloaded | 12 t/s | 21 t/s | 1.8xgpt-oss-120b repeat (92% accept)| 181 t/s | 814 t/s | 4.5x+ Refs: https://github.com/ggml-org/llama.cpp/blob/master/docs/speculative.md+ https://github.com/ggml-org/llama.cpp/pull/19164+ https://github.com/ggml-org/llama.cpp/pull/18471+ MTP guide: unsloth.ai/docs/models/qwen3.6#mtp-guideSub-3B dense MTP regresses vs spec-off: the draft head's per-tokencost exceeds the acceptance savings at this scale. Q4_K_XL clean@@ -3472,10 +3353,8 @@ class LlamaCppBackend:self._spec_draft_n_max = Noneself._speculative_type = None- # Canonical UI-facing requested mode: auto / mtp / ngram /- # 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 UI-facing requested mode (legacy values mapped via+ # _canonicalize_spec_mode).canonical_mode = _canonicalize_spec_mode(speculative_type)is_mtp_model = bool(self._nextn_predict_layers) or (_is_mtp_model_name(model_identifier, model_path)@@ -3485,9 +3364,8 @@ class LlamaCppBackend:_mtp_too_small = _mtp_size_b is not None and _mtp_size_b < 3.0if user_owns_spec_type:- # User --spec-type in extra_args wins outright; suppress- # auto-emit to avoid a duplicate / conflicting spec block.- # Record requested mode as None.+ # User --spec-type wins outright; suppress auto-emit to avoid a+ # duplicate spec block.self._requested_spec_mode = Nonereturn flags@@ -3685,10 +3563,8 @@ class LlamaCppBackend:if _norm(self._cache_type_kv) != _norm(cache_type_kv):return False- # 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.+ # Compare on the canonical requested mode. With --spec-type in+ # extra_args the backend stores None; mirror that here.if _extra_args_set_spec_type(extra_args):req_mode = Noneelse:@@ -3697,10 +3573,9 @@ class LlamaCppBackend:if req_mode != backend_mode:return False- # 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.+ # spec_draft_n_max only matters when an MTP variant is engaged. Compare+ # on the resolved spec so an Auto request promoted to draft-mtp still+ # bounces a reload when n_max changes.if (self._speculative_type == "draft-mtp"and spec_draft_n_max is not None@@ -3727,9 +3602,8 @@ class LlamaCppBackend: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; CUDA/ROCm/Metal/Vulkan/OpenCL/SYCL are GPU, CPU* are not.gpu_markers = ("CUDA", "ROCm", "Metal", "Vulkan", "OpenCL", "SYCL")saw_buffer_line = Falsesaw_gpu_buffer = False@@ -3828,13 +3702,11 @@ class LlamaCppBackend:logger.warning(f"Error killing llama-server process: {e}")finally:self._process = None- # Clear healthy so a /load arriving during the replacement- # server's warm-up window can't short-circuit against the- # previous server's health (#5401).+ # Clear healthy so a /load during the replacement's warm-up 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 Apply paths record the kill.self._last_kill_monotonic = time.monotonic()if self._stdout_thread is not None:self._stdout_thread.join(timeout = 2)@@ -3863,10 +3735,8 @@ class LlamaCppBackend:"""try:# -- Build the ownership allowlist --------------------------------- # Two match kinds:- # exact_binaries -- env var overrides (exact path match only)- # install_roots -- Studio-owned dir trees (binary must be- # *under* one of these)+ # exact_binaries -- env var overrides (exact path match).+ # install_roots -- Studio-owned dir trees (binary must be under one).install_roots: list[Path] = []# Env-mode custom root (mirrors _find_llama_server_binary).@@ -3885,9 +3755,8 @@ class LlamaCppBackend:except (ImportError, OSError, ValueError):pass- # Primary install dir (default mode only). Env-mode skips this so- # a custom-root Studio can't kill a concurrent default-install- # Studio's llama-server (same OS user, different install).+ # Primary install dir (default mode only). Env-mode skips this so a+ # custom-root Studio can't kill a default-install Studio's server.if not _is_custom_root:install_roots.append(Path.home() / ".unsloth" / "llama.cpp")@@ -3947,8 +3816,7 @@ class LlamaCppBackend:exe_path = Path(exe).resolve()- # Ownership: exact binary match OR binary under a- # known install root (proper ancestry, not substring).+ # Ownership: exact match OR binary under a known root.is_ours = exe_path in exact_binaries or any(exe_path.is_relative_to(root) for root in resolved_roots)@@ -3987,10 +3855,9 @@ class LlamaCppBackend:if pid == my_pid:continue- # 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/<pid>/exe symlinks the real binary, avoiding+ # cmdline-parsing ambiguities; 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)@@ -4026,11 +3893,7 @@ class LlamaCppBackend:timeout: float = 120.0,interval: float = 0.5,) -> bool:- """- Poll llama-server's /health endpoint until it responds 200.-- Also monitors the subprocess for early exit/crash.- """+ """Poll llama-server's /health until 200; also detect early exit/crash."""deadline = time.monotonic() + timeouturl = f"http://127.0.0.1:{self._port}/health"@@ -4054,10 +3917,8 @@ class LlamaCppBackend:except (httpx.ConnectError,httpx.TimeoutException,- # ReadError covers TCP RST mid-read while llama-server is- # still binding the port (Windows: WinError 10054). The- # crash branch above catches a real exit; this keeps a- # transient socket close from masking it.+ # ReadError covers TCP RST mid-read while still binding the port+ # (Windows: WinError 10054); the crash branch catches real exits.httpx.ReadError,httpx.RemoteProtocolError,httpx.WriteError,@@ -4079,12 +3940,8 @@ class LlamaCppBackend:@staticmethoddef _build_openai_messages(messages: list[dict], image_b64: Optional[str] = None) -> list[dict]:- """- Build OpenAI-format messages, optionally injecting an image_url- content part into the last user message for vision models.-- Returns messages as-is if no image is provided.- """+ """Build OpenAI-format messages, optionally injecting an image_url part+ into the last user message for vision models. As-is if no image."""if not image_b64:return messages@@ -4115,13 +3972,10 @@ class LlamaCppBackend:def _iter_text_cancellable(response: "httpx.Response", cancel_event: Optional[threading.Event] = None) -> Generator[str, None, None]:- """Iterate over an httpx streaming response with cancel support.+ """Iterate 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,- unblocking iter_text() once the response exists. During normal- streaming llama-server sends tokens frequently, so the between-chunk- check is the primary mechanism.+ Checks cancel_event between chunks and on ReadTimeout; the+ _stream_with_retry watcher also closes the response on cancel."""text_iter = response.iter_text()while True:@@ -4149,18 +4003,11 @@ class LlamaCppBackend:):"""Open an httpx streaming POST with cancel support.- 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.+ Sends once with a long read timeout (120 s) so prefill finishes without+ a retry storm (the old 0.5 s timeout caused duplicate POSTs every half+ second). A watcher thread cancels by closing the response. httpx can't+ interrupt a blocked read before the response exists, so cancel during+ the header wait (1-5 s prefill) is deferred until headers arrive."""if cancel_event is not None and cancel_event.is_set():raise GeneratorExitdiff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 9d11157bf9a..66c7f10d425 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -72,10 +72,9 @@ _DENYLIST: frozenset[str] = frozenset().union(*_DENYLIST_GROUPS)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`.+ Peels `--key=value` to `--key`, treats `-1`/`-0.5` as values (shorts+ always start with a letter), and normalises attached `-np8` / `-np-1` /+ `-np8x` to `-np`. Mirrors the CLI's `_expand_attached_np_short`."""token = token.strip()if not token.startswith("-") or token in {"-", "--"}:@@ -162,8 +161,8 @@ _BOOLEAN_SHADOWING_FLAGS: frozenset[str] = frozenset({"--spec-default", "--jinjadef parse_ctx_override(args: Optional[Iterable[str]]) -> Optional[int]:"""Return the last user-supplied ``-c`` / ``--ctx-size`` value.- Mirrors llama.cpp's last-wins parsing for the one pass-through numeric- knob Studio's load-time fit logic needs to see.+ Mirrors llama.cpp's last-wins parsing for the one numeric knob Studio's+ load-time fit logic needs."""if not args:return None@@ -201,10 +200,8 @@ 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 ``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.+ Single source of truth for load_model's ctx-override conditional so+ tests don't reimplement and assert against their own logic."""override = parse_ctx_override(args)return override if override is not None else fallback_n_ctx@@ -213,10 +210,8 @@ 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.- 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.+ Recognises -ctk (key) and -ctv (value); treats both as one setting,+ since Studio's KV estimate has a single cache_type_kv knob."""if not args:return None@@ -271,8 +266,7 @@ def strip_shadowing_flags(Used when inheriting a previous load's ``llama_extra_args`` so aninherited `-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.+ cache / spec / template). Each ``strip_*`` toggle controls one group."""shadowing: set[str] = set()if strip_context:diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex d1a565b2323..9a7fd1f074d 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -31,20 +31,17 @@ 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 surrounding- # quotes on a token. Strip a matched pair so argv reaches the subprocess- # clean ('"C:\\Program Files\\node"' -> C:\\Program Files\\node).+ # posix=False keeps backslash paths but also keeps surrounding quotes;+ # strip a matched pair so argv reaches the subprocess clean.parts = [p[1:-1] if len(p) >= 2 and p[0] == p[-1] and p[0] in "\"'" else p for p in parts]return partsdef stdio_mcp_enabled() -> bool:- """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. Stays off for Colab- and any network (0.0.0.0) bind."""+ """stdio MCP servers spawn local processes as the backend user (bypassing the+ sandbox), so allowed only when the host is the user's own machine. The Tauri+ app sets UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1; localhost/self-hosted users can opt+ in with the same var. Off for Colab and any network (0.0.0.0) bind."""return os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") == "1"@@ -82,8 +79,8 @@ def _oauth_store():from key_value.aio.stores.filetree import FileTreeStorefrom 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.+ # Hash keys/collections — fastmcp uses raw URLs as keys, and FileTreeStore+ # would treat the "://" as nested directories._oauth_token_store = FileTreeStore(data_directory = ensure_dir(studio_root() / "mcp-oauth-tokens"),key_sanitization_strategy = AlwaysHashStrategy(),@@ -94,10 +91,9 @@ 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 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."""+ URL, so on server delete / URL change / OAuth disable we must clear them, else+ re-registering the same URL reuses the old account's token. Best-effort: store+ / OAuth failures must not 500 the delete / update route."""try:from fastmcp.client.auth import OAuthauth = OAuth(mcp_url = url, token_storage = _oauth_store())@@ -123,9 +119,8 @@ def _client(parts = parse_stdio_command(url)if not parts:raise ValueError(f"Empty stdio command: {url!r}")- # env vars ride the headers field (merged over the SDK's safe default- # env). keep_alive=False tears the subprocess down on exit, so a- # one-shot probe/tool call never leaves an orphan.+ # env vars ride the headers field (merged over the SDK default env).+ # keep_alive=False tears the subprocess down so a one-shot call leaves no orphan.return Client(StdioTransport(command = parts[0],@@ -191,10 +186,9 @@ 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 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.+ ``cancel_event``: optional ``threading.Event``. When set, the in-flight call is+ cancelled and a cancellation Error returned. Polled alongside the tool call via+ ``asyncio.wait`` so a /cancel POST interrupts even mid-network-read."""async def _call() -> Any:@@ -209,8 +203,7 @@ def call_tool_sync(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).+ # short-circuits before opening the transport / HTTP connection.if cancel_event is not None and cancel_event.is_set():raise _MCPCancelledcall_task = asyncio.create_task(_call())diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 31bca0f5d62..fbbdb9a7734 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -13,8 +13,7 @@ logger = get_logger(__name__)def _build_generation_stats(prompt_n, prompt_tps, gen_n, gen_tps):- """Map mlx_lm / mlx_vlm stream stats onto the usage/timings shape- llama-server emits so the chat speed popover renders the same."""+ """Map mlx stream stats onto the usage/timings shape llama-server emits."""prompt_n = int(prompt_n or 0)gen_n = int(gen_n or 0)prompt_tps = float(prompt_tps or 0.0)@@ -52,7 +51,6 @@ class MLXInferenceBackend:# usage/timings of the latest generation; shipped on gen_done.self.last_generation_stats = None- # MLX stateself._model = Noneself._tokenizer = Noneself._processor = None@@ -65,8 +63,7 @@ class MLXInferenceBackend:def _configure_memory_limits(self):"""Apply Metal memory caps before loading a model.- Mirrors MLXTrainer._configure_memory_limits defaults:- memory_limit = 85% of recommended working-set,+ memory_limit = 85% of recommended working-set;wired_limit = min(recommended, memory_limit). Recorded so unload canlower wired_limit back to release pinned RAM."""@@ -109,16 +106,10 @@ 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:`) 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.+ # GGUF guard. GGUF models are served by llama-server in the parent+ # process, not mlx-lm here. Reaching this with is_gguf=True means the+ # route's first detection flaked (transient HF Hub) but the subprocess+ # re-detected GGUF; raise loudly instead of a cryptic mlx_lm error.if getattr(config, "is_gguf", False):raise RuntimeError(f"MLXInferenceBackend cannot load GGUF model '{model_name}': "@@ -185,9 +176,8 @@ 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 ships it back and+ # the route layer classifies capabilities like the other paths.self._populate_chat_template_info(model_name)logger.info("Model %s loaded successfully", model_name)@@ -197,8 +187,7 @@ class MLXInferenceBackend:"""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 template the model actually uses."""+ resolved ``tokenizer.chat_template``."""entry = self.models.get(model_name)if not entry:return@@ -273,9 +262,8 @@ 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; rendered via+ # apply_chat_template_for_generation like the transformers path.tools = None,enable_thinking = None,reasoning_effort = None,@@ -385,8 +373,7 @@ class MLXInferenceBackend:min_p = float(min_p or 0.0),min_tokens_to_keep = 1,)- # Only build a logits processor for a non-trivial repetition penalty- # (1.0 is the no-op value).+ # Only build a logits processor for a non-trivial repetition penalty.logits_processors = Noneif repetition_penalty is not None and float(repetition_penalty) not in (0.0,@@ -421,7 +408,7 @@ class MLXInferenceBackend:):final_response = responsetoken_ids.append(response.token)- # Decode full sequence with skip_special_tokens — like GPU+ # Decode full sequence with skip_special_tokenscumulative = self._tokenizer.decode(token_ids,skip_special_tokens = True,@@ -467,9 +454,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 with their own+ # apply_chat_template + chat_template (e.g. Qwen2.5-VL) use it+ # directly; else fall back to the nested tokenizer.chat_target = self._processorif (getattr(self._processor, "apply_chat_template", None) is None@@ -487,8 +474,7 @@ class MLXInferenceBackend:preserve_thinking = preserve_thinking,)- # For VLM: always use mlx_vlm's stream_generate, which handles- # pixel_values properly (None for text-only, image for VLM)+ # mlx_vlm's stream_generate handles pixel_values (None for text-only)images = [image] if image is not None else Nonecumulative = ""@@ -498,11 +484,9 @@ class MLXInferenceBackend:image is not None,)# mlx_vlm.stream_generate forwards **kwargs into generate_step, which- # 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).+ # builds the sampler + logits_processors internally.+ # GOTCHA: generate_step expects ``temperature=`` (long form); ``temp=``+ # silently falls into **kwargs and is ignored, stuck at greedy 0.0.vlm_kwargs = dict(max_tokens = max_new_tokens,temperature = temperature,diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex d7fc1ef9a67..0cbdea13379 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -59,16 +59,15 @@ class InferenceOrchestrator:self._proc: Optional[mp.Process] = Noneself._cmd_queue: Any = Noneself._resp_queue: Any = None- self._cancel_event: Any = None # mp.Event — set to cancel generation instantly+ self._cancel_event: Any = None # mp.Event — set to cancel generationself._lock = threading.Lock()- self._gen_lock = threading.Lock() # Serializes generation — one request at a time+ self._gen_lock = threading.Lock() # Serializes generation- # Dispatcher state — for compare mode (adapter-controlled requests).- # These bypass _gen_lock: they send commands directly and read from- # per-request mailboxes. A dispatcher thread routes resp_queue events- # by request_id.+ # Dispatcher state for compare mode (adapter-controlled requests):+ # bypass _gen_lock, send commands directly, read from per-request+ # mailboxes routed by a dispatcher thread on request_id.self._mailboxes: dict[str, queue.Queue] = {}- self._mailbox_lock = threading.Lock() # Protects _mailboxes dict+ self._mailbox_lock = threading.Lock()self._dispatcher_thread: Optional[threading.Thread] = Noneself._dispatcher_stop = threading.Event()@@ -84,13 +83,11 @@ class InferenceOrchestrator:self._top_hub_cache: Optional[list[str]] = Noneself._top_models_ready = threading.Event()- # Version tracking for subprocess reuseself._current_transformers_major: Optional[str] = None # "4" or "5"atexit.register(self._cleanup)logger.info("InferenceOrchestrator initialized (subprocess mode)")- # Background fetch of top models from HFthreading.Thread(target = self._fetch_top_models, daemon = True, name = "top-models").start()# ------------------------------------------------------------------@@ -99,13 +96,13 @@ class InferenceOrchestrator:@propertydef default_models(self) -> list[str]:- # Wait up to 5s for background HF fetch to finish+ # Wait up to 5s for background HF fetchself._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), then HF- # download-ranked models to backfill. Send extras so the frontend- # still has 4 per category after removing downloaded ones.+ # Curated static defaults first, then HF download-ranked to backfill.+ # Send extras so the frontend keeps 4 per category after removing+ # downloaded ones.result: list[str] = []seen: set[str] = set()for m in self._static_models + top_gguf + top_hub:@@ -130,8 +127,7 @@ class InferenceOrchestrator:)if resp.status_code == 200:models = resp.json()- # Top 40 GGUFs - frontend pages through them via infinite- # scroll, so send a deep pool.+ # Top 40 GGUFs (deep pool for frontend infinite scroll)gguf_ids = [m["id"] for m in models if m.get("id", "").upper().endswith("-GGUF")][:40]@@ -189,14 +185,14 @@ class InferenceOrchestrator:def _shutdown_subprocess(self, timeout: float = 10.0) -> None:"""Gracefully shut down the inference subprocess."""- self._stop_dispatcher() # Stop dispatcher before killing subprocess+ self._stop_dispatcher() # before killing subprocessif self._proc is None or not self._proc.is_alive():self._proc = Nonereturn# 1. Cancel any ongoing generation first (instant via mp.Event)self._cancel_generation()- time.sleep(0.5) # Brief wait for generation to stop+ time.sleep(0.5)# 2. Drain stale responsesself._drain_queue()@@ -416,8 +412,8 @@ class InferenceOrchestrator:mbox.put(resp)continue- # No matching mailbox — maybe for a _gen_lock reader or orphaned.- # Can't un-get from mp.Queue, so just log a warning.+ # No matching mailbox (a _gen_lock reader or orphaned). Can't+ # un-get from mp.Queue, so just log.if rtype not in ("status",):logger.debug("Dispatcher: no mailbox for request_id=%s type=%s, dropping",@@ -446,13 +442,9 @@ class InferenceOrchestrator:) -> Generator[str, None, None]:"""Dispatched generation — sends command without holding _gen_lock.- Uses a per-request mailbox for tokens, so two compare-mode requests- can be queued in the subprocess at once, avoiding the- inter-generation round-trip overhead.-- The subprocess runs commands sequentially from its cmd_queue, so- generation stays serialized at the GPU level — this only avoids- orchestrator-level lock contention.+ Uses a per-request mailbox for tokens so two compare-mode requests can+ be queued at once. The subprocess still runs commands sequentially, so+ GPU work stays serialized; this only avoids orchestrator lock contention."""if not self._ensure_subprocess_alive():yield "Error: Inference subprocess is not running"@@ -528,7 +520,6 @@ class InferenceOrchestrator:# 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 requestself._drain_mailbox(mailbox, timeout = 5.0)returnyield resp.get("text", "")@@ -611,9 +602,8 @@ class InferenceOrchestrator:) -> bool:"""Load a model for inference.- Always spawns a fresh subprocess per load for a clean interpreter —- no stale unsloth patches, torch.compile caches, or- 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 getsource failures)."""from utils.transformers_version import needs_transformers_5@@ -643,15 +633,13 @@ class InferenceOrchestrator:sub_config["gpu_selection"] = gpu_selection# Always kill the existing subprocess and spawn fresh: reusing one- # after unsloth patches torch internals causes- # inspect.getsource() failures on the next load.+ # after unsloth patches torch internals breaks getsource on reload.if self._ensure_subprocess_alive():self._cancel_generation()time.sleep(0.3)self._shutdown_subprocess()elif self._proc is not None:- # Dead subprocess — clean upself._shutdown_subprocess(timeout = 2)disable_xet = sub_config.get("disable_xet", False) or (@@ -673,7 +661,7 @@ class InferenceOrchestrator:try:resp = self._wait_response("loaded")except DownloadStallError:- # First stall with Xet enabled -> retry with Xet disabled+ # First stall with Xet on -> retry with Xet disabledif attempt == 0 and not disable_xet:logger.warning("Download stalled for '%s' -- retrying with HF_HUB_DISABLE_XET=1",@@ -682,14 +670,13 @@ class InferenceOrchestrator:self._shutdown_subprocess(timeout = 5)disable_xet = Truecontinue- # Second stall (or xet already disabled) -> give up+ # Second stall (or xet already off) -> give upself._shutdown_subprocess(timeout = 5)raise RuntimeError(f"Download stalled for '{model_name}' even with "f"HF_HUB_DISABLE_XET=1 -- check your network connection")- # Got a response — check successif resp.get("success"):self._current_transformers_major = needed_majormodel_info = resp.get("model_info", {})@@ -703,8 +690,8 @@ class InferenceOrchestrator:"audio_type": model_info.get("audio_type"),"has_audio_input": model_info.get("has_audio_input", False),}- # Mirror chat_template_info so routes can classify- # capabilities without re-entering the subprocess.+ # Mirror chat_template_info so routes can classify caps+ # without re-entering the subprocess._tpl_info = model_info.get("chat_template_info")if isinstance(_tpl_info, dict):self.models[self.active_model_name]["chat_template_info"] = _tpl_info@@ -789,14 +776,12 @@ class InferenceOrchestrator:) -> Generator[str, None, None]:"""Generate response, streaming tokens from subprocess.- Optional ``tools`` / ``enable_thinking`` / ``reasoning_effort`` /- ``preserve_thinking`` kwargs are forwarded to the worker so- ``tokenizer.apply_chat_template`` can render tool schemas and- reasoning controls when the template supports them.+ ``tools`` / ``enable_thinking`` / ``reasoning_effort`` /+ ``preserve_thinking`` are forwarded so the template can render tool+ schemas and reasoning controls.``stats_holder``: caller-owned dict; on gen_done its "stats" key gets- the worker's usage/timings. Request-scoped so concurrent streams cannot- read each other's stats.+ the worker's usage/timings. Request-scoped to avoid cross-stream reads."""yield from self._generate_inner(messages = messages,@@ -840,12 +825,11 @@ 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 the parent process,+ calling the worker for each turn.Yields the same event dicts as the GGUF tool loop so the route layer- can stream both backends through one helper. See- ``safetensors_agentic.run_safetensors_tool_loop`` for the protocol.+ can stream both backends through one helper."""from core.inference.safetensors_agentic import run_safetensors_tool_loopfrom core.inference.tools import execute_tool@@ -853,8 +837,7 @@ class InferenceOrchestrator:max_new_tokens = max_tokens if max_tokens and max_tokens > 0 else 2048def _single_turn(conv: list):- # ``conv`` already carries any system message: the loop appends- # to a list seeded with system+user above.+ # ``conv`` already carries any system message.common_kwargs = dict(messages = conv,system_prompt = "",@@ -870,7 +853,7 @@ class InferenceOrchestrator:enable_thinking = enable_thinking,reasoning_effort = reasoning_effort,preserve_thinking = preserve_thinking,- # last turn wins, same as the GGUF tool loop's metadata+ # last turn wins, like the GGUF tool loopstats_holder = stats_holder,)if use_adapter is not None:@@ -949,14 +932,11 @@ class InferenceOrchestrator:yield "Error: No active model"return- # If the dispatcher is running (from a previous compare-mode request),- # wait for dispatched requests to finish then stop it, so we can read- # from resp_queue directly.+ # Drain any prior compare-mode dispatcher so we can read resp_queue.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: two concurrent readers on resp_queue would+ # consume and drop each other's token events.with self._gen_lock:yield from self._generate_locked(messages = messages,@@ -1020,8 +1000,7 @@ class InferenceOrchestrator:if use_adapter is not None:cmd["use_adapter"] = use_adapter- # Only forward template kwargs the caller set, so older workers that- # ignore unknown keys still work.+ # Only forward template kwargs the caller set, for older worker compat.if tools is not None:cmd["tools"] = toolsif enable_thinking is not None:@@ -1037,8 +1016,7 @@ class InferenceOrchestrator:yield f"Error: {exc}"return- # Yield tokens from response queue — we are the only reader since- # _gen_lock is held.+ # We are the only resp_queue reader (under _gen_lock).while True:resp = self._read_resp(timeout = 30.0)@@ -1065,9 +1043,8 @@ class InferenceOrchestrator:# 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 ack cancellation- # (gen_done/gen_error) so stale events don't leak into- # the next generation request.+ # Wait for the cancel ack so stale events don't leak into+ # the next request.self._drain_until_gen_done(timeout = 5.0)returnyield resp.get("text", "")@@ -1301,9 +1278,7 @@ class InferenceOrchestrator:img,max_size: int = 800,):- """Resize image preserving aspect ratio.- No ML imports — runs locally in the parent process.- """+ """Resize image preserving aspect ratio (runs locally, no ML imports)."""if img is None:return Noneif img.size[0] > max_size or img.size[1] > max_size:@@ -1340,8 +1315,7 @@ class InferenceOrchestrator:return Falsedef _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 route avoids an IPC round-trip."""from utils.datasets import is_gpt_oss_model_namereturn is_gpt_oss_model_name(model_name or self.active_model_name or "")diff --git a/studio/backend/core/inference/pricing.py b/studio/backend/core/inference/pricing.pyindex efb92681708..3b611d35969 100644--- a/studio/backend/core/inference/pricing.py+++ b/studio/backend/core/inference/pricing.py@@ -95,9 +95,8 @@ def _lookup(provider: str, model: str) -> Optional[dict[str, float]]:return Noneif model in table:return table[model]- # 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".+ # Longest-prefix match on a dash boundary: dated snapshots inherit+ # canonical prices, but "claude-opus-4-15" won't match "claude-opus-4-1".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]@@ -105,10 +104,9 @@ 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 (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).+ """Return a per-turn USD cost breakdown (per-bucket + total).++ Unknown model -> ``priced`` False and USD fields 0.0 (token counts still report)."""prices = _lookup(provider, model)out: dict[str, float] = {diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.pyindex 9c98133f672..f7a2da2833f 100644--- a/studio/backend/core/inference/providers.py+++ b/studio/backend/core/inference/providers.py@@ -26,10 +26,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"supports_tool_calling": True,"auth_header": "Authorization","auth_prefix": "Bearer ",- # 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.+ # Scope the picker to the current generation. /v1/models returns many+ # historical snapshots, fine-tunes, and non-chat models we don't want."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}$"),@@ -45,10 +43,7 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"claude-sonnet-4-5","claude-haiku-4-5",],- # Anthropic /v1/models returns dated snapshot ids alongside the- # canonical names (e.g. claude-3-5-sonnet-20241022). Hide the- # YYYYMMDD-suffixed variants — same intent as the OpenAI denylist,- # just a different date format (no dashes).+ # Hide YYYYMMDD-suffixed snapshot ids (e.g. claude-3-5-sonnet-20241022)."model_id_denylist": re.compile(r"-\d{8}$"),"supports_streaming": True,"supports_vision": True,@@ -63,21 +58,15 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {},"gemini": {"display_name": "Google Gemini",- # 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.+ # Native Gemini REST endpoint -- does NOT speak OpenAI Chat Completions;+ # translated in `_stream_gemini` (external_provider.py).# https://ai.google.dev/gemini-api/docs"base_url": "https://generativelanguage.googleapis.com/v1beta",- # 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 keeps the retired ids from re-appearing via- # live ListModels. Verified against `/v1beta/models` 2026-05-24.+ # Curated lineup (ListModels returns many historical/experimental ids).+ # Excluded on purpose:+ # - `gemini-2.0-flash*` (retired 2026-06-01; 404 on use)+ # - `gemini-3-pro-preview` (shut down 2026-03-09; auto-redirects to+ # `gemini-3.1-pro-preview`, so we surface 3.1 directly)."default_models": ["gemini-3.1-pro-preview","gemini-3.5-flash",@@ -96,8 +85,7 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"supports_streaming": True,"supports_vision": True,"supports_tool_calling": True,- # Native API takes the key on `x-goog-api-key`; empty `auth_prefix`- # sends the bare key.+ # Native API takes the bare key on `x-goog-api-key`."auth_header": "x-goog-api-key","auth_prefix": "","openai_compatible": False,@@ -106,19 +94,13 @@ 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 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.+ # gemini-3-pro-preview was shut down 2026-03-09 and auto-aliased to+ # gemini-3.1-pro-preview; drop it so users see one canonical card."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 (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- # excluded on purpose -- ListModels would re-surface them and they- # 404 on use.+ # Chat-capable 3.5 / 3.1 / 3 / 2.5 families plus rolling *-latest+ # aliases. Image-tier ids flow through the Nano Banana+ # `responseModalities` path in `_stream_gemini`. Retired 2.0 ids+ # excluded (they 404 on use)."model_id_allowlist": re.compile(r"^("r"gemini-3\.5-(?:flash|pro)(?:-preview)?|"@@ -179,14 +161,11 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"kimi": {"display_name": "Kimi","base_url": "https://api.moonshot.ai/v1",- # Current Kimi model lineup per the official docs:- # https://platform.kimi.ai/docs/models- # 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; everything else (moonshot-v1-*, dated k2 previews) is- # filtered out by model_id_allowlist below.+ # Surface only the two SoTA multimodal models (kimi-k2.6/k2.5);+ # moonshot-v1-* and dated k2 previews are filtered by the allowlist.+ # Docs: https://platform.kimi.ai/docs/models+ # Listing/overview: https://platform.kimi.ai/docs/api/list-models+ # https://platform.kimi.ai/docs/api/overview"default_models": ["kimi-k2.6","kimi-k2.5",@@ -198,10 +177,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"auth_prefix": "Bearer ","notes": "Moonshot API key. China: use base URL https://api.moonshot.cn/v1","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"- # (same for top_p). Strip both fields from the outbound body so the- # server falls back to its required defaults.+ # Reasoning-class: the API rejects custom temperature/top_p ("only 1+ # is allowed"). Strip both so the server uses its required defaults."body_omit": ("temperature", "top_p"),},"qwen": {@@ -223,9 +200,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"huggingface": {"display_name": "Hugging Face","base_url": "https://router.huggingface.co/v1",- # 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.+ # Seed the picker before the live /v1/models call resolves; the remote+ # listing (see model_list_mode) is the source of truth."default_models": ["openai/gpt-oss-120b","deepseek-ai/DeepSeek-V3",@@ -243,27 +219,22 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"returns the cross-provider chat catalog. See ""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). Remote so users see live- # availability -- the picker has search, and loadModels() merges- # defaults so default_models stay visible if the remote call fails.+ # Remote so users see live availability; loadModels() merges defaults+ # so they stay visible if the remote call fails."model_list_mode": "remote",- # 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.).+ # Scope to trusted first-party org repos (the response is otherwise+ # hundreds of community fine-tunes, mirrors, fp8 variants)."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"; the- # default_models seed keeps flagship ids near the top regardless of- # the API's order.+ # Cap the post-filter list to first N matches (no server-side sort);+ # default_models keeps flagship ids near the top."model_id_limit": 15,},"vllm": {"display_name": "vLLM",- # User-supplied via provider_base_url; the route layer falls back to- # the payload's base_url when the registry entry has none.+ # User-supplied via provider_base_url; the route falls back to the+ # payload's base_url when the registry entry has none."base_url": "","default_models": [],"supports_streaming": True,@@ -271,14 +242,11 @@ 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 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.+ # Force /v1/chat/completions -- vLLM's /v1/responses rebuilds messages+ # through the chat template, 400ing on strict-alternation templates+ # (Gemma 3). The chat-completions path takes messages verbatim."notes": "Self-hosted vLLM server. Always routed to /v1/chat/completions.",- # Surfaced via 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 dropdown."hidden": True,},"ollama": {@@ -314,7 +282,7 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {"openrouter": {"display_name": "OpenRouter","base_url": "https://openrouter.ai/api/v1",- # Curated list for Studio's picker (explicitly locked, not live /models).+ # Curated picker list (locked, not live /models)."default_models": ["openrouter/free","openai/gpt-4o",@@ -364,10 +332,8 @@ 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 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 are filtered out: they exist only for backend lookups and+ are surfaced via ``CUSTOM_PROVIDER_PRESETS`` instead of the 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.pyindex 954a2b3d195..acf6bd9edae 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -4,16 +4,14 @@"""Safetensors/transformers agentic tool loop.-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``.+Wraps a single-turn cumulative-text generator with the same tool-calling,+thinking-block, status, and metadata event protocol the GGUF path uses, so+the front-end SSE shape is identical across backends.++Unlike the GGUF path (``llama_cpp.py``), which uses llama-server's structured+``delta.tool_calls``, native transformers has no such channel, so this loop+parses tool calls from the cumulative text and dispatches via+``core.inference.tools``."""import jsondiff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex 1b453df0ffa..601cd9f92bf 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -11,11 +11,9 @@ import jsonimport 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 hyphenated-# MCP tool names (e.g. mcp__srv__list-issues) parse the same as built-in-# web_search/python/terminal names.+# _TOOL_CLOSED_PATS: closed pairs only. _TOOL_ALL_PATS: also trailing unclosed+# runs so truncated tails don't leak markup. The [\w-] name set matches OpenAI's+# so hyphenated MCP tool names (mcp__srv__list-issues) parse like built-ins._TOOL_CLOSED_PATS = [re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL),re.compile(r"<function=[\w-]+>.*?</function>", re.DOTALL),@@ -72,8 +70,7 @@ _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 schemas with-# `issue-number`, `repo-name`); `\w+` alone dropped those keys.+# [\w-] so hyphenated MCP param names (issue-number) aren't dropped._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,10 +121,10 @@ 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 skipping braces- # inside JSON strings.+ # Pattern 1: <tool_call>{json}. Balanced-brace scan, skipping braces in+ # JSON strings.for m in _TC_JSON_START_RE.finditer(content):- brace_start = m.end() - 1 # position of the opening {+ brace_start = m.end() - 1 # opening {depth, i = 0, brace_startin_string = Falsewhile i < len(content):@@ -166,8 +163,7 @@ def parse_tool_calls_from_text(content: str, *, id_offset: int = 0) -> list[dictpass# Pattern 2: <function=name><parameter=k>v... -- closing tags optional;- # don't use </function> as body boundary since code values can contain- # that literal.+ # </function> isn't a body boundary since code values can contain it.if not tool_calls:func_starts = [fm@@ -190,7 +186,7 @@ def parse_tool_calls_from_text(content: str, *, id_offset: int = 0) -> list[dictarguments: dict = {}param_starts = list(_TC_PARAM_START_RE.finditer(body))if len(param_starts) == 1:- # Single param: take everything to body end so embedded+ # Single param: take everything to body end so an embedded# </parameter> in code strings is preserved.pm = param_starts[0]val = body[pm.end() :]diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex bc1897199f9..023cab3e5ef 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -1,11 +1,8 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Tool definitions and executors for LLM tool calling.--Web search (DuckDuckGo), Python code execution, and terminal commands.-"""+"""Tool definitions and executors for LLM tool calling: web search+(DuckDuckGo), Python code execution, and terminal commands."""import astimport http.client@@ -42,8 +39,8 @@ logger = get_logger(__name__)_EXEC_TIMEOUT = 300 # 5 minutes-# 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).+# Import these at module level so the preexec_fn closure triggers no imports in+# the forked child (which can deadlock multi-threaded servers)._libc = Noneif sys.platform == "linux":try:@@ -160,10 +157,9 @@ def _find_blocked_commands(command: str) -> set[str]:"""blocked: set[str] = set()- # shlex with punctuation_chars splits `;`, `&&`, `||`, `|`, `(`, `)`, `` ` ``- # 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 `;`).+ # punctuation_chars splits separators into their own tokens, so command+ # position is detected even in `echo done; rm -rf x` (no whitespace) or+ # quote-split names (`r''m` collapses to `rm` after `;`).try:if sys.platform == "win32":tokens = shlex.split(command, posix = False)@@ -175,8 +171,7 @@ def _find_blocked_commands(command: str) -> set[str]:tokens = command.split()def _token_basename(tok: str) -> str:- # shlex may glue meta-chars onto a token (`rm;`); strip leading and- # trailing ones so the basename still matches `rm`.+ # Strip glued-on meta-chars (`rm;`) so the basename still matches `rm`.tok = tok.strip(";&|()`{}")base = os.path.basename(tok).lower()stem, ext = os.path.splitext(base)@@ -192,8 +187,8 @@ def _find_blocked_commands(command: str) -> set[str]:prefix_pending = Falsecontinueif token.startswith("-"):- # Flags belong to the active command. While a wrapper prefix awaits- # its command (`stdbuf -oL cmd`, `xargs -- cmd`), keep expect_command.+ # Flags belong to the active command, but keep expect_command while a+ # wrapper prefix awaits its command (`stdbuf -oL cmd`, `xargs -- cmd`).if not prefix_pending:expect_command = Falsecontinue@@ -208,9 +203,8 @@ def _find_blocked_commands(command: str) -> set[str]: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 in- # _BLOCKED_COMMANDS, so it's flagged AND we keep walking.+ # Wrappers (env/time/xargs/sudo) consume one command; the next non-flag,+ # non-numeric token is the real command. sudo is also in _BLOCKED_COMMANDS.if base in _COMMAND_PREFIXES:prefix_pending = Truecontinue@@ -224,10 +218,9 @@ def _find_blocked_commands(command: str) -> set[str]:if base in _BLOCKED_COMMANDS:blocked.add(base)- # 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.+ # Regex catches blocked words at command boundaries shlex misses: inside+ # $(rm -rf), <(rm), backtick chains, or "foo;rm". Anchored to command-position+ # delimiters, so it doesn't match in argument position.lowered = command.lower()if _BLOCKED_COMMANDS:words_alt = "|".join(re.escape(w) for w in sorted(_BLOCKED_COMMANDS))@@ -238,10 +231,9 @@ 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 '...'). 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.+ # Nested shell invocations (bash -c '...', bash -lc '...', cmd /c '...'):+ # on a -c/-/c flag, look back for a shell name (skipping flags) and+ # recursively scan the nested command string._SHELLS = {"bash", "sh", "zsh", "dash", "ksh", "csh", "tcsh", "fish"}_SHELLS_WIN = {"cmd", "cmd.exe"}for i, token in enumerate(tokens):@@ -253,9 +245,8 @@ 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 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).+ # Look back past flags for the shell binary. Windows flags and absolute+ # paths both start with /, so only skip short /X flags (not /bin/bash).for j in range(i - 1, -1, -1):prev = tokens[j]if prev.startswith("-"):@@ -275,15 +266,13 @@ 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; 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 ~/.+ Whitelist-built from scratch (parent env NOT inherited): only PATH/HOME/+ TMPDIR/LANG/TERM/PYTHONIOENCODING (+VIRTUAL_ENV or Windows SystemRoot) reach+ the child; all credential vars (HF_TOKEN, AWS_*, etc.) are absent. HOME+ points at the sandbox workdir so SDKs can't read the operator's cached creds."""- # Start with the running interpreter's directory so 'python', 'pip', etc.- # resolve to the same environment the Studio server runs in.+ # Start from the running interpreter's dir so 'python'/'pip' 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 []@@ -300,7 +289,7 @@ def _build_safe_env(workdir: str) -> dict[str, str]:else:path_entries.extend(["/usr/local/bin", "/usr/bin", "/bin"])- # Deduplicate while preserving order+ # Deduplicate, preserving order.deduped = list(dict.fromkeys(p for p in path_entries if p))env = {@@ -313,17 +302,15 @@ def _build_safe_env(workdir: str) -> dict[str, str]:}if venv:env["VIRTUAL_ENV"] = venv- # Windows needs SystemRoot for Python/subprocess to work+ # Windows needs SystemRoot for Python/subprocess to work.if sys.platform == "win32":env["SystemRoot"] = os.environ.get("SystemRoot", r"C:\Windows")return envdef _sandbox_preexec():- """Best-effort sandbox setup for sandboxed subprocesses.-- Modules are resolved at import time so the forked child runs no imports.- """+ """Best-effort sandbox setup for sandboxed subprocesses (modules are+ resolved at import time so the forked child runs no imports)."""try:os.setsid()except OSError:@@ -371,10 +358,9 @@ def _sandbox_preexec():except (ValueError, OSError, AttributeError):passtry:- # Default high enough for multi-shard safetensors mmaps + Python's- # 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).+ # High enough for multi-shard safetensors mmaps; tunable via env.+ # Clamp to the inherited hard limit so setrlimit doesn't ValueError+ # when the parent's hard cap is below the request.nofile = int(os.environ.get("UNSLOTH_STUDIO_SANDBOX_NOFILE", "16384"))_soft_cur, hard_cur = _resource.getrlimit(_resource.RLIMIT_NOFILE)target = nofile if hard_cur == _resource.RLIM_INFINITY else min(nofile, hard_cur)@@ -556,10 +542,9 @@ RENDER_HTML_TOOL = {ALL_TOOLS = [WEB_SEARCH_TOOL, PYTHON_TOOL, TERMINAL_TOOL, RENDER_HTML_TOOL]-# OpenAI's function.name regex: ^[a-zA-Z0-9_-]{1,64}$ -- enforced before-# streaming starts. MCP servers can return tool names containing '.', '/',-# spaces, etc., which the prefix scheme would forward to OpenAI verbatim-# and 400 the whole request. Validate up front and skip with a warning.+# OpenAI's function.name regex ^[a-zA-Z0-9_-]{1,64}$, enforced before streaming.+# MCP tool names with '.', '/', spaces, etc. would 400 the whole request, so we+# validate up front and skip with a warning._OPENAI_FN_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")@@ -574,9 +559,8 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:logger.warning("Skipping MCP tool on '%s': empty name.", display)continuename = f"{MCP_TOOL_PREFIX}{server['id']}__{raw_name}"- # OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; bad chars- # (., /, spaces, etc.) or oversized names would 400 the whole- # request. Skip + warn so the rest of the tools still ship.+ # Bad chars or oversized names would 400 the whole request; skip + warn+ # so the rest of the tools still ship.if not _OPENAI_FN_NAME_RE.fullmatch(name):logger.warning("Skipping MCP tool '%s' on '%s': composed name '%s' is not "@@ -586,8 +570,7 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:name,)continue- # Same MCP server returning duplicate tool names would also 400- # OpenAI ("tools[N].function.name duplicates ..."). Drop dupes.+ # Duplicate tool names would also 400 OpenAI; drop dupes.if name in seen_names:logger.warning("Skipping duplicate MCP tool '%s' on '%s'.", raw_name, display)continue@@ -608,7 +591,7 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:async def get_enabled_mcp_tools() -> list[dict]:servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]# Never spawn stdio servers when stdio is disabled on this host (e.g. a DB- # carried over from a desktop install onto a Colab / network deployment).+ # carried from a desktop install onto a Colab/network deployment).if not stdio_mcp_enabled():servers = [s for s in servers if not is_stdio(s["url"])]if not servers:@@ -670,11 +653,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 a string.+ """Execute a tool by name with the given arguments; returns a string.- ``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.+ ``timeout``: int seconds, ``None`` = no limit, unset = ``_EXEC_TIMEOUT``.+ ``session_id``: optional ID for per-conversation sandbox isolation."""logger.info(f"execute_tool: name={name}, session_id={session_id}, timeout={timeout}")effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeout@@ -714,11 +696,10 @@ def execute_tool(return f"Unknown tool: {name}"-_MAX_PAGE_CHARS = 16000 # limit fetched page text (after HTML-to-MD conversion)-# 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_PAGE_CHARS = 16000 # cap fetched page text (after HTML-to-MD conversion)+# Raw download cap > _MAX_PAGE_CHARS because SSR pages embed large <head>+# sections stripped during conversion; 512 KB reaches article content even+# where <head> alone is ~200 KB._MAX_FETCH_BYTES = 512 * 1024_USER_AGENTS = (@@ -739,13 +720,12 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):class _PinnedHTTPSConnection(http.client.HTTPSConnection):- """HTTPS connection to a pinned IP, using a different hostname for SNI- and certificate verification.+ """HTTPS connection to a pinned IP, using a different hostname for SNI and+ cert 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.+ SSRF IP-pinning rewrites URLs to raw IPs; a normal HTTPSConnection would then+ send no SNI and verify the cert against the IP (both fail). This splits the+ concerns: TCP connects to the pinned IP (``host``), TLS uses ``sni_hostname``."""def __init__(self, host: str, *, sni_hostname: str, **kwargs):@@ -753,8 +733,7 @@ class _PinnedHTTPSConnection(http.client.HTTPSConnection):self._sni_hostname = sni_hostnamedef connect(self):- # TCP connect to the pinned IP in self.host (+ tunnel if a proxy is set- # via set_tunnel, though we don't use one).+ # TCP connect to the pinned IP in self.host.http.client.HTTPConnection.connect(self)# TLS handshake with the real hostname for SNI + cert verification.self.sock = self._context.wrap_socket(@@ -764,11 +743,11 @@ class _PinnedHTTPSConnection(http.client.HTTPSConnection):class _SNIHTTPSHandler(urllib.request.HTTPSHandler):- """HTTPS handler that sends the correct SNI hostname during TLS handshake.+ """HTTPS handler sending the correct SNI hostname during TLS handshake.- 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.+ SSRF IP-pinning breaks SNI and cert verification; this returns a+ ``_PinnedHTTPSConnection`` that connects to the pinned IP but verifies TLS+ against the original hostname."""def __init__(self, hostname: str):@@ -803,14 +782,10 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, strfor *_, sockaddr in infos:ip = ipaddress.ip_address(sockaddr[0])- # `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; the non-global check is the source of truth and- # prevents future ranges from leaking.+ # `not ip.is_global` is the source of truth: it rejects every category+ # below PLUS shared/CGNAT (100.64.0.0/10) and benchmarking/doc ranges+ # Python marks is_private=False and is_global=False. The explicit+ # predicates only give human-readable categories in the error message.if (not ip.is_globalor ip.is_private@@ -822,7 +797,7 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str):return False, f"Blocked: refusing to fetch non-public address {ip}.", ""- # Return the first resolved address for pinning+ # Return the first resolved address for pinning.first_ip = infos[0][4][0]return True, "", first_ip@@ -860,8 +835,8 @@ def _fetch_page_text(ua = random.choice(_USER_AGENTS)for _hop in range(5):- # Pin to the validated IP (prevents DNS rebinding): rewrite the URL- # to the IP and set the Host header.+ # Pin to the validated IP (prevents DNS rebinding): rewrite URL to+ # the IP, 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@@ -901,7 +876,7 @@ def _fetch_page_text(return reason2current_host = rp.hostnamecontinue- # Success -- read capped body+ # Success: read capped body.raw_bytes = resp.read(max_bytes)breakelse:@@ -914,7 +889,7 @@ def _fetch_page_text(except Exception as e:return f"Failed to fetch URL: {e}"- # Convert HTML to Markdown with the builtin converter (no external deps)+ # Convert HTML to Markdown with the builtin converter (no external deps).from ._html_to_md import html_to_markdowntext = html_to_markdown(raw_html)@@ -936,7 +911,7 @@ def _web_search(If ``url`` is provided, fetches that page directly instead of searching."""- # Direct URL fetch mode+ # Direct URL fetch mode.if url and url.strip():fetch_timeout = 60 if timeout is None else min(timeout, 60)return _fetch_page_text(url.strip(), timeout = fetch_timeout)@@ -968,14 +943,9 @@ def _web_search(def _check_signal_escape_patterns(code: str):- """- 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).-- Returns (safe: bool, details: dict)- """+ """Check for patterns that could escape signal-based timeouts. Returns+ (safe: bool, details: dict). Vendored from unsloth_zoo.rl_environments to+ avoid importing unsloth_zoo (needs GPU drivers; fails on Apple Silicon)."""try:tree = ast.parse(code)except SyntaxError as e:@@ -1006,7 +976,7 @@ def _check_signal_escape_patterns(code: str):return full_name in namesreturn False- # Dangerous os/subprocess functions that can execute shell commands+ # Dangerous os/subprocess functions that can execute shell commands._SHELL_EXEC_FUNCS = frozenset({"os.system",@@ -1081,8 +1051,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 fully-qualified form for- # from-import tracking (e.g. "system" -> "os.system")+ # Bare name -> fully-qualified form for from-import tracking+ # (e.g. "system" -> "os.system").self.shell_exec_aliases: dict[str, str] = {}self.loop_depth = 0@@ -1118,7 +1088,7 @@ def _check_signal_escape_patterns(code: str):self.os_aliases.add("os")else:self.subprocess_aliases.add("subprocess")- # Track from-imports of dangerous functions+ # Track from-imports of dangerous functions.for alias in node.names:fq = f"{node.module}.{alias.name}"if fq in _SHELL_EXEC_FUNCS:@@ -1194,11 +1164,11 @@ def _check_signal_escape_patterns(code: str):elif func.value.id in self.subprocess_aliases:shell_func = f"subprocess.{func.attr}"elif isinstance(func, ast.Name):- # Check from-import aliases: from os import system; system(...)+ # from-import aliases: from os import system; system(...)shell_func = self.shell_exec_aliases.get(func.id)if shell_func and shell_func in _SHELL_EXEC_FUNCS:- # Expand **kwargs dicts to inspect their keys+ # Expand **kwargs dicts to inspect their keys.expanded_kwargs: dict[str, ast.AST] = {}has_opaque_kwargs = Falsefor kw in node.keywords:@@ -1217,7 +1187,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",@@ -1237,10 +1207,9 @@ 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).+ # Only flag dynamic args for funcs that interpret strings as+ # shell commands, or when shell= might be on. Any non-literal-+ # False shell= is treated as potentially True (conservative)._STRING_SHELL_FUNCS = frozenset({"os.system",@@ -1256,7 +1225,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_FUNCSor shell_func in _SHELL_EXEC_FUNCS@@ -1298,10 +1267,9 @@ def _check_signal_escape_patterns(code: str):})elif isinstance(node.type, ast.Name):- # Only flag BaseException and TimeoutError, NOT Exception.- # except Exception doesn't catch SystemExit/KeyboardInterrupt,- # so it can't suppress timeout enforcement; flagging it would- # false-positive on normal error handling.+ # Flag BaseException/TimeoutError but NOT Exception: `except+ # Exception` can't catch SystemExit/KeyboardInterrupt, so it+ # can't suppress timeout enforcement.if node.type.id in ("TimeoutError", "BaseException"):exception_catching.append({@@ -1331,7 +1299,7 @@ def _check_signal_escape_patterns(code: str):# 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.+ # caught by the bash blocklist.network_calls: list[dict] = []sensitive_file_reads: list[dict] = []_NETWORK_FQ_PREFIXES = (@@ -1577,10 +1545,9 @@ def _check_signal_escape_patterns(code: str):return Truereturn False- # Bare method-name fallback (`x.upload_file(...)`) is intentionally fuzzy,- # 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.+ # Bare method-name fallback (`x.upload_file(...)`) is fuzzy, so it fires only+ # when huggingface_hub/hf_api is imported; else paramiko.upload_file,+ # boto3.create_commit, etc. would false-positive. Pre-scan for the imports._HF_IMPORT_MODULES = ("huggingface_hub","hf_api",@@ -1618,13 +1585,9 @@ def _check_signal_escape_patterns(code: str):_hf_in_scope = _module_has_hf_import(tree)def _method_call_hf_upload_name(node: ast.Call) -> str | None:- """Return the HF upload method name (`upload_file`, ...) or None.-- 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, so- paramiko/boto3 don't false-positive.- """+ """Return the HF upload method name (`upload_file`, ...) or None. Covers+ the Attribute and bare-Name forms; the bare-name branch fires only when+ an HF import is in scope so paramiko/boto3 don't false-positive."""if not _hf_in_scope:return Nonef = node.func@@ -1634,9 +1597,8 @@ def _check_signal_escape_patterns(code: str):return f.idreturn None- # 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.+ # Kwargs that ship a credential over the wire. The sandbox env strips+ # credentials up front, so any value here is hard-coded or lifted from parent._HF_SENSITIVE_KWARGS = frozenset({"token",@@ -1659,16 +1621,11 @@ 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) catches wrapper calls like- `str(os.environ)`, `json.dumps(os.environ)`,- `'-'.join(os.environ.values())`.+ """True if any node in the subtree resolves to an env/process read.- 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- could lift parent env via `printenv` / `env` / `set`.+ Walks the whole subtree (not just the root) to catch wrappers like+ `str(os.environ)`. Covers os.environ[/.get]/os.getenv, bare getenv, and+ subprocess.{run,check_output,...} that could lift parent env via printenv."""if node is None:return False@@ -1716,7 +1673,7 @@ def _check_signal_escape_patterns(code: str):if node is None:return Falseif isinstance(node, ast.Constant) and isinstance(node.value, (bytes, bytearray)):- return True # inline bytes; no file access+ return True # inline bytes, no file accessif isinstance(node, ast.Constant) and isinstance(node.value, str):return _is_safe_relative_path(node.value)if isinstance(node, ast.Call):diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 72783f1031b..4f5b985234b 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -4,14 +4,10 @@"""Inference subprocess entry point.-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.--Pattern follows core/training/worker.py.+Each session runs in a persistent spawn subprocess, giving a clean interpreter+with no stale module state (solves transformers version-switching). It stays+alive while a model is loaded, taking commands (generate, load, unload) via+mp.Queue, and exits on shutdown or unload. Pattern follows core/training/worker.py."""from __future__ import annotations@@ -96,16 +92,10 @@ 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/`` 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 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.+ With *model_names*, only those models' ``blobs/`` dirs are checked (faster);+ accepts multiple names so LoRA loads can watch adapter + base repos at once.+ *has_incomplete* is True when any ``*.incomplete`` files exist (download+ active). None means state could not be determined, so callers skip stall logic."""try:from huggingface_hub.constants import HF_HUB_CACHE@@ -123,10 +113,8 @@ def _get_hf_download_state(model_names: list[str] | None = None) -> tuple[int, bfor name in model_names:if not name:continue- # Skip local filesystem paths -- HF model IDs use forward- # slashes (org/model) but never start with / . ~ or contain- # backslashes, distinguishing them from absolute, relative,- # and Windows paths.+ # Skip local filesystem paths -- HF IDs (org/model) never start+ # with / . ~ or contain backslashes.if name.startswith(("/", ".", "~")) or "\\" in name:continuename = resolve_cached_repo_id_case(name)@@ -163,16 +151,10 @@ def _start_heartbeat() -> threading.Event:"""Start a daemon thread that sends periodic status heartbeats.- 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 init (quantization, GPU weight loading) is never- misclassified as a stalled download.-- Returns a stop event -- set it to terminate the heartbeat thread.+ A stall is reported only when ``*.incomplete`` files are present (download+ active) AND cache size hasn't changed for *stall_timeout* seconds. When the+ download finishes the timer resets, so post-download init (quantization, GPU+ weight load) isn't misclassified as a stall. Returns a stop event."""stop = threading.Event()transport = "https" if xet_disabled else "xet"@@ -204,9 +186,8 @@ def _start_heartbeat(last_size = current_sizelast_change = now- # 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.+ # Only fire stall while .incomplete files confirm an active download;+ # reset the timer otherwise so model init isn't counted as a stall.if not has_incomplete:last_change = nowelif now - last_change >= stall_timeout:@@ -221,7 +202,7 @@ def _start_heartbeat("ts": time.time(),},)- # Only fire once -- the orchestrator will kill us.+ # fire once -- the orchestrator will kill usreturn_send_response(@@ -277,10 +258,8 @@ 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:- # 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).+ # Auto-enable trust_remote_code only for NemotronH/Nano (config parsing+ # bugs require it). Must NOT match Llama-Nemotron (standard Llama arch)._NEMOTRON_TRUST_SUBSTRINGS = ("nemotron_h", "nemotron-h", "nemotron-3-nano")trust_remote_code = config.get("trust_remote_code", False)if not trust_remote_code:@@ -295,12 +274,10 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:model_name,)- # Send heartbeats every 30s so the orchestrator knows we're alive- # (download/weight loading can be slow on slow connections).+ # Heartbeat every 30s so the orchestrator knows we're alive during slow loads.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 real bottleneck).+ # Watch model + base repos (base download is the LoRA bottleneck).watch_repos = [mc.identifier]base = getattr(mc, "base_model", None)if base and str(base) != mc.identifier:@@ -338,8 +315,7 @@ 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.try:_bm = getattr(backend, "models", {}) or {}_entry = (@@ -394,21 +370,18 @@ 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. 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.+ cancel_event is an mp.Event the parent can set anytime (user stop, or new+ model load mid-generate); generation stops within 1-2 tokens."""request_id = cmd.get("request_id", "")try:- # Decode image if provided.image = Noneimage_b64 = cmd.get("image_base64")if image_b64:image = _decode_image(image_b64)image = _resize_image(image)- # Build generation kwargs.gen_kwargs = {"messages": cmd["messages"],"system_prompt": cmd.get("system_prompt", ""),@@ -422,8 +395,7 @@ 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 present so- # the backend signature can evolve without breaking older payloads.+ # Forward only present optional keys so the backend signature can evolve.for opt_key in ("tools","enable_thinking",@@ -433,7 +405,6 @@ 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.use_adapter = cmd.get("use_adapter")if use_adapter is not None:generator = backend.generate_with_adapter_control(@@ -537,7 +508,7 @@ def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_evetry:import numpy as np- # Decode audio array from list (numpy arrays can't go through mp.Queue).+ # numpy arrays can't go through mp.Queue, so decode from list.audio_array = np.array(cmd["audio_data"], dtype = np.float32)audio_type = cmd.get("audio_type")@@ -868,7 +839,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 in this subprocess; unload the current one first.+ # Unload the current model before loading the new one.if backend.active_model_name:backend.unload_model(backend.active_model_name)_handle_load(backend, cmd, resp_queue)@@ -901,7 +872,6 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf)elif cmd_type == "status":- # Return current status._send_response(resp_queue,{@@ -921,7 +891,6 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, confelif cmd_type == "shutdown":logger.info("Shutdown command received, exiting")- # 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.pyindex 9ef60e00dfd..973520d5cdf 100644--- a/studio/backend/core/tool_healing.py+++ b/studio/backend/core/tool_healing.py@@ -3,24 +3,20 @@"""Tool-call XML parsing and stripping helpers.-Extracted verbatim from studio/backend/core/inference/llama_cpp.py so-external inference servers (llama-server wrappers, llama-swap, custom-shims) can reuse the logic without importing the inference orchestrator,-structlog, httpx, or the rest of the studio backend.--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.+Extracted verbatim from studio/backend/core/inference/llama_cpp.py so external+inference servers can reuse the logic without importing the inference+orchestrator, structlog, httpx, or the rest of the studio backend.++Regexes and bodies are byte-for-byte identical to the original; any change must+preserve that. test_tool_healing_extraction_is_exact.py verifies via AST."""import jsonimport re-# 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.+# Pre-compiled patterns for tool XML stripping. The hyphen in the name+# char-class lets dashed MCP tool/parameter names (mcp__srv__list-issues,+# issue-number) 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),@@ -51,8 +47,8 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:"""tool_calls = []- # Pattern 1: JSON inside <tool_call> tags. 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@@ -93,18 +89,16 @@ def parse_tool_calls_from_text(content: str) -> list[dict]:pass# Pattern 2: XML-style <function=name><parameter=key>value</parameter></function>- # All closing tags optional -- models frequently omit </parameter>,- # </function>, and/or </tool_call>.+ # All closing tags optional; models frequently omit them.if not tool_calls:- # 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.+ # Step 1: Find <function=name> positions and extract bodies. Use only+ # </tool_call> or the next <function= as hard boundaries (</function>+ # can appear in code values); trim a trailing </function> afterwards.func_starts = list(_TC_FUNC_START_RE.finditer(content))for idx, fm in enumerate(func_starts):func_name = fm.group(1)body_start = fm.end()- # Hard boundaries: next <function= tag or </tool_call>+ # Boundaries: next <function= tag or </tool_call>next_func = func_starts[idx + 1].start() if idx + 1 < len(func_starts) else len(content)end_tag = _TC_END_TAG_RE.search(content[body_start:])if end_tag:@@ -113,18 +107,16 @@ 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 the real closing </function> tag if present- body = _TC_FUNC_CLOSE_RE.sub("", body)+ body = _TC_FUNC_CLOSE_RE.sub("", body) # trim closing </function># 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.+ # functions, 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 after the tag to- # end of body, trimming any trailing </parameter>.+ # Value is everything after the tag to end of body, less a+ # trailing </parameter>.pm = param_starts[0]val = body[pm.end() :]val = _TC_PARAM_CLOSE_RE.sub("", val)@@ -133,15 +125,14 @@ 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 the next <parameter= or end of body+ # Value ends at next <parameter= or end of bodynext_param = (param_starts[pidx + 1].start()if pidx + 1 < len(param_starts)else len(body))val = body[val_start:next_param]- # Trim trailing </parameter> if present- val = _TC_PARAM_CLOSE_RE.sub("", val)+ val = _TC_PARAM_CLOSE_RE.sub("", val) # trim trailing </parameter>arguments[param_name] = val.strip()tc = {diff --git a/studio/backend/core/training/__init__.py b/studio/backend/core/training/__init__.pyindex 6ce85aab0d9..f0e4113ac3b 100644--- a/studio/backend/core/training/__init__.py+++ b/studio/backend/core/training/__init__.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-"""Training submodule: backends and trainer classes."""+"""Training backends and trainer classes."""from .training import TrainingBackend, TrainingProgress, get_training_backenddiff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex c43c269aed3..3d6ab2411c6 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -11,16 +11,14 @@ import osimport sysimport types-# Prevent tokenizer parallelism deadlocks when datasets uses multiprocessing fork+# Prevent tokenizer parallelism deadlocks when datasets forks.os.environ["TOKENIZERS_PARALLELISM"] = "false"-# 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 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.+# Make compiled cache modules importable by any subprocess. On spawn platforms+# (Windows/macOS) spawned dataset.map() workers re-import top-level modules, and+# the cache's trainer files import torch + unsloth_zoo (inits CUDA). Propagating+# UNSLOTH_COMPILE_LOCATION via PYTHONPATH lets any subprocess find them.+# 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")if not os.path.isabs(_compile_cache):@@ -42,8 +40,8 @@ from utils.hardware import (get_visible_gpu_count,)-# 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 wheels.+# recompile_limit was removed in some ROCm torch builds; 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 = 64from unsloth import FastLanguageModel, FastVisionModel, is_bfloat16_supported@@ -167,13 +165,11 @@ class UnslothTrainer:) -> None:"""Lightweight detection and tokenizer load — no model weights, no VRAM.- Sets is_vlm, _audio_type, is_audio_vlm, model_name and loads a- lightweight tokenizer for dataset formatting. Call before- load_and_format_dataset() to process the dataset BEFORE loading the- training model (avoids VRAM contention with the LLM-assisted detector).-- load_model() may run afterwards — it re-detects and loads the full- model + tokenizer, overwriting the lightweight one set here.+ Sets is_vlm, _audio_type, is_audio_vlm, model_name and loads a lightweight+ tokenizer for dataset formatting. Call before load_and_format_dataset() so+ the dataset is processed before the training model loads (avoids VRAM+ contention). load_model() later re-detects and loads the full model ++ tokenizer, overwriting the lightweight one set here."""self.model_name = model_nameself.max_seq_length = max_seq_length@@ -208,8 +204,8 @@ class UnslothTrainer:)# --- Load lightweight tokenizer/processor (CPU only, no VRAM) ---- # Whisper needs AutoProcessor (feature_extractor + tokenizer); others- # use AutoTokenizer (CSM loads its own processor inline).+ # Whisper needs AutoProcessor; others use AutoTokenizer (CSM loads its+ # own processor inline).if self._audio_type == "whisper":from transformers import AutoProcessorself.tokenizer = AutoProcessor.from_pretrained(@@ -320,10 +316,8 @@ class UnslothTrainer:*,extra_args = None,):- """Build the training args dict for audio branches.-- Builds the common config (batch size, lr, warmup, fp16/bf16, etc.)- and applies per-branch overrides via extra_args.+ """Build the training args dict for audio branches: common config (batch+ size, lr, warmup, fp16/bf16, etc.) with per-branch overrides via extra_args."""batch_size = training_args.get("batch_size", 2)gradient_accumulation_steps = training_args.get("gradient_accumulation_steps", 4)@@ -410,10 +404,10 @@ class UnslothTrainer:def _cleanup_audio_artifacts(self):"""Remove sys.path/sys.modules entries from previous audio preprocessing.- 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.+ After audio training, cloned repo dirs (OuteTTS, Spark-TTS) and heavy+ modules (snac, whisper, sparktts, outetts) linger; the next+ dataset.map(num_proc=N) forks children that inherit this stale state and+ deadlock."""# Remove cloned audio repo paths from sys.pathbase_dir = os.path.dirname(os.path.abspath(__file__))@@ -523,12 +517,10 @@ class UnslothTrainer:# to prevent deadlocks when forking dataset.map() workersself._cleanup_audio_artifacts()- # 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.+ # Reload Unsloth-patched modeling modules before clearing the cache.+ # __UNSLOTH_PATCHED__ blocks re-compilation, so clearing the disk+ # cache alone would leave files missing; reloading restores original+ # class defs so Unsloth re-compiles cleanly.import importlibfor _key, _mod in list(sys.modules.items()):@@ -589,13 +581,11 @@ class UnslothTrainer:logger.info(f"\nLoading {model_type_label} model: {model_name}")- # Set HF token if providedif hf_token:os.environ["HF_TOKEN"] = hf_token- # Proactive gated-model check before from_pretrained. Catches ALL- # gated/private models (text, vision, audio) globally. Skip when- # offline -- from_pretrained uses the cache.+ # Proactive gated-model check before from_pretrained (catches all+ # gated/private models). Skip when offline -- it uses the cache.if "/" in model_name and not _env_offline():try:from huggingface_hub import model_info as hf_model_info@@ -631,15 +621,11 @@ class UnslothTrainer:f"Using device_map='{device_map}' ({get_visible_gpu_count()} GPU(s) visible)")- # 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.+ # AMD ROCm without native bf16 (e.g. RDNA2/gfx103x) crashes with an+ # LLVM error on the first bf16 kernel if dtype=None auto-picks bf16, so+ # force float16 there. NVIDIA keeps dtype=None so unsloth's auto-detect+ # (incl. FORCE_FLOAT32) is honored -- T4/V100 must NOT be coerced to+ # float16. Derive ROCm inline since hardware.IS_ROCM may be unset here._is_rocm = (bool(getattr(torch.version, "hip", None)) or "rocm" in torch.__version__.lower())@@ -703,11 +689,9 @@ class UnslothTrainer:logger.info(f"Loaded {self._audio_type} audio model (FastLanguageModel)")elif self._audio_type == "bicodec":- # 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)+ # Spark-TTS: download full repo (sparktts + BiCodec weights), then+ # load only the LLM subfolder. model_name may be+ # "Spark-TTS-0.5B/LLM" (YAML mapping) or "unsloth/Spark-TTS-0.5B".from unsloth import FastModelfrom huggingface_hub import snapshot_download@@ -782,7 +766,7 @@ class UnslothTrainer:)logger.info("Loaded vision model")- # Diagnostic: did FastVisionModel return a Processor or a raw tokenizer?+ # Did FastVisionModel return a Processor or a raw tokenizer?from transformers import ProcessorMixintok = self.tokenizer@@ -826,11 +810,9 @@ class UnslothTrainer:if "could not get source code" in str(e) and not getattr(self, "_source_code_retried", False):- # Unsloth's patching can leave stale state that makes- # inspect.getsource() fail when switching model families- # (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.+ # Unsloth patching can leave stale state that breaks+ # inspect.getsource() when switching model families (e.g. gemma3 →+ # gemma3n); the first failure clears it, so a retry succeeds.self._source_code_retried = Truelogger.info(f"\n'could not get source code' — retrying once...\n")return self.load_model(@@ -1132,12 +1114,10 @@ class UnslothTrainer:def _apply_csm_forward_fix(self):"""Monkey-patch CsmForConditionalGeneration.forward for depth decoder kwargs.- 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.-- Patch at both instance AND class level for reliability, and strip- non-TransformersKwargs params that Unsloth/PEFT inject.+ The original forward leaks raw **kwargs (num_items_in_batch, causal_mask,+ etc.) from Trainer/PEFT into the depth decoder, causing+ depth_decoder_loss=None and a 'Tensor + NoneType' crash. Patch at both+ instance and class level and strip non-TransformersKwargs params."""import torchimport torch.nn as nn@@ -1178,8 +1158,7 @@ class UnslothTrainer:logits_to_keep = 0,**kwargs,):- # Strip non-standard kwargs from Unsloth/PEFT (causal_mask,- # num_logits_to_keep, task_ids, return_dict, etc.)+ # Strip non-standard kwargs from Unsloth/PEFT.output_attentions = kwargs.pop("output_attentions", None)output_hidden_states = kwargs.pop("output_hidden_states", None)kwargs.pop("return_dict", None)@@ -1242,8 +1221,7 @@ class UnslothTrainer:]depth_decoder_labels = labels[train_mask]- # Clean kwargs for depth decoder; scale num_items_in_batch- # for its 31 codebooks+ # Scale num_items_in_batch for the depth decoder's 31 codebooks.dd_kwargs = clean_kwargs.copy()if "num_items_in_batch" in dd_kwargs:dd_kwargs["num_items_in_batch"] = dd_kwargs["num_items_in_batch"] * (@@ -1295,10 +1273,9 @@ class UnslothTrainer:),)- # Patch BOTH instance and class level for reliability.- # Instance: catches calls via BaseTuner.forward -> self.model.forward()+ # Instance level: catches BaseTuner.forward -> self.model.forward().base_csm.forward = types.MethodType(_fixed_csm_forward, base_csm)- # Class: catches any path resolving through the class dict+ # Class level: catches paths resolving through the class dict.CsmForConditionalGeneration.forward = _fixed_csm_forwardlogger.info("Applied CSM forward fix (class + instance level)\n")@@ -1317,10 +1294,9 @@ 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 — some fine-tuned+ # models 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@@ -1371,8 +1347,8 @@ class UnslothTrainer:],}]- # NOTE: pad_to_multiple_of intentionally omitted from text_kwargs —- # CsmProcessor._merge_kwargs leaks it to EncodecFeatureExtractor, which rejects it.+ # pad_to_multiple_of omitted: _merge_kwargs leaks it to+ # EncodecFeatureExtractor, which rejects it.model_inputs = processor.apply_chat_template(conversation,tokenize = True,@@ -1691,8 +1667,8 @@ class UnslothTrainer:device = "cuda" if torch.cuda.is_available() else "cpu"- # 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.+ # sparktts lives in the SparkAudio/Spark-TTS GitHub repo, not the 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):@@ -2296,10 +2272,9 @@ class UnslothTrainer:return result.datasetif local_datasets:- # 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).+ # Use load_dataset() for an Arrow-backed result; in-memory+ # Dataset.from_list() has no cache and forces num_proc=1 during+ # tokenization/map (sharding needs Arrow files).all_files = self._resolve_local_files(local_datasets)if all_files:@@ -2665,9 +2640,8 @@ class UnslothTrainer:return False# 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.+ # patched_import hook 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 cachedfrom transformers import ( # noqa: F401Trainer as _HFTrainer,@@ -2724,10 +2698,9 @@ class UnslothTrainer:def _train_worker(self, dataset: Dataset, **training_args):"""Worker function for training (runs in separate thread)"""try:- # On spawn-based platforms (Windows, macOS), register all known- # compiled-cache dirs on sys.path/PYTHONPATH before any- # dataset.map() call so spawned workers can import dynamically- # compiled modules such as UnslothSFTTrainer.+ # On spawn platforms, register compiled-cache dirs on sys.path/PYTHONPATH+ # before any dataset.map() so spawned workers can import compiled+ # modules such as UnslothSFTTrainer.if sys.platform in ("win32", "darwin"):from utils.cache_cleanup import register_compiled_cache_on_pathregister_compiled_cache_on_path()@@ -2754,8 +2727,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) with+ # remove_unused_columns=False for the depth decoder.from transformers import Trainer as HFTrainer, TrainingArgumentsself._apply_csm_forward_fix()@@ -2792,8 +2765,8 @@ class UnslothTrainer:elif self._audio_type == "snac":# 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.+ # DataCollatorForSeq2Seq pads variable-length sequences per batch+ # and pads labels with -100.from transformers import (Trainer as HFTrainer,TrainingArguments,@@ -2915,9 +2888,9 @@ class UnslothTrainer:logger.info("Configuring DeepSeek OCR data collator...\n")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 preset.+ # (image_size, base_size, crop_mode) is a coupled preset;+ # changing image_size alone desyncs the per-crop 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 "@@ -2940,8 +2913,8 @@ class UnslothTrainer:returnelif self.is_audio_vlm and not raw_text_mode:- # Audio VLM collator (e.g. Gemma 3N with audio).- # Mirrors the collate_fn from Gemma3N_(4B)-Audio notebook.+ # Audio VLM collator (e.g. Gemma 3N), mirrors the+ # Gemma3N_(4B)-Audio notebook collate_fn.logger.info("Configuring audio VLM data collator...\n")processor = self.tokenizer # FastModel returns processor as tokenizer@@ -3035,9 +3008,8 @@ class UnslothTrainer:f"[DEBUG] dataset_num_proc={config_args['dataset_num_proc']} (is_audio={self.is_audio}, is_audio_vlm={self.is_audio_vlm}, _cuda_audio_used={self._cuda_audio_used})")- # On spawn-based platforms (Windows, macOS) with transformers 5.x,- # disable DataLoader multiprocessing to avoid modified sys.path- # (.venv_t5) issues in spawned workers.+ # On spawn platforms with transformers 5.x, disable DataLoader+ # multiprocessing to avoid modified sys.path issues in spawned workers.if sys.platform in ("win32", "darwin"):import transformers as _tfif _tf.__version__.startswith("5."):@@ -3098,8 +3070,7 @@ class UnslothTrainer: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 on VLM models goes to the- # text path below.+ # remove_unused_columns); raw-text VLM 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")# Provided values or vision defaults@@ -3156,9 +3127,8 @@ 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).+ # Audio VLM (e.g. Gemma 3N): raw Dataset from+ # _format_audio_vlm_dataset, processing_class=processor.tokenizer.# Raw-text runs go to the text path below.train_dataset = dataset if isinstance(dataset, Dataset) else dataset["dataset"]processing_class = (@@ -3191,11 +3161,10 @@ class UnslothTrainer:trainer_kwargs["eval_dataset"] = eval_datasetself.trainer = SFTTrainer(**trainer_kwargs)else:- # 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'.+ # For text-only training, unwrap a Processor (e.g. Gemma-3 returns+ # ProcessorMixin even for text) to the raw tokenizer; else SFTTrainer+ # sets _is_vlm=True, skips _prepare_dataset, and 'text' never gets+ # tokenized to 'input_ids'.from transformers import ProcessorMixinsft_tokenizer = self.tokenizer@@ -3249,8 +3218,8 @@ class UnslothTrainer:if eval_dataset is not None:trainer_kwargs["eval_dataset"] = eval_datasetself.trainer = SFTTrainer(**trainer_kwargs)- # Restore full processor as processing_class so checkpoints- # include preprocessor_config.json (needed for GGUF export).+ # Restore full processor so checkpoints include+ # preprocessor_config.json (needed for GGUF export).if sft_tokenizer is not self.tokenizer:self.trainer.processing_class = self.tokenizerlogger.info("Trainer initialized\n")@@ -3332,11 +3301,10 @@ class UnslothTrainer:)logger.info("Train on responses only configured successfully\n")- # ── Safety net: check if all samples were filtered out ──- # 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.+ # Safety net: train_on_responses_only masks non-response+ # tokens with -100. If max_seq_length is too short, the+ # response is truncated away, every sample becomes all -100,+ # and Unsloth drops them, leaving 0 usable samples.filtered_len = len(self.trainer.train_dataset)original_len = len(dataset["dataset"])dropped = original_len - filtered_len@@ -3496,14 +3464,11 @@ class UnslothTrainer:def _ensure_deepseek_ocr_installed():- """- Auto-install the DeepSeek OCR module if missing (from HuggingFace hub as- a local module).+ """Auto-install the DeepSeek OCR module from HF hub if missing.Returns True if available (already installed or just installed)."""try:- # Already available?from deepseek_ocr.modeling_deepseekocr import format_messageslogger.info("DeepSeek OCR module already available")return True@@ -3518,7 +3483,6 @@ def _ensure_deepseek_ocr_installed():import sysimport os- # Install locally at project rootscript_dir = os.path.dirname(os.path.abspath(__file__))parent_dir = os.path.dirname(script_dir) # project root@@ -3527,11 +3491,9 @@ def _ensure_deepseek_ocr_installed():snapshot_download("unsloth/DeepSeek-OCR", local_dir = local_dir, local_dir_use_symlinks = False)- # Add to sys.path if neededif parent_dir not in sys.path:sys.path.insert(0, parent_dir)- # Retry importfrom deepseek_ocr.modeling_deepseekocr import format_messageslogger.info("DeepSeek OCR module installed successfully")diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 5c5626625bd..c5bc3dbad5e 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -4,14 +4,10 @@"""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).--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.+Each job runs in a fresh spawn subprocess (solving transformers version-switching);+the in-process UnslothTrainer singleton is only used inside the worker. This file+orchestrates the subprocess lifecycle, pumps events from the worker's mp.Queue, and+exposes the same API to routes/training.py. Pattern follows data_recipe/jobs/manager.py."""import json as _json@@ -47,9 +43,8 @@ _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 can't be bypassed.+ Completed ``checkpoint-<int>/`` dirs 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 +90,7 @@ PLOT_HEIGHT = 3.5@dataclassclass TrainingProgress:- """Mirror of trainer.TrainingProgress — here so the parent process never- imports the heavy ML modules."""+ """Mirror of trainer.TrainingProgress so the parent never imports heavy ML modules."""epoch: float = 0step: int = 0@@ -244,12 +238,11 @@ class TrainingBackend:"gpu_ids": kwargs.get("gpu_ids"),}- # Full finetuning always runs in 16-bit. LoRA/QLoRA and CPT keep the- # explicit request so 4-bit adapter/raw-text runs stay possible.+ # Full finetuning always runs in 16-bit; LoRA/QLoRA/CPT keep the request.if config["training_type"] == "Full Finetuning":config["load_in_4bit"] = False- # Spawn subprocess — use locals so state is untouched on failure+ # Spawn into locals so state is untouched on failure.from utils.hardware import hardware as _hwif _hw.DEVICE == _hw.DeviceType.MLX:@@ -296,7 +289,7 @@ class TrainingBackend:logger.info("Training subprocess started (pid=%s)", proc.pid)- # Reset state — safe: old pump thread confirmed dead, proc.start() succeeded+ # Reset state (old pump thread dead, proc.start() succeeded).self.current_job_id = job_idself._should_stop = Falseself._cancel_requested = False@@ -319,15 +312,14 @@ class TrainingBackend:self._db_config = {k: v for k, v in config.items() if k not in {"hf_token", "wandb_token"}}self._db_started_at = datetime.now(timezone.utc).isoformat()- # Assign subprocess handles after state reset+ # Assign subprocess handles after state reset.self._event_queue = event_queueself._stop_queue = stop_queueself._proc = proc- # Eagerly create DB run row so it 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 threadself._pump_thread = threading.Thread(target = self._pump_loop, daemon = True)self._pump_thread.start()@@ -344,7 +336,7 @@ class TrainingBackend:self._stop_queue.put({"type": "stop", "save": save})except (OSError, ValueError):pass- # Update progress immediately for responsive UI+ # Update progress immediately for responsive UI.self._progress.status_message = ("Stopping training and saving checkpoint..." if save else "Cancelling training...")@@ -366,8 +358,7 @@ class TrainingBackend:proc.kill()proc.join(timeout = 2.0)- # Wait for pump thread to finish DB finalization before returning- # (8s covers SQLite's 5s lock timeout plus execution overhead)+ # Wait for pump thread to finish DB finalization (8s covers SQLite's 5s lock timeout).if self._pump_thread is not None and self._pump_thread.is_alive():self._pump_thread.join(timeout = 8.0)@@ -383,22 +374,19 @@ class TrainingBackend:def is_training_active(self) -> bool:"""Check if training is currently active."""with self._lock:- # Subprocess alive = activeif self._proc is not None and self._proc.is_alive():return True- # Stop was requested and process exited → inactiveif self._should_stop:return False- # Check progress statep = self._progressif p.is_training:return Trueif p.is_completed or p.error:return False- # Check status message for activity+ # Infer activity from the status message.status_lower = (p.status_message or "").lower()if any(k in status_lower@@ -491,21 +479,19 @@ class TrainingBackend:if self._proc is None or self._event_queue is None:return- # Try to read an eventevent = self._read_queue(self._event_queue, timeout_sec = 0.25)if event is not None:self._handle_event(event)continue- # No event — check if process is still aliveif self._proc.is_alive():continue- # Process exited — drain remaining events+ # Process exited — drain remaining events.for e in self._drain_queue(self._event_queue):self._handle_event(e)- # Mark as done if no explicit complete/error was received+ # Mark done if no explicit complete/error was received.with self._lock:if self._progress.is_training:if self._should_stop:@@ -540,7 +526,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 sanitized below; update progress after coercion+ # loss/lr sanitized below._raw_loss = event.get("loss")_raw_lr = event.get("learning_rate")try:@@ -578,7 +564,7 @@ class TrainingBackend:if status:self._progress.status_message = status- # Update metric histories — reuse sanitized values above+ # Update metric histories using sanitized values.step = event.get("step", 0)loss = _safe_losslr = _safe_lr@@ -614,7 +600,7 @@ class TrainingBackend:else:eval_loss = None- # Buffer metric for DB flush (loss/lr already sanitized)+ # Buffer metric for DB flush.self._metric_buffer.append({"step": step,@@ -628,7 +614,7 @@ class TrainingBackend:})- # Pick the DB action to run 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 = {@@ -782,14 +768,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 bound 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 survive+ # 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@@ -952,9 +938,8 @@ 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. No-op placeholder.+ No-op: with subprocess training the model is freed on exit, so inference+ must load from the saved checkpoint on disk."""logger.info("_transfer_to_inference_backend: subprocess training — "diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex e9d98909a67..50323478b24 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -73,10 +73,9 @@ _FAST_PATH_HOOKS_SKIP_ENV = "UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS"# run_training_process() and isn't GC'd mid-run._WINDOWS_ROCM_GROUPED_MM_LIB = None-# 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.+# Subprocesses don't inherit os.add_dll_directory registrations. Replicate+# main.py's Windows ROCm DLL setup so the first `import torch` finds+# amdhip64.dll. Handles retained at module scope so they aren't GC'd._ROCM_DLL_HANDLES: list = []if sys.platform == "win32":@@ -91,7 +90,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".parts = []for chunk in name.split("."):try:@@ -143,21 +142,13 @@ 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 ``/usr/include/c++/<N>`` C++ headers, or- ``None`` if no match (or non-Linux / non-x86_64).+ """Highest-numbered ``/usr/lib/gcc/x86_64-linux-gnu/<N>`` that has BOTH the+ gcc runtime dir AND ``/usr/include/c++/<N>`` headers, or None.- Ubuntu 24.04 ships gcc-14 runtime 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 loop ``bbf004c`` added to- ``studio/setup.sh`` for the llama.cpp HIP build (PR #5301).+ Ubuntu 24.04 ships gcc-14 runtime but not ``/usr/include/c++/14``; ROCm+ clang-20 picks the highest runtime dir, finds no ``<cstdlib>``, and the HIP+ build fails. The returned path is passed to clang via+ ``--gcc-install-dir``. Mirrors bbf004c in studio/setup.sh (PR #5301)."""if not sys.platform.startswith("linux"):return None@@ -307,15 +298,10 @@ 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 / 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 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).+ # On Ubuntu 24.04 + ROCm clang-20 the HIP source build dies on a missing+ # <cstdlib> (gcc-14 runtime dir lacks C++ headers). Inject+ # --gcc-install-dir for a gcc whose headers exist, respecting any+ # pre-existing one. Mirrors bbf004c in studio/setup.sh (PR #5301)._existing_flags = os.environ.get("HIPCC_COMPILE_FLAGS_APPEND", "")if "--gcc-install-dir" not in _existing_flags:_gcc_dir = _hipcc_gcc_install_dir()@@ -851,16 +837,16 @@ 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) 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.+# first call (at modeling import) drives the install. Models that never query+# the gate (Llama, Gemma, dense Qwen) pay nothing.+# UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 falls back to the substring path.def _rebind_in_already_imported_modules(*, attr_name: str, old_obj: Any, new_obj: Any) -> int:- """Rebind `attr_name -> new_obj` in every module that already imported `old_obj`.+ """Rebind `attr_name -> new_obj` in every module that imported `old_obj`.`from X import Y` creates a local binding that reassigning X.Y won't reach.- Uses `__dict__.get` (not `getattr`) to skip lazy `__getattr__` aliases.+ Uses `__dict__.get` to skip lazy `__getattr__` aliases."""count = 0missing = object()@@ -1753,10 +1739,9 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->config: Training config dict with all parameters."""os.environ["TOKENIZERS_PARALLELISM"] = "false"- os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports+ os.environ["PYTHONWARNINGS"] = "ignore" # 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).if "HF_HUB_OFFLINE" not in os.environ:import socket as _socketimport threading as _threading@@ -1801,8 +1786,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->model_name = config["model_name"]# ── 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.+ # Apple Silicon uses MLXTrainer directly -- skip torch imports / installs.backend_path = str(Path(__file__).resolve().parent.parent.parent)if backend_path not in sys.path:sys.path.insert(0, backend_path)@@ -1855,10 +1839,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 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).+ # NemotronH needs trust_remote_code=True to work around config-parsing bugs.+ # Other 5.x models are native and don't need it (it bypasses the compiler,+ # disabling fused CE). Must NOT match Llama-Nemotron (standard Llama arch)._NEMOTRON_TRUST_SUBSTRINGS = ("nemotron_h", "nemotron-h", "nemotron-3-nano")_lowered = model_name.lower()if (@@ -1873,18 +1856,12 @@ 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) 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.+ # 1) causal-conv1d ALWAYS runs eagerly via the substring path: some SSM+ # modeling files lazy_load it without calling is_causal_conv1d_available.+ # 2) FLA + tilelang: gated by the runtime hook on+ # is_flash_linear_attention_available (hooks also wrap causal-conv1d).+ # 3) mamba-ssm + flash-attn keep their substring / size gates.+ # 4) UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 falls back to the substring path.try:_ensure_causal_conv1d_fast_path(event_queue, model_name)if os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1":@@ -1915,11 +1892,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->return# ── 1c. Set fork start method so dataset.map() can multiprocess ──- # 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.+ # The compiled SFTTrainer disables num_proc if start method isn't "fork".+ # Linux only and safe here (no CUDA context yet); macOS/Windows excluded.if sys.platform == "linux":import multiprocessing as _mptry:@@ -1940,17 +1914,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: no RCCL backend). No-op off Windows ROCm. Must run before any- # import of transformers / unsloth_zoo.+ # See core/_torchao_stub.py for the rationale (no RCCL backend on Windows+ # ROCm). No-op elsewhere. Must run before importing transformers/unsloth_zoo.from core._torchao_stub import install_torchao_windows_rocm_stubinstall_torchao_windows_rocm_stub()# ── 1e. Ensure torch.distributed helper attrs are present ──- # Single-GPU training never inits the process group, so these helpers are- # never called — but transformers/trl import them unconditionally.+ # Single-GPU never inits the process group, but transformers/trl import+ # these unconditionally._td_stubs = {"is_initialized": lambda: False,"is_available": lambda: False,@@ -1978,32 +1950,19 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -># ── 1f. Windows ROCm runtime patches ──# torch._grouped_mm has a null HIP kernel on gfx1200 (ROCm ≤ 7.12 Windows),- # causing 0xC0000005 (access violation) during training.- #- # 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 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.- #- # Schema: _grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None,- # 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. Module-level- # _WINDOWS_ROCM_GROUPED_MM_LIB keeps the registration alive past return / GC.+ # causing 0xC0000005 during training. Root cause: JitDecomp (not+ # torch.compile) dispatches _grouped_mm → null crash; TORCHDYNAMO_DISABLE+ # doesn't cover JitDecomp, so we also override the CUDA dispatch key with a+ # Python fallback. Fixed in torch==2.11.0+rocm7.13.0, so gate on HIP < 7.13.+ # Schema: _grouped_mm(self, mat2, offs=None, bias=None, out_dtype=None);+ # offs: optional group-split offsets (MoE-style variable-size batches).+ # _WINDOWS_ROCM_GROUPED_MM_LIB keeps the registration alive past return/GC.global _WINDOWS_ROCM_GROUPED_MM_LIBif 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 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).+ # Broad check (torch.version.hip OR "rocm" in __version__): AMD SDK /+ # Radeon wheels don't always set torch.version.hip, and without it the+ # BNB pin, dynamo-disable, and _grouped_mm fallback would silently skip._build_version_for_rocm = (getattr(_torch_for_rocm, "__version__", "").lower()if _torch_for_rocm is not None@@ -2017,19 +1976,16 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->))if _is_win_rocm_torch:- # Disable dynamo (belt-and-suspenders; the JitDecomp patch below is- # the real fix, but dynamo off avoids any other compile paths).+ # Disable dynamo (belt-and-suspenders; the JitDecomp patch is the+ # real fix, but this avoids 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 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.+ # BNB picks a rocm DLL from torch.version.hip, but AMD's Windows BNB+ # wheel may ship a DLL whose suffix doesn't match. Detect the actual+ # DLL name and override; "72" is a safe fallback. Callers may+ # pre-set the var to override.if "BNB_ROCM_VERSION" not in os.environ:_bnb_rocm_ver = Nonetry:@@ -2050,9 +2006,7 @@ 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 "713" wins over- # "72" when both are present. Glob order isn't guaranteed,- # so always sort rather than take the first match.+ # Highest numeric suffix wins (glob order isn't sorted).if _all_vers:_bnb_rocm_ver = max(_all_vers, key = lambda v: int(v))except Exception:@@ -2066,11 +2020,9 @@ 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- # 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.+ # Parse HIP version for the kernel-fix gate below, falling back to+ # the rocm version embedded in torch.__version__ when version.hip is+ # unset (AMD SDK / Radeon wheels).def _hip_ver_at_least(major: int, minor: int) -> bool:_hip_str = getattr(getattr(_torch_for_rocm, "version", None), "hip", None)if not _hip_str:@@ -2081,13 +2033,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->int(_ver_match.group(1)),int(_ver_match.group(2)),) >= (major, minor)- # AMD SDK / Radeon Windows wheels encode the build as- # "+rocmsdk<date>" (e.g. "2.9.0+rocmsdk20251116") with no- # 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.+ # "+rocmsdk<date>" wheels postdate the gfx120X null-kernel+ # fix (ROCm 7.13), so treat them as >= 7.13 (no workaround).if "rocmsdk" in _build_version_for_rocm:logger.debug("Windows ROCm: AMD SDK wheel detected (%r); "@@ -2121,9 +2068,8 @@ 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); fixed in ROCm 7.13 (torch 2.11+). Install the Python- # fallback only on affected versions so 7.13+ gets the real GPU kernel.+ # Install the Python fallback only on affected versions (ROCm ≤ 7.12)+ # so 7.13+ uses the real GPU kernel.if not _hip_ver_at_least(7, 13):try:import warnings as _warnings@@ -2140,9 +2086,8 @@ 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_rocmif offs is None:- # 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.+ # No offsets: 2-D -> mm, 3-D batched -> bmm+ # (unconditional mm broke 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:@@ -2154,8 +2099,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->else:result = _t.mm(self.contiguous(), mat2.contiguous())else:- # Grouped: 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.offs_list = offs.tolist()pieces = []prev = 0@@ -2216,17 +2160,12 @@ 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 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, 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.+ # On ROCm, exhausting VRAM can hang the HIP driver instead of raising.+ # set_per_process_memory_fraction caps the allocator so PyTorch raises+ # OutOfMemoryError first (NVIDIA already has a graceful OOM path).+ # Unified-memory APUs (gfx1150/gfx1151) share GPU+system RAM, so use 0.80+ # vs 0.90 for discrete. Classify via gcnArchName, else device-name markers.+ # Non-fatal: skipped if torch is not importable.if _hw.IS_ROCM:try:import torch as _torch_mem@@ -2356,9 +2295,8 @@ 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- # (incl. LLM-assisted detection) runs BEFORE model loading so both never- # occupy VRAM at once.+ # Order: detect → dataset → model → prepare → train. Dataset processing 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@@ -2403,25 +2341,6 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->dataset = dataset_resulteval_dataset = None- # [DEBUG] Print first sample before model is loaded- # dataset is a dict {"dataset": <Dataset>, "detected_format": ..., ...}- # or a raw Dataset for audio paths- # try:- # ds = dataset["dataset"] if isinstance(dataset, dict) else dataset- # print(- # f"\n[DEBUG] Dataset loaded BEFORE model. type={type(ds).__name__}, len={len(ds)}",- # flush = True,- # )- # print(f"[DEBUG] Columns: {ds.column_names}", flush = True)- # sample = ds[0]- # preview = {k: str(v)[:300] for k, v in sample.items()}- # print(f"[DEBUG] First sample: {preview}\n", flush = True)- # except Exception as e:- # print(- # f"[DEBUG] Could not preview first sample: {type(e).__name__}: {e}",- # flush = True,- # )-# Disable eval if eval_steps <= 0eval_steps = config.get("eval_steps", 0.00)if eval_steps is not None and float(eval_steps) <= 0:diff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.pyindex 35e2764fe9a..8977ab49070 100644--- a/studio/backend/loggers/config.py+++ b/studio/backend/loggers/config.py@@ -3,15 +3,8 @@"""Structured logging configuration via structlog.-Centralized config with environment-specific formats and processors for-development and production.--Key features:-- Environment-specific formatting (JSON for prod, console for dev)-- ISO timestamps-- Context variable integration-- Log level filtering-- Logger caching for performance+Environment-specific formats (JSON for prod, console for dev), ISO timestamps,+context-var integration, log-level filtering, and logger caching."""import logging@@ -25,11 +18,7 @@ from loggers.handlers import filter_sensitive_dataclass LogConfig:- """Structured logging configuration for the application.-- Static method to configure structlog with environment-specific- formatting and processors.- """+ """Structured logging configuration for the application."""@staticmethoddef setup_logging(diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex 419e041a72f..f03af7b40e8 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -1,18 +1,11 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Logging handlers and middleware for structured logging.--FastAPI middleware + structlog processors for:-- Request/response logging with timing-- 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+"""Structured logging handlers and middleware.++LoggingMiddleware (request/response logging with timing),+filter_sensitive_data (structlog processor for sanitization), and+get_logger (factory for structured loggers)."""import re@@ -107,8 +100,5 @@ def filter_sensitive_data(logger, method_name, event_dict):def get_logger(name: str) -> structlog.BoundLogger:- """Get a bound structured logger for a module.- Args:- name: Usually __name__ of the module- """+ """Get a bound structured logger for a module (name is usually __name__)."""return structlog.get_logger(name)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 1bc96c62063..104d557eea4 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -27,8 +27,7 @@ if sys.platform == "win32":_val = os.environ.get(_var)if _val:candidates.append(os.path.join(_val, "bin"))- # 2. Standard AMD installer location: C:\Program Files\AMD\ROCm\<ver>\bin- # Scan all installed versions, newest first.+ # 2. AMD installer: C:\Program Files\AMD\ROCm\<ver>\bin, newest first._default_root = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "AMD", "ROCm")@@ -62,15 +61,11 @@ if sys.platform == "win32":del _add_rocm_dll_dirs# ── Windows AMD ROCm: set BNB_ROCM_VERSION before any bitsandbytes import ─- # 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.+ # bitsandbytes derives the rocm<ver>.dll name from torch.version.hip, but the+ # wheel ships rocm72.dll, so the server crashes ("Configured ROCm binary not+ # found") without this. Detect the shipped DLL and fall back to "72" (mirrors+ # worker.py). Gate on the rocm bnb DLL / HIP_PATH rather than torch.version.hip+ # to avoid importing torch on every Windows host.if "BNB_ROCM_VERSION" not in os.environ:import glob as _globimport logging as _logging@@ -164,14 +159,11 @@ _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, 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)."""+ """Per-install opaque id at $STUDIO_HOME/share/studio_install_id.++ Returns "" when absent or not a 64-char lowercase-hex token; then+ /api/health emits "" and the launcher accepts any healthy backend.+ Carries no install-path info (matters when Studio runs -H 0.0.0.0)."""try:token = (_STUDIO_ROOT_RESOLVED / "share" / "studio_install_id").read_text().strip()except (OSError, ValueError):@@ -183,20 +175,16 @@ _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 token is present; the launcher contract treats "" as "no baked id,- accept any healthy backend"."""+ """Same-install discriminator for /api/health (cached at import).++ Empty when no installer token is present; the launcher treats "" as+ "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 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.+# Fix broken Windows registry MIME types: some installs map .js to text/plain,+# which mimetypes (hence StaticFiles) inherits and browsers reject for ES+# modules. add_type() before StaticFiles forces correct types.if sys.platform == "win32":mimetypes.add_type("application/javascript", ".js")mimetypes.add_type("text/css", ".css")@@ -215,7 +203,6 @@ from fastapi.responses import FileResponse, HTMLResponse, Responsefrom pathlib import Pathfrom datetime import datetime-# Import routersfrom routes import (auth_router,chat_history_router,@@ -296,16 +283,14 @@ def _desktop_owner() -> dict[str, str] | None:@asynccontextmanagerasync def lifespan(app: FastAPI):"""Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""- # Clean up stale compiled cache from previous runsclear_unsloth_compiled_cache()- # Remove stale .venv_overlay from previous versions — no longer used.- # Version switching now uses .venv_t5/ (pre-installed by setup.sh).+ # Remove stale .venv_overlay from old versions; switching now uses .venv_t5/.overlay_dir = Path(__file__).resolve().parent.parent.parent / ".venv_overlay"if overlay_dir.is_dir():shutil.rmtree(overlay_dir, ignore_errors = True)- # Detect hardware first — sets DEVICE global used everywhere+ # Detect hardware first — sets the DEVICE global used everywhere.detect_hardware()# llama.cpp probes: capability (MTP support) + freshness (release age).@@ -382,12 +367,10 @@ async def lifespan(app: FastAPI):else:app.state.bootstrap_password = storage.get_bootstrap_password()yield- # Cleanup_hw_module.DEVICE = Noneclear_unsloth_compiled_cache()-# Create FastAPI appapp = FastAPI(title = "Unsloth UI Backend",version = UNSLOTH_VERSION,@@ -395,7 +378,6 @@ app = FastAPI(lifespan = lifespan,)-# Initialize structured loggingfrom loggers.config import LogConfigfrom loggers.handlers import LoggingMiddleware@@ -432,19 +414,14 @@ def _build_csp(script_nonce: "str | None" = None) -> str:script_src = "script-src 'self'"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 — 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.+ # Colab parent frames span multi-level *.prod.colab.dev subdomains (CSP+ # wildcards match one level only) and null-origin iframes; use '*' since+ # 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 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.+ # In Colab, the kernel/output scaffolding injects scripts and fetch/WS from+ # *.prod.colab.dev and *.googleusercontent.com, so widen script-src and+ # connect-src for those. Scripts still use a nonce, not 'unsafe-inline'.if _IS_COLAB:script_src += " https://*.prod.colab.dev https://*.googleusercontent.com"connect_src = (@@ -693,7 +670,6 @@ async def _recipes_redirect(rest: str = ""):return _RedirectResponse(url = target, status_code = 308)-# CORS middleware_api_only = os.environ.get("UNSLOTH_API_ONLY") == "1"_cors_origins = ["*"]if _api_only:@@ -729,9 +705,7 @@ app.include_router(inference_router, prefix = "/api/inference", tags = ["inferen# 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: mount the inference router at /v1 for external tools.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"])@@ -747,14 +721,12 @@ app.include_router(training_history_router, prefix = "/api/train", tags = ["trai@app.get("/api/health")async def health_check(request: Request):- """Liveness plus launcher capability bits; install fingerprint gated on a valid bearer.-- 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 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.+ """Liveness plus launcher capability bits; host fingerprint gated on a bearer.++ Unauthenticated callers get non-sensitive fields (service, studio_root_id,+ chat_only, desktop_*, native_path_leases_supported) to re-adopt a sibling+ backend and gate UI before a token exists. version / studio_version /+ device_type require a bearer since they fingerprint the host."""base = {"status": "healthy",@@ -837,11 +809,9 @@ async def shutdown_server(request: Request, current_subject: str = Depends(get_casync 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 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.+ Auth-gated: the response (platform, Python/GPU, memory, ML packages) can+ fingerprint a host, which matters in -H 0.0.0.0 / Colab / Tauri-relayed+ setups where remote callers can reach /api/system."""import platformimport psutil@@ -860,8 +830,8 @@ async def get_system_info(current_subject: str = Depends(get_current_subject)):return {"platform": platform.platform(),"python_version": platform.python_version(),- # Centralized _backend_label so /api/system reports "rocm" on AMD hosts- # instead of "cuda", matching /api/hardware and /api/gpu-visibility.+ # _backend_label so /api/system reports "rocm" (not "cuda") on AMD,+ # matching /api/hardware and /api/gpu-visibility."device_backend": _backend_label(get_device()),"cpu_count": psutil.cpu_count(),"memory": {@@ -898,10 +868,9 @@ 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, 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.+ Vite's default ``crossorigin`` forces CORS mode on font loads, which+ Firefox HTTPS-Only Mode breaks over plain HTTP; stripping it makes them+ same-origin fetches that work on any protocol."""html = html_bytes.decode("utf-8")html = _re.sub(r'\s+crossorigin(?:="[^"]*")?', "", html)@@ -983,10 +952,10 @@ def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]def _is_same_origin_request(request: Request) -> bool:"""True when Origin is missing or matches request's scheme://host:port.- 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- don't misclassify same-origin requests as cross-origin.++ Missing Origin counts as same-origin (top-level GETs omit it). Both sides+ are canonicalised via :func:`_canonical_origin`; callers must emit+ ``Vary: Origin``."""origin = request.headers.get("origin")if origin is None:@@ -1021,7 +990,6 @@ def setup_frontend(app: FastAPI, build_path: Path):if not build_path.exists():return False- # Mount assetsassets_dir = build_path / "assets"if assets_dir.exists():app.mount("/assets", StaticFiles(directory = assets_dir), name = "assets")diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex d7ce6741411..9005f087be6 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -106,9 +106,7 @@ class UnloadRequest(BaseModel):class ValidateModelRequest(BaseModel):- """Lightweight check whether a model identifier *can be resolved* into a- ModelConfig. Does NOT load weights into GPU memory.- """+ """Check whether an identifier resolves to a ModelConfig; does NOT load weights."""model_path: str = Field(..., description = "Model identifier or local path")native_path_lease: Optional[str] = Field(@@ -123,8 +121,7 @@ class ValidateModelRequest(BaseModel):class ValidateModelResponse(BaseModel):"""Result of model validation.- valid == True means ModelConfig.from_identifier() succeeded and basic- introspection (GGUF / LoRA / vision flags) is available.+ valid == True means from_identifier() succeeded and GGUF/LoRA/vision flags are available."""valid: bool = Field(..., description = "Whether the model identifier looks valid")@@ -239,9 +236,8 @@ class UnloadResponse(BaseModel):class LoadProgressResponse(BaseModel):"""Progress of the active GGUF load, sampled on demand.- 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.+ Drives a real progress bar during the post-download warmup (mmap + CUDA upload)+ instead of a spinner that freezes for minutes on large MoE models."""phase: Optional[str] = Field(@@ -399,13 +395,9 @@ class ImageContentPart(BaseModel):class InputDocumentContentPart(BaseModel):"""Document (PDF / file) content part in a multimodal message.- 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`` 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``).+ Studio-normalised shape (file_data or file_url, plus optional filename/media_type).+ Mapped onto Anthropic ``document`` / OpenAI ``input_file`` for vision providers;+ dropped for non-vision providers."""type: Literal["input_document"]@@ -430,10 +422,8 @@ 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. OpenAI-only; routes strip it for every other- provider before proxying.+ Reasoning models may require this replayed before an ``image_generation_call``+ id. OpenAI-only; routes strip it for other providers before proxying."""type: Literal["reasoning"]@@ -445,12 +435,9 @@ 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 request;- ``external_provider`` maps it back to the provider-specific top-level- input item.+ Prior ``image_generation_call`` items let follow-up prompts edit a generated+ image without resending the payload. The frontend forwards it as a synthetic+ assistant part; ``external_provider`` maps it back to a top-level input item."""type: Literal["image_generation_call"]@@ -462,17 +449,12 @@ class ImageGenerationCallContentPart(BaseModel):class CompactionContentPart(BaseModel):- """Anthropic server-side compaction state, attached to an assistant- message for round-tripping on the next turn.-- 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+ """Anthropic server-side compaction state, round-tripped on the next turn.++ Anthropic returns a ``compaction`` block on the assistant message; the next+ request must forward it back so Anthropic reuses the compaction state instead+ of re-summarising. See ``external_provider._stream_anthropic`` andhttps://platform.claude.com/docs/en/build-with-claude/compaction- for the upstream contract."""type: Literal["compaction"]@@ -508,10 +490,9 @@ ContentPart = Annotated[class ChatMessage(BaseModel):"""Single message in a chat conversation.- ``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.+ ``content`` is a string or list of multimodal parts. Assistant messages with+ only ``tool_calls`` may set ``content=None``. Missing ``tool_call_id`` on+ ``role="tool"`` is resolved at the ``ChatCompletionRequest`` layer."""role: Literal["system", "user", "assistant", "tool"] = Field(..., description = "Message role")@@ -568,10 +549,8 @@ class ChatCompletionRequest(BaseModel):Non-OpenAI extension fields are marked with 'x-unsloth'."""- # 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.+ # Accept unknown fields so future OpenAI fields aren't dropped before route+ # code runs. Mirrors AnthropicMessagesRequest and ResponsesRequest.model_config = {"extra": "allow"}model: str = Field(@@ -729,16 +708,13 @@ class ChatCompletionRequest(BaseModel):@field_validator("enable_prompt_caching", mode = "before")@classmethoddef _coerce_enable_prompt_caching(cls, value: Any) -> Any:- """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."""+ """Coerce JSON bool strings back to bool. Widening to Union[bool, str] for+ Gemini cache names would let `"false"` read as truthy, so canonical bool+ literals are coerced to keep explicit opt-outs working."""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 old opt-outs still parse. Anything else- # stays a string for Gemini's cachedContent resource path.+ # Match Pydantic v1's bool coercion table; anything else stays a+ # string for Gemini's cachedContent resource path.if lowered in ("true", "t", "1", "yes", "y", "on"):return Trueif lowered in ("false", "f", "0", "no", "n", "off"):@@ -828,8 +804,7 @@ class ChatCompletionRequest(BaseModel):unconsumed tool_call; synth a random id only if none exists. A userturn breaks the lookup."""- # Pre-mark explicit ids first so a sibling missing-id result doesn't- # steal one already claimed by name.+ # Pre-mark explicit ids so a missing-id sibling can't steal a claimed one.consumed: set[tuple[int, int]] = set()def _mark_consumed(start_idx: int, tool_call_id: str) -> None:@@ -891,10 +866,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 backend persistent storage.+ """Shared body for the OpenAI container endpoints (list / create / delete).++ Carries the encrypted API key + base URL so the route can decrypt and proxy+ to the user's account, keeping the key off backend persistent storage."""encrypted_api_key: str = Field(@@ -1041,11 +1016,9 @@ class ResponsesInputImagePart(BaseModel):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 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.+ Clients looping on a stateless Responses endpoint round-trip prior assistant+ messages as ``output_text`` parts; we keep the text and ignore the+ annotations/logprobs when flattening into Chat Completions."""type: Literal["output_text"]@@ -1057,10 +1030,9 @@ class ResponsesOutputTextPart(BaseModel):class ResponsesUnknownContentPart(BaseModel):- """Catch-all for content-part types we don't model explicitly.+ """Catch-all for unmodelled content-part types.- Keeps validation green when a client sends newer part types (e.g.- ``input_audio``, ``input_file``) we haven't mapped; these are skipped+ Keeps validation green for newer part types (e.g. ``input_audio``); skippedduring normalisation rather than rejected with a 422."""@@ -1084,17 +1056,15 @@ class ResponsesInputMessage(BaseModel):role: Literal["system", "user", "assistant", "developer"]content: Union[str, list[ResponsesContentPart]]- # Codex (gpt-5.3-codex+) attaches a `phase` field ("commentary" |- # "final_answer") to assistant messages and requires clients to preserve- # it across turns. We accept and round-trip it; llama-server ignores it.+ # Codex attaches a `phase` field to assistant messages and requires clients+ # to preserve it across turns; we round-trip it, llama-server ignores it.model_config = {"extra": "allow"}class ResponsesFunctionCallInputItem(BaseModel):"""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 in assistant messages), correlated across turns by ``call_id``.+ Tool calls are top-level input items (not nested), correlated by ``call_id``."""type: Literal["function_call"]@@ -1125,12 +1095,10 @@ class ResponsesFunctionCallOutputInputItem(BaseModel):class ResponsesUnknownInputItem(BaseModel):- """Catch-all for Responses input item types we don't model explicitly.+ """Catch-all for unmodelled Responses input item types.- Covers ``reasoning`` items (replayed from prior o-series / gpt-5 turns)- 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.+ Covers ``reasoning`` items and future types. Dropped during normalisation+ (GGUFs can't consume them), but kept in the union so unrelated turns don't 422."""type: str@@ -1141,12 +1109,9 @@ class ResponsesUnknownInputItem(BaseModel):def _responses_input_item_discriminator(v: Any) -> str:"""Route a Responses input item to the correct tagged variant.- 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.+ Pydantic's smart-union matching misreports errors when a strict-``Literal``+ variant doesn't match; an explicit discriminator makes routing deterministic+ and falls through to the catch-all."""if isinstance(v, dict):t = v.get("type")@@ -1177,10 +1142,8 @@ ResponsesInputItem = Annotated[class ResponsesFunctionTool(BaseModel):"""Flat function-tool definition for the Responses API request.- Unlike Chat Completions (which nests ``{"name": ..., "parameters": ...}``- 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.+ Unlike Chat Completions (nested under a ``"function"`` key), this uses a flat+ shape with ``type``/``name``/``description``/``parameters``/``strict`` at top level."""type: Literal["function"]@@ -1204,11 +1167,9 @@ 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). Plain list so- # built-in tool shapes (``web_search``, ``file_search``, ``mcp``, ...)- # round-trip without validation errors; the translator forwards only- # ``type=="function"`` entries.+ # OpenAI function-calling fields, forwarded via the Chat Completions+ # pass-through. Plain list so built-in tool shapes round-trip without+ # validation errors; the translator forwards only ``type=="function"`` entries.tools: Optional[list[dict]] = Field(None,description = (@@ -1264,9 +1225,7 @@ class ResponsesOutputMessage(BaseModel):class ResponsesOutputFunctionCall(BaseModel):"""A function-call output item in the Responses API response.- 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.+ Each tool call is its own top-level ``output`` item, correlated via ``call_id``."""type: Literal["function_call"] = "function_call"diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex 829be12c916..4a3303c734c 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -10,9 +10,8 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validafrom typing import Any, Optional, List, Dict, Literal-# ASCII integer with an optional single sign. Used by _check_vision_image_size-# to reject "++512", "--256", and Unicode-digit strings ("512", "٥١٢") that-# would otherwise slip through str.isdigit() + int().+# ASCII integer, optional single sign. Rejects "++512" and Unicode digits+# ("512") that slip through str.isdigit() + int()._INT_RE = re.compile(r"[+-]?[0-9]+")@@ -131,8 +130,7 @@ class TrainingStartRequest(BaseModel):@field_validator("num_epochs")@classmethoddef _check_num_epochs(cls, v: int) -> int:- # 0 is a sentinel meaning "use max_steps instead"; the frontend's- # steps-vs-epochs toggle sends it.+ # 0 is a sentinel for "use max_steps instead" (frontend toggle).if v is None:return 1if v < 0 or v > _MAX_EPOCHS:@@ -342,8 +340,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. Both 0 means nothing to train against.+ # Each accepts 0 as "use the other"; both 0 means nothing to train.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 selfdiff --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__.pyindex fd3846dc21e..62ecb2e280b 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@@ -2,6 +2,5 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0# 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 depending on data_designer.engine.* during-# Studio's bootstrap (circular import).+# in plugin.py, so importing this package must not touch data_designer.engine.*+# during Studio 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.pyindex 9190b6a738f..330e917f3f0 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@@ -16,13 +16,10 @@ from .config import GitHubRepoSeedSourcefrom .scraper import ScrapeConfig, materialize_to_jsonl-# In-process cache mapping a stable config signature to the JSONL materialization-# 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.+# In-process cache: config signature -> JSONL path. A recipe job reads the seed+# multiple times (validation, preview, sampling); memoize to avoid re-scraping+# GitHub on each call. Key uses a short SHA-256 of the token (never the raw value)+# so token never hits memory twice and rotation invalidates cleanly._SCRAPE_CACHE: dict[tuple, str] = {}_SCRAPE_CACHE_LOCK = threading.Lock()@@ -46,8 +43,7 @@ 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, restart, ...); drop it so the caller- # materializes a fresh file instead of returning a dangling path.+ # Stale entry (tmp cleanup/restart); drop it so the caller re-materializes.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.pyindex 926606c24ca..637193e8b3e 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@@ -19,7 +19,7 @@ import uuidfrom dataclasses import dataclassfrom pathlib import Path-# Defer scraper_impl imports until `scrape()` runs with a resolved token.+# Defer scraper_impl imports until scrape() has a resolved token._IMPL_DIR = Path(__file__).parent / "scraper_impl"@@ -165,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 large cap.+ # Per-resource limits; limit <= 0 means "all" (large cap).effective_limit = cfg.limit if cfg.limit and cfg.limit > 0 else 1_000_000trial_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.pyindex 9ab174c2d4f..0ba3394ca3f 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@@ -112,9 +112,8 @@ class GitHubClient:def _is_auth_failure(self, r: "requests.Response") -> bool:"""Tell auth failures apart from rate limiting on 401/403.- - 401: always an auth failure (invalid / expired / wrong-scope token).- - 403: auth failure UNLESS it carries a rate-limit signal (Retry-After,- X-RateLimit-Remaining: 0, or secondary / abuse rate-limit text).+ 401 is always auth; 403 is auth unless it carries a rate-limit signal+ (Retry-After, X-RateLimit-Remaining: 0, or abuse/secondary text)."""if r.status_code == 401:return True@@ -168,7 +167,6 @@ class GitHubClient:timeout = 120,)self.calls_graphql += 1- # Update rate info from headersrem = r.headers.get("X-RateLimit-Remaining")rst = r.headers.get("X-RateLimit-Reset")if rem is not None:@@ -203,7 +201,7 @@ class GitHubClient:r.raise_for_status()data = r.json()if "errors" in data and data["errors"]:- # Surface errors but allow partial data; retry on RATE_LIMITED+ # Allow partial data; retry on RATE_LIMITEDerrs = data["errors"]for e in errs:if e.get("type") == "RATE_LIMITED":@@ -301,7 +299,6 @@ class GitHubClient:items = items.get("items", [])for it in items:yield it- # Follow Link headerlink = r.headers.get("Link", "")nxt = Nonefor part in link.split(","):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.pyindex 08e2a28ceb9..a7ddaef5fef 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@@ -49,9 +49,9 @@ class RepoScraper:self.base_dir = base_dirself.client = clientself.trial_limits = trial_limits or {}- # 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.+ # 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 = lightself.repo_dir = base_dir / f"{owner}__{name}"self.repo_dir.mkdir(parents = True, exist_ok = True)@@ -115,9 +115,8 @@ class RepoScraper:return 0total_new = 0page = 0- # Light query skips heavy nested fields; safe at 50 per page.- # Clamp by trial_limit so e.g. limit=1 asks GitHub for first:1- # instead of fetching a full 50-item page and discarding 49.+ # Light query skips heavy nested fields; safe at 50/page. Clamp by+ # trial_limit so limit=1 asks for first:1, not a full 50-item page.page_cap = 50 if self.light else 15trial_cap = self.trial_limits.get(key)per_page = min(page_cap, trial_cap) if trial_cap and trial_cap > 0 else page_cap@@ -223,10 +222,9 @@ class RepoScraper:return 0total_new = 0page = 0- # Heavy nested PR query is capped at 3 per page (GitHub node-count- # ceiling); light query skips reviewThreads/reviews/commits/etc and- # goes to 25 per page. Clamp by trial_limit so limit=1 does not- # fetch a whole 25-item page.+ # Heavy nested PR query caps at 3/page (GitHub node-count ceiling);+ # light query skips nested fields and goes to 25/page. Clamp by+ # trial_limit so limit=1 does not fetch a whole 25-item page.page_cap = 25 if self.light else 3trial_cap = self.trial_limits.get(key)per_page = min(page_cap, trial_cap) if trial_cap and trial_cap > 0 else page_capdiff --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.pyindex e5c2f7a492d..ee7d8727fc4 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@@ -74,7 +74,7 @@ def _round_robin_preview(rows: list[dict[str, str]], preview_size: int) -> list[if not rows or preview_size <= 0:return []- # Group rows by source_file, preserving first-appearance order.+ # Group by source_file, preserving first-appearance order.from collections import OrderedDictgrouped: OrderedDict[str, list[dict[str, str]]] = OrderedDict()diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex c19560c5298..3ac85380feb 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/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-"""-Authentication API routes-"""+"""Authentication API routes."""from fastapi import APIRouter, Depends, HTTPException, Request, Response, status@@ -43,17 +41,12 @@ 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 (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.+ Prefer the absolute path to this install's ``unsloth`` launcher (sibling of+ the running interpreter) so the hint works even when its dir isn't on PATH.++ POSIX paths are shell-quoted. On Windows we use the bare absolute path only+ when it has no spaces (a quoted path differs between cmd and PowerShell);+ otherwise, or if the launcher can't be located, fall back to the PATH form."""try:bin_dir = os.path.dirname(os.path.abspath(sys.executable))diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 8496c970d01..782bba3be0f 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -189,8 +189,6 @@ class ChatMessagesBatchResponse(BaseModel):class ChatImportLedgerResponse(BaseModel):- # Plain list of legacy thread ids; key-less payload keeps the client diff- # to a single Set construction.threadIds: list[str]@@ -201,8 +199,7 @@ class ChatImportLedgerRecordRequest(BaseModel):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.+ # (ON CONFLICT DO NOTHING skips already-recorded ids).accepted: intinserted: int@@ -351,8 +348,7 @@ async def get_thread_messages(thread_id: str, current_subject: str = Depends(getasync 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 return empty lists so callers don't need a pre-flight."""+ """One round-trip per sidebar/search rebuild instead of N. Unknown thread ids return empty lists."""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"]@@ -443,10 +439,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 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."""+ """Legacy-Dexie import ledger: legacy thread ids already copied into chat tables.++ The frontend checks this on tab open to decide whether to re-run the Dexie -> studio.db import.+ """return ChatImportLedgerResponse(threadIds = list_chat_legacy_imports())@@ -478,8 +474,7 @@ 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 in one BEGIN IMMEDIATE so concurrent- # slider drags can't drop each other's updates.+ # Atomic read + deep-merge + write in one BEGIN IMMEDIATE so concurrent updates don't clobber.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.pyindex 01991cd8656..3874bd587c8 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -36,14 +36,9 @@ 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`` - 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 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.+ 1. ``app.state.server_port`` (run.py, post-bind) - survives proxies/tunnels.+ 2. ``request.scope["server"]`` - when Studio starts outside ``run_server``.+ 3. parsed ``request.base_url`` - last resort for test fixtures."""port: Any = getattr(request.app.state, "server_port", None)if not isinstance(port, int) or port <= 0:@@ -76,14 +71,11 @@ def _request_has_desktop_access_token(request: Request) -> bool:def _used_llm_model_aliases(recipe: dict[str, Any]) -> set[str]:- """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 convention in- ``core/data_recipe/service.py::_recipe_has_llm_columns`` and covers all- frontend LLM column types (llm-text, llm-code, llm-structured,- llm-judge).+ """Return model_aliases actually referenced by an LLM column.++ Narrows the "Chat model loaded" gate so orphan model_config nodes don't+ block unrelated runs. The ``llm-`` prefix matches+ ``service.py::_recipe_has_llm_columns`` and covers all LLM column types."""aliases: set[str] = set()for column in recipe.get("columns", []):@@ -180,17 +172,13 @@ 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 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 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.+ """Inject an OpenAI ``response_format`` for each local llm-structured column.++ Clones the model_config and repoints the column at the clone so llm-text /+ llm-judge columns sharing the alias keep free-form sampling. Without this,+ data_designer only adds a prompt-level "return JSON" hint, which small GGUFs+ often break. Forwarding ``response_format`` lets llama-server apply+ grammar-constrained sampling, guaranteeing parseable output."""columns = recipe.get("columns")model_configs = recipe.get("model_configs")@@ -242,14 +230,12 @@ def _inject_local_structured_response_format(if not isinstance(params, dict):params = {}clone["inference_parameters"] = params- # 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.+ # BaseInferenceParams is extra="forbid", so response_format can't sit at+ # the top level. Its `extra_body` passthrough is spread into the request+ # body top level by the OpenAI client, where llama-server reads+ # response_format. Per tools/server/README.md the schema sits directly+ # under response_format (not nested in a json_schema object as OpenAI+ # expects) and is converted to a GBNF grammar for sampling.extra_body = params.get("extra_body")if not isinstance(extra_body, dict):extra_body = {}@@ -266,22 +252,18 @@ 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, set- the endpoint to this server and inject a short-lived internal- sk-unsloth-* API key for workflow auth.+ """Mutate recipe in-place: point is_local providers at this server and mint+ a short-lived internal sk-unsloth-* key for workflow auth.- 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.+ Returns the minted key's row id (for the caller to revoke on 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. Strict- # `is True` guard so malformed payloads (is_local: 1, is_local: "true")- # do not trigger the loopback rewrite.+ # Collect local providers and pop is_local from ALL dicts. Strict `is True`+ # guard so malformed payloads (1, "true") don't trigger the loopback rewrite.local_indices: list[int] = []for i, provider in enumerate(providers):if not isinstance(provider, dict):@@ -296,9 +278,8 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optionaendpoint = _resolve_local_v1_endpoint(request)# 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.+ # column via a model_config. Orphan model_config nodes shouldn't block runs;+ # the recipe never calls /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 = {@@ -310,20 +291,16 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optionatoken = ""internal_key_id: Optional[int] = Noneif local_names & referenced_providers:- # Verify the selected local model is loaded before minting a workflow- # 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.+ # Verify the selected local model is loaded before minting a key. Still+ # a point-in-time check (TOCTOU); the /v1 endpoint returns a clear 400 if+ # the model is unloaded or swapped before the subprocess calls it._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 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.+ # Mint an internal sk-unsloth-* key scoped to this run via the unified+ # API-key path. Marked internal so it's hidden from the user's 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",@@ -333,11 +310,9 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optiona)internal_key_id = int(row["id"])- # 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.+ # Strip stale "external"-only fields (extra_headers/extra_body/api_key_env)+ # the frontend may have serialized; a provider flipped from external to local+ # could otherwise carry invalid JSON or rogue auth headers into the /v1 call.for i in local_indices:providers[i]["endpoint"] = endpointproviders[i]["api_key"] = token@@ -346,27 +321,21 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optionaproviders[i].pop("extra_headers", None)providers[i].pop("extra_body", None)- # 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.+ # Force skip_health_check on local model_configs. llama-server's /v1/models+ # response can differ from the selected id (cache aliases, GGUF variants),+ # and we already gated on a loaded backend, so the health check would be+ # redundant and could reject valid local selections.for mc in recipe.get("model_configs", []):if not isinstance(mc, dict):continueif 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 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).+ # Disable thinking for local data-recipe inference. The+ # <think>...</think> preamble roughly doubles tokens per row and+ # pushes answers past data_designer's json-fence regex. Forward+ # chat_template_kwargs={enable_thinking: False} via extra_body so+ # llama-server renders the template without it: llm-text columns get+ # the latency cut, structured columns stop leaking think tags.params = mc.get("inference_parameters")if not isinstance(params, dict):params = {}@@ -381,9 +350,8 @@ def _inject_local_providers(recipe: dict[str, Any], request: Request) -> Optionaextra_body["chat_template_kwargs"] = tpl_kwargsparams["extra_body"] = extra_body- # 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 max_tokens budget on broken JSON.+ # Forward each llm-structured column's output_format as a response_format so+ # llama-server uses grammar-constrained sampling instead of broken JSON._inject_local_structured_response_format(recipe, local_names)return internal_key_id@@ -442,11 +410,9 @@ def create_job(payload: RecipePayload, request: Request):log = logger,) from exc- # 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.). Without the bare except, those would let the- # sk-unsloth-* key live until its 24h TTL.+ # Single try over get_job_manager() AND mgr.start() so a minted key never+ # outlives the request on an unexpected exception; without the bare except it+ # would live until its 24h TTL.try:mgr = get_job_manager()job_id = mgr.start(@@ -483,8 +449,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- revocation failures never mask the caller's own error path."""+ """Best-effort revoke of a workflow-minted key; never mask the caller's error."""try:from auth import storage # deferred: avoids circular importstorage.revoke_internal_api_key(key_id)diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.pyindex 848ed7d5571..8fb034ea4ee 100644--- a/studio/backend/routes/data_recipe/seed.py+++ b/studio/backend/routes/data_recipe/seed.py@@ -581,8 +581,7 @@ def inspect_seed_upload(payload: SeedInspectUploadRequest) -> SeedInspectResponsseed_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 supports only .txt/.md;- # PDF/DOCX extraction uses the multi-file upload endpoint instead+ # Legacy single-file path is .txt/.md only; PDF/DOCX use multi-file upload_LEGACY_UNSTRUCTURED_EXTS = {".txt", ".md"}if seed_source_type == "unstructured":if ext not in _LEGACY_UNSTRUCTURED_EXTS:diff --git a/studio/backend/routes/data_recipe/validate.py b/studio/backend/routes/data_recipe/validate.pyindex 732fa902d64..ffe36ba69ee 100644--- a/studio/backend/routes/data_recipe/validate.py+++ b/studio/backend/routes/data_recipe/validate.py@@ -121,8 +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.- Strict `is True` check matches _inject_local_providers in jobs.py:- truthy but non-boolean is_local values are not treated as local.+ Strict `is True` matches _inject_local_providers: truthy non-boolean values+ aren't treated as local."""for provider in recipe.get("model_providers", []):if not isinstance(provider, dict):@@ -150,13 +150,10 @@ def validate(payload: RecipePayload) -> ValidateResponse:try:build_config_builder(recipe)except ModuleNotFoundError as exc:- # data_designer is an optional runtime dep. Static validation- # 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.+ # data_designer is an optional runtime dep; static validation passed+ # and full validation is deferred to run start, so a missing import+ # shouldn't block the recipe. Restrict the bypass to data_designer so+ # other ImportErrors still surface as failures.if not (exc.name or "").startswith("data_designer"):raiselogger.debug(diff --git a/studio/backend/routes/datasets.py b/studio/backend/routes/datasets.pyindex 1bf035b6843..b755bf9d4a3 100644--- a/studio/backend/routes/datasets.py+++ b/studio/backend/routes/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-"""-Datasets API routes-"""+"""Datasets API routes."""import base64import io@@ -43,11 +41,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.+ """Resolved realpath for a HF cache repo dir: most-recent snapshot, else cache root.- 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.+ Mirrors routes/models.py; duplicated here to keep this module self-contained."""try:snapshots_dir = repo_dir / "snapshots"@@ -61,12 +57,10 @@ def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:return None-# Add backend directory to path.backend_path = Path(__file__).parent.parent.parentif str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))-# Import dataset utilities.from utils.datasets import check_dataset_formatfrom utils.upload_limits import get_upload_limit_bytes, get_upload_limit_labelfrom auth.authentication import get_current_subject@@ -128,12 +122,9 @@ def _serialize_preview_rows(rows):]-# --- Endpoints -----# 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.+# Data-file extensions for the single-file fallback. Tier 1 preview prefers+# tabular over archives: archives (e.g. images.zip) load as ImageFolder 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@@ -378,10 +369,8 @@ 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`` 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.+ ``datasets--owner--name`` cache dir under HF_HUB_CACHE, where in-progress+ download bytes are visible. Returns ``cache_path`` so the UI can show it."""_empty = {"downloaded_bytes": 0,@@ -431,9 +420,8 @@ 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 "done".+ # 95% threshold (as in the model endpoint): HF blob dedup makes+ # completed_bytes drift under expected_bytes; inter-file gaps look "done".if completed_bytes >= expected_bytes * 0.95:progress = 1.0else:@@ -451,12 +439,10 @@ async def get_dataset_download_progress(@router.post("/check-format", response_model = CheckFormatResponse)def check_format(request: CheckFormatRequest, current_subject: str = Depends(get_current_subject)):- """- Check if a dataset requires manual column mapping.+ """Check if a dataset requires manual column mapping.HuggingFace strategy:- 1. list_repo_files → first data file → load_dataset(data_files=[…]).- Avoids resolving thousands of files; typically ~2-4 s.+ 1. list_repo_files -> first data file -> load_dataset (avoids resolving thousands of files; ~2-4 s).2. Full streaming load_dataset as a last-resort fallback.Local files load directly. Plain `def` (not async) so FastAPI runs it in a@@ -484,7 +470,7 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(get)else:# ── HuggingFace dataset ─────────────────────────────────- # Tier 1: list_repo_files → load only the first data file+ # Tier 1: load only the first data file from list_repo_filespreview_slice = Nonetry:@@ -498,15 +484,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 over archives (e.g. images.zip → ImageFolder- # with synthetic image/label columns not in the real schema).+ # Prefer tabular over archives (e.g. images.zip -> ImageFolder+ # with synthetic 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- # With a subset, narrow to files whose name matches- # (e.g. subset="testmini" → prefer "testmini.parquet").+ # With a subset, narrow to files whose name matches it.if request.subset and candidates:subset_matches = [f for f in candidates if request.subset in Path(f).stem]if subset_matches:@@ -532,7 +517,7 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getlogger.warning(f"Tier 1 (single-file) failed: {e}")if preview_slice is None:- # Tier 2: full streaming (resolves all files — slow for large repos)+ # Tier 2: full streaming (resolves all files; slow for large repos)logger.info("Tier 2: falling back to full streaming load_dataset")load_kwargs = {"path": request.dataset_name,@@ -556,14 +541,12 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getpreview_slice = Dataset.from_list(rows)total_rows = None- # 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.preview_samples = Noneif not result["requires_manual_mapping"]:if result.get("suggested_mapping"):@@ -575,7 +558,7 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getformat_result = format_dataset(preview_slice,format_type = "auto",- num_proc = None, # Only 10 preview rows -- no multiprocessing needed+ num_proc = None, # Only 10 preview rows)processed = format_result["dataset"]preview_samples = _serialize_preview_rows(processed)@@ -585,7 +568,7 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getelse:preview_samples = _serialize_preview_rows(preview_slice)- # Collect warnings from check_dataset_format + URL-based image detection.+ # Warnings from check_dataset_format plus 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 []):@@ -629,15 +612,11 @@ def check_format(request: CheckFormatRequest, current_subject: str = Depends(getdef ai_assist_mapping(request: AiAssistMappingRequest, current_subject: str = Depends(get_current_subject)):- """- Run LLM-assisted dataset conversion advisor (user-triggered).-- 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.+ """Run LLM-assisted dataset conversion advisor (user-triggered).- Falls back to simple column classification if the advisor fails.+ Multi-pass analysis with a 7B helper model: classify dataset type, generate+ conversion strategy, validate quality. Falls back to simple column+ classification if the advisor fails."""try:from utils.datasets.llm_assist import llm_conversion_advisordiff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex d687a22f8ed..abb89a13dae 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -16,17 +16,14 @@ from fastapi.responses import StreamingResponseimport structlogfrom loggers import get_logger-# Add backend directory to pathbackend_path = Path(__file__).parent.parent.parentif str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))-# Authfrom auth.authentication import get_current_subjectfrom utils.utils import safe_error_detail-# Backend functionstry:from core.export import get_export_backendexcept ImportError:@@ -35,7 +32,6 @@ except ImportError:sys.path.insert(0, str(parent_backend))from core.export import get_export_backend-# Pydantic modelsfrom models import (LoadCheckpointRequest,ExportStatusResponse,@@ -56,9 +52,6 @@ async def load_checkpoint():"""Load a checkpoint into the export backend (ExportBackend.load_checkpoint)."""try:- # The subprocess-based export backend handles version switching- # automatically — no ensure_transformers_version() needed here.-# Free GPU memory: shut down running inference/training subprocesses# before loading the export checkpoint (they'd compete for VRAM).try:@@ -81,8 +74,7 @@ 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 the training subprocess to exit; else 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.for _ in range(60): # up to 30sif not trn.is_training_active():break@@ -94,9 +86,8 @@ async def load_checkpoint(logger.warning("Could not stop training: %s", e)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.+ # Run in a worker thread (spawns and waits on a subprocess, can take+ # minutes) so the event loop stays free to serve the live log SSE stream.success, message = await asyncio.to_thread(backend.load_checkpoint,checkpoint_path = request.checkpoint_path,@@ -329,21 +320,14 @@ async def export_lora_adapter()-# ─────────────────────────────────────────────────────────────────────-# Live export log stream (Server-Sent Events)-# ─────────────────────────────────────────────────────────────────────+# Live export log stream (Server-Sent Events).#-# 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 shows a live terminal-style-# panel while load_checkpoint / export_merged / export_gguf / export_lora /-# export_base run.+# The export worker's stdout/stderr is piped to the orchestrator as log+# entries (core/export/worker.py, orchestrator.py); this endpoint streams+# them to the browser for a live terminal panel during export operations.#-# Shape follows the training progress SSE endpoint-# (routes/training.py::stream_training_progress): each event carries `id`,-# `event`, `data` fields, the stream starts with a `retry:` directive, and+# Shape follows routes/training.py::stream_training_progress: each event+# carries id/event/data, the stream starts with a `retry:` directive, and# `Last-Event-ID` is honored on reconnect.@@ -388,11 +372,9 @@ async def stream_export_logs("""backend = get_export_backend()- # 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.+ # Starting cursor: explicit `since` wins, then Last-Event-ID on reconnect,+ # else the run-start snapshot so the client sees every line since the run+ # began even if the SSE connection opened after the export-kickoff POST.last_event_id = request.headers.get("last-event-id")if since is None and last_event_id is not None:try:@@ -441,8 +423,8 @@ async def stream_export_logs(yield _format_sse("{}", event = "heartbeat")last_yield = nowif not backend.is_export_active():- # Give the reader thread a moment to drain trailing- # lines the worker printed just before signalling done.+ # Let the reader thread drain trailing lines printed just+ # before the worker signalled done.if idle_since is None:idle_since = nowelif now - idle_since > 1.0:@@ -457,8 +439,7 @@ async def stream_export_logs(await asyncio.sleep(0.1)except asyncio.CancelledError:- # Client disconnected mid-yield. Don't re-raise; end the- # generator cleanly so StreamingResponse finalizes.+ # Client disconnected mid-yield: end cleanly so StreamingResponse finalizes.returnexcept 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.pyindex 86b4251d15d..cf264d0dc9c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -107,12 +107,10 @@ def _friendly_error(exc: Exception) -> str:return "An internal error occurred"-# Add backend directory to pathbackend_path = Path(__file__).parent.parent.parentif str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))-# Import backend functionstry:from core.inference import get_inference_backendfrom core.inference.llama_cpp import (diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 1d8f73eb884..098c64fe39e 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -44,10 +44,8 @@ def _validate_url(url: str) -> str:trimmed = (url or "").strip()if not trimmed: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- # keep existing behaviour and treat any non-HTTP value as a command here.+ # When stdio is enabled, a non-HTTP value is a local command (reuses this+ # field so stdio servers ride existing CRUD/storage).if stdio_mcp_enabled() and is_stdio(trimmed):try:parts = parse_stdio_command(trimmed)@@ -76,8 +74,7 @@ def _validate_url(url: str) -> str:"MCP server address must start with http:// or https:// ""(for example https://example.com/mcp).")- # Host-scoped wording ("this server"), not "desktop only": self-hosted- # hosts can opt in via the env var.+ # Host-scoped wording: self-hosted hosts can opt in via the env var.if _looks_like_command(trimmed):detail += " Running a local command is not enabled on this server."raise HTTPException(status_code = 400, detail = detail)diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 319330d428e..ce4e41a062e 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -28,11 +28,10 @@ def _is_valid_repo_id(repo_id: str) -> bool:def _safe_is_dir(path) -> bool:"""``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.+ Python >= 3.12 propagates ``PermissionError`` from ``is_dir()``;+ folder-scan endpoints probe system locations (e.g. root-owned+ ``/usr/share/ollama``) and must treat un-stat-able paths as "not a+ directory", never 500."""try:return Path(path).is_dir()@@ -40,14 +39,12 @@ def _safe_is_dir(path) -> bool:return False-# Add backend dir to pathbackend_path = Path(__file__).parent.parent.parentif str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))from auth.authentication import get_current_subject-# Import backend functionstry:from utils.models import (scan_trained_models,@@ -76,7 +73,7 @@ try:resolve_export_dir,)except ImportError:- # Fallback: 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))@@ -164,14 +161,10 @@ def _resolve_hf_cache_dir() -> Path:def _is_model_directory(d: Path) -> bool:"""Return ``True`` when *d* looks like 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.) to avoid- false positives.+ Requires both a config (``config.json``/``adapter_config.json``) and+ weight files. Excludes ``mmproj`` GGUFs (vision projectors) and+ non-weight ``.bin`` files (``tokenizer.bin`` etc.) to avoid false+ positives."""def _is_weight_file(f: Path) -> bool:@@ -235,8 +228,7 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Locaor any(child.glob("*.gguf")))except OSError:- # Skip unreadable children (permissions, broken symlinks)- # rather than failing the whole scan.+ # Skip unreadable children rather than failing the scan.continueif not has_model_files:continue@@ -253,7 +245,7 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Locaupdated_at = updated_at,),)- # Also scan standalone .gguf files 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:@@ -317,10 +309,8 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:if not lm_dir.exists() or not lm_dir.is_dir():return []- # 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 lm_dir is itself a model directory (not a publisher structure),+ # return it as a single entry rather than skipping it silently.if _is_model_directory(lm_dir):try:updated_at = lm_dir.stat().st_mtime@@ -356,9 +346,8 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:)continue- # If the child looks like a model directory (config AND- # weights), surface it directly instead of descending into- # it as a publisher.+ # Surface a model-directory child directly instead of+ # descending into it as a publisher.if _is_model_directory(child):try:updated_at = child.stat().st_mtime@@ -375,7 +364,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:)continue- # child is a publisher directory -- scan its subdirectories+ # child is a publisher directory; scan its subdirectories.for model_dir in child.iterdir():try:if model_dir.is_dir():@@ -427,10 +416,8 @@ def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:"""Return a writable directory for Ollama ``.gguf`` symlinks.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.+ blobs; falls back to a per-ollama-dir namespace under Studio's cache+ when the models dir is read-only (common for system installs)."""from utils.paths.storage_roots import cache_root@@ -445,8 +432,8 @@ def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:e,)- # Fallback: namespace by a hash of ollama_dir so two Ollama roots- # don't collide. Cache path, not a security boundary.+ # Fallback: namespace by a hash of ollama_dir so two roots don't+ # collide. Cache path, not a security boundary.try:digest = hashlib.sha256(str(ollama_dir.resolve()).encode()).hexdigest()[:12]except OSError:@@ -467,29 +454,19 @@ 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 uses a content-addressable layout::-- <ollama_dir>/manifests/<host>/<namespace>/<model>/<tag>- <ollama_dir>/blobs/sha256-...-- 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 uses a content-addressable layout+ (``manifests/<host>/<namespace>/<model>/<tag>`` + ``blobs/sha256-...``);+ we ``rglob`` all manifests 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+ and ``...image.projector`` is the vision adapter.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.+ requires, so we create ``.gguf``-named links to them (one subdir per+ model, keyed by a short hash of the manifest path, so+ ``detect_mmproj_file`` only sees that model's projector). Links are+ symlinks when possible, else hardlinks; the link dir is+ ``.studio_links/`` when writable, else Studio's cache."""manifests_root = ollama_dir / "manifests"if not manifests_root.is_dir():@@ -508,10 +485,8 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locadef _make_link(link_dir: Path, link_name: str, target: Path) -> Optional[str]:"""Create a .gguf-named link to an Ollama blob.- 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.-+ Tries symlink, then hardlink; skips the model if neither works+ (a multi-GB copy in a sync request would block the backend).Idempotent: skips recreation when a valid link already exists."""link_dir.mkdir(parents = True, exist_ok = True)@@ -519,8 +494,7 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locaresolved = target.resolve()# 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.+ # only; size checks can reuse stale links after `ollama pull`.try:if link_path.exists() and os.path.samefile(str(link_path), str(resolved)):return str(link_path)@@ -673,10 +647,7 @@ async def list_local_models(),current_subject: str = Depends(get_current_subject),):- """- List local model candidates from custom models dir, HF cache,- legacy Unsloth HF cache, and LM Studio directories.- """+ """List local model candidates from the models dir, HF caches, and LM Studio dirs."""from utils.paths import (legacy_hf_cache_dir,hf_default_cache_dir,@@ -691,7 +662,7 @@ async def list_local_models(# 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.+ # used for matching only, 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,11 +690,11 @@ async def list_local_models(try:local_models = _scan_models_dir(models_root) + _scan_hf_cache(hf_cache_dir)- # Scan legacy Unsloth HF cache for backward compatibility+ # Scan legacy Unsloth HF cache for backward compatibility.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 under env overrides)+ # Scan HF system default cache (may differ under env overrides).if (hf_default.is_dir()and hf_default.resolve() != hf_cache_dir.resolve()@@ -731,11 +702,11 @@ async def list_local_models():local_models += _scan_hf_cache(hf_default)- # Scan LM Studio directories+ # Scan LM Studio directories.for lm_dir in lm_dirs:local_models += _scan_lmstudio_dir(lm_dir)- # Scan user-added custom folders (per-folder cap)+ # Scan user-added custom folders (per-folder cap).from storage.studio_db import list_scan_folders_MAX_MODELS_PER_FOLDER = 200@@ -747,9 +718,8 @@ 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 generic scanners to avoid- # duplicates and leaking internal paths into the UI.+ # Filter Ollama .studio_links/ from generic scanners to+ # avoid duplicates and leaking internal paths into the UI._generic = [mfor m in (@@ -770,10 +740,9 @@ async def list_local_models(continuelocal_models += [m.model_copy(update = {"source": "custom"}) for m in custom_models]- # 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.+ # Deduplicate, but always keep custom folder entries (keyed by+ # (id, source)) so they show in the "Custom Folders" UI section+ # even when the model is also in the HF cache.deduped: dict[str, LocalModelInfo] = {}for model in local_models:key = f"{model.id}\x00custom" if model.source == "custom" else model.id@@ -820,8 +789,7 @@ async def add_scan_folder_endpoint(folder = add_scan_folder(body.path)except ValueError as e:logger.warning("Scan folder rejected: %s (path=%s)", e, body.path)- # Curated, path-free validation message (e.g. "Path does not exist"):- # forward the text, not the raw exception.+ # Forward the curated, path-free validation message.rejection_message = str(e)raise HTTPException(status_code = 400, detail = rejection_message)logger.info("Scan folder added: %s", folder.get("path"))@@ -844,10 +812,9 @@ 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 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.+ Lightweight alternative to ``browse-folders`` for the frontend's+ one-click "Recommended" chips; returns existing paths only (HF+ cache, LM Studio, Ollama, ``~/models``, etc.)."""from utils.paths.storage_roots import lmstudio_model_dirs@@ -867,14 +834,14 @@ async def get_recommended_folders(current_subject: str = Depends(get_current_subseen.add(resolved)folders.append(resolved)- # LM Studio model directories+ # LM Studio model directories.try:for p in lmstudio_model_dirs():_add(p)except Exception as e:logger.warning("Failed to scan for LM Studio model directories: %s", e)- # Ollama model directories+ # Ollama model directories.ollama_env = os.environ.get("OLLAMA_MODELS")if ollama_env:_add(Path(ollama_env).expanduser())@@ -889,24 +856,19 @@ async def get_recommended_folders(current_subject: str = Depends(get_current_sub# 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.+# holds models; keeps the browser snappy on huge dirs._BROWSE_MODEL_HINT_PROBE = 64-# 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.+# Hard cap on subdirectory entries returned, so browsing ``/usr/lib``+# can't stat-storm the process or flood the client._BROWSE_ENTRY_CAP = 2000def _count_model_files(directory: Path, cap: int = 200) -> int:"""Count GGUF/safetensors files immediately inside *directory*.- 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.+ Surfaces a count-hint so the UI can mark a weights-only leaf dir as a+ valid "Use this folder" target. Bounded by *visited entries* (stops+ after ``cap``), so the hint never costs more than a bounded walk."""n = 0visited = 0@@ -932,10 +894,9 @@ 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 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."""+ """Return True if an immediate child signals a model: a+ GGUF/safetensors/config.json file or a ``models--*`` subdir (HF+ cache). Bounded by ``_BROWSE_MODEL_HINT_PROBE``."""try:it = directory.iterdir()except OSError:@@ -962,22 +923,13 @@ def _has_direct_model_signal(directory: Path) -> bool:def _looks_like_model_dir(directory: Path) -> bool:- """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 ``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 -- 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.+ """Bounded heuristic to flag dirs worth exploring in the browser.++ False negatives are fine (the real scanner is authoritative). Three+ signals, cheapest first: (1) name ``models--*`` (HF cache layout),+ (2) an immediate child weight/config file, (3) a grandchild with a+ direct signal (LM Studio / Ollama ``publisher/model`` layout, probing+ the first ``_BROWSE_MODEL_HINT_PROBE`` child dirs)."""if directory.name.startswith("models--"):return True@@ -997,7 +949,6 @@ def _looks_like_model_dir(directory: Path) -> bool:continueexcept OSError:continue- # Fast name check first.if child.name.startswith("models--"):return Trueif _has_direct_model_signal(child):@@ -1008,15 +959,13 @@ def _looks_like_model_dir(directory: Path) -> bool:def _build_browse_allowlist() -> list[Path]:- """Return the root directories the folder browser may walk. The same- list seeds the sidebar suggestion chips, so chip targets are always- reachable.+ """Return the root directories the folder browser may walk.- Roots: the user's HOME, resolved HF cache dirs, Studio's+ The same list seeds the sidebar suggestion chips, so chip targets are+ always reachable. Roots: HOME, resolved HF cache dirs, Studio'soutputs/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.+ local-LLM dirs (LM Studio, Ollama, ``~/models``); each added only if+ it resolves to a real directory."""from utils.paths import (hf_default_cache_dir,@@ -1085,7 +1034,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 descends from any allowed root.+ """True if *target* equals or descends from any allowed root.+Uses ``os.path.realpath`` so symlinks can't escape the sandbox."""try:@@ -1243,31 +1193,21 @@ async def browse_folders(),current_subject: str = Depends(get_current_subject),):- """- List immediate subdirectories of *path* for the Custom Folders picker.+ """List immediate subdirectories of *path* for the Custom Folders picker.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: bounded to the allowlist from- :func:`_build_browse_allowlist` (HOME, HF cache, Studio dirs,- 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`).+ dialog. Read-only: enumerates visible subdirectories so the user can+ click to a folder and hand the string to POST /api/models/scan-folders.++ Sandbox: bounded to :func:`_build_browse_allowlist`; paths outside it+ return 403, and symlinks are resolved via ``os.path.realpath`` first+ so traversal can't escape. Sorting: model-bearing dirs, then plain,+ then hidden (if ``show_hidden=true``)."""from utils.paths import hf_default_cache_dir, well_known_model_dirsfrom storage.studio_db import list_scan_folders- # Build the allowlist once -- the sandbox check and suggestion chips- # share it, so chips are always navigable.+ # Build once; the sandbox check and suggestion chips share it.allowed_roots = _build_browse_allowlist()try:@@ -1282,8 +1222,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 us.+ # Enumerate immediate subdirectories with a bounded cap.entries: list[BrowseEntry] = []truncated = Falsevisited = 0@@ -1303,12 +1242,9 @@ async def browse_folders(try:for child in it:- # 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.+ # Bound by *visited*, not *appended*: a cap on len(entries)+ # would never trigger in dirs full of files. Counting visits+ # caps worst-case work at ``_BROWSE_ENTRY_CAP`` calls.visited += 1if visited > _BROWSE_ENTRY_CAP:truncated = True@@ -1336,10 +1272,10 @@ async def browse_folders(exc,)except OSError as exc:- # Rare: iterdir succeeded but reading a specific entry failed.+ # Rare: iterdir succeeded but reading an entry failed.logger.warning("browse-folders: partial enumeration of %s: %s", target, exc)- # Model-bearing dirs first, then plain, then hidden; case-insensitive+ # Model-bearing first, then plain, then hidden; case-insensitive# alphabetical within each bucket.def _sort_key(e: BrowseEntry) -> tuple[int, str]:bucket = 0 if e.has_models else (2 if e.hidden else 1)@@ -1347,10 +1283,9 @@ async def browse_folders(entries.sort(key = _sort_key)- # 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 is None at the filesystem root and when it would leave the+ # sandbox (else the up-row would 403 on click); users can still hop+ # to other allowed roots via the suggestion chips.parent: Optional[str]if target.parent == target or not _is_path_inside_allowlist(target.parent, allowed_roots):parent = None@@ -1387,12 +1322,8 @@ async def browse_folders(_add_sug(Path(folder.get("path", "")))except Exception as exc:logger.debug("browse-folders: could not load scan folders: %s", exc)- # 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.+ # Dirs used by other local-LLM tools (LM Studio, Ollama, ~/models);+ # the helper returns only existing paths, so no dead chips.try:for p in well_known_model_dirs():_add_sug(p)@@ -1410,8 +1341,8 @@ async def browse_folders(def _looks_like_mlx_repo(model_id: str) -> bool:- """Name heuristic for unloaded models, mirrors the -GGUF suffix check.- Tokenized so MLX only matches as a whole name segment."""+ """Name heuristic for unloaded models (mirrors the -GGUF suffix check);+ tokenized so MLX only matches as a whole name segment."""if model_id.lower().startswith("mlx-community/"):return Truetail = model_id.split("/")[-1]@@ -1459,14 +1390,12 @@ async def list_models(current_subject: str = Depends(get_current_subject)):))- # Combine default and loaded models.+ # Combine default and loaded; prefer loaded entries for duplicate+ # ids so runtime flags survive.all_models = []seen_ids = set()-- # 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 modelsfor model_id in default_models:if model_id not in seen_ids:model_info = loaded_by_id.get(model_id) or ModelDetails(@@ -1478,7 +1407,6 @@ async def list_models(current_subject: str = Depends(get_current_subject)):all_models.append(model_info)seen_ids.add(model_id)- # Add loaded models.for model_info in loaded_models:if model_info.id not in seen_ids:all_models.append(model_info)@@ -1551,12 +1479,11 @@ async def get_model_config(config_dict = load_model_defaults(model_name)- # Detect capabilities (pass HF token for gated models).+ # Detect capabilities (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.is_lora = Falsebase_model = Nonemax_position_embeddings = None@@ -1568,7 +1495,7 @@ async def get_model_config(except Exception:pass- # Fallback: try AutoConfig directly if not found yet.+ # Fallback: try AutoConfig directly.if max_position_embeddings is None:try:from transformers import AutoConfig as _AutoConfig@@ -1630,7 +1557,6 @@ async def scan_loras(resolved_exports_dir = str(resolve_export_dir(exports_dir))lora_list = []- # 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)@@ -2092,16 +2018,15 @@ 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 GGUF quantization variants for a HuggingFace repo or local- directory (e.g. LM Studio model folder).+ """List GGUF quantization variants for a HF repo or local directory.- Returns all variants (Q4_K_M, Q8_0, BF16, etc.) with file sizes,- whether the model supports vision, and the recommended default.+ Returns all variants with file sizes, vision support, 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 — scan filesystem.if is_local_path(repo_id):variants, has_vision = list_local_gguf_variants(repo_id)@@ -2127,22 +2052,19 @@ async def get_gguf_variants(# Remote HuggingFace repo — query HF API.variants, has_vision = list_gguf_variants(repo_id, hf_token = hf_token)- # 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# 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+ # GGUFs ALL shards must be present, so sum cached bytes per variant+ # vs. the expected total. Cache dir casing may differ from the# canonical repo_id, so match case-insensitively.cached_bytes_by_quant: dict[str, int] = {}try:import re as _refrom huggingface_hub import constants as hf_constants- # 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}")@@ -2166,7 +2088,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- # Small rounding tolerance (symlinks vs real sizes).+ # Rounding tolerance (symlinks vs real sizes).return cached >= variant.size_bytes * 0.99return GgufVariantsResponse(@@ -2226,7 +2148,7 @@ async def get_gguf_download_progress(fname = f.name.lower().replace("-", "").replace("_", "")if not variant_lower or variant_lower in fname:downloaded_bytes += f.stat().st_size- # In-progress downloads (.incomplete) in blobs.+ # In-progress (.incomplete) downloads in blobs.blobs_dir = entry / "blobs"if blobs_dir.is_dir():for f in blobs_dir.iterdir():@@ -2251,9 +2173,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` points- at), falling back to the cache repo root. Returns the resolved- realpath so symlinks under snapshots/ follow back to blobs/.+ Prefers the most-recent snapshot dir (what ``from_pretrained`` uses),+ falling back to the cache repo root. Returns the resolved realpath so+ snapshot symlinks follow back to blobs/."""try:snapshots_dir = repo_dir / "snapshots"@@ -2318,7 +2240,6 @@ async def get_download_progress(if downloaded_bytes == 0:return {**_empty, "cache_path": cache_path}- # Expected size from HF API (cached per repo_id).expected_bytes = _get_repo_size_cached(repo_id)if expected_bytes <= 0:# Total unknown; report bytes only, no percentage.@@ -2329,10 +2250,9 @@ async def get_download_progress("cache_path": cache_path,}- # 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.+ # 95% threshold (blob dedup can skew completed_bytes). Do NOT+ # treat "no .incomplete files" as done: HF downloads sequentially,+ # so none exist between files even when far from finished.if completed_bytes >= expected_bytes * 0.95:progress = 1.0else:@@ -2374,7 +2294,7 @@ def _all_hf_cache_scans():scans = [scan_cache_dir()]seen: set[str] = set()try:- # Resolve the active cache dir for deduplication.+ # Resolve the active cache dir for dedup.from huggingface_hub.constants import HF_HUB_CACHEseen.add(str(Path(HF_HUB_CACHE).resolve()))except Exception:diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex c78739be848..64d1c3eab39 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -54,10 +54,8 @@ 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, 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``).+ ``fingerprint`` is a short SHA256 of the PEM; a mismatch with what the+ frontend captured at encrypt time signals the keypair rotated mid-flight."""return {"public_key": get_public_key_pem(),@@ -80,9 +78,7 @@ 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."""+ usage into per-turn USD cost. See ``core/inference/pricing.py`` for sourcing."""return pricing_snapshot()@@ -307,15 +303,10 @@ 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 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".+ # Registry model-id filters only apply to the native Gemini base. A+ # custom OAI-compatible proxy returns prefixed IDs the native allowlist+ # would strip, leaving the picker empty; match the host check here so the+ # model list and chat dispatch agree on what counts as "native".apply_registry_model_filters = Trueif payload.provider_type == "gemini":try:@@ -342,10 +333,8 @@ 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", ""))]- # 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.+ # Optional cap after filtering to keep large catalogs picker-sized.+ # Unsorted, so "first N matches"; pair with default_models for flagships.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.pyindex 7ce086e5b20..96403e21a56 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -16,12 +16,11 @@ import asynciofrom datetime import datetimeimport uuid as _uuid-# Add backend directory to path (same directory structure).+# Add backend directory to path.backend_path = Path(__file__).parent.parent.parentif str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))-# Import backend functions.try:from core.training import get_training_backendfrom core.training.resume import (@@ -33,7 +32,7 @@ try:from utils.models.model_config import load_model_defaultsfrom utils.paths import resolve_dataset_pathexcept ImportError:- # Fallback: import from the parent directory.+ # Fallback: parent directory.parent_backend = backend_path.parent / "backend"if str(parent_backend) not in sys.path:sys.path.insert(0, str(parent_backend))@@ -121,13 +120,12 @@ async def start_training(try:logger.info(f"Starting training job with model: {request.model_name}")- # NOTE: No in-process ensure_transformers_version() call here.- # The subprocess (worker.py) activates the correct version in a- # fresh Python interpreter before importing any ML libraries.+ # No in-process ensure_transformers_version(): the subprocess+ # (worker.py) activates the correct version before importing ML libs.backend = get_training_backend()- # Check if training is already active (before mutating state).+ # Check before mutating state.if backend.is_training_active():existing_job_id: Optional[str] = getattr(backend, "current_job_id", "")return TrainingJobResponse(@@ -140,8 +138,8 @@ async def start_training(error = "Training already active",)- # Job ID — passed to start_training(), which sets it on the backend only- # after confirming the old pump thread is dead.+ # Job ID; start_training() sets it on the backend only after 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.@@ -239,9 +237,8 @@ async def start_training("gpu_ids": request.gpu_ids,}- # Training page has no trust_remote_code toggle — the value comes from- # YAML model defaults on model select. As a safety net, consult the YAML- # directly so models that need it always get it.+ # Training page has no trust_remote_code toggle; as a safety net consult+ # YAML model defaults 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)@@ -407,10 +404,8 @@ async def get_training_status(current_subject: str = Depends(get_current_subjectbackend = get_training_backend()job_id: str = getattr(backend, "current_job_id", "") or ""- # Check if training is activeis_active = backend.is_training_active()- # Get progress info from trainertry:progress = backend.trainer.get_training_progress()except Exception:@@ -421,7 +416,6 @@ async def get_training_status(current_subject: str = Depends(get_current_subject) or "Ready to train"error_message = getattr(progress, "error", None) if progress else None- # Check if training was stopped by usertrainer_stopped = getattr(backend, "_should_stop", False)# Derive high-level phase@@ -497,14 +491,12 @@ async def get_training_metrics(current_subject: str = Depends(get_current_subjectry:backend = get_training_backend()- # Get metrics from backendloss_history = backend.loss_historylr_history = backend.lr_historystep_history = backend.step_historygrad_norm_history = getattr(backend, "grad_norm_history", [])grad_norm_step_history = getattr(backend, "grad_norm_step_history", [])- # Get current valuescurrent_loss = loss_history[-1] if loss_history else Nonecurrent_lr = lr_history[-1] if lr_history else Nonecurrent_step = step_history[-1] if step_history else None@@ -753,8 +745,8 @@ async def stream_training_progress(# No steps yet, but training is active (model loading, etc.).no_update_count += 1if no_update_count % 5 == 0:- # Pull total_steps + status from trainer so the frontend- # can show "Tokenizing…" etc.+ # Pull total_steps + status 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.pyindex b9f271b4bee..c992a4bec23 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -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-# Anaconda/conda-forge Python: seed platform._sys_version_cache before-# 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/102396import _platform_compat # noqa: F401@@ -83,10 +83,9 @@ 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 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"."""+ """Rewrite Uvicorn's startup log line: swap wildcard bind for the+ externally-reachable address, use our Mac-aware stop hint, and rename the+ prefix to "Unsloth Studio running on"."""import loggingimport re@@ -147,8 +146,8 @@ def _local_port_open(def _working_local_url(port: int) -> "str | None":- """A working loopback URL on this machine, or None if neither- 127.0.0.1 nor ::1 responds. 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):@@ -159,10 +158,9 @@ 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 won't reach 127.0.0.1.- 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.+ Local Studio binds to 127.0.0.1. Where localhost resolves to IPv6 only (::1),+ http://localhost:<port> fails (or hits a different process on ::1) even though+ http://127.0.0.1:<port> works. Return the IPv4 URL for the caller to surface."""import socket@@ -193,11 +191,10 @@ def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":if host == "::1":has_ipv6_loopback = True- # 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.+ # 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. Dual-stack+ # localhost is fine (browsers fall back to 127.0.0.1), so only the IPv6-only+ # case strands the user.if has_ipv6_loopback and not has_ipv4_loopback:return ipv4_urlreturn None@@ -230,11 +227,10 @@ 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 (verifier failing != 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 output lands between the banner URLs and the+ stop hint. Bounded at ~15s; failures swallowed (verifier failing != Studio+ failing). Only meaningful for a wildcard bind."""import ipaddressimport jsonimport time@@ -423,9 +419,8 @@ 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) listening on *port*, or None.- 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.+ Uses psutil when available, else None so callers can still report the conflict+ without process details."""try:import psutil@@ -450,17 +445,14 @@ 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), 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.+ For a ``0.0.0.0`` wildcard host, also check whether anything is listening on+ ``127.0.0.1`` (and ``::1`` when IPv6 exists): an SSH tunnel may hold loopback+ while the wildcard bind succeeds, making Studio unreachable via ``localhost``."""import socket# 1. Can we bind to the requested address? getaddrinfo resolves both- # IPv4 ("0.0.0.0") and IPv6 ("::") to the right address family.+ # IPv4 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]@@ -470,9 +462,8 @@ def _is_port_free(host: str, port: int) -> bool:except OSError:return False- # 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.+ # 2. On a wildcard bind, verify localhost isn't already claimed by another+ # process (e.g. an SSH -L tunnel); a successful connect means it is.if host in ("0.0.0.0", "::"):for loopback, family in [("127.0.0.1", socket.AF_INET),@@ -550,9 +541,8 @@ def _remove_pid_file():def _graceful_shutdown(server = None):"""Shut down all subprocess backends and the uvicorn server.- Called from signal handlers to clean up child processes before the- parent exits. Critical on Windows where atexit handlers are- unreliable after Ctrl+C.+ Called from signal handlers to clean up children before exit. Critical on+ Windows where atexit handlers are unreliable after Ctrl+C."""_remove_pid_file()logger.info("Graceful shutdown initiated — cleaning up subprocesses...")@@ -610,9 +600,8 @@ _DEFAULT_FRONTEND_PATH = Path(__file__).resolve().parent.parent / "frontend" / "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 with no vite build (e.g. plain `pip install- unsloth` from PyPI).+ Covers PATH-shadowed binaries whose __file__ resolves into a site-packages+ tree with no vite build (e.g. plain `pip install unsloth`)."""import astimport re@@ -638,9 +627,8 @@ 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/multi-line dict literals; [^}]* rejects nested+ # dicts, which the setuptools editable template never emits.m = re.search(r"^MAPPING\s*(?::[^=]*)?=\s*(\{[^}]*\})", src, re.M | re.S)if not m:continue@@ -648,8 +636,7 @@ 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 isn't a dict.+ # literal_eval can return a set/list/None if `{...}` isn't a dict.if not isinstance(mapping, dict):continuestudio_pkg = mapping.get("studio")@@ -661,8 +648,8 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":def _resolve_frontend_path(frontend_path: Path) -> tuple[Optional[Path], list[Path]]:"""Pick a frontend dir that contains `index.html`.- Returns (chosen, attempted). `chosen` is None if nothing servable was- found; `attempted` is the ordered list for diagnostics.+ Returns (chosen, attempted). `chosen` is None if nothing servable was found;+ `attempted` is the ordered list for diagnostics."""attempted: list[Path] = []seen: set[Path] = set()@@ -706,14 +693,12 @@ def run_server(llama_parallel_slots: parallel slots for llama-serverNote:- 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.+ Signal handlers are NOT registered here so embedders (e.g. Colab) keep+ their own interrupt semantics; standalone callers register them after."""global _server, _shutdown_event- # Windows console encoding (cp1252) can't encode emoji. Reconfigure- # stdout to UTF-8 so startup messages don't crash the server.+ # Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8.if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):try:sys.stdout.reconfigure(encoding = "utf-8", errors = "replace")@@ -756,9 +741,8 @@ 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 loudly rather than serving 404 on `/`.+ # Setup frontend (skip in api-only). Falls back through alternate locations if+ # the default lacks a built dist; errors loudly rather than 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):@@ -775,9 +759,8 @@ def run_server(or os.environ.get("STUDIO_HOME")or str(Path.home() / ".unsloth" / "studio"))- # 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.+ # Windows shim: $STUDIO_HOME/bin/unsloth.exe; Linux/macOS venv binary:+ # $STUDIO_HOME/unsloth_studio/bin/unsloth.home = Path(home_str).expanduser()if sys.platform == "win32":installer_bin = home / "bin" / "unsloth.exe"@@ -821,11 +804,10 @@ def run_server(access_log = False,server_header = False,)- # 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.+ # Colab only: trust X-Forwarded-* from Colab's reverse proxy so the app sees+ # the real https origin. forwarded_allow_ips="*" is safe in Colab's+ # single-user sandbox but too lax for local/standalone, so leave uvicorn's+ # loopback-only default elsewhere.if _IS_COLAB:config_kwargs["proxy_headers"] = Trueconfig_kwargs["forwarded_allow_ips"] = "*"@@ -833,16 +815,14 @@ def run_server(_server = _ReadyServer(config)_shutdown_event = Event()- # 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.+ # Expose the actual bound port so handlers build loopback URLs at the real+ # backend, not whatever a proxy/tunnel exposed. For ephemeral binds (port==0)+ # leave it unset so handlers fall back to the request scope / base_url.app.state.server_port = port if port and port > 0 else Noneapp.state.llama_parallel_slots = llama_parallel_slots- # Expose a shutdown callable via app.state before the server accepts- # requests so /api/shutdown is ready as soon as readiness publishes.+ # Expose a shutdown callable 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:@@ -850,10 +830,9 @@ def run_server(app.state.trigger_shutdown = _trigger_shutdown- # 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.+ # Run server in a daemon thread with explicit new_event_loop() ++ # run_until_complete() (not asyncio.run) so nest_asyncio's patches don't+ # interfere when Colab/IPython already runs a loop on the main thread.def _run():loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)@@ -870,9 +849,8 @@ def run_server(thread = Thread(target = _run, daemon = True)thread.start()- # 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.+ # Wait until uvicorn finishes lifespan startup and binds sockets, or until it+ # exits/fails first. No deadline: a slow but live startup stays in progress.try:while not ready_event.is_set():if startup_failed.is_set() or not thread.is_alive():@@ -892,8 +870,7 @@ def run_server(atexit.register(_remove_pid_file)- # Output port for Tauri to parse in api-only mode. Emit only after- # uvicorn sockets are bound and FastAPI startup completed.+ # Output port for Tauri (api-only), only after sockets bind and startup done.if api_only:print(f"TAURI_PORT={port}", flush = True)@@ -935,9 +912,8 @@ if __name__ == "__main__":action = "store_true",help = "API server only, no frontend (for Tauri)",)- # Mirror unsloth_cli/commands/studio.py's _PARALLEL_*. Default 1- # applies to direct backend launches only; `unsloth studio run`- # always passes its own value (4) explicitly.+ # Mirror unsloth_cli/commands/studio.py's _PARALLEL_*. Default 1 is for direct+ # backend launches; `unsloth studio run` always passes its own value (4)._PARALLEL_MIN = 1_PARALLEL_MAX = 64_PARALLEL_DEFAULT_PLAIN = 1@@ -991,9 +967,8 @@ if __name__ == "__main__":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,- # preventing Python from delivering SIGINT (Ctrl+C). A short timeout- # in a loop lets the interpreter process pending signals.+ # Keep running until shutdown signal. Event.wait() without a timeout blocks at+ # the C level on Linux, preventing SIGINT delivery; 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.pyindex 08ceae1b595..7bfca61b73e 100644--- a/studio/backend/startup_banner.py+++ b/studio/backend/startup_banner.py@@ -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+ """Print the trailing stop hint + closing divider, separate from thebanner so callers can interleave content (e.g. a reachability check)."""use_color = stdout_supports_color()dim = "\033[38;5;245m"diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.pyindex bbd7186ed40..6482bae1406 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 added after the first release; backfill for pre-existing DBs.+ # Backfill use_oauth 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.pyindex e58133090d5..07165cbe70a 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -1,14 +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-"""-SQLite storage for external LLM provider configurations.--Same pattern as studio_db.py: module-level functions, raw sqlite3, WAL-mode, per-function connections.+"""SQLite storage for external LLM provider configurations.-NOTE: API keys are NOT stored here. They live only in the browser-(localStorage) and are sent encrypted per-request.+Same pattern as studio_db.py (module-level functions, raw sqlite3, WAL,+per-function connections). API keys are NOT stored here: they live only in+the browser (localStorage) and are sent encrypted per-request."""import loggingdiff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex d3900387d4a..a9b17fc7f54 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -1,13 +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-"""-SQLite storage for training run history and metrics.+"""SQLite storage for training run history and metrics.-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+Like auth/storage.py (module-level functions, raw sqlite3, per-function+connections) plus WAL mode and PRAGMA foreign_keys = ON for CASCADE deletes."""import json@@ -34,8 +31,7 @@ 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.+ # macOS realpath() resolves /etc -> /private/etc etc; include /private variants.return ["/System","/Library",@@ -174,9 +170,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:""")conn.execute("CREATE INDEX IF NOT EXISTS idx_metrics_run_id ON training_metrics(run_id)")- # 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.+ # Windows: COLLATE NOCASE so C:\Models and c:\models dedup. Elsewhere keep+ # case-sensitive BINARY so /Models and /models stay distinct.collation = "COLLATE NOCASE" if platform.system() == "Windows" else ""conn.execute(f"""@@ -287,14 +282,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)""")- # 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).+ # Import ledger inside studio.db (vs. a localStorage boolean) so a db wipe+ # re-triggers the legacy Dexie import instead of silently hiding threads.+ # Keyed by legacy thread id; Dexie is read-only so per-thread suffices.conn.execute("""CREATE TABLE IF NOT EXISTS chat_legacy_imports (@@ -700,9 +690,8 @@ 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, 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).+ # Windows: normcase for the denylist check but store original casing+ # so consumers see the native drive-letter casing (e.g. C:\Models).is_win = platform.system() == "Windows"check = os.path.normcase(normalized) if is_win else normalizedfor prefix in _denied_path_prefixes():@@ -712,8 +701,7 @@ def add_scan_folder(path: str) -> dict:conn = get_connection()try:now = datetime.now(timezone.utc).isoformat()- # On Windows, case-insensitive lookup so C:\Models and c:\models dedup- # while preserving the originally-stored casing.+ # Windows: case-insensitive lookup so C:\Models and c:\models dedup.if is_win:existing = conn.execute("SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE",@@ -733,9 +721,8 @@ def add_scan_folder(path: str) -> dict:)conn.commit()except sqlite3.IntegrityError:- pass # duplicate -- fall through to SELECT- # Same collation as the pre-check so we find the row even when a- # concurrent writer stored it with different casing (Windows).+ pass # duplicate; fall through to SELECT+ # Same collation as the pre-check to catch concurrent writes (Windows).fallback_sql = ("SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE"if is_win@@ -1454,11 +1441,7 @@ 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 one small PK-only table. The frontend puts the result in a- Set before walking Dexie, so the diff is O(|Dexie|).- """+ """Return the legacy_thread_id of every thread already imported."""conn = get_connection()try:rows = conn.execute("SELECT legacy_thread_id FROM chat_legacy_imports").fetchall()@@ -1470,14 +1453,9 @@ def list_chat_legacy_imports() -> list[str]: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: 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 newly-inserted rows, so- callers distinguish first-time imports from idempotent re-runs without an- extra SELECT.+ Returns (accepted, inserted): count of deduped non-empty input ids, and+ count of rows actually new. RETURNING lets callers tell 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.pyindex d903e045146..a9fc185536e 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -1,30 +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-"""-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 is launched.-2. Provide a hybrid ``studio_server`` session fixture for end-to-end tests- (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). 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. 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`` /- ``UNSLOTH_E2E_VARIANT`` env vars, then the defaults in- ``test_studio_api.py``.+"""Shared pytest configuration for the backend test suite.++Puts the backend root on sys.path (mirrors app launch) and provides a hybrid+``studio_server`` session fixture for end-to-end tests with two modes:+external server (``UNSLOTH_E2E_BASE_URL``/``UNSLOTH_E2E_API_KEY``) for fast+iteration, or a fixture-managed server started/torn down per session for CI.+Model/variant for the managed mode resolve from ``--unsloth-model`` /+``--unsloth-gguf-variant``, then env vars, then ``test_studio_api.py`` defaults."""import os@@ -33,13 +17,13 @@ from pathlib import Pathimport pytest-# Add backend root to sys.path (mirrors how the app itself is launched)+# Add backend root to sys.path (mirrors app launch)_backend_root = Path(__file__).resolve().parent.parentif str(_backend_root) not in sys.path:sys.path.insert(0, str(_backend_root))-# ── Pytest CLI options ───────────────────────────────────────────────+# Pytest CLI optionsdef pytest_addoption(parser):@@ -71,25 +55,16 @@ def pytest_addoption(parser):)-# ── E2E server fixtures ──────────────────────────────────────────────+# E2E server fixtures@pytest.fixture(scope = "session")def studio_server(request):"""Yield ``(base_url, api_key)`` for e2e tests.- Resolution order:-- 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. 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.+ Uses ``UNSLOTH_E2E_BASE_URL`` (requires ``UNSLOTH_E2E_API_KEY``) if set,+ else starts/tears down a fresh server via ``_start_server``. Session-scoped+ and lazy so the GGUF load happens at most once and only when requested."""external_url = os.environ.get("UNSLOTH_E2E_BASE_URL")if external_url:@@ -103,9 +78,7 @@ def studio_server(request):yield external_url, api_keyreturn- # 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, so this is a cache hit.import test_studio_api as _e2emodel = (diff --git a/studio/backend/tests/test_anthropic_cache_ttl.py b/studio/backend/tests/test_anthropic_cache_ttl.pyindex 895c5985460..d39d0e93842 100644--- a/studio/backend/tests/test_anthropic_cache_ttl.py+++ b/studio/backend/tests/test_anthropic_cache_ttl.py@@ -3,14 +3,9 @@"""Unit tests for prompt_cache_ttl threading on the Anthropic path.-Anthropic accepts an optional ``ttl`` on each ``cache_control`` marker:-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+Anthropic's ``cache_control`` marker takes an optional ``ttl``: default 5m+pool, ``ttl:"1h"`` the 1h pool. These tests pin the outbound body shape:+"1h" puts ``ttl:"1h"`` on both markers; default omits the field; garbagevalues are silently dropped."""@@ -127,11 +122,8 @@ 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 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+ # The extended-cache-ttl-2025-04-11 beta header is now GA (verified live+ # 2026-05-22); 1h TTL works with no beta header. Pin so a regression that# re-adds the header surfaces here.captured = _capture(monkeypatch, ttl = "1h")beta = captured["headers"].get("anthropic-beta", "")@@ -153,8 +145,7 @@ def test_unknown_ttl_silently_dropped(monkeypatch, bogus):ccs = _cache_controls(captured["body"])assert len(ccs) == 2, ccsfor cc in ccs:- # Bogus TTLs must NOT round-trip; marker stays at the default- # (no `ttl` key = 5m pool upstream).+ # Bogus TTLs must not round-trip; marker stays at default (no ttl = 5m).assert cc == {"type": "ephemeral"}, ccdiff --git a/studio/backend/tests/test_anthropic_citations.py b/studio/backend/tests/test_anthropic_citations.pyindex c6104f2425a..25d5f5e8866 100644--- a/studio/backend/tests/test_anthropic_citations.py+++ b/studio/backend/tests/test_anthropic_citations.py@@ -126,8 +126,7 @@ def _joined(lines: list[str]) -> str:def test_no_citations_stream_unchanged(monkeypatch):- """Plain text streams pass through with no inline markers and no- document_citations tool_event."""+ """Plain text passes through with no inline markers or document_citations."""lines = _capture(monkeypatch,[diff --git a/studio/backend/tests/test_anthropic_code_execution.py b/studio/backend/tests/test_anthropic_code_execution.pyindex cc0fb21deb1..22bbb191256 100644--- a/studio/backend/tests/test_anthropic_code_execution.py+++ b/studio/backend/tests/test_anthropic_code_execution.py@@ -1,27 +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-"""-Unit tests for Anthropic's server-side `code_execution_20250825` tool-translation in `_stream_anthropic`.--Covers:-- 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 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``.-"""+"""Tests for Anthropic server-side `code_execution` tool translation in+`_stream_anthropic`: request body/beta header, combined web_search,+bash/text_editor SSE tool events, and the container_expired error path."""import asyncioimport json@@ -114,13 +96,11 @@ 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`) with REPL- # state persistence + programmatic tool calling.+ # Opus 4.7 gets the newer date-pinned variant with REPL persistence.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 flag; both `_20250825` and `_20260120`- # are unlocked by the same header per upstream docs.+ # Same beta header unlocks both _20250825 and _20260120.beta_header = captured["headers"].get("anthropic-beta", "")assert "code-execution-2025-08-25" in beta_header@@ -191,11 +171,9 @@ def test_no_code_execution_tool_when_pill_off(monkeypatch):_drive(run())tools = captured["body"].get("tools") or []- # Pill off -- neither the legacy nor new code_execution variant may- # appear on the wire.+ # Pill off: no code_execution variant 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 is off --- # that flag is opt-in only.+ # Beta header must omit code-execution when the tool is off (opt-in only).assert "code-execution-2025-08-25" not in captured["headers"].get("anthropic-beta", "")@@ -268,8 +246,7 @@ 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 a provider-side synthetic tool card for- # the frontend's history serializer.+ # `_server_tool: True` marks a provider-side synthetic tool card.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.pyindex 5047a93979d..1528eebe8b6 100644--- a/studio/backend/tests/test_anthropic_compaction.py+++ b/studio/backend/tests/test_anthropic_compaction.py@@ -3,16 +3,13 @@"""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. 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.+Compaction is a beta (header ``compact-2026-01-12``) gated to Opus 4.6/4.7,+Sonnet 4.6, and Mythos preview. When enabled, Studio attaches+``context_management.edits[{type:"compact_20260112", trigger:{type:"input_tokens",+value:N}}]``; the 50k-token minimum is clamped up so the request doesn't 400.++Pins body shape per model, beta header merge with code-execution, threshold+clamping, and silent no-op on unsupported models."""import asyncio@@ -168,9 +165,8 @@ 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 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.+ # ge=50_000 on the field would 422 before the in-helper clamp fires; the+ # schema must accept any positive int and let _stream_anthropic clamp up.from models.inference import ChatCompletionRequestreq = ChatCompletionRequest.model_validate(@@ -207,13 +203,10 @@ 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- # 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?".+ # On mid-stream compaction the message_delta usage carries+ # `iterations: [{type:"compaction", ...}, ...]`. Top-level tokens only cover+ # the `message` iteration, so the helper folds compaction totals into+ # last_usage and surfaces them in the closing summary log.def http_handler(request: httpx.Request) -> httpx.Response:body = (@@ -256,8 +249,7 @@ def test_message_delta_iterations_array_aggregates_compaction_tokens(monkeypatch_drive(run())- # structlog renders the closing summary via the stdlib bridge onto- # stdout. Capture and check the rendered line.+ # structlog renders the closing summary onto stdout; check the rendered line.out = capsys.readouterr().outsummary = next((line for line in out.splitlines() if "Anthropic stream complete" in line),@@ -268,9 +260,8 @@ def test_message_delta_iterations_array_aggregates_compaction_tokens(monkeypatchdef 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 then- # (would otherwise double-bill).+ # Re-applying a prior compaction block emits no fresh iterations array;+ # the helper must not invent compaction keys (would double-bill).def http_handler(request: httpx.Request) -> httpx.Response:body = (b"event: message_delta\n"@@ -329,17 +320,14 @@ def _async_collect(agen):def test_compaction_block_emitted_as_tool_event(monkeypatch):- # 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.+ # When 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; else the next turn loses state and re-compacts.def http_handler(request: httpx.Request) -> httpx.Response:- # 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.+ # Compaction blocks arrive as a content_block_start with type:"compaction",+ # with the summary on the start event AND/OR streamed via text_delta on the+ # same index. Test the streamed-delta path (harder case).body = (b"event: message_start\n"b'data: {"type":"message_start","message":{"usage":{}}}\n\n'@@ -406,9 +394,7 @@ def test_compaction_block_emitted_as_tool_event(monkeypatch):parsed = json.loads(raw)except json.JSONDecodeError:continue- # tool_event payloads ride inside chat.completion.chunk.choices[0].delta.content- # as a JSON-encoded string. Simpler: look for the marker substring- # anywhere in the chunk.+ # tool_event payloads ride inside the chunk as JSON; just match the marker.if "compaction_block" in raw:events.append(raw)assert events, f"no compaction_block tool event found in {lines}"@@ -441,10 +427,8 @@ 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.+ # The next turn's outbound body must forward a persisted+ # {type:"compaction", content:"..."} block verbatim so the API recognises the state.captured: dict = {}def http_handler(request: httpx.Request) -> httpx.Response:@@ -502,9 +486,7 @@ def test_compaction_block_round_trips_through_outbound_messages(monkeypatch):def test_compaction_content_part_accepted_by_chat_message_schema():- # Without this Pydantic Tag the discriminated Union would 422 the- # request at parse time and the round-trip would never reach the- # translator.+ # Without the Pydantic Tag the discriminated Union would 422 at parse time.from models.inference import ChatMessagemsg = ChatMessage.model_validate(@@ -523,10 +505,8 @@ 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 Anthropic-only; the builder must gate it on+ # provider_type=="anthropic" since others 400 on the unknown content type.from models.inference import ChatMessagefrom routes.inference import _build_external_messages@@ -549,11 +529,9 @@ 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, 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.+ # A provider switch or reused history can hand compaction blocks to a+ # non-Anthropic provider whose validator rejects the unknown type, so the+ # builder must strip the part for every non-anthropic provider.from models.inference import ChatMessagefrom routes.inference import _build_external_messages@@ -579,9 +557,7 @@ def test_build_external_messages_strips_compaction_for_non_anthropic_providers()def test_build_external_messages_strips_compaction_when_provider_type_unknown():- # Defensive: if provider_type is None (legacy path) the part must- # also be stripped -- forwarding to an unknown destination is- # never safe.+ # Defensive: provider_type=None (legacy path) must also strip the part.from models.inference import ChatMessagefrom routes.inference import _build_external_messages@@ -603,9 +579,8 @@ def test_build_external_messages_strips_compaction_when_provider_type_unknown():def test_build_external_messages_non_vision_anthropic_keeps_compaction():- # Defensive: even though compaction-capable Anthropic models all- # currently report supports_vision=True, gate the non-vision branch- # by provider_type too so future config changes don't drop it.+ # Defensive: gate the non-vision branch by provider_type too, so future+ # config changes don't drop compaction for Anthropic.from models.inference import ChatMessagefrom routes.inference import _build_external_messagesdiff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex c55ccbaaefd..77b0b212127 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -1,10 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""-Tests for Anthropic Messages API schemas and translation layer.-No running server or GPU required.-"""+"""Tests for Anthropic Messages API schemas and translation layer (no server/GPU)."""import sysimport osdiff --git a/studio/backend/tests/test_anthropic_thinking_translation.py b/studio/backend/tests/test_anthropic_thinking_translation.pyindex 144de166f25..02c48937358 100644--- a/studio/backend/tests/test_anthropic_thinking_translation.py+++ b/studio/backend/tests/test_anthropic_thinking_translation.py@@ -1,20 +1,16 @@# 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 Anthropic extended-thinking translation in external_provider.+"""Unit tests for 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).+- Adaptive-mode body nests effort under ``output_config: {effort}`` (a+ top-level ``effort`` field 400s).+- Streaming ``thinking_delta`` is translated into inline ``<think>...</think>``+ chunks for the frontend reasoning panel.+- The ``<think>`` tag closes on the first ``text_delta``, ``content_block_stop``,+ ``message_delta``, or ``message_stop``.+- Thinking forces ``temperature=1`` with no ``top_p`` / ``top_k`` (contract)."""import asynciodiff --git a/studio/backend/tests/test_anthropic_tool_versions.py b/studio/backend/tests/test_anthropic_tool_versions.pyindex f9ff448f66d..fe2da26d73a 100644--- a/studio/backend/tests/test_anthropic_tool_versions.py+++ b/studio/backend/tests/test_anthropic_tool_versions.py@@ -1,34 +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-"""-Unit tests for the per-model Anthropic server-side tool-version dispatch-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 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``- pick ``_20260209`` for Opus 4.6+, Opus 4.7, Sonnet 4.6 and fall back- to ``_20250305`` / ``_20250910`` for everything else (4.5 family,- Haiku 4.5, 4.1, 4.0).-- ``_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: 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).-"""+"""Tests for the per-model Anthropic tool-version dispatch helpers in+``core.inference.external_provider``.++Anthropic ships date-pinned tool versions per model family; sending the+wrong-dated variant to a model 400s upstream. Pins the dispatch matrix for+web_search/web_fetch/code_execution helpers, the ``_stream_anthropic`` body+integration, and the unchanged code-execution beta header."""import asyncioimport json@@ -164,9 +143,7 @@ def test_outbound_body_uses_new_versions_on_opus_4_7(monkeypatch):assert "code_execution_20260120" in tool_typesassert "web_search_20250305" not in tool_typesassert "code_execution_20250825" not in tool_types- # 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.+ # One beta header gates both _20250825 and _20260120.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.pyindex 542048ebd4c..bf24175256b 100644--- a/studio/backend/tests/test_anthropic_web_fetch.py+++ b/studio/backend/tests/test_anthropic_web_fetch.py@@ -369,12 +369,10 @@ def _finish_reasons(lines: list[str]) -> list:def test_pause_turn_does_not_emit_finish_reason_chunk(monkeypatch):- # 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.+ # Anthropic emits `pause_turn` when a long server-tool turn pauses and+ # resumes next request. Mapping it to finish_reason="stop" truncates the+ # OpenAI client's message, so the adapter must skip the chunk and end+ # cleanly with [DONE] and no terminal finish_reason.sse_events = [{"type": "message_start", "message": {"usage": {}}},{@@ -488,11 +486,9 @@ def test_refusal_maps_to_content_filter(monkeypatch):def test_web_fetch_titleless_document_falls_back_to_url(monkeypatch):- # 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.+ # Anthropic may omit `document.title`. Without a fallback the formatter+ # emits no `Title:` line, and the frontend's parseSourcesFromResult drops+ # those entries (source pill disappears). Verify it falls back to the URL.sse_events = [{"type": "message_start", "message": {"usage": {}}},{diff --git a/studio/backend/tests/test_cache_case_resolution.py b/studio/backend/tests/test_cache_case_resolution.pyindex 50340bda633..22e961891e4 100644--- a/studio/backend/tests/test_cache_case_resolution.py+++ b/studio/backend/tests/test_cache_case_resolution.py@@ -5,8 +5,7 @@ from pathlib import Pathimport sysimport types-# Keep this test runnable in lightweight environments where optional logging-# deps are not installed.+# Stub structlog so this test runs where the optional dep is absent.if "structlog" not in sys.modules:class _DummyLogger:diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 0274d5b4da1..20aa37a2b44 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -7,8 +7,7 @@ import typesfrom pathlib import Pathfrom types import SimpleNamespace-# Keep this test runnable in lightweight environments without optional-# logging deps.+# Keep this test runnable without optional logging deps.if "structlog" not in sys.modules:class _DummyLogger:@@ -211,8 +210,7 @@ def test_list_cached_models_skips_non_suffix_repo_when_gguf_files_exist(monkeypadef 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 shows it as a GGUF download."""+ """Mixed repo still surfaces in cached-gguf as a GGUF download."""mixed = _repo("Org/MixedRepo",[@@ -240,9 +238,8 @@ def test_list_cached_gguf_includes_mixed_repo_with_gguf_and_safetensors(monkeypadef 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 unknown bytes as zero instead of raising TypeError from- ``sum()`` and wiping the whole response."""+ """``size_on_disk = None`` (partial download) is treated as zero, not a+ TypeError from ``sum()`` that wipes the response."""partial = _repo("Org/PartialDownload",[_file("Q4_K_M.gguf", None), _file("Q6_K.gguf", 5_000)],@@ -267,8 +264,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 the other repos in the scan."""+ """One repo raising during classification must not poison the response."""class _ExplodingRepo:repo_id = "Org/Broken"@@ -303,9 +299,8 @@ def test_list_cached_gguf_skips_malformed_repo_without_wiping_response(monkeypatdef 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`` is an mmproj vision adapter is not a GGUF+ repo: mmproj is filtered out, leaving zero variants."""mmproj_only = _repo("Org/MmprojOnly",[@@ -327,9 +322,8 @@ def test_list_cached_gguf_skips_repo_with_only_mmproj_gguf(monkeypatch, tmp_pathdef 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."""+ """A safetensors repo with an auxiliary mmproj adapter still surfaces in+ cached-models as a normal model."""mmproj_aux = _repo("Org/MmprojAux",[@@ -351,10 +345,8 @@ def test_list_cached_models_includes_repo_with_only_mmproj_gguf(monkeypatch, tmpdef 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. Reported size is the main weight size; mmproj is excluded- from GGUF-size accounting since it is filtered out at classification- time."""+ """A vision GGUF repo (main weight + mmproj) is a GGUF repo; reported size+ is the main weight only, since mmproj is filtered at classification."""vision_repo = _repo("Org/VisionGguf",[diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 92cac1a50d4..bc74ec172ad 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -30,8 +30,7 @@ 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;+ macOS tmp_path resolves under /private/tmp, which the delete guard refuses;only the denied case falls back to a home subdir."""candidate = tmp_path / "Projects"diff --git a/studio/backend/tests/test_cleanup_cancelled_checkpoints.py b/studio/backend/tests/test_cleanup_cancelled_checkpoints.pyindex 138cda30d45..3799a4f91b0 100644--- a/studio/backend/tests/test_cleanup_cancelled_checkpoints.py+++ b/studio/backend/tests/test_cleanup_cancelled_checkpoints.py@@ -18,9 +18,8 @@ if str(_BACKEND_ROOT) not in sys.path:def outputs_setup(tmp_path, monkeypatch):"""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 patch the symbol on the- importer module, not on storage_roots.+ training binds ``outputs_root`` at import time, so patch the symbol on+ the importer module, not on storage_roots."""from core.training import training as training_mod@@ -36,8 +35,8 @@ def _mk_dir(parent: Path, name: str) -> Path:def test_completed_checkpoints_are_preserved(outputs_setup):- """The big regression: before this fix, every completed checkpoint-N/- was rmtree'd on Cancel, destroying resume points."""+ """Regression: completed checkpoint-N/ used to be rmtree'd on Cancel,+ destroying resume points."""from core.training.training import _cleanup_cancelled_checkpointsout = outputs_setup / "run-1"diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 9d80c718cbc..e7022ee4350 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -293,9 +293,8 @@ 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 whether the incoming session was desktop or web.+ # _inject_local_providers mints an internal sk-unsloth-* API key (not a+ # forwarded JWT) that validates as admin whether the session was desktop or web.from auth.authentication import create_access_token, get_current_subjectseed_user(must_change_password = True)@@ -318,8 +317,7 @@ def test_local_recipe_token_authenticates_as_admin_for_desktop_user(loaded_localdef 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 tokens; get_current_subject works the same.+ # Mirror of the desktop variant: API-key issuance is identical for web/desktop tokens.from auth.authentication import create_access_token, get_current_subjectseed_user(must_change_password = False)diff --git a/studio/backend/tests/test_export_log_cursor.py b/studio/backend/tests/test_export_log_cursor.pyindex 25f276b0f50..5b614ab9c82 100644--- a/studio/backend/tests/test_export_log_cursor.py+++ b/studio/backend/tests/test_export_log_cursor.py@@ -4,21 +4,15 @@"""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. 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.+Race: the frontend opens the SSE connection AFTER the POST that starts the+export, so lines emitted in the gap (seqs 1..k) are unreachable when the SSE+default cursor `get_current_log_seq()` returns k.++Fix: `clear_logs()` snapshots the pre-run seq into `_run_start_seq` (via+`get_run_start_seq()`), and the SSE cursor defaults to that snapshot, so the+client sees the full run regardless of connect time.++These tests exercise the orchestrator contract only (no subprocess/FastAPI)."""from __future__ import annotations@@ -30,14 +24,12 @@ from pathlib import Pathimport pytest-# Backend root on sys.path so `from core.export.orchestrator import ...`-# and friends resolve without the studio app bootstrap.+# Backend root on sys.path so core.export.orchestrator resolves without bootstrap._BACKEND_DIR = Path(__file__).resolve().parent.parentif str(_BACKEND_DIR) not in sys.path:sys.path.insert(0, str(_BACKEND_DIR))-# 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.+# Stub orchestrator.py's heavy top-level imports so it loads without the venv._loggers_stub = types.ModuleType("loggers")_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)sys.modules.setdefault("loggers", _loggers_stub)@@ -45,8 +37,7 @@ sys.modules.setdefault("loggers", _loggers_stub)# 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; stub it so orchestrator.py's top-level import resolves.+# Stub utils.paths 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")@@ -77,14 +68,14 @@ def _append(def test_run_start_seq_is_zero_before_any_logs(orchestrator) -> None:- """New orchestrator must report run_start_seq == 0 so a first SSE- connection picks up every line from seq 1 onward."""+ """run_start_seq == 0 on a new orchestrator, so the first SSE picks up+ every line from seq 1 onward."""assert orchestrator.get_run_start_seq() == 0def 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() captures _log_seq BEFORE clearing, so the next run can+ anchor its SSE cursor at the snapshot."""_append(orchestrator, "old run line 1")_append(orchestrator, "old run line 2")_append(orchestrator, "old run line 3")@@ -102,13 +93,9 @@ 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 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,- returning the last-seen seq and missing lines N+1..M.- """+ """POST-then-SSE race: worker emits lines right after clear_logs(), SSE+ connects later. get_run_start_seq() as the default cursor returns every+ line since clear_logs() (pre-fix it missed them)."""# Previous run leaves some buffered lines._append(orchestrator, "previous run line A")_append(orchestrator, "previous run line B")@@ -136,10 +123,8 @@ 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(), 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.- """+ """After clear_logs(), previous-run lines must not leak into the new+ run's SSE stream (the fix must preserve this)."""_append(orchestrator, "previous run line 1")_append(orchestrator, "previous run line 2")_append(orchestrator, "previous run line 3")@@ -155,9 +140,8 @@ 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 one- 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 each re-anchor run_start at the current+ seq, giving successive runs 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.pyindex f462e1c8e97..ebfd6a8f50b 100644--- a/studio/backend/tests/test_external_provider_usage_chunk.py+++ b/studio/backend/tests/test_external_provider_usage_chunk.py@@ -1,27 +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-"""-Unit tests for the prompt-cache accounting chunk emitted by the-external-provider streaming proxy.--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, so clients see cache savings without scraping-the structlog stream.--Covers:-- Helper alone: shape for Anthropic / OpenAI usage payloads, missing- fields treated as 0, all-zero usage suppressed.-- Anthropic stream: ``message_start.usage`` + ``message_delta.usage``- with ``cache_creation_input_tokens`` and ``cache_read_input_tokens``- produce the expected usage chunk before ``[DONE]``.-- 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 chunk so- length-truncated turns still report cached tokens.+"""Unit tests for the prompt-cache accounting chunk from the external-provider proxy.++The streaming Anthropic + OpenAI Responses paths emit one extra include_usage+SSE chunk (``choices: []`` with a ``usage`` block) before ``[DONE]`` so clients+see cache savings. Covers the helper directly plus the Anthropic stream and the+OpenAI Responses completed/incomplete streams."""import asynciodiff --git a/studio/backend/tests/test_frontend_resolution.py b/studio/backend/tests/test_frontend_resolution.pyindex 7224ee7a04e..c3e0524a30e 100644--- a/studio/backend/tests/test_frontend_resolution.py+++ b/studio/backend/tests/test_frontend_resolution.py@@ -18,8 +18,8 @@ _REPO_STUDIO_DIR = _RUN_PY.parent.parent # studio/def _load_helpers_only():- """Import just the resolver helpers from run.py, skipping the- server-side imports (uvicorn, structlog, etc.)."""+ """Import just the resolver helpers from run.py, skipping server-side+ imports (uvicorn, structlog, etc.)."""source = _RUN_PY.read_text(encoding = "utf-8")tree = ast.parse(source)keep = []diff --git a/studio/backend/tests/test_gguf_reload_inheritance.py b/studio/backend/tests/test_gguf_reload_inheritance.pyindex 500bfc2d4c7..5d5f3c5a83e 100644--- a/studio/backend/tests/test_gguf_reload_inheritance.py+++ b/studio/backend/tests/test_gguf_reload_inheritance.py@@ -3,10 +3,9 @@"""Backend contract for the GGUF reload duplicate-load guard.-``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.+``LlamaCppBackend._already_in_target_state`` short-circuits a duplicate /load so+it cannot kill the just-spawned llama-server. Pins local-file identity, the+HF-mode hf_variant fallback, and ``extra_args`` None-vs-[] inherit semantics."""from __future__ import annotationsdiff --git a/studio/backend/tests/test_gguf_routing.py b/studio/backend/tests/test_gguf_routing.pyindex c640218943d..8a8bff69aa4 100644--- a/studio/backend/tests/test_gguf_routing.py+++ b/studio/backend/tests/test_gguf_routing.py@@ -43,10 +43,9 @@ 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.- 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.+ Regression: on Windows is_file()/exists() call stat(), which raises OSError+ in the brief lock window after llama-server is killed. detect_gguf_model must+ still route to llama-server by file extension alone."""gguf = tmp_path / "gpt-oss-20b-MXFP4.gguf"gguf.write_bytes(b"")diff --git a/studio/backend/tests/test_host_defaults.py b/studio/backend/tests/test_host_defaults.pyindex c66385721e3..5c7129bc650 100644--- a/studio/backend/tests/test_host_defaults.py+++ b/studio/backend/tests/test_host_defaults.py@@ -61,10 +61,8 @@ def _parse_argparse_add_argument_default(source: str, option_name: str):def test_run_server_default_host_is_loopback():"""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 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.+ 0.0.0.0 exposes the service on all interfaces; loopback is the+ least-permissive default. Users needing network access pass -H 0.0.0.0."""source = _RUN_PY.read_text()defaults = _parse_function_param_defaults(source, "run_server")diff --git a/studio/backend/tests/test_index_bootstrap_origin.py b/studio/backend/tests/test_index_bootstrap_origin.pyindex 85b785ee109..b9d7f588676 100644--- a/studio/backend/tests/test_index_bootstrap_origin.py+++ b/studio/backend/tests/test_index_bootstrap_origin.py@@ -2,8 +2,9 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0"""Regression coverage for the bootstrap-pw cross-origin leak (PR 5739).-``_is_same_origin_request`` gates ``_inject_bootstrap`` so the seeded-admin password only ships to same-origin callers.++``_is_same_origin_request`` gates ``_inject_bootstrap`` so the seeded admin+password only ships to same-origin callers."""import os@@ -61,9 +62,7 @@ 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 netloc may keep- ``:443``. Canonicalise both sides so this stays same-origin.- """+ """RFC 6454 strips default ports on Origin; canonicalise both sides so this stays same-origin."""from main import _is_same_origin_requestreq = _build_request("example.com:443", origin = "https://example.com", scheme = "https")@@ -109,9 +108,7 @@ def test_is_same_origin_request_null_origin_is_cross_origin():def test_is_same_origin_request_unparseable_origin_is_cross_origin():- """Hostless garbage falls to cross-origin; a malformed header- must not leak the bootstrap.- """+ """Hostless garbage falls to cross-origin so a malformed header can't leak the bootstrap."""from main import _is_same_origin_requestreq = _build_request("example.com", origin = "not-a-url")@@ -119,8 +116,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."""+ """``user:pass@host:port`` netlocs (RFC 3986) must compare equal to the credentials-less Origin."""from main import _is_same_origin_requestreq = _build_request("user:[email protected]:80", origin = "http://example.com")diff --git a/studio/backend/tests/test_inference_model_validation.py b/studio/backend/tests/test_inference_model_validation.pyindex dddf5c8052b..2427ad35fa8 100644--- a/studio/backend/tests/test_inference_model_validation.py+++ b/studio/backend/tests/test_inference_model_validation.py@@ -206,7 +206,7 @@ def test_walkback_skips_explicitly_consumed_tool_call_id():def test_walkback_handles_malformed_function_string():"""A tool_call with ``function`` as a string (provider quirk) must not- raise; resolution falls back to fallback id selection."""+ raise; resolution falls back to id selection."""req = _req([{diff --git a/studio/backend/tests/test_kv_cache_estimation.py b/studio/backend/tests/test_kv_cache_estimation.pyindex cd679b0bf11..cd834b345bf 100644--- a/studio/backend/tests/test_kv_cache_estimation.py+++ b/studio/backend/tests/test_kv_cache_estimation.py@@ -19,10 +19,8 @@ from pathlib import Pathimport pytest-# ---------------------------------------------------------------------------# 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)if _BACKEND_DIR not in sys.path:@@ -37,10 +35,9 @@ 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 shadows ``HTTPError`` / ``Response`` etc. that-# ``huggingface_hub.errors`` imports at load time, making the transformers-# introspection tier silently return None in the test process.+# httpx -- only stub when the real library is missing. Unconditional stubbing+# shadows HTTPError/Response that huggingface_hub.errors imports at load time,+# silently breaking the transformers introspection tier.try:import httpx as _httpx_real # noqa: F401except ImportError:@@ -76,9 +73,7 @@ except ImportError:from core.inference.llama_cpp import LlamaCppBackend-# ---------------------------------------------------------------------------# Helpers-# ---------------------------------------------------------------------------def _make_gguf_bytes(arch: str, kv_pairs: dict) -> bytes:@@ -154,9 +149,7 @@ def _backend_from_gguf(os.unlink(path)-# ---------------------------------------------------------------------------# A. GGUF Parser Tests-# ---------------------------------------------------------------------------class TestGGUFParserNewFields:@@ -704,9 +697,7 @@ class TestGGUFParserReset:assert b._n_layers == 64-# ---------------------------------------------------------------------------# B. _can_estimate_kv Gate Tests-# ---------------------------------------------------------------------------class TestCanEstimateKV:@@ -764,9 +755,7 @@ class TestCanEstimateKV:assert not b._can_estimate_kv()-# ---------------------------------------------------------------------------# C. Path 1: MLA Estimation-# ---------------------------------------------------------------------------class TestMLAEstimation:@@ -835,9 +824,7 @@ class TestMLAEstimation:assert result_q4 == int(61 * 1000 * 1 * 576 * 0.5625)-# ---------------------------------------------------------------------------# D. Path 2: Hybrid Mamba Estimation-# ---------------------------------------------------------------------------class TestHybridMambaEstimation:@@ -895,9 +882,7 @@ class TestHybridMambaEstimation:assert result == expected-# ---------------------------------------------------------------------------# E. Path 3: Sliding Window Estimation-# ---------------------------------------------------------------------------class TestSlidingWindowEstimation:@@ -993,9 +978,7 @@ class TestSlidingWindowEstimation:assert b._estimate_kv_cache_bytes(1000, "f16") == expected-# ---------------------------------------------------------------------------# F. Path 4: Standard GQA Estimation-# ---------------------------------------------------------------------------class TestStandardGQAEstimation:@@ -1039,9 +1022,7 @@ class TestStandardGQAEstimation:assert gqa_result > legacy_result # key_length (128) > head_dim (64)-# ---------------------------------------------------------------------------# G. Path 5: Legacy Fallback Estimation-# ---------------------------------------------------------------------------class TestLegacyEstimation:@@ -1085,9 +1066,7 @@ class TestLegacyEstimation:assert b._estimate_kv_cache_bytes(n_ctx, "f16") == old_formula-# ---------------------------------------------------------------------------# H. Path Priority (selection order)-# ---------------------------------------------------------------------------class TestPathPriority:@@ -1182,9 +1161,7 @@ class TestPathPriority:assert len(set(values)) == 5, f"Expected 5 distinct values, got {values}"-# ---------------------------------------------------------------------------# I. KV Cache Quantization-# ---------------------------------------------------------------------------class TestQuantization:@@ -1219,9 +1196,7 @@ class TestQuantization:assert result == expected-# ---------------------------------------------------------------------------# J. Edge Cases-# ---------------------------------------------------------------------------class TestEdgeCases:@@ -1282,10 +1257,8 @@ class TestEdgeCases:assert result == expected-# ---------------------------------------------------------------------------# J2. Server-flag knobs (--swa-full, --kv-unified/--parallel,# --ctx-checkpoints, --kv-offload)-# ---------------------------------------------------------------------------class TestServerFlags:@@ -1563,9 +1536,7 @@ class TestServerFlags:assert fitted_full < ctx-# ---------------------------------------------------------------------------# J2.5. --parallel N memory accounting (per-layer-type scaling rule)-# ---------------------------------------------------------------------------class TestParallelSWAScaling:@@ -1772,9 +1743,7 @@ class TestParallelSWAScaling:), f"slots={slots}: got {got_mib} MiB, expected {expected_mib} MiB"-# ---------------------------------------------------------------------------# J3. shared_kv_layers (Gemma 3n / Gemma 4)-# ---------------------------------------------------------------------------class TestSharedKVLayers:@@ -1952,9 +1921,7 @@ class TestSharedKVLayers:assert b._shared_kv_layers is None-# ---------------------------------------------------------------------------# K. Lifecycle Tests-# ---------------------------------------------------------------------------class TestLifecycle:diff --git a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.pyindex 8fca27dfe18..3443f53a126 100644--- a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py+++ b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py@@ -89,9 +89,7 @@ def _lookup_family(gfx: str) -> str | None:return None-# ---------------------------------------------------------------------------# GPU family mapping-# ---------------------------------------------------------------------------@pytest.mark.parametrize(@@ -113,9 +111,7 @@ def test_unknown_gpu_not_in_families():assert _lookup_family("gfx999") is None-# ---------------------------------------------------------------------------# Asset resolution - hits real lemonade GitHub API-# ---------------------------------------------------------------------------@pytest.mark.parametrize(@@ -145,11 +141,9 @@ def test_unknown_gpu_falls_through_to_upstream():assert result is None-# ---------------------------------------------------------------------------# Simple-policy dispatcher must plan a lemonade ROCm attempt for AMD-only hosts.-# This is the path setup.sh actually invokes (via --simple-policy), so the-# lemonade integration is useless if it isn't wired in here.-# ---------------------------------------------------------------------------+# This is the path setup.sh invokes (via --simple-policy), so the lemonade+# integration is useless if it isn't wired in here.direct_linux_release_plan = getattr(_mod, "direct_linux_release_plan", None)direct_upstream_release_plan = getattr(_mod, "direct_upstream_release_plan", None)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.pyindex 215936bd207..666a503dbbd 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@@ -1,18 +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-"""Tests for the cache-aware disk-space preflight in-``LlamaCppBackend.load_model``.--The preflight used to compare the repo's total GGUF download size against-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.+"""Tests for the cache-aware disk-space preflight in ``LlamaCppBackend.load_model``.++The preflight used to compare the repo's total GGUF size against free disk+without counting bytes already in the HF cache, so re-loading a cached large+model failed cold even though nothing needed downloading. These tests exercise+the preflight arithmetic in isolation (no network/GPU/subprocess)."""from __future__ import annotations@@ -25,10 +19,8 @@ from unittest.mock import patchimport pytest-# ----------------------------------------------------------------------------# Stub heavy / unavailable external deps 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)if _BACKEND_DIR not in sys.path:@@ -96,12 +88,11 @@ def _preflight(hf_repo = "unsloth/Example-GGUF",hf_token = None,):- """Run the preflight arithmetic as in llama_cpp.py; return the decision- outcome as a dict.+ """Run the llama_cpp.py preflight arithmetic; return the decision as a dict.``repo_files``: list of (filename, remote_bytes).- ``cached_files``: dict {filename: on_disk_bytes} for files already cached.- ``free_bytes``: value returned by shutil.disk_usage(cache_dir).free.+ ``cached_files``: {filename: on_disk_bytes} for files already cached.+ ``free_bytes``: shutil.disk_usage(cache_dir).free."""import osimport shutil@@ -109,8 +100,8 @@ def _preflight(path_infos = [_FakePathInfo(name, size) for name, size in repo_files]with tempfile.TemporaryDirectory() as tmp:- # SPARSE files for the cached ones so os.path.exists / os.path.getsize- # pass without allocating bytes on disk -- critical for multi-GB models.+ # Sparse files so exists/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("/", "_")@@ -122,8 +113,7 @@ def _preflight(def fake_try_to_load_from_cache(repo_id, filename):return cache_paths.get(filename)- # Mirror the real code's variable names and control flow so behavioral- # drift is caught immediately.+ # Mirror the real code's names and control flow so drift is caught.total_bytes = sum((p.size or 0) for p in path_infos)already_cached_bytes = 0for p in path_infos:diff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.pyindex ec66411bfd8..58226f938ce 100644--- a/studio/backend/tests/test_llama_cpp_context_fit.py+++ b/studio/backend/tests/test_llama_cpp_context_fit.py@@ -5,24 +5,14 @@Guards two regressions in ``LlamaCppBackend.load_model``:-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 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.--Avoids GPU probing, subprocess spawning, and GGUF I/O by driving the-post-metadata decision block directly against a stubbed instance.--No GPU, network, or libraries beyond pytest. Cross-platform.+1. Auto mode (``n_ctx == 0``) when weights exceed every GPU subset's free+ memory: auto-pick should fall back to 4096 (a usable slider value) rather+ than leaving native ctx. User can still drag higher onto ``--fit on``.+2. Explicit ctx must never be silently shrunk: when KV overflows fittable+ weights, honor the explicit ctx with ``--fit on`` flexing ``-ngl``.++Drives the post-metadata decision block against a stubbed instance: no GPU,+network, subprocess, or GGUF I/O. Cross-platform."""from __future__ import annotations@@ -34,24 +24,20 @@ from pathlib import Pathimport pytest# ----------------------------------------------------------------------------# Stub heavy / unavailable deps before importing the module under test.-# Same pattern as test_kv_cache_estimation.py.+# Stub heavy/unavailable deps before importing the module under test.# ---------------------------------------------------------------------------_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)-# loggers_loggers_stub = _types.ModuleType("loggers")_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)sys.modules.setdefault("loggers", _loggers_stub)-# structlog_structlog_stub = _types.ModuleType("structlog")sys.modules.setdefault("structlog", _structlog_stub)-# httpx_httpx_stub = _types.ModuleType("httpx")for _exc_name in ("ConnectError",@@ -101,8 +87,7 @@ def _make_backend(kv_key_length = 128,kv_value_length = 128,):- """LlamaCppBackend with GGUF metadata fields set and the decision- block's helpers stubbed out."""+ """LlamaCppBackend with GGUF metadata set and decision helpers stubbed."""inst = LlamaCppBackend.__new__(LlamaCppBackend)inst._context_length = native_ctxinst._n_layers = n_layers@@ -134,8 +119,8 @@ def _drive():"""Drive the post-metadata portion of load_model with stubbed inputs.- Mirrors the decision block at llama_cpp.py:1137-1296 to assert the- command that would be built, without subprocesses or GPU probes.+ Mirrors llama_cpp.py:1137-1296 to assert the built command, without+ subprocesses or GPU probes."""inst = _make_backend(native_ctx = native_ctx)model_size = int(model_gib * GIB)@@ -152,8 +137,7 @@ def _drive(inst._can_estimate_kv = lambda: can_estimate_kvcontext_length = inst._context_length- # Use the production helper, not a local reimplementation: a local copy- # would test the test's own logic, not production's, and hide drift.+ # Use the production helper, not a reimplementation, to avoid testing our own logic.ctx_override = parse_ctx_override(extra_args)requested_ctx = resolve_requested_ctx(extra_args, n_ctx)@@ -491,9 +475,8 @@ class TestTightFitPinsToGPU:@pytest.mark.parametrize("platform_tag", ["linux", "windows", "mac", "rocm"])def test_identical_decision_across_platforms(platform_tag):- """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."""+ """Decision takes ``[(gpu_idx, free_mib), ...]`` regardless of source;+ 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_tagdiff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.pyindex 25bcf851b4e..cb17e0d5e75 100644--- a/studio/backend/tests/test_llama_cpp_freshness.py+++ b/studio/backend/tests/test_llama_cpp_freshness.py@@ -119,10 +119,9 @@ def test_read_install_marker_finds_windows_cmake_layout(tmp_path):@pytest.mark.parametrize("repo", ["unslothai/llama.cpp", "ggml-org/llama.cpp"])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 all surface the right "latest"- # tag.+ # The freshness check queries whichever release repo the marker records,+ # so CUDA (unslothai), CPU/macOS (ggml-org), and ROCm all get 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.pyindex dcbe16be505..cc1c6256a8c 100644--- a/studio/backend/tests/test_llama_cpp_load_progress.py+++ b/studio/backend/tests/test_llama_cpp_load_progress.py@@ -3,32 +3,20 @@"""Tests for ``LlamaCppBackend.load_progress()``.-The chat settings flow and the training overlay both show a generic-"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- but ``_healthy`` is False- * returns ``{"phase": "ready", ...}`` once ``_healthy`` flips- * ``bytes_total`` is derived from the resolved on-disk path- (which the paired fix assigns to ``self._gguf_path`` on both the- local-GGUF and HF-download code paths)+For large MoE GGUFs, llama-server spends minutes paging shards into the page+cache after download. ``load_progress()`` samples ``/proc/<pid>/status VmRSS``+against the total shard size on disk so the UI can render a real bar plus+rate/ETA. Contract pinned here:++ * ``None`` when no load is in flight+ * ``{"phase": "mmap", ...}`` while the subprocess is alive but ``_healthy`` is False+ * ``{"phase": "ready", ...}`` once ``_healthy`` flips+ * ``bytes_total`` derived from the resolved on-disk path (``self._gguf_path``)* ``bytes_loaded`` is VmRSS in bytes, capped by total, rounded- * ``fraction`` is clamped to 0..1 and rounded to 4 decimal places+ * ``fraction`` clamped to 0..1, rounded to 4 dp-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.+Linux-only via ``/proc``; returns ``None`` (not raises) without it, so tests+skip cleanly on macOS / Windows."""from __future__ import annotations@@ -42,10 +30,7 @@ from unittest.mock import patchimport pytest-# ---------------------------------------------------------------------------# 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)if _BACKEND_DIR not in sys.path:diff --git a/studio/backend/tests/test_llama_cpp_load_progress_live.py b/studio/backend/tests/test_llama_cpp_load_progress_live.pyindex ce9dd509bf5..98e19944dd0 100644--- a/studio/backend/tests/test_llama_cpp_load_progress_live.py+++ b/studio/backend/tests/test_llama_cpp_load_progress_live.py@@ -3,18 +3,10 @@"""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,-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``).+The companion mocked tests patch ``builtins.open`` for synthetic VmRSS values;+this one uses real subprocesses, file sizes, and ``/proc`` so format drift the+mocks can't see (kernel ``/proc`` layout, stat vs getsize) gets caught. Skipped+on non-Linux (no ``/proc``)."""from __future__ import annotations@@ -28,10 +20,7 @@ from pathlib import Pathimport pytest-# ----------------------------------------------------------------------------# Same stubs as the matrix file (self-contained so this file runs standalone-# and via the full suite).-# ---------------------------------------------------------------------------+# Same stubs as the matrix file (self-contained for standalone + full-suite runs)._BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:diff --git a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py b/studio/backend/tests/test_llama_cpp_load_progress_matrix.pyindex 1a698d3613d..5c4d9106d8b 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,12 @@"""Extended test matrix for ``LlamaCppBackend.load_progress()``.-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 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 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``, 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.--Linux-only in practice (``/proc`` stubbed where needed). The stable-subset runs in well under a second.+Companion to ``test_llama_cpp_load_progress.py`` (basic contract). Covers+cross-platform edge cases: platform matrix (/proc absence), VmRSS parsing,+filesystem edges (HF-cache symlinks, broken/missing/relative paths), shard+aggregation, lifecycle races, concurrent sampling, and fraction bounds.++Linux-only in practice (``/proc`` stubbed where needed)."""from __future__ import annotations@@ -40,10 +23,7 @@ from unittest.mock import patchimport pytest-# ---------------------------------------------------------------------------# 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)if _BACKEND_DIR not in sys.path:@@ -420,11 +400,8 @@ class TestConcurrentSampling:def test_parallel_invocations_never_raise(self, tmp_path):"""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.+ No ``builtins.open`` patch: ``mock.patch`` isn't thread-safe and could+ leak a Mock into ``open``. Each thread hits the real ``/proc/self/status``."""_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.pyindex 30131991ae5..310aaf6c0fa 100644--- a/studio/backend/tests/test_llama_cpp_max_context_threshold.py+++ b/studio/backend/tests/test_llama_cpp_max_context_threshold.py@@ -28,10 +28,8 @@ from pathlib import Pathimport pytest-# ---------------------------------------------------------------------------# 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)if _BACKEND_DIR not in sys.path:@@ -79,9 +77,7 @@ sys.modules.setdefault("httpx", _httpx_stub)from core.inference.llama_cpp import LlamaCppBackend-# ---------------------------------------------------------------------------# Helpers-# ---------------------------------------------------------------------------GIB = 1024**3@@ -154,9 +150,7 @@ def _compute_max_available_ctx(return max_available_ctx-# ---------------------------------------------------------------------------# Weights exceed every GPU subset's VRAM (MiniMax-M2.7-like)-# ---------------------------------------------------------------------------class TestMaxContextLengthForWeightsExceedVRAM:@@ -193,9 +187,7 @@ class TestMaxContextLengthForWeightsExceedVRAM:assert got == 2048-# ---------------------------------------------------------------------------# Fittable models (regression guard)-# ---------------------------------------------------------------------------class TestMaxContextLengthForFittableModels:@@ -233,9 +225,7 @@ class TestMaxContextLengthForFittableModels:assert got >= 131072 - 256 # rounded to 256 boundary-# ---------------------------------------------------------------------------# Property plumbing-# ---------------------------------------------------------------------------class TestMaxContextLengthProperty:diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.pyindex fc21c48b76d..784ab1b259c 100644--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py@@ -402,11 +402,9 @@ 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"). 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.+ # Vision loads drop speculative decoding at the route level (req -> "off").+ # _already_in_target_state compares canonical requested modes; a vision+ # backend with _requested_spec_mode="off" matches req "off" or None+vision.backend = _mtp_backend(_model_identifier = "unsloth/Qwen3-VL-4B-Instruct-GGUF",_is_vision = True,diff --git a/studio/backend/tests/test_llama_cpp_no_context_shift.py b/studio/backend/tests/test_llama_cpp_no_context_shift.pyindex 312adea83e4..10b1dc7ff65 100644--- a/studio/backend/tests/test_llama_cpp_no_context_shift.py+++ b/studio/backend/tests/test_llama_cpp_no_context_shift.py@@ -101,8 +101,7 @@ def test_flag_sits_inside_the_base_cmd_list():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).rest = source[start:]end_rel = -1for line_start, line in _iter_lines_with_offset(rest):@@ -119,7 +118,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 sits next to -c / --ctx so the grouping makes sense.+ # Pin that it sits next to -c / --ctx so the grouping makes sense.assert '"-c"' in blockassert '"--flash-attn"' in blockdiff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.pyindex d787107d392..33f9e9d803d 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py@@ -50,9 +50,7 @@ for _exc_name in (def _make_backend(port: int = 12345) -> LlamaCppBackend:- """Barebones LlamaCppBackend with only the attributes- _wait_for_health touches. Bypasses __init__ to avoid the full- subprocess + logging stack."""+ """Barebones LlamaCppBackend with only the attributes _wait_for_health touches (bypasses __init__)."""b = LlamaCppBackend.__new__(LlamaCppBackend)b._port = portb._stdout_thread = None@@ -70,12 +68,9 @@ class TestWaitForHealthResilience:assert b._wait_for_health(timeout = 1.0, interval = 0.01) is Truedef test_read_error_loops_to_subprocess_poll(self, monkeypatch):- """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."""+ """WinError 10054 (httpx.ReadError) must be swallowed; the next iteration sees the dead subprocess and returns False with a structured exit-code log."""b = _make_backend()- # Iter 1: process alive (reach the httpx probe).- # Iter 2: process exited (hit the exit-code branch, return False).+ # Iter 1: alive (reach probe); iter 2: exited (exit-code branch -> False).b._process.poll.side_effect = [None, 1]b._process.returncode = 1b._stdout_lines = ["llama-server: ggml-cuda.dll failed to load"]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.pyindex 51835536071..493bb93e8cc 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@@ -19,10 +19,7 @@ from unittest.mock import patchimport pytest-# ----------------------------------------------------------------------------# Same external-dep stubs as the other llama_cpp tests so this module imports-# without httpx / structlog / loggers installed.-# ---------------------------------------------------------------------------+# External-dep stubs so this module imports without httpx / structlog / loggers._BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)@@ -34,8 +31,7 @@ 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)-# Set get_logger even if a prior test inserted a bare ``structlog`` stub-# via ``setdefault``.+# Set get_logger even if a prior test inserted a bare ``structlog`` stub.if not hasattr(sys.modules["structlog"], "get_logger"):sys.modules["structlog"].get_logger = _structlog_stub.get_logger@@ -265,9 +261,7 @@ 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- ``inspect.getsource`` pattern from ``test_llama_cpp_no_context_shift``.- """+ ``had_live_process`` in-band flag regression."""import inspectsrc = inspect.getsource(LlamaCppBackend.load_model)diff --git a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.pyindex 4fa7d2f8e61..957de4bad67 100644--- a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py+++ b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py@@ -60,8 +60,7 @@ from core.inference.llama_cpp import LlamaCppBackend # noqa: E402def _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 in each leaf so isdir() picks them up."""+ """Build a fake nvidia/<pkg>/{bin|Library/bin} tree with a stub DLL per leaf."""nv = prefix / "Lib" / "site-packages" / "nvidia"for pkg, layout in pkgs_with_layout.items():if layout == "bin":@@ -133,10 +132,8 @@ class TestWindowsPipNvidiaDllDirs:assert result == []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/ rather- # than as separate nvidia-* wheels. Without this, torch-bundled-CUDA- # installs still hit #5106.+ # PyTorch's Windows CUDA wheel bundles cudart64/cublas64 DLLs under+ # torch/lib/ rather than as nvidia-* wheels; else still hits #5106.torch_lib = tmp_path / "Lib" / "site-packages" / "torch" / "lib"torch_lib.mkdir(parents = True)(torch_lib / "cudart64_12.dll").write_bytes(b"")@@ -179,16 +176,13 @@ class TestWindowsPipNvidiaDllDirs:assert result == []def test_missing_prefix_does_not_raise(self):- # If sys.prefix points to a nonexistent path (unusual but possible- # during test setup), the resolver must return [], not raise.+ # Nonexistent sys.prefix: 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, the new CUDA 13 wheel- # generation hits the original #5106 failure mode.+ # nvidia 13.x Windows wheels ship DLLs under nvidia/cu13/bin/x86_64/+ # not nvidia/<pkg>/bin/; else the new CUDA 13 wheels hit #5106.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"):@@ -219,10 +213,8 @@ class TestWindowsPipNvidiaDllDirs:assert cu13_arch in result_setdef test_glob_meta_in_prefix_is_safe(self, tmp_path):- # 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.+ # Windows paths can contain ``[``/``]``; a glob-based resolver would+ # read these as a character class. The iterdir impl must handle them.prefix = tmp_path / "studio_[gpu]_install"dll_dir = prefix / "Lib" / "site-packages" / "nvidia" / "cuda_runtime" / "bin"dll_dir.mkdir(parents = True)@@ -231,9 +223,8 @@ 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 the Windows- # DLL search finds cudart64_X.dll even if the parent ``bin`` is empty.+ # When both bin/ and bin/x86_64/ exist, the arch subdir must come first+ # so the Windows DLL search finds cudart64_X.dll if parent bin is empty.site = tmp_path / "Lib" / "site-packages"outer_bin = site / "nvidia" / "cu13" / "bin"arch_bin = outer_bin / "x86_64"diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex 60d4fb0bc38..52e3848157a 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -16,10 +16,8 @@ from pathlib import Pathimport 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 to avoid dragging in the full backend+# chain via core/inference/__init__.py. The validator is dependency-free._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 +70,9 @@ validate_extra_args = _lsa.validate_extra_args# Reasoning controls["--reasoning-format", "deepseek"],["-rea", "auto"],- # 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.+ # Soft-managed: user flags last-wins over Studio's auto-set version.+ # --parallel / -np / --n-parallel are hard-denied (KV-cache + slot+ # count would desync); use `unsloth studio run --parallel N` instead.["-c", "131072"],["--ctx-size", "8192"],["--flash-attn", "off"],diff --git a/studio/backend/tests/test_login_rate_limit.py b/studio/backend/tests/test_login_rate_limit.pyindex 6f2d2c7d94e..14b10576dab 100644--- a/studio/backend/tests/test_login_rate_limit.py+++ b/studio/backend/tests/test_login_rate_limit.py@@ -69,8 +69,7 @@ class TestClientIp:"127.0.0.1",{"x-forwarded-for": "198.51.100.7, 10.0.0.1"},)- # Proxy header can be spoofed; without the opt-in, trust only the- # direct connection.+ # Proxy header is spoofable; without the opt-in, trust 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 +122,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, else suffix- # variations create attacker-controlled buckets.+ # Pick the first Forwarded 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"},@@ -189,9 +188,7 @@ class TestBucketKeyAndBlocking:req = _FakeRequest("203.0.113.10")for idx in range(5):auth_routes._record_login_failure(auth_routes._unknown_user_key(req))- # A different "username" each attempt wouldn't throttle under- # per-(ip,username) only; the IP aggregate must.- # The next missing-user attempt is blocked.+ # Per-(ip,username) alone wouldn't throttle distinct usernames; the IP aggregate must.assert auth_routes._login_blocked(auth_routes._unknown_user_key(req)) > 0def test_unknown_user_bucket_is_single_sentinel(self, env_no_proxy):@@ -202,8 +199,7 @@ 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.+ # Exactly one sentinel bucket for this IP regardless of usernames sprayed.ip_keys = [k for k in auth_routes._LOGIN_BUCKETS if k[0] == "203.0.113.11"]assert len(ip_keys) == 1assert ip_keys[0][1].startswith("\x00")diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.pyindex 9def1619d78..ede3cf15d45 100644--- a/studio/backend/tests/test_mcp_servers.py+++ b/studio/backend/tests/test_mcp_servers.py@@ -151,8 +151,7 @@ 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}$; names with '.',- '/', spaces, etc. would 400 the whole request."""+ """OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; bad names 400 the request."""from core.inference.tools import _mcp_specs_for_serverserver = {"id": "srv", "display_name": "S"}@@ -177,8 +176,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 duplicates before forwarding."""+ """Duplicate tool names from one server -> OpenAI rejects; drop before forwarding."""from core.inference.tools import _mcp_specs_for_serverserver = {"id": "srv", "display_name": "S"}@@ -188,8 +186,7 @@ def test_mcp_specs_drops_duplicate_names():def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):- """cancel_event set before the call -> immediate Error: cancelled, no- network round-trip."""+ """Pre-set cancel_event -> immediate cancellation, no network round-trip."""import threadingfrom core.inference import mcp_client@@ -399,9 +396,8 @@ def test_test_endpoint_surfaces_url_validation_as_400(tmp_path, monkeypatch):def test_tool_xml_parser_handles_hyphenated_parameter_names():- """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 names round-trip."""+ """Hyphenated property names like `issue-number` must round-trip through the+ XML parser (the old `<parameter=\\w+>` regex dropped them)."""from core.inference.tool_call_parser import parse_tool_calls_from_textimport json as _json@@ -417,8 +413,8 @@ def test_tool_xml_parser_handles_hyphenated_parameter_names():def test_tool_healing_strip_handles_hyphenated_function_names():- """GGUF's core/tool_healing.py has its own copy of the XML strip- regex; the round-4 fix to the shared parser missed this file."""+ """core/tool_healing.py has its own copy of the XML strip regex that the+ shared-parser fix missed."""from core.tool_healing import strip_tool_call_markupout = strip_tool_call_markup(@@ -428,9 +424,8 @@ 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). execute_tool previously ran the call regardless."""+ """A tool call not in the per-request list must be refused by the GGUF+ agentic loop (mirroring the safetensors path)."""from core.inference import tools as tools_modcaptured: list[str] = []@@ -441,8 +436,7 @@ def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):monkeypatch.setattr(tools_mod, "execute_tool", fake_execute)- # Re-create the allow-list check inline to unit-test the behavior- # without spinning up llama-server.+ # Inline allow-list check to unit-test behavior without llama-server.def _gate(tools_advertised, called_name, args):allowed = {(t.get("function") or {}).get("name")@@ -472,9 +466,8 @@ 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 made.- The call task was previously created before the cancel check, opening a- transport that the watcher then had to cancel."""+ """Pre-set cancel_event -> no HTTP request (task used to open a transport+ before the cancel check)."""from core.inference import mcp_clientopened: list[str] = []@@ -511,8 +504,7 @@ 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 into a 500 from the- delete / update routes."""+ must not bubble into a 500 from the delete/update routes."""import asynciofrom core.inference import mcp_client@@ -534,9 +526,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, else the- model can call the tool but Studio cannot dispatch."""+ """Hyphenated tool names like `mcp__srv__list-issues` must parse, else the+ model can call the tool but Studio can't dispatch."""from core.inference.tool_call_parser import parse_tool_calls_from_textcalls = parse_tool_calls_from_text(@@ -570,9 +561,8 @@ def test_tool_xml_strip_handles_hyphenated_function_names():def test_safetensors_agentic_empty_allowlist_still_means_allow_all():- """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+ """Contract: at the safetensors_agentic layer tools=[] means "no+ constraint". The MCP-only-no-discovery fix lives at the route level ininference.py, which refuses use_tools when the resolved list is empty."""import threadingfrom core.inference.safetensors_agentic import run_safetensors_tool_loopdiff --git a/studio/backend/tests/test_mcp_stdio_improvements.py b/studio/backend/tests/test_mcp_stdio_improvements.pyindex bec4f9393e5..b0bfd451352 100644--- a/studio/backend/tests/test_mcp_stdio_improvements.py+++ b/studio/backend/tests/test_mcp_stdio_improvements.py@@ -188,8 +188,7 @@ def test_validate_url_allows_url_in_argument(monkeypatch):# ── P6: Data Recipe stdio path obeys the same host gate ─────────────-# build_mcp_providers needs the data_designer plugin, installed only in the-# Studio test job; skip there rather than fail the core matrix.+# build_mcp_providers needs the Studio-only data_designer plugin; skip if absent._STDIO_RECIPE = {"mcp_providers": [diff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.pyindex d744c07b14e..c6a4898d5d9 100644--- a/studio/backend/tests/test_mcp_stdio_pr5863.py+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py@@ -1,13 +1,10 @@"""Verification tests for PR #5863 (stdio MCP server support).-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-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+Covers the pure helpers, the route-level _validate_url gate, and 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 is stubbed so no subprocess spawns;+a recorder asserts whether it was reached."""import sysdiff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex 2ff7acfbd06..16a7bbc46de 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -27,9 +27,7 @@ def main_module():return _main-# =====================================================================# MaxBodyMiddleware-# =====================================================================def _make_protected_app(@@ -205,9 +203,7 @@ class TestMaxBodyMiddleware:assert "Content-Length" in r.json()["detail"]-# =====================================================================# SecurityHeadersMiddleware / CSP-# =====================================================================def _make_csp_app(main_module, attach_nonce: str | None = None):@@ -301,9 +297,7 @@ class TestSecurityHeadersMiddleware:assert any(src == host for src in img_sources)-# =====================================================================# /api/health auth gate-# =====================================================================@pytest.fixturediff --git a/studio/backend/tests/test_multimodal_document.py b/studio/backend/tests/test_multimodal_document.pyindex 29926299cef..5cd7c876cca 100644--- a/studio/backend/tests/test_multimodal_document.py+++ b/studio/backend/tests/test_multimodal_document.py@@ -85,9 +85,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 so this test- # focuses on translation, not the caching layer.+ # Strip the prompt-cache cache_control off the last user block so this+ # test focuses on translation, not the caching layer.return {k: v for k, v in p.items() if k != "cache_control"}@@ -115,8 +114,8 @@ def test_anthropic_base64_pdf_becomes_document_block(monkeypatch):types = [p.get("type") for p in parts]assert "document" in types, partsdoc = _strip_cache(next(p for p in parts if p.get("type") == "document"))- # citations:{enabled:true} opts into Anthropic's natural-citation- # pipeline; without it the citations_delta handler is a no-op.+ # citations:{enabled:true} opts into Anthropic's citation pipeline;+ # without it the citations_delta handler is a no-op.assert doc == {"type": "document","source": {@@ -177,9 +176,8 @@ def test_anthropic_empty_document_part_is_dropped(monkeypatch):def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):- # 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").+ # 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").captured = _capture(monkeypatch,provider = "anthropic",@@ -195,9 +193,8 @@ def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):- # 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.+ # A `data:application/pdf;base64,` with empty/whitespace payload makes an+ # empty `source.data` that Anthropic 400s on; filter it before the wire.captured = _capture(monkeypatch,provider = "anthropic",@@ -226,11 +223,9 @@ 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: 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.+ # The empty-data-URI -> file_url fallback existed on OpenAI but not+ # Anthropic, which 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",@@ -341,10 +336,9 @@ 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 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.+ # An empty `data:application/pdf;base64,` payload was preferred over a valid+ # `file_url` in the same part, sending `file_data=""` and 400ing. The+ # translator must treat empty data URIs as missing and recover via file_url.captured = _capture(monkeypatch,provider = "openai",@@ -444,12 +438,9 @@ def test_openai_empty_document_part_is_dropped(monkeypatch):# ── Pydantic schema + builder pass-through ──────────────────────────-#-# 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.+# The tests above call the client with hand-built dicts, bypassing the schema+# and _build_external_messages. The tests below parse an input_document part+# through the real schema + builder and assert it survives to the client dict.def test_chat_message_accepts_input_document_part():diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.pyindex 2856bb7cada..aab58adfff2 100644--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py@@ -3,27 +3,14 @@"""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 ``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 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.--No GPU, no network, no subprocess. Linux, macOS, Windows compatible.+When ``huggingface.co`` is unreachable but the repo is cached, three failures+hit: ``list_gguf_variants`` 500'd (empty dropdown), ``detect_gguf_model_remote``+returned None (GGUF-only repo misrouted), and ``_download_gguf`` synthesised a+name absent from cache. Follow-ups: the cache filter matches the snapshot-relative+path (subdir layouts findable), and DNS auto-detect scopes ``HF_HUB_OFFLINE`` to+one load so a transient hiccup can't pin the singleton offline.++No GPU, no network, no subprocess. Linux/macOS/Windows compatible."""from __future__ import annotations@@ -269,10 +256,8 @@ class TestDetectGgufFromCache:assert _detect_gguf_from_hf_cache("unsloth/a") == "a-UD-Q4_K_XL.gguf"def test_subdir_only_quant_resolves(self, hf_cache):- """P1 #1 regression: ``BF16/foo.gguf`` (quant only in directory).- The pre-fix cache scan matched on basename, missing this layout- and falling through to the synthetic ``{repo}-{variant}.gguf``- heuristic."""+ """Regression: ``BF16/foo.gguf`` (quant only in directory). The pre-fix+ cache scan matched on basename and missed this layout."""_build_cache(hf_cache,"unsloth/gpt-oss-20b-BF16",@@ -440,9 +425,8 @@ class TestHfOfflineIfDnsDead:class TestExtractQuantLabelSubdir:- """``_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."""+ """``_extract_quant_label`` must consider parent dirs when the basename has+ no quant token (subdir layouts like ``BF16/foo.gguf``)."""def test_quant_in_basename_unchanged(self):assert _extract_quant_label("BF16/foo-BF16.gguf") == "BF16"@@ -455,15 +439,13 @@ 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 match, prefer the innermost (closest- # to the file), matching repos like ``models/MXFP4_MOE/foo.gguf``.+ # Multiple matching parents: prefer the innermost (closest to the file).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 cached."""+ """``_download_mmproj`` must resolve cached mmproj GGUFs offline, like+ ``_download_gguf``; else the offline vision load returns None despite a cache hit."""def test_cache_lookup_returns_cached_mmproj_when_list_repo_files_fails(self, hf_cache):_build_cache(@@ -667,9 +649,8 @@ class TestDetectGgufFromCacheExcludesMmproj:class TestProbeDnsDeadNoGlobalTimeoutMutation:- """``_probe_dns_dead`` must not change ``socket.setdefaulttimeout``- process-wide -- concurrent sockets without an explicit timeout would- inherit it for the probe window."""+ """``_probe_dns_dead`` must not change ``socket.setdefaulttimeout`` process-wide;+ concurrent sockets would inherit it during the probe window."""def test_default_timeout_unchanged_when_dns_up(self, monkeypatch):import socket as _socket@@ -712,9 +693,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."""+ """A TCP RST mid-read while llama-server is still binding (Windows: WinError+ 10054) must not abort the health-poll loop and mask warmup as a fatal load."""def test_read_error_then_success(self, monkeypatch):import httpxdiff --git a/studio/backend/tests/test_openai_citation_markers.py b/studio/backend/tests/test_openai_citation_markers.pyindex dafcffc8bd2..3549a5993e5 100644--- a/studio/backend/tests/test_openai_citation_markers.py+++ b/studio/backend/tests/test_openai_citation_markers.py@@ -66,8 +66,7 @@ def test_unknown_source_marker_dropped_silently():def test_multiple_concatenated_markers_resolved_in_order():- """Real-world wire shape: markers butted together after a sentence,- as in the user-reported bug."""+ """Real-world wire shape: markers butted together after a sentence (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 = [@@ -135,8 +134,7 @@ def test_citation_without_source_id_does_not_crash(citation):def test_multiple_source_id_aliases_resolve_to_same_url():- """Every alias for the same URL must resolve, not just the first.- Regression for the Codex P1 on the original PR."""+ """Every alias for the same URL must resolve, not just the first (Codex P1 regression)."""a = _marker("turn0view0")b = _marker("turn0view0_span_1")c = _marker("turn0view0_span_2")@@ -156,8 +154,7 @@ def test_multiple_source_id_aliases_resolve_to_same_url():def test_source_ids_list_and_legacy_source_id_both_resolve():- """Mixed-shape citation: legacy ``source_id`` plus newer- ``source_ids`` aliases both resolve."""+ """Mixed-shape citation: legacy ``source_id`` plus newer ``source_ids`` aliases both resolve."""legacy = _marker("legacy_id")alias = _marker("alias_id")text = f"Both {legacy} and {alias} work."@@ -173,11 +170,9 @@ def test_source_ids_list_and_legacy_source_id_both_resolve():assert not _has_marker_codepoints(out)-# ---------------------------------------------------------------------------# _rewrite_citation_markers_partial: deferred-annotation tests. OpenAI emits# url_citation annotations on a later SSE event; this helper reports# `has_unresolved` so the stream loop defers emission. See PR #5713 audit.-# ---------------------------------------------------------------------------def test_partial_known_marker_resolves_and_clears_unresolved():@@ -201,7 +196,7 @@ def test_partial_unknown_marker_preserves_verbatim_and_flags():def test_partial_resolves_after_late_annotation():- """Two-pass: first call sees no citations, second resolves after annotation."""+ """Two-pass: first call sees no citations; second resolves after annotation."""text = f"See {_marker('s1')} for details."out1, unresolved1 = _rewrite_citation_markers_partial(text, [])assert unresolved1 is True@@ -213,9 +208,7 @@ 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)."""+ """Any unresolved token in a multi-source marker leaves the whole marker verbatim with ``unresolved`` True until every id resolves or end-of-stream flushes."""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"}]diff --git a/studio/backend/tests/test_openai_code_execution.py b/studio/backend/tests/test_openai_code_execution.pyindex e1b66b40505..63e94613ed1 100644--- a/studio/backend/tests/test_openai_code_execution.py+++ b/studio/backend/tests/test_openai_code_execution.py@@ -1,29 +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-"""-Unit tests for OpenAI's server-side `shell` tool translation in+"""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":- "container_auto"}}`` to ``tools``.-- 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` 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).-- Stale-container handling: 400 with "container expired" body emits a- `container_invalidated` event before propagating the error.+Covers: request body shaping (container_auto, container_reference), the cloud+guard (no shell tool on non-cloud base_urls), SSE translation of a+shell_call/shell_call_output pair into tool_start/tool_end events, container_id+surfacing as container_ready, and stale-container invalidation."""import asyncio@@ -191,8 +175,7 @@ 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 — they 400- # on the unknown tool type.+ # Shell tool must not leak to local OpenAI-compat servers (they 400 on it).assert all(t.get("type") != "shell" for t in tools)@@ -265,9 +248,8 @@ def test_shell_call_emits_tool_start_and_end(monkeypatch):assert len(ends) == 1assert starts[0]["tool_name"] == "code_execution"assert starts[0]["tool_call_id"] == "scall_1"- # `_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.+ # `_server_tool: True` marks a synthetic builtin so the frontend 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"]@@ -391,10 +373,9 @@ 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 sees only container_invalidated,- then the normal stream from the retry — never an error line.+ """On a 'Container is expired' 400 for a container_reference request, the+ streamer retries once with the container stripped; the user sees only+ container_invalidated then the retry stream, never an error line."""calls: list[dict] = []@@ -407,8 +388,7 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):if tool.get("type") == "shell":shell_env_type = tool.get("environment", {}).get("type")break- # First call has container_reference -> 400 expired.- # Retry omits container -> normal SSE stream.+ # container_reference -> 400 expired; retry omits container -> normal stream.if shell_env_type == "container_reference":return httpx.Response(400,diff --git a/studio/backend/tests/test_openai_image_generation.py b/studio/backend/tests/test_openai_image_generation.pyindex 39cf672dc1f..ace57588d39 100644--- a/studio/backend/tests/test_openai_image_generation.py+++ b/studio/backend/tests/test_openai_image_generation.py@@ -3,17 +3,11 @@"""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; 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.+The tool is a server-side Responses-API tool (``{type: "image_generation"}``);+the result comes back as an ``image_generation_call`` output item, which Studio+translates into ``_toolEvent`` chunks so the chat adapter renders it inline.+Tests pin: the tool is added to the body only on a cloud OpenAI base when asked+for, the done event produces the expected chunks, and non-cloud bases drop it."""import asynciodiff --git a/studio/backend/tests/test_openai_responses_translation.py b/studio/backend/tests/test_openai_responses_translation.pyindex 19d4959aa19..f7d7e83a43c 100644--- a/studio/backend/tests/test_openai_responses_translation.py+++ b/studio/backend/tests/test_openai_responses_translation.py@@ -193,7 +193,7 @@ def test_responses_sse_translates_to_chat_completions_chunks(monkeypatch):lines = _drive(run())- # Drop empty / non-data lines for assertion clarity.+ # Keep only data lines for assertion clarity.data_lines = [line for line in lines if line.startswith("data:")]payloads = []for line in data_lines:diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex b9f086a4b90..4437bf22129 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -1,20 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""-Tests for the OpenAI /v1/chat/completions client-side tool pass-through.--Covers:-- ChatCompletionRequest accepts standard OpenAI `tools` / `tool_choice` / `stop`.-- ChatMessage accepts role="tool" with `tool_call_id` and role="assistant"- 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 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.--No running server or GPU required.+"""Tests for the OpenAI /v1/chat/completions client-side tool pass-through.++Covers ChatMessage tool/assistant roles, ChatCompletionRequest tool fields and+extra="allow", anthropic_tool_choice_to_openai, _build_passthrough_payload+tool_choice propagation, and _friendly_error's httpx-to-"Lost connection"+mapping. No server or GPU required."""import os@@ -303,23 +295,16 @@ class TestChatCompletionRequestToolFields:assert req.session_id == "abc"def test_stream_defaults_false_matching_openai_spec(self):- # OpenAI's /v1/chat/completions spec defaults `stream` to false.- # 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.+ # OpenAI defaults `stream` to false. Studio used to default true,+ # breaking naive curl/.NET clients (#5047) that omit it. Pin the fix.req = self._make()assert req.stream is Falsedef 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` (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.+ # Wire-level guard: a POST body omitting `stream` must deserialise to+ # stream=False and return application/json, never text/event-stream.+ # Mounts the real router to catch middleware/aliasing regressions;+ # backends are bypassed via provider_type + a stubbed proxy.from fastapi import FastAPIfrom fastapi.responses import JSONResponsefrom fastapi.testclient import TestClient@@ -482,13 +467,10 @@ 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"``, ...) 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.+ """When llama-server is down, httpx RequestError strings lack the+ "Lost connection to llama-server" substring the sync path keys off, so the+ old substring-only `_friendly_error` returned a useless generic message.+ These tests pin the new isinstance-based mapping."""def _req(self):diff --git a/studio/backend/tests/test_pricing_edge.py b/studio/backend/tests/test_pricing_edge.pyindex 4197d8c9f0a..1fcc428f903 100644--- a/studio/backend/tests/test_pricing_edge.py+++ b/studio/backend/tests/test_pricing_edge.py@@ -95,7 +95,6 @@ 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.out = calculate_cost("openai","gpt-5.5",diff --git a/studio/backend/tests/test_providers_api.py b/studio/backend/tests/test_providers_api.pyindex f343cef635f..5e24ed752db 100644--- a/studio/backend/tests/test_providers_api.py+++ b/studio/backend/tests/test_providers_api.py@@ -72,11 +72,9 @@ def _url(path: str) -> str:def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:- """- Read an SSE response, return (assembled_text, saw_done).+ """Read an SSE response, return (assembled_text, saw_done).- Each chunk is JSON with choices[0].delta.content; stream ends with- `data: [DONE]`.+ Each chunk is JSON with choices[0].delta.content; stream ends at `data: [DONE]`."""reply_parts: list[str] = []saw_done = False@@ -110,19 +108,12 @@ def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:@pytest.fixture(scope = "session")def auth_headers() -> dict[str, str]:- """- Log in once per session and return auth headers.-- 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 auto-change new password is:- STUDIO_TEST_NEW_PASSWORD (env var, optional)- or PASSWORD + "-test" (derived default)+ """Log in once per session and return auth headers.- On the second run, set STUDIO_TEST_PASSWORD to the new password.+ On a fresh install the bootstrap password forces a change; this fixture+ detects must_change_password, auto-completes the change (new password =+ STUDIO_TEST_NEW_PASSWORD or PASSWORD + "-test"), and re-logs in. On the+ second run, set STUDIO_TEST_PASSWORD to the new password."""assert PASSWORD, ("STUDIO_TEST_PASSWORD is not set.\n"@@ -140,8 +131,8 @@ def auth_headers() -> dict[str, str]:assert token, "access_token is empty"if body.get("must_change_password"):- # Bootstrap token only works with /api/auth/change-password; auto-complete- # the forced change so the rest of the tests get a full token.+ # Bootstrap token only works with 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"),@@ -173,12 +164,10 @@ 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 as a base64 data URI.+ """Download the sloth image once per session as a base64 data URI.- 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.+ A data URI sends the image inline; Gemini's OpenAI-compatible layer doesn't+ fetch external HTTP URLs, so raw image_url links give empty Gemini replies."""resp = requests.get(_VISION_IMAGE_URL, timeout = 30)resp.raise_for_status()@@ -189,11 +178,10 @@ def vision_image_data_url() -> str:@pytest.fixture(scope = "session")def encrypt_key(public_key_pem: str):+ """Return encrypt_key(plaintext) -> base64 RSA-OAEP ciphertext.++ Uses the backend's RSA public key; mirrors the frontend."""- Return encrypt_key(plaintext: str) -> str (base64 RSA-OAEP ciphertext).- Uses the backend's RSA public key — mirrors the frontend.- """- # Load RSA public key from PEMpem_bytes = public_key_pem.encode("utf-8")rsa_pub = serialization.load_pem_public_key(pem_bytes)@@ -554,12 +542,10 @@ class TestVisionInference:class TestLocalInferenceUnaffected:def test_chat_without_provider(self, auth_headers: dict[str, str]):- """- POST /v1/chat/completions without provider fields must not return 422 or 500.+ """POST /v1/chat/completions without provider fields must not 422/500.- 200 = local model loaded and responded.- 503 = no model loaded (expected in test env — fine).- Any other 4xx/5xx (except 503) = request-handling regression.+ 200 = local model responded; 503 = no model loaded (fine in tests);+ any other 4xx/5xx = 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.pyindex f1574fb31ec..59842214ef1 100644--- a/studio/backend/tests/test_pytorch_mirror.py+++ b/studio/backend/tests/test_pytorch_mirror.py@@ -20,7 +20,7 @@ OFFICIAL_URL = "https://download.pytorch.org/whl"def _reload_whl_base(monkeypatch, mirror_value = None):"""(Re-)import install_python_stack with a controlled env, return _PYTORCH_WHL_BASE."""- # Drop cached module so the module-level assignment re-executes+ # 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)- # 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.pyindex ffe8c65ac0f..33a457755e8 100644--- a/studio/backend/tests/test_recommended_folders_permission.py+++ b/studio/backend/tests/test_recommended_folders_permission.py@@ -59,8 +59,7 @@ _skip_as_root = pytest.mark.skipif(def test_helper_exists_in_source():- # Guard against a refactor silently dropping the helper the fix needs- # (the extractor would then raise StopIteration).+ # Guard against a refactor silently dropping the helper the fix needs.assert callable(safe_is_dir)diff --git a/studio/backend/tests/test_responses_api.py b/studio/backend/tests/test_responses_api.pyindex 6ef874bd988..693e8321132 100644--- a/studio/backend/tests/test_responses_api.py+++ b/studio/backend/tests/test_responses_api.py@@ -1,11 +1,8 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""-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.-"""+"""Tests for OpenAI Responses API Pydantic schemas and the+_normalise_responses_input helper. No server or GPU required."""import sysimport os@@ -33,9 +30,8 @@ from models.inference import ()-# ── _normalise_responses_input: copied from routes/inference.py ──-# Can't import routes.inference directly: routes/__init__.py pulls in-# heavy deps (structlog/twisted/torch). This is a direct copy for tests.+# Copied from routes/inference.py: can't import it directly because+# routes/__init__.py pulls in heavy deps (structlog/twisted/torch).def _normalise_responses_input(payload: ResponsesRequest) -> list:diff --git a/studio/backend/tests/test_rocm_oom_guard.py b/studio/backend/tests/test_rocm_oom_guard.pyindex 6b2c6aa84fc..21edabd1425 100644--- a/studio/backend/tests/test_rocm_oom_guard.py+++ b/studio/backend/tests/test_rocm_oom_guard.py@@ -3,16 +3,12 @@"""Unit tests for _rocm_classify_unified_memory (ROCm OOM-guard classifier).-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: 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.+Three paths: (1) canonical gcnArchName, (2) alternate-spelling attr, (3) all+arch attrs absent -> device-name substring match.++Regression: Strix Halo (gfx1151) was misclassified as discrete on Radeon wheels+that set props.name="Radeon 8060S Graphics" but no gcnArchName, applying the+wrong headroom factor on a 128 GiB unified-memory pool."""from __future__ import annotationsdiff --git a/studio/backend/tests/test_safetensors_capability_advertise.py b/studio/backend/tests/test_safetensors_capability_advertise.pyindex 1e40f376f32..1e8fb9e2b26 100644--- a/studio/backend/tests/test_safetensors_capability_advertise.py+++ b/studio/backend/tests/test_safetensors_capability_advertise.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-"""-Capability advertisement contract: classifier honesty, worker→orchestrator-IPC hop, route-layer end-to-end. Pure helpers + fakes; no torch/transformers.-"""+"""Capability advertisement contract: classifier honesty, worker->orchestrator+IPC hop, route-layer end-to-end. Pure helpers + fakes; no torch/transformers."""from __future__ import annotations@@ -128,10 +126,9 @@ def test_detect_safetensors_features_gptoss_disables_tools():assert flags["supports_tools"] is False-# 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.+# Llama-3 / Mistral advertise tools but emit <|python_tag|> / [TOOL_CALLS],+# which our parser can't read. The route helper must not flip supports_tools=True+# for them, else the UI enables a pill the agentic loop can't honour.LLAMA3_TEMPLATE = """{%- if tools %}@@ -205,10 +202,9 @@ 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 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.+# Qwen3.5 family pin: the live GGUF + safetensors templates 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"diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.pyindex 526ea2d19fc..55d2a48df18 100644--- a/studio/backend/tests/test_safetensors_tool_loop.py+++ b/studio/backend/tests/test_safetensors_tool_loop.py@@ -1,29 +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-"""-Tests for the safetensors agentic tool loop.--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 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) 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.-* Cancel is honoured between iterations.-* ``max_tool_iterations`` cap is respected and a final-answer attempt closes the- stream cleanly.+"""Tests for the safetensors agentic tool loop.++Covers the ``tool_call_parser`` helpers and the cumulative-text state machine in+``run_safetensors_tool_loop``, run against fake single-turn generators (no model+load). Edge cases: plain answers, JSON and XML tool-call forms, truncated/unclosed+calls, tool-result feedback, bad-JSON heal, duplicate-call short-circuit,+``__IMAGES__`` sentinel stripping, executor errors, cancel, and the iteration cap."""import threading@@ -85,9 +69,8 @@ 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: the parser uses end-of-body as the only boundary for- # single-parameter calls.+ # A code parameter with a literal </parameter> must not truncate: the+ # parser uses end-of-body as the only boundary for single-param calls.text = ("<function=python><parameter=code>html = '<a></a>'\n""print('hi')</parameter></function>"@@ -266,13 +249,13 @@ class TestLoopBasic:def test_single_tool_then_answer(self):loop, exec_fn = _make_loop(turns = [- # : tool call only.+ # Tool call only.['<tool_call>{"name":"web_search",','"arguments":{"query":"weather"}}',"</tool_call>",],- # : final answer.+ # Final answer.["The ", "weather is ", "sunny."],],exec_results = ["Sunny and 22C"],@@ -411,13 +394,10 @@ 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 routes as {"query": ...}.+ # Non-JSON string arguments heal to {"query": ...} under auto_heal_tool_calls.loop, exec_fn = _make_loop(turns = [- # 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.+ # ``arguments`` is a string _coerce_arguments can't parse, so heal runs.['<tool_call>{"name":"web_search","arguments":"hello world"}</tool_call>'],["ok"],],@@ -430,8 +410,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 runs only once.+ # Two identical calls in a row: the second short-circuits with a "do not+ # repeat" message; execute_tool runs once.loop, exec_fn = _make_loop(turns = [['<tool_call>{"name":"web_search","arguments":{"query":"x"}}</tool_call>'],@@ -448,9 +428,8 @@ 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'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.+ # The image sentinel is stripped before the next turn, but tool_end still+ # carries the raw result for the UI.loop, exec_fn = _make_loop(turns = [['<tool_call>{"name":"python","arguments":{"code":"plot()"}}</tool_call>'],@@ -556,8 +535,7 @@ 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.+ # With cancel set, the loop bails before invoking execute_tool.exec_fn = FakeExecuteTool([])events = list(run_safetensors_tool_loop(@@ -578,9 +556,9 @@ class TestLoopControl:# asking for tools, then emits a final-attempt round.loop, exec_fn = _make_loop(turns = [- # : tool call (executes once)+ # Tool call (executes once).['<tool_call>{"name":"web_search","arguments":{"query":"a"}}</tool_call>'],- # : model gives a final answer when nudged.+ # Model gives a final answer when nudged.["here is the final answer"],],exec_results = ["result"],@@ -613,16 +591,13 @@ class TestStatusFormatting:class TestProseMentioningToolCall:def test_assistant_prose_with_literal_tool_call_text_survives(self):- # 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.+ # Regression: prose that mentions a literal ``<tool_call>`` (no real call)+ # must surface in full, not be stripped past the marker.loop, exec_fn = _make_loop(turns = [- # : a real tool call so the loop moves to- # .+ # A real tool call so the loop advances a turn.['<tool_call>{"name":"web_search","arguments":{"query":"x"}}</tool_call>'],- # : prose that mentions the literal text.+ # Prose that mentions the literal text.["the docs say <tool_call> means an LLM tool call wrapper"],],exec_results = ["result"],@@ -636,9 +611,8 @@ 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 parse only the MODEL output, not the tool result, so we see- # exactly one call.+ # A literal ``<tool_call>`` in the tool result must not re-trigger: the+ # loop parses only model output, so 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.pyindex 1841d084b9e..24b1da17728 100644--- a/studio/backend/tests/test_sandbox_tools.py+++ b/studio/backend/tests/test_sandbox_tools.py@@ -223,11 +223,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 the- operator's process config. Covers Linux/macOS/WSL/Windows shapes.- """+ """Sandbox env is built from a whitelist, so credential-shaped parent+ vars stay absent regardless of operator config (Linux/macOS/WSL/Windows)."""_SECRET_KEYS = (# HF + ML tooling@@ -346,12 +343,8 @@ 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 .`- and `echo source` were rejected. The position-anchored regex plus a- shlex-aware command-position-only token check fixes this.- """+ """The blocklist must fire at command position only, so args like+ `grep -r curl .` and `echo source` are not falsely rejected."""@staticmethoddef _find():@@ -464,9 +457,8 @@ class TestBashBlocklistPosition:class TestHfUploadImportGate:- """HfApi-style upload-method blocking requires an HF import in scope;- otherwise paramiko / boto3 / internal SDKs with the same method names- false-positive."""+ """Upload-method blocking requires an HF import in scope, so paramiko /+ boto3 / internal SDKs with the same method names don't false-positive."""def test_paramiko_upload_file_allowed_without_hf_import(self):_ok("import paramiko; sftp=None; sftp.upload_file('a','b')")@@ -523,10 +515,9 @@ class TestHfUploadImportGate:class TestHfUploadSandboxLocalPaths:- """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."""+ """HF upload gate allows only files in the sandbox workdir. Absolute paths,+ `..` traversal, home expansion, and Windows drives are rejected (they could+ lift secrets from outside the sandbox)."""def test_relative_literal_allowed(self):_ok(@@ -673,11 +664,9 @@ class TestHfUploadSandboxLocalPaths:class TestHfUploadEnvAndSecretLeakBlock:- """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."""+ """HF upload gate rejects any arg sourced from os.environ / os.getenv /+ subprocess env reads, since a script can reach the parent env directly+ despite the safe-env shell wrapper."""def test_path_from_os_environ_subscript_blocked(self):_blocked(diff --git a/studio/backend/tests/test_studio_api.py b/studio/backend/tests/test_studio_api.pyindex c40729d9a87..27f695b7442 100644--- a/studio/backend/tests/test_studio_api.py+++ b/studio/backend/tests/test_studio_api.py@@ -65,17 +65,17 @@ import urllib.requestfrom pathlib import Path-# ── Configuration ────────────────────────────────────────────────────+# ConfigurationDEFAULT_MODEL = "unsloth/Qwen3-1.7B-GGUF"DEFAULT_VARIANT = "UD-Q4_K_XL"PORT = 18222 # high port unlikely to collideHOST = "127.0.0.1"-STARTUP_TIMEOUT = 120 # seconds to wait for banner+STARTUP_TIMEOUT = 120 # secondsLOG_FILE = Path(__file__).resolve().parent.parent.parent.parent / "temp" / "test_studio_api.log"-# ── Helpers ──────────────────────────────────────────────────────────+# Helpersdef _http(@@ -125,7 +125,7 @@ def _stream_http(return exc.code, []-# ── Test functions ───────────────────────────────────────────────────+# Test functionsdef test_help_output():@@ -265,19 +265,13 @@ def test_curl_with_tools(base_url: str, api_key: str):print(f" PASS curl with tools: {len(chunks)} chunks, {len(full)} chars content")-# ── Standard OpenAI function-calling pass-through tests ─────────────+# 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, ...) 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.+# Regression coverage for unslothai/unsloth#4999: /v1/chat/completions used+# to strip standard OpenAI `tools`/`tool_choice`, so clients never got+# structured tool_calls back. These exercise the pass-through that forwards+# those fields to llama-server verbatim. Require a tool-capable GGUF+# (supports_tools=True); the default unsloth/Qwen3-1.7B-GGUF qualifies._WEATHER_TOOL = {"type": "function",@@ -532,7 +526,7 @@ def test_no_key_rejected(base_url: str):print(f" PASS no API key rejected ({status})")-# ── Anthropic SSE helper ─────────────────────────────────────────────+# Anthropic SSE helperdef _stream_anthropic_http(@@ -580,7 +574,7 @@ def _collect_anthropic_text(events: list[tuple[str, dict]]) -> str:return "".join(parts)-# ── Anthropic /v1/messages test functions ────────────────────────────+# Anthropic /v1/messages test functionsdef test_anthropic_basic(base_url: str, api_key: str):@@ -763,7 +757,7 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):)-# ── Server lifecycle ─────────────────────────────────────────────────+# Server lifecycledef _start_server(model: str, variant: str | None) -> tuple[subprocess.Popen, str]:@@ -837,7 +831,7 @@ def _kill_server(proc: subprocess.Popen):proc.wait(timeout = 5)-# ── Main ─────────────────────────────────────────────────────────────+# Maindef main():@@ -870,11 +864,11 @@ def main():failed += 1print(f" ERROR {fn.__name__}: {type(exc).__name__}: {exc}")- # ── 1. --help (no server needed) ────────────────────────────+ # 1. --help (no server needed)print("\n[1/16] Testing --help output")run_test(test_help_output)- # ── 2-16. Start server and run API tests ─────────────────────────+ # 2-16. Start server and run API testsprint(f"\nStarting server: {args.model} (variant={args.gguf_variant}) on port {PORT}...")proc = Nonetry:@@ -929,14 +923,14 @@ def main():except RuntimeError as exc:print(f"\nFATAL: Server failed to start: {exc}")- failed += 16 # count remaining tests as failed+ failed += 16 # remaining tests count as failedfinally:if proc:print("\nStopping server...")_kill_server(proc)print("Server stopped.")- # ── Summary ──────────────────────────────────────────────────────+ # Summarytotal = passed + failedprint(f"\n{'=' * 40}")print(f"Results: {passed}/{total} passed, {failed} failed")diff --git a/studio/backend/tests/test_studio_train_validation.py b/studio/backend/tests/test_studio_train_validation.pyindex ed33c07689f..0ffecb3ce48 100644--- a/studio/backend/tests/test_studio_train_validation.py+++ b/studio/backend/tests/test_studio_train_validation.py@@ -94,8 +94,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; contract is "integer or null".+ # Regression guard: multi-sign strings say "integer or null", not int()'s raw message.with pytest.raises(ValidationError) as exc:_check_field("vision_image_size", value)assert "integer or null" in str(exc.value)@@ -103,8 +102,7 @@ class TestVisionImageSizeCap:@pytest.mark.parametrize("value", ["512", "٥١٢", "१०२४"])def test_unicode_digit_string_rejected(self, value):- # Full-width / Arabic-Indic / Devanagari digits must be rejected so the- # value reaching the backend equals the ASCII the user typed.+ # Reject non-ASCII (full-width/Arabic-Indic/Devanagari) digits.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_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.pyindex 5b7b70eefe2..3c5d6cd0946 100644--- a/studio/backend/tests/test_training_worker_flash_attn.py+++ b/studio/backend/tests/test_training_worker_flash_attn.py@@ -370,9 +370,8 @@ 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 added- # because fla/utils.py imports them at load but neither is in- # fla-core's METADATA (an upstream FLA gap).+ # 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 argsassert "packaging" in argsassert "triton" in args@@ -491,14 +490,10 @@ def test_tilelang_backend_installs_pinned_pair_for_qwen3_5(monkeypatch):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`- — 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 correct packages.+ 1 (repair): --force-reinstall --no-deps apache-tvm-ffi -- downgrades only+ the broken package; --no-deps stops the cascade through its deps to torch.+ 2 (install): plain apache-tvm-ffi + tilelang -- resolves missing transitive+ deps without --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")@@ -633,12 +628,9 @@ def test_tilelang_backend_swallows_install_failure(monkeypatch):assert any("failed" in s.lower() for s in statuses)-# ───────────────────────────────────────────────────────────────────-# Runtime hook on `is_flash_linear_attention_available` /-# `is_causal_conv1d_available` — the primary gate in normal operation.-# The substring tests above cover the-# UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 fallback.-# ───────────────────────────────────────────────────────────────────+# Runtime hook on is_flash_linear_attention_available /+# is_causal_conv1d_available -- the primary gate in normal operation. The+# substring tests above cover the SKIP_FAST_PATH_HOOKS=1 fallback.class _FakeQueue(list):@@ -840,10 +832,9 @@ def test_hook_clears_lru_cache_before_first_check(monkeypatch):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 misses those local bindings;- the hook installer sweeps sys.modules and rebinds them.+ """Modeling files bind is_flash_linear_attention_available locally via+ `from ... import is_X`. Reassigning the attribute on import_utils alone+ misses those; 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)@@ -905,8 +896,7 @@ def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):assert install_mock.call_count == 1-# ───────────────────────────────────────────────────────────────────-# Regression tests for the 10-reviewer findings:+# Regression tests for the reviewer findings:# 1. tilelang Qwen-guard on hook path (non-Qwen FLA models)# 2. tilelang repair must not replace torch / CUDA stack# 3. hook must trust installer's bool, not transformers metadata@@ -915,7 +905,6 @@ def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):# 6. tilelang skipped when FLA was skipped / failed# 7. tilelang repair runs when FLA is already True# 8. older FLA detected as stale and reinstalled-# ───────────────────────────────────────────────────────────────────def test_hook_does_not_install_tilelang_for_model_outside_allowlist(monkeypatch):@@ -1006,18 +995,9 @@ 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 (metadata-only) returns True after pip succeeds.-- 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 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.+ """Finding #3: if pip exits 0 but deep imports fail, the installer returns+ False; the hook must propagate that False even if the metadata-only gate+ returns True after pip succeeds, so transformers takes the torch fallback."""# Gate flips True after install (simulating "metadata sees fla").fla_gate = _make_fake_gate(initial_return = False)@@ -1158,14 +1138,10 @@ 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 won't fire- for them. The orchestrator must always run the eager substring- installer regardless of hook mode.-- 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.+ """Finding #4: SSM modeling files use lazy_load_kernel and never call+ is_causal_conv1d_available(), so the hook won't fire; the orchestrator must+ always run the eager installer regardless of hook mode. Reads the worker+ source and asserts the eager install is OUTSIDE the if/else hook branch."""import inspect@@ -1184,13 +1160,10 @@ def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():)-# ───────────────────────────────────────────────────────────────────-# HIP / ROCm regression coverage (h34v3nzc0dex Strix Halo report).+# HIP / ROCm regression coverage (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". Fix: skip-# install on HIP-built torch AND setdefault FLA_TILELANG=0 so an-# already-installed tilelang isn't used either.-# ───────────────────────────────────────────────────────────────────+# mid-backward on AMD ("Unsupported target for gemm: hip"). Fix: skip install on+# HIP torch AND setdefault FLA_TILELANG=0 so an existing tilelang isn't used.def test_tilelang_platform_unsupported_on_hip_torch(monkeypatch):@@ -1420,16 +1393,12 @@ def test_model_wants_tilelang_normalizes_separators(monkeypatch):assert worker._model_wants_tilelang(variant) is True, variant-# ────────────────────────────────────────────────────────────────────-# 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 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).-# ────────────────────────────────────────────────────────────────────+# HIP source-build gcc-install-dir coverage (Strix Halo).+# Ubuntu 24.04 ships gcc-14's runtime dir without /usr/include/c++/14, so ROCm+# clang-20 picks it and fails ('cstdlib' not found) building causal-conv1d.+# _hipcc_gcc_install_dir() finds a gcc dir with both halves; the HIP branch of+# _install_package_wheel_first passes it via HIPCC_COMPILE_FLAGS_APPEND.+# Parallels bbf004c's setup.sh fix for the llama.cpp HIP build (PR #5301).def _isdir_for_layout(*existing: str):diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.pyindex c8d6a4fd100..915bc4b13b0 100644--- a/studio/backend/tests/test_transformers_version.py+++ b/studio/backend/tests/test_transformers_version.py@@ -185,9 +185,8 @@ class TestNeedsTransformers5:config_cfg = {"model_name": "Qwen/Qwen3.5-9B"}(tmp_path / "config.json").write_text(json.dumps(config_cfg))- # ensure_transformers_version calls _resolve_base_model, but- # needs_transformers_5 just does substring matching. Test the- # full resolution chain here.+ # needs_transformers_5 only does substring matching, so test the+ # full resolution chain via _resolve_base_model here.resolved = _resolve_base_model(str(tmp_path))assert needs_transformers_5(resolved) is True@@ -311,7 +310,6 @@ class TestGetTransformersTier:def test_550_checked_before_530(self):"""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.pyindex 765235bd32d..c66d56528ac 100644--- a/studio/backend/tests/test_utils.py+++ b/studio/backend/tests/test_utils.py@@ -1,20 +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-"""-Tests for utils/hardware and utils/utils — device detection, GPU memory, error formatting.--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 needing torch/mlx-internals for mocking are skipped when unavailable.+"""Tests for utils/hardware and utils/utils: device detection, GPU memory, error formatting.-Run with:- cd studio/backend- python -m pytest tests/test_utils.py -v+Passes on any platform (NVIDIA/CUDA, Apple Silicon/MLX, CPU-only). No ML framework+is imported at top level; tests needing torch/mlx internals skip when unavailable."""import platform@@ -189,9 +179,8 @@ class TestGetGpuMemoryInfo:assert "backend" in get_gpu_memory_info()def test_backend_matches_device(self):- # 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`.+ # _backend_label swaps "cuda" for "rocm" on AMD hosts; elsewhere it+ # equals get_device().value.from utils.hardware.hardware import _backend_labelresult = 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.pyindex 0df474b586f..2fee50d8426 100644--- a/studio/backend/tests/test_vision_cache.py+++ b/studio/backend/tests/test_vision_cache.py@@ -20,9 +20,7 @@ from unittest.mock import patch, MagicMockimport pytest-# ---------------------------------------------------------------------------# sys.path + logger stub — same pattern as the rest of the test suite-# ---------------------------------------------------------------------------_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)@@ -38,9 +36,7 @@ from utils.models.model_config import ()-# ---------------------------------------------------------------------------# Helpers-# ---------------------------------------------------------------------------@pytest.fixture(autouse = True)@@ -51,9 +47,7 @@ def _clear_vision_cache():_vision_detection_cache.clear()-# ---------------------------------------------------------------------------# Cache hit / miss tests-# ---------------------------------------------------------------------------class TestVisionCacheHitMiss:@@ -93,9 +87,7 @@ class TestVisionCacheStoresFalse:assert _vision_detection_cache[("org/text-only", None)] is False-# ---------------------------------------------------------------------------# Subprocess path (transformers 5.x) caching-# ---------------------------------------------------------------------------class TestVisionCacheSubprocessPath:@@ -128,9 +120,7 @@ class TestVisionCacheSubprocessPath:mock_raw_config.assert_called_once_with("unsloth/gemma-4-E4B-it", hf_token = None)-# ---------------------------------------------------------------------------# Exception handling — cache the False fallback-# ---------------------------------------------------------------------------class TestVisionCacheOnException:@@ -146,14 +136,10 @@ class TestVisionCacheOnException:def test_permanent_exception_result_cached(self, mock_needs_t5, mock_load_config):"""A permanent failure (ValueError / RepositoryNotFoundError /GatedRepoError / JSONDecodeError) is caught, returns False, and- that False is cached so subsequent calls don't retry.-- 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.+ that False is cached so subsequent calls don't retry. ValueError+ stands in as the simplest cacheable exception type."""+ # First call raises -> False; second is a cache hit.assert is_vision_model("broken/model") is False- # Second call: cache hit, load_model_config not called again.assert is_vision_model("broken/model") is Falsemock_load_config.assert_called_once()@@ -164,21 +150,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) 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.+ _is_vision_model_uncached, surfaces as False, and is NOT cached+ so the next call retries."""+ # First call: OSError -> False, not cached; second call retries.assert is_vision_model("broken/model") is False- # Second call: cache miss again, load_model_config called twice.assert is_vision_model("broken/model") is Falseassert mock_load_config.call_count == 2-# ---------------------------------------------------------------------------# Direct detection path (non-transformers-5 models) caching-# ---------------------------------------------------------------------------class TestVisionCacheDirectPath:@@ -278,9 +258,7 @@ class TestVisionCacheDirectPath:mock_load_config.assert_called_once()-# ---------------------------------------------------------------------------# hf_token handling-# ---------------------------------------------------------------------------class TestVisionCacheTokenHandling:diff --git a/studio/backend/tests/test_windows_gpu_detection_mock.py b/studio/backend/tests/test_windows_gpu_detection_mock.pyindex 3a82541a311..88a1a28d146 100644--- a/studio/backend/tests/test_windows_gpu_detection_mock.py+++ b/studio/backend/tests/test_windows_gpu_detection_mock.py@@ -34,12 +34,9 @@ _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 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.+# Stub heavy deps only if they fail to import (unconditional stubs would shadow+# the real module for sibling tests). Use try-import, not find_spec: loggers+# imports fastapi at load, so find_spec succeeds but the import then raises.import importlib as _importlib # noqa: E402@@ -131,9 +128,7 @@ REAL_PIP_NVIDIA_WHEEL_LAYOUTS = {def _populate_studio_venv(prefix: Path) -> None:- """Lay out fake nvidia + torch wheels in <prefix>/Lib/site-packages- matching real win_amd64 layouts. Contents are stub bytes; only- directory structure matters."""+ """Lay out fake nvidia + torch wheels matching real win_amd64 layouts (stub bytes)."""site = prefix / "Lib" / "site-packages"for rel, dlls in REAL_PIP_NVIDIA_WHEEL_LAYOUTS.items():d = site / Path(rel)@@ -147,8 +142,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 + cudart bundle overlay."""+ """Lay out install_dir/build/bin/Release/ as #5322 leaves it: payload + cudart overlay."""rel = install_dir / "build" / "bin" / "Release"rel.mkdir(parents = True, exist_ok = True)for fn in (@@ -172,9 +166,7 @@ def _build_path_dirs_like_start_llama_server(prefix: Path,cuda_path: str = "",) -> list[str]:- """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."""+ """Wrapper around the real _build_windows_path_dirs staticmethod."""return LlamaCppBackend._build_windows_path_dirs(str(binary_dir), str(prefix), cuda_path)diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.pyindex 4e582ae926e..210735973d8 100644--- a/studio/backend/utils/cache_cleanup.py+++ b/studio/backend/utils/cache_cleanup.py@@ -1,14 +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-"""-Utility for cleaning up the Unsloth compiled cache directory.+"""Clean up the Unsloth compiled cache directory.-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.+unsloth_compiled_cache (created by unsloth_zoo/compiler.py during+FastModel.from_pretrained) holds model-type-specific compiled files. Clear it+selectively between model loads, preserving model-agnostic components (Trainers)+that spawned subprocesses need."""import shutil@@ -79,7 +77,6 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)for item in cache_dir.iterdir():if item.is_file():- # Keep the file if it matches any preserve patternpreserve = any(item.match(pattern) for pattern in preserve_patterns)if not preserve:try:@@ -91,6 +88,6 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)# Always clear __pycache__ and other subdirectoriesshutil.rmtree(item, ignore_errors = True)else:- # Legacy behavior: remove the entire directory+ # Legacy: remove the entire directorylogger.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.pyindex 5cf2ff1ce23..4ed0021054c 100644--- a/studio/backend/utils/cpu_threads.py+++ b/studio/backend/utils/cpu_threads.py@@ -19,8 +19,8 @@ def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> Non"""Apply ``UNSLOTH_CPU_THREADS`` to native CPU pools when configured.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.+ pool. Library-specific vars are left untouched so users can override a+ single runtime independently."""environ = os.environ if env is None else envconfigured = environ.get("UNSLOTH_CPU_THREADS", "").strip()diff --git a/studio/backend/utils/datasets/__init__.py b/studio/backend/utils/datasets/__init__.pyindex 3ecb0854780..caa471bde5d 100644--- a/studio/backend/utils/datasets/__init__.py+++ b/studio/backend/utils/datasets/__init__.py@@ -1,20 +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-"""-Dataset utilities for LLM/VLM fine-tuning: format detection, conversion,-and processing.+"""Dataset utilities for LLM/VLM fine-tuning: detection, conversion, templating, collators, mappings."""-Modules:-- format_detection: Detect dataset formats (Alpaca, ShareGPT, ChatML)-- format_conversion: Convert between dataset formats-- chat_templates: Apply chat templates to datasets-- vlm_processing: Vision-Language Model processing utilities-- data_collators: Custom data collators for training-- model_mappings: Model-to-template mapping constants-"""--# Format detectionfrom .format_detection import (detect_dataset_format,detect_custom_format_heuristic,@@ -22,7 +10,6 @@ from .format_detection import (detect_vlm_dataset_structure,)-# Format conversionfrom .format_conversion import (standardize_chat_format,convert_chatml_to_alpaca,@@ -32,7 +19,6 @@ from .format_conversion import (convert_sharegpt_with_images_to_vlm_format,)-# Chat templatesfrom .chat_templates import (apply_chat_template_to_dataset,get_dataset_info_summary,@@ -40,19 +26,16 @@ from .chat_templates import (DEFAULT_ALPACA_TEMPLATE,)-# VLM processingfrom .vlm_processing import (generate_smart_vlm_instruction,)-# Data collatorsfrom .data_collators import (DataCollatorSpeechSeq2SeqWithPadding,DeepSeekOCRDataCollator,VLMDataCollator,)-# Model mappings (constants)from .model_mappings import (TEMPLATE_TO_MODEL_MAPPER,MODEL_TO_TEMPLATE_MAPPER,@@ -60,14 +43,13 @@ from .model_mappings import (is_gpt_oss_model_name,)-# Legacy imports from dataset_utils.py (not yet refactored) for backward compat+# Legacy dataset_utils.py imports kept for backward compatfrom .dataset_utils import (check_dataset_format,format_and_template_dataset,format_dataset,)-# Public API__all__ = [# Detection"detect_dataset_format",diff --git a/studio/backend/utils/datasets/chat_templates.py b/studio/backend/utils/datasets/chat_templates.pyindex 4b8ee93e9c6..82a30fd55b7 100644--- a/studio/backend/utils/datasets/chat_templates.py+++ b/studio/backend/utils/datasets/chat_templates.py@@ -44,28 +44,25 @@ def _chat_template_kwargs() -> dict:def get_tokenizer_chat_template(tokenizer, model_name):- """- Get the chat template for a tokenizer based on the model.- Uses Unsloth's get_chat_template if the model is in the mapper.+ """Apply a chat template to the tokenizer, using Unsloth's+ get_chat_template when the model class name is in the mapper.Args:tokenizer: HuggingFace tokenizermodel_name: Model class name (e.g., "Gemma3ForCausalLM")Returns:- tokenizer: Tokenizer with the chat template applied+ tokenizer with the chat template applied"""try:from unsloth.chat_templates import get_chat_templateexcept ImportError:- # Unsloth not available; return tokenizer as-is.return tokenizermodel_name_lower = model_name.lower()matched_template = None- # 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}")@@ -79,7 +76,6 @@ 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 whether the tokenizer has a chat_template set.has_chat_template = (hasattr(tokenizer, 'chat_template')and tokenizer.chat_template is not None@@ -87,7 +83,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(@@ -140,8 +136,7 @@ def apply_chat_template_to_dataset(num_proc = None,progress_callback = None,):- """- Apply the chat template to a 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@@ -164,7 +159,6 @@ def apply_chat_template_to_dataset(warnings = list(dataset_info.get("warnings", []))errors = []- # Get EOS token if needed.eos_token = ""if add_eos_token:if hasattr(tokenizer, 'eos_token') and tokenizer.eos_token:@@ -174,7 +168,6 @@ def apply_chat_template_to_dataset(# CUSTOM FORMAT MAPPING (for non-standard datasets)if final_format == "unknown":- # Auto-detect if no custom mapping was provided.if custom_format_mapping is None and auto_detect_mapping:# Skip if format_dataset already tried and failed.if not dataset_info.get("auto_detection_attempted", False):@@ -246,7 +239,6 @@ def apply_chat_template_to_dataset(try:dataset = dataset.map(_apply_custom_mapping, batched = True, batch_size = batch_size)- # Switch to conversations format.final_format = "chatml_conversations"chat_column = "conversations"is_standardized = True@@ -263,8 +255,7 @@ def apply_chat_template_to_dataset(# ALPACA FORMATif final_format == "alpaca":- # Set alpaca chat template on the tokenizer (if unset) so it's- # saved with the model for inference.+ # Set alpaca chat template (if unset) so it's saved for inference.if not (hasattr(tokenizer, 'chat_template') and tokenizer.chat_template):try:from unsloth.chat_templates import get_chat_template@@ -277,7 +268,6 @@ 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.def _format_alpaca_custom(examples):texts = []for i in range(len(examples["instruction"])):@@ -392,7 +382,7 @@ def apply_chat_template_to_dataset(dataset_map_kwargs['num_proc'] = num_procdataset_map_kwargs['desc'] = f"Applying chat template to {final_format}"- # Monitor tqdm progress from dataset.map() and relay it.+ # Monitor dataset.map() tqdm progress and relay it._tqdm_monitor_stop = Noneif progress_callback and not _is_torch_iterable:import threadingdiff --git a/studio/backend/utils/datasets/data_collators.py b/studio/backend/utils/datasets/data_collators.pyindex 5f249b32f91..9bfb60ba179 100644--- a/studio/backend/utils/datasets/data_collators.py+++ b/studio/backend/utils/datasets/data_collators.py@@ -1,11 +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-"""-Data collators for dataset processing.--Custom training collators, particularly for VLM/OCR processing.-"""+"""Custom training data collators, particularly for VLM/OCR processing."""from dataclasses import dataclassfrom typing import Any, List, Optional, Union@@ -44,13 +40,10 @@ class DataCollatorSpeechSeq2SeqWithPadding:@dataclassclass DeepSeekOCRDataCollator:- """- Data collator for DeepSeek OCR VLM training.+ """Data collator for DeepSeek OCR VLM training.- Handles:- - Image processing via processor- - Text tokenization- - Proper label masking for instruction fine-tuning+ Handles image processing, text tokenization, and label masking for+ instruction fine-tuning."""processor: Any # Qwen2VLProcessor or similar@@ -70,7 +63,6 @@ class DeepSeekOCRDataCollator:"""from PIL import Image- # Extract messages and images.all_messages = []all_images = []@@ -78,7 +70,6 @@ class DeepSeekOCRDataCollator:messages = sample["messages"]all_messages.append(messages)- # Extract PIL images from content.for msg in messages:content = msg.get("content", [])if isinstance(content, list):@@ -88,9 +79,7 @@ class DeepSeekOCRDataCollator:if img is not None and hasattr(img, "size"): # PIL Imageall_images.append(img)- # Process with the VL processor.try:- # Qwen2VL-style processing.texts = [self.processor.apply_chat_template(msgs, tokenize = False, add_generation_prompt = False@@ -98,7 +87,6 @@ class DeepSeekOCRDataCollator:for msgs in all_messages]- # Process with images.inputs = self.processor(text = texts,images = all_images if all_images else None,@@ -108,10 +96,7 @@ class DeepSeekOCRDataCollator:max_length = self.max_length,)- # Create labels (mask input, keep output).labels = inputs["input_ids"].clone()-- # Mask padding tokens.labels[labels == self.processor.tokenizer.pad_token_id] = self.ignore_indexinputs["labels"] = labels@@ -125,14 +110,7 @@ class DeepSeekOCRDataCollator:@dataclassclass VLMDataCollator:- """- Generic VLM data collator that works with various processors.-- Supports:- - Qwen2VL- - LLaVA- - Other VL models with compatible processors- """+ """Generic VLM data collator for various processors (Qwen2VL, LLaVA, etc.)."""processor: Anymax_length: int = 2048@@ -140,9 +118,7 @@ class VLMDataCollator:mask_input_tokens: bool = True # Mask user tokens in labelsdef __call__(self, batch: List[dict]) -> dict:- """- Collate a batch of VLM samples.- """+ """Collate a batch of VLM samples."""all_messages = []all_images = []@@ -150,7 +126,6 @@ class VLMDataCollator:messages = sample.get("messages", [])all_messages.append(messages)- # Extract images.for msg in messages:content = msg.get("content", [])if isinstance(content, list):@@ -160,13 +135,11 @@ class VLMDataCollator:if img is not None:all_images.append(img)- # Apply chat template.texts = [self.processor.apply_chat_template(msgs, tokenize = False, add_generation_prompt = False)for msgs in all_messages]- # Process inputs.inputs = self.processor(text = texts,images = all_images if all_images else None,@@ -176,7 +149,6 @@ class VLMDataCollator:max_length = self.max_length,)- # Create labels.labels = inputs["input_ids"].clone()# Mask padding.diff --git a/studio/backend/utils/datasets/dataset_none_detect.py b/studio/backend/utils/datasets/dataset_none_detect.pyindex 354fd360d36..a2fd8ef667b 100644--- a/studio/backend/utils/datasets/dataset_none_detect.py+++ b/studio/backend/utils/datasets/dataset_none_detect.py@@ -1,6 +1,4 @@"""-dataset_none_detect.py-Detect None/empty content turns in conversation datasets. Reports findingswithout modifying data.@@ -71,10 +69,8 @@ def _probe_conversation(dataset: Dataset, candidates = None):breakif first is None:# No usable dict turn in 100 rows. Record an all_corrupt fallback,- # 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.+ # plausible only with turn-shaped data (None cell or list of dict/None+ # turns); a later plausible candidate upgrades a non-plausible one.if all_corrupt_fallback is None or not all_corrupt_fallback.get("has_plausible_turns"):has_plausible_turns = Falsefor i in range(min(len(dataset), 100)):diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.pyindex 03387e5331d..2d65b6ecbc9 100644--- a/studio/backend/utils/datasets/dataset_utils.py+++ b/studio/backend/utils/datasets/dataset_utils.py@@ -20,7 +20,6 @@ Internal utilities live in separate modules:import json-# Import from modular filesfrom .format_detection import (detect_dataset_format,detect_multimodal_dataset,@@ -915,8 +914,7 @@ def format_and_template_dataset("errors": [],}except Exception as e:- # User mapping failed — fall back to auto-detection rather- # than give up (handles stale cached mappings gracefully)+ # User mapping failed; fall back to auto-detection (handles stale cached mappings).warnings.append(f"User VLM mapping (image='{user_vlm_image_column}', "f"text='{user_vlm_text_column}') failed: {e} — "@@ -1154,8 +1152,7 @@ def format_and_template_dataset(all_warnings = dataset_info.get("warnings", []) + template_result.get("warnings", [])all_errors = template_result.get("errors", [])- # If format_dataset returned "unknown" but apply_chat_template rescued- # it via heuristic detection, update final_format accordingly.+ # If apply_chat_template rescued an "unknown" format, update final_format.final_format = dataset_info["final_format"]requires_manual = dataset_info.get("requires_manual_mapping", False)if final_format == "unknown" and template_result["success"]:diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.pyindex 09521e160ce..7a556a97456 100644--- a/studio/backend/utils/datasets/format_conversion.py+++ b/studio/backend/utils/datasets/format_conversion.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-"""-Dataset format conversion: convert between Alpaca, ShareGPT, and ChatML,-and standardize chat formats.-"""+"""Dataset format conversion between Alpaca, ShareGPT, and ChatML."""import os@@ -290,14 +287,11 @@ def convert_to_vlm_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, reporting a time- estimate or warning via progress_callback before the full conversion.+ For URL-based datasets, runs a 200-sample parallel probe first to+ estimate speed/failure rate via progress_callback.Args:- progress_callback: Optional callable(status_message=str) to- report progress to the training overlay.+ progress_callback: Optional callable(status_message=str) for progress.Returns:list: List of dicts with 'messages' field@@ -385,9 +379,8 @@ def convert_to_vlm_format(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") not present locally. Build a basename→repo_path- # lookup to resolve them via hf_hub_download during conversion.+ # ── Bare-filename detection: build a basename→repo_path lookup so+ # filename-only images resolve via hf_hub_download during conversion._image_lookup = None_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff")if (diff --git a/studio/backend/utils/datasets/format_detection.py b/studio/backend/utils/datasets/format_detection.pyindex 72f8f48cf75..b3a4e3d6d59 100644--- a/studio/backend/utils/datasets/format_detection.py+++ b/studio/backend/utils/datasets/format_detection.py@@ -1,11 +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-"""Format detection utilities for dataset processing.--Detects dataset formats (Alpaca, ShareGPT, ChatML), multimodal/VLM-structures, and heuristic column mapping.-"""+"""Dataset format detection: Alpaca/ShareGPT/ChatML, multimodal/VLM structures, heuristic column mapping."""import re@@ -48,7 +44,6 @@ def detect_dataset_format(dataset):chat_column = "texts"if chat_column:- # Inspect structure: ShareGPT or ChatML?try:sample = next(iter(dataset))chat_data = sample[chat_column]@@ -57,7 +52,7 @@ def detect_dataset_format(dataset):first_msg = chat_data[0]msg_keys = set(first_msg.keys())- # ShareGPT uses "from" and "value"+ # ShareGPT: "from"/"value"if "from" in msg_keys or "value" in msg_keys:return {"format": "sharegpt",@@ -66,7 +61,7 @@ def detect_dataset_format(dataset):"sample_keys": list(msg_keys),}- # ChatML uses "role" and "content"+ # ChatML: "role"/"content"elif "role" in msg_keys and "content" in msg_keys:return {"format": "chatml",@@ -75,7 +70,6 @@ def detect_dataset_format(dataset):"sample_keys": list(msg_keys),}- # Has chat column but unknown structureelse:return {"format": "unknown",@@ -92,7 +86,6 @@ def detect_dataset_format(dataset):"error": str(e),}- # No recognized formatreturn {"format": "unknown","chat_column": None,@@ -115,7 +108,6 @@ def detect_custom_format_heuristic(dataset):mapping = {}- # Keywordsassistant_words = ["output","answer",@@ -132,7 +124,6 @@ def detect_custom_format_heuristic(dataset):"solve",]- # Split into high/low priorityuser_words_high_priority = ["input","question",@@ -159,7 +150,7 @@ def detect_custom_format_heuristic(dataset):"task", # also a system keyword]- # Metadata columns to ignore+ # Metadata columns to ignore.metadata_exact_match = {"id","idx",@@ -254,12 +245,11 @@ def detect_custom_format_heuristic(dataset):score = 0score += 10- # Penalize ambiguous keywords when scoring for user+ # Penalize ambiguous "task" so other user columns win.if role_type == "user":col_lower = col_name.lower()- # ONLY "task" (or task_xxx): lower priority for user roleif "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+ score -= 15priority_bonus = get_priority_score(col_name)score += priority_bonus@@ -286,14 +276,12 @@ def detect_custom_format_heuristic(dataset):return score- # Drop metadata columnscontent_columns = [col for col in all_columns if not is_metadata(col)]- # Count candidatesassistant_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)]- # STEP 1: Find best ASSISTANT column+ # STEP 1: best ASSISTANT columnassistant_candidates = []for col in assistant_potential:score = score_column(col, assistant_words, "assistant", len(assistant_potential))@@ -307,7 +295,7 @@ def detect_custom_format_heuristic(dataset):else:assistant_col = None- # STEP 2: Find best USER column (with penalty for ambiguous keywords)+ # STEP 2: best USER column (penalizing ambiguous keywords)user_candidates = []for col in user_potential:if col == assistant_col:@@ -323,35 +311,32 @@ def detect_custom_format_heuristic(dataset):else:user_col = None- # STEP 3: Check ALL remaining columns for SYSTEM matches (priority check)+ # STEP 3: check remaining columns for SYSTEM matchesremaining_columns = [col for col in content_columns if col not in mapping]system_col = Nonefor col in remaining_columns:if has_keyword(col, system_words):- # System match foundmapping[col] = "system"system_col = colbreak- # STEP 4: Handle any additional remaining columns+ # STEP 4: handle any additional remaining columnsif system_col:remaining_columns = [col for col in remaining_columns if col != system_col]if len(remaining_columns) >= 1:remaining_col = remaining_columns[0]- # No strong keyword match: decide by 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 usermapping[remaining_col] = "user"else:- # Already have user + assistant: treat as system contextmapping[remaining_col] = "system"- # Ensure we have at least user + assistant+ # Ensure at least user + assistant.has_user = any(role == "user" for role in mapping.values())has_assistant = any(role == "assistant" for role in mapping.values())@@ -371,25 +356,13 @@ def detect_custom_format_heuristic(dataset):def detect_multimodal_dataset(dataset):"""Detect multimodal data (images and/or audio) in a dataset.- Two passes per modality:- 1. Column-name heuristic (fast): keyword match.- 2. Value-type inspection (reliable): check actual sample values.-- Returns:- dict: {- "is_image": bool,- "multimodal_columns": list of column names containing image data,- "modality_types": list of detected types (e.g., ["image", "audio"]),- "is_audio": bool,- "audio_columns": list of column names containing audio data,- "detected_audio_column": str or None,- "detected_text_column": str or None,- }+ Two passes per modality: column-name keyword heuristic, then value-type+ inspection. Returns a dict with is_image/is_audio flags, detected columns,+ modality types, and detected audio/text/speaker columns."""sample = next(iter(dataset))column_names = list(sample.keys())- # Image keywordsimage_keywords = ["image","img",@@ -410,7 +383,6 @@ def detect_multimodal_dataset(dataset):"filename",]- # Audio keywordsaudio_keywords = ["audio", "speech", "wav", "waveform", "sound"]multimodal_columns = []@@ -418,8 +390,7 @@ def detect_multimodal_dataset(dataset):modality_types = set()# ── Image detection ─────────────────────────────────────- # Pass 1: column-name heuristic (word-boundary match avoids false- # positives like 'pic' in 'topic')+ # Pass 1: column-name heuristic (word-boundary match)for col_name in column_names:for keyword in image_keywords:if _keyword_in_column(keyword, col_name):@@ -456,13 +427,13 @@ def detect_multimodal_dataset(dataset):audio_columns.append(col_name)modality_types.add("audio")- # Drop audio columns 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 (a {"bytes","path"} audio column+ # can 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]- # Text column for audio datasets+ # Text column for audio datasets.detected_text_col = Noneif audio_columns:text_keywords = ["text", "sentence", "transcript", "transcription", "label"]@@ -499,7 +470,6 @@ def _is_image_value(value) -> bool:if value is None:return False- # PIL Image instancetry:from PIL.Image import Image as PILImageif isinstance(value, PILImage):@@ -513,7 +483,7 @@ def _is_image_value(value) -> bool:if "array" in value and "sampling_rate" in value:return False # audio, not imageif "bytes" in value and "path" in value:- # Use 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@@ -521,20 +491,17 @@ def _is_image_value(value) -> bool:return Falsereturn True- # Raw bytes with a known image magic headerif isinstance(value, (bytes, bytearray)):return _has_image_header(value)- # String that looks like an image file path or URL+ # String that looks like an image file path or URL._IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".svg")if isinstance(value, str) and len(value) < 1000:lower = value.strip().lower()- # Image URL (http://... ending in image extension)if lower.startswith(("http://", "https://")) and any(lower.split("?")[0].endswith(ext) for ext in _IMAGE_EXTS):return True- # Image file path (relative or absolute)if any(lower.endswith(ext) for ext in _IMAGE_EXTS):return True@@ -559,11 +526,10 @@ def _is_audio_value(value) -> bool:if value is None:return False- # HF Audio feature: decoded → {"array": np.ndarray, "sampling_rate": int}+ # HF Audio feature: decoded -> {"array", "sampling_rate"}; undecoded -> {"bytes", "path"}.if isinstance(value, dict):if "array" in value and "sampling_rate" in value:return True- # 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(@@ -578,20 +544,15 @@ def _has_image_header(data: bytes) -> bool:"""Quick magic-byte check for common image formats."""if len(data) < 4:return False- # JPEG- if data[:2] == b"\xff\xd8":+ if data[:2] == b"\xff\xd8": # JPEGreturn True- # PNG- if data[:4] == b"\x89PNG":+ if data[:4] == b"\x89PNG": # PNGreturn True- # GIF- if data[:3] == b"GIF":+ if data[:3] == b"GIF": # GIFreturn True- # WebP- if data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP":+ if data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP": # WebPreturn True- # BMP- if data[:2] == b"BM":+ if data[:2] == b"BM": # BMPreturn Truereturn False@@ -615,7 +576,6 @@ def detect_vlm_dataset_structure(dataset):column_names = set(sample.keys())- # Has messages column?if "messages" in column_names:messages = sample["messages"]@@ -665,11 +625,10 @@ def detect_vlm_dataset_structure(dataset):first_msg = chat_data[0]if not isinstance(first_msg, dict):continue- # ShareGPT (from/value) or ChatML (role/content) keys+ # ShareGPT (from/value) or ChatML (role/content).msg_text = first_msg.get("value") or first_msg.get("content")if not isinstance(msg_text, str):continue- # <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@@ -677,7 +636,7 @@ def detect_vlm_dataset_structure(dataset):)if not has_image_placeholder:continue- # Find companion image column+ # Find companion image column.image_col = Nonefor col in column_names:if col == chat_col:@@ -718,7 +677,6 @@ def detect_vlm_dataset_structure(dataset):],}- # Image keywordsimage_keywords = ["image","img",@@ -731,7 +689,6 @@ def detect_vlm_dataset_structure(dataset):"filename",]- # Text keywordstext_keywords = ["text","caption",@@ -747,11 +704,8 @@ def detect_vlm_dataset_structure(dataset):"""True if the column name looks like metadata."""col_lower = col_name.lower()- # Suffixesif any(col_lower.endswith(suffix) for suffix in metadata_patterns["suffixes"]):return True-- # Prefixesif any(col_lower.startswith(prefix) for prefix in metadata_patterns["prefixes"]):return True@@ -759,39 +713,36 @@ 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 (already loaded -> highest)+ # PIL Image (already loaded) -> highest.if hasattr(sample_value, "size") and hasattr(sample_value, "mode"):return 100- # Dict with bytes/path from HF Image feature+ # HF Image feature dict.if isinstance(sample_value, dict) and ("bytes" in sample_value or "path" in sample_value):return 75if isinstance(sample_value, str):- # URL- if sample_value.startswith(("http://", "https://")):+ if sample_value.startswith(("http://", "https://")): # URLreturn 70 if not is_metadata_column(col) else 55- # Bare file path- if is_metadata_column(col):+ if is_metadata_column(col): # bare file pathreturn 30return 50return 0def _probe_image_candidate(col, sample_value):- """Probe whether an image candidate is reachable.- True if likely valid, False if definitely broken."""+ """Probe whether an image candidate is reachable (True unless definitely broken)."""import os- # PIL / dict — already loaded, always valid+ # PIL / dict — already loaded.if not isinstance(sample_value, str):return True- # Local file — check it exists+ # Local file — check it exists.if not sample_value.startswith(("http://", "https://")):- return os.path.exists(sample_value) # bare filenames return False here, that's OK+ return os.path.exists(sample_value) # bare filenames return False, that's OK- # URL — quick HEAD with short timeout+ # URL — quick HEAD with short timeout.try:import urllib.request@@ -802,11 +753,10 @@ def detect_vlm_dataset_structure(dataset):return Falsedef find_image_column():- """Find image column by keyword match + value-based fallback,- probing candidates to find one that works."""+ """Find image column by keyword match + value-based fallback, probing for one that works."""candidates = []- # Pass 1: keyword-matched columns+ # Pass 1: keyword-matched columns.for col in column_names:if any(_keyword_in_column(keyword, col) for keyword in image_keywords):sample_value = sample[col]@@ -814,8 +764,8 @@ def detect_vlm_dataset_structure(dataset):if score > 0:candidates.append((col, score))- # Pass 2: value-based fallback — columns with image URLs/paths- # even if the name doesn't match image keywords+ # Pass 2: value-based fallback for image URLs/paths even when the name+ # doesn't match keywords.already = {c[0] for c in candidates}for col in column_names:if col in already:@@ -823,7 +773,7 @@ def detect_vlm_dataset_structure(dataset):sample_value = sample[col]if _is_image_value(sample_value):score = _score_image_candidate(col, sample_value)- # 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:@@ -831,18 +781,17 @@ def detect_vlm_dataset_structure(dataset):candidates.sort(key = lambda x: x[1], reverse = True)- # Single candidate or top 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 candidates — probe for one that 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- # None probed OK — return highest-scored and let conversion handle- # the error (it may still resolve via hf_hub_download)+ # None probed OK — return highest-scored; conversion may still resolve it.return candidates[0][0]def find_text_column():@@ -853,25 +802,22 @@ def detect_vlm_dataset_structure(dataset):if is_metadata_column(col):continue- # Text keyword (word-boundary match)if any(_keyword_in_column(keyword, col) for keyword in text_keywords):- # Verify it's actually textsample_value = sample[col]if isinstance(sample_value, str) and len(sample_value) > 0:- # Longer text = higher priority (content, not 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)candidates.append((col, priority))elif (isinstance(sample_value, list)and len(sample_value) > 0and isinstance(sample_value[0], str)):- # List of strings (e.g. captions) — lower priority than plain str+ # List of strings (e.g. captions) — lower priority than plain str.priority = min(len(sample_value[0]), 1000) // 2candidates.append((col, priority))- # Highest-priority candidateif 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.pyindex d6bb0dc91d0..f7b35e28697 100644--- a/studio/backend/utils/datasets/llm_assist.py+++ b/studio/backend/utils/datasets/llm_assist.py@@ -1,16 +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-"""-LLM-assisted dataset analysis using an ephemeral GGUF helper model.--Complements heuristic detection in format_detection.py and vlm_processing.py.-Only invoked when heuristics are uncertain.+"""LLM-assisted dataset analysis using an ephemeral GGUF helper model.-Architecture:- - Instantiates LlamaCppBackend, loads model, runs completion(s), unloads.- - Not kept warm — VRAM is freed immediately after use.- - Degrades gracefully: returns None when unavailable (no binary, OOM, disabled).+Complements heuristic detection (format_detection.py, vlm_processing.py); only+invoked when heuristics are uncertain. Loads LlamaCppBackend, runs completion(s),+unloads (VRAM freed immediately). Degrades gracefully to None when unavailable."""import json@@ -33,21 +28,15 @@ README_MAX_CHARS = 1500def _strip_think_tags(text: str) -> str:- """Strip <think>...</think> reasoning blocks emitted by some models.-- 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.- """+ """Strip <think>...</think> blocks, keeping content outside; if all inside, return the inner."""if "<think>" not in text:return text- # Strip think blocks — keep content outside themstripped = re.sub(r"<think>.*?</think>\s*", "", text, flags = re.DOTALL).strip()if stripped:return stripped- # Everything was inside <think> tags — return the last block's inner content+ # 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()@@ -56,12 +45,9 @@ def _strip_think_tags(text: str) -> str:def precache_helper_gguf():- """- Pre-download the helper GGUF to HF cache.+ """Pre-download the helper GGUF to HF cache (on startup, background thread).- 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.+ Lets later ``_run_with_helper()`` calls skip the download. No-op if cached or disabled."""if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):return@@ -76,12 +62,11 @@ def precache_helper_gguf():disable_progress_bars()logging.getLogger("huggingface_hub").setLevel(logging.WARNING)- # Find the GGUF file matching the variantapi = HfApi()files = api.list_repo_files(repo, repo_type = "model")gguf_files = [f for f in files if f.endswith(".gguf")]- # All GGUF files matching the variant (may be split into shards)+ # 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("-", "_"))@@ -105,11 +90,7 @@ def precache_helper_gguf():def _run_with_helper(prompt: str, max_tokens: int = 256) -> Optional[str]:- """- Load helper model, run one chat completion, unload.-- Returns the completion text, or None on any failure.- """+ """Load helper model, run one chat completion, unload. Returns text or None on failure."""if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):return None@@ -149,7 +130,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 # last value is full textresult = cumulative.strip()result = _strip_think_tags(result)@@ -177,21 +158,10 @@ def llm_generate_vlm_instruction(samples: list[dict],dataset_name: Optional[str] = None,) -> Optional[dict]:- """- Ask a helper LLM to generate a task-specific VLM instruction.+ """Ask a helper LLM for a task-specific VLM instruction (when heuristics are low-confidence).- Called when heuristic instruction generation returns low confidence or- falls back to generic.-- Args:- column_names: Column names in the dataset.- samples: 3-5 sample rows with text values (images replaced by "<image>").- dataset_name: Optional HF dataset identifier for context.-- Returns:- {"instruction": str, "confidence": 0.85} or None.+ Returns {"instruction": str, "confidence": 0.85} or None."""- # Format samples for the promptformatted = ""for i, row in enumerate(samples[:5], 1):parts = []@@ -217,9 +187,8 @@ def llm_generate_vlm_instruction(if not result:return None- # Strip quotes; ensure a single sentenceinstruction = result.strip().strip('"').strip("'").strip()- # Reject 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@@ -232,17 +201,9 @@ def llm_generate_vlm_instruction(def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Optional[dict[str, str]]:- """- Ask a helper LLM to classify dataset columns into roles.+ """Ask a helper LLM to classify columns into roles (when heuristic detection fails).- Called when heuristic column detection fails (returns None).-- Args:- column_names: Column names in the dataset.- samples: 3-5 sample rows with values truncated to 200 chars.-- Returns:- Dict mapping column_name → role ("user"|"assistant"|"system"|"metadata"), or None.+ Returns {column_name: role} for roles user|assistant|system|metadata, or None."""formatted = ""for i, row in enumerate(samples[:5], 1):@@ -268,10 +229,9 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Optionif not result:return None- # Parse JSON from response (may have markdown fences)+ # Parse JSON from response (may have markdown fences).text = result.strip()if text.startswith("```"):- # Strip markdown code fencelines = text.split("\n")text = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])text = text.strip()@@ -279,7 +239,6 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Optiontry:mapping = json.loads(text)except json.JSONDecodeError:- # Find a JSON object in the responseimport rematch = re.search(r"\{[^}]+\}", text)if match:@@ -295,7 +254,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Optionif not isinstance(mapping, dict):return None- # Validate: all values must be valid roles+ # Keep only valid roles.valid_roles = {"user", "assistant", "system", "metadata"}cleaned = {}for col, role in mapping.items():@@ -305,7 +264,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Optionif not cleaned:return None- # Must have at least user + assistant+ # Must have at least user + assistant.roles_present = set(cleaned.values())if "user" not in roles_present or "assistant" not in roles_present:logger.warning(f"Helper model mapping missing user/assistant: {cleaned}")@@ -321,19 +280,9 @@ def llm_generate_dataset_warning(modality: str = "text",column_names: Optional[list[str]] = None,) -> Optional[str]:- """- Ask the helper LLM to turn technical dataset issues into a friendly warning.+ """Ask the helper LLM to turn technical dataset issues into a friendly warning (any modality).- Works for all modalities (text, vision, audio).-- Args:- issues: List of technical issue descriptions found during analysis.- dataset_name: Optional HF dataset name.- modality: "text", "vision", or "audio".- column_names: Optional list of column names for context.-- Returns:- A human-friendly warning string, or None on failure.+ Returns a human-friendly warning string, or None on failure."""if not issues:return None@@ -357,7 +306,6 @@ def llm_generate_dataset_warning(return Nonewarning = result.strip()- # Reject bad outputsif len(warning) < 10 or len(warning) > 500:return None@@ -417,7 +365,7 @@ def _generate_with_backend(top_k = 20,max_tokens = max_tokens,repetition_penalty = 1.0,- enable_thinking = False, # Always disable thinking for AI Assist+ enable_thinking = False, # disable thinking for AI Assist):if isinstance(chunk, dict):continue # skip metadata events@@ -430,12 +378,7 @@ def _generate_with_backend(def fetch_hf_dataset_card(dataset_name: str, hf_token: Optional[str] = None) -> tuple[Optional[str], Optional[dict]]:- """- Fetch HF dataset card (README) and metadata.-- Returns:- (readme_text, metadata_dict) or (None, None) on failure.- """+ """Fetch HF dataset card (README) and metadata. Returns (readme, metadata) or (None, None)."""try:from huggingface_hub import DatasetCard@@ -450,7 +393,7 @@ def fetch_hf_dataset_card(else:readme = readme[:README_MAX_CHARS] + "\n[...truncated]"- # Extract metadata from YAML frontmatter+ # Extract metadata from YAML frontmatter.metadata = {}if card.data:for key in (@@ -484,10 +427,9 @@ def _run_multi_pass_advisor(model_type: Optional[str] = None,hf_token: Optional[str] = None,) -> Optional[dict[str, Any]]:- """- Multi-pass LLM analysis: classify → convert → validate.+ """Multi-pass LLM analysis (classify -> convert -> validate), model loaded across passes.- Keeps the model loaded across passes. Returns combined result dict or None.+ Returns combined result dict or None."""if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):return None@@ -617,7 +559,7 @@ def _run_multi_pass_advisor(logger.warning(f"Advisor Pass 1 failed to produce JSON: {raw1[:200]}")return None- # 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,@@ -726,7 +668,7 @@ def _run_multi_pass_advisor(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}")- return None # triggers fallback to simple classification+ return None # falls back to simple classification# ── Pass 3: System prompt (non-conversational datasets only) ──sys_prompt = ""@@ -737,7 +679,7 @@ def _run_multi_pass_advisor(logger.info("Pass 3: Generating system prompt...")t3 = time.monotonic()- # Format label mapping for the prompt+ # Format label mapping for the prompt.label_info = ""if label_map:for col, mapping in label_map.items():@@ -745,7 +687,6 @@ def _run_multi_pass_advisor(pairs = ", ".join(f"{k} = {v}" for k, v in mapping.items())label_info += f"\nLabel mapping for '{col}': {pairs}"- # Describe the role assignments for contextuser_cols = [c for c, r in column_roles.items() if r == "user"]asst_cols = [c for c, r in column_roles.items() if r == "assistant"]task_desc = pass1.get("task_description") or pass1.get("description", "")@@ -780,18 +721,18 @@ def _run_multi_pass_advisor()if raw3:- # Pass 3 returns raw text, not JSON — clean it+ # Pass 3 returns raw text, not JSON.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"):suggested_mapping[col] = role- # Build user notification from Pass 1 classification+ # Build user notification from Pass 1 classification.desc = pass1.get("task_description") or pass1.get("description", "")note_parts = [f"This is a {dtype} dataset (not conversational)."]if desc:@@ -837,23 +778,18 @@ def llm_conversion_advisor(model_name: Optional[str] = None,model_type: Optional[str] = None,) -> Optional[dict[str, Any]]:- """- Full conversion advisor: fetch HF card → multi-pass LLM analysis.+ """Full conversion advisor: fetch HF card -> multi-pass LLM analysis.Falls back to simple llm_classify_columns() if the multi-pass advisor fails.-- Returns:- Dict with keys: success, suggested_mapping, system_prompt, user_template,- assistant_template, label_mapping, dataset_type, is_conversational,- user_notification. Or None on complete failure.+ Returns a result dict (success, suggested_mapping, system_prompt, label_mapping,+ dataset_type, is_conversational, user_notification, ...) or None."""- # Fetch HF dataset card if this looks like a HF dataset (has a slash)+ # Fetch HF dataset card if this looks like a HF dataset (has a slash).dataset_card = Nonedataset_metadata = Noneif dataset_name and "/" in dataset_name:dataset_card, dataset_metadata = fetch_hf_dataset_card(dataset_name, hf_token)- # Try the multi-pass advisorresult = _run_multi_pass_advisor(columns = column_names,samples = samples,@@ -869,7 +805,7 @@ def llm_conversion_advisor(logger.info(f"Conversion advisor succeeded: type={result.get('dataset_type')}")return result- # Fallback: simple column classification+ # Fallback: simple column classification.logger.info("Advisor failed, falling back to simple column classification")simple_mapping = llm_classify_columns(column_names, samples)if simple_mapping:diff --git a/studio/backend/utils/datasets/model_mappings.py b/studio/backend/utils/datasets/model_mappings.pyindex b550dc81bd8..463d26a692b 100644--- a/studio/backend/utils/datasets/model_mappings.py+++ b/studio/backend/utils/datasets/model_mappings.py@@ -434,7 +434,7 @@ for key, values in TEMPLATE_TO_MODEL_MAPPER.items():for value in values:MODEL_TO_TEMPLATE_MAPPER[value] = key- # Get lowercased+ # Also map lowercased names.lowered_key = key.lower()for value in values:MODEL_TO_TEMPLATE_MAPPER[value.lower()] = lowered_keydiff --git a/studio/backend/utils/datasets/raw_text.py b/studio/backend/utils/datasets/raw_text.pyindex 86b1963fc12..03315fb2870 100644--- a/studio/backend/utils/datasets/raw_text.py+++ b/studio/backend/utils/datasets/raw_text.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-"""-Shared helpers for raw-text dataset preparation.-"""+"""Shared helpers for raw-text dataset preparation."""from dataclasses import dataclassfrom typing import Literaldiff --git a/studio/backend/utils/datasets/vlm_processing.py b/studio/backend/utils/datasets/vlm_processing.pyindex 4919b8884d0..f018913fa8a 100644--- a/studio/backend/utils/datasets/vlm_processing.py+++ b/studio/backend/utils/datasets/vlm_processing.py@@ -58,7 +58,6 @@ def generate_smart_vlm_instruction(# ===== LEVEL 2: Infer from Column Names + Content =====text_col_lower = text_column.lower()- # Sample text content for pattern detectiontext_sample = str(sample.get(text_column, ""))[:500] # First 500 chars# Task-specific keywords and their instructions@@ -66,7 +65,7 @@ def generate_smart_vlm_instruction(# OCR / Transcription"ocr": {"keywords": ["ocr", "transcribe", "transcript"],- "content_hints": [r"[A-Za-z\u0600-\u06FF]{10,}"], # Long text passages (Latin/Arabic)+ "content_hints": [r"[A-Za-z\u0600-\u06FF]{10,}"], # Long Latin/Arabic passages"instruction": "Transcribe all the text shown in this image.","confidence": 0.9,},@@ -129,17 +128,14 @@ def generate_smart_vlm_instruction(for task_name, task_info in task_patterns.items():score = 0.0- # Column nameif any(keyword in text_col_lower for keyword in task_info["keywords"]):score += 0.5- # Dataset name if providedif dataset_name and any(keyword in dataset_name.lower() for keyword in task_info["keywords"]):score += 0.3- # Content patternsfor pattern in task_info["content_hints"]:if re.search(pattern, text_sample, re.IGNORECASE):score += 0.4diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.pyindex 7ccba6315e1..5f2b2abbcf0 100644--- a/studio/backend/utils/hardware/__init__.py+++ b/studio/backend/utils/hardware/__init__.py@@ -84,8 +84,8 @@ __all__ = [def __getattr__(name: str):- """Resolve IS_ROCM at access time so callers see the live value after- detect_hardware() runs (it flips the flag in hardware.py)."""+ """Resolve IS_ROCM lazily so callers see the live value detect_hardware()+ sets 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.pyindex 41ee9f3fbeb..39aafe04895 100644--- a/studio/backend/utils/hardware/amd.py+++ b/studio/backend/utils/hardware/amd.py@@ -26,9 +26,8 @@ logger = get_logger(__name__)# 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, stop polling it.+# Circuit breaker: stop polling amd-smi after this many consecutive failures+# (each Windows failure may pop a UAC/DiskPart elevation prompt)._AMD_SMI_FAILURE_LIMIT = 3_amd_smi_consecutive_failures = 0_amd_smi_disabled = False@@ -50,8 +49,8 @@ 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.+ # amd-smi ships with Adrenalin, not the HIP SDK; absence is expected+ # on HIP SDK-only Windows setups.logger.debug("amd-smi not found (not in PATH): %s", e)else:logger.warning("amd-smi query failed: %s", e)@@ -74,9 +73,8 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona_amd_smi_disabled = Truereturn Noneif not result.stdout.strip():- # 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.+ # Exit 0 with no output (no GPUs visible, or a version emitting nothing+ # for --json). Not a tool failure, so don't trip the circuit breaker.logger.debug("amd-smi exited 0 but returned no output")return None_amd_smi_consecutive_failures = 0 # reset on success@@ -132,8 +130,8 @@ def _parse_memory_mb(value: Any) -> Optional[float]:if num is None:return None- # 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.+ # GPU tools use binary units even when labeled "GB"/"MB", so treat GB/GiB+ # and MB/MiB the same.if "gib" in unit or "gb" in unit:return num * 1024if "mib" in unit or "mb" in unit:@@ -144,12 +142,9 @@ def _parse_memory_mb(value: Any) -> Optional[float]:# Plain bytesreturn num / (1024 * 1024)- # 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.+ # No explicit unit: default to MB (the amd-smi convention for bare numbers).+ # A bytes-above-~10M heuristic was dropped because it misclassified small+ # VRAM allocations; modern amd-smi always ships explicit units.return num@@ -162,9 +157,8 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:else:gpu_util = _parse_numeric(usage)- # 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.+ # Temperature: try keys in priority order, checking each parses to a real+ # number (dict.get() can return "N/A" strings rather than falling through).temp_data = gpu_data.get("temperature", {})temp = Noneif isinstance(temp_data, dict):@@ -189,10 +183,9 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:power_draw = Nonepower_limit = None- # 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: unit-aware parsing across amd-smi formats. Newer versions use+ # "mem_usage" with "total_vram"/"used_vram"; older 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", {})),@@ -235,12 +228,11 @@ 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.+ """Return True when ``metrics`` has at least one non-None value.- ``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.+ amd-smi can return a zero-exit envelope missing every field (error,+ unsupported card, hipless container), yielding an all-None dict; callers must+ surface that as ``available: False``."""return any(value is not None for value in metrics.values())@@ -252,9 +244,8 @@ def get_physical_gpu_count() -> Optional[int]:return Noneif isinstance(data, list):return len(data)- # Some versions return a dict with a "gpu" / "gpus" key. Guard .get()- # with isinstance so a malformed scalar/string response cannot raise- # AttributeError.+ # Some versions return a dict with a "gpu"/"gpus" key; guard with isinstance+ # so a malformed scalar/string response can't raise AttributeError.if not isinstance(data, dict):return Nonegpus = data.get("gpu", data.get("gpus", []))@@ -282,10 +273,8 @@ def _first_visible_amd_gpu_id() -> Optional[str]:raw = raw.strip()if raw == "" or raw == "-1":return None- # 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. ``,,,``).+ # Drop empty tokens, tolerating typos like ``",1"`` while still falling+ # through to the next env var when every token is empty (``,,,``).tokens = [t.strip() for t in raw.split(",") if t.strip()]if tokens:return tokens[0]@@ -316,9 +305,8 @@ def get_primary_gpu_utilization() -> dict[str, Any]:metrics = _extract_gpu_metrics(gpu_data)if not _has_real_metrics(metrics):- # 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.+ # Envelope with no usable fields: surface as unavailable so the UI+ # doesn't render a ghost device.return {"available": False}metrics["available"] = Truereturn metrics@@ -347,14 +335,11 @@ 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 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.+ # Extract a device list across envelope shapes: a JSON array, a dict under+ # "gpu_data"/"gpus"/"gpu", or a guarded scalar/string fallback.if isinstance(data, list):gpu_list = dataelif isinstance(data, dict):- # Newer amd-smi wraps output in {"gpu_data": [...]}gpu_list = data.get("gpu_data", data.get("gpus", data.get("gpu", [data])))else:gpu_list = [data]@@ -363,15 +348,11 @@ def get_visible_gpu_utilization(devices = []for fallback_idx, gpu_data in enumerate(gpu_list):- # 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.+ # Skip non-dict entries (a scalar in the array would raise AttributeError).if not isinstance(gpu_data, dict):continue- # 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.+ # Use the AMD-reported GPU ID, else the enumeration index. _parse_numeric+ # handles bare ints/floats/strings and the {"value", "unit"} dict shape.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:@@ -395,9 +376,8 @@ def get_visible_gpu_utilization(continuemetrics = _extract_gpu_metrics(gpu_data)if not _has_real_metrics(metrics):- # 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.+ # Skip ghost entries (no usable fields) so the UI doesn't show an+ # all-None device row.continuemetrics["index"] = idxmetrics["index_kind"] = "physical"diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex df3fbac47a6..7292fa185fd 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -57,11 +57,8 @@ IS_ROCM: bool = False # True when running on AMD ROCm (HIP) -- routes GPU monitdef _backend_label(device: DeviceType) -> str:"""Return the user-facing backend name for API responses.- 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.+ ROCm hosts stay ``DeviceType.CUDA`` internally (ROCm reuses ``torch.cuda.*``),+ but "cuda" is misleading in JSON, so swap to ``"rocm"`` when ``IS_ROCM`` is set."""if IS_ROCM and device == DeviceType.CUDA:return "rocm"@@ -117,10 +114,8 @@ def detect_hardware() -> DeviceType:CHAT_ONLY = Falsedevice_name = torch.cuda.get_device_properties(0).name- # 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)- # don't set torch.version.hip, so fall back to __version__.+ # Distinguish ROCm from CUDA for display only (DeviceType stays CUDA).+ # AMD SDK wheels 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@@ -144,9 +139,8 @@ def detect_hardware() -> DeviceType:if is_apple_silicon() and _has_mlx():DEVICE = DeviceType.MLXCHAT_ONLY = False- # 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.+ # Use platform.machine() ("arm64"); platform.processor() returns "i386"+ # on universal2 / Rosetta builds even on native arm64.chip = platform.machine() or "arm64"print(f"Hardware detected: MLX — Apple Silicon ({chip})")return DEVICE@@ -191,8 +185,7 @@ def clear_gpu_cache():torch.xpu.synchronize()torch.xpu.empty_cache()elif device == DeviceType.MLX:- # MLX manages memory automatically; no empty_cache equivalent,- # so the gc.collect() above is enough.+ # MLX manages memory automatically; gc.collect() above is enough.pass@@ -271,16 +264,14 @@ def get_gpu_memory_info() -> Dict[str, Any]:import mlx.core as mximport psutil- # MLX uses unified memory: total = system RAM, GPU used comes- # from IORegistry's AGXAccelerator (system-wide, no sudo).+ # Unified memory: total = system RAM, GPU used from IORegistry AGX.total = psutil.virtual_memory().totalagx = _read_apple_gpu_stats()allocated = agx.get("vram_used_bytes", 0) if agx else 0try:info = mx.device_info()- # See detect_hardware(): platform.processor() can return "i386"- # on native arm64 builds, so prefer machine() as fallback.+ # prefer machine(); processor() can return "i386" on native arm64.gpu_name = info.get("device_name") or platform.machine() or "arm64"except Exception:gpu_name = platform.machine() or "arm64"@@ -409,11 +400,10 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]devices = []for ordinal, phys_idx in enumerate(device_indices):try:- # torch uses 0-based ordinals relative to CUDA_VISIBLE_DEVICES+ # torch ordinals are 0-based relative to CUDA_VISIBLE_DEVICES.props = mod.get_device_properties(ordinal)total_bytes = props.total_memory- # Prefer mem_get_info (system-wide usage, not just this process)- # so auto-selection accounts for other GPU consumers.+ # Prefer mem_get_info (system-wide) so auto-select sees other consumers.if hasattr(mod, "mem_get_info"):free_bytes, total_bytes = mod.mem_get_info(ordinal)used_bytes = total_bytes - free_bytes@@ -631,13 +621,11 @@ def get_gpu_utilization() -> Dict[str, Any]:if result is not None:result["backend"] = _backend_label(device)if IS_ROCM:- # Fix unified-memory VRAM on AMD iGPUs (Strix Halo etc.)+ # 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 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 can't see from the Studio server process.+ # SMI unavailable. On Windows, use Performance Counters (Task Manager+ # source) for system-wide VRAM, covering cross-process usage torch can't see.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:@@ -699,8 +687,7 @@ def get_gpu_utilization() -> Dict[str, Any]:"power_utilization_pct": None,}- # MLX path: one _read_apple_gpu_stats() call carries both VRAM-used bytes- # and GPU utilization %. psutil for unified-memory total is cheap.+ # MLX: _read_apple_gpu_stats() carries both VRAM-used and GPU util%.if device == DeviceType.MLX:try:import psutil@@ -790,9 +777,8 @@ def _apply_unified_memory_correction(def _reconcile_rocm_unified_memory(utilization: Dict[str, Any], device_indices: list[int]) -> None:"""Fix amd-smi VRAM for ROCm unified-memory GPUs (e.g. Strix Halo).- 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 real available memory.+ amd-smi reports only the dedicated slice; torch sees the full GTT pool. When+ torch total > smi total, overwrite per-device VRAM fields with the real value."""torch_devices = _torch_get_per_device_info(device_indices)if not torch_devices:@@ -814,9 +800,8 @@ 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 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.+ # Empty mask: no GPU visible. Querying torch device 0 would raise or+ # return stale data, so bail rather than write bad values.returnelse:primary_idx = [int(numeric_ids[0])]@@ -840,15 +825,14 @@ def get_visible_gpu_utilization() -> Dict[str, Any]:result["backend"] = _backend_label(device)numeric_ids = parent_visible_spec.get("numeric_ids")if IS_ROCM and numeric_ids is not None:- # Fix unified-memory VRAM on AMD iGPUs (Strix Halo etc.)+ # Fix unified-memory VRAM on AMD iGPUs (Strix Halo etc.)._reconcile_rocm_unified_memory(result, numeric_ids)return result# Torch-based fallback for CUDA (nvidia-smi unavailable, AMD ROCm) and XPU (Intel)if device in (DeviceType.CUDA, DeviceType.XPU):parent_ids = get_parent_visible_gpu_ids()- # When parent_visible_ids is empty (UUID/MIG mask or no CVD set),- # enumerate torch-visible ordinals so the UI still shows devices.+ # Empty parent_ids (UUID/MIG mask or no CVD): enumerate torch ordinals.if parent_ids:torch_indices = parent_idsindex_kind = "physical"@@ -935,13 +919,10 @@ _visible_gpu_count: Optional[int] = Nonedef _get_parent_visible_gpu_spec() -> Dict[str, Any]:- # 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.+ # ROCm uses HIP/ROCR_VISIBLE_DEVICES on top of CUDA_VISIBLE_DEVICES; check+ # them first. Explicit None checks (not `or`) so "" reads as "no visible GPUs".cuda_visible = None- # Prefer ROCm masks only on a ROCm host, or when no CUDA mask is set, so a+ # Prefer ROCm masks only on a ROCm host or when no CUDA mask is set, so a# 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@@ -1028,15 +1009,13 @@ 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 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.+ # Only enforce the physical upper bound when the count is reliable (nvidia-smi).+ # A torch count reflects only visible devices, so it could falsely reject valid+ # physical indices. 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:- # Count is plausibly physical (not just visible), so enforce it+ # Count is plausibly physical, so enforce it.out_of_range = [gpu_id for gpu_id in requested_ids if gpu_id >= physical_gpu_count]if out_of_range:raise ValueError(@@ -1115,13 +1094,11 @@ def _load_config_for_gpu_estimate(model_name: str, hf_token: Optional[str] = Nondef _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 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.+ # torch.distributed is incomplete on Windows ROCm (torch._C._distributed_c10d+ # can't be imported). Inject stubs into sys.modules before importing+ # torch.distributed, then patch the missing process-group helpers.if sys.platform == "win32" and IS_ROCM:- # Dummy for any name torch.distributed imports from these stubs+ # Dummy for any name torch.distributed imports from these stubs.class _Dummy:pass@@ -1132,8 +1109,7 @@ def _determine_attention_impl_for_gpu_estimate(config) -> str:):if _c10d_name not in sys.modules:_stub = types.ModuleType(_c10d_name)- # torch.distributed imports these names from _distributed_c10d;- # provide no-op dummies so the import doesn't raise AttributeError.+ # No-op dummies for names torch.distributed imports from _distributed_c10d.for _sym in ("FakeProcessGroup","ProcessGroup",@@ -1169,11 +1145,9 @@ def _determine_attention_impl_for_gpu_estimate(config) -> str:from unsloth.models._utils import resolve_attention_implementationfrom transformers import AutoModel, AutoModelForCausalLM- # 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 would still mutate those shared inner objects on the cached- # config from _load_config_for_gpu_estimate. Deepcopy isolates them.+ # why: resolve_attention_implementation writes _attn_implementation onto the+ # config and propagates to nested sub-configs; a shallow copy would still+ # mutate the cached config's shared inner objects. Deepcopy isolates them.config_copy = copy.deepcopy(config)model_class = None@@ -1349,31 +1323,29 @@ def estimate_required_model_memory_gb(config)except Exception as e:- # 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.+ # Debug-level: fires every estimate on Windows ROCm (stub lacks Store);+ # expected and non-actionable -- eager is the safe fallback.logger.debug("Could not resolve attention implementation for '%s': %s",estimate_model,e,)- # why: if flash attention can't be proven usable, charge the- # quadratic non-flash activation path so GPU selection stays- # conservative.+ # why: charge the quadratic non-flash activation path so GPU+ # selection stays conservative when flash attn isn't proven usable.vram_config.attention_implementation = "eager"arch = extract_arch_config(config) if config is not None else Noneif 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 the text-arch fp16 total misses.+ # why: extract_arch_config only sees text_config; add the vision/audio+ # tower bytes that the text-arch fp16 total misses.arch_fp16_bytes = compute_total_params(arch) * 2extra_bytes = max(0, int(model_size_bytes) - arch_fp16_bytes)if extra_bytes > 0:breakdown.model_weights += extra_bytesif training_method == "full":- # why: full fine-tuning makes the extra (vision/audio) params- # trainable; optimizer + gradient bytes scale with them.+ # why: full fine-tuning makes extra params trainable; optimizer ++ # gradient bytes scale with them.extra_params = extra_bytes // 2breakdown.optimizer_states += compute_optimizer_bytes(extra_params,@@ -1392,7 +1364,7 @@ def estimate_required_model_memory_gb()return required_gb, metadata- # Fallback when model config is unavailable+ # Fallback when model config is unavailable.overhead_gb = CUDA_OVERHEAD_BYTES / (1024**3)if training_method == "full":required_gb = model_size_gb * 3.5 + overhead_gb@@ -1452,8 +1424,7 @@ def auto_select_gpu_ids(return None, metadataif required_gb is None:- # Cannot estimate model size -- fall back to all visible GPUs rather- # than risk loading on a single GPU that may lack memory.+ # Can't estimate size -- use all visible GPUs rather than risk one too small.parent_ids = get_parent_visible_gpu_ids()metadata["selection_mode"] = "fallback_all"metadata["selected_gpu_ids"] = parent_ids@@ -1491,16 +1462,13 @@ 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 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.+ # Sharding has inter-GPU overhead, so each extra GPU contributes less than+ # its raw free memory (first GPU keeps full capacity). 0.85 is empirical on+ # 2-8 GPU setups: covers NCCL buffers, pipeline bubbles, fragmentation.multi_gpu_overhead = 0.85- # Per-GPU check: activations don't shard, so each GPU needs its weight- # shard + full activation cost. Uses precomputed min_per_gpu_N values.+ # Per-GPU check: activations don't shard, so each GPU needs its weight shard+ # + full activation cost. Uses precomputed min_per_gpu_N values.vram_breakdown = estimate_metadata.get("vram_breakdown", {})for candidate in ranked:@@ -1537,7 +1505,7 @@ def auto_select_gpu_ids()return selected, metadata- # Use only GPUs with verified VRAM data (gpu_candidates, not raw devices)+ # Use only GPUs with verified VRAM data.fallback_all = [c["index"] for c in gpu_candidates] if gpu_candidates else parent_idsmetadata["selection_mode"] = "fallback_all"if ranked:@@ -1642,7 +1610,7 @@ def get_physical_gpu_count() -> int:return _physical_gpu_countexcept Exception:pass- # SMI tool unavailable or failed -- fall back to torch+ # SMI unavailable -- fall back to torch.count = _torch_get_physical_gpu_count()_physical_gpu_count = count if count is not None else 1return _physical_gpu_count@@ -1678,7 +1646,7 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:device = get_device()if device in (DeviceType.CUDA, DeviceType.XPU):parent_visible_ids = get_parent_visible_gpu_ids()- # Try native SMI tool first (nvidia-smi for NVIDIA, skipped for ROCm)+ # Try native SMI first (nvidia-smi; skipped for ROCm).if device == DeviceType.CUDA and not IS_ROCM:try:from . import nvidia@@ -1694,9 +1662,8 @@ 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).- # When parent_visible_ids is empty (UUID/MIG mask), enumerate by- # torch ordinal so the UI still shows devices.+ # Torch fallback (ROCm, XPU, nvidia-smi missing). Empty parent_visible_ids+ # (UUID/MIG mask) -> enumerate by torch ordinal so the UI shows devices.if parent_visible_ids:torch_indices = parent_visible_idsindex_kind = "physical"@@ -1814,9 +1781,8 @@ def apply_gpu_ids(gpu_ids) -> None:if gpu_ids is None:return- # 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.+ # Empty list -> treat like None (inherit parent); setting CUDA_VISIBLE_DEVICES=""+ # disables CUDA entirely and crashes downstream torch calls.if isinstance(gpu_ids, (list, tuple)) and len(gpu_ids) == 0:return@@ -1828,23 +1794,16 @@ def apply_gpu_ids(gpu_ids) -> None:value = str(gpu_ids)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. 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.+ # Keep ROCm visibility env vars in sync. Workers may call apply_gpu_ids()+ # before detect_hardware() (IS_ROCM still False), so also mirror when the+ # parent set a ROCm visibility var, with a torch.version.hip probe fallback._inherits_rocm_visibility = ("HIP_VISIBLE_DEVICES" in os.environ or "ROCR_VISIBLE_DEVICES" in os.environ)_is_rocm = IS_ROCM or _inherits_rocm_visibilityif not _is_rocm:- # torch.version.hip is a non-empty string on ROCm, None on CUDA.- # 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.+ # torch.version.hip is set on ROCm, None on CUDA; AMD SDK wheels may leave+ # it unset but encode "rocm" in __version__. Broad except: never crash a worker.try:import torch as _torch_is_rocm = (@@ -1887,8 +1846,8 @@ def get_device_map(gpu_ids: Optional[list[int]] = None) -> str:multi_gpu = gpu_ids is not None and len(gpu_ids) > 1if not multi_gpu:- # UUID/MIG masks can't be split into numeric IDs, so if multiple- # GPUs are visible we assume multi-GPU sharding is intended.+ # UUID/MIG masks can't be split into numeric IDs; >1 visible GPU+ # means 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:multi_gpu = Truediff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.pyindex b8f307df9ed..f98ca4343e5 100644--- a/studio/backend/utils/hardware/nvidia.py+++ b/studio/backend/utils/hardware/nvidia.py@@ -110,9 +110,8 @@ 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]:- # 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.+ # parent_visible_ids None (UUID/MIG mask): can't map nvidia-smi rows to+ # visible devices, so return empty rather than exposing all physical GPUs.if parent_visible_ids is None:return {"available": False,@@ -196,8 +195,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]:- # parent_visible_ids None (UUID/MIG mask): can't safely map- # nvidia-smi rows to visible devices.+ # parent_visible_ids None (UUID/MIG mask): can't map nvidia-smi rows to+ # visible devices.if parent_visible_ids is None:return {"available": False,diff --git a/studio/backend/utils/hardware/vram_estimation.py b/studio/backend/utils/hardware/vram_estimation.pyindex 51903e0c97c..86069ead3d3 100644--- a/studio/backend/utils/hardware/vram_estimation.py+++ b/studio/backend/utils/hardware/vram_estimation.py@@ -59,8 +59,7 @@ OPTIMIZER_BYTES_PER_PARAM: Dict[str, int] = {}# (full_ft_multiplier, lora_multiplier) — fraction of num_layers.-# LoRA: frozen base layers skip activation storage, but ~1 layer is always-# in flight during backprop recomputation.+# LoRA: frozen layers skip activation storage, but ~1 is in flight during backprop.GC_LAYER_MULTIPLIERS = {"none": (None, None),"true": (2.0, 1.0),@@ -181,8 +180,7 @@ 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."""# 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.+ # prefer per-position `mlp_layer_types` over prefix `first_k_dense_replace`.layer_types = getattr(text_config, "mlp_layer_types", None)if layer_types:return tuple(@@ -197,10 +195,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)- # 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).+ # ERNIE 4.5 (VL) MoE: layers via moe_layer_start/end_index + interval;+ # per-layer guard `(layer_idx+1) % interval == 0` within [start, 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)if moe_start is not None and moe_interval is not None and int(moe_interval) > 0:@@ -296,9 +293,8 @@ 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- # 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.+ # DBRX moe_top_k; Hunyuan-V1-MoE moe_topk (may be a per-layer list).+ # _max_scalar normalizes lists to the worst case so int(...) can't crash.num_experts_per_tok = (_max_scalar(_moe_attr("num_experts_per_tok"))or _max_scalar(_moe_attr("top_k_experts"))@@ -312,9 +308,8 @@ 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)- # Llama4 dense layers use intermediate_size_mlp; routed/shared experts use- # intermediate_size. Llama4TextMoe builds one shared_expert per MoE layer- # (modeling_llama4.py).+ # Llama4 dense layers use intermediate_size_mlp; experts use+ # intermediate_size. 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@@ -458,10 +453,8 @@ def _per_layer_input_norm_elements(arch: ModelArchConfig) -> int:def _per_layer_input_lora_params(arch: ModelArchConfig, r: int, target_modules) -> int:- # 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.+ # get_peft_regex requires a component tag (mlp/attn/...); PLE names lack+ # one, so all-linear skips them. Count PLE LoRA only when named explicitly.pli = arch.hidden_size_per_layer_inputif pli <= 0:return 0@@ -541,18 +534,16 @@ def _module_path_matches(skip_module: str, alias: str) -> bool:if alias_parts[0] == "layers":return skip_parts == alias_partsif len(skip_parts) <= len(alias_parts):- # 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.+ # BNB suffix-matches short skip entries (["q_proj"], ["lm_head"]) so a+ # skip shorter than the alias is a tail match.return alias_parts[-len(skip_parts) :] == skip_partsif skip_parts[-len(alias_parts) :] != alias_parts:return Falseprefix_parts = skip_parts[: len(skip_parts) - len(alias_parts)]if not prefix_parts:return True- # 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.+ # Bound the prefix to text-tower roots so VLM skips like+ # vision_tower.model.layers... don't shadow the text alias.return ".".join(prefix_parts) in _SKIP_MODULE_TEXT_PREFIXES@@ -585,9 +576,8 @@ 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:- # _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.+ # MLA splits q/o into q_a/q_b/kv_a/kv_b; 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():@@ -605,17 +595,13 @@ 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:- # 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.+ # Qwen3.5-MoE: mlp.shared_expert; Exaone-MoE/Laguna/GLM:+ # mlp.shared_experts. Register both so skip_modules match.layer_modules["mlp.shared_expert"] = shared_moeif arch.moe_has_dense_mlp:- # 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.+ # enable_moe_block runs dense MLP and experts in parallel;+ # register both. Non-structured _get_mlp_size prefers+ # moe_intermediate_size, so rebuild dense dims directly.if _uses_structured_layer_shapes(arch):dense_dims = mlp_dimselse:@@ -648,10 +634,9 @@ 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."))- # 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` doesn't over-skip into the experts block.+ # gemma4 enable_moe_block puts routed experts at sibling+ # layers.<i>.experts, not under self.mlp; keep the "mlp" aggregate to+ # the dense path so a `model.layers.0.mlp` skip doesn't over-skip.is_sibling_experts = bool(arch.moe_has_dense_mlp)mlp_total = sum(value@@ -681,12 +666,10 @@ 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:- # gemma4 enable_moe_block exposes routed experts at- # layers.<i>.experts (sibling of self.mlp), not under mlp.+ # gemma4: routed experts at sibling layers.<i>.experts, not mlp._add_module_aliases(aliases, canonical, f"layers.{layer_idx}.experts")elif name == "mlp.shared_expert":- # Exaone-MoE / Laguna / GLM-style use the plural- # `shared_experts` attribute name; register both spellings.+ # Exaone-MoE/Laguna/GLM use plural `shared_experts`; add both._add_module_aliases(aliases,canonical,@@ -780,9 +763,7 @@ def _compute_shared_moe_elements(arch: ModelArchConfig) -> int:hd = arch.hidden_sizeshared_size = _shared_expert_size(arch)total = hd * shared_size * 3 * arch.n_shared_experts- # 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.+ # Only Qwen2/Qwen3.5-MoE add a shared_expert_gate Linear (hidden_size->1);# shared_expert_intermediate_size is the Qwen-style discriminator.if arch.shared_expert_intermediate_size:total += arch.n_shared_experts * hd@@ -1078,17 +1059,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)- # 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.+ # KV-shared layers (Gemma4/Gemma3n) drop k/v WEIGHTS but the donor's+ # K/V tensors stay alive, so activations still pay 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 2qkv_size = q_size + kv_size * kv_countif is_moe_layer:- # Each token routes through `num_experts_per_tok` experts; their- # gate/up/down intermediates are all live during MLP forward.+ # Each token routes through num_experts_per_tok experts; all their+ # gate/up/down intermediates are live during MLP forward.mlp_size = _get_mlp_size(arch) * arch.num_experts_per_tokif arch.n_shared_experts:mlp_size += _shared_expert_size(arch) * arch.n_shared_experts@@ -1116,9 +1096,8 @@ def _per_layer_activation_bytes(activation_qkv = seq_len * batch_size * qkv_sizeresidual_memory = (seq_len * batch_size) * 2activation_mlp = seq_len * batch_size * (mlp_size + mlp_size)- # 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.+ # PLE gate (hd) + projection (pli) outputs materialize once per decoder+ # layer when hidden_size_per_layer_input is set (gemma4 modular:1141-1145).pli = arch.hidden_size_per_layer_inputactivation_ple = seq_len * batch_size * (arch.hidden_size + pli) if pli > 0 else 0return int((activation_qkv + residual_memory + activation_mlp + activation_ple) * 2 * 1.25)diff --git a/studio/backend/utils/inference/inference_config.py b/studio/backend/utils/inference/inference_config.pyindex 87e2aac833c..05eb08067cb 100644--- a/studio/backend/utils/inference/inference_config.py+++ b/studio/backend/utils/inference/inference_config.py@@ -1,13 +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-"""-Inference configuration loading utilities.--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.-"""+"""Load inference params (temperature, top_p, top_k, min_p) from model YAML, family defaults, or default.yaml."""from pathlib import Pathfrom typing import Dict, Any, Optional@@ -48,17 +42,10 @@ def _load_family_defaults():def get_family_inference_params(model_id: str) -> Dict[str, Any]:- """- Look up recommended inference parameters by model family.+ """Look up recommended inference params by model family.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")-- Returns:- Dict with inference params, or empty dict if no family match.+ "qwen3.5") and returns matching params from inference_defaults.json, or {}."""_load_family_defaults()@@ -87,13 +74,11 @@ def _has_specific_yaml(model_identifier: str) -> bool:script_dir = Path(__file__).parent.parent.parentdefaults_dir = script_dir / "assets" / "configs" / "model_defaults"- # Check the mapping.if model_identifier.lower() in _REVERSE_MODEL_MAPPING:return True- # 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).+ # For local paths, normalize backslashes so Path().parts splits correctly,+ # then match the last 1-2 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@@ -108,8 +93,7 @@ def _has_specific_yaml(model_identifier: str) -> bool:else:_lookup = model_identifier- # Exact filename match (basename for local paths; passing absolute paths to- # rglob raises "Non-relative patterns are unsupported" on Windows).+ # Exact filename match (basename for local paths; absolute paths break rglob on Windows).model_filename = _lookup.replace("/", "_") + ".yaml"for config_path in defaults_dir.rglob(model_filename):if config_path.is_file():@@ -119,27 +103,11 @@ def _has_specific_yaml(model_identifier: str) -> bool:def load_inference_config(model_identifier: str) -> Dict[str, Any]:+ """Load inference params for a model.++ Priority: model-specific YAML, then family defaults (inference_defaults.json),+ then default.yaml. Returns a dict of temperature/top_p/top_k/min_p/etc."""- 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.-- Args:- model_identifier: Model identifier (e.g., "unsloth/llama-3-8b-bnb-4bit")-- Returns:- Dict of inference parameters:- {- "temperature": float,- "top_p": float,- "top_k": int,- "min_p": float- }- """- # Model defaults for inference parameters.model_defaults = load_model_defaults(model_identifier)# default.yaml for fallback values.diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.pyindex 3635969c73b..3e5066ca2d8 100644--- a/studio/backend/utils/llama_cpp_freshness.py+++ b/studio/backend/utils/llama_cpp_freshness.py@@ -53,10 +53,7 @@ def read_install_marker(binary_path: Optional[str]) -> Optional[dict]:return cachedp = Path(binary_path)marker: Optional[dict] = None- # Cover all _find_llama_server_binary layouts:- # <install>/llama-server (1 up)- # <install>/build/bin/llama-server (3 up, Linux/macOS cmake)- # <install>/build/bin/Release/llama-server.exe (4 up, Windows cmake)+ # Cover all _find_llama_server_binary layouts (binary is 1-4 dirs deep):for parent in p.parents[:5]:candidate = parent / _INSTALL_MARKER_NAMEif candidate.is_file():diff --git a/studio/backend/utils/models/__init__.py b/studio/backend/utils/models/__init__.pyindex 808e2b012e7..74d08ac116e 100644--- a/studio/backend/utils/models/__init__.py+++ b/studio/backend/utils/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-"""-Model and LoRA configuration handling-"""+"""Model and LoRA configuration handling."""from .model_config import (ModelConfig,diff --git a/studio/backend/utils/models/checkpoints.py b/studio/backend/utils/models/checkpoints.pyindex 80312af0f74..5a992926ec7 100644--- a/studio/backend/utils/models/checkpoints.py+++ b/studio/backend/utils/models/checkpoints.py@@ -14,11 +14,7 @@ logger = get_logger(__name__)def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:- """- Read training loss from a checkpoint's trainer_state.json.-- Returns the loss from the last log_history entry, or None if unavailable.- """+ """Read loss from the last log_history entry of trainer_state.json, or None."""trainer_state = checkpoint_path / "trainer_state.json"if not trainer_state.exists():return None@@ -36,14 +32,13 @@ def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:def scan_checkpoints(outputs_dir: str = str(outputs_root()),) -> List[Tuple[str, List[Tuple[str, str, Optional[float]]], dict]]:- """- Scan outputs folder for training runs and their checkpoints.+ """Scan outputs folder for training runs and their checkpoints.Returns:- List of tuples: [(model_name, [(display_name, checkpoint_path, loss), ...], metadata), ...]- metadata keys: base_model, peft_type, lora_rank (all optional)- The first entry in each checkpoint list is the main adapter; its loss is- set to the loss of the last (highest-step) intermediate checkpoint.+ [(model_name, [(display_name, checkpoint_path, loss), ...], metadata), ...]+ metadata keys (optional): base_model, peft_type, lora_rank.+ First checkpoint entry is the main adapter; its loss mirrors the last+ (highest-step) intermediate checkpoint."""models = []outputs_path = resolve_output_dir(outputs_dir)@@ -63,7 +58,7 @@ def scan_checkpoints(if not (config_file.exists() or adapter_config.exists()):continue- # Extract training metadata from adapter_config.json / config.json+ # Training metadata from adapter_config.json / config.jsonmetadata: dict = {}try:if adapter_config.exists():@@ -75,7 +70,7 @@ def scan_checkpoints(cfg = json.loads(config_file.read_text())metadata["base_model"] = cfg.get("_name_or_path")- # Detect BNB quantization from config.json (present in both cases)+ # Detect BNB quantization from config.jsonif config_file.exists():if "cfg" not in dir():cfg = json.loads(config_file.read_text())diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex abddd073679..0df7a1a4773 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -472,13 +472,12 @@ def load_model_config(from transformers import AutoConfigif token:- # Explicit token providedreturn AutoConfig.from_pretrained(model_name, trust_remote_code = trust_remote_code, token = token)if not use_auth:- # No authentication (for public model checks)+ # No auth, for public model checkswith without_hf_auth():return AutoConfig.from_pretrained(model_name,@@ -486,7 +485,7 @@ def load_model_config(token = None,)- # Default authentication (cached tokens)+ # Default auth (cached tokens)return AutoConfig.from_pretrained(model_name,trust_remote_code = trust_remote_code,@@ -626,16 +625,12 @@ except Exception as exc:def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None) -> Optional[bool]:- """Run is_vision_model check in a subprocess with transformers 5.x.+ """Run is_vision_model in a subprocess with transformers 5.x.- Same pattern as training/inference workers: spawn a clean subprocess- 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. Subprocess failures are treated as transient since they may- stem from temporary HF/auth/network issues.+ Spawns a clean subprocess with .venv_t5/ on sys.path so AutoConfig+ recognizes newer architectures. Returns True/False for definitive results,+ or None for transient failures (timeouts, subprocess errors), which are not+ cached so they can be retried."""token_arg = hf_token or ""@@ -695,10 +690,8 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)def _token_fingerprint(token: Optional[str]) -> Optional[str]:- """SHA256 digest of the token for use as a cache key.-- Avoids storing the raw bearer token in process memory as a dict key.- """+ """SHA256 digest of the token for use as a cache key (avoids storing the+ raw bearer token in process memory)."""if token is None:return Nonereturn hashlib.sha256(token.encode("utf-8")).hexdigest()@@ -714,23 +707,18 @@ _vision_cache_lock = threading.Lock()def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:"""- 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.+ Detect vision-language models (VLMs) via architecture in config. Works for+ fine-tuned models since they inherit the base architecture.+ Models needing transformers 5.x are checked in a .venv_t5/ subprocess.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.+ lifetime; transient failures are not cached so they can be retried.Args:model_name: Model identifier (HF repo or local path)- hf_token: Optional HF token for accessing gated/private models+ hf_token: Optional HF token for gated/private models"""- # Normalize model name for cache key to avoid duplicate entries for- # different casings of the same HF repo (e.g. "Org/Model" vs "org/model").+ # Normalize model name so different casings of the same repo share a keytry:if is_local_path(model_name):resolved_name = normalize_path(model_name)@@ -745,21 +733,17 @@ def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:resolved_name = model_namecache_key = (resolved_name, _token_fingerprint(hf_token))- # Lock-free fast path for cache hits. Sentinel distinguishes "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- # (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.+ # Compute outside the lock so long-running detection isn't serialized across+ # models. Two concurrent calls may both run, but produce the same result.result = _is_vision_model_uncached(resolved_name, hf_token)- # Only cache definitive results; None means a transient failure, so- # retry on the next call instead of locking in a wrong answer.+ # Only cache definitive results; None is a transient failure, retry later.if result is not None:with _vision_cache_lock:_vision_detection_cache[cache_key] = result@@ -768,16 +752,13 @@ 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().+ """Uncached vision detection; use is_vision_model() instead.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 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.+ # Models needing transformers 5.x must be checked in a subprocess: the main+ # process (transformers 4.57.x) doesn't recognize their architectures.from utils.transformers_version import needs_transformers_5if needs_transformers_5(model_name):@@ -814,7 +795,7 @@ 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 (not found, gated, bad config) cache as False;- # transient failures (network, timeout) should not.+ # transient ones (network, timeout) should not.try:from huggingface_hub.errors import RepositoryNotFoundError, GatedRepoErrorexcept ImportError:@@ -857,13 +838,11 @@ _AUDIO_TOKEN_PATTERNS = {def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:- """- Detect if a model is an audio model and return its type.+ """Detect if a model is an audio model and return its type.- 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.+ Works for any model via tokenizer_config.json special tokens.+ Returns an audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper',+ 'audio_vlm') or None."""if model_name in _audio_detection_cache:return _audio_detection_cache[model_name]@@ -877,10 +856,10 @@ def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Optiondef _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:- """Detect audio type from tokenizer special tokens (LLM-based audio models).+ """Detect audio type from tokenizer special tokens.- Checks local HF cache first, then fetches tokenizer_config.json from- HuggingFace. Examines added_tokens_decoder for distinctive patterns.+ Checks local HF cache first, then fetches tokenizer_config.json from HF;+ examines added_tokens_decoder for distinctive patterns."""def _check_token_patterns(tok_config: dict) -> Optional[str]:@@ -919,7 +898,6 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = Noneimport ospaths_to_try = ["tokenizer_config.json", "LLM/tokenizer_config.json"]- # Use provided token, else envtoken = hf_token or os.environ.get("HF_TOKEN")headers = {}if token:@@ -943,10 +921,7 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = Nonedef is_audio_input_type(audio_type: Optional[str]) -> bool:- """Check if an audio_type accepts audio input (ASR/speech understanding).-- Whisper (ASR) and audio_vlm (Gemma3n) accept audio input.- """+ """True if an audio_type accepts audio input: whisper (ASR), audio_vlm (Gemma3n)."""return audio_type in ("whisper", "audio_vlm")@@ -955,8 +930,7 @@ def _is_mmproj(filename: str) -> bool:return "mmproj" in filename.lower()-# Family tokens for #5347's filename fallback. Lowercase. Order does not-# matter (see ``_detect_family_token``).+# Family tokens for #5347's filename fallback. Lowercase; order irrelevant._MODEL_FAMILY_TOKENS: tuple[str, ...] = ("qwen","gemma",@@ -989,8 +963,8 @@ _MODEL_FAMILY_TOKENS: tuple[str, ...] = ()-# Word-bounded match: a letter on either side disqualifies. Stops-# ``phi`` matching ``sapphire``, ``yi`` matching ``tiny``, etc.+# Word-bounded match: a letter on either side disqualifies (stops ``phi``+# matching ``sapphire``, ``yi`` matching ``tiny``)._FAMILY_TOKEN_RE_CACHE: Dict[str, "_re.Pattern[str]"] = {}@@ -1164,18 +1138,11 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optionaldef detect_gguf_model(path: str) -> Optional[str]:- """- Check if the given local path is or contains a GGUF model file.-- Handles two cases:- 1. path is a direct .gguf file path- 2. path is a directory containing .gguf files-- Skips mmproj (vision projection) files — those must be passed via- ``--mmproj``, not ``-m``. Use :func:`detect_mmproj_file` instead.+ """Check if a local path is or contains a GGUF model file.- Returns the full path to the .gguf file if found, None otherwise.- For HuggingFace repo detection, use detect_gguf_model_remote() instead.+ Handles a direct .gguf path or a directory of .gguf files. Skips mmproj+ files (pass those via ``--mmproj``; see :func:`detect_mmproj_file`). Returns+ the .gguf path or None. For HF repos, use detect_gguf_model_remote()."""p = Path(path)@@ -1206,10 +1173,9 @@ def detect_gguf_model(path: str) -> Optional[str]:return None-# 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.+# Preferred GGUF quant levels, descending priority. UD (Unsloth Dynamic)+# variants beat standard quants on quality per bit; repos without UD 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",@@ -1253,22 +1219,16 @@ _GGUF_QUANT_PREFERENCE = [def _pick_best_gguf(filenames: list[str]) -> Optional[str]:- """- Pick the best GGUF file from a list of filenames.-- Prefers quant levels in _GGUF_QUANT_PREFERENCE order; else the first .gguf.- """+ """Pick the best GGUF file: quant levels in _GGUF_QUANT_PREFERENCE order, else first .gguf."""gguf_files = [f for f in filenames if f.lower().endswith(".gguf")]if not gguf_files:return None- # Try preferred quantization levelsfor quant in _GGUF_QUANT_PREFERENCE:for f in gguf_files:if quant in f:return f- # Fallback: first GGUF filereturn gguf_files[0]@@ -1378,18 +1338,17 @@ def _list_gguf_variants_from_hf_cache(repo_id: str) -> Optional[tuple[list[GgufVdef list_gguf_variants(repo_id: str, hf_token: Optional[str] = None) -> tuple[list[GgufVariantInfo], bool]:- """- List all GGUF quantization variants in a HuggingFace repo.+ """List all GGUF quant variants in a HF repo.- Separates main model files from mmproj (vision projection) files;- mmproj presence indicates a vision-capable model.+ Separates main model files from mmproj (vision projection) files; mmproj+ presence flags a vision-capable model.Returns:- (variants, has_vision): list of non-mmproj GGUF variants + vision flag.+ (variants, has_vision): non-mmproj GGUF variants + vision flag."""from huggingface_hub import model_info as hf_model_info- # Offline: skip the API and serve from cache.+ # Offline: skip the API and serve from cacheif _env_offline():cached = _list_gguf_variants_from_hf_cache(repo_id)if cached is not None:@@ -1422,7 +1381,7 @@ def list_gguf_variants(has_vision = Falsequant_totals: dict[str, int] = {} # quant -> total bytes- quant_first_file: dict[str, str] = {} # quant -> first filename (for display)+ quant_first_file: dict[str, str] = {} # quant -> first filename (display)for sibling in info.siblings:fname = sibling.rfilename@@ -1449,8 +1408,8 @@ def list_gguf_variants())- # Sort by size descending (largest = best quality first). Recommended- # pinning and OOM demotion happen client-side where GPU VRAM info exists.+ # Sort by size descending (largest = best quality first); pinning and OOM+ # demotion happen client-side where GPU VRAM info exists.variants.sort(key = lambda v: -v.size_bytes)return variants, has_vision@@ -1478,14 +1437,13 @@ 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.+ """List GGUF quant variants in a local directory.- 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.+ Like :func:`list_gguf_variants` but reads the filesystem. Aggregates shard+ sizes by quant label so split GGUFs appear as one variant.Returns:- (variants, has_vision): list of non-mmproj GGUF variants + vision flag.+ (variants, has_vision): non-mmproj GGUF variants + vision flag."""p = _resolve_gguf_dir(Path(directory))if p is None:@@ -1571,20 +1529,11 @@ def _detect_gguf_from_hf_cache(repo_id: str) -> Optional[str]:def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Optional[str]:- """- Check if a HuggingFace repo contains GGUF files.-- Returns the filename of the best GGUF file in the repo, or None.+ """Return the best GGUF filename in a HF repo, or None.- 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).+ Retries (3 attempts, 1s/2s/4s backoff) on transient HF Hub failures: a+ silent None would make the caller treat a GGUF-only repo as non-GGUF and+ fall through to MLX on Apple Silicon. Offline falls back to the local cache."""import timefrom huggingface_hub import model_info as hf_model_info@@ -1602,7 +1551,7 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Opreturn _pick_best_gguf(repo_files)except Exception as e:last_err = e- # 404 / RepoNotFound is permanent -- don't retry.+ # 404 / RepoNotFound is permanent -- don't retryerr_name = type(e).__name__if err_name in ("RepositoryNotFoundError",@@ -1634,11 +1583,7 @@ def download_gguf_file(filename: str,hf_token: Optional[str] = None,) -> str:- """- Download a specific GGUF file from a HuggingFace repo.-- Returns the local path to the downloaded file.- """+ """Download a specific GGUF file from a HF repo; returns the local path."""from huggingface_hub import hf_hub_downloadlocal_path = hf_hub_download(@@ -1654,30 +1599,24 @@ _embedding_detection_cache: Dict[tuple, bool] = {}def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:- """- Detect embedding/sentence-transformer models via HuggingFace metadata.+ """Detect embedding/sentence-transformer models via HF metadata.- Combines three signals:- 1. "sentence-transformers" in model tags- 2. "feature-extraction" in model tags- 3. pipeline_tag is "sentence-similarity" or "feature-extraction"-- Catches all known embedding models, including ones like gte-modernbert- whose library_name is "transformers" rather than "sentence-transformers".+ Combines three signals: "sentence-transformers" or "feature-extraction" in+ tags, or pipeline_tag in {"sentence-similarity", "feature-extraction"}.+ Catches models like gte-modernbert whose library_name is "transformers".Args:model_name: Model identifier (HF repo or local path)- hf_token: Optional HF token for accessing gated/private models+ hf_token: Optional HF token for gated/private modelsReturns:- True if embedding model, else False. Defaults to False for local- paths or on errors.+ True if embedding model, else False (default for local paths or errors)."""cache_key = (model_name, hf_token)if cache_key in _embedding_detection_cache:return _embedding_detection_cache[cache_key]- # Local paths: check for sentence-transformer marker file (modules.json)+ # Local paths: check for sentence-transformer marker (modules.json)if is_local_path(model_name):local_dir = normalize_path(model_name)is_emb = os.path.isfile(os.path.join(local_dir, "modules.json"))@@ -1759,12 +1698,11 @@ def _looks_like_lora_adapter(model_dir: Path) -> bool:def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[str, str, str]]:- """- Scan outputs folder for trained Studio models.+ """Scan outputs folder for trained Studio models.Returns:- List of [(display_name, model_path, model_type), ...].- model_type is "lora" for adapter runs, "merged" for full finetunes.+ List of (display_name, model_path, model_type), where model_type is+ "lora" for adapter runs or "merged" for full finetunes."""trained_models = []outputs_path = resolve_output_dir(outputs_dir)@@ -1803,16 +1741,14 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[stdef scan_exported_models(exports_dir: str = str(exports_root()),) -> List[Tuple[str, str, str, Optional[str]]]:- """- Scan exports folder for exported models (merged, LoRA, GGUF).+ """Scan exports folder for exported models (merged, LoRA, GGUF).- Supports two directory layouts:- - Two-level: {run}/{checkpoint}/ (merged & LoRA exports)- - Flat: {name}-finetune-gguf/ (GGUF exports)+ Supports two layouts: two-level {run}/{checkpoint}/ (merged & LoRA) and+ flat {name}-finetune-gguf/ (GGUF).Returns:- List of [(display_name, model_path, export_type, base_model), ...].- export_type: "lora" | "merged" | "gguf"+ List of (display_name, model_path, export_type, base_model), where+ export_type is "lora" | "merged" | "gguf"."""results = []exports_path = resolve_export_dir(exports_dir)@@ -1839,7 +1775,7 @@ def scan_exported_models(passdisplay_name = run_dir.name- model_path = str(gguf_files[0]) # the .gguf file+ model_path = str(gguf_files[0])results.append((display_name, model_path, "gguf", base_model))logger.debug(f"Found GGUF export: {display_name}")continue@@ -1878,8 +1814,8 @@ def scan_exported_models(elif has_gguf:export_type = "gguf"gguf_list = list(_iter_gguf_files(checkpoint_dir))- # Check checkpoint_dir first, then parent run_dir- # (export.py writes metadata to the top-level export dir)+ # checkpoint_dir first, then 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:@@ -1899,8 +1835,7 @@ def scan_exported_models(else:continue- # Fallback: read base model from the training run's- # adapter_config.json in ./outputs/{run_name}/+ # Fallback: base model from ./outputs/{run_name}/adapter_config.jsonif not base_model:outputs_adapter_cfg = resolve_output_dir(run_dir.name) / "adapter_config.json"try:@@ -1986,15 +1921,7 @@ def get_base_model_from_checkpoint(checkpoint_path: str) -> Optional[str]:def get_base_model_from_lora(lora_path: str) -> Optional[str]:- """- Read the base model name from a LoRA adapter's config.-- Args:- lora_path: Path to the LoRA adapter directory-- Returns:- Base model identifier or None if not found- """+ """Read the base model name from a LoRA adapter's config, or None."""try:lora_path_obj = Path(lora_path)@@ -2028,13 +1955,10 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:# except Exception as e:# logger.warning(f"Could not load training_args.bin: {e}")- # Last resort: parse from directory name- # Format: unsloth_Meta-Llama-3.1-8B-Instruct-bnb-4bit_timestamp+ # Last resort: parse from dir name (unsloth_<model>_<timestamp>)dir_name = lora_path_obj.nameif dir_name.startswith("unsloth_"):- # Drop timestamp suffix (usually _1234567890)parts = dir_name.split("_")- # Reconstruct model nameif len(parts) >= 2:model_parts = parts[1:-1] # Skip "unsloth" and timestampbase_model = "unsloth/" + "_".join(model_parts)@@ -2054,28 +1978,19 @@ UI_STATUS_INDICATORS = [" (Ready)", " (Loading...)", " (Active)", "↓ "]def load_model_defaults(model_name: str) -> Dict[str, Any]:- """- Load default training parameters for a model from YAML file.-- Args:- model_name: Model identifier (e.g., "unsloth/Meta-Llama-3.1-8B-bnb-4bit")-- Returns:- Dict of default parameters from the YAML file, or empty dict if none.+ """Load default training parameters for a model from a YAML file.- 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.+ Looks in configs/model_defaults/ (incl. subfolders) by model name or its+ MODEL_NAME_MAPPING aliases, else falls back to default.yaml. Returns the+ parameter dict, or {} if none found."""try:- # Locate configs relative to the script dirscript_dir = Path(__file__).parent.parent.parentdefaults_dir = script_dir / "assets" / "configs" / "model_defaults"# Check the mapping firstif model_name.lower() in _REVERSE_MODEL_MAPPING:canonical_file = _REVERSE_MODEL_MAPPING[model_name.lower()]- # Search subfolders and rootfor config_path in defaults_dir.rglob(canonical_file):if config_path.is_file():with open(config_path, "r", encoding = "utf-8") as f:@@ -2165,17 +2080,12 @@ class ModelConfig:lora_path: str,hf_token: Optional[str] = None,) -> Optional["ModelConfig"]:- """- Create ModelConfig from a local LoRA adapter path.-- Auto-detects the base model from adapter config.+ """Create ModelConfig from a local LoRA adapter path, auto-detecting the+ base model from adapter config.Args:- lora_path: Path to LoRA adapter (e.g., "./outputs/unsloth_Meta-Llama-3.1_.../")+ lora_path: Path to the LoRA adapter directoryhf_token: HF token for vision detection-- Returns:- ModelConfig for the LoRA adapter"""try:lora_path_obj = Path(lora_path)@@ -2193,14 +2103,14 @@ class ModelConfig:audio_type = detect_audio_type(base_model, hf_token = hf_token)display_name = lora_path_obj.name- identifier = lora_path # path as identifier for local LoRAs+ identifier = lora_path # path is the identifier for local LoRAsreturn 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 cachedis_vision = is_vision,is_lora = True,is_audio = audio_type is not None and audio_type != "audio_vlm",@@ -2221,25 +2131,18 @@ class ModelConfig:is_lora: bool = False,gguf_variant: Optional[str] = None,) -> Optional["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:- - "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"- - "./outputs/my_lora_adapter"- - "/absolute/path/to/model"+ """Create ModelConfig from a clean model identifier (HF repo or local+ path), for FastAPI routes that send sanitized paths.Args:model_id: Clean model identifier (HF repo name or local path)hf_token: Optional HF token for vision detection on gated modelsis_lora: Whether this is a LoRA adapter- 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().+ gguf_variant: Optional GGUF quant variant (e.g. "Q4_K_M") to load+ via -hf for remote repos; None auto-selects via _pick_best_gguf().Returns:- ModelConfig or None if configuration cannot be created+ ModelConfig or None if it cannot be created."""if not model_id or not model_id.strip():return None@@ -2253,9 +2156,8 @@ 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.+ # Reuse a cached case-variant's 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:@@ -2295,12 +2197,9 @@ class ModelConfig:except Exception as e:logger.debug(f"Could not read export metadata: {e}")- # 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.+ # Pass search_root=path so detect_mmproj_file walks up to the+ # snapshot root: the weight may sit in a quant subdir while+ # mmproj-*.gguf lives at the root.mmproj_file = detect_mmproj_file(gguf_file, search_root = path)if mmproj_file:gguf_is_vision = True@@ -2324,8 +2223,7 @@ class ModelConfig:# 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 the user- # waits for a multi-GB download llama-server handles natively+ # Preflight: verify llama-server binary exists before a multi-GB downloadfrom core.inference.llama_cpp import LlamaCppBackendif not LlamaCppBackend._find_llama_server_binary():@@ -2337,8 +2235,7 @@ class ModelConfig:# list_gguf_variants() detects vision & resolves the variantvariants, has_vision = list_gguf_variants(identifier, hf_token = hf_token)variant = gguf_variant- if not variant:- # Auto-select best quantization+ if not variant: # auto-select best quantvariant_filenames = [v.filename for v in variants]best = _pick_best_gguf(variant_filenames)if best:@@ -2454,10 +2351,7 @@ class ModelConfig:hf_token: Optional[str] = None,is_lora: bool = False,) -> Optional["ModelConfig"]:- """- Create a ModelConfig from UI dropdown/search selections.- Handles base models and LoRA adapters.- """+ """Create a ModelConfig from UI dropdown/search selections (base models and LoRAs)."""selected = Noneif search_value and search_value.strip():selected = search_value.strip()diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.pyindex 8805308829a..1dcc9191fd1 100644--- a/studio/backend/utils/paths/__init__.py+++ b/studio/backend/utils/paths/__init__.py@@ -44,8 +44,8 @@ from .storage_roots import (resolve_dataset_path,)-# Re-export shim: reference the project-path helpers by name so the-# import-hoist safety net sees them used, not just named in __all__.+# Re-export shim: mark project-path helpers as used so the import-hoist+# safety net does not flag them as unused._REEXPORTED = (documents_root, project_workspaces_root)__all__ = [diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.pyindex a065250154a..e8dabc89541 100644--- a/studio/backend/utils/paths/path_utils.py+++ b/studio/backend/utils/paths/path_utils.py@@ -44,19 +44,10 @@ _IS_WSL: bool = _is_wsl()def normalize_path(path: str) -> str:- """- Normalize filesystem paths for cross-platform use.-- On WSL, converts Windows drive-letter paths to ``/mnt/<drive>/...``.- On native Windows, keeps the drive letter and normalizes separators.- On Linux/macOS (non-WSL), paths are returned with forward slashes.-- Examples (WSL):- C:\\Users\\... -> /mnt/c/Users/...- Examples (native Windows):- C:\\Users\\... -> C:/Users/...- Examples (Linux/macOS):- /home/user/... -> /home/user/... (unchanged)+ """Normalize filesystem paths for cross-platform use.++ WSL maps drive-letter paths to ``/mnt/<drive>/...``; native Windows keeps+ the drive and normalizes separators; elsewhere slashes are forward-only."""if not path:return path@@ -162,8 +153,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:expected_dir = f"models--{model_name.replace('/', '--')}"- # Check the exact-case path first so a newly-appeared exact match wins over- # any previously memoized variant.+ # Exact-case path first so a new exact match beats a memoized variant.exact_path = cache_dir / expected_dirif exact_path.is_dir():if use_memo:@@ -171,8 +161,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:_CACHE_CASE_RESOLUTION_STATS["exact_hits"] += 1return model_name- # Validate memoized entries still exist on disk before returning them,- # preventing stale results when cache dirs are deleted/recreated.+ # Revalidate memoized entries on disk to avoid stale results.if use_memo:cached = _CACHE_CASE_RESOLUTION_MEMO.get(model_name)if cached is not None:diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.pyindex de88a0bf311..63d24afd0c4 100644--- a/studio/backend/utils/paths/storage_roots.py+++ b/studio/backend/utils/paths/storage_roots.py@@ -182,7 +182,7 @@ def lmstudio_model_dirs() -> list[Path]:seen.add(resolved)dirs.append(p)- # 1. LM Studio settings.json custom downloads folder+ # LM Studio settings.json custom downloads foldersettings_path = Path.home() / ".lmstudio" / "settings.json"if settings_path.is_file():try:@@ -194,10 +194,10 @@ def lmstudio_model_dirs() -> list[Path]:except Exception:pass- # 2. LM Studio current default models directory (all platforms)+ # LM Studio default models directory (all platforms)_add(Path.home() / ".lmstudio" / "models")- # 3. Legacy LM Studio cache location+ # Legacy LM Studio cache location_add(Path.home() / ".cache" / "lm-studio" / "models")return dirs@@ -232,7 +232,7 @@ def well_known_model_dirs() -> list[Path]:for name in ("models", "Models"):candidates.append(Path.home() / name)- # Deduplicate while preserving order; keep only extant dirs+ # Dedupe preserving order; keep only extant dirsout: list[Path] = []seen: set[str] = set()for p in candidates:@@ -249,15 +249,11 @@ def well_known_model_dirs() -> list[Path]:def _setup_cache_env() -> None:- """Set cache environment variables for HuggingFace, uv, and vLLM.+ """Set cache env vars for HuggingFace, uv, and vLLM.- Respects the standard HF cache resolution chain: explicit ``HF_HOME``- / ``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.+ Respects the standard HF cache chain (explicit HF_HOME / HF_HUB_CACHE,+ then XDG_CACHE_HOME, then ~/.cache/huggingface) and only sets vars the+ user hasn't, so explicit overrides are honored."""root = cache_root()xdg_cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")).expanduser()diff --git a/studio/backend/utils/subprocess_compat.py b/studio/backend/utils/subprocess_compat.pyindex b7fe906e916..f2fa6eadc79 100644--- a/studio/backend/utils/subprocess_compat.py+++ b/studio/backend/utils/subprocess_compat.py@@ -8,10 +8,9 @@ import sysdef windows_hidden_subprocess_kwargs() -> dict[str, object]:- """Return Windows-only subprocess kwargs that suppress console windows.+ """Windows-only subprocess kwargs that suppress console windows.- Returns an empty dict off Windows so callers can always unpack it into- ``subprocess.run`` / ``subprocess.Popen`` via+ Empty dict off Windows, so callers can always unpack via``**windows_hidden_subprocess_kwargs()``."""if sys.platform != "win32":diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 7c1bc361b66..bf8d14b7cbe 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -1,27 +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-"""-Automatic transformers version switching.--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 target directories:- - .venv_t5_530/ — transformers 5.3.0 (Ministral-3, GLM, Qwen3 MoE, etc.)- - .venv_t5_550/ — transformers 5.5.0 (Gemma 4)--For a custom-named LoRA adapter, the base model is resolved from-``adapter_config.json`` and checked against the model list.+"""Automatic transformers version switching.-Strategy:- 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.+Some newer architectures need transformers>=5.3.0 (.venv_t5_530/); Gemma 4+needs >=5.5.0 (.venv_t5_550/). Everything else uses the default 4.57.x. A+custom-named LoRA adapter's base model is resolved from adapter_config.json.- For export (in-process), ensure_transformers_version() does a lightweight- sys.path swap using the same setup.sh-installed directories.+Training/inference run in subprocesses that activate the right version via+sys.path; export (in-process) uses ensure_transformers_version() for the swap."""import importlib@@ -397,12 +384,11 @@ _PURGE_PREFIXES = ("trl","accelerate","auto_gptq",- # NOTE: bitsandbytes is intentionally EXCLUDED — it registers torch custom- # 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`)+ # NOTE: bitsandbytes is intentionally EXCLUDED -- it registers torch custom+ # operators via torch.library.define() into torch's global registry, which+ # survives module purge; re-importing after purge -> duplicate registration+ # -> crash.+ # Our own modules that import from transformers at module level."utils.models","core.training","core.inference",diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex c51fc267f21..3818253ac9e 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.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-"""-Shared backend utilities-"""+"""Shared backend utilities."""import osimport structlog@@ -18,16 +16,12 @@ logger = get_logger(__name__)# ── Client-safe error helpers ───────────────────────────────────-# Never return raw exception text to clients (it can leak paths/internals);-# log the full exception server-side and return a generic message.+# Never return raw exception text to clients; log server-side, return generic.def safe_error_detail(error: Exception, fallback: str = "An internal error occurred") -> str:- """Map a caught exception to a generic, client-safe message.-- Never includes raw ``str(error)`` (which can leak internal paths or stack- detail); known transient conditions get a friendlier hint. Always log the- real exception server-side (e.g. via ``log_and_http_error``) for diagnosis.+ """Map an exception to a generic, client-safe message (never raw+ ``str(error)``, which can leak paths). Log the real exception server-side."""text = str(error).lower()if (@@ -43,10 +37,10 @@ def safe_error_detail(error: Exception, fallback: str = "An internal error occurdef safe_curated_detail(error: Exception, fallback: str = "An internal error occurred") -> str:- """Client-safe text for curated domain/validation exceptions meant for the user.+ """Client-safe text for curated domain/validation exceptions.- Keeps the message (paths stripped) instead of a generic fallback; use for known- exception types, keep ``safe_error_detail`` for generic ``Exception``.+ Keeps the message (paths stripped) instead of a generic fallback; for known+ exception types only (use ``safe_error_detail`` for generic ``Exception``)."""from utils.native_path_leases import redact_native_paths@@ -69,7 +63,7 @@ def log_and_http_error("""from fastapi import HTTPException- # Works for both structlog and stdlib loggers; exc_info=error logs its traceback.+ # exc_info=error works for both structlog and stdlib loggers.(log or logger).error(f"{event}: {error}", exc_info = error)return HTTPException(status_code = status_code, detail = public_message)@@ -84,7 +78,6 @@ def without_hf_auth():# Code that should run without cached tokensmodel_info(model_name, token=None)"""- # Save and clear env varssaved_env = {}env_vars = ["HF_TOKEN", "HUGGINGFACE_HUB_TOKEN", "HF_HOME"]for var in env_vars:diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.pyindex 59632963b76..98697df83c9 100644--- a/studio/backend/utils/wheel_utils.py+++ b/studio/backend/utils/wheel_utils.py@@ -24,16 +24,12 @@ FLASH_ATTN_RELEASE_BASE_URL = "https://github.com/Dao-AILab/flash-attention/rele@functools.lru_cache(maxsize = 1)def has_blackwell_gpu() -> bool:- """Return True if any visible NVIDIA GPU has compute capability >= 10.0- (Blackwell: sm_100, sm_120, sm_121, ...).+ """Return True if any visible NVIDIA GPU has compute capability >= 10.0 (Blackwell).- 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.-- 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.+ Dao-AILab ships no flash-attention wheels for these archs and older-arch wheels+ fail to load, so callers use this to skip the flash-attn install path. Cached+ for the process lifetime; tests mocking nvidia-smi must call+ ``has_blackwell_gpu.cache_clear()`` first."""exe = shutil.which("nvidia-smi")if not exe:diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 80e5257c8d0..5d3f0ed3390 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -113,19 +113,13 @@ 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 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.+ """GitHub API URL for the lemonade release matching a llama.cpp tag.++ "latest"/unset -> /releases/latest; a pinned tag -> the same lemonade tag.+ Lemonade tracks ggml-org build tags but may lag, so a tag it skipped 404s+ and the caller falls back to the upstream tarball (keeps pinned installs+ reproducible). Do NOT pass a fork tag -- the fork namespace always 404s.+ Tag is URL-encoded (safe="") to prevent URL injection."""normalized = (llama_tag or "").strip()if not normalized or normalized.lower() == "latest":diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 0cff45daefa..2c8f6228d4e 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -40,11 +40,9 @@ IS_MACOS = sys.platform == "darwin"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 (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.+# torchcodec ships wheels only for manylinux_2_28_x86_64, macosx_12_0_arm64,+# and win_amd64. On other hosts the audio extras must be filtered out (the+# extras-no-deps step would otherwise fail), regardless of NO_TORCH.PLATFORM_LACKS_TORCHCODEC_WHEEL = ((IS_LINUX and platform.machine() in {"aarch64", "arm64"})or (IS_WINDOWS and platform.machine().lower() in {"arm64", "aarch64"})@@ -83,8 +81,7 @@ _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).-# Format: https://repo.amd.com/rocm/whl/{arch_family}/+# AMD Windows ROCm wheels (repo.amd.com/rocm/whl/{arch_family}/).# 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"@@ -119,11 +116,9 @@ _BNB_ROCM_PRERELEASE_URLS: dict[str, str] = {"download/continuous-release_main/""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 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.+ # Windows ROCm wheel ships libbitsandbytes_rocm{VER}.dll. BNB's HIP+ # auto-detect may mismatch the DLL suffix, so we scan the wheel and set+ # BNB_ROCM_VERSION in _install_bnb_windows_rocm() and worker.py."win_amd64": ("https://github.com/bitsandbytes-foundation/bitsandbytes/releases/""download/continuous-release_main/"@@ -144,7 +139,6 @@ def _bnb_rocm_prerelease_url() -> str | None:def _detect_rocm_version() -> tuple[int, int] | None:"""Return (major, minor) of the installed ROCm stack, or None."""- # Check /opt/rocm/.info/version or ROCM_PATH equivalentrocm_root = os.environ.get("ROCM_PATH") or "/opt/rocm"for path in (os.path.join(rocm_root, ".info", "version"),diff --git a/tests/_zoo_aggressive_cuda_spoof.py b/tests/_zoo_aggressive_cuda_spoof.pyindex 9111aa95193..dafe81c8296 100644--- a/tests/_zoo_aggressive_cuda_spoof.py+++ b/tests/_zoo_aggressive_cuda_spoof.py@@ -1,15 +1,12 @@# Auto-generated by .github/workflows/consolidated-tests-ci.yml.# Aggressive CUDA spoof for the consolidated CPU-only CI job. Extends-# tests/conftest.py:84-141's import-time harness with deeper patches that-# unblock more patch_* functions and unsloth_zoo init paths on a GPU-less-# runner. Imported by every shim test file in this workflow before any-# unsloth / unsloth_zoo / transformers import.+# tests/conftest.py's import-time harness with deeper patches that unblock+# more patch_* and unsloth_zoo init paths on a GPU-less runner. Imported by+# every shim test file before any unsloth / unsloth_zoo / transformers import.#-# Design: only no-op or value-returning patches. We do NOT replace tensor-# allocators. The single exception is `pin_memory=True` kwarg dropping,-# which converts a hard CUDA-required call into a CPU-OK call -- the-# intent of pin_memory is a CUDA-host fast-copy, which simply has no-# meaning on this runner; downgrading silently is the right behavior here.+# Only no-op or value-returning patches; tensor allocators are NOT replaced.+# The one exception is dropping `pin_memory=True` (a CUDA-host fast-copy hint+# that is meaningless here), which downgrades a CUDA-required call to CPU-OK.from __future__ import annotations@@ -25,7 +22,7 @@ def apply() -> None:if getattr(torch.cuda, "_unsloth_consolidated_spoof", False):return- # ----- device probes (cheap, value-returning) -------------------------+ # Device probes (cheap, value-returning)torch.cuda.is_available = lambda: Truetorch.cuda.device_count = lambda: 1torch.cuda.current_device = lambda: 0@@ -49,7 +46,7 @@ def apply() -> None:torch.cuda.get_device_properties = lambda *a, **k: _Props() # type: ignore[assignment]- # ----- cudart() wrapper -----------------------------------------------+ # cudart() wrapperclass _CudaRt:@staticmethoddef cudaMemGetInfo(device: int = 0):@@ -57,7 +54,7 @@ def apply() -> None:@staticmethoddef cudaGetDeviceCount(*_a, **_k):- return 0 # Not used on the spoof path+ return 0 # unused on the spoof path@staticmethoddef cudaSetDevice(*_a, **_k):@@ -65,7 +62,7 @@ def apply() -> None:torch.cuda.cudart = lambda: _CudaRt() # type: ignore[assignment]- # ----- memory module --------------------------------------------------+ # memory moduletry:import torch.cuda.memory as _cuda_memory # type: ignore@@ -79,7 +76,7 @@ def apply() -> None:except Exception:pass- # ----- nvtx no-op stub ------------------------------------------------+ # nvtx no-op stubnvtx_stub = types.ModuleType("torch.cuda.nvtx")nvtx_stub.range_push = lambda *a, **k: None # type: ignore[attr-defined]nvtx_stub.range_pop = lambda *a, **k: None # type: ignore[attr-defined]@@ -87,18 +84,15 @@ def apply() -> None:sys.modules.setdefault("torch.cuda.nvtx", nvtx_stub)torch.cuda.nvtx = nvtx_stub # type: ignore[attr-defined]- # ----- random API ----------------------------------------------------- # CRITICAL: torch.manual_seed() internally calls torch.cuda.manual_seed_all(),- # so routing the cuda seed APIs back through torch.manual_seed would- # infinite-recurse (observed as RecursionError in run #8 cells 2/3 of the- # consolidated CI matrix). No-op them: callers that explicitly seed CUDA- # have already paid the cost of seeding CPU via torch.manual_seed; the- # CUDA-side seeding has no meaning on a GPU-less runner.+ # random API+ # CRITICAL: torch.manual_seed() calls torch.cuda.manual_seed_all(), so+ # routing the cuda seed APIs back through torch.manual_seed would+ # infinite-recurse (RecursionError in CI). No-op them; CUDA-side seeding+ # is meaningless on a GPU-less runner.torch.cuda.manual_seed = lambda *a, **k: None # type: ignore[assignment]torch.cuda.manual_seed_all = lambda *a, **k: None # type: ignore[assignment]- # rng_state APIs: return a CPU-shaped placeholder and accept anything for- # set; do NOT route through torch.set_rng_state / get_rng_state -- those- # operate on the CPU RNG directly and are independent of the cuda surface.+ # rng_state APIs: return a CPU-shaped placeholder, accept anything for set;+ # do NOT route through torch.{get,set}_rng_state (those touch the CPU RNG).import torch as _t_empty_rng_state = _t.empty(0, dtype = _t.uint8)@@ -110,7 +104,7 @@ def apply() -> None:torch.cuda.seed = lambda *a, **k: None # type: ignore[assignment]torch.cuda.seed_all = lambda *a, **k: None # type: ignore[assignment]- # ----- Stream / Event no-op classes -----------------------------------+ # Stream / Event no-op classesclass _NoopStream:def __init__(self, *a, **k): ...def __enter__(self):@@ -141,9 +135,8 @@ def apply() -> None:torch.cuda.current_stream = lambda *a, **k: _NoopStream() # type: ignore[assignment]torch.cuda.default_stream = lambda *a, **k: _NoopStream() # type: ignore[assignment]- # ----- pin_memory drop -------------------------------------------------- # `torch.empty(..., pin_memory=True)` and friends raise on a CPU-only- # build. Strip the kwarg — pin_memory has no meaning here.+ # pin_memory drop: torch.empty(..., pin_memory=True) and friends raise on+ # a CPU-only build; strip the kwarg since pin_memory has no meaning here.for _name in ("empty","zeros",@@ -175,10 +168,8 @@ def apply() -> None:if hasattr(torch.Tensor, "is_pinned"):torch.Tensor.is_pinned = lambda self, *a, **k: False # type: ignore[assignment]- # ----- amp.GradScaler: use the real one if torch ships a CPU-friendly- # path, else stub. Newer torch ships torch.amp.GradScaler that handles- # CPU; torch.cuda.amp.GradScaler is a wrapper. Both should work; just- # guard against import error.+ # amp.GradScaler: use the real one if importable (newer torch handles CPU),+ # else stub.try:import torch.cuda.amp # type: ignoreexcept Exception:@@ -209,7 +200,7 @@ def apply() -> None:sys.modules.setdefault("torch.cuda.amp", cuda_amp)torch.cuda.amp = cuda_amp # type: ignore[attr-defined]- # ----- Sentinel ------------------------------------------------------+ # Sentineltorch.cuda._unsloth_consolidated_spoof = True # type: ignore[attr-defined]diff --git a/tests/conftest.py b/tests/conftest.pyindex ad58cb9706d..4b7081b30bf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -140,14 +140,11 @@ if not _has_real_accelerator():# ----------------------------------------------------------------------------# Apply ALL upstream-drift fixes (vllm GuidedDecodingParams alias, triton-# CompiledKernel attr wrap, peft transformers_weight_conversion stub, etc.)-# by triggering ``import unsloth``. Fixes live on ``unsloth/import_fixes.py``-# and apply at unsloth import time. The GPU-free harness above pre-spoofs-# the device-type chain so ``import unsloth`` survives on a CPU-only runner.-# Suites without unsloth installed (e.g. security-only) keep passing ---# the ImportError is swallowed and the drift detectors will surface any-# pathology the missing patches would have hidden.+# Apply upstream-drift fixes (vllm/triton/peft) by triggering ``import+# unsloth``; they live in ``unsloth/import_fixes.py`` and run at import time.+# The GPU-free harness above lets ``import unsloth`` survive CPU-only runners.+# Suites without unsloth keep passing -- the ImportError is swallowed and the+# drift detectors surface anything the missing patches would have hidden.# ---------------------------------------------------------------------------diff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.pyindex 6c504579ce7..0f2e73257ac 100644--- a/tests/python/test_cross_platform_parity.py+++ b/tests/python/test_cross_platform_parity.py@@ -21,8 +21,7 @@ class TestNoTorchBackendAutoInInstallSh:def test_no_torch_backend_auto_outside_fallback(self):lines = INSTALL_SH.read_text().splitlines()- # Find the fallback block: starts with the "else" after the- # TORCH_INDEX_URL check and ends at the next "fi".+ # Fallback block: from "GPU detection failed" to the next "fi".fallback_start = Nonefallback_end = Nonefor i, line in enumerate(lines):diff --git a/tests/python/test_e2e_no_torch_sandbox.py b/tests/python/test_e2e_no_torch_sandbox.pyindex 382d0afe4e3..9b3bda133f3 100644--- a/tests/python/test_e2e_no_torch_sandbox.py+++ b/tests/python/test_e2e_no_torch_sandbox.py@@ -1,19 +1,11 @@-"""Comprehensive E2E sandbox tests for PR #4624 (fix/install-mac-intel-no-torch).--Proves that:-- The BEFORE state (top-level torch imports) crashes without torch-- The AFTER state (lazy/removed imports) works without torch-- Edge cases (broken torch, partial torch) are handled gracefully-- Hardware detection falls back to CPU without torch-- install.sh flag parsing and platform detection work correctly-- install_python_stack.py NO_TORCH filtering is correct-- Live server starts and responds without torch (optional, requires studio venv)+"""E2E sandbox tests for PR #4624 (fix/install-mac-intel-no-torch): BEFORE+(top-level torch) crashes, AFTER (lazy imports) works, broken/partial torch,+CPU hardware fallback, install.sh parsing, NO_TORCH filtering, and live server.Run:- # Lightweight tests (Groups 1-6, ~26 tests):+ # Lightweight (Groups 1-6):python -m pytest tests/python/test_e2e_no_torch_sandbox.py -v -k "not server"-- # Server tests (Group 7, 4 tests, requires studio venv):+ # Server (Group 7, requires studio venv):python -m pytest tests/python/test_e2e_no_torch_sandbox.py -v -m server"""@@ -212,12 +204,8 @@ def no_torch_venv(request, tmp_path_factory):class TestBeforeAfterImportChain:- """Prove the bug exists in BEFORE state and is fixed in AFTER state.-- BEFORE = PR branch files with top-level torch import synthetically prepended- (simulates the main branch).- AFTER = PR branch files as-is (lazy imports / torch import removed).- """+ """BEFORE (PR files with a synthetic top-level torch import, simulating+ main) crashes; AFTER (PR files as-is, lazy imports) works."""# -- BEFORE: crashes --diff --git a/tests/python/test_fast_sentence_transformer_redirect_lifecycle.py b/tests/python/test_fast_sentence_transformer_redirect_lifecycle.pyindex 3f5f235aae4..6fa7d06ec30 100644--- a/tests/python/test_fast_sentence_transformer_redirect_lifecycle.py+++ b/tests/python/test_fast_sentence_transformer_redirect_lifecycle.py@@ -18,8 +18,8 @@ import pytestdef _stub_module(name: str) -> types.ModuleType:- # __spec__ must be set so importlib.util.find_spec(name) does not raise- # ValueError if a downstream test imports the real package.+ # __spec__ set so find_spec(name) doesn't raise if a later test imports+ # the real package.mod = types.ModuleType(name)mod.__spec__ = importlib.util.spec_from_loader(name, loader = None)return moddiff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.pyindex 16538ae42ba..64373cb4b8a 100644--- a/tests/python/test_install_python_stack.py+++ b/tests/python/test_install_python_stack.py@@ -10,12 +10,11 @@ from unittest import mockimport pytest-# Add the studio directory so we can import install_python_stack+# Add the studio directory so we can import install_python_stack.STUDIO_DIR = Path(__file__).resolve().parents[2] / "studio"sys.path.insert(0, str(STUDIO_DIR))-# _build_uv_cmd lives at module level; import after path setup.-# We need to mock parts of the module that do work at import time.+# Import after path setup.import install_python_stack as ipsdiff --git a/tests/python/test_studio_import_no_torch.py b/tests/python/test_studio_import_no_torch.pyindex c8b67023f53..7b7a7103d27 100644--- a/tests/python/test_studio_import_no_torch.py+++ b/tests/python/test_studio_import_no_torch.py@@ -61,7 +61,6 @@ def no_torch_venv(request, tmp_path_factory):if venv_python is None:pytest.skip(f"Could not create Python {py_version} venv")- # Verify torch is NOT importablecheck = subprocess.run([str(venv_python), "-c", "import torch"],capture_output = True,diff --git a/tests/python/test_tokenizers_and_torch_constraint.py b/tests/python/test_tokenizers_and_torch_constraint.pyindex 17f2d17f945..40924efca2a 100644--- a/tests/python/test_tokenizers_and_torch_constraint.py+++ b/tests/python/test_tokenizers_and_torch_constraint.py@@ -1,7 +1,6 @@-"""-Tests for two install fixes:- 1. tokenizers added to no-torch-runtime.txt (prevents AutoConfig crash)- 2. TORCH_CONSTRAINT variable in install.sh (arm64 macOS + py313+ -> torch>=2.6)+"""Tests for two install fixes:+1. tokenizers in no-torch-runtime.txt (prevents AutoConfig crash)+2. TORCH_CONSTRAINT in install.sh (arm64 macOS + py313+ -> torch>=2.6)"""from __future__ import annotationsdiff --git a/tests/saving/gpt-oss-merge/test_merged_model.py b/tests/saving/gpt-oss-merge/test_merged_model.pyindex 497c74debf0..024d48f2767 100644--- a/tests/saving/gpt-oss-merge/test_merged_model.py+++ b/tests/saving/gpt-oss-merge/test_merged_model.py@@ -39,7 +39,7 @@ inputs = merged_tokenizer.apply_chat_template(add_generation_prompt = True,return_tensors = "pt",return_dict = True,- reasoning_effort = "low", # **NEW!** Set reasoning effort to low, medium or high+ reasoning_effort = "low", # low, medium or high).to(merged_model.device)_ = merged_model.generate(**inputs, max_new_tokens = 512, streamer = TextStreamer(merged_tokenizer))diff --git a/tests/saving/gpt-oss-merge/train_and_merge.py b/tests/saving/gpt-oss-merge/train_and_merge.pyindex 8c76ff9662b..1d35c6759d1 100644--- a/tests/saving/gpt-oss-merge/train_and_merge.py+++ b/tests/saving/gpt-oss-merge/train_and_merge.py@@ -1,4 +1,3 @@-# train_and_merge.pyfrom unsloth import FastLanguageModelfrom trl import SFTTrainer, SFTConfigfrom datasets import load_dataset@@ -21,7 +20,7 @@ def safe_remove_directory(path):return False-# This tokenizer will be used by the mapping function+# Used by the mapping function below.tokenizer = Nonediff --git a/tests/saving/language_models/test_merge_4bit_validation.py b/tests/saving/language_models/test_merge_4bit_validation.pyindex c8890017068..2e2e823bd30 100644--- a/tests/saving/language_models/test_merge_4bit_validation.py+++ b/tests/saving/language_models/test_merge_4bit_validation.py@@ -48,7 +48,6 @@ tokenizer = get_chat_template(chat_template = "llama-3.1",)-# Load small dataset for quick trainingdataset_train = load_dataset("allenai/openassistant-guanaco-reformatted", split = "train[:100]")dataset_train = dataset_train.map(formatting_prompts_func, batched = True)@@ -126,7 +125,6 @@ print(f"\n{'='*80}")print("🔍 PHASE 4: Loading 4bit Model and Second Fine-tuning")print(f"{'='*80}")-# Clean up first modeldel modeldel tokenizertorch.cuda.empty_cache()@@ -146,7 +144,7 @@ tokenizer_4bit = get_chat_template(print("✅ 4bit model loaded successfully!")-# Add LoRA adapters to the 4bit model+# Add LoRA adaptersmodel_4bit = FastLanguageModel.get_peft_model(model_4bit,r = 16,@@ -233,7 +231,6 @@ print(f"\n{'='*80}")print("🔍 CLEANUP")print(f"{'='*80}")-# Cleanupsafe_remove_directory("./outputs")safe_remove_directory("./outputs_4bit")safe_remove_directory("./unsloth_compiled_cache")diff --git a/tests/saving/language_models/test_merge_model_perplexity_llama-3.2.py b/tests/saving/language_models/test_merge_model_perplexity_llama-3.2.pyindex 3f2b811b07f..f8f81c550e7 100644--- a/tests/saving/language_models/test_merge_model_perplexity_llama-3.2.py+++ b/tests/saving/language_models/test_merge_model_perplexity_llama-3.2.py@@ -31,7 +31,6 @@ from tests.utils.perplexity_eval import ()-# Define helper functions outside of maindef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -51,14 +50,12 @@ def load_and_compute_8bit_ppl(from unsloth.chat_templates import get_chat_templatefrom tests.utils.perplexity_eval import ppl_model- # Load modelmerged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_llama_text_model",max_seq_length = 2048,load_in_4bit = load_in_4bit,load_in_8bit = load_in_8bit,)- # Set up tokenizermerged_tokenizer = get_chat_template(merged_tokenizer,chat_template = "llama-3.1",@@ -67,7 +64,6 @@ def load_and_compute_8bit_ppl(# Load dataset fresh in subprocessdataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval")- # Format the datasetdef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -78,21 +74,18 @@ def load_and_compute_8bit_ppl(dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True)- # Compute perplexity using the passed datasetppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl)- # IMPORTANT: Convert to Python float if it's a tensor+ # Coerce to a plain Python float for cross-process transferif torch.is_tensor(ppl_value):- ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar+ ppl_value = ppl_value.cpu().item()elif hasattr(ppl_value, "item"):- ppl_value = ppl_value.item() # Convert numpy or other array types+ ppl_value = ppl_value.item()else:- ppl_value = float(ppl_value) # Ensure it's a float+ ppl_value = float(ppl_value)- # Return only the perplexity valueresult_queue.put(ppl_value)- # Clean updel merged_modeldel merged_tokenizerdel dataset_ppl@@ -100,7 +93,6 @@ def load_and_compute_8bit_ppl(gc.collect()-# Main execution code should be wrapped in this guardif __name__ == "__main__":mp.set_start_method("spawn", force = True)@@ -193,12 +185,10 @@ if __name__ == "__main__":response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",)- # run trainingtrainer_stats = trainer.train()add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl))- # saving and merging the model to local diskprint("merge and save to local disk")model.save_pretrained_merged(save_directory = "./unsloth_out/merged_llama_text_model", tokenizer = tokenizer@@ -210,7 +200,6 @@ if __name__ == "__main__":# torch.cuda.empty_cache()# gc.collect()- # load model from local disk and testprint("Loading merged model in 4 bit for perplexity test")merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_llama_text_model",@@ -247,7 +236,6 @@ if __name__ == "__main__":print_model_comparison()- # final cleanupsafe_remove_directory("./outputs")safe_remove_directory("./unsloth_compiled_cache")safe_remove_directory("./unsloth_out")diff --git a/tests/saving/language_models/test_merge_model_perplexity_mistral.py b/tests/saving/language_models/test_merge_model_perplexity_mistral.pyindex d17a20d755b..d467089a47d 100644--- a/tests/saving/language_models/test_merge_model_perplexity_mistral.py+++ b/tests/saving/language_models/test_merge_model_perplexity_mistral.py@@ -39,20 +39,18 @@ def load_and_compute_8bit_ppl(from unsloth import FastLanguageModelfrom tests.utils.perplexity_eval import ppl_model- # Load modelmerged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_mistral_text_model",max_seq_length = 2048,load_in_4bit = load_in_4bit,load_in_8bit = load_in_8bit,)- # Set up tokenizer# merged_tokenizer = get_chat_template(# merged_tokenizer,# chat_template="llama-3.1",# )- # Load dataset fresh in subprocess+ # Load dataset fresh in subprocess.dataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval")alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.@@ -75,7 +73,6 @@ def load_and_compute_8bit_ppl(texts = []for conversation in examples["messages"]:- # Extract user message and assistant responseuser_message = ""assistant_message = ""@@ -85,13 +82,11 @@ def load_and_compute_8bit_ppl(elif turn["role"] == "assistant":assistant_message = turn["content"]- # Store intermediate formatinstruction = "Complete the statement"instructions.append(instruction)inputs.append(user_message)outputs.append(assistant_message)- # Create formatted texttext = alpaca_prompt.format(instruction, user_message, assistant_message) + EOS_TOKENtexts.append(text)@@ -104,21 +99,18 @@ def load_and_compute_8bit_ppl(dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True)- # Compute perplexity using the passed datasetppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl)- # IMPORTANT: Convert to Python float if it's a tensor+ # Convert to Python float if it's a tensor.if torch.is_tensor(ppl_value):- ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar+ ppl_value = ppl_value.cpu().item()elif hasattr(ppl_value, "item"):- ppl_value = ppl_value.item() # Convert numpy or other array types+ ppl_value = ppl_value.item()else:- ppl_value = float(ppl_value) # Ensure it's a float+ ppl_value = float(ppl_value)- # Return only the perplexity valueresult_queue.put(ppl_value)- # Clean updel merged_modeldel merged_tokenizerdel dataset_ppl@@ -126,7 +118,6 @@ def load_and_compute_8bit_ppl(gc.collect()-# Main execution code should be wrapped in this guardif __name__ == "__main__":mp.set_start_method("spawn", force = True)@@ -160,7 +151,6 @@ if __name__ == "__main__":### Response:{}"""- # Define helper functions outside of maindef formatting_prompts_func(examples):instructions = []inputs = []@@ -168,7 +158,6 @@ if __name__ == "__main__":texts = []for conversation in examples["messages"]:- # Extract user message and assistant responseuser_message = ""assistant_message = ""@@ -178,13 +167,11 @@ if __name__ == "__main__":elif turn["role"] == "assistant":assistant_message = turn["content"]- # Store intermediate formatinstruction = "Complete the statement"instructions.append(instruction)inputs.append(user_message)outputs.append(assistant_message)- # Create formatted texttext = alpaca_prompt.format(instruction, user_message, assistant_message) + EOS_TOKENtexts.append(text)@@ -251,12 +238,11 @@ if __name__ == "__main__":),)- # run trainingtrainer_stats = trainer.train()add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl))- # saving and merging the model to local disk+ # Merge and save to local disk.print("merge and save to local disk")model.save_pretrained_merged(save_directory = "./unsloth_out/merged_mistral_text_model", tokenizer = tokenizer@@ -268,7 +254,7 @@ if __name__ == "__main__":# torch.cuda.empty_cache()# gc.collect()- # load model from local disk and test+ # Load merged model from disk and test.print("Loading merged model in 4 bit for perplexity test")merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_mistral_text_model",diff --git a/tests/saving/language_models/test_merge_model_perplexity_phi_4.py b/tests/saving/language_models/test_merge_model_perplexity_phi_4.pyindex 6dbdf36032e..391d1b90db4 100644--- a/tests/saving/language_models/test_merge_model_perplexity_phi_4.py+++ b/tests/saving/language_models/test_merge_model_perplexity_phi_4.py@@ -31,7 +31,6 @@ from tests.utils.perplexity_eval import ()-# Define helper functions outside of maindef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -48,19 +47,17 @@ def load_and_compute_8bit_ppl(load_in_4bit = False,load_in_8bit = False,):- """Load model and compute perplexity in subprocess"""+ """Load model and compute perplexity in subprocess."""from unsloth import FastLanguageModelfrom unsloth.chat_templates import get_chat_templatefrom tests.utils.perplexity_eval import ppl_model- # Load modelmerged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_phi4_text_model",max_seq_length = 2048,load_in_4bit = load_in_4bit,load_in_8bit = load_in_8bit,)- # Set up tokenizermerged_tokenizer = get_chat_template(merged_tokenizer,chat_template = "phi-4",@@ -69,7 +66,6 @@ def load_and_compute_8bit_ppl(# Load dataset fresh in subprocessdataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval")- # Format the datasetdef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -80,21 +76,18 @@ def load_and_compute_8bit_ppl(dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True)- # Compute perplexity using the passed datasetppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl)- # IMPORTANT: Convert to Python float if it's a tensor+ # Coerce to a Python float regardless of source type.if torch.is_tensor(ppl_value):- ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar+ ppl_value = ppl_value.cpu().item()elif hasattr(ppl_value, "item"):- ppl_value = ppl_value.item() # Convert numpy or other array types+ ppl_value = ppl_value.item()else:- ppl_value = float(ppl_value) # Ensure it's a float+ ppl_value = float(ppl_value)- # Return only the perplexity valueresult_queue.put(ppl_value)- # Clean updel merged_modeldel merged_tokenizerdel dataset_ppl@@ -102,7 +95,6 @@ def load_and_compute_8bit_ppl(gc.collect()-# Main execution code should be wrapped in this guardif __name__ == "__main__":mp.set_start_method("spawn", force = True)@@ -193,12 +185,11 @@ if __name__ == "__main__":response_part = "<|im_start|>assistant<|im_sep|>\n\n",)- # run trainingtrainer_stats = trainer.train()add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl))- # saving and merging the model to local disk+ # Merge and save to local disk.print("merge and save to local disk")model.save_pretrained_merged(save_directory = "./unsloth_out/merged_phi4_text_model", tokenizer = tokenizer@@ -210,7 +201,6 @@ if __name__ == "__main__":# torch.cuda.empty_cache()# gc.collect()- # load model from local disk and testprint("Loading merged model in 4 bit for perplexity test")merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_phi4_text_model",@@ -247,7 +237,6 @@ if __name__ == "__main__":print_model_comparison()- # final cleanupsafe_remove_directory("./outputs")safe_remove_directory("./unsloth_compiled_cache")safe_remove_directory("./unsloth_out")diff --git a/tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.py b/tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.pyindex a0624f0c2c3..9c2c1acb415 100644--- a/tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.py+++ b/tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.py@@ -50,14 +50,12 @@ def load_and_compute_8bit_ppl(from unsloth.chat_templates import get_chat_templatefrom tests.utils.perplexity_eval import ppl_model- # Load modelmerged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_llama_text_model",max_seq_length = 2048,load_in_4bit = load_in_4bit,load_in_8bit = load_in_8bit,)- # Set up tokenizermerged_tokenizer = get_chat_template(merged_tokenizer,chat_template = "llama-3.1",@@ -66,7 +64,6 @@ def load_and_compute_8bit_ppl(# Load dataset fresh in subprocessdataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval")- # Format the datasetdef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -77,21 +74,18 @@ def load_and_compute_8bit_ppl(dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True)- # Compute perplexity using the passed datasetppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl)- # IMPORTANT: Convert to Python float if it's a tensor+ # Convert to a Python float (tensor / numpy / other)if torch.is_tensor(ppl_value):- ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar+ ppl_value = ppl_value.cpu().item()elif hasattr(ppl_value, "item"):- ppl_value = ppl_value.item() # Convert numpy or other array types+ ppl_value = ppl_value.item()else:- ppl_value = float(ppl_value) # Ensure it's a float+ ppl_value = float(ppl_value)- # Return only the perplexity valueresult_queue.put(ppl_value)- # Clean updel merged_modeldel merged_tokenizerdel dataset_ppl@@ -99,7 +93,6 @@ def load_and_compute_8bit_ppl(gc.collect()-# Main execution code should be wrapped in this guardif __name__ == "__main__":mp.set_start_method("spawn", force = True)@@ -197,12 +190,11 @@ if __name__ == "__main__":tokenizer.decode(trainer.train_dataset[0]["input_ids"])- # run trainingtrainer_stats = trainer.train()add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl))- # saving and merging the model to local disk+ # save and merge the model to local diskprint("merge and save to local disk")model.save_pretrained_merged(save_directory = "./unsloth_out/merged_llama_text_model", tokenizer = tokenizer@@ -214,7 +206,6 @@ if __name__ == "__main__":# torch.cuda.empty_cache()# gc.collect()- # load model from local disk and testprint("Loading merged model in 4 bit for perplexity test")merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_llama_text_model",@@ -251,7 +242,6 @@ if __name__ == "__main__":print_model_comparison()- # final cleanupsafe_remove_directory("./outputs")safe_remove_directory("./unsloth_compiled_cache")safe_remove_directory("./unsloth_out")diff --git a/tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.py b/tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.pyindex 0b377eca818..cdbad174a49 100644--- a/tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.py+++ b/tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.py@@ -42,7 +42,6 @@ alpaca_prompt = """Below is an instruction that describes a task, paired with an{}"""-# Define helper functions outside of maindef formatting_prompts_func(examples):instructions = []inputs = []@@ -50,7 +49,6 @@ def formatting_prompts_func(examples):texts = []for conversation in examples["messages"]:- # Extract user message and assistant responseuser_message = ""assistant_message = ""@@ -60,13 +58,11 @@ def formatting_prompts_func(examples):elif turn["role"] == "assistant":assistant_message = turn["content"]- # Store intermediate formatinstruction = "Complete the statement"instructions.append(instruction)inputs.append(user_message)outputs.append(assistant_message)- # Create formatted texttext = alpaca_prompt.format(instruction, user_message, assistant_message)texts.append(text)@@ -83,11 +79,10 @@ def load_and_compute_8bit_ppl(load_in_4bit = False,load_in_8bit = False,):- """Load model and compute perplexity in subprocess"""+ """Load model and compute perplexity in subprocess."""from unsloth import FastLanguageModelfrom tests.utils.perplexity_eval import ppl_model- # Load modelmerged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_qwen_text_model",max_seq_length = 2048,@@ -121,7 +116,6 @@ def load_and_compute_8bit_ppl(texts = []for conversation in examples["messages"]:- # Extract user message and assistant responseuser_message = ""assistant_message = ""@@ -131,13 +125,11 @@ def load_and_compute_8bit_ppl(elif turn["role"] == "assistant":assistant_message = turn["content"]- # Store intermediate formatinstruction = "Complete the statement"instructions.append(instruction)inputs.append(user_message)outputs.append(assistant_message)- # Create formatted texttext = alpaca_prompt.format(instruction, user_message, assistant_message)texts.append(text)@@ -150,18 +142,16 @@ def load_and_compute_8bit_ppl(dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True)- # Compute perplexity using the passed datasetppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl)- # IMPORTANT: Convert to Python float if it's a tensor+ # Coerce to a Python float regardless of source type.if torch.is_tensor(ppl_value):- ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar+ ppl_value = ppl_value.cpu().item()elif hasattr(ppl_value, "item"):- ppl_value = ppl_value.item() # Convert numpy or other array types+ ppl_value = ppl_value.item()else:- ppl_value = float(ppl_value) # Ensure it's a float+ ppl_value = float(ppl_value)- # Return only the perplexity valueresult_queue.put(ppl_value)# Clean up@@ -172,7 +162,6 @@ def load_and_compute_8bit_ppl(# gc.collect()-# Main execution code should be wrapped in this guardif __name__ == "__main__":mp.set_start_method("spawn", force = True)@@ -250,12 +239,11 @@ if __name__ == "__main__":),)- # run trainingtrainer_stats = trainer.train()add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl))- # saving and merging the model to local disk+ # Merge and save to local disk.print("merge and save to local disk")model.save_pretrained_merged(save_directory = "./unsloth_out/merged_qwen_text_model", tokenizer = tokenizer@@ -267,7 +255,6 @@ if __name__ == "__main__":# torch.cuda.empty_cache()# gc.collect()- # load model from local disk and testprint("Loading merged model in 4 bit for perplexity test")merged_model, merged_tokenizer = FastLanguageModel.from_pretrained(model_name = "./unsloth_out/merged_qwen_text_model",diff --git a/tests/saving/language_models/test_push_to_hub_merged.py b/tests/saving/language_models/test_push_to_hub_merged.pyindex aa793945568..cacb1e2a106 100644--- a/tests/saving/language_models/test_push_to_hub_merged.py+++ b/tests/saving/language_models/test_push_to_hub_merged.py@@ -32,7 +32,6 @@ from tests.utils.perplexity_eval import ()-# Define helper functions outside of maindef formatting_prompts_func(examples):convos = examples["messages"]texts = [@@ -135,7 +134,7 @@ trainer = train_on_responses_only(trainer_stats = trainer.train()-# saving and merging the model to local disk+# save and merge the model to local diskhf_username = os.environ.get("HF_USER", "")if not hf_username:hf_username = input("Please enter your Hugging Face username: ").strip()diff --git a/tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.py b/tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.pyindex 38b82c54692..59a09f06ec9 100644--- a/tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.py+++ b/tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.py@@ -131,7 +131,6 @@ trainer = train_on_responses_only(response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",)-# run trainingtrainer_stats = trainer.train()diff --git a/tests/saving/language_models/test_save_merged_grpo_model.py b/tests/saving/language_models/test_save_merged_grpo_model.pyindex b5d8025fcb8..63e4b970a6a 100644--- a/tests/saving/language_models/test_save_merged_grpo_model.py+++ b/tests/saving/language_models/test_save_merged_grpo_model.py@@ -75,7 +75,6 @@ def evaluate_merged_model(gc.collect()-# Main execution code should be wrapped in this guarddef training_run(result_queue):model, tokenizer = FastLanguageModel.from_pretrained(model_name = "meta-llama/Llama-3.2-3B-Instruct",@@ -145,12 +144,10 @@ def training_run(result_queue):</answer>"""def format_limo(example):- # Create the assistant responseassistant_response = f"<reasoning>\n{example['solution']}\n</reasoning>\n<answer>\n{example['answer']}\n</answer>"- # Return a DICTIONARY with the conversation in a fieldreturn {- "prompt": [ # ← This is the key change - wrap in a dict+ "prompt": [{"role": "system", "content": system_prompt},{"role": "user", "content": example["question"]},{"role": "assistant", "content": assistant_response},@@ -379,7 +376,6 @@ def training_run(result_queue):print("COMPREHENSIVE MODEL COMPARISON")print(f"{'='*80}")- # Main tableprint(f"{'Model':<15} {'Format %':<10} {'Exact %':<10} {'Plausible %':<12} {'Confidence':<12}")@@ -394,7 +390,6 @@ def training_run(result_queue):f"{result['avg_confidence']:<12.3f}")- # Improvement analysisif len(all_results) > 1:print(f"\n{'='*50}")print("IMPROVEMENT ANALYSIS")@@ -415,7 +410,6 @@ def training_run(result_queue):print(f" Exact matches: {exact_improvement:+.1f}%")print(f" Plausible matches: {plausible_improvement:+.1f}%")- # Save comparisoncomparison_data = {"summary": all_results,"best_model": max(all_results, key = lambda x: x["exact_match_pct"]),@@ -445,23 +439,18 @@ def training_run(result_queue):from datasets import load_dataset- # Load GSM8Kgsm8k_dataset = load_dataset("openai/gsm8k", "main", split = "train")-- # Load LIMO (adjust this based on your access method)limo_train = load_dataset("GAIR/LIMO", split = "train")- # Prepare datasetsgsm8k_train = prepare_gsm8k_dataset(gsm8k_dataset)limo_train = prepare_limo_dataset(limo_train)print(f" GSM8K train: {len(gsm8k_train)}")print(f" LIMO train: {len(limo_train) if limo_train else 0}")- # Store resultsall_results = []- # Single temperature evaluation on combined dataset+ # Single temperature evaluation on combined dataset.results = evaluate_model_aime(model = model,tokenizer = tokenizer,@@ -557,16 +546,13 @@ def training_run(result_queue):response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",)- # Trainprint(f"🚂 Starting SFT training on {len(limo_train)} examples...")trainer.train()- # Save checkpointmodel.save_pretrained("qlora_checkpoint")tokenizer.save_pretrained("qlora_checkpoint")print("💾 Qlora checkpoint saved!")- # Cleanupdel trainercleanup_memory()@@ -574,7 +560,6 @@ def training_run(result_queue):else:print("⚠️ Skipping Qlora training - no LIMO dataset available")- # Cleanupcleanup_memory()global PRINTED_TIMES@@ -596,7 +581,7 @@ def training_run(result_queue):]scores = []- # Print only every few steps+ # Print only every few steps.global PRINTED_TIMESglobal PRINT_EVERY_STEPSif PRINTED_TIMES % PRINT_EVERY_STEPS == 0:@@ -613,10 +598,9 @@ def training_run(result_queue):if guess is None:scores.append(0)continue- # Convert to numberstry:true_answer = float(true_answer.strip())- # Remove commas like in 123,456+ # Remove commas like in 123,456.guess = float(guess.strip().replace(",", ""))scores.append(1.5 if guess == true_answer else -0.5)except:@@ -628,7 +612,6 @@ def training_run(result_queue):print("🎯 STAGE 2: GRPO Fine-Tuning on GSM8K")print(f"{'*'*60}")- # Get max prompt lengthmax_prompt_length, _ = get_max_prompt_length(gsm8k_train, tokenizer)max_prompt_length = min(max_prompt_length + 10, 512) # Add buffer, cap at 512@@ -670,16 +653,13 @@ def training_run(result_queue):train_dataset = gsm8k_train,)- # Trainprint(f"🚂 Starting GRPO training on {len(gsm8k_train)} examples...")trainer.train()- # Save checkpointmodel.save_pretrained("grpo_checkpoint")tokenizer.save_pretrained("grpo_checkpoint")print("💾 GRPO checkpoint saved!")- # Cleanupdel trainerdel training_argscleanup_memory()@@ -708,7 +688,6 @@ def training_run(result_queue):print("💾 SAVING FINAL MODEL")print(f"{'='*60}")- # Save as merged modeltry:model.save_pretrained_merged("final_merged_model", tokenizer, save_method = "merged_16bit")print("✅ Merged model saved to: final_merged_model/")@@ -722,7 +701,6 @@ def training_run(result_queue):result_queue.put(results)- # Clean updel modeldel tokenizertorch.cuda.empty_cache()@@ -771,7 +749,7 @@ if __name__ == "__main__":result_queue = mp.Queue()all_results = []- # run main finetuning and grpo loop+ # Run main finetuning and GRPO loop.p = mp.Process(target = training_run, args = (result_queue,))p.start()p.join()@@ -779,7 +757,7 @@ if __name__ == "__main__":results = result_queue.get()all_results = results- # evaluate merged model loaded 16bits+ # Evaluate merged model loaded 16bits.p = mp.Process(target = evaluate_merged_model, args = (result_queue, False, False))p.start()p.join()@@ -808,11 +786,8 @@ if __name__ == "__main__":safe_remove_directory("./unsloth_compiled_cache")- # AIME-specific comparison function-print(f"\n{'='*80}")print("🏆 FINAL TRAINING PIPELINE RESULTS")print(f"{'='*80}")- # Use the AIME-specific comparisoncompare_aime_results(all_results)diff --git a/tests/saving/non_peft/test_mistral_non_peft.py b/tests/saving/non_peft/test_mistral_non_peft.pyindex b2610360fe6..0ace3dd352f 100644--- a/tests/saving/non_peft/test_mistral_non_peft.py+++ b/tests/saving/non_peft/test_mistral_non_peft.py@@ -27,8 +27,6 @@ model, tokenizer = FastLanguageModel.from_pretrained(print("✅ Base model loaded successfully!")-### Attempting save merge-print(f"\n{'='*80}")print("🔍 PHASE 2: Attempting save_pretrained_merged (Should Warn)")@@ -38,7 +36,6 @@ with warnings.catch_warnings(record = True) as w:warnings.simplefilter("always")model.save_pretrained_merged("test_output", tokenizer)- # Verify warningassert len(w) >= 1, "Expected warning but none raised"warning_msg = str(w[0].message)expected_msg = "Model is not a PeftModel (no Lora adapters detected). Skipping Merge. Please use save_pretrained() or push_to_hub() instead!"@@ -55,7 +52,7 @@ print(f"{'='*80}")try:with warnings.catch_warnings():- warnings.simplefilter("error") # Treat warnings as errors here+ warnings.simplefilter("error") # Treat warnings as errorsmodel.save_pretrained("test_output")print("✅ Standard save_pretrained completed successfully!")except Exception as e:diff --git a/tests/saving/non_peft/test_whisper_non_peft.py b/tests/saving/non_peft/test_whisper_non_peft.pyindex 2d5676ec9c1..b0f2b2e751d 100644--- a/tests/saving/non_peft/test_whisper_non_peft.py+++ b/tests/saving/non_peft/test_whisper_non_peft.py@@ -27,8 +27,6 @@ model, tokenizer = FastModel.from_pretrained(print("✅ Base model loaded successfully!")-### Attempting save merge-print(f"\n{'='*80}")print("🔍 PHASE 2: Attempting save_pretrained_merged (Should Warn)")@@ -38,7 +36,6 @@ with warnings.catch_warnings(record = True) as w:warnings.simplefilter("always")model.save_pretrained_merged("test_output", tokenizer)- # Verify warningassert len(w) >= 1, "Expected warning but none raised"warning_msg = str(w[0].message)expected_msg = "Model is not a PeftModel (no Lora adapters detected). Skipping Merge. Please use save_pretrained() or push_to_hub() instead!"diff --git a/tests/saving/test_unsloth_save.py b/tests/saving/test_unsloth_save.pyindex c7dd712734a..a85c119e04d 100644--- a/tests/saving/test_unsloth_save.py+++ b/tests/saving/test_unsloth_save.py@@ -31,7 +31,6 @@ torchao_models = []-# Variablessave_file_sizes = {}save_file_sizes["merged_16bit"] = {}save_file_sizes["merged_4bit"] = {}@@ -55,7 +54,6 @@ def loaded_model_tokenizer(request):load_in_4bit = True,)- # Apply LoRAmodel = FastModel.get_peft_model(model,r = 16,@@ -80,7 +78,6 @@ def fp16_model_tokenizer(request):load_in_4bit = False, # No BnB quantization)- # Apply LoRAmodel = FastModel.get_peft_model(model,r = 16,@@ -112,7 +109,6 @@ def temp_save_dir():def delete_quantization_config(model):- # Since merged, edit quantization_configold_config = model.confignew_config = model.config.to_dict()if "quantization_config" in new_config:@@ -134,7 +130,6 @@ def test_save_merged_16bit(model, tokenizer, temp_save_dir: str):model.save_pretrained_merged(save_path, tokenizer = tokenizer, save_method = "merged_16bit")- # Check model filesassert os.path.isdir(save_path), f"Directory {save_path} does not exist."assert os.path.isfile(os.path.join(save_path, "config.json")), "config.json not found."@@ -143,25 +138,23 @@ def test_save_merged_16bit(model, tokenizer, temp_save_dir: str):]assert len(weight_files) > 0, "No weight files found in the save directory."- # Check tokenizer filesfor file in tokenizer_files:assert os.path.isfile(os.path.join(save_path, file)), f"{file} not found in the save directory."- # Check config to see if it is 16bit by checking for quantization config+ # 16bit if there's no quantization configconfig_path = os.path.join(save_path, "config.json")with open(config_path, "r") as f:config = json.load(f)assert "quantization_config" not in config, "Quantization config not found in the model config."- # Store the size of the model filestotal_size = sum(os.path.getsize(os.path.join(save_path, f)) for f in weight_files)save_file_sizes["merged_16bit"][model.config._name_or_path] = total_sizeprint(f"Total size of merged_16bit files: {total_size} bytes")- # Test loading the model from the saved path+ # Verify the saved model loadsloaded_model, loaded_tokenizer = FastLanguageModel.from_pretrained(save_path,max_seq_length = 128,@@ -179,7 +172,6 @@ def test_save_merged_4bit(model, tokenizer, temp_save_dir: str):model.save_pretrained_merged(save_path, tokenizer = tokenizer, save_method = "merged_4bit_forced")- # Check model filesassert os.path.isdir(save_path), f"Directory {save_path} does not exist."assert os.path.isfile(os.path.join(save_path, "config.json")), "config.json not found."@@ -188,13 +180,11 @@ def test_save_merged_4bit(model, tokenizer, temp_save_dir: str):]assert len(weight_files) > 0, "No weight files found in the save directory."- # Check tokenizer filesfor file in tokenizer_files:assert os.path.isfile(os.path.join(save_path, file)), f"{file} not found in the save directory."- # Store the size of the model filestotal_size = sum(os.path.getsize(os.path.join(save_path, f)) for f in weight_files)save_file_sizes["merged_4bit"][model.config._name_or_path] = total_size@@ -204,14 +194,14 @@ def test_save_merged_4bit(model, tokenizer, temp_save_dir: str):total_size < save_file_sizes["merged_16bit"][model.config._name_or_path]), "Merged 4bit files are larger than merged 16bit files."- # Check config to see if it is 4bit+ # 4bit if there's a quantization configconfig_path = os.path.join(save_path, "config.json")with open(config_path, "r") as f:config = json.load(f)assert "quantization_config" in config, "Quantization config not found in the model config."- # Test loading the model from the saved path+ # Verify the saved model loadsloaded_model, loaded_tokenizer = FastModel.from_pretrained(save_path,max_seq_length = 128,@@ -248,7 +238,6 @@ def test_save_torchao(fp16_model_tokenizer, temp_save_dir: str):torchao_save_path = save_path + "-torchao"- # Check model filesassert os.path.isdir(torchao_save_path), f"Directory {torchao_save_path} does not exist."assert os.path.isfile(os.path.join(torchao_save_path, "config.json")), "config.json not found."@@ -257,13 +246,11 @@ def test_save_torchao(fp16_model_tokenizer, temp_save_dir: str):]assert len(weight_files) > 0, "No weight files found in the save directory."- # Check tokenizer filesfor file in tokenizer_files:assert os.path.isfile(os.path.join(torchao_save_path, file)), f"{file} not found in the save directory."- # Store the size of the model filestotal_size = sum(os.path.getsize(os.path.join(torchao_save_path, f)) for f in weight_files)save_file_sizes["torchao"][model.config._name_or_path] = total_size@@ -271,16 +258,14 @@ def test_save_torchao(fp16_model_tokenizer, temp_save_dir: str):total_size < save_file_sizes["merged_16bit"][model.config._name_or_path]), "torchao files are larger than merged 16bit files."- # Check config to see if it is quantized with torchaoconfig_path = os.path.join(torchao_save_path, "config.json")with open(config_path, "r") as f:config = json.load(f)assert "quantization_config" in config, "Quantization config not found in the model config."- # Test loading the model from the saved path- # can't set `load_in_4bit` to True because the model is torchao quantized- # can't quantize again with bitsandbytes+ # load_in_4bit must stay False: a torchao-quantized model can't be+ # re-quantized with bitsandbytes.import torch.serializationwith torch.serialization.safe_globals([getattr]):@@ -308,7 +293,6 @@ def test_save_and_inference_torchao(fp16_model_tokenizer, temp_save_dir: str):torchao_config = Int8DynamicActivationInt8WeightConfig()- # Save with TorchAOmodel.save_pretrained_torchao(save_path,tokenizer = tokenizer,@@ -318,12 +302,10 @@ def test_save_and_inference_torchao(fp16_model_tokenizer, temp_save_dir: str):torchao_save_path = save_path + "-torchao"- # Verify files existassert os.path.isdir(torchao_save_path), f"TorchAO directory {torchao_save_path} does not exist."- # Load with safe globalsimport torch.serializationwith torch.serialization.safe_globals([getattr]):@@ -334,7 +316,7 @@ def test_save_and_inference_torchao(fp16_model_tokenizer, temp_save_dir: str):load_in_4bit = False,)- FastModel.for_inference(loaded_model) # Enable native 2x faster inference+ FastModel.for_inference(loaded_model)messages = [{@@ -345,21 +327,20 @@ def test_save_and_inference_torchao(fp16_model_tokenizer, temp_save_dir: str):inputs = loaded_tokenizer.apply_chat_template(messages,tokenize = True,- add_generation_prompt = True, # Must add for generation+ add_generation_prompt = True, # required for generationreturn_tensors = "pt",).to("cuda")- outputs = loaded_model.generate( # ← Use loaded_model, not model+ outputs = loaded_model.generate(input_ids = inputs,max_new_tokens = 64,- use_cache = False, # Avoid cache issues+ use_cache = False, # avoid cache issuestemperature = 1.5,min_p = 0.1,do_sample = True,pad_token_id = loaded_tokenizer.pad_token_id or loaded_tokenizer.eos_token_id,)- # Decode with the LOADED tokenizergenerated_text = loaded_tokenizer.decode(outputs[0], skip_special_tokens = True)input_text = loaded_tokenizer.decode(inputs[0], skip_special_tokens = True)response_part = generated_text[len(input_text) :].strip()diff --git a/tests/saving/text_to_speech_models/test_csm.py b/tests/saving/text_to_speech_models/test_csm.pyindex dd2287d1d64..3d04bc39cb2 100644--- a/tests/saving/text_to_speech_models/test_csm.py+++ b/tests/saving/text_to_speech_models/test_csm.py@@ -139,15 +139,13 @@ try:inputs = processor(f"[{speaker_id}]{text}", add_special_tokens = True).to("cuda")audio_values = model.generate(**inputs,- max_new_tokens = 125, # 125 tokens is 10 seconds of audio, for longer speech increase this- # play with these parameters to get the best results+ max_new_tokens = 125, # 125 tokens ~= 10 seconds of audiodepth_decoder_temperature = 0.6,depth_decoder_top_k = 0,depth_decoder_top_p = 0.9,temperature = 0.8,top_k = 50,top_p = 1.0,- #########################################################output_audio = True,)audio = audio_values[0].to(torch.float32).cpu().numpy()@@ -157,8 +155,6 @@ except Exception as e:assert False, f"Inference failed with exception: {e}"-## assert that transcribed_text contains The birch canoe slid on the smooth planks. Glued the sheet to the dark blue background. It's easy to tell the depth of a well. Four hours of steady work faced us.-print("✅ All sections passed successfully!")diff --git a/tests/saving/text_to_speech_models/test_orpheus.py b/tests/saving/text_to_speech_models/test_orpheus.pyindex 2915749d998..83adaf8dbc5 100644--- a/tests/saving/text_to_speech_models/test_orpheus.py+++ b/tests/saving/text_to_speech_models/test_orpheus.py@@ -99,7 +99,7 @@ print("🔍 SECTION 4: Saving and Merging Model")print(f"{'='*80}")with warnings.catch_warnings():- warnings.simplefilter("error") # Treat warnings as errors+ warnings.simplefilter("error")try:model.save_pretrained_merged("orpheus", tokenizer)print("✅ Model saved and merged successfully without warnings!")@@ -135,7 +135,6 @@ print(f"{'='*80}")FastLanguageModel.for_inference(model) # Enable native 2x faster inference-# Moving snac_model cuda to cpusnac_model.to("cpu")prompts = ["Hey there my name is Elise, <giggles> and I'm a speech generation model that can sound like a person.",@@ -263,7 +262,6 @@ try:except Exception as e:assert False, f"Inference failed with exception: {e}"-# Verify the file existsimport osassert os.path.exists(output_path), f"Audio file not found at {output_path}"diff --git a/tests/saving/text_to_speech_models/test_whisper.py b/tests/saving/text_to_speech_models/test_whisper.pyindex d0eeb49d177..e0271d098e2 100644--- a/tests/saving/text_to_speech_models/test_whisper.py+++ b/tests/saving/text_to_speech_models/test_whisper.py@@ -153,7 +153,6 @@ import torchFastModel.for_inference(model)model.eval()-# Create pipeline without specifying the devicewhisper = pipeline("automatic-speech-recognition",model = model,@@ -161,9 +160,8 @@ whisper = pipeline(feature_extractor = tokenizer.feature_extractor,processor = tokenizer,return_language = True,- torch_dtype = torch.float16, # Remove the device parameter+ torch_dtype = torch.float16,)-# Example usageaudio_file = "Speech_12dB_s16.flac"transcribed_text = whisper(audio_file)# audio, sr = sf.read(audio_file)diff --git a/tests/saving/vision_models/test_index_file_sharded_model.py b/tests/saving/vision_models/test_index_file_sharded_model.pyindex 79a25ec6665..6f2d0ff7827 100644--- a/tests/saving/vision_models/test_index_file_sharded_model.py+++ b/tests/saving/vision_models/test_index_file_sharded_model.py@@ -1,5 +1,3 @@-## Import required libraries-from unsloth import FastVisionModel, is_bf16_supportedfrom unsloth.trainer import UnslothVisionDataCollator@@ -18,14 +16,10 @@ sys.path.insert(0, str(REPO_ROOT))from tests.utils.cleanup_utils import safe_remove_directory-## Dataset Preparation"""-print("\n📊 Loading and preparing dataset...")dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train")-# To select the first 2000 examplestrain_dataset = dataset.select(range(2000))-# To select the next 200 examples for evaluationeval_dataset = dataset.select(range(2000, 2200))print(f"✅ Dataset loaded successfully!")@@ -33,7 +27,7 @@ print(f" 📈 Training samples: {len(train_dataset)}")print(f" 📊 Evaluation samples: {len(eval_dataset)}")-# Convert dataset to OAI messages+# Convert dataset to OAI messages.def format_data(sample):return {"messages": [@@ -64,8 +58,7 @@ def format_data(sample):print("\n🔄 Formatting dataset for vision training...")system_message = "You are an expert french ocr system."-# Convert dataset to OAI messages-# need to use list comprehension to keep Pil.Image type, .map convert image to bytes+# List comprehension (not .map) keeps PIL.Image type; .map would convert images to bytes.train_dataset = [format_data(sample) for sample in train_dataset]eval_dataset = [format_data(sample) for sample in eval_dataset]print("✅ Dataset formatting completed!")@@ -76,11 +69,9 @@ print("✅ Dataset formatting completed!")print("\n" + "=" * 80)print("=== MODEL LOADING AND SETUP ===".center(80))print("=" * 80 + "\n")-# Load Base Modelprint("🤖 Loading base vision model...")try:model, tokenizer = FastVisionModel.from_pretrained(- # model_name = "unsloth/Qwen2-VL-7B-Instruct",model_name = "unsloth/Qwen2-VL-7B-Instruct",max_seq_length = 2048, # Choose any for long context!load_in_4bit = True, # 4 bit quantization to reduce memory@@ -92,7 +83,6 @@ except Exception as e:raiseprint("\n🔧 Setting up LoRA configuration...")-## Lora Finetuningtry:model = FastVisionModel.get_peft_model(model,@@ -175,7 +165,6 @@ except Exception as e:print("\n" + "=" * 80)print("=== STARTING TRAINING ===".center(80))print("=" * 80 + "\n")-# run trainingtry:print("🚀 Starting training process...")trainer_stats = trainer.train()@@ -213,7 +202,7 @@ success = {"safetensors_check": False,"download": False,}-# Stage 1: Upload model to Hub+# Stage 1: upload model to Hubtry:print("\n" + "=" * 80)print("=== UPLOADING MODEL TO HUB ===".center(80))@@ -226,7 +215,7 @@ except Exception as e:print(f"❌ Failed to upload model: {e}")raise Exception("Model upload failed.")-# Stage 2: Verify safetensors.index.json exists+# Stage 2: verify safetensors.index.json existstry:print("\n" + "=" * 80)print("=== VERIFYING REPO CONTENTS ===".center(80))@@ -245,7 +234,7 @@ except Exception as e:print(f"❌ Verification failed: {e}")raise Exception("Repo verification failed.")-# test downloading model even if cached+# Stage 3: test download even if cachedsafe_remove_directory(f"./{hf_username}")try:@@ -253,19 +242,16 @@ try:print("=== TESTING MODEL DOWNLOAD ===".center(80))print("=" * 80 + "\n")print("📥 Testing model download...")- # Force download even if cachedtest_model, test_tokenizer = FastVisionModel.from_pretrained(repo_name)success["download"] = Trueprint("✅ Model downloaded successfully!")- # Clean up test modeldel test_model, test_tokenizertorch.cuda.empty_cache()except Exception as e:print(f"❌ Download failed: {e}")raise Exception("Model download failed.")-# Final reportprint("\n" + "=" * 80)print("=== VALIDATION REPORT ===".center(80))print("=" * 80 + "\n")@@ -281,7 +267,6 @@ else:raise Exception("Validation failed for one or more stages.")-# Final cleanupprint("\n🧹 Cleaning up temporary files...")safe_remove_directory("./checkpoints")safe_remove_directory("./unsloth_compiled_cache")diff --git a/tests/saving/vision_models/test_push_to_hub_merged.py b/tests/saving/vision_models/test_push_to_hub_merged.pyindex 86c7b56cf20..d83c66de4be 100644--- a/tests/saving/vision_models/test_push_to_hub_merged.py+++ b/tests/saving/vision_models/test_push_to_hub_merged.py@@ -23,10 +23,10 @@ from tests.utils.cleanup_utils import safe_remove_directoryprint("\n📊 Loading and preparing dataset...")dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train")-# To select the first 2000 examples+# First 2000 examples for trainingtrain_dataset = dataset.select(range(2000))-# To select the next 200 examples for evaluation+# Next 200 examples for evaluationeval_dataset = dataset.select(range(2000, 2200))print(f"✅ Dataset loaded successfully!")@@ -65,8 +65,7 @@ def format_data(sample):print("\n🔄 Formatting dataset for vision training...")system_message = "You are an expert french ocr system."-# Convert dataset to OAI messages-# need to use list comprehension to keep Pil.Image type, .map convert image to bytes+# Use a list comprehension (not .map) to keep PIL.Image type; .map converts images to bytes.train_dataset = [format_data(sample) for sample in train_dataset]eval_dataset = [format_data(sample) for sample in eval_dataset]print("✅ Dataset formatting completed!")diff --git a/tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.py b/tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.pyindex 391d7baccad..548e6bfc37e 100644--- a/tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.py+++ b/tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.py@@ -23,10 +23,7 @@ from tests.utils.ocr_eval import OCRModelEvaluatorfrom datasets import load_datasetdataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train")-# To select the first 2000 examplestrain_dataset = dataset.select(range(2000))--# To select the next 200 examples for evaluationeval_dataset = dataset.select(range(2000, 2200))@@ -60,8 +57,7 @@ def format_data(sample):system_message = "You are an expert french ocr system."-# Convert dataset to OAI messages-# need to use list comprehension to keep Pil.Image type, .map convert image to bytes+# List comprehension (not .map) to keep PIL.Image type; .map converts images to bytes.train_dataset = [format_data(sample) for sample in train_dataset]eval_dataset = [format_data(sample) for sample in eval_dataset]@@ -73,12 +69,10 @@ import pandas as pdfrom jiwer import wer, cerfrom qwen_vl_utils import process_vision_info-#ocr_evaluator = OCRModelEvaluator()model_comparison_results = {}## Finetuning Setup and Run-# Load Base Modelmodel, tokenizer = FastVisionModel.from_pretrained(model_name = "unsloth/Qwen2.5-VL-32B-Instruct-bnb-4bit",@@ -88,7 +82,7 @@ model, tokenizer = FastVisionModel.from_pretrained(full_finetuning = False, # [NEW!] We have full finetuning now!)-# benchmark base model performance+# Benchmark base modelmodel_name = "Unsloth Base model"FastVisionModel.for_inference(model)avg_wer, avg_cer = ocr_evaluator.evaluate_model(@@ -119,7 +113,7 @@ model = FastVisionModel.get_peft_model(from unsloth import is_bf16_supportedfrom unsloth.trainer import UnslothVisionDataCollator-FastVisionModel.for_training(model) # Enable for training!+FastVisionModel.for_training(model)model.config.use_cache = False@@ -159,7 +153,6 @@ trainer = SFTTrainer(),)-# run trainingtrainer_stats = trainer.train()model.save_pretrained("unsloth-qwen2.5-vl-32b-french-ocr-adapter", tokenizer)@@ -167,7 +160,6 @@ tokenizer.save_pretrained("unsloth-qwen2.5-vl-32b-french-ocr-adapter")## Measure Adapter Performance-# benchmark lora model performancemodel_name = "Unsloth lora adapter model"FastVisionModel.for_inference(model)avg_wer, avg_cer = ocr_evaluator.evaluate_model(@@ -191,7 +183,7 @@ base = find_lora_base_model(model)print((base.__class__.__name__))-# merge default 16 bits+# Merge to 16-bit (default)model.save_pretrained_merged(save_directory = "qwen2.5-ocr-merged-finetune-merge-16bit", tokenizer = tokenizer)@@ -205,7 +197,6 @@ model, tokenizer = FastVisionModel.from_pretrained("./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = False)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-16bits"model.config.use_cache = True@@ -217,12 +208,11 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-# load 16bits-merged model in 4 bits+# Load 16bits-merged model in 4 bitsmodel, tokenizer = FastVisionModel.from_pretrained("./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = True, load_in_8bit = False)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-4bits"model.config.use_cache = True@@ -234,12 +224,11 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-# load model in 8 bits+# Load 16bits-merged model in 8 bitsmodel, tokenizer = FastVisionModel.from_pretrained("./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = True)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-8bits"avg_wer, avg_cer = ocr_evaluator.evaluate_model(model,@@ -270,7 +259,6 @@ ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)# ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)# Model comparison report-# print model comparisonocr_evaluator.print_model_comparison()diff --git a/tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.py b/tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.pyindex b4812cdfa8b..66064600eae 100644--- a/tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.py+++ b/tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.py@@ -19,18 +19,15 @@ from tests.utils.cleanup_utils import safe_remove_directoryfrom tests.utils.ocr_eval import OCRModelEvaluator-## Dataset Preparationfrom datasets import load_datasetdataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train")-# To select the first 2000 examplestrain_dataset = dataset.select(range(2000))-# To select the next 200 examples for evaluationeval_dataset = dataset.select(range(2000, 2200))-# Convert dataset to OAI messages+# Convert dataset to OAI messages.def format_data(sample):return {"messages": [@@ -60,12 +57,10 @@ def format_data(sample):system_message = "You are an expert french ocr system."-# Convert dataset to OAI messages-# need to use list comprehension to keep Pil.Image type, .map convert image to bytes+# List comprehension (not .map) keeps PIL.Image type; .map would convert images to bytes.train_dataset = [format_data(sample) for sample in train_dataset]eval_dataset = [format_data(sample) for sample in eval_dataset]-## Setup OCR main evaluation function and helpersimport osimport torchfrom tqdm import tqdm@@ -73,13 +68,9 @@ import pandas as pdfrom jiwer import wer, cerfrom qwen_vl_utils import process_vision_info-#ocr_evaluator = OCRModelEvaluator()model_comparison_results = {}-## Finetuning Setup and Run-# Load Base Model-model, tokenizer = FastVisionModel.from_pretrained(model_name = "unsloth/Qwen2-VL-7B-Instruct",max_seq_length = 2048, # Choose any for long context!@@ -88,7 +79,7 @@ model, tokenizer = FastVisionModel.from_pretrained(full_finetuning = False, # [NEW!] We have full finetuning now!)-# benchmark base model performance+# Benchmark base model performance.model_name = "Unsloth Base model"FastVisionModel.for_inference(model)avg_wer, avg_cer = ocr_evaluator.evaluate_model(@@ -96,7 +87,6 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-## Lora Finetuningmodel = FastVisionModel.get_peft_model(model,finetune_vision_layers = True, # Turn off for just text!@@ -159,15 +149,12 @@ trainer = SFTTrainer(),)-# run trainingtrainer_stats = trainer.train()model.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter", tokenizer)tokenizer.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter")-## Measure Adapter Performance--# benchmark lora model performance+# Benchmark lora adapter model performance.model_name = "Unsloth lora adapter model"FastVisionModel.for_inference(model)avg_wer, avg_cer = ocr_evaluator.evaluate_model(@@ -175,8 +162,6 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-## Merge Model-def find_lora_base_model(model_to_inspect):current = model_to_inspect@@ -191,21 +176,17 @@ base = find_lora_base_model(model)print((base.__class__.__name__))-# merge default 16 bits+# Merge at default 16 bits.model.save_pretrained_merged(save_directory = "qwen2-ocr-merged-finetune-merge-16bit", tokenizer = tokenizer)-## Benchmark merged model performance--### 16 bits merged model-+# Benchmark 16-bit merged model loaded at various precisions.model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = False)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-16bits"model.config.use_cache = True@@ -217,12 +198,11 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-# load 16bits-merged model in 4 bits+# Load 16bits-merged model in 4 bits.model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = True, load_in_8bit = False)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-4bits"model.config.use_cache = True@@ -234,12 +214,11 @@ avg_wer, avg_cer = ocr_evaluator.evaluate_model()ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-# load model in 8 bits+# Load 16bits-merged model in 8 bits.model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = True)-# benchmark 4bit loaded, 16bits merged model performancemodel_name = "Unsloth 16bits-merged model load-8bits"avg_wer, avg_cer = ocr_evaluator.evaluate_model(model,@@ -269,12 +248,9 @@ ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)# avg_wer, avg_cer = ocr_evaluator.evaluate_model(model, tokenizer, eval_dataset, output_dir="unsloth_4bits_merged_model_load_8bits_results")# ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer)-# Model comparison report-# print model comparisonocr_evaluator.print_model_comparison()-# Final cleanupprint("\n🧹 Cleaning up temporary files...")safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-adapter")safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-checkpoints")diff --git a/tests/security/conftest.py b/tests/security/conftest.pyindex 6febeec3e7b..c5071842e54 100644--- a/tests/security/conftest.py+++ b/tests/security/conftest.py@@ -1,11 +1,8 @@"""Shared fixtures for the security regression suite.-The scanner scripts under audit are designed to be offline-safe. Pin-that invariant by autouse-installing a session-scoped network blocker-that refuses any non-loopback `socket.connect()` from inside the test-process. If a future test (or a scanner regression) accidentally tries-to reach the public internet, pytest fails loudly instead of leaking-the request.+The scanners under audit must be offline-safe. An autouse session-scoped network+blocker refuses any non-loopback `socket.connect()` so a regression that reaches+the internet fails loudly instead of leaking the request."""from __future__ import annotations@@ -17,8 +14,7 @@ from pathlib import Pathimport pytest-# Make `scripts/` importable as a package so tests can grab the scanner-# constants directly. The repo root sits two levels above this file.+# Make `scripts/` importable so tests can grab scanner constants directlyREPO_ROOT = Path(__file__).resolve().parents[2]if str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))@@ -70,11 +66,8 @@ class _BlockedSocket(socket.socket):@pytest.fixture(scope = "session", autouse = True)def network_blocker():- """Session-scoped fixture; replaces `socket.socket` with a blocker.-- Yields nothing; the swap is the side effect. Restored at teardown- so other test sessions (run interleaved) see a clean module.- """+ """Session-scoped fixture; swaps `socket.socket` for a blocker, restored at+ teardown so interleaved sessions see a clean module."""original = socket.socketsocket.socket = _BlockedSocket # type: ignore[assignment]try:diff --git a/tests/security/fixtures/_build.py b/tests/security/fixtures/_build.pyindex b2f862a23ed..4cbda6aab54 100644--- a/tests/security/fixtures/_build.py+++ b/tests/security/fixtures/_build.py@@ -1,20 +1,12 @@"""Deterministic builder for the wheel + sdist binary fixtures.-This script is NOT run from CI; the produced .whl / .tar.gz bytes are-committed alongside it. Re-run only when the IOC literal changes.--Determinism strategy----------------------- All member timestamps fixed to `SOURCE_DATE_EPOCH=0` (Unix epoch).-- All members written with uid=0, gid=0, uname="", gname="".-- Permission bits fixed: 0o644 for files, 0o755 for directories.-- Members emitted in sorted order so the archive byte stream does not- depend on filesystem iteration order.-- `zipfile.ZipFile` is invoked with `compresslevel=6` (default DEFLATE)- to keep output stable across stdlib versions.--Re-running this script and diffing the .whl bytes against git is the-regression test for determinism (also asserted in test_scan_packages).+Not run from CI; the produced .whl / .tar.gz bytes are committed alongside+it. Re-run only when the IOC literal changes.++Determinism: fixed timestamps (SOURCE_DATE_EPOCH=0), uid/gid=0, empty+uname/gname, fixed perms (0o644 files / 0o755 dirs), sorted member order,+and DEFLATE compresslevel=6 for stability across stdlib versions. Diffing+re-built .whl bytes against git is the regression test (see test_scan_packages)."""from __future__ import annotations@@ -33,9 +25,8 @@ _ZIP_DOS_EPOCH = (1980, 1, 1, 0, 0, 0)HERE = Path(__file__).resolve().parent-# The IOC literal that scan_packages.py must trip on. Keep this in-# sync with KNOWN_IOC_STRINGS in scripts/scan_npm_packages.py and-# RE_MAY12_IOC in scripts/scan_packages.py.+# IOC literal scan_packages.py must trip on. Keep in sync with+# KNOWN_IOC_STRINGS (scan_npm_packages.py) and RE_MAY12_IOC (scan_packages.py).MALICIOUS_SETUP_PY = '''"""Test fixture: do NOT install.This file embeds the May-12 Mini Shai-Hulud IOC literal so thediff --git a/tests/security/test_lockfile_supply_chain_audit.py b/tests/security/test_lockfile_supply_chain_audit.pyindex cec07aea28f..905c4afcac2 100644--- a/tests/security/test_lockfile_supply_chain_audit.py+++ b/tests/security/test_lockfile_supply_chain_audit.py@@ -51,10 +51,8 @@ def _run_auditor(def test_malicious_lockfile_exits_1(tmp_path):- """The malicious fixture combines a non-registry resolved URL, a- known IOC substring (`filev2.getsession.org`), and a missing- integrity hash. The auditor must refuse with exit 1.- """+ """Fixture combines a non-registry resolved URL, a known IOC substring+ (`filev2.getsession.org`), and a missing integrity hash: auditor exits 1."""fixture = FIXTURES / "malicious_lockfile.json"assert fixture.is_file()proc = _run_auditor(root = tmp_path, npm_lockfiles = [fixture])@@ -66,13 +64,9 @@ def test_malicious_lockfile_exits_1(tmp_path):assert "non-registry-resolved-url" in combinedassert "missing-integrity-hash" in combinedassert "known-ioc-string" in combined- # Verify the scanner WROTE the IOC name into its stdout/stderr. The- # literal is constructed at runtime so CodeQL's- # py/incomplete-url-substring-sanitization rule (which fires on- # source-literal + `in` even when the operand is the scanner's own- # output, not a URL being sanitized) does not false-positive across- # pre-commit reformatting that may split the assert onto multiple- # lines and detach an inline lgtm comment from the operator.+ # IOC literal built at runtime so CodeQL's+ # py/incomplete-url-substring-sanitization rule doesn't false-positive on+ # the source-literal + `in` (the operand is the scanner's own output)._ioc_host = "filev2." + "getsession.org"assert _ioc_host in combined@@ -170,15 +164,9 @@ checksum = "0000000000000000000000000000000000000000000000000000000000000000"def test_malicious_cargo_lockfile_refused(tmp_path):- """Inline Cargo.lock with `source = "git+https://example.com/..."`- must trip the `non-registry-cargo-source` check.-- `non-registry-cargo-source` is an advisory finding kind in the- auditor's default mode (per the audit script's BLOCKING_KINDS- set). To exercise the historical "refuse to install" behavior we- pass --strict here; that promotes every finding to blocking and- keeps the test honest about its intent (detection + refusal).- """+ """Inline Cargo.lock with a `git+https://...` source must trip the+ `non-registry-cargo-source` check. It's advisory in default mode, so+ --strict promotes it to blocking to exercise the refuse-to-install path."""lockfile = tmp_path / "Cargo.lock"lockfile.write_text(_MALICIOUS_CARGO_LOCK)proc = _run_auditor(@@ -231,13 +219,9 @@ def test_audit_cargo_lockfile_direct_call(tmp_path):def test_gha_escape_collapses_finding_to_one_line():- """`_gha_escape()` must collapse newlines (`%0A`), carriage- returns (`%0D`), and percent signs (`%25`) so that- `::warning::<msg>` / `::error::<msg>` render the full finding- in the GitHub Actions UI annotation instead of being truncated- at the first newline. The `%` replacement must happen first or- the subsequent `%0A` / `%0D` escapes get double-encoded.- """+ """`_gha_escape()` collapses newlines (`%0A`), carriage returns (`%0D`),+ and percent signs (`%25`) so GHA annotations aren't truncated at the first+ newline. `%` must escape first or the `%0A`/`%0D` escapes double-encode."""assert lsa._gha_escape("a\nb\nc") == "a%0Ab%0Ac"assert lsa._gha_escape("a\rb") == "a%0Db"assert lsa._gha_escape("100%") == "100%25"@@ -260,13 +244,9 @@ def test_gha_escape_collapses_finding_to_one_line():def test_advisory_finding_emitted_as_single_line_annotation(tmp_path):- """End-to-end check: the `::warning::` line emitted for an- advisory finding must be a SINGLE physical line (the rest of- the Finding is `%0A`-escaped inside the message). Regression- test for the gemini-code-assist review on PR #5604: without- `_gha_escape`, GitHub Actions truncates the annotation after- `[kind] path` and the package + detail fields never render.- """+ """The `::warning::` line for an advisory finding must be a SINGLE physical+ line (rest of the Finding `%0A`-escaped). Regression for PR #5604: without+ `_gha_escape`, GHA truncates after `[kind] path` and drops package/detail."""lockfile = tmp_path / "Cargo.lock"lockfile.write_text(_MALICIOUS_CARGO_LOCK)proc = _run_auditor(@@ -296,11 +276,9 @@ def test_advisory_finding_emitted_as_single_line_annotation(tmp_path):def test_skip_env_var_with_short_value_rejected(tmp_path):- """`UNSLOTH_LOCKFILE_AUDIT_SKIP=1` used to silently bypass the- audit. Per SF4 it must instead emit a `::warning::` to stderr and- fall through to run the audit. A real justification value- (>=5 chars, not a boolean shape) is still honored.- """+ """`UNSLOTH_LOCKFILE_AUDIT_SKIP=1` must no longer silently bypass: per SF4+ it warns and falls through to run the audit. A real justification value+ (>=5 chars, not a boolean shape) is still honored."""fixture = FIXTURES / "clean_lockfile.json"# Case 1 -- "1" rejected, audit RUNS.diff --git a/tests/security/test_new_install_scripts.py b/tests/security/test_new_install_scripts.pyindex 9a73f4b0d95..e71659dd884 100644--- a/tests/security/test_new_install_scripts.py+++ b/tests/security/test_new_install_scripts.py@@ -44,9 +44,7 @@ def _write(path: Path, content: dict) -> Path:return path-# ----------------------------------------------------------------------------# Lockfile fixtures.-# ---------------------------------------------------------------------------+# Lockfile fixturesdef _v3_lockfile(packages: dict) -> dict:@@ -70,9 +68,7 @@ def _v2_lockfile(packages: dict, dependencies: dict) -> dict:}-# ----------------------------------------------------------------------------# Tests.-# ---------------------------------------------------------------------------+# Testsdef test_no_new_install_scripts_exit_0(tmp_path: Path):diff --git a/tests/security/test_scan_npm_packages.py b/tests/security/test_scan_npm_packages.pyindex fb575b730d2..2c79b9c3ed7 100644--- a/tests/security/test_scan_npm_packages.py+++ b/tests/security/test_scan_npm_packages.py@@ -46,14 +46,9 @@ def _run_scanner(lockfile: Path, *, timeout: int = 30) -> subprocess.CompletedPrdef test_malicious_lockfile_exits_1():- """Structural IOCs alone must fail the scanner.-- `structural_only_lockfile.json` contains: (a) a non-registry- `resolved` URL (filev2.getsession.org), (b) an entry missing- its `integrity` field. Both are caught in `parse_lockfile()`- before any tarball download attempt -- so the test is fully- offline.- """+ """Structural IOCs alone must fail the scanner. The fixture has a+ non-registry `resolved` URL and a missing `integrity` field, both caught in+ `parse_lockfile()` before any tarball download, so the test is offline."""fixture = FIXTURES / "structural_only_lockfile.json"assert fixture.is_file(), fixtureproc = _run_scanner(fixture)@@ -166,12 +161,8 @@ def test_blocked_npm_versions_complete():reason = "Fork 1 (BLOCKED_NPM_VERSIONS pre-fetch hook) not merged yet",)def test_blocked_npm_versions_short_circuits_download():- """With Fork 1's pre-fetch hook, the malicious tanstack entry- must produce a `blocked-known-malicious` finding without ever- calling out to the npm registry. The full malicious fixture- contains the tanstack entry; the test asserts exit 1 and that- the new finding pattern appears in scanner output.- """+ """The pre-fetch hook must flag the malicious tanstack entry as+ `blocked-known-malicious` (exit 1) without hitting the npm registry."""fixture = FIXTURES / "malicious_lockfile.json"proc = _run_scanner(fixture, timeout = 10)assert proc.returncode == 1@@ -203,10 +194,8 @@ def _extract_pkg_with_ioc(ioc: str, tmp_path: Path) -> Path:def test_every_known_ioc_string_caught(tmp_path):- """For every entry in `KNOWN_IOC_STRINGS`, embed the IOC in a- one-file package tree and confirm `scan_extracted_tree()`- surfaces it. Guards against silent regex / table drift.- """+ """Embed each `KNOWN_IOC_STRINGS` entry in a one-file package tree and+ confirm `scan_extracted_tree()` surfaces it. Guards against table drift."""iocs = snp.KNOWN_IOC_STRINGSassert iocs, "KNOWN_IOC_STRINGS unexpectedly empty"@@ -234,10 +223,8 @@ def test_every_known_ioc_string_caught(tmp_path):def test_parse_lockfile_structural_findings():- """`parse_lockfile()` returns (entries, structural_findings). The- structural-only fixture should produce 2 structural findings and- 0 entries (because both bad entries are `continue`d).- """+ """The structural-only fixture yields 2 structural findings and 0 entries+ (both bad entries are `continue`d in `parse_lockfile()`)."""entries, struct = snp.parse_lockfile(FIXTURES / "structural_only_lockfile.json")assert entries == []patterns = {f.pattern for f in struct}diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.pyindex b35d89ce489..5b6e1152138 100644--- a/tests/security/test_scan_packages.py+++ b/tests/security/test_scan_packages.py@@ -1,9 +1,8 @@"""Regression tests for `scripts/scan_packages.py`.-The scanner's primary entry point (`download_packages`) reaches PyPI;-to keep the suite offline we exercise it via the module's public-in-process helpers (`scan_archive`) and assert against the binary-wheel / sdist fixtures committed under `tests/security/fixtures/`.+`download_packages` reaches PyPI; to stay offline we drive the in-process+`scan_archive` helper against the wheel/sdist fixtures under+`tests/security/fixtures/`."""from __future__ import annotations@@ -37,9 +36,8 @@ def test_fixture_files_exist():def test_fixture_bytes_are_deterministic(tmp_path):"""Re-running `_build.py` must produce byte-identical archives.- The build helper sets every member's mtime/uid/gid/mode and emits- members in sorted order. We rebuild into a temp dir and compare- SHA-256 against the committed bytes.+ The build helper pins each member's mtime/uid/gid/mode and sorts members.+ Rebuild into a temp dir and compare SHA-256 against the committed bytes."""# Snapshot committed hashes.expected: dict[str, str] = {}@@ -53,7 +51,7 @@ def test_fixture_bytes_are_deterministic(tmp_path):builder_src = (FIXTURES / "_build.py").read_text()rebuilt_helper = rebuild_dir / "_build.py"rebuilt_helper.write_text(builder_src)- # Run with SOURCE_DATE_EPOCH=0 and HERE-override via a tiny shim.+ # Run with SOURCE_DATE_EPOCH=0 and HERE override via a tiny shim.shim = rebuild_dir / "run.py"shim.write_text("import sys, pathlib\n"@@ -168,20 +166,16 @@ def test_re_may12_ioc_catches_each_literal():reason = "Fork 1 (RE_MAY12_IOC integration) not merged yet",)def test_may12_ioc_caught_by_scan_archive():- """Once RE_MAY12_IOC is wired into check_py_file (per Fork 1's- plan), the malicious wheel's setup.py must produce a finding- that explicitly references the May-12 IOC string.+ """Once RE_MAY12_IOC is wired into check_py_file, the malicious wheel's+ setup.py must produce a finding referencing the May-12 IOC string."""findings = sp.scan_archive(str(FIXTURES / "malicious_wheel.whl"),"malicious_fixture",)- # The IOC literals are built at runtime so CodeQL's- # py/incomplete-url-substring-sanitization rule does not false-- # positive on the (literal `in` operand) pattern -- the operand is- # the scanner's own evidence string, not a URL being sanitized.- # Runtime construction also survives pre-commit reformatting that- # would otherwise detach an inline lgtm comment from the operator.+ # IOC literals built at runtime so CodeQL's url-substring-sanitization+ # rule doesn't false-positive on the `in` operand (it's evidence, not a+ # URL), and so reformatting can't detach an inline lgtm comment._ioc_host = "git-tanstack." + "com"_ioc_drop = "transformers." + "pyz"hit = any(@@ -202,16 +196,11 @@ def test_may12_ioc_caught_by_scan_archive():def test_scan_packages_pip_download_failure_propagates(tmp_path):- """A pip download failure must NOT be silently swallowed into a- `0 findings, exit 0` report. Item (4) of the silent-failure- hardening: an obviously unresolvable spec is fed to the scanner- as a subprocess; the orchestrator must exit 2 (scan incomplete)- and the stderr must carry the SCAN INCOMPLETE banner.-- The spec name is deliberately long + random-looking so it cannot- accidentally resolve on any real package index. We do not rely on- network reachability: even an offline runner will get a clean- "could not resolve" failure from pip.+ """A pip download failure must NOT be swallowed into `0 findings, exit 0`.++ Feeds an unresolvable spec to the scanner subprocess; it must exit 2+ (scan incomplete) with a SCAN INCOMPLETE banner on stderr. The spec name+ is long/random so it can't resolve on any index, even offline."""script = REPO_ROOT / "scripts" / "scan_packages.py"assert script.is_file(), script@@ -233,9 +222,8 @@ def test_scan_packages_pip_download_failure_propagates(tmp_path):def test_archive_corruption_produces_critical_finding(tmp_path):- """SF1: a corrupted wheel (truncated bytes) used to be silently- skipped by `except Exception: continue` inside iter_archive_files.- It must now yield a CRITICAL `archive_corrupted` finding.+ """SF1: a corrupted wheel was silently skipped by `except: continue` in+ iter_archive_files; it must now yield a CRITICAL `archive_corrupted`."""bad = tmp_path / "broken-0.0.1-py3-none-any.whl"bad.write_bytes(b"X") # 1-byte "wheel" -- not a valid zip containerdiff --git a/tests/studio/_playwright_robust.py b/tests/studio/_playwright_robust.pyindex 831153bf96f..bc0e3f783ba 100644--- a/tests/studio/_playwright_robust.py+++ b/tests/studio/_playwright_robust.py@@ -1,21 +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-"""Shared robustness helpers for the Studio Playwright tests.+"""Shared robustness helpers for the Studio Playwright tests, the single+point of truth for the CI-runner workarounds (Chromium flags, view-transition+killer, page recovery, post-action response wait) that both+`playwright_chat_ui.py` and `playwright_extra_ui.py` need.-Both `playwright_chat_ui.py` and `playwright_extra_ui.py` re-implemented-the same set of CI-runner workarounds (Chromium launch flags, view--transition CSS killer, change-password retry / page-recovery, post--action response wait). When one diverged the other slowly rotted; the-mac/win/linux failure modes are mostly identical so the cure is the-same. This module is the single point of truth.--Importable directly by the standalone scripts via:+Importable directly by the standalone scripts:sys.path.insert(0, str(Path(__file__).parent))from _playwright_robust import (...)-It does NOT depend on pytest -- both consumers run as plain Python.+Does NOT depend on pytest -- both consumers run as plain Python."""from __future__ import annotations@@ -30,28 +26,16 @@ import urllib.requestfrom pathlib import Pathfrom typing import Any, Callable-# ─────────────────────────────────────────────────────────────────────# Chromium launch args.-# ─────────────────────────────────────────────────────────────────────-#-# Base set works on every CI runner. The four "throttling" flags fight-# Chromium's tendency to deprioritise CPU + timers when it thinks the-# window is backgrounded -- which CI runners routinely flag because-# the headless context has no real focus. Without these, gemma-3-270m-# inference on Mac slowed to a crawl mid-test (run 25586583024 had a-# turn budget that never released the Stop button) and the React-# render queue stalled long enough for `wait_for_function` waits to-# crowd their per-turn budget.#-# `--disable-features=TranslateUI` strips the translate prompt that-# occasionally adds a popup which intercepts pointer events.-# `--disable-ipc-flooding-protection` lets us send rapid-fire clicks-# during the slider sweep without Chromium queuing them.+# The throttling flags stop Chromium deprioritising CPU/timers when it thinks+# the headless window is backgrounded (run 25586583024 stalled gemma-3-270m+# inference and the React render queue mid-test). TranslateUI strips a popup+# that intercepts pointer events; ipc-flooding-protection off lets rapid clicks+# through during the slider sweep.#-# `--single-process` is darwin-only. On Mac it is the documented free--# runner fix for the pipeTransport.js JSON-RPC crash; on Win/Linux it-# strictly destabilises the renderer-isolation safety net so any-# crash takes the whole context down.+# `--single-process` is darwin-only: the documented free-runner fix for the+# pipeTransport.js JSON-RPC crash; on Win/Linux it destabilises the renderer._BASE_CHROMIUM_ARGS = ("--disable-dev-shm-usage","--no-sandbox",@@ -65,11 +49,8 @@ _BASE_CHROMIUM_ARGS = (def chromium_launch_args(platform: str | None = None) -> list[str]:- """Return the Chromium launch arg list appropriate for `platform`.-- Defaults to the running interpreter's `sys.platform`. Pass a- string to test the darwin branch on Linux.- """+ """Return Chromium launch args for `platform` (defaults to `sys.platform`;+ pass a string to test the darwin branch on Linux)."""p = sys.platform if platform is None else platformargs = list(_BASE_CHROMIUM_ARGS)if p == "darwin":@@ -77,19 +58,14 @@ def chromium_launch_args(platform: str | None = None) -> list[str]:return args-# ─────────────────────────────────────────────────────────────────────# Init scripts injected into every Playwright context.-# ─────────────────────────────────────────────────────────────────────#-# CSS view-transitions are otherwise rendered as a full-window-# pseudo-element that intercepts pointer events for a beat after each-# theme/route swap. Even with `reduced_motion = "reduce"` set on the-# context, Studio's components run their own startViewTransition() in-# a few places (theme toggle, sidebar collapse) and Playwright's-# actionability check then reports `<html> intercepts pointer events`-# on the next click. Killing the pseudo-elements + monkey-patching-# document.startViewTransition into a synchronous shim removes both-# failure modes. Idempotent and safe to install on every page.+# CSS view-transitions render a full-window pseudo-element that intercepts+# pointer events for a beat after each theme/route swap, so Playwright reports+# `<html> intercepts pointer events` on the next click (even with+# reduced_motion, since Studio calls startViewTransition() directly). Killing+# the pseudo-elements + shimming startViewTransition synchronously fixes both.+# Idempotent and safe to install on every page._VIEW_TRANSITION_KILLER_JS = """(function () {try {@@ -130,16 +106,11 @@ def install_view_transition_killer(ctx: Any) -> None:ctx.add_init_script(_VIEW_TRANSITION_KILLER_JS)-# ─────────────────────────────────────────────────────────────────────# Server health pre-flight.-# ─────────────────────────────────────────────────────────────────────#-# Both workflows already wait for /api/health at the bash level before-# launching the Python script, but the macos-14 free runner has been-# observed to surface a brief window where /api/health responds 200-# yet /api/auth endpoints still 503 because the auth DB hasn't-# finished migrating. A second probe inside the script catches that-# narrow gap before we sink 60s into a change-password timeout.+# The bash wait already gates on /api/health, but on the macos-14 free runner+# /api/health can return 200 while /api/auth still 503s (auth DB mid-migration).+# A second in-script probe catches that gap before a 60s change-password timeout.def _http_get_status_and_body(url: str, timeout: float) -> tuple[int, dict | None]:@@ -162,13 +133,9 @@ def wait_for_health(timeout: float = 30.0,info: Callable[[str], None] | None = None,) -> bool:- """Poll {base_url}/api/health until status==200 with healthy body.-- Returns True on success, False on timeout. Never raises -- the- caller decides whether to fail. The test scripts use the boolean- only for diagnostic logging, since the workflow's own /api/health- wait is the authoritative gate.- """+ """Poll {base_url}/api/health until status==200. Returns True on success,+ False on timeout; never raises. Diagnostic only -- the workflow's own+ /api/health wait is the authoritative gate."""deadline = time.monotonic() + timeoutlast_status: int | None = Nonelast_body: dict | None = None@@ -193,14 +160,11 @@ def wait_for_health(return False-# ─────────────────────────────────────────────────────────────────────# Page recovery.-# ─────────────────────────────────────────────────────────────────────#-# The single canonical "did the page die mid-test" recovery path. Used-# by every retry block in both scripts. If the page is closed, opens a-# fresh one in the same context (auth state in localStorage survives);-# otherwise leaves the page alone. Optionally re-navigates.+# Canonical "did the page die mid-test" path used by every retry block. If the+# page is closed, opens a fresh one in the same context (localStorage auth+# survives); otherwise leaves it alone. Optionally re-navigates.def recover_or_replace_page(@@ -212,13 +176,9 @@ def recover_or_replace_page(settle_networkidle: bool = True,info: Callable[[str], None] | None = None,) -> Any:- """Return a usable page. Replaces `page` if it is closed.-- If `goto_url` is provided, navigates the (possibly new) page there- and best-effort waits for networkidle. Errors during recovery are- logged through `info` (if provided) and swallowed -- the caller- handles a still-broken page on the next retry iteration.- """+ """Return a usable page, replacing `page` if it is closed. If `goto_url` is+ given, navigates there and best-effort waits for networkidle. Recovery+ errors are logged and swallowed; the caller retries a still-broken page."""try:if page.is_closed():page = ctx.new_page()@@ -254,15 +214,10 @@ def click_and_wait_for_response(timeout_ms: int = 30_000,info: Callable[[str], None] | None = None,) -> tuple[int | None, Exception | None]:- """Click + wait for the matching XHR/fetch response in one step.-- Returns (status, err). On success: (status, None). On failure to- capture the response: (None, exception). Callers typically check- `status >= 400` to surface a server-side rejection immediately- rather than discovering it 60s later via a downstream wait_for.- Falls back to a fire-and-forget click on any wait error so the- outer retry loop still runs.- """+ """Click + wait for the matching XHR/fetch response. Returns (status, None)+ on success or (None, exception) on capture failure. Callers check+ `status >= 400` to surface server rejections immediately. Falls back to a+ fire-and-forget click on any wait error so the outer retry loop runs."""try:with page.expect_response(lambda r: url_substr in r.url and r.request.method == method,@@ -284,19 +239,13 @@ def click_and_wait_for_response(return None, exc-# ─────────────────────────────────────────────────────────────────────# Console-error / page-error filtering.-# ─────────────────────────────────────────────────────────────────────#-# Two categories:-# - BENIGN_PAGE_ERROR_PATTERNS: thrown JS errors that fire as a side-# effect of slow CI infra (server timeouts, request races) and have-# no user-visible consequence. The page-error gate at the end of-# each test should NOT count these.-# - BENIGN_CONSOLE_ERROR_PATTERNS: console.error events that fire-# for the same reason. Tests don't gate on console.error today-# (they only count for diagnostics), but the same list is useful-# for filtering noise out of the diagnostic dumps.+# - BENIGN_PAGE_ERROR_PATTERNS: JS errors from slow CI infra (timeouts,+# request races) with no user-visible effect; the page-error gate must not+# count these.+# - BENIGN_CONSOLE_ERROR_PATTERNS: same-cause console.error events, used only+# to filter noise from diagnostic dumps (tests don't gate on console.error).BENIGN_PAGE_ERROR_PATTERNS: tuple[str, ...] = ("Request failed (422)",@@ -308,21 +257,15 @@ BENIGN_PAGE_ERROR_PATTERNS: tuple[str, ...] = ()BENIGN_CONSOLE_ERROR_PATTERNS: tuple[str, ...] = (- # macos-14 free runner buffer-exhaustion under --single-process- # Chromium. The browser surfaces this on resource fetches but the- # test catches the underlying request failure via expect_response- # and retries; the console line itself is informational.+ # macos-14 buffer-exhaustion under --single-process; the test catches the+ # underlying request failure via expect_response and retries."net::ERR_NO_BUFFER_SPACE",- # Chromium emits a console.error every time a fetch is aborted,- # even when the abort is intentional (component unmount, route- # change). All four scripts trigger several of these per run.+ # Intentional fetch aborts (unmount, route change) log a console.error."AbortError","The user aborted a request",- # Same shape: lazy-loaded chunk that's no longer needed because- # the user navigated away mid-load.+ # Lazy chunk no longer needed because the user navigated away mid-load."Loading chunk",- # Filtered as a benign page-error too; included here for the- # parallel diagnostic dump path.+ # Also a benign page-error; here for the diagnostic dump path."Failed to fetch",)@@ -348,14 +291,9 @@ def dump_diagnostics(info: Callable[[str], None] | None = None,extra: dict | None = None,) -> None:- """Write a screenshot + URL/title + body excerpt + storage dump.-- Diagnostic only. Never raises. The screenshot path lives in- `art_dir/{name}.png`; the JSON sidecar lives in `art_dir/{name}.json`.- The screenshot is wrapped in try/except because Page.screenshot- waits for webfonts to load and can crowd CI font load on macos-14- even at 90s. The JSON sidecar is best-effort too.- """+ """Write a screenshot (`art_dir/{name}.png`) + a JSON sidecar+ (`art_dir/{name}.json`) with URL/title/body/storage. Diagnostic only, never+ raises; both are best-effort (screenshot can crowd CI font load on macos-14)."""art = Path(art_dir)try:art.mkdir(parents = True, exist_ok = True)@@ -404,26 +342,13 @@ def dump_diagnostics(info(f"diagnostics: json sidecar {name} failed: {exc}")-# ─────────────────────────────────────────────────────────────────────# Bounded in-page fetch.-# ─────────────────────────────────────────────────────────────────────-#-# Playwright's `page.evaluate(...)` has no `timeout=` argument. If the-# JS body awaits a fetch that never resolves (the renderer's network-# thread wedges, the server accepts the connection but never replies,-# the macos-14 free runner under --single-process Chromium loses its-# IPC pipe), the entire Python script hangs until the runner-level-# timeout fires. Run 25696797934 / job 75446949358 on PR #5387 showed-# this exact failure: studio.log went idle after the chat surface-# mounted, no further requests reached the server, and Playwright-# burned 27+ minutes on a single page.evaluate(fetch /api/inference/-# load) before the 30-min runner cancel.#-# `evaluate_fetch` wraps the fetch in an AbortController.signal so the-# JS side resolves either with a real response or with a synthetic-# `{status: 0, error: "AbortError..."}` after `timeout_ms` ms. Either-# way page.evaluate returns and the script proceeds (or fails) with-# a debuggable signal instead of a silent wedge.+# `page.evaluate(...)` has no `timeout=`, so a fetch that never resolves hangs+# the whole script until the runner timeout (run 25696797934 / PR #5387 burned+# 27+ min on one page.evaluate). `evaluate_fetch` wraps the fetch in an+# AbortController.signal so the JS side always resolves -- with a real response+# or a synthetic `{status: 0, error: "AbortError..."}` after `timeout_ms`.def evaluate_fetch(page: Any,url: str,@@ -435,18 +360,11 @@ def evaluate_fetch(transport_retries: int = 2,transport_backoff_ms: int = 250,) -> dict[str, Any]:- """Run `fetch(url, opts)` inside the page with an AbortSignal deadline.-- Returns `{"status": int, "body": parsed_or_text, "error": str|None}`.- On AbortSignal timeout returns `{"status": 0, "body": None, "error":- "AbortError: ..."}`. Callers should treat `status == 0` (or any- non-None `error`) as a transport failure rather than an HTTP- response.-- `body` may be a `str` (sent verbatim) or a `dict`/`list` (JSON-- encoded here). Pass headers explicitly when you need- `Content-Type: application/json` or an `Authorization` bearer.- """+ """Run `fetch(url, opts)` in the page with an AbortSignal deadline. Returns+ `{"status", "body", "error"}`; on timeout `status==0` with an AbortError+ string. Treat `status == 0` or a non-None `error` as transport failure, not+ an HTTP response. `body` may be a str (verbatim) or dict/list (JSON-encoded+ here); pass headers explicitly for Content-Type / Authorization."""body_arg: str | Noneif body is None:body_arg = None@@ -487,13 +405,11 @@ def evaluate_fetch("body": body_arg,"timeoutMs": int(timeout_ms),}- # Bounded retry on transport failures only.- # status != 0 -> real HTTP response (incl. 4xx/5xx); propagate.- # AbortError -> caller's deadline; propagate.- # else (==0) -> stale-keepalive / "TypeError: Failed to fetch"- # on macos-14 right after auth rotations close- # existing sessions. Retry after backoff so the- # browser pool evicts the dead socket.+ # Bounded retry on transport failures only:+ # status != 0 -> real HTTP response (incl. 4xx/5xx); propagate.+ # AbortError -> caller's deadline; propagate.+ # else (==0) -> stale-keepalive / "Failed to fetch" after auth rotation;+ # retry after backoff so the pool evicts the dead socket.last: dict[str, Any] | None = Noneattempts = max(1, int(transport_retries) + 1)for attempt in range(attempts):@@ -523,36 +439,23 @@ def evaluate_fetch(return last or {"status": 0, "body": None, "error": "no attempt made"}-# ─────────────────────────────────────────────────────────────────────# Wall-clock watchdog.-# ─────────────────────────────────────────────────────────────────────-#-# Even with every action and fetch bounded, a sufficiently strange-# wedge inside the browser (a CPU-pinned JS infinite loop, a renderer-# crash that doesn't propagate to Playwright, an asyncio deadlock in-# the sync wrapper) can still hang the script. The watchdog is a-# daemon Timer that calls `os._exit(2)` after `deadline_s` seconds,-# printing the wedge location to stderr so the CI log shows where the-# script was at force-kill time. The exit code matches "test failure-# by deadline" so the workflow's `set -e` propagates correctly.#-# Pick `deadline_s` generously enough to cover the slowest healthy-# run -- macos-14 free runners with cold caches measure ~7-9 min for-# the comprehensive chat UI test. 12 minutes (720 s) leaves headroom-# without amplifying every real wedge to the 30-min runner-level cap.+# Even with every action/fetch bounded, a strange browser wedge (CPU-pinned JS+# loop, renderer crash that doesn't propagate, asyncio deadlock) can hang the+# script. A daemon Timer calls `os._exit(2)` after `deadline_s`, printing the+# wedge location to stderr; exit code 2 lets the workflow's `set -e` propagate.+# Pick `deadline_s` above the slowest healthy run (macos-14 cold cache ~7-9 min;+# 720s leaves headroom without nearing the 30-min runner cap).def install_wall_clock_watchdog(deadline_s: float,*,label: str = "playwright",info: Callable[[str], None] | None = None,) -> threading.Timer:- """Start a daemon Timer that hard-exits the process at `deadline_s`.-- Returns the Timer so the caller can `.cancel()` it on clean exit.- The Timer is daemonised; if the script exits normally before the- deadline the Timer dies with the process even without an explicit- cancel.- """+ """Start a daemon Timer that hard-exits the process at `deadline_s`. Returns+ it so the caller can `.cancel()` on clean exit; being daemonised, it also+ dies with the process if the script exits first."""def _kaboom() -> None:msg = (diff --git a/tests/studio/install/smoke_test_parallel_studio_home.py b/tests/studio/install/smoke_test_parallel_studio_home.pyindex c4fc2506556..be011477402 100644--- a/tests/studio/install/smoke_test_parallel_studio_home.py+++ b/tests/studio/install/smoke_test_parallel_studio_home.py@@ -1,50 +1,29 @@#!/usr/bin/env python3"""Smoke test: N parallel install.sh runs with distinct UNSLOTH_STUDIO_HOME-values must produce N fully isolated installs whose backends can run-side by side without clashing.+values must produce N fully isolated installs whose backends run side by side.-Covers the env-override path added in #5190:+Covers the env-override path from #5190:install-time- * N concurrent ``install.sh --local --no-torch`` runs against- this checkout, each pinned to its own UNSLOTH_STUDIO_HOME and- a redirected HOME, all exit 0.- * Each STUDIO_HOME contains its own bin/, share/, llama.cpp/- and unsloth_studio/ venv, with no cross-install absolute- paths.- * share/studio_install_id is unique across the N installs.- * share/studio.conf exports UNSLOTH_EXE, UNSLOTH_STUDIO_HOME- and UNSLOTH_LLAMA_CPP_PATH, all pointing inside this install.- * share/launch-studio.sh has @@DATA_DIR@@ substituted to its- own share/ at install time.- * bin/unsloth is a symlink that resolves into its own venv.- * The redirected HOME is left clean: no shell-rc append, no- .desktop file, no Studio.app stub, no shared marker.+ * N concurrent ``install.sh --local --no-torch`` runs, each pinned to+ its own UNSLOTH_STUDIO_HOME + redirected HOME, all exit 0.+ * Each STUDIO_HOME has its own bin/share/llama.cpp/unsloth_studio venv,+ a unique share/studio_install_id, and a studio.conf / launch-studio.sh+ pointing only inside this install. bin/unsloth resolves into its venv.+ * The redirected HOME is left clean (no rc append, .desktop, app stub).runtime- * N concurrent ``bin/unsloth studio`` launches each bind their- own dynamically allocated free port and stay healthy.- * /api/health is 200, status is healthy, chat_only is true- under --no-torch.- * The studio_root_id reported by /api/health on each backend- equals that install's share/studio_install_id, so the- runtime resolver agrees with the install-time write.- * studio_root_id values are pairwise distinct.- * GET / and GET /api/chat are 200 on every backend.- * The Python interpreter behind each PID is the install's own- venv python (the bin/unsloth shim does not cross-resolve).--This is an integration smoke runner, not a pytest unit test. It does-real installs (~1 minute end to end on a warm uv cache) and is meant-to be invoked explicitly:-- python tests/studio/install/smoke_test_parallel_studio_home.py- python tests/studio/install/smoke_test_parallel_studio_home.py --n 6 --keep--Exits 0 on PASS, 1 on FAIL, 2 on infrastructure error. Artifacts land-under a temporary directory and are removed on PASS unless --keep is-set; on FAIL or ERROR they are kept regardless so logs can be-inspected.+ * N ``bin/unsloth studio`` launches each bind a free port and report+ /api/health 200, healthy, chat_only true under --no-torch.+ * studio_root_id equals the install's studio_install_id and is pairwise+ distinct; GET / and /api/chat are 200; each PID's python is its venv.++Integration smoke runner (not pytest); ~1 minute on a warm uv cache. Invoke:++ python tests/studio/install/smoke_test_parallel_studio_home.py [--n 6 --keep]++Exits 0 PASS / 1 FAIL / 2 error. Artifacts removed on PASS unless --keep;+kept on FAIL/ERROR for inspection."""from __future__ import annotationsdiff --git a/tests/studio/install/test_llama_pr_force_and_source.py b/tests/studio/install/test_llama_pr_force_and_source.pyindex 17c58cba515..8e2a56ae393 100644--- a/tests/studio/install/test_llama_pr_force_and_source.py+++ b/tests/studio/install/test_llama_pr_force_and_source.py@@ -40,9 +40,8 @@ def run_bash(timeout: int = 60,env: dict | None = None,) -> subprocess.CompletedProcess:- """Run a bash script fragment and return the CompletedProcess.- 60s default tolerates slow shell startup on heavily-loaded CI- runners; the scripts themselves run in well under a second."""+ """Run a bash script fragment. 60s default tolerates slow CI shell+ startup; the scripts themselves run in well under a second."""run_env = os.environ.copy()if env:run_env.update(env)@@ -61,10 +60,8 @@ def run_pwsh(timeout: int = 60,env: dict | None = None,) -> subprocess.CompletedProcess:- """Run a PowerShell script fragment and return the CompletedProcess.- 60s default tolerates slow pwsh startup on heavily-loaded CI- runners; the scripts themselves run in well under a second.- A 10s budget previously surfaced as a flaky TimeoutExpired."""+ """Run a PowerShell script fragment. 60s default tolerates slow CI pwsh+ startup (a 10s budget was flaky); the scripts run in under a second."""run_env = os.environ.copy()run_env["NO_COLOR"] = "1"if env:diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex bcfc42c69fb..e0309dbd351 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -232,9 +232,7 @@ UPSTREAM_ASSETS = {}-# =============================================================================# TEST: install_llama_prebuilt.py -- resolve_upstream_asset_choice-# =============================================================================class TestResolveUpstreamAssetChoice:@@ -332,9 +330,7 @@ class TestResolveUpstreamAssetChoice:resolve_upstream_asset_choice(host, LLAMA_TAG)-# =============================================================================# TEST: install_llama_prebuilt.py -- runtime_patterns_for_choice-# =============================================================================class TestRuntimePatterns:@@ -398,9 +394,7 @@ class TestRuntimePatterns:assert "lib*.dylib" in patterns-# =============================================================================# TEST: install_llama_prebuilt.py -- HostInfo.has_rocm field-# =============================================================================class TestHostInfoRocm:@@ -449,9 +443,7 @@ class TestHostInfoRocm:assert "hipinfo" in source or "amd-smi" in source-# =============================================================================# TEST: install_python_stack.py -- _detect_rocm_version-# =============================================================================class TestDetectRocmVersion:@@ -548,9 +540,7 @@ class TestDetectRocmVersion:assert result is None-# =============================================================================# TEST: install_python_stack.py -- _ensure_rocm_torch-# =============================================================================class TestEnsureRocmTorch:@@ -707,9 +697,7 @@ class TestEnsureRocmTorch:mock_pip.assert_not_called()-# =============================================================================# TEST: install_python_stack.py -- _ROCM_TORCH_INDEX mapping-# =============================================================================class TestRocmTorchIndex:@@ -766,9 +754,7 @@ class TestRocmTorchIndex:assert tag == "rocm6.4"-# =============================================================================# TEST: hardware.py -- IS_ROCM flag and detect_hardware-# =============================================================================class TestHardwareRocmFlag:@@ -850,9 +836,7 @@ class TestHardwareRocmFlag:assert attr in source, f"distributed stub for '{attr}' missing from hardware.py"-# =============================================================================# TEST: tokenizer_utils.py -- error message-# =============================================================================class TestTokenizerErrorMessage:@@ -871,9 +855,7 @@ class TestTokenizerErrorMessage:assert "docs.unsloth.ai" in source or "No GPU detected" in source-# =============================================================================# TEST: install.sh -- structural checks-# =============================================================================class TestInstallShStructure:@@ -1003,9 +985,7 @@ class TestInstallShStructure:assert darwin_pos < rocm_pos, "macOS check should come before ROCm detection"-# =============================================================================# TEST: Live regression on current host (NVIDIA B200 expected)-# =============================================================================class TestLiveRegression:@@ -1051,9 +1031,7 @@ class TestLiveRegression:assert "cu1" in url or "cuda" in url.lower(), f"Expected CUDA URL, got: {url}"-# =============================================================================# TEST: worker.py -- ROCm Mamba/SSM source build path-# =============================================================================# Load worker.py module_WORKER_PATH = PACKAGE_ROOT / "studio" / "backend" / "core" / "training" / "worker.py"@@ -1140,9 +1118,7 @@ class TestWorkerRocmMambaSsm:assert "timeout" in source-# =============================================================================# TEST: amd.py -- AMD GPU monitoring-# =============================================================================class TestAmdGpuMonitoring:@@ -1217,9 +1193,8 @@ class TestAmdGpuMonitoring:pytest.skip("Could not load amd module")# _first_visible_amd_gpu_id() short-circuits to None when any of- # HIP / ROCR / CUDA_VISIBLE_DEVICES is set to "" or "-1". CI runners- # often unset CUDA at the env level by setting CUDA_VISIBLE_DEVICES- # to "" so the test must not inherit that.+ # HIP / ROCR / CUDA_VISIBLE_DEVICES is "" or "-1". CI often sets+ # CUDA_VISIBLE_DEVICES="", so the test must not inherit that.for var in ("HIP_VISIBLE_DEVICES","ROCR_VISIBLE_DEVICES",@@ -1292,9 +1267,7 @@ class TestAmdGpuMonitoring:assert result["available"] is False-# =============================================================================# TEST: hardware.py -- IS_ROCM branching to amd.py-# =============================================================================class TestHardwareAmdBranching:@@ -1349,9 +1322,7 @@ class TestHardwareAmdBranching:assert "from . import amd" in func_body-# =============================================================================# TEST: hardware.py -- apply_gpu_ids ROCm fallback (issue #5180)-# =============================================================================class TestApplyGpuIdsRocmFallback:@@ -1385,9 +1356,7 @@ class TestApplyGpuIdsRocmFallback:assert "except Exception" in func_body-# =============================================================================# TEST: install_python_stack.py -- Windows AMD warning-# =============================================================================class TestWindowsRocmWarning:@@ -1410,9 +1379,7 @@ class TestWindowsRocmWarning:assert "docs.unsloth.ai/get-started/install-and-update/amd" in source-# =============================================================================# TEST: unsloth/kernels/utils.py -- is_rdna() expansion-# =============================================================================class TestIsRdnaExpansion:@@ -1477,9 +1444,7 @@ class TestIsRdnaExpansion:assert "gfx1100" not in func_body-# =============================================================================# TEST: install_python_stack.py -- _windows_rocm_index_url arch mapping-# =============================================================================class TestWindowsRocmIndexUrl:@@ -1536,9 +1501,7 @@ class TestWindowsRocmIndexUrl:assert url is not None-# =============================================================================# TEST: install_python_stack.py -- _detect_windows_gfx_arch-# =============================================================================class TestDetectWindowsGfxArch:@@ -1595,9 +1558,7 @@ class TestDetectWindowsGfxArch:assert result == "gfx1201"-# =============================================================================# TEST: install_python_stack.py -- _install_bnb_windows_rocm-# =============================================================================class TestInstallBnbWindowsRocm:@@ -1742,9 +1703,7 @@ class TestDetectBnbRocmDllVer:assert stack_mod._detect_bnb_rocm_dll_ver() == "713"-# =============================================================================# TEST: install_python_stack.py -- UNSLOTH_ROCM_TORCH_INSTALLED early-return path-# =============================================================================class TestRocmTorchInstalledEnvVar:@@ -1813,9 +1772,7 @@ class TestRocmTorchInstalledEnvVar:mock_bnb.assert_not_called()-# =============================================================================# TEST: worker.py -- Windows ROCm patches (source-level checks)-# =============================================================================class TestWorkerWindowsRocmPatches:@@ -1951,9 +1908,7 @@ class TestWorkerWindowsRocmPatches:assert 'split(".")[:2]' in source or ".split('.')[:2]" in source-# =============================================================================# TEST: install_python_stack.py -- _ROCM_TORCH_PKG_SPECS mapping-# =============================================================================class TestRocmTorchPkgSpecs:@@ -2000,9 +1955,7 @@ class TestRocmTorchPkgSpecs:assert mapping.get(arch) == "gfx110X-all", f"{arch} missing from mapping"-# =============================================================================# TEST: setup.ps1 / install.ps1 -- Strix Halo gfx arch detection-# =============================================================================_SETUP_PS1_PATH = PACKAGE_ROOT / "studio" / "setup.ps1"_INSTALL_PS1_PATH = PACKAGE_ROOT / "install.ps1"@@ -2084,9 +2037,7 @@ class TestStrixHaloGfxArchDetection:), f"gfx arch regex not found in {path.name}"-# =============================================================================# TEST: HIP SDK tool path resolution via HIP_PATH / ROCM_PATH env vars-# =============================================================================class TestHipSdkEnvPathResolution:@@ -2203,9 +2154,7 @@ class TestHipSdkEnvPathResolution:assert "PATH" in source and ("SetEnvironmentVariable" in source or "Add" in source)-# =============================================================================# TEST: HIP SDK detected substep -- path + hipconfig version shown in terminal-# =============================================================================class TestHipSdkDetectedSubstep:@@ -2258,9 +2207,7 @@ class TestHipSdkDetectedSubstep:assert "ROCmVersionFull" in source and "rocm" in source-# =============================================================================# TEST: install.sh -- Strix Halo rocm7.1 → rocm7.2 override-# =============================================================================_INSTALL_SH_PATH = PACKAGE_ROOT / "install.sh"_SETUP_SH_PATH = PACKAGE_ROOT / "studio" / "setup.sh"@@ -2324,9 +2271,7 @@ class TestStrixRocm71Override:assert "rocm/whl/gfx" in source-# =============================================================================# TEST: setup.sh -- gcc-install-dir fix for Ubuntu 24.04 + ROCm 7.x clang-20-# =============================================================================class TestSetupShGccInstallDir:@@ -2365,9 +2310,7 @@ class TestSetupShGccInstallDir:assert "gcc install dir" in source or "GCC_INSTALL_DIR" in source-# =============================================================================# TEST: main.py -- BNB_ROCM_VERSION server startup + distributed stubs-# =============================================================================_MAIN_PY_PATH = PACKAGE_ROOT / "studio" / "backend" / "main.py"_HARDWARE_PY_PATH = PACKAGE_ROOT / "studio" / "backend" / "utils" / "hardware" / "hardware.py"@@ -2455,9 +2398,7 @@ class TestServerStartupRocmFixes:assert "_distributed_rpc" in source-# =============================================================================# TEST: install.ps1 / setup.ps1 -- HipSdkInstalled flag (SDK found, device inaccessible)-# =============================================================================class TestHipSdkInstalledButDeviceInaccessible:@@ -2527,11 +2468,9 @@ class TestHipSdkInstalledButDeviceInaccessible:assert "GPU not ROCm-accessible" in source-# =============================================================================# TEST: --rocm-gfx forwarding -- setup.sh/setup.ps1 hand their resolved gfx arch# to install_llama_prebuilt.py so the lemonade HIP prebuilt is selected even when# the installer's own hipinfo/amd-smi probe cannot report it.-# =============================================================================_SETUP_SH_PATH = PACKAGE_ROOT / "studio" / "setup.sh"diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.pyindex 1ada35888ca..27cf30496f6 100644--- a/tests/studio/install/test_selection_logic.py+++ b/tests/studio/install/test_selection_logic.py@@ -111,9 +111,7 @@ def load_studio_run_module(monkeypatch):return module-# ---------------------------------------------------------------------------# Helper factories-# ---------------------------------------------------------------------------def make_host(**overrides):@@ -271,9 +269,7 @@ def mock_windows_runtime(monkeypatch, lines):)-# ===========================================================================# Studio run.py localhost warning-# ===========================================================================class TestStudioLocalhostIpv6Warning:@@ -454,9 +450,7 @@ class TestStudioLocalhostIpv6Warning:assert calls["stop_hint"] == 1-# ===========================================================================# A. normalize_compute_cap-# ===========================================================================class TestNormalizeComputeCap:@@ -488,9 +482,7 @@ class TestNormalizeComputeCap:assert normalize_compute_cap("9.0") == "90"-# ===========================================================================# B. normalize_compute_caps-# ===========================================================================class TestNormalizeComputeCaps:@@ -507,9 +499,7 @@ class TestNormalizeComputeCaps:assert normalize_compute_caps([]) == []-# ===========================================================================# C. parse_cuda_visible_devices-# ===========================================================================class TestParseCudaVisibleDevices:@@ -532,9 +522,7 @@ class TestParseCudaVisibleDevices:assert parse_cuda_visible_devices(" 0 , 1 ") == ["0", "1"]-# ===========================================================================# D. supports_explicit_visible_device_matching-# ===========================================================================class TestSupportsExplicitVisibleDeviceMatching:@@ -554,9 +542,7 @@ class TestSupportsExplicitVisibleDeviceMatching:assert supports_explicit_visible_device_matching(["0", "MIG-device"]) is False-# ===========================================================================# E. select_visible_gpu_rows-# ===========================================================================class TestSelectVisibleGpuRows:@@ -589,9 +575,7 @@ class TestSelectVisibleGpuRows:assert result == []-# ===========================================================================# F. compatible_linux_runtime_lines-# ===========================================================================class TestCompatibleLinuxRuntimeLines:@@ -648,9 +632,7 @@ class TestParseDirectLinuxReleaseBundle:assert art.max_sm == 120 # inherited from cuda13-newer-# ===========================================================================# G. pick_windows_cuda_runtime + compatible_windows_runtime_lines-# ===========================================================================class TestPickWindowsCudaRuntime:@@ -697,9 +679,7 @@ class TestCompatibleWindowsRuntimeLines:assert compatible_windows_runtime_lines(host) == ["cuda14", "cuda13", "cuda12"]-# ===========================================================================# H. runtime_line_from_cuda_version-# ===========================================================================class TestRuntimeLineFromCudaVersion:@@ -719,9 +699,7 @@ class TestRuntimeLineFromCudaVersion:assert runtime_line_from_cuda_version("") is None-# ===========================================================================# I. apply_approved_hashes-# ===========================================================================class TestApplyApprovedHashes:@@ -835,9 +813,7 @@ class TestApplyApprovedHashes:apply_approved_hashes([], checksums)-# ===========================================================================# J. published release resolution-# ===========================================================================class TestPublishedReleaseResolution:@@ -1171,9 +1147,7 @@ class TestValidatedChecksumsForBundle:validated_checksums_for_bundle("unslothai/llama.cpp", bundle)-# ===========================================================================# K. linux_cuda_choice_from_release -- core selection-# ===========================================================================class TestLinuxCudaChoiceFromRelease:@@ -1500,9 +1474,7 @@ class TestBlackwellUltraSm103Coverage:assert result is None-# ===========================================================================# L. resolve_install_attempts-# ===========================================================================class TestResolveInstallAttempts:@@ -2023,9 +1995,7 @@ class TestResolveInstallReleasePlans:sys.modules.pop(spec.name, None)-# ===========================================================================# N. windows_cuda_attempts-# ===========================================================================class TestWindowsCudaAttempts:@@ -2243,9 +2213,7 @@ class TestWindowsCudaAttempts:assert result[0].name == f"llama-{self.TAG}-bin-win-cuda-13.3-x64.zip"-# ===========================================================================# N.1b. _pinned_windows_cuda_fallback -- pinned b9360 cuda-13.1 Blackwell fallback-# ===========================================================================class TestPinnedBlackwellCudaFallback:@@ -2387,9 +2355,7 @@ class TestPinnedBlackwellCudaFallback:assert _windows_cuda_attempt_covers_blackwell(cpu) is False-# ===========================================================================# N.1c. direct_upstream_release_plan -- pinned Blackwell fallback ordering-# ===========================================================================class TestDirectUpstreamBlackwellPin:@@ -2453,9 +2419,7 @@ class TestDirectUpstreamBlackwellPin:assert plan.attempts[0].name == f"llama-{self.TAG}-bin-win-cuda-13.3-x64.zip"-# ===========================================================================# N.1d. published_windows_cuda_attempts -- version-dynamic ordering seed-# ===========================================================================class TestPublishedWindowsCudaAttemptsDynamicMajor:@@ -2521,9 +2485,7 @@ class TestPublishedWindowsCudaAttemptsDynamicMajor:assert result[0].runtime_line == "cuda12"-# ===========================================================================# N.1e. resolve_release_asset_choice -- pin on the published install path-# ===========================================================================class TestResolveReleaseAssetChoicePin:@@ -2616,9 +2578,7 @@ class TestResolveReleaseAssetChoicePin:assert "b9360" not in [a.tag for a in result]-# ===========================================================================# N.1. apply_approved_hashes -- runtime archive checksum threading-# ===========================================================================class TestApplyApprovedHashesRuntimePair:@@ -2690,9 +2650,7 @@ class TestApplyApprovedHashesRuntimePair:assert result[0].runtime_sha256 is None-# ===========================================================================# O. resolve_upstream_asset_choice -- platform routing-# ===========================================================================class TestResolveUpstreamAssetChoice:@@ -2835,9 +2793,7 @@ class TestResolveUpstreamAssetChoice:assert result.name == cuda_name-# ===========================================================================# N.2. Deterministic macOS prebuilt pin (b9415)-# ===========================================================================def _macos_host(machine = "arm64", version = (15, 5)):@@ -2960,9 +2916,7 @@ class TestResolveSimpleMacosPin:assert calls[0][2] == "latest"-# ===========================================================================# Linux arm64 + GPU must not install the x64-only fork bundle-# ===========================================================================class TestLinuxArm64ForkFallsBackToSource:@@ -3016,9 +2970,7 @@ class TestLinuxArm64ForkFallsBackToSource:assert "linux-x64 prebuilts" not in str(exc.value)-# ===========================================================================# arm64 Linux GPU: CPU prebuilt fallback after a failed source build (--cpu-fallback)-# ===========================================================================class TestCpuFallback:diff --git a/tests/studio/load_freeze/llama_server_shim.py b/tests/studio/load_freeze/llama_server_shim.pyindex bb9e1198209..4030fcd6c4b 100644--- a/tests/studio/load_freeze/llama_server_shim.py+++ b/tests/studio/load_freeze/llama_server_shim.py@@ -224,8 +224,8 @@ class FakeLlamaServer:self._thread: Optional[threading.Thread] = Nonedef start(self) -> "FakeLlamaServer":- # port=0 lets ThreadingHTTPServer pick a free port atomically- # (avoids find-port-then-bind race); read back via server_address[1].+ # port=0 lets ThreadingHTTPServer pick a free port atomically (no+ # find-then-bind race); read back via server_address[1].self._server = FakeLlamaServer._Server((self.host, self._requested_port), _Handler)self._server.config = self.configbound_port = self._server.server_address[1]diff --git a/tests/studio/load_freeze/test_load_orchestrator.py b/tests/studio/load_freeze/test_load_orchestrator.pyindex b76c4c361b0..d091e56e703 100644--- a/tests/studio/load_freeze/test_load_orchestrator.py+++ b/tests/studio/load_freeze/test_load_orchestrator.py@@ -33,9 +33,7 @@ from pathlib import Pathimport pytest-# ---------------------------------------------------------------------------# Repo discovery-# ---------------------------------------------------------------------------def _find_repo_root() -> Path | None:@@ -79,9 +77,7 @@ from core.inference.llama_cpp import LlamaCppBackend # noqa: E402from llama_server_shim import FakeLlamaServer # noqa: E402-# ---------------------------------------------------------------------------# Fixtures / helpers-# ---------------------------------------------------------------------------def _make_backend(port: int, *, loaded: bool = True) -> LlamaCppBackend:@@ -208,9 +204,7 @@ def _drive_concurrent_probe_and_health(return max(latencies), elapsed, latencies-# ---------------------------------------------------------------------------# (1) Behavioural canary-# ---------------------------------------------------------------------------def test_buggy_route_blocks_event_loop():@@ -239,9 +233,7 @@ def test_fixed_route_keeps_event_loop_responsive():assert max_lat < 0.25, f"expected <0.25s; got {max_lat:.3f}s (all: {lats})"-# ---------------------------------------------------------------------------# (2) Functional equivalence -- sync == to_thread for each codec branch-# ---------------------------------------------------------------------------@pytest.fixture@@ -366,9 +358,7 @@ def test_functional_equivalence_bicodec_match():assert sync_result == threaded-# ---------------------------------------------------------------------------# (3) Failure modes-# ---------------------------------------------------------------------------def test_shim_returns_500_on_tokenize_returns_none():@@ -432,9 +422,7 @@ def test_backend_not_loaded_short_circuits():assert threaded_t < 0.05-# ---------------------------------------------------------------------------# (4) Stress / concurrency-# ---------------------------------------------------------------------------def test_50_concurrent_probes_complete_without_deadlock():@@ -499,9 +487,7 @@ def test_100_concurrent_healths_during_slow_probe_all_responsive():assert max_lat < 0.35, f"100-burst max latency {max_lat:.3f}s exceeds 350 ms"-# ---------------------------------------------------------------------------# (5) Drift / regression guards on the production source-# ---------------------------------------------------------------------------def test_load_model_caches_audio_type_inside_serial_load_lock():@@ -588,9 +574,7 @@ def test_no_other_async_route_calls_detect_audio_type_unwrapped():)-# ---------------------------------------------------------------------------# (6) Timing budgets-# ---------------------------------------------------------------------------def test_load_response_under_2s_with_fast_shim():@@ -624,9 +608,7 @@ def test_repeated_loads_bounded_total_time():assert elapsed < 10.0-# ---------------------------------------------------------------------------# (7) Browser-compatibility surface-# ---------------------------------------------------------------------------def test_response_is_valid_browser_parseable_json():@@ -692,9 +674,7 @@ def test_response_shape_matches_pre_fix_for_no_match():assert body == {"audio_type": None}-# ---------------------------------------------------------------------------# (8) Cancellation-# ---------------------------------------------------------------------------def test_client_disconnect_during_probe_does_not_crash_server():diff --git a/tests/studio/playwright_chat_ime_i18n.py b/tests/studio/playwright_chat_ime_i18n.pyindex 828187d4625..f27266193de 100644--- a/tests/studio/playwright_chat_ime_i18n.py+++ b/tests/studio/playwright_chat_ime_i18n.py@@ -4,20 +4,15 @@"""Studio chat composer IME + multilingual regression smoke.Covers three surfaces:- A. Stuck IME composition (issue #5318 / PR #5327): duplicate- compositionstart with no compositionend left isComposing=true,- dropping all subsequent keystrokes including ASCII.- B. Multilingual paste round-trip across 31 scripts -- guards the- controlled-textarea / React state plumbing against Unicode mangling.- C. Stuck compositionend (issue #5546): Chrome on Windows over WSL- fires compositionstart + compositionupdate but never compositionend,- wedging Send disabled after the IME commits. Verifies the- watchdog in useImeComposerInputHandlers releases the flag.+ A. Stuck IME composition (#5318 / PR #5327): duplicate compositionstart with+ no compositionend left isComposing=true, dropping keystrokes.+ B. Multilingual paste round-trip across 31 scripts (Unicode plumbing).+ C. Stuck compositionend (#5546): WSL Chrome never fires compositionend,+ wedging Send disabled; the useImeComposerInputHandlers watchdog releases it.Model-free; the bug surface is the composer, not inference.--Env contract matches playwright_chat_ui.py:- BASE_URL, STUDIO_NEW_PW, PW_ART_DIR, STUDIO_UI_STRICT.+Env contract matches playwright_chat_ui.py: BASE_URL, STUDIO_NEW_PW, PW_ART_DIR,+STUDIO_UI_STRICT."""import os@@ -49,8 +44,7 @@ STRICT = os.environ.get("STUDIO_UI_STRICT", "0") == "1"WALL_TIMEOUT_S = float(os.environ.get("STUDIO_IME_WALL_TIMEOUT_S", "300"))-# One short greeting + arithmetic per script (ordered by speaker count) ---# each entry catches a distinct class of Unicode regression.+# One greeting + arithmetic per script; each catches a distinct Unicode class.I18N_SAMPLES = [("en", "English", "Hello, 1+1=2"),("zh-CN", "Chinese (Simplified)", "你好,1+1=2"),@@ -156,8 +150,8 @@ with sync_playwright() as p:except Exception as _shoot_err:info(f"WARN: screenshot {name} failed: {_shoot_err}")- # 1. Bootstrap auth via /change-password (mirrors playwright_chat_ui.py- # retry-on-rerender to absorb React form-detach races).+ # 1. Bootstrap auth via /change-password (retry-on-rerender absorbs React+ # form-detach races, mirroring playwright_chat_ui.py).step("change-password through UI (Setup your account)")form_err: Exception | None = Nonefor _form_attempt in range(3):@@ -205,7 +199,7 @@ with sync_playwright() as p:if form_err is not None:raise form_err- # 2. Wait for composer mount. No GGUF: the bug surface is React state, not inference.+ # 2. Wait for composer mount (no GGUF: the bug is React state, not inference).step("wait for composer to mount")try:page.wait_for_load_state("networkidle", timeout = 30_000)@@ -251,8 +245,8 @@ with sync_playwright() as p:else:info('composer dir="auto" present')- # Source-level guard for the edit and compare composers (neither- # is mounted here): grep the JSX for dir="auto" inside each block.+ # Source-level guard for the unmounted edit/compare composers: grep their+ # JSX for dir="auto"._repo_root = Path(__file__).resolve().parents[2]_thread_src = (_repo_root / "studio/frontend/src/components/assistant-ui/thread.tsx"@@ -276,9 +270,9 @@ with sync_playwright() as p:return composer.evaluate("(el) => el.value")def set_value_via_setter(s: str) -> str:- """Write via React's monkey-patched setter + paste input event,- then await two rAFs so the controlled value is committed before- readback (plain `.value=s` would be overwritten on next render)."""+ """Write via React's setter + paste input event, then await two rAFs so the+ controlled value commits before readback (plain `.value=s` is overwritten+ on next render)."""return composer.evaluate("""async (el, v) => {const setter = Object.getOwnPropertyDescriptor(@@ -369,9 +363,9 @@ with sync_playwright() as p:shoot("05-normal-composition")clear()- # 6. Stuck IME repro for issue #5318: duplicate compositionstart with- # no compositionend wedged isComposing=true and dropped ASCII keys.- # PR #5327 cleared the stale state on non-composing input.+ # 6. Stuck IME repro (#5318): duplicate compositionstart with no+ # compositionend wedged isComposing=true; PR #5327 clears it on+ # non-composing input.step("BUG REPRO: stuck IME composition recovery (issue #5318)")clear()composer.click()@@ -385,9 +379,8 @@ with sync_playwright() as p:el.dispatchEvent(new CompositionEvent('compositionstart', {bubbles:true, data:''}));}""")- # Drive the real keyboard path; on the broken build React drops- # 'abcd' and reconciles el.value back to ''. wait_for_function- # crosses the microtask boundary so we see committed React state.+ # On the broken build React drops 'abcd' and reconciles el.value to ''.+ # wait_for_function crosses the microtask boundary to see committed state.page.keyboard.type("abcd")try:page.wait_for_function(@@ -424,12 +417,9 @@ with sync_playwright() as p:info("stuck-composition recovery PASS")clear()- # 6b. WSL + Windows Chrome repro for issue #5546: Chrome never emits- # compositionend after the IME commit, so the watchdog has to- # release the composing flag on its own once the events go silent.- # This dispatches a realistic "compose, commit, then nothing"- # sequence — no compositionend, no follow-up keystrokes — and- # waits for the Send button to come back enabled.+ # 6b. WSL+Chrome repro (#5546): Chrome never emits compositionend after the+ # IME commit, so the watchdog must release the composing flag once events+ # go silent. Dispatch "compose, commit, then nothing" and wait for Send.step("BUG REPRO: stuck compositionend recovery (issue #5546)")clear()composer.click()@@ -473,13 +463,10 @@ with sync_playwright() as p:info("compositionend watchdog recovery PASS")clear()- # 6c. Watchdog-race repro: after the watchdog clears composingRef during a- # long candidate pause, a subsequent IME keydown (browser still sees- # isComposing=true / keyCode 229) must not slip preedit text through- # the form submit. The onKeyDown gate re-pins composingRef so the- # handleSubmit / blockSend guards keep refusing. The Send button stays- # visually enabled (watchdog has already cleared the React state); the- # refusal happens at form.requestSubmit() time, not at the button.+ # 6c. Watchdog-race repro: after the watchdog clears composingRef, a later+ # IME keydown (isComposing=true / keyCode 229) must not slip preedit text+ # through submit. The onKeyDown gate re-pins composingRef so handleSubmit+ # refuses at form.requestSubmit() time, not at the (enabled) button.step("BUG REPRO: keydown re-pin after watchdog cleared composing (issue #5546 follow-up)")clear()composer.click()@@ -504,10 +491,9 @@ with sync_playwright() as p:expect(send_btn_keydown).not_to_be_disabled(timeout = 8_000)except Exception:soft_fail("watchdog did not clear before keydown re-pin test")- # Fire the IME-confirm Enter (keyCode 229, isComposing=true) then trigger- # the form submit synchronously. With the keydown gate, composingRef is- # re-pinned before handleSubmit runs and the submit is prevented; the- # textarea must still hold the preedit text.+ # Fire the IME-confirm Enter (keyCode 229) then submit synchronously. The+ # keydown gate re-pins composingRef before handleSubmit, preventing submit;+ # the textarea must still hold the preedit text.submit_probe = composer.evaluate("""(el) => {el.focus();@@ -533,11 +519,9 @@ with sync_playwright() as p:clear()# 6d. Keydown re-pin must also re-arm the watchdog. On the WSL+Chrome- # stuck-compositionend path the IME never fires a follow-up- # compositionend or non-composing input, so after the IME keydown- # re-pins composingRef the watchdog has to take it back to false on- # its own — otherwise Send re-locks permanently after the very- # scenario this PR was supposed to fix. (Codex P1, commit 597af0d0.)+ # stuck-compositionend path no follow-up event arrives, so after keydown+ # re-pins composingRef the watchdog must clear it again or Send re-locks+ # permanently. (Codex P1, commit 597af0d0.)step("BUG REPRO: keydown re-pin re-arms watchdog (#5546 follow-up regression)")clear()composer.click()@@ -563,8 +547,7 @@ with sync_playwright() as p:except Exception:soft_fail("watchdog did not clear before re-arm test (first cycle)")# IME-confirm keydown re-pins composingRef. Without the re-arm fix the- # watchdog would never run again and Send would stay blocked at the- # submit-time guard forever, even though no follow-up IME event arrives.+ # watchdog never runs again and Send stays blocked forever.composer.evaluate("""(el) => {el.focus();@@ -574,9 +557,9 @@ with sync_playwright() as p:}));}""")- # Second watchdog cycle: a real submit attempt now must eventually be- # allowed. Trigger requestSubmit() after the re-armed watchdog window- # plus a little slack; on the buggy build the form stays gated forever.+ # Second watchdog cycle: a real submit must eventually be allowed. Trigger+ # requestSubmit() after the re-armed window plus slack; the buggy build stays+ # gated forever.rearm_probe = page.evaluate("""async (selector) => {const ta = document.querySelector(selector);@@ -609,8 +592,8 @@ with sync_playwright() as p:info("keydown re-pin re-arm PASS")clear()- # 7. Final state. The change-password redirect emits benign 401 noise,- # so we filter via is_benign_* and only fail on real errors.+ # 7. Final state. Filter benign 401 noise from the change-password redirect+ # via is_benign_*; fail only on real errors.shoot("07-final")real_page_errors = [e for e in page_errors if not is_benign_page_error(e)]real_console_errors = [e for e in console_errors if not is_benign_console_error(e)]diff --git a/tests/studio/run_real_mlx_smoke.py b/tests/studio/run_real_mlx_smoke.pyindex 3b494a4272e..6bf02882063 100644--- a/tests/studio/run_real_mlx_smoke.py+++ b/tests/studio/run_real_mlx_smoke.py@@ -4,58 +4,24 @@"""End-to-end MLX smoke test on real Apple Silicon -- multi-process driver.-Two subcommands so the workflow can drive cold-start reloads in fresh-Python processes (the way real users hit the load path):+Two subcommands let the workflow drive cold-start reloads in fresh+processes (the way real users hit the load path):python run_real_mlx_smoke.py train --workdir DIRpython run_real_mlx_smoke.py reload --format {lora|merged|gguf} --dir D-The `train` subcommand:- 1. Loads `unsloth/gemma-3-270m-it` via FastMLXModel.from_pretrained.- 2. Applies LoRA r=8 on q/k/v/o.- 3. Computes pre-training loss + grad norm via mx.nn.value_and_grad.- 4. Trains 7 deterministic steps on a dataset of the SAME row repeated- ("<<HELLO!!>> My name is Unsloth!"), with batch_size=2 and- gradient_accumulation_steps=3 so each step processes 6 sequences- and the run sees 42 sequences total.- 5. Computes post-training loss + grad norm.- 6. Generates from "<<HELLO!!>> My name is " and asserts "Unsloth"- appears in the in-memory completion.- 7. Saves the trained model in three formats:- - LoRA adapter (save_pretrained_merged save_method="lora")- - Merged 16-bit (save_pretrained_merged save_method="merged_16bit")- - GGUF (save_pretrained_gguf, best-effort -- skipped with a- clear reason if save raises; e.g. llama.cpp's- convert_hf_to_gguf currently asserts on Gemma-3-270m's- tokenizer vocab. Soft-skipped so the LoRA + merged checks- continue to gate the PR.)- 8. Emits `train_metrics.json` with per-phase timing / peak GPU /- peak RSS / per-step losses / pre+post grad norms / generations- / gguf_supported flag, for regression detection across CI runs.--Reloads run as separate workflow steps so each is a fresh Python-process. For lora / merged the reload uses-FastMLXModel.from_pretrained directly. For gguf the reload spawns-the llama-cli binary built by save_pretrained_gguf and parses-stdout. Each subcommand emits `<format>_reload_metrics.json` next-to the saved dir.--The two upstream unsloth_zoo bugs the earlier draft of this script-worked around are fixed in unslothai/unsloth-zoo#627: GGUF export-no longer raises NotImplementedError on Apple Silicon (llama_cpp.py-catches it from the device_type module-level call) and LoRA reload-via FastMLXModel.from_pretrained(lora_dir) works without an external-config.json copy (mlx_loader.py preserves local_path when config.json-is missing so the adapter_config.json branch can run).--Determinism: seeds Python `random`, `numpy`, and `mlx.core.random` in-every process before any MLX operation. Forwards `random_state=SEED`-to FastMLXModel.from_pretrained / get_peft_model and `seed=SEED` to-MLXTrainingConfig. Metal still has minor reduction-order-nondeterminism, so loss assertions are bounds rather than exact.--Only runnable on a real Apple Silicon host; invoked from-.github/workflows/mlx-ci.yml on the macos-14 runner.+`train` loads gemma-3-270m-it, applies LoRA, probes pre/post loss+grad,+overfits one repeated row, generates, saves in lora/merged_16bit/gguf+(gguf best-effort), and writes train_metrics.json. `reload` reopens each+saved format in a fresh process and writes <format>_reload_metrics.json.++GGUF export and LoRA reload fixes land in unslothai/unsloth-zoo#627.++Determinism: seeds random/numpy/mlx.core.random and forwards SEED to+from_pretrained / get_peft_model / MLXTrainingConfig. Metal has minor+reduction-order nondeterminism, so loss assertions are bounds, not exact.++Apple-Silicon only; invoked from .github/workflows/mlx-ci.yml."""from __future__ import annotations@@ -99,10 +65,7 @@ def _peak_gpu_gb() -> float:if not mx.metal.is_available():return 0.0- # Newer MLX deprecates mx.metal.get_peak_memory in favour of the- # top-level mx.get_peak_memory; fall back to the old API for- # compatibility with older MLX versions still present in the- # environment.+ # Newer MLX moved get_peak_memory to top-level; fall back to mx.metal for old versions.getter = getattr(mx, "get_peak_memory", None) or getattr(mx.metal, "get_peak_memory", None)if getter is None:return 0.0@@ -113,8 +76,7 @@ def _peak_gpu_gb() -> float:def _peak_rss_gb() -> float:- """Peak resident set size for this process. macOS getrusage returns- bytes; Linux returns kilobytes."""+ """Peak RSS for this process (macOS getrusage = bytes, Linux = KB)."""rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrssif sys.platform == "darwin":return float(rss) / (1024**3)@@ -122,8 +84,7 @@ def _peak_rss_gb() -> float:class Phase:- """Wall-clock + memory tracker for a named phase. Records into a- metrics dict so we can later JSON-dump for regression detection."""+ """Wall-clock + memory tracker for a named phase; records into a metrics dict."""def __init__(self, name: str, metrics: dict):self.name = name@@ -154,8 +115,7 @@ class Phase:def _compute_loss_and_grad_norm(model, tokenizer, text: str) -> tuple[float, float]:- """One forward+backward of next-token cross-entropy on `text`.- Returns (loss, ||grad||_2)."""+ """One fwd+bwd of next-token CE on `text`. Returns (loss, ||grad||_2)."""import mlx.core as mximport mlx.nn as nnfrom mlx.utils import tree_flatten@@ -185,23 +145,12 @@ def _compute_loss_and_grad_norm(model, tokenizer, text: str) -> tuple[float, flodef _teacher_forced_completion_loss(model, tokenizer, prompt: str, completion: str) -> float:- """Mean next-token CE loss on `completion` tokens given `prompt` (teacher- forced -- no decoding, no sampling, no greedy argmax).-- Decouples the memorisation check from greedy-decode geometry. A 47-round,- 13-seed sweep on this fixture showed greedy `completion in output` lands- in the 46-77% range across MLX configs (config-fragile), while- post_train_loss is < 0.1 in 100% of configs that reach the basin. Teacher-- forced completion loss is a subset of post_train_loss so it inherits the- same reliability AND is more specific: it asserts *what* the model- memorised, not just *that* it reached low loss on the full row.-- Args:- model: the LoRA-trained MLX model- tokenizer: the tokenizer used during training (must match)- prompt: the conditioning text (e.g. PROMPT)- completion: the substring the model should have learnt to emit- after `prompt` (e.g. EXPECT_IN_OUTPUT + "!")+ """Mean next-token CE on `completion` given `prompt`, teacher-forced.++ Decouples the memorisation check from greedy-decode geometry: a sweep+ found greedy `completion in output` lands at 46-77% across MLX configs+ while post_train_loss is < 0.1 whenever the run reaches the basin. This+ asserts *what* the model memorised, not just that loss is low.Returns mean cross-entropy over the completion's tokens."""@@ -275,13 +224,9 @@ def cmd_train(args) -> int:mx.random.seed(SEED)with Phase("apply_lora", metrics):- # Standard unsloth LoRA target set (q/k/v/o + gate/up/down).- # With bs=2 grad_accum=3 (effective batch 6) the q/k/v/o-only- # LoRA collapsed in 7 steps -- training loss kept dropping but- # inference output the structural skeleton ("My name") without- # recovering the specific "Unsloth" token. Including the MLP- # projections gives the LoRA enough capacity to memorize the- # training row at the larger effective batch.+ # Standard unsloth LoRA target set (q/k/v/o + gate/up/down). q/k/v/o+ # alone collapsed in 7 steps (loss dropped but "Unsloth" wasn't+ # recovered); MLP projections add the capacity to memorize the row.model = FastMLXModel.get_peft_model(model,r = 8,@@ -314,29 +259,19 @@ def cmd_train(args) -> int:config = MLXTrainingConfig(per_device_train_batch_size = 2,gradient_accumulation_steps = 3,- # 47-round mlx-parity-probes sweep (PR #5498 / staging-2#119)- # found 7 steps is below the convergence horizon at any clip- # setting -- the trainer hasn't memorized the train row yet- # when the smoke probes loss/generation. At 30 steps every- # seed tested hits post_train_loss=0 across all clip- # configurations, so 30 is the seed-robust gate.+ # Sweep (PR #5498) found 7 steps is below the convergence horizon+ # at any clip; at 30 steps every seed hits post_train_loss=0, so+ # 30 is the seed-robust gate.max_steps = 30,learning_rate = 1e-3,warmup_steps = 0,lr_scheduler_type = "constant",optim = "adamw",weight_decay = 0.0,- # max_grad_value (elementwise) is materially cheaper than- # max_grad_norm on MLX -- norm clip needs a cross-tree- # reduction + materializing all grad tensors at full- # precision, value clip is tree_map(mx.clip) per leaf.- # MLXTrainingConfig defaults to max_grad_value=1.0 for- # exactly this reason; pin both explicitly here so the- # configured clip matches what runs (the trainer prints a- # notice when both > 0 and value wins, so disable norm).- # Empirical 13-seed pass rate at this fixture: value=1.0- # 62%, norm=1.0 46%, value=5.0 33%, value=0.5 77% -- the- # cheaper default is also the higher-pass-rate default.+ # Elementwise value clip is cheaper than norm clip on MLX (no+ # cross-tree reduction) and has a higher 13-seed pass rate at this+ # fixture (value=1.0 62%, norm=1.0 46%). Pin both: value wins when+ # both > 0, so disable norm.max_grad_norm = 0.0,max_grad_value = 1.0,logging_steps = 1,diff --git a/tests/studio/test_auth_form_input_count.py b/tests/studio/test_auth_form_input_count.pyindex b80f59d960e..80f73e40652 100644--- a/tests/studio/test_auth_form_input_count.py+++ b/tests/studio/test_auth_form_input_count.py@@ -3,21 +3,15 @@"""Pin the auth-form input-count contract on the change-password page.-PR #5490 added a third visible "Current password" input so the-admin-forced must_change_password reset path (where no bootstrap-script is injected) could supply a current password. The side-effect was that the dominant first-boot UX, where the backend-injects window.__UNSLOTH_BOOTSTRAP__ and the form silently reuses-that password, now showed three visible inputs instead of the two-it had before. PR #5545 restores the two-input first-boot UX by-rendering the Current password input only when-window.__UNSLOTH_BOOTSTRAP__ is absent.--These tests inspect the auth-form source file directly. They never-boot Studio, never spawn a browser, and have no network or device-dependencies, so they are fully deterministic and run on any CI-runner without a JS toolchain. The companion Playwright probe lives-in tests/studio/playwright_chat_ui.py and covers the runtime side.+PR #5490 added a third "Current password" input for the admin-forced reset+path; this regressed the first-boot UX (which reuses the injected+window.__UNSLOTH_BOOTSTRAP__ password) to three visible inputs. PR #5545+restores two inputs by rendering Current password only when BOOTSTRAP is+absent.++These tests inspect the auth-form source directly (no Studio, browser, or+network), so they run deterministically on any CI runner. The runtime side+is covered by tests/studio/playwright_chat_ui.py."""from __future__ import annotationsdiff --git a/tests/studio/test_cancel_id_wiring.py b/tests/studio/test_cancel_id_wiring.pyindex b6f75c0be96..d8217864312 100644--- a/tests/studio/test_cancel_id_wiring.py+++ b/tests/studio/test_cancel_id_wiring.py@@ -51,11 +51,10 @@ def test_chat_completion_request_has_cancel_id_field():def test_cancel_route_matches_cancel_id_exclusively_when_present():- # A stale cancel POST carrying cancel_id AND session_id must not- # cancel a later run on the same thread via the shared session_id.- # Enforce this by requiring the handler to early-return through an- # exclusive-cancel_id path -- either an atomic helper or a keys- # list containing ONLY cancel_id (never session_id).+ # A stale cancel POST carrying cancel_id AND session_id must not cancel a+ # later run via the shared session_id. Require the handler to early-return+ # through an exclusive-cancel_id path (atomic helper, or keys list with+ # ONLY cancel_id, never session_id).for node in ast.walk(ast.parse(ROUTES_SRC)):if isinstance(node, ast.AsyncFunctionDef) and node.name == "cancel_inference":break@@ -137,10 +136,9 @@ def test_chat_adapter_sends_cancel_id_in_abort_cancel_post():def test_abort_cancel_post_uses_plain_fetch_with_manual_auth_header():- # authFetch redirects to login on 401, which would kick the user to- # the login page mid-stop if the access token expired during a long- # stream. Use plain fetch + manual Authorization header for a- # best-effort cancel that never triggers the refresh/redirect flow.+ # authFetch redirects to login on 401, kicking the user out mid-stop if+ # the token expired during a long stream. Use plain fetch + manual+ # Authorization header for a best-effort cancel with no refresh/redirect.start = ADAPTER_SRC.find("const onAbortCancel")assert start >= 0, "onAbortCancel handler missing"rest = ADAPTER_SRC[start:]diff --git a/tests/studio/test_cli_studio_defaults.py b/tests/studio/test_cli_studio_defaults.pyindex a83a62f586e..ed1bd37c3de 100644--- a/tests/studio/test_cli_studio_defaults.py+++ b/tests/studio/test_cli_studio_defaults.py@@ -23,13 +23,10 @@ def _find_typer_option_default(source: str, func_name: str, long_option: str):continueif func_node.name != func_name:continue- # Walk both regular args and kwonly args, each paired with its default.all_args = func_node.args.args + func_node.args.kwonlyargsall_defaults = func_node.args.defaults + [d for d in func_node.args.kw_defaults if d is not None]- # ast pads defaults right-aligned against args (ignoring kwonly). We- # iterate calls directly, which is simpler and robust.for default in all_defaults:if not isinstance(default, ast.Call):continue@@ -42,8 +39,7 @@ def _find_typer_option_default(source: str, func_name: str, long_option: str):)if not is_typer_option:continue- # First positional is the default value; remaining positionals are- # option flags like "--host", "-H".+ # First positional is the default; the rest are flags like "--host".if not default.args:continueflags = [diff --git a/tests/studio/test_composer_rtl_bidi_attribute.py b/tests/studio/test_composer_rtl_bidi_attribute.pyindex e4273c87314..33e5c450cff 100644--- a/tests/studio/test_composer_rtl_bidi_attribute.py+++ b/tests/studio/test_composer_rtl_bidi_attribute.py@@ -133,10 +133,9 @@ def _extract_block(opener: str = "(",closer: str = ")",) -> str:- """Return the source between the first balanced opener/closer that- starts at or after `anchor`. Used to scope assertions to a specific- handler so a re-arm call in some other function does not satisfy- the gate test."""+ """Return the source within the first balanced opener/closer at or+ after `anchor`. Scopes assertions to one handler so a re-arm call+ elsewhere does not satisfy the gate test."""start = src.find(anchor)assert start != -1, f"anchor {anchor!r} not found"open_idx = src.find(opener, start)diff --git a/tests/studio/test_frontend_dep_removal.py b/tests/studio/test_frontend_dep_removal.pyindex 138ffb4ba06..d1835c2bac7 100644--- a/tests/studio/test_frontend_dep_removal.py+++ b/tests/studio/test_frontend_dep_removal.py@@ -315,14 +315,10 @@ def run_case(case: Case, head_pkg: dict) -> tuple[bool, str]:)-# ----------------------------------------------------------------------------# Classifier unit tests: feed hand-crafted snippets directly into classify()-# and assert the returned kind. Covers sneaky import shapes that an-# adversarial / careless dev might use to obscure a real usage.-# -----------------------------------------------------------------------------# Import the script's classify() by file path so this test does not need-# the package to be installed.+# Classifier unit tests: feed hand-crafted snippets into classify() and assert+# the returned kind. Covers sneaky import shapes used to obscure a real usage.++# Import classify() by file path so this test needs no installed package.import importlib.util as _ilu_spec = _ilu.spec_from_file_location("_dep_check", str(SCRIPT))@@ -739,11 +735,9 @@ def run_classify_unit_tests() -> int:return 0 if passed == len(CLASSIFY_CASES) else 1-# ----------------------------------------------------------------------------# Adversarial end-to-end cases: drop a sneaky synthetic file into src/,-# run the checker, then clean up. Catches the case where pattern detection-# regresses for a real grep+classify pipeline (not just classify in isolation).-# ---------------------------------------------------------------------------+# Adversarial end-to-end cases: drop a sneaky synthetic file into src/, run the+# checker, then clean up. Catches detection regressions in the full+# grep+classify pipeline (not just classify in isolation).ADVERSARIAL_TMP_DIR = REPO / "studio/frontend/src/__dep_check_adversarial__"@@ -894,14 +888,9 @@ ADV_CASES: list[AdvCase] = []-# ---------------------------------------------------------------------------# package.json field-reference cases: simulate `prettier: "@x/config"`,-# `eslintConfig.extends`, `overrides`, `peerDependenciesMeta`, etc.-# These test the package_json_extra_refs() coverage. Cross-checked against-# the patterns used by Tailwind, Stylelint, Prettier, Next.js, Astro,-# TypeScript, ESLint, SvelteKit, Storybook, Vite, and TanStack/Query-# manifests.-# ---------------------------------------------------------------------------+# `eslintConfig.extends`, `overrides`, `peerDependenciesMeta`, etc., testing+# package_json_extra_refs() coverage across common tool manifests.@dataclass@@ -1205,9 +1194,7 @@ def run_adversarial_cases() -> int:return 0 if passed == len(ADV_CASES) else 1-# ----------------------------------------------------------------------------# Dead-dep enumeration cases.-# ---------------------------------------------------------------------------+# Dead-dep enumeration cases@dataclass@@ -1383,14 +1370,9 @@ def run_enum_cases() -> int:return 0 if passed == len(ENUM_CASES) else 1-# ----------------------------------------------------------------------------# Script-wrapper cases: exercise scripts_bin_refs / _next_real_bin so a-# package.json script like `cross-env CI=1 biome check` correctly credits-# `@biomejs/biome` rather than the wrapper itself. The 10x reviewer flagged-# the original "first non-env token" heuristic as too narrow: any project-# using cross-env / dotenv / dotenvx / env-cmd / a quoted env value would-# bypass the bin-name check.-# ---------------------------------------------------------------------------+# Script-wrapper cases: exercise scripts_bin_refs / _next_real_bin so a script+# like `cross-env CI=1 biome check` credits `@biomejs/biome`, not the wrapper.+# The original "first non-env token" heuristic missed cross-env / dotenv / etc.@dataclassdiff --git a/tests/studio/test_hardware_dispatch_matrix.py b/tests/studio/test_hardware_dispatch_matrix.pyindex 8864075dd7d..edb8a66b933 100644--- a/tests/studio/test_hardware_dispatch_matrix.py+++ b/tests/studio/test_hardware_dispatch_matrix.py@@ -1,35 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only-"""-Comprehensive hardware dispatch matrix for Studio.--Drives every supported hardware profile from a single test host by-spoofing platform / torch.cuda / torch.xpu / sys.modules['mlx'] so we-can exercise the CUDA, ROCm, XPU, MLX, and CPU dispatch paths-deterministically without real hardware.--Profiles checked:-- nvidia_cuda Linux x86_64 + torch.cuda.is_available()=True,- torch.version.hip=None- amd_rocm Linux x86_64 + torch.cuda.is_available()=True,- torch.version.hip="6.1" (PyTorch ROCm aliases- torch.cuda.* over HIP)- intel_xpu Linux x86_64 + torch.cuda off, torch.xpu.is_available()=True- apple_silicon_mlx Darwin arm64 + cuda off + xpu off + mlx importable- apple_silicon_no_mlx Darwin arm64 + everything off (no mlx pkg)- linux_arm64_with_mlx Linux arm64 + mlx importable -- gate must NOT activate- (canary against accidental Linux-arm64 hijack)- cpu_only Linux x86_64 + nothing -- pure CPU fallback--For each profile we assert three contracts:-- 1. ``unsloth._IS_MLX`` (re-evaluated under the spoof).- 2. ``utils.hardware.detect_hardware()`` ``DeviceType`` and ``IS_ROCM``.- 3. ``utils.hardware.is_apple_silicon()``.--Add a row to ``PROFILES`` to extend coverage; tests parametrize over it-automatically. No real hardware required.-"""+"""Hardware dispatch matrix for Studio.++Spoofs platform / torch.cuda / torch.xpu / sys.modules['mlx'] to exercise the+CUDA, ROCm, XPU, MLX, and CPU dispatch paths deterministically without real+hardware. Each profile in ``PROFILES`` (CUDA, ROCm, XPU, Apple+/-mlx, the+linux-arm64-with-mlx canary, CPU) asserts three contracts: ``unsloth._IS_MLX``,+``detect_hardware()`` DeviceType + ``IS_ROCM``, and ``is_apple_silicon()``.+Add a row to ``PROFILES`` to extend coverage; tests parametrize over it."""from __future__ import annotations@@ -189,10 +166,7 @@ PROFILE_IDS = [p.name for p in PROFILES]@pytest.fixturedef spoof_hardware(monkeypatch):"""Return a function that applies a HardwareProfile to the live process.-- Idempotent: each call re-applies the profile. Cleanup happens- automatically when the test exits via monkeypatch.- """+ Idempotent; monkeypatch cleans up on test exit."""def _apply(profile: HardwareProfile) -> None:import platform@@ -202,12 +176,9 @@ def spoof_hardware(monkeypatch):monkeypatch.setattr(platform, "system", lambda: profile.system)monkeypatch.setattr(platform, "machine", lambda: profile.machine)- # torch.cuda.is_availablemonkeypatch.setattr(torch.cuda, "is_available", lambda: profile.cuda_available)- # detect_hardware reads torch.cuda.get_device_properties(0).name when- # cuda_available is True. On a CPU CI runner that triggers _cuda_init- # and crashes with "No CUDA GPUs are available". Stub it so the- # dispatch path under test runs end-to-end.+ # Stub get_device_properties: detect_hardware reads .name when CUDA is+ # available, which crashes on a CPU CI runner ("No CUDA GPUs").if profile.cuda_available:stub_props = types.SimpleNamespace(name = "Stub GPU" if not profile.hip_version else "Stub AMD GPU",@@ -219,13 +190,12 @@ def spoof_hardware(monkeypatch):raising = False,)- # torch.version.hip — None on NVIDIA, "6.1" etc. on ROCm+ # torch.version.hip: None on NVIDIA, "6.1" etc. on ROCmtorch_version = torch.versionmonkeypatch.setattr(torch_version, "hip", profile.hip_version, raising = False)- # torch.xpu.is_available + get_device_name -- detect_hardware reads both.- # Real torch.xpu.get_device_name requires the XPU-compiled torch build,- # so always stub it under the spoof to keep tests hardware-agnostic.+ # Stub torch.xpu.* (detect_hardware reads both); real get_device_name+ # needs the XPU torch build, so always stub to stay hardware-agnostic.if hasattr(torch, "xpu"):monkeypatch.setattr(torch.xpu, "is_available", lambda: profile.xpu_available)monkeypatch.setattr(@@ -255,8 +225,7 @@ def spoof_hardware(monkeypatch):monkeypatch.setitem(sys.modules, "mlx", fake_mlx)monkeypatch.setitem(sys.modules, "mlx.core", fake_mlx_core)else:- # Drop any cached mlx modules and patch find_spec so the- # unsloth gate (which uses importlib.util.find_spec) sees+ # Drop cached mlx and patch find_spec so the unsloth gate sees# mlx as absent.monkeypatch.delitem(sys.modules, "mlx", raising = False)monkeypatch.delitem(sys.modules, "mlx.core", raising = False)@@ -269,11 +238,9 @@ def spoof_hardware(monkeypatch):monkeypatch.setattr(importlib.util, "find_spec", _no_mlx)- # Studio's _has_mlx() literally does `import mlx.core`, not- # find_spec, so on a real Apple Silicon host with mlx- # genuinely installed the import would still succeed. Block- # it via a meta_path finder that raises ImportError for any- # `mlx` / `mlx.*` import while this profile is active.+ # Studio's _has_mlx() does `import mlx.core`, not find_spec, so on a+ # real Apple Silicon host with mlx installed it would still succeed.+ # Block it via a meta_path finder that raises ImportError for mlx.*.class _BlockMLXFinder:def find_spec(self_inner,@@ -288,8 +255,7 @@ def spoof_hardware(monkeypatch):return Noneblocker = _BlockMLXFinder()- # Replace meta_path with a NEW list so monkeypatch can fully- # restore the original on teardown (mutating the list in+ # New list so monkeypatch fully restores on teardown (mutating in# place would survive the test).monkeypatch.setattr(sys,@@ -373,10 +339,8 @@ def test_studio_is_apple_silicon_matches_profile(profile, spoof_hardware):def test_cuda_takes_priority_over_mlx_when_both_available(spoof_hardware):- """If both CUDA and MLX are available, Studio MUST pick CUDA. This is the- canary that protects every existing GPU user from being silently routed- to MLX after future refactors.- """+ """If both CUDA and MLX are available, Studio MUST pick CUDA: the canary+ guarding GPU users from being silently routed to MLX after refactors."""profile = HardwareProfile(name = "cuda_plus_mlx",system = "Darwin",diff --git a/tests/studio/test_is_mlx_dispatch_gate.py b/tests/studio/test_is_mlx_dispatch_gate.pyindex 4e379aa976f..594ab39076d 100644--- a/tests/studio/test_is_mlx_dispatch_gate.py+++ b/tests/studio/test_is_mlx_dispatch_gate.py@@ -42,16 +42,11 @@ REPO_ROOT = Path(__file__).resolve().parents[2]UNSLOTH_INIT = REPO_ROOT / "unsloth" / "__init__.py"-# ---------------------------------------------------------------------------# 1. Source-level structure check on _IS_MLX (no platform dependencies).-# ---------------------------------------------------------------------------def test_is_mlx_gate_uses_three_required_predicates():- """The _IS_MLX assignment must AND together exactly the three checks- that Studio depends on: Darwin OS, arm64 machine, and an importable- mlx package. Dropping any one of them silently breaks dispatch.- """+ """_IS_MLX must AND the three checks Studio depends on (Darwin, arm64, importable mlx); dropping any breaks dispatch."""tree = ast.parse(UNSLOTH_INIT.read_text())target = None@@ -95,18 +90,13 @@ def test_is_mlx_gate_uses_three_required_predicates():), "_IS_MLX helper must run the local MLX precheck before importing zoo"-# ---------------------------------------------------------------------------# 2. Runtime gate behavior with the platform spoofed to Apple Silicon and a-# fake mlx module in sys.modules. Re-evaluates the same expression-# rather than reloading unsloth (which would cascade-reload torch).-# ---------------------------------------------------------------------------+# fake mlx module in sys.modules. Re-evaluates the same expression rather+# than reloading unsloth (which would cascade-reload torch).def _evaluate_is_mlx_precheck(platform_module, importlib_util, os_module):- """Re-evaluate the local _is_mlx_available precheck using injected dependencies.-- Mirrors only the cheap import barrier before unsloth imports unsloth_zoo.- """+ """Re-evaluate the local _is_mlx_available precheck (the import barrier before zoo) with injected deps."""return (os_module.environ.get("UNSLOTH_FORCE_GPU_PATH", "0") != "1"and platform_module.system() == "Darwin"diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.pyindex 6906e9b7d27..6bd74f00de3 100644--- a/tests/studio/test_stream_cancel_registration_timing.py+++ b/tests/studio/test_stream_cancel_registration_timing.py@@ -1,43 +1,19 @@-"""-Tests that the cancel tracker is registered BEFORE StreamingResponse is-returned, and that cleanup runs via a `finally` block inside each-async generator.--The zombie-generation scenario is: user clicks Stop during prefill /-warmup / proxy buffering, before the first SSE chunk. If _tracker-__enter__ lives inside the async generator body, the registry is empty-at the moment /api/inference/cancel lands -- so cancel returns 0 and-the decode runs to completion.--The fix moves _tracker = _TrackedCancel(...) and _tracker.__enter__()-to the synchronous body of openai_chat_completions (before the-StreamingResponse is returned) and places _tracker.__exit__ inside-each generator's `finally` block. Using a generator `finally` (rather-than a Starlette BackgroundTask) guarantees cleanup on every-termination path -- normal exhaustion, CancelledError from-ClientDisconnect, and OSError / BrokenPipeError during send() ---because Starlette skips `background` callbacks when stream_response-raises.--Structural verifies:- - No `async def ...:` body contains `_tracker.__enter__()` in- routes/inference.py (registration moved to sync body).- - Each of the four async generators (gguf_tool_stream,- gguf_stream_chunks, stream_chunks, audio_input_stream) contains- `_tracker.__exit__(None, None, None)` inside a try/finally block.- - No StreamingResponse in openai_chat_completions passes- `background=` (cleanup now lives in the generator finally).--Behavioral verifies (extracting `_TrackedCancel` from source and-exercising the actual runtime semantics):- - `finally: _tracker.__exit__(...)` runs on normal completion,- mid-stream exception (OSError / BrokenPipeError from send()),- and aclose() from Starlette ClientDisconnect.- - A pre-set cancel_event (from `_TrackedCancel.__enter__` replaying- a pending cancel POST) lets the GGUF while-loop break cleanly- and emit final_chunk + [DONE] instead of propagating- `GeneratorExit` out of `_stream_with_retry` into the async- generator's `except Exception` (which would not catch it).+"""Tests that the cancel tracker is registered BEFORE StreamingResponse is+returned and that cleanup runs in a `finally` inside each async generator.++Zombie scenario: Stop during prefill/warmup/proxy buffering (before the first+SSE chunk). If _tracker.__enter__ ran inside the generator body, the registry+would be empty when /api/inference/cancel lands, so cancel returns 0 and decode+runs to completion. The fix registers in the sync body of+openai_chat_completions and cleans up in each generator's `finally` -- a+BackgroundTask would be skipped when stream_response raises.++Structural verifies: no `_tracker.__enter__()` inside the async generators;+each of the four generators has `_tracker.__exit__(...)` in a try/finally; no+StreamingResponse passes `background=`. Behavioral verifies (running the+extracted `_TrackedCancel`): finally cleanup on normal completion, mid-stream+OSError, and aclose() from ClientDisconnect; and a pre-set cancel_event lets+the GGUF loop break cleanly emitting final_chunk + [DONE]."""from __future__ import annotations@@ -328,11 +304,9 @@ def test_finally_cleanup_on_aclose():def test_preset_cancel_event_exits_cleanly_with_done():- # Pending-replay: POST /cancel arrived before the stream registered,- # was stashed, then consumed by _TrackedCancel.__enter__ which set- # cancel_event. The generator must break out of the loop cleanly- # and emit final_chunk + [DONE] rather than calling next(gen) and- # propagating `GeneratorExit` out of the GGUF stream wrapper.+ # Pending-replay: a stashed cancel set cancel_event via __enter__. The+ # generator must break cleanly and emit final_chunk + [DONE] rather than+ # calling next(gen) and propagating GeneratorExit out of the GGUF wrapper.ev = threading.Event()ev.set()chunks = asyncio.run(_consume(_post_fix_gguf_loop(ev)))@@ -465,11 +439,9 @@ def test_audio_input_stream_offloads_blocking_next_to_thread():def test_stream_chunks_cancel_branch_resets_backend_state():- # The Unsloth path's cancel branch must flush GPU / KV-cache state- # via `backend.reset_generation_state()` -- the orchestrator's- # internal cancel path does not do this, so a cancel-via-POST that- # only broke the loop would leave the subprocess in a dirty state- # for the next request.+ # The Unsloth cancel branch must call backend.reset_generation_state() to+ # flush GPU/KV-cache state, else a cancel-via-POST leaves the subprocess+ # dirty for the next request.fn = Nonetop = Nonefor n in ast.walk(_TREE):@@ -618,12 +590,9 @@ def test_audio_stream_stays_responsive_under_blocking_next():def test_unsloth_stream_loop_emits_zero_tokens_on_preset_cancel():- # Pending-cancel replay: _TrackedCancel.__enter__ already set- # cancel_event before the generator body starts iterating. The- # top-of-loop check must short-circuit the very first iteration so- # no token is emitted. Catches a regression that moves the check- # below `next()` -- the mid-loop test would still pass but this- # test would observe one extra token leak.+ # Pending-cancel replay: cancel_event was pre-set before iterating, so the+ # top-of-loop check must short-circuit iteration 1 (zero tokens). Catches a+ # regression that moves the check below next() (leaks one extra token).cancel_event = threading.Event()cancel_event.set()reset_calls = [0]diff --git a/tests/test_cli_export_unpacking.py b/tests/test_cli_export_unpacking.pyindex 3dbab90b5a1..626ff41bc1d 100644--- a/tests/test_cli_export_unpacking.py+++ b/tests/test_cli_export_unpacking.py@@ -1,24 +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-"""-Regression tests for unsloth_cli.commands.export.+"""Regression tests for unsloth_cli.commands.export.-Context: the studio export dialog live-logs work changed-ExportOrchestrator.export_{merged_model,base_model,gguf,lora_adapter}-to return (success, message, output_path) instead of (success, message)-so the frontend can show the on-disk realpath on the success screen.-The CLI at unsloth_cli/commands/export.py still unpacks two values,-so every `unsloth export --format ...` crashes with:-- ValueError: too many values to unpack (expected 2)--These tests pin the CLI to the 3-tuple contract by invoking it against-a fake ExportBackend and asserting exit_code == 0 for each --format.-No real ML imports; the fake is installed via sys.modules injection so-the CLI's deferred `from studio.backend.core.export import ExportBackend`-binds to it.-"""+ExportOrchestrator.export_* now returns (success, message, output_path) so the+frontend can show the realpath, but the CLI still unpacked two values, crashing+every `unsloth export` with "too many values to unpack (expected 2)". These+tests pin the CLI to the 3-tuple contract via a fake ExportBackend injected into+sys.modules (the CLI's deferred import binds to it), asserting exit_code == 0+per --format."""from __future__ import annotations@@ -37,11 +27,8 @@ from typer.testing import CliRunnerclass _FakeExportBackend:- """Stand-in for studio.backend.core.export.ExportBackend.-- All export_* methods return the new 3-tuple contract. load_checkpoint- keeps its 2-tuple shape (unchanged by the live-logs work).- """+ """Stand-in for ExportBackend: export_* return the new 3-tuple;+ load_checkpoint keeps its 2-tuple shape."""def __init__(self) -> None:self.loaded: str | None = None@@ -67,15 +54,9 @@ class _FakeExportBackend:def _install_fake_studio_backend(monkeypatch: pytest.MonkeyPatch) -> None:- """Inject fake studio.backend.core.export into sys.modules.-- The CLI imports ExportBackend lazily inside the command function, so- patching sys.modules before invoking the command is sufficient to- steer the `from studio.backend.core.export import ExportBackend`- statement at the fake. Parent packages (studio, studio.backend,- studio.backend.core) are stubbed too so Python's import machinery- doesn't try to resolve the real (structlog-dependent) tree.- """+ """Inject fake studio.backend.core.export into sys.modules. The CLI imports+ ExportBackend lazily, so this steers it at the fake; parent packages are+ stubbed too so import machinery skips the real structlog-dependent tree."""for name in ("studio", "studio.backend", "studio.backend.core"):monkeypatch.setitem(sys.modules, name, types.ModuleType(name))@@ -83,9 +64,7 @@ def _install_fake_studio_backend(monkeypatch: pytest.MonkeyPatch) -> None:fake_mod.ExportBackend = _FakeExportBackendmonkeypatch.setitem(sys.modules, "studio.backend.core.export", fake_mod)- # Drop any cached import of the CLI module so the deferred import- # inside export() re-resolves against our fake module rather than a- # previously cached real one.+ # Drop cached CLI module so export()'s deferred import re-resolves the fake.monkeypatch.delitem(sys.modules, "unsloth_cli.commands.export", raising = False)diff --git a/tests/test_enforce_kwargs_spacing.py b/tests/test_enforce_kwargs_spacing.pyindex 5e135c982c9..4521b0362dc 100644--- a/tests/test_enforce_kwargs_spacing.py+++ b/tests/test_enforce_kwargs_spacing.py@@ -82,7 +82,7 @@ def test_blank_removed_for_small_import_block(name):out, changed = remove_blank_after_short_import(src)assert changed is Trueassert out != src- # The import line and the following statement are now adjacent (no blank between).+ # Import and following statement now adjacent (no blank between).assert "\n\n" not in out or out.count("\n\n") < src.count("\n\n")# Semantics preserved and idempotent.assert ast.dump(ast.parse(out)) == ast.dump(ast.parse(src))diff --git a/tests/test_finetune_last_n_layers.py b/tests/test_finetune_last_n_layers.pyindex e2dafb76385..fa708ddd3e1 100644--- a/tests/test_finetune_last_n_layers.py+++ b/tests/test_finetune_last_n_layers.py@@ -1,16 +1,9 @@# Unsloth - 2x faster, 70% less memory LLM finetuning# Tests for the `finetune_last_n_layers` parity knob (CUDA side).#-# Mirrors unsloth-zoo's `FastMLXModel.get_peft_model` parameter.-# mlx-lm CLI's CONFIG_DEFAULTS['num_layers']=16 applies LoRA to the-# last 16 transformer blocks only. On the CUDA path, PEFT exposes-# `layers_to_transform` to do the same. This convenience knob fills-# `layers_to_transform` for the user when set, matching mlx-lm CLI-# AND unsloth-zoo's MLX path with a single config value.-#-# The tests intentionally avoid pulling in CUDA / a real model-# checkpoint — they exercise only the helper that translates-# `finetune_last_n_layers` into `layers_to_transform`.+# Mirrors unsloth-zoo's MLX path: fills PEFT's `layers_to_transform` so LoRA+# applies to the last N transformer blocks, matching mlx-lm CLI's num_layers.+# Exercises only the translation helper, no CUDA / real checkpoint.from __future__ import annotationsdiff --git a/tests/test_import_fixes_drift.py b/tests/test_import_fixes_drift.pyindex bf033d02358..373830ae4ab 100644--- a/tests/test_import_fixes_drift.py+++ b/tests/test_import_fixes_drift.py@@ -48,9 +48,7 @@ def _safe_version(raw):return _PkgVersion(match.group(0))-# ===========================================================================# protobuf-# ===========================================================================def test_protobuf_message_factory_get_prototype_or_get_message_class_present():@@ -73,9 +71,7 @@ def test_protobuf_message_factory_get_prototype_or_get_message_class_present():assert has_get_prototype or has_get_message_class-# ===========================================================================# datasets-# ===========================================================================def test_datasets_version_not_in_broken_recursion_range():@@ -92,9 +88,7 @@ def test_datasets_version_not_in_broken_recursion_range():)-# ===========================================================================# trl-# ===========================================================================def test_trl_is_x_available_returns_bool_not_tuple():@@ -165,9 +159,7 @@ def test_trl_cached_available_flags_are_not_tuples():)-# ===========================================================================# transformers-# ===========================================================================def test_pretrained_model_enable_input_require_grads_uses_old_pattern():@@ -234,9 +226,7 @@ def test_transformers_is_causal_conv1d_available_symbol_present():)-# ===========================================================================# transformers + accelerate (wandb checkers)-# ===========================================================================def test_transformers_and_accelerate_is_wandb_available_callable():@@ -266,9 +256,7 @@ def test_transformers_and_accelerate_is_wandb_available_callable():)-# ===========================================================================# peft-# ===========================================================================def test_peft_transformers_weight_conversion_importable_and_signature():@@ -298,9 +286,7 @@ def test_peft_transformers_weight_conversion_importable_and_signature():)-# ===========================================================================# triton-# ===========================================================================def test_triton_compiled_kernel_has_num_ctas_and_cluster_dims():@@ -335,9 +321,7 @@ def test_triton_compiled_kernel_has_num_ctas_and_cluster_dims():)-# ===========================================================================# torch + torchvision pairing table-# ===========================================================================# Mirrors TORCH_TORCHVISION_COMPAT in torchvision_compatibility_check@@ -401,9 +385,7 @@ def test_installed_torch_torchvision_pair_is_compatible():)-# ===========================================================================# vllm-# ===========================================================================def test_vllm_guided_decoding_params_or_structured_outputs_present():@@ -447,9 +429,7 @@ def test_vllm_aimv2_ovis_config_is_past_fix_version():)-# ===========================================================================# huggingface_hub-# ===========================================================================def test_huggingface_hub_is_offline_mode_or_hf_hub_offline_present():@@ -477,9 +457,7 @@ def test_huggingface_hub_is_offline_mode_or_hf_hub_offline_present():)-# ===========================================================================# torch-# ===========================================================================def test_torch_nn_init_trunc_normal_exists():@@ -494,9 +472,7 @@ def test_torch_nn_init_trunc_normal_exists():)-# ===========================================================================# xformers-# ===========================================================================def test_xformers_is_post_num_splits_key_fix_or_not_installed():@@ -515,9 +491,7 @@ def test_xformers_is_post_num_splits_key_fix_or_not_installed():)-# ===========================================================================# transformers (PreTrainedModel base import sanity)-# ===========================================================================def test_transformers_pretrained_model_has_get_input_embeddings():@@ -533,18 +507,14 @@ def test_transformers_pretrained_model_has_get_input_embeddings():)-# ===========================================================================# accelerate -- ``is_X_available`` API stability used across the fixes-# ===========================================================================-# ===========================================================================# transformers LOSS_MAPPING -- patch_loss_functions() coverage# Regression for https://github.com/unslothai/unsloth/issues/4188:# Qwen3_5ForConditionalGeneration has loss_type='ForConditionalGeneration',# a separate LOSS_MAPPING key that was never patched, leaving the model with# the stock ForCausalLMLoss which does logits.float() and OOMs on <=24 GB GPUs.-# ===========================================================================def _reset_loss_mapping(mapping, saved):diff --git a/tests/test_model_registry.py b/tests/test_model_registry.pyindex 3d34e783bae..bbcfdd8aa9e 100644--- a/tests/test_model_registry.py+++ b/tests/test_model_registry.py@@ -1,11 +1,7 @@-"""--Test model registration methods-Checks that model registration methods work for respective models as well as all models-The check is performed-- by registering the models-- checking that the instantiated models can be found on huggingface hub by querying for the model id+"""Test model registration methods.+Registers each model set and checks the registered model ids exist on the+Hugging Face Hub."""from dataclasses import dataclassdiff --git a/tests/test_multi_image_grpo_chunking.py b/tests/test_multi_image_grpo_chunking.pyindex 07ad95d5d78..ccd10f905a8 100644--- a/tests/test_multi_image_grpo_chunking.py+++ b/tests/test_multi_image_grpo_chunking.py@@ -16,7 +16,7 @@ def _read_source() -> str:return fh.read()-# ---------- Per-chunk slicing fixes (cum_rows, cum_imgs, axes) ----------+# Per-chunk slicing fixes (cum_rows, cum_imgs, axes)def test_cum_rows_materialized_on_cpu():@@ -60,7 +60,7 @@ def test_image_sizes_chunked_after_branch_decision():)-# ---------- Behavioral simulation of chunk math ----------+# Behavioral simulation of chunk mathdef _simulate_chunk_indices(num_images, B):@@ -106,7 +106,7 @@ def test_simulate_pixel_attention_mask_axis_decision():assert select_axis(2, 2, 2, 2, False) == "sample"-# ---------- Zoo compatibility guard ----------+# Zoo compatibility guarddef test_zoo_guard_branch_present():diff --git a/tests/test_public_api_surface.py b/tests/test_public_api_surface.pyindex 50cc5047499..140fda99f56 100644--- a/tests/test_public_api_surface.py+++ b/tests/test_public_api_surface.py@@ -13,14 +13,10 @@"""Public-API surface drift detectors for unsloth itself.-Companion to tests/test_import_fixes_drift.py: that file catches drift-in THIRD-PARTY libraries (transformers / trl / triton / peft / etc.)-that unsloth's import_fixes patches around. This file catches drift in-unsloth's OWN public-surface API -- the top-10 symbols and classmethods-that the unslothai/notebooks tree (and therefore every user on Colab)-calls. If a refactor on this repo renames FastLanguageModel.from_pretrained-or drops one of the documented kwargs, the test fires DRIFT DETECTED-here BEFORE the breakage reaches users.+Companion to tests/test_import_fixes_drift.py (which catches THIRD-PARTY drift):+this catches drift in unsloth's OWN public surface -- the top symbols and+classmethods the unslothai/notebooks tree calls -- so a rename or dropped kwarg+fires DRIFT DETECTED here before it reaches users.Call-site counts measured against unslothai/notebooks @ main:FastLanguageModel.from_pretrained 506@@ -33,10 +29,9 @@ Call-site counts measured against unslothai/notebooks @ main:FastModel.from_pretrained 103FastModel.get_peft_model 67-Mirrors the unsloth-zoo / unsloth drift-detector skeleton:-``pytest.importorskip("unsloth")`` to gate, assert the healthy upstream-shape, ``pytest.fail("DRIFT DETECTED: ...")`` (never ``pytest.skip``) on-regression so the matrix cell goes red.+Mirrors the drift-detector skeleton: gate on ``pytest.importorskip("unsloth")``,+assert the healthy shape, and ``pytest.fail("DRIFT DETECTED: ...")`` (never skip)+on regression so the matrix cell goes red."""from __future__ import annotations@@ -70,10 +65,8 @@ def _accepts(callable_obj, kwargs: set[str]) -> tuple[bool, set[str]]:return (not missing), missing-# ===========================================================================-# FastLanguageModel: the headline class. 506 from_pretrained + 370-# for_inference + 304 get_peft_model call sites across the notebooks.-# ===========================================================================+# FastLanguageModel: headline class (506 from_pretrained + 370 for_inference ++# 304 get_peft_model call sites).def test_fast_language_model_class_present():@@ -126,9 +119,7 @@ def test_fast_language_model_for_inference_callable():)-# ===========================================================================# FastVisionModel: 183 + 176 + 99 + 60 call sites across vision notebooks.-# ===========================================================================def test_fast_vision_model_class_and_methods():@@ -165,9 +156,7 @@ def test_fast_vision_model_get_peft_model_vision_kwargs():)-# ===========================================================================-# FastModel: the modern unified entry point. 103 + 67 call sites.-# ===========================================================================+# FastModel: modern unified entry point. 103 + 67 call sites.def test_fast_model_class_and_methods():@@ -197,9 +186,7 @@ def test_fast_model_from_pretrained_kwargs():)-# ===========================================================================# Bf16 helper alias (renamed once already; keep both accepted).-# ===========================================================================def test_is_bf16_supported_or_alias_callable():diff --git a/tests/test_raw_text.py b/tests/test_raw_text.pyindex dda8de9a5e6..b930e7ab310 100644--- a/tests/test_raw_text.py+++ b/tests/test_raw_text.py@@ -22,10 +22,10 @@ class MockDataset:def __getitem__(self, idx):if isinstance(idx, str):- # Allow accessing columns by name like dataset['text']+ # Access columns by name, e.g. dataset['text']return self.data[idx]elif isinstance(idx, int):- # Allow accessing individual rows by index+ # Access individual rows by indexreturn {key: values[idx] for key, values in self.data.items()}else:raise TypeError(f"Invalid index type: {type(idx)}")diff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.pyindex a0093adb122..7d93645ca99 100644--- a/tests/test_studio_install_workspace_guard.py+++ b/tests/test_studio_install_workspace_guard.py@@ -16,12 +16,10 @@ INSTALL_PS1 = REPO_ROOT / "install.ps1"SETUP_PS1 = REPO_ROOT / "studio" / "setup.ps1"SETUP_SH = REPO_ROOT / "studio" / "setup.sh"-# Stubs for helpers that the extracted install.sh guard block calls in real-# installs (`substep` for status output, `_start_studio_venv_replacement` for-# the rollback-managed move). The tests run the block in isolation, so we-# stand in a minimal `mv`-based replacement that exercises the same observable-# effect (venv directory is no longer present at $VENV_DIR after a permitted-# cleanup) without dragging in install.sh's full rollback machinery.+# Stubs for helpers the extracted install.sh guard block calls (`substep`,+# `_start_studio_venv_replacement`). Tests run the block in isolation, so a+# minimal `mv`-based replacement reproduces the observable effect (venv gone+# from $VENV_DIR after permitted cleanup) without the full rollback machinery._INSTALL_GUARD_STUBS = ("substep() { :; }\n""_start_studio_venv_replacement() {\n"@@ -623,11 +621,9 @@ def test_tauri_preflight_scrubs_studio_home_env():"""All three Tauri CLI-spawn sites that lacked the scrub must nowenv_remove UNSLOTH_STUDIO_HOME and STUDIO_HOME, mirroringprocess.rs / install.rs / desktop_auth.rs / update.rs."""- # preflight was originally a single .rs file; PR #5341 split it into- # a directory of submodules (backend / managed / types / version).- # Read whichever shape is on disk so the guard stays valid through- # future reorgs as long as the scrub calls live somewhere under- # studio/src-tauri/src/preflight*.+ # preflight was one .rs file; PR #5341 split it into a submodule dir. Read+ # whichever shape is on disk so the guard survives reorgs, as long as the+ # scrub calls live under studio/src-tauri/src/preflight*.preflight_root = REPO_ROOT / "studio" / "src-tauri" / "src"preflight_paths = [preflight_root / "preflight.rs",@@ -908,9 +904,8 @@ def test_install_sh_install_id_survives_symlinked_studio_home(tmp_path):# Write a stub install id at the canonical location.valid_id = "ab12" * 16(studio_home / "share" / "studio_install_id").write_text(valid_id)- # Read it back via both the canonical and the symlinked path; both must- # see the SAME content (which is what makes install.sh's cat and the- # backend's read_text agree without any canonicalization dance).+ # Read back via canonical and symlinked path; both must see the SAME+ # content so install.sh's cat and the backend's read_text agree.raw_via_link = link / ".unsloth" / "studio" / "share" / "studio_install_id"raw_direct = studio_home / "share" / "studio_install_id"assert raw_via_link.read_text() == valid_iddiff --git a/tests/utils/aime_eval.py b/tests/utils/aime_eval.pyindex 8fd0207180f..6b7db2026d6 100644--- a/tests/utils/aime_eval.py+++ b/tests/utils/aime_eval.py@@ -1,7 +1,5 @@"""-AIME Dataset Evaluation Module--This module provides functions to evaluate language models on the combined AIME dataset+Evaluate language models on the combined AIME dataset(test2024 + test2025-I + test2025-II)."""@@ -27,7 +25,6 @@ def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str:os.makedirs(data_dir, exist_ok = True)combined_filepath = os.path.join(data_dir, "aime.jsonl")- # Check if combined file already existsif os.path.exists(combined_filepath):print(f"Combined AIME dataset already exists at {combined_filepath}")return combined_filepath@@ -44,12 +41,11 @@ def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str:response = requests.get(url)response.raise_for_status()- # Parse each line and add source information+ # Parse each line and tag with source + global IDfor line_num, line in enumerate(response.text.strip().split("\n")):if line.strip():try:data = json.loads(line)- # Add source dataset information and global IDdata["source_dataset"] = dataset_namedata["original_id"] = data.get("id", line_num)data["global_id"] = global_id@@ -65,7 +61,6 @@ def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str:print(f" Error downloading {dataset_name}: {e}")continue- # Write combined datasetif all_problems:with open(combined_filepath, "w", encoding = "utf-8") as f:for problem in all_problems:@@ -74,7 +69,6 @@ def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str:print(f"✅ Combined {len(all_problems)} problems from {len(datasets)} datasets")print(f" Saved to: {combined_filepath}")- # Print summary by datasetfor dataset_name in datasets.keys():count = sum(1 for p in all_problems if p["source_dataset"] == dataset_name)print(f" {dataset_name}: {count} problems")@@ -88,7 +82,6 @@ def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str:def load_aime_dataset(data_dir: str = "./data/aime") -> List[Dict[str, Any]]:"""Load combined AIME dataset and format for evaluation"""- # Download and combine if neededfilepath = download_and_combine_aime_datasets(data_dir)examples = []@@ -99,7 +92,6 @@ def load_aime_dataset(data_dir: str = "./data/aime") -> List[Dict[str, Any]]:try:data = json.loads(line)- # Format as expected by our evaluationformatted_example = {"global_id": data.get("global_id", line_num),"original_id": data.get("original_id", data.get("id", line_num)),@@ -128,7 +120,6 @@ def load_aime_dataset(data_dir: str = "./data/aime") -> List[Dict[str, Any]]:print(f"Loaded {len(examples)} problems from combined AIME dataset")- # Print breakdown by sourcesource_counts = {}for example in examples:source = example["source_dataset"]@@ -143,8 +134,7 @@ def load_aime_dataset(data_dir: str = "./data/aime") -> List[Dict[str, Any]]:def extract_aime_answer(response: str) -> str:"""Extract numerical answer from AIME response"""- # AIME answers are integers from 0-999- # Look for patterns like "The answer is 123" or just standalone numbers+ # AIME answers are integers 0-999; match "The answer is 123" etc.patterns = [r"(?:the )?(?:final )?answer is (\d{1,3})",r"(?:therefore|thus|so),?\s*(?:the )?(?:final )?answer is (\d{1,3})",@@ -159,19 +149,18 @@ def extract_aime_answer(response: str) -> str:for pattern in patterns:matches = re.findall(pattern, response_lower, re.MULTILINE | re.IGNORECASE)if matches:- # Get the last match (most likely to be final answer)- answer = matches[-1]+ answer = matches[-1] # last match is most likely the final answertry:num = int(answer)- if 0 <= num <= 999: # AIME answers are in range 0-999+ if 0 <= num <= 999:return str(num)except ValueError:continue- # If no clear pattern found, try to extract any 1-3 digit number+ # Fallback: any 1-3 digit number, scanning from the endnumbers = re.findall(r"\b(\d{1,3})\b", response)if numbers:- for num_str in reversed(numbers): # Check from end+ for num_str in reversed(numbers):try:num = int(num_str)if 0 <= num <= 999:@@ -208,7 +197,6 @@ def evaluate_model_aime(print(f"Combined Dataset: test2024 + test2025-I + test2025-II")print(f"{'='*70}")- # Load combined AIME datasettry:eval_dataset = load_aime_dataset()except Exception as e:@@ -219,7 +207,6 @@ def evaluate_model_aime(print("No examples found in dataset")return None- # Initialize tracking variablesrecords = {}input_tokens = []output_tokens = []@@ -268,11 +255,9 @@ def evaluate_model_aime(try:print(f"\n🚀 Evaluating {len(eval_dataset)} problems...")- # Main evaluation loopwith tqdm(total = len(eval_dataset), desc = "Processing AIME problems", unit = "problem") as pbar:for task_id, item in enumerate(eval_dataset):try:- # Prepare promptprompt_text = tokenizer.apply_chat_template(item["prompt"], add_generation_prompt = True, tokenize = False)@@ -287,17 +272,15 @@ def evaluate_model_aime(use_tqdm = False,)[0].outputs- # Process all generated responsesresponses = [output.text for output in outputs]extracted_answers = [extract_aime_answer(response) for response in responses]- # Calculate total output tokenstotal_output_tokens = sum(get_num_tokens(response, tokenizer) for response in responses)output_tokens.append(total_output_tokens)- # Check if any answer is correct+ # Correct if any sample matches ground truthground_truth = item["answer"]correct_responses = [ans == ground_truth for ans in extracted_answers]is_correct = any(correct_responses)@@ -306,7 +289,6 @@ def evaluate_model_aime(correct_answers += 1source_stats[item["source_dataset"]]["correct"] += 1- # Store detailed recordrecords[task_id] = {"global_id": item["global_id"],"original_id": item["original_id"],@@ -325,7 +307,6 @@ def evaluate_model_aime("url": item.get("url", ""),}- # Update progresscurrent_accuracy = correct_answers / (task_id + 1) * 100pbar.set_postfix({@@ -355,11 +336,10 @@ def evaluate_model_aime(for logger_name, level in original_levels.items():logging.getLogger(logger_name).setLevel(level)- # Calculate metricstotal_problems = len(eval_dataset)accuracy = correct_answers / total_problems * 100- # Calculate Pass@k (probability that at least one of k samples is correct)+ # Pass@k: probability at least one of k samples is correctpass_at_k_scores = []for record in records.values():if "n_correct" in record and "n_total" in record:@@ -372,7 +352,7 @@ def evaluate_model_aime(pass_at_k = sum(pass_at_k_scores) / len(pass_at_k_scores) if pass_at_k_scores else 0- # Calculate per-source accuracies+ # Per-source accuraciessource_accuracies = {}for source, stats in source_stats.items():source_accuracies[source] = (@@ -399,12 +379,10 @@ def evaluate_model_aime("max_output_tokens": max(output_tokens) if output_tokens else 0,}- # Save resultsfilename = f"aime_eval_combined_{model_type}_t{temperature}_n{n_sampling}.json"with open(filename, "w", encoding = "utf-8") as f:json.dump({"results": results, "records": records}, f, indent = 4)- # Print comprehensive summaryprint(f"\n{'='*70}")print(f"📊 AIME EVALUATION RESULTS - {model_type.upper()}")print(f"{'='*70}")diff --git a/tests/utils/cleanup_utils.py b/tests/utils/cleanup_utils.pyindex dbe5dbd5568..c04523a7a4a 100644--- a/tests/utils/cleanup_utils.py+++ b/tests/utils/cleanup_utils.py@@ -21,7 +21,7 @@ def clear_memory(clear_all_caches: Clear all types of caches (recommended for memory leaks)"""- # Save current logging levels+ # Save logging levels to restore latersaved_log_levels = {}for name, logger in logging.Logger.manager.loggerDict.items():if isinstance(logger, logging.Logger):@@ -42,11 +42,11 @@ def clear_memory("bnb_config",]- # 1. Clear LRU caches FIRST (very important for memory leaks)+ # Clear LRU caches first (important for memory leaks)if clear_all_caches:clear_all_lru_caches(verbose)- # 2. Delete specified variables+ # Delete specified variablesg = globals()deleted_vars = []for var in variables_to_clear:@@ -57,24 +57,21 @@ def clear_memory(if verbose and deleted_vars:print(f"Deleted variables: {deleted_vars}")- # 3. Multiple garbage collection passes (important for circular references)+ # Multiple GC passes (important for circular references)for i in range(3):collected = gc.collect()if verbose and collected > 0:print(f"GC pass {i+1}: collected {collected} objects")- # 4. CUDA cleanup+ # CUDA cleanupif torch.cuda.is_available():- # Get memory before cleanupif verbose:mem_before = torch.cuda.memory_allocated() / 1024**3torch.cuda.empty_cache()torch.cuda.synchronize()- # Additional CUDA cleanup for persistent leaksif clear_all_caches:- # Reset memory statstorch.cuda.reset_peak_memory_stats()torch.cuda.reset_accumulated_memory_stats()@@ -82,10 +79,8 @@ def clear_memory(if hasattr(torch.jit, "_state") and hasattr(torch.jit._state, "_clear_class_state"):torch.jit._state._clear_class_state()- # Force another CUDA cache cleartorch.cuda.empty_cache()- # Final garbage collectiongc.collect()if verbose:@@ -96,7 +91,7 @@ def clear_memory(if mem_before > 0:print(f"Memory freed: {mem_before - mem_after:.2f} GB")- # restore original logging levels+ # Restore original logging levelslogging.getLogger().setLevel(root_level)for name, level in saved_log_levels.items():if name in logging.Logger.manager.loggerDict:@@ -108,7 +103,7 @@ def clear_all_lru_caches(verbose = True):"""Clear all LRU caches in loaded modules."""cleared_caches = []- # Modules to skip to avoid warnings+ # Skip these to avoid warningsskip_modules = {"torch.distributed","torchaudio",@@ -117,20 +112,18 @@ def clear_all_lru_caches(verbose = True):"torchaudio.backend",}- # Create a static list of modules to avoid RuntimeError+ # Static list to avoid RuntimeError during iterationmodules = list(sys.modules.items())- # Method 1: Clear caches in all loaded modules+ # Clear caches in all loaded modulesfor module_name, module in modules:if module is None:continue- # Skip problematic modulesif any(module_name.startswith(skip) for skip in skip_modules):continuetry:- # Look for functions with lru_cachefor attr_name in dir(module):try:# Suppress warnings when checking attributes@@ -144,11 +137,11 @@ def clear_all_lru_caches(verbose = True):attr.cache_clear()cleared_caches.append(f"{module_name}.{attr_name}")except Exception:- continue # Skip problematic attributes+ continueexcept Exception:- continue # Skip problematic modules+ continue- # Method 2: Clear specific known caches+ # Clear specific known cachesknown_caches = ["transformers.utils.hub.cached_file","transformers.tokenization_utils_base.get_tokenizer",@@ -169,7 +162,7 @@ def clear_all_lru_caches(verbose = True):obj.cache_clear()cleared_caches.append(cache_path)except Exception:- continue # Skip problematic caches+ continueif verbose and cleared_caches:print(f"Cleared {len(cleared_caches)} LRU caches")@@ -183,7 +176,6 @@ def clear_specific_lru_cache(func):return False-# Additional utility for monitoring cache sizesdef monitor_cache_sizes():"""Monitor LRU cache sizes across modules."""cache_info = []diff --git a/tests/utils/data_utils.py b/tests/utils/data_utils.pyindex 48d732b5f8c..aa36a2afb40 100644--- a/tests/utils/data_utils.py+++ b/tests/utils/data_utils.py@@ -57,29 +57,10 @@ def describe_param(as_str: bool = True,) -> dict:"""- Provide a statistical summary of a 2D weight matrix or tensor.- If as_str is True, the summary is returned as a formatted string.- Parameters:- param: torch.Tensor- include_l1 (bool): Whether to include the L1 norm (sum of absolute values).- include_l2 (bool): Whether to include the L2 norm (Frobenius norm).- include_infinity (bool): Whether to include the infinity norm (max absolute value).- as_str (bool): Whether to return the summary as a formatted string.-- Returns:- dict: A dictionary with the following statistics:- - shape: Dimensions of the matrix.- - mean: Average value.- - median: Median value.- - std: Standard deviation.- - min: Minimum value.- - max: Maximum value.- - percentile_25: 25th percentile.- - percentile_75: 75th percentile.- Additionally, if enabled:- - L1_norm: Sum of absolute values.- - L2_norm: Euclidean (Frobenius) norm.- - infinity_norm: Maximum absolute value.+ Statistical summary (shape, mean, std, min/max, percentiles) of a tensor.++ Optionally includes L1/L2/infinity norms. Returns a formatted string when+ as_str is True, else a dict."""param = param.float()@@ -105,16 +86,7 @@ def describe_param(def format_summary(stats: dict, precision: int = 6) -> str:- """- Format the statistical summary dictionary for printing.-- Parameters:- stats (dict): The dictionary returned by describe_param.- precision (int): Number of decimal places for floating point numbers.-- Returns:- str: A formatted string representing the summary.- """+ """Format the describe_param summary dict into a printable string."""lines = []for key, value in stats.items():if isinstance(value, float):diff --git a/tests/utils/generate_dataset_with_none.py b/tests/utils/generate_dataset_with_none.pyindex decda5d5a6c..64df3f86261 100644--- a/tests/utils/generate_dataset_with_none.py+++ b/tests/utils/generate_dataset_with_none.py@@ -1,28 +1,18 @@"""-generate_dataset_with_none.py+Generate a small synthetic dataset with intentional None/empty turns so+dataset_none_detect.py can be verified end-to-end.-Generates a small synthetic dataset that intentionally contains None/empty-turns so dataset_none_detect.py can be verified end-to-end.--Produces three formats:- - chatml (messages column, role/content turns)- - sharegpt (conversations column, from/value turns)- - alpaca (instruction/output columns)--Each format gets ~20 rows; roughly half have at least one bad turn.--No heavy dependencies -- just `datasets`.+Three formats: chatml (messages, role/content), sharegpt (conversations,+from/value), and alpaca (instruction/output). ~20 rows each; roughly half+have at least one bad turn. Only depends on `datasets`."""from datasets import Dataset-# ---------------------------------------------------------------------------# ChatML (messages, role/content)-# ----------------------------------------------------------------------------# NOTE: pyarrow requires uniform types in a column, so rows with messages=None-# or messages="not a list" (P1 cases) live in a SEPARATE dataset (see-# make_chatml_p1_dataset below) so pyarrow can infer the column type correctly.+# pyarrow requires uniform types in a column, so messages=None / non-list (P1)+# rows live in a SEPARATE dataset so pyarrow can infer the column type._CHATML_ROWS = [# clean rows@@ -133,10 +123,9 @@ _CHATML_ROWS = [{"messages": [None, {"role": "assistant", "content": "Reply"}]}, # None turn element]-# P1 test rows: messages is None or non-list.-# Stored as a plain list of dicts rather than an HF Dataset because pyarrow-# cannot mix list and non-list values in the same column. The test runner-# uses a lightweight mock to exercise find_none_chatml directly.+# P1 test rows: messages is None or non-list. Stored as plain dicts (not an+# HF Dataset) since pyarrow can't mix list and non-list values in one column;+# the test runner mocks find_none_chatml directly._CHATML_P1_ROWS = [{"messages": None}, # whole column None{"messages": "not a list"}, # wrong type@@ -148,9 +137,7 @@ def make_chatml_p1_rows() -> list:return list(_CHATML_P1_ROWS)-# ---------------------------------------------------------------------------# ShareGPT (conversations, from/value)-# ---------------------------------------------------------------------------_SHAREGPT_ROWS = [# clean@@ -207,9 +194,7 @@ _SHAREGPT_ROWS = [{"conversations": [None, {"from": "gpt", "value": "Hi"}]},]-# ---------------------------------------------------------------------------# Alpaca (instruction / output columns)-# ---------------------------------------------------------------------------_ALPACA_ROWS = [# cleandiff --git a/tests/utils/ocr_eval.py b/tests/utils/ocr_eval.pyindex 05c56982f8c..f02cd5a26a4 100644--- a/tests/utils/ocr_eval.py+++ b/tests/utils/ocr_eval.py@@ -40,21 +40,16 @@ class OCRModelEvaluator:"""Evaluate a model on an OCR dataset."""- # Create output directory if it doesn't existos.makedirs(output_dir, exist_ok = True)- # Initialize results storageresults = []- # Process each sample in the datasetfor i, sample in enumerate(tqdm(dataset, desc = "Evaluating OCR performance", disable = not verbose)):try:- # Extract components from samplemessages = sample["messages"]- # Get ground truth, image, and questionground_truth, image, question, input_messages = self._extract_sample_components(messages, i, verbose)@@ -62,16 +57,13 @@ class OCRModelEvaluator:if ground_truth is None or image is None or question is None:continue- # Generate model responsegenerated_response = self._generate_response(model, processor, input_messages, max_new_tokens, temperature, min_p)- # Calculate metricsword_error = wer(ground_truth, generated_response)char_error = cer(ground_truth, generated_response)- # Save individual resultself._save_individual_result(output_dir,i,@@ -82,7 +74,6 @@ class OCRModelEvaluator:char_error,)- # Store results for summaryresults.append({"sample_id": i,@@ -99,7 +90,6 @@ class OCRModelEvaluator:print(f"Error processing sample {i}: {str(e)}")traceback.print_exc()- # Generate summary reportreturn self._generate_summary_report(results, output_dir, verbose)def _extract_sample_components(@@ -107,24 +97,20 @@ class OCRModelEvaluator:) -> Tuple[Optional[str], Optional[Any], Optional[str], List[Dict]]:"""Extract ground truth, image, question, and input messages from sample."""- # Extract system message (if present)system_message = next((msg for msg in messages if msg["role"] == "system"), None)- # Extract user message with the image and questionuser_message = next((msg for msg in messages if msg["role"] == "user"), None)if not user_message:if verbose:print(f"Skipping sample {sample_idx}: No user message found")return None, None, None, []- # Extract assistant message with ground truthassistant_message = next((msg for msg in messages if msg["role"] == "assistant"), None)if not assistant_message:if verbose:print(f"Skipping sample {sample_idx}: No assistant message (ground truth) found")return None, None, None, []- # Extract ground truth textground_truth = Nonefor content_item in assistant_message["content"]:if content_item["type"] == "text":@@ -139,7 +125,6 @@ class OCRModelEvaluator:# Extract image and question from user messageimage = Nonequestion = None-for content_item in user_message["content"]:if content_item["type"] == "image":image = content_item["image"]@@ -156,7 +141,7 @@ class OCRModelEvaluator:print(f"Skipping sample {sample_idx}: No question found in user message")return None, None, None, []- # Construct messages for the model input (excluding assistant message)+ # Model input excludes the assistant messageinput_messages = []if system_message:input_messages.append(system_message)@@ -175,15 +160,12 @@ class OCRModelEvaluator:) -> str:"""Generate response from the model."""- # Preparation for inference using Qwen's specific processingtext = processor.apply_chat_template(input_messages, tokenize = False, add_generation_prompt = True)- # Process vision info (images/videos) from messagesimage_inputs, video_inputs = process_vision_info(input_messages)- # Create model inputsinputs = processor(text = [text],images = image_inputs,@@ -193,7 +175,6 @@ class OCRModelEvaluator:)inputs = inputs.to(model.device)- # Generate responsewith torch.no_grad():generated_ids = model.generate(**inputs,@@ -203,12 +184,11 @@ class OCRModelEvaluator:use_cache = True,)- # Extract only the generated part (not the input)+ # Keep only the generated part, not the inputgenerated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]- # Decode the generated textgenerated_response = processor.batch_decode(generated_ids_trimmed,skip_special_tokens = True,@@ -247,16 +227,13 @@ class OCRModelEvaluator:df = pd.DataFrame(results)- # Calculate overall averagesavg_wer = df["wer"].mean()avg_cer = df["cer"].mean()- # Save average metricswith open(os.path.join(output_dir, "avg_metrics.txt"), "w") as f:f.write(f"Average WER: {avg_wer:.4f}\n")f.write(f"Average CER: {avg_cer:.4f}\n")- # Save detailed resultsdf.to_csv(os.path.join(output_dir, "detailed_results.csv"), index = False)if verbose:@@ -283,7 +260,6 @@ class OCRModelEvaluator:print("\n==== MODEL COMPARISON REPORT ====")- # Create a comparison dataframecomparison_df = pd.DataFrame({"Model": list(self.model_comparison_results.keys()),@@ -292,20 +268,17 @@ class OCRModelEvaluator:})- # Sort by WER (best performance first)+ # Sort by WER (best first)comparison_df = comparison_df.sort_values("WER")- # Display the comparison tableprint("\nComparison Table (sorted by WER):")print(comparison_df.to_string(index = False))- # Save the comparison tableif save_csv:comparison_file = "model_comparison_results.csv"comparison_df.to_csv(comparison_file, index = False)print(f"\nComparison table saved to {comparison_file}")- # Generate a bar chart visualizationif save_plot:self._create_comparison_plot(comparison_df)@@ -353,9 +326,7 @@ def evaluate_ocr_model(output_dir = "ocr_evaluation_results",**kwargs,):- """- Convenience function that maintains backward compatibility with the original function.- """+ """Convenience wrapper kept for backward compatibility."""evaluator = OCRModelEvaluator()return evaluator.evaluate_model(model, processor, dataset, output_dir, **kwargs)diff --git a/tests/utils/os_utils.py b/tests/utils/os_utils.pyindex 7bf0821200b..2dcd9c732e0 100644--- a/tests/utils/os_utils.py+++ b/tests/utils/os_utils.py@@ -60,13 +60,12 @@ def check_package_installed(package_name, package_manager = None):def require_package(package_name, executable_name = None):"""Require a package to be installed, exit if not found"""- # First check if executable is in PATH (most reliable)+ # Executable in PATH is the most reliable signalif executable_name:if shutil.which(executable_name):print(f"✓ {executable_name} is available")return- # Then check with package managerpm = detect_package_manager()is_installed = check_package_installed(package_name, pm)@@ -74,7 +73,6 @@ def require_package(package_name, executable_name = None):print(f"✓ Package {package_name} is installed")return- # Package not found - show installation instructionsprint(f"❌ Error: {package_name} is not installed")print(f"\nPlease install {package_name} using your system package manager:")diff --git a/tests/utils/perplexity_eval.py b/tests/utils/perplexity_eval.pyindex bebc5ed99c3..83c632a0a75 100644--- a/tests/utils/perplexity_eval.py+++ b/tests/utils/perplexity_eval.py@@ -3,10 +3,9 @@ import torchimport pandas as pdmodel_comparison_results = {}-# return the perplexity of the model on the dataset-# The perplexity is computed on each example, individually, with a sliding window for examples longer than 512 tokens.+# Per-example perplexity, sliding window for examples longer than 512 tokens.def ppl_model(model, tokenizer, dataset):nlls = []max_length = 2048@@ -21,7 +20,6 @@ def ppl_model(model, tokenizer, dataset):input_ids = encodings.input_ids[:, begin_loc:end_loc].to("cuda")target_ids = input_ids.clone()target_ids[:, :-trg_len] = -100- # Create attention mask based on pad token idpad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0attention_mask = (input_ids != pad_token_id).long()with torch.no_grad():@@ -35,20 +33,14 @@ def ppl_model(model, tokenizer, dataset):return ppl-# --------------------------------------------------------------------+# ----------- Reporting helpers ----------- #-## ----------- Reporting helper function ----------- ##---# Create a simple function to add results to the comparisondef add_to_comparison(model_name, ppl):"""Add model results to the comparison tracker"""model_comparison_results[model_name] = {"ppl": ppl}- # return model_comparison_results-# Create a function to print the comparison report whenever neededdef print_model_comparison():"""Print a comparison of all models evaluated so far"""if not model_comparison_results:@@ -57,19 +49,16 @@ def print_model_comparison():print("\n==== MODEL COMPARISON REPORT ====")- # Create a comparison dataframecomparison_df = pd.DataFrame({"Model": list(model_comparison_results.keys()),- # "Perplexity": [results["ppl"] for results in model_comparison_results.values()],"Perplexity": [- # Convert tensors to CPU and then to float if needed+ # Tensors to CPU float if needed.results["ppl"].cpu().item() if torch.is_tensor(results["ppl"]) else results["ppl"]for results in model_comparison_results.values()],})- # Display the comparison tableprint("\nComparison Table:")print(comparison_df.to_string(index = False))diff --git a/tests/utils/run_none_detect_tests.py b/tests/utils/run_none_detect_tests.pyindex 979d3865c9d..2afea75bab1 100644--- a/tests/utils/run_none_detect_tests.py+++ b/tests/utils/run_none_detect_tests.py@@ -21,10 +21,8 @@ from datetime import datetimefrom io import StringIOfrom pathlib import Path-# Allow running from repo root without install.-# Insert the datasets directory directly so dataset_none_detect is imported-# as a top-level module, bypassing utils/datasets/__init__.py which pulls in-# torch, fastapi, and other heavy studio deps not needed for this utility.+# Import dataset_none_detect as a top-level module, bypassing+# utils/datasets/__init__.py which pulls in torch, fastapi, and other heavy deps.REPO_ROOT = Path(__file__).resolve().parent.parent.parentsys.path.insert(0, str(REPO_ROOT / "studio" / "backend" / "utils" / "datasets"))@@ -38,9 +36,7 @@ LOG_DIR = REPO_ROOT / "tests" / "logs"LOG_DIR.mkdir(parents = True, exist_ok = True)LOG_PATH = LOG_DIR / "none_detect_results.log"-# ---------------------------------------------------------------------------# Helpers-# ---------------------------------------------------------------------------class Tee:@@ -108,15 +104,10 @@ def assert_exact_recall(stats: dict, expected_bad: set, label: str):return all_caught-# ---------------------------------------------------------------------------# 1. Synthetic datasets-# -----------------------------------------------------------------------------# ---------------------------------------------------------------------------# Minimal mock so find_none_chatml can be called with hand-crafted rows that# pyarrow can't represent (e.g. messages=None, messages="not a list").-# ---------------------------------------------------------------------------class _MockDataset:@@ -468,9 +459,7 @@ def test_synthetic():return results-# ---------------------------------------------------------------------------# 2. HuggingFace: peteromallet/dataclaw-peteromallet-# ---------------------------------------------------------------------------def _brute_force_bad_rows(ds, fmt: str) -> set:@@ -576,9 +565,7 @@ def test_dataclaw():return None-# ---------------------------------------------------------------------------# 3. HuggingFace: peteromallet/my-personal-codex-data-# ---------------------------------------------------------------------------def test_codex_data():@@ -613,9 +600,7 @@ def test_codex_data():return None-# ---------------------------------------------------------------------------# Main-# ---------------------------------------------------------------------------def main():@@ -648,9 +633,7 @@ def main():all_results["dataclaw"] = test_dataclaw()all_results["codex_data"] = test_codex_data()- # ---------------------------------------------------------------------------# Summary table- # ---------------------------------------------------------------------------section("SUMMARY")rows = [("Dataset", "Format", "Total rows", "Bad rows", "Bad turns"),diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.pyindex 590419ad520..6fa6ae8d34b 100644--- a/tests/utils/test_packing.py+++ b/tests/utils/test_packing.py@@ -194,7 +194,7 @@ class _DummyTrainer:breakexcept TypeError:continue- # Ensure attributes exist even if the constructor did not accept them+ # Ensure attributes exist even if the constructor rejected them.if not hasattr(self.data_collator, "padding_free"):self.data_collator.padding_free = Trueif not hasattr(self.data_collator, "return_position_ids"):diff --git a/tests/utils/test_q_galore.py b/tests/utils/test_q_galore.pyindex 3a2925fca1d..7248e60a939 100644--- a/tests/utils/test_q_galore.py+++ b/tests/utils/test_q_galore.py@@ -104,7 +104,6 @@ class TestGaLoreProjector:low = proj.project(grad, step = 0)assert low.shape == (16, 4)- # The projection matrix should be stored as uint8assert proj.ortho_matrix.dtype == torch.uint8def test_quantized_projection_int4(self):@@ -165,7 +164,7 @@ class TestQuantizationUtils:q, scales, zeros, shape = _quantize(w, n_bit = 8)w_hat = _dequantize(q, scales, zeros, shape)- # Error should be bounded by the quantization step size+ # Error bounded by the quantization step size.error = (w - w_hat).abs().max()assert error < 0.1, f"Max error {error} exceeds threshold"@@ -215,7 +214,6 @@ class TestParamGroupHelper:def test_param_group_separation(self):"""GaLore vs non-GaLore params are correctly separated."""- # Create a mini-transformer-like modelmodel = nn.Module()model.q_proj = nn.Linear(64, 64, bias = False)model.k_proj = nn.Linear(64, 64, bias = False)@@ -224,15 +222,14 @@ class TestParamGroupHelper:groups = make_q_galore_param_groups(model, rank = 8, weight_quant = False)- # Should have 2 groups: galore and non-galore+ # galore + non-galore.assert len(groups) == 2galore_group = [g for g in groups if "rank" in g][0]non_galore_group = [g for g in groups if "rank" not in g][0]- # q_proj and k_proj should be in galore group (2 params)+ # q_proj + k_proj in galore group.assert len(galore_group["params"]) == 2- # embed and norm should be in non-galore groupassert len(non_galore_group["params"]) == 3 # embed weight + norm weight + norm biasdef test_custom_target_modules(self):diff --git a/tests/version_compat/_fetch.py b/tests/version_compat/_fetch.pyindex be968230163..9688780be53 100644--- a/tests/version_compat/_fetch.py+++ b/tests/version_compat/_fetch.py@@ -1,15 +1,11 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team."""Shared helpers for the version-compat suites: fetch a file from-GitHub raw at a specific tag/branch, and grep for class / def / module-symbols without ast.parse so a single non-importable line doesn't-false-fail us. Mirrors tests/vllm_compat/test_vllm_pinned_symbols.py.+GitHub raw at a tag/branch, and grep for class/def/module symbols+without ast.parse so one non-importable line doesn't false-fail us.+Mirrors tests/vllm_compat/test_vllm_pinned_symbols.py.-Used by:- - tests/version_compat/test_trl_grpo_pinned_symbols.py- - tests/version_compat/test_peft_pinned_symbols.py- - tests/version_compat/test_sentence_transformers_pinned_symbols.py- - tests/version_compat/test_bitsandbytes_pinned_symbols.py+Used by the test_*_pinned_symbols.py suites under tests/version_compat/."""from __future__ import annotations@@ -23,10 +19,8 @@ import pytestdef fetch_text(repo: str, ref: str, path: str) -> str | None:- """Fetch a file from GitHub raw. None on 404 (the path was renamed- or removed in this version, which is informational and the caller- decides whether that's fatal). Skips the test on transient network- errors so we don't make CI flaky."""+ """Fetch a file from GitHub raw. None on 404 (caller decides if+ fatal). Skips the test on transient network errors to avoid CI flake."""url = f"https://raw.githubusercontent.com/{repo}/{ref}/{path}"req = urllib.request.Request(url)token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")@@ -48,13 +42,9 @@ def has_def(name: str,kind: str = "any",) -> bool:- """Heuristic AST-equivalent grep for `class Name`, `def name`,- or `Name = ...` — at any indent level. We avoid a full ast.parse- so a single non-importable line (e.g. `# type: ignore` after an- unresolved alias) doesn't false-fail us. Indented matches are- accepted because most class methods we want to verify live four- spaces in (and tests should pass for `class.method` definitions- just as much as for module-level `def`)."""+ """Heuristic grep for `class Name`, `def name`, or `Name = ...` at+ any indent level. Avoids ast.parse so one non-importable line doesn't+ false-fail us; indented matches are accepted so class methods count too."""if kind in ("any", "class") and re.search(rf"^\s*class\s+{re.escape(name)}\b", src, re.MULTILINE):@@ -69,9 +59,8 @@ def has_def(def first_match(repo: str, ref: str, paths: list[str]) -> tuple[str, str] | None:- """Try a list of candidate paths; return (path, src) for the first- one that exists, or None if none do. Useful when upstream split or- moved a module across versions."""+ """Return (path, src) for the first existing candidate path, else+ None. Useful when upstream moved a module across versions."""for p in paths:src = fetch_text(repo, ref, p)if src is not None:diff --git a/tests/version_compat/test_bitsandbytes_pinned_symbols.py b/tests/version_compat/test_bitsandbytes_pinned_symbols.pyindex ec6e5fdaa12..247cc7e6b97 100644--- a/tests/version_compat/test_bitsandbytes_pinned_symbols.py+++ b/tests/version_compat/test_bitsandbytes_pinned_symbols.py@@ -36,11 +36,8 @@ BNB_TAGS = []-# --------------------------------------------------------------------------# bnb.functional: dequantize_4bit / quantize_4bit are the public 4-bit-# surface unsloth's compiled kernels and unsloth-zoo's vllm_utils-# bnb-loader patches all call into.-# -------------------------------------------------------------------------+# bnb.functional: dequantize_4bit / quantize_4bit are the public 4-bit surface+# unsloth's compiled kernels and unsloth-zoo's vllm_utils bnb-loader call into.@pytest.mark.parametrize("tag", BNB_TAGS)@@ -59,10 +56,8 @@ def test_bnb_functional_4bit(tag: str):)-# -------------------------------------------------------------------------# bnb.nn.Linear4bit / Params4bit: the two classes peft and unsloth# isinstance-check against. Renaming either silently breaks 4-bit LoRA.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", BNB_TAGS)@@ -89,16 +84,12 @@ def test_bnb_nn_linear4bit_classes(tag: str):)-# =========================================================================-# Coverage extension (added 2026-05): every bnb symbol unsloth +-# unsloth-zoo touch, derived from a full grep of both repos.-# =========================================================================+# Coverage extension (added 2026-05): every bnb symbol unsloth + unsloth-zoo+# touch, derived from a full grep of both repos.-# -------------------------------------------------------------------------# Top-level convenience export. unsloth/kernels/utils.py + unsloth-zoo# vllm_utils.py call `bnb.matmul_4bit(x, w, bias=, quant_state=)`.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", BNB_TAGS)diff --git a/tests/version_compat/test_peft_pinned_symbols.py b/tests/version_compat/test_peft_pinned_symbols.pyindex 10fc690d808..7e29aa62ac3 100644--- a/tests/version_compat/test_peft_pinned_symbols.py+++ b/tests/version_compat/test_peft_pinned_symbols.py@@ -45,11 +45,9 @@ PEFT_TAGS = []-# -------------------------------------------------------------------------# Top-level public re-exports. unsloth/models/sentence_transformer.py:1948# does `from peft import LoraConfig, get_peft_model as peft_get_peft_model`.# unsloth_zoo's saving_utils + lora extractors hit `peft.PeftModel`.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -69,12 +67,9 @@ def test_peft_top_level_exports(tag: str):)-# -------------------------------------------------------------------------# LoraConfig at the canonical sub-module path: peft.tuners.lora.LoraConfig-# (or peft.tuners.lora.config.LoraConfig). unsloth-zoo's LoraConfig-# normaliser inspects it via getattr() and dataclass field-# introspection.-# -------------------------------------------------------------------------+# (or peft.tuners.lora.config.LoraConfig). unsloth-zoo's normaliser inspects+# it via getattr() and dataclass field introspection.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -92,9 +87,7 @@ def test_peft_lora_config_class(tag: str):assert found_in, f"{tag}: peft.tuners.lora.LoraConfig not in any of {candidates}"-# -------------------------------------------------------------------------# get_peft_model: top-level helper used by sentence_transformer.py:2043.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -114,12 +107,8 @@ def test_get_peft_model_function(tag: str):pytest.fail(f"{tag}: def get_peft_model(...) not found in any of {candidates}")-# --------------------------------------------------------------------------# LoraLayer base class: unsloth-zoo's MoE LoRA extractor walks subclasses-# of peft.tuners.lora.LoraLayer to find quantised LoRA modules. If the-# class is renamed or moved, the walk silently returns 0 modules (the-# pytest tests mentioned in the audit report exercise exactly this).-# -------------------------------------------------------------------------+# LoraLayer base class: unsloth-zoo's MoE LoRA extractor walks subclasses of+# peft.tuners.lora.LoraLayer. A rename/move makes the walk silently return 0.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -140,12 +129,8 @@ def test_peft_lora_layer_class(tag: str):)-# --------------------------------------------------------------------------# bnb-aware LoRA: peft.tuners.lora.bnb is the integration point with-# bitsandbytes. unsloth + unsloth-zoo dispatch to this when the user-# loads a 4-bit base. Missing this module -> 4bit LoRA silently falls-# back to fp16 LoRA (silently bigger memory footprint).-# -------------------------------------------------------------------------+# bnb-aware LoRA: peft.tuners.lora.bnb is the bitsandbytes integration point.+# Missing it -> 4bit LoRA silently falls back to fp16 (bigger memory footprint).@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -177,16 +162,12 @@ def test_peft_lora_bnb_integration(tag: str):)-# =========================================================================# Coverage extension (added 2026-05): symbols from the 8-PR audit# unsloth#5015, #5167, #5036, #4807 + unsloth-zoo#618, #596, #482, #430.-# =========================================================================-# -------------------------------------------------------------------------# 1. peft.tuners.lora.layer.VARIANT_KWARG_KEYS — added in peft 0.18.# unsloth-zoo#430 injects the import into the compiled forward.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -201,12 +182,8 @@ def test_peft_variant_kwarg_keys_const(tag: str):)-# --------------------------------------------------------------------------# 2. peft.tuners.lora.layer.ParamWrapper — peft 0.18 added the class-# for MoE 3D-parameter LoRA. Required attrs: parameter_name, lora_A,-# forward, get_base_layer. peft 0.19 also added _did_swap_in_out_features.-# unsloth-zoo#618 monkey-patches the MoE LoRA extractor.-# -------------------------------------------------------------------------+# 2. peft.tuners.lora.layer.ParamWrapper — peft 0.18 added the class for MoE+# 3D-parameter LoRA. unsloth-zoo#618 monkey-patches the MoE LoRA extractor.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -219,17 +196,13 @@ def test_peft_param_wrapper_class(tag: str):f"unsloth_zoo/temporary_patches/qwen3_moe.py:43-130 + "f"moe_utils.py:757 ImportError (unsloth-zoo#618)")- # Required member names — informational only; the class may- # legitimately move some to a base class. The bug we want to- # catch is full-class-removal.+ # Member names: informational only; the real bug to catch is full removal.for name in ("parameter_name", "forward", "lora_A", "get_base_layer"):_present = name in src-# --------------------------------------------------------------------------# 3. peft.tuners.lora.LoraConfig.target_parameters — peft 0.19+. Used-# by unsloth-zoo's MoE target-parameter extractor.-# -------------------------------------------------------------------------+# 3. peft.tuners.lora.LoraConfig.target_parameters — peft 0.19+. Used by+# unsloth-zoo's MoE target-parameter extractor.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -237,8 +210,7 @@ def test_peft_lora_config_target_parameters(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/tuners/lora/config.py")if src is None:pytest.skip(f"{tag}: src/peft/tuners/lora/config.py missing")- # Optional on 0.18.x; required from 0.19.0+. Don't fail older- # versions; the test is informational below the floor.+ # Optional on 0.18.x, required from 0.19.0+has_it = "target_parameters" in srcif "0.18" in tag and not has_it:pytest.skip(f"{tag}: target_parameters not yet introduced (peft 0.18)")@@ -248,10 +220,8 @@ def test_peft_lora_config_target_parameters(tag: str):)-# -------------------------------------------------------------------------# 4. peft.tuners.lora.model.LoraModel._create_and_replace — unsloth#4807-# monkey-patches this for Gemma4ClippableLinear. Signature pin.-# -------------------------------------------------------------------------+# monkey-patches this for Gemma4ClippableLinear.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -266,12 +236,8 @@ def test_peft_lora_model_create_and_replace(tag: str):)-# --------------------------------------------------------------------------# 5. peft.utils.transformers_weight_conversion.{build_peft_weight_mapping,-# WeightConversion} — unsloth#5167 wraps build_peft_weight_mapping-# to handle WeightConversion.__init__ kwargs (distributed_operation,-# quantization_operation).-# -------------------------------------------------------------------------+# 5. peft.utils.transformers_weight_conversion.build_peft_weight_mapping —+# unsloth#5167 wraps it to handle WeightConversion.__init__ kwargs.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -292,10 +258,8 @@ def test_peft_transformers_weight_conversion_module(tag: str):)-# -------------------------------------------------------------------------# 6. peft.utils.integrations.dequantize_module_weight — used by 3 unsloth/-# unsloth-zoo callsites. Function name + module path.-# -------------------------------------------------------------------------+# unsloth-zoo callsites.@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -314,9 +278,7 @@ def test_peft_integrations_dequantize_module_weight(tag: str):)-# -------------------------------------------------------------------------# 7. peft.PeftType.LORA — used by unsloth-zoo vllm_utils.py:2520-2559.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -340,10 +302,8 @@ def test_peft_type_lora_enum(tag: str):)-# -------------------------------------------------------------------------# 8. peft.utils.ModulesToSaveWrapper — both peft.utils.* and# peft.utils.other.* import paths used.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)@@ -365,34 +325,27 @@ def test_peft_modules_to_save_wrapper(tag: str):)-# --------------------------------------------------------------------------# 9. peft.PeftModel.from_pretrained signature pin — unsloth#4807-# call site uses (model, name, token, revision, is_trainable,-# trust_remote_code).-# -------------------------------------------------------------------------+# 9. peft.PeftModel.from_pretrained signature pin — unsloth#4807.@pytest.mark.parametrize("tag", PEFT_TAGS)def test_peft_peft_model_from_pretrained_signature(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/peft_model.py")assert src is not None, f"{tag}: src/peft/peft_model.py missing"- # We expect `def from_pretrained` in PeftModel class. Just check- # the method name exists; full kwarg list is too brittle.+ # Just check the method name; the full kwarg list is too brittle.assert has_def(src, "from_pretrained", "func"), f"{tag}: PeftModel.from_pretrained missing in peft_model.py"-# -------------------------------------------------------------------------# 10. peft.__version__ exported via known mechanism.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", PEFT_TAGS)def test_peft_version_parseable(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/__init__.py")assert src is not None- # Same gates as the TRL test: literal / submodule / metadata / VERSION file.+ # Same gates as the TRL test: literal / submodule / metadatahas_literal = bool(re.search(r'^__version__\s*=\s*["\']', src, re.MULTILINE))has_subimport = bool(re.search(r"^from\s+\.version\s+import\s+__version__", src, re.MULTILINE))has_metadata = bool(diff --git a/tests/version_compat/test_sentence_transformers_pinned_symbols.py b/tests/version_compat/test_sentence_transformers_pinned_symbols.pyindex c0cb1a6d969..87b358724b4 100644--- a/tests/version_compat/test_sentence_transformers_pinned_symbols.py+++ b/tests/version_compat/test_sentence_transformers_pinned_symbols.py@@ -15,9 +15,8 @@ unsloth/models/sentence_transformer.py that:sentence_transformers.models.transformer.Transformer; lines1169-1171) — at least ONE must resolve.-Strategy: GitHub raw fetch + symbol grep (no pip install, runs CPU-only-on every PR + daily cron). Versioning policy: ST is unpinned in-unsloth/pyproject.toml; cover the most recent minors (5.x line) plus+Strategy: GitHub raw fetch + symbol grep (no pip install, CPU-only).+ST is unpinned in unsloth/pyproject.toml; cover recent 5.x minors plus`main`."""@@ -42,10 +41,8 @@ ST_TAGS = []-# -------------------------------------------------------------------------# Top-level public surface: SentenceTransformer + SentenceTransformerTrainer# must be importable as `from sentence_transformers import X`.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", ST_TAGS)@@ -60,22 +57,17 @@ def test_st_top_level_exports(tag: str):)-# -------------------------------------------------------------------------# Sub-modules: Transformer / Pooling / Normalize. unsloth walks# `sentence_transformers.models` to introspect these (line 1016, 1206).-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", ST_TAGS)def test_st_models_re_exports(tag: str):"""Transformer / Pooling / Normalize must be reachable through- `sentence_transformers.models`. ST 5.4 reorganised the package- (no more top-level `models/` dir; modules live under- `sentence_transformer/` and `base/modules/`), but the public- re-export at `sentence_transformers/__init__.py` still has to- surface these three so user code (and unsloth/models/sentence_transformer.py:1016,1206,1467)- can `from sentence_transformers.models import Transformer` (or- equivalently `from sentence_transformers import models`)."""+ `sentence_transformers.models`. ST 5.4 reorganised the package, but+ the top-level re-export must still surface these three so user code+ (and unsloth/models/sentence_transformer.py:1016,1206,1467) can+ `from sentence_transformers.models import Transformer`."""# Layout 1 (legacy < 5.4): sentence_transformers/models[.py|/__init__.py].# Layout 2 (>= 5.4): top-level __init__.py re-exports the symbols# plus the modules live under base/modules and sentence_transformer/.@@ -95,14 +87,10 @@ def test_st_models_re_exports(tag: str):)return- # ST 5.4+ modular layout: classes moved under- # - sentence_transformers/base/modules/transformer.py (Transformer)- # - sentence_transformers/sentence_transformer/modules/pooling.py (Pooling)- # - sentence_transformers/sentence_transformer/modules/normalize.py (Normalize)- # Backward compatibility for `from sentence_transformers.models- # import X` is set up at import time via- # `sentence_transformers.util.deprecated_import.setup_deprecated_module_imports`- # called from sentence_transformers/__init__.py.+ # ST 5.4+ modular layout: classes moved under base/modules and+ # sentence_transformer/modules. Backward compat for+ # `from sentence_transformers.models import X` is wired at import via+ # setup_deprecated_module_imports in sentence_transformers/__init__.py.expected_paths = {"Transformer": ["sentence_transformers/base/modules/transformer.py",@@ -142,10 +130,8 @@ def test_st_models_re_exports(tag: str):)-# -------------------------------------------------------------------------# Transformer base class: unsloth checks two alternate paths at# sentence_transformer.py:1169-1171. At least ONE must resolve.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", ST_TAGS)@@ -167,20 +153,16 @@ def test_st_transformer_base_class_either_path(tag: str):)-# -------------------------------------------------------------------------# sentence_transformers.util: import_from_string + load_dir_path are the# two helpers unsloth.models.sentence_transformer:1177,1205 calls.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", ST_TAGS)def test_st_util_helpers(tag: str):"""`sentence_transformers.util.{import_from_string, load_dir_path}` —used by unsloth.models.sentence_transformer:1177,1205. ST 5.4+ moved- util into a package; we accept either layout. We also accept the- function being defined in any submodule of the util package, since- `from sentence_transformers.util import import_from_string` works- when util/__init__.py re-exports."""+ util into a package; accept either layout, or a re-export from any+ util submodule."""candidates = ["sentence_transformers/util.py","sentence_transformers/util/__init__.py",diff --git a/tests/version_compat/test_trl_grpo_pinned_symbols.py b/tests/version_compat/test_trl_grpo_pinned_symbols.pyindex ce5e2644fda..f84a4fd6699 100644--- a/tests/version_compat/test_trl_grpo_pinned_symbols.py+++ b/tests/version_compat/test_trl_grpo_pinned_symbols.py@@ -88,10 +88,8 @@ TRL_TAGS = []-# -------------------------------------------------------------------------# HARD-import top-level: from trl import X must keep working for these.# unsloth/trainer.py + unsloth/models/rl.py rebind these by name.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -107,11 +105,9 @@ def test_trl_top_level_grpo_sft(tag: str):)-# -------------------------------------------------------------------------# trl.trainer.grpo_trainer.GRPOTrainer -- the canonical class. unsloth's# RL patcher discovers it via `eval(f"trl.trainer.{trainer_file}.{name}")`# in unsloth/models/rl.py:548-594.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -141,11 +137,9 @@ def test_grpo_config_class_canonical_path(tag: str):)-# -------------------------------------------------------------------------# DataCollatorForPreference: unsloth.models.rl_replacements:318 hard-imports# from trl.trainer.dpo_trainer. Some old TRL versions had it in# trl.trainer.utils; modern ones moved to trl.trainer.dpo_trainer.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -168,10 +162,8 @@ def test_data_collator_for_preference_resolvable(tag: str):)-# -------------------------------------------------------------------------# trl.trainer.utils.pad: emitted into the GRPO compile cell as# _unsloth_trl_pad (rl_replacements.py:326).-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -189,11 +181,9 @@ def test_trl_trainer_utils_pad(tag: str):)-# -------------------------------------------------------------------------# trl.models.unwrap_model_for_generation -- moved between submodules# across releases. unsloth/models/rl.py:152-155 handles both paths.# Assert at least one resolves on every tag.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -219,11 +209,9 @@ def test_unwrap_model_for_generation_either_path(tag: str):)-# -------------------------------------------------------------------------# trl.experimental.openenv: gated import (rl_replacements.py:1765-1770# wraps in try/except). When present, must export the symbols unsloth# patches.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -241,11 +229,9 @@ def test_trl_experimental_openenv_gated(tag: str):)-# -------------------------------------------------------------------------# trl.generation.vllm_generation: gated import for the fast_inference# server mode (rl_replacements.py:1846-1848). When present, must define# at least one symbol unsloth patches against.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -270,11 +256,9 @@ def test_trl_generation_vllm_generation_gated(tag: str):)-# -------------------------------------------------------------------------# Sanity: TRL's __version__ string is parseable. unsloth/models/rl.py:63# does `from trl import __version__ as trl_version_raw` and string-# matches on it.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -307,15 +291,11 @@ def test_trl_version_parseable(tag: str):)-# =========================================================================# Coverage extension (added 2026-05): symbols / source-string contracts# unsloth + unsloth-zoo touch but the original suite missed.-# =========================================================================-# -------------------------------------------------------------------------# 1. trl.is_conversational — soft import in unsloth-zoo dataset_utils.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -328,10 +308,8 @@ def test_trl_is_conversational_export(tag: str):pytest.skip(f"{tag}: trl.is_conversational not exported (legacy TRL)")-# -------------------------------------------------------------------------# 2-4. trl.trainer.sft_trainer module surface used by unsloth tokenizer# utils + tests.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -351,10 +329,8 @@ def test_trl_sft_trainer_module_internals(tag: str):pass-# -------------------------------------------------------------------------# 5-6. trl.trainer.dpo_trainer module + MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES# — patched by unsloth-zoo/temporary_patches/misc.py:1376-1379.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -367,11 +343,9 @@ def test_trl_dpo_trainer_module_exists(tag: str):assert has_def(src, "DPOTrainer", "class"), f"{tag}: class DPOTrainer missing in dpo_trainer.py"-# -------------------------------------------------------------------------# 7. trl.trainer.utils.ConstantLengthDataset — soft import in# unsloth-zoo/dataset_utils.py:596. Optional (TRL 0.20.0 removed it# on some paths).-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -390,12 +364,10 @@ def test_trl_constant_length_dataset_optional(tag: str):)-# -------------------------------------------------------------------------# 8. trl.models.utils.disable_gradient_checkpointing — added in TRL# 1.0.0+. unsloth/models/rl.py:1976-1994 uses hasattr() for gating;# we still want the assertion that the symbol exists from 1.0.0# onwards so a future removal gets caught.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -423,11 +395,9 @@ def test_trl_models_utils_disable_gradient_checkpointing(tag: str):)-# -------------------------------------------------------------------------# 9. trl.import_utils + the `_*_available` cache pattern — used by# unsloth/import_fixes.py:508-516 to clear cached `is_X_available`# booleans so vllm-ascend imports work.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -450,11 +420,9 @@ def test_trl_import_utils_available_pattern(tag: str):)-# -------------------------------------------------------------------------# 10. trl.experimental.openenv.utils generators — at least one of the# two function names must exist (unsloth/models/rl_replacements.py# :1775-1781 calls getattr() to find one).-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -471,12 +439,10 @@ def test_trl_openenv_utils_generators(tag: str):)-# -------------------------------------------------------------------------# 11-16. GRPOTrainer required method names. unsloth/models/rl_replacements# .py uses function_name == "..." dispatch keys; if a method is# renamed, the patch silently doesn't apply. List of methods is# the precise dispatch key set.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -508,7 +474,6 @@ def test_trl_grpo_trainer_required_methods(tag: str):_ = _present-# -------------------------------------------------------------------------# Source-string contracts on trl/trainer/grpo_trainer.py. Each substring# is one half of a `function.replace(old, new)` rewrite — if the# substring no longer appears in TRL source, the rewrite is a no-op@@ -516,7 +481,6 @@ def test_trl_grpo_trainer_required_methods(tag: str):## Broken into per-version-window tests because some patterns only apply# to a subset of TRL minors.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -535,10 +499,8 @@ def test_trl_grpo_source_inference_mode_unwrap(tag: str):)-# -------------------------------------------------------------------------# 17. KTOTrainer.get_batch_logps + the literal raise message rewriter# hits.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -586,12 +548,10 @@ def test_trl_kto_get_batch_logps_signature(tag: str):)-# -------------------------------------------------------------------------# 18. SFTTrainer.__init__ literal `dict_args.pop("push_to_hub_token")`# OR our shim must short-circuit. transformers 5.0 removed this# kwarg; if TRL stops emitting the bare pop, our patch becomes# a no-op AND TRL itself crashes on transformers 5.0.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -606,9 +566,7 @@ def test_trl_sft_trainer_class(tag: str):assert has_def(src, "SFTTrainer", "class"), f"{tag}: class SFTTrainer missing"-# -------------------------------------------------------------------------# 19-21. DPOTrainer methods unsloth-zoo's rl_replacements rewrites.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)@@ -641,14 +599,12 @@ def test_trl_dpo_trainer_methods(tag: str):_ = _present # informational; rewriter no-ops cleanly when absent-# -------------------------------------------------------------------------# 22-23. trl.trainer.grpo_trainer must IMPORT or DEFINE the helpers# unsloth's source rewriters reference: profiling_context,# maybe_apply_chat_template, truncate_with_protected_tokens.# Either the symbol is locally defined OR imported from elsewhere# in trl.* — the rewriter only needs the NAME to be in scope at# the call site.-# -------------------------------------------------------------------------@pytest.mark.parametrize("tag", TRL_TAGS)diff --git a/tests/vllm_compat/test_extended_module_imports.py b/tests/vllm_compat/test_extended_module_imports.pyindex cbf6a7e3019..d6d32638275 100644--- a/tests/vllm_compat/test_extended_module_imports.py+++ b/tests/vllm_compat/test_extended_module_imports.py@@ -97,10 +97,8 @@ def _has_unsloth() -> bool:return importlib.util.find_spec("unsloth") is not None-# -------------------------------------------------------------------------# Extended unsloth-zoo module list. Modules with no top-level vllm/CUDA# import are expected to load cleanly on a CPU spoof runner.-# -------------------------------------------------------------------------_ZOO_VLLM_FREE_MODULES = [@@ -130,11 +128,9 @@ _ZOO_VLLM_FREE_MODULES = [@pytest.mark.skipif(not _has_unsloth_zoo(), reason = "unsloth_zoo not installed")@pytest.mark.parametrize("modname", _ZOO_VLLM_FREE_MODULES)def test_unsloth_zoo_module_imports_under_spoof(modname: str):- """Each unsloth_zoo module must import cleanly on a CPU-only spoof- runner. Catches transformers/peft/bnb symbol drift that pins fail- at import time (vs runtime)."""- # Force fresh resolution: drops stale partial-import state from- # a previous module's failure.+ """Each unsloth_zoo module must import cleanly on a CPU-only spoof runner.+ Catches transformers/peft/bnb symbol drift that fails at import time."""+ # Force fresh resolution: drop stale partial-import state from a prior failuresys.modules.pop(modname, None)try:importlib.import_module(modname)@@ -144,10 +140,8 @@ def test_unsloth_zoo_module_imports_under_spoof(modname: str):)-# -------------------------------------------------------------------------# Spoof correctness: _IS_MLX must remain False on a non-Mac runner-# AND _IS_CUDA / DEVICE_TYPE must reflect the spoofed CUDA layer.-# -------------------------------------------------------------------------+# and _IS_CUDA / DEVICE_TYPE must reflect the spoofed CUDA layer.@pytest.mark.skipif(not _has_unsloth(), reason = "unsloth not installed")@@ -163,11 +157,8 @@ def test_unsloth_is_mlx_false_under_spoof():)-# --------------------------------------------------------------------------# unsloth.models.* — the core RL + sentence-transformer surfaces. These-# are the entry points unsloth/__init__.py loads transitively when a-# user does `from unsloth import FastLanguageModel`.-# -------------------------------------------------------------------------+# unsloth.models.* — core RL + sentence-transformer surfaces, loaded+# transitively by `from unsloth import FastLanguageModel`._UNSLOTH_CORE_MODULES = [@@ -184,14 +175,11 @@ _UNSLOTH_CORE_MODULES = [@pytest.mark.skipif(not _has_unsloth(), reason = "unsloth not installed")@pytest.mark.parametrize("modname", _UNSLOTH_CORE_MODULES)def test_unsloth_core_module_imports_under_spoof(modname: str):- """Core unsloth modules must import on a CPU-only runner under- the CUDA spoof. Drift in transformers/peft/trl symbols pinned at- module-top crashes here BEFORE any user-visible call.-- Bootstraps via `import unsloth` first, since most sub-modules- require the package's _gpu_init side effects. Without that, every- `import unsloth.models.*` raises a guard `Please restructure your- imports with 'import unsloth' at the top of your file.`"""+ """Core unsloth modules must import on a CPU-only runner under the CUDA+ spoof; module-top symbol drift crashes here before any user-visible call.++ Bootstraps via `import unsloth` first, since most sub-modules need the+ package's _gpu_init side effects (else an import-guard fires)."""try:import unsloth # noqa: F401 -- triggers _gpu_init side effectsexcept Exception as e:@@ -210,11 +198,8 @@ def test_unsloth_core_module_imports_under_spoof(modname: str):)-# --------------------------------------------------------------------------# Public API surface dump for FastLanguageModel / FastVisionModel /-# FastModel under spoof. Asserts the surface is non-empty and that-# the patch hooks unsloth-zoo's RL surface relies on are present.-# -------------------------------------------------------------------------+# Public API surface for FastLanguageModel / FastVisionModel / FastModel under+# spoof: surface must be non-empty and the notebook-relied methods present.@pytest.mark.skipif(not _has_unsloth(), reason = "unsloth not installed")@@ -229,9 +214,7 @@ def test_fast_model_class_surface_under_spoof():continuefound_at_least_one = Truepublic = sorted(n for n in dir(cls) if not n.startswith("_"))- # Notebooks rely on these methods. Loss of any one is a regression- # the existing api-introspect notebook job would catch a step- # later — but here at the import / spoof layer.+ # Notebooks rely on these methods; loss of any one is a regressionfor method in ("from_pretrained", "get_peft_model"):assert method in public, (f"unsloth.{cls_name}.{method} missing under spoof; "@@ -243,12 +226,9 @@ def test_fast_model_class_surface_under_spoof():)-# --------------------------------------------------------------------------# RL surface drill-down: GRPO, SFT, DPO classes must be reachable AND-# the source-rewriter dispatch table must be populated. Catches the-# scenario where unsloth.models.rl_replacements imports cleanly but-# RL_FUNCTIONS or RL_REPLACEMENTS is silently empty.-# -------------------------------------------------------------------------+# RL surface drill-down: GRPO/SFT/DPO classes must be reachable and the+# source-rewriter dispatch table populated. Catches rl_replacements importing+# cleanly while RL_FUNCTIONS / RL_REPLACEMENTS is silently empty.@pytest.mark.skipif(not _has_unsloth(), reason = "unsloth not installed")@@ -277,11 +257,8 @@ def test_unsloth_rl_replacements_dispatch_populated():), f"RL_FUNCTIONS[{key!r}] is empty list; rewrites no-op"-# --------------------------------------------------------------------------# unsloth-zoo compiler test_apply_fused_lm_head — exercises the actual-# fused-LM-head emit path with a tiny fixture. Already covered as a-# named test in compiler.py:1983; we just call it.-# -------------------------------------------------------------------------+# unsloth-zoo compiler test_apply_fused_lm_head — the fused-LM-head emit path+# (named test in compiler.py:1983); we just confirm it's callable.@pytest.mark.skipif(not _has_unsloth_zoo(), reason = "unsloth_zoo not installed")@@ -295,11 +272,8 @@ def test_zoo_compiler_apply_fused_lm_head_callable():)-# --------------------------------------------------------------------------# Spot-check signature stability of FastModel.from_pretrained — every-# notebook call site relies on these kwargs. A removed kwarg silently-# becomes positional drift.-# -------------------------------------------------------------------------+# Spot-check signature stability of FastModel.from_pretrained — every notebook+# call site relies on these kwargs; a removal becomes silent positional drift.@pytest.mark.skipif(not _has_unsloth(), reason = "unsloth not installed")diff --git a/tests/vllm_compat/test_unsloth_zoo_imports.py b/tests/vllm_compat/test_unsloth_zoo_imports.pyindex cc93bb904dc..3f1f5a287db 100644--- a/tests/vllm_compat/test_unsloth_zoo_imports.py+++ b/tests/vllm_compat/test_unsloth_zoo_imports.py@@ -1,32 +1,23 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team."""-CPU-only smoke imports for the unsloth_zoo modules that interact with-vLLM and GRPO + fast_inference=True. Asserts each module imports-cleanly under the existing tests/_zoo_aggressive_cuda_spoof harness.--Two modules in scope are vllm-free by design (verified by the-upstream survey: rl_replacements has zero `import vllm` lines;-empty_model operates on already-built vllm_internals objects passed-in). Those two MUST import on CPU with no vllm installed -- this-file proves it.--The remaining three modules (vllm_utils, vllm_lora_request,-vllm_lora_worker_manager) hard-import multiple vllm submodules at-module top. We do not attempt to import them on a runner without-vllm; the symbol-presence test in test_vllm_pinned_symbols.py-covers that path against pinned vLLM source.--Cross-references:-- unsloth_zoo PRs that fixed bugs surfaced here:+CPU-only smoke imports for the unsloth_zoo modules touching vLLM and+GRPO + fast_inference=True, under the tests/_zoo_aggressive_cuda_spoof+harness.++rl_replacements and empty_model are vllm-free by design and MUST import+on CPU with no vllm installed -- this file proves it. The other three+(vllm_utils, vllm_lora_request, vllm_lora_worker_manager) hard-import+vllm and are skipped without it; test_vllm_pinned_symbols.py covers them+statically against pinned vLLM source.++Cross-references (unsloth_zoo commits that fixed bugs surfaced here):e3072a23 (WorkerLoRAManager.supports_tower_connector_lora missing),0c95753a (_call_create_lora_manager TypeError on vLLM 0.9.x),2a80d543 (vLLM 0.15 LoRA manager compat),ec186187 (vLLM PR #30253 vllm.lora.models split),- e915bca1 (LoRA embeddings= arg removed; lora_extra_vocab_size- optional),- fa82dcc2 / 664e52ea (UNSLOTH_VLLM_STANDBY hard-error windows on- vLLM 0.10.x and 0.14.x).+ e915bca1 (LoRA embeddings= arg removed; lora_extra_vocab_size optional),+ fa82dcc2 / 664e52ea (UNSLOTH_VLLM_STANDBY hard-error on vLLM 0.10/0.14)."""from __future__ import annotations@@ -40,9 +31,9 @@ from pathlib import Pathimport pytest-# Apply the consolidated CPU spoof at module import time, mirroring how+# Apply the consolidated CPU spoof at import time, like# .github/workflows/consolidated-tests-ci.yml shims unsloth before any-# unsloth-touching import (lines 309/417/536/626/826/1081/1586/1998).+# unsloth-touching import._SPOOF_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(_SPOOF_DIR))import _zoo_aggressive_cuda_spoof as _spoof # noqa: E402@@ -50,9 +41,8 @@ import _zoo_aggressive_cuda_spoof as _spoof # noqa: E402_spoof.apply()-# Some unsloth_zoo modules read pynvml at import for memory probes.-# pynvml may not be installed on the runner; stub it here. Same for-# triton (vLLM transitively expects it for kernel JIT).+# Some unsloth_zoo modules read pynvml at import for memory probes; it may+# not be installed on the runner, so stub it.def _stub_module(name: str, attrs: dict | None = None) -> None:if name in sys.modules:return@@ -103,30 +93,24 @@ def _has_vllm() -> bool:return importlib.util.find_spec("vllm") is not None-# -------------------------------------------------------------------------# rl_replacements: zero direct vllm imports; must import on a vllm-less-# CPU runner. This is the GRPO + fast_inference user-facing surface.-# -------------------------------------------------------------------------+# CPU runner. The GRPO + fast_inference user-facing surface.@pytest.mark.skipif(not _has_unsloth_zoo(), reason = "unsloth_zoo not installed")def test_rl_replacements_imports_without_vllm():- """unsloth_zoo.rl_replacements must NOT pull in vllm at import time.- The user-facing GRPOConfig / GRPOTrainer surface depends only on the- use_vllm / vllm_importance_sampling_* keyword flags, which are- re-exported as plain Python and never touch the vllm package on a- fast_inference=False training run."""+ """unsloth_zoo.rl_replacements must NOT pull in vllm at import time;+ the GRPOConfig/GRPOTrainer surface relies only on plain-Python keyword+ flags and never touches vllm on a fast_inference=False run."""sys.modules.pop("unsloth_zoo.rl_replacements", None)rl = importlib.import_module("unsloth_zoo.rl_replacements")- # If vllm WAS imported as a side-effect, the rl path on Colab without- # vllm installed crashes at GRPOTrainer construction. Refuse a- # transitive import.+ # A transitive vllm import crashes GRPOTrainer construction on Colab.assert "vllm" not in sys.modules, ("unsloth_zoo.rl_replacements imported vllm transitively; this breaks ""GRPO on environments without vllm installed (the use_vllm=False path ""is supposed to work without vllm).")- # Spot-check a known public surface:+ # Spot-check a known public surfaceassert (hasattr(rl, "RL_REPLACEMENTS")or hasattr(rl, "RL_FUNCTIONS")@@ -134,11 +118,8 @@ def test_rl_replacements_imports_without_vllm():), "expected at least one GRPO-related export in rl_replacements"-# -------------------------------------------------------------------------# empty_model: no vllm import either; pure builder for the-# fast_inference=True path that creates an empty TRL/PEFT model and-# fills it from a vLLM internals dict passed in by patch_vllm.-# -------------------------------------------------------------------------+# fast_inference=True path, filled from a vLLM internals dict by patch_vllm.@pytest.mark.skipif(not _has_unsloth_zoo(), reason = "unsloth_zoo not installed")@@ -148,7 +129,7 @@ def test_empty_model_imports_without_vllm():assert ("vllm" not in sys.modules), "unsloth_zoo.empty_model imported vllm transitively; expected to be vllm-free"- # Public function the GRPO + fast_inference path relies on:+ # Public function the GRPO + fast_inference path relies onassert (hasattr(em, "create_empty_causal_lm")or hasattr(em, "create_empty_model")@@ -156,11 +137,9 @@ def test_empty_model_imports_without_vllm():), "expected a create_empty_* helper in empty_model"-# -------------------------------------------------------------------------# vllm_lora_request / vllm_lora_worker_manager / vllm_utils: hard-import-# vllm. Skip if vllm isn't on the runner. The pinned-symbols test below-# covers the version compatibility statically without needing pip install.-# -------------------------------------------------------------------------+# vllm; skip if it isn't on the runner. The pinned-symbols test covers+# version compatibility statically.@pytest.mark.skipif(@@ -177,9 +156,8 @@ def test_vllm_lora_request_imports():def test_vllm_lora_worker_manager_imports():sys.modules.pop("unsloth_zoo.vllm_lora_worker_manager", None)mod = importlib.import_module("unsloth_zoo.vllm_lora_worker_manager")- # commit e3072a23 added supports_tower_connector_lora to handle- # vLLM 0.14's gpu_model_runner that calls it unconditionally on- # any LoRA-VLM. Assert the patched class exposes it.+ # e3072a23 added supports_tower_connector_lora for vLLM 0.14's+ # gpu_model_runner; assert the patched class exposes it.cls = getattr(mod, "WorkerLoRAManager", None)if cls is not None:assert (diff --git a/unsloth-cli.py b/unsloth-cli.pyindex 4ebc36164f8..f0b386286f3 100644--- a/unsloth-cli.py+++ b/unsloth-cli.py@@ -3,18 +3,10 @@"""🦥 Starter Script for Fine-Tuning FastLanguageModel with Unsloth-This script is designed as a starting point for fine-tuning your models using unsloth.-It includes configurable options for model loading, PEFT parameters, training arguments,-and model saving/pushing functionalities.+Configurable options for model loading, PEFT, training, and saving/pushing.+Customize the dataset loading/preprocessing and the save/push config for your case.-You will likely want to customize this script to suit your specific use case-and requirements.--Here are a few suggestions for customization:- - Modify the dataset loading and preprocessing steps to match your data.- - Customize the model saving and pushing configurations.--Usage: (most of the options have valid default values this is an extended example for demonstration purposes)+Usage (most options have sensible defaults; this is an extended example):python unsloth-cli.py --model_name "unsloth/llama-3-8b" --max_seq_length 8192 --dtype None --load_in_4bit \--r 64 --lora_alpha 32 --lora_dropout 0.1 --bias "none" --use_gradient_checkpointing "unsloth" \--random_state 3407 --use_rslora --per_device_train_batch_size 4 --gradient_accumulation_steps 8 \@@ -23,10 +15,7 @@ Usage: (most of the options have valid default values this is an extended exampl--report_to "tensorboard" --save_model --save_path "model" --quantization_method "f16" \--push_model --hub_path "hf/model" --hub_token "your_hf_token"-To see a full list of configurable options, use:- python unsloth-cli.py --help--Happy fine-tuning!+Run `python unsloth-cli.py --help` for the full list of options."""import argparse@@ -103,7 +92,6 @@ def run(args):def load_dataset_smart(args):from transformers.utils import strtoboolif args.raw_text_file:- # Use raw text loaderloader = RawTextDataLoader(tokenizer, args.chunk_size, args.stride)dataset = loader.load_from_file(args.raw_text_file)elif args.dataset.endswith((".txt", ".md", ".json", ".jsonl")):@@ -111,16 +99,14 @@ def run(args):loader = RawTextDataLoader(tokenizer)dataset = loader.load_from_file(args.dataset)else:- # Check for modelscope usageuse_modelscope = strtobool(os.environ.get("UNSLOTH_USE_MODELSCOPE", "False"))if use_modelscope:from modelscope import MsDatasetdataset = MsDataset.load(args.dataset, split = "train")else:- # Existing HuggingFace dataset logicdataset = load_dataset(args.dataset, split = "train")- # Apply formatting for structured datasets+ # Format structured datasetsdataset = dataset.map(formatting_prompts_func, batched = True)return dataset@@ -163,7 +149,7 @@ def run(args):# Save modelif args.save_model:- # if args.quantization_method is a list, we will save the model for each quantization method+ # If args.quantization is a list, save once per quantization methodif args.save_gguf:if isinstance(args.quantization, list):for quantization_method in args.quantization:diff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex b723611c5ab..8202195ca8b 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -17,14 +17,10 @@ import os, importlib.util, platformos.environ["UNSLOTH_IS_PRESENT"] = "1"# ── Windows console UTF-8 safety ─────────────────────────────────────────────-# Legacy Windows consoles use a non-UTF-8 code page (e.g. cp1252) that cannot-# encode the emoji / box-drawing glyphs Unsloth prints, so a bare-# print("\U0001f9a5 ...") raises UnicodeEncodeError and aborts (observed at-# SFTTrainer init, unsloth/trainer.py). Reconfigure stdout/stderr to UTF-8 ONLY-# on Windows and ONLY when they are not already UTF-8 -- this is a no-op when-# PYTHONUTF8 / PYTHONIOENCODING is set (Unsloth Studio worker, modern terminals)-# and is never touched on Linux/macOS, so it cannot change their behaviour.-# errors="replace" guarantees we can never crash on an unencodable glyph.+# Legacy Windows consoles (cp1252) can't encode Unsloth's emoji/box-drawing+# glyphs and crash with UnicodeEncodeError. Force stdout/stderr to UTF-8 only on+# Windows and only when not already UTF-8; no-op elsewhere. errors="replace"+# guarantees we never crash on an unencodable glyph.if platform.system() == "Windows":import sys as _sysfor _name in ("stdout", "stderr"):@@ -38,11 +34,9 @@ if platform.system() == "Windows":def _is_mlx_available():- # Transitional import barrier: while the paired unsloth-zoo MLX runtime- # rollout is in flight, keep non-Apple-Silicon imports from touching- # unsloth_zoo here. After both PRs are released together and- # unsloth_zoo.mlx is guaranteed to be import-safe on GPU hosts,- # this helper can collapse back to the centralized zoo runtime call below.+ # Transitional import barrier: keep non-Apple-Silicon imports from touching+ # unsloth_zoo until unsloth_zoo.mlx is import-safe on GPU hosts. Then this+ # can collapse back to the centralized zoo runtime call below.if (os.environ.get("UNSLOTH_FORCE_GPU_PATH", "0") == "1"or platform.system() != "Darwin"@@ -68,11 +62,9 @@ if _IS_MLX:"Unsloth: MLX support requires `unsloth-zoo` with MLX modules. ""Reinstall with `pip install unsloth-zoo` or rerun install.sh.") from _e- # The mlx.trainer / mlx.loader submodules ship with unsloth-zoo's MLX- # support. An older installed unsloth-zoo (e.g. from PyPI before the- # MLX release lands) will satisfy `import unsloth_zoo` but be missing- # these submodules. Surface the same friendly install hint instead of- # a raw ImportError on the submodule path.+ # An older unsloth-zoo satisfies `import unsloth_zoo` but lacks the+ # mlx.trainer / mlx.loader submodules. Surface a friendly install hint+ # instead of a raw ImportError on the submodule path.try:from unsloth_zoo.mlx.trainer import MLXTrainer, MLXTrainingConfigfrom unsloth_zoo.mlx.loader import FastMLXModeldiff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex 3a84b8b012f..172c69c5d85 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -17,10 +17,9 @@ from packaging.version import Versionimport os, re, subprocess, inspect, functoolsimport numpy as np-# Log Unsloth is being usedos.environ["UNSLOTH_IS_PRESENT"] = "1"-# Check if modules that need patching are already imported+# Modules that need patching but may already be importedcritical_modules = ["trl", "transformers", "peft"]already_imported = [mod for mod in critical_modules if mod in sys.modules]@@ -54,13 +53,10 @@ del torchvision_compatibility_checkdel fix_diffusers_warningsdel fix_huggingface_hub-# This check is critical because Unsloth optimizes these libraries by modifying-# their code at import time. If they're imported first, the original (slower,-# more memory-intensive) implementations will be used instead of Unsloth's-# optimized versions, potentially causing OOM errors or slower training.+# Unsloth patches these libraries at import time; if imported first, the+# unoptimized versions run, risking OOM or slower training.if already_imported:- # stacklevel=2 makes warning point to user's import line rather than this library code,- # showing them exactly where to fix the import order in their script+ # stacklevel=2 points the warning at the user's import linewarnings.warn(f"WARNING: Unsloth should be imported before [{', '.join(already_imported)}] "f"to ensure all optimizations are applied. Your code may run slower or encounter "@@ -70,10 +66,7 @@ if already_imported:)del already_imported, critical_modules-# Unsloth currently does not work on multi GPU setups - sadly we are a 2 brother team so-# enabling it will require much more work, so we have to prioritize. Please understand!-# We do have a beta version, which you can contact us about!-# Thank you for your understanding and we appreciate it immensely!+# Multi-GPU is not yet supported (beta available on request).# Fixes https://github.com/unslothai/unsloth/issues/1266os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"@@ -178,10 +171,9 @@ patch_vllm_for_notebooks()patch_torchcodec_audio_decoder()disable_torchcodec_if_broken()disable_broken_wandb()-# Must run before patch_peft_weight_converter_compatibility -- stubs the-# transformers v5 submodules peft 0.19.x imports unconditionally, so the-# next patch can actually wrap build_peft_weight_mapping instead of being-# swallowed by its bare ImportError except.+# Must run before patch_peft_weight_converter_compatibility: stubs the+# transformers v5 submodules peft 0.19.x imports, so the next patch can wrap+# build_peft_weight_mapping instead of being swallowed by its ImportError.fix_peft_transformers_weight_conversion_import()patch_peft_weight_converter_compatibility()@@ -345,10 +337,8 @@ from unsloth_zoo.rl_environments import (launch_openenv,)-# Patch TRL trainers for backwards compatibility.-# Skipped under UNSLOTH_ALLOW_CPU=1 (CPU-only CI) because rebinding-# trl.SFTTrainer.__init__ to a generic wrapper changes-# inspect.getsource(SFTTrainer.__init__) and corrupts downstream-# drift detectors that anchor on the pristine upstream source.+# Patch TRL trainers for backwards compatibility. Skipped under+# UNSLOTH_ALLOW_CPU=1 (CPU-only CI): rebinding trl.SFTTrainer.__init__+# changes inspect.getsource() and corrupts downstream drift detectors.if os.environ.get("UNSLOTH_ALLOW_CPU", "0") != "1":_patch_trl_trainer()diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 956fcb23923..b96f8cb7a09 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -1964,11 +1964,8 @@ def get_chat_template(elif map_eos_token and (stop_word != "eos_token"):logger.warning_once(f"Unsloth: Will map {stop_word} to EOS = {tokenizer.eos_token}.")- # Replaces the old EOS token with a new one.- # Useful for ChatML <|im_end|> for example.- # Usually we train 2 more tokens <|im_start|> and <|im_end|>- # But training the lm_head and embeddings are slow!- # This is a HACK!+ # HACK: replace old EOS with a new one (e.g. ChatML <|im_end|>) to+ # avoid the slow lm_head/embedding retraining of new tokens.# Idea from https://huggingface.co/cognitivecomputations/dolphin-2.6-mistral-7b-dpo-laserold_bos_token = getattr(tokenizer, "bos_token", None)@@ -2193,18 +2190,14 @@ def to_sharegpt(random_state = 3407,):"""- Converts a dataset to ShareGPT style.- ShareGPT requires only 1 input and 1 output field.- This means one has to merge multiple columns into 1 for 1 input field.- Use `conversation_extension` to increase the length of each conversation by randomnly- selecting a few and packing them into 1.+ Converts a dataset to ShareGPT style (1 input + 1 output field).+ Merge multiple columns into 1 input via `merged_prompt`; use+ `conversation_extension` to pack several convos into one.merged_prompt = "", Prompt to merge columns into 1 inputmerged_column_name = "instruction", Final column name for the input fieldoutput_column_name = "output", Final column name for the output field- remove_unused_columns = True,- conversation_extension = 1, Automatically combines `conversation_extension` convos into 1- random_state = 3407,+ conversation_extension = 1, Combines this many convos into 1"""if "conversations" in dataset.column_names:convo = dataset[0]["conversations"]diff --git a/unsloth/dataprep/raw_text.py b/unsloth/dataprep/raw_text.pyindex 3abb6df6cdd..076a781d4b7 100644--- a/unsloth/dataprep/raw_text.py+++ b/unsloth/dataprep/raw_text.py@@ -102,11 +102,10 @@ class RawTextDataLoader:def create_causal_dataset(self, chunks):"""Create dataset for causal language modeling"""if chunks and isinstance(chunks[0], dict):- # If chunks are already tokenized (dict with input_ids, attention_mask)- # Reorganize the data structure for Dataset.from_dict+ # Already-tokenized chunks: reshape for Dataset.from_dictinput_ids = [chunk["input_ids"] for chunk in chunks]attention_mask = [chunk["attention_mask"] for chunk in chunks]- # Labels are same as input_ids for causal LM training+ # Labels == input_ids for causal LMlabels = [list(ids) for ids in input_ids]return Dataset.from_dict({@@ -116,7 +115,7 @@ class RawTextDataLoader:})else:- # If chunks are text strings (backward compatibility)+ # Text strings (backward compatibility)return Dataset.from_dict({"text": chunks})def smart_chunk_text(@@ -133,29 +132,26 @@ class RawTextDataLoader:3. Maintains context with stride overlap4. Returns tokenized chunks directly (more efficient) or text chunks"""- # First pass: tokenize the entire text to get accurate token counts+ # Tokenize the whole text once for accurate token countstokenized = self.tokenizer(text, return_tensors = "pt", add_special_tokens = False)tokens = tokenized["input_ids"]- # Handle different tokenizer return formats+ # Normalise tokenizer return formatsif hasattr(tokens, "__len__") and len(tokens) > 0:- # If it's a nested structure, get the first elementif hasattr(tokens[0], "__len__"):tokens = tokens[0]elif isinstance(tokens, int):- # If tokenizer returns just a count, create a simple range+ # Tokenizer returned a count; build a rangetokens = list(range(tokens))if len(tokens) <= chunk_size:- # Text is small enough to fit in one chunk+ # Fits in a single chunkif return_tokenized:- # Add EOS token to the tokens if availableeos_token_id = getattr(self.tokenizer, "eos_token_id", None)if eos_token_id is not None:tokens = tokens.tolist() if hasattr(tokens, "tolist") else list(tokens)tokens.append(eos_token_id)- # Create attention maskattention_mask = [1] * len(tokens)return [{"input_ids": tokens, "attention_mask": attention_mask}]else:@@ -166,25 +162,20 @@ class RawTextDataLoader:start_idx = 0while start_idx < len(tokens):- # Calculate end index for this chunkend_idx = min(start_idx + chunk_size, len(tokens))-- # Extract tokens for this chunkchunk_tokens = tokens[start_idx:end_idx]if return_tokenized:- # Convert to list if it's a tensorchunk_tokens_list = (chunk_tokens.tolist() if hasattr(chunk_tokens, "tolist") else list(chunk_tokens))- # Add EOS token if it's the last chunk or chunk is complete+ # Append EOS on the last or a full chunkif end_idx == len(tokens) or len(chunk_tokens_list) == chunk_size:eos_token_id = getattr(self.tokenizer, "eos_token_id", None)if eos_token_id is not None:chunk_tokens_list.append(eos_token_id)- # Create attention mask (all tokens are attended to)attention_mask = [1] * len(chunk_tokens_list)chunks.append({"input_ids": chunk_tokens_list, "attention_mask": attention_mask})@@ -192,14 +183,14 @@ class RawTextDataLoader:# Decode back to text (backward compatibility)chunk_text = self.tokenizer.decode(chunk_tokens, skip_special_tokens = True)- # Add EOS token if it's the last chunk or chunk is complete+ # Append EOS on the last or a full chunkif end_idx == len(tokens) or len(chunk_tokens) == chunk_size:eos_token = self.tokenizer.eos_token if self.tokenizer.eos_token else ""chunk_text += eos_tokenchunks.append(chunk_text)- # Move to next chunk with stride overlap+ # Advance with stride overlapif end_idx == len(tokens):breakstart_idx += chunk_size - stridediff --git a/unsloth/dataprep/synthetic.py b/unsloth/dataprep/synthetic.pyindex 9d9143254bc..90021c0c8d3 100644--- a/unsloth/dataprep/synthetic.py+++ b/unsloth/dataprep/synthetic.py@@ -217,7 +217,7 @@ class SyntheticDataKit:elif dtype_val == torch.float32:dtype_val = "float32"engine_args["dtype"] = dtype_val- # Convert torch.bfloat16, torch.float16, etc. to valid CLI string+ # Convert torch dtype to valid CLI stringif hasattr(dtype_val, "name"):engine_args["dtype"] = dtype_val.nameelif isinstance(dtype_val, str) and dtype_val.startswith("torch."):@@ -412,7 +412,6 @@ class SyntheticDataKit:boundaries = np.stack((boundaries[:-1], (boundaries + self.overlap)[1:])).Tboundaries = np.minimum(boundaries, length).tolist()- # Get extension of filename like .txtfilename, extension = os.path.splitext(filename)if filename.endswith("/"):filename = filename[:-1]diff --git a/unsloth/device_type.py b/unsloth/device_type.pyindex 170d5541f4b..0e425e20015 100644--- a/unsloth/device_type.py+++ b/unsloth/device_type.py@@ -52,11 +52,8 @@ def is_hip():@functools.cachedef get_device_type():- # Test-only CPU fallback. Short-circuits the detection chain so the- # rest of the function -- and every DEVICE_TYPE == "cuda" branch in- # the codebase -- behaves identically to a real CUDA host. The env- # var is read exactly once per process because get_device_type is- # @functools.cache'd, so production hosts pay no runtime cost.+ # Test-only CPU fallback: report "cuda" so every DEVICE_TYPE == "cuda"+ # branch behaves identically. Read once per process (function is cached).if os.environ.get("UNSLOTH_ALLOW_CPU", "0") == "1":return "cuda"if _IS_MLX:diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex c8be78bc3c1..25f5fdb9d28 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -106,11 +106,10 @@ except Exception:def suppress_cuda_printf():"""Suppress CUDA device-side printf by redirecting stdout/stderr fds to /dev/null.- CUDA device printf (eg CUTLASS "Arch conditional MMA" errors on Blackwell)- writes to stdout fd 1 at the C level, bypassing Python sys.stdout entirely.- The existing HidePrintMessage filter on sys.stderr cannot catch these since- they go to a different fd at a different layer. This context manager redirects- both fd 1 and fd 2 at the OS level, syncs CUDA, then restores them.+ CUDA device printf (e.g. CUTLASS "Arch conditional MMA" errors on Blackwell)+ writes to fd 1 at the C level, bypassing Python's sys.stdout, so the+ HidePrintMessage filter can't catch it. Redirect fd 1 and 2 at the OS level,+ sync CUDA, then restore."""sys.stdout.flush()sys.stderr.flush()@@ -575,22 +574,18 @@ def check_fbgemm_gpu_version():def patch_enable_input_require_grads():- """- Patch transformers PreTrainedModel.enable_input_require_grads to handle vision models- that raise NotImplementedError from get_input_embeddings().-- """+ """Patch PreTrainedModel.enable_input_require_grads to tolerate vision models+ that raise NotImplementedError from get_input_embeddings()."""import inspectfrom transformers import PreTrainedModel- # Check if the original function iterates over self.modules() instead of just returning the enable_input_require_grads+ # Only patch the new variant that iterates over self.modules().# Ref: https://github.com/huggingface/transformers/pull/41993/files#diff-6b72b98c4c2dcfc6cc606843917733f5d858374fbc22a735ff483bbc0c1e63eaL1979-R1996try:original_source = inspect.getsource(PreTrainedModel.enable_input_require_grads)except:return- # Only patch if the new pattern exists (iterating over self.modules())if "for module in self.modules()" not in original_source:return@@ -610,8 +605,8 @@ def patch_enable_input_require_grads():try:input_embeddings = module.get_input_embeddings()except NotImplementedError:- # Vision models may not implement get_input_embeddings - skip them- # For GLM V4.6 for example, this skips only `self.visual`+ # Vision models may not implement get_input_embeddings (e.g. GLM+ # V4.6 skips only `self.visual`); skip themcontinueif input_embeddings is None:@@ -635,11 +630,10 @@ def patch_enable_input_require_grads():def _is_custom_torch_build(raw_version_str):"""Check if a raw version string indicates a custom or source build.- Must operate on the raw string from importlib_version(), not the parsed- Version object, since our custom Version() strips local identifiers.- Standard PyTorch releases use: +cu124, +rocm6.3, +cpu, +xpu- Source/custom builds use: +gitXXXXXXX, +HEXHASH, or other suffixes.+ Operates on the raw importlib_version() string (our Version() strips local+ identifiers). Standard releases use +cu124/+rocm6.3/+cpu/+xpu; custom builds+ use +gitXXXX or other suffixes."""if "+" not in raw_version_str:return False@@ -701,13 +695,12 @@ def torchvision_compatibility_check():(2, 4): (0, 19),}- # Extract major.minor from the parsed versiontorch_release = torch_v.releaseif len(torch_release) < 2:returntorch_major, torch_minor = torch_release[0], torch_release[1]- # Try known table first, then fall back to formula for forward compatibility+ # Known table first, then the formula for forward compatibilityrequired = TORCH_TORCHVISION_COMPAT.get((torch_major, torch_minor))if required is None:@@ -1018,11 +1011,10 @@ def check_vllm_torch_sm100_compatibility():This check runs early (before vLLM import) to provide a helpful error messageinstead of a cryptic std::bad_alloc crash."""- # Check if vLLM is installed (without importing it)+ # vLLM installed? (without importing it)if importlib.util.find_spec("vllm") is None:return- # Check torch versiontry:torch_version = Version(importlib_version("torch"))if torch_version >= Version("2.9.0"):@@ -1030,7 +1022,7 @@ def check_vllm_torch_sm100_compatibility():except Exception:return # Can't determine torch version, skip check- # Check if any CUDA GPU is SM100 (Blackwell)+ # Any SM100 (Blackwell) GPU?try:import torch@@ -1051,13 +1043,12 @@ def check_vllm_torch_sm100_compatibility():except Exception:return- # Get vLLM version for the error messagetry:vllm_version = importlib_version("vllm")except Exception:vllm_version = "unknown"- # Incompatible combination detected - raise helpful error+ # Incompatible combination: raise a helpful errorraise RuntimeError(f"Unsloth: Incompatible configuration detected.\n\n"f" GPU: {sm100_gpu_name} (SM100 / Blackwell architecture)\n"@@ -1085,14 +1076,13 @@ def fix_vllm_pdl_blackwell():if importlib.util.find_spec("vllm") is None:return- # Check if any CUDA GPU is SM100 (Blackwell)+ # Any SM100 (Blackwell) GPU? Fix applies globally via env var + monkey-patch.try:import torchif not torch.cuda.is_available():return- # Scan all GPUs for SM100 - fix applies globally via env var and monkey-patchhas_sm100 = Falsesm100_gpu_name = Nonefor i in range(torch.cuda.device_count()):@@ -1107,14 +1097,13 @@ def fix_vllm_pdl_blackwell():except Exception:return- # Helper to check if module spec existsdef _spec_exists(name):try:return importlib.util.find_spec(name) is not Noneexcept (ImportError, OSError, ModuleNotFoundError, ValueError):return False- # Check if vLLM has the PDL-related modules before doing internet check+ # PDL-related modules present?has_utils = _spec_exists("vllm.lora.ops.triton_ops.utils")has_expand_op = _spec_exists("vllm.lora.ops.triton_ops.lora_expand_op")has_shrink_op = _spec_exists("vllm.lora.ops.triton_ops.lora_shrink_op")@@ -1123,7 +1112,7 @@ def fix_vllm_pdl_blackwell():# Old vLLM version without PDL support - nothing to patchreturn- # Check if vLLM version includes the fix+ # vLLM version already includes the fix?VLLM_PDL_FIX_VERSION = "0.15.0"try:vllm_version = Version(importlib_version("vllm"))@@ -1150,9 +1139,8 @@ def fix_vllm_pdl_blackwell():patched.append(name)patched_names.add(name)- # First, patch the source module (utils.py) where supports_pdl is defined.- # This is critical because supports_pdl uses @lru_cache - we must clear the- # cache to prevent stale cached results from the original function.+ # Patch the source module (utils.py) where supports_pdl is defined. It uses+ # @lru_cache, so clear the cache to avoid stale results.try:utils_module = importlib.import_module("vllm.lora.ops.triton_ops.utils")if hasattr(utils_module, "supports_pdl"):@@ -1164,9 +1152,7 @@ def fix_vllm_pdl_blackwell():except (ImportError, ModuleNotFoundError, AttributeError):pass- # Also patch the consumer modules that import supports_pdl from utils.- # This ensures the patched function is used even if the module was already- # imported before this fix runs.+ # Also patch consumer modules that imported supports_pdl before this ran.consumer_modules = {"lora_expand_op": "vllm.lora.ops.triton_ops.lora_expand_op","lora_shrink_op": "vllm.lora.ops.triton_ops.lora_shrink_op",@@ -1328,10 +1314,9 @@ def disable_broken_wandb():tf_integration.is_wandb_available = _wandb_falseexcept (ImportError, AttributeError):pass- # Patch accelerate's is_wandb_available (used by trl/trainer/callbacks.py).- # Must patch both the source module AND the re-export namespace since- # `from accelerate.utils import is_wandb_available` reads from- # accelerate.utils, not accelerate.utils.imports.+ # Patch accelerate's is_wandb_available. Patch both the source module and+ # the re-export namespace, since `from accelerate.utils import+ # is_wandb_available` reads accelerate.utils, not accelerate.utils.imports.try:import accelerate.utils.imports as acc_importsacc_imports.is_wandb_available = _wandb_falsediff --git a/unsloth/kernels/__init__.py b/unsloth/kernels/__init__.pyindex d46e0f4d596..7ff472112f6 100644--- a/unsloth/kernels/__init__.py+++ b/unsloth/kernels/__init__.py@@ -44,7 +44,7 @@ from .fast_lora import (apply_lora_o,fast_lora_forward,)-from .fp8 import * # This step is to ensure that we patch the FbgmemFP8Linear and FP8Linear's forward functions before the execution of model creation so that this applies to compiled non fast inference models as well+from .fp8 import * # Patch FbgmemFP8Linear/FP8Linear forwards before model creation, so compiled non-fast-inference models are covered toofrom .utils import (fast_dequantize,fast_gemv,diff --git a/unsloth/kernels/cross_entropy_loss.py b/unsloth/kernels/cross_entropy_loss.pyindex a170ed3dcfa..39446ec639f 100644--- a/unsloth/kernels/cross_entropy_loss.py+++ b/unsloth/kernels/cross_entropy_loss.py@@ -462,10 +462,9 @@ if (Version(torch.__version__) < Version("2.4.0")) and not hasattr(def patch_loss_functions(torch_compile = True):_patch_loss_functions(fast_cross_entropy_loss, torch_compile = torch_compile)- # Defense-in-depth sweep for LOSS_MAPPING aliases still pointing at the- # stock ForCausalLMLoss (e.g. ForConditionalGeneration for Qwen3.5,- # CsmForConditionalGeneration). unsloth_zoo also does this; remove once- # the floor pin moves past unslothai/unsloth-zoo#656.+ # Redirect LOSS_MAPPING aliases still pointing at stock ForCausalLMLoss+ # (e.g. ForConditionalGeneration for Qwen3.5, Csm...). unsloth_zoo also+ # does this; remove once the floor pin passes unslothai/unsloth-zoo#656.try:import transformers.loss.loss_utils as _lu_unsloth_loss = _lu.LOSS_MAPPING.get("ForCausalLM")diff --git a/unsloth/kernels/fast_lora.py b/unsloth/kernels/fast_lora.pyindex a49a9e04e82..f5d85e80885 100644--- a/unsloth/kernels/fast_lora.py+++ b/unsloth/kernels/fast_lora.py@@ -692,11 +692,8 @@ def fast_lora_forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:passresult = self.base_layer(x, *args, **kwargs)- # As per Tim Dettmers, for 4bit, we need to defensively clone here.- # The reason is that in some cases, an error can occur that backprop- # does not work on a manipulated view. This issue may be solved with- # newer PyTorch versions but this would need extensive testing to be- # sure.+ # Per Tim Dettmers: for 4bit, defensively clone -- backprop can fail on a+ # manipulated view (may be fixed in newer PyTorch, untested).result = result.clone()for active_adapter in self.active_adapters:diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex 81dfe9880d1..ca608fa01b5 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -128,9 +128,8 @@ def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)x = tl.load(x_ptr + offs).to(tl.float32)s = tl.max(tl.abs(x)) / 448.0- # For a row of all zeros, lets return zeros as is- # for LoRA, there are cases where dY has 0 in it and we should not let it be NaN- # this is a deviation from the original implementation.+ # All-zero row: keep scale at 1 so LoRA's zero dY doesn't become NaN+ # (a deviation from the original implementation).s = 1.0 if s == 0 else sy = x / sy = y.to(y_ptr.dtype.element_ty)@@ -320,9 +319,9 @@ def torchao_block_matmul(return out.to(output_dtype)-# Note that older versions of fbgemm (<=1.3.0) cause numerical imprecisions resulting in NaNs especially when X has high values in it.-# So our preference order is fbgemm (>=1.4.0) > torchao > triton. All of these have similar outputs/losses. Never use fbgemm (<=1.3.0) for block quantized FP8 matmul.-# This torchao FP8 matmul seems to be ~3x faster than the w8a8_block_fp8_matmul_triton. Though torchao is 15-30% slower than fbgemm implementation (on H100 GPUs).+# fbgemm <=1.3.0 causes NaNs for high X values, so never use it for block FP8.+# Preference: fbgemm (>=1.4.0) > torchao > triton (similar outputs/losses).+# torchao is ~3x faster than the triton kernel but 15-30% slower than fbgemm (H100).fp8_block_matmul = (torchao_block_matmul if torchao_blockwise_gemm is not None else w8a8_block_fp8_matmul_triton)@@ -333,13 +332,12 @@ class FP8BlockQuantLinear(torch.autograd.Function):def forward(ctx, X, weight, weight_scale):m, n = weight.shape- # Save original scale for backward (before any transformation)+ # Original scale, saved for backward before any transformationoriginal_weight_scale = weight_scale- # Handle per-tensor quantization: expand scalar to block scale shape+ # Per-tensor quant: expand scalar to (ceil(m/128), ceil(n/128)) block shapeif weight_scale.numel() == 1:block_size = [128, 128]- # Expand scalar to (ceil(m/128), ceil(n/128)) - same value for all blocksnum_blocks_m = triton.cdiv(m, block_size[0])num_blocks_n = triton.cdiv(n, block_size[1])weight_scale = weight_scale.expand(num_blocks_m, num_blocks_n).contiguous()@@ -362,7 +360,6 @@ class FP8BlockQuantLinear(torch.autograd.Function):if not weight.is_contiguous():weight = weight.contiguous()- # Quantize input and run FP8 matmulqinput, scale = act_quant(X, block_size[1])output = fp8_block_matmul(qinput,@@ -401,23 +398,19 @@ class FbgemmFp8Linear_matmul(torch.autograd.Function):if weight.shape[0] == weight_scale.shape[0] and (weight.shape[0] % 8 == 0 and weight.shape[1] % 8 == 0):- # Edit: The kernel seems to expect that the weight has dimensions divisible by 8. Otherwise it throws `RuntimeError: cutlass cannot implement`- # One thing we can do is to pad the weight and weight scale to multiple of 8 and perform a F8F8BF16 operation.- # I tried benchmarking that for speed but observed that dequantize+bf16 matmul is significantly faster than padding+f8f8bf16 matmul. So we'll go that route.- # So essentially, f8f8bf16_rowise only happens when shapes are proper (no transposes) and divisible by 8.+ # The kernel needs weight dims divisible by 8 (else `cutlass cannot+ # implement`). Padding + f8f8bf16 is slower than dequant + bf16 matmul,+ # so f8f8bf16_rowwise runs only for proper, divisible-by-8 shapes.- # quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here+ # quantize_fp8_per_row squashes leading dims; save the shape firstoutput_shape = (*x.shape[:-1], -1)- # x_quantized and x_scale are not necessarily on the same device as x, this is an issue.- # https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45+ # x_quantized/x_scale may land on a different device than x (FBGEMM+ # quantize.cu#L1237). Moving them here produces gibberish; move the+ # output instead. Compute runs on weight's device regardless.x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(x.view(-1, x.shape[-1]).contiguous(),scale_ub = getattr(weight, "input_scale_ub", None),)- # moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works- # x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device)-- # The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weightweight_scale_float32 = weight_scale.to(torch.float32)if not weight.is_contiguous():@@ -429,17 +422,15 @@ class FbgemmFp8Linear_matmul(torch.autograd.Function):x_quantized, weight, x_scale, weight_scale_float32, use_fast_accum = True)output = output + bias if bias is not None else output- # Hacky for now, we have the output to the device of x+ # Move output back to x's device (the move-input path produced gibberish)output = output.to(x.device, x.dtype)output = output.reshape(output_shape)del x_quantized, x_scaleelif (weight.shape[0] != weight_scale.shape[0] and weight.shape[1] == weight_scale.shape[0]) or (weight.shape[0] % 8 != 0 or weight.shape[1] % 8 != 0):- # Either the weight/scale is transposed or its shape is not divisible by 8. Both cases, dequantizing is the preferred way.- # The transpose case is generally noticed in backward pass when we do dY@W instead of @W.T as we do for forward.- # The shape case, I noticed to happen in MLP of Qwen 2.5 VL 7B where the gate proj is of shape (3420, 1280) and 3420/8=427.5-+ # Transposed weight/scale (backward dY@W) or non-divisible-by-8 shape+ # (e.g. Qwen 2.5 VL 7B gate proj 3420x1280): dequant is preferred.W_deq = weight_dequant(weight, weight_scale).Toutput = torch_matmul(x, W_deq)output = output + bias if bias is not None else output@@ -493,8 +484,8 @@ class FP8_fbgemm_block_linear(torch.autograd.Function):if triton.cdiv(m, bs_n) != p or triton.cdiv(n, bs_k) != q:if triton.cdiv(m, bs_n) == q and triton.cdiv(n, bs_k) == p:- # weights are transposed during backward pass for training :)- # We transpose weight scale to counter that. Note that transposing weight would cause issues with matmul with input X+ # Backward transposes the weight; transpose the scale to match+ # (transposing the weight itself would break matmul with X).weight_scale = weight_scale.Telse:raise ValueError(@@ -502,10 +493,9 @@ class FP8_fbgemm_block_linear(torch.autograd.Function):)xq, xs = triton_quantize_fp8_block(X, bs_m, bs_n, None)- ## TODO: Investigate and resolve the high divergence of this output from baseline- # WARNING: This causes the outputs to diverge from expected when X has high values in it.- # That results in the model producing gibberish, especially on longer sequences and training loss starting at high values like 8 instead of <1 ideally- # Please refrain from using this till this issue is resolved. This exists here just for a future headstart.+ # TODO: WARNING - diverges from baseline for high X values, producing+ # gibberish / high starting loss. Do not use until resolved; kept for a+ # future headstart.output = torch.ops.fbgemm.f8f8bf16_blockwise(xq, weight.contiguous(), xs, weight_scale.contiguous(), bs_m, bs_n, bs_k)@@ -540,9 +530,8 @@ def fp8_fbgemm_block_linear(def test_has_fbgemm():- # We must manually check if the faster FBGEMM works on the specific GPU- # For example RTX 5090 and RTX 4090 does not work- # Also SM100 (Blackwell B200/B100) GPUs fail with CUTLASS SM90 kernels+ # Probe whether the faster FBGEMM works on this GPU. RTX 4090/5090 and+ # SM100 (Blackwell B200/B100) fail with CUTLASS SM90 kernels.# [TODO] Investigate with TorchAO why FBGEMM fails on consumer GPUsM, N, K = 128, 128, 128xq = torch.ones(M, K, dtype = torch.float8_e4m3fn, device = "cuda")@@ -558,8 +547,7 @@ def test_has_fbgemm():del outexcept Exception as e:error_str = str(e).lower()- # Catch any CUTLASS/CUDA errors and disable FBGEMM- # This includes MMA instruction errors, architecture mismatches, kernel launch failures, etc.+ # Disable FBGEMM on any CUTLASS/CUDA error (MMA, arch mismatch, launch, etc.)cutlass_cuda_errors = ("cutlass","cuda error",@@ -591,15 +579,11 @@ if "UNSLOTH_HAS_FBGEMM" not in os.environ:try:import fbgemm_gpu- # Older versions cause numerical imprecisions resulting in NaNs especially when X has high values in it.- # This is both fast and accurate hence preferred.- # This makes it 15% faster than the torchao implementation.+ # >=1.4.0 is fast and accurate (older versions NaN on high X); ~15% faster+ # than torchao. Must probe blockwise FBGEMM since consumer GPUs fail.if Version(fbgemm_gpu.__version__) >= Version("1.4.0"):- # We must manually confirm if blockwise FBGEMM works!- # This check is a must for consumer grade GPUs which fail- # Suppress CUDA device printf during probe -- on Blackwell (SM100) GPUs,- # FBGEMM's CUTLASS blockwise kernel (hardcoded SM90) fires thousands of- # "Arch conditional MMA" lines to stdout fd 1 before aborting.+ # Suppress CUDA printf during probe: on Blackwell (SM100), FBGEMM's+ # SM90 CUTLASS kernel floods stdout with "Arch conditional MMA" before aborting.from unsloth.import_fixes import suppress_cuda_printfwith suppress_cuda_printf():_has_fbgemm = test_has_fbgemm()@@ -620,11 +604,10 @@ def fp8_linear(weight_scale,bias = None,):- # Per-tensor quantization: single scalar scale for entire weight- # Block quantized FP8: 2D scale tensor with multiple columns+ # Per-tensor (scalar scale) or block FP8 (2D scale, multiple columns)if weight_scale.numel() == 1 or (weight_scale.ndim == 2 and weight_scale.shape[1] > 1):out = fp8_block_quant_linear(X, weight, weight_scale)- # Row/channel quantized FP8: 2D scale with shape (n, 1)+ # Row/channel FP8: 2D scale shaped (n, 1)else:out = fbgemm_fp8_linear(X, weight, weight_scale, bias)return outdiff --git a/unsloth/kernels/moe/autotune_cache.py b/unsloth/kernels/moe/autotune_cache.pyindex 5756a9c4161..775c67d2ab9 100644--- a/unsloth/kernels/moe/autotune_cache.py+++ b/unsloth/kernels/moe/autotune_cache.py@@ -29,7 +29,6 @@ import tritonlogger = logging.getLogger(__name__)-# Global cache for kernel configurations_kernel_config_cache: Dict[str, Any] = {}_autotune_completed: Dict[str, bool] = {}@@ -74,7 +73,7 @@ def load_cached_config(cache_key: str) -> Optional[Dict[str, Any]]:with open(cache_file, "r", encoding = "utf-8") as f:cached_data = json.load(f)- # Verify cache is still valid (same device, etc.)+ # Invalidate if device capability changedcurrent_device_capability = torch.cuda.get_device_capability()if cached_data.get("device_capability") != current_device_capability:logger.info("Device capability changed, invalidating cache")@@ -158,7 +157,7 @@ def get_or_autotune_moe_kernels(seq_len,)- # 0. Check for environment variable override to DISABLE autotuning+ # Env override to disable autotuningif os.environ.get("UNSLOTH_MOE_DISABLE_AUTOTUNE", "0") == "1":logger.info(f"UNSLOTH_MOE_DISABLE_AUTOTUNE=1: Using Heuristic (Safe) MoE kernel configs for SM{device_capability[0]}{device_capability[1]}"@@ -172,7 +171,7 @@ def get_or_autotune_moe_kernels(if not force_autotune:cached_data = load_cached_config(cache_key)if cached_data is not None:- # Reconstruct config objects from cached data+ # Reconstruct config objects from cachetry:from .grouped_gemm.kernels.tuning import (KernelConfigForward,@@ -190,7 +189,6 @@ def get_or_autotune_moe_kernels(except Exception as e:logger.warning(f"Failed to reconstruct cached configs: {e}")- # Run autotuningif cache_key in _autotune_completed and not force_autotune:logger.info(f"Autotuning already completed for: {cache_key}")return _kernel_config_cache[cache_key]@@ -205,7 +203,6 @@ def get_or_autotune_moe_kernels(num_experts, hidden_dim, intermediate_dim, top_k, dtype, seq_len)- # Cache the results_kernel_config_cache[cache_key] = configs_autotune_completed[cache_key] = True@@ -246,18 +243,13 @@ def _run_moe_autotuning() -> Tuple[Any, Any, Any]:"""Run the actual auto-tuning for MoE kernels."""- # Create dummy inputs for tuningdevice = "cuda"- # Use a fixed, safe number of tokens for autotuning to avoid OOMs and dependency on seq_len- # 4096 is standard for finding good kernels without consuming 10GB+ VRAM- # We ignore the passed seq_len for the actual allocation to satisfy user request+ # Fixed token count avoids OOMs and seq_len dependency; we ignore the passed seq_len herenum_tokens = 4096total_tokens = num_tokens * top_k- # Create dummy tensorshidden_states = torch.randn(num_tokens, hidden_dim, device = device, dtype = dtype)- # Create dummy weightsgate_up_weights = torch.randn(num_experts, 2 * intermediate_dim, hidden_dim, device = device, dtype = dtype)@@ -265,10 +257,10 @@ def _run_moe_autotuning(num_experts, hidden_dim, intermediate_dim, device = device, dtype = dtype)- # Create dummy routing data+ # Dummy routing datam_sizes = torch.randint(1, total_tokens // num_experts + 1, (num_experts,), device = device)m_sizes = m_sizes * (total_tokens // m_sizes.sum().item())- # Adjust to ensure exact total+ # Adjust to exact totaldiff = total_tokens - m_sizes.sum().item()if diff != 0:m_sizes[0] += diff@@ -276,8 +268,7 @@ def _run_moe_autotuning(gather_indices = torch.arange(total_tokens, device = device)torch.randperm(total_tokens, out = gather_indices)- # Autotune forward kernel - use the interface function with autotune=True- # This properly invokes the kernel and lets triton handle the autotuning+ # Autotune via the interface function with autotune=True (lets triton tune)from .grouped_gemm.interface import (grouped_gemm_forward,grouped_gemm_dX,@@ -295,7 +286,6 @@ def _run_moe_autotuning()logger.info("Autotuning forward kernel (first GEMM)...")- # Run with autotune=True to trigger autotuning_ = grouped_gemm_forward(X = hidden_states,W = gate_up_weights,@@ -308,7 +298,6 @@ def _run_moe_autotuning()triton_config_fwd = _autotuned_grouped_gemm_forward_kernel.best_config- # Convert triton.Config to KernelConfigForwardconfig_fwd = KernelConfigForward(BLOCK_SIZE_M = triton_config_fwd.kwargs["BLOCK_SIZE_M"],BLOCK_SIZE_N = triton_config_fwd.kwargs["BLOCK_SIZE_N"],@@ -335,7 +324,6 @@ def _run_moe_autotuning()triton_config_bwd_dx = _autotuned_grouped_gemm_dX_kernel.best_config- # Convert triton.Config to KernelConfigBackward_dXconfig_bwd_dx = KernelConfigBackward_dX(BLOCK_SIZE_M = triton_config_bwd_dx.kwargs["BLOCK_SIZE_M"],BLOCK_SIZE_N = triton_config_bwd_dx.kwargs["BLOCK_SIZE_N"],@@ -361,7 +349,6 @@ def _run_moe_autotuning()triton_config_bwd_dw = _autotuned_grouped_gemm_dW_kernel.best_config- # Convert triton.Config to KernelConfigBackward_dWconfig_bwd_dw = KernelConfigBackward_dW(BLOCK_SIZE_M = triton_config_bwd_dw.kwargs["BLOCK_SIZE_M"],BLOCK_SIZE_N = triton_config_bwd_dw.kwargs["BLOCK_SIZE_N"],diff --git a/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py b/unsloth/kernels/moe/benchmark/benchmark_fused_moe.pyindex a5ea4a4e71b..ce627012407 100644--- a/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py+++ b/unsloth/kernels/moe/benchmark/benchmark_fused_moe.py@@ -49,9 +49,7 @@ def run_benchmark_forward(kernel_config_fwd: KernelConfigForward = None,bs: int = 1,):- torch.manual_seed(- SEED- ) # Should not be needed when running using pytest -- autouse fixture in conftest.py+ torch.manual_seed(SEED) # Redundant under pytest (autouse fixture in conftest.py)device = "cuda"hidden_size = config.hidden_size@@ -89,9 +87,7 @@ def run_benchmark_backward(dtype: torch.dtype,bs = 1,):- torch.manual_seed(- SEED- ) # Should not be needed when running using pytest -- autouse fixture in conftest.py+ torch.manual_seed(SEED) # Redundant under pytest (autouse fixture in conftest.py)device = "cuda"hidden_size = config.hidden_size@@ -279,13 +275,13 @@ if __name__ == "__main__":)parser.add_argument("--use_tma_load_w", action = "store_true"- ) # No need to specify, will automatically parametrize these for each kernel config+ ) # Auto-parametrized per kernel config; no need to specifyparser.add_argument("--use_tma_load_x", action = "store_true"- ) # No need to specify, will automatically parametrize these for each kernel config+ ) # Auto-parametrized per kernel config; no need to specifyparser.add_argument("--use_tma_load_dy", action = "store_true"- ) # No need to specify, will automatically parametrize these for each kernel config+ ) # Auto-parametrized per kernel config; no need to specifyparser.add_argument("--mode",type = str,@@ -321,9 +317,9 @@ if __name__ == "__main__":end_time = time.time()print(f"Total time: {end_time - start_time:.4f} seconds")- # NOTE: better to use autotuner for now, since the MoE block needs 2 different kernel configs for forward (2 grouped gemms, gate_up_proj and down_proj)- # and the backward pass needs 4 different kernel configs (2 grouped gemms each for dW and dX)- # The benchmark only supports 1 kernel config at a time so the same config will be used for both grouped gemms, which is suboptimal.+ # NOTE: prefer the autotuner for now. The MoE block needs 2 forward+ # configs (gate_up_proj, down_proj) and 4 backward (dW + dX each); this+ # benchmark only supports 1 config at a time, so it's suboptimal here.else:assert False, "Use autotune for now"kernel_configs = create_kernel_configs(args, args.permute_x, args.permute_y)diff --git a/unsloth/kernels/moe/grouped_gemm/interface.py b/unsloth/kernels/moe/grouped_gemm/interface.pyindex 86b1558ff9f..a404b726dc2 100644--- a/unsloth/kernels/moe/grouped_gemm/interface.py+++ b/unsloth/kernels/moe/grouped_gemm/interface.py@@ -26,10 +26,8 @@ from .kernels.tuning import ()logger = logging.getLogger(__name__)-# Set formatter to include timestamp, pathname and linenoformatter = logging.Formatter("%(asctime)s::%(levelname)s,%(pathname)s:%(lineno)d:: %(message)s")-# Add console handlerch = logging.StreamHandler()ch.setFormatter(formatter)logger.addHandler(ch)@@ -45,7 +43,7 @@ def _check_tma_support():import triton.language as tlgpu_supports_tma = torch.cuda.get_device_capability()[0] >= 9- # Check for both old experimental and new stable API names+ # Support both old experimental and new stable API namestriton_has_tma_api = hasattr(tl, "make_tensor_descriptor") or hasattr(tl, "_experimental_make_tensor_descriptor")@@ -62,23 +60,18 @@ def supports_tma():return _SUPPORTS_TMA-# Helper to support allow_in_graphtry:from torch.compiler import allow_in_graphexcept ImportError:from torch._dynamo import allow_in_graph-# Helper to detect if we're in tracing/compilation modedef _is_tracing(*tensors):"""- Check if tensors are fake tensors used during torch.compile tracing.- During tracing, tensors are FakeTensor/FunctionalTensor and we can't run Triton kernels.- During execution, tensors are real Tensors and we MUST run the kernels.+ True if tensors are fake tensors used during torch.compile tracing (Triton can't run).- NOTE: We do NOT use torch.compiler.is_compiling() because it returns True- during both tracing AND execution. We only want to skip kernels during tracing- when tensors are actually fake.+ NOTE: We do NOT use torch.compiler.is_compiling() because it returns True during both+ tracing AND execution; we only want to skip kernels during tracing on fake tensors."""for t in tensors:name = type(t).__name__@@ -129,9 +122,9 @@ def grouped_gemm_forward(permute_x: bool = False,permute_y: bool = False,fuse_mul_post: bool = False,- # Autotuning - manual kernel params will be ignored if autotune is True+ # Autotuning -- overrides manual kernel params when Trueautotune: bool = False,- # Kernel tuning params if not autotuning -- NOTE: these params need to be tuned, otherwise performance will be poor+ # Kernel tuning params (must be tuned, else poor performance)BLOCK_SIZE_M: int = 32,BLOCK_SIZE_N: int = 32,BLOCK_SIZE_K: int = 32,@@ -140,7 +133,7 @@ def grouped_gemm_forward(use_tma_load_w: bool = False,use_tma_load_x: bool = False,use_tma_store: bool = False,- # software pipelining -- set to True for now, won't impact until loop is re-written+ # software pipelining; no effect until loop is re-writtenflatten: bool = True,# debuggingdebug: bool = False,@@ -829,9 +822,7 @@ def check_valid_config_fwd(fuse_mul_post,is_first_gemm,):- """- Check if the configuration is valid for the forward pass.- """+ """Check if the configuration is valid for the forward pass."""is_second_gemm = not is_first_gemmassert not (permute_x and permute_y), "Cannot permute both X and Y"@@ -855,9 +846,7 @@ def check_valid_config_bwd_dW(fuse_mul_post,is_first_gemm,):- """- Check if the configuration is valid for the backward pass of dW.- """+ """Check if the configuration is valid for the backward pass of dW."""is_second_gemm = not is_first_gemmif fuse_mul_post:assert False, "Cannot fuse_mul is not supported for backward pass"@@ -876,9 +865,7 @@ def check_valid_config_bwd_dX(fuse_mul_post,is_first_gemm,):- """- Check if the configuration is valid for the backward pass of dW.- """+ """Check if the configuration is valid for the backward pass of dW."""is_second_gemm = not is_first_gemmif fuse_mul_post:assert False, "Cannot fuse_mul is not supported for backward pass"diff --git a/unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py b/unsloth/kernels/moe/grouped_gemm/kernels/autotuning.pyindex 7c1b25e234e..bea59a4548d 100644--- a/unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py+++ b/unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py@@ -59,9 +59,8 @@ def _triton_supports_tma():)-# Precompute at module import-# NOTE: TMA is disabled for now due to compatibility issues with permute_x/permute_y settings-# in the MoE grouped GEMM forward/backward passes. Re-enable once these are resolved.+# TMA disabled for now: incompatible with permute_x/permute_y in the MoE+# grouped GEMM passes. Re-enable once resolved._TRITON_HAS_TMA = False # _triton_supports_tma()diff --git a/unsloth/kernels/moe/grouped_gemm/kernels/backward.py b/unsloth/kernels/moe/grouped_gemm/kernels/backward.pyindex 8c3c8fd13e8..b78ea58bd04 100644--- a/unsloth/kernels/moe/grouped_gemm/kernels/backward.py+++ b/unsloth/kernels/moe/grouped_gemm/kernels/backward.py@@ -128,9 +128,8 @@ def _grouped_gemm_dX_kernel(block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K],)- # Lower bound and upper bound are defined relative to the total tiles processed so far- # This ensures that we are only processing tiles for the current expert group AND- # we never exceed the total number of tiles for all expert groups+ # Bounds are relative to tiles processed so far, so we only handle+ # this expert's tiles and never exceed the total across experts.while tidx >= processed_tiles and tidx < (processed_tiles + num_tiles_per_expert):group_index = tidx - processed_tilesdiff --git a/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py b/unsloth/kernels/moe/grouped_gemm/kernels/tuning.pyindex c1962c11168..35d6ff7504b 100644--- a/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py+++ b/unsloth/kernels/moe/grouped_gemm/kernels/tuning.py@@ -1,9 +1,7 @@# SPDX-License-Identifier: GNU Affero General Public License v3.0# Copyright 2023-present the Unsloth team. All rights reserved.-"""-Manual tuning utils-"""+"""Manual tuning utils."""from collections import OrderedDictfrom dataclasses import asdict, dataclass, fields@@ -258,7 +256,6 @@ class TritonTuningContext:self.success = Truedef __enter__(self):- # Setup code can be added here if neededreturn selfdef __exit__(self, exc_type, exc_value, traceback):diff --git a/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py b/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.pyindex 863765b0b8e..a1d94d2c7d1 100644--- a/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py+++ b/unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py@@ -189,13 +189,13 @@ class Llama4GroupedGemmTextMoe(Llama4TextMoe):hidden_states = hidden_states.sum(dim = 1)hidden_states_after_weight_merge = hidden_states.view(-1, hidden_dim)- # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order- # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph+ # Token counts per expert + gather indices (token->expert order).+ # Auxiliary structs; not recorded in the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)- # 2. Permute tokens from token order to expert order+ # Permute tokens into expert orderhidden_states = permute(hidden_states_after_weight_merge, gather_indices, self.top_k)assert hidden_states.shape == (total_tokens, hidden_dim)@@ -365,13 +365,13 @@ class Llama4TritonTextMoe(Llama4GroupedGemmTextMoe):hidden_states = hidden_states.sum(dim = 1)hidden_states = hidden_states.view(-1, hidden_dim)- # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order- # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph+ # Token counts per expert + gather indices (token->expert order).+ # Auxiliary structs; not recorded in the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)- # 2. Permute tokens from token order to expert order+ # Permute tokens into expert orderhidden_states = permute(hidden_states, gather_indices, self.top_k)assert hidden_states.shape == (total_tokens, hidden_dim)@@ -410,8 +410,7 @@ class Llama4TritonTextMoe(Llama4GroupedGemmTextMoe):dX_only = self.dX_only,)- # Post-processing- # 1. Unpermute from expert order to token order+ # Unpermute from expert order back to token orderif not self.permute_y:hidden_states = unpermute(hidden_states, gather_indices)hidden_states += shared_expert_outdiff --git a/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py b/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.pyindex bd51cac3777..da3faa5f93c 100644--- a/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py+++ b/unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py@@ -157,13 +157,13 @@ class Qwen3MoeGroupedGEMMBlock(torch.nn.Module):router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order- # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph+ # Token counts per expert + gather indices (token->expert order).+ # Auxiliary structs; not recorded in the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)- # 2. Permute tokens from token order to expert order+ # Permute tokens into expert orderhidden_states = permute(hidden_states, gather_indices, self.top_k)assert hidden_states.shape == (total_tokens, hidden_dim)@@ -179,12 +179,11 @@ class Qwen3MoeGroupedGEMMBlock(torch.nn.Module):)assert second_gemm.shape == (total_tokens, hidden_dim)- # Post-processing- # 1. Unpermute from expert order to token order+ # Unpermute from expert order back to token orderhidden_states_unpermute = unpermute(second_gemm, gather_indices)assert hidden_states_unpermute.shape == (total_tokens, hidden_dim)- # 2. Merge topk weights+ # Merge topk weightshidden_states = (hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim)* routing_weights[..., None]@@ -275,14 +274,13 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):hidden_states = hidden_states.view(-1, hidden_dim)router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # Pre-processing- # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order- # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph+ # Token counts per expert + gather indices (token->expert order).+ # Auxiliary structs; not recorded in the autograd graph.token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)- # 2. permute_x -> permutation will be fused in prologue of first grouped gemm+ # When permute_x is set, the permute fuses into the first gemm prologueif not self.permute_x:hidden_states = permute(hidden_states, gather_indices, self.top_k)# Start expert computation@@ -320,12 +318,11 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):dX_only = self.dX_only,)- # Post-processing- # 1. Unpermute from expert order to token order+ # Unpermute from expert order back to token orderif not self.permute_y:hidden_states = unpermute(hidden_states, gather_indices)- # 2. Merge topk weights+ # Merge topk weightshidden_states = (hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None])diff --git a/unsloth/kernels/moe/tests/moe_utils.py b/unsloth/kernels/moe/tests/moe_utils.pyindex 71f58735107..3b87fe45a40 100644--- a/unsloth/kernels/moe/tests/moe_utils.py+++ b/unsloth/kernels/moe/tests/moe_utils.py@@ -34,13 +34,13 @@ def rebind_experts_to_shared_buffer(moe_block: Qwen3MoeSparseMoeBlock, config: Qbuffer_gate = torch.empty(num_experts, interm_size, hidden_size, device = device, dtype = dtype)buffer_down = torch.empty(num_experts, hidden_size, interm_size, device = device, dtype = dtype)- # Step 2: Copy existing expert weights into buffers+ # Copy existing expert weights into buffersfor i, expert in enumerate(moe_block.experts):buffer_up[i].copy_(expert.up_proj.weight.data)buffer_gate[i].copy_(expert.gate_proj.weight.data)buffer_down[i].copy_(expert.down_proj.weight.data)- # Step 3: Rebind expert weights to views in shared buffer+ # Rebind expert weights to views in the shared bufferfor i, expert in enumerate(moe_block.experts):expert.up_proj.weight = torch.nn.Parameter(buffer_up[i])expert.gate_proj.weight = torch.nn.Parameter(buffer_gate[i])@@ -332,13 +332,11 @@ def run_backward(class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):- """- Reference implementation of MoE block using grouped gemm.-- This is the same as the Qwen3MoeGroupedGEMMBlock but with triton grouped gemm in place of torch-native grouped gemm implementation.+ """Reference MoE block using triton grouped gemm.- NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging.- See grouped_gemm/reference/moe_block.py for a cleaner implementation.+ Like Qwen3MoeGroupedGEMMBlock but with triton (not torch-native) grouped gemm.+ NOT for production: it saves intermediate results and runs extra checks for+ debugging. See grouped_gemm/reference/moe_block.py for a cleaner version."""def __init__(@@ -406,14 +404,13 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):hidden_states = hidden_states.view(-1, hidden_dim)router_logits, routing_weights, selected_experts = self.run_router(hidden_states)- # Pre-processing- # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order- # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph+ # Pre-processing: token counts per expert + token-order -> expert-order+ # gather indices (auxiliary, not recorded in the autograd graph).token_counts_by_expert, gather_indices = self.get_token_counts_and_gather_indices(selected_experts)- # 2. permute_x -> permutation will be fused in prologue of first grouped gemm+ # permute_x fuses the permutation into the first grouped gemm's prologueif not self.permute_x:hidden_states = permute(hidden_states, gather_indices, self.top_k)assert hidden_states.shape == (total_tokens, hidden_dim)@@ -452,15 +449,14 @@ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock):)assert second_gemm.shape == (total_tokens, hidden_dim)- # Post-processing- # 1. Unpermute from expert order to token order+ # Post-processing: unpermute expert order -> token orderif not self.permute_y:hidden_states_unpermute = unpermute(second_gemm, gather_indices)assert hidden_states_unpermute.shape == (total_tokens, hidden_dim)else:hidden_states_unpermute = second_gemm- # 2. Merge topk weights+ # Merge topk weightshidden_states = (hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim)* routing_weights[..., None]diff --git a/unsloth/kernels/moe/tests/test_grouped_gemm.py b/unsloth/kernels/moe/tests/test_grouped_gemm.pyindex 35de6fca51a..7ff47d07678 100644--- a/unsloth/kernels/moe/tests/test_grouped_gemm.py+++ b/unsloth/kernels/moe/tests/test_grouped_gemm.py@@ -43,12 +43,8 @@ from .common import (SEED = 0-# Only certain combinations of permute_x, permute_y, use_W1 are valid.-# use_W1 => first grouped GEMM in a fused MoE MLP-# use_W2 => second grouped GEMM in a fused MoE MLP-# permute_x => permute the input to the grouped GEMM, only done for the first grouped GEMM-# permute_y => permute the output of the grouped GEMM, only done for the second grouped GEMM-# fuse_mul_post => fuse the multiplication of topk weights in the epilogue of the second grouped GEMM; only used for inference, not currently tested+# Only certain (permute_x, permute_y, use_W1) combinations are valid; see the+# module string below for the full rationale.def check_valid_config(permute_x,permute_y,diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex 0db97aabcba..43ed198a4ac 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -283,9 +283,8 @@ def QUANT_STATE(W):def get_lora_parameters(proj):- """- Return a 5-tuple of (weight, weight quant_state, lora A, lora B, and lora scale).- If QAT is enabled, additionally fake quantize the base layer and lora weights.+ """Return (weight, weight quant_state, lora A, lora B, lora scale).+ With QAT enabled, also fake-quantizes the base layer and lora weights."""# For DPO or disabled adaptersbase_layer = getattr(@@ -382,10 +381,8 @@ def get_lora_parameters_bias(proj):def _maybe_fake_quantize_activations(X: torch.Tensor, proj: torch.nn.Module) -> torch.Tensor:- """- If QAT is enabled, fake quantize the input activations.- Otherwise, just return the input activations as is.- Weights are fake quantized separately in `get_lora_parameters`.+ """Fake-quantize input activations if QAT is enabled, else return as-is.+ Weights are fake-quantized separately in `get_lora_parameters`."""base_layer = getattr(proj, "base_layer", proj)activation_fake_quantizer = getattr(base_layer, "activation_fake_quantizer", None)@@ -1089,9 +1086,8 @@ def matmul_lora(if isinstance(W, Float8Tensor):assert W.ndim == 2if W.block_size[0] == W.shape[0] and W.block_size[1] == 1:- # In the backward pass, rowwise scaled becomes colwise scaled after we- # transpose the weight tensor. Use this case to detect backward.- # TODO: would be simpler if we simply don't call `matmul_lora` in backward+ # Rowwise scaling becomes colwise after transpose, so this detects+ # the backward pass. TODO: avoid calling matmul_lora in backward.W = W.dequantize()else:W = W.contiguous()diff --git a/unsloth/models/__init__.py b/unsloth/models/__init__.pyindex 138f3090325..dc7e3091091 100644--- a/unsloth/models/__init__.py+++ b/unsloth/models/__init__.py@@ -24,7 +24,7 @@ from .sentence_transformer import FastSentenceTransformertry:from .falcon_h1 import FastFalconH1Modelexcept:- # transformers_version < 4.53.0 does not have falcon_h1 so silently skip it for now+ # falcon_h1 absent before transformers 4.53.0; skippassfrom .dpo import PatchDPOTrainer, PatchKTOTrainerfrom ._utils import is_bfloat16_supported, is_vLLM_available, __version__diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex f8324bf8e01..486a9074786 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -196,8 +196,7 @@ def apply_unsloth_gradient_checkpointing(use_gradient_checkpointing, max_seq_len"""Apply gradient checkpointing with smart heuristics.- For seq < 512, the overhead of gradient offloading in gc="unsloth" mode- is not worth it. Benchmarks show standard gc is faster for small sequences.+ For seq < 512, gc="unsloth" offloading overhead isn't worth it; standard gc is faster.Args:use_gradient_checkpointing: "unsloth", True, False, or None@@ -208,9 +207,7 @@ def apply_unsloth_gradient_checkpointing(use_gradient_checkpointing, max_seq_lenThe effective use_gradient_checkpointing value (may change from "unsloth" to True)"""if use_gradient_checkpointing == "unsloth":- # Gradient offloading overhead is not worth it for small sequences.- # Benchmarks show crossover point is around seq_len 384-512.- # For seq < 512, standard gradient checkpointing is faster.+ # Offloading not worth it below ~512; standard gc is faster (crossover ~384-512).if max_seq_length < 512:unpatch_unsloth_smart_gradient_checkpointing()return True@@ -1807,16 +1804,7 @@ if DEVICE_COUNT == 1 and int(os.environ.get("WORLD_SIZE", "1")) <= 1:# to move multiple tensors to the same devicedef move_to_device(target_device, *tensors):- """- Move multiple tensors to target device if they're not already there.-- Args:- target_device: The target device to move tensors to- *tensors: Variable number of tensors to potentially move-- Returns:- tuple: The tensors on the target device (same objects if already on device, new if moved)- """+ """Move tensors to target_device (returns same objects if already there)."""if isinstance(target_device, int):target_device = torch.device(target_device)elif isinstance(target_device, str):diff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.pyindex 3b03333241f..b940c95c686 100644--- a/unsloth/models/falcon_h1.py+++ b/unsloth/models/falcon_h1.py@@ -62,9 +62,7 @@ try:FalconH1Attention,)except ModuleNotFoundError:- # if we are on an old version of transformers technically it should fail in the try except above- # but if somehow we make it here, we need to raise an error since FalconH1Attention is not available- # or renamed+ # FalconH1Attention unavailable or renamed (old transformers).raise ImportError("Unsloth: Could not import FalconH1Attention from transformers.models.falcon_h1.modeling_falcon_h1.")@@ -487,8 +485,7 @@ def _FalconH1_fast_forward_inference(attention_fast_forward_inference = FalconH1Attention_fast_forward_inference,mlp_fast_forward_inference = fast_swiglu_inference,):- # This makes the attention and MLP customisable.- # Now for models like qwen3 or cohere which use custom attention operations, we can use this function+ # Makes attention and MLP customisable (e.g. qwen3/cohere custom attention).def FalconH1Model_fast_forward_inference_custom(self,input_ids,diff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex c3398d6554e..68b9ebe22f2 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -421,10 +421,9 @@ def Gemma2Attention_fast_forward_inference(Vnn = Vnn.reshape(bsz, n_heads, cached_len, head_dim)# Attention- # [TODO] Gemma2 uses manual matmul for all batch sizes because SDPA does- # not support softcapping (tanh logit scaling). If a future PyTorch adds- # a softcap param to scaled_dot_product_attention, consider using SDPA- # for bsz > 1 to match the llama/qwen3 pattern.+ # [TODO] Gemma2 uses manual matmul for all batch sizes since SDPA lacks+ # softcapping (tanh logit scaling). If PyTorch adds a softcap param to+ # SDPA, consider SDPA for bsz > 1 to match the llama/qwen3 pattern.Qn *= (self.scalar) # See https://github.com/ggerganov/llama.cpp/issues/7805#issuecomment-2153349963diff --git a/unsloth/models/glm4_moe.py b/unsloth/models/glm4_moe.pyindex e5fd88acbca..793a1beb06f 100644--- a/unsloth/models/glm4_moe.py+++ b/unsloth/models/glm4_moe.py@@ -42,22 +42,20 @@ import torch.nn.functional as Ffrom typing import Optional, Tuplefrom ..kernels import fast_rms_layernorm-# Import the grouped gemm utilities from unsloth kernels-# The grouped_gemm module expects its parent directory to be in sys.path+# grouped_gemm expects its parent dir on sys.pathHAS_GROUPED_GEMM = Falsetry:import sysimport os- # Add the moe directory (parent of grouped_gemm) to sys.path_moe_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "kernels", "moe")if _moe_path not in sys.path:sys.path.insert(0, _moe_path)- # Import grouped_gemm package first to apply TMA compatibility shim- # This patches triton.language to support both old and new TMA API names+ # Import first to apply the TMA compatibility shim (patches triton.language+ # for both old and new TMA API names)import grouped_gemm # noqa: F401 - triggers TMA compatibility shimfrom grouped_gemm.interface import grouped_gemm@@ -134,30 +132,23 @@ def Glm4MoeLiteMoE_fast_forward(self, hidden_states):batch_size, seq_len, hidden_dim = orig_shapenum_tokens = batch_size * seq_len- # Flatten hidden states for routinghidden_states = hidden_states.view(-1, hidden_dim)- # Router computationrouter_logits = self.gate(hidden_states) # [num_tokens, n_routed_experts]topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)- # Cast routing weights to match hidden_states dtype (Qwen3 pattern)- # Sigmoid router returns fp32, but hidden_states may be bf16+ # Sigmoid router returns fp32; cast weights to hidden_states dtype (e.g. bf16)topk_weights = topk_weights.to(hidden_states.dtype)- # Get routing indices for grouped GEMMwith torch.no_grad():token_counts_by_expert, gather_indices = get_routing_indices(topk_indices, self.n_routed_experts)- # Use grouped GEMM for expert computationif HAS_GROUPED_GEMM:- # Cast hidden_states to match expert weights dtype- # Under autocast, hidden_states may be fp32 while weights are bf16+ # Under autocast hidden_states may be fp32 while weights are bf16hidden_states = hidden_states.to(self.experts.gate_up_proj.dtype)- # First grouped GEMM: gate_up_proj with permute_x- # Input: [num_tokens, hidden_dim] -> Output: [total_tokens, 2*intermediate_dim]+ # gate_up_proj: [num_tokens, hidden_dim] -> [total_tokens, 2*intermediate_dim]intermediate = grouped_gemm(X = hidden_states,W = self.experts.gate_up_proj,@@ -174,8 +165,7 @@ def Glm4MoeLiteMoE_fast_forward(self, hidden_states):gate, up = intermediate.chunk(2, dim = -1)intermediate = torch_nn_functional_silu(gate) * up- # Second grouped GEMM: down_proj with permute_y- # Input: [total_tokens, intermediate_dim] -> Output: [total_tokens, hidden_dim]+ # down_proj: [total_tokens, intermediate_dim] -> [total_tokens, hidden_dim]expert_output = grouped_gemm(X = intermediate,W = self.experts.down_proj,@@ -193,7 +183,6 @@ def Glm4MoeLiteMoE_fast_forward(self, hidden_states):expert_output.view(num_tokens, self.top_k, hidden_dim) * topk_weights.unsqueeze(-1)).sum(dim = 1)else:- # Fallback to naive implementationhidden_states = self.experts(hidden_states, topk_indices, topk_weights)# Add shared expert output@@ -218,11 +207,9 @@ def Glm4MoeLiteNaiveMoe_fast_forward("""num_tokens, hidden_dim = hidden_states.shapetop_k = top_k_index.shape[1]- # Cast routing weights to match hidden_states dtype (Qwen3 pattern)top_k_weights = top_k_weights.to(hidden_states.dtype)if not HAS_GROUPED_GEMM:- # Fallback to original naive implementationfinal_hidden_states = torch.zeros_like(hidden_states)with torch.no_grad():expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes = self.num_experts)@@ -251,12 +238,10 @@ def Glm4MoeLiteNaiveMoe_fast_forward(return final_hidden_states- # Get routing indices for grouped GEMMwith torch.no_grad():token_counts_by_expert, gather_indices = get_routing_indices(top_k_index, self.num_experts)- # Cast hidden_states to match expert weights dtype- # Under autocast, hidden_states may be fp32 while weights are bf16+ # Under autocast hidden_states may be fp32 while weights are bf16hidden_states = hidden_states.to(self.gate_up_proj.dtype)# First grouped GEMM: gate_up_proj@@ -311,7 +296,6 @@ def Glm4MoeLiteDecoderLayer_fast_forward("""Optimized decoder layer forward with fast RMS layernorm."""- # Check if we're in inference modeis_inference = use_cache and hasattr(self, "_flag_for_generation")if is_inference:@@ -385,18 +369,15 @@ class FastGLM47Model(FastLlamaModel):"Please upgrade with: pip install --upgrade transformers")- # Patch MoE forward with grouped GEMM optimization- # TMA compatibility is handled by grouped_gemm/__init__.py which patches- # triton.language to support both old (_experimental_make_tensor_descriptor)- # and new (make_tensor_descriptor) API names+ # Patch MoE forward with grouped GEMM (TMA compat handled by+ # grouped_gemm/__init__.py)if HAS_GROUPED_GEMM:Glm4MoeLiteNaiveMoe.forward = Glm4MoeLiteNaiveMoe_fast_forwardGlm4MoeLiteMoE.forward = Glm4MoeLiteMoE_fast_forward- # Note: We don't patch the following for GLM4 MoE because:- # - GLM4 uses MLA (Multi-head Latent Attention) which has different projection names- # - Glm4MoeLiteRotaryEmbedding doesn't have extend_rope_embedding method- # - The decoder layer and model forward functions assume Llama-compatible infrastructure+ # Attention/rope/decoder/model forwards are NOT patched: GLM4 uses MLA+ # with different projection names and lacks extend_rope_embedding, so the+ # Llama-compatible infrastructure doesn't apply.return@@ -415,7 +396,7 @@ class FastGLM47Model(FastLlamaModel):trust_remote_code = False,**kwargs,):- # Pop kwargs that are used by loader but not passed to model+ # Used by loader, not passed to modelkwargs.pop("unsloth_force_compile", None)return FastLlamaModel.from_pretrained(diff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex 084dc7722f5..f5b0f57aa63 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -493,10 +493,9 @@ class GraniteRotaryEmbedding(LlamaRotaryEmbedding):def patched_init(original_init):def new_init(self, *args, **kwargs):- # we can use self.residual_multiplier arg in GraniteDecoderLayer_fast_forward as mentioned here+ # GraniteModel_fast_forward_inference can't reach residual_multiplier/config,+ # so stash the whole config here to pass it around. See:# https://github.com/huggingface/transformers/blob/e5fd865ebae062b7cf03a81b8c6affeb39f30bec/src/transformers/models/granite/modeling_granite.py#L243- # The problem is, we don't have access to either the value or config in GraniteModel_fast_forward_inference- # So we need a way to pass this value around. It is probably better to pass on entire config just in case we need it laterconfig = kwargs.get("config", args[0] if args else None)if config is not None:self.config = configdiff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 17d485f9f96..6018a4ccb4d 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -156,34 +156,13 @@ def _offload_frozen_module_for_training(device_type: str,offload_device: Optional[str] = "cpu",) -> None:- """- Offload frozen module to CPU and configure trainable copy for mixed precision training.-- This function optimizes memory usage by:- 1. Moving the trainable copy to the target device with appropriate precision- 2. Optionally offloading the original frozen module to CPU/disk to free VRAM- 3. Converting float16 to float32 for compatibility with certain GPUs (e.g., Tesla T4)+ """Move the trainable copy to ``device_type`` and offload the frozen original.- Args:- module: The module to configure. Must be a ModulesToSaveWrapper with a- `modules_to_save` attribute containing trainable and original modules.- device_type: Target device string for training (e.g., "cuda:0", "xpu:0")- offload_device: Device to offload frozen parameters (default: "cpu").- If None, the original frozen module remains on its current device.- Note: Currently only "cpu" is supported; disk offloading is planned.-- Returns:- None (modifies module in-place)-- Note:- - Float16 weights are automatically promoted to float32 for GPU compatibility- - When offload_device is specified, frozen parameters are moved to free VRAM- - Future versions will support disk-based offloading for even larger models-- See Also:- - https://github.com/unslothai/unsloth/pull/1200 (Tesla T4 float32 requirement)+ float16 is promoted to float32 for GPU compatibility (e.g. Tesla T4).+ ``offload_device`` currently only supports "cpu"; None leaves the frozen+ module in place. Modifies ``module`` in-place.+ See https://github.com/unslothai/unsloth/pull/1200 (Tesla T4 float32)."""- # Early return with explicit None if module doesn't support mixed precision trainingif not hasattr(module, "modules_to_save"):return None@@ -213,8 +192,7 @@ def _fast_prepare_inputs_for_generation(past_key_values = kwargs.get("past_key_values", None)original_attention_mask = attention_mask- # Handle inputs_embeds - only use on FIRST generation step (no cache)- # This fixes GitHub issue #3798: inputs_embeds was ignored+ # Only use inputs_embeds on the first step (no cache). Fixes issue #3798.use_inputs_embeds = inputs_embeds is not None and past_key_values is Noneif input_ids is not None and input_ids.numel() > 0:@@ -470,11 +448,10 @@ def LlamaAttention_fast_forward_inference(# Need to do it prior 2 steps before hitting full on short KV cache# or else error- # ensure correct shapeif position_ids.dim() == 1:position_ids = position_ids[:, None]- # Transformers 5.x generate() accumulates position_ids as [batch, full_seq_len]- # across decode steps. In single-token inference we only need the last position.+ # Transformers 5.x accumulates position_ids as [batch, full_seq_len] across+ # decode steps; single-token inference only needs the last position.if position_ids.shape[-1] > 1:position_ids = position_ids[:, -1:]position_ids = position_ids.to(Qn.device)@@ -1152,12 +1129,8 @@ def LlamaModel_fast_forward(IS_ATTENTION_REFACTORand (hasattr(self, "rotary_emb") or not hasattr(self.layers[0].self_attn, "rotary_emb"))) or IS_GRANITE:- # Transformers main has made it mandatory to pass position_embeddings- # https://github.com/huggingface/transformers/pull/34858- # Also, transformers 4.45.0 supports granite but with the attention refactor (it always had the refactor)- # unsloth's check for granite too has "version >= 4.45.0 (rightly so)".- # so let granite always use the attention refactor implementation.-+ # position_embeddings is mandatory on main: https://github.com/huggingface/transformers/pull/34858+ # granite always had the attention refactor, so let it always use this path.self.rotary_emb.extend_rope_embedding(hidden_states, self.config.max_position_embeddings)position_embeddings = self.rotary_emb.get_cached(self.config.max_position_embeddings, hidden_states.device.index@@ -1264,8 +1237,7 @@ def _LlamaModel_fast_forward_inference(attention_fast_forward_inference = LlamaAttention_fast_forward_inference,mlp_fast_forward_inference = fast_swiglu_inference,):- # This makes the attention and MLP customisable.- # Now for models like qwen3 or cohere which use custom attention operations, we can use this function+ # Makes attention and MLP customisable for models like qwen3/cohere.def LlamaModel_fast_forward_inference_custom(self,input_ids,@@ -1533,8 +1505,7 @@ def CausalLM_fast_forward(fast_forward_inference):logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)logit_scaling = getattr(self.config, "logit_scale", 0)if self.config.model_type == "granite":- # granite uses logit_scaling as key and they divide by the scale unlike cohere- # notice that for granite, logits_scale is 16 and for cohere it is 0.125 (aka 1/8) in their respective configs+ # granite divides by logits_scaling (16) unlike cohere which multiplies by 0.125.# granite: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/granite/modeling_granite.py#L1103# cohere: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/cohere/modeling_cohere.py#L1176logit_scaling = 1 / getattr(self.config, "logits_scaling", 1)@@ -2019,11 +1990,10 @@ class LongRopeRotaryEmbedding(torch.nn.Module):def unsloth_fast_generate(self, *args, **kwargs):- # If the model starts out in training mode, restore training mode after generation+ # Restore training mode after generation if we started in itrestore_training_mode = self.training- # why: snapshot the actual GC mode value (e.g. "unsloth") before for_inference- # clears it, so the post-generate restore preserves the caller's configured GC- # mode rather than collapsing it to a plain bool.+ # Snapshot the real GC mode (e.g. "unsloth") before for_inference clears it,+ # so the restore preserves it rather than collapsing to a plain bool.use_gradient_checkpointing = next((v for v in (getattr(m, "gradient_checkpointing", False) for m in self.modules()) if v),False,@@ -2031,11 +2001,9 @@ def unsloth_fast_generate(self, *args, **kwargs):FastLlamaModel.for_inference(self)- # Unpack BatchEncoding passed as input_ids for backwards compatibility.- # Old notebooks do model.generate(input_ids=tokenizer(...)) where the tokenizer- # output is a BatchEncoding (dict-like). Transformers v5 generate() calls- # .shape on it directly and crashes. Unpack into separate kwargs so both- # v4 and v5 work transparently.+ # Unpack BatchEncoding passed as input_ids (old notebooks do+ # generate(input_ids=tokenizer(...))). v5 generate() calls .shape on it and+ # crashes; unpack into separate kwargs so v4 and v5 both work._maybe_encoding = kwargs.get("input_ids", None)if (_maybe_encoding is not None@@ -2067,8 +2035,8 @@ def unsloth_fast_generate(self, *args, **kwargs):# For newer HFkwargs["cache_implementation"] = "dynamic"- # transformers 4.50 renamed num_logits_to_keep -> logits_to_keep.- # Pop both, re-emit under the spelling forward() accepts.+ # transformers 4.50 renamed num_logits_to_keep -> logits_to_keep; pop both,+ # re-emit under the spelling forward() accepts._provided_num = kwargs.pop("num_logits_to_keep", None)_provided_logits = kwargs.pop("logits_to_keep", None)_provided = _provided_logits if _provided_logits is not None else _provided_num@@ -2378,12 +2346,10 @@ class FastLlamaModel:bnb_4bit_compute_dtype = dtype,llm_int8_skip_modules = llm_int8_skip_modules,)- # For pre-quantized checkpoints (e.g. unsloth/Qwen3-4B-bnb-4bit),- # transformers uses the quantization_config baked into the- # checkpoint's config.json and ignores the runtime BitsAndBytesConfig- # we pass via kwargs. Merge our skip list into that bundled config- # so task heads like `score` (for *ForSequenceClassification) stay- # in the compute dtype. See unslothai/unsloth#5027.+ # Pre-quantized checkpoints (e.g. unsloth/Qwen3-4B-bnb-4bit) use the+ # quantization_config baked into config.json, ignoring our runtime+ # BitsAndBytesConfig. Merge our skip list into the bundled config so+ # task heads like `score` stay in compute dtype. See unslothai/unsloth#5027.if _ckpt_quant_method == "bitsandbytes" and _ckpt_qcfg is not None:if isinstance(_ckpt_qcfg, dict):_ckpt_skip = list(_ckpt_qcfg.get("llm_int8_skip_modules") or [])@@ -2436,10 +2402,8 @@ class FastLlamaModel:attn_implementation = preferred_attn_impl,**kwargs,)- # Defensive: make sure the task head ended up in a floating dtype.- # The primary protection is SKIP_QUANTIZATION_MODULES plus the skip- # list merge above; this guards against a downstream path accidentally- # leaving the head in an integer storage. See unslothai/unsloth#5027.+ # Defensive: ensure the task head is in a floating dtype, guarding+ # against any path leaving it as integer storage. See unslothai/unsloth#5027.for _head_name in ("score", "classifier", "qa_outputs"):_head = getattr(model, _head_name, None)if (@@ -2712,12 +2676,10 @@ class FastLlamaModel:model._old_generate = model.generateunsloth_fast_generate.__doc__ = model._old_generate.__doc__model.generate = types.MethodType(unsloth_fast_generate, model)- # Set weight[padding_idx] = 0 for embeddings that are NOT tied with the- # lm_head. When weights are tied, zeroing the padding row also zeros- # the corresponding lm_head row, forcing logit = 0 for the pad token.- # This is higher than the (negative) logits for real tokens in models- # like Gemma, causing the decoder to emit <pad> and produce gibberish.- # Skip entirely if eos_token == pad_token to avoid zeroing EOS embedding.+ # Zero weight[padding_idx] only for embeddings NOT tied to lm_head: when+ # tied, zeroing the row forces pad logit = 0, which beats the (negative)+ # logits of real tokens (e.g. Gemma) and makes the decoder emit <pad>.+ # Skip if eos_token == pad_token to avoid zeroing the EOS embedding.eos_token_id = getattr(tokenizer, "eos_token_id", None) if tokenizer is not None else Nonepad_token_id = getattr(tokenizer, "pad_token_id", None) if tokenizer is not None else Noneif tokenizer is not None and eos_token_id != pad_token_id:diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 34514e70130..b0ce28969e0 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -147,19 +147,11 @@ DISABLE_SDPA_MODEL_NAMES = [def _fix_rope_inv_freq(model):"""Fix inv_freq corruption caused by transformers v5 meta-device loading.- Transformers v5 initializes models on the meta device, then- _move_missing_keys_from_meta_to_device() (modeling_utils.py) replaces ALL- non-persistent buffers with torch.empty_like() -- uninitialized memory.-- Vanilla transformers restores inv_freq via _init_weights() which checks for- hasattr(module, "original_inv_freq"). Unsloth's LlamaRotaryEmbedding and- subclasses do not have this attribute, so inv_freq stays corrupted. This- produces wrong positional encodings and causes 5-11x higher training loss.-- This function recomputes inv_freq from the stored base and dim, applies- any model-specific scaling, and rebuilds the cos/sin caches.-- Only runs on transformers >= 5.0.0. No-op on v4.+ v5 inits on meta then replaces all non-persistent buffers with uninitialized+ memory. Vanilla restores inv_freq via _init_weights() (needs original_inv_freq),+ but Unsloth rotary classes lack that attr, so inv_freq stays corrupted -> wrong+ positional encodings and 5-11x higher training loss. Here we recompute inv_freq+ from base/dim, apply scaling, and rebuild cos/sin caches. No-op on v4."""if not _NEEDS_ROPE_FIX:return modeldiff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex d304bb454e6..98458ad3079 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -49,7 +49,7 @@ BAD_MAPPINGS = {def _get_torchao_fp8_config(fp8_mode):- # Import lazily so an optional, broken vLLM install does not break plain `import unsloth`.+ # Lazy import so a broken optional vLLM install doesn't break `import unsloth`.from unsloth_zoo.vllm_utils import _get_torchao_fp8_config as _implreturn _impl(fp8_mode)@@ -126,10 +126,8 @@ def __get_model_name(else:if lower_model_name in FLOAT_TO_FP8_BLOCK_MAPPER:return FLOAT_TO_FP8_BLOCK_MAPPER[lower_model_name]- # Mapper didn't find a pre-quantized model.- # For vllm >= 0.12.0, we can quantize the model to FP8 on the fly,- # so just return the original model name. Older vllm versions will- # fall through to offline quantization via _offline_quantize_to_fp8.+ # No pre-quantized model found. vllm >= 0.12.0 quantizes to FP8 on the+ # fly (return original name); older vllm falls through to offline quant.if importlib.util.find_spec("vllm") is not None:import vllmif Version(vllm.__version__) >= Version("0.12.0"):@@ -160,8 +158,7 @@ def __get_model_name(return new_model_nameelif load_in_4bit and SUPPORTS_FOURBIT and lower_model_name in FLOAT_TO_INT_MAPPER:- # Support returning original full -bnb-4bit name if specified specifically- # since we'll map it to the dynamic version instead+ # Keep an explicit -bnb-4bit name; otherwise map to the dynamic version.if lower_model_name.endswith("-bnb-4bit"):return model_name@@ -232,8 +229,7 @@ def get_model_name(float_to_int = FLOAT_TO_INT_MAPPER,map_to_unsloth_16bit = MAP_TO_UNSLOTH_16bit,)- # In the rare case, we convert bad model names to other names- # For eg too large dynamic quants or MoEs+ # Remap "bad" names (e.g. oversized dynamic quants or MoEs)if (new_model_name is not Noneand type(new_model_name) is str@@ -269,16 +265,10 @@ def get_model_name(def _offline_quantize_to_fp8(model_name: str, fp8_mode: str) -> str:- """- Quantizes the model to fp8 using torchao and saving the quantized model to a- temporary location. Return the path to the quantized model.-- Note: For vllm >= 0.12.0, we should dynamically quantize the model in vllm instead:+ """Quantize the model to fp8 via torchao, save to a temp dir, return its path.- llm = LLM(- ...- hf_overrides={"quantization_config_file": "torchao_config.json"},- )+ For vllm >= 0.12.0, prefer dynamic quantization in vllm instead (via+ hf_overrides={"quantization_config_file": "torchao_config.json"})."""temp_dir = tempfile.gettempdir()new_model_name = model_name.split("/")[-1] + "-fp8-" + fp8_mode@@ -322,9 +312,7 @@ def _offline_quantize_to_fp8(model_name: str, fp8_mode: str) -> str:def _tag_model_with_fp8_torchao_config(model: torch.nn.Module, fp8_mode: str):- """- Tag a model with a `TorchAOConfig` so downstream callers will know what to do with it.- """+ """Tag a model with a `TorchAOConfig` so downstream callers know how to handle it."""try:base_config = _get_torchao_fp8_config(fp8_mode)model.torchao_config = TorchAOConfig(@@ -384,16 +372,9 @@ def _get_fp8_mode_and_check_settings(load_in_8bit: bool = False,load_in_16bit: bool = False,) -> str:- """- Assuming `load_in_fp8` is enabled, raise appropriate errors on incompatible settings- and environment. Currently this feature requires:-- 1. H100 GPUs or after- 2. torchao 0.15.0+ (or nightly)- 3. torch 2.9.0+- 4. If fbgemm_gpu_genai is installed, require 1.4.1+-- Returns the fp8 mode, one of "row" or "block".+ """Validate `load_in_fp8` settings/environment and return the fp8 mode+ ("row" or "block"). Requires H100+, torchao 0.15.0+, torch 2.9.0+, and+ fbgemm_gpu_genai 1.4.1+ if installed."""assert load_in_fp8 is not Falseif load_in_fp8 is True:diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.pyindex cd6dd2ed1a6..74f7acbb03f 100644--- a/unsloth/models/mistral.py+++ b/unsloth/models/mistral.py@@ -179,13 +179,9 @@ def MistralForCausalLM_fast_forward(# If attention_mask exists, it will be handled in the attention forwardelif self.training:- # During training, LlamaModel_fast_forward's DPO embed-masking- # block requires a 2D attention_mask (it does- # inputs_embeds *= attention_mask.unsqueeze(0).transpose(0, 1).transpose(1, 2)).- # Afterwards, LlamaModel_fast_forward sets attention_mask=None- # before the attention layers anyway, so leaving the 2D mask- # untouched here is safe and avoids converting to 4D (which would- # crash the DPO block).+ # LlamaModel_fast_forward's DPO embed-masking block needs the 2D+ # attention_mask; it nulls the mask before attention anyway, so+ # leaving it 2D is safe and avoids a 4D conversion that crashes DPO.passelse:diff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.pyindex c515347b5bf..e28e72d3ea3 100644--- a/unsloth/models/qwen3.py+++ b/unsloth/models/qwen3.py@@ -103,10 +103,8 @@ def Qwen3Attention_fast_forward(V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)seq_info = get_packed_info_from_kwargs(kwargs, hidden_states.device)- # Qwen3 has QKNorm. This seems to be the only difference from Qwen2.- # Note that using fast_layernorm_compiled causes issues as the dimensions don't match up.- # I tried to add a compiled version of the new norm but the numbers don't match up with Transformers- # TODO: Check on the differences here.+ # Qwen3 adds QKNorm (the only difference from Qwen2). A compiled norm+ # mismatches Transformers' numbers, so use fast_rms_layernorm. TODO: investigate.Q = fast_rms_layernorm(self.q_norm, Q)K = fast_rms_layernorm(self.k_norm, K)@@ -180,33 +178,12 @@ def Qwen3Attention_fast_forward_inference(attention_mask = None,**kwargs,):- """- https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L406- Fast inference using KV cache.- QK^T can be computed in 4 chunks-- [Q, q] @ [K, k].T where q, k are the new tokens.- [QK^T, Qk^T]- [qK^T, qk^T]-- Since the attention mask wipes Qk^T, we just get- [QK^T, 0]- [qK^T, qk^T]-- Since softmax is row-wise, we get- softmax([QK^T, 0])- softmax([qK^T, qk^T])-- We then multiply by [V]- [v]- softmax([QK^T, 0]) [softmax(QK^T)V] *- softmax([qK^T, qk^T]) [softmax([qK^T, qk^T]) @ [V, v]]-- But notice * [softmax(QK^T)V] is just the last attention.- We just need to compute the last final row.+ """Fast inference using the KV cache.- This means we can pass in a row of Q, but we need to- remember K and V, which are called the KV cache.+ QK^T splits into 4 chunks; the mask zeroes Qk^T and softmax is row-wise, so+ softmax(QK^T)V is just the prior step's attention. We therefore only compute+ the final row: pass one row of Q while remembering K and V (the KV cache).+ Ref: https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L406"""Xn = hidden_statesbsz, _, hd = hidden_states.size()@@ -417,11 +394,8 @@ class FastQwen3Model(FastLlamaModel):PeftModelForCausalLM.forward = PeftModel_fast_forwardfix_prepare_inputs_for_generation(Qwen3ForCausalLM)- # Solves https://github.com/unslothai/unsloth/issues/168- # Static KV Cache was introduced in 4.38.0, causing training to be much slower.- # Inference can now be CUDAGraphed, but we shall retain the old rotary embeddings.- # https://github.com/huggingface/transformers/pull/27931- # https://github.com/huggingface/transformers/blob/v4.37.2/src/transformers/models/llama/modeling_llama.py+ # Retain old rotary embeddings; static KV cache (transformers 4.38.0)+ # slowed training. See unslothai/unsloth#168 and transformers#27931.import transformers.models.qwen3.modeling_qwen3transformers.models.qwen3.modeling_qwen3.Qwen3RotaryEmbedding = LlamaRotaryEmbeddingdiff --git a/unsloth/models/qwen3_moe.py b/unsloth/models/qwen3_moe.pyindex 8e692e46ea7..7a5dcbd889c 100644--- a/unsloth/models/qwen3_moe.py+++ b/unsloth/models/qwen3_moe.py@@ -67,31 +67,26 @@ def Qwen3MoeSparseMoeBlock_fast_forward(routing_weights = torch_nn_functional_softmax(router_logits, dim = -1, dtype = torch.float32)routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim = -1)routing_weights /= routing_weights.sum(dim = -1, keepdim = True)- # we cast back to the input dtype+ # cast back to the input dtyperouting_weights = routing_weights.to(X.dtype)final_X = torch.zeros((bsz * seq_len, hd), dtype = torch.float32, device = X.device)- # One hot encode the selected experts to create an expert mask- # this will be used to easily index which expert is going to be sollicitated+ # One-hot the selected experts into a mask to index which expert is usedexpert_mask = torch.nn.functional.one_hot(selected_experts, num_classes = self.num_experts).permute(2, 1, 0)- # Loop over all available experts in the model and perform the computation on each expertfor expert_idx in range(self.num_experts):expert_layer = self.experts[expert_idx]idx, top_x = torch.where(expert_mask[expert_idx])- # Index the correct hidden states and compute the expert hidden state for- # the current expert. We need to make sure to multiply the output hidden- # states by `routing_weights` on the corresponding tokens (top-1 and top-2)+ # Index hidden states for this expert and scale by routing_weightscurrent_state = X[None, top_x].reshape(-1, hd)current_X = (expert_layer(current_state) * routing_weights[top_x, idx, None]- ) # Qwen3MoeMLP.forward = fast_swiglu_inference takes care of making this faster. Analogous to Dense models' MLP+ ) # Qwen3MoeMLP.forward = fast_swiglu_inference speeds this up- # However `index_add_` only support torch tensors for indexing so we'll use- # the `top_x` tensor here.+ # index_add_ needs a tensor index, so use top_xfinal_X.index_add_(0, top_x, current_X.to(X.dtype))final_X = final_X.reshape(bsz, seq_len, hd)return final_X, router_logitsdiff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex a9d2a90b8af..5fb8cf6ddc2 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1643,13 +1643,11 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):flags = re.DOTALL,)- # Remove TRL's unconditional bfloat16 cast of trainable params (added in- # TRL 0.26.0). TRL hardcodes bfloat16 for QLoRA per the original paper's- # recommendation, but this is wrong: it ignores the user's requested dtype- # and breaks GradScaler when training with fp16=True. Unsloth already- # handles adapter dtype correctly via patch_model_and_tokenizer, so the- # entire block is unnecessary. For GRPOTrainer the enclosing peft init- # block is already removed above, making this a no-op for GRPO.+ # Remove TRL 0.26.0's unconditional bfloat16 cast of trainable params. It+ # hardcodes bfloat16 for QLoRA, ignoring the user's dtype and breaking+ # GradScaler with fp16=True. Unsloth already handles adapter dtype via+ # patch_model_and_tokenizer, so the block is unnecessary (and already a+ # no-op for GRPO, whose peft init block is removed above).RLTrainer_source = RLTrainer_source.replace('if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False):',"if False:",@@ -1664,13 +1662,11 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):)RLTrainer_source = RLTrainer_source.replace(original_text, new_text)- # Do NOT override _is_vlm -- let TRL detect VLM models naturally.- # In TRL 0.27.1+, forcing _is_vlm=False causes a ValueError when- # vision datasets are used with VLM models.- #- # However, some notebooks pass a bare tokenizer (processor.tokenizer) as- # processing_class. TRL then sets _is_vlm=False even for VLM models.- # Add a model-architecture-based override before the validation check.+ # Do NOT override _is_vlm -- let TRL detect VLM models naturally+ # (forcing _is_vlm=False errors on vision datasets in TRL 0.27.1+).+ # But some notebooks pass a bare tokenizer as processing_class, so TRL+ # sets _is_vlm=False even for VLMs; add an architecture-based override+ # before the validation check._vlm_check_original = (' self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample\n'" if self._is_vision_dataset and not self._is_vlm:"@@ -1689,13 +1685,11 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):if _vlm_check_original in RLTrainer_source:RLTrainer_source = RLTrainer_source.replace(_vlm_check_original, _vlm_check_patched)- # Fix TRL 0.22.x: VLM models with text-only datasets.- # TRL 0.22.x checks _is_vlm (model type) not _is_vision_dataset (dataset- # content, added in 0.25.1+). When _is_vlm=True, signature columns are- # vision-only ["messages","prompt","completion","images"], which have zero- # overlap with tokenized text columns. Fix: merge both column sets into the- # VLM branch. Extra columns not in the dataset are harmlessly ignored by- # _remove_unused_columns (it only raises when zero columns match).+ # Fix TRL 0.22.x: VLM models with text-only datasets. It checks _is_vlm+ # (model type), not _is_vision_dataset (added in 0.25.1+); with+ # _is_vlm=True the vision-only signature columns don't overlap tokenized+ # text columns. Fix: merge both column sets into the VLM branch. Extra+ # columns are ignored by _remove_unused_columns (raises only on zero match)._sig_vlm_old = 'self._signature_columns = ["messages", "prompt", "completion", "images"]'_sig_vlm_new = ('self._signature_columns = ["messages", "prompt", "completion", "images",'@@ -2161,26 +2155,15 @@ def patch_trl_rl_trainers():def patch_trl_disable_gradient_checkpointing():# TRL 1.0.0+ wraps generation in:# with torch.no_grad(), disable_gradient_checkpointing(self.model, ...):- # The toggle exists only to suppress a cosmetic PyTorch warning- # ("None of the inputs have requires_grad=True"). Inside torch.no_grad()- # the gradient checkpointing state has no functional effect on the- # forward pass.+ # The toggle only suppresses a cosmetic PyTorch warning; under no_grad it+ # has no functional effect. But on exit it calls+ # gradient_checkpointing_enable(), overwriting Unsloth's custom+ # "unsloth" wrapper -- for Gemma-4 this corrupts forward numerics and+ # blows GRPO KL divergence up to ~10^12 at step 1.#- # On exit, the context manager calls model.gradient_checkpointing_enable()- # which dispatches to HuggingFace's generic implementation and overwrites- # Unsloth's custom `use_gradient_checkpointing="unsloth"` wrapper. For- # Gemma-4 (and likely other models) this corrupts the forward numerics- # enough to make GRPO KL divergence explode to ~10^12 at step 1.- #- # Replacing the context manager with a no-op preserves Unsloth's custom- # gradient checkpointing wrapper across generation/inference passes.- #- # Backwards compatibility:- # - trl < 1.0.0 (no disable_gradient_checkpointing): early return.- # - trl >= 1.0.0: noop is functionally equivalent for forward- # correctness. The only loss is a cosmetic warning being emitted- # by PyTorch when use_reentrant=True (which is exactly the warning- # TRL added the toggle to suppress in the first place).+ # Replacing the context manager with a no-op preserves Unsloth's wrapper.+ # trl < 1.0.0 (no disable_gradient_checkpointing): early return.+ # trl >= 1.0.0: noop is correct; only loss is the cosmetic warning.try:import trl.models.utils as _tmuexcept ImportError:@@ -2203,12 +2186,9 @@ def patch_trl_disable_gradient_checkpointing():_tmu.disable_gradient_checkpointing = _noop_disable_gradient_checkpointing# Also rebind any trl.* module that already imported the symbol by- # reference, so the noop applies even when the trainer module cached the- # original at import time. We walk sys.modules dynamically rather than- # hardcoding a list, so this picks up every trainer that does- # `from ...models.utils import disable_gradient_checkpointing`- # (grpo, dpo, rloo, dppo, gfpo, grpo_with_replay_buffer, and any future- # TRL trainer module).+ # reference (cached at import time). Walk sys.modules dynamically so this+ # catches every trainer doing+ # `from ...models.utils import disable_gradient_checkpointing`.for _mod_name, _mod in list(sys.modules.items()):if _mod is None or not _mod_name.startswith("trl."):continue@@ -2272,12 +2252,10 @@ def PatchFastRL(algorithm = None, FastLanguageModel = None):if os.environ.get("UNSLOTH_ALLOW_CPU", "0") == "1":return# Install the disable_gradient_checkpointing noop BEFORE- # patch_trl_rl_trainers. patch_trl_rl_trainers imports extra trl.* trainer- # submodules while generating the compiled cache; any new trl.* modules- # imported after the sys.modules walk would keep their original (broken)- # binding of disable_gradient_checkpointing. Running the noop install- # first ensures the canonical trl.models.utils symbol is already replaced- # before those submodules bind it.+ # patch_trl_rl_trainers, which imports extra trl.* submodules; any module+ # imported after the sys.modules walk would keep the original broken+ # binding. Installing first ensures the canonical symbol is replaced before+ # those submodules bind it.patch_trl_disable_gradient_checkpointing()patch_trl_rl_trainers()patch_trl_openenv()diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex a42340f2829..7e43442bfd3 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -56,7 +56,6 @@ def _save_pretrained_torchao():self.save_pretrained(save_directory)- # grab inner modelinner_model = self[0].auto_modelif hasattr(inner_model, "_orig_mod"):inner_model = inner_model._orig_mod@@ -65,7 +64,6 @@ def _save_pretrained_torchao(if hasattr(inner_model, "merge_and_unload"):inner_model = inner_model.merge_and_unload()- # confirm Transformer pathtransformer_path = "0_Transformer"modules_path = os.path.join(save_directory, "modules.json")if os.path.exists(modules_path):@@ -96,7 +94,6 @@ def _save_pretrained_torchao(try:yieldfinally:- # unpatchtransformers.AutoModelForCausalLM = original_causalshutil.rmtree = original_rmtree@@ -116,7 +113,6 @@ def _save_pretrained_torchao(if not os.path.exists(transformer_dir):os.makedirs(transformer_dir, exist_ok = True)- # move contentsfor item in os.listdir(torchao_dir):s = os.path.join(torchao_dir, item)d = os.path.join(transformer_dir, item)@@ -125,7 +121,6 @@ def _save_pretrained_torchao(else:shutil.copy2(s, d)- # remove torchao dirshutil.rmtree(torchao_dir)# remove conflicting safetensors if we brought in bin@@ -164,14 +159,11 @@ def _save_pretrained_gguf(# 1. Save standard SentenceTransformer structure (configs, modules.json, etc.)self.save_pretrained(save_directory)- # 2. Extract inner transformer model+ # 2. Extract inner transformer model (PEFT merge handled by the gguf saver)inner_model = self[0].auto_modelif hasattr(inner_model, "_orig_mod"):inner_model = inner_model._orig_mod- # If it's a PEFT model, unsloth_save_pretrained_gguf handles merging,- # but we pass the inner model wrapper.-# 3. Identify where the transformer weights are storedtransformer_path = "0_Transformer"modules_path = os.path.join(save_directory, "modules.json")@@ -186,18 +178,17 @@ def _save_pretrained_gguf(except:pass- # This is where Unsloth will perform the save + conversion operations+ # Unsloth saves + converts here; absolute for later commonpath comparisontransformer_dir = os.path.join(save_directory, transformer_path)- # Ensure this path is absolute for consistent comparison latertransformer_dir = os.path.abspath(transformer_dir)if tokenizer is None:tokenizer = self.tokenizer- # 4. Patch environment to ensure Unsloth treats this embedding model correctly+ # 4. Patch environment so Unsloth treats this embedding model correctly@contextlib.contextmanagerdef patch_unsloth_gguf_save():- # Prevent deletion of the directory we just created via self.save_pretrained+ # Prevent deletion of the directory self.save_pretrained just createdoriginal_rmtree = shutil.rmtreetry:yield@@ -229,27 +220,24 @@ def _save_pretrained_gguf(filename = os.path.basename(gguf_file)dest_path = os.path.join(save_directory, filename)- # Convert to absolute path to avoid mixing relative/absolute in commonpathabs_gguf_file = os.path.abspath(gguf_file)- # Check if file is inside transformer_dir (subpath)try:is_subpath = os.path.commonpath([abs_gguf_file, transformer_dir]) == transformer_direxcept ValueError:- # Can happen on Windows with different drives, or mix of absolute/relative (handled by abspath above)+ # Windows different-drive commonpath raisesis_subpath = Falseif is_subpath:- # If the GGUF file is inside the transformer_dir, move it out to root+ # Move the GGUF out of transformer_dir to rootshutil.move(gguf_file, dest_path)new_gguf_locations.append(dest_path)else:- # If it's elsewhere, move it to root if not already there+ # Elsewhere: move to root if not already thereif os.path.abspath(dest_path) != abs_gguf_file:shutil.move(gguf_file, dest_path)new_gguf_locations.append(dest_path)- # Update result with new locationsresult["gguf_files"] = new_gguf_locations# 7. Add branding@@ -364,7 +352,6 @@ def _push_to_hub_gguf(api = HfApi(token = token)- # Determine full repo_idif "/" not in repo_id:username = api.whoami()["name"]full_repo_id = f"{username}/{repo_id}"@@ -373,7 +360,6 @@ def _push_to_hub_gguf(model_name = full_repo_id.split("/")[-1]- # Create repotry:api.create_repo(repo_id = full_repo_id,@@ -384,11 +370,10 @@ def _push_to_hub_gguf(except Exception as e:print(f"Unsloth Warning: Could not create repo: {e}")- # Save to temporary directory first+ # Convert locally in a temp dir, then uploadwith tempfile.TemporaryDirectory(prefix = "unsloth_st_gguf_") as temp_dir:print(f"Unsloth: Converting SentenceTransformer to GGUF format...")- # Call save_pretrained_gguf to do the local conversionresult = _save_pretrained_gguf(self,save_directory = temp_dir,@@ -522,12 +507,10 @@ This sentence-transformers model was finetuned and converted to GGUF format usinclass FastSentenceTransformer(FastModel):@staticmethoddef _save_base_config_for_processor_resume(config, output_path):- """- sentence-transformers >= 5.4 reloads Transformer modules through- AutoProcessor. Tokenizer-only checkpoint roots make AutoProcessor fall- back to AutoConfig, so PEFT adapter checkpoints still need the base- config.json next to adapter_config.json.- """+ """sentence-transformers >= 5.4 reloads Transformer modules via+ AutoProcessor, which falls back to AutoConfig for tokenizer-only+ roots -- so PEFT adapter checkpoints still need base config.json+ next to adapter_config.json."""if config is None or not getattr(config, "model_type", None):returnif hasattr(config, "save_pretrained"):@@ -559,9 +542,7 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _read_pooling_mode(model_name, token):- """- Read the pooling mode from the modules.json file if it exists, otherwise return "mean".- """+ """Read the pooling mode from modules.json, else return "mean"."""try:if os.path.exists(model_name) and os.path.exists(os.path.join(model_name, "modules.json")@@ -578,7 +559,7 @@ class FastSentenceTransformer(FastModel):if module.get("type", "") == "sentence_transformers.models.Pooling":pooling_path = module.get("path", "")if pooling_path:- # try to find config.json for pooling module+ # find config.json for the pooling moduleif os.path.exists(model_name) and os.path.exists(os.path.join(model_name, pooling_path, "config.json")):@@ -621,16 +602,11 @@ class FastSentenceTransformer(FastModel):# should prolly be done upstream instead of this hackfest here@staticmethoddef _patch_mpnet_v4():- """- Patch the MPNetModel to support gradient checkpointing.- Supports transformers 4.- """+ """Patch MPNetModel for gradient checkpointing (transformers 4)."""from transformers.models.mpnet import modeling_mpnet- # add supports_gradient_checkpointing flagmodeling_mpnet.MPNetModel.supports_gradient_checkpointing = True- # add _set_gradient_checkpointing methoddef _set_gradient_checkpointing(self,module = None,@@ -643,8 +619,7 @@ class FastSentenceTransformer(FastModel):modeling_mpnet.MPNetModel._set_gradient_checkpointing = _set_gradient_checkpointing- # patch MPNetEncoder.forward to support checkpointing- # based on:+ # patch MPNetEncoder.forward for checkpointing; based on:# https://github.com/huggingface/transformers/blob/v4.57.3/src/transformers/models/mpnet/modeling_mpnet.py#L321def forward(self,@@ -664,11 +639,9 @@ class FastSentenceTransformer(FastModel):if output_hidden_states:all_hidden_states = all_hidden_states + (hidden_states,)- # do gradient checkpointing if enabled and trainingif getattr(self, "gradient_checkpointing", False) and self.training:def create_custom_forward(module):- # bog standard checkpointdef custom_forward(*inputs):return module(*inputs, output_attentions = output_attentions)@@ -683,7 +656,6 @@ class FastSentenceTransformer(FastModel):use_reentrant = True, # fix for torch 2.9)else:- # original code from here onlayer_outputs = layer_module(hidden_states,attention_mask,@@ -711,21 +683,15 @@ class FastSentenceTransformer(FastModel):attentions = all_attentions,)- # assign the patched forwardmodeling_mpnet.MPNetEncoder.forward = forward@staticmethoddef _patch_mpnet_v5():- """- Patch the MPNetModel to support gradient checkpointing.- Supports transformers 5.- """+ """Patch MPNetModel for gradient checkpointing (transformers 5)."""from transformers.models.mpnet import modeling_mpnet- # add supports_gradient_checkpointing flagmodeling_mpnet.MPNetModel.supports_gradient_checkpointing = True- # add _set_gradient_checkpointing methoddef _set_gradient_checkpointing(self,module = None,@@ -738,8 +704,7 @@ class FastSentenceTransformer(FastModel):modeling_mpnet.MPNetModel._set_gradient_checkpointing = _set_gradient_checkpointing- # patch MPNetEncoder.forward to support checkpointing- # based on:+ # patch MPNetEncoder.forward for checkpointing; based on:# https://github.com/huggingface/transformers/blob/v5.0.0rc1/src/transformers/models/mpnet/modeling_mpnet.py#L284def forward(self,@@ -758,11 +723,9 @@ class FastSentenceTransformer(FastModel):if output_hidden_states:all_hidden_states = all_hidden_states + (hidden_states,)- # do gradient checkpointing if enabled and trainingif getattr(self, "gradient_checkpointing", False) and self.training:def create_custom_forward(module):- # checkpointdef custom_forward(*inputs):return module(*inputs, output_attentions = output_attentions)@@ -776,7 +739,6 @@ class FastSentenceTransformer(FastModel):use_reentrant = True, # required for torch >= 2.9)else:- # original code from here onlayer_outputs = layer_module(hidden_states,attention_mask,@@ -808,14 +770,10 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _patch_distilbert_v4():# change kwargs to positional args to be compatible with peft_utils- """- Patch the forward method of the DistilBertModel to use positional arguments instead of keyword arguments.- Transformers 4 version.- """+ """Patch DistilBertModel.forward to use positional args (transformers 4)."""# based on:# https://github.com/huggingface/transformers/blob/v4.57.3/src/transformers/models/distilbert/modeling_distilbert.py#L666- # original code from here on:def forward(self,input_ids: Optional[torch.Tensor] = None,@@ -853,7 +811,6 @@ class FastSentenceTransformer(FastModel):device = input_ids.device if input_ids is not None else inputs_embeds.devicehead_mask_is_none = head_mask is None- # Prepare head mask if neededhead_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)@@ -888,13 +845,10 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _has_add_pooling_layer(config, auto_model_class = None):- """- Checks if the model class supports the `add_pooling_layer` argument- """+ """Check if the model class accepts the `add_pooling_layer` argument."""try:if auto_model_class is None:auto_model_class = AutoModel- # try to resolve the classmodel_class = resolve_model_class(auto_model_class, config)if model_class:@@ -907,13 +861,9 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _patch_distilbert_v5():- """- Patch the forward method of the DistilBertModel to use positional arguments instead of keyword arguments.- Transformers 5 version.- """+ """Patch DistilBertModel.forward to use positional args (transformers 5)."""# based on:# https://github.com/huggingface/transformers/blob/v5.0.0rc1/src/transformers/models/distilbert/modeling_distilbert.py#L386- # original code from here on:from transformers.masking_utils import create_bidirectional_maskdef forward(@@ -950,9 +900,7 @@ class FastSentenceTransformer(FastModel):token,tags = None,):- """- Add Unsloth and sentence-transformers tags to the Hugging Face Hub repository.- """+ """Add Unsloth + sentence-transformers tags to the HF Hub repo."""from huggingface_hub import HfApiapi = HfApi(token = token)@@ -970,9 +918,7 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _add_unsloth_branding(save_directory):- """- Add Unsloth branding to the README.md file generated by sentence-transformers.- """+ """Add Unsloth branding to the sentence-transformers-generated README.md."""readme_path = os.path.join(save_directory, "README.md")if not os.path.exists(readme_path):return@@ -984,18 +930,16 @@ class FastSentenceTransformer(FastModel):if "---\ntags:\n" in content:content = content.replace("---\ntags:\n", "---\ntags:\n- unsloth\n")else:- # if tags exist but not right at start, use regex to append+ # tags exist but not at the start: append via regexpattern = r"(^tags:\s*\n)"if re.search(pattern, content, re.MULTILINE):content = re.sub(pattern, r"\1- unsloth\n", content, count = 1, flags = re.MULTILINE)- # add branding badge and textbranding = ("\n\nThis model was finetuned with [Unsloth](https://github.com/unslothai/unsloth).\n\n"'[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)\n')- # add to descriptionif "# SentenceTransformer" in content:parts = content.split("# SentenceTransformer", 1)content = parts[0] + "# SentenceTransformer" + branding + parts[1]@@ -1007,9 +951,7 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _module_path(model_name, token = None):- """- Returns the path to the modules.json file or None- """+ """Return the path to the modules.json file, or None."""try:if os.path.exists(model_name) and os.path.isdir(model_name):path = os.path.join(model_name, "modules.json")@@ -1027,13 +969,11 @@ class FastSentenceTransformer(FastModel):"""Helper to create and configure a Transformer module."""from sentence_transformers.models import Transformer- # prevents sentence-transformers from loading the model a second time, thanks Etherl- # Also redirect AutoProcessor / AutoTokenizer so the Transformer.__init__- # picks up our pre-fixed tokenizer. On sentence-transformers >=5.4 the- # `tokenizer` attribute became a read-only @property backed by `self.processor`,- # so a post-init assignment raises AttributeError; redirecting the constructor's- # AutoProcessor.from_pretrained call sets self.processor correctly and keeps- # downstream state (input_formatter) consistent.+ # Prevents loading the model a second time and redirects AutoProcessor/+ # AutoTokenizer so Transformer.__init__ picks up our pre-fixed tokenizer.+ # On sentence-transformers >=5.4 `tokenizer` is a read-only @property+ # backed by `self.processor`, so a post-init assignment raises; the+ # constructor redirect sets self.processor correctly instead.from transformers import AutoProcessor, AutoTokenizerdef is_requested_model_name(args, kwargs):@@ -1112,10 +1052,9 @@ class FastSentenceTransformer(FastModel):elif "tokenizer_args" in transformer_init_params:transformer_kwargs["tokenizer_args"] = trust_remote_code_kwargs.copy()- # Initialize Transformertransformer_module = Transformer(model_name, **transformer_kwargs)finally:- # Restore original functionality immediately+ # Restore original Auto* loading immediatelyAutoModel.from_pretrained = original_model_from_pretrainedAutoProcessor.from_pretrained = original_processor_from_pretrainedAutoTokenizer.from_pretrained = original_tokenizer_from_pretrained@@ -1197,8 +1136,7 @@ class FastSentenceTransformer(FastModel):pooling_mode,trust_remote_code = False,) -> tuple[OrderedDict, bool]:- """- Load modules from modules.json if available, otherwise fallback to hard-coded modules.+ """Load modules from modules.json, else fall back to hard-coded modules.Returns:tuple[OrderedDict, bool]: (modules, no_modules_json)@@ -1286,19 +1224,12 @@ class FastSentenceTransformer(FastModel):grad_accum = None,max_seq_length = None,):- """- Estimate the minimum training steps needed for torch.compile to be beneficial.- Returns the threshold with a 1.2x safety margin built in.+ """Estimate the minimum training steps for torch.compile to pay off+ (with a 1.2x safety margin), from empirical benchmarks.- Based on empirical benchmarks:- - Larger models have lower breakeven (more time saved per step)- - Warmup time scales with model size but speedup also increases-- Optional inputs (batch_size, grad_accum, max_seq_length) allow- a coarse pre-run adjustment. These are intentionally conservative- and avoid any runtime measurements.+ Optional batch_size / grad_accum / max_seq_length give a coarse,+ conservative pre-run adjustment with no runtime measurements."""- # Get parameter count from inner modelif hasattr(model, "__getitem__"):try:inner = model[0].auto_model@@ -1399,10 +1330,8 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _apply_torch_compile(model, mode = "default"):- """- Apply torch.compile to a SentenceTransformer model.- Includes workaround for accelerate's unwrap_model bug.- """+ """Apply torch.compile to a SentenceTransformer model (with an+ accelerate unwrap_model bug workaround)."""if hasattr(model, "__getitem__"):inner_model = model[0].auto_modelcompiled = torch.compile(inner_model, mode = mode)@@ -1465,12 +1394,10 @@ class FastSentenceTransformer(FastModel):):st_device = None- # this was added because when loading for inference it was defaulting to float32- # propagate dtype to model_kwargs, default to "auto"+ # Propagate dtype to model_kwargs (else inference defaults to float32)model_kwargs = kwargs.get("model_kwargs", {})model_kwargs["dtype"] = dtype if dtype is not None else "auto"- # filter kwargs for SentenceTransformerst_kwargs = {"device": st_device,"trust_remote_code": trust_remote_code,@@ -1479,7 +1406,6 @@ class FastSentenceTransformer(FastModel):"model_kwargs": model_kwargs,}- # add other known kwargs if presentknown_keys = ["cache_folder","truncate_dim",@@ -1694,7 +1620,7 @@ class FastSentenceTransformer(FastModel):if supported:kwargs["add_pooling_layer"] = False- # forces fp8 to be False since it's not supported+ # fp8 is not supported, force it offfp8 = kwargs.pop("load_in_fp8", None)if fp8:logging.info("Unsloth: Disabling fp8 for model")@@ -1718,9 +1644,8 @@ class FastSentenceTransformer(FastModel):elif is_mpnet:FastSentenceTransformer._patch_mpnet_v5()- # check if modules.json exists - if not, force 16-bit training- # why? because i have to implement saving myself for these models, and i don't feel like adding dequantization- # to the save_pretrained_merged for a model that really should be trained in 16-bit anyway+ # No modules.json -> force 16-bit: saving is custom for these models and+ # 4-bit would need dequant in save_pretrained_merged, not worth it.has_modules_json = FastSentenceTransformer._module_path(model_name, token) is not Noneif not has_modules_json and load_in_4bit:@@ -1762,7 +1687,6 @@ class FastSentenceTransformer(FastModel):finally:os.environ["UNSLOTH_WARN_UNINITIALIZED"] = old_environ- # try to load modules, otherwise fallback to old hard-coded modulesfrom sentence_transformers import SentenceTransformermodules, no_modules = FastSentenceTransformer._load_modules(diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 3e779a46b12..500c6509a40 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -299,7 +299,6 @@ def unsloth_base_fast_generate(self, *args, **kwargs):if do_bfloat16_mixed_precision:dtype = torch.bfloat16- # Check if VLMis_vlm = any(x.endswith(("ForConditionalGeneration", "ForVisionText2Text"))for x in self.config.architectures@@ -319,8 +318,7 @@ def unsloth_base_fast_generate(self, *args, **kwargs):global NUM_LOGITS_TO_KEEPif arch not in NUM_LOGITS_TO_KEEP:m = self- # Find which is needed ie- # num_logits_to_keep or logits_to_keep+ # Find which is used: num_logits_to_keep or logits_to_keepwhile hasattr(m, "model"):if hasattr(m, "forward"):keys = inspect.signature(m.forward).parameters.keys()@@ -337,7 +335,6 @@ def unsloth_base_fast_generate(self, *args, **kwargs):if key is not None and key not in kwargs:kwargs[key] = 1- # Check pad_tokenmodel_eos_token_id = getattr(self.config, "eos_token_id", None)if model_eos_token_id is not None and hasattr(model_eos_token_id, "__iter__"):model_eos_token_id = model_eos_token_id[0]@@ -424,7 +421,6 @@ def unsloth_base_fast_generate(self, *args, **kwargs):except:pass- # DO INFERENCEwith torch.inference_mode(), autocaster:output = self._old_generate(*args, **kwargs)diff --git a/unsloth/optimizers/q_galore_adamw.py b/unsloth/optimizers/q_galore_adamw.pyindex 1f4219d69af..9acd597f614 100644--- a/unsloth/optimizers/q_galore_adamw.py+++ b/unsloth/optimizers/q_galore_adamw.py@@ -34,7 +34,7 @@ try:_HAS_BNB = Trueexcept ImportError:_HAS_BNB = False- # Provide a fallback base so the module can at least be imported.+ # Fallback base so the module can still be imported.Optimizer2State = torch.optim.Optimizer@@ -99,10 +99,6 @@ class QGaLoreAdamW8bit(Optimizer2State):is_paged = is_paged,)- # ------------------------------------------------------------------- # Core step- # -------------------------------------------------------------------@torch.no_grad()def step(self, closure = None):"""Perform a single optimization step.@@ -173,8 +169,7 @@ class QGaLoreAdamW8bit(Optimizer2State):grad = state["projector"].project(p.grad, state["step"])- # Save current weight; replace p.data with zeros so- # the 8-bit update writes the pure weight delta.+ # Zero p.data so the 8-bit update writes the pure delta.p._saved_data = p.data.clone()p.data = torch.zeros_like(grad, dtype = p.data.dtype, device = p.data.device)p.grad = grad@@ -213,9 +208,9 @@ class QGaLoreAdamW8bit(Optimizer2State):p._q_scales = scalesp._q_zeros = zerosp._q_shape = shape- # Replace p.data with a scalar placeholder to free float memory.- # A forward pre-hook (install_weight_quant_hooks) will- # dequantize back to float before the next forward pass.+ # Scalar placeholder to free float memory; the forward+ # pre-hook (install_weight_quant_hooks) dequantizes before+ # the next forward pass.p.data = torch.empty(1, dtype = p.data.dtype, device = p.data.device)state["step"] += 1@@ -225,10 +220,6 @@ class QGaLoreAdamW8bit(Optimizer2State):return loss- # ------------------------------------------------------------------- # Helpers- # -------------------------------------------------------------------@staticmethoddef _has_weight_quant(p: torch.Tensor, group: dict) -> bool:"""Check if this parameter uses INT8 weight quantization."""@@ -260,10 +251,9 @@ class QGaLoreAdamW8bit(Optimizer2State):for name, p in model.named_parameters():if id(p) in weight_quant_params:- # Store quantization metadata WITHOUT converting weights to- # uint8. The first optimizer.step() will quantize after the- # update. We store dummy scales/zeros so _has_weight_quant()- # returns True on the first step.+ # Store metadata without converting weights to uint8; the first+ # step() quantizes after the update. Dummy scales/zeros keep+ # _has_weight_quant() True on the first step.p._q_scales = Nonep._q_zeros = Nonep._q_shape = p.data.shape@@ -298,10 +288,6 @@ def install_weight_quant_hooks(model: torch.nn.Module) -> list:return handles-# ======================================================================-# Param-group construction helper-# ======================================================================-# Default linear layer names in transformer blocks that should use GaLore._DEFAULT_GALORE_TARGETS = {"q_proj",@@ -369,9 +355,8 @@ def make_q_galore_param_groups(if not param.requires_grad:continue- # Check if any target module name appears as a component in the param name.- # Exclude 1-D parameters (biases, norms) because GaLoreProjector.project- # requires 2-D gradients.+ # Match target module names; exclude 1-D params (biases, norms) since+ # GaLoreProjector.project requires 2-D gradients.name_parts = name.split(".")is_galore = param.dim() >= 2 and any(t in name_parts for t in targets)diff --git a/unsloth/optimizers/q_galore_projector.py b/unsloth/optimizers/q_galore_projector.pyindex 809e15512cd..3fba75e5b39 100644--- a/unsloth/optimizers/q_galore_projector.py+++ b/unsloth/optimizers/q_galore_projector.py@@ -27,22 +27,16 @@ class GaLoreProjector:"""Low-rank gradient projector with optional INT4/INT8 quantized projectionmatrices and layer-adaptive subspace update scheduling.- The projector computes an SVD of the gradient to obtain an orthogonal basis- for the top-``rank`` subspace. Gradients are projected into this subspace- for the optimizer step, then projected back to full rank for the weight- update.-- Two key Q-GaLore innovations are implemented:-- 1. **Quantized projection matrices** — when ``quant=True``, the orthogonal- matrix is stored in INT4/INT8, reducing the memory cost of keeping the- projector state.-- 2. **Layer-adaptive update scheduling** — a rolling queue of cosine- similarities between consecutive orthogonal vectors is maintained. When- the average exceeds ``cos_threshold``, ``update_proj_gap`` is multiplied- by ``gamma_proj``, effectively reducing the frequency of expensive SVD- recomputations for layers whose subspace has stabilized.+ SVD of the gradient gives an orthogonal basis for the top-``rank`` subspace.+ Gradients are projected in for the optimizer step, then back to full rank for+ the weight update. Two Q-GaLore innovations:++ 1. Quantized projection matrices: with ``quant=True`` the orthogonal matrix+ is stored in INT4/INT8 to cut projector-state memory.+ 2. Layer-adaptive update scheduling: when the rolling-average cosine+ similarity of consecutive orthogonal vectors exceeds ``cos_threshold``,+ ``update_proj_gap`` is multiplied by ``gamma_proj`` to recompute SVD less+ often for stabilized layers.Args:rank: Target rank for the low-rank projection.diff --git a/unsloth/registry/__init__.py b/unsloth/registry/__init__.pyindex dede85329f0..6880f80f85f 100644--- a/unsloth/registry/__init__.py+++ b/unsloth/registry/__init__.py@@ -33,12 +33,9 @@ def search_models(search_pattern: str = None,) -> list[ModelInfo]:"""- Get model info from the registry.-- See registry.ModelInfo for more fields.-- If search_pattern is provided, the full model path will be matched against the pattern, where the model path is the model_id on huggingface hub.+ Get model info from the registry. See registry.ModelInfo for more fields.+ search_pattern is matched against the full model path (the HF hub model_id)."""if not _ARE_MODELS_REGISTERED:register_models()diff --git a/unsloth/registry/registry.py b/unsloth/registry/registry.pyindex 009223088c0..b6aa5038deb 100644--- a/unsloth/registry/registry.py+++ b/unsloth/registry/registry.py@@ -33,9 +33,7 @@ class ModelInfo:base_name: strversion: strsize: int- name: str = (- None # full model name, constructed from base_name, version, and size unless provided- )+ name: str = None # constructed from base_name, version, size unless providedis_multimodal: bool = Falseinstruct_tag: str = Nonequant_type: QuantType = None@@ -168,7 +166,7 @@ def _register_models(model_meta: ModelMeta, include_original_model: bool = False_quant_types = quant_typesfor quant_type in _quant_types:# NOTE: models registered with org="unsloth" and QUANT_TYPE.NONE are aliases of QUANT_TYPE.UNSLOTH- _org = "unsloth" # unsloth models -- these are all quantized versions of the original model+ _org = "unsloth" # quantized versions of the original modelregister_model(model_info_cls = model_info_cls,org = _org,diff --git a/unsloth/save.py b/unsloth/save.pyindex a44f186e407..4ff56cc4774 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -160,10 +160,8 @@ def _quantize_q2_k_l(n_threads: int,print_output: bool = True,):- # "Q2_K_L" is a Unsloth-side preset, not a native llama.cpp ftype. It- # maps to the `q2_k` ftype with `--output-tensor-type q8_0` and- # `--token-embedding-type q8_0` so the output/embedding tensors retain- # higher precision than a plain Q2_K quant.+ # "Q2_K_L" is an Unsloth preset, not a native llama.cpp ftype: q2_k with+ # output/token-embedding tensors kept at q8_0 for higher precision.command = [str(quantizer_location),"--output-tensor-type",@@ -1045,9 +1043,8 @@ def unsloth_save_model(# Check if pushing to an organizationif save_pretrained_settings["push_to_hub"] and (username != actual_username):print(f"Unsloth: Saving to organization with address {new_save_directory}")- # Pushing to organization!- # Sadly .save_pretrained doesn't work :(- # We first save it via .save_pretrained, then upload manually!+ # Pushing to organization: .save_pretrained doesn't work, so save+ # locally first then upload manually.save_pretrained_settings["save_directory"] = new_save_directorysave_pretrained_settings["push_to_hub"] = Falseinternal_model.save_pretrained(**save_pretrained_settings)@@ -2226,9 +2223,8 @@ def unsloth_save_pretrained_gguf(except Exception as e:raise RuntimeError(f"Failed to save/merge model: {e}")else:- # Non-PEFT model — checkpoint files already exist on disk.- # Point save_to_gguf at the original checkpoint path instead of- # re-saving to a temporary "model" subdirectory.+ # Non-PEFT model: checkpoint files already exist; point save_to_gguf+ # at the original path instead of re-saving to a temp subdir.original_path = getattr(self.config, "_name_or_path", None)if original_path and os.path.isdir(original_path):print(@@ -3004,10 +3000,8 @@ def unsloth_generic_save(elif save_method == "merged_4bit_forced":save_method = "merged_4bit"- # Full-finetuned models (no LoRA) cannot use merge_and_overwrite_lora- # since there are no adapters to merge. Fall back to save_pretrained.- # This mirrors the non-PeftModel handling in save_pretrained_torchao- # and the GGUF save path.+ # Full-finetuned models (no LoRA) have no adapters to merge, so fall back+ # to save_pretrained, mirroring the torchao and GGUF save paths._is_peft = isinstance(model, PeftModel)if not _is_peft:if not is_main_process:diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex 556b2e53e28..f454d5c5049 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -419,15 +419,13 @@ def fix_sentencepiece_tokenizer(def fix_sentencepiece_gguf(saved_location):"""- Fixes sentencepiece tokenizers which did not extend the vocabulary with- user defined tokens.- Inspiration from https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py-- Also fixes special tokens (e.g. Gemma 3's <start_of_turn>/<end_of_turn>) that are- already present in the sentencepiece model but are incorrectly typed as NORMAL instead- of CONTROL. This causes them to be written to GGUF with token_type=1 (NORMAL) instead- of token_type=3 (CONTROL), which breaks chat inference in llama.cpp since parse_special- only matches CONTROL tokens.+ Fix sentencepiece tokenizers that didn't extend the vocab with user-defined+ tokens. Inspired by llama.cpp's convert_hf_to_gguf.py.++ Also retypes special tokens (e.g. Gemma 3's <start_of_turn>/<end_of_turn>)+ that exist in the sentencepiece model but are typed NORMAL instead of CONTROL.+ NORMAL writes token_type=1 to GGUF, breaking llama.cpp chat inference since+ parse_special only matches CONTROL (type=3)."""from copy import deepcopyimport sys@@ -1436,9 +1434,8 @@ def check_tokenizer(def get_tokenizer_info(tokenizer) -> dict:"""Return a concise diagnostic summary of a tokenizer instance.- Collects key properties into a plain dict suitable for logging, debugging,- or displaying in the Unsloth Studio UI. All fields are safe to access —- missing attributes fall back to ``None`` rather than raising.+ Collects key properties into a JSON-safe dict for logging, debugging, or the+ Studio UI. Missing attributes fall back to ``None`` rather than raising.Example output::@@ -1459,11 +1456,10 @@ def get_tokenizer_info(tokenizer) -> dict:}Args:- tokenizer: Any HuggingFace ``PreTrainedTokenizer`` or- ``PreTrainedTokenizerFast`` instance.+ tokenizer: Any HuggingFace ``PreTrainedTokenizer(Fast)`` instance.Returns:- A ``dict`` of tokenizer properties. Safe to serialize to JSON.+ A ``dict`` of tokenizer properties."""return {"name_or_path": getattr(tokenizer, "name_or_path", None),diff --git a/unsloth/trainer.py b/unsloth/trainer.pyindex c5df9516df1..9b80b10705b 100644--- a/unsloth/trainer.py+++ b/unsloth/trainer.py@@ -268,20 +268,19 @@ class UnslothTrainer(SFTTrainer):# --- Split embedding params with custom LR (Fix #2) ---if embedding_lr is not None:- # Build a fast param->name lookup (O(N) instead of O(N*M))+ # Fast param->name lookup (O(N) instead of O(N*M))param_to_name = {id(p): name for name, p in self.model.named_parameters()}new_groups = []for group in param_groups:if "rank" in group:- # GaLore group — keep as-is (embeddings are never in here)+ # GaLore group: keep as-is (no embeddings here)new_groups.append(group)continue# Non-GaLore group: split out embedding paramsembed_params = []other_params = []for p in group["params"]:- # Check if this param belongs to a modules_to_save embeddingname = param_to_name.get(id(p))if name and name.endswith("modules_to_save.default.weight"):partial_name = name[: -len(".modules_to_save.default.weight")]@@ -312,7 +311,6 @@ class UnslothTrainer(SFTTrainer):eps = self.args.adam_epsilon,)- # Initialize INT8 weight quantization if enabledif config.weight_quant:QGaLoreAdamW8bit.init_weight_quantization(self.model,@@ -320,9 +318,8 @@ class UnslothTrainer(SFTTrainer):group_size = config.weight_group_size,stochastic = config.stochastic_round,)- # Forward pre-hooks dequantize INT8 weights to float before each- # forward pass, allowing the optimizer to free float weight memory- # between steps.+ # Pre-hooks dequantize INT8 weights to float before each forward,+ # letting the optimizer free float weight memory between steps.install_weight_quant_hooks(self.model)n_galore = sum(len(g["params"]) for g in param_groups if "rank" in g)@@ -341,9 +338,8 @@ class UnslothTrainer(SFTTrainer):def _resolve_trainer_params(trainer_class, init_fn):"""Resolve the real named parameters for a trainer __init__.- Some TRL trainers (e.g., ORPOTrainer in TRL 0.27.1) are thin wrappers- with only ``def __init__(self, *args, **kwargs)``. For those, walk the- MRO and return the first parent class that has real named parameters.+ Some TRL trainers are thin ``*args, **kwargs`` wrappers; for those, walk the+ MRO and return the first parent with real named parameters."""params = inspect.signature(init_fn).parametersnamed = {@@ -386,7 +382,7 @@ def _backwards_compatible_trainer(trainer_class, config_class):@wraps(original_init)def new_init(self, *args, **kwargs):- # All Trainer tokenizer are now called processing_class+ # tokenizer is now processing_classtrainer_params = _resolve_trainer_params(trainer_class, original_init)if "processing_class" in trainer_params and "tokenizer" in kwargs:@@ -395,23 +391,21 @@ def _backwards_compatible_trainer(trainer_class, config_class):if ("args" in kwargs) and (Version(trl) >= Version("0.13.0.dev0")):training_args = kwargs.pop("args", None)- # Get parameters that Trainer.__init__ actually expectstrainer_params.remove("self")trainer_params.remove("args")- # Get fields that should be passed to Config init+ # Fields that should be passed to Config initconfig_fields = {field.name: field for field in dataclasses.fields(config_class) if field.init}- # Create config dict with valid fields from training_argsconfig_dict = {name: getattr(training_args, name)for name in config_fieldsif hasattr(training_args, name)}- # Get parameters that exist in Config but not in TrainingArguments+ # Params in Config but not in TrainingArgumentsfrom transformers import TrainingArgumentsmoved_params = set(inspect.signature(config_class).parameters.keys()) - set(@@ -430,14 +424,11 @@ def _backwards_compatible_trainer(trainer_class, config_class):else:additional_config_kwargs[key] = value- # Update config_dict with additional kwargsconfig_dict.update(additional_config_kwargs)- # Create Config with all the collected parameters- # Reinitialising config class with parameters (that were none initially but populated on first init)- # causes the 2nd init to fail as there are mutual exclusive checks on pairs of parameters.- # Refer: https://github.com/huggingface/trl/blob/main/trl/trainer/grpo_config.py#L499-L502 for example- # So we only create config class if the previous init was not TrainingArguments+ # Only build the config if the previous init wasn't TrainingArguments:+ # reinitialising it would re-trigger mutually-exclusive param checks.+ # See https://github.com/huggingface/trl/blob/main/trl/trainer/grpo_config.py#L499-L502if not isinstance(training_args, TrainingArguments):config = config_class(**config_dict)else:@@ -468,7 +459,6 @@ def _patch_sft_trainer_auto_packing(trl_module):else:config_arg = kwargs.get("args")- # Check if model type is unsupported for padding_freemodel = kwargs.get("model")is_unsupported_model = Falseis_vlm = False@@ -476,10 +466,8 @@ def _patch_sft_trainer_auto_packing(trl_module):model_config = getattr(model, "config", None)if model_config is not None:model_types = get_transformers_model_type(model_config)- # Blocklist: models that don't work correctly with padding_freeis_unsupported_model = any(x in PADDING_FREE_BLOCKLIST for x in model_types)- # Check if VLMarchitectures = getattr(model_config, "architectures", None)if architectures is None:architectures = []@@ -489,7 +477,7 @@ def _patch_sft_trainer_auto_packing(trl_module):processing_class = kwargs.get("processing_class") or kwargs.get("tokenizer")data_collator = kwargs.get("data_collator")- # We also disable vision language models for padding free collators+ # Disable padding-free for VLMs / custom collators / blocklisted modelsblocked = ((data_collator is not None)or isinstance(processing_class, ProcessorMixin)diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex 8f10d7570a5..3ff581b7fcd 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -56,11 +56,9 @@ class AttentionConfig:"""Per-layer attention metadata.- NOTE(djsaunde): I had originally intended this to be populated once per layer, but- we're currently constructing it on every forward pass since it can possibly be- invalid from one forward pass to the next (e.g., switching from training to- inference). For now, I'm keeping separate from AttentionContext for the sake of- better grouping of params.+ NOTE(djsaunde): Constructed on every forward pass (not once per layer) since+ it can be invalid across passes (e.g. switching training/inference). Kept+ separate from AttentionContext to group params."""backend: str@@ -107,25 +105,18 @@ def run_attention("""Run attention using config / context info.- Backend choice is prioritized for speed: FlashAttention when installed- (`flash_varlen` for packed/variable-length inputs with `seq_info`, otherwise dense- flash), then xFormers if flash is unavailable, with PyTorch SDPA as the final- fallback (e.g., CPU or no fused kernels).-- Varlen flash is preferred when packing metadata is present because it avoids padding- and keeps peak memory low. xFormers and SDPA can also handle packed batches (we- pass a block-diagonal mask into each).+ Backend priority (speed): FlashAttention if installed (varlen for packed+ inputs with `seq_info`, else dense), then xFormers, then SDPA as fallback.+ Varlen flash is preferred for packed batches as it avoids padding; xFormers+ and SDPA handle packing via a block-diagonal mask."""backend = config.backendif backend == FLASH_VARLEN and context.seq_info is None:backend = FLASH_DENSE if HAS_FLASH_ATTENTION else SDPA- # [TODO] Flash attention does not support arbitrary attention masks (only- # causal via flag). When a padding mask is present (e.g. left-padded- # batched generation), fall back to SDPA which consumes attn_mask.- # xFormers also does not thread context.attention_mask through, so the- # same fallback applies.+ # [TODO] Flash/xFormers don't support arbitrary attn masks; with a padding+ # mask present (e.g. left-padded generation), fall back to SDPA.if context.attention_mask is not None and backend in (FLASH_DENSE,FLASH_VARLEN,diff --git a/unsloth/utils/hf_hub.py b/unsloth/utils/hf_hub.pyindex e3960ba0ce2..b349e568f60 100644--- a/unsloth/utils/hf_hub.py+++ b/unsloth/utils/hf_hub.py@@ -30,9 +30,8 @@ def get_model_info("""Get the model info for a specific model.- properties: list[str] = See https://huggingface.co/docs/huggingface_hub/api-ref/hf_hub/hf_api/model_info- Default properties: ["safetensors", "lastModified"], only retrieves minimal information.- Set to None to retrieve the full model information.+ properties: see https://huggingface.co/docs/huggingface_hub/api-ref/hf_hub/hf_api/model_info+ Defaults to minimal info; set to None for the full model information."""global _HFAPIif _HFAPI is None:@@ -56,12 +55,9 @@ def list_models("""Retrieve model information from the Hugging Face Hub.- properties: list[str] = See https://huggingface.co/docs/huggingface_hub/api-ref/hf_hub/hf_api/list_models- full: bool = Whether to retrieve the full model information, if True properties will be ignored.- sort: str = The sort order.- author: str = The author of the model.- search: str = The search query for filtering models.-+ properties: see https://huggingface.co/docs/huggingface_hub/api-ref/hf_hub/hf_api/list_models+ full: retrieve full model info; if True, properties is ignored.+ sort/author/search: sort order, model author, and search filter."""global _HFAPIif _HFAPI is None:diff --git a/unsloth_cli/_tool_policy.py b/unsloth_cli/_tool_policy.pyindex 5dd6c70d9f2..58caacbff03 100644--- a/unsloth_cli/_tool_policy.py+++ b/unsloth_cli/_tool_policy.py@@ -10,12 +10,10 @@ from typing import Callable, Optionalimport typer-# Claude Code brand orange — used so the security warning stands out-# in a crowded terminal.+# Orange so the security warning stands out in a crowded terminal._PROMPT_FG = (217, 119, 87)-# Loopback aliases. Any other bind address (0.0.0.0, ::, a specific-# LAN IP, a hostname, ...) is treated as network-reachable.+# Loopback aliases; any other bind address is treated as network-reachable._LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})@@ -47,14 +45,11 @@ def resolve_tool_policy("""Return the resolved server-side tool policy.Args:- host: The bind address (e.g. "127.0.0.1", "0.0.0.0", or a- specific network IP).- flag: Tri-state from `--enable-tools/--disable-tools`- (None when neither was passed).- yes: True if the operator passed `--yes/-y`.- silent: True if the operator passed `--silent/-q`.- prompt: Callable used for the network-bind + on confirmation- (injected for testability; defaults to ``typer.confirm``).+ host: The bind address.+ flag: Tri-state from `--enable-tools/--disable-tools` (None if neither passed).+ yes: True if `--yes/-y` was passed.+ silent: True if `--silent/-q` was passed.+ prompt: Confirmation callable (injected for testability).Raises:typer.Exit: when the operator declines the confirmation.diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex b889a1e3bc9..a458f195b41 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -738,11 +738,10 @@ def _split_repo_variant(model_arg: str) -> tuple[str, Optional[str]]:def _expand_attached_np_short() -> None:- # Click clusters `-np8` as `-n -p 8` (-p = --port), dropping the- # parallel value. Split to `-np <N>` so typer's alias matches.- # Stops at `--`; accepts signed and digit-prefix-junk forms so- # typer can report a clean error against `-np`. Kept in lockstep- # with the backend `_flag_name` recogniser.+ # Click clusters `-np8` as `-n -p 8` (-p = --port), dropping the parallel+ # value. Split to `-np <N>` so typer's alias matches. Stops at `--`;+ # accepts signed/junk forms so typer reports a clean error against `-np`.+ # Kept in lockstep with the backend `_flag_name` recogniser.i = 0while i < len(sys.argv):tok = sys.argv[i]@@ -1210,14 +1209,10 @@ def _run_setup_script(*, verbose: bool = False) -> None:powershell_args.extend(["-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden"])- # Use -Command + `*>&1` instead of -File so setup.ps1's- # Write-Host output (PowerShell Information stream / #6) is- # merged into the success stream and reaches the parent's- # stdout. With -File, Information stream output is dropped- # whenever stdout is a pipe, which is exactly the situation- # CI hits with `unsloth studio update --local 2>&1 | tee- # logs/update.log`. Single-quote escaping handles paths that- # contain apostrophes.+ # Use -Command + `*>&1` (not -File) so setup.ps1's Write-Host output+ # (Information stream #6) merges into stdout. -File drops it when+ # stdout is a pipe, e.g. `unsloth studio update --local 2>&1 | tee`.+ # Single-quote escaping handles paths containing apostrophes.script_pwsh_literal = str(script).replace("'", "''")powershell_args.extend([@@ -1227,20 +1222,13 @@ def _run_setup_script(*, verbose: bool = False) -> None:f"& '{script_pwsh_literal}' *>&1",])- # Explicitly hand stdin/stdout/stderr to the child so the- # CI tee actually sees setup.ps1's output. Without this,- # subprocess.run on Windows uses close_fds=True (default,- # since Python 3.7) which sets bInheritHandles=False on- # CreateProcess. With CREATE_NO_WINDOW also set (via- # _windows_hidden_subprocess_kwargs in non-TTY runs), the- # child has neither a console nor any inherited std- # handles, so PowerShell's Write-Host -- and even- # [Console]::Out.WriteLine -- writes to nothing. Passing- # stdout=sys.stdout / stderr=sys.stderr makes Python set up- # PROC_THREAD_ATTRIBUTE_HANDLE_LIST with the std handles- # explicitly inheritable, which works alongside- # CREATE_NO_WINDOW. Empty update.log on the windows-latest- # CI was the smoking gun (run 25533694490 and 25534292239).+ # Explicitly hand std handles to the child so CI tee sees setup.ps1's+ # output. On Windows, subprocess.run defaults to close_fds=True+ # (bInheritHandles=False); combined with CREATE_NO_WINDOW the child+ # has no console and no inherited handles, so Write-Host writes to+ # nothing. Passing stdout/stderr makes Python mark the std handles+ # inheritable via PROC_THREAD_ATTRIBUTE_HANDLE_LIST. Empty update.log+ # on windows-latest CI was the smoking gun (runs 25533694490/25534292239).result = subprocess.run(powershell_args,env = env,diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.pyindex 88a95946392..9d47a574d5b 100644--- a/unsloth_cli/commands/train.py+++ b/unsloth_cli/commands/train.py@@ -41,8 +41,8 @@ def train(cfg.apply_overrides(**config_overrides)- # CLI/env tokens take precedence over config- # Handle case where typer.Option isn't resolved (decorator interaction)+ # CLI/env tokens take precedence; guard against unresolved typer.Option+ # (decorator interaction)from typer.models import OptionInfoif isinstance(hf_token, OptionInfo):@@ -68,7 +68,7 @@ def train(typer.echo("Error: provide --dataset or --local-dataset (or via --config)", err = True)raise typer.Exit(code = 2)- # Check if the model path is a LoRA adapter (has adapter_config.json)+ # A LoRA adapter dir has adapter_config.jsonmodel_path = Path(cfg.model) if cfg.model else Nonemodel_is_lora = (model_path and model_path.is_dir() and (model_path / "adapter_config.json").exists()diff --git a/unsloth_cli/config.py b/unsloth_cli/config.pyindex 3cfa87ec6d8..8192f7d7497 100644--- a/unsloth_cli/config.py+++ b/unsloth_cli/config.py@@ -78,9 +78,8 @@ class Config(BaseModel):def model_kwargs(self, use_lora: bool, is_vision: bool) -> dict:"""Return kwargs for trainer.prepare_model_for_training()."""- # Determine target modules based on model typeif use_lora and is_vision:- # Vision models expect a string (e.g., "all-linear"); fall back to None to use trainer defaults+ # Vision models expect a string (e.g. "all-linear"); None uses trainer defaultstarget_modules = "all-linear" if self.lora.vision_all_linear else Noneelse:parsed = [diff --git a/unsloth_cli/options.py b/unsloth_cli/options.pyindex 4a2470ac009..03c7540faad 100644--- a/unsloth_cli/options.py+++ b/unsloth_cli/options.py@@ -49,7 +49,7 @@ def _get_python_type(annotation: Any) -> type:def _collect_config_fields(config_class: type[BaseModel]) -> list[tuple[str, Any]]:"""- Collect all fields from a config class, flattening nested models. Returns list of+ Flatten config class fields (recursing into nested models) into a list of(name, field_info) tuples. Raises ValueError on duplicate field names."""fields = []@@ -57,7 +57,7 @@ def _collect_config_fields(config_class: type[BaseModel]) -> list[tuple[str, Anyfor name, field_info in config_class.model_fields.items():annotation = field_info.annotation- # Skip nested models - recurse into them+ # Recurse into nested modelsif isinstance(annotation, type) and issubclass(annotation, BaseModel):for nested_name, nested_field in annotation.model_fields.items():if nested_name in seen_names:diff --git a/unsloth_cli/tests/test_studio_run_short_alias_clashes.py b/unsloth_cli/tests/test_studio_run_short_alias_clashes.pyindex 2fb94c37c7b..4234eb75f40 100644--- a/unsloth_cli/tests/test_studio_run_short_alias_clashes.py+++ b/unsloth_cli/tests/test_studio_run_short_alias_clashes.py@@ -162,8 +162,7 @@ def test_previously_broken_short_flag_now_passes_through(monkeypatch, flag, valudef test_dash_hf_documented_alias_still_works(monkeypatch):- """`-hf` is documented and must keep working (multi-char shorts- don't cluster in Click)."""+ """`-hf` must keep working: multi-char shorts don't cluster in Click."""captured = _invoke(monkeypatch,["-hf", "unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL"],@@ -206,8 +205,7 @@ def test_legacy_frontend_alias_still_promotes_to_frontend(monkeypatch):captured = _invoke(monkeypatch, ["--model", "X", "-f", "/tmp/dist"])assert len(captured) == 1argv = captured[0]- # Compare via Path so Windows's str(Path("/tmp/dist")) = "\tmp\dist"- # doesn't trip the assertion on the same logical path.+ # Compare via Path: on Windows str(Path("/tmp/dist")) = "\tmp\dist".assert Path(argv[argv.index("--frontend") + 1]) == Path("/tmp/dist"), argvassert "-f" not in argv, f"-f leaked into child argv: {argv}"