From 8292e699e4d4c3d8f079b4cdd695fe7c2e282d32 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 8 Jun 2026 23:07:28 -0700 Subject: [PATCH] Studio: make code comments and docstrings more succinct (#6029) Trim and tighten code comments and docstrings across studio/ Python. Comment-only: every changed file verified code-identical to main via AST/token comparison. --- studio/backend/_platform_compat.py | 26 +- studio/backend/auth/__init__.py | 4 +- studio/backend/auth/authentication.py | 14 +- studio/backend/auth/storage.py | 85 +- studio/backend/colab.py | 63 +- studio/backend/core/__init__.py | 14 +- studio/backend/core/_torchao_stub.py | 38 +- .../backend/core/data_recipe/huggingface.py | 4 +- .../backend/core/data_recipe/jobs/manager.py | 12 +- studio/backend/core/data_recipe/jobs/parse.py | 4 +- studio/backend/core/data_recipe/jobs/types.py | 4 +- .../backend/core/data_recipe/jobs/worker.py | 9 +- studio/backend/core/data_recipe/service.py | 13 +- studio/backend/core/export/__init__.py | 4 +- studio/backend/core/export/export.py | 73 +- studio/backend/core/export/orchestrator.py | 138 +- studio/backend/core/export/worker.py | 110 +- studio/backend/core/inference/__init__.py | 8 +- studio/backend/core/inference/_html_to_md.py | 62 +- .../core/inference/anthropic_compat.py | 38 +- studio/backend/core/inference/audio_codecs.py | 28 +- .../core/inference/chat_template_helpers.py | 4 +- .../core/inference/external_provider.py | 1935 ++++++++--------- studio/backend/core/inference/inference.py | 340 ++- studio/backend/core/inference/key_exchange.py | 24 +- studio/backend/core/inference/llama_cpp.py | 1356 ++++++------ .../core/inference/llama_server_args.py | 91 +- studio/backend/core/inference/mcp_client.py | 55 +- .../backend/core/inference/mlx_inference.py | 71 +- studio/backend/core/inference/orchestrator.py | 189 +- studio/backend/core/inference/pricing.py | 85 +- studio/backend/core/inference/providers.py | 121 +- .../core/inference/safetensors_agentic.py | 73 +- .../core/inference/tool_call_parser.py | 24 +- studio/backend/core/inference/tools.py | 252 +-- studio/backend/core/inference/worker.py | 120 +- studio/backend/core/tool_healing.py | 53 +- studio/backend/core/training/__init__.py | 4 +- studio/backend/core/training/trainer.py | 422 ++-- studio/backend/core/training/training.py | 64 +- studio/backend/core/training/worker.py | 398 ++-- studio/backend/loggers/config.py | 24 +- studio/backend/loggers/handlers.py | 21 +- studio/backend/main.py | 185 +- studio/backend/models/__init__.py | 4 +- studio/backend/models/auth.py | 4 +- studio/backend/models/data_recipe.py | 4 +- studio/backend/models/datasets.py | 4 +- studio/backend/models/export.py | 4 +- studio/backend/models/inference.py | 181 +- studio/backend/models/models.py | 6 +- studio/backend/models/providers.py | 4 +- studio/backend/models/responses.py | 6 +- studio/backend/models/training.py | 4 +- studio/backend/models/users.py | 5 +- .../__init__.py | 2 +- .../data_designer_github_repo_seed/impl.py | 17 +- .../data_designer_github_repo_seed/scraper.py | 11 +- .../scraper_impl/gh_client.py | 22 +- .../scraper_impl/queries.py | 6 +- .../scraper_impl/scraper.py | 14 +- .../scraper_impl/state_store.py | 2 +- .../chunking.py | 6 +- .../requirements/single-env/patch_metadata.py | 4 +- studio/backend/routes/auth.py | 44 +- studio/backend/routes/chat_history.py | 24 +- studio/backend/routes/data_recipe/jobs.py | 164 +- studio/backend/routes/data_recipe/seed.py | 4 +- studio/backend/routes/data_recipe/validate.py | 18 +- studio/backend/routes/datasets.py | 78 +- studio/backend/routes/export.py | 106 +- studio/backend/routes/inference.py | 1199 +++++----- studio/backend/routes/mcp_servers.py | 28 +- studio/backend/routes/models.py | 487 ++--- studio/backend/routes/providers.py | 59 +- studio/backend/routes/training.py | 74 +- studio/backend/run.py | 266 ++- studio/backend/startup_banner.py | 10 +- studio/backend/storage/mcp_servers_db.py | 2 +- studio/backend/storage/providers_db.py | 6 +- studio/backend/storage/studio_db.py | 65 +- studio/backend/tests/conftest.py | 42 +- .../backend/tests/test_anthropic_cache_ttl.py | 32 +- .../backend/tests/test_anthropic_citations.py | 9 +- .../tests/test_anthropic_citations_edge.py | 77 +- .../tests/test_anthropic_code_execution.py | 44 +- .../tests/test_anthropic_compaction.py | 86 +- .../test_anthropic_fast_mode_and_refusal.py | 16 +- .../tests/test_anthropic_fast_mode_edge.py | 17 +- .../backend/tests/test_anthropic_messages.py | 45 +- .../test_anthropic_thinking_translation.py | 45 +- .../tests/test_anthropic_tool_versions.py | 27 +- .../backend/tests/test_anthropic_web_fetch.py | 60 +- .../tests/test_audio_token_detection.py | 7 +- .../tests/test_browse_folders_route.py | 3 +- .../tests/test_cache_case_resolution.py | 4 +- .../backend/tests/test_cached_gguf_routes.py | 32 +- .../tests/test_chat_history_storage.py | 10 +- .../test_cleanup_cancelled_checkpoints.py | 10 +- studio/backend/tests/test_cpu_threads.py | 4 +- studio/backend/tests/test_desktop_auth.py | 14 +- .../backend/tests/test_detect_mmproj_file.py | 2 +- .../backend/tests/test_export_log_cursor.py | 78 +- .../test_external_provider_usage_chunk.py | 27 +- .../backend/tests/test_frontend_resolution.py | 35 +- studio/backend/tests/test_gemini_provider.py | 841 ++++--- studio/backend/tests/test_gguf_metadata.py | 6 +- .../tests/test_gguf_reload_inheritance.py | 9 +- studio/backend/tests/test_gguf_routing.py | 17 +- studio/backend/tests/test_gpu_selection.py | 4 +- .../tests/test_gpu_selection_sandbox.py | 32 +- studio/backend/tests/test_host_defaults.py | 18 +- .../tests/test_index_bootstrap_origin.py | 9 +- .../test_index_bootstrap_origin_extra.py | 34 +- .../tests/test_inference_model_validation.py | 7 +- .../backend/tests/test_kv_cache_estimation.py | 194 +- .../test_lemonade_llamacpp_rocm_bins_mock.py | 43 +- .../test_llama_cpp_cache_aware_disk_check.py | 44 +- .../tests/test_llama_cpp_context_fit.py | 73 +- .../backend/tests/test_llama_cpp_freshness.py | 16 +- .../tests/test_llama_cpp_load_progress.py | 38 +- .../test_llama_cpp_load_progress_live.py | 44 +- .../test_llama_cpp_load_progress_matrix.py | 77 +- .../test_llama_cpp_max_context_threshold.py | 39 +- .../tests/test_llama_cpp_mtp_detection.py | 63 +- .../tests/test_llama_cpp_no_context_shift.py | 51 +- ..._llama_cpp_start_failure_classification.py | 12 +- .../tests/test_llama_cpp_wait_for_health.py | 52 +- .../test_llama_cpp_wait_for_vram_settle.py | 46 +- .../test_llama_cpp_windows_nvidia_path.py | 67 +- .../backend/tests/test_llama_server_args.py | 50 +- .../tests/test_log_filter_no_truncation.py | 6 +- studio/backend/tests/test_login_rate_limit.py | 34 +- studio/backend/tests/test_mcp_servers.py | 65 +- .../tests/test_mcp_stdio_improvements.py | 18 +- studio/backend/tests/test_mcp_stdio_pr5863.py | 28 +- studio/backend/tests/test_middleware.py | 18 +- .../tests/test_mlx_inference_backend.py | 18 +- .../backend/tests/test_multimodal_document.py | 96 +- .../tests/test_native_context_length.py | 30 +- .../tests/test_offline_gguf_cache_fallback.py | 78 +- .../tests/test_offline_inference_parent.py | 2 +- .../tests/test_openai_citation_markers.py | 23 +- .../test_openai_citation_markers_edge.py | 57 +- .../tests/test_openai_code_execution.py | 63 +- .../backend/tests/test_openai_compaction.py | 73 +- .../tests/test_openai_container_crud.py | 35 +- .../tests/test_openai_image_generation.py | 27 +- .../test_openai_responses_translation.py | 46 +- .../tests/test_openai_tool_passthrough.py | 67 +- .../test_openai_tool_result_fallbacks.py | 12 +- studio/backend/tests/test_pricing.py | 14 +- studio/backend/tests/test_pricing_edge.py | 46 +- studio/backend/tests/test_providers_api.py | 72 +- studio/backend/tests/test_pytorch_mirror.py | 6 +- .../test_recommended_folders_permission.py | 39 +- studio/backend/tests/test_responses_api.py | 29 +- .../tests/test_responses_tool_passthrough.py | 76 +- studio/backend/tests/test_rocm_oom_guard.py | 20 +- .../test_safetensors_capability_advertise.py | 34 +- .../tests/test_safetensors_tool_loop.py | 100 +- studio/backend/tests/test_sandbox_tools.py | 65 +- studio/backend/tests/test_studio_api.py | 70 +- .../tests/test_studio_train_validation.py | 6 +- .../backend/tests/test_tool_policy_gates.py | 4 +- studio/backend/tests/test_tool_xml_strip.py | 12 +- .../tests/test_training_worker_flash_attn.py | 237 +- .../tests/test_transformers_version.py | 27 +- studio/backend/tests/test_utils.py | 13 +- studio/backend/tests/test_vision_cache.py | 73 +- studio/backend/tests/test_vram_estimation.py | 55 +- .../tests/test_windows_gpu_detection_mock.py | 71 +- studio/backend/utils/cache_cleanup.py | 25 +- studio/backend/utils/cpu_threads.py | 6 +- studio/backend/utils/datasets/__init__.py | 9 +- .../backend/utils/datasets/chat_templates.py | 58 +- .../backend/utils/datasets/data_collators.py | 35 +- .../utils/datasets/dataset_none_detect.py | 90 +- .../backend/utils/datasets/dataset_utils.py | 69 +- .../utils/datasets/format_conversion.py | 116 +- .../utils/datasets/format_detection.py | 161 +- studio/backend/utils/datasets/llm_assist.py | 56 +- .../backend/utils/datasets/model_mappings.py | 10 +- .../backend/utils/datasets/vlm_processing.py | 29 +- studio/backend/utils/hardware/__init__.py | 8 +- studio/backend/utils/hardware/amd.py | 131 +- studio/backend/utils/hardware/hardware.py | 302 ++- studio/backend/utils/hardware/nvidia.py | 12 +- .../backend/utils/hardware/vram_estimation.py | 171 +- .../utils/inference/inference_config.py | 50 +- studio/backend/utils/llama_cpp_freshness.py | 2 +- studio/backend/utils/models/checkpoints.py | 18 +- studio/backend/utils/models/gguf_metadata.py | 25 +- studio/backend/utils/models/model_config.py | 376 ++-- studio/backend/utils/paths/__init__.py | 8 +- studio/backend/utils/paths/path_utils.py | 27 +- studio/backend/utils/paths/storage_roots.py | 49 +- studio/backend/utils/studio_version.py | 4 +- studio/backend/utils/subprocess_compat.py | 4 +- studio/backend/utils/transformers_version.py | 105 +- studio/backend/utils/update_status.py | 11 +- studio/backend/utils/utils.py | 15 +- studio/backend/utils/wheel_utils.py | 10 +- studio/install_llama_prebuilt.py | 448 ++-- studio/install_python_stack.py | 356 ++- 205 files changed, 8016 insertions(+), 8863 deletions(-) diff --git a/studio/backend/_platform_compat.py b/studio/backend/_platform_compat.py index 490e1820d7..37bf5e3fb5 100644 --- a/studio/backend/_platform_compat.py +++ b/studio/backend/_platform_compat.py @@ -4,17 +4,17 @@ """ Compatibility shim for Anaconda/conda-forge Python builds. -Anaconda modifies sys.version to include distributor metadata between pipe -characters, e.g. '3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'. -Python's platform._sys_version() has a hardcoded regex that cannot parse this, -raising ValueError. CPython closed this as "not planned" (cpython#102396). +Anaconda puts distributor metadata between pipes in sys.version, e.g. +'3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'. The hardcoded +regex in platform._sys_version() can't parse this and raises ValueError; +CPython closed it as "not planned" (cpython#102396). -This module seeds platform._sys_version_cache so the stdlib parser never sees -the problematic string, fixing the import chain: +We seed platform._sys_version_cache so the stdlib parser never sees the bad +string, fixing the import chain: structlog -> rich.pretty -> attrs._compat -> platform.python_implementation() -Import this module before any library imports that may trigger the above chain. -Safe to import multiple times (no-op if cache is already seeded or no pipes). +Import before any library that may trigger that chain. Idempotent (no-op if the +cache is already seeded or there are no pipes). """ import platform @@ -29,12 +29,12 @@ def _seed_sys_version_cache() -> None: # Strip paired |...| segments (Anaconda, conda-forge metadata) cleaned = re.sub(r"\s*\|[^|]*\|\s*", " ", raw).strip() - # Format B: "ver (build) | label | (build_dup) \n[compiler]" - # After pipe-strip, two consecutive (...) groups remain; drop the second. + # Format B: "ver (build) | label | (build_dup) \n[compiler]" leaves two + # consecutive (...) groups after pipe-strip; drop the second. cleaned = re.sub(r"(\([^)]*\))\s+\([^)]*\)", r"\1", cleaned) if "|" in cleaned: - # Unpaired pipe remaining -- keep version + everything from "(" onward + # Unpaired pipe left: keep version + everything from "(" onward m = re.match(r"([\w.+]+)\s*", cleaned) p = cleaned.find("(") if m and p > 0: @@ -47,9 +47,9 @@ def _seed_sys_version_cache() -> None: try: result = platform._sys_version(cleaned) except ValueError: - return # Cleaning didn't produce a parseable string; don't make things worse + return # Still unparsable; don't make things worse - # Seed the cache so future calls with the raw string skip parsing entirely + # Seed the cache so future calls with the raw string skip parsing cache = getattr(platform, "_sys_version_cache", None) if isinstance(cache, dict): cache[raw] = result diff --git a/studio/backend/auth/__init__.py b/studio/backend/auth/__init__.py index b3e1a8a9c0..a63d5303d4 100644 --- a/studio/backend/auth/__init__.py +++ b/studio/backend/auth/__init__.py @@ -1,9 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 -""" -Authentication module for JWT-based auth with SQLite storage. -""" +"""Authentication module for JWT-based auth with SQLite storage.""" from .authentication import ( create_access_token, diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.py index bb5b873e65..6509cb6825 100644 --- a/studio/backend/auth/authentication.py +++ b/studio/backend/auth/authentication.py @@ -58,7 +58,7 @@ def create_access_token( """ Create a signed JWT for the given subject (e.g. username). - Tokens are valid across restarts because the signing secret is stored in SQLite. + Valid across restarts: the signing secret is stored in SQLite. """ to_encode = {"sub": subject} if desktop: @@ -100,7 +100,7 @@ def create_refresh_token(subject: str, *, desktop: bool = False) -> str: """ Create a random refresh token, store its hash in SQLite, and return it. - Refresh tokens are opaque (not JWTs) and expire after REFRESH_TOKEN_EXPIRE_DAYS. + Refresh tokens are opaque (not JWTs); expire after REFRESH_TOKEN_EXPIRE_DAYS. """ token = secrets.token_urlsafe(48) expires_at = datetime.now(timezone.utc) + timedelta(days = REFRESH_TOKEN_EXPIRE_DAYS) @@ -112,8 +112,8 @@ def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[st """ Validate a refresh token and issue a new access token. - The refresh token itself is NOT consumed — it stays valid until expiry. - Returns a new access_token or None if the refresh token is invalid/expired. + The refresh token is NOT consumed; it stays valid until expiry. + Returns a new access_token, or None if the refresh token is invalid/expired. """ verified = verify_refresh_token(refresh_token) if verified is None: @@ -128,7 +128,7 @@ def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[st def reload_secret() -> None: """ - Keep legacy API compatibility for callers expecting auth storage init. + Legacy API compat for callers expecting auth storage init. Auth now resolves the current signing secret directly from SQLite. """ @@ -157,9 +157,9 @@ async def _get_current_subject( credentials: HTTPAuthorizationCredentials, *, allow_password_change: bool ) -> str: """ - FastAPI dependency to validate the JWT and return the subject. + FastAPI dependency: validate the JWT and return the subject. - Use this as a dependency on routes that should be protected, e.g.: + Use as a dependency on protected routes, e.g.: @router.get("/secure") async def secure_endpoint(current_subject: str = Depends(get_current_subject)): diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py index 0e34a0cf28..42e2de7450 100644 --- a/studio/backend/auth/storage.py +++ b/studio/backend/auth/storage.py @@ -1,9 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 -""" -SQLite storage for authentication data (user credentials + JWT secret). -""" +"""SQLite storage for auth data (user credentials + JWT secret).""" import hashlib import os @@ -17,20 +15,19 @@ from utils.paths import auth_db_path, ensure_dir DB_PATH = auth_db_path() DEFAULT_ADMIN_USERNAME = "unsloth" -# Plaintext bootstrap password file — lives beside auth.db, deleted on -# first password change so the credential never lingers on disk. +# Plaintext bootstrap password file beside auth.db, deleted on first password +# change so the credential never lingers on disk. _BOOTSTRAP_PW_PATH = DB_PATH.parent / ".bootstrap_password" -# In-process cache so we don't re-read the file on every HTML serve. +# In-process cache to avoid re-reading the file on every HTML serve. _bootstrap_password: Optional[str] = None def generate_bootstrap_password() -> str: """Generate a 4-word diceware passphrase and persist it to disk. - The passphrase is written to ``_BOOTSTRAP_PW_PATH`` so that it - survives server restarts (the DB only stores the *hash*). On - subsequent calls / restarts, the persisted value is returned. + Written to ``_BOOTSTRAP_PW_PATH`` so it survives restarts (the DB only + stores the *hash*). Later calls / restarts return the persisted value. """ global _bootstrap_password @@ -51,7 +48,7 @@ def generate_bootstrap_password() -> str: options = diceware.handle_options(args = ["-n", "4", "-d", "", "-c"]) ) - # Persist so the *same* passphrase is used if the server restarts + # Persist so the *same* passphrase is reused if the server restarts # before the user changes the password. ensure_dir(_BOOTSTRAP_PW_PATH.parent) _BOOTSTRAP_PW_PATH.write_text(_bootstrap_password) @@ -88,21 +85,19 @@ def clear_bootstrap_password() -> None: def _hash_token(token: str) -> str: - """SHA-256 hash helper used for refresh token storage. + """SHA-256 hash helper for refresh token storage. - Plain SHA-256 is intentional here: refresh tokens are high-entropy - random strings from ``secrets.token_urlsafe(48)`` (384 bits of - entropy), so a slow KDF (Argon2 / bcrypt / PBKDF2) provides zero - additional security — no attacker can brute-force 2^384 regardless - of hash speed — while adding tens of ms of CPU to every refresh. - See the OWASP Password Storage Cheat Sheet on fast-vs-slow hashing - of high-entropy inputs. + 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 below, which - runs PBKDF2-HMAC-SHA256 with a persistent server-side salt — not - for cryptographic reasons (128-bit random tokens don't need slow - hashing), but because CodeQL's ``py/weak-sensitive-data-hashing`` - query mislabels API keys as passwords and demands a KDF. + API keys use the separate ``_pbkdf2_api_key`` helper (PBKDF2-HMAC-SHA256 + with a persistent server-side salt) — not for crypto reasons (128-bit + random tokens don't need slow hashing) but because CodeQL's + ``py/weak-sensitive-data-hashing`` query mislabels them as passwords and + demands a KDF. """ return hashlib.sha256(token.encode("utf-8")).hexdigest() @@ -176,22 +171,20 @@ def get_connection() -> sqlite3.Connection: # ── API-key PBKDF2 salt ──────────────────────────────────────────────── # -# Module-level cache for the persistent API-key PBKDF2 salt. Populated -# lazily on first use via ``_get_or_create_api_key_pbkdf2_salt``. Not -# protected by a lock because (a) the ``INSERT OR IGNORE`` provides -# atomicity at the SQLite layer and (b) concurrent populations converge -# on the same value, so the worst case is a harmless duplicate read on -# startup. +# Module-level cache for the persistent API-key PBKDF2 salt, populated lazily +# via ``_get_or_create_api_key_pbkdf2_salt``. No lock needed: (a) ``INSERT OR +# IGNORE`` is atomic at the SQLite layer and (b) concurrent populations +# converge on the same value, so the worst case is a harmless duplicate read +# on startup. _api_key_pbkdf2_salt_cache: Optional[bytes] = None def _get_or_create_api_key_pbkdf2_salt() -> bytes: """Return the persistent API-key PBKDF2 salt, generating it once if missing. - Stored as a hex-encoded 32-byte random value in the ``app_secrets`` - table under key ``"api_key_pbkdf2_salt"``. Regenerated only if the row - is missing (i.e. fresh install, or operator manually deleted the row - and accepts invalidating existing API keys). + Stored as a hex-encoded 32-byte random value in ``app_secrets`` under key + ``"api_key_pbkdf2_salt"``. Regenerated only when the row is missing (fresh + install, or operator deleted it and accepts invalidating existing keys). """ global _api_key_pbkdf2_salt_cache if _api_key_pbkdf2_salt_cache is not None: @@ -233,22 +226,18 @@ _DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at" def _pbkdf2_api_key(raw_key: str) -> str: """PBKDF2-HMAC-SHA256 an API key with a persistent server-side salt. - Used for API-key storage ONLY, not refresh tokens. Matches the - PBKDF2 algorithm + iteration count used by the password hasher in - ``auth/hashing.py`` so the codebase is consistent on which KDF it - uses for credential storage. + 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. - Notes on why a slow KDF here is *only* a CodeQL appeasement and - *not* a cryptographic requirement: API keys are cryptographically - random 128-bit tokens (via ``secrets.token_hex``), so brute force - against 2^128 is infeasible regardless of hash speed. CodeQL's - ``py/weak-sensitive-data-hashing`` query mislabels these tokens as - "password" sensitive data and then demands a KDF from its - allowlist (Argon2 / scrypt / bcrypt / PBKDF2). Per the query's - own recommendation page we use PBKDF2. The persistent salt is - still loaded from ``app_secrets`` so an attacker dumping the - ``api_keys`` table alone cannot derive hashes for candidate - tokens without also obtaining the salt row. + The slow KDF here is *only* a CodeQL appeasement, not a crypto + requirement: API keys are random 128-bit tokens (``secrets.token_hex``), + so brute force against 2^128 is infeasible regardless of hash speed. + CodeQL's ``py/weak-sensitive-data-hashing`` query mislabels them as + "password" data and demands a KDF from its allowlist (Argon2 / scrypt / + bcrypt / PBKDF2); we use PBKDF2 per its recommendation page. The salt is + still loaded from ``app_secrets`` so dumping the ``api_keys`` table alone + can't derive hashes for candidate tokens without the salt row. """ salt = _get_or_create_api_key_pbkdf2_salt() dk = hashlib.pbkdf2_hmac( diff --git a/studio/backend/colab.py b/studio/backend/colab.py index c3a1e03fbe..1f618a34ab 100644 --- a/studio/backend/colab.py +++ b/studio/backend/colab.py @@ -2,15 +2,14 @@ # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 """ -Colab-specific helpers for running Unsloth Studio. -Uses Colab's built-in proxy - no external tunneling needed! +Colab helpers for Unsloth Studio. Uses Colab's built-in proxy. """ from pathlib import Path import sys -# Fix for Anaconda/conda-forge Python: seed platform._sys_version_cache before -# any library imports that trigger attrs -> rich -> structlog -> platform crash. +# Anaconda/conda-forge Python: seed platform._sys_version_cache before any +# import that triggers attrs -> rich -> structlog -> platform crash. # See: https://github.com/python/cpython/issues/102396 _backend_dir = str(Path(__file__).parent) if _backend_dir not in sys.path: @@ -25,11 +24,10 @@ logger = get_logger(__name__) def get_colab_url(port: int = 8888) -> str: """ - Get the actual Colab proxy URL for a port. + Get the Colab proxy URL for a port. - Retries up to 3 times and validates that the result is a real HTTPS Colab - URL before returning. Falls back to http://localhost:{port} only when all - attempts fail. + Retries up to 3 times, validating the result is a real HTTPS Colab URL. + Falls back to http://localhost:{port} only when all attempts fail. """ import time as _time @@ -43,7 +41,7 @@ def get_colab_url(port: int = 8888) -> str: for attempt in range(3): try: url = eval_js(f"google.colab.kernel.proxyPort({port})", timeout_sec = 10) - # A valid Colab proxy URL starts with https:// and embeds the port. + # Valid Colab proxy URL starts with https:// and embeds the port. if url and isinstance(url, str) and url.startswith("https://") and str(port) in url: return url.rstrip("/") except Exception as e: @@ -61,16 +59,16 @@ def get_colab_url(port: int = 8888) -> str: def show_link(port: int = 8888, *, _url: "str | None" = None): """Display a styled clickable link to the UI. - *_url* is an optional pre-fetched Colab proxy URL. When omitted, - ``get_colab_url(port)`` is called internally. Pass it from - ``_show_and_embed`` to avoid a second ``eval_js`` round-trip. + *_url* is an optional pre-fetched Colab proxy URL; when omitted, + ``get_colab_url(port)`` is called. Pass it from ``_show_and_embed`` to + avoid a second ``eval_js`` round-trip. """ from IPython.display import display, HTML url = _url if _url is not None else get_colab_url(port) - # Build a truncated display URL. Wrap in try/except so an unexpected URL - # shape never prevents the link from rendering. + # Truncated display URL. try/except so an unexpected URL shape never + # prevents the link from rendering. try: port_prefix = f"{port}-" idx = url.index(port_prefix) @@ -79,8 +77,7 @@ def show_link(port: int = 8888, *, _url: "str | None" = None): except (ValueError, IndexError): short_url = url - # Also emit a plain-text line so the URL is visible even if HTML display - # is suppressed or fails. + # Plain-text line so the URL is visible even if HTML display fails. logger.info(f"🌐 Unsloth Studio URL: {url}") html = f""" @@ -123,12 +120,10 @@ def _is_studio_healthy(port: int, timeout: float = 2.0) -> bool: def _show_and_embed(port: int): """Embed the Studio inline for *port* with a branded header bar. - Fetches the Colab proxy URL once (registering the port with Colab's - reverse-proxy at the same time) then renders a header bar + full-height - iframe as a single HTML block. - - Falls back to ``serve_kernel_port_as_iframe`` if ``IPython.display.HTML`` - is unavailable for any reason. + Fetches the Colab proxy URL once (also registering the port with Colab's + reverse-proxy) then renders a header bar + full-height iframe as one HTML + block. Falls back to ``serve_kernel_port_as_iframe`` if + ``IPython.display.HTML`` is unavailable. """ url = get_colab_url(port) logger.info(f"🌐 Unsloth Studio URL: {url}") @@ -138,7 +133,7 @@ def _show_and_embed(port: int): iframe_id = f"unsloth-studio-{port}" - # Truncated URL shown in the header — best-effort, falls back to full URL. + # Truncated header URL — best-effort, falls back to full URL. try: port_prefix = f"{port}-" idx = url.index(port_prefix) @@ -188,8 +183,8 @@ def start(port: int = 8888): logger.info("🦥 Starting Unsloth Studio...") # --- Fast path: Studio is already running (cell re-run) --- - # Re-launching would either collide on the port or silently shift to a new - # port and confuse the user. Just re-show the link and iframe instead. + # Re-launching would collide on the port or silently shift to a new one. + # Just re-show the link and iframe instead. if _is_studio_healthy(port): logger.info(f" Studio is already running on port {port} — reusing existing server.") _show_and_embed(port) @@ -222,16 +217,16 @@ def start(port: int = 8888): logger.error(f"❌ Unsloth Studio failed to start: {exc}") return - # run_server auto-increments the port when the requested one is already in - # use (e.g. Jupyter occupying 8888). Read back the actual bound port so the - # Colab proxy URL and iframe always point at the right place. + # run_server auto-increments the port if the requested one is in use (e.g. + # Jupyter on 8888). Read back the bound port so the Colab proxy URL and + # iframe point at the right place. actual_port: int = getattr(getattr(app, "state", None), "server_port", None) or port logger.info(f" Server started on port {actual_port}!") - # Poll health endpoint to confirm the server is truly reachable before - # showing the link and registering the iframe — avoids the race where - # ready_event fires but the process hasn't finished binding. + # Poll health endpoint to confirm reachability before showing the link and + # registering the iframe — avoids the race where ready_event fires but the + # process hasn't finished binding. import urllib.request server_ready = False @@ -252,9 +247,9 @@ def start(port: int = 8888): _show_and_embed(actual_port) - # Keep kernel alive so the daemon server thread stays running. - # Handle KeyboardInterrupt cleanly so the user gets a readable message - # rather than a raw traceback when they interrupt the cell. + # Keep kernel alive so the daemon server thread stays running. Handle + # KeyboardInterrupt cleanly so interrupting the cell gives a readable + # message, not a raw traceback. try: for _ in range(10000): time.sleep(300) diff --git a/studio/backend/core/__init__.py b/studio/backend/core/__init__.py index 2ba9d5c65c..5400ef0d35 100644 --- a/studio/backend/core/__init__.py +++ b/studio/backend/core/__init__.py @@ -4,18 +4,16 @@ """ Unified core module for Unsloth backend -Imports are LAZY (via __getattr__) so that training subprocesses can -import core.training.worker without pulling in heavy ML dependencies -like unsloth, transformers, or torch before the version activation -code has a chance to run. +Imports are LAZY (via __getattr__) so training subprocesses can import +core.training.worker without pulling in heavy ML deps (unsloth, transformers, +torch) before the version-activation code runs. """ import sys from pathlib import Path -# Ensure the backend directory is on sys.path so that bare "from utils.*" -# imports used throughout the backend work when core is imported as a package -# (e.g. from the CLI: "from studio.backend.core import ModelConfig"). +# Put the backend dir on sys.path so bare "from utils.*" imports work when core +# is imported as a package (e.g. CLI: "from studio.backend.core import ModelConfig"). _backend_dir = str(Path(__file__).resolve().parent.parent) if _backend_dir not in sys.path: sys.path.insert(0, _backend_dir) @@ -69,7 +67,7 @@ def __getattr__(name): globals()["TrainingProgress"] = TrainingProgress return globals()[name] - # Config (from utils.models) + # Config (utils.models) if name in ( "is_vision_model", "ModelConfig", diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.py index 217c25fda3..4a62004bac 100644 --- a/studio/backend/core/_torchao_stub.py +++ b/studio/backend/core/_torchao_stub.py @@ -6,15 +6,14 @@ torchao (pulled in by transformers.quantizers) imports torch.distributed._functional_collectives at module level, which imports distributed_c10d.py unconditionally — that file crashes on Windows ROCm because -torch._C._distributed_c10d (the RCCL backend) is absent. -torch/distributed/__init__.py itself is guarded by `if is_available()` so -`import torch.distributed` alone is safe; the crash only comes via torchao's -import chain. Stubbing torchao short-circuits it entirely. +torch._C._distributed_c10d (the RCCL backend) is absent. `import +torch.distributed` alone is safe (guarded by `if is_available()`); the crash +only comes via torchao's import chain, so stubbing torchao short-circuits it. _StubSubpackageFinder handles any depth of torchao.xxx.yyy imports. -This logic used to be duplicated inline inside run_export_process() and -run_training_process(); it now lives here so both worker subprocesses call the -single `install_torchao_windows_rocm_stub()` entrypoint before importing +Previously duplicated inline in run_export_process() and run_training_process(); +now both worker subprocesses call the single +`install_torchao_windows_rocm_stub()` entrypoint before importing transformers / unsloth_zoo. """ @@ -28,9 +27,9 @@ import importlib.machinery _STUB_SENTINEL = object() -# Metaclass for stub types so that isinstance(x, StubClass) returns False -# instead of raising TypeError ("arg 2 must be a type"). -# peft/tuners/lora/torchao.py does: +# Metaclass for stub types so isinstance(x, StubClass) returns False instead +# of raising TypeError ("arg 2 must be a type"). peft/tuners/lora/torchao.py +# does: # from torchao.dtypes import AffineQuantizedTensor, LinearActivationQuantizedTensor # isinstance(weight, (AffineQuantizedTensor, LinearActivationQuantizedTensor)) # If those names resolve to stub modules rather than types, isinstance() raises. @@ -71,8 +70,8 @@ def _make_mod_stub(mod_name): ): if attr.startswith("__"): raise AttributeError(attr) - # Return a stub CLASS (not a module) so that isinstance(x, attr) - # works and returns False instead of raising TypeError. + # Return a stub CLASS (not a module) so isinstance(x, attr) returns + # False instead of raising TypeError. child = _make_stub_type(f"{_n}.{attr}") setattr(_m, attr, child) return child @@ -114,14 +113,13 @@ class _StubSubpackageFinder(importlib.abc.MetaPathFinder): def install_torchao_windows_rocm_stub() -> None: """Pre-stub torchao on Windows ROCm so transformers/peft imports don't crash. - No-op on every other platform (Windows CUDA included — there torchao is real - and shadowing it would break torchao-based quantization paths). Must run - before any import of transformers / unsloth_zoo. Safe to call once per worker - process. + No-op on every other platform (incl. Windows CUDA — there torchao is real + and shadowing it would break torchao quantization paths). Must run before + any import of transformers / unsloth_zoo. Safe to call once per worker. """ # Gate on the active torch runtime, not env-var presence -- HIP_PATH / - # ROCM_PATH stay set after a user installs the HIP SDK and reverts to a - # CUDA torch wheel. AMD SDK / Radeon ROCm wheels may not set torch.version.hip + # ROCM_PATH stay set after installing the HIP SDK and reverting to a CUDA + # torch wheel. AMD SDK / Radeon ROCm wheels may not set torch.version.hip # but still encode "rocm" in torch.__version__, so accept either. _is_win32_rocm = False if sys.platform == "win32": @@ -135,8 +133,8 @@ def install_torchao_windows_rocm_stub() -> None: except Exception: pass if _is_win32_rocm: - # Register the finder only on Windows ROCm -- on other platforms there - # are no stub modules seeded, so appending is a pure accumulation. + # Register the finder only on Windows ROCm -- elsewhere no stub modules + # are seeded, so appending would be pure accumulation. sys.meta_path.append(_StubSubpackageFinder()) # Seed torchao top-level + key submodules; the finder handles the rest. for _tao_name in ( diff --git a/studio/backend/core/data_recipe/huggingface.py b/studio/backend/core/data_recipe/huggingface.py index d5a6db6baf..3012fed1ea 100644 --- a/studio/backend/core/data_recipe/huggingface.py +++ b/studio/backend/core/data_recipe/huggingface.py @@ -95,8 +95,8 @@ def publish_recipe_dataset( tags = None, ) card.text = card.text.replace(_DATA_DESIGNER_FOOTER, _UNSLOTH_STUDIO_FOOTER) - # Data Designer currently drops the explicit token when pushing the - # dataset card. Push it ourselves so auth stays request-local. + # Data Designer drops the explicit token when pushing the dataset + # card, so push it ourselves to keep auth request-local. card.push_to_hub(repo_id, token = hf_token, repo_type = "dataset") client._upload_main_dataset_files( diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.py index 75dc1efb9c..71c2b7468f 100644 --- a/studio/backend/core/data_recipe/jobs/manager.py +++ b/studio/backend/core/data_recipe/jobs/manager.py @@ -134,8 +134,8 @@ class JobManager: ``internal_api_key_id`` is the row id of a workflow-scoped sk-unsloth-* key minted by the route layer for local providers. - JobManager revokes it when the job reaches a terminal state so the - key's live window is no longer than the run. + JobManager revokes it on terminal state so the key's live window is + no longer than the run. """ llm_columns = recipe.get("columns") or [] llm_column_count = 0 @@ -202,7 +202,7 @@ class JobManager: return True def get_status(self, job_id: str) -> dict | None: - """UI friendly snapshot that we need. Alternative to sse kinda of and structured""" + """UI-friendly structured snapshot; an alternative to SSE.""" with self._lock: if self._job is None or self._job.job_id != job_id: return None @@ -537,9 +537,9 @@ class JobManager: def _retire_workflow_key(self, job: Job) -> None: """Revoke the workflow-scoped sk-unsloth-* key, if one was minted. - Best-effort: revocation failures are swallowed. The key would - expire on its own after 24h, so a missed revoke is a latency - concern, not a correctness one. + Best-effort: revocation failures are swallowed. The key expires on + its own after 24h, so a missed revoke is a latency concern, not a + correctness one. """ key_id = getattr(job, "internal_api_key_id", None) if not key_id: diff --git a/studio/backend/core/data_recipe/jobs/parse.py b/studio/backend/core/data_recipe/jobs/parse.py index 8ca3702edd..e37d7064ed 100644 --- a/studio/backend/core/data_recipe/jobs/parse.py +++ b/studio/backend/core/data_recipe/jobs/parse.py @@ -46,7 +46,7 @@ class ParsedUpdate: source_progress: SourceProgress | None = None -# kinda of a bummber but currently only option, Best effort parser from data-designer logs -> structured status for UI. +# Best-effort parser from data-designer logs -> structured status for UI. _RE_SAMPLERS = re.compile( r"Preparing samplers to generate (?P\d+) records across (?P\d+) columns" ) @@ -327,7 +327,7 @@ def apply_update(job: Job, update: ParsedUpdate) -> None: _apply_source_progress(job, update.source_progress) if update.stage in USAGE_RESET_STAGES: - # usage summary is a short block so we reset once we move into the next stage. + # Usage summary is a short block; reset on entering the next stage. job._in_usage_summary = False if update.usage_section_start is not None: diff --git a/studio/backend/core/data_recipe/jobs/types.py b/studio/backend/core/data_recipe/jobs/types.py index 3d3ddb974e..6dd4db5973 100644 --- a/studio/backend/core/data_recipe/jobs/types.py +++ b/studio/backend/core/data_recipe/jobs/types.py @@ -91,8 +91,8 @@ class Job: source_progress_estimated_total: int | None = None completed_columns: list[str] = field(default_factory = list) # Id of the internal sk-unsloth-* API key minted for a local-model - # workflow. Revoked when the job terminates so the key's live window - # matches the run rather than its 24h TTL. + # workflow. Revoked when the job ends so the key's window matches the + # run rather than its 24h TTL. internal_api_key_id: int | None = None _current_usage_model: str | None = None _in_usage_summary: bool = False diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.py index f59538769e..27d08e90fe 100644 --- a/studio/backend/core/data_recipe/jobs/worker.py +++ b/studio/backend/core/data_recipe/jobs/worker.py @@ -73,10 +73,7 @@ def _build_dataset_name(*, run_name: str | None, job_id: str, artifact_root: Pat def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any]) -> None: - """ - Subprocess entrypoint. - Sends events to `event_queue`. - """ + """Subprocess entrypoint. Sends events to `event_queue`.""" import os os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports @@ -115,8 +112,8 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any]) builder = build_config_builder(recipe) designer = create_data_designer(recipe, artifact_path = str(_ARTIFACT_ROOT)) - # DataDesigner configures root logging in DataDesigner.__init__. - # Attach queue logger directly to `data_designer` so parser events survive root resets. + # DataDesigner configures root logging in __init__. Attach the queue + # logger to `data_designer` directly so parser events survive root resets. handler = _QueueLogHandler(event_queue) handler.setLevel(logging.INFO) for logger_name in ( diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.py index cb5901f04e..addbe8f848 100644 --- a/studio/backend/core/data_recipe/service.py +++ b/studio/backend/core/data_recipe/service.py @@ -167,9 +167,10 @@ def _validate_recipe_runtime_support(recipe: dict[str, Any], model_providers: li def build_mcp_providers(recipe: dict[str, Any]) -> list: from data_designer.config.mcp import LocalStdioMCPProvider, MCPProvider # pyright: ignore[reportMissingImports] - # Same gate as the chat MCP path: stdio providers spawn a local subprocess, - # so only build them when this host allows it (desktop / explicit opt-in). - # Skip them otherwise so a recipe carried onto a hosted host cannot spawn. + # Same gate as the chat MCP path: stdio providers spawn a local + # subprocess, so build them only when this host allows it (desktop / + # explicit opt-in). Otherwise a recipe carried onto a hosted host + # cannot spawn. from core.inference.mcp_client import stdio_mcp_enabled stdio_allowed = stdio_mcp_enabled() @@ -258,7 +259,7 @@ def build_config_builder(recipe: dict[str, Any]): ) # DataDesignerConfigBuilder.from_config currently skips processors. - # Re-attach explicitly so drop_columns/schema_transform survive API payload. + # Re-attach so drop_columns/schema_transform survive the API payload. for processor in recipe_core.get("processors") or []: if not isinstance(processor, dict): continue @@ -283,8 +284,8 @@ def create_data_designer(recipe: dict[str, Any], *, artifact_path: str | None = _validate_recipe_runtime_support(recipe, model_providers) # DataDesigner requires at least one model provider in its registry even - # when the pipeline contains no LLM columns. Supply a lightweight stub - # so sampler/expression-only recipes can run without a real provider. + # when the pipeline has no LLM columns. Supply a lightweight stub so + # sampler/expression-only recipes can run without a real provider. if not model_providers: from data_designer.config.models import ModelProvider # pyright: ignore[reportMissingImports] model_providers = [ diff --git a/studio/backend/core/export/__init__.py b/studio/backend/core/export/__init__.py index 16fba368ef..db9d1b352c 100644 --- a/studio/backend/core/export/__init__.py +++ b/studio/backend/core/export/__init__.py @@ -5,8 +5,8 @@ Export submodule - Model export operations The default get_export_backend() returns an ExportOrchestrator that -delegates to a subprocess. The original ExportBackend runs inside -the subprocess and can be imported directly from .export when needed. +delegates to a subprocess. The original ExportBackend runs inside the +subprocess and can be imported directly from .export when needed. """ from .orchestrator import ExportOrchestrator, get_export_backend diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py index e74dc13e8a..aaae8002fc 100644 --- a/studio/backend/core/export/export.py +++ b/studio/backend/core/export/export.py @@ -2,9 +2,7 @@ # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 # backend/export.py -""" -Export backend - handles model exporting in various formats -""" +"""Export backend - exports models in various formats.""" import glob import json @@ -46,10 +44,10 @@ def _is_wsl(): def _apply_wsl_sudo_patch(): """On WSL, monkey-patch do_we_need_sudo() to return False. - WSL doesn't have passwordless sudo, and do_we_need_sudo() runs - `sudo apt-get update` which hangs waiting for a stdin password - inside a non-interactive subprocess. setup.sh pre-installs the - build dependencies on WSL, so sudo is not needed at runtime. + WSL lacks passwordless sudo, and do_we_need_sudo() runs + `sudo apt-get update`, which hangs on a stdin password in a + non-interactive subprocess. setup.sh pre-installs the build deps on + WSL, so sudo isn't needed at runtime. """ if not _is_wsl(): return @@ -110,7 +108,7 @@ class ExportBackend: try: logger.info("Starting memory cleanup...") - # Unload all models from inference backend + # Unload all inference-backend models model_names = list(self.inference_backend.models.keys()) for model_name in model_names: self.inference_backend.unload_model(model_name) @@ -121,7 +119,7 @@ class ExportBackend: self.current_checkpoint = None self._audio_type = None - # Clear GPU memory cache (handles gc + backend-specific cleanup) + # Clear GPU cache (handles gc + backend-specific cleanup) clear_gpu_cache() logger.info("Memory cleanup completed successfully") @@ -137,8 +135,7 @@ class ExportBackend: """ Scan outputs folder for training runs and their checkpoints. - Returns: - List of tuples: [(model_name, [(display_name, checkpoint_path), ...]), ...] + Returns: [(model_name, [(display_name, checkpoint_path), ...]), ...] """ from utils.models.checkpoints import scan_checkpoints return scan_checkpoints(outputs_dir = outputs_dir) @@ -159,12 +156,12 @@ class ExportBackend: try: logger.info(f"Loading checkpoint: {checkpoint_path}") - # First, cleanup existing models + # Cleanup existing models first self.cleanup_memory() checkpoint_path_obj = Path(checkpoint_path) - # Determine the model identity for type detection + # Model identity for type detection adapter_config = checkpoint_path_obj / "adapter_config.json" base_model = None if adapter_config.exists(): @@ -246,7 +243,7 @@ class ExportBackend: load_in_4bit = load_in_4bit, trust_remote_code = trust_remote_code, ) - tokenizer = processor # For vision models, processor acts as tokenizer + tokenizer = processor # vision: processor acts as tokenizer else: logger.info("Loading as text model...") @@ -258,14 +255,13 @@ class ExportBackend: trust_remote_code = trust_remote_code, ) - # Check if PEFT / LoRA model + # Detect PEFT / LoRA model if _IS_MLX: # MLX doesn't use PeftModel — detect LoRA via adapter_config.json self.is_peft = adapter_config.exists() else: self.is_peft = isinstance(model, (PeftModel, PeftModelForCausalLM)) - # Store loaded model self.current_model = model self.current_tokenizer = tokenizer self.current_checkpoint = checkpoint_path @@ -459,7 +455,7 @@ class ExportBackend: if _IS_MLX: # MLX: save_pretrained_merged handles non-LoRA models too - # (fuse() is a no-op when there are no LoRA layers) + # (fuse() is a no-op without LoRA layers) self.current_model.save_pretrained_merged( save_directory, self.current_tokenizer, @@ -509,12 +505,11 @@ class ExportBackend: private = private, ) else: - # Get base model name from request or model config + # Base model name from request or model config base_model = ( base_model_id or self.current_model.config._name_or_path or "unknown" ) - # Create repo hf_api = HfApi(token = hf_token) repo_id = PushToHubMixin._create_repo( PushToHubMixin, @@ -524,7 +519,7 @@ class ExportBackend: ) username = repo_id.split("/")[0] - # Create and push model card + # Build and push model card content = MODEL_CARD.format( username = username, base_model = base_model, @@ -535,7 +530,7 @@ class ExportBackend: card = ModelCard(content) card.push_to_hub(repo_id, token = hf_token, commit_message = "Unsloth Model Card") - # Upload model files + # Upload files if save_directory: hf_api.upload_folder( folder_path = save_directory, @@ -585,7 +580,7 @@ class ExportBackend: output_path: Optional[str] = None try: - # Convert quantization method to lowercase for unsloth + # unsloth expects lowercase quant method quant_method = quantization_method.lower() # Pin convert_hf_to_gguf.py to the same llama.cpp ref as the @@ -613,27 +608,26 @@ class ExportBackend: # Save locally if requested if save_directory: save_directory = str(resolve_export_dir(save_directory)) - # Resolve to absolute path so unsloth's relative-path internals + # Use absolute path so unsloth's relative-path internals # (check_llama_cpp, use_local_gguf, _download_convert_hf_to_gguf) - # all resolve against the repo root cwd, NOT the export directory. + # resolve against the repo root cwd, NOT the export directory. abs_save_dir = os.path.abspath(save_directory) logger.info(f"Saving GGUF model locally to: {abs_save_dir}") - # Create the directory if it doesn't exist ensure_dir(Path(abs_save_dir)) # On WSL, patch out sudo check before llama.cpp build _apply_wsl_sudo_patch() - # Snapshot existing .gguf files in cwd before conversion. - # unsloth's convert_to_gguf writes output files relative to - # cwd (repo root), so we diff afterwards and relocate them. + # Snapshot existing .gguf files in cwd before conversion; + # unsloth's convert_to_gguf writes output relative to cwd + # (repo root), so we diff afterwards and relocate. cwd = os.getcwd() pre_existing_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf"))) - # Pass absolute path — no os.chdir needed. - # unsloth saves intermediate HF model files into model_save_path. - # unsloth-zoo's check_llama_cpp() uses ~/.unsloth/llama.cpp by default. + # Absolute path — no os.chdir needed. unsloth saves intermediate + # HF model files into model_save_path; unsloth-zoo's + # check_llama_cpp() uses ~/.unsloth/llama.cpp by default. model_save_path = os.path.join(abs_save_dir, "model") self.current_model.save_pretrained_gguf( model_save_path, @@ -642,17 +636,17 @@ class ExportBackend: ) # Relocate GGUF artifacts into the export directory. - # convert_to_gguf writes .gguf files to cwd (repo root) - # because --outfile is a relative path like "model.Q4_K_M.gguf". + # convert_to_gguf writes .gguf to cwd (repo root) because + # --outfile is a relative path like "model.Q4_K_M.gguf". new_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf"))) - pre_existing_ggufs for src in sorted(new_ggufs): dest = os.path.join(abs_save_dir, os.path.basename(src)) shutil.move(src, dest) logger.info(f"Relocated GGUF: {os.path.basename(src)} → {abs_save_dir}/") - # Flatten any .gguf files from subdirectories into abs_save_dir. + # Flatten any .gguf from subdirs into abs_save_dir. # save_pretrained_gguf may create subdirs (e.g. model_gguf/) - # with a name different from model_save_path. + # named differently from model_save_path. for sub in list(Path(abs_save_dir).iterdir()): if not sub.is_dir(): continue @@ -660,13 +654,13 @@ class ExportBackend: dest = os.path.join(abs_save_dir, src.name) shutil.move(str(src), dest) logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/") - # Clean up the subdirectory (intermediate HF files, etc.) + # Clean up the subdir (intermediate HF files, etc.) shutil.rmtree(str(sub), ignore_errors = True) logger.info(f"Cleaned up subdirectory: {sub.name}") # For non-PEFT models, save_pretrained_gguf redirects to the - # checkpoint path, leaving a *_gguf directory in outputs/. - # Relocate any GGUFs from there and clean it up. + # checkpoint path, leaving a *_gguf dir in outputs/. Relocate + # any GGUFs from there and clean it up. if self.current_checkpoint: ckpt = Path(self.current_checkpoint) gguf_dir = ckpt.parent / f"{ckpt.name}_gguf" @@ -686,8 +680,7 @@ class ExportBackend: # Write export metadata so the Chat page can identify the base model self._write_export_metadata(abs_save_dir) - # Log final file locations (after relocation) so it's clear - # where the GGUF files actually ended up. + # Log final file locations (post-relocation). final_ggufs = sorted(glob.glob(os.path.join(abs_save_dir, "*.gguf"))) logger.info( "GGUF export complete. Final files in %s:\n %s", diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py index 90a946163e..49c1af8822 100644 --- a/studio/backend/core/export/orchestrator.py +++ b/studio/backend/core/export/orchestrator.py @@ -1,15 +1,13 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 -""" -Export orchestrator — subprocess-based. +"""Export orchestrator — subprocess-based. -Provides the same API as ExportBackend, but delegates all ML work -to a persistent subprocess. The subprocess is spawned on first checkpoint -load and stays alive for subsequent export operations. +Same API as ExportBackend, but delegates all ML work to a persistent +subprocess spawned on first checkpoint load and reused for later exports. -When switching between checkpoints that need different transformers versions, -the old subprocess is killed and a new one is spawned with the correct version. +When switching between checkpoints needing different transformers +versions, the old subprocess is killed and a new one spawned. Pattern follows core/inference/orchestrator.py. """ @@ -30,9 +28,9 @@ logger = get_logger(__name__) _CTX = mp.get_context("spawn") -# Maximum number of captured log lines kept in memory per export -# orchestrator. Acts as scrollback for the live export log panel in the -# UI. 4000 lines is ~1 MB worst-case at 256 chars/line. +# Max captured log lines kept in memory per export orchestrator; +# scrollback for the live export log panel. 4000 lines is ~1 MB +# worst-case at 256 chars/line. _LOG_BUFFER_MAXLEN = 4000 @@ -41,46 +39,44 @@ class ExportOrchestrator: Export backend orchestrator — subprocess-based. Exposes the same API surface as ExportBackend so routes/export.py - needs minimal changes. Internally, all heavy ML operations happen in - a persistent subprocess. + needs minimal changes. All heavy ML work happens in a persistent + subprocess. """ def __init__(self): - # Subprocess state + # Subprocess state. self._proc: Optional[mp.Process] = None self._cmd_queue: Any = None self._resp_queue: Any = None - # Serializes export operations (load_checkpoint, export_*, - # cleanup) so concurrent HTTP requests can never interleave - # commands on the subprocess queue. Previously unused. + # Serializes export ops (load_checkpoint, export_*, cleanup) so + # concurrent HTTP requests can't interleave commands on the + # subprocess queue. self._lock = threading.Lock() - # Local state mirrors (updated from subprocess responses) + # Local state mirrors (updated from subprocess responses). self.current_checkpoint: Optional[str] = None self.is_vision: bool = False self.is_peft: bool = False # ── Live log capture ───────────────────────────────────── - # Thread-safe ring buffer of log lines forwarded from the - # worker subprocess. Powers the GET /api/export/logs/stream - # SSE endpoint that the export dialog consumes. + # Thread-safe ring buffer of log lines from the worker + # subprocess. Powers the GET /api/export/logs/stream SSE + # endpoint the export dialog consumes. self._log_buffer: Deque[Dict[str, Any]] = deque(maxlen = _LOG_BUFFER_MAXLEN) self._log_lock = threading.Lock() - # Monotonically increasing sequence number. Never reset across - # operations, so SSE clients can use it as a stable cursor even - # if clear_logs() is called mid-session. + # Monotonic sequence number. Never reset across operations, so + # SSE clients can use it as a stable cursor even if clear_logs() + # runs mid-session. self._log_seq: int = 0 - # Snapshot of _log_seq captured at the start of the current run - # (updated by clear_logs()). The SSE endpoint defaults its - # cursor to this value so a client that connects AFTER the - # worker has already emitted its first lines still sees the - # full run. Every line appended during the current run has seq - # strictly greater than _run_start_seq, and every line from - # prior runs has seq less than or equal to it. + # Snapshot of _log_seq at the start of the current run (set by + # clear_logs()). The SSE endpoint defaults its cursor here so a + # client connecting AFTER the worker's first lines still sees the + # full run. Lines in the current run have seq > _run_start_seq; + # prior-run lines have seq <= it. self._run_start_seq: int = 0 - # True while an export operation (load/export/cleanup) is - # running. The SSE endpoint ends the stream 1 second after - # this flips back to False to drain any trailing log lines. + # True while an export op (load/export/cleanup) is running. The + # SSE endpoint ends the stream 1s after this flips False to drain + # trailing log lines. self._export_active: bool = False atexit.register(self._cleanup) @@ -91,12 +87,11 @@ class ExportOrchestrator: # ------------------------------------------------------------------ def _append_log(self, entry: Dict[str, Any]) -> None: - """Append a log line from the worker subprocess to the buffer. + """Append a worker-subprocess log line to the buffer. Entries look like {"type": "log", "stream": "stdout"|"stderr", - "line": "...", "ts": ...}. Each is stamped with a monotonic - seq number before it lands in the buffer so SSE clients can - cursor through new lines. + "line": "...", "ts": ...}. Each gets a monotonic seq number so + SSE clients can cursor through new lines. """ line = entry.get("line") if not line: @@ -113,17 +108,16 @@ class ExportOrchestrator: ) def clear_logs(self) -> None: - """Drop any buffered log lines from a previous operation. + """Drop buffered log lines from a previous operation. Called at the start of each export op so the UI shows only the - output of the current run. The seq counter is NOT reset, so an - SSE client that captured the cursor before clear_logs() will - still see new lines (with strictly greater seq numbers). + current run. The seq counter is NOT reset, so an SSE client that + captured the cursor before clear_logs() still sees new lines + (with strictly greater seq). - Also snapshots the current seq into ``_run_start_seq`` so the - SSE endpoint can anchor its default cursor at the start of - this run. Anything appended after this call has seq strictly - greater than the snapshot and is reachable via + Also snapshots the current seq into ``_run_start_seq`` so the SSE + endpoint can anchor its default cursor at this run's start. + Anything appended after has seq > the snapshot, reachable via ``get_logs_since(get_run_start_seq())``. """ with self._log_lock: @@ -144,11 +138,11 @@ class ExportOrchestrator: return self._log_seq def get_run_start_seq(self) -> int: - """Return the seq value captured at the start of the current run. + """Return the seq captured at the start of the current run. The SSE endpoint uses this as the default cursor so a client - that connects AFTER the worker has already started emitting - output still sees every line from the current run. + connecting AFTER the worker started emitting still sees every + line from the current run. """ with self._log_lock: return self._run_start_seq @@ -193,22 +187,22 @@ class ExportOrchestrator: self._proc = None return - # 1. Drain stale responses + # 1. Drain stale responses. self._drain_queue() - # 2. Send shutdown command + # 2. Send shutdown command. try: self._cmd_queue.put({"type": "shutdown"}) except (OSError, ValueError): pass - # 3. Wait for graceful shutdown + # 3. Wait for graceful shutdown. try: self._proc.join(timeout = timeout) except Exception: pass - # 4. Force kill if still alive + # 4. Force kill if still alive. if self._proc is not None and self._proc.is_alive(): logger.warning("Export subprocess did not exit gracefully, terminating") try: @@ -268,9 +262,8 @@ class ExportOrchestrator: ) -> dict: """Block until a response of the expected type arrives. - Export operations can take a very long time — GGUF conversion for - large models (30B+) easily takes 20-30 minutes. Default timeout - is 1 hour. + Export ops can take a long time — GGUF conversion for large + models (30B+) easily takes 20-30 minutes. Default timeout 1 hour. """ deadline = time.monotonic() + timeout @@ -279,7 +272,7 @@ class ExportOrchestrator: resp = self._read_resp(timeout = min(remaining, 2.0)) if resp is None: - # Check subprocess health + # Check subprocess health. if not self._ensure_subprocess_alive(): raise RuntimeError("Export subprocess crashed during wait") continue @@ -294,17 +287,16 @@ class ExportOrchestrator: raise RuntimeError(f"Subprocess error: {error_msg}") if rtype == "log": - # Forwarded stdout/stderr line from the worker process. + # Forwarded stdout/stderr line from the worker. self._append_log(resp) continue if rtype == "status": message = resp.get("message", "") logger.info("Export subprocess status: %s", message) - # Surface status messages in the live log panel too so - # users see high level progress (e.g. "Importing - # Unsloth...", "Loading checkpoint: ...") alongside - # subprocess output. + # Surface status in the live log panel too so users see + # high-level progress (e.g. "Importing Unsloth...", + # "Loading checkpoint: ...") alongside subprocess output. if message: self._append_log( { @@ -315,7 +307,7 @@ class ExportOrchestrator: ) continue - # Other response types during wait — skip + # Other response types during wait — skip. logger.debug( "Skipping response type '%s' while waiting for '%s'", rtype, @@ -362,12 +354,11 @@ class ExportOrchestrator: } with self._lock: - # Start a fresh log buffer for this operation so the UI - # sees only the current run's output. + # Fresh log buffer so the UI sees only this run's output. self.clear_logs() self._export_active = True try: - # Always kill existing subprocess and spawn fresh. + # Always kill any existing subprocess and spawn fresh. if self._ensure_subprocess_alive(): self._shutdown_subprocess() elif self._proc is not None: @@ -488,12 +479,11 @@ class ExportOrchestrator: def _run_export(self, export_type: str, params: dict) -> Tuple[bool, str, Optional[str]]: """Send an export command to the subprocess and wait for result. - Returns ``(success, message, output_path)``. ``output_path`` is the - resolved on-disk directory the worker actually wrote to (None when - the export only pushed to Hub or failed before any file was - written). Surfaced via the export route's ``details.output_path`` - so the dialog's success screen can show the user where the model - landed. + Returns ``(success, message, output_path)``. ``output_path`` is + the resolved on-disk dir the worker wrote to (None when the + export only pushed to Hub or failed before writing). Surfaced via + the export route's ``details.output_path`` so the dialog's success + screen shows where the model landed. """ with self._lock: if not self._ensure_subprocess_alive(): @@ -527,7 +517,7 @@ class ExportOrchestrator: """Cleanup export-related models from memory.""" with self._lock: if not self._ensure_subprocess_alive(): - # No subprocess — just clear local state + # No subprocess — clear local state. self.current_checkpoint = None self.is_vision = False self.is_peft = False @@ -542,7 +532,7 @@ class ExportOrchestrator: except RuntimeError: success = False - # Shut down subprocess after cleanup — no model loaded + # Shut down subprocess after cleanup — no model loaded. self._shutdown_subprocess() self.current_checkpoint = None @@ -553,7 +543,7 @@ class ExportOrchestrator: self._export_active = False def scan_checkpoints(self, outputs_dir: str = str(outputs_root())) -> List[Tuple[str, list]]: - """Scan for checkpoints — no ML imports needed, runs locally.""" + """Scan for checkpoints — runs locally, no ML imports.""" from utils.models.checkpoints import scan_checkpoints return scan_checkpoints(outputs_dir = outputs_dir) diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py index 405956ec9d..a517d6d7b1 100644 --- a/studio/backend/core/export/worker.py +++ b/studio/backend/core/export/worker.py @@ -4,9 +4,9 @@ """ Export subprocess entry point. -Each export session runs in a persistent subprocess (mp.get_context("spawn")). -This gives us a clean Python interpreter with no stale module state — -solving the transformers version-switching problem completely. +Each export session runs in a persistent subprocess (mp.get_context("spawn")), +giving a clean interpreter with no stale module state — solving the +transformers version-switching problem completely. The subprocess stays alive while a model is loaded, accepting commands (load, export_merged, export_base, export_gguf, export_lora, cleanup, @@ -31,41 +31,39 @@ from typing import Any logger = get_logger(__name__) -# Gate that controls whether captured stdout/stderr lines are forwarded -# to the parent's resp_queue (and from there to the export-dialog SSE -# stream). Closed by default so the noisy bootstrap phase -- transformers -# venv activation, Unsloth/torch imports, base-model resolution, "Top -# GGUF/hub models" lists, vision detection, weight loading bars -- is -# suppressed in the UI. _handle_export() opens the gate at the start of -# the actual export work and leaves it open; the orchestrator always -# spawns a fresh subprocess for the next checkpoint load (see -# orchestrator._spawn_subprocess) which resets this state. +# Gate controlling whether captured stdout/stderr lines are forwarded to +# the parent's resp_queue (and on to the export-dialog SSE stream). Closed +# by default so the noisy bootstrap phase -- transformers venv activation, +# Unsloth/torch imports, base-model resolution, "Top GGUF/hub models" lists, +# vision detection, weight loading bars -- is suppressed in the UI. +# _handle_export() opens the gate when actual export work starts and leaves +# it open; the orchestrator spawns a fresh subprocess for the next checkpoint +# load (see orchestrator._spawn_subprocess), resetting this state. # # Lines dropped while the gate is closed are still echoed to the saved -# original stdout/stderr fds so the server console / log file keeps the -# full output for debugging. +# original stdout/stderr fds so the server console / log file keeps the full +# output for debugging. _log_forward_gate = threading.Event() def _setup_log_capture(resp_queue: Any) -> None: """Redirect fds 1 and 2 through pipes so every line printed by this - worker process and any child process it spawns is forwarded to the - parent process via resp_queue as {"type": "log", ...} messages. + worker and any child it spawns is forwarded to the parent via resp_queue + as {"type": "log", ...} messages. - Must be called BEFORE LogConfig.setup_logging and BEFORE any ML - imports, otherwise library handlers may capture the original stderr - reference and bypass the pipe. + Must run BEFORE LogConfig.setup_logging and any ML imports, else library + handlers may capture the original stderr reference and bypass the pipe. - Lines are also echoed back to the original stdout/stderr so the - server console keeps receiving the full subprocess output, even - while ``_log_forward_gate`` is closed. + Lines are also echoed back to the original stdout/stderr so the server + console keeps the full subprocess output, even while + ``_log_forward_gate`` is closed. """ try: saved_out_fd = os.dup(1) saved_err_fd = os.dup(2) except OSError: - # dup failed (exotic platforms) - give up quietly, export still + # dup failed (exotic platforms) - give up quietly; export still # works, just no live log streaming. return @@ -88,13 +86,13 @@ def _setup_log_capture(resp_queue: Any) -> None: pass return - # Close the write ends we just dup2'd (fds 1 and 2 are the real - # write ends now). + # Close the write ends we just dup2'd (fds 1 and 2 are now the real + # write ends). os.close(w_out) os.close(w_err) - # Replace Python's sys.stdout/sys.stderr with line-buffered writers - # bound to the (now-redirected) fds 1 and 2. + # Replace sys.stdout/sys.stderr with line-buffered writers bound to the + # (now-redirected) fds 1 and 2. try: sys.stdout = os.fdopen(1, "w", buffering = 1, encoding = "utf-8", errors = "replace") sys.stderr = os.fdopen(2, "w", buffering = 1, encoding = "utf-8", errors = "replace") @@ -112,8 +110,8 @@ def _setup_log_capture(resp_queue: Any) -> None: continue if not chunk: break - # Echo to the original fd so the server console still sees - # the full output. + # Echo to the original fd so the server console keeps the + # full output. try: os.write(echo_fd, chunk) except OSError: @@ -133,9 +131,9 @@ def _setup_log_capture(resp_queue: Any) -> None: if not line: continue if not _log_forward_gate.is_set(): - # Gate closed (bootstrap phase) -- already echoed to - # the saved console fd above; drop the line so the - # export dialog doesn't see import / vendoring noise. + # Gate closed (bootstrap) -- already echoed to the saved + # console fd above; drop the line so the export dialog + # doesn't see import / vendoring noise. continue try: resp_queue.put_nowait( @@ -147,8 +145,8 @@ def _setup_log_capture(resp_queue: Any) -> None: } ) except Exception: - # Queue put failed (full, closed, etc.) - drop the - # line rather than crash the reader thread. + # Queue put failed (full, closed, etc.) - drop the line + # rather than crash the reader thread. pass if buf and _log_forward_gate.is_set(): try: @@ -181,7 +179,7 @@ def _setup_log_capture(resp_queue: Any) -> None: def _activate_transformers_version(model_name: str) -> None: """Activate the correct transformers version BEFORE any ML imports.""" - # Ensure backend is on path for utils imports + # Ensure backend is on sys.path for utils imports backend_path = str(Path(__file__).resolve().parent.parent.parent) if backend_path not in sys.path: sys.path.insert(0, backend_path) @@ -267,11 +265,11 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None: export_type = cmd["export_type"] # "merged", "base", "gguf", "lora" response_type = f"export_{export_type}_done" - # Open the log forwarding gate so the user sees the actual export - # progress (Unsloth merge bars, file copies, GGUF conversion, etc.) - # in the live log panel. The gate stays open for the rest of this - # subprocess's life; the orchestrator spawns a fresh subprocess for - # the next checkpoint load, which resets the gate to closed. + # Open the log forwarding gate so the user sees actual export progress + # (Unsloth merge bars, file copies, GGUF conversion, etc.) in the live + # log panel. The gate stays open for the rest of this subprocess's life; + # the orchestrator spawns a fresh subprocess for the next checkpoint + # load, which resets the gate to closed. _log_forward_gate.set() output_path: Any = None @@ -372,23 +370,23 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None """ import queue as _queue - # Install fd-level stdout/stderr capture FIRST so every subsequent - # print and every child process inherits the redirected fds. This - # is what powers the live export log stream in the UI. + # Install fd-level stdout/stderr capture FIRST so every subsequent print + # and every child process inherits the redirected fds. This powers the + # live export log stream in the UI. _setup_log_capture(resp_queue) os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["PYTHONWARNINGS"] = "ignore" # Suppress warnings at C-level before imports - # Force unbuffered output from any child Python process (e.g. the - # GGUF converter) so their prints surface in the log stream as they - # happen rather than at the end. + # Force unbuffered output from child Python processes (e.g. the GGUF + # converter) so their prints surface in the log stream as they happen, + # not at the end. os.environ["PYTHONUNBUFFERED"] = "1" # tqdm defaults to a 10-second mininterval when stdout is not a tty - # (which it isn't here -- we redirected fd 1/2 to a pipe). That makes - # multi-step progress bars look frozen in the export log panel. Force - # frequent flushes so the user sees movement during merge / GGUF - # conversion. Has no effect on single-step bars (e.g. "Copying 1 - # files") which only emit start/end events regardless. + # (it isn't -- we redirected fd 1/2 to a pipe), making multi-step + # progress bars look frozen in the export log panel. Force frequent + # flushes so the user sees movement during merge / GGUF conversion. No + # effect on single-step bars (e.g. "Copying 1 files") which only emit + # start/end events anyway. os.environ.setdefault("TQDM_MININTERVAL", "0.5") import warnings @@ -419,7 +417,7 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None ) return - # ── 1b. On Windows, check Triton availability (must be before import torch) ── + # ── 1b. Check Triton on Windows (must precede import torch) ── if sys.platform == "win32": try: import triton # noqa: F401 @@ -433,9 +431,9 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None # ── 1c. Stub torchao on Windows ROCm ── # Shared with the training worker; see core/_torchao_stub.py for the full - # rationale (torchao -> torch.distributed._functional_collectives crashes on - # Windows ROCm because the RCCL backend is absent). No-op off Windows ROCm. - # Must run before any import of transformers / unsloth_zoo. + # rationale (torchao -> torch.distributed._functional_collectives crashes + # on Windows ROCm: RCCL backend absent). No-op off Windows ROCm. Must run + # before importing transformers / unsloth_zoo. from core._torchao_stub import install_torchao_windows_rocm_stub install_torchao_windows_rocm_stub() @@ -511,7 +509,7 @@ def run_export_process(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None try: if cmd_type == "load": - # Load a new checkpoint (reusing this subprocess) + # Load a new checkpoint, reusing this subprocess backend.cleanup_memory() _handle_load(backend, cmd, resp_queue) diff --git a/studio/backend/core/inference/__init__.py b/studio/backend/core/inference/__init__.py index 35318f6357..2faf70bb79 100644 --- a/studio/backend/core/inference/__init__.py +++ b/studio/backend/core/inference/__init__.py @@ -2,17 +2,17 @@ # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 """ -Inference submodule - Inference backend for model loading and generation +Inference submodule - backend for model loading and generation. The default get_inference_backend() returns an InferenceOrchestrator that -delegates to a subprocess. The original InferenceBackend runs inside -the subprocess and can be imported directly from .inference when needed. +delegates to a subprocess. The original InferenceBackend runs inside the +subprocess and can be imported directly from .inference when needed. """ from .orchestrator import InferenceOrchestrator, get_inference_backend from .llama_cpp import LlamaCppBackend -# Expose InferenceOrchestrator as InferenceBackend for backward compat +# Expose InferenceOrchestrator as InferenceBackend for backward compat. InferenceBackend = InferenceOrchestrator __all__ = [ diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.py index f999120ffb..b6262d9974 100644 --- a/studio/backend/core/inference/_html_to_md.py +++ b/studio/backend/core/inference/_html_to_md.py @@ -5,7 +5,7 @@ Minimal HTML-to-Markdown converter using only the standard library. Replaces the external ``html2text`` (GPL-3.0) dependency with a ~250-line -``html.parser.HTMLParser`` subclass. Covers headings, links, bold/italic, +``html.parser.HTMLParser`` subclass. Covers headings, links, bold/italic, lists, tables, blockquotes, code blocks, and entity decoding. """ @@ -81,9 +81,9 @@ class _MarkdownRenderer(HTMLParser): self._pre_parts: list[str] = [] self._in_inline_code: bool = False - # Blockquote state -- stack of output buffers so nested - # blockquotes each collect their own content and get prefixed - # with the correct number of ">" markers on close. + # Blockquote state -- stack of output buffers so nested blockquotes + # each collect their own content and get prefixed with the correct + # number of ">" markers on close. self._bq_stack: list[list[str]] = [] # ------------------------------------------------------------------ @@ -102,7 +102,7 @@ class _MarkdownRenderer(HTMLParser): # ------------------------------------------------------------------ def _prefix_blockquote(self, content: str) -> str: """Prefix every line of *content* with ``> ``.""" - # Strip trailing whitespace first, then collapse blank lines + # Strip trailing whitespace, then collapse blank lines. content = re.sub(r"[ \t]+$", "", content, flags = re.MULTILINE) content = re.sub(r"\n{3,}", "\n\n", content).strip() if not content: @@ -117,8 +117,8 @@ class _MarkdownRenderer(HTMLParser): return "\n".join(prefixed) # ------------------------------------------------------------------ - # Table helpers -- flush open cells and rows so that HTML with - # omitted optional end tags (, ) does not lose data. + # Table helpers -- flush open cells/rows so HTML with omitted optional + # end tags (, ) does not lose data. # ------------------------------------------------------------------ def _finish_cell(self) -> None: if not self._in_cell: @@ -143,8 +143,8 @@ class _MarkdownRenderer(HTMLParser): self._row_has_th = False # ------------------------------------------------------------------ - # Link text helper -- normalize whitespace so block-level content - # inside an does not produce multiline Markdown link labels. + # Link text helper -- normalize whitespace so block-level content inside + # an does not produce multiline Markdown link labels. # ------------------------------------------------------------------ def _finish_link(self) -> None: text = re.sub(r"\s+", " ", "".join(self._link_text_parts)).strip() @@ -234,13 +234,13 @@ class _MarkdownRenderer(HTMLParser): self._emit("\n\n") elif tag == "tr": - # Flush any open cell/row from a previous row that may - # have omitted its optional or end tags. + # Flush any open cell/row from a previous row that omitted its + # optional or end tags. self._finish_cell() self._finish_row() elif tag in ("th", "td"): - # Flush any open cell (handles omitted /) + # Flush any open cell (handles omitted /). self._finish_cell() self._cell_parts = [] self._in_cell = True @@ -248,8 +248,8 @@ class _MarkdownRenderer(HTMLParser): self._row_has_th = True elif tag == "img": - # Skip images -- keeps fetched page text focused on readable - # content and avoids data-URI amplification. + # Skip images -- keeps page text focused on readable content and + # avoids data-URI amplification. return def handle_endtag(self, tag: str) -> None: @@ -310,7 +310,7 @@ class _MarkdownRenderer(HTMLParser): self._finish_row() elif tag == "table": - # Flush any remaining row (handles omitted ) + # Flush any remaining row (handles omitted ). self._finish_cell() self._finish_row() self._in_table = False @@ -325,15 +325,15 @@ class _MarkdownRenderer(HTMLParser): if self._in_pre: self._pre_parts.append(data) return - # Preserve literal whitespace inside inline spans + # Preserve literal whitespace inside inline spans. if self._in_inline_code: self._emit(data) return - # Collapse all whitespace (including newlines) per HTML rules + # Collapse all whitespace (including newlines) per HTML rules. text = re.sub(r"\s+", " ", data) - # Suppress whitespace-only text nodes between table structural - # elements (indentation from source HTML) to prevent leading - # spaces from breaking Markdown table row alignment. + # Suppress whitespace-only text nodes between table structural elements + # (source indentation) so leading spaces don't break Markdown table + # row alignment. if self._in_table and not self._in_cell and not text.strip(): return self._emit(text) @@ -354,9 +354,9 @@ class _MarkdownRenderer(HTMLParser): def flush_pending(self) -> None: """Flush any open side-buffers into ``_out``. - Called after ``close()`` to recover content from truncated HTML - where closing tags were never seen (common when ``_fetch_page_text`` - caps the download by byte count). + Called after ``close()`` to recover content from truncated HTML where + closing tags were never seen (common when ``_fetch_page_text`` caps the + download by byte count). """ # Flush innermost buffers first so their content propagates outward. @@ -376,7 +376,7 @@ class _MarkdownRenderer(HTMLParser): block = "```\n" + raw + "\n```" self._emit("\n\n" + block + "\n\n") - # Flatten any open blockquote buffers (innermost first) + # Flatten any open blockquote buffers (innermost first). while self._bq_stack: content = "".join(self._bq_stack.pop()) prefixed = self._prefix_blockquote(content) @@ -394,8 +394,8 @@ class _MarkdownRenderer(HTMLParser): def _cleanup(text: str) -> str: """Normalize whitespace and blank lines in the final output. - Preserves content inside fenced code blocks verbatim so that - intentional blank lines in ``
`` content are not collapsed.
+    Preserves content inside fenced code blocks verbatim so intentional blank
+    lines in ``
`` content are not collapsed.
     """
     lines = text.split("\n")
     out: list[str] = []
@@ -411,7 +411,7 @@ def _cleanup(text: str) -> str:
             continue
 
         if in_fence:
-            # Preserve code block content exactly as-is
+            # Preserve code block content exactly as-is.
             out.append(line)
             continue
 
@@ -433,11 +433,11 @@ def _cleanup(text: str) -> str:
 def html_to_markdown(source_html: str) -> str:
     """Convert an HTML string to Markdown.
 
-    Handles headings, links, bold/italic, lists (ordered and unordered),
-    tables, blockquotes, code blocks, and HTML entities.  ``")
@@ -98,9 +96,7 @@ def test_is_same_origin_request_data_url_origin_is_cross_origin():
 
 
 def test_is_same_origin_request_blob_url_origin_is_cross_origin():
-    """``blob:`` URLs carry the inner origin only in non-canonical form; the
-    canonical comparison rejects them.
-    """
+    """``blob:`` URLs carry the inner origin only in non-canonical form; the canonical comparison rejects them."""
     from main import _is_same_origin_request
 
     req = _build_request("127.0.0.1:8902", origin = "blob:http://127.0.0.1:8902/uuid")
@@ -108,8 +104,8 @@ def test_is_same_origin_request_blob_url_origin_is_cross_origin():
 
 
 def test_is_same_origin_request_file_url_origin_is_cross_origin():
-    """``file://`` pages usually send ``Origin: null``; historical engines
-    sent ``Origin: file://``. Neither is same-origin vs an http listener.
+    """``file://`` pages usually send ``Origin: null``; older engines sent
+    ``Origin: file://``. Neither is same-origin vs an http listener.
     """
     from main import _is_same_origin_request
 
@@ -121,8 +117,8 @@ def test_is_same_origin_request_file_url_origin_is_cross_origin():
 
 
 def test_is_same_origin_request_comma_joined_origins_cross_origin():
-    """Starlette concatenates repeated headers with ``, ``; the canonical
-    parser can't safely split this, so it falls to cross-origin.
+    """Starlette joins repeated headers with ``, ``; the canonical parser can't
+    safely split this, so it falls to cross-origin.
     """
     from main import _is_same_origin_request
 
@@ -137,8 +133,8 @@ def test_is_same_origin_request_comma_joined_origins_cross_origin():
 
 
 def test_is_same_origin_request_localhost_vs_127_is_cross_origin():
-    """Browsers treat ``localhost`` and ``127.0.0.1`` as distinct origins;
-    the canonical comparison must not DNS-collapse them.
+    """Browsers treat ``localhost`` and ``127.0.0.1`` as distinct origins; the
+    canonical comparison must not DNS-collapse them.
     """
     from main import _is_same_origin_request
 
@@ -157,7 +153,7 @@ def test_is_same_origin_request_127_vs_localhost_is_cross_origin():
 
 def test_is_same_origin_request_malformed_ipv6_bracket_is_cross_origin():
     """``urlparse`` raises ``ValueError('Invalid IPv6 URL')`` on unclosed
-    brackets (CVE-2024-11168 hardening). The gate must swallow and fall to
+    brackets (CVE-2024-11168 hardening). The gate must swallow it and fall to
     cross-origin rather than 500 the SPA handler.
     """
     from main import _is_same_origin_request
@@ -184,8 +180,8 @@ def test_is_same_origin_request_bracket_with_trailing_garbage_is_cross_origin():
 
 
 def test_is_same_origin_request_empty_origin_header_is_cross_origin():
-    """Explicit empty ``Origin:`` is not a valid serialised origin and must
-    not be conflated with a missing header; cross-origin, bootstrap withheld.
+    """Explicit empty ``Origin:`` is not a valid serialised origin and must not
+    be conflated with a missing header; cross-origin, bootstrap withheld.
     """
     from main import _is_same_origin_request
 
diff --git a/studio/backend/tests/test_inference_model_validation.py b/studio/backend/tests/test_inference_model_validation.py
index faf5a67873..dddf5c8052 100644
--- a/studio/backend/tests/test_inference_model_validation.py
+++ b/studio/backend/tests/test_inference_model_validation.py
@@ -170,16 +170,15 @@ def test_walkback_does_not_cross_user_turn():
         ]
     )
     last = req.messages[-1].tool_call_id
-    # The walkback must NOT pick old_call because a user turn intervenes;
-    # falls back to synth.
+    # Walkback must NOT pick old_call across a user turn; falls back to synth.
     assert last is not None
     assert last != "old_call"
     assert last.startswith("call_")
 
 
 def test_walkback_skips_explicitly_consumed_tool_call_id():
-    """Sibling tool result with an explicit id must reserve its assistant
-    slot so a follow-up missing-id result picks the OTHER tool call."""
+    """An explicit-id tool result reserves its assistant slot so a
+    follow-up missing-id result picks the OTHER tool call."""
     req = _req(
         [
             {
diff --git a/studio/backend/tests/test_kv_cache_estimation.py b/studio/backend/tests/test_kv_cache_estimation.py
index 001b5f1bee..cd679b0bf1 100644
--- a/studio/backend/tests/test_kv_cache_estimation.py
+++ b/studio/backend/tests/test_kv_cache_estimation.py
@@ -7,8 +7,7 @@ Covers the GGUF metadata parser, _can_estimate_kv gate, all 5 estimation
 paths (MLA, Hybrid Mamba, Sliding Window, Standard GQA, Legacy), KV cache
 quantization, edge cases, and lifecycle (init/unload/reparse).
 
-Requires no GPU, network, or external libraries beyond pytest.
-Cross-platform: Linux, macOS, Windows, WSL.
+No GPU, network, or libraries beyond pytest. Cross-platform.
 """
 
 import io
@@ -21,8 +20,8 @@ from pathlib import Path
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test.  Same pattern as test_native_context_length.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_native_context_length.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -38,11 +37,10 @@ sys.modules.setdefault("loggers", _loggers_stub)
 _structlog_stub = _types.ModuleType("structlog")
 sys.modules.setdefault("structlog", _structlog_stub)
 
-# httpx -- only stub when the real library isn't installed.  Stubbing
-# unconditionally would shadow ``HTTPError`` / ``Response`` etc. that
-# ``huggingface_hub.errors`` imports at module load time, which causes
-# the transformers introspection tier to silently return None inside
-# the test process.
+# httpx -- only stub when the real library isn't installed. Stubbing
+# unconditionally shadows ``HTTPError`` / ``Response`` etc. that
+# ``huggingface_hub.errors`` imports at load time, making the transformers
+# introspection tier silently return None in the test process.
 try:
     import httpx as _httpx_real  # noqa: F401
 except ImportError:
@@ -84,9 +82,9 @@ from core.inference.llama_cpp import LlamaCppBackend
 
 
 def _make_gguf_bytes(arch: str, kv_pairs: dict) -> bytes:
-    """Build a minimal GGUF v3 binary blob with the given KV metadata.
+    """Build a minimal GGUF v3 blob with the given KV metadata.
 
-    Supports the scalar and simple array metadata used by the parser.
+    Supports the scalar and simple array metadata the parser uses.
     """
     buf = io.BytesIO()
     # Header: magic, version, tensor_count, kv_count
@@ -134,9 +132,8 @@ def _backend_from_gguf(
 ) -> LlamaCppBackend:
     """Create a LlamaCppBackend with parsed GGUF metadata from given fields.
 
-    `general` lets a test inject extra `general.*` metadata (used to
-    verify the dynamic SWA resolver picks up source-repo hints from
-    GGUFs that ship them).
+    `general` injects extra `general.*` metadata, to verify the dynamic
+    SWA resolver picks up source-repo hints from GGUFs that ship them.
     """
     kv = {"general.architecture": arch}
     for k, v in (general or {}).items():
@@ -163,7 +160,7 @@ def _backend_from_gguf(
 
 
 class TestGGUFParserNewFields:
-    """Verify that architecture-aware fields are correctly parsed."""
+    """Architecture-aware fields are parsed correctly."""
 
     @pytest.mark.parametrize(
         "field,gguf_key,value",
@@ -217,9 +214,9 @@ class TestGGUFParserNewFields:
         )
         # Per-layer KV head count is preserved exactly...
         assert b._n_kv_heads_by_layer == [8, 8, 8, 8, 8, 2]
-        # ...and mirrored into the scalar field as a conservative max so
-        # non-SWA estimator paths and any caller using
-        # `n_kv = self._n_kv_heads or ...` get a safe upper bound.
+        # ...and mirrored into the scalar field as a conservative max, so
+        # non-SWA paths and callers using `n_kv = self._n_kv_heads or ...`
+        # get a safe upper bound.
         assert b._n_kv_heads == 8
         assert b._sliding_window_pattern == [True, True, True, True, True, False]
 
@@ -270,7 +267,7 @@ class TestArchSwaPatternDefaults:
         assert b._sliding_window_pattern is None
 
     def test_explicit_pattern_overrides_arch_default(self):
-        # Period=6 is the gemma3 default; the explicit array must win.
+        # gemma3 default is period=6; the explicit array must win.
         b = _backend_from_gguf(
             "gemma3",
             {
@@ -310,8 +307,8 @@ class TestArchSwaPatternDefaults:
         "arch", ["llama", "qwen2", "qwen3", "mistral", "mistral3", "glm4", "llama4"]
     )
     def test_non_swa_arch_uses_full_attention_path(self, arch):
-        # Pure-GQA arches: GGUF has no sliding_window, no synthetic
-        # pattern, estimator hits Path 4.
+        # Pure-GQA arches: no sliding_window, no synthetic pattern,
+        # estimator hits Path 4.
         b = _backend_from_gguf(
             arch,
             {
@@ -340,7 +337,7 @@ class TestArchSwaPatternDefaults:
             "embedding_length": 5376,
         }
         with_default = _backend_from_gguf("gemma3", common)
-        # Arch not in the table -> legacy 1/4 path.
+        # Arch not in table -> legacy 1/4 path.
         without_default = _backend_from_gguf("totallymadeupv7", common)
 
         kv_default = with_default._estimate_kv_cache_bytes(131072, "f16")
@@ -430,7 +427,7 @@ class TestDynamicSwaResolver:
     def test_period_from_layer_types_finds_smallest_period(self):
         from core.inference.llama_cpp import _period_from_layer_types
 
-        # gemma3 (1 global per 6), gpt-oss (alternating), gemma3n (1 per 5).
+        # gemma3 (1 global/6), gpt-oss (alternating), gemma3n (1/5).
         assert _period_from_layer_types((["sliding_attention"] * 5 + ["full_attention"]) * 4) == 6
         assert _period_from_layer_types(["sliding_attention", "full_attention"] * 12) == 2
         assert _period_from_layer_types((["sliding_attention"] * 4 + ["full_attention"]) * 7) == 5
@@ -481,14 +478,14 @@ class TestDynamicSwaResolver:
 
     def test_disk_cache_takes_precedence_over_bootstrap(self, monkeypatch, tmp_path):
         self._isolate_cache(monkeypatch, tmp_path)
-        # Override bootstrap=6 with a cached period=3.
+        # Cached period=3 overrides bootstrap=6.
         with open(tmp_path / "swa_cache.json", "w") as f:
             json.dump({"gemma3": 3}, f)
         b = _backend_from_gguf("gemma3", dict(_SWA_FIELDS, block_count = 18))
         assert b._sliding_window_pattern == [(i + 1) % 3 != 0 for i in range(18)]
 
     def test_disk_cache_supports_array_entries(self, monkeypatch, tmp_path):
-        # Aperiodic mask gets tiled across n_layers.
+        # Aperiodic mask is tiled across n_layers.
         self._isolate_cache(monkeypatch, tmp_path)
         mask = [True, False, True, True, False, True, False, False]
         with open(tmp_path / "swa_cache.json", "w") as f:
@@ -556,7 +553,7 @@ class TestDynamicSwaResolver:
         from core.inference import llama_cpp as lc
 
         monkeypatch.setattr(lc, "_fetch_swa_entry_from_hf", lambda repo_id: None)
-        # Force the failure into the Tier 3 path; bypass Tier 2.5.
+        # Force failure into Tier 3; bypass Tier 2.5.
         monkeypatch.setattr(lc, "_resolve_swa_entry_from_transformers", lambda arch: None)
         b = _backend_from_gguf(
             "newmodel",
@@ -639,7 +636,7 @@ class TestTransformersIntrospection:
         assert _resolve_swa_entry_from_transformers("totally-fake-arch-xyz") is None
 
     def test_full_resolver_uses_transformers_before_hf_fetch(self, monkeypatch, tmp_path):
-        # With bootstrap empty, Tier 2.5 must answer before Tier 3 fires.
+        # Bootstrap empty: Tier 2.5 must answer before Tier 3 fires.
         self._isolate_cache(monkeypatch, tmp_path)
         from core.inference import llama_cpp as lc
 
@@ -660,10 +657,10 @@ class TestTransformersIntrospection:
 
 
 class TestGGUFParserReset:
-    """Verify that fields are properly reset between parses."""
+    """Fields are reset between parses."""
 
     def test_reset_between_parses(self):
-        # First parse with all fields
+        # First parse: all fields set
         b = _backend_from_gguf(
             "arch1",
             {
@@ -685,7 +682,7 @@ class TestGGUFParserReset:
         assert b._kv_value_length_swa == 64
         assert b._ssm_inner_size == 4096
 
-        # Second parse without those fields -- they should be None
+        # Second parse without those fields -- they must be None
         kv = {"general.architecture": "arch2", "arch2.block_count": 64}
         import tempfile, os
 
@@ -713,7 +710,7 @@ class TestGGUFParserReset:
 
 
 class TestCanEstimateKV:
-    """Verify gate logic for all field combinations."""
+    """Gate logic for all field combinations."""
 
     def test_no_layers_returns_false(self):
         b = LlamaCppBackend()
@@ -729,7 +726,7 @@ class TestCanEstimateKV:
         assert b._can_estimate_kv()
 
     def test_key_length_alone_insufficient(self):
-        """key_length without value_length should NOT be enough."""
+        """key_length without value_length is NOT enough."""
         b = LlamaCppBackend()
         b._n_layers = 32
         b._kv_key_length = 128
@@ -799,33 +796,33 @@ class TestMLAEstimation:
         assert b._estimate_kv_cache_bytes(163840, "f16") == expected
 
     def test_mla_ignores_value_length(self):
-        """MLA should NOT add value_length -- V is reconstructed from the latent."""
+        """MLA must NOT add value_length -- V is reconstructed from the latent."""
         b = self._mla_backend()
         result = b._estimate_kv_cache_bytes(1000, "f16")
-        # Should be n_layers * ctx * 1 * key_len(576) * 2
+        # n_layers * ctx * 1 * key_len(576) * 2
         expected = 61 * 1000 * 1 * 576 * 2
         assert result == expected
 
     def test_mla_fallback_when_no_key_length(self):
-        """If key_length is missing, fallback to kv_lora_rank + key_length_mla."""
+        """No key_length: fall back to kv_lora_rank + key_length_mla."""
         b = self._mla_backend(_kv_key_length = None)
-        # _key_length_mla=192 in default, so rope_dim=192
+        # default _key_length_mla=192, so rope_dim=192
         result = b._estimate_kv_cache_bytes(1000, "f16")
         expected = 61 * 1000 * 1 * (512 + 192) * 2  # 704
         assert result == expected
 
     def test_mla_fallback_no_key_length_mla(self):
-        """If both key_length and key_length_mla are missing, fallback to +64."""
+        """No key_length and no key_length_mla: fall back to +64."""
         b = self._mla_backend(_kv_key_length = None, _key_length_mla = None)
         result = b._estimate_kv_cache_bytes(1000, "f16")
         expected = 61 * 1000 * 1 * (512 + 64) * 2  # 576
         assert result == expected
 
     def test_mla_defaults_n_kv_to_1_when_heads_absent(self):
-        """MLA should use n_kv=1 even if n_kv_heads is None (not n_heads)."""
+        """MLA uses n_kv=1 even if n_kv_heads is None (not n_heads)."""
         b = self._mla_backend(_n_kv_heads = None)  # n_heads=128 still set
         result = b._estimate_kv_cache_bytes(1000, "f16")
-        # Should use n_kv_mla=1, NOT n_heads=128
+        # Uses n_kv_mla=1, NOT n_heads=128
         expected = 61 * 1000 * 1 * 576 * 2
         assert result == expected
 
@@ -883,14 +880,14 @@ class TestHybridMambaEstimation:
         assert b._estimate_kv_cache_bytes(262144, "f16") == expected
 
     def test_hybrid_without_explicit_dims(self):
-        """Fallback to head_dim when key_length/value_length are missing."""
+        """Fall back to head_dim when key_length/value_length are missing."""
         b = self._hybrid_backend(_kv_key_length = None, _kv_value_length = None)
         head_dim = 5120 // 24  # 213
         expected = 16 * 4096 * 4 * 2 * head_dim * 2
         assert b._estimate_kv_cache_bytes(4096, "f16") == expected
 
     def test_fai_zero_safety(self):
-        """full_attention_interval=0 should not cause ZeroDivisionError."""
+        """full_attention_interval=0 must not ZeroDivisionError."""
         b = self._hybrid_backend(_full_attention_interval = 0)
         result = b._estimate_kv_cache_bytes(4096, "f16")
         # fai=0 -> n_attn = n_layers (all layers)
@@ -978,7 +975,7 @@ class TestSlidingWindowEstimation:
             assert b._estimate_kv_cache_bytes(ctx, "f16") == expected(ctx)
 
     def test_ctx_smaller_than_window(self):
-        """When context < 2 * sliding_window, SWA cache caps at ctx."""
+        """When ctx < 2 * sliding_window, SWA cache caps at ctx."""
         b = self._swa_backend(_sliding_window = 8192)
         n_global = max(1, 62 // 4)  # 15
         n_swa = 62 - n_global  # 47
@@ -1031,11 +1028,11 @@ class TestStandardGQAEstimation:
         assert b._estimate_kv_cache_bytes(4096, "f16") == expected
 
     def test_differs_from_legacy(self):
-        """GQA path should differ from legacy when key_length != embed//n_heads."""
+        """GQA path differs from legacy when key_length != embed//n_heads."""
         b = self._gqa_backend()
         head_dim = 1024 // 16  # 64
         gqa_result = b._estimate_kv_cache_bytes(4096, "f16")
-        # Legacy would use: 2 * 8 * 64 * 28 * 4096 * 2
+        # Legacy: 2 * 8 * 64 * 28 * 4096 * 2
         legacy_result = int(2 * 8 * head_dim * 28 * 4096 * 2)
         # GQA: 28 * 4096 * 8 * (128+128) * 2 -- uses actual key_length=128
         assert gqa_result != legacy_result
@@ -1077,7 +1074,7 @@ class TestLegacyEstimation:
         assert b._estimate_kv_cache_bytes(4096, "f16") == expected
 
     def test_legacy_identical_to_old_formula(self):
-        """Confirm legacy path produces the same result as the pre-PR formula."""
+        """Legacy path matches the pre-PR formula."""
         b = self._legacy_backend()
         n_layers = 32
         n_kv_heads = 8
@@ -1097,7 +1094,7 @@ class TestPathPriority:
     """Confirm: MLA > Hybrid Mamba > SWA > GQA > Legacy."""
 
     def test_mla_takes_priority_over_all(self):
-        """If kv_lora_rank is set, MLA path is used even if other fields are present."""
+        """If kv_lora_rank is set, MLA path wins even with other fields present."""
         b = LlamaCppBackend()
         b._n_layers = 61
         b._n_kv_heads = 1
@@ -1132,9 +1129,9 @@ class TestPathPriority:
         assert b._estimate_kv_cache_bytes(1000, "f16") == expected_hybrid
 
     def test_all_paths_produce_different_values(self):
-        """With carefully chosen params, each path should yield a distinct value."""
-        # Use embedding_length=768 so legacy head_dim (768//16=48) differs from
-        # key_length (256), and MLA key_len (256) != legacy K+V (2*48=96).
+        """With chosen params, each path yields a distinct value."""
+        # embedding_length=768 so legacy head_dim (768//16=48) != key_length
+        # (256), and MLA key_len (256) != legacy K+V (2*48=96).
         params = {
             "_n_layers": 40,
             "_n_kv_heads": 4,
@@ -1191,7 +1188,7 @@ class TestPathPriority:
 
 
 class TestQuantization:
-    """Verify all supported cache_type_kv values produce correct scaling."""
+    """All supported cache_type_kv values scale correctly."""
 
     @pytest.mark.parametrize(
         "cache_type,expected_bpe",
@@ -1332,7 +1329,7 @@ class TestServerFlags:
         b = self._swa_backend()
         ctx = 32_768
         flagged = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
-        # With swa_full, every layer caches n_ctx -- equals path 4 sizing.
+        # swa_full: every layer caches n_ctx -- equals path 4 sizing.
         kv_per_token = 4 * (256 + 256) * 2  # n_kv_heads * (k+v) * f16
         expected = 26 * ctx * kv_per_token
         assert flagged == expected
@@ -1366,10 +1363,9 @@ class TestServerFlags:
         assert with_cp > b._estimate_kv_cache_bytes(8192, "f16")
 
     # ── --parallel + --kv-unified ──────────────────────────────────
-    # Empirically verified against llama-server: non-SWA caches partition
-    # n_ctx across slots (total memory constant); SWA layers are the only
-    # portion that scales with --parallel.  --kv-unified is currently a
-    # no-op for memory math (kept for API forward-compat).
+    # Verified against llama-server: non-SWA caches partition n_ctx across
+    # slots (total memory constant); only SWA layers scale with --parallel.
+    # --kv-unified is a no-op for memory math (kept for API forward-compat).
 
     def test_gqa_kv_constant_across_parallel(self):
         b = self._gqa_backend()
@@ -1394,7 +1390,7 @@ class TestServerFlags:
         b = self._swa_backend()
         ctx = 8192
         baseline = b._estimate_kv_cache_bytes(ctx, "f16")
-        # Decompose baseline by walking the same loop the estimator does.
+        # Decompose baseline by walking the estimator's own loop.
         swa = b._sliding_window
         per_token_global = 4 * (256 + 256) * 2  # n_kv * (k+v) * f16
         per_token_swa = 4 * (256 + 256) * 2  # k_swa/val_swa fall back
@@ -1409,10 +1405,10 @@ class TestServerFlags:
         )
         # Sanity: parallel=1 reproduces baseline exactly
         assert global_bytes + swa_bytes_per_slot == baseline
-        # Only SWA portion scales by parallel
+        # Only the SWA portion scales by parallel
         for slots in (1, 2, 3, 4):
             scaled = b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = slots, kv_unified = False)
-            # SWA cells get clamped to per_slot_ctx when ctx/slots < 2*swa
+            # SWA cells clamp to per_slot_ctx when ctx/slots < 2*swa
             per_slot_ctx = max(1, ctx // slots)
             cells = min(ctx, 2 * swa, per_slot_ctx)
             swa_bps = sum(
@@ -1452,7 +1448,7 @@ class TestServerFlags:
         ctx = 8192
         baseline = b._estimate_kv_cache_bytes(ctx, "f16")
         flagged = b._estimate_kv_cache_bytes(ctx, "f16", ctx_checkpoints = 4)
-        # 22 SWA layers * 4 checkpoints * 512 cells * 4 heads * (256+256) * 2 bytes
+        # 22 SWA layers * 4 cps * 512 cells * 4 heads * (256+256) * 2 bytes
         n_swa_layers = sum(1 for f in [True, True, True, True, True, False] * 4 + [True, True] if f)
         per_layer = 4 * 512 * 4 * (256 + 256) * 2
         assert flagged == baseline + n_swa_layers * per_layer
@@ -1470,7 +1466,7 @@ class TestServerFlags:
 
     def test_ctx_checkpoints_compose_with_n_parallel(self):
         # Only the SWA + checkpoint portion scales by n_parallel; the
-        # global-layer portion stays constant.
+        # global-layer portion is constant.
         b = self._swa_backend()
         ctx = 8192
         swa = b._sliding_window
@@ -1493,7 +1489,7 @@ class TestServerFlags:
 
     def test_fit_returns_requested_when_kv_off_gpu(self):
         b = self._gqa_backend()
-        # Tiny VRAM budget -- normally would force a reduction.
+        # Tiny VRAM budget -- would normally force a reduction.
         fitted = b._fit_context_to_vram(
             requested_ctx = 32_768,
             available_mib = 1,
@@ -1515,8 +1511,8 @@ class TestServerFlags:
         assert fitted < 32_768
 
     def test_fit_mtp_engaged_returns_smaller_or_equal_context(self):
-        # MTP-engaged budget is 0.85 of available; non-MTP is 0.90.
-        # On a tight budget the MTP path must yield <= the non-MTP path.
+        # MTP budget is 0.85 of available, non-MTP is 0.90; on a tight
+        # budget MTP must yield <= non-MTP.
         b = self._gqa_backend()
         common = dict(
             requested_ctx = 32_768,
@@ -1529,7 +1525,7 @@ class TestServerFlags:
         assert mtp <= baseline
 
     def test_fit_mtp_engaged_unchanged_when_kv_off_gpu(self):
-        # kv_on_gpu=False short-circuits the fit; mtp_engaged is irrelevant.
+        # kv_on_gpu=False short-circuits the fit; mtp_engaged irrelevant.
         b = self._gqa_backend()
         fitted = b._fit_context_to_vram(
             requested_ctx = 32_768,
@@ -1548,7 +1544,7 @@ class TestServerFlags:
         kv_default = b._estimate_kv_cache_bytes(ctx, "f16")
         kv_full = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
         assert kv_full > kv_default
-        # Budget = model + kv_default (rounded up) -- swa_full should not fit.
+        # Budget = model + kv_default (rounded up) -- swa_full must not fit.
         budget_mib = (1024 * 1024 + kv_default) / (1024 * 1024) / 0.90 + 1
         fitted_default = b._fit_context_to_vram(
             requested_ctx = ctx,
@@ -1573,16 +1569,16 @@ class TestServerFlags:
 
 
 class TestParallelSWAScaling:
-    """Verifies the per-layer-type scaling rule against the closed form
-    measured from llama-server. Empirical formula on Gemma-3 270m at
-    ctx=8192: total_kv = 24 + parallel * 15 (MiB).
+    """Per-layer-type scaling rule vs the closed form measured from
+    llama-server. Empirical formula on Gemma-3 270m at ctx=8192:
+    total_kv = 24 + parallel * 15 (MiB).
 
     Rule (verified vs ``llama-server`` log on real GGUFs):
       * non-SWA layers: total cells = n_ctx, partitioned across slots,
         memory CONSTANT in n_parallel.
       * SWA layers: per-slot cells = 2 * sliding_window (clamped at
         n_ctx and at per_slot_ctx); memory LINEAR in n_parallel.
-      * --kv-unified is a no-op for memory math; both modes yield the
+      * --kv-unified is a no-op for memory math; both modes give the
         same total in measured cases.
     """
 
@@ -1703,7 +1699,7 @@ class TestParallelSWAScaling:
 
     def test_swa_per_slot_clamped_when_ctx_lt_slots_x_2window(self):
         # ctx=4096 / slots=8 -> per_slot_ctx=512, but 2*sliding=1024.
-        # SWA cells should clamp at per_slot_ctx (512), not 2*sliding.
+        # SWA cells clamp at per_slot_ctx (512), not 2*sliding.
         b = self._swa_backend()
         ctx = 4096
         per_slot_ctx_at_8 = ctx // 8
@@ -1719,8 +1715,8 @@ class TestParallelSWAScaling:
         assert b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = 8) == expected
 
     def test_swa_full_does_not_scale_under_parallel(self):
-        # swa_full forces every layer to n_ctx; result is the all-global
-        # GQA-style total, which is constant in parallel.
+        # swa_full forces every layer to n_ctx -> all-global GQA-style
+        # total, constant in parallel.
         b = self._swa_backend()
         ctx = 8192
         baseline = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
@@ -1732,8 +1728,8 @@ class TestParallelSWAScaling:
     # ── kv_unified: no-op for memory math ──────────────────────────
 
     def test_kv_unified_is_no_op_for_memory_math(self):
-        # Both unified=True and unified=False must produce the same
-        # total bytes for every backend type and every parallel value.
+        # unified=True and unified=False must give the same total bytes
+        # for every backend type and parallel value.
         backends = [
             ("gqa", self._gqa_backend()),
             ("swa", self._swa_backend()),
@@ -1761,9 +1757,8 @@ class TestParallelSWAScaling:
         b._kv_key_length = 256
         b._kv_value_length = 256
         b._sliding_window = 512
-        # 5-period [swa,swa,swa,swa,full] * 3 + [swa,swa,swa]: mirrors the
-        # bootstrap-resolved pattern for gemma3 (period 6) on an 18-layer
-        # model (15 SWA, 3 global).
+        # Mirrors the bootstrap-resolved gemma3 pattern (period 6) on an
+        # 18-layer model: 15 SWA, 3 global.
         b._sliding_window_pattern = [(i + 1) % 6 != 0 for i in range(18)]
         n_global = 3
         n_swa = 15
@@ -1784,13 +1779,13 @@ class TestParallelSWAScaling:
 
 class TestSharedKVLayers:
     """``.attention.shared_kv_layers`` reduces the layer count that
-    actually allocates KV.  The trailing ``shared_kv_layers`` blocks reuse
-    earlier caches (Gemma 3n: 35 layers, 15 shared -> 20 allocate; Gemma 4
-    same field).  Unset on every other arch -> no behavioural change."""
+    allocates KV. The trailing ``shared_kv_layers`` blocks reuse earlier
+    caches (Gemma 3n: 35 layers, 15 shared -> 20 allocate; Gemma 4 same
+    field). Unset on every other arch -> no behavioural change."""
 
     def _gemma3n_backend(self, **overrides):
-        # Mirrors google/gemma-3n-E4B-it: 35 layers, 15 shared,
-        # SWA window 1024, period 5 (4 sliding + 1 full repeating).
+        # Mirrors google/gemma-3n-E4B-it: 35 layers, 15 shared, SWA window
+        # 1024, period 5 (4 sliding + 1 full repeating).
         defaults = {
             "_n_layers": 35,
             "_n_kv_heads": 4,
@@ -1873,9 +1868,8 @@ class TestSharedKVLayers:
     def test_path3_pattern_loops_only_unshared_layers(self):
         b = self._gemma3n_backend()
         ctx = 8192
-        # First 20 layers contribute; layers 20..34 are skipped.
-        # Pattern: [s,s,s,s,F] repeated.  In layers 0..19:
-        #   sliding: 16, full: 4
+        # First 20 layers contribute; layers 20..34 skipped. Pattern
+        # [s,s,s,s,F] repeated -> in layers 0..19: sliding 16, full 4.
         sliding_in_unshared = sum(b._sliding_window_pattern[:20])
         full_in_unshared = 20 - sliding_in_unshared
         assert sliding_in_unshared == 16
@@ -1890,7 +1884,7 @@ class TestSharedKVLayers:
         with_shared = b._estimate_kv_cache_bytes(8192, "f16")
         b._shared_kv_layers = 0
         without_shared = b._estimate_kv_cache_bytes(8192, "f16")
-        # 20/35 = 0.571 of the work; expect ~43% reduction.
+        # 20/35 = 0.571 of the work; ~43% reduction.
         ratio = with_shared / without_shared
         assert 0.5 < ratio < 0.65
 
@@ -1898,8 +1892,8 @@ class TestSharedKVLayers:
         b = self._gemma3n_backend()
         ctx = 8192
         flagged = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)
-        # Every unshared layer caches n_ctx; equals path-4-style sizing
-        # over only the 20 unshared layers.
+        # Every unshared layer caches n_ctx -> path-4-style sizing over
+        # only the 20 unshared layers.
         kv_per = 4 * (256 + 256) * 2
         assert flagged == 20 * ctx * kv_per
 
@@ -1917,15 +1911,15 @@ class TestSharedKVLayers:
         assert b._estimate_kv_cache_bytes(ctx, "f16") == expected
 
     def test_shared_floors_at_one_layer(self):
-        # Pathological: shared >= n_layers should not zero out the cache.
+        # Pathological: shared >= n_layers must not zero out the cache.
         b = self._gqa_backend(_shared_kv_layers = 99)
         ctx = 4096
         kv_per = 8 * (128 + 128) * 2
         assert b._estimate_kv_cache_bytes(ctx, "f16") == 1 * ctx * kv_per
 
     def test_composes_with_n_parallel(self):
-        # Only the SWA portion of the unshared layers scales by n_parallel;
-        # the global portion stays constant.
+        # Only the SWA portion of unshared layers scales by n_parallel;
+        # the global portion is constant.
         b = self._gemma3n_backend()
         ctx = 8192
         swa = b._sliding_window
@@ -1946,7 +1940,7 @@ class TestSharedKVLayers:
         ctx = 8192
         baseline = b._estimate_kv_cache_bytes(ctx, "f16")
         with_cp = b._estimate_kv_cache_bytes(ctx, "f16", ctx_checkpoints = 4)
-        # Checkpoints only count over UNSHARED SWA layers (16 of them).
+        # Checkpoints count only over UNSHARED SWA layers (16 of them).
         sliding_in_unshared = sum(b._sliding_window_pattern[:20])
         per_cp_layer = 4 * 1024 * 4 * (256 + 256) * 2  # cps * swa * heads * (k+v) * bpe
         assert with_cp == baseline + sliding_in_unshared * per_cp_layer
@@ -2017,7 +2011,7 @@ class TestLifecycle:
         assert b._n_kv_heads_by_layer is None
 
     def test_end_to_end_synthetic_mla(self):
-        """Full round-trip: write GGUF -> parse -> estimate."""
+        """Round-trip: write GGUF -> parse -> estimate."""
         b = _backend_from_gguf(
             "deepseek2",
             {
@@ -2075,8 +2069,8 @@ class TestLifecycle:
         )
         assert b._can_estimate_kv()
         result = b._estimate_kv_cache_bytes(131072, "f16")
-        # gemma3 -> period 6 from the bootstrap table, SWA cache
-        # double-buffered to 2 * sliding_window cells.
+        # gemma3 -> period 6 from bootstrap; SWA cache double-buffered to
+        # 2 * sliding_window cells.
         period = 6
         kv_per = 16 * 256 * 2
         expected = 0
@@ -2104,13 +2098,13 @@ class TestLifecycle:
         )
         assert b._can_estimate_kv()
         assert b._shared_kv_layers == 15
-        # Bootstrap table for gemma3n_text -> period 5; the resolver
-        # synthesises a 35-entry bool array.  The first 20 entries
-        # (n_layers - shared) are the only ones that allocate KV.
+        # Bootstrap for gemma3n_text -> period 5; resolver synthesises a
+        # 35-entry bool array. Only the first 20 (n_layers - shared)
+        # allocate KV.
         result = b._estimate_kv_cache_bytes(8192, "f16")
         assert result > 0
-        # Sanity: setting shared back to 0 must produce a strictly larger
-        # estimate (more layers allocate).
+        # Sanity: shared back to 0 -> strictly larger estimate (more
+        # layers allocate).
         b._shared_kv_layers = 0
         unshared = b._estimate_kv_cache_bytes(8192, "f16")
         assert unshared > result
diff --git a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
index f887f7747c..8fca27dfe1 100644
--- a/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
+++ b/studio/backend/tests/test_lemonade_llamacpp_rocm_bins_mock.py
@@ -1,11 +1,10 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""Validates that the installer correctly resolves lemonade ROCm prebuilt assets.
+"""Validates that the installer resolves lemonade ROCm prebuilt assets.
 
-Uses a faked HostInfo so no AMD GPU is needed. Network calls to the lemonade
-GitHub API are stubbed out so the suite runs without internet access and is
-not subject to rate limits.
+Uses a faked HostInfo so no AMD GPU is needed. The lemonade GitHub API calls
+are stubbed so the suite runs offline and isn't subject to rate limits.
 """
 
 from __future__ import annotations
@@ -33,7 +32,7 @@ if resolve_lemonade_rocm_choice is None or _LEMONADE_GFX_FAMILIES is None:
 @pytest.fixture(autouse = True)
 def _clear_lemonade_release_cache():
     """Prevent cross-test pollution of the lemonade release lru_cache when
-    future tests vary the fetch_json mock return value."""
+    tests vary the fetch_json mock return value."""
     _cache = getattr(_mod, "_fetch_lemonade_release_cached", None)
     if _cache is not None and hasattr(_cache, "cache_clear"):
         _cache.cache_clear()
@@ -157,10 +156,9 @@ direct_upstream_release_plan = getattr(_mod, "direct_upstream_release_plan", Non
 
 
 def _stub_unsloth_release(release_tag: str = "b9022") -> dict:
-    # Minimal payload that parse_direct_linux_release_bundle accepts. It
-    # requires at least one `app-{label}-linux-x64*.tar.gz` asset for the
-    # bundle to be recognised; we ship a bare CPU one so the planner has a
-    # baseline non-ROCm attempt to fall through to.
+    # Minimal payload parse_direct_linux_release_bundle accepts. It needs at
+    # least one `app-{label}-linux-x64*.tar.gz` asset to recognise the bundle;
+    # we ship a bare CPU one so the planner has a baseline non-ROCm fallback.
     asset_name = f"app-{release_tag}-linux-x64.tar.gz"
     return {
         "tag_name": release_tag,
@@ -255,9 +253,8 @@ def test_lemonade_release_api_url_pinned_tag():
 
 
 def test_lemonade_release_api_url_encodes_tag():
-    """Unexpected slashes / hashes in the tag must be URL-encoded so the URL
-    cannot be reshaped (defence in depth -- tags should already be sanitised
-    upstream)."""
+    """Slashes / hashes in the tag must be URL-encoded so the URL can't be
+    reshaped (defence in depth -- tags should already be sanitised upstream)."""
     url = _mod._lemonade_release_api_for("b1260/../latest")
     assert "/releases/tags/b1260%2F..%2Flatest" in url
     assert "//latest" not in url.split("/releases/tags/", 1)[1]
@@ -272,9 +269,9 @@ def test_lemonade_resolver_skipped_by_opt_out_env(monkeypatch):
 
 
 def test_lemonade_resolver_rejects_non_github_url(monkeypatch):
-    """If the GitHub API response somehow contained an off-host download URL,
-    the resolver must refuse to use it (lemonade assets are not in the
-    approved-hash manifest)."""
+    """If the GitHub API response contained an off-host download URL, the
+    resolver must refuse it (lemonade assets aren't in the approved-hash
+    manifest)."""
     bad_release = {
         "tag_name": _STUB_TAG,
         "assets": [
@@ -298,7 +295,7 @@ def test_lemonade_resolver_rejects_http_scheme():
 
 
 def test_lemonade_resolver_accepts_github_cdn():
-    # Real GitHub release CDN URLs carry the /github-production-release-asset- prefix.
+    # Real GitHub release CDN URLs carry the /github-production-release-asset- prefix
     assert _mod._is_trusted_github_release_url(
         "https://objects.githubusercontent.com/github-production-release-asset-abc123/456/789?token=x",
         "lemonade-sdk/llamacpp-rocm",
@@ -306,7 +303,7 @@ def test_lemonade_resolver_accepts_github_cdn():
 
 
 def test_lemonade_resolver_rejects_arbitrary_cdn_path():
-    # A CDN URL without the release-asset path prefix must be rejected.
+    # A CDN URL without the release-asset path prefix must be rejected
     assert not _mod._is_trusted_github_release_url(
         "https://objects.githubusercontent.com/abc/def",
         "lemonade-sdk/llamacpp-rocm",
@@ -348,7 +345,7 @@ def test_lemonade_runtime_patterns_include_hip_runtime():
 
     Lemonade ZIPs carry transitive deps (libamd_comgr, libLLVM, libclang-cpp,
     ...) whose names change across ROCm releases. A broad ``lib*.so*`` glob
-    avoids having to enumerate every transitive dependency by name.
+    avoids enumerating every transitive dependency by name.
     """
     from install_llama_prebuilt import runtime_patterns_for_choice, AssetChoice
 
@@ -362,7 +359,7 @@ def test_lemonade_runtime_patterns_include_hip_runtime():
     )
     pats = runtime_patterns_for_choice(choice)
     # The broad glob must be present so every .so in the lemonade bundle
-    # (including transitive deps added in future ROCm releases) gets overlaid.
+    # (including future transitive deps) gets overlaid.
     assert "lib*.so*" in pats, f"'lib*.so*' missing from linux-rocm patterns: {pats}"
 
 
@@ -374,9 +371,9 @@ _pick_rocm_gfx_target = getattr(_mod, "_pick_rocm_gfx_target", None)
     reason = "_pick_rocm_gfx_target not present on this branch",
 )
 def test_pick_rocm_gfx_target_honors_cuda_visible_devices(monkeypatch):
-    """AMD HIP honours CUDA_VISIBLE_DEVICES identically to HIP_VISIBLE_DEVICES;
-    on a gfx1151 + gfx1100 mixed host, CUDA_VISIBLE_DEVICES=1 must select gfx1100."""
-    # Two GPUs; rocminfo reports each token twice (as in the real tool output).
+    """AMD HIP honours CUDA_VISIBLE_DEVICES like HIP_VISIBLE_DEVICES; on a
+    gfx1151 + gfx1100 mixed host, CUDA_VISIBLE_DEVICES=1 must select gfx1100."""
+    # Two GPUs; rocminfo reports each token twice (as in real tool output).
     probe_out = "gfx1151\ngfx1151\ngfx1100\ngfx1100"
     monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
     monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
@@ -405,7 +402,7 @@ def test_pick_rocm_gfx_target_same_arch_multi_gpu(monkeypatch):
     """Regression: [gfx1100, gfx1100, gfx1151] with HIP_VISIBLE_DEVICES=2 must
     return gfx1151, not fall back to GPU 0 due to dict.fromkeys collapsing the
     two gfx1100 entries into one and making index 2 out of range."""
-    # Simulate rocminfo output for 3 GPUs (2x gfx1100 dGPU + 1x gfx1151 APU).
+    # rocminfo output for 3 GPUs (2x gfx1100 dGPU + 1x gfx1151 APU).
     # Each GPU gets its own Agent section with a few token mentions.
     probe_out = (
         "***\nAgent 1\n***\n  gfx1100 some info\n  gfx1100\n"
diff --git a/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py b/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
index 255c04a956..215936bd20 100644
--- a/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
+++ b/studio/backend/tests/test_llama_cpp_cache_aware_disk_check.py
@@ -5,17 +5,14 @@
 ``LlamaCppBackend.load_model``.
 
 The preflight used to compare the repo's total GGUF download size against
-free disk without accounting for bytes already present in the Hugging
-Face cache. That made re-loading a cached large model (e.g.
-``unsloth/MiniMax-M2.7-GGUF`` at 131 GB) fail cold whenever free disk was
-below the full weight footprint, even though nothing needed
-downloading.
+free disk without accounting for bytes already in the Hugging Face cache.
+That made re-loading a cached large model (e.g. ``unsloth/MiniMax-M2.7-GGUF``
+at 131 GB) fail cold whenever free disk was below the full weight footprint,
+even though nothing needed downloading.
 
 These tests exercise the preflight arithmetic in isolation by driving
 ``get_paths_info`` and ``try_to_load_from_cache`` through ``mock.patch``.
-No network, GPU, or subprocess use.
-
-Cross-platform: Linux, macOS, Windows, WSL.
+No network, GPU, or subprocess use. Cross-platform: Linux, macOS, Windows, WSL.
 """
 
 from __future__ import annotations
@@ -29,8 +26,8 @@ from unittest.mock import patch
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test.  Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable external deps before importing the module under
+# test. Same pattern as test_kv_cache_estimation.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -99,11 +96,11 @@ def _preflight(
     hf_repo = "unsloth/Example-GGUF",
     hf_token = None,
 ):
-    """Run the preflight arithmetic as written in llama_cpp.py and return
-    the decision outcome as a dict.
+    """Run the preflight arithmetic as in llama_cpp.py; return the decision
+    outcome as a dict.
 
     ``repo_files``: list of (filename, remote_bytes).
-    ``cached_files``: dict {filename: on_disk_bytes} for files already in cache.
+    ``cached_files``: dict {filename: on_disk_bytes} for files already cached.
     ``free_bytes``: value returned by shutil.disk_usage(cache_dir).free.
     """
     import os
@@ -112,22 +109,21 @@ def _preflight(
     path_infos = [_FakePathInfo(name, size) for name, size in repo_files]
 
     with tempfile.TemporaryDirectory() as tmp:
-        # Create SPARSE files for the cached ones so os.path.exists /
-        # os.path.getsize pass without actually allocating bytes on disk.
-        # This is critical when simulating multi-GB models.
+        # SPARSE files for the cached ones so os.path.exists / os.path.getsize
+        # pass without allocating bytes on disk -- critical for multi-GB models.
         cache_paths = {}
         for name, sz in cached_files.items():
             p = Path(tmp) / name.replace("/", "_")
             with open(p, "wb") as fh:
                 if sz > 0:
-                    fh.truncate(sz)  # sparse allocation: no data blocks written
+                    fh.truncate(sz)  # sparse: no data blocks written
             cache_paths[name] = str(p)
 
         def fake_try_to_load_from_cache(repo_id, filename):
             return cache_paths.get(filename)
 
-        # Mirror the same variable names and control flow as the real code
-        # so behavioral drift is caught immediately.
+        # Mirror the real code's variable names and control flow so behavioral
+        # drift is caught immediately.
         total_bytes = sum((p.size or 0) for p in path_infos)
         already_cached_bytes = 0
         for p in path_infos:
@@ -189,8 +185,8 @@ class TestCacheAwarePreflight:
         assert out["would_raise_disk_error"] is False
 
     def test_partial_cache_insufficient_disk_for_rest_still_raises(self):
-        """Two of four shards cached; remaining 70 GB still bigger than
-        free disk -> preflight correctly wants to raise."""
+        """Two of four shards cached; remaining 70 GB still exceeds free
+        disk -> preflight correctly wants to raise."""
         shards = [(f"UD-Q4_K_XL/shard-{i}.gguf", 35 * GIB) for i in range(4)]
         cached = {
             shards[0][0]: shards[0][1],
@@ -217,8 +213,8 @@ class TestCacheAwarePreflight:
         assert out["would_raise_disk_error"] is False
 
     def test_incomplete_cached_blob_is_not_credited(self):
-        """A partial file on disk (e.g. interrupted download) is not
-        counted as cached -- we still require bytes for it."""
+        """A partial file on disk (e.g. interrupted download) isn't counted
+        as cached -- we still require bytes for it."""
         shards = [("UD-Q4_K_XL/shard-0.gguf", 40 * GIB)]
         partial = {"UD-Q4_K_XL/shard-0.gguf": 10 * GIB}
         out = _preflight(
@@ -231,7 +227,7 @@ class TestCacheAwarePreflight:
         assert out["would_raise_disk_error"] is False
 
     def test_zero_size_path_infos_do_not_crash(self):
-        """A path_info with size=0 should not be credited or break the
+        """A path_info with size=0 must not be credited or break the
         arithmetic."""
         shards = [("mmproj.gguf", 0), ("UD-Q4_K_XL/shard-0.gguf", 40 * GIB)]
         out = _preflight(
diff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.py
index ee8d54443a..ec66411bfd 100644
--- a/studio/backend/tests/test_llama_cpp_context_fit.py
+++ b/studio/backend/tests/test_llama_cpp_context_fit.py
@@ -5,26 +5,24 @@
 
 Guards two regressions in ``LlamaCppBackend.load_model``:
 
-1. **Auto mode on weights-exceed-VRAM** (``n_ctx == 0``): when the model
-   weights alone exceed 90% of every GPU subset's free memory, the
-   auto-pick loop used to exit without matching, leaving
-   ``effective_ctx`` at the model's native context (e.g. 196608 for
-   MiniMax-M2.7). The intended default per Studio's UI spec is 4096 so
-   the slider lands on a usable value; the user can still drag higher
-   and trigger ``--fit on`` with a warning.
+1. **Auto mode on weights-exceed-VRAM** (``n_ctx == 0``): when weights
+   alone exceed 90% of every GPU subset's free memory, the auto-pick loop
+   used to exit without matching, leaving ``effective_ctx`` at the native
+   context (e.g. 196608 for MiniMax-M2.7). Studio's UI spec wants 4096 so
+   the slider lands on a usable value; the user can still drag higher and
+   trigger ``--fit on`` with a warning.
 
 2. **Explicit ctx silently shrunk when KV overflows**: with fittable
-   weights but a requested ctx whose KV cache pushes total memory over
-   90% of VRAM, the old code binary-searched a smaller ctx and emitted
-   ``-c  -ngl -1`` without informing the caller. The UI had
-   already surfaced its "might be slower" warning and expects the user's
-   explicit ctx to be honored with ``--fit on`` flexing ``-ngl`` instead.
+   weights but a ctx whose KV cache pushes total memory over 90% of VRAM,
+   the old code binary-searched a smaller ctx and emitted ``-c 
+   -ngl -1`` without telling the caller. The UI already showed its "might
+   be slower" warning and expects the explicit ctx honored with ``--fit
+   on`` flexing ``-ngl`` instead.
 
-Tests avoid GPU probing, subprocess spawning, and GGUF I/O by driving the
+Avoids GPU probing, subprocess spawning, and GGUF I/O by driving the
 post-metadata decision block directly against a stubbed instance.
 
-Requires no GPU, network, or external libraries beyond pytest.
-Cross-platform: Linux, macOS, Windows, WSL.
+No GPU, network, or libraries beyond pytest. Cross-platform.
 """
 
 from __future__ import annotations
@@ -36,8 +34,8 @@ from pathlib import Path
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test.  Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -103,8 +101,8 @@ def _make_backend(
     kv_key_length = 128,
     kv_value_length = 128,
 ):
-    """Create a LlamaCppBackend instance with GGUF metadata fields set and
-    the helpers used by the decision block stubbed out."""
+    """LlamaCppBackend with GGUF metadata fields set and the decision
+    block's helpers stubbed out."""
     inst = LlamaCppBackend.__new__(LlamaCppBackend)
     inst._context_length = native_ctx
     inst._n_layers = n_layers
@@ -136,8 +134,8 @@ def _drive(
 ):
     """Drive the post-metadata portion of load_model with stubbed inputs.
 
-    Mirrors the decision block at llama_cpp.py:1137-1296 so we can assert
-    the command that would be built, without subprocesses or GPU probes.
+    Mirrors the decision block at llama_cpp.py:1137-1296 to assert the
+    command that would be built, without subprocesses or GPU probes.
     """
     inst = _make_backend(native_ctx = native_ctx)
     model_size = int(model_gib * GIB)
@@ -154,9 +152,8 @@ def _drive(
     inst._can_estimate_kv = lambda: can_estimate_kv
 
     context_length = inst._context_length
-    # Use the production helper instead of reimplementing the conditional
-    # locally; reimplementing makes the test pass for the test's own logic
-    # rather than production's, and silent drift won't be caught.
+    # Use the production helper, not a local reimplementation: a local copy
+    # would test the test's own logic, not production's, and hide drift.
     ctx_override = parse_ctx_override(extra_args)
     requested_ctx = resolve_requested_ctx(extra_args, n_ctx)
 
@@ -267,8 +264,8 @@ class TestAutoModeWeightsExceedVRAM:
         assert plan["c_arg"] == FALLBACK_CTX
         assert plan["use_fit"] is True
         assert plan["gpu_indices"] is None
-        # UI slider ceiling stays at native: user can still drag higher
-        # and get the "might be slower" path.
+        # UI slider ceiling stays at native: user can drag higher and get
+        # the "might be slower" path.
         assert plan["max_available_ctx"] == 196608
 
     def test_multi_gpu_all_subsets_fail(self):
@@ -304,9 +301,8 @@ class TestExplicitCtxRespectsUser:
     """``n_ctx > 0`` must never be silently shrunk."""
 
     def test_fittable_weights_oversized_kv(self):
-        # 8 GB weights + 131k ctx KV on 24 GB VRAM.
-        # Budget = 21.6 GB, KV at 131k >> 13.6 GB remaining, so
-        # _select_gpus flips use_fit=True.
+        # 8 GB weights + 131k ctx KV on 24 GB VRAM. Budget = 21.6 GB, KV
+        # at 131k >> 13.6 GB remaining, so _select_gpus flips use_fit=True.
         plan = _drive(
             n_ctx = 131072,
             model_gib = 8,
@@ -350,7 +346,7 @@ class TestExplicitCtxRespectsUser:
         assert plan["use_fit"] is True
 
     def test_explicit_below_floor_honored(self):
-        # 2048 is below --fit-ctx default; still honored since user set it.
+        # 2048 is below --fit-ctx default; honored since user set it.
         plan = _drive(
             n_ctx = 2048,
             model_gib = 8,
@@ -451,8 +447,8 @@ class TestTightFitPinsToGPU:
     """Models that fit at 91-95% of free VRAM must use the GPU."""
 
     def test_rtx_4090_qwen_24gb_class(self):
-        # noahterbest's #5106 log: 20.8 GB model on 22805 MiB free
-        # GPU, ctx=4096 -> ~94% utilization, ~1.4 GiB headroom.
+        # noahterbest's #5106 log: 20.8 GB model on 22805 MiB free GPU,
+        # ctx=4096 -> ~94% utilization, ~1.4 GiB headroom.
         plan = _drive(
             n_ctx = 0,
             model_gib = 20.8,
@@ -495,9 +491,9 @@ class TestTightFitPinsToGPU:
 
 @pytest.mark.parametrize("platform_tag", ["linux", "windows", "mac", "rocm"])
 def test_identical_decision_across_platforms(platform_tag):
-    """The decision function takes ``[(gpu_idx, free_mib), ...]`` regardless
-    of how upstream (nvidia-smi / nvidia-smi.exe / Metal / rocm-smi) produced
-    it. Identical inputs must yield identical plans."""
+    """The decision takes ``[(gpu_idx, free_mib), ...]`` regardless of the
+    source (nvidia-smi / nvidia-smi.exe / Metal / rocm-smi). Identical
+    inputs must yield identical plans."""
     plan_a = _drive(n_ctx = 0, model_gib = 8, gpus = [(0, 24_000)])
     plan_b = _drive(n_ctx = 0, model_gib = 8, gpus = [(0, 24_000)])
     assert plan_a == plan_b, platform_tag
@@ -525,8 +521,8 @@ class TestClassifyGpuOffload:
         assert inst._classify_gpu_offload(True, [(0, 22805)]) is True
 
     def test_cpu_only_buffer_returns_false(self):
-        # llama-server printed buffer lines but only CPU buffers --
-        # this is the silent CPU fallback symptom we want to catch.
+        # Buffer lines printed but only CPU buffers -- the silent CPU
+        # fallback symptom we want to catch.
         inst = self._backend(
             [
                 "load_tensors:   CPU_Mapped model buffer size = 21000.0 MiB",
@@ -555,8 +551,7 @@ class TestClassifyGpuOffload:
         assert inst._classify_gpu_offload(False, []) is None
 
     def test_user_did_not_intend_gpu_returns_none(self):
-        # Studio called start_llama_server without expecting GPU use;
-        # don't warn.
+        # Studio called start_llama_server without expecting GPU; don't warn.
         inst = self._backend(
             [
                 "load_tensors:   CPU_Mapped model buffer size = 21000.0 MiB",
diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.py
index c7dd111ee3..25bcf851b4 100644
--- a/studio/backend/tests/test_llama_cpp_freshness.py
+++ b/studio/backend/tests/test_llama_cpp_freshness.py
@@ -3,8 +3,8 @@
 
 """Tests for the llama.cpp prebuilt freshness check.
 
-Pins the marker parser, the disk+memory cache, the stale decision
-matrix, and fail-open behaviour on missing data.
+Pins the marker parser, disk+memory cache, stale-decision matrix, and
+fail-open behaviour on missing data.
 """
 
 from __future__ import annotations
@@ -57,7 +57,7 @@ def _write_marker(install_dir: Path, **overrides) -> Path:
 
 
 def _fake_binary(install_dir: Path, *, layout: str = "cmake") -> Path:
-    """Stub llama-server under one of the supported install layouts."""
+    """Stub llama-server under a supported install layout."""
     if layout == "cmake":
         bin_dir = install_dir / "build" / "bin"
         bin_name = "llama-server"
@@ -77,7 +77,7 @@ def _fake_binary(install_dir: Path, *, layout: str = "cmake") -> Path:
 
 @pytest.fixture(autouse = True)
 def _reset(monkeypatch, tmp_path):
-    # Isolate disk cache per-test; never touch the user's real cache.
+    # Isolate disk cache per-test; never touch the real cache.
     monkeypatch.setattr(fr, "_cache_dir", lambda: tmp_path / ".freshness")
     fr.reset_caches()
     yield
@@ -107,8 +107,8 @@ def test_read_install_marker_finds_root_layout(tmp_path):
 
 
 def test_read_install_marker_finds_windows_cmake_layout(tmp_path):
-    # Windows cmake puts the .exe under build/bin/Release/, so the
-    # marker is four levels above the binary.
+    # Windows cmake puts the .exe under build/bin/Release/, so the marker
+    # is four levels above the binary.
     install_dir = tmp_path / "llama.cpp"
     _write_marker(install_dir, tag = "b8888")
     bin_path = _fake_binary(install_dir, layout = "windows")
@@ -121,8 +121,8 @@ def test_read_install_marker_finds_windows_cmake_layout(tmp_path):
 def test_read_install_marker_carries_published_repo_dynamically(tmp_path, repo):
     # The freshness check queries whichever release repo the marker
     # records, so CUDA Linux (unslothai), CPU Linux x86_64 / macOS
-    # (ggml-org), and ROCm source-build (unslothai upstream label)
-    # all surface the right "latest" tag.
+    # (ggml-org), and ROCm source-build all surface the right "latest"
+    # tag.
     install_dir = tmp_path / "llama.cpp"
     _write_marker(install_dir, tag = "b9000", published_repo = repo)
     bin_path = _fake_binary(install_dir, layout = "cmake")
diff --git a/studio/backend/tests/test_llama_cpp_load_progress.py b/studio/backend/tests/test_llama_cpp_load_progress.py
index f95d8bf1a4..dcbe16be50 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress.py
@@ -4,18 +4,17 @@
 """Tests for ``LlamaCppBackend.load_progress()``.
 
 The chat settings flow and the training overlay both show a generic
-"Starting model..." spinner during the window after a GGUF download
-finishes and before llama-server reports healthy. For small models
-that window is a second or two and nobody notices. For large MoE GGUFs
-(MiniMax-M2.7, Qwen3.5-397B-A17B, etc.) the llama-server process spends
-minutes in kernel state D, paging tens or hundreds of GB of shards
-into the page cache. The UI has no way to show a real progress bar,
-rate, or ETA during that window.
+"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//status VmRSS`` (what the
-kernel has actually paged in) against the total shard file size on
-disk, so the frontend can render a real bar plus rate/ETA. This
-module pins that contract:
+``load_progress()`` samples ``/proc//status VmRSS`` (what the kernel
+actually paged in) against the total shard file size on disk, so the
+frontend can render a real bar plus rate/ETA. This module pins that
+contract:
 
   * returns ``None`` when no load is in flight
   * returns ``{"phase": "mmap", ...}`` while the subprocess is alive
@@ -27,10 +26,9 @@ module pins that contract:
   * ``bytes_loaded`` is VmRSS in bytes, capped by total, rounded
   * ``fraction`` is clamped to 0..1 and rounded to 4 decimal places
 
-Linux-only via ``/proc``. On platforms without ``/proc`` the method
-returns ``None`` instead of raising.
-Cross-platform test: skips cleanly on macOS / Windows if ``/proc`` is
-not available.
+Linux-only via ``/proc``; without ``/proc`` the method returns ``None``
+instead of raising. Cross-platform test: skips cleanly on macOS / Windows
+when ``/proc`` is unavailable.
 """
 
 from __future__ import annotations
@@ -45,8 +43,8 @@ from unittest.mock import patch
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -106,7 +104,7 @@ def _make_instance():
 
 
 class _FakeProc:
-    """Minimal stand-in for subprocess.Popen that just carries a pid."""
+    """Minimal stand-in for subprocess.Popen carrying just a pid."""
 
     def __init__(self, pid: int):
         self.pid = pid
@@ -188,7 +186,7 @@ class TestLoadProgressSingleShard:
 
 
 class TestLoadProgressMultiShard:
-    """Shard-aware total: for ``*-00001-of-00004.gguf`` primaries the
+    """Shard-aware total: for ``*-00001-of-00004.gguf`` primaries, the
     method sums sibling files with the same prefix."""
 
     def test_sharded_total_aggregates_siblings(self, tmp_path):
@@ -197,7 +195,7 @@ class TestLoadProgressMultiShard:
                 tmp_path / f"model-{i:05d}-of-00004.gguf",
                 size_bytes = 20 * 1024**3,
             )
-        # Drop an unrelated .gguf in the same folder -- must not be counted.
+        # An unrelated .gguf in the same folder -- must not be counted.
         _write_sparse_file(tmp_path / "mmproj-BF16.gguf", 2 * 1024**3)
 
         inst = _make_instance()
diff --git a/studio/backend/tests/test_llama_cpp_load_progress_live.py b/studio/backend/tests/test_llama_cpp_load_progress_live.py
index 44a8f00834..ce9dd509bf 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress_live.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress_live.py
@@ -4,17 +4,15 @@
 """Live, no-mock integration test for ``LlamaCppBackend.load_progress()``.
 
 The companion files (``test_llama_cpp_load_progress.py`` and
-``test_llama_cpp_load_progress_matrix.py``) patch ``builtins.open`` to
-feed synthetic VmRSS values. This file is the opposite: it uses **real**
-subprocesses, **real** file sizes, and the **real** ``/proc``
-interface. It is the sanity check that the contract we keep in the
-mocked tests still maps to what the kernel actually returns on a live
-Linux system.
+``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 a buggy implementation that
-parses ``/proc`` output in a format the kernel no longer uses, or that
-makes assumptions about ``Path.stat()`` vs ``os.path.getsize``. This
-file hits the real APIs so any format drift gets caught.
+Why both: the mocked tests can be fooled by an implementation that parses
+``/proc`` in a format the kernel no longer uses, or assumes ``Path.stat()`` vs
+``os.path.getsize``. This file hits the real APIs so format drift gets caught.
 
 Skipped cleanly on non-Linux (no ``/proc``).
 """
@@ -31,8 +29,8 @@ from pathlib import Path
 import pytest
 
 # ---------------------------------------------------------------------------
-# Same stubs as the matrix file (keep self-contained so the file can be
-# run standalone as well as via the full suite).
+# Same stubs as the matrix file (self-contained so this file runs standalone
+# and via the full suite).
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -88,8 +86,8 @@ def _make_backend(
 
 
 def test_live_rss_matches_kernel_vmrss(tmp_path):
-    """Spawn a real child, let it allocate real bytes, confirm
-    ``bytes_loaded`` tracks the kernel's VmRSS within a sane tolerance."""
+    """Spawn a real child, let it allocate real bytes, confirm ``bytes_loaded``
+    tracks the kernel's VmRSS within a sane tolerance."""
     # Child that allocates ~100 MB of zero'd bytes and then idles.
     script = tmp_path / "burn.py"
     script.write_text(
@@ -112,7 +110,7 @@ def test_live_rss_matches_kernel_vmrss(tmp_path):
         ready = proc.stdout.readline()
         assert ready.strip() == b"ready"
 
-        # Create a fake 200 MB sparse gguf so bytes_total is concrete.
+        # Fake 200 MB sparse gguf so bytes_total is concrete.
         gguf = tmp_path / "model.gguf"
         with open(gguf, "wb") as f:
             f.truncate(200 * 1024 * 1024)
@@ -123,8 +121,8 @@ def test_live_rss_matches_kernel_vmrss(tmp_path):
         assert out is not None, "load_progress returned None for live pid"
         assert out["phase"] == "mmap"
         assert out["bytes_total"] == 200 * 1024 * 1024
-        # VmRSS for the Python child includes the interpreter + the 100MB
-        # buffer, so a realistic floor is 50 MB and ceiling is 200 MB.
+        # VmRSS for the Python child includes the interpreter + 100MB buffer,
+        # so a realistic floor is 50 MB and ceiling is 200 MB.
         assert (
             out["bytes_loaded"] >= 50 * 1024 * 1024
         ), f"bytes_loaded unexpectedly low: {out['bytes_loaded']}"
@@ -153,8 +151,8 @@ def test_live_ready_phase_when_healthy(tmp_path):
 
 
 def test_live_dead_pid_returns_none(tmp_path):
-    """A recently-dead pid may linger in /proc for ms; use a clearly
-    invalid id so the read reliably fails."""
+    """A recently-dead pid may linger in /proc for ms; use a clearly invalid id
+    so the read reliably fails."""
     gguf = tmp_path / "m.gguf"
     gguf.touch()
 
@@ -164,8 +162,8 @@ def test_live_dead_pid_returns_none(tmp_path):
 
 
 def test_live_shard_aggregation_counts_real_files(tmp_path):
-    """With 4 real sibling shards on disk, ``bytes_total`` equals their
-    summed size to the byte."""
+    """With 4 real sibling shards on disk, ``bytes_total`` equals their summed
+    size to the byte."""
     shard_size = 7 * 1024 * 1024  # 7 MB each
     for i in range(1, 5):
         f = tmp_path / f"model-{i:05d}-of-00004.gguf"
@@ -186,8 +184,8 @@ def test_live_shard_aggregation_counts_real_files(tmp_path):
 
 
 def test_live_repeated_polling_stays_sane(tmp_path):
-    """Sampling the same backend 20 times should not raise or produce
-    non-numeric output, even under normal kernel RSS jitter."""
+    """Sampling the same backend 20 times must not raise or produce non-numeric
+    output, even under normal kernel RSS jitter."""
     gguf = tmp_path / "m.gguf"
     with open(gguf, "wb") as f:
         f.truncate(500 * 1024 * 1024)
diff --git a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py b/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
index a88450ec0b..1a698d3613 100644
--- a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
+++ b/studio/backend/tests/test_llama_cpp_load_progress_matrix.py
@@ -3,29 +3,29 @@
 
 """Extended test matrix for ``LlamaCppBackend.load_progress()``.
 
-Companion to ``test_llama_cpp_load_progress.py`` (which pins the basic
-contract). This file widens coverage to the edge cases that bit users
-or were hypothesized to bite them on cross-platform installs:
+Companion to ``test_llama_cpp_load_progress.py`` (basic contract). Widens
+coverage to edge cases that bit (or were thought to bite) cross-platform
+installs:
 
-  * Platform matrix — macOS/Windows simulation via ``/proc`` absence.
+  * Platform matrix — macOS/Windows via ``/proc`` absence.
   * ``VmRSS`` parsing — tab vs space delimiter, missing line, malformed
     integer.
   * Filesystem edges — HF-cache symlinks, broken symlinks, nonexistent
     paths, relative paths.
-  * Shard aggregation — partial multi-shard downloads where some shards
-    are still ``.incomplete``, two shard series in the same dir,
+  * Shard aggregation — partial multi-shard downloads with some shards
+    still ``.incomplete``, two shard series in one dir,
     ``mmproj-*.gguf`` sibling exclusion for non-sharded primaries,
     single-file models.
-  * Lifecycle races — process set before ``_gguf_path`` is assigned,
-    process dead mid-sample, ``_healthy`` flipped to True.
-  * Concurrent sampling — 10 threads × 50 iterations against a single
-    backend, hitting real ``/proc`` (no mocks — see the note in
+  * Lifecycle races — process set before ``_gguf_path``, process dead
+    mid-sample, ``_healthy`` flipped to True.
+  * Concurrent sampling — 10 threads × 50 iterations against one
+    backend, hitting real ``/proc`` (no mocks — see
     ``TestConcurrentSampling`` for why).
   * Fraction bounds — capped at 1.0 when RSS exceeds total; 0.0 when
     total is zero.
 
-All tests are Linux-only in practice (we stub ``/proc`` where needed).
-The stable subset runs in well under a second.
+Linux-only in practice (``/proc`` stubbed where needed). The stable
+subset runs in well under a second.
 """
 
 from __future__ import annotations
@@ -41,8 +41,8 @@ from unittest.mock import patch
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test. Same pattern as test_llama_cpp_load_progress.py.
+# Stub heavy/unavailable deps before importing the module under test.
+# Same pattern as test_llama_cpp_load_progress.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -113,7 +113,7 @@ def _sparse(path, size):
 
 
 def _fake_proc_reader(rss_kb):
-    """Return an ``open()`` replacement that fakes /proc reads with a VmRSS line."""
+    """An ``open()`` replacement faking /proc reads with a VmRSS line."""
 
     def fake_open(path, *args, **kwargs):
         if str(path).startswith("/proc/"):
@@ -129,8 +129,8 @@ def _fake_proc_reader(rss_kb):
 
 
 class TestPlatformMatrix:
-    """The method is Linux-first via /proc. On macOS/Windows it must
-    degrade to None rather than crash."""
+    """Linux-first via /proc. On macOS/Windows must degrade to None
+    rather than crash."""
 
     def test_linux_live_proc_is_self_pid(self, tmp_path):
         """Self-pid /proc read uses the real kernel interface."""
@@ -144,7 +144,7 @@ class TestPlatformMatrix:
         assert out is not None
         assert out["phase"] == "mmap"
         assert out["bytes_total"] == 1 * 1024**3
-        # Our Python process has some RSS -- just sanity-check positive.
+        # Our process has some RSS -- sanity-check it's positive.
         assert out["bytes_loaded"] > 0
 
     def test_macos_no_proc_returns_none(self, tmp_path):
@@ -199,7 +199,7 @@ class TestVmRSSParsing:
         assert out["bytes_loaded"] == 2 * 1024**3
 
     def test_space_separated_fallback(self, tmp_path):
-        """Some kernels emit single-space rather than tab."""
+        """Some kernels emit a single space, not a tab."""
         gguf = tmp_path / "m.gguf"
         _sparse(gguf, 4 * 1024**3)
         inst = _make()
@@ -235,8 +235,8 @@ class TestVmRSSParsing:
         assert out["fraction"] == 0.0
 
     def test_malformed_vmrss_value(self, tmp_path):
-        """Non-integer VmRSS value should be treated as if the line were
-        absent (early ValueError caught)."""
+        """Non-integer VmRSS is treated like an absent line (ValueError
+        caught)."""
         gguf = tmp_path / "m.gguf"
         _sparse(gguf, 1 * 1024**3)
         inst = _make()
@@ -250,7 +250,7 @@ class TestVmRSSParsing:
 
         with patch("builtins.open", side_effect = fake_open):
             out = inst.load_progress()
-        # The implementation catches ValueError on int() and returns None.
+        # int() ValueError is caught and returns None.
         assert out is None
 
 
@@ -262,7 +262,7 @@ class TestVmRSSParsing:
 class TestFilesystemEdges:
     def test_symlink_primary_follows_to_blob(self, tmp_path):
         """HF cache stores blobs under blobs/ and symlinks them from
-        snapshots/. The method must follow the symlink."""
+        snapshots/. Must follow the symlink."""
         blob = tmp_path / "blob"
         _sparse(blob, 12 * 1024**3)
         snap = tmp_path / "snap"
@@ -300,7 +300,7 @@ class TestFilesystemEdges:
 
     def test_relative_gguf_path(self, tmp_path):
         """Relative paths shouldn't crash; behaviour depends on CWD but
-        the method must not raise."""
+        must not raise."""
         cwd = os.getcwd()
         try:
             os.chdir(tmp_path)
@@ -323,11 +323,11 @@ class TestFilesystemEdges:
 
 class TestShardAggregation:
     def test_partial_multi_shard_download(self, tmp_path):
-        """Primary present but shards 2..N still downloading as
-        ``.incomplete``. Sums only the fully-arrived ``.gguf`` files."""
+        """Primary present but shards 2..N still ``.incomplete``. Sums
+        only the fully-arrived ``.gguf`` files."""
         _sparse(tmp_path / "m-00001-of-00004.gguf", 30 * 1024**3)
         _sparse(tmp_path / "m-00002-of-00004.gguf", 30 * 1024**3)
-        # 3 and 4 still downloading as .incomplete
+        # 3 and 4 still downloading as .incomplete.
         _sparse(tmp_path / "m-00003-of-00004.gguf.incomplete", 5 * 1024**3)
         inst = _make()
         inst._process = _Proc(os.getpid())
@@ -337,8 +337,8 @@ class TestShardAggregation:
         assert out["bytes_total"] == 60 * 1024**3  # only the .gguf siblings
 
     def test_two_shard_series_in_same_dir(self, tmp_path):
-        """Defensive: if two quant series share a dir, prefix filter
-        only sums siblings of the chosen primary."""
+        """Defensive: when two quant series share a dir, the prefix
+        filter sums only siblings of the chosen primary."""
         for i in range(1, 3):
             _sparse(tmp_path / f"m_q4-{i:05d}-of-00002.gguf", 10 * 1024**3)
             _sparse(tmp_path / f"m_q8-{i:05d}-of-00002.gguf", 20 * 1024**3)
@@ -351,7 +351,7 @@ class TestShardAggregation:
 
     def test_mmproj_sibling_not_counted(self, tmp_path):
         """Vision models drop an ``mmproj-*.gguf`` alongside. For a
-        single-file (non-sharded) primary we only count the primary."""
+        single-file (non-sharded) primary, count only the primary."""
         _sparse(tmp_path / "m.gguf", 8 * 1024**3)
         _sparse(tmp_path / "mmproj-BF16.gguf", 2 * 1024**3)
         inst = _make()
@@ -359,7 +359,7 @@ class TestShardAggregation:
         inst._gguf_path = str(tmp_path / "m.gguf")
         with patch("builtins.open", side_effect = _fake_proc_reader(0)):
             out = inst.load_progress()
-        # Non-sharded primary: only the primary is counted.
+        # Non-sharded: only the primary is counted.
         assert out["bytes_total"] == 8 * 1024**3
 
     def test_single_file_model(self, tmp_path):
@@ -381,7 +381,7 @@ class TestShardAggregation:
 
 class TestLifecycleRaces:
     def test_process_set_but_gguf_path_not_yet(self, tmp_path):
-        """Moment between Popen and self._gguf_path=model_path."""
+        """Window between Popen and self._gguf_path=model_path."""
         inst = _make()
         inst._process = _Proc(os.getpid())
         inst._gguf_path = None
@@ -418,14 +418,13 @@ class TestLifecycleRaces:
 
 class TestConcurrentSampling:
     def test_parallel_invocations_never_raise(self, tmp_path):
-        """Many concurrent samplers hitting the same backend must not raise.
+        """Many concurrent samplers on one backend must not raise.
 
-        We intentionally do NOT patch ``builtins.open`` here because
-        ``unittest.mock.patch`` is not thread-safe: interleaved
-        enter/exit across threads can leak a Mock into ``builtins.open``
-        and poison every subsequent test in the session. Instead, we
-        let each thread hit the real ``/proc/self/status`` of the test
-        process, which is exactly the code path that matters in prod.
+        We do NOT patch ``builtins.open`` here: ``unittest.mock.patch``
+        is not thread-safe -- interleaved enter/exit across threads can
+        leak a Mock into ``builtins.open`` and poison later tests.
+        Instead each thread hits the real ``/proc/self/status``, the
+        code path that matters in prod.
         """
         _sparse(tmp_path / "m.gguf", 1 * 1024**3)
         inst = _make()
diff --git a/studio/backend/tests/test_llama_cpp_max_context_threshold.py b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
index aa0198892f..30131991ae 100644
--- a/studio/backend/tests/test_llama_cpp_max_context_threshold.py
+++ b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
@@ -3,22 +3,20 @@
 
 """Tests for the ``max_context_length`` warning-threshold semantics.
 
-``/api/inference/status.max_context_length`` is what the ctx slider in
-the chat settings sheet reads to decide when to render the "Exceeds
-estimated VRAM capacity. The model may use system RAM." warning:
+The ctx slider in the chat settings sheet reads
+``/api/inference/status.max_context_length`` to decide when to render the
+"Exceeds estimated VRAM capacity. The model may use system RAM." warning:
 
     ctxDisplayValue > ggufMaxContextLength → show warning
 
-For models whose weights fit on some GPU subset, the warning threshold
-is the largest ctx that fits fully in VRAM (the binary-search cap from
-``_fit_context_to_vram``). For models whose weights exceed 90% of every
-GPU subset's free memory, the warning must fire as soon as the user
-drags above the 4096 spec default (otherwise a user loading e.g.
-MiniMax-M2.7 on a 97 GB GPU sees a slider up to 196608 with no
-indication that any value above 4096 will trigger ``--fit on`` and
-degrade performance).
+When weights fit on some GPU subset, the threshold is the largest ctx that
+fits fully in VRAM (the binary-search cap from ``_fit_context_to_vram``).
+When weights exceed 90% of every GPU subset's free memory, the warning must
+fire as soon as the user drags above the 4096 spec default (otherwise loading
+e.g. MiniMax-M2.7 on a 97 GB GPU shows a slider up to 196608 with no hint that
+any value above 4096 triggers ``--fit on`` and degrades performance).
 
-These tests pin both cases. No GPU probing, no subprocess, no GGUF I/O.
+These tests pin both cases. No GPU probing, subprocess, or GGUF I/O.
 Cross-platform: Linux, macOS, Windows, WSL.
 """
 
@@ -31,8 +29,8 @@ from pathlib import Path
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test.  Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -115,9 +113,8 @@ def _compute_max_available_ctx(
     gpus,
     kv_per_token_bytes = 325_000,
 ):
-    """Run the ceiling-probe block from load_model and return the final
-    ``max_available_ctx`` value the backend would assign to
-    ``_max_context_length``.
+    """Run load_model's ceiling-probe block and return the final
+    ``max_available_ctx`` the backend would assign to ``_max_context_length``.
     """
     inst = _make_backend(native_ctx = native_ctx)
     model_size = int(model_gib * GIB)
@@ -163,8 +160,8 @@ def _compute_max_available_ctx(
 
 
 class TestMaxContextLengthForWeightsExceedVRAM:
-    """The UI ``max_context_length`` threshold must fall back to 4096 so
-    the warning fires as soon as the user drags above the spec default.
+    """UI ``max_context_length`` must fall back to 4096 so the warning fires
+    as soon as the user drags above the spec default.
     """
 
     def test_minimax_like(self):
@@ -186,8 +183,8 @@ class TestMaxContextLengthForWeightsExceedVRAM:
         assert got == 4096
 
     def test_native_below_fallback_is_preserved(self):
-        """If the model's native ctx is itself smaller than 4096, do not
-        advertise a larger value than the model supports."""
+        """If native ctx is itself below 4096, don't advertise a larger value
+        than the model supports."""
         got = _compute_max_available_ctx(
             native_ctx = 2048,
             model_gib = 200,
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index 9e7944913a..fc21c48b76 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -187,9 +187,9 @@ def _mtp_backend(**overrides):
     backend._requested_n_ctx = 8192
     backend._cache_type_kv = None
     backend._speculative_type = "draft-mtp"
-    # Default fixture simulates Auto having auto-promoted to draft-mtp.
-    # Individual tests override _requested_spec_mode when they want a
-    # forced mode or the user---spec-type-extra-args path.
+    # Fixture simulates Auto having auto-promoted to draft-mtp. Tests
+    # override _requested_spec_mode for a forced mode or the
+    # user---spec-type-extra-args path.
     backend._requested_spec_mode = "auto"
     backend._chat_template_override = None
     backend._is_vision = False
@@ -239,11 +239,10 @@ def test_already_in_target_state_matches_when_request_uses_default_for_mtp_model
 
 
 def test_already_in_target_state_auto_request_matches_auto_backend_for_non_mtp_model():
-    # Under the requested-mode round-trip model, Auto requested against an
-    # Auto-recorded backend matches regardless of model name. The underlying
-    # resolved emission (--spec-default vs draft-mtp) is handled by the
-    # backend's own load path and reflected in _speculative_type; the
-    # short-circuit comparison only cares whether the *intent* changed.
+    # In the requested-mode round-trip model, Auto-vs-Auto matches regardless
+    # of model name. The resolved emission (--spec-default vs draft-mtp) is
+    # handled by the load path and reflected in _speculative_type; the
+    # short-circuit only cares whether the *intent* changed.
     backend = _mtp_backend(
         _model_identifier = "unsloth/Qwen3.6-27B-GGUF",
         _speculative_type = "default",
@@ -404,10 +403,10 @@ def test_already_in_target_state_vision_mtp_default_matches():
 
 def test_already_in_target_state_vision_off_matches_vision_backend():
     # Vision loads silently drop speculative decoding at the route level
-    # (_request_matches_loaded_settings overrides req to "off"). At the
-    # llama_cpp.py level, _already_in_target_state compares canonical
-    # requested modes; a vision backend recorded with _requested_spec_mode
-    # = "off" matches a req of "off" or None+vision.
+    # (_request_matches_loaded_settings overrides req to "off"). In
+    # llama_cpp.py, _already_in_target_state compares canonical requested
+    # modes; a vision backend recorded with _requested_spec_mode = "off"
+    # matches a req of "off" or None+vision.
     backend = _mtp_backend(
         _model_identifier = "unsloth/Qwen3-VL-4B-Instruct-GGUF",
         _is_vision = True,
@@ -616,9 +615,8 @@ def test_probe_detects_legacy_ngram_mod_flavor(tmp_path):
 
 @_NEEDS_BASH
 def test_probe_ignores_removal_stub_descriptions(tmp_path):
-    # Post-rename binary: legacy flags are present but with
-    # "argument has been removed" descriptions; must not be detected
-    # as legacy.
+    # Post-rename binary: legacy flags present but with "argument has been
+    # removed" descriptions; must not be detected as legacy.
     fake = _make_fake_llama_server(tmp_path / "llama-server", _POST_RENAME_HELP)
     _clear_caps_cache()
     caps = LlamaCppBackend.probe_server_capabilities(str(fake))
@@ -784,16 +782,15 @@ def test_already_in_target_state_draft_n_max_ignored_when_not_mtp():
     )
 
 
-# Sub-3B MTP gate -- tiny dense models regress with the MTP draft
-# head, so load_model falls back to ngram-mod (when the binary supports
-# it) instead of draft-mtp. The reload-skip mirror must follow the
-# same fallback so a sub-3B reload-with-default does not bounce a
-# correctly-configured ngram-mod / off backend.
+# Sub-3B MTP gate -- tiny dense models regress with the MTP draft head, so
+# load_model falls back to ngram-mod (when the binary supports it) instead of
+# draft-mtp. The reload-skip mirror must follow the same fallback so a sub-3B
+# reload-with-default doesn't bounce a correctly-configured ngram-mod/off backend.
 
 
 def _patch_probe(monkeypatch, ngram_supported):
-    """Force probe_server_capabilities to a deterministic result so
-    tests don't depend on whatever llama-server happens to be on PATH."""
+    """Force probe_server_capabilities to a deterministic result so tests
+    don't depend on whatever llama-server is on PATH."""
     fake = {
         "found": True,
         "mtp_token": "draft-mtp",
@@ -815,8 +812,8 @@ def _patch_probe(monkeypatch, ngram_supported):
 
 
 def test_already_in_target_state_sub_3b_falls_back_to_ngram_mod_when_supported(monkeypatch):
-    # 0.8B MTP request -- load_model would have promoted to ngram-mod
-    # (no MTP head); reload check must match a ngram-mod backend.
+    # 0.8B MTP request -- load_model would have promoted to ngram-mod (no MTP
+    # head); reload check must match a ngram-mod backend.
     _patch_probe(monkeypatch, ngram_supported = True)
     backend = _mtp_backend(
         _model_identifier = "unsloth/Qwen3.5-0.8B-MTP-GGUF",
@@ -888,8 +885,8 @@ def test_already_in_target_state_4b_mtp_request_promotes_as_before(monkeypatch):
 
 
 def test_already_in_target_state_2b_falls_back_to_ngram_below_threshold(monkeypatch):
-    # 2.0B is below the 3B threshold -> ngram-mod fallback, not
-    # draft-mtp. Clean-bench shows 2B regresses with draft-mtp.
+    # 2.0B is below the 3B threshold -> ngram-mod fallback, not draft-mtp.
+    # Clean-bench shows 2B regresses with draft-mtp.
     _patch_probe(monkeypatch, ngram_supported = True)
     backend = _mtp_backend(
         _model_identifier = "unsloth/Qwen3.5-2B-MTP-GGUF",
@@ -1023,9 +1020,9 @@ def _resolver_backend(
 
 
 def _flags_dict(flags):
-    """Parse the spec-flag list into a small {flag: value} dict; collapses
-    repeated flags by keeping the last (only --spec-type can repeat and
-    never does in our resolver)."""
+    """Parse the spec-flag list into a {flag: value} dict; collapses repeated
+    flags by keeping the last (only --spec-type can repeat, and never does
+    in our resolver)."""
     out = {}
     i = 0
     while i < len(flags):
@@ -1125,8 +1122,8 @@ def test_build_speculative_flags_user_extra_args_owns_spec_type(monkeypatch):
         gpus = True,
         binary = "/fake/llama-server",
     )
-    # No flags emitted by the resolver -- the user's extra_args carries
-    # the --spec-type, and the resolver records requested_spec_mode = None.
+    # Resolver emits nothing -- the user's extra_args carries the --spec-type,
+    # and the resolver records requested_spec_mode = None.
     assert flags == []
     assert backend.requested_spec_mode is None
     assert backend.speculative_type is None
@@ -1179,7 +1176,7 @@ def test_build_speculative_flags_mtp_token_missing_logs_and_skips(monkeypatch):
         binary = "/fake/llama-server",
     )
     assert "--spec-type" not in flags
-    # _speculative_type stays None (resolved emission was none), but
-    # _requested_spec_mode still reflects the user's choice.
+    # _speculative_type stays None (resolved emission was none); the user's
+    # choice is still reflected in _requested_spec_mode.
     assert backend.requested_spec_mode == "mtp"
     assert backend.speculative_type is None
diff --git a/studio/backend/tests/test_llama_cpp_no_context_shift.py b/studio/backend/tests/test_llama_cpp_no_context_shift.py
index b9f25faf88..312adea83e 100644
--- a/studio/backend/tests/test_llama_cpp_no_context_shift.py
+++ b/studio/backend/tests/test_llama_cpp_no_context_shift.py
@@ -3,17 +3,15 @@
 
 """``--no-context-shift`` launch-flag contract.
 
-When llama-server runs with its default context-shift behavior, the UI
-has no way to tell the user that the KV cache has been rotated --
-earlier turns silently vanish from the conversation. The Studio
-backend always passes ``--no-context-shift`` so the server returns a
+With llama-server's default context-shift behavior, the UI cannot tell the user
+the KV cache was rotated -- earlier turns silently vanish from the conversation.
+The Studio backend always passes ``--no-context-shift`` so the server returns a
 clean error instead, and the chat adapter can point the user at the
 ``Context Length`` input in the settings panel.
 
-This file is a static read of the launch command: we ask
-``LlamaCppBackend`` to assemble its ``cmd`` list and assert the flag
-is always present. Testing via the real subprocess would require an
-actual GGUF on disk, which is out of scope for the fast test suite.
+This file statically reads the launch command: we ask ``LlamaCppBackend`` to
+assemble its ``cmd`` list and assert the flag is present. Testing via the real
+subprocess would need an actual GGUF on disk, out of scope for the fast suite.
 """
 
 from __future__ import annotations
@@ -68,11 +66,10 @@ from core.inference import llama_cpp as llama_cpp_module
 def _load_model_source() -> str:
     """Return the source of ``LlamaCppBackend.load_model``.
 
-    Using ``inspect.getsource`` instead of reading the file directly
-    scopes the assertions to the function that actually launches
-    llama-server, so neither the presence check nor the location check
-    can be fooled by a stray occurrence of ``"--no-context-shift"``
-    elsewhere in the module.
+    Using ``inspect.getsource`` instead of reading the file scopes the assertions
+    to the function that launches llama-server, so neither the presence nor the
+    location check can be fooled by a stray ``"--no-context-shift"`` elsewhere in
+    the module.
     """
     return inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
 
@@ -80,10 +77,9 @@ def _load_model_source() -> str:
 def test_no_context_shift_is_in_load_model():
     """The flag is part of the static launch-command template.
 
-    We check the source of ``load_model`` rather than mocking the whole
-    call chain (GPU probing, GGUF stat, etc.): the flag is written as
-    a literal in one place and any regression has to delete it, which
-    a text search will catch.
+    We check the source of ``load_model`` rather than mocking the whole call
+    chain (GPU probing, GGUF stat, etc.): the flag is a literal in one place and
+    any regression must delete it, which a text search catches.
     """
     assert '"--no-context-shift"' in _load_model_source(), (
         "llama-server must be launched with --no-context-shift so the "
@@ -93,21 +89,20 @@ def test_no_context_shift_is_in_load_model():
 
 
 def test_flag_sits_inside_the_base_cmd_list():
-    """Pin the flag's location so a future refactor can't accidentally
-    move it into a branch that only fires on some code paths.
+    """Pin the flag's location so a refactor can't move it into a branch that
+    only fires on some code paths.
 
-    We slice from ``cmd = [`` to the first ``]`` at the same indent.
-    Using ``inspect.getsource`` means the function lives in its own
-    string and there are no siblings to worry about, so a plain
-    bracket search would also work -- anchoring on the trailing indent
-    just keeps the slice from wandering into a later expression if the
-    opening literal ever grows an in-line comment trailing it.
+    We slice from ``cmd = [`` to the first ``]`` at the same indent. Since
+    ``inspect.getsource`` gives the function its own string with no siblings, a
+    plain bracket search would also work -- anchoring on the trailing indent just
+    keeps the slice from wandering into a later expression if the opening literal
+    ever grows a trailing in-line comment.
     """
     source = _load_model_source()
     start = source.find("cmd = [")
     assert start >= 0, "could not find the base cmd = [...] block"
-    # Find the first line containing only ``]`` (possibly indented).
-    # Works for any indentation style the formatter picks.
+    # Find the first line containing only ``]`` (possibly indented); works for
+    # any indentation style the formatter picks.
     rest = source[start:]
     end_rel = -1
     for line_start, line in _iter_lines_with_offset(rest):
@@ -124,7 +119,7 @@ def test_flag_sits_inside_the_base_cmd_list():
         "conditional branch -- otherwise some code paths would still "
         "run with silent context shift enabled."
     )
-    # Also pin that it is next to -c / --ctx so the grouping makes sense.
+    # Also pin that it sits next to -c / --ctx so the grouping makes sense.
     assert '"-c"' in block
     assert '"--flash-attn"' in block
 
diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
index 202fd36c86..8d88a61ae3 100644
--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py
+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
@@ -4,10 +4,10 @@
 """Tests for LlamaCppBackend._classify_llama_start_failure.
 
 When llama-server exits before becoming healthy, load_model turns its
-captured stdout/stderr into a user-facing reason. A diffusion / image
-GGUF (FLUX, Qwen-Image, ...) is a valid file with plenty of memory, so
-the generic "invalid file or out of memory" message is actively
-misleading (issue #5842). These tests pin the classification.
+captured stdout/stderr into a user-facing reason. A diffusion/image GGUF
+(FLUX, Qwen-Image, ...) is a valid file with plenty of memory, so the
+generic "invalid file or out of memory" message is misleading (issue
+#5842). These tests pin the classification.
 """
 
 from __future__ import annotations
@@ -22,8 +22,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
     sys.path.insert(0, _BACKEND_DIR)
 
-# Match the stubbing pattern in sibling tests so the module imports in a
-# lightweight env without fastapi.
+# Match sibling tests' stubbing so the module imports in a lightweight
+# env without fastapi.
 _loggers_stub = _types.ModuleType("loggers")
 _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
 sys.modules.setdefault("loggers", _loggers_stub)
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.py
index bcf2eb1683..d787107d39 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py
@@ -3,10 +3,10 @@
 
 """Tests for LlamaCppBackend._wait_for_health resilience.
 
-The probe loop must swallow transient httpx errors and fall through to
-the subprocess.poll() branch so a crashed llama-server surfaces a
-structured "exited with code X" log instead of bubbling an opaque
-exception up to the /api/inference/load route.
+The probe loop must swallow transient httpx errors and fall through to the
+subprocess.poll() branch so a crashed llama-server surfaces a structured
+"exited with code X" log instead of bubbling an opaque exception up to the
+/api/inference/load route.
 """
 
 from __future__ import annotations
@@ -22,8 +22,7 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
     sys.path.insert(0, _BACKEND_DIR)
 
-# Match the stubbing pattern in sibling tests so the module imports in
-# a lightweight env without fastapi.
+# Mirror sibling tests' stubbing so the module imports without fastapi.
 _loggers_stub = _types.ModuleType("loggers")
 _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
 sys.modules.setdefault("loggers", _loggers_stub)
@@ -33,11 +32,10 @@ import httpx  # noqa: E402
 
 from core.inference.llama_cpp import LlamaCppBackend  # noqa: E402
 
-# Sibling tests in this directory install lightweight httpx stubs via
-# sys.modules.setdefault. When collected together, our `httpx` symbol
-# may be one of those stubs, which lacks `get`. Ensure the production
-# code finds a working `httpx.get` and the standard exception types
-# regardless of collection order by adding the missing attributes.
+# Sibling tests install lightweight httpx stubs via sys.modules.setdefault.
+# When collected together, our `httpx` may be such a stub lacking `get`. Add
+# the missing attributes so production code finds a working `httpx.get` and
+# the standard exception types regardless of collection order.
 if not hasattr(httpx, "get"):
     httpx.get = None  # placeholder; every test below monkeypatches it
 for _exc_name in (
@@ -52,9 +50,9 @@ for _exc_name in (
 
 
 def _make_backend(port: int = 12345) -> LlamaCppBackend:
-    """Build a barebones LlamaCppBackend instance with only the
-    attributes _wait_for_health touches. Bypasses __init__ so we do not
-    pull in the full subprocess + logging stack."""
+    """Barebones LlamaCppBackend with only the attributes
+    _wait_for_health touches. Bypasses __init__ to avoid the full
+    subprocess + logging stack."""
     b = LlamaCppBackend.__new__(LlamaCppBackend)
     b._port = port
     b._stdout_thread = None
@@ -72,14 +70,12 @@ class TestWaitForHealthResilience:
         assert b._wait_for_health(timeout = 1.0, interval = 0.01) is True
 
     def test_read_error_loops_to_subprocess_poll(self, monkeypatch):
-        """WinError 10054 maps to httpx.ReadError. The loop must swallow
-        it and the next iteration must detect the dead subprocess via
-        poll() != None, returning False with a structured exit-code log
-        instead of bubbling the ReadError."""
+        """WinError 10054 maps to httpx.ReadError. The loop must swallow it;
+        the next iteration detects the dead subprocess via poll() != None and
+        returns False with a structured exit-code log, not the ReadError."""
         b = _make_backend()
-        # First iteration: process alive (so we reach the httpx probe).
-        # Second iteration: process has exited (so we hit the structured
-        # exit-code branch and return False).
+        # Iter 1: process alive (reach the httpx probe).
+        # Iter 2: process exited (hit the exit-code branch, return False).
         b._process.poll.side_effect = [None, 1]
         b._process.returncode = 1
         b._stdout_lines = ["llama-server: ggml-cuda.dll failed to load"]
@@ -89,12 +85,12 @@ class TestWaitForHealthResilience:
 
         monkeypatch.setattr(httpx, "get", raise_read_error)
         assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
-        # Both iterations of the loop ran -- the ReadError did not bubble.
+        # Both loop iterations ran -- the ReadError did not bubble.
         assert b._process.poll.call_count >= 2
 
     def test_remote_protocol_error_also_swallowed(self, monkeypatch):
-        """Partial / malformed response on the probe (server crashed
-        mid-headers) raises RemoteProtocolError -- also non-fatal."""
+        """A partial/malformed probe response (server crashed mid-headers)
+        raises RemoteProtocolError -- also non-fatal."""
         b = _make_backend()
         b._process.poll.side_effect = [None, -1]
         b._process.returncode = -1
@@ -121,8 +117,8 @@ class TestWaitForHealthResilience:
         assert b._process.poll.call_count >= 2
 
     def test_connect_error_swallowed_until_success(self, monkeypatch):
-        """Sanity: existing ConnectError swallowing still works -- the
-        loop retries until llama-server eventually answers 200."""
+        """Sanity: existing ConnectError swallowing still works -- the loop
+        retries until llama-server answers 200."""
         b = _make_backend()
         b._process.poll.return_value = None
         calls = {"n": 0}
@@ -139,8 +135,8 @@ class TestWaitForHealthResilience:
         assert calls["n"] >= 3
 
     def test_dead_process_before_probe_returns_false(self, monkeypatch):
-        """If poll() != None on entry, _wait_for_health must return
-        False immediately without calling httpx at all."""
+        """poll() != None on entry: _wait_for_health returns False
+        immediately without calling httpx."""
         b = _make_backend()
         b._process.poll.return_value = 137
         b._process.returncode = 137
diff --git a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
index 125b13782a..5183553607 100644
--- a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
+++ b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py
@@ -3,9 +3,9 @@
 
 """``_wait_for_vram_settle`` helper contract.
 
-Pins the bounded poll over ``_get_gpu_free_memory`` that bridges the
-kill -> spawn VRAM-reclaim window. Patches ``_get_gpu_free_memory``;
-no real llama-server or nvidia-smi involved.
+Pins the bounded poll over ``_get_gpu_free_memory`` bridging the kill -> spawn
+VRAM-reclaim window. Patches ``_get_gpu_free_memory``; no real llama-server or
+nvidia-smi involved.
 """
 
 from __future__ import annotations
@@ -20,8 +20,8 @@ import pytest
 
 
 # ---------------------------------------------------------------------------
-# Same external-dep stubs as the other llama_cpp tests so this module
-# imports cleanly without httpx / structlog / loggers installed.
+# Same external-dep stubs as the other llama_cpp tests so this module imports
+# without httpx / structlog / loggers installed.
 # ---------------------------------------------------------------------------
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
@@ -34,8 +34,8 @@ sys.modules.setdefault("loggers", _loggers_stub)
 _structlog_stub = _types.ModuleType("structlog")
 _structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
 sys.modules.setdefault("structlog", _structlog_stub)
-# Ensure get_logger is set even if a previous test module already
-# inserted a bare ``structlog`` stub via ``setdefault``.
+# Set get_logger even if a prior test inserted a bare ``structlog`` stub
+# via ``setdefault``.
 if not hasattr(sys.modules["structlog"], "get_logger"):
     sys.modules["structlog"].get_logger = _structlog_stub.get_logger
 
@@ -74,8 +74,8 @@ def _patch_probe(samples):
     """Patch ``_get_gpu_free_memory`` to yield ``samples`` in order.
 
     Each entry is a list[(idx, free_mib)], a callable, or an exception
-    (instance or class). Calls past the end repeat the last entry so
-    tests can assert "stopped polling" via the call count.
+    (instance or class). Calls past the end repeat the last entry so tests
+    can assert "stopped polling" via the call count.
     """
     state = {"i": 0, "calls": 0}
 
@@ -112,8 +112,8 @@ def _kw(**extra):
 
 
 def test_cold_start_returns_immediately_without_probing():
-    """Default ``since_kill=0.0`` is cold-start: no kill recorded,
-    helper short-circuits without ever invoking the probe."""
+    """Default ``since_kill=0.0`` is cold-start: no kill recorded, so the
+    helper short-circuits without invoking the probe."""
     ctx, state = _patch_probe([[(0, 10000)], [(0, 10000)]])
     with ctx:
         start = time.monotonic()
@@ -154,8 +154,8 @@ def test_first_probe_raises_returns_without_polling():
 
 
 def test_two_consecutive_samples_within_tolerance_settles():
-    """The reclaim ramp from 10000 → 11500 → 11550: third sample within
-    256 MiB of the second so the helper returns after exactly three probes."""
+    """Reclaim ramp 10000 → 11500 → 11550: third sample within 256 MiB of
+    the second, so the helper returns after exactly three probes."""
     ctx, state = _patch_probe(
         [
             [(0, 10000)],
@@ -168,7 +168,7 @@ def test_two_consecutive_samples_within_tolerance_settles():
         LlamaCppBackend._wait_for_vram_settle(**_kw(max_wait = 2.0, interval = 0.05))
         elapsed = time.monotonic() - start
     assert state["calls"] == 3
-    # interval * 2 sleeps = 0.10; allow generous slack for scheduler jitter.
+    # interval * 2 sleeps = 0.10; allow slack for scheduler jitter.
     assert elapsed < 1.0
 
 
@@ -199,7 +199,7 @@ def test_max_wait_respected_when_never_settles():
         start = time.monotonic()
         LlamaCppBackend._wait_for_vram_settle(**_kw(max_wait = 0.5, interval = 0.1))
         elapsed = time.monotonic() - start
-    # We must stop near max_wait, not run forever. Generous upper bound for CI.
+    # Must stop near max_wait, not run forever. Generous upper bound for CI.
     assert 0.3 <= elapsed < 2.0, f"helper ignored max_wait: elapsed={elapsed:.3f}s"
 
 
@@ -217,8 +217,8 @@ def test_max_wait_respected_when_probe_is_slow():
             **_kw(max_wait = 0.4, interval = 0.25),
         )
         elapsed = time.monotonic() - start
-    # First probe (0.30 s) + at most one short clipped sleep + bail.
-    # Hard cap well below the old behaviour of 0.30 + 0.25 + 0.30 = 0.85.
+    # First probe (0.30 s) + at most one clipped sleep + bail.
+    # Hard cap well below the old 0.30 + 0.25 + 0.30 = 0.85.
     assert elapsed < 0.85, f"helper exceeded the deadline due to slow probes: {elapsed:.3f}s"
 
 
@@ -264,8 +264,8 @@ def test_tolerance_two_percent_for_large_cards():
 
 
 def test_load_model_calls_helper_outside_lock_and_uses_last_kill_timestamp():
-    """Pin the call site: outside Phase 3 lock, gated on the timestamp,
-    no ``had_live_process`` in-band flag regression. Mirrors the
+    """Pin the call site: outside Phase 3 lock, gated on the timestamp, no
+    ``had_live_process`` in-band flag regression. Mirrors the
     ``inspect.getsource`` pattern from ``test_llama_cpp_no_context_shift``.
     """
     import inspect
@@ -274,11 +274,11 @@ def test_load_model_calls_helper_outside_lock_and_uses_last_kill_timestamp():
     assert "_wait_for_vram_settle" in src
     assert "since_kill" in src
     assert "self._last_kill_monotonic" in src
-    # Must be invoked before Phase 3's broad lock so /unload, /cancel,
-    # /status are not blocked during the wait.
+    # Must run before Phase 3's broad lock so /unload, /cancel, /status
+    # are not blocked during the wait.
     assert src.index("_wait_for_vram_settle") < src.index("# ── Phase 3:")
-    # An in-band ``had_live_process`` flag would silently regress the
-    # frontend /unload+/load Apply path; use the timestamp instead.
+    # An in-band ``had_live_process`` flag would regress the frontend
+    # /unload+/load Apply path; use the timestamp instead.
     assert "had_live_process" not in src
 
 
diff --git a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
index a5c9d2255f..4fa7d2f8e6 100644
--- a/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
+++ b/studio/backend/tests/test_llama_cpp_windows_nvidia_path.py
@@ -4,9 +4,9 @@
 """Tests for the Windows pip-nvidia DLL dir resolver.
 
 Studio installs torch with bundled CUDA wheels (nvidia-cuda-runtime-cu13,
-nvidia-cublas-cu13, etc.) and the prebuilt llama-server.exe must find
-those DLLs at runtime to load CUDA. Mirrors the Linux LD_LIBRARY_PATH
-block. See unslothai/unsloth#5106.
+nvidia-cublas-cu13, etc.) and the prebuilt llama-server.exe must find those
+DLLs at runtime to load CUDA. Mirrors the Linux LD_LIBRARY_PATH block.
+See unslothai/unsloth#5106.
 """
 
 from __future__ import annotations
@@ -61,7 +61,7 @@ from core.inference.llama_cpp import LlamaCppBackend  # noqa: E402
 
 def _make_nvidia_layout(prefix: Path, pkgs_with_layout: dict[str, str]):
     """Build a fake /Lib/site-packages/nvidia//{bin|Library/bin}
-    tree with a stub DLL inside each leaf so isdir() picks them up."""
+    tree with a stub DLL in each leaf so isdir() picks them up."""
     nv = prefix / "Lib" / "site-packages" / "nvidia"
     for pkg, layout in pkgs_with_layout.items():
         if layout == "bin":
@@ -124,9 +124,8 @@ class TestWindowsPipNvidiaDllDirs:
         assert len(result) == 4
 
     def test_does_not_walk_outside_known_paths(self, tmp_path):
-        # Only nvidia//{bin,Library/bin} and torch/lib are picked
-        # up. Unrelated site-packages contents (numpy, scipy, ...) must
-        # be ignored.
+        # Only nvidia//{bin,Library/bin} and torch/lib are picked up.
+        # Unrelated site-packages contents (numpy, scipy, ...) are ignored.
         site = tmp_path / "Lib" / "site-packages"
         (site / "numpy").mkdir(parents = True)
         (site / "scipy" / "linalg").mkdir(parents = True)
@@ -135,9 +134,9 @@ class TestWindowsPipNvidiaDllDirs:
 
     def test_picks_up_torch_lib(self, tmp_path):
         # PyTorch's Windows CUDA wheel bundles cudart64_X.dll /
-        # cublas64_X.dll directly under Lib/site-packages/torch/lib/
-        # instead of as separate nvidia-* wheels. Without this, users
-        # on torch-bundled-CUDA installs still hit #5106.
+        # cublas64_X.dll directly under Lib/site-packages/torch/lib/ rather
+        # than as separate nvidia-* wheels. Without this, torch-bundled-CUDA
+        # installs still hit #5106.
         torch_lib = tmp_path / "Lib" / "site-packages" / "torch" / "lib"
         torch_lib.mkdir(parents = True)
         (torch_lib / "cudart64_12.dll").write_bytes(b"")
@@ -146,8 +145,7 @@ class TestWindowsPipNvidiaDllDirs:
         assert Path(result[0]) == torch_lib
 
     def test_torch_lib_combined_with_nvidia_wheels(self, tmp_path):
-        # Both modular nvidia-* wheels and torch/lib are returned when
-        # present together.
+        # Both modular nvidia-* wheels and torch/lib are returned together.
         _make_nvidia_layout(
             tmp_path,
             {
@@ -165,8 +163,7 @@ class TestWindowsPipNvidiaDllDirs:
         assert any(Path(p) == torch_lib for p in result)
 
     def test_torch_lib_must_be_a_directory(self, tmp_path):
-        # If torch/lib exists as a file (broken install), it is
-        # ignored, not returned.
+        # If torch/lib exists as a file (broken install), it is ignored.
         site = tmp_path / "Lib" / "site-packages" / "torch"
         site.mkdir(parents = True)
         (site / "lib").write_bytes(b"not a dir")
@@ -176,24 +173,22 @@ class TestWindowsPipNvidiaDllDirs:
     def test_skips_non_directories(self, tmp_path):
         nv = tmp_path / "Lib" / "site-packages" / "nvidia"
         (nv / "cuda_runtime").mkdir(parents = True)
-        # Create a regular file at the path where 'bin' would normally be a dir
+        # Regular file where 'bin' would normally be a dir
         (nv / "cuda_runtime" / "bin").write_bytes(b"not a dir")
         result = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(tmp_path))
         assert result == []
 
     def test_missing_prefix_does_not_raise(self):
-        # If sys.prefix points to a path that doesn't exist (unusual,
-        # but possible during test setup), the resolver must just
-        # return [] rather than raising.
+        # If sys.prefix points to a nonexistent path (unusual but possible
+        # during test setup), the resolver must return [], not raise.
         result = LlamaCppBackend._windows_pip_nvidia_dll_dirs("/this/path/does/not/exist/anywhere")
         assert result == []
 
     def test_picks_up_cu13_bin_x86_64_layout(self, tmp_path):
-        # Current ``nvidia-cuda-runtime`` 13.x and ``nvidia-cublas``
-        # 13.x Windows wheels ship DLLs under
-        # ``nvidia/cu13/bin/x86_64/`` instead of ``nvidia//bin/``.
-        # Without this, users on the new CUDA 13 wheel generation hit
-        # the original #5106 failure mode.
+        # Current ``nvidia-cuda-runtime`` 13.x and ``nvidia-cublas`` 13.x
+        # Windows wheels ship DLLs under ``nvidia/cu13/bin/x86_64/`` instead
+        # of ``nvidia//bin/``. Without this, the new CUDA 13 wheel
+        # generation hits the original #5106 failure mode.
         dll_dir = tmp_path / "Lib" / "site-packages" / "nvidia" / "cu13" / "bin" / "x86_64"
         dll_dir.mkdir(parents = True)
         for name in ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"):
@@ -203,7 +198,7 @@ class TestWindowsPipNvidiaDllDirs:
 
     def test_picks_up_bin_x64_layout(self, tmp_path):
         # Some repackaged wheels use ``bin/x64`` (Windows-x64 convention)
-        # instead of ``bin/x86_64`` (NVIDIA-internal convention).
+        # rather than ``bin/x86_64`` (NVIDIA-internal convention).
         dll_dir = tmp_path / "Lib" / "site-packages" / "nvidia" / "cu13" / "bin" / "x64"
         dll_dir.mkdir(parents = True)
         (dll_dir / "cudart64_13.dll").write_bytes(b"")
@@ -211,9 +206,8 @@ class TestWindowsPipNvidiaDllDirs:
         assert str(dll_dir) in result
 
     def test_mixed_cu12_and_cu13_layouts(self, tmp_path):
-        # A venv could have both the modular cu12 wheels (legacy) and
-        # the unsuffixed cu13 wheel installed side by side. Both must
-        # be reachable.
+        # A venv could have both the modular cu12 wheels (legacy) and the
+        # unsuffixed cu13 wheel side by side. Both must be reachable.
         site = tmp_path / "Lib" / "site-packages"
         cu12_bin = site / "nvidia" / "cuda_runtime" / "bin"
         cu13_arch = site / "nvidia" / "cu13" / "bin" / "x86_64"
@@ -225,10 +219,10 @@ class TestWindowsPipNvidiaDllDirs:
         assert cu13_arch in result_set
 
     def test_glob_meta_in_prefix_is_safe(self, tmp_path):
-        # Windows usernames / install paths can contain ``[`` or ``]``.
-        # A glob-based resolver would interpret these as a character
-        # class and silently return [] even when DLL dirs exist. The
-        # iterdir-based implementation must work on such paths.
+        # Windows usernames / install paths can contain ``[`` or ``]``. A
+        # glob-based resolver would read these as a character class and
+        # return [] even when DLL dirs exist. The iterdir-based
+        # implementation must work on such paths.
         prefix = tmp_path / "studio_[gpu]_install"
         dll_dir = prefix / "Lib" / "site-packages" / "nvidia" / "cuda_runtime" / "bin"
         dll_dir.mkdir(parents = True)
@@ -237,18 +231,17 @@ class TestWindowsPipNvidiaDllDirs:
         assert str(dll_dir) in result, f"bracket-prefixed path returned empty: {result}"
 
     def test_arch_subdir_listed_before_parent_bin(self, tmp_path):
-        # When both ``nvidia//bin/`` and
-        # ``nvidia//bin/x86_64/`` exist, the arch-specific subdir
-        # must be listed first so Windows DLL search picks up the
-        # cudart64_X.dll location even if the parent ``bin`` is empty.
+        # When both ``nvidia//bin/`` and ``nvidia//bin/x86_64/``
+        # exist, the arch-specific subdir must be listed first so the Windows
+        # DLL search finds cudart64_X.dll even if the parent ``bin`` is empty.
         site = tmp_path / "Lib" / "site-packages"
         outer_bin = site / "nvidia" / "cu13" / "bin"
         arch_bin = outer_bin / "x86_64"
         arch_bin.mkdir(parents = True)
         (arch_bin / "cudart64_13.dll").write_bytes(b"")
         result = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(tmp_path))
-        # outer_bin exists as a directory (it contains arch_bin); the
-        # arch-specific subdir should come first in the list.
+        # outer_bin exists as a dir (it holds arch_bin); the arch-specific
+        # subdir should come first in the list.
         result_paths = [Path(p) for p in result]
         assert arch_bin in result_paths
         assert outer_bin in result_paths
diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.py
index 2c7362a9ff..60d4fb0bc3 100644
--- a/studio/backend/tests/test_llama_server_args.py
+++ b/studio/backend/tests/test_llama_server_args.py
@@ -4,8 +4,8 @@
 """Unit tests for the llama-server pass-through args validator.
 
 The validator is the boundary between user CLI/HTTP input and the
-llama-server subprocess. These tests pin denylist behaviour so it
-doesn't quietly regress when new managed flags are added.
+llama-server subprocess. These tests pin denylist behaviour so it doesn't
+regress when new managed flags are added.
 """
 
 from __future__ import annotations
@@ -16,10 +16,10 @@ from pathlib import Path
 
 import pytest
 
-# Load llama_server_args.py directly so this test doesn't drag in the
-# full backend chain (fastapi / structlog / loggers / utils.hardware)
-# via core/inference/__init__.py. The validator is intentionally
-# dependency-free and unit-tests should reflect that.
+# Load llama_server_args.py directly so this test doesn't drag in the full
+# backend chain (fastapi / structlog / loggers / utils.hardware) via
+# core/inference/__init__.py. The validator is intentionally dependency-free
+# and unit tests should reflect that.
 _LSA_PATH = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_server_args.py"
 _spec = importlib.util.spec_from_file_location("_lsa_test_only", _LSA_PATH)
 _lsa = importlib.util.module_from_spec(_spec)
@@ -72,10 +72,10 @@ validate_extra_args = _lsa.validate_extra_args
         # Reasoning controls
         ["--reasoning-format", "deepseek"],
         ["-rea", "auto"],
-        # Soft-managed: user-supplied flags last-wins-override Studio's
-        # auto-set version. --parallel / -np / --n-parallel are NOT
-        # here -- they're hard-denied (KV-cache + slot count would
-        # desync). Use `unsloth studio run --parallel N` instead.
+        # Soft-managed: user flags last-wins-override Studio's auto-set
+        # version. --parallel / -np / --n-parallel are NOT here -- they're
+        # hard-denied (KV-cache + slot count would desync). Use
+        # `unsloth studio run --parallel N` instead.
         ["-c", "131072"],
         ["--ctx-size", "8192"],
         ["--flash-attn", "off"],
@@ -124,8 +124,8 @@ def test_non_flag_token_passes_through():
         "-np",
         "--parallel",
         "--n-parallel",
-        # Model identity (every alias; bumping llama.cpp must keep
-        # every form rejected, not just the long).
+        # Model identity (every alias; bumping llama.cpp must keep every
+        # form rejected, not just the long one).
         "-m",
         "--model",
         "-mu",
@@ -173,8 +173,8 @@ def test_non_flag_token_passes_through():
         "--models-max",
         "--models-autoload",
         "--no-models-autoload",
-        # Server-mode flips: --embedding / --rerank would restrict
-        # llama-server to those endpoints and break Studio's chat hop.
+        # Server-mode flips: --embedding / --rerank restrict llama-server to
+        # those endpoints and break Studio's chat hop.
         "--embedding",
         "--embeddings",
         "--rerank",
@@ -191,16 +191,16 @@ def test_denylist_rejects_all_aliases(denied):
 @pytest.mark.parametrize(
     "args,offending",
     [
-        # Pass-through --parallel would last-wins-override the real
-        # slot count while Studio's KV-cache fit + llama_parallel_slots
-        # stay at the typer value -- plan vs. process disagree.
+        # Pass-through --parallel would last-wins-override the real slot
+        # count while Studio's KV-cache fit + llama_parallel_slots stay at
+        # the typer value -- plan vs. process disagree.
         (["--parallel", "8"], "--parallel"),
         (["--parallel=8"], "--parallel"),
         (["--n-parallel", "16"], "--n-parallel"),
         (["--n-parallel=16"], "--n-parallel"),
         (["-np", "32"], "-np"),
-        # Attached short form: Click clusters it CLI-side; HTTP /load
-        # with `["-np8"]` must still resolve to managed.
+        # Attached short form: Click clusters it CLI-side; HTTP /load with
+        # `["-np8"]` must still resolve to managed.
         (["-np8"], "-np"),
         (["-np64"], "-np"),
         # Out-of-range values that would bypass the typer 1..64 guard.
@@ -227,8 +227,8 @@ def test_denylist_rejects_equals_form():
     [" --parallel", "--parallel ", "\t--parallel", "  -np", "-np \n", "-np\t"],
 )
 def test_denylist_rejects_whitespace_padded_forms(padded):
-    # `_flag_name` trims whitespace before lookup; otherwise a trailing
-    # space could slip a managed flag past the boundary.
+    # `_flag_name` trims whitespace before lookup; else a trailing space
+    # could slip a managed flag past the boundary.
     with pytest.raises(ValueError, match = "parallel|np"):
         validate_extra_args([padded, "8"])
 
@@ -238,15 +238,15 @@ def test_denylist_rejects_whitespace_padded_forms(padded):
     ["-np8x", "-np-1foo", "-np+1bar", "-np9zzz"],
 )
 def test_denylist_rejects_np_with_digit_prefix_and_junk(attached):
-    # Backend `_flag_name` must classify the same forms the CLI
-    # rewriter expands, else HTTP /load could smuggle `-np8x` through.
+    # Backend `_flag_name` must classify the same forms the CLI rewriter
+    # expands, else HTTP /load could smuggle `-np8x` through.
     with pytest.raises(ValueError, match = "np"):
         validate_extra_args([attached])
 
 
 def test_denylist_rejects_short_form_when_long_is_denied():
-    # `-m` is the short form of --model; rejecting only the long
-    # form would leave a trivial bypass.
+    # `-m` is the short form of --model; rejecting only the long form
+    # would leave a trivial bypass.
     with pytest.raises(ValueError, match = "-m"):
         validate_extra_args(["-m", "/some/other/path.gguf"])
 
diff --git a/studio/backend/tests/test_log_filter_no_truncation.py b/studio/backend/tests/test_log_filter_no_truncation.py
index d9a6e2bc4a..52ffa2ba32 100644
--- a/studio/backend/tests/test_log_filter_no_truncation.py
+++ b/studio/backend/tests/test_log_filter_no_truncation.py
@@ -4,9 +4,9 @@
 """
 Regression tests for loggers.handlers.filter_sensitive_data.
 
-Pins two properties: (1) long strings with commas/slashes pass through
-unchanged (the base64-truncation heuristic from PR #5246 was too aggressive),
-and (2) native-path lease redaction still fires for both inline and dict-key forms.
+Pins two properties: (1) long strings with commas/slashes pass through unchanged
+(the base64-truncation heuristic from PR #5246 was too aggressive), and
+(2) native-path lease redaction still fires for inline and dict-key forms.
 """
 
 from loggers.handlers import filter_sensitive_data
diff --git a/studio/backend/tests/test_login_rate_limit.py b/studio/backend/tests/test_login_rate_limit.py
index 1b084cf436..6f2d2c7d94 100644
--- a/studio/backend/tests/test_login_rate_limit.py
+++ b/studio/backend/tests/test_login_rate_limit.py
@@ -4,11 +4,11 @@
 """Tests for the per-(ip, username) login rate limiter.
 
 Covers:
-  - bucket key composition is (client-ip, username.lower())
-  - X-Forwarded-For is honoured only when UNSLOTH_STUDIO_TRUST_FORWARDED is set
+  - bucket key is (client-ip, username.lower())
+  - X-Forwarded-For honoured only when UNSLOTH_STUDIO_TRUST_FORWARDED is set
   - 429 detail body does NOT leak the client IP
-  - One username failing does not lock out a different user from the same IP
-  - One IP failing does not lock out the same user from a different IP
+  - One username failing doesn't lock out a different user from the same IP
+  - One IP failing doesn't lock out the same user from a different IP
 """
 
 import os
@@ -69,8 +69,8 @@ class TestClientIp:
             "127.0.0.1",
             {"x-forwarded-for": "198.51.100.7, 10.0.0.1"},
         )
-        # The proxy header could be spoofed; without the opt-in we
-        # only trust the direct connection.
+        # Proxy header can be spoofed; without the opt-in, trust only the
+        # direct connection.
         assert _client_ip(req) == "127.0.0.1"
 
     def test_honours_first_xff_when_trust_on(self, env_trust_proxy):
@@ -123,8 +123,8 @@ class TestClientIp:
     def test_forwarded_isolates_first_element(self, env_trust_proxy):
         from routes.auth import _client_ip
 
-        # Multi-element Forwarded must pick the first element only,
-        # otherwise suffix variations create attacker-controlled buckets.
+        # Multi-element Forwarded must pick the first element only, else suffix
+        # variations create attacker-controlled buckets.
         req = _FakeRequest(
             "127.0.0.1",
             {"forwarded": "for=198.51.100.42, for=10.0.0.1;proto=https"},
@@ -155,7 +155,7 @@ class TestBucketKeyAndBlocking:
         for _ in range(_LOGIN_MAX_FAILS):
             _record_login_failure(_bucket_key(req, "alice"))
         assert _login_blocked(_bucket_key(req, "alice")) > 0
-        # bob's account from the same IP is unaffected by alice's typos.
+        # bob's account from the same IP is unaffected by alice's typos
         assert _login_blocked(_bucket_key(req, "bob")) == 0
 
     def test_record_per_ip_isolates_other_ips(self, env_no_proxy):
@@ -189,8 +189,8 @@ class TestBucketKeyAndBlocking:
         req = _FakeRequest("203.0.113.10")
         for idx in range(5):
             auth_routes._record_login_failure(auth_routes._unknown_user_key(req))
-            # Different "username" each attempt would not have throttled
-            # under per-(ip,username) only; the IP aggregate must.
+            # A different "username" each attempt wouldn't throttle under
+            # per-(ip,username) only; the IP aggregate must.
         # The next missing-user attempt is blocked.
         assert auth_routes._login_blocked(auth_routes._unknown_user_key(req)) > 0
 
@@ -202,8 +202,8 @@ class TestBucketKeyAndBlocking:
         unknown_key = auth_routes._unknown_user_key(req)
         for _ in range(20):
             auth_routes._record_login_failure(unknown_key)
-        # Account bucket cardinality stays at exactly one sentinel entry
-        # for this IP regardless of how many distinct usernames sprayed.
+        # Account bucket cardinality stays at exactly one sentinel entry for
+        # this IP regardless of how many distinct usernames sprayed.
         ip_keys = [k for k in auth_routes._LOGIN_BUCKETS if k[0] == "203.0.113.11"]
         assert len(ip_keys) == 1
         assert ip_keys[0][1].startswith("\x00")
@@ -216,7 +216,7 @@ class TestBucketKeyAndBlocking:
         req = _FakeRequest("203.0.113.12")
         for idx in range(50):
             auth_routes._record_login_failure((req.client.host, f"user-{idx}"))
-        # Hard cap respected; further keys do not allocate.
+        # Hard cap respected; further keys don't allocate.
         assert len(auth_routes._LOGIN_BUCKETS) <= 10
 
 
@@ -249,7 +249,7 @@ class TestLogin429Body:
     def test_429_detail_does_not_leak_ip(self, env_no_proxy, login_client):
         from routes.auth import _LOGIN_MAX_FAILS
 
-        # Drive 6 failures from the same client IP / username.
+        # Drive 6 failures from the same client IP / username
         for _ in range(_LOGIN_MAX_FAILS):
             r = login_client.post(
                 "/api/auth/login",
@@ -262,8 +262,8 @@ class TestLogin429Body:
         )
         assert r.status_code == 429
         detail = r.json()["detail"]
-        # The 429 body must not interpolate the source IP.
+        # The 429 body must not interpolate the source IP
         assert "127.0.0.1" not in detail
         assert "Too many" in detail
-        # Retry-After header is still set for clients.
+        # Retry-After header is still set for clients
         assert "Retry-After" in r.headers
diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.py
index 0d263d7630..9def1619d7 100644
--- a/studio/backend/tests/test_mcp_servers.py
+++ b/studio/backend/tests/test_mcp_servers.py
@@ -151,8 +151,8 @@ def test_execute_tool_disabled_server(tmp_path, monkeypatch):
 
 
 def test_mcp_specs_skip_invalid_openai_function_names():
-    """OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; tools whose
-    names contain '.', '/', spaces, etc. would 400 the whole request."""
+    """OpenAI requires function.name ^[a-zA-Z0-9_-]{1,64}$; names with '.',
+    '/', spaces, etc. would 400 the whole request."""
     from core.inference.tools import _mcp_specs_for_server
 
     server = {"id": "srv", "display_name": "S"}
@@ -178,7 +178,7 @@ def test_mcp_specs_skip_empty_tool_name():
 
 def test_mcp_specs_drops_duplicate_names():
     """Same tool name twice from one MCP server -> OpenAI rejects the
-    request as 'duplicates'. Drop the duplicate before forwarding."""
+    request as 'duplicates'. Drop duplicates before forwarding."""
     from core.inference.tools import _mcp_specs_for_server
 
     server = {"id": "srv", "display_name": "S"}
@@ -188,8 +188,8 @@ def test_mcp_specs_drops_duplicate_names():
 
 
 def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
-    """cancel_event already set before the call -> immediate Error: cancelled
-    without making a network round-trip."""
+    """cancel_event set before the call -> immediate Error: cancelled, no
+    network round-trip."""
     import threading
     from core.inference import mcp_client
 
@@ -203,7 +203,7 @@ def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
 
         async def call_tool(self, name, args):
             import asyncio as _asyncio
-            await _asyncio.sleep(30)  # never finishes within the test
+            await _asyncio.sleep(30)  # never finishes during the test
 
     monkeypatch.setattr(mcp_client, "_client", lambda *a, **kw: _StubClient())
 
@@ -221,8 +221,8 @@ def test_call_tool_sync_respects_pre_set_cancel_event(monkeypatch):
 
 
 def test_clear_oauth_tokens_async_no_op_safe(tmp_path, monkeypatch):
-    """clear_oauth_tokens_async on a URL with no stored token must not raise --
-    the delete + update handlers call it best-effort regardless of prior state."""
+    """clear_oauth_tokens_async on a URL with no stored token must not raise;
+    the delete + update handlers call it best-effort regardless of state."""
     import asyncio
 
     monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
@@ -233,7 +233,7 @@ def test_clear_oauth_tokens_async_no_op_safe(tmp_path, monkeypatch):
 
 
 def test_delete_server_calls_oauth_cleanup_when_oauth_was_on(tmp_path, monkeypatch):
-    """delete_mcp_server route helper should invoke clear_oauth_tokens_async
+    """delete_mcp_server route helper must call clear_oauth_tokens_async
     when the deleted row had use_oauth=true."""
     import asyncio
 
@@ -255,7 +255,7 @@ def test_delete_server_calls_oauth_cleanup_when_oauth_was_on(tmp_path, monkeypat
         calls.append(url)
 
     monkeypatch.setattr(mcp_client, "clear_oauth_tokens_async", fake_clear)
-    # Re-import the route's binding through the module so the patch is seen.
+    # Patch the route's module binding too so it's seen.
     import routes.mcp_servers as routes_mcp
 
     monkeypatch.setattr(routes_mcp, "clear_oauth_tokens_async", fake_clear)
@@ -292,7 +292,7 @@ def test_delete_server_skips_oauth_cleanup_when_oauth_off(tmp_path, monkeypatch)
 
 def test_update_server_clears_oauth_on_url_change(tmp_path, monkeypatch):
     """Changing the URL on an OAuth server must drop the old URL's tokens
-    so the new URL doesn't silently inherit credentials."""
+    so the new URL doesn't inherit credentials."""
     import asyncio
 
     _reset_db(tmp_path, monkeypatch)
@@ -381,7 +381,7 @@ def test_changes_from_payload_rejects_null_use_oauth():
 
 def test_test_endpoint_surfaces_url_validation_as_400(tmp_path, monkeypatch):
     """POST /api/mcp/servers/test must 400 on invalid URL like create/update;
-    previously the same input returned 200 with {"ok": false}."""
+    it previously returned 200 with {"ok": false}."""
     import asyncio
 
     _reset_db(tmp_path, monkeypatch)
@@ -399,9 +399,9 @@ def test_test_endpoint_surfaces_url_validation_as_400(tmp_path, monkeypatch):
 
 
 def test_tool_xml_parser_handles_hyphenated_parameter_names():
-    """MCP tool schemas commonly use hyphenated property names like
+    """MCP tool schemas often use hyphenated property names like
     `issue-number` / `repo-name`; the XML parser's `` regex
-    dropped those keys. Verify hyphenated parameter names round-trip."""
+    dropped those keys. Verify hyphenated names round-trip."""
     from core.inference.tool_call_parser import parse_tool_calls_from_text
     import json as _json
 
@@ -428,9 +428,9 @@ def test_tool_healing_strip_handles_hyphenated_function_names():
 
 
 def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
-    """When the model emits a tool call not in the per-request tool list
-    the GGUF agentic loop must refuse to dispatch -- mirroring the
-    safetensors path. Previously execute_tool ran the call regardless."""
+    """When the model emits a tool call not in the per-request tool list,
+    the GGUF agentic loop must refuse to dispatch (mirroring the
+    safetensors path). execute_tool previously ran the call regardless."""
     from core.inference import tools as tools_mod
 
     captured: list[str] = []
@@ -441,8 +441,8 @@ def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
 
     monkeypatch.setattr(tools_mod, "execute_tool", fake_execute)
 
-    # Re-create the allow-list check inline so we can unit-test the
-    # behavior without spinning up llama-server.
+    # Re-create the allow-list check inline to unit-test the behavior
+    # without spinning up llama-server.
     def _gate(tools_advertised, called_name, args):
         allowed = {
             (t.get("function") or {}).get("name")
@@ -472,9 +472,9 @@ def test_gguf_allow_list_blocks_unadvertised_tool(monkeypatch):
 
 
 def test_call_tool_sync_short_circuits_on_pre_set_cancel(monkeypatch):
-    """cancel_event set BEFORE call_tool_sync runs -> no HTTP request
-    is made. Previously the call task was created before the cancel
-    check, opening a transport that the watcher then had to cancel."""
+    """cancel_event set BEFORE call_tool_sync runs -> no HTTP request made.
+    The call task was previously created before the cancel check, opening a
+    transport that the watcher then had to cancel."""
     from core.inference import mcp_client
 
     opened: list[str] = []
@@ -510,9 +510,9 @@ def test_call_tool_sync_short_circuits_on_pre_set_cancel(monkeypatch):
 
 
 def test_clear_oauth_tokens_swallows_constructor_errors(tmp_path, monkeypatch):
-    """clear_oauth_tokens_async is best-effort; an OAuth constructor
-    failure (e.g. missing fastmcp.client.auth) must not bubble out into
-    a 500 from the delete / update routes."""
+    """clear_oauth_tokens_async is best-effort; an OAuth constructor failure
+    (e.g. missing fastmcp.client.auth) must not bubble into a 500 from the
+    delete / update routes."""
     import asyncio
     from core.inference import mcp_client
 
@@ -535,8 +535,8 @@ def test_clear_oauth_tokens_swallows_constructor_errors(tmp_path, monkeypatch):
 
 def test_tool_xml_parser_handles_hyphenated_function_names():
     """MCP tool names are advertised as `mcp__srv__list-issues` (the regex
-    fix allows '-'); the XML tool-call parser must parse them too,
-    otherwise the model can call the tool but Studio cannot dispatch."""
+    fix allows '-'); the XML tool-call parser must parse them too, else the
+    model can call the tool but Studio cannot dispatch."""
     from core.inference.tool_call_parser import parse_tool_calls_from_text
 
     calls = parse_tool_calls_from_text(
@@ -552,7 +552,7 @@ def test_tool_xml_parser_handles_hyphenated_function_names():
 
 def test_tool_xml_strip_handles_hyphenated_function_names():
     """routes/inference.py:_TOOL_XML_RE must strip a ``
-    block; otherwise hyphenated MCP tool-call XML leaks into chat history."""
+    block; else hyphenated MCP tool-call XML leaks into chat history."""
     import re as _re
     from pathlib import Path
 
@@ -570,11 +570,10 @@ def test_tool_xml_strip_handles_hyphenated_function_names():
 
 
 def test_safetensors_agentic_empty_allowlist_still_means_allow_all():
-    """Document existing contract: at the safetensors_agentic layer,
-    tools=[] is still treated as "no constraint" (so existing callers
-    work unchanged). The real fix for the MCP-only-no-discovery case
-    lives at the route level in inference.py, which refuses to enter
-    use_tools when the resolved tool list is empty."""
+    """Document the contract: at the safetensors_agentic layer, tools=[] is
+    still "no constraint" (existing callers work unchanged). The real fix
+    for the MCP-only-no-discovery case lives at the route level in
+    inference.py, which refuses use_tools when the resolved list is empty."""
     import threading
     from core.inference.safetensors_agentic import run_safetensors_tool_loop
 
diff --git a/studio/backend/tests/test_mcp_stdio_improvements.py b/studio/backend/tests/test_mcp_stdio_improvements.py
index 515e39d5b6..bec4f9393e 100644
--- a/studio/backend/tests/test_mcp_stdio_improvements.py
+++ b/studio/backend/tests/test_mcp_stdio_improvements.py
@@ -1,8 +1,8 @@
 """Tests for the proposed PR #5863 improvements.
 
 Covers: _client() self-gating + keep_alive, OAuth normalised off for stdio
-(create + update), env/header dropped on a transport-type switch, and the
-backend rejecting a command whose first token is a URL scheme.
+(create + update), env/header dropped on a transport-type switch, and rejecting
+a command whose first token is a URL scheme.
 
 Run from studio/backend:  python -m pytest tests/test_mcp_stdio_improvements.py -q
 """
@@ -41,7 +41,7 @@ def test_client_refuses_stdio_when_disabled(monkeypatch):
 def test_client_builds_stdio_when_enabled_without_spawning(monkeypatch):
     _enable(monkeypatch)
     # Constructing the Client must not spawn the subprocess (spawn happens on
-    # __aenter__); we only assert it builds.
+    # __aenter__); only assert it builds.
     client = mcp_client._client("npx -y server /tmp", {"K": "v"})
     assert client is not None
 
@@ -122,7 +122,7 @@ def test_switch_stdio_to_http_drops_env(tmp_path, monkeypatch):
             "s1", McpServerUpdate(url = "https://remote/mcp"), current_subject = "u"
         )
     )
-    # the stdio env must NOT survive as HTTP headers on the remote endpoint
+    # stdio env must NOT survive as HTTP headers on the remote endpoint
     assert resp.headers == {}
     assert mcp_servers_db.get_server("s1")["headers_json"] is None
 
@@ -161,7 +161,7 @@ def test_same_transport_edit_keeps_headers(tmp_path, monkeypatch):
         url = "npx server",
         headers_json = '{"API_KEY": "secret"}',
     )
-    # editing only the display name (still stdio) must not wipe env vars
+    # editing only the display name (still stdio) must keep env vars
     resp = asyncio.run(
         routes_mcp.update_mcp_server("s1", McpServerUpdate(display_name = "B"), current_subject = "u")
     )
@@ -183,13 +183,13 @@ def test_validate_url_rejects_url_scheme_command_when_enabled(monkeypatch):
 def test_validate_url_allows_url_in_argument(monkeypatch):
     from routes.mcp_servers import _validate_url
     _enable(monkeypatch)
-    # :// inside an ARGUMENT (not the first token) is still a valid command
+    # :// inside an ARGUMENT (not the first token) is a valid command
     assert _validate_url("npx server --url https://x/mcp") == ("npx server --url https://x/mcp")
 
 
 # ── P6: Data Recipe stdio path obeys the same host gate ─────────────
-# build_mcp_providers needs the data_designer plugin, which is only installed in
-# the Studio test job; skip there rather than fail the core matrix.
+# build_mcp_providers needs the data_designer plugin, installed only in the
+# Studio test job; skip there rather than fail the core matrix.
 
 _STDIO_RECIPE = {
     "mcp_providers": [
@@ -209,7 +209,7 @@ def test_data_recipe_skips_stdio_when_disabled(monkeypatch):
     _disable(monkeypatch)
     from core.data_recipe.service import build_mcp_providers
 
-    # gate off -> the stdio provider is dropped (no subprocess can be spawned)
+    # gate off -> the stdio provider is dropped (no subprocess spawned)
     assert build_mcp_providers(_STDIO_RECIPE) == []
 
 
diff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.py
index 277306836b..d744c07b14 100644
--- a/studio/backend/tests/test_mcp_stdio_pr5863.py
+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py
@@ -2,10 +2,10 @@
 
 Covers the pure helpers (is_stdio / parse_stdio_command / stdio_mcp_enabled /
 probe_timeout), the route-level _validate_url gate, and - most importantly -
-that the UNSLOTH_STUDIO_ALLOW_STDIO_MCP gate blocks the stdio transport at all
-five enforcement points (create, update, test, refresh, discovery, execute)
-when disabled, and reaches it when enabled. The transport (_client) is stubbed
-so no real subprocess is spawned; a recorder asserts whether it was reached.
+that the UNSLOTH_STUDIO_ALLOW_STDIO_MCP gate blocks the stdio transport at
+every enforcement point (create, update, test, refresh, discovery, execute)
+when disabled and reaches it when enabled. The transport (_client) is stubbed
+so no real subprocess spawns; a recorder asserts whether it was reached.
 
 Run from studio/backend:  python -m pytest tests/test_mcp_stdio_pr5863.py -q
 """
@@ -57,7 +57,7 @@ class _FakeResult:
 
 
 class _RecordingClient:
-    """Stands in for fastmcp.Client; records that the transport was opened."""
+    """Stand-in for fastmcp.Client; records that the transport was opened."""
 
     def __init__(self, url, headers, use_oauth, recorder):
         recorder.append({"url": url, "headers": headers, "use_oauth": use_oauth})
@@ -78,7 +78,7 @@ class _RecordingClient:
 @pytest.fixture
 def transport(monkeypatch):
     """Patch mcp_client._client with a recorder. Returns the recorder list;
-    empty == the stdio transport was never reached."""
+    empty == stdio transport never reached."""
     recorder = []
     monkeypatch.setattr(
         mcp_client,
@@ -156,8 +156,8 @@ def test_parse_unclosed_quote_raises_valueerror():
 
 
 def test_parse_windows_strips_wrapping_quotes(monkeypatch):
-    # gemini "medium": posix=False keeps backslash paths but also the wrapping
-    # quotes; the PR strips a matched pair so argv[0] reaches the OS clean.
+    # gemini "medium": posix=False keeps backslash paths but also the
+    # wrapping quotes; the PR strips a matched pair so argv[0] is clean.
     monkeypatch.setattr(sys, "platform", "win32")
     parts = mcp_client.parse_stdio_command(r'"C:\Program Files\node\node.exe" server.js')
     assert parts[0] == r"C:\Program Files\node\node.exe"
@@ -214,8 +214,8 @@ def test_validate_url_gate_off_rejects_stdio(monkeypatch):
 
 
 def test_validate_url_gate_off_message_depends_on_whitespace(monkeypatch):
-    # The message names a command only when the value has whitespace, and never
-    # says "desktop app only" (self-hosted hosts can opt in via the env var).
+    # The message names a command only when the value has whitespace, and
+    # never says "desktop app only" (self-hosted can opt in via the env var).
     _disable(monkeypatch)
     from routes.mcp_servers import _validate_url
 
@@ -242,8 +242,8 @@ def test_validate_url_gate_on_accepts_stdio(monkeypatch):
     assert _validate_url("https://x/mcp") == "https://x/mcp"
     # url-bearing argument accepted as a command
     assert _validate_url("npx server --url https://x/mcp") == ("npx server --url https://x/mcp")
-    # A lone token is ambiguous; keep the prior behaviour and accept it as a
-    # command rather than guessing it's a URL (no regression for single binaries).
+    # A lone token is ambiguous; accept it as a command rather than
+    # guessing it's a URL (no regression for single binaries).
     assert _validate_url("/usr/local/bin/my-mcp-server") == "/usr/local/bin/my-mcp-server"
     assert _validate_url("mcp-server-sqlite") == "mcp-server-sqlite"
     # empty / unparseable still rejected
@@ -284,7 +284,7 @@ def test_update_http_to_stdio_blocked_when_off(tmp_path, monkeypatch):
     _reset_db(tmp_path, monkeypatch)
     _disable(monkeypatch)
     mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")
-    # editing url -> stdio command must 400 (http->stdio edit bypass closed)
+    # editing url -> stdio command must 400 (http->stdio bypass closed)
     with pytest.raises(HTTPException) as exc:
         asyncio.run(
             routes_mcp.update_mcp_server(
@@ -321,7 +321,7 @@ def test_refresh_route_gate(tmp_path, monkeypatch, transport):
     import routes.mcp_servers as routes_mcp
 
     _reset_db(tmp_path, monkeypatch)
-    # a stdio row as if carried over from a desktop DB
+    # a stdio row, as if carried over from a desktop DB
     mcp_servers_db.create_server(id = "stdio1", display_name = "FS", url = "npx server")
 
     _disable(monkeypatch)
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 2d6efa9f8b..2ff7acfbd0 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -109,8 +109,8 @@ class TestMaxBodyMiddleware:
         assert "too large" in r.json()["detail"].lower()
 
     def test_chunked_upload_over_cap_rejected(self, main_module):
-        # Regression: declared-Content-Length-only check could be bypassed
-        # by chunked transfer-encoding.
+        # Regression: declared-Content-Length-only check could be bypassed by
+        # chunked transfer-encoding.
         app = _make_protected_app(1024, main_module)
         c = TestClient(app)
 
@@ -282,13 +282,13 @@ class TestSecurityHeadersMiddleware:
 
     def test_img_src_allows_google_favicons(self, main_module):
         # sources.tsx fetches https://www.google.com/s2/favicons?... ; without
-        # this allowlist entry citation favicons fall back to gray initials.
+        # this allowlist entry, citation favicons fall back to gray initials.
         csp = main_module._build_csp()
         img_directive = next(
             chunk.strip() for chunk in csp.split(";") if chunk.strip().startswith("img-src ")
         )
-        # Tokenise and compare with `==` so CodeQL's URL-substring rule does
-        # not read directive-string `in` membership as URL sanitisation.
+        # Tokenise and compare with `==` so CodeQL's URL-substring rule
+        # doesn't read directive-string `in` membership as URL sanitisation.
         img_sources = img_directive.split()
         assert any(src == "https://www.google.com" for src in img_sources)
         # Pre-existing favicon CDNs stay allowed.
@@ -332,9 +332,9 @@ def health_app(tmp_path, monkeypatch):
 
 
 class TestHealthAuthGate:
-    # Launcher / frontend bootstrap fields are available unauth so the Tauri
-    # watchdog can re-adopt a sibling backend and the SPA can detect chat-only
-    # mode before any token exists. Version / device_type still require a bearer.
+    # Launcher / frontend bootstrap fields are unauth so the Tauri watchdog can
+    # re-adopt a sibling backend and the SPA can detect chat-only mode before
+    # any token exists. Version / device_type still require a bearer.
     LAUNCHER_BITS = (
         "service",
         "studio_root_id",
@@ -361,7 +361,7 @@ class TestHealthAuthGate:
             assert forbidden not in body
 
     def test_invalid_bearer_returns_launcher_bits_only(self, health_app):
-        # Regression: calling the async dep without await made any Bearer header pass.
+        # Regression: calling the async dep without await let any Bearer header pass.
         c = TestClient(health_app)
         r = c.get(
             "/api/health",
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 49afab048d..9871965ce8 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -159,10 +159,9 @@ def test_mlx_inference_vlm_lora_uses_unsloth_loader_without_native_adapter_rewri
     assert isinstance(backend._tokenizer, _DummyTokenizer)
 
 
-# Regression: MLXInferenceBackend.generate_chat_response must accept the
-# four template kwargs (tools / enable_thinking / reasoning_effort /
-# preserve_thinking) so the route layer can forward what the user
-# toggled in the UI. The previous signature raised
+# Regression: generate_chat_response must accept the four template kwargs
+# (tools / enable_thinking / reasoning_effort / preserve_thinking) so the route
+# layer can forward UI toggles. The old signature raised
 # "got an unexpected keyword argument 'tools'" on Mac.
 
 
@@ -184,8 +183,8 @@ def test_mlx_generate_chat_response_accepts_template_kwargs():
 
 
 def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
-    """The Mac text path must route through apply_chat_template_for_
-    generation so reasoning / tool kwargs reach the tokenizer."""
+    """Mac text path must route through apply_chat_template_for_generation so
+    reasoning / tool kwargs reach the tokenizer."""
     _install_fake_mlx(monkeypatch)
     from core.inference.mlx_inference import MLXInferenceBackend
 
@@ -203,9 +202,8 @@ def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
         raising = True,
     )
 
-    # mlx_lm.stream_generate yields response objects with .token; make a
-    # one-token generator so _generate_text returns without touching the
-    # real stack.
+    # mlx_lm.stream_generate yields response objects with .token; use a
+    # one-token generator so _generate_text returns without the real stack.
     import types as _types
 
     mlx_lm_pkg = _types.ModuleType("mlx_lm")
@@ -250,7 +248,7 @@ def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):
         )
     )
     assert out == ["hi"]
-    # The kwargs the user toggled must reach the chat-template helper.
+    # The toggled kwargs must reach the chat-template helper.
     assert captured["kwargs"]["tools"] == [{"function": {"name": "web_search"}}]
     assert captured["kwargs"]["enable_thinking"] is True
     assert captured["kwargs"]["reasoning_effort"] == "medium"
diff --git a/studio/backend/tests/test_multimodal_document.py b/studio/backend/tests/test_multimodal_document.py
index b2986f2c3a..29926299ce 100644
--- a/studio/backend/tests/test_multimodal_document.py
+++ b/studio/backend/tests/test_multimodal_document.py
@@ -3,17 +3,16 @@
 
 """Tests for PDF / document attachment translation on external providers.
 
-Studio introduces a normalised `input_document` content part on
-ChatCompletionRequest so the frontend doesn't have to know the
-per-provider attachment shape:
+Studio adds a normalised `input_document` content part on
+ChatCompletionRequest so the frontend needn't know the per-provider
+attachment shape:
 
-- Anthropic: translates to `{type:"document", source:{type:"base64"|"url", ...}}`
-- OpenAI Responses: translates to `{type:"input_file", file_data|file_url, filename?}`
+- Anthropic: `{type:"document", source:{type:"base64"|"url", ...}}`
+- OpenAI Responses: `{type:"input_file", file_data|file_url, filename?}`
 
-These tests pin the translation shape on both paths for base64 data
-URIs and remote URLs, with optional filename metadata, and confirm
-unknown / empty document parts are dropped without breaking the
-request.
+Pins the translation shape on both paths for base64 data URIs and remote
+URLs (with optional filename), and confirms unknown / empty document
+parts are dropped without breaking the request.
 """
 
 import asyncio
@@ -87,9 +86,8 @@ _PDF_DATA_URI = f"data:application/pdf;base64,{_TINY_PDF_B64}"
 
 def _strip_cache(p: dict) -> dict:
     # Studio's prompt-cache wiring attaches cache_control:{type:ephemeral}
-    # to the tail block of the last user message; strip it before
-    # comparing the document core fields so this test stays focused
-    # on the translation, not the caching layer.
+    # to the tail block of the last user message; strip it so this test
+    # focuses on translation, not the caching layer.
     return {k: v for k, v in p.items() if k != "cache_control"}
 
 
@@ -117,7 +115,7 @@ def test_anthropic_base64_pdf_becomes_document_block(monkeypatch):
     types = [p.get("type") for p in parts]
     assert "document" in types, parts
     doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
-    # citations: {enabled: true} opts into Anthropic's natural-citation
+    # citations:{enabled:true} opts into Anthropic's natural-citation
     # pipeline; without it the citations_delta handler is a no-op.
     assert doc == {
         "type": "document",
@@ -179,9 +177,9 @@ def test_anthropic_empty_document_part_is_dropped(monkeypatch):
 
 
 def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):
-    # If the ONLY part in a user message is an unparseable input_document,
-    # the helper must NOT append an empty-content message to the outbound
-    # body (Anthropic 400s on "at least one block is required").
+    # If the ONLY part is an unparseable input_document, the helper must
+    # NOT append an empty-content message (Anthropic 400s on "at least
+    # one block is required").
     captured = _capture(
         monkeypatch,
         provider = "anthropic",
@@ -192,14 +190,14 @@ def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):
         ],
     )
     msgs = captured["body"]["messages"]
-    # The empty-content message must be skipped; only the second remains.
+    # Empty-content message skipped; only the second remains.
     assert len(msgs) == 1, msgs
 
 
 def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):
-    # Codex P2: `data:application/pdf;base64,` with no payload (or
-    # whitespace-only) would create an empty `source.data` that
-    # Anthropic 400s on. Must be filtered before the wire.
+    # Codex P2: `data:application/pdf;base64,` with no (or whitespace-only)
+    # payload would make an empty `source.data` that Anthropic 400s on.
+    # Must be filtered before the wire.
     captured = _capture(
         monkeypatch,
         provider = "anthropic",
@@ -228,12 +226,11 @@ def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):
 
 
 def test_anthropic_empty_data_uri_falls_back_to_file_url(monkeypatch):
-    # Codex P2 follow-up: my previous fix added the empty-data-URI ->
-    # file_url fallback to the OpenAI side but missed the Anthropic
-    # side, where the empty-payload branch did `continue` and discarded
-    # an otherwise-valid file_url on the same part. Mirror the OpenAI
-    # behavior so a malformed inline payload + remote URL still
-    # attaches.
+    # Codex P2 follow-up: the empty-data-URI -> file_url fallback was on
+    # the OpenAI side but missing on Anthropic, where the empty-payload
+    # branch did `continue` and discarded a valid file_url on the same
+    # part. Mirror OpenAI so a malformed inline payload + remote URL
+    # still attaches.
     captured = _capture(
         monkeypatch,
         provider = "anthropic",
@@ -255,7 +252,7 @@ def test_anthropic_empty_data_uri_falls_back_to_file_url(monkeypatch):
     )
     parts = captured["body"]["messages"][0]["content"]
     doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
-    # base64 source MUST NOT have landed on the wire; URL source survived.
+    # base64 source MUST NOT reach the wire; URL source survives.
     assert doc == {
         "type": "document",
         "source": {"type": "url", "url": "https://example.com/doc.pdf"},
@@ -344,11 +341,10 @@ def test_openai_url_pdf_becomes_input_file(monkeypatch):
 
 
 def test_openai_empty_data_uri_falls_back_to_file_url(monkeypatch):
-    # Codex P2 follow-up: an empty `data:application/pdf;base64,`
-    # payload was being preferred over a perfectly valid `file_url`
-    # in the same part, sending `file_data=""` to OpenAI and 400ing
-    # the whole turn. The translator must treat empty data URIs as
-    # missing and recover via file_url.
+    # Codex P2 follow-up: an empty `data:application/pdf;base64,` payload
+    # was preferred over a valid `file_url` in the same part, sending
+    # `file_data=""` and 400ing the turn. The translator must treat empty
+    # data URIs as missing and recover via file_url.
     captured = _capture(
         monkeypatch,
         provider = "openai",
@@ -370,7 +366,7 @@ def test_openai_empty_data_uri_falls_back_to_file_url(monkeypatch):
     )
     parts = captured["body"]["input"][0]["content"]
     fileblk = next(p for p in parts if p.get("type") == "input_file")
-    # file_data MUST NOT be on the wire; file_url survives.
+    # file_data MUST NOT reach the wire; file_url survives.
     assert "file_data" not in fileblk, fileblk
     assert fileblk["file_url"] == "https://example.com/doc.pdf"
     assert fileblk["filename"] == "doc.pdf"
@@ -402,8 +398,8 @@ def test_openai_whitespace_only_data_uri_falls_back_to_file_url(monkeypatch):
 
 
 def test_openai_empty_data_uri_without_fallback_is_dropped(monkeypatch):
-    # If the only signal is an empty data URI (no file_url), the
-    # whole part is skipped rather than sent as `file_data=""`.
+    # Only signal is an empty data URI (no file_url): skip the whole part
+    # rather than send `file_data=""`.
     captured = _capture(
         monkeypatch,
         provider = "openai",
@@ -449,12 +445,11 @@ def test_openai_empty_document_part_is_dropped(monkeypatch):
 
 # ── Pydantic schema + builder pass-through ──────────────────────────
 #
-# The translation tests above call the external-provider client directly
-# with hand-built dicts, which bypasses BOTH ChatCompletionRequest's
-# discriminated Union AND routes/inference._build_external_messages. The
-# tests below close that gap: parse an input_document part through the
-# real request schema, run the builder, and assert the part survives to
-# the dict the client would receive.
+# The translation tests above call the client directly with hand-built
+# dicts, bypassing both ChatCompletionRequest's discriminated Union and
+# routes/inference._build_external_messages. The tests below close that
+# gap: parse an input_document part through the real schema, run the
+# builder, and assert the part survives to the dict the client receives.
 
 
 def test_chat_message_accepts_input_document_part():
@@ -482,10 +477,9 @@ def test_chat_message_accepts_input_document_part():
 
 
 def test_build_external_messages_passes_input_document_for_anthropic_and_openai():
-    # Both providers' stream helpers have explicit input_document
-    # translation logic (Anthropic -> {type:"document"}, OpenAI
-    # Responses -> {type:"input_file"}), so the part round-trips
-    # through the builder unchanged on those routes.
+    # Both providers' stream helpers translate input_document (Anthropic ->
+    # {type:"document"}, OpenAI Responses -> {type:"input_file"}), so the
+    # part round-trips through the builder unchanged on those routes.
     from models.inference import ChatMessage
     from routes.inference import _build_external_messages
 
@@ -518,10 +512,10 @@ def test_build_external_messages_passes_input_document_for_anthropic_and_openai(
 
 def test_build_external_messages_strips_input_document_for_unmapped_providers():
     # Codex P1 follow-up: gemini / mistral / kimi / openrouter / deepseek
-    # / custom go through generic /chat/completions passthrough that
-    # forwards `messages` verbatim. Handing them an `input_document`
-    # part fails the upstream validator. Builder must strip the part
-    # for every provider whose stream helper doesn't translate it.
+    # / custom use generic /chat/completions passthrough that forwards
+    # `messages` verbatim, so an `input_document` part fails the upstream
+    # validator. The builder must strip it for any provider whose stream
+    # helper doesn't translate it.
     from models.inference import ChatMessage
     from routes.inference import _build_external_messages
 
@@ -551,8 +545,8 @@ def test_build_external_messages_strips_input_document_for_unmapped_providers():
 
 
 def test_build_external_messages_strips_input_document_when_provider_type_unknown():
-    # Defensive: legacy callers that don't pass provider_type must
-    # not leak the part to an unknown destination.
+    # Defensive: legacy callers without provider_type must not leak the
+    # part to an unknown destination.
     from models.inference import ChatMessage
     from routes.inference import _build_external_messages
 
diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.py
index 01c05d3ec6..0290bb1308 100644
--- a/studio/backend/tests/test_native_context_length.py
+++ b/studio/backend/tests/test_native_context_length.py
@@ -3,11 +3,11 @@
 
 """Tests for the native_context_length feature (PR #4746).
 
-Verifies that the new `native_context_length` property on LlamaCppBackend
-and the corresponding Pydantic model fields work correctly.  The raw GGUF
-`_context_length` must never be overwritten by VRAM-capping logic.
+Verifies the `native_context_length` property on LlamaCppBackend and the
+matching Pydantic fields. The raw GGUF `_context_length` must never be
+overwritten by VRAM-capping logic.
 
-Requires no GPU, network, or external libraries beyond pytest and pydantic.
+Needs no GPU, network, or libraries beyond pytest and pydantic.
 """
 
 import io
@@ -21,8 +21,8 @@ from unittest.mock import patch
 import pytest
 
 # ---------------------------------------------------------------------------
-# Stub heavy / unavailable external dependencies before importing the
-# module under test.  Same pattern as test_kv_cache_estimation.py.
+# Stub heavy / unavailable deps before importing the module under test.
+# Same pattern as test_kv_cache_estimation.py.
 # ---------------------------------------------------------------------------
 
 _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -38,7 +38,7 @@ sys.modules.setdefault("loggers", _loggers_stub)
 _structlog_stub = _types.ModuleType("structlog")
 sys.modules.setdefault("structlog", _structlog_stub)
 
-# httpx -- stub only the names referenced at import / class-definition time
+# httpx -- stub only names referenced at import / class-definition time
 _httpx_stub = _types.ModuleType("httpx")
 for _exc_name in (
     "ConnectError",
@@ -227,7 +227,7 @@ class TestContextValueSeparation:
     def test_all_equal_when_uncapped(self, backend):
         """All three equal when no VRAM constraint."""
         backend._context_length = 8192
-        # No effective or max set -- properties fall back to _context_length
+        # No effective/max set -- properties fall back to _context_length.
         assert backend.native_context_length == 8192
         assert backend.max_context_length == 8192
         assert backend.context_length == 8192
@@ -241,16 +241,16 @@ class TestContextValueSeparation:
         backend._embedding_length = 4096
         original = backend._context_length
 
-        # Simulate a very small VRAM budget that forces capping
+        # Tiny VRAM budget forces capping.
         result = backend._fit_context_to_vram(
             requested_ctx = 131072,
             available_mib = 512,  # very small
             model_size_bytes = 0,
         )
-        # _fit_context_to_vram returns the capped value, not modifying _context_length
+        # Returns the capped value without modifying _context_length.
         assert backend._context_length == original
         assert backend.native_context_length == original
-        # The returned capped value should be <= requested
+        # Capped value must be <= requested.
         assert result <= 131072
 
     def test_native_gt_context_when_capped(self, backend):
@@ -370,7 +370,7 @@ class TestRouteCompleteness:
             start = self._source.find(f"{class_name}(", idx)
             if start == -1:
                 break
-            # Find matching closing paren (simple depth counter)
+            # Find the matching closing paren via a depth counter.
             depth = 0
             end = start
             for i, ch in enumerate(self._source[start:], start):
@@ -401,8 +401,8 @@ class TestRouteCompleteness:
         """Non-GGUF LoadResponse blocks do not set native_context_length (defaults to None)."""
         blocks = self._find_construction_blocks("LoadResponse")
         non_gguf = [b for b in blocks if "is_gguf = True" not in b and "is_gguf=True" not in b]
-        # Non-GGUF paths should not reference native_context_length
-        # (Pydantic defaults it to None, so not setting it is correct)
+        # Non-GGUF paths shouldn't reference native_context_length
+        # (Pydantic defaults it to None, so omitting it is correct).
         for block in non_gguf:
             assert (
                 "native_context_length" not in block
@@ -476,7 +476,7 @@ class TestNativeContextEdgeCases:
         backend._read_gguf_metadata(path)
         assert backend.native_context_length == 131072
 
-        # Simulate VRAM capping by setting effective and max
+        # Simulate VRAM capping via effective and max.
         backend._effective_context_length = 16384
         backend._max_context_length = 32768
         assert backend.native_context_length == 131072
diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.py
index df7652a590..2856bb7cad 100644
--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py
+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py
@@ -3,27 +3,25 @@
 
 """Regression tests for the offline GGUF cache fallback path (#5505).
 
-Three failure modes hit users when ``huggingface.co`` is unreachable
-but the requested GGUF repo is fully cached locally:
+Three failure modes hit users when ``huggingface.co`` is unreachable but the
+requested GGUF repo is fully cached locally:
 
-* ``list_gguf_variants`` raised through ``HTTPException(500)`` so the
-  variant dropdown sat empty.
-* ``detect_gguf_model_remote`` returned ``None`` so a GGUF-only repo
-  was misrouted into the transformers/Unsloth backend (on macOS this
-  surfaced as a hardware error).
-* ``_download_gguf`` fell back to a synthetic ``{repo}-{variant}.gguf``
-  name that did not exist in cache when the in-repo filename did not
-  echo the repo name (e.g. ``unsloth/Qwen3.6-27B-MTP-GGUF`` ships
+* ``list_gguf_variants`` raised ``HTTPException(500)`` so the variant
+  dropdown sat empty.
+* ``detect_gguf_model_remote`` returned ``None`` so a GGUF-only repo was
+  misrouted into the transformers/Unsloth backend (a hardware error on macOS).
+* ``_download_gguf`` fell back to a synthetic ``{repo}-{variant}.gguf`` name
+  absent from cache when the in-repo filename did not echo the repo name
+  (e.g. ``unsloth/Qwen3.6-27B-MTP-GGUF`` ships
   ``Qwen3.6-27B-UD-Q4_K_XL.gguf`` with no ``MTP`` token).
 
-Two follow-up regressions covered here:
+Two follow-up regressions also covered:
 
-* P1 #1: the cache-side variant filter must match the snapshot-relative
-  path, not just the basename, so subdir layouts like
-  ``BF16/foo.gguf`` are findable.
-* P1 #2: the DNS auto-detect must scope ``HF_HUB_OFFLINE`` to one load
-  via try/finally so a transient resolver hiccup cannot lock the
-  long-lived ``LlamaCppBackend`` singleton offline forever.
+* P1 #1: the cache-side variant filter must match the snapshot-relative path,
+  not just the basename, so subdir layouts like ``BF16/foo.gguf`` are findable.
+* P1 #2: the DNS auto-detect must scope ``HF_HUB_OFFLINE`` to one load via
+  try/finally so a transient resolver hiccup cannot lock the long-lived
+  ``LlamaCppBackend`` singleton offline forever.
 
 No GPU, no network, no subprocess. Linux, macOS, Windows compatible.
 """
@@ -44,8 +42,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
     sys.path.insert(0, _BACKEND_DIR)
 
-# Stub heavy/unavailable external deps before importing the modules
-# under test (same pattern as other studio backend tests).
+# Stub heavy/unavailable external deps before importing the modules under
+# test (same pattern as other studio backend tests).
 _loggers_stub = _types.ModuleType("loggers")
 _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
 sys.modules.setdefault("loggers", _loggers_stub)
@@ -182,7 +180,7 @@ class TestIterHfCacheSnapshots:
 
     def test_repo_id_match_is_case_insensitive(self, hf_cache):
         _build_cache(hf_cache, "unsloth/Foo-GGUF", {"Foo-Q4_K_M.gguf": 1})
-        # Lookup with a different casing of the org/name still resolves
+        # Lookup with different org/name casing still resolves
         out = list(_iter_hf_cache_snapshots("UNSLOTH/foo-gguf"))
         assert len(out) == 1
 
@@ -272,9 +270,9 @@ class TestDetectGgufFromCache:
 
     def test_subdir_only_quant_resolves(self, hf_cache):
         """P1 #1 regression: ``BF16/foo.gguf`` (quant only in directory).
-        Before the fix, the offline cache scan matched on basename and
-        missed this layout, falling through to the synthetic
-        ``{repo}-{variant}.gguf`` heuristic."""
+        The pre-fix cache scan matched on basename, missing this layout
+        and falling through to the synthetic ``{repo}-{variant}.gguf``
+        heuristic."""
         _build_cache(
             hf_cache,
             "unsloth/gpt-oss-20b-BF16",
@@ -316,7 +314,7 @@ class TestDetectGgufModelRemoteOffline:
         assert out == "a-Q4_K_M.gguf"
 
     def test_repository_not_found_does_not_consult_cache(self, hf_cache, clean_offline_env):
-        # Cache has a file but the API explicitly says repo is gone.
+        # Cache has a file but the API says the repo is gone.
         _build_cache(hf_cache, "unsloth/a", {"a-Q4_K_M.gguf": 1})
 
         class RepositoryNotFoundError(Exception):
@@ -442,9 +440,9 @@ class TestHfOfflineIfDnsDead:
 
 
 class TestExtractQuantLabelSubdir:
-    """``_extract_quant_label`` must consider the parent directories when
-    the basename has no quant token. Subdir layouts like ``BF16/foo.gguf``
-    are documented in this codebase and surface through the cache scan."""
+    """``_extract_quant_label`` must consider parent directories when the
+    basename has no quant token. Subdir layouts like ``BF16/foo.gguf`` are
+    documented here and surface through the cache scan."""
 
     def test_quant_in_basename_unchanged(self):
         assert _extract_quant_label("BF16/foo-BF16.gguf") == "BF16"
@@ -457,17 +455,15 @@ class TestExtractQuantLabelSubdir:
         assert _extract_quant_label("UD-Q4_K_XL/weight.gguf") == "UD-Q4_K_XL"
 
     def test_deeper_nesting_picks_nearest_quant_dir(self):
-        # When multiple parent segments could match, prefer the one closest
-        # to the file (innermost). This matches how repos like
-        # ``models/MXFP4_MOE/foo.gguf`` are laid out.
+        # When multiple parent segments match, prefer the innermost (closest
+        # to the file), matching repos like ``models/MXFP4_MOE/foo.gguf``.
         assert _extract_quant_label("models/MXFP4_MOE/foo.gguf") == "MXFP4_MOE"
 
 
 class TestDownloadMmprojOfflineCacheFallback:
-    """``LlamaCppBackend._download_mmproj`` must resolve cached mmproj
-    GGUFs offline, same shape as ``_download_gguf``. Without this the
-    offline vision GGUF load path returns ``None`` even when the mmproj
-    is present in cache."""
+    """``LlamaCppBackend._download_mmproj`` must resolve cached mmproj GGUFs
+    offline, same shape as ``_download_gguf``. Without this the offline vision
+    GGUF load path returns ``None`` even when the mmproj is cached."""
 
     def test_cache_lookup_returns_cached_mmproj_when_list_repo_files_fails(self, hf_cache):
         _build_cache(
@@ -559,7 +555,7 @@ class TestDownloadMmprojOfflineCacheFallback:
 
 class TestListLocalGgufVariantsSubdir:
     """Subdir layouts like ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf`` must
-    produce distinct quant labels, not collapse on basename."""
+    yield distinct quant labels, not collapse on basename."""
 
     def test_two_subdir_variants_do_not_collapse(self, tmp_path):
         from utils.models.model_config import list_local_gguf_variants
@@ -642,8 +638,8 @@ class TestListGgufVariantsPermanentErrors:
 
 
 class TestDetectGgufFromCacheExcludesMmproj:
-    """A partial cache with only a vision projector must not route the
-    projector as the main model."""
+    """A partial cache with only a vision projector must not route it as
+    the main model."""
 
     def test_mmproj_only_returns_none(self, hf_cache):
         from utils.models.model_config import _detect_gguf_from_hf_cache
@@ -672,7 +668,7 @@ class TestDetectGgufFromCacheExcludesMmproj:
 
 class TestProbeDnsDeadNoGlobalTimeoutMutation:
     """``_probe_dns_dead`` must not change ``socket.setdefaulttimeout``
-    process-wide -- concurrent sockets without explicit timeout would
+    process-wide -- concurrent sockets without an explicit timeout would
     inherit it for the probe window."""
 
     def test_default_timeout_unchanged_when_dns_up(self, monkeypatch):
@@ -694,7 +690,7 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:
         try:
             _probe_dns_dead("example.invalid", timeout = 0.5)
         finally:
-            # Restore exact state regardless of any test-side mutation.
+            # Restore exact state regardless of test-side mutation.
             original_set(prev)
 
         assert set_calls == [], (
@@ -717,8 +713,8 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:
 
 class TestWaitForHealthRetriesOnReadError:
     """A TCP RST mid-read while llama-server is still binding the port
-    (Windows: WinError 10054) must not abort the health-poll loop --
-    that masks a legitimate 'still warming up' state as a fatal load."""
+    (Windows: WinError 10054) must not abort the health-poll loop -- that
+    masks a legitimate 'still warming up' state as a fatal load."""
 
     def test_read_error_then_success(self, monkeypatch):
         import httpx
diff --git a/studio/backend/tests/test_offline_inference_parent.py b/studio/backend/tests/test_offline_inference_parent.py
index fbb0aa8999..71331220d6 100644
--- a/studio/backend/tests/test_offline_inference_parent.py
+++ b/studio/backend/tests/test_offline_inference_parent.py
@@ -140,7 +140,7 @@ class TestLoraDetectOffline:
         monkeypatch.setenv("HF_HUB_OFFLINE", "1")
 
         # Studio catches Exception broadly; pin that the call still happens
-        # (so cached LoRAs aren't missed) and returns fast via mock.
+        # (so cached LoRAs aren't missed) and returns fast via the mock.
         class _OfflineModeIsEnabled(Exception):
             pass
 
diff --git a/studio/backend/tests/test_openai_citation_markers.py b/studio/backend/tests/test_openai_citation_markers.py
index ccc17be329..dafcffc8bd 100644
--- a/studio/backend/tests/test_openai_citation_markers.py
+++ b/studio/backend/tests/test_openai_citation_markers.py
@@ -4,8 +4,8 @@
 """Tests for the OpenAI Responses-API citation marker rewriter.
 
 The stream interleaves text deltas with ``\\ue200cite\\ue202SOURCE_ID\\ue201``
-markers. The rewriter resolves each to `[N](URL)` when the annotation has
-arrived and drops it otherwise; the URL list still flows to Sources via
+markers. The rewriter resolves each to `[N](URL)` once the annotation arrives
+and drops it otherwise; the URL list still flows to Sources via
 `_record_url_citation`.
 
 Reference: https://developers.openai.com/api/docs/guides/citation-formatting
@@ -58,8 +58,7 @@ def test_marker_rewritten_to_link_when_annotation_known():
 def test_unknown_source_marker_dropped_silently():
     text = f"Foo {_marker('turn9view9')} bar."
     out = _replace_openai_citation_markers(text, [])
-    # Marker stripped, no garbled "E202" glyph leaks through, and the
-    # surrounding text stays intact.
+    # Marker stripped, no garbled "E202" glyph leaks, surrounding text intact.
     assert not _has_marker_codepoints(out)
     assert "E202" not in out
     assert "turn9view9" not in out
@@ -67,8 +66,8 @@ def test_unknown_source_marker_dropped_silently():
 
 
 def test_multiple_concatenated_markers_resolved_in_order():
-    """Real-world wire shape: a string of markers butted up against each other
-    after a sentence, as in the user-reported bug."""
+    """Real-world wire shape: markers butted together after a sentence,
+    as in the user-reported bug."""
     markers = "".join(_marker(f"turn{i}view{j}") for i, j in [(1, 0), (1, 1), (3, 0)])
     text = f"All animals ranked. {markers}"
     citations = [
@@ -150,8 +149,8 @@ def test_multiple_source_id_aliases_resolve_to_same_url():
         },
     ]
     out = _replace_openai_citation_markers(text, citations)
-    # All three aliases collapse onto citation [1] -- the URL is the
-    # same so it would be misleading to show three different numbers.
+    # All three aliases collapse onto citation [1] -- same URL, so showing
+    # three different numbers would mislead.
     assert out.count("[[1]](https://example.com/paris)") == 3
     assert not _has_marker_codepoints(out)
 
@@ -176,7 +175,7 @@ def test_source_ids_list_and_legacy_source_id_both_resolve():
 
 # ---------------------------------------------------------------------------
 # _rewrite_citation_markers_partial: deferred-annotation tests. OpenAI emits
-# url_citation annotations on a subsequent SSE event; this helper reports
+# url_citation annotations on a later SSE event; this helper reports
 # `has_unresolved` so the stream loop defers emission. See PR #5713 audit.
 # ---------------------------------------------------------------------------
 
@@ -216,15 +215,15 @@ def test_partial_resolves_after_late_annotation():
 def test_partial_multi_source_partial_resolution_keeps_marker_pending():
     """Any unresolved token in a multi-source marker leaves the whole marker
     verbatim with ``unresolved`` True; defer until every id resolves or
-    end-of-stream forces a flush (dropping unresolved tokens then)."""
+    end-of-stream forces a flush (dropping unresolved tokens)."""
     cite = f"{CITE_START}cite{CITE_DELIM}known{CITE_DELIM}locator{CITE_STOP}"
     text = f"Pre {cite} post."
     citations = [{"source_id": "known", "url": "https://example.com/y"}]
     out, unresolved = _rewrite_citation_markers_partial(text, citations)
     assert unresolved is True
     assert cite in out
-    # End-of-stream force flush: drop the unresolved token, keep the
-    # resolved link. The streamer routes pending segments through
+    # End-of-stream force flush: drop the unresolved token, keep the resolved
+    # link. The streamer routes pending segments through
     # `_replace_openai_citation_markers` at force=True for this.
     forced = _replace_openai_citation_markers(out, citations)
     assert "[[1]](https://example.com/y)" in forced
diff --git a/studio/backend/tests/test_openai_citation_markers_edge.py b/studio/backend/tests/test_openai_citation_markers_edge.py
index e8d0be6246..f44975ce33 100644
--- a/studio/backend/tests/test_openai_citation_markers_edge.py
+++ b/studio/backend/tests/test_openai_citation_markers_edge.py
@@ -13,8 +13,8 @@ Reference: https://developers.openai.com/api/docs/guides/citation-formatting
 import importlib
 
 
-# Streaming integration is exercised by ``_simulate_delta_stream`` further
-# down, mirroring the head/buffer/flush dance from ``_stream_openai_responses``.
+# Streaming is exercised by ``_simulate_delta_stream`` below, mirroring the
+# head/buffer/flush dance from ``_stream_openai_responses``.
 _module = importlib.import_module("core.inference.external_provider")
 _replace_openai_citation_markers = _module._replace_openai_citation_markers
 _split_pending_citation_tail = _module._split_pending_citation_tail
@@ -27,7 +27,7 @@ CITE_DELIM = ""
 
 def _marker(*source_ids: str, locator: str | None = None) -> str:
     """Build a ``\\ue200cite\\ue202[\\ue202...][\\ue202]\\ue201``
-    marker. Accepts one or many ``source_ids`` plus an optional ``locator``."""
+    marker from one or more ``source_ids`` plus an optional ``locator``."""
     payload = f"{CITE_START}cite{CITE_DELIM}" + CITE_DELIM.join(source_ids)
     if locator:
         payload = f"{payload}{CITE_DELIM}{locator}"
@@ -39,7 +39,7 @@ def _no_private_use(text: str) -> bool:
 
 
 # Harness mirroring the head/pending-tail/flush dance in
-# `_stream_openai_responses`, so streaming tests skip the httpx mock.
+# `_stream_openai_responses` so streaming tests skip the httpx mock.
 def _simulate_delta_stream(
     deltas: list[str],
     citations: list[dict],
@@ -56,8 +56,8 @@ def _simulate_delta_stream(
             if head:
                 emitted.append(head)
     if flush and pending:
-        # Mirror `_flush_pending_marker_tail`: drop the tail entirely if no
-        # closing stop byte arrived; the literal ``cite`` would leak otherwise.
+        # Mirror `_flush_pending_marker_tail`: drop the tail if no closing stop
+        # byte arrived; the literal ``cite`` would leak otherwise.
         if CITE_STOP not in pending:
             rendered = ""
         else:
@@ -79,7 +79,7 @@ def _simulate_delta_stream(
 
 def test_multi_source_marker_all_resolve():
     """\\ue200cite\\ue202id1\\ue202id2\\ue202id3\\ue201 expands to three links
-    when every id is known. Earlier regex captured only id1 and dropped id2/id3."""
+    when every id is known. Earlier regex captured only id1."""
     text = f"All three: {_marker('id1', 'id2', 'id3')}"
     citations = [
         {"source_id": "id1", "url": "https://example.com/1"},
@@ -136,14 +136,14 @@ def test_marker_with_range_locator():
 
 
 def test_marker_split_in_source_id():
-    """Delta-1 ends mid-source-id (``\\ue200cite\\ue202tu``), delta-2 starts
-    with the rest (``rn0view0\\ue201``). The buffer stitches the halves
-    back together so they resolve to one link instead of leaking."""
+    """Delta-1 ends mid-source-id (``\\ue200cite\\ue202tu``), delta-2 has the
+    rest (``rn0view0\\ue201``). The buffer stitches the halves so they resolve
+    to one link instead of leaking."""
     full = f"See {_marker('turn0view0')} now."
     # Cut right after the second delim + "tu" inside the source id.
     cut = full.index("tu", full.index(CITE_START)) + len("tu")
     d1, d2 = full[:cut], full[cut:]
-    # Sanity check: delta-1 actually contains a partial marker.
+    # Sanity: delta-1 contains a partial marker.
     assert CITE_START in d1 and CITE_STOP not in d1
     assert CITE_STOP in d2
     citations = [{"source_id": "turn0view0", "url": "https://x"}]
@@ -153,8 +153,8 @@ def test_marker_split_in_source_id():
 
 
 def test_marker_split_at_start_byte():
-    """Split exactly after the opening ``\\ue200`` byte; the buffer must
-    hold the lone open byte until the rest arrives."""
+    """Split right after the opening ``\\ue200`` byte; the buffer must hold the
+    lone open byte until the rest arrives."""
     full = f"Text {_marker('sid')} done"
     cut = full.index(CITE_START) + 1  # right AFTER the open byte
     d1, d2 = full[:cut], full[cut:]
@@ -167,7 +167,7 @@ def test_marker_split_at_start_byte():
 def test_marker_split_across_three_deltas():
     """Worst case: marker chopped into three pieces across three deltas."""
     full = f"A {_marker('threesplit')} B"
-    # cut at two points inside the marker
+    # Cut at two points inside the marker.
     open_pos = full.index(CITE_START)
     stop_pos = full.index(CITE_STOP)
     cut1 = open_pos + 4
@@ -206,21 +206,20 @@ def test_split_marker_unknown_source_is_dropped_cleanly():
 
 
 def test_unterminated_marker_at_stream_end_dropped_on_flush():
-    """Stream ends mid-marker (e.g. response.incomplete); the tail is
-    flushed with private-use bytes stripped, no `E202` text leaks."""
+    """Stream ends mid-marker (e.g. response.incomplete); the flushed tail
+    strips private-use bytes, no `E202` text leaks."""
     deltas = ["Some text ", f"{CITE_START}citetu", "rn0view0"]  # no STOP ever
     out = _simulate_delta_stream(deltas, [], flush = True)
     assert _no_private_use(out)
     assert "E200" not in out and "E202" not in out
-    # Surrounding prose stays; we don't assert exact marker remainder.
+    # Surrounding prose stays; don't assert exact marker remainder.
     assert "Some text " in out
 
 
 def test_flush_resolves_marker_when_late_annotation_arrives():
-    """Marker in a delta, matching annotation arrives later (on
-    response.output_text.annotation.added after the final delta). The
-    rewriter reads ``all_url_citations`` LIVE at flush, so the buffered
-    marker still resolves."""
+    """Marker in a delta; the matching annotation arrives later (on
+    response.output_text.annotation.added after the final delta). The rewriter
+    reads ``all_url_citations`` LIVE at flush, so the buffered marker resolves."""
     deltas = ["Look ", f"{CITE_START}cite{CITE_DELIM}late_sid"]
     pending = ""
     citations: list[dict] = []
@@ -291,8 +290,8 @@ def test_rewriter_idempotent_on_marker_free_text():
 
 
 def test_only_marker_no_surrounding_text():
-    """A delta that is JUST a marker (no prose) still renders correctly;
-    used to leak without the empty-string short-circuit in the split helper."""
+    """A delta that is JUST a marker (no prose) renders correctly; it leaked
+    before the empty-string short-circuit in the split helper."""
     text = _marker("solo")
     citations = [{"source_id": "solo", "url": "https://solo.example"}]
     out = _replace_openai_citation_markers(text, citations)
@@ -311,15 +310,15 @@ def test_back_to_back_markers_with_no_separator():
 
 
 def test_split_helper_buffers_only_after_last_open_byte():
-    """A complete marker followed by an unterminated one: head includes
-    the complete marker, buffer holds only the trailing partial."""
+    """Complete marker followed by an unterminated one: head includes the
+    complete marker, buffer holds only the trailing partial."""
     complete = _marker("done")
     partial = f"{CITE_START}cite{CITE_DELIM}half"  # no STOP
     text = f"pre {complete} mid {partial}"
     head, tail = _split_pending_citation_tail(text)
     assert head == f"pre {complete} mid "
     assert tail == partial
-    # And the head, once rewritten, drops every private-use byte.
+    # Head, once rewritten, drops every private-use byte.
     rewritten = _replace_openai_citation_markers(head, [{"source_id": "done", "url": "https://d"}])
     assert rewritten == "pre [[1]](https://d) mid "
 
@@ -355,7 +354,7 @@ def test_unknown_marker_does_not_perturb_citation_indexing():
         {"source_id": "real_b", "url": "https://example.com/b"},
     ]
     out = _replace_openai_citation_markers(text, citations)
-    # real_a is index 1; unknown does not take a slot.
+    # real_a is index 1; unknown takes no slot.
     assert "[[1]](https://example.com/a)" in out
     assert "[[2]](https://example.com/b)" in out
     assert _no_private_use(out)
@@ -368,8 +367,8 @@ def test_unknown_marker_does_not_perturb_citation_indexing():
 
 
 def test_unterminated_marker_does_not_leak_cite_residue():
-    """Stream ends mid-marker: drop the whole tail rather than strip
-    codepoints and leave ``cite`` behind."""
+    """Stream ends mid-marker: drop the whole tail rather than strip codepoints
+    and leave ``cite`` behind."""
     half = f"Hi there {CITE_START}cite{CITE_DELIM}turn0view0"
     out = _simulate_delta_stream([half], [], flush = True)
     # Prose before the marker stays; no private-use bytes or cite residue.
diff --git a/studio/backend/tests/test_openai_code_execution.py b/studio/backend/tests/test_openai_code_execution.py
index d4f814856b..e1b66b4050 100644
--- a/studio/backend/tests/test_openai_code_execution.py
+++ b/studio/backend/tests/test_openai_code_execution.py
@@ -6,23 +6,22 @@ Unit tests for OpenAI's server-side `shell` tool translation in
 `_stream_openai_responses`.
 
 Covers:
-- Request body: ``enabled_tools=["code_execution"]`` on the OpenAI
-  cloud base_url appends ``{"type": "shell", "environment": {"type":
+- Request body: ``enabled_tools=["code_execution"]`` on the OpenAI cloud
+  base_url appends ``{"type": "shell", "environment": {"type":
   "container_auto"}}`` to ``tools``.
-- Container reuse: when ``openai_code_exec_container_id`` is provided,
-  the outgoing ``environment.type`` flips to ``"container_reference"``
-  and the id propagates.
-- Cloud guard: code_execution on a non-cloud base_url (e.g. a local
-  OpenAI-compat preset / ollama / llama.cpp / vLLM) does NOT add the
-  shell tool, preventing a guaranteed 400 from those servers.
+- Container reuse: with ``openai_code_exec_container_id``, the outgoing
+  ``environment.type`` flips to ``"container_reference"`` and the id
+  propagates.
+- Cloud guard: code_execution on a non-cloud base_url (local
+  OpenAI-compat / ollama / llama.cpp / vLLM) does NOT add the shell tool,
+  avoiding a guaranteed 400 from those servers.
 - SSE translation: a `shell_call` + `shell_call_output` pair emits one
   ``_toolEvent`` `tool_start` (`tool_name="code_execution"`,
-  `arguments.kind="bash"`) and one `tool_end` whose `result` contains
-  the joined stdout from the shell_call_output entries.
-- Container surfacing: container_id captured from
+  `arguments.kind="bash"`) and one `tool_end` whose `result` is the
+  joined stdout from the shell_call_output entries.
+- Container surfacing: container_id from
   `response.completed.container_id` is emitted as a synthetic
-  `container_ready` `_toolEvent` (only when it differs from the
-  inbound id).
+  `container_ready` `_toolEvent` (only when it differs from the inbound id).
 - Stale-container handling: 400 with "container expired" body emits a
   `container_invalidated` event before propagating the error.
 """
@@ -192,8 +191,8 @@ def test_shell_tool_refused_for_non_cloud_base_url(monkeypatch):
     _drive(run())
 
     tools = captured["body"].get("tools") or []
-    # Shell tool must NOT leak to local OpenAI-compat servers — those
-    # 400 on the unknown tool type.
+    # Shell tool must NOT leak to local OpenAI-compat servers — they 400
+    # on the unknown tool type.
     assert all(t.get("type") != "shell" for t in tools)
 
 
@@ -266,10 +265,9 @@ def test_shell_call_emits_tool_start_and_end(monkeypatch):
     assert len(ends) == 1
     assert starts[0]["tool_name"] == "code_execution"
     assert starts[0]["tool_call_id"] == "scall_1"
-    # `_server_tool: True` is the synthetic-builtin marker the
-    # backend stamps onto every provider-side tool_start so the
-    # frontend serializer can distinguish hosted tools from
-    # user-declared functions on history replay.
+    # `_server_tool: True` marks a synthetic builtin: stamped onto every
+    # provider-side tool_start so the frontend serializer can tell hosted
+    # tools from user-declared functions on history replay.
     assert starts[0]["arguments"] == {"kind": "bash", "command": "ls -la", "_server_tool": True}
     assert ends[0]["tool_call_id"] == "scall_1"
     assert "total 24" in ends[0]["result"]
@@ -395,21 +393,21 @@ def test_stale_container_emits_invalidated(monkeypatch):
 def test_expired_container_triggers_transparent_retry(monkeypatch):
     """When OpenAI 400s with 'Container is expired' on a request that
     carried container_reference, the streamer retries once with the
-    container field stripped. The user never sees an error line — only
-    container_invalidated, then the normal stream from the retry.
+    container field stripped. The user sees only container_invalidated,
+    then the normal stream from the retry — never an error line.
     """
     calls: list[dict] = []
 
     def handler(request: httpx.Request) -> httpx.Response:
         body = json.loads(request.content.decode("utf-8"))
         calls.append(body)
-        # Find the shell tool entry to inspect environment.type.
+        # Inspect the shell tool's environment.type.
         shell_env_type = None
         for tool in body.get("tools", []) or []:
             if tool.get("type") == "shell":
                 shell_env_type = tool.get("environment", {}).get("type")
                 break
-        # First call carries container_reference -> 400 expired.
+        # First call has container_reference -> 400 expired.
         # Retry omits container -> normal SSE stream.
         if shell_env_type == "container_reference":
             return httpx.Response(
@@ -424,8 +422,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
                 ).encode("utf-8"),
                 headers = {"content-type": "application/json"},
             )
-        # Successful retry: minimal SSE — a completed response with a
-        # fresh container_id so container_ready latches.
+        # Successful retry: minimal SSE — completed response with a fresh
+        # container_id so container_ready latches.
         sse = _openai_sse(
             [
                 {
@@ -461,8 +459,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
     lines = _drive(run())
     events = _tool_events(lines)
 
-    # Two outbound HTTP calls were made: the expired-container attempt
-    # then the retry without the container field.
+    # Two outbound calls: the expired-container attempt, then the retry
+    # without the container field.
     assert len(calls) == 2
     shell_types = []
     for body in calls:
@@ -471,14 +469,14 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
                 shell_types.append(tool.get("environment", {}).get("type"))
     assert shell_types == ["container_reference", "container_auto"]
 
-    # container_invalidated emitted (frontend will null its stored id).
+    # container_invalidated emitted (frontend nulls its stored id).
     assert any(e.get("type") == "container_invalidated" for e in events)
     # container_ready emitted from the retry stream with the fresh id.
     assert any(
         e.get("type") == "container_ready" and e.get("container_id") == "cntr_fresh_111"
         for e in events
     )
-    # CRUCIALLY: no SSE error line surfaced to the chat — only completion.
+    # CRUCIALLY: no SSE error line surfaced to the chat.
     error_lines = [
         line
         for line in lines
@@ -488,8 +486,8 @@ def test_expired_container_triggers_transparent_retry(monkeypatch):
 
 
 def test_expired_container_retries_only_once(monkeypatch):
-    """If the retry ALSO fails (any 4xx, expired or otherwise), the
-    error is surfaced normally — no infinite retry loop.
+    """If the retry ALSO fails (any 4xx), the error surfaces normally —
+    no infinite retry loop.
     """
     call_count = {"n": 0}
 
@@ -528,8 +526,7 @@ def test_expired_container_retries_only_once(monkeypatch):
 
     lines = _drive(run())
 
-    # Exactly two calls (first + one retry). Third would mean an
-    # infinite loop.
+    # Exactly two calls (first + one retry); a third would be a loop.
     assert call_count["n"] == 2
     # The second failure surfaces normally as an error SSE line.
     error_lines = [line for line in lines if '"error"' in line and "_toolEvent" not in line]
diff --git a/studio/backend/tests/test_openai_compaction.py b/studio/backend/tests/test_openai_compaction.py
index f0599952c6..c7de0a9aed 100644
--- a/studio/backend/tests/test_openai_compaction.py
+++ b/studio/backend/tests/test_openai_compaction.py
@@ -4,14 +4,13 @@
 """Unit tests for OpenAI Responses API context_management wiring.
 
 OpenAI's Responses API supports server-side compaction via
-``context_management: [{type:"compaction", compact_threshold:N}]``.
-There is no beta header and no dated version pin; the threshold is
-silently accepted and the API runs the compaction step when the
-rendered prompt crosses it.
+``context_management: [{type:"compaction", compact_threshold:N}]``. No
+beta header, no dated version pin; the threshold is silently accepted and
+compaction runs when the rendered prompt crosses it.
 
-These tests pin: the body shape when threshold is set on cloud OpenAI,
-the silent no-op when the base URL is non-cloud, and the
-omitted-threshold pass-through.
+These pin: the body shape when threshold is set on cloud OpenAI, the
+silent no-op on non-cloud base URLs, and the omitted-threshold
+pass-through.
 """
 
 import asyncio
@@ -32,8 +31,7 @@ def _capture(monkeypatch, *, base_url: str, threshold) -> dict:
 
     def handler(request: httpx.Request) -> httpx.Response:
         captured["body"] = json.loads(request.content.decode("utf-8"))
-        # Send an empty Responses-shaped SSE stream so the helper exits
-        # cleanly.
+        # Empty Responses-shaped SSE stream so the helper exits cleanly.
         return httpx.Response(
             200,
             content = (
@@ -88,8 +86,8 @@ def test_cloud_openai_sets_compaction_block(monkeypatch):
 
 
 def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
-    # Studio doesn't clamp the OpenAI side -- the API accepts whatever
-    # the caller sends, so a small probe like 60k still goes through.
+    # Studio doesn't clamp the OpenAI side -- the API accepts whatever the
+    # caller sends, so a small probe like 60k still goes through.
     captured = _capture(
         monkeypatch,
         base_url = "https://api.openai.com/v1",
@@ -105,8 +103,8 @@ def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
 
 def test_non_cloud_base_silently_drops_compaction(monkeypatch):
     # ollama / llama.cpp / "custom" presets collapse to provider="openai"
-    # but don't implement context_management. Sending the field would
-    # 400 those servers, so it must NOT appear on the wire.
+    # but lack context_management. Sending the field would 400 them, so it
+    # must NOT appear on the wire.
     captured = _capture(
         monkeypatch,
         base_url = "http://127.0.0.1:11434/v1",
@@ -120,9 +118,9 @@ def test_non_cloud_base_silently_drops_compaction(monkeypatch):
 
 def test_azure_openai_base_url_carries_compaction_block(monkeypatch):
     # Azure OpenAI Foundry exposes the same /v1/responses extensions
-    # (context_management, prompt_cache_retention, container shell)
-    # under a *.openai.azure.com base URL. Treat it as cloud so the
-    # compaction field actually reaches the API.
+    # (context_management, prompt_cache_retention, container shell) under
+    # a *.openai.azure.com base URL. Treat it as cloud so the compaction
+    # field reaches the API.
     captured = _capture(
         monkeypatch,
         base_url = "https://my-resource.openai.azure.com/openai/v1",
@@ -132,14 +130,14 @@ def test_azure_openai_base_url_carries_compaction_block(monkeypatch):
         {"type": "compaction", "compact_threshold": 200_000}
     ]
     # Sibling Azure-cloud extension: prompt_cache_retention should also
-    # be set so caching works the same way on Azure deployments.
+    # be set so caching works the same on Azure deployments.
     assert captured["body"].get("prompt_cache_retention") == "24h"
 
 
 def test_azure_openai_mixed_case_base_url_matches(monkeypatch):
-    # The match is case-insensitive so URLs copy-pasted from the Azure
-    # portal (which sometimes capitalise the resource name) still get
-    # the cloud-only fields.
+    # Case-insensitive match so URLs copy-pasted from the Azure portal
+    # (which sometimes capitalise the resource name) still get the
+    # cloud-only fields.
     captured = _capture(
         monkeypatch,
         base_url = "https://My-Resource.OpenAI.Azure.Com/openai/v1",
@@ -151,12 +149,11 @@ def test_azure_openai_mixed_case_base_url_matches(monkeypatch):
 
 
 def test_cloud_gate_uses_hostname_not_substring(monkeypatch):
-    # CodeQL py/incomplete-url-substring-sanitization: an attacker who
-    # controls the configured base_url could embed `api.openai.com` or
-    # `.openai.azure.com` as part of a path or a subdomain on an
-    # arbitrary host to slip the cloud-only request body fields to a
-    # server they control. The hostname-anchored helper must reject
-    # both shapes.
+    # CodeQL py/incomplete-url-substring-sanitization: an attacker
+    # controlling base_url could embed `api.openai.com` or
+    # `.openai.azure.com` in a path or subdomain on an arbitrary host to
+    # slip cloud-only body fields to their own server. The
+    # hostname-anchored helper must reject both shapes.
     for evil in [
         "https://evil.com/api.openai.com/v1",
         "https://api.openai.com.attacker.com/v1",
@@ -188,19 +185,17 @@ def test_omitted_threshold_no_body_field(monkeypatch):
 
 
 def test_chat_completion_request_accepts_any_positive_compaction_threshold():
-    # Codex follow-up: the field is documented as a no-op for non-cloud
-    # OpenAI bases and every non-OpenAI provider, so a cross-provider
-    # schema floor would 422 perfectly valid Anthropic / ollama /
-    # llama.cpp requests that happen to carry the field. Keep schema
-    # floor at ge=1 (any positive int) and rely on per-provider
-    # helpers (_stream_openai_responses / _stream_anthropic) to
-    # enforce or clamp the real floor.
+    # Codex follow-up: the field is a no-op for non-cloud OpenAI bases and
+    # every non-OpenAI provider, so a cross-provider schema floor would
+    # 422 valid Anthropic / ollama / llama.cpp requests carrying it. Keep
+    # the schema floor at ge=1 (any positive int) and let per-provider
+    # helpers (_stream_openai_responses / _stream_anthropic) enforce or
+    # clamp the real floor.
     import pytest as _pytest
 
     from models.inference import ChatCompletionRequest
 
-    # Non-positive values still rejected so blank-string posts don't
-    # sneak through.
+    # Non-positive values rejected so blank-string posts don't sneak in.
     with _pytest.raises(Exception):
         ChatCompletionRequest.model_validate(
             {
@@ -211,10 +206,10 @@ def test_chat_completion_request_accepts_any_positive_compaction_threshold():
         )
 
     # Any positive int passes schema validation, including values that
-    # would be no-ops on the OpenAI cloud path. This is intentional --
-    # the OpenAI helper drops the field on non-cloud bases and
-    # forwards-as-is on cloud bases; if the value is below the model's
-    # effective floor, the upstream API surfaces the error.
+    # are no-ops on the OpenAI cloud path. Intentional -- the OpenAI
+    # helper drops the field on non-cloud bases and forwards as-is on
+    # cloud bases; if it's below the model's effective floor, the upstream
+    # API surfaces the error.
     for v in (1, 5_000, 9_999, 10_000, 200_000):
         req = ChatCompletionRequest.model_validate(
             {
diff --git a/studio/backend/tests/test_openai_container_crud.py b/studio/backend/tests/test_openai_container_crud.py
index 48acf97e1f..e0604527fd 100644
--- a/studio/backend/tests/test_openai_container_crud.py
+++ b/studio/backend/tests/test_openai_container_crud.py
@@ -4,11 +4,11 @@
 """Unit tests for the /v1/containers CRUD client methods.
 
 Covers:
-- All three calls (list / create / delete) send
-  ``OpenAI-Beta: containers=v1``. Without it, OpenAI silently no-ops
-  the DELETE while still returning 200 ``{"deleted": true}``.
-- ``delete_openai_container`` raises when the response body does not
-  report ``{"deleted": true}``, even on a 2xx response.
+- list / create / delete all send ``OpenAI-Beta: containers=v1``. Without
+  it, OpenAI silently no-ops the DELETE but still returns 200
+  ``{"deleted": true}``.
+- ``delete_openai_container`` raises when the body omits
+  ``{"deleted": true}``, even on a 2xx response.
 """
 
 from __future__ import annotations
@@ -28,11 +28,10 @@ def _drive(coro):
 
 
 def _mock_http_client(monkeypatch, handler):
-    """Wire `handler` for both the shared `_http_client` AND any
-    per-call `httpx.AsyncClient(...)` instances. delete_openai_container
-    intentionally creates a fresh AsyncClient (see comment in
-    external_provider.delete_openai_container) so the test must
-    also intercept that constructor."""
+    """Wire `handler` for the shared `_http_client` AND any per-call
+    `httpx.AsyncClient(...)`. delete_openai_container creates a fresh
+    AsyncClient (see external_provider.delete_openai_container), so we
+    must also intercept that constructor."""
     transport = httpx.MockTransport(handler)
     monkeypatch.setattr(ep_mod, "_http_client", httpx.AsyncClient(transport = transport))
     real_async_client = httpx.AsyncClient
@@ -110,13 +109,12 @@ def test_delete_sends_openai_beta_header_and_accepts_confirmation(monkeypatch):
 
 def test_delete_raises_when_response_lacks_deleted_true(monkeypatch):
     """OpenAI returns 200 ``{"deleted": true}`` even when the request is
-    silently rejected (e.g. before we started sending OpenAI-Beta).
-    Defensive guard: when the body omits ``deleted: true``, surface it
-    as an error so the UI can report the failure instead of falsely
-    reporting success."""
+    silently rejected (e.g. before we sent OpenAI-Beta). Guard: when the
+    body omits ``deleted: true``, surface an error so the UI reports the
+    failure instead of false success."""
 
     def handler(request: httpx.Request) -> httpx.Response:
-        # 200 but no deleted flag — simulate an unexpected payload shape.
+        # 200 but no deleted flag — unexpected payload shape.
         return httpx.Response(200, json = {"id": "cntr_x", "object": "container"})
 
     _mock_http_client(monkeypatch, handler)
@@ -159,10 +157,9 @@ def test_delete_propagates_openai_4xx(monkeypatch):
 
 
 def test_list_route_filters_expired_containers(monkeypatch):
-    """OpenAI keeps containers in /v1/containers indefinitely with
-    status="expired" after their idle TTL passes — they can't be
-    used but still show up. The list route must drop them so the
-    picker only surfaces usable containers."""
+    """OpenAI keeps containers in /v1/containers with status="expired"
+    after their idle TTL passes — unusable but still listed. The list
+    route must drop them so the picker shows only usable containers."""
     from routes import inference as inf_mod
     from models.inference import OpenAIContainerRequest
 
diff --git a/studio/backend/tests/test_openai_image_generation.py b/studio/backend/tests/test_openai_image_generation.py
index f5dee2561a..39cf672dc1 100644
--- a/studio/backend/tests/test_openai_image_generation.py
+++ b/studio/backend/tests/test_openai_image_generation.py
@@ -4,17 +4,16 @@
 """Unit tests for OpenAI Responses API image_generation tool wiring.
 
 The image_generation tool is a server-side Responses-API tool:
-``{type: "image_generation"}`` in the request's tools array, and the
-result comes back as an ``image_generation_call`` output item carrying
-the base64 image on ``result``. Studio translates the output item
-into ``_toolEvent`` chunks (``tool_start`` with `kind:"image"`,
-``tool_end`` with ``image_b64`` + ``image_mime``) so the chat adapter
-can render the image inline.
+``{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.
+These tests pin: the tool is added to the outbound body only when the caller
+asks for it on a cloud OpenAI base; the SSE output_item.done for
+``image_generation_call`` produces the expected _toolEvent chunks; non-cloud
+bases drop the tool silently.
 """
 
 import asyncio
@@ -75,8 +74,8 @@ def _capture_body(monkeypatch, *, base_url: str, enabled_tools) -> dict:
 
 
 def _collect_tool_events(monkeypatch) -> list[dict]:
-    """Drive a Responses stream that emits one image_generation_call done
-    event and return the parsed _toolEvent chunks."""
+    """Drive a Responses stream with one image_generation_call done event and
+    return the parsed _toolEvent chunks."""
 
     sse = (
         b"event: response.output_item.done\n"
@@ -207,8 +206,8 @@ def test_image_generation_done_emits_tool_event_chunks(monkeypatch):
     ends = [e for e in image_events if e.get("type") == "tool_end"]
     assert len(starts) == 1, image_events
     assert len(ends) == 1, image_events
-    # `_server_tool: True` marks this as a provider-side synthetic
-    # tool card on the frontend's history serializer.
+    # `_server_tool: True` marks this as a provider-side synthetic tool card
+    # for the frontend's history serializer.
     assert starts[0]["arguments"] == {
         "kind": "image",
         "prompt": "A photorealistic cat sitting",
diff --git a/studio/backend/tests/test_openai_responses_translation.py b/studio/backend/tests/test_openai_responses_translation.py
index 95e9b2d63c..19d4959aa1 100644
--- a/studio/backend/tests/test_openai_responses_translation.py
+++ b/studio/backend/tests/test_openai_responses_translation.py
@@ -5,14 +5,14 @@
 Unit tests for the OpenAI `/v1/responses` translation in external_provider.
 
 Covers:
-- Request body shape: system messages collapse into `instructions`, user/
-  assistant messages go into `input`, sampling knobs Responses does not
-  support (presence_penalty, top_k) are not forwarded.
-- SSE translation: `response.output_text.delta` events become OpenAI Chat
-  Completions chunks, `response.completed` emits a `finish_reason: stop`
-  chunk, the stream terminates with `data: [DONE]`.
-- Image parts in user content are rewritten from Chat Completions
-  `{type: image_url, image_url: {url}}` into Responses
+- Request body shape: system messages collapse into `instructions`,
+  user/assistant messages go into `input`, and unsupported sampling knobs
+  (presence_penalty, top_k) are not forwarded.
+- SSE translation: `response.output_text.delta` → Chat Completions chunks,
+  `response.completed` → a `finish_reason: stop` chunk, stream ends with
+  `data: [DONE]`.
+- Image parts rewritten from Chat Completions
+  `{type: image_url, image_url: {url}}` to Responses
   `{type: input_image, image_url: }`.
 """
 
@@ -101,9 +101,9 @@ def test_responses_request_body_uses_input_and_instructions(monkeypatch):
     assert body["input"] == [{"role": "user", "content": "Hi"}]
     assert body["max_output_tokens"] == 512
     assert body["stream"] is True
-    # Responses API on reasoning-class models (gpt-5.x / o3 / gpt-4.5 — the
-    # only OpenAI ids the registry allowlist exposes) rejects these as
-    # `Unsupported parameter`. Make sure we never silently forward them.
+    # Responses API on reasoning-class models (gpt-5.x / o3 / gpt-4.5 — the only
+    # OpenAI ids the registry allowlist exposes) rejects these as `Unsupported
+    # parameter`. Never silently forward them.
     assert "temperature" not in body
     assert "top_p" not in body
     assert "presence_penalty" not in body
@@ -213,11 +213,11 @@ def test_responses_sse_translates_to_chat_completions_chunks(monkeypatch):
 
 
 def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypatch):
-    """Round 12: caller-supplied function tools forwarded into /v1/responses
-    must have their `function_call` output items translated back into Chat
-    Completions delta.tool_calls, and the terminal chunk must emit
-    finish_reason="tool_calls" so the frontend's accumulator runs the
-    function instead of seeing finish_reason="stop"."""
+    """Round 12: function tools forwarded into /v1/responses must have their
+    `function_call` output items translated back into Chat Completions
+    delta.tool_calls, and the terminal chunk must emit
+    finish_reason="tool_calls" (not "stop") so the frontend's accumulator runs
+    the function."""
 
     def handler(request: httpx.Request) -> httpx.Response:
         events = [
@@ -288,7 +288,7 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat
     assert tc["id"] == "call_xyz"
     assert tc["function"]["name"] == "get_weather"
     assert tc["function"]["arguments"] == '{"city":"SF"}'
-    # Final chunk reports tool_calls instead of stop.
+    # Final chunk reports tool_calls, not stop.
     terminal = next(
         p
         for p in payloads
@@ -301,8 +301,8 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat
 
 def test_responses_parallel_function_calls_get_distinct_indices(monkeypatch):
     """Round 13: parallel function_call items must land on distinct
-    delta.tool_calls[].index slots so index-keyed clients don't
-    collapse the second call into the first."""
+    delta.tool_calls[].index slots so index-keyed clients don't collapse the
+    second call into the first."""
 
     def handler(request: httpx.Request) -> httpx.Response:
         events = [
@@ -388,10 +388,10 @@ def test_responses_parallel_function_calls_get_distinct_indices(monkeypatch):
 
 
 def test_responses_follow_up_tool_result_uses_function_call_output_items(monkeypatch):
-    """Round 13: a second turn after a Responses function call must
-    serialize the tool_calls history and tool result as Responses
-    `function_call` / `function_call_output` input items, not as
-    Chat Completions role="tool" content."""
+    """Round 13: a second turn after a Responses function call must serialize
+    the tool_calls history and tool result as Responses `function_call` /
+    `function_call_output` input items, not Chat Completions role="tool"
+    content."""
     captured: dict = {}
 
     def handler(request: httpx.Request) -> httpx.Response:
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 7d488ae4c9..b9f086a4b9 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -10,8 +10,7 @@ Covers:
   with `content: None` + `tool_calls`.
 - ChatCompletionRequest carries unknown fields via `extra="allow"`.
 - anthropic_tool_choice_to_openai() covers all four Anthropic shapes.
-- _build_passthrough_payload() honors a caller-supplied tool_choice and
-  defaults to "auto" when unset.
+- _build_passthrough_payload() honors a caller tool_choice, defaults to "auto".
 - _friendly_error() maps httpx transport errors to a "Lost connection"
   message so passthrough failures are legible instead of bare 500s.
 
@@ -120,8 +119,8 @@ class TestChatMessageToolRoles:
             ChatMessage(role = "function", content = "x")
 
     def test_content_absent_on_assistant_tool_call_defaults_to_none(self):
-        # Assistant messages that carry only tool_calls are the one
-        # documented case where `content=None` is permitted.
+        # Assistant messages carrying only tool_calls are the one documented
+        # case where `content=None` is permitted.
         msg = ChatMessage(
             role = "assistant",
             tool_calls = [
@@ -136,9 +135,9 @@ class TestChatMessageToolRoles:
 
     def test_tool_role_missing_tool_call_id_left_for_request_validator(self):
         # Per-message: missing tool_call_id is now allowed at this layer.
-        # ChatCompletionRequest's walkback fills it in from the prior
-        # assistant tool_calls; see test_inference_model_validation.py for
-        # the resolution coverage.
+        # ChatCompletionRequest's walkback fills it from the prior assistant
+        # tool_calls; see test_inference_model_validation.py for resolution
+        # coverage.
         msg = ChatMessage(role = "tool", content = '{"temperature": 72}')
         assert msg.tool_call_id is None
         assert msg.content == '{"temperature": 72}'
@@ -173,7 +172,7 @@ class TestChatMessageToolRoles:
         assert "content" in str(exc_info.value)
 
     def test_assistant_without_content_or_tool_calls_tolerated(self):
-        # Stop-button leaves an empty assistant turn; tolerate so replay round-trips.
+        # Stop-button leaves an empty assistant turn; tolerate for replay.
         msg = ChatMessage(role = "assistant")
         assert msg.content is None
         assert msg.tool_calls is None
@@ -280,9 +279,8 @@ class TestChatCompletionRequestToolFields:
         assert req.stop is None
 
     def test_extra_fields_accepted(self):
-        # `frequency_penalty`, `seed`, `response_format` are not yet
-        # explicitly declared but must survive Pydantic parsing now that
-        # extra="allow" is set.
+        # `frequency_penalty`, `seed`, `response_format` aren't explicitly
+        # declared but must survive Pydantic parsing now that extra="allow".
         req = self._make(
             frequency_penalty = 0.5,
             seed = 42,
@@ -306,24 +304,22 @@ class TestChatCompletionRequestToolFields:
 
     def test_stream_defaults_false_matching_openai_spec(self):
         # OpenAI's /v1/chat/completions spec defaults `stream` to false.
-        # Studio previously defaulted to true, which broke naive curl
-        # clients (and .NET / System.Text.Json SDKs per #5047) that omit
-        # `stream` -- they expect a JSON blob, got SSE.
-        # Pin the corrected default so it can't silently regress.
+        # Studio previously defaulted to true, breaking naive curl clients
+        # (and .NET / System.Text.Json SDKs per #5047) that omit `stream`:
+        # they expect a JSON blob, got SSE. Pin the corrected default so it
+        # can't silently regress.
         req = self._make()
         assert req.stream is False
 
     def test_post_without_stream_field_decodes_to_stream_false_over_http(self, monkeypatch):
         # Wire-level guard for the same default: a POST body that omits
-        # `stream` entirely (the exact shape naive curl / .NET clients
-        # send) must deserialise into stream=False *and* the response
-        # must be `application/json`, never `text/event-stream`.
-        # Mounts the real `routes.inference.router` so this catches
-        # regressions in middleware/aliasing on the actual endpoint
-        # (e.g. someone adding a request layer that injects stream=True
-        # before pydantic builds the model). Backends are bypassed by
-        # routing through `provider_type` and stubbing the external
-        # provider proxy.
+        # `stream` (the exact shape naive curl / .NET clients send) must
+        # deserialise into stream=False *and* return `application/json`, never
+        # `text/event-stream`. Mounts the real `routes.inference.router` so
+        # this catches middleware/aliasing regressions on the actual endpoint
+        # (e.g. a request layer that injects stream=True before pydantic builds
+        # the model). Backends are bypassed via `provider_type` + a stubbed
+        # external provider proxy.
         from fastapi import FastAPI
         from fastapi.responses import JSONResponse
         from fastapi.testclient import TestClient
@@ -487,12 +483,12 @@ class TestBuildPassthroughPayloadToolChoice:
 
 class TestFriendlyErrorHttpx:
     """The async pass-through helpers talk to llama-server via httpx.
-    When the subprocess is down, httpx raises RequestError subclasses
-    whose string form (``"All connection attempts failed"``, ``"[Errno 111]
-    Connection refused"``, ...) does NOT contain the substring
-    ``"Lost connection to llama-server"`` the sync path uses, so the
-    previous substring-only `_friendly_error` returned a useless generic
-    message. These tests pin the new isinstance-based mapping.
+    When the subprocess is down, httpx raises RequestError subclasses whose
+    string form (``"All connection attempts failed"``, ``"[Errno 111]
+    Connection refused"``, ...) lacks the ``"Lost connection to llama-server"``
+    substring the sync path uses, so the old substring-only `_friendly_error`
+    returned a useless generic message. These tests pin the new
+    isinstance-based mapping.
     """
 
     def _req(self):
@@ -515,9 +511,8 @@ class TestFriendlyErrorHttpx:
         assert "Lost connection" in _friendly_error(exc)
 
     def test_non_httpx_unchanged(self):
-        # Non-httpx exceptions still fall through to the existing substring
-        # heuristics — a context-size message must still produce the
-        # "Message too long" path.
+        # Non-httpx exceptions still fall through to the substring heuristics
+        # — a context-size message must still produce "Message too long".
         ctx_msg = "request (4096 tokens) exceeds the available context size (2048 tokens)"
         assert "Message too long" in _friendly_error(ValueError(ctx_msg))
 
@@ -543,7 +538,7 @@ class TestDropEmptyAssistantSentinels:
         assert out == [{"role": "user", "content": "hi"}, {"role": "user", "content": "again"}]
 
     def test_drops_assistant_with_no_content_key(self):
-        # exclude_none=True strips the content key entirely; filter must catch this.
+        # exclude_none=True strips the content key entirely; filter must catch it.
         msgs = [
             {"role": "user", "content": "hi"},
             {"role": "assistant"},
@@ -658,8 +653,8 @@ class TestGgufVisionMessages:
         assert len(messages[2]["content"]) == 2
         assert isinstance(messages[1]["content"], str)
 
-        # Legacy top-level image_base64 must be ignored when any message-level
-        # image already exists; otherwise turn 2 ends up with two image parts.
+        # Legacy top-level image_base64 must be ignored when a message-level
+        # image exists; otherwise turn 2 ends up with two image parts.
         for msg in messages:
             content = msg.get("content")
             if isinstance(content, list):
diff --git a/studio/backend/tests/test_openai_tool_result_fallbacks.py b/studio/backend/tests/test_openai_tool_result_fallbacks.py
index 7c033bc348..5ea812441f 100644
--- a/studio/backend/tests/test_openai_tool_result_fallbacks.py
+++ b/studio/backend/tests/test_openai_tool_result_fallbacks.py
@@ -3,8 +3,8 @@
 
 """Regression tests for OpenAI Responses tool-result rendering.
 
-Covers two bug classes: empty web_search cards (per-card result seeded
-with "Searching: ") and orphan shell_call cards (bundled-output
+Two bug classes: empty web_search cards (per-card result seeded with
+"Searching: ") and orphan shell_call cards (bundled-output
 fallback + final flush at response.completed / response.incomplete).
 """
 
@@ -137,8 +137,8 @@ def test_web_search_each_call_carries_its_own_query_as_result(monkeypatch):
 
 
 def test_web_search_last_call_overwritten_with_citations(monkeypatch):
-    """Last call still gets the aggregated citation list; earlier calls
-    keep their per-call `Searching:` text."""
+    """Last call gets the aggregated citations; earlier calls keep their
+    per-call `Searching:` text."""
     sse_events = [
         {
             "type": "response.output_item.done",
@@ -170,12 +170,12 @@ def test_web_search_last_call_overwritten_with_citations(monkeypatch):
     events = _tool_events(lines)
     ends = [e for e in events if e["type"] == "tool_end"]
     by_id: dict = {}
-    # Keep the LAST tool_end per id (the citation overwrite for ws_2).
+    # Keep the LAST tool_end per id (citation overwrite for ws_2).
     for e in ends:
         by_id[e["tool_call_id"]] = e
     # First call keeps its own query.
     assert by_id["ws_1"]["result"] == "Searching: first query"
-    # Last call gets overwritten with the citation block.
+    # Last call overwritten with the citation block.
     assert "Title: Example A" in by_id["ws_2"]["result"]
     assert "URL: https://example.com/a" in by_id["ws_2"]["result"]
 
diff --git a/studio/backend/tests/test_pricing.py b/studio/backend/tests/test_pricing.py
index d669747b1a..8cd7796f14 100644
--- a/studio/backend/tests/test_pricing.py
+++ b/studio/backend/tests/test_pricing.py
@@ -1,8 +1,8 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""Unit tests for the per-session cost calculator. Verifies math
-against ``core/inference/pricing.py`` and graceful degradation."""
+"""Unit tests for the per-session cost calculator: math against
+``core/inference/pricing.py`` plus graceful degradation."""
 
 import math
 
@@ -462,12 +462,12 @@ def test_snapshot_contains_provider_buckets_and_multipliers():
 
 
 # ── longest-prefix match: dated mini variant must not collide with the
-#    shorter family prefix. ──
+#    shorter family prefix ──
 
 
 def test_longest_prefix_match_wins_for_dated_mini_snapshot():
-    """`gpt-5.4-mini-2026-...` must inherit the mini rate, not the
-    shorter `gpt-5.4` rate (longest prefix wins)."""
+    """`gpt-5.4-mini-2026-...` inherits the mini rate, not the shorter
+    `gpt-5.4` rate (longest prefix wins)."""
     out = calculate_cost(
         "openai",
         "gpt-5.4-mini-2026-04-23",
@@ -493,7 +493,7 @@ def test_longest_prefix_match_wins_for_dated_pro_snapshot():
 
 
 def test_openai_chat_style_usage_keys_priced_correctly():
-    """Chat-style envelope (`prompt_tokens` / `completion_tokens`) must
+    """Chat-style envelope (`prompt_tokens`/`completion_tokens`) must
     produce a non-zero cost (previously silently zeroed)."""
     out = calculate_cost(
         "openai",
@@ -577,7 +577,7 @@ def test_openai_chat_style_prompt_tokens_keeps_cache_read_semantics():
 
 def test_openai_chat_style_envelope_reads_cache_from_prompt_tokens_details():
     """Chat-style envelope ships cached under prompt_tokens_details;
-    calculator must honour both this and input_tokens_details."""
+    calculator must honour both that and input_tokens_details."""
     base = OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
     raw = calculate_cost(
         "openai",
diff --git a/studio/backend/tests/test_pricing_edge.py b/studio/backend/tests/test_pricing_edge.py
index 5818b42e8a..4197d8c9f0 100644
--- a/studio/backend/tests/test_pricing_edge.py
+++ b/studio/backend/tests/test_pricing_edge.py
@@ -30,8 +30,8 @@ def _isclose(
 
 
 def test_prefix_match_requires_dash_boundary_opus_variant():
-    # `claude-opus-4-15` must not inherit `claude-opus-4-1` pricing;
-    # next char must be `-` or end-of-string.
+    # `claude-opus-4-15` must not inherit `claude-opus-4-1` pricing; the next
+    # char must be `-` or end-of-string.
     assert _lookup("anthropic", "claude-opus-4-15") is None
     out = calculate_cost(
         "anthropic",
@@ -55,8 +55,8 @@ def test_prefix_match_requires_dash_boundary_gpt_variant():
 
 
 def test_prefix_match_requires_dash_boundary_pro_lookalike():
-    # `gpt-5.5-prod` must fall through `gpt-5.5-pro` (6x overcharge)
-    # and land on the canonical `gpt-5.5` row.
+    # `gpt-5.5-prod` must fall through `gpt-5.5-pro` (6x overcharge) and land on
+    # the canonical `gpt-5.5` row.
     prices = _lookup("openai", "gpt-5.5-prod")
     assert prices is not None
     assert (
@@ -81,7 +81,7 @@ def test_prefix_match_still_resolves_legit_dated_snapshots():
     assert out["priced"] is True
     assert _isclose(out["input_usd"], 0.75)
 
-    # And Anthropic dated snapshot still resolves to canonical row.
+    # Anthropic dated snapshot still resolves to the canonical row.
     out = calculate_cost(
         "anthropic",
         "claude-opus-4-7-20260414",
@@ -95,7 +95,7 @@ def test_prefix_match_still_resolves_legit_dated_snapshots():
 
 
 def test_explicit_zero_input_tokens_wins_over_stale_prompt_tokens():
-    # Input-side mirror of the output zero precedence test.
+    # Input-side mirror of the output zero-precedence test.
     out = calculate_cost(
         "openai",
         "gpt-5.5",
@@ -110,7 +110,7 @@ def test_explicit_zero_input_tokens_wins_over_stale_prompt_tokens():
 
 
 def test_none_input_tokens_falls_through_to_prompt_tokens():
-    # `None` is "key present but unset"; chat-style mirror wins.
+    # `None` means "key present but unset"; chat-style mirror wins.
     out = calculate_cost(
         "openai",
         "gpt-5.5",
@@ -176,8 +176,8 @@ def test_negative_prompt_tokens_chat_style_clamp():
 
 
 def test_anthropic_chat_cache_read_exceeds_prompt_no_negative_billable():
-    # cache_read > prompt_tokens clamps uncached_input at 0; billable
-    # still reflects cache buckets (we charge for what we got).
+    # cache_read > prompt_tokens clamps uncached_input at 0; billable still
+    # reflects cache buckets (we charge for what we got).
     out = calculate_cost(
         "anthropic",
         "claude-opus-4-7",
@@ -216,8 +216,8 @@ def test_openai_raw_cached_tokens_exceeds_input_clamp_non_cached():
 
 
 def test_openai_long_context_triggers_on_cache_creation_inflated_billable():
-    # cache_creation pushes billable past 272k -> long-context tier
-    # must fire to avoid undercounting.
+    # cache_creation pushes billable past 272k -> long-context tier must fire to
+    # avoid undercounting.
     out = calculate_cost(
         "openai",
         "gpt-5.5",
@@ -272,8 +272,8 @@ def test_openai_chat_envelope_long_context_parity_with_raw():
 
 
 def test_cache_creation_as_int_does_not_crash():
-    # Proxies sometimes fold cache_creation to an int; tolerate it
-    # and fall back to the 5m default.
+    # Proxies sometimes fold cache_creation to an int; tolerate it and fall back
+    # to the 5m default.
     base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
     out = calculate_cost(
         "anthropic",
@@ -363,16 +363,16 @@ def test_empty_usage_dict_zero_bill():
 
 
 def test_anthropic_prompt_tokens_details_fallback_when_native_key_missing():
-    """Chat-style envelope without `cache_read_input_tokens` but with
-    mirrored `prompt_tokens_details.cached_tokens` should still apply
-    the cache_read discount."""
+    """Chat-style envelope without `cache_read_input_tokens` but with mirrored
+    `prompt_tokens_details.cached_tokens` should still apply the cache_read
+    discount."""
     r = calculate_cost(
         provider = "anthropic",
         model = "claude-opus-4-7",
         usage = {
             "prompt_tokens": 1_000_000,
             "completion_tokens": 0,
-            # Only the mirrored shape (no native key).
+            # Mirrored shape only (no native key).
             "prompt_tokens_details": {"cached_tokens": 1_000_000},
             "cache_creation_input_tokens": 0,
         },
@@ -383,8 +383,8 @@ def test_anthropic_prompt_tokens_details_fallback_when_native_key_missing():
 
 
 def test_anthropic_native_key_takes_precedence_over_mirrored():
-    """When both native and mirrored cache-read fields are present,
-    the native Anthropic field wins (mirror is fallback-only)."""
+    """When both native and mirrored cache-read fields are present, the native
+    Anthropic field wins (mirror is fallback-only)."""
     r = calculate_cost(
         provider = "anthropic",
         model = "claude-opus-4-7",
@@ -403,8 +403,8 @@ def test_anthropic_native_key_takes_precedence_over_mirrored():
 
 
 def test_anthropic_native_zero_takes_precedence_over_mirrored():
-    """Explicit `cache_read_input_tokens: 0` is authoritative; a stale
-    mirrored block from a proxy must not inflate cache_read past it."""
+    """Explicit `cache_read_input_tokens: 0` is authoritative; a stale mirrored
+    block from a proxy must not inflate cache_read past it."""
     r = calculate_cost(
         provider = "anthropic",
         model = "claude-opus-4-7",
@@ -429,8 +429,8 @@ def test_anthropic_native_zero_takes_precedence_over_mirrored():
 
 
 def test_build_usage_chunk_forwards_anthropic_cache_creation_breakdown():
-    """Chat-style envelope must carry the 5m/1h cache-write breakdown
-    so downstream cost calc applies the 2x 1h premium."""
+    """Chat-style envelope must carry the 5m/1h cache-write breakdown so
+    downstream cost calc applies the 2x 1h premium."""
     import json
     from core.inference.external_provider import _build_usage_chunk
 
diff --git a/studio/backend/tests/test_providers_api.py b/studio/backend/tests/test_providers_api.py
index 88df886b6c..f343cef635 100644
--- a/studio/backend/tests/test_providers_api.py
+++ b/studio/backend/tests/test_providers_api.py
@@ -4,13 +4,13 @@
 """
 Integration tests for the external providers API.
 
-Requires a running Unsloth Studio server. Configure via environment variables:
+Requires a running Unsloth Studio server. Configure via env vars:
 
     export STUDIO_TEST_URL="http://localhost:8888"   # default
     export STUDIO_TEST_USER="unsloth"                # default
     export STUDIO_TEST_PASSWORD="..."                # required — see .bootstrap_password
 
-    # Provider API keys — any left unset will have their tests automatically skipped
+    # Provider API keys — tests skip when their key is unset
     export OPENAI_API_KEY="sk-..."
     export MISTRAL_API_KEY="..."
     export GOOGLE_API_KEY="..."
@@ -38,15 +38,14 @@ BASE_URL = os.getenv("STUDIO_TEST_URL", "http://localhost:8000")
 USERNAME = os.getenv("STUDIO_TEST_USER", "unsloth")
 PASSWORD = os.getenv("STUDIO_TEST_PASSWORD", "")
 
-# These tests require a live Studio server reachable at BASE_URL with a known
-# bootstrap password. Skip the whole module when that environment is missing
-# (e.g. on CI runners) so pytest discovery does not error out.
+# Skip the whole module when no live Studio server / bootstrap password is
+# available (e.g. on CI) so pytest discovery does not error out.
 pytestmark = pytest.mark.skipif(
     not PASSWORD,
     reason = "Integration test requires a running Studio server; set STUDIO_TEST_PASSWORD to enable.",
 )
 
-# Map provider_type → (env var name, model to use for inference test)
+# provider_type → (env var name, model for inference test)
 _PROVIDER_CONFIGS: dict[str, tuple[str, str]] = {
     "openai": ("OPENAI_API_KEY", "gpt-4o-mini"),
     "mistral": ("MISTRAL_API_KEY", "mistral-small-2506"),
@@ -74,10 +73,10 @@ def _url(path: str) -> str:
 
 def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:
     """
-    Read a streaming SSE response and return (assembled_text, saw_done).
+    Read an SSE response, return (assembled_text, saw_done).
 
-    Each chunk is a JSON object with choices[0].delta.content.
-    The stream ends with `data: [DONE]`.
+    Each chunk is JSON with choices[0].delta.content; stream ends with
+    `data: [DONE]`.
     """
     reply_parts: list[str] = []
     saw_done = False
@@ -93,7 +92,7 @@ def _parse_sse_stream(response: requests.Response) -> tuple[str, bool]:
             break
         try:
             chunk = json.loads(data)
-            # Handle both error payloads and normal chunks
+            # Handle error payloads and normal chunks
             if "error" in chunk:
                 raise RuntimeError(f"Provider error in stream: {chunk['error']}")
             delta = chunk.get("choices", [{}])[0].get("delta", {})
@@ -114,13 +113,12 @@ def auth_headers() -> dict[str, str]:
     """
     Log in once per session and return auth headers.
 
-    On a fresh Studio install the bootstrap password triggers a forced password
-    change (must_change_password=True).  Any subsequent API call using that token
-    returns 403 "Password change required".  This fixture detects that state,
-    automatically completes the change-password flow, and re-logs in so all other
-    tests get a fully usable token.
+    On a fresh install the bootstrap password forces a change
+    (must_change_password=True); calls with that token return 403 "Password
+    change required". This fixture detects that, auto-completes the change, and
+    re-logs in so other tests get a usable token.
 
-    The new password used during auto-change is:
+    The auto-change new password is:
         STUDIO_TEST_NEW_PASSWORD  (env var, optional)
         or PASSWORD + "-test"     (derived default)
 
@@ -142,8 +140,8 @@ def auth_headers() -> dict[str, str]:
     assert token, "access_token is empty"
 
     if body.get("must_change_password"):
-        # Bootstrap token is restricted — only /api/auth/change-password works with it.
-        # Auto-complete the forced change so the rest of the tests get a full token.
+        # Bootstrap token only works with /api/auth/change-password; auto-complete
+        # the forced change so the rest of the tests get a full token.
         new_password = os.getenv("STUDIO_TEST_NEW_PASSWORD") or f"{PASSWORD}-test"
         change_resp = requests.post(
             _url("/api/auth/change-password"),
@@ -176,11 +174,11 @@ def public_key_pem(auth_headers: dict[str, str]) -> str:
 @pytest.fixture(scope = "session")
 def vision_image_data_url() -> str:
     """
-    Download the sloth image once per session and return it as a base64 data URI.
+    Download the sloth image once per session as a base64 data URI.
 
-    Using a data URI instead of a remote URL ensures every provider receives
-    the image inline — Gemini's OpenAI-compatible layer does not fetch external
-    HTTP URLs, so raw image_url links silently produce empty replies for Gemini.
+    A data URI sends the image inline to every provider; Gemini's
+    OpenAI-compatible layer does not fetch external HTTP URLs, so raw image_url
+    links silently produce empty Gemini replies.
     """
     resp = requests.get(_VISION_IMAGE_URL, timeout = 30)
     resp.raise_for_status()
@@ -192,10 +190,10 @@ def vision_image_data_url() -> str:
 @pytest.fixture(scope = "session")
 def encrypt_key(public_key_pem: str):
     """
-    Return a callable encrypt_key(plaintext: str) -> str (base64 RSA-OAEP ciphertext).
-    Uses the backend's RSA public key — mirrors what the frontend does.
+    Return encrypt_key(plaintext: str) -> str (base64 RSA-OAEP ciphertext).
+    Uses the backend's RSA public key — mirrors the frontend.
     """
-    # Decode PEM → load RSA public key
+    # Load RSA public key from PEM
     pem_bytes = public_key_pem.encode("utf-8")
     rsa_pub = serialization.load_pem_public_key(pem_bytes)
 
@@ -298,8 +296,8 @@ class TestRegistry:
 
 class TestProviderCRUD:
     """
-    These tests run sequentially within the class and share state via class variables.
-    They create, read, update, and delete a single test provider config.
+    Run sequentially, sharing state via class variables. Create, read, update,
+    and delete a single test provider config.
     """
 
     _created_id: str = ""
@@ -356,7 +354,7 @@ class TestProviderCRUD:
         )
         assert resp.status_code == 204, f"Delete failed ({resp.status_code}): {resp.text}"
 
-        # Confirm gone from list
+        # Confirm gone
         list_resp = requests.get(_url("/api/providers/"), headers = auth_headers, timeout = 10)
         ids = [p["id"] for p in list_resp.json()]
         assert TestProviderCRUD._created_id not in ids, "Deleted provider still in list"
@@ -366,7 +364,7 @@ class TestProviderCRUD:
 # ── TestProviderInference ────────────────────────────────────────────
 
 
-# Build parametrize list: (provider_type, model, api_key) for configured providers only
+# Parametrize (provider_type, model, api_key) for configured providers
 _INFERENCE_PARAMS = [
     pytest.param(
         ptype,
@@ -384,8 +382,8 @@ _INFERENCE_PARAMS = [
 
 class TestProviderInference:
     """
-    Live inference tests — one parametrized set per provider.
-    Each test is automatically skipped when the provider's API key env var is not set.
+    Live inference tests, one parametrized set per provider. Each is skipped
+    when the provider's API key env var is unset.
     """
 
     @pytest.mark.parametrize("provider_type,model,api_key", _INFERENCE_PARAMS)
@@ -475,7 +473,7 @@ class TestProviderInference:
 
 # ── TestVisionInference ─────────────────────────────────────────────
 
-# Sloth photo — used to test vision routing across providers
+# Sloth photo for testing vision routing across providers
 _VISION_IMAGE_URL = "https://www.travelexcellence.com/images/where-to-see-sloths-in-costa-rica.jpg"
 
 _VISION_PARAMS = [
@@ -496,8 +494,8 @@ _VISION_PARAMS = [
 
 class TestVisionInference:
     """
-    Send a 1×1 white PNG alongside a text question to each vision-capable provider.
-    Verifies that image content parts survive the proxy and the provider replies.
+    Send a 1×1 white PNG plus a text question to each vision-capable provider.
+    Verifies image content parts survive the proxy and the provider replies.
     """
 
     @pytest.mark.parametrize("provider_type,model,api_key", _VISION_PARAMS)
@@ -559,9 +557,9 @@ class TestLocalInferenceUnaffected:
         """
         POST /v1/chat/completions without provider fields must not return 422 or 500.
 
-        200 = a local model is loaded and responded.
-        503 = no model loaded (expected in test environment — that's fine).
-        Any other 4xx/5xx (except 503) = regression in request handling.
+        200 = local model loaded and responded.
+        503 = no model loaded (expected in test env — fine).
+        Any other 4xx/5xx (except 503) = request-handling regression.
         """
         resp = requests.post(
             _url("/v1/chat/completions"),
diff --git a/studio/backend/tests/test_pytorch_mirror.py b/studio/backend/tests/test_pytorch_mirror.py
index 5844f209b6..f1574fb31e 100644
--- a/studio/backend/tests/test_pytorch_mirror.py
+++ b/studio/backend/tests/test_pytorch_mirror.py
@@ -19,8 +19,8 @@ OFFICIAL_URL = "https://download.pytorch.org/whl"
 
 
 def _reload_whl_base(monkeypatch, mirror_value = None):
-    """(Re-)import install_python_stack with a controlled env and return _PYTORCH_WHL_BASE."""
-    # Remove cached module so the module-level assignment re-executes
+    """(Re-)import install_python_stack with a controlled env, return _PYTORCH_WHL_BASE."""
+    # Drop cached module so the module-level assignment re-executes
     sys.modules.pop("install_python_stack", None)
 
     if mirror_value is None:
@@ -28,7 +28,7 @@ def _reload_whl_base(monkeypatch, mirror_value = None):
     else:
         monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", mirror_value)
 
-    # Temporarily add the script's directory to sys.path for import
+    # Add the script's directory to sys.path for import
     script_dir = str(_INSTALL_SCRIPT.parent)
     monkeypatch.syspath_prepend(script_dir)
 
diff --git a/studio/backend/tests/test_recommended_folders_permission.py b/studio/backend/tests/test_recommended_folders_permission.py
index 659c3b547d..ffe8c65ac0 100644
--- a/studio/backend/tests/test_recommended_folders_permission.py
+++ b/studio/backend/tests/test_recommended_folders_permission.py
@@ -6,17 +6,16 @@ Regression test for the /recommended-folders (and /browse-folders) 500
 caused by an unreadable model directory, e.g. a stock root-owned
 ``ollama`` install at ``/usr/share/ollama/.ollama/models``.
 
-Root cause: the folder-scan helpers in ``routes.models`` probed candidate
-paths with a bare ``Path(p).is_dir()``. On Python <= 3.11 that returned
-``False`` for an unreadable path; on Python >= 3.12 ``is_dir()`` propagates
+Root cause: ``routes.models`` folder-scan helpers probed candidates with a
+bare ``Path(p).is_dir()``. On Python <= 3.11 that returned ``False`` for an
+unreadable path; on Python >= 3.12 ``is_dir()`` propagates
 ``PermissionError`` (EACCES), so the endpoint 500-ed through the whole
-middleware stack instead of just skipping the directory. The probes now go
-through the module-level ``_safe_is_dir`` helper.
+middleware stack instead of skipping the directory. Probes now go through
+the module-level ``_safe_is_dir`` helper.
 
-``routes.models`` pulls the full backend dependency tree (fastapi,
-structlog, the models package, ...), so rather than stand up the app we
-extract the real ``_safe_is_dir`` definition from the source file and
-exercise that exact function in isolation. The test therefore stays
+``routes.models`` pulls the full backend dep tree (fastapi, structlog, the
+models package, ...), so rather than stand up the app we extract the real
+``_safe_is_dir`` from the source file and exercise it in isolation —
 dependency-free while still running the shipped code.
 
 Run:
@@ -36,7 +35,7 @@ _models_src = _backend_root / "routes" / "models.py"
 
 def _load_safe_is_dir():
     """Return the real ``_safe_is_dir`` from routes/models.py without
-    importing the (heavily dependency-laden) module."""
+    importing the dependency-laden module."""
     tree = ast.parse(_models_src.read_text())
     fn = next(
         node
@@ -51,8 +50,8 @@ def _load_safe_is_dir():
 
 safe_is_dir = _load_safe_is_dir()
 
-# Permission bits are bypassed for the superuser, so the chmod-000 setup
-# below would not actually deny access when running as root.
+# The superuser bypasses permission bits, so the chmod-000 setup below
+# would not deny access when running as root.
 _skip_as_root = pytest.mark.skipif(
     hasattr(os, "geteuid") and os.geteuid() == 0,
     reason = "root bypasses filesystem permission bits",
@@ -60,8 +59,8 @@ _skip_as_root = pytest.mark.skipif(
 
 
 def test_helper_exists_in_source():
-    # Guards against a refactor silently dropping the helper the fix
-    # depends on (the extractor would then raise StopIteration).
+    # Guard against a refactor silently dropping the helper the fix needs
+    # (the extractor would then raise StopIteration).
     assert callable(safe_is_dir)
 
 
@@ -83,8 +82,8 @@ def test_file_is_false(tmp_path):
 def test_mode000_dir_itself_is_still_a_dir(tmp_path):
     """A mode-000 directory is still stat-able via its (traversable)
     parent, so _safe_is_dir reports True without raising. Filtering out
-    dirs we cannot actually *read* is the caller's separate
-    os.access(R_OK|X_OK) check, not this helper's job."""
+    dirs we can't *read* is the caller's separate os.access(R_OK|X_OK)
+    check, not this helper's job."""
     locked = tmp_path / "locked"
     locked.mkdir()
     os.chmod(locked, 0o000)
@@ -96,8 +95,8 @@ def test_mode000_dir_itself_is_still_a_dir(tmp_path):
 
 @_skip_as_root
 def test_path_under_unreadable_parent_returns_false_not_raises(tmp_path):
-    """The exact production scenario: stat()-ing a child of a mode-700
-    system directory, e.g. ``/usr/share/ollama/.ollama/models``."""
+    """The production scenario: stat()-ing a child of a mode-700 system
+    directory, e.g. ``/usr/share/ollama/.ollama/models``."""
     parent = tmp_path / "ollama"
     parent.mkdir()
     os.chmod(parent, 0o000)
@@ -113,8 +112,8 @@ def test_path_under_unreadable_parent_returns_false_not_raises(tmp_path):
     reason = "is_dir() only propagates PermissionError on Python >= 3.12",
 )
 def test_demonstrates_the_underlying_stdlib_regression(tmp_path):
-    """Documents *why* _safe_is_dir exists: the old bare pattern raises
-    on the interpreters Studio ships on (3.12+)."""
+    """Documents *why* _safe_is_dir exists: the old bare pattern raises on
+    the interpreters Studio ships on (3.12+)."""
     parent = tmp_path / "ollama"
     parent.mkdir()
     os.chmod(parent, 0o000)
diff --git a/studio/backend/tests/test_responses_api.py b/studio/backend/tests/test_responses_api.py
index c0ec876ad0..6ef874bd98 100644
--- a/studio/backend/tests/test_responses_api.py
+++ b/studio/backend/tests/test_responses_api.py
@@ -2,9 +2,9 @@
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
 
 """
-Tests for the OpenAI Responses API schemas and input normalisation.
-These tests do NOT require a running server or GPU -- they validate
-the Pydantic models and the _normalise_responses_input helper.
+Tests for OpenAI Responses API schemas and input normalisation.
+No running server or GPU required -- validates the Pydantic models and
+the _normalise_responses_input helper.
 """
 
 import sys
@@ -12,7 +12,7 @@ import os
 import json
 import re
 
-# Ensure backend is on path
+# Ensure backend is on path.
 _backend = os.path.join(os.path.dirname(__file__), "..")
 sys.path.insert(0, _backend)
 
@@ -34,33 +34,32 @@ from models.inference import (
 
 
 # ── _normalise_responses_input: copied from routes/inference.py ──
-# We cannot import routes.inference directly because routes/__init__.py
-# pulls in heavy dependencies (structlog/twisted/torch). This is a
-# direct copy of the function for testing purposes.
+# Can't import routes.inference directly: routes/__init__.py pulls in
+# heavy deps (structlog/twisted/torch). This is a direct copy for tests.
 
 
 def _normalise_responses_input(payload: ResponsesRequest) -> list:
-    """Convert a ResponsesRequest into a list of ChatMessage for the completions backend."""
+    """Convert a ResponsesRequest into ChatMessages for the completions backend."""
     messages = []
 
-    # System / developer instructions
+    # System / developer instructions.
     if payload.instructions:
         messages.append(ChatMessage(role = "system", content = payload.instructions))
 
-    # Simple string input
+    # Simple string input.
     if isinstance(payload.input, str):
         if payload.input:
             messages.append(ChatMessage(role = "user", content = payload.input))
         return messages
 
-    # List of ResponsesInputMessage
+    # List of ResponsesInputMessage.
     for msg in payload.input:
         role = "system" if msg.role == "developer" else msg.role
 
         if isinstance(msg.content, str):
             messages.append(ChatMessage(role = role, content = msg.content))
         else:
-            # Convert Responses content parts -> Chat content parts
+            # Convert Responses content parts -> Chat content parts.
             parts = []
             for part in msg.content:
                 if isinstance(part, ResponsesInputTextPart):
@@ -130,7 +129,7 @@ class TestResponsesRequest:
         assert req.instructions == "You are a helpful assistant."
 
     def test_extra_fields_accepted(self):
-        """OpenAI SDK may send fields we don't model -- extra='allow' should pass."""
+        """OpenAI SDK may send unmodeled fields -- extra='allow' must pass."""
         req = ResponsesRequest(
             input = "test",
             tools = [{"type": "web_search_preview"}],
@@ -167,7 +166,7 @@ class TestResponsesRequest:
 
 
 class TestResponsesResponse:
-    """Validate response models serialise correctly."""
+    """Response models serialise correctly."""
 
     def test_basic_response(self):
         resp = ResponsesResponse(
@@ -224,7 +223,7 @@ class TestResponsesResponse:
 
 
 class TestNormaliseResponsesInput:
-    """Test _normalise_responses_input converts Responses input to ChatMessages."""
+    """_normalise_responses_input converts Responses input to ChatMessages."""
 
     def test_string_input(self):
         payload = ResponsesRequest(input = "Hello world")
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index 146d6017d0..c182e3d6d0 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -6,19 +6,19 @@ Tests for the OpenAI /v1/responses client-side function-calling pass-through.
 
 Covers:
 - ResponsesRequest accepts Responses-shape `tools`, `tool_choice`,
-  `parallel_tool_calls`, and the `function_call` / `function_call_output`
-  input items used for multi-turn tool loops.
-- _translate_responses_tools_to_chat() converts the flat Responses tool
-  shape to the nested Chat Completions shape, drops non-function built-in
-  tools, and returns None for empty lists.
-- _translate_responses_tool_choice_to_chat() passes string choices through
-  and converts {type:function,name:X} to Chat Completions' nested shape.
-- _normalise_responses_input() maps function_call_output items to
+  `parallel_tool_calls`, and `function_call` / `function_call_output`
+  input items for multi-turn tool loops.
+- _translate_responses_tools_to_chat(): flat Responses tool shape ->
+  nested Chat Completions shape, drops non-function built-in tools,
+  returns None for empty lists.
+- _translate_responses_tool_choice_to_chat(): passes string choices
+  through, converts {type:function,name:X} to the nested shape.
+- _normalise_responses_input(): maps function_call_output items to
   role="tool" ChatMessages with tool_call_id, and function_call items to
   assistant messages with tool_calls.
-- _chat_tool_calls_to_responses_output() preserves call_id and drops
+- _chat_tool_calls_to_responses_output(): keeps call_id, drops
   non-function tool calls.
-- ResponsesOutputFunctionCall and ResponsesResponse round-trip tool-call
+- ResponsesOutputFunctionCall / ResponsesResponse round-trip tool-call
   outputs without losing fields.
 
 No running server or GPU required.
@@ -104,9 +104,9 @@ class TestResponsesRequestTools:
         assert req.parallel_tool_calls is True
 
     def test_builtin_tool_type_passes_validation(self):
-        """Non-function built-in tools (web_search, file_search, mcp, ...) must
-        not raise at request validation so SDKs that default to them don't
-        fail on Studio; they are filtered out during translation."""
+        """Non-function built-in tools (web_search, file_search, mcp, ...)
+        must not raise at validation so SDKs that default to them don't
+        fail on Studio; they're filtered out during translation."""
         req = ResponsesRequest(
             input = "hi",
             tools = [{"type": "web_search_preview"}],
@@ -249,8 +249,8 @@ class TestToolChoiceTranslation:
         ) == {"type": "function", "function": {"name": "get_weather"}}
 
     def test_already_chat_nested_shape_passes_through(self):
-        """If a client happens to send the Chat Completions nested shape,
-        we don't double-wrap it."""
+        """A client sending the Chat Completions nested shape isn't
+        double-wrapped."""
         already_nested = {"type": "function", "function": {"name": "get_weather"}}
         assert _translate_responses_tool_choice_to_chat(already_nested) == already_nested
 
@@ -297,10 +297,10 @@ class TestNormaliseResponsesInputWithTools:
 
     def test_instructions_plus_developer_message_are_merged(self):
         """Codex CLI sends `instructions` (system prompt) AND a developer
-        message in `input`. Strict chat templates (harmony / gpt-oss, Qwen3,
-        ...) raise "System message must be at the beginning" when two
-        separate system-role messages appear, so we must emit exactly one
-        merged system message at the top.
+        message in `input`. Strict chat templates (harmony / gpt-oss,
+        Qwen3, ...) raise "System message must be at the beginning" on two
+        separate system-role messages, so we emit exactly one merged
+        system message at the top.
         """
         payload = ResponsesRequest(
             instructions = "Base instructions.",
@@ -314,14 +314,14 @@ class TestNormaliseResponsesInputWithTools:
         assert len(system_roles) == 1
         assert "Base instructions." in system_roles[0].content
         assert "Developer override." in system_roles[0].content
-        # System must be the very first message for strict templates.
+        # System must be the first message for strict templates.
         assert msgs[0].role == "system"
         assert msgs[1].role == "user"
 
     def test_developer_message_after_user_is_still_hoisted(self):
-        """Multi-turn conversations where a developer message appears after
-        user turns must still produce a single leading system message, not
-        a mid-conversation system that strict templates reject."""
+        """A developer message appearing after user turns must still
+        produce a single leading system message, not a mid-conversation
+        system that strict templates reject."""
         payload = ResponsesRequest(
             input = [
                 {"role": "user", "content": "Hello"},
@@ -486,8 +486,8 @@ class TestCodexStyleRequestShapes:
     """Regression tests for the request shapes OpenAI Codex CLI sends."""
 
     def test_assistant_replay_output_text_accepted(self):
-        """Codex replays prior assistant turns with `output_text` content.
-        Before, this triggered a 422 on every turn after the first."""
+        """Codex replays prior assistant turns with `output_text` content;
+        this used to 422 on every turn after the first."""
         req = ResponsesRequest(
             input = [
                 {"role": "user", "content": "Hi"},
@@ -514,7 +514,7 @@ class TestCodexStyleRequestShapes:
 
     def test_reasoning_item_accepted_as_unknown(self):
         """`reasoning` items replayed from prior o-series turns must not
-        fail validation — Codex preserves them in multi-turn."""
+        fail validation — Codex keeps them in multi-turn."""
         req = ResponsesRequest(
             input = [
                 {"role": "user", "content": "Hi"},
@@ -532,7 +532,7 @@ class TestCodexStyleRequestShapes:
 
     def test_unknown_content_part_type_accepted(self):
         """Unknown content-part types (e.g. future input_audio) validate as
-        ResponsesUnknownContentPart so the whole request doesn't 422."""
+        ResponsesUnknownContentPart so the request doesn't 422."""
         req = ResponsesRequest(
             input = [
                 {
@@ -596,15 +596,15 @@ class TestCodexStyleRequestShapes:
             ],
         )
         msgs = _normalise_responses_input(payload)
-        # Single leading merged system; no mid-conversation system.
+        # One leading merged system; no mid-conversation system.
         assert msgs[0].role == "system"
         assert sum(1 for m in msgs if m.role == "system") == 1
         assert "Base instructions." in msgs[0].content
         assert "Dev override." in msgs[0].content
 
         roles = [m.role for m in msgs[1:]]
-        # Reasoning item is dropped. Order: user, assistant(tool_calls),
-        # tool, assistant(text), user.
+        # Reasoning dropped. Order: user, assistant(tool_calls), tool,
+        # assistant(text), user.
         assert roles == ["user", "assistant", "tool", "assistant", "user"]
         assert msgs[2].tool_calls is not None
         assert msgs[3].role == "tool"
@@ -612,9 +612,9 @@ class TestCodexStyleRequestShapes:
         assert msgs[4].content == "It's 20°C."
 
     def test_single_output_text_part_flattens_to_string(self):
-        """ChatMessage assistant role prefers plain string content — tests
-        confirm we don't forward a single-part array that would otherwise
-        force legacy chat templates into multimodal handling."""
+        """ChatMessage assistant role prefers plain string content — we
+        don't forward a single-part array that would force legacy chat
+        templates into multimodal handling."""
         payload = ResponsesRequest(
             input = [
                 {
@@ -630,9 +630,9 @@ class TestCodexStyleRequestShapes:
 
 
 class TestTranslatedMessagesValidate:
-    """Verify that the messages produced by _normalise_responses_input
-    satisfy ChatMessage's role-shape validator so the downstream /v1/chat/
-    completions pass-through does not reject them."""
+    """Messages from _normalise_responses_input satisfy ChatMessage's
+    role-shape validator so the downstream /v1/chat/completions
+    pass-through doesn't reject them."""
 
     def test_round_trip_multi_turn(self):
         payload = ResponsesRequest(
@@ -654,6 +654,6 @@ class TestTranslatedMessagesValidate:
         )
         msgs = _normalise_responses_input(payload)
         for m in msgs:
-            # Constructing a fresh ChatMessage from the dump round-trips the
-            # role-shape validator — the key invariant for the passthrough.
+            # Building a fresh ChatMessage from the dump round-trips the
+            # role-shape validator — the passthrough's key invariant.
             ChatMessage(**m.model_dump(exclude_none = True))
diff --git a/studio/backend/tests/test_rocm_oom_guard.py b/studio/backend/tests/test_rocm_oom_guard.py
index d27ee83f1d..6b2c6aa84f 100644
--- a/studio/backend/tests/test_rocm_oom_guard.py
+++ b/studio/backend/tests/test_rocm_oom_guard.py
@@ -3,16 +3,16 @@
 
 """Unit tests for _rocm_classify_unified_memory (ROCm OOM-guard classifier).
 
-Covers the three classification paths:
+Three classification paths:
   Path 1 – canonical gcnArchName attribute present.
   Path 2 – gcnArchName absent, alternate-spelling attribute present.
   Path 3 – ALL arch attrs absent; falls back to device-name substring match.
 
-Regression for: Strix Halo (gfx1151) misclassified as discrete on AMD SDK /
-Radeon wheels that populate props.name = "Radeon 8060S Graphics" but do NOT
-set any gcnArchName attribute.  Without the 8060s/8050s name patterns the
-fallback returned is_unified=False, applying the 0.90 fraction instead of
-0.80 and leaving only ~12.8 GiB OS headroom on a 128 GiB unified-memory pool.
+Regression: Strix Halo (gfx1151) misclassified as discrete on AMD SDK / Radeon
+wheels that set props.name = "Radeon 8060S Graphics" but no gcnArchName attr.
+Without the 8060s/8050s name patterns the fallback returned is_unified=False,
+applying 0.90 instead of 0.80 and leaving only ~12.8 GiB OS headroom on a
+128 GiB unified-memory pool.
 """
 
 from __future__ import annotations
@@ -62,7 +62,7 @@ class TestCanonicalGcnArchName:
         assert is_unified is True
 
     def test_canonical_attr_wins_over_name(self) -> None:
-        """Arch attr takes priority; device name should be ignored."""
+        """Arch attr takes priority; device name is ignored."""
         # Discrete arch, but name looks like a unified SKU — arch must win.
         props = _props(gcnArchName = "gfx1100", name = "Radeon 890M")
         gcn, is_unified = _rocm_classify_unified_memory(props)
@@ -97,7 +97,7 @@ class TestAlternateSpellingFallback:
         assert is_unified is False
 
     def test_first_non_empty_attr_wins(self) -> None:
-        """When multiple alternate attrs are present the first non-empty one wins."""
+        """With multiple alternate attrs, the first non-empty one wins."""
         props = _props(gcn_arch_name = "gfx1151", arch_name = "gfx1100", name = "irrelevant")
         gcn, is_unified = _rocm_classify_unified_memory(props)
         assert gcn == "gfx1151"
@@ -147,7 +147,7 @@ class TestDeviceNameFallback:
             "Radeon RX 6900 XT",
             "Radeon Pro W7900",
             "AMD Instinct MI300X",
-            # Names that contain superficially similar substrings but are discrete
+            # Superficially similar substrings but discrete
             "Radeon RX 580",
             "Radeon VII",
         ],
@@ -161,7 +161,7 @@ class TestDeviceNameFallback:
         ), f"discrete device {device_name!r} should NOT be classified as unified-memory"
 
     def test_empty_name_returns_false(self) -> None:
-        """Completely absent name must not crash and must default to discrete."""
+        """Absent name must not crash and must default to discrete."""
         props = _props()  # no 'name' attr at all
         gcn, is_unified = _rocm_classify_unified_memory(props)
         assert gcn == ""
diff --git a/studio/backend/tests/test_safetensors_capability_advertise.py b/studio/backend/tests/test_safetensors_capability_advertise.py
index 5e3d2cc9d1..1e40f376f3 100644
--- a/studio/backend/tests/test_safetensors_capability_advertise.py
+++ b/studio/backend/tests/test_safetensors_capability_advertise.py
@@ -2,9 +2,8 @@
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
 """
-Capability advertisement contract: classifier honesty, worker→
-orchestrator IPC hop, and route-layer end-to-end. Pure helpers + fakes;
-no torch / transformers import.
+Capability advertisement contract: classifier honesty, worker→orchestrator
+IPC hop, route-layer end-to-end. Pure helpers + fakes; no torch/transformers.
 """
 
 from __future__ import annotations
@@ -116,7 +115,7 @@ def test_detect_safetensors_features_none_template_returns_all_false():
 
 
 def test_detect_safetensors_features_gptoss_disables_tools():
-    """gpt-oss Harmony: tools intentionally off even if template marks it."""
+    """gpt-oss Harmony: tools off even if template marks it."""
     from routes.inference import _detect_safetensors_features
 
     backend = MagicMock()
@@ -129,11 +128,10 @@ def test_detect_safetensors_features_gptoss_disables_tools():
     assert flags["supports_tools"] is False
 
 
-# Llama-3 / Mistral templates advertise tool handling but the model emits
-# tool calls in <|python_tag|> / [TOOL_CALLS] format -- not the
-#  /  / [TOOL_CALLS] format -- not the  / \n...``. Capture a faithful slice so the
-# classifier never silently regresses for this family.
+# Qwen3.5 family pins -- the live GGUF + safetensors templates from the
+# unsloth/Qwen3.5-0.8B(-GGUF) repos both wrap tool calls as
+# ``\n...``. Faithful slice so the classifier
+# never silently regresses for this family.
 
 QWEN35_TOOL_INSTRUCTION = (
     "{%- if tools %}\n"
@@ -234,7 +232,7 @@ QWEN35_TOOL_INSTRUCTION = (
 
 
 def test_detect_safetensors_features_qwen35_keeps_tools_on():
-    """unsloth/Qwen3.5-0.8B family must surface tools+reasoning enabled."""
+    """unsloth/Qwen3.5-0.8B family must surface tools+reasoning on."""
     from routes.inference import _detect_safetensors_features
 
     backend = SimpleNamespace(active_model_name = "unsloth/Qwen3.5-0.8B")
@@ -248,7 +246,7 @@ def test_detect_safetensors_features_qwen35_keeps_tools_on():
 
 
 def test_orchestrator_mirrors_chat_template_info_into_models_dict():
-    """Worker → orchestrator must copy chat_template_info verbatim."""
+    """Worker → orchestrator copies chat_template_info verbatim."""
     from core.inference.orchestrator import InferenceOrchestrator
 
     orch = InferenceOrchestrator.__new__(InferenceOrchestrator)
@@ -274,7 +272,7 @@ def test_orchestrator_mirrors_chat_template_info_into_models_dict():
         },
     }
 
-    # Replay orchestrator.load_model's mirror block verbatim.
+    # Replay orchestrator.load_model's mirror block.
     orch.active_model_name = model_info["identifier"]
     orch.models[orch.active_model_name] = {
         "is_vision": model_info.get("is_vision", False),
@@ -386,7 +384,7 @@ def test_worker_load_reply_payload_includes_chat_template_info():
 
 
 def test_worker_load_reply_payload_survives_missing_template():
-    """Tokenizer with no chat_template still produces a valid reply."""
+    """Tokenizer with no chat_template still yields a valid reply."""
 
     class _StubBackend:
         def __init__(self):
@@ -421,7 +419,7 @@ def test_worker_load_reply_payload_survives_missing_template():
 
 
 def test_route_layer_emits_supports_tools_true_for_qwen3_safetensors():
-    """End-to-end: Qwen3 safetensors flips supports_tools=True."""
+    """E2E: Qwen3 safetensors flips supports_tools=True."""
     from routes.inference import _detect_safetensors_features
 
     backend = SimpleNamespace(
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index ff5653c742..526ea2d19f 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -4,27 +4,26 @@
 """
 Tests for the safetensors agentic tool loop.
 
-Covers the shared ``tool_call_parser`` helpers and the cumulative-text
-state machine inside ``safetensors_agentic.run_safetensors_tool_loop``.
-The loop is exercised with hand-crafted fake single-turn generators so
-no model load is needed; the tests run in CI under a few seconds.
+Covers the shared ``tool_call_parser`` helpers and the cumulative-text state
+machine in ``safetensors_agentic.run_safetensors_tool_loop``. The loop runs
+against hand-crafted fake single-turn generators, so no model load is needed;
+the tests finish in CI within a few seconds.
 
-Edge cases under coverage:
+Edge cases covered:
 * Plain answers (no tool calls) flush full content.
 * Single ``{json}`` triggers the tool and re-enters.
 * Single ``...`` XML form triggers the same path.
 * Truncated unclosed ```` is still parsed.
 * Tool result is fed back as ``role=tool`` for the next iteration.
-* Bad JSON inside ```` does not raise and (when healed) is
-  routed as a ``{"query": ...}`` web search call.
-* Duplicate tool calls produce a synthetic "do not repeat" result the
-  second time.
+* Bad JSON inside ```` does not raise and (when healed) routes as a
+  ``{"query": ...}`` web search call.
+* Duplicate tool calls produce a synthetic "do not repeat" result the 2nd time.
 * ``__IMAGES__`` sentinel is stripped before the model sees the result.
-* Tool execution errors are tagged so the model gets a nudge but the
-  loop keeps streaming.
+* Tool execution errors are tagged so the model gets a nudge but the loop keeps
+  streaming.
 * Cancel is honoured between iterations.
-* ``max_tool_iterations`` cap is respected and a final-answer attempt
-  closes the stream cleanly.
+* ``max_tool_iterations`` cap is respected and a final-answer attempt closes the
+  stream cleanly.
 """
 
 import threading
@@ -64,7 +63,7 @@ class TestParser:
         assert "hello" in tc["function"]["arguments"]
 
     def test_json_tool_call_unclosed(self):
-        # No ; balanced-brace extractor must still close.
+        # No ; balanced-brace extractor must still close it.
         text = '{"name":"python","arguments":{"code":"print(1)"}}'
         result = parse_tool_calls_from_text(text)
         assert len(result) == 1
@@ -86,9 +85,9 @@ class TestParser:
         assert "ls -la" in result[0]["function"]["arguments"]
 
     def test_code_with_embedded_xml(self):
-        # A code parameter contains the literal . Must not
-        # truncate the value because the parser uses end-of-body as the
-        # only boundary for single-parameter calls.
+        # A code parameter contains the literal . Must not truncate
+        # the value: the parser uses end-of-body as the only boundary for
+        # single-parameter calls.
         text = (
             "html = ''\n"
             "print('hi')"
@@ -121,7 +120,7 @@ class TestParser:
     def test_bad_json_does_not_raise(self):
         text = "{not valid json}"
         result = parse_tool_calls_from_text(text)
-        # Bad JSON is silently dropped; caller can fall back to text.
+        # Bad JSON is dropped silently; caller can fall back to text.
         assert result == []
 
     def test_has_tool_signal(self):
@@ -147,7 +146,7 @@ class TestParser:
 
     def test_strip_markup_unclosed_final(self):
         text = "before {partial"
-        # With final=True the trailing run is dropped.
+        # final=True drops the trailing run.
         assert strip_tool_markup(text, final = True) == "before"
         # Without final=True the unclosed run is preserved.
         assert "partial" in strip_tool_markup(text)
@@ -220,8 +219,7 @@ def _make_loop(
 ):
     """Build a configured loop with a multi-turn fake generator.
 
-    ``turns`` is a list of chunk-lists; iteration N yields chunks from
-    ``turns[N]``.
+    ``turns`` is a list of chunk-lists; iteration N yields chunks from ``turns[N]``.
     """
     turn_iter = iter(turns)
 
@@ -260,7 +258,7 @@ class TestLoopBasic:
         contents = [e for e in events if e["type"] == "content"]
         statuses = [e for e in events if e["type"] == "status"]
         assert contents, "expected at least one content event"
-        # Final cumulative content should contain the answer.
+        # Final cumulative content must contain the answer.
         final_text = contents[-1]["text"]
         assert "Hello world!" in final_text
         assert statuses and statuses[-1]["text"] == ""
@@ -284,7 +282,7 @@ class TestLoopBasic:
 
         assert "tool_start" in kinds
         assert "tool_end" in kinds
-        # Tool was actually called with the parsed arguments.
+        # Tool was called with the parsed arguments.
         assert exec_fn.calls == [("web_search", {"query": "weather"})]
 
         tool_start = next(e for e in events if e["type"] == "tool_start")
@@ -402,8 +400,8 @@ class TestLoopBasic:
     def test_truncated_unclosed_tool_call(self):
         loop, exec_fn = _make_loop(
             turns = [
-                # No ; balanced-brace parser must still
-                # succeed because the JSON itself is balanced.
+                # No ; balanced-brace parser still succeeds because
+                # the JSON itself is balanced.
                 ['{"name":"web_search","arguments":{"query":"x"}}'],
                 ["done"],
             ],
@@ -413,14 +411,13 @@ class TestLoopBasic:
         assert exec_fn.calls == [("web_search", {"query": "x"})]
 
     def test_bad_json_healed_to_query(self):
-        # Tool call with non-JSON string arguments. With auto_heal_tool_calls
-        # the string is routed as {"query": ...}.
+        # Tool call with non-JSON string arguments. With auto_heal_tool_calls,
+        # the string routes as {"query": ...}.
         loop, exec_fn = _make_loop(
             turns = [
-                # JSON inside the tool call is well-formed; the
-                # ``arguments`` is a string that is not itself valid
-                # JSON for ``_coerce_arguments`` to parse, so the
-                # heal path runs.
+                # JSON inside the tool call is well-formed, but ``arguments`` is
+                # a string that ``_coerce_arguments`` cannot parse as JSON, so
+                # the heal path runs.
                 ['{"name":"web_search","arguments":"hello world"}'],
                 ["ok"],
             ],
@@ -433,9 +430,8 @@ class TestLoopBasic:
 
 class TestLoopBehaviour:
     def test_duplicate_tool_call_synthetic_result(self):
-        # Two identical successful calls in a row: the second is short-
-        # circuited with a "do not repeat" message and execute_tool is
-        # called only once.
+        # Two identical successful calls in a row: the second is short-circuited
+        # with a "do not repeat" message and execute_tool runs only once.
         loop, exec_fn = _make_loop(
             turns = [
                 ['{"name":"web_search","arguments":{"query":"x"}}'],
@@ -452,9 +448,9 @@ class TestLoopBehaviour:
         assert "do not repeat" in tool_end_events[1]["result"].lower()
 
     def test_image_sentinel_stripped_from_model_feed(self):
-        # The tool result has a frontend image sentinel that should be
-        # stripped before being fed back into the next turn, BUT the
-        # tool_end event still carries the raw result for the UI.
+        # The tool result's frontend image sentinel must be stripped before
+        # being fed into the next turn, BUT the tool_end event still carries the
+        # raw result for the UI.
         loop, exec_fn = _make_loop(
             turns = [
                 ['{"name":"python","arguments":{"code":"plot()"}}'],
@@ -490,7 +486,7 @@ class TestLoopBehaviour:
                 auto_heal_tool_calls = True,
             )
         )
-        # Model's second turn must not see "__IMAGES__".
+        # The model's second turn must not see "__IMAGES__".
         assert len(captured) >= 2
         tool_msgs = [m for m in captured[1] if m.get("role") == "tool"]
         assert tool_msgs, "no tool message reached the model"
@@ -539,7 +535,7 @@ class TestLoopBehaviour:
         events = _collect_events(loop)
         tool_end = next(e for e in events if e["type"] == "tool_end")
         assert tool_end["result"].startswith("Error")
-        # The loop must still produce a content event after the failure.
+        # The loop must still emit a content event after the failure.
         contents = [e for e in events if e["type"] == "content"]
         assert contents
 
@@ -560,8 +556,8 @@ class TestLoopControl:
     def test_cancel_event_breaks_loop(self):
         cancel = threading.Event()
         cancel.set()
-        # Even with a fake stream that emits tool calls, the loop must
-        # bail before invoking execute_tool when cancel is set.
+        # Even with a fake stream that emits tool calls, the loop must bail
+        # before invoking execute_tool when cancel is set.
         exec_fn = FakeExecuteTool([])
         events = list(
             run_safetensors_tool_loop(
@@ -578,8 +574,8 @@ class TestLoopControl:
         assert exec_fn.calls == []
 
     def test_max_iterations_caps_loop(self):
-        # The loop should stop after max_tool_iterations even if the
-        # model keeps asking for tools, then emit a final-attempt round.
+        # The loop stops after max_tool_iterations even if the model keeps
+        # asking for tools, then emits a final-attempt round.
         loop, exec_fn = _make_loop(
             turns = [
                 # : tool call (executes once)
@@ -592,13 +588,13 @@ class TestLoopControl:
         )
         events = _collect_events(loop)
         contents = [e for e in events if e["type"] == "content"]
-        # Final content must include the final answer.
+        # Final content must contain the final answer.
         assert contents and "final answer" in contents[-1]["text"]
 
 
 class TestStatusFormatting:
     def test_status_for_known_tools(self):
-        # Use the private helper directly to verify status formatting.
+        # Call the private helper directly to verify status formatting.
         assert (
             safetensors_agentic._status_for_tool("web_search", {"query": "abc"}) == "Searching: abc"
         )
@@ -617,10 +613,10 @@ class TestStatusFormatting:
 
 class TestProseMentioningToolCall:
     def test_assistant_prose_with_literal_tool_call_text_survives(self):
-        # Regression: if the assistant text legitimately mentions
-        # ```` as a literal string and the parser finds no
-        # actual call, the loop must surface the full content instead
-        # of silently stripping everything past the literal marker.
+        # Regression: if assistant text legitimately mentions ```` as
+        # a literal string and the parser finds no actual call, the loop must
+        # surface the full content instead of stripping everything past the
+        # literal marker.
         loop, exec_fn = _make_loop(
             turns = [
                 # : a real tool call so the loop moves to
@@ -640,9 +636,9 @@ class TestProseMentioningToolCall:
         ), f"prose mentioning  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 ```` string.
-        # The loop must only parse the MODEL output, not the tool
-        # result, so we should see exactly one call.
+        # Tool result text contains the literal ```` string. The loop
+        # must parse only the MODEL output, not the tool result, so we see
+        # exactly one call.
         loop, exec_fn = _make_loop(
             turns = [
                 ['{"name":"web_search","arguments":{"query":"x"}}'],
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 92fee2e8e5..1841d084b9 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -117,7 +117,7 @@ class TestUntrustedHostBlock:
         )
 
     def test_dynamic_url_not_statically_blocked(self):
-        # Static AST cannot resolve runtime URLs; bash blocklist is the fallback.
+        # Static AST can't resolve runtime URLs; bash blocklist is the fallback.
         _ok('import requests; url = "https://example.com/"; requests.get(url)')
 
 
@@ -225,8 +225,8 @@ class TestUploadDenylist:
 class TestSandboxEnvIsolation:
     """The sandbox subprocess env is built from a whitelist, not by stripping.
 
-    Confirm every credential-shaped parent var is absent regardless of how the
-    operator's process is configured. Covers Linux/macOS/WSL/Windows shapes.
+    Confirm every credential-shaped parent var is absent regardless of the
+    operator's process config. Covers Linux/macOS/WSL/Windows shapes.
     """
 
     _SECRET_KEYS = (
@@ -313,8 +313,8 @@ class TestSandboxEnvIsolation:
     def test_term_is_dumb(self, tmp_path):
         from core.inference.tools import _build_safe_env
 
-        # Prevents the sandbox from re-using the operator's TERM (e.g. xterm-256color)
-        # which could trigger color-escape parsing in downstream tools.
+        # Avoid re-using the operator's TERM (e.g. xterm-256color) that
+        # could trigger color-escape parsing in downstream tools.
         env = _build_safe_env(str(tmp_path))
         assert env["TERM"] == "dumb"
 
@@ -348,9 +348,9 @@ class TestMaxBodyDefault:
 class TestBashBlocklistPosition:
     """The blocklist must fire at command position only.
 
-    Pre-fix the per-token loop fired on any token, so `grep -r curl .`
+    Pre-fix, the per-token loop fired on any token, so `grep -r curl .`
     and `echo source` were rejected. The position-anchored regex plus a
-    shlex-aware command-position-only token check is sufficient.
+    shlex-aware command-position-only token check fixes this.
     """
 
     @staticmethod
@@ -366,8 +366,7 @@ class TestBashBlocklistPosition:
         assert self._find()("echo source the data") == set()
 
     def test_cat_with_word_source_allowed(self):
-        # The 'source' word is an argument to echo; not blocked.
-        # `echo` itself isn't blocked. Only legit allowed tokens here.
+        # 'source' is an argument to echo, and echo isn't blocked either.
         assert self._find()("cat README.md && echo source") == set()
         assert "source" not in self._find()("cat README.md && echo source")
         assert "echo" not in self._find()("cat README.md && echo source")
@@ -397,14 +396,14 @@ class TestBashBlocklistPosition:
         assert "wget" in self._find()("cd /tmp && wget https://bad")
 
     def test_split_quotes_obfuscation_blocked(self):
-        # shlex collapses 'r''m' -> 'rm' as a single token at command position.
+        # shlex collapses 'r''m' -> 'rm' at command position.
         assert "rm" in self._find()("r''m -rf /")
 
     def test_path_prefixed_command_blocked(self):
         assert "sudo" in self._find()("/usr/bin/sudo whoami")
 
     def test_nested_bash_c_blocked(self):
-        # Recursion into the nested command string still catches command-position curl.
+        # Recursion into the nested command string catches command-position curl.
         assert "curl" in self._find()("bash -c 'curl https://x'")
 
     def test_subshell_command_blocked(self):
@@ -465,9 +464,9 @@ class TestBashBlocklistPosition:
 
 
 class TestHfUploadImportGate:
-    """HfApi-style upload-method blocking should require an HF import in
-    scope; otherwise paramiko / boto3 / internal SDKs with the same
-    method names hit a false positive."""
+    """HfApi-style upload-method blocking requires an HF import in scope;
+    otherwise paramiko / boto3 / internal SDKs with the same method names
+    false-positive."""
 
     def test_paramiko_upload_file_allowed_without_hf_import(self):
         _ok("import paramiko; sftp=None; sftp.upload_file('a','b')")
@@ -476,14 +475,14 @@ class TestHfUploadImportGate:
         _ok("client=None; client.create_commit(Repo='x')")
 
     def test_hf_api_upload_safe_path_allowed(self):
-        # Sandbox-local relative path -- the call shape we want to permit.
+        # Sandbox-local relative path -- the permitted call shape.
         _ok("from huggingface_hub import HfApi; HfApi().upload_file('a','b','c')")
 
     def test_hf_upload_file_fq_safe_path_allowed(self):
         _ok("import huggingface_hub; huggingface_hub.upload_file('a','b','c')")
 
     def test_dynamic_builtin_import_safe_path_allowed(self):
-        # `__import__('huggingface_hub')` puts HF in scope; relative-literal path is safe.
+        # `__import__('huggingface_hub')` puts HF in scope; relative literal is safe.
         _ok("hf=__import__('huggingface_hub'); hf.HfApi().upload_file('a','b','c')")
 
     def test_dynamic_importlib_safe_path_allowed(self):
@@ -499,8 +498,8 @@ class TestHfUploadImportGate:
         )
 
     def test_hf_bare_name_upload_safe_path_allowed(self):
-        # `from huggingface_hub import upload_file` then bare `upload_file(...)`
-        # with a sandbox-local relative-path literal is allowed.
+        # Bare `upload_file(...)` (imported from huggingface_hub) with a
+        # sandbox-local relative-path literal is allowed.
         _ok(
             "from huggingface_hub import upload_file;"
             " upload_file(path_or_fileobj='x', path_in_repo='x', repo_id='r')"
@@ -519,15 +518,15 @@ class TestHfUploadImportGate:
         )
 
     def test_bare_name_upload_file_without_hf_import_allowed(self):
-        # No HF import -- local helper named upload_file should pass.
+        # No HF import -- local helper named upload_file passes.
         _ok("def upload_file(*a, **k):\n    pass\nupload_file('x', 'y', 'z')")
 
 
 class TestHfUploadSandboxLocalPaths:
-    """The HF upload gate must only allow uploads of files that already live in
-    the sandbox workdir. Absolute paths, `..` traversal, home expansion, and
-    Windows drive letters are rejected because the LLM can use them to lift
-    secrets from outside the sandbox."""
+    """The HF upload gate allows only files already in the sandbox workdir.
+    Absolute paths, `..` traversal, home expansion, and Windows drive
+    letters are rejected — the LLM could use them to lift secrets from
+    outside the sandbox."""
 
     def test_relative_literal_allowed(self):
         _ok(
@@ -621,8 +620,8 @@ class TestHfUploadSandboxLocalPaths:
         )
 
     def test_dynamic_variable_path_blocked(self):
-        # A non-literal expression could resolve to any path at runtime;
-        # the static checker cannot prove safety, so block.
+        # A non-literal expr could resolve to any path at runtime; the
+        # static checker can't prove safety, so block.
         _blocked(
             "import huggingface_hub, os\n"
             "p = os.path.join('outputs', 'x.bin')\n"
@@ -674,11 +673,11 @@ class TestHfUploadSandboxLocalPaths:
 
 
 class TestHfUploadEnvAndSecretLeakBlock:
-    """The HF upload gate must reject any positional / keyword arg sourced from
-    `os.environ` / `os.getenv` / subprocess env reads. Even though
-    `_build_safe_env` strips HF_TOKEN/WANDB/AWS upfront for the sandbox shell,
-    a Python script can still reach the parent process env if it bypasses the
-    safe-env wrapper at the source -- so block statically."""
+    """The HF upload gate rejects any positional / keyword arg sourced from
+    `os.environ` / `os.getenv` / subprocess env reads. `_build_safe_env`
+    strips HF_TOKEN/WANDB/AWS for the sandbox shell, but a Python script
+    can still reach the parent env if it bypasses the safe-env wrapper at
+    the source -- so block statically."""
 
     def test_path_from_os_environ_subscript_blocked(self):
         _blocked(
@@ -756,7 +755,7 @@ class TestHfUploadEnvAndSecretLeakBlock:
         )
 
     def test_env_dict_unpacked_via_environ_attr_blocked(self):
-        # `os.environ` as a bare reference (passed somewhere it gets serialized).
+        # Bare `os.environ` reference (passed somewhere it gets serialized).
         _blocked(
             "import huggingface_hub, os\n"
             "huggingface_hub.upload_file(path_or_fileobj=str(os.environ),"
@@ -765,8 +764,8 @@ class TestHfUploadEnvAndSecretLeakBlock:
         )
 
     def test_repo_id_from_env_also_blocked(self):
-        # Even non-path args must not source env vars -- an attacker could
-        # encode secrets in repo_id or path_in_repo.
+        # Non-path args must not source env vars either -- an attacker
+        # could encode secrets in repo_id or path_in_repo.
         _blocked(
             "import huggingface_hub, os\n"
             'huggingface_hub.upload_file(path_or_fileobj="x.bin",'
diff --git a/studio/backend/tests/test_studio_api.py b/studio/backend/tests/test_studio_api.py
index 70a103a2f8..c40729d9a8 100644
--- a/studio/backend/tests/test_studio_api.py
+++ b/studio/backend/tests/test_studio_api.py
@@ -4,9 +4,9 @@
 """
 End-to-end tests for Unsloth Studio's HTTP API surface.
 
-Covers the OpenAI-compatible and Anthropic-compatible endpoints exposed
-by the server that ``unsloth studio run`` boots, plus API key
-authentication and the CLI's ``--help`` output:
+Covers the OpenAI- and Anthropic-compatible endpoints exposed by the
+server that ``unsloth studio run`` boots, plus API key authentication and
+the CLI's ``--help`` output:
 
     1. curl -- basic chat completions (non-streaming)
     2. curl -- streaming chat completions
@@ -38,14 +38,14 @@ Usage:
     export UNSLOTH_E2E_API_KEY=sk-unsloth-...   # from the server banner
     pytest tests/test_studio_api.py -v
 
-    # Pytest mode, fixture-managed server — pytest launches and tears
-    # down the server itself. One-shot verification, CI-friendly.
+    # Pytest mode, fixture-managed server — pytest launches and tears down
+    # the server itself. One-shot verification, CI-friendly.
     pytest tests/test_studio_api.py -v \\
         --unsloth-model unsloth/Qwen3-1.7B-GGUF \\
         --unsloth-gguf-variant UD-Q4_K_XL
 
-The ``base_url`` / ``api_key`` parameters on the test functions resolve
-via the ``studio_server`` session fixture in ``conftest.py``.
+The ``base_url`` / ``api_key`` parameters on the test functions resolve via
+the ``studio_server`` session fixture in ``conftest.py``.
 
 Requires a GPU and ~2 GB of disk for the GGUF download.
 """
@@ -233,10 +233,10 @@ def test_openai_sdk(base_url: str, api_key: str):
 def test_curl_with_tools(base_url: str, api_key: str):
     """Example 4: chat completion with tool calling enabled.
 
-    Note: when ``enable_tools`` is set the server always returns SSE
-    streaming regardless of the ``stream`` flag, so we parse SSE chunks.
-    The model may or may not produce visible content -- tool orchestration
-    can intercept the response -- so we only assert the endpoint succeeds.
+    When ``enable_tools`` is set the server always returns SSE streaming
+    regardless of the ``stream`` flag, so we parse SSE chunks. The model may
+    not produce visible content (tool orchestration can intercept the
+    response), so we only assert the endpoint succeeds.
     """
     status, chunks = _stream_http(
         f"{base_url}/v1/chat/completions",
@@ -268,16 +268,16 @@ def test_curl_with_tools(base_url: str, api_key: str):
 # ── Standard OpenAI function-calling pass-through tests ─────────────
 #
 # Regression coverage for unslothai/unsloth#4999: Studio's
-# /v1/chat/completions used to silently strip standard OpenAI `tools`
-# and `tool_choice` fields, so clients (opencode, Claude Code, Cursor,
-# Continue, ...) could never get structured tool_calls back. These
-# tests exercise the client-side pass-through path that forwards those
-# fields to llama-server verbatim.
+# /v1/chat/completions used to silently strip standard OpenAI `tools` and
+# `tool_choice` fields, so clients (opencode, Claude Code, Cursor,
+# Continue, ...) never got structured tool_calls back. These tests exercise
+# the client-side pass-through path that forwards those fields to
+# llama-server verbatim.
 #
-# They require a tool-capable GGUF (``supports_tools=True`` — e.g.
-# Qwen3, Qwen2.5-Coder, Llama-3.1-Instruct). The default test model
-# ``unsloth/Qwen3-1.7B-GGUF`` advertises tool support via its chat
-# template metadata.
+# They require a tool-capable GGUF (``supports_tools=True`` — e.g. Qwen3,
+# Qwen2.5-Coder, Llama-3.1-Instruct). The default test model
+# ``unsloth/Qwen3-1.7B-GGUF`` advertises tool support via its chat template
+# metadata.
 
 _WEATHER_TOOL = {
     "type": "function",
@@ -301,9 +301,9 @@ _WEATHER_TOOL = {
 def _collect_streamed_tool_calls(chunks: list[dict]) -> list[dict]:
     """Reassemble OpenAI streaming delta.tool_calls into full tool calls.
 
-    OpenAI streams partial tool calls across chunks — the first chunk for
-    a given index carries ``id`` + ``function.name``, and subsequent
-    chunks append fragments to ``function.arguments``.
+    OpenAI streams partial tool calls across chunks — the first chunk for a
+    given index carries ``id`` + ``function.name``, and later chunks append
+    fragments to ``function.arguments``.
     """
     by_index: dict[int, dict] = {}
     for c in chunks:
@@ -346,8 +346,8 @@ def _final_finish_reason(chunks: list[dict]) -> str | None:
 def test_openai_tools_nonstream(base_url: str, api_key: str):
     """Standard OpenAI function calling, non-streaming, tool_choice='required'.
 
-    Regression: before the fix, Studio silently stripped `tools` and the
-    model returned plain text with finish_reason='stop'. After the fix,
+    Regression: before the fix, Studio stripped `tools` and the model
+    returned plain text with finish_reason='stop'. After the fix,
     llama-server's response is forwarded verbatim so the client sees
     finish_reason='tool_calls' with a structured tool_calls array and
     non-zero usage.prompt_tokens.
@@ -428,9 +428,9 @@ def test_openai_tools_multiturn(base_url: str, api_key: str):
     messages and assistant messages carrying tool_calls are accepted.
 
     Regression: before the fix, ChatMessage.role was restricted to
-    {system,user,assistant} and rejected role='tool' at the Pydantic
-    validation stage. This test sends a full round trip so the model
-    receives the simulated tool result and responds with final text.
+    {system,user,assistant} and rejected role='tool' at Pydantic
+    validation. This test sends a full round trip so the model receives the
+    simulated tool result and responds with final text.
     """
     status, text = _http(
         "POST",
@@ -467,7 +467,7 @@ def test_openai_tools_multiturn(base_url: str, api_key: str):
     assert status == 200, f"Expected 200, got {status}: {text[:500]}"
     data = json.loads(text)
     msg = data["choices"][0]["message"]
-    # The model should respond with text now that it has the tool result
+    # The model should respond with text now it has the tool result
     content = msg.get("content") or ""
     assert len(content) > 0 or msg.get(
         "tool_calls"
@@ -701,9 +701,9 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
     """Anthropic Messages API: ``tool_choice: {"type": "any"}`` must be
     honored (forwarded as OpenAI ``tool_choice: "required"`` to
     llama-server). Regression for the secondary fix bundled with #4999 —
-    previously this field was accepted on the request model but silently
-    dropped with a warning log, so the model was free to answer from
-    memory instead of using the tool.
+    previously this field was accepted on the request model but dropped with
+    a warning log, so the model could answer from memory instead of using
+    the tool.
     """
     status, events = _stream_anthropic_http(
         f"{base_url}/v1/messages",
@@ -711,7 +711,7 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
             "model": "default",
             "max_tokens": 256,
             "messages": [
-                # A question the model could easily answer from memory if
+                # A question the model could answer from memory if
                 # tool_choice were not enforced.
                 {
                     "role": "user",
@@ -740,7 +740,7 @@ def test_anthropic_tool_choice_any(base_url: str, api_key: str):
     assert status == 200, f"Expected 200, got {status}"
     assert len(events) > 0, "No SSE events received"
 
-    # With tool_choice=any, stop_reason must be tool_use (not end_turn)
+    # With tool_choice=any, stop_reason must be tool_use, not end_turn
     stop_reason = None
     for etype, data in events:
         if etype == "message_delta":
@@ -870,7 +870,7 @@ def main():
             failed += 1
             print(f"  ERROR {fn.__name__}: {type(exc).__name__}: {exc}")
 
-    # ── 1. Test --help (no server needed) ────────────────────────────
+    # ── 1. --help (no server needed) ────────────────────────────
     print("\n[1/16] Testing --help output")
     run_test(test_help_output)
 
diff --git a/studio/backend/tests/test_studio_train_validation.py b/studio/backend/tests/test_studio_train_validation.py
index 6df491610b..ed33c07689 100644
--- a/studio/backend/tests/test_studio_train_validation.py
+++ b/studio/backend/tests/test_studio_train_validation.py
@@ -24,7 +24,7 @@ from models.training import (
 
 
 def _check_field(field_name: str, value):
-    """Run the field validator without constructing a full TrainingStartRequest."""
+    """Run the field validator without building a full TrainingStartRequest."""
     from models.training import TrainingStartRequest
 
     schema_field = TrainingStartRequest.model_fields[field_name]
@@ -87,7 +87,7 @@ class TestVisionImageSizeCap:
 
     @pytest.mark.parametrize("value", [True, False])
     def test_bool_error_says_integer_not_range(self, value):
-        # Regression guard: bools must say "integer or null", not "in [256, 2048]".
+        # Regression guard: bools say "integer or null", not "in [256, 2048]".
         with pytest.raises(ValidationError) as exc:
             _check_field("vision_image_size", value)
         assert "integer or null" in str(exc.value)
@@ -95,7 +95,7 @@ class TestVisionImageSizeCap:
     @pytest.mark.parametrize("value", ["++512", "--256", "+-+512", "+", "-"])
     def test_multi_sign_string_says_integer_not_raw(self, value):
         # Regression guard: multi-sign strings must not leak int()'s raw
-        # "invalid literal" message; precise contract is "integer or null".
+        # "invalid literal" message; contract is "integer or null".
         with pytest.raises(ValidationError) as exc:
             _check_field("vision_image_size", value)
         assert "integer or null" in str(exc.value)
diff --git a/studio/backend/tests/test_tool_policy_gates.py b/studio/backend/tests/test_tool_policy_gates.py
index 01f6bbbc3f..fad121a4a1 100644
--- a/studio/backend/tests/test_tool_policy_gates.py
+++ b/studio/backend/tests/test_tool_policy_gates.py
@@ -2,8 +2,8 @@
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
 
 """
-Tests for `_effective_enable_tools` -- the helper that folds the
-process-level `tool_policy` over a request's `enable_tools` field.
+Tests for `_effective_enable_tools` -- folds the process-level `tool_policy`
+over a request's `enable_tools` field.
 
 Truth table (policy x payload.enable_tools -> effective):
   policy=None  + payload=None  -> None
diff --git a/studio/backend/tests/test_tool_xml_strip.py b/studio/backend/tests/test_tool_xml_strip.py
index 857302d543..6cc01f2595 100644
--- a/studio/backend/tests/test_tool_xml_strip.py
+++ b/studio/backend/tests/test_tool_xml_strip.py
@@ -1,9 +1,9 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""Tests for `_TOOL_XML_RE` (routes/inference.py) -- strips tool-call
-XML that leaks past the speculative buffer in core/inference/llama_cpp.py
-when the open/close pair is split across the visible/DRAIN boundary.
+"""Tests for `_TOOL_XML_RE` (routes/inference.py) -- strips tool-call XML that
+leaks past the speculative buffer in core/inference/llama_cpp.py when the
+open/close pair is split across the visible/DRAIN boundary.
 """
 
 from __future__ import annotations
@@ -134,7 +134,7 @@ def test_strips_tail_only_parameter_orphan_no_trailing_ws():
 
 
 def test_preserves_mid_string_parameter_in_code_sample():
-    # Tail-anchor on `` is required so doc/example prose survives.
+    # Tail-anchor on `` so doc/example prose survives.
     text = (
         "Here is the Qwen tool-call format:\n"
         "```xml\n"
@@ -207,8 +207,8 @@ def test_real_world_sweep_leaks_get_stripped(leak):
 # ── Real-world tail-only  from gdpval sweep ──────────
 
 
-# All end-anchored: outer  truncated by EOS,
-# inner  open DRAINED, leaving bare  tail.
+# All end-anchored: outer  truncated by EOS, inner
+#  open DRAINED, leaving bare  tail.
 GDPVAL_PARAMETER_LEAKS = [
     # Qwen3.5-27B Q8_0 / worldbank s00
     "the page contains image data and the text is not readable.\n\n\n",
diff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.py
index edc47c705e..5b7b70eefe 100644
--- a/studio/backend/tests/test_training_worker_flash_attn.py
+++ b/studio/backend/tests/test_training_worker_flash_attn.py
@@ -221,7 +221,7 @@ def test_mamba_ssm_path_preserves_wheel_first_install_args(monkeypatch):
 
 
 def _force_missing_fla_imports(monkeypatch):
-    """Make fla.modules / fla.ops.gated_delta_rule imports raise ImportError."""
+    """Force fla.modules / fla.ops imports to raise ImportError."""
     real_import = builtins.__import__
 
     def fake_import(name, *a, **kw):
@@ -267,8 +267,8 @@ def test_flash_linear_attention_skips_for_unrelated_models(monkeypatch):
 
 
 def test_flash_linear_attention_skips_for_ssm_only_models(monkeypatch):
-    # Nemotron-H / Falcon-H1 / Granite-H / LFM2 take the mamba_ssm path
-    # and never call FLA's gated_delta_rule kernels.
+    # Nemotron-H / Falcon-H1 / Granite-H / LFM2 take the mamba_ssm path,
+    # never FLA's gated_delta_rule kernels.
     run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
     monkeypatch.setattr(worker._sp, "run", run_mock)
 
@@ -289,7 +289,7 @@ def test_flash_linear_attention_matches_full_qwen3_family(monkeypatch):
     monkeypatch.setattr(worker._sp, "run", run_mock)
     _force_missing_fla_imports(monkeypatch)
     monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
-    # Hermetic discovery: pretend installed transformers ships all the Qwen GDN families.
+    # Hermetic discovery: pretend transformers ships all Qwen GDN families.
     monkeypatch.setattr(
         worker,
         "_discover_fla_model_types",
@@ -370,9 +370,9 @@ def test_flash_linear_attention_install_includes_einops(monkeypatch):
 
     args = run_mock.call_args[0][0]
     assert "--no-deps" in args
-    # einops is declared by fla-core; packaging and triton are pulled in
-    # because fla/utils.py imports them at module load but neither is
-    # declared in fla-core's METADATA (an upstream FLA gap).
+    # einops is declared by fla-core; packaging and triton are added
+    # because fla/utils.py imports them at load but neither is in
+    # fla-core's METADATA (an upstream FLA gap).
     assert "einops" in args
     assert "packaging" in args
     assert "triton" in args
@@ -389,8 +389,8 @@ def test_flash_linear_attention_logs_post_install_import_failure(monkeypatch):
 
     def fake_importable():
         import_calls["count"] += 1
-        # First call (pre-install probe) -> False so we attempt install.
-        # Second call (post-install verify) -> still False.
+        # Pre-install probe -> False (attempt install); post-install
+        # verify -> still False.
         return False
 
     monkeypatch.setattr(worker, "_flash_linear_attention_importable", fake_importable)
@@ -433,13 +433,13 @@ def test_tilelang_backend_pins_only_binary(monkeypatch):
     run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
     monkeypatch.setattr(worker._sp, "run", run_mock)
     monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
-    # Need to bypass the post-install probe too.
+    # Bypass the post-install probe too.
     probe_calls = {"count": 0}
 
     def fake_probe():
         probe_calls["count"] += 1
-        # First probe (pre-install): False so install runs.
-        # Second probe (post-install): True so success branch taken.
+        # Pre-install probe: False (install runs); post-install: True
+        # (success branch taken).
         return probe_calls["count"] > 1
 
     monkeypatch.setattr(worker, "_tilelang_importable", fake_probe)
@@ -492,13 +492,13 @@ def test_tilelang_backend_reinstalls_when_tvm_ffi_is_broken(monkeypatch):
     """Repair path issues TWO pip calls:
 
     Call 1 (repair): `--force-reinstall --no-deps apache-tvm-ffi==0.1.9`
-      — surgically downgrades the broken package only. `--no-deps` here
-      is REQUIRED to prevent --force-reinstall from cascading through
-      apache-tvm-ffi's dep graph and replacing torch / the CUDA stack.
+      — downgrades only the broken package. `--no-deps` is REQUIRED so
+      --force-reinstall doesn't cascade through apache-tvm-ffi's dep
+      graph and replace torch / the CUDA stack.
 
     Call 2 (install): plain `apache-tvm-ffi==0.1.9 tilelang==0.1.8`
       — resolves missing transitive deps (z3-solver, ml-dtypes) without
-      --force-reinstall, so it never replaces already-correct packages.
+      --force-reinstall, so it never replaces correct packages.
     """
     monkeypatch.delenv(worker._TILELANG_SKIP_ENV, raising = False)
     monkeypatch.setattr(worker.shutil, "which", lambda name: "/usr/bin/uv")
@@ -515,14 +515,14 @@ def test_tilelang_backend_reinstalls_when_tvm_ffi_is_broken(monkeypatch):
     assert run_mock.call_count == 2
     repair_args, install_args = (call[0][0] for call in run_mock.call_args_list)
 
-    # Repair: --force-reinstall --no-deps, apache-tvm-ffi ONLY (no tilelang).
+    # Repair: --force-reinstall --no-deps, apache-tvm-ffi ONLY.
     assert "--force-reinstall" in repair_args
     assert "--no-deps" in repair_args, "Repair MUST use --no-deps to avoid replacing torch / CUDA"
     assert "--only-binary=:all:" in repair_args
     assert f"apache-tvm-ffi=={worker._APACHE_TVM_FFI_PACKAGE_VERSION}" in repair_args
     assert all("tilelang" not in a for a in repair_args), "Repair MUST only touch apache-tvm-ffi"
 
-    # Install: regular dep-resolving install, NO --force-reinstall.
+    # Install: regular dep-resolving install, no --force-reinstall.
     assert "--force-reinstall" not in install_args
     assert "--no-deps" not in install_args
     assert "--only-binary=:all:" in install_args
@@ -573,7 +573,7 @@ def test_tilelang_backend_swallows_install_timeout(monkeypatch):
     statuses: list[str] = []
     monkeypatch.setattr(worker, "_send_status", lambda queue, msg: statuses.append(msg))
 
-    # Should not raise.
+    # Must not raise.
     worker._ensure_tilelang_backend(
         event_queue = [],
         model_name = "unsloth/Qwen3.5-2B",
@@ -588,7 +588,7 @@ def test_tilelang_backend_skipped_for_ssm_models(monkeypatch):
     monkeypatch.setattr(worker._sp, "run", run_mock)
 
     # Nemotron-H / Falcon-H1 / Granite-H take the mamba_ssm path, not FLA's
-    # gated_delta_rule -> tilelang has no effect on them.
+    # gated_delta_rule -> tilelang doesn't affect them.
     for name in (
         "tiiuae/Falcon-H1-0.5B-Instruct",
         "nvidia/Nemotron-H-8B-Base",
@@ -635,25 +635,24 @@ def test_tilelang_backend_swallows_install_failure(monkeypatch):
 
 # ───────────────────────────────────────────────────────────────────
 # Runtime hook on `is_flash_linear_attention_available` /
-# `is_causal_conv1d_available`. These are the primary gate in
-# normal operation; the substring tests above cover the
+# `is_causal_conv1d_available` — the primary gate in normal operation.
+# The substring tests above cover the
 # UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 fallback.
 # ───────────────────────────────────────────────────────────────────
 
 
 class _FakeQueue(list):
-    """List with `.put` so worker._send_status can send into it during tests."""
+    """List with `.put` so worker._send_status can send into it in tests."""
 
     def put(self, item):
         self.append(item)
 
 
 def _make_fake_gate(initial_return: bool):
-    """Build a callable that mimics transformers' lru_cache-decorated gates.
+    """Callable mimicking transformers' lru_cache-decorated gates.
 
-    Tracks call count and exposes a `cache_clear` attribute. The return
-    value can be flipped to mimic install-then-True behaviour by setting
-    `.next_return`.
+    Tracks call count and exposes `cache_clear`. Flip `.next_return` to
+    mimic install-then-True behaviour.
     """
 
     class Gate:
@@ -707,7 +706,7 @@ def test_hook_installs_when_gate_returns_false(monkeypatch):
 
     from transformers.utils import import_utils as _iu
 
-    # Both gates are now wrapped. Call them — the hook should drive the install.
+    # Both gates wrapped; calling them should drive the install.
     assert _iu.is_flash_linear_attention_available() is True
     fla_install.assert_called_once()
     tile_install.assert_called_once()
@@ -716,9 +715,9 @@ def test_hook_installs_when_gate_returns_false(monkeypatch):
 
 
 def test_hook_skips_install_when_gate_already_true(monkeypatch):
-    """When both gates are already True AND tilelang is healthy, the hook
-    must do zero install work. (Tilelang repair on the already-True path
-    is covered by test_hook_runs_tilelang_repair_when_fla_already_true.)
+    """Both gates already True AND tilelang healthy -> zero install work.
+    (Tilelang repair on the already-True path is covered by
+    test_hook_runs_tilelang_repair_when_fla_already_true.)
     """
     fla_gate = _make_fake_gate(initial_return = True)
     conv_gate = _make_fake_gate(initial_return = True)
@@ -730,9 +729,8 @@ def test_hook_skips_install_when_gate_already_true(monkeypatch):
     monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", fla_install)
     monkeypatch.setattr(worker, "_ensure_tilelang_backend_unconditional", tile_install)
     monkeypatch.setattr(worker, "_install_package_wheel_first", conv_install)
-    # Tilelang healthy so the post_available path is a no-op (otherwise
-    # it would call tile_install, which is correct behaviour but
-    # outside the scope of this test).
+    # Tilelang healthy -> post_available path is a no-op (otherwise it
+    # would call tile_install, correct but out of scope here).
     monkeypatch.setattr(worker, "_tilelang_importable", lambda: True)
     monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.9")
     monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
@@ -776,7 +774,7 @@ def test_hook_idempotent_on_repeat_call(monkeypatch):
 
     # First call: hook fires.
     _iu.is_flash_linear_attention_available()
-    # Subsequent calls: must not re-trigger the installer.
+    # Later calls: must not re-trigger the installer.
     _iu.is_flash_linear_attention_available()
     _iu.is_flash_linear_attention_available()
     assert fla_install.call_count == 1
@@ -800,7 +798,7 @@ def test_hook_handles_install_failure_gracefully(monkeypatch):
 
     from transformers.utils import import_utils as _iu
 
-    # Must not raise; returns False so transformers falls back to torch loop.
+    # Must not raise; returns False so transformers uses the torch loop.
     assert _iu.is_flash_linear_attention_available() is False
 
 
@@ -817,7 +815,7 @@ def test_hook_can_be_disabled_via_env(monkeypatch):
 
     from transformers.utils import import_utils as _iu
 
-    # Hook should NOT have been installed; gates remain the fakes.
+    # Hook not installed; gates remain the fakes.
     assert _iu.is_flash_linear_attention_available is fla_gate
     assert _iu.is_causal_conv1d_available is conv_gate
     fla_install.assert_not_called()
@@ -837,21 +835,21 @@ def test_hook_clears_lru_cache_before_first_check(monkeypatch):
     from transformers.utils import import_utils as _iu
 
     _iu.is_flash_linear_attention_available()
-    # The wrapper called cache_clear at least once before delegating.
+    # Wrapper called cache_clear at least once before delegating.
     assert fla_gate.cache_clear_count >= 1
 
 
 def test_hook_rewrites_previously_imported_module_bindings(monkeypatch):
     """Modeling files bind `is_flash_linear_attention_available` locally
     via `from ... import is_X`. Reassigning the attribute on
-    transformers.utils.import_utils alone does NOT reach those local
-    bindings. The hook installer sweeps sys.modules and rebinds them.
+    transformers.utils.import_utils alone misses those local bindings;
+    the hook installer sweeps sys.modules and rebinds them.
     """
     fla_gate = _make_fake_gate(initial_return = False)
     conv_gate = _make_fake_gate(initial_return = True)
     _patch_iu_gates(monkeypatch, fla_gate, conv_gate)
 
-    # Create a fake modeling module that did `from ... import is_flash_linear_attention_available`.
+    # Fake modeling module that did `from ... import is_flash_linear_attention_available`.
     fake_mod = sys.modules.setdefault(
         "_test_fake_modeling_qwen35", type(sys)("_test_fake_modeling_qwen35")
     )
@@ -868,9 +866,9 @@ def test_hook_rewrites_previously_imported_module_bindings(monkeypatch):
 
     worker._install_fast_path_hooks(event_queue = _FakeQueue(), model_name = "unsloth/Qwen3.5-2B")
 
-    # The fake module's local binding has been rewritten to the wrapper.
+    # The fake module's local binding is rewritten to the wrapper.
     assert fake_mod.is_flash_linear_attention_available is not fla_gate
-    # Calling through the fake module's reference triggers the install.
+    # Calling through the fake module's reference triggers install.
     assert fake_mod.is_flash_linear_attention_available() is True
 
     del sys.modules["_test_fake_modeling_qwen35"]
@@ -894,7 +892,7 @@ def test_hook_skips_when_import_utils_unavailable(monkeypatch):
 
 
 def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):
-    """Hook disabled -> legacy gate falls back to auto-discovered model types."""
+    """Hook disabled -> legacy gate falls back to auto-discovered types."""
     install_mock = mock.Mock()
     monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", install_mock)
     monkeypatch.setattr(worker, "_discover_fla_model_types", lambda: frozenset({"qwen3_5"}))
@@ -921,8 +919,8 @@ def test_substring_fallback_unchanged_when_hook_skipped(monkeypatch):
 
 
 def test_hook_does_not_install_tilelang_for_model_outside_allowlist(monkeypatch):
-    """A model whose name is not in the auto-discovered FLA allowlist calls
-    is_flash_linear_attention_available but should NOT get tilelang."""
+    """A model not in the auto-discovered FLA allowlist calls
+    is_flash_linear_attention_available but must NOT get tilelang."""
     fla_gate = _make_fake_gate(initial_return = False)
     conv_gate = _make_fake_gate(initial_return = True)
     _patch_iu_gates(monkeypatch, fla_gate, conv_gate)
@@ -939,7 +937,7 @@ def test_hook_does_not_install_tilelang_for_model_outside_allowlist(monkeypatch)
     monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
     # Hermetize the auto-discovered set so the test stays valid as new
     # transformers releases add FLA-using model_types (eg olmo_hybrid in
-    # 5.4.0). The semantic under test is "outside-allowlist -> no tilelang".
+    # 5.4.0). Test semantic: "outside-allowlist -> no tilelang".
     monkeypatch.setattr(
         worker,
         "_discover_fla_model_types",
@@ -986,7 +984,7 @@ def test_hook_does_install_tilelang_for_qwen35(monkeypatch):
 
 def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
     """Finding #2: the broken-tvm-ffi repair must use --no-deps on the
-    forced step so --force-reinstall does not cascade through
+    forced step so --force-reinstall doesn't cascade through
     apache-tvm-ffi's dep graph and pull a different torch wheel.
     """
     monkeypatch.delenv(worker._TILELANG_SKIP_ENV, raising = False)
@@ -1000,9 +998,9 @@ def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
 
     assert run_mock.call_count == 2
     repair_args = run_mock.call_args_list[0][0][0]
-    # The forced step MUST be --no-deps so torch / CUDA stack is untouched.
+    # Forced step MUST be --no-deps so torch / CUDA stack is untouched.
     assert "--force-reinstall" in repair_args and "--no-deps" in repair_args
-    # And it touches ONLY apache-tvm-ffi, not tilelang / torch.
+    # Touches ONLY apache-tvm-ffi, not tilelang / torch.
     assert all("tilelang" not in a for a in repair_args)
     assert all("torch" not in a for a in repair_args)
 
@@ -1010,25 +1008,24 @@ def test_tilelang_repair_does_not_touch_torch_cuda_stack(monkeypatch):
 def test_hook_trusts_installer_bool_not_metadata(monkeypatch):
     """Finding #3: if pip exits 0 but deep imports fail, the installer
     returns False; the hook must propagate False even if the underlying
-    `original()` gate (which only checks metadata) returns True after
-    pip succeeds.
+    `original()` gate (metadata-only) returns True after pip succeeds.
 
-    Setup mirrors the real bug:
-      1. Pre-install: gate=False (FLA not present) → wrapper triggers install.
+    Mirrors the real bug:
+      1. Pre-install: gate=False (FLA absent) → wrapper triggers install.
       2. Installer's `_flash_linear_attention_importable` post-probe fails,
-         so the installer returns False. (pip exited 0 but `import fla.modules`
-         raised because of a missing transitive dep.)
-      3. Post-install: gate would return True (metadata check sees fla-core
-         version) — but the wrapper must IGNORE that and use the installer's
-         False so transformers takes the torch fallback.
+         so it returns False. (pip exited 0 but `import fla.modules` raised
+         due to a missing transitive dep.)
+      3. Post-install: gate would return True (metadata sees fla-core) — but
+         the wrapper must IGNORE that and use the installer's False so
+         transformers takes the torch fallback.
     """
     # Gate flips True after install (simulating "metadata sees fla").
     fla_gate = _make_fake_gate(initial_return = False)
     conv_gate = _make_fake_gate(initial_return = True)
     _patch_iu_gates(monkeypatch, fla_gate, conv_gate)
 
-    # Installer "succeeds" at pip, AND flips the gate to True (metadata
-    # sees fla post-install), BUT returns False (deep import broken).
+    # Installer "succeeds" at pip and flips the gate to True (metadata
+    # sees fla post-install), but returns False (deep import broken).
     def _bad_install(eq):
         fla_gate.next_return = True  # metadata says yes after pip
         return False  # but deep import is broken
@@ -1051,9 +1048,9 @@ def test_hook_trusts_installer_bool_not_metadata(monkeypatch):
 
 
 def test_rebind_does_not_trigger_module_getattr(monkeypatch):
-    """Finding #5: the rebind sweep must use __dict__, not getattr(),
-    to avoid invoking transformers' lazy module __getattr__ which spits
-    out hundreds of "Accessing X from .models..." warnings.
+    """Finding #5: the rebind sweep must use __dict__, not getattr(), to
+    avoid invoking transformers' lazy module __getattr__ which spits out
+    hundreds of "Accessing X from .models..." warnings.
     """
     original = object()
     replacement = object()
@@ -1068,8 +1065,8 @@ def test_rebind_does_not_trigger_module_getattr(monkeypatch):
     lazy = _GetattrTripwire("_lazy_test_module")
     sys.modules["_lazy_test_module"] = lazy
     try:
-        # No module-level binding to `is_flash_linear_attention_available`
-        # in __dict__, so the sweep must NOT trip the tripwire.
+        # No `is_flash_linear_attention_available` in __dict__, so the
+        # sweep must NOT trip the tripwire.
         worker._rebind_in_already_imported_modules(
             attr_name = "is_flash_linear_attention_available",
             old_obj = original,
@@ -1085,7 +1082,7 @@ def test_rebind_does_not_trigger_module_getattr(monkeypatch):
 def test_hook_skips_tilelang_when_fla_install_is_skipped(monkeypatch):
     """Finding #6: env-skipped FLA returns False from
     _ensure_flash_linear_attention_unconditional; tilelang must NOT
-    install in that case.
+    install then.
     """
     fla_gate = _make_fake_gate(initial_return = False)
     conv_gate = _make_fake_gate(initial_return = True)
@@ -1107,9 +1104,9 @@ def test_hook_skips_tilelang_when_fla_install_is_skipped(monkeypatch):
 
 
 def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
-    """Finding #7: when FLA is already importable (gate returns True at
-    first probe) but tilelang is missing or apache-tvm-ffi is on the
-    broken list, the post-available action must still run tilelang.
+    """Finding #7: when FLA is already importable (gate True at first
+    probe) but tilelang is missing or apache-tvm-ffi is on the broken
+    list, the post-available action must still run tilelang.
     """
     fla_gate = _make_fake_gate(initial_return = True)
     conv_gate = _make_fake_gate(initial_return = True)
@@ -1120,7 +1117,7 @@ def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
     monkeypatch.setattr(worker, "_ensure_flash_linear_attention_unconditional", fla_install)
     monkeypatch.setattr(worker, "_ensure_tilelang_backend_unconditional", tile_install)
     monkeypatch.setattr(worker, "_install_package_wheel_first", mock.Mock(return_value = True))
-    # tilelang missing AND tvm-ffi is on broken list — both trigger repair.
+    # tilelang missing AND tvm-ffi on broken list — both trigger repair.
     monkeypatch.setattr(worker, "_tilelang_importable", lambda: False)
     monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.11")
     monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
@@ -1130,19 +1127,19 @@ def test_hook_runs_tilelang_repair_when_fla_already_true(monkeypatch):
     from transformers.utils import import_utils as _iu
 
     _iu.is_flash_linear_attention_available()
-    # FLA install was NOT needed; tilelang repair WAS still triggered.
+    # FLA install NOT needed; tilelang repair still triggered.
     fla_install.assert_not_called()
     tile_install.assert_called_once()
 
 
 def test_fla_installer_force_reinstalls_when_older_version_present(monkeypatch):
-    """Finding #8: when an older `flash-linear-attention` is importable
-    but below the pin, the installer must force a reinstall (not no-op).
+    """Finding #8: an older `flash-linear-attention` that is importable
+    but below the pin must force a reinstall (not no-op).
     """
     monkeypatch.delenv(worker._FLA_SKIP_ENV, raising = False)
     monkeypatch.setattr(worker.shutil, "which", lambda name: "/usr/bin/uv")
     monkeypatch.setattr(worker, "_installed_torch_version_tuple", lambda: (2, 9))
-    # Importable but stale (current() reports False even though importable() is True).
+    # Importable but stale (current()=False though importable()=True).
     monkeypatch.setattr(worker, "_flash_linear_attention_importable", lambda: True)
     monkeypatch.setattr(worker, "_flash_linear_attention_current", lambda **kw: False)
     run_mock = mock.Mock(return_value = mock.Mock(returncode = 0, stdout = ""))
@@ -1162,22 +1159,22 @@ def test_fla_installer_force_reinstalls_when_older_version_present(monkeypatch):
 
 def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():
     """Finding #4: SSM modeling files use `lazy_load_kernel("causal-conv1d")`
-    and never call `is_causal_conv1d_available()`, so the hook would not
-    fire for them. The orchestrator must always run the eager
-    substring installer regardless of hook mode.
+    and never call `is_causal_conv1d_available()`, so the hook won't fire
+    for them. The orchestrator must always run the eager substring
+    installer regardless of hook mode.
 
-    This test reads the worker source rather than running the full
-    orchestrator (which requires a configured training config). It
-    asserts the eager install is OUTSIDE the if/else hook branch.
+    Reads the worker source rather than running the full orchestrator
+    (which needs a configured training config), asserting the eager
+    install is OUTSIDE the if/else hook branch.
     """
     import inspect
 
     src = inspect.getsource(worker.run_training_process)
-    # Find the orchestration block.
+    # Orchestration block.
     assert "_ensure_causal_conv1d_fast_path(event_queue, model_name)" in src
     assert "_install_fast_path_hooks(event_queue, model_name)" in src
-    # The eager causal_conv1d call must appear BEFORE the hook-mode if/else,
-    # not nested inside the `if _FAST_PATH_HOOKS_SKIP_ENV` branch.
+    # Eager causal_conv1d call must come BEFORE the hook-mode if/else, not
+    # nested inside the `if _FAST_PATH_HOOKS_SKIP_ENV` branch.
     eager_pos = src.find("_ensure_causal_conv1d_fast_path(event_queue, model_name)")
     skip_check_pos = src.find('os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1"')
     assert eager_pos < skip_check_pos, (
@@ -1189,17 +1186,17 @@ def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():
 
 # ───────────────────────────────────────────────────────────────────
 # HIP / ROCm regression coverage (h34v3nzc0dex Strix Halo report).
-# tilelang 0.1.8 has no HIP GEMM backend; FLA's TileLang dispatch
-# crashes mid-backward on AMD with "Unsupported target for gemm: hip".
-# The fix: skip the install on HIP-built torch AND setdefault
-# FLA_TILELANG=0 so already-installed tilelang doesn't get used either.
+# tilelang 0.1.8 has no HIP GEMM backend; FLA's TileLang dispatch crashes
+# mid-backward on AMD with "Unsupported target for gemm: hip". Fix: skip
+# install on HIP-built torch AND setdefault FLA_TILELANG=0 so an
+# already-installed tilelang isn't used either.
 # ───────────────────────────────────────────────────────────────────
 
 
 def test_tilelang_platform_unsupported_on_hip_torch(monkeypatch):
-    """Strix Halo / MI300 with ROCm torch: linux + x86_64 looks
-    identical to a CUDA box at the OS level, so the platform check
-    must consult torch.version.hip explicitly.
+    """Strix Halo / MI300 with ROCm torch: linux + x86_64 looks identical
+    to a CUDA box at the OS level, so the platform check must consult
+    torch.version.hip explicitly.
     """
     monkeypatch.setattr(worker, "_torch_has_hip", lambda: True)
     assert worker._tilelang_platform_supported() is False
@@ -1220,9 +1217,9 @@ def test_tilelang_install_skipped_on_hip_torch(monkeypatch):
 
 
 def test_install_fast_path_hooks_sets_fla_tilelang_zero_on_hip(monkeypatch):
-    """When HIP torch is detected, hook installer must set
-    FLA_TILELANG=0 (via setdefault — respects user override) so any
-    PRE-EXISTING tilelang install isn't used by FLA's dispatcher.
+    """On HIP torch, the hook installer must setdefault FLA_TILELANG=0
+    (respecting user override) so a PRE-EXISTING tilelang install isn't
+    used by FLA's dispatcher.
     """
     import os as _os
 
@@ -1239,8 +1236,8 @@ def test_install_fast_path_hooks_sets_fla_tilelang_zero_on_hip(monkeypatch):
 
 
 def test_install_fast_path_hooks_respects_user_fla_tilelang_override(monkeypatch):
-    """If the user explicitly set FLA_TILELANG (even on HIP), don't
-    overwrite — they may know they have a HIP-aware tilelang fork.
+    """If the user set FLA_TILELANG (even on HIP), don't overwrite — they
+    may have a HIP-aware tilelang fork.
     """
     import os as _os
 
@@ -1278,7 +1275,7 @@ def test_install_fast_path_hooks_does_not_set_fla_tilelang_on_cuda(monkeypatch):
 
 
 def _make_fake_transformers_tree(tmp_path, fla_types: list[str], non_fla_types: list[str]):
-    """Lay out a tmp dir as `transformers/models/{type}/modeling_{type}.py`."""
+    """Lay out tmp dir as `transformers/models/{type}/modeling_{type}.py`."""
     pkg = tmp_path / "transformers"
     models = pkg / "models"
     models.mkdir(parents = True)
@@ -1341,7 +1338,7 @@ def test_discover_fla_model_types_caches_across_calls(tmp_path, monkeypatch):
     second = worker._discover_fla_model_types()
 
     assert first == second
-    assert read_calls[0] == after_first  # cache hit: no extra disk reads
+    assert read_calls[0] == after_first  # cache hit: no extra reads
 
 
 def test_discover_fla_model_types_handles_missing_transformers(monkeypatch):
@@ -1382,7 +1379,7 @@ def test_discover_fla_model_types_handles_unreadable_file(tmp_path, monkeypatch)
 
     monkeypatch.setattr(_Path, "read_text", boom_read)
     result = worker._discover_fla_model_types()
-    assert result == frozenset()  # unreadable file simply doesn't contribute
+    assert result == frozenset()  # unreadable file doesn't contribute
 
 
 def test_model_wants_tilelang_handles_real_repo_names(monkeypatch):
@@ -1425,20 +1422,19 @@ def test_model_wants_tilelang_normalizes_separators(monkeypatch):
 
 # ────────────────────────────────────────────────────────────────────
 # HIP source-build gcc-install-dir coverage (h34v3nzc0dex Strix Halo).
-# Ubuntu 24.04 ships gcc-14's runtime dir without /usr/include/c++/14,
-# so ROCm clang-20 picks it and fails with 'cstdlib' file not found
-# when building causal-conv1d (or any other HIP source fallback).
-# _hipcc_gcc_install_dir() finds a gcc dir that has both halves; the
+# Ubuntu 24.04 ships gcc-14's runtime dir without /usr/include/c++/14, so
+# ROCm clang-20 picks it and fails with 'cstdlib' file not found when
+# building causal-conv1d (or any HIP source fallback).
+# _hipcc_gcc_install_dir() finds a gcc dir with both halves; the
 # _install_package_wheel_first HIP branch passes it to clang via
-# HIPCC_COMPILE_FLAGS_APPEND. Parallel to bbf004c's setup.sh fix for
-# the llama.cpp HIP build (PR #5301).
+# HIPCC_COMPILE_FLAGS_APPEND. Parallel to bbf004c's setup.sh fix for the
+# llama.cpp HIP build (PR #5301).
 # ────────────────────────────────────────────────────────────────────
 
 
 def _isdir_for_layout(*existing: str):
-    """Return an os.path.isdir replacement that only treats the given
-    absolute paths as directories. Lets a test simulate exactly which
-    gcc runtime dirs and C++ header dirs exist on the host."""
+    """os.path.isdir replacement treating only the given absolute paths as
+    directories, to simulate which gcc runtime / C++ header dirs exist."""
     valid = set(existing)
 
     def fake_isdir(path: str) -> bool:
@@ -1449,7 +1445,7 @@ def _isdir_for_layout(*existing: str):
 
 def test_hipcc_gcc_install_dir_picks_highest_with_headers(monkeypatch):
     """gcc-14 has runtime but no /usr/include/c++/14; loop falls through
-    to gcc-13 which has both. This is the exact Ubuntu 24.04 layout."""
+    to gcc-13 which has both. The exact Ubuntu 24.04 layout."""
     monkeypatch.setattr(sys, "platform", "linux")
     import platform as _platform
 
@@ -1485,8 +1481,8 @@ def test_hipcc_gcc_install_dir_picks_14_when_headers_exist(monkeypatch):
 
 
 def test_hipcc_gcc_install_dir_returns_none_when_no_match(monkeypatch):
-    """No gcc dir has both halves → return None and skip the env injection
-    rather than guessing wrong and surfacing a confusing build failure."""
+    """No gcc dir has both halves → return None and skip env injection
+    rather than guessing wrong and causing a confusing build failure."""
     monkeypatch.setattr(sys, "platform", "linux")
     import platform as _platform
 
@@ -1516,10 +1512,9 @@ def test_hipcc_gcc_install_dir_returns_none_on_non_x86_64(monkeypatch):
 
 
 def _make_hip_install_env(monkeypatch, *, gcc_dir: str | None):
-    """Common scaffolding for tests that exercise the HIP source-build
-    branch of _install_package_wheel_first end-to-end. The package isn't
-    installed yet, no prebuilt wheel exists, hipcc is on PATH, and the
-    fake env reports an HIP torch."""
+    """Scaffolding for end-to-end tests of the HIP source-build branch of
+    _install_package_wheel_first: package not installed, no prebuilt
+    wheel, hipcc on PATH, fake env reports HIP torch."""
     monkeypatch.setattr(builtins, "__import__", _missing_module_import("causal_conv1d"))
     monkeypatch.setattr(
         worker,
@@ -1574,8 +1569,8 @@ def test_install_injects_gcc_install_dir_on_hip_source_build(monkeypatch):
 
 
 def test_install_appends_to_existing_hipcc_compile_flags(monkeypatch):
-    """User has HIPCC_COMPILE_FLAGS_APPEND='-O3 -DFOO' set → final value
-    keeps the user's flags AND adds --gcc-install-dir at the end."""
+    """User has HIPCC_COMPILE_FLAGS_APPEND='-O3 -DFOO' → final value keeps
+    the user's flags AND appends --gcc-install-dir."""
     monkeypatch.setenv("HIPCC_COMPILE_FLAGS_APPEND", "-O3 -DFOO")
     _make_hip_install_env(monkeypatch, gcc_dir = "/usr/lib/gcc/x86_64-linux-gnu/13")
 
@@ -1636,9 +1631,9 @@ def test_install_respects_user_gcc_install_dir(monkeypatch):
         release_base_url = "https://example.com",
     )
 
-    # subprocess.run was invoked without env override (the user already
-    # set HIPCC_COMPILE_FLAGS_APPEND with --gcc-install-dir, so we left
-    # the env alone — the existing value is inherited normally).
+    # subprocess.run invoked without env override (user already set
+    # HIPCC_COMPILE_FLAGS_APPEND with --gcc-install-dir, so we left the
+    # env alone — the existing value is inherited).
     assert captured == {"_called": "yes_no_env"}
 
 
@@ -1660,7 +1655,7 @@ def test_install_does_not_inject_env_on_cuda(monkeypatch):
     monkeypatch.setattr(worker, "direct_wheel_url", lambda **kw: None)
     monkeypatch.setattr(worker.shutil, "which", lambda name: None)
     monkeypatch.setattr(worker, "_send_status", lambda *a, **k: None)
-    # If _hipcc_gcc_install_dir were called on CUDA we'd want to know.
+    # _hipcc_gcc_install_dir must not be called on CUDA.
     monkeypatch.setattr(
         worker,
         "_hipcc_gcc_install_dir",
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index ff5e1f1381..c8d6a4fd10 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -10,9 +10,8 @@ from unittest.mock import patch
 
 
 # ---------------------------------------------------------------------------
-# We need to be able to import the module under test.  The studio backend
-# uses relative-style imports (``from utils.…``), so we add the backend
-# directory to *sys.path* if it is not already there.
+# The studio backend uses relative-style imports (``from utils.…``), so
+# add the backend directory to *sys.path* if not already present.
 # ---------------------------------------------------------------------------
 import sys
 
@@ -20,8 +19,8 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
     sys.path.insert(0, _BACKEND_DIR)
 
-# Stub the custom logger before importing the module under test so it
-# doesn't fail on the ``from loggers import get_logger`` line.
+# Stub the custom logger before import so ``from loggers import
+# get_logger`` doesn't fail.
 import types as _types
 
 _loggers_stub = _types.ModuleType("loggers")
@@ -90,7 +89,7 @@ class TestResolveBaseModel:
         (tmp_path / "config.json").write_text(json.dumps(config_cfg))
 
         result = _resolve_base_model(str(tmp_path))
-        # Should fall through, not return the self-referencing path
+        # Falls through; does not return the self-referencing path.
         assert result == str(tmp_path)
 
     def test_no_config_files(self, tmp_path: Path):
@@ -174,7 +173,7 @@ class TestNeedsTransformers5:
 
     def test_llama_does_not_need_v5(self):
         """Standard models should not trigger v5."""
-        # Patch network call to avoid real fetch
+        # Patch network call to avoid a real fetch.
         with patch(
             "utils.transformers_version._check_tokenizer_config_needs_v5",
             return_value = False,
@@ -182,13 +181,13 @@ class TestNeedsTransformers5:
             assert needs_transformers_5("meta-llama/Llama-3-8B") is False
 
     def test_local_checkpoint_resolved_via_config(self, tmp_path: Path):
-        """A local checkpoint with config.json pointing to Qwen3.5 should need v5."""
+        """Local checkpoint with config.json pointing to Qwen3.5 needs v5."""
         config_cfg = {"model_name": "Qwen/Qwen3.5-9B"}
         (tmp_path / "config.json").write_text(json.dumps(config_cfg))
 
-        # _resolve_base_model is called by ensure_transformers_version,
-        # but needs_transformers_5 just does substring matching.
-        # We test the full resolution chain here:
+        # ensure_transformers_version calls _resolve_base_model, but
+        # needs_transformers_5 just does substring matching. Test the
+        # full resolution chain here.
         resolved = _resolve_base_model(str(tmp_path))
         assert needs_transformers_5(resolved) is True
 
@@ -230,7 +229,7 @@ class TestCheckConfigNeeds550:
 
     def test_no_config_json(self, tmp_path: Path):
         """Missing config.json should return False (fail-open)."""
-        # Patch network call to avoid real fetch
+        # Patch network call to avoid a real fetch.
         with patch("urllib.request.urlopen") as mock_urlopen:
             mock_urlopen.side_effect = Exception("no network")
             assert _check_config_needs_550(str(tmp_path)) is False
@@ -311,8 +310,8 @@ class TestGetTransformersTier:
             assert get_transformers_tier("meta-llama/Llama-3-8B") == "default"
 
     def test_550_checked_before_530(self):
-        """Ensure 5.5.0 is checked first — a model matching both should get 550."""
-        # This shouldn't happen in practice, but verifies priority
+        """5.5.0 is checked first — a model matching both gets 550."""
+        # Shouldn't happen in practice, but verifies priority.
         assert get_transformers_tier("gemma-4-model") == "550"
 
     def test_needs_transformers_5_compat(self):
diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.py
index bdb1cd2ce8..765235bd32 100644
--- a/studio/backend/tests/test_utils.py
+++ b/studio/backend/tests/test_utils.py
@@ -4,13 +4,13 @@
 """
 Tests for utils/hardware and utils/utils — device detection, GPU memory, error formatting.
 
-These tests are designed to pass on ANY platform:
+Designed to pass on ANY platform:
   • NVIDIA GPU  (CUDA backend, requires torch)
   • Apple Silicon (MLX backend, requires mlx)
   • CPU-only     (no GPU at all)
 
-No ML framework is imported at the top level.
-Tests that need torch/mlx internals for mocking are skipped when unavailable.
+No ML framework is imported at the top level; tests needing torch/mlx
+internals for mocking are skipped when unavailable.
 
 Run with:
     cd studio/backend
@@ -189,10 +189,9 @@ class TestGetGpuMemoryInfo:
         assert "backend" in get_gpu_memory_info()
 
     def test_backend_matches_device(self):
-        # The backend field uses _backend_label, which swaps "cuda" for
-        # "rocm" when running on an AMD host (IS_ROCM=True) so the UI
-        # can render the correct label. On CUDA / XPU / MLX / CPU hosts
-        # it is equivalent to `get_device().value`.
+        # backend uses _backend_label, which swaps "cuda" for "rocm" on
+        # AMD hosts (IS_ROCM=True) for the UI label. On CUDA/XPU/MLX/CPU
+        # hosts it equals `get_device().value`.
         from utils.hardware.hardware import _backend_label
         result = get_gpu_memory_info()
         assert result["backend"] == _backend_label(get_device())
diff --git a/studio/backend/tests/test_vision_cache.py b/studio/backend/tests/test_vision_cache.py
index 78f88fd7ea..0df474b586 100644
--- a/studio/backend/tests/test_vision_cache.py
+++ b/studio/backend/tests/test_vision_cache.py
@@ -3,14 +3,13 @@
 
 """Tests for is_vision_model() caching behaviour.
 
-The vision detection cache (``_vision_detection_cache``) mirrors the existing
-``_audio_detection_cache`` pattern used by ``detect_audio_type()``.  These
-tests verify that:
+``_vision_detection_cache`` mirrors the ``_audio_detection_cache``
+pattern used by ``detect_audio_type()``. These tests verify:
 
-* Repeated calls for the same model hit the cache (no redundant work).
+* Repeated calls for the same model hit the cache.
 * Different models each trigger their own detection.
 * Both True and False results are cached.
-* The subprocess path (transformers 5.x models) is also cached.
+* The subprocess path (transformers 5.x models) is cached.
 * Exceptions that fall back to False are cached.
 """
 
@@ -62,8 +61,7 @@ class TestVisionCacheHitMiss:
 
     @patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
     def test_second_call_uses_cache(self, mock_uncached):
-        """Calling is_vision_model() twice for the same model should invoke
-        the uncached function only once."""
+        """Two calls for the same model invoke the uncached fn once."""
         assert is_vision_model("org/my-vlm") is True
         assert is_vision_model("org/my-vlm") is True
         mock_uncached.assert_called_once_with("org/my-vlm", None)
@@ -101,15 +99,15 @@ class TestVisionCacheStoresFalse:
 
 
 class TestVisionCacheSubprocessPath:
-    """Models needing transformers 5.x go through _is_vision_model_subprocess.
-    The cache should prevent the subprocess from being spawned more than once
-    per model per process."""
+    """transformers 5.x models go through _is_vision_model_subprocess.
+    The cache should spawn the subprocess at most once per model per
+    process."""
 
     @patch("utils.models.model_config._is_vision_model_subprocess", return_value = True)
     @patch("utils.transformers_version.needs_transformers_5", return_value = True)
     def test_subprocess_called_once_with_cache(self, mock_needs_t5, mock_subprocess):
-        """Subprocess should only fire on the first call; second is cached."""
-        # First call: goes through uncached → subprocess
+        """Subprocess fires only on the first call; second is cached."""
+        # First call: uncached → subprocess
         assert is_vision_model("unsloth/Qwen3.5-2B") is True
         # Second call: cache hit, no subprocess
         assert is_vision_model("unsloth/Qwen3.5-2B") is True
@@ -136,10 +134,9 @@ class TestVisionCacheSubprocessPath:
 
 
 class TestVisionCacheOnException:
-    """When detection raises an exception, _is_vision_model_uncached
-    distinguishes permanent failures (cached as False) from transient
-    failures (returned as None, not cached so the next call can retry).
-    Verify both contracts."""
+    """On exception, _is_vision_model_uncached distinguishes permanent
+    failures (cached as False) from transient ones (returned as None,
+    not cached, so the next call retries). Verify both contracts."""
 
     @patch(
         "utils.models.model_config.load_model_config",
@@ -148,13 +145,12 @@ class TestVisionCacheOnException:
     @patch("utils.transformers_version.needs_transformers_5", return_value = False)
     def test_permanent_exception_result_cached(self, mock_needs_t5, mock_load_config):
         """A permanent failure (ValueError / RepositoryNotFoundError /
-        GatedRepoError / JSONDecodeError) should be caught, return False,
-        and that False should be cached so subsequent calls don't retry.
+        GatedRepoError / JSONDecodeError) is caught, returns False, and
+        that False is cached so subsequent calls don't retry.
 
-        ValueError is used here because it's the simplest of the
-        code-path's cacheable exception types and does not require an
-        import of huggingface_hub errors (whose module path varies
-        across versions)."""
+        ValueError is used as the simplest cacheable exception type that
+        avoids importing huggingface_hub errors (whose module path
+        varies across versions)."""
         # First call: load_model_config raises -> except branch -> False.
         assert is_vision_model("broken/model") is False
         # Second call: cache hit, load_model_config not called again.
@@ -167,17 +163,15 @@ class TestVisionCacheOnException:
     )
     @patch("utils.transformers_version.needs_transformers_5", return_value = False)
     def test_transient_exception_not_cached(self, mock_needs_t5, mock_load_config):
-        """A transient failure (OSError, timeouts) should return None from
-        _is_vision_model_uncached, surface as False to the caller, and
-        NOT be cached, so the next call retries detection.  This matches
-        the documented behaviour on _vision_detection_cache:
-        'transient failures (network errors, timeouts) are NOT cached so
-        they can be retried.'"""
-        # First call: load_model_config raises OSError -> uncached None
-        # -> caller returns False without caching.
+        """A transient failure (OSError, timeouts) returns None from
+        _is_vision_model_uncached, surfaces as False to the caller, and
+        is NOT cached, so the next call retries. Matches the documented
+        _vision_detection_cache behaviour: 'transient failures (network
+        errors, timeouts) are NOT cached so they can be retried.'"""
+        # First call: OSError -> uncached None -> caller returns False,
+        # no caching.
         assert is_vision_model("broken/model") is False
-        # Second call: cache miss again, load_model_config called a
-        # second time.
+        # Second call: cache miss again, load_model_config called twice.
         assert is_vision_model("broken/model") is False
         assert mock_load_config.call_count == 2
 
@@ -188,7 +182,7 @@ class TestVisionCacheOnException:
 
 
 class TestVisionCacheDirectPath:
-    """For models that do NOT need transformers 5.x, the detection goes through
+    """Models that do NOT need transformers 5.x detect via
     load_model_config directly. The cache must work the same way."""
 
     @patch("utils.transformers_version.needs_transformers_5", return_value = False)
@@ -214,7 +208,7 @@ class TestVisionCacheDirectPath:
         cfg.architectures = ["LlamaForCausalLM"]
         mock_load_config.return_value = cfg
 
-        # LlamaForCausalLM doesn't end with VLM suffixes, no vision_config, etc.
+        # No VLM suffix, no vision_config, etc.
         assert is_vision_model("meta-llama/Llama-3-8B") is False
         assert is_vision_model("meta-llama/Llama-3-8B") is False
         mock_load_config.assert_called_once()
@@ -290,15 +284,14 @@ class TestVisionCacheDirectPath:
 
 
 class TestVisionCacheTokenHandling:
-    """The cache is keyed on (model_name, hf_token).
-    Different tokens for the same model should trigger separate detections
-    to handle gated models correctly."""
+    """The cache is keyed on (model_name, hf_token). Different tokens
+    for the same model trigger separate detections for gated models."""
 
     @patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
     def test_different_tokens_trigger_new_detection(self, mock_uncached):
-        """Calls with different tokens should trigger separate detections to
-        handle gated models correctly (e.g. unauthenticated probe → False,
-        then authenticated call should re-check)."""
+        """Different tokens trigger separate detections for gated models
+        (e.g. unauthenticated probe → False, then authenticated
+        re-check)."""
         assert is_vision_model("gated/model", hf_token = "token-a") is True
         assert is_vision_model("gated/model", hf_token = "token-b") is True
         assert mock_uncached.call_count == 2
diff --git a/studio/backend/tests/test_vram_estimation.py b/studio/backend/tests/test_vram_estimation.py
index 65964908d7..2def8738e2 100644
--- a/studio/backend/tests/test_vram_estimation.py
+++ b/studio/backend/tests/test_vram_estimation.py
@@ -531,7 +531,7 @@ class TestQuantizationSkips(unittest.TestCase):
         )
 
     def test_vlm_prefix_skip_module_does_not_match_text_alias(self):
-        # vision_tower-prefixed skips must not shadow text aliases sharing the
+        # vision_tower-prefixed skips must not shadow text aliases with the
         # same suffix.
         baseline = replace(QUANT_SKIP_STRUCTURED, quantization_skip_modules = [])
         vlm_skip = replace(
@@ -995,9 +995,9 @@ class TestParallelDenseMoE(unittest.TestCase):
             + with_parallel.num_experts * with_parallel.hidden_size
         )
         dense_only = with_parallel.hidden_size * with_parallel.intermediate_size * 3
-        # why: under gemma4 enable_moe_block, the layer's `self.experts` is a
-        # sibling of `self.mlp`; the `text.layers..mlp` aggregate must
-        # cover the dense path only, with experts in their own aggregate.
+        # why: under gemma4 enable_moe_block, `self.experts` is a sibling of
+        # `self.mlp`; the `text.layers..mlp` aggregate covers the dense path
+        # only, with experts in their own aggregate.
         self.assertEqual(elements["text.layers.0.mlp"], dense_only)
         self.assertEqual(elements["text.layers.0.experts"], moe_only)
 
@@ -1148,9 +1148,9 @@ class TestPerLayerInputAccounting(unittest.TestCase):
     def test_per_layer_input_modules_count_quantizable_block(self):
         with_ple = self._arch()
         without_ple = replace(with_ple, hidden_size_per_layer_input = 0)
-        # The PLE block adds: model_projection (hd*nl*pli), per_layer_input_gate
-        # (hd*pli per layer) + per_layer_projection (pli*hd per layer) as
-        # quantizable text linears.
+        # PLE block adds these quantizable text linears: model_projection
+        # (hd*nl*pli), per_layer_input_gate (hd*pli per layer),
+        # per_layer_projection (pli*hd per layer).
         n_layers = with_ple.num_hidden_layers
         hd = with_ple.hidden_size
         pli = with_ple.hidden_size_per_layer_input
@@ -1161,10 +1161,10 @@ class TestPerLayerInputAccounting(unittest.TestCase):
         self.assertGreaterEqual(delta, expected_quantizable_extra)
 
     def test_all_linear_lora_excludes_per_layer_input_modules(self):
-        # why: Unsloth's get_peft_regex requires module names to contain a
-        # component tag (mlp/attn/...); PLE module names (per_layer_input_gate,
-        # per_layer_projection, per_layer_model_projection) lack any tag, so
-        # all-linear training does NOT attach LoRA to them.
+        # why: Unsloth's get_peft_regex requires a component tag (mlp/attn/...)
+        # in module names; PLE names (per_layer_input_gate, per_layer_projection,
+        # per_layer_model_projection) lack one, so all-linear does NOT attach
+        # LoRA to them.
         arch = self._arch()
         without_ple = replace(arch, hidden_size_per_layer_input = 0)
         self.assertEqual(
@@ -1234,11 +1234,10 @@ class TestExpertsSkipGranularity(unittest.TestCase):
         bytes_skip_experts = compute_model_weights_bytes(skip_experts, "qlora", True)
         bytes_skip_mlp = compute_model_weights_bytes(skip_full_mlp, "qlora", True)
         # why: under gemma4 enable_moe_block, `self.experts` is a sibling of
-        # `self.mlp`; skipping `model.layers.0.mlp` should cover only the
-        # dense MLP, while `model.layers.0.mlp.experts` covers the routed
-        # experts. Routed experts have far more params than the dense MLP,
-        # so skipping experts must add more bytes than skipping the dense
-        # path.
+        # `self.mlp`; skipping `model.layers.0.mlp` covers only the dense MLP,
+        # while `model.layers.0.mlp.experts` covers the routed experts. Routed
+        # experts have far more params than the dense MLP, so skipping experts
+        # must add more bytes than skipping the dense path.
         self.assertGreater(bytes_skip_experts, bytes_no_skip)
         self.assertGreater(bytes_skip_mlp, bytes_no_skip)
         self.assertGreater(bytes_skip_experts, bytes_skip_mlp)
@@ -1485,8 +1484,8 @@ class TestPerLayerInputSkipAlias(unittest.TestCase):
         )
 
         arch_with = extract_arch_config(self._hf(["model.layers.0"]))
-        # The text.layers.0 aggregate must include the PLE per-layer modules,
-        # so the same skip on a config without PLE produces a smaller value.
+        # text.layers.0 aggregate includes the PLE per-layer modules, so the
+        # same skip on a no-PLE config produces a smaller value.
         arch_without = extract_arch_config(
             SimpleNamespace(
                 text_config = SimpleNamespace(
@@ -1558,7 +1557,7 @@ class TestSharedExpertVariants(unittest.TestCase):
         arch_separate = extract_arch_config(self._hf(shared_expert_intermediate_size = 64))
         arch_implicit = extract_arch_config(self._hf(n_shared_experts = 1))
         # Different shared sizes (64 vs default moe_intermediate_size=128) must
-        # produce different MoE element counts.
+        # give different MoE element counts.
         self.assertNotEqual(
             _compute_moe_mlp_elements(arch_separate),
             _compute_moe_mlp_elements(arch_implicit),
@@ -1567,7 +1566,7 @@ class TestSharedExpertVariants(unittest.TestCase):
     def test_shared_expert_gate_counted_only_for_qwen_style(self):
         from utils.hardware.vram_estimation import _compute_moe_mlp_elements
 
-        # Qwen-style: shared_expert_intermediate_size set -> shared_expert_gate counted.
+        # Qwen-style: shared_expert_intermediate_size set -> gate counted.
         qwen_arch = extract_arch_config(self._hf(shared_expert_intermediate_size = 64))
         hd = qwen_arch.hidden_size
         ms = qwen_arch.moe_intermediate_size
@@ -1624,8 +1623,8 @@ class TestSharedExpertActivation(unittest.TestCase):
         )
 
     def test_shared_expert_plus_dense_block_compose(self):
-        # gemma4 enable_moe_block with hypothetical shared expert: dense + routed
-        # + shared all live per layer; mlp_size should sum all three terms.
+        # gemma4 enable_moe_block with a hypothetical shared expert: dense +
+        # routed + shared all live per layer; mlp_size sums all three.
         from utils.hardware.vram_estimation import _layer_qkv_mlp_sizes
 
         arch = self._make(
@@ -1773,7 +1772,7 @@ class TestSparseMoeSkipAliases(unittest.TestCase):
                 shared_expert_intermediate_size = 32,
             )
         )
-        # shared_expert delta only -- routed mlp.experts is NOT skipped.
+        # shared_expert delta only -- routed mlp.experts NOT skipped.
         delta = _compute_skipped_quantizable_elements(arch)
         self.assertGreater(delta, 0)
         full_layer = extract_arch_config(
@@ -1944,10 +1943,10 @@ class TestErnieMoEListConfig(unittest.TestCase):
                 moe_intermediate_size = [1536, 512],
             )
         )
-        # why: ERNIE 4.5 VL MoE encodes [text_routed, vision_routed]; the
-        # second element is the vision-routed expert width, not the shared
-        # expert width. Shared experts are sized from the text-routed width
-        # (= moe_intermediate_size[0]) when moe_num_shared_experts is set.
+        # why: ERNIE 4.5 VL MoE encodes [text_routed, vision_routed]; element 1
+        # is the vision-routed width, not the shared-expert width. Shared
+        # experts size from the text-routed width (moe_intermediate_size[0])
+        # when moe_num_shared_experts is set.
         self.assertEqual(arch.moe_intermediate_size, 1536)
         self.assertIsNone(arch.shared_expert_intermediate_size)
         self.assertEqual(arch.n_shared_experts, 0)
@@ -2070,7 +2069,7 @@ class TestMultimodalFullModelBytes(unittest.TestCase):
                 load_in_4bit = True,
             )
         self.assertEqual(metadata.get("estimation_mode"), "detailed")
-        # model_weights_gb must reflect the extra non-text bytes (>5 GB
+        # model_weights_gb must reflect the extra non-text bytes (>5 GB,
         # since text-only arch_fp16 is small for these dims).
         self.assertGreater(metadata["vram_breakdown"]["model_weights_gb"], 5.0)
 
diff --git a/studio/backend/tests/test_windows_gpu_detection_mock.py b/studio/backend/tests/test_windows_gpu_detection_mock.py
index bc887f8cc5..3a82541a31 100644
--- a/studio/backend/tests/test_windows_gpu_detection_mock.py
+++ b/studio/backend/tests/test_windows_gpu_detection_mock.py
@@ -3,12 +3,12 @@
 
 """Windows GPU-detection regression test on a synthetic layout.
 
-The bug (#5106): on Windows without a system CUDA toolkit, the prebuilt
-llama-server.exe could not LoadLibrary cudart64_X / cublas64_X /
+Bug (#5106): on Windows without a system CUDA toolkit, the prebuilt
+llama-server.exe couldn't LoadLibrary cudart64_X / cublas64_X /
 cublasLt64_X, so ggml-cuda.dll's static import on cublas64_X.dll failed
 and the model fell back to CPU even when nvidia-smi reported the GPU.
 
-The fix:
+Fix:
   * #5322 overlays upstream's paired cudart bundle into
     install_dir/build/bin/Release/ next to llama-server.exe.
   * #5324 prepends pip-installed nvidia//{bin,bin/x86_64,Library/
@@ -34,13 +34,12 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
 if _BACKEND_DIR not in sys.path:
     sys.path.insert(0, _BACKEND_DIR)
 
-# Stub heavy deps only if they actually fail to import -- unconditional
-# stubs would shadow the real module for sibling tests in this dir.
-# Use try-import rather than find_spec: loggers/__init__.py re-exports
-# handlers.get_logger, which does `from fastapi import Request,
-# Response` at module load. find_spec("loggers") returns a spec even
-# without fastapi, but the import then raises. CI has fastapi, so this
-# is dev-machine ergonomics only.
+# Stub heavy deps only if they fail to import -- unconditional stubs
+# would shadow the real module for sibling tests here. Use try-import,
+# not find_spec: loggers/__init__.py re-exports handlers.get_logger,
+# which does `from fastapi import Request, Response` at load. find_spec
+# returns a spec even without fastapi, but the import then raises. CI has
+# fastapi, so this is dev-machine ergonomics only.
 import importlib as _importlib  # noqa: E402
 
 
@@ -100,7 +99,7 @@ from core.inference.llama_cpp import LlamaCppBackend  # noqa: E402
 
 
 # Upstream b9103 cudart bundle: exactly these three DLLs per CUDA major,
-# no executables, no subdirectories. Verified by direct unzip.
+# no executables or subdirectories. Verified by direct unzip.
 REAL_UPSTREAM_CUDART_BUNDLE = {
     "12.4": ("cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll"),
     "13.1": ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"),
@@ -133,15 +132,15 @@ REAL_PIP_NVIDIA_WHEEL_LAYOUTS = {
 
 def _populate_studio_venv(prefix: Path) -> None:
     """Lay out fake nvidia + torch wheels in /Lib/site-packages
-    matching the real win_amd64 wheel layouts. Contents are stub bytes;
-    only directory structure matters."""
+    matching real win_amd64 layouts. Contents are stub bytes; only
+    directory structure matters."""
     site = prefix / "Lib" / "site-packages"
     for rel, dlls in REAL_PIP_NVIDIA_WHEEL_LAYOUTS.items():
         d = site / Path(rel)
         d.mkdir(parents = True, exist_ok = True)
         for name in dlls:
             (d / name).write_bytes(b"PE-stub")
-    # install_python_stack always installs torch alongside nvidia.
+    # install_python_stack always installs torch beside nvidia.
     (site / "torch" / "lib").mkdir(parents = True, exist_ok = True)
     for fn in ("c10.dll", "torch.dll", "torch_cpu.dll", "torch_python.dll"):
         (site / "torch" / "lib" / fn).write_bytes(b"PE-stub")
@@ -149,7 +148,7 @@ def _populate_studio_venv(prefix: Path) -> None:
 
 def _populate_studio_install(install_dir: Path, runtime: str = "13.1") -> None:
     """Lay out install_dir/build/bin/Release/ as #5322 leaves it: main
-    archive payload + paired cudart bundle overlay."""
+    archive payload + cudart bundle overlay."""
     rel = install_dir / "build" / "bin" / "Release"
     rel.mkdir(parents = True, exist_ok = True)
     for fn in (
@@ -163,7 +162,7 @@ def _populate_studio_install(install_dir: Path, runtime: str = "13.1") -> None:
         "mtmd.dll",
     ):
         (rel / fn).write_bytes(b"PE-stub")
-    # The cudart overlay #5322 contributes.
+    # The cudart overlay from #5322.
     for fn in REAL_UPSTREAM_CUDART_BUNDLE[runtime]:
         (rel / fn).write_bytes(b"PE-stub")
 
@@ -173,15 +172,15 @@ def _build_path_dirs_like_start_llama_server(
     prefix: Path,
     cuda_path: str = "",
 ) -> list[str]:
-    """Path-friendly wrapper around LlamaCppBackend._build_windows_path_dirs.
-    Asserting against the staticmethod (not a hand-copy) is the point:
-    if the win32 PATH order drops _windows_pip_nvidia_dll_dirs, tests fail."""
+    """Path-friendly wrapper around _build_windows_path_dirs. Asserting
+    against the real staticmethod (not a hand-copy) is the point: if the
+    win32 PATH order drops _windows_pip_nvidia_dll_dirs, tests fail."""
     return LlamaCppBackend._build_windows_path_dirs(str(binary_dir), str(prefix), cuda_path)
 
 
 def _mock_nvidia_smi_run(fake_output: str, returncode: int = 0) -> "mock._patch":
     """Patch subprocess.run so the nvidia-smi probe returns fake_output;
-    other subprocess.run calls pass through."""
+    other calls pass through."""
     real_run = subprocess.run
 
     def fake_run(cmd, *args, **kwargs):
@@ -199,11 +198,11 @@ def _mock_nvidia_smi_run(fake_output: str, returncode: int = 0) -> "mock._patch"
 # --------------------------------------------------------------------- #
 class TestWindowsGpuDetectionAfter5106Fix:
     """End-to-end #5106 fix on a synthetic Windows layout. nvidia-smi
-    mocked; resolver, PATH builder and install layout exercised live."""
+    mocked; resolver, PATH builder, and install layout run live."""
 
     def test_nvidia_smi_probe_reports_synthetic_gpu(self, monkeypatch):
         """Probe parses CSV output and returns (index, free_mib)."""
-        # Clear inherited masks so the synthetic CSV is not filtered.
+        # Clear inherited masks so the synthetic CSV isn't filtered.
         monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
         monkeypatch.delenv("NVIDIA_VISIBLE_DEVICES", raising = False)
         # The #5106 reporter's exact reproducer: RTX 4090, 22805 MiB.
@@ -222,7 +221,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
 
     def test_windows_install_dir_has_all_three_cudart_dlls(self, tmp_path):
         """All three bundle DLLs must land in install_dir/build/bin/
-        Release; missing any one breaks ggml-cuda.dll's PE import chain."""
+        Release; any missing one breaks ggml-cuda.dll's PE import chain."""
         install = tmp_path / "studio_install"
         _populate_studio_install(install, runtime = "13.1")
         rel = install / "build" / "bin" / "Release"
@@ -232,8 +231,8 @@ class TestWindowsGpuDetectionAfter5106Fix:
         assert (rel / "ggml-cuda.dll").exists()
 
     def test_resolver_finds_real_pypi_wheel_layouts(self, tmp_path):
-        """Resolver must pick up every real-world wheel layout:
-        nvidia//bin, nvidia//bin/x86_64, torch/lib."""
+        """Resolver must pick up every wheel layout: nvidia//bin,
+        nvidia//bin/x86_64, torch/lib."""
         prefix = tmp_path / "studio_venv"
         _populate_studio_venv(prefix)
         out = LlamaCppBackend._windows_pip_nvidia_dll_dirs(str(prefix))
@@ -249,8 +248,8 @@ class TestWindowsGpuDetectionAfter5106Fix:
 
     def test_path_assembly_makes_cudart_reachable_without_toolkit(self, tmp_path):
         """The #5106 scenario: GPU detected, pip nvidia wheels present,
-        no system CUDA toolkit. cudart must be reachable from PATH, and
-        from BOTH binary_dir (#5322) and a pip nvidia dir (#5324)."""
+        no system CUDA toolkit. cudart must be reachable from PATH via
+        BOTH binary_dir (#5322) and a pip nvidia dir (#5324)."""
         prefix = tmp_path / "studio_venv"
         install = tmp_path / "studio_install"
         _populate_studio_venv(prefix)
@@ -278,7 +277,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
         ), f"#5324's pip nvidia dir not contributing cudart: {cudart_locations}"
 
     def test_cublas_and_cublasLt_also_reachable(self, tmp_path):
-        """ggml-cuda imports cublas64; cublas64 imports cublasLt64. All
+        """ggml-cuda imports cublas64, which imports cublasLt64. All
         three must resolve or LoadLibrary returns NULL."""
         prefix = tmp_path / "studio_venv"
         install = tmp_path / "studio_install"
@@ -293,7 +292,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
             )
 
     def test_no_pip_nvidia_wheels_still_works_via_install_dir(self, tmp_path):
-        """No pip nvidia wheels (CPU-only torch / unsloth run standalone):
+        """No pip nvidia wheels (CPU-only torch / standalone unsloth):
         cudart still resolves via #5322's binary_dir drop."""
         prefix = tmp_path / "bare_venv"
         prefix.mkdir()
@@ -309,7 +308,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
 
     def test_no_install_dir_still_works_via_pip_wheels(self, tmp_path):
         """Pre-#5322 install (binary_dir lacks cudart): #5324's pip
-        wheel directories on PATH still resolve cudart."""
+        wheel dirs on PATH still resolve cudart."""
         prefix = tmp_path / "studio_venv"
         _populate_studio_venv(prefix)
         install = tmp_path / "studio_install_pre5322"
@@ -339,9 +338,9 @@ class TestWindowsGpuDetectionAfter5106Fix:
         assert cublas_reachable, "cublas unreachable on cudart-less install"
 
     def test_pre_pr_scenario_would_have_failed(self, tmp_path):
-        """Negative control: pre-#5322 + pre-#5324 world leaves cudart
+        """Negative control: pre-#5322 + pre-#5324 leaves cudart
         unreachable -- the original failure mode. Confirms the test
-        actually catches a regression."""
+        catches a regression."""
         prefix = tmp_path / "studio_venv"
         _populate_studio_venv(prefix)
         install = tmp_path / "pre_pr_install"
@@ -349,7 +348,7 @@ class TestWindowsGpuDetectionAfter5106Fix:
         rel.mkdir(parents = True)
         for fn in ("llama-server.exe", "llama.dll", "ggml-cuda.dll"):
             (rel / fn).write_bytes(b"PE-stub")
-        # Pre-PR PATH: binary_dir only. No pip nvidia dirs, no toolkit.
+        # Pre-PR PATH: binary_dir only, no pip nvidia dirs, no toolkit.
         pre_pr_path_dirs = [str(rel)]
         cudart_reachable_pre = any(
             (Path(d) / "cudart64_12.dll").exists() or (Path(d) / "cudart64_13.dll").exists()
@@ -362,9 +361,9 @@ class TestWindowsGpuDetectionAfter5106Fix:
 
 
 class TestWindowsSysPlatformMocked:
-    """Confirm the win32 branch in start_llama_server is what we test
-    (not the linux fallback). Patches sys.platform and re-runs the
-    branch-selecting helper."""
+    """Confirm we test the win32 branch in start_llama_server, not the
+    linux fallback. Patches sys.platform and re-runs the branch-selecting
+    helper."""
 
     def test_sys_platform_win32_uses_pip_nvidia_resolver(self, monkeypatch, tmp_path):
         monkeypatch.setattr(sys, "platform", "win32")
diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.py
index 9d01b40add..4e582ae926 100644
--- a/studio/backend/utils/cache_cleanup.py
+++ b/studio/backend/utils/cache_cleanup.py
@@ -4,11 +4,11 @@
 """
 Utility for cleaning up the Unsloth compiled cache directory.
 
-The unsloth_compiled_cache is created by unsloth_zoo/compiler.py during
-FastModel.from_pretrained() and contains model-type-specific compiled Python
-files. It should be selectively cleared between model loads to avoid stale
-artefacts, while preserving model-agnostic components (like Trainers) needed
-by spawned subprocesses.
+unsloth_compiled_cache is created by unsloth_zoo/compiler.py during
+FastModel.from_pretrained() and holds model-type-specific compiled Python files.
+Clear it selectively between model loads to avoid stale artefacts, while
+preserving model-agnostic components (like Trainers) needed by spawned
+subprocesses.
 """
 
 import shutil
@@ -38,9 +38,8 @@ def get_existing_cache_dirs() -> List[Path]:
 def register_compiled_cache_on_path() -> None:
     """Add all existing compiled-cache directories to sys.path and PYTHONPATH.
 
-    This ensures spawned workers (on platforms using the 'spawn' start method,
-    i.e. Windows and macOS) can import dynamically compiled modules such as
-    UnslothSFTTrainer.
+    Ensures spawned workers (on 'spawn'-start platforms, i.e. Windows and macOS)
+    can import dynamically compiled modules such as UnslothSFTTrainer.
     """
     import os
     import sys
@@ -48,8 +47,8 @@ def register_compiled_cache_on_path() -> None:
     pypath = os.environ.get("PYTHONPATH", "")
     pypath_entries = [p for p in pypath.split(os.pathsep) if p]
 
-    # Iterate in reverse so that earlier _CACHE_DIRS entries (higher priority)
-    # are inserted last and therefore end up first in sys.path / PYTHONPATH.
+    # Iterate in reverse so earlier _CACHE_DIRS entries (higher priority) are
+    # inserted last and thus end up first in sys.path / PYTHONPATH.
     for cache_dir in reversed(get_existing_cache_dirs()):
         resolved = str(cache_dir.resolve())
         if resolved not in sys.path:
@@ -65,7 +64,7 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
     Remove compiled files from the cache directory (idempotent).
 
     Args:
-        preserve_patterns: A list of glob patterns for files to keep
+        preserve_patterns: glob patterns for files to keep
                            (e.g., ["Unsloth*Trainer.py"]). If None or empty,
                            the entire cache directory is deleted (legacy behavior).
     """
@@ -80,7 +79,7 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
 
             for item in cache_dir.iterdir():
                 if item.is_file():
-                    # Check if the file matches any of the patterns we want to keep
+                    # Keep the file if it matches any preserve pattern
                     preserve = any(item.match(pattern) for pattern in preserve_patterns)
                     if not preserve:
                         try:
@@ -92,6 +91,6 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
                     # Always clear __pycache__ and other subdirectories
                     shutil.rmtree(item, ignore_errors = True)
         else:
-            # Legacy behavior: nuke the entire directory
+            # Legacy behavior: remove the entire directory
             logger.info(f"Removing unsloth compiled cache: {cache_dir}")
             shutil.rmtree(cache_dir, ignore_errors = True)
diff --git a/studio/backend/utils/cpu_threads.py b/studio/backend/utils/cpu_threads.py
index 922f95ce55..5cf2ff1ce2 100644
--- a/studio/backend/utils/cpu_threads.py
+++ b/studio/backend/utils/cpu_threads.py
@@ -18,9 +18,9 @@ _THREAD_POOL_ENV_VARS = (
 def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> None:
     """Apply ``UNSLOTH_CPU_THREADS`` to native CPU pools when configured.
 
-    This must run before importing libraries that initialize an OpenMP or
-    BLAS thread pool. Library-specific variables are left untouched so users
-    can override a single runtime independently.
+    Must run before importing libraries that initialize an OpenMP or BLAS
+    thread pool. Library-specific variables are left untouched so users can
+    override a single runtime independently.
     """
     environ = os.environ if env is None else env
     configured = environ.get("UNSLOTH_CPU_THREADS", "").strip()
diff --git a/studio/backend/utils/datasets/__init__.py b/studio/backend/utils/datasets/__init__.py
index 7988b09972..3ecb085478 100644
--- a/studio/backend/utils/datasets/__init__.py
+++ b/studio/backend/utils/datasets/__init__.py
@@ -2,10 +2,8 @@
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
 """
-Dataset utilities package.
-
-This package provides utilities for dataset format detection, conversion,
-and processing for LLM and VLM fine-tuning workflows.
+Dataset utilities for LLM/VLM fine-tuning: format detection, conversion,
+and processing.
 
 Modules:
 - format_detection: Detect dataset formats (Alpaca, ShareGPT, ChatML)
@@ -62,8 +60,7 @@ from .model_mappings import (
     is_gpt_oss_model_name,
 )
 
-# Legacy imports from the original dataset_utils.py for backward compatibility
-# These functions have not yet been refactored into separate modules
+# Legacy imports from dataset_utils.py (not yet refactored) for backward compat
 from .dataset_utils import (
     check_dataset_format,
     format_and_template_dataset,
diff --git a/studio/backend/utils/datasets/chat_templates.py b/studio/backend/utils/datasets/chat_templates.py
index cfdd811853..4b8ee93e9c 100644
--- a/studio/backend/utils/datasets/chat_templates.py
+++ b/studio/backend/utils/datasets/chat_templates.py
@@ -1,11 +1,9 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Chat template application utilities for dataset processing.
+"""Chat template utilities for dataset processing.
 
-This module contains functions for applying chat templates to datasets
-and generating dataset info summaries.
+Apply chat templates to datasets and generate dataset info summaries.
 """
 
 from .format_detection import detect_dataset_format, detect_multimodal_dataset, detect_custom_format_heuristic
@@ -47,29 +45,27 @@ def _chat_template_kwargs() -> dict:
 
 def get_tokenizer_chat_template(tokenizer, model_name):
     """
-    Gets appropriate chat template for tokenizer based on model.
-    Uses Unsloth's get_chat_template if model is in the mapper.
+    Get the chat template for a tokenizer based on the model.
+    Uses Unsloth's get_chat_template if the model is in the mapper.
 
     Args:
         tokenizer: HuggingFace tokenizer
         model_name: Model class name (e.g., "Gemma3ForCausalLM")
 
     Returns:
-        tokenizer: Tokenizer with appropriate chat template applied
+        tokenizer: Tokenizer with the chat template applied
     """
     try:
         from unsloth.chat_templates import get_chat_template
     except ImportError:
-        # Unsloth not available, return tokenizer as-is
+        # Unsloth not available; return tokenizer as-is.
         return tokenizer
 
-    # Normalize model_name to lowercase for matching
     model_name_lower = model_name.lower()
 
-    # Check if model matches any template in mapper
     matched_template = None
 
-    # Direct match in MODEL_TO_TEMPLATE_MAPPER
+    # Direct match in MODEL_TO_TEMPLATE_MAPPER.
     if model_name_lower in MODEL_TO_TEMPLATE_MAPPER:
         matched_template = MODEL_TO_TEMPLATE_MAPPER[model_name_lower]
         logger.info(f"📝 Applying Unsloth chat template: {matched_template}")
@@ -83,7 +79,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
             logger.info(f"⚠️ Failed to apply Unsloth template '{matched_template}': {e}")
             logger.info(f"   Falling back to tokenizer's default chat template")
     else:
-        # Check if tokenizer actually has a chat_template set
+        # Check whether the tokenizer has a chat_template set.
         has_chat_template = (
             hasattr(tokenizer, 'chat_template')
             and tokenizer.chat_template is not None
@@ -91,7 +87,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
         if has_chat_template:
             logger.info(f"📝 Using tokenizer's own chat template (no Unsloth template match)")
         else:
-            # Base model with no chat template — apply default ChatML
+            # Base model with no chat template — apply default ChatML.
             logger.info(f"📝 No chat template found — applying default ChatML template (base model)")
             try:
                 tokenizer = get_chat_template(
@@ -107,9 +103,7 @@ def get_tokenizer_chat_template(tokenizer, model_name):
 
 
 def get_dataset_info_summary(dataset_info):
-    """
-    Returns a human-readable summary for UI display.
-    """
+    """Return a human-readable summary for UI display."""
     detected_format = dataset_info["detected_format"]
     final_format = dataset_info["final_format"]
 
@@ -147,14 +141,14 @@ def apply_chat_template_to_dataset(
     progress_callback = None,
 ):
     """
-    Applies chat template to dataset based on its format.
+    Apply the chat template to a dataset based on its format.
 
     Args:
         dataset_info: Output from format_dataset() with metadata
         tokenizer: Tokenizer with chat template
         custom_prompt_template: Optional string template for custom formatting
-        add_eos_token: If True, appends tokenizer.eos_token to each text
-        remove_bos_prefix: If True, removes '' prefix (for Gemma, etc.)
+        add_eos_token: If True, append tokenizer.eos_token to each text
+        remove_bos_prefix: If True, remove '' prefix (Gemma, etc.)
         custom_format_mapping: Dict mapping custom columns to standard format
         batch_size: Batch size for processing
         num_proc: Number of processes
@@ -170,7 +164,7 @@ def apply_chat_template_to_dataset(
     warnings = list(dataset_info.get("warnings", []))
     errors = []
 
-    # Get EOS token if needed
+    # Get EOS token if needed.
     eos_token = ""
     if add_eos_token:
         if hasattr(tokenizer, 'eos_token') and tokenizer.eos_token:
@@ -180,9 +174,9 @@ def apply_chat_template_to_dataset(
 
     # CUSTOM FORMAT MAPPING (for non-standard datasets)
     if final_format == "unknown":
-        # Try auto-detection if no custom mapping provided
+        # Auto-detect if no custom mapping was provided.
         if custom_format_mapping is None and auto_detect_mapping:
-            # Check if format_dataset already tried and failed
+            # Skip if format_dataset already tried and failed.
             if not dataset_info.get("auto_detection_attempted", False):
                 custom_format_mapping = detect_custom_format_heuristic(dataset)
                 if custom_format_mapping:
@@ -196,7 +190,7 @@ def apply_chat_template_to_dataset(
                         "errors": errors
                     }
             else:
-                # Already failed once in format_dataset, don't retry
+                # Already failed once in format_dataset; don't retry.
                 errors.append(
                     "Format remains unknown after detection attempts. "
                     "Please provide custom_format_mapping to specify column roles manually."
@@ -216,7 +210,7 @@ def apply_chat_template_to_dataset(
                 conversations = []
                 num_examples = len(examples[list(examples.keys())[0]])
 
-                # Only preserve unmapped columns if auto-detected
+                # Preserve unmapped columns only if auto-detected.
                 preserved_columns = {}
                 if not is_user_provided:
                     all_columns = set(examples.keys())
@@ -236,10 +230,10 @@ def apply_chat_template_to_dataset(
                                 content = examples[col_name][i]
 
                                 if is_user_provided:
-                                    # User explicitly mapped - include even if empty
+                                    # User-mapped: include even if empty.
                                     convo.append({"role": role, "content": str(content) if content else ""})
                                 else:
-                                    # Auto-detected - skip empty
+                                    # Auto-detected: skip empty.
                                     if content and str(content).strip():
                                         convo.append({"role": role, "content": str(content)})
 
@@ -252,7 +246,7 @@ def apply_chat_template_to_dataset(
 
             try:
                 dataset = dataset.map(_apply_custom_mapping, batched = True, batch_size = batch_size)
-                # Update to use conversations format
+                # Switch to conversations format.
                 final_format = "chatml_conversations"
                 chat_column = "conversations"
                 is_standardized = True
@@ -269,8 +263,8 @@ def apply_chat_template_to_dataset(
     # ALPACA FORMAT
     if final_format == "alpaca":
 
-        # Set alpaca chat template on tokenizer for saving (if not already set)
-        # This ensures the template is saved with the model for inference
+        # Set alpaca chat template on the tokenizer (if unset) so it's
+        # saved with the model for inference.
         if not (hasattr(tokenizer, 'chat_template') and tokenizer.chat_template):
             try:
                 from unsloth.chat_templates import get_chat_template
@@ -283,7 +277,7 @@ def apply_chat_template_to_dataset(
             except Exception as e:
                 logger.info(f"⚠️ Could not set alpaca template on tokenizer: {e}")
 
-        # Use custom template if provided
+        # Use custom template if provided.
         def _format_alpaca_custom(examples):
             texts = []
             for i in range(len(examples["instruction"])):
@@ -349,7 +343,7 @@ def apply_chat_template_to_dataset(
         if not is_standardized:
             warnings.append("Dataset may not be fully standardized")
 
-        # Apply Unsloth chat template if model matches
+        # Apply Unsloth chat template if the model matches.
         if model_name:
             tokenizer = get_tokenizer_chat_template(tokenizer, model_name)
 
@@ -398,7 +392,7 @@ def apply_chat_template_to_dataset(
                 dataset_map_kwargs['num_proc'] = num_proc
                 dataset_map_kwargs['desc'] = f"Applying chat template to {final_format}"
 
-            # Monitor tqdm progress from dataset.map() and relay to callback
+            # Monitor tqdm progress from dataset.map() and relay it.
             _tqdm_monitor_stop = None
             if progress_callback and not _is_torch_iterable:
                 import threading
diff --git a/studio/backend/utils/datasets/data_collators.py b/studio/backend/utils/datasets/data_collators.py
index 2955ec9023..5f249b32f9 100644
--- a/studio/backend/utils/datasets/data_collators.py
+++ b/studio/backend/utils/datasets/data_collators.py
@@ -4,8 +4,7 @@
 """
 Data collators for dataset processing.
 
-This module contains custom data collators for training,
-particularly for VLM/OCR processing.
+Custom training collators, particularly for VLM/OCR processing.
 """
 
 from dataclasses import dataclass
@@ -20,9 +19,9 @@ class DataCollatorSpeechSeq2SeqWithPadding:
     """
     Data collator for Whisper speech-to-text training.
 
-    Pads input features (audio) and label sequences (text) separately,
-    masks padding in labels with -100, and strips leading BOS token.
-    Mirrors the collator from the Whisper.ipynb notebook.
+    Pads audio input features and text labels separately, masks label padding
+    with -100, and strips the leading BOS token. Mirrors the Whisper.ipynb
+    notebook collator.
     """
 
     processor: Any
@@ -71,7 +70,7 @@ class DeepSeekOCRDataCollator:
         """
         from PIL import Image
 
-        # Extract messages and images
+        # Extract messages and images.
         all_messages = []
         all_images = []
 
@@ -79,7 +78,7 @@ class DeepSeekOCRDataCollator:
             messages = sample["messages"]
             all_messages.append(messages)
 
-            # Extract PIL images from content
+            # Extract PIL images from content.
             for msg in messages:
                 content = msg.get("content", [])
                 if isinstance(content, list):
@@ -89,9 +88,9 @@ class DeepSeekOCRDataCollator:
                             if img is not None and hasattr(img, "size"):  # PIL Image
                                 all_images.append(img)
 
-        # Process with the VL processor
+        # Process with the VL processor.
         try:
-            # Qwen2VL style processing
+            # Qwen2VL-style processing.
             texts = [
                 self.processor.apply_chat_template(
                     msgs, tokenize = False, add_generation_prompt = False
@@ -99,7 +98,7 @@ class DeepSeekOCRDataCollator:
                 for msgs in all_messages
             ]
 
-            # Process with images
+            # Process with images.
             inputs = self.processor(
                 text = texts,
                 images = all_images if all_images else None,
@@ -109,10 +108,10 @@ class DeepSeekOCRDataCollator:
                 max_length = self.max_length,
             )
 
-            # Create labels (mask input, keep output)
+            # Create labels (mask input, keep output).
             labels = inputs["input_ids"].clone()
 
-            # Simple masking: mask padding tokens
+            # Mask padding tokens.
             labels[labels == self.processor.tokenizer.pad_token_id] = self.ignore_index
 
             inputs["labels"] = labels
@@ -138,7 +137,7 @@ class VLMDataCollator:
     processor: Any
     max_length: int = 2048
     ignore_index: int = -100
-    mask_input_tokens: bool = True  # Whether to mask user tokens in labels
+    mask_input_tokens: bool = True  # Mask user tokens in labels
 
     def __call__(self, batch: List[dict]) -> dict:
         """
@@ -151,7 +150,7 @@ class VLMDataCollator:
             messages = sample.get("messages", [])
             all_messages.append(messages)
 
-            # Extract images
+            # Extract images.
             for msg in messages:
                 content = msg.get("content", [])
                 if isinstance(content, list):
@@ -161,13 +160,13 @@ class VLMDataCollator:
                             if img is not None:
                                 all_images.append(img)
 
-        # Apply chat template
+        # Apply chat template.
         texts = [
             self.processor.apply_chat_template(msgs, tokenize = False, add_generation_prompt = False)
             for msgs in all_messages
         ]
 
-        # Process inputs
+        # Process inputs.
         inputs = self.processor(
             text = texts,
             images = all_images if all_images else None,
@@ -177,10 +176,10 @@ class VLMDataCollator:
             max_length = self.max_length,
         )
 
-        # Create labels
+        # Create labels.
         labels = inputs["input_ids"].clone()
 
-        # Mask padding
+        # Mask padding.
         if hasattr(self.processor, "tokenizer"):
             pad_token_id = self.processor.tokenizer.pad_token_id
         else:
diff --git a/studio/backend/utils/datasets/dataset_none_detect.py b/studio/backend/utils/datasets/dataset_none_detect.py
index e48e153fb8..354fd360d3 100644
--- a/studio/backend/utils/datasets/dataset_none_detect.py
+++ b/studio/backend/utils/datasets/dataset_none_detect.py
@@ -1,8 +1,8 @@
 """
 dataset_none_detect.py
 
-Detect None/empty content turns in conversation datasets.
-Reports findings without modifying data.
+Detect None/empty content turns in conversation datasets. Reports findings
+without modifying data.
 
 Usage:
     from .dataset_none_detect import scan_dataset, print_report
@@ -18,8 +18,8 @@ Supported formats (via FORMAT_REGISTRY):
     sharegpt   conversations                 from/value per turn
     gptoss     messages (alias: gpt-oss)     role/content; has a developer turn
 
-Any role/content chat template matches the chatml entry, so new templates need
-no change; add a FORMAT_REGISTRY entry only for a genuinely new column/turn shape.
+Any role/content chat template matches chatml, so new templates need no change;
+add a FORMAT_REGISTRY entry only for a genuinely new column/turn shape.
 """
 
 from datasets import Dataset
@@ -31,7 +31,7 @@ from datasets import Dataset
 # Candidate column names for conversational datasets, checked in priority order.
 CONVERSATION_COLUMNS = ("messages", "conversations", "texts")
 
-# Minimum turn key sets that identify a column as conversational (not e.g. messages=[{"id":1}]).
+# Minimum turn key sets identifying a column as conversational (not e.g. messages=[{"id":1}]).
 _CHAT_KEY_SETS = (frozenset({"role", "content"}), frozenset({"from", "value"}))
 
 
@@ -39,13 +39,13 @@ def _probe_conversation(dataset: Dataset, candidates = None):
     """
     Probe a dataset for its conversation column and turn structure.
 
-    candidates - iterable of column names to try, in priority order.
+    candidates - column names to try, in priority order.
                  Defaults to CONVERSATION_COLUMNS when None.
 
     Returns a dict with:
-        column    - name of the conversation column found
-        turn_keys - set of keys present in the first turn dict
-        roles     - set of all role values seen across the first few samples
+        column    - conversation column found
+        turn_keys - keys present in the first turn dict
+        roles     - all role values seen across the first few samples
 
     Returns None if no conversation column is found.
     """
@@ -53,12 +53,12 @@ def _probe_conversation(dataset: Dataset, candidates = None):
         candidates = CONVERSATION_COLUMNS
     columns = set(dataset.column_names)
     # Remember the first all-corrupt candidate, but keep probing: a later column
-    # may be healthy and should win (e.g. bad messages, good conversations).
+    # may be healthy and win (e.g. bad messages, good conversations).
     all_corrupt_fallback = None
     for col in candidates:
         if col not in columns:
             continue
-        # Scan up to 100 rows - row 0 alone may be empty or malformed.
+        # Scan up to 100 rows - row 0 alone may be empty/malformed.
         first = None
         for i in range(min(len(dataset), 100)):
             sample = dataset[i][col]
@@ -71,9 +71,9 @@ def _probe_conversation(dataset: Dataset, candidates = None):
                 break
         if first is None:
             # No usable dict turn in 100 rows. Record an all_corrupt fallback,
-            # marking it plausible only if we saw turn-shaped data (a None cell or
-            # a list holding a dict/None turn); scalars and list-of-strings must
-            # not look like chatml. Upgrade a non-plausible fallback when a later
+            # plausible only if we saw turn-shaped data (a None cell or a list
+            # holding a dict/None turn); scalars and list-of-strings must not
+            # look like chatml. Upgrade a non-plausible fallback when a later
             # candidate is plausible, so probe order keeps the best match.
             if all_corrupt_fallback is None or not all_corrupt_fallback.get("has_plausible_turns"):
                 has_plausible_turns = False
@@ -86,8 +86,8 @@ def _probe_conversation(dataset: Dataset, candidates = None):
                     # not chat: leave it for "unknown format", matching
                     # format_detection.py.
                     if isinstance(cell, list):
-                        # Plausible only if the list holds a dict/None turn; empty
-                        # lists and list-of-strings are not chat data.
+                        # Plausible only if the list holds a dict/None turn;
+                        # empty lists and list-of-strings are not chat data.
                         if any(t is None or isinstance(t, dict) for t in cell):
                             has_plausible_turns = True
                             break
@@ -112,11 +112,11 @@ def _probe_conversation(dataset: Dataset, candidates = None):
                         r = t.get("role") or t.get("from")
                         if r:
                             roles.add(str(r))
-        # Column lacks a full chat key pair. If it still has a conversational key
-        # (role/from/content/value) it is a corrupt-but-real chat column, so save
-        # a plausible fallback for find_none_chatml to flag. Pure metadata (e.g.
-        # [{"id":1}]) is not plausible, so a later real-but-corrupt column (e.g.
-        # conversations=None) can still win.
+        # Column lacks a full chat key pair. If it has a conversational key
+        # (role/from/content/value) it is a corrupt-but-real chat column, so
+        # save a plausible fallback for find_none_chatml to flag. Pure metadata
+        # (e.g. [{"id":1}]) is not plausible, so a later real-but-corrupt column
+        # (e.g. conversations=None) can still win.
         _CONV_KEYS = {"role", "from", "content", "value"}
         if not any(keys <= turn_keys for keys in _CHAT_KEY_SETS):
             schema_less_plausible = bool(turn_keys & _CONV_KEYS)
@@ -143,7 +143,7 @@ def is_none_or_empty(value) -> bool:
     if value is None:
         return True
     if isinstance(value, str):
-        # Treat zero-width/BOM chars (U+FEFF/200B/200C/200D/2060) as empty too;
+        # Treat zero-width/BOM chars (U+FEFF/200B/200C/200D/2060) as empty;
         # they render invisibly. Two-pass strip (ws, invisibles, ws) catches
         # mixed cases like "\u200b \u200b".
         stripped = value.strip().strip("\ufeff\u200b\u200c\u200d\u2060").strip()
@@ -156,7 +156,7 @@ def is_none_or_empty(value) -> bool:
         # exists (an image-only turn is valid).
         if len(value) == 0:
             return True
-        # No dict blocks at all (e.g. [None], ['  ']) -> malformed/empty.
+        # No dict blocks (e.g. [None], ['  ']) -> malformed/empty.
         dict_blocks = [item for item in value if isinstance(item, dict)]
         if not dict_blocks:
             return True
@@ -190,7 +190,7 @@ def _classify_empty(value) -> str:
         if len(value) == 0:
             return "empty_list"
         return "empty_vlm_content"
-    return "valid"  # should not reach here if is_none_or_empty was True
+    return "valid"  # unreachable if is_none_or_empty was True
 
 
 # ---------------------------------------------------------------------------
@@ -201,7 +201,7 @@ def _classify_empty(value) -> str:
 def find_none_alpaca(dataset: Dataset) -> dict:
     """
     Scan alpaca dataset for None/empty instruction or output fields.
-    Returns stats dict with a detailed 'findings' list.
+    Returns a stats dict with a detailed 'findings' list.
     """
     stats = {
         "total_rows": len(dataset),
@@ -242,8 +242,8 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
     Scan chatml/sharegpt/gptoss dataset for turns with None/empty content.
     Auto-detects the conversation column if col=None.
 
-    Returns a stats dict that includes a complete 'findings' list - one entry
-    per bad turn with row_index, turn_index, role, value_type, and raw_value.
+    Returns a stats dict with a complete 'findings' list - one entry per bad
+    turn with row_index, turn_index, role, value_type, and raw_value.
     """
     if col is None:
         # Reuse _probe_conversation so the all_corrupt path is handled here too.
@@ -292,7 +292,7 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
             continue
 
         if len(conversation) == 0:
-            # Zero-turn conversation: flag so it does not scan as clean.
+            # Zero-turn conversation: flag so it doesn't scan as clean.
             stats["bad_row_indices"].append(i)
             stats["rows_with_none_turns"] += 1
             stats["total_none_turns"] += 1
@@ -340,8 +340,8 @@ def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
                 role = r
             else:
                 role = str(r)
-            # Pick the content key: from+value -> value (ShareGPT, even if role is
-            # also set); role -> content (or value); from only -> value (None when
+            # Pick the content key: from+value -> value (ShareGPT, even if role
+            # is set); role -> content (or value); from only -> value (None when
             # missing, so it is flagged); neither -> content then value.
             if "from" in turn and "value" in turn:
                 content = turn.get("value")
@@ -388,7 +388,7 @@ def find_none_sharegpt(dataset: Dataset, col: str = None) -> dict:
     """ShareGPT uses 'from'/'value' keys - same scan logic handles both."""
     if col is None:
         # ShareGPT lives in 'conversations'; probe only that column so a corrupt
-        # one is still scanned, not replaced by a healthy 'messages' (P1 fix).
+        # one is still scanned, not replaced by healthy 'messages' (P1 fix).
         conv_info = _probe_conversation(dataset, candidates = ("conversations",))
         if conv_info is None:
             raise ValueError(
@@ -403,7 +403,7 @@ def find_none_gptoss(dataset: Dataset, col: str = None) -> dict:
     """gptoss: role/content plus optional thinking/tool_calls. Only content checked."""
     if col is None:
         # gptoss lives in 'messages': target it whenever present (even if
-        # corrupt), and fall back to 'conversations' only if 'messages' is absent.
+        # corrupt); fall back to 'conversations' only if 'messages' is absent.
         if "messages" in dataset.column_names:
             conv_info = _probe_conversation(dataset, candidates = ("messages",))
         else:
@@ -420,7 +420,7 @@ def find_none_gptoss(dataset: Dataset, col: str = None) -> dict:
 # ---------------------------------------------------------------------------
 # Format registry - first match wins; detect_format() auto-scales.
 # Each entry: name (label/--format value), match(dataset, conv_info) -> bool,
-# scan (find_none_* function). Put specific formats before generalisations
+# scan (find_none_* function). Put specific formats before general ones
 # (gptoss before chatml, since gptoss is chatml with a 'developer' role).
 # To add a format: write find_none_() (or reuse find_none_chatml) and
 # append an entry; detect_format(), --format, and scan_dataset() pick it up.
@@ -460,7 +460,7 @@ FORMAT_REGISTRY = [
             and (
                 {"role", "content"} <= conv["turn_keys"]
                 # all_corrupt: column found but every row malformed; require
-                # has_plausible_turns so scalar/string columns are not chatml.
+                # has_plausible_turns so scalar/string columns aren't chatml.
                 or (conv.get("all_corrupt") and conv.get("has_plausible_turns"))
             )
         ),
@@ -479,7 +479,7 @@ def detect_format(dataset: Dataset) -> str:
     """
     Auto-detect dataset format by probing columns and turn structure.
 
-    Returns one of the format names in FORMAT_REGISTRY, or 'unknown'.
+    Returns a format name from FORMAT_REGISTRY, or 'unknown'.
     Walks the registry in order; first match wins.
     """
     conv_info = _probe_conversation(dataset)
@@ -507,7 +507,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
     # Reject a DatasetDict / IterableDatasetDict (load_dataset without split):
     # its column_names is a split map and would yield a confusing "unknown
     # format". Check both (IterableDatasetDict is not a DatasetDict subclass);
-    # import locally so this module never hard-requires those symbols.
+    # import locally so this module never hard-requires them.
     _dict_types = []
     try:
         from datasets import DatasetDict as _DatasetDict
@@ -526,7 +526,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
             "Pass dataset[] or use load_dataset(..., split='train')."
         )
     # Streaming IterableDataset has no len()/column_names; give a clear error
-    # instead of a confusing TypeError downstream.
+    # instead of a confusing downstream TypeError.
     try:
         from datasets import IterableDataset as _IterableDataset
         if isinstance(dataset, _IterableDataset):
@@ -555,8 +555,8 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
             if entry["match"](dataset, conv_info):
                 fmt = entry["name"]
                 break
-        # No format matched: return clean stats (format="unknown") rather than
-        # raise, so callers can branch on stats["format"].
+        # No format matched: return clean stats (format="unknown") instead of
+        # raising, so callers can branch on stats["format"].
         if fmt == "unknown":
             return {
                 "format": "unknown",
@@ -567,7 +567,7 @@ def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
     scanner = get_scanner(fmt)
     if scanner is None:
         raise ValueError(f"Unknown or unsupported format: '{fmt}'")
-    # Column forwarding: on auto-detect pass the probed column (already the best
+    # Column forwarding: on auto-detect pass the probed column (the best
     # choice). On an explicit format let that scanner pick its own column, so
     # e.g. fmt='sharegpt' always scans 'conversations', not 'messages' (P1 fix);
     # gptoss has its own messages-first rule. alpaca never takes a column.
@@ -620,7 +620,7 @@ def _print_summary_header(stats: dict, fmt: str) -> bool:
         if rows_all:
             print(f"  Rows ALL bad: {rows_all} (every turn is None/empty)")
 
-    # Rows with no Nones - compute the count directly instead of allocating a
+    # Rows with no Nones - compute the count directly rather than allocating a
     # full set of row indices, which OOMs on large (10M+ row) datasets.
     bad_indices = set(stats.get("bad_row_indices", []))
     clean_count = total - len(bad_indices)
@@ -696,8 +696,8 @@ def show_row(
         print(f"  Row {ri}")
         print(f"{'=' * 64}")
 
-        # Print non-conversation columns. For alpaca, skip the fields the
-        # alpaca block below prints with status markers (avoid double render).
+        # Print non-conversation columns. For alpaca, skip fields the alpaca
+        # block below prints with status markers (avoid double render).
         _ALPACA_FIELDS = {"instruction", "input", "output"}
         for key in dataset.column_names:
             if key == col:
@@ -732,7 +732,7 @@ def show_row(
                         c = t.get("value")
                     else:
                         c = t.get("content") if "content" in t else t.get("value")
-                    # Mirror scanner logic: tool_calls exemption is assistant-only;
+                    # Mirror scanner: tool_calls exemption is assistant-only;
                     # other roles with empty content + tool_calls are still bad.
                     r = t.get("role") if t.get("role") is not None else t.get("from")
                     if is_none_or_empty(c) and not (str(r) == "assistant" and t.get("tool_calls")):
@@ -743,7 +743,7 @@ def show_row(
                 print(f"  {col}: {len(conversation)} turns ({none_count} None)")
                 print(f"  {'-' * 60}")
                 for i, turn in enumerate(conversation):
-                    # Non-dict turn - can't extract role or content normally.
+                    # Non-dict turn - can't extract role/content normally.
                     if not isinstance(turn, dict):
                         label = "None" if turn is None else "invalid_type"
                         print(f"  [{i:>3d}] {'unknown':<12s} [{label}]  << NONE")
diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.py
index 792e0ea9bc..03387e5331 100644
--- a/studio/backend/utils/datasets/dataset_utils.py
+++ b/studio/backend/utils/datasets/dataset_utils.py
@@ -4,12 +4,12 @@
 """
 Dataset utilities for format detection, conversion, and template application.
 
-This module provides the main entry points for dataset processing:
-- check_dataset_format: Lightweight check if manual mapping is needed (for frontend)
-- format_dataset: Detects and normalizes dataset formats
-- format_and_template_dataset: End-to-end processing with chat template application
+Main entry points for dataset processing:
+- check_dataset_format: lightweight check if manual mapping is needed (frontend)
+- format_dataset: detects and normalizes dataset formats
+- format_and_template_dataset: end-to-end processing with chat template
 
-All internal utilities have been moved to separate modules:
+Internal utilities live in separate modules:
 - format_detection: detect_dataset_format, detect_multimodal_dataset, etc.
 - format_conversion: standardize_chat_format, convert_chatml_to_alpaca, etc.
 - chat_templates: apply_chat_template_to_dataset, get_tokenizer_chat_template, etc.
@@ -54,8 +54,8 @@ def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
     """
     Lightweight format check without processing - for frontend validation.
 
-    Use this to quickly determine if user needs to manually map columns
-    before calling the full format_and_template_dataset().
+    Quickly determines if the user must manually map columns before the full
+    format_and_template_dataset().
 
     Args:
         dataset: HuggingFace dataset
@@ -121,7 +121,7 @@ def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
         }
 
     if is_audio:
-        # Audio dataset — require manual mapping only when columns can't be auto-detected
+        # Audio dataset — require manual mapping only when columns aren't auto-detected
         detected_audio = multimodal_info.get("detected_audio_column")
         detected_text = multimodal_info.get("detected_text_column")
         needs_mapping = not detected_audio or not detected_text
@@ -211,9 +211,9 @@ def _apply_user_mapping(
     Apply user-provided column mapping to convert dataset to conversations format.
 
     Accepts chatml (user/assistant/system), sharegpt (human/gpt/system), and
-    alpaca (instruction/input/output) role names — all normalised to chatml output.
+    alpaca (instruction/input/output) role names — all normalised to chatml.
 
-    If the mapping contains ``__``-prefixed metadata keys (from the conversion
+    If the mapping has ``__``-prefixed metadata keys (from the conversion
     advisor), routes to template-based conversion instead of simple role mapping.
 
     Returns:
@@ -262,7 +262,7 @@ def _apply_user_mapping(
 
 def _extract_column_value(val, col: str, label_mapping: dict) -> str:
     """Extract a string value from a column, handling complex types and label mapping."""
-    # Handle complex types (dicts, lists) — extract useful text instead of raw repr
+    # Complex types (dicts, lists): extract useful text instead of raw repr
     if isinstance(val, dict):
         # Common pattern: {"text": [...]} in QA datasets
         if "text" in val:
@@ -291,10 +291,9 @@ def _apply_template_mapping(
     """
     Apply advisor-driven mapping for non-conversational datasets.
 
-    Groups columns by their assigned role (user/assistant), concatenates
-    values within each role into a single message, and injects an optional
-    system prompt.  Label mapping is applied to convert integer labels
-    to human-readable strings.
+    Groups columns by assigned role (user/assistant), concatenates values
+    within each role into one message, and injects an optional system prompt.
+    Label mapping converts integer labels to human-readable strings.
 
     Returns:
         Dataset with single 'conversations' column
@@ -327,7 +326,7 @@ def _apply_template_mapping(
             if system_prompt:
                 convo.append({"role": "system", "content": system_prompt})
 
-            # User message: concatenate all user-role column values
+            # User message: concatenate user-role column values
             user_parts = []
             for col in role_groups["user"]:
                 if col in examples:
@@ -335,7 +334,7 @@ def _apply_template_mapping(
             if user_parts:
                 convo.append({"role": "user", "content": "\n".join(user_parts)})
 
-            # Assistant message: concatenate all assistant-role column values
+            # Assistant message: concatenate assistant-role column values
             asst_parts = []
             for col in role_groups["assistant"]:
                 if col in examples:
@@ -433,7 +432,7 @@ def format_dataset(
             "final_format": final format after processing,
             "chat_column": column name with chat data,
             "is_standardized": whether role names are standardized,
-            "requires_manual_mapping": True if format detection failed and user must map columns,
+            "requires_manual_mapping": True if detection failed and user must map columns,
             "warnings": list of warning messages
         }
     """
@@ -455,7 +454,7 @@ def format_dataset(
             "warnings": [notice.message for notice in raw_result.notices],
         }
 
-    # If user provided explicit mapping, skip detection and apply in the requested format
+    # If user provided explicit mapping, skip detection and apply it
     if custom_format_mapping:
         try:
             if format_type == "alpaca":
@@ -465,8 +464,8 @@ def format_dataset(
                 final_format = "alpaca"
                 chat_column = None
             else:
-                # auto / chatml / sharegpt / conversational — all produce chatml conversations
-                # (sharegpt is always standardized to role/content internally)
+                # auto / chatml / sharegpt / conversational all produce chatml
+                # conversations (sharegpt standardized to role/content internally)
                 mapped_dataset = _apply_user_mapping(dataset, custom_format_mapping, batch_size)
                 final_format = "chatml_conversations"
                 chat_column = "conversations"
@@ -577,11 +576,11 @@ def format_dataset(
                 "warnings": warnings,
             }
 
-        # Unknown - try standardization, if fails pass as is
+        # Unknown - try standardization, pass as-is on failure
         else:
             warnings.append(f"Unknown format detected. Keys found: {detected['sample_keys']}")
 
-            # NEW: Try heuristic detection
+            # Try heuristic detection
             if auto_detect_custom:
                 custom_mapping = detect_custom_format_heuristic(dataset)
                 if custom_mapping:
@@ -853,8 +852,8 @@ def format_and_template_dataset(
     progress_callback = None,
 ):
     """
-    Convenience function that combines format_dataset and apply_chat_template_to_dataset.
-    Perfect for UI workflows - one function does everything!
+    Combines format_dataset and apply_chat_template_to_dataset. Convenient for
+    UI workflows: one function does everything.
 
     Returns:
         dict: {
@@ -862,7 +861,7 @@ def format_and_template_dataset(
             "detected_format": Original format,
             "final_format": Format after processing,
             "success": Whether template application succeeded,
-            "requires_manual_mapping": True if format detection failed and user must map columns,
+            "requires_manual_mapping": True if detection failed and user must map columns,
             "warnings": List of warnings,
             "errors": List of errors,
             "summary": Human-readable summary
@@ -876,7 +875,7 @@ def format_and_template_dataset(
 
         multimodal_info = detect_multimodal_dataset(dataset)
 
-        # NEW: If user provided explicit mapping for VLM, use it directly
+        # If user provided explicit mapping for VLM, use it directly
         if custom_format_mapping:
             # Expect mapping like: {"image_col": "image", "caption_col": "text"}
             user_vlm_image_column = None
@@ -916,15 +915,15 @@ def format_and_template_dataset(
                         "errors": [],
                     }
                 except Exception as e:
-                    # User mapping failed — fall back to auto-detection instead
-                    # of giving up (handles stale cached mappings gracefully)
+                    # User mapping failed — fall back to auto-detection rather
+                    # than give up (handles stale cached mappings gracefully)
                     warnings.append(
                         f"User VLM mapping (image='{user_vlm_image_column}', "
                         f"text='{user_vlm_text_column}') failed: {e} — "
                         f"falling back to auto-detection"
                     )
                     logger.info(f"⚠️ User VLM mapping failed, falling back to auto-detection...")
-                    custom_format_mapping = None  # clear so auto-detection runs below
+                    custom_format_mapping = None  # so auto-detection runs below
             else:
                 errors.append(
                     f"Invalid VLM mapping: need 'image' and 'text' roles. Got: {custom_format_mapping}"
@@ -967,7 +966,7 @@ def format_and_template_dataset(
                     "errors": errors,
                 }
 
-        # Handle ShareGPT/ChatML + image column (e.g. ShareGPT4V, LLaVA-style)
+        # ShareGPT/ChatML + image column (e.g. ShareGPT4V, LLaVA-style)
         elif vlm_structure["format"] == "sharegpt_with_images":
             try:
                 dataset = convert_sharegpt_with_images_to_vlm_format(
@@ -1087,7 +1086,7 @@ def format_and_template_dataset(
             "errors": errors,
         }
 
-    # LLM FLOW (Existing code)
+    # LLM FLOW
     else:
         # Step 1: Format the dataset
         n_rows = len(dataset) if hasattr(dataset, "__len__") else None
@@ -1127,7 +1126,7 @@ def format_and_template_dataset(
             progress_callback(
                 status_message = f"Applying chat template to {detected} ({n_rows:,} rows)..."
             )
-        # Gemma emits a leading  that must be stripped for text-only chatml/sharegpt.
+        # Gemma emits a leading , stripped for text-only chatml/sharegpt.
         is_alpaca = format_type == "alpaca" or (
             format_type == "auto" and dataset_info["detected_format"] == "alpaca"
         )
@@ -1156,7 +1155,7 @@ def format_and_template_dataset(
         all_errors = template_result.get("errors", [])
 
         # If format_dataset returned "unknown" but apply_chat_template rescued
-        # it via heuristic detection, update final_format to reflect reality.
+        # it via heuristic detection, update final_format accordingly.
         final_format = dataset_info["final_format"]
         requires_manual = dataset_info.get("requires_manual_mapping", False)
         if final_format == "unknown" and template_result["success"]:
@@ -1170,7 +1169,7 @@ def format_and_template_dataset(
             "detected_format": dataset_info["detected_format"],
             "final_format": final_format,
             "chat_column": dataset_info.get("chat_column"),
-            "is_vlm": False,  # This is LLM flow
+            "is_vlm": False,  # LLM flow
             "success": template_result["success"],
             "requires_manual_mapping": requires_manual,
             "warnings": all_warnings,
diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.py
index 5433d3115c..09521e160c 100644
--- a/studio/backend/utils/datasets/format_conversion.py
+++ b/studio/backend/utils/datasets/format_conversion.py
@@ -2,10 +2,8 @@
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
 """
-Format conversion utilities for dataset processing.
-
-This module contains functions for converting between dataset formats
-(Alpaca, ShareGPT, ChatML) and standardizing chat formats.
+Dataset format conversion: convert between Alpaca, ShareGPT, and ChatML,
+and standardize chat formats.
 """
 
 import os
@@ -36,14 +34,14 @@ def standardize_chat_format(
     num_proc = None,
 ):
     """
-    Our own standardization function that handles BOTH messages and conversations.
-    Converts non-standard role names and keys to standard format.
+    Standardize BOTH messages and conversations: map non-standard role
+    names and keys to the standard format.
     """
     import collections
     import itertools
     from datasets import IterableDataset
 
-    # Check if vision tokenizer is used
+    # Detect a vision tokenizer
     is_vlm = False
     if tokenizer is not None:
         if hasattr(tokenizer, "image_processor") or hasattr(tokenizer, "tokenizer"):
@@ -51,7 +49,7 @@ def standardize_chat_format(
 
     column_names = set(next(iter(dataset)).keys())
 
-    #   Check for both 'conversations' and 'messages'
+    # Find the chat column
     chat_column = None
     if "conversations" in column_names:
         chat_column = "conversations"
@@ -69,7 +67,7 @@ def standardize_chat_format(
         for message in example[chat_column]:
             for key, value in message.items():
                 if type(value) is not str:
-                    continue  # Skip non-string values
+                    continue  # Skip non-strings
                 uniques[key].append(value)
 
     if len(uniques.keys()) != 2:
@@ -79,7 +77,7 @@ def standardize_chat_format(
     length_first = len(set(uniques[keys[0]]))
     length_second = len(set(uniques[keys[1]]))
 
-    # Determine which is role and which is content
+    # Fewer unique values => role; the other => content
     if length_first < length_second:
         role_key = keys[0]
         content_key = keys[1]
@@ -102,18 +100,15 @@ def standardize_chat_format(
         for convo in convos:
             new_convo = []
             for message in convo:
-                # Get original role and content
                 original_role = message.get(role_key, "")
                 original_content = message.get(content_key, "")
 
-                # Map to standard role name
                 standard_role = aliases_mapping.get(original_role, original_role)
 
-                # Handle VLM format
                 if is_vlm:
                     original_content = [{"type": "text", "text": original_content}]
 
-                # Create dict with EXPLICIT ORDER
+                # Keep EXPLICIT key order
                 new_message = {"role": standard_role, "content": original_content}
                 new_convo.append(new_message)
 
@@ -146,8 +141,7 @@ def convert_chatml_to_alpaca(
     num_proc = None,
 ):
     """
-    Converts ChatML format (messages OR conversations) to Alpaca format.
-    Handles both standardized and ShareGPT formats.
+    Convert ChatML (messages OR conversations) to Alpaca format.
 
     Supports:
     - "messages" or "conversations" column
@@ -160,7 +154,7 @@ def convert_chatml_to_alpaca(
         _is_torch_iterable = False
 
     def _convert(examples):
-        # Auto-detect which column name is used
+        # Auto-detect the column name
         chatml_data = (
             examples.get("messages") or examples.get("conversations") or examples.get("texts")
         )
@@ -177,20 +171,20 @@ def convert_chatml_to_alpaca(
             output = ""
 
             for msg in convo:
-                # Handle both standard and ShareGPT formats
+                # Standard and ShareGPT key names
                 role = msg.get("role") or msg.get("from")
                 content = msg.get("content") or msg.get("value")
 
-                # Get first user message as instruction
+                # First user message -> instruction
                 if role in ["user", "human", "input"] and not instruction:
                     instruction = content
-                # Get first assistant message as output
+                # First assistant message -> output
                 elif role in ["assistant", "gpt", "output"] and not output:
                     output = content
                     break  # Stop after first assistant response
 
             instructions.append(instruction)
-            inputs.append("")  # Alpaca typically has empty input
+            inputs.append("")  # Alpaca input usually empty
             outputs.append(output)
 
         return {"instruction": instructions, "input": inputs, "output": outputs}
@@ -220,9 +214,9 @@ def convert_alpaca_to_chatml(
     num_proc = None,
 ):
     """
-    Converts Alpaca format to ChatML format.
+    Convert Alpaca format to ChatML format.
 
-    Output format: Uses 'conversations' column with standard 'role'/'content' structure.
+    Output: 'conversations' column with standard 'role'/'content' dicts.
     """
     try:
         from torch.utils.data import IterableDataset
@@ -238,13 +232,12 @@ def convert_alpaca_to_chatml(
             input_text = examples.get("input", [""] * len(examples["instruction"]))[i]
             output = examples["output"][i]
 
-            # Combine instruction and input (if exists) for user message
+            # User message = instruction + input (if any)
             if input_text and input_text.strip():
                 user_content = f"{instruction}\n\n{input_text}".strip()
             else:
                 user_content = instruction
 
-            # Build conversation in standard ChatML format
             convo = [
                 {"role": "user", "content": user_content},
                 {"role": "assistant", "content": output},
@@ -294,17 +287,17 @@ def convert_to_vlm_format(
     progress_callback = None,
 ):
     """
-    Converts simple {image, text} format to VLM messages format.
+    Convert simple {image, text} format to VLM messages format.
 
     Returns a LIST, not a HuggingFace Dataset (to preserve PIL Images).
 
-    For URL-based image datasets, runs a 200-sample parallel probe first to
-    estimate download speed and failure rate, then reports time estimate or
-    warning through progress_callback before proceeding with the full conversion.
+    For URL-based image datasets, runs a 200-sample parallel probe first
+    to estimate download speed and failure rate, reporting a time
+    estimate or warning via progress_callback before the full conversion.
 
     Args:
-        progress_callback: Optional callable(status_message=str) to report
-                          progress to the training overlay.
+        progress_callback: Optional callable(status_message=str) to
+                          report progress to the training overlay.
 
     Returns:
         list: List of dicts with 'messages' field
@@ -313,11 +306,11 @@ def convert_to_vlm_format(
     from .vlm_processing import generate_smart_vlm_instruction
 
     def _notify(msg):
-        """Send status update to the training overlay if callback is available."""
+        """Send a status update to the training overlay if callback set."""
         if progress_callback:
             progress_callback(status_message = msg)
 
-    # Generate smart instruction if not provided
+    # Generate a smart instruction if none provided
     if instruction is None:
         instruction_info = generate_smart_vlm_instruction(
             dataset,
@@ -342,7 +335,7 @@ def convert_to_vlm_format(
 
     def _convert_single_sample(sample):
         """Convert a single sample to VLM format."""
-        # Get image (might be PIL Image, local path, URL, or bare filename)
+        # Image may be a PIL Image, local path, URL, or bare filename
         image_data = sample[image_column]
 
         if isinstance(image_data, str):
@@ -363,19 +356,18 @@ def convert_to_vlm_format(
             else:
                 image_data = Image.open(image_data).convert("RGB")
 
-        # Get text (if list of strings, pick a random one — e.g. multiple captions)
+        # Text: if a list (e.g. multiple captions), pick one at random
         text_data = sample[text_column]
         if isinstance(text_data, list) and len(text_data) > 0:
             import random
             text_data = random.choice(text_data)
 
-        # Get instruction (static or dynamic)
+        # Instruction: static or dynamic
         if uses_dynamic and instruction_column:
             current_instruction = sample[instruction_column]
         else:
             current_instruction = instruction
 
-        # Build VLM messages - simple structure
         messages = [
             {
                 "role": "user",
@@ -387,16 +379,15 @@ def convert_to_vlm_format(
             {"role": "assistant", "content": [{"type": "text", "text": text_data}]},
         ]
 
-        # Return dict with messages
         return {"messages": messages}
 
     total = len(dataset)
     first_image = next(iter(dataset))[image_column]
     has_urls = isinstance(first_image, str) and first_image.startswith(("http://", "https://"))
 
-    # ── Bare-filename detection: images stored as filenames (e.g. "img_001.png")
-    #    that don't exist locally.  Build a basename→repo_path lookup so we can
-    #    resolve them via hf_hub_download during conversion.
+    # ── Bare-filename detection: images stored as filenames (e.g.
+    #    "img_001.png") not present locally. Build a basename→repo_path
+    #    lookup to resolve them via hf_hub_download during conversion.
     _image_lookup = None
     _IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff")
     if (
@@ -431,7 +422,7 @@ def convert_to_vlm_format(
             logger.info(f"⚠️ Failed to build HF repo image lookup: {e}")
             _image_lookup = None
 
-    # ── URL probe: 200 samples with parallel workers to estimate speed + failure rate ──
+    # ── URL probe: 200 parallel samples to estimate speed + failure rate ──
     PROBE_SIZE = 200
     MAX_FAIL_RATE = 0.3
 
@@ -468,7 +459,7 @@ def convert_to_vlm_format(
                 f"{fail_rate:.0%} of the first {PROBE_SIZE} image URLs failed to download ({probe_fail}/{probe_total})",
                 "Images are external URLs, not embedded in the dataset",
             ]
-            # Try LLM-friendly warning
+            # LLM-friendly warning
             friendly = None
             try:
                 from .llm_assist import llm_generate_dataset_warning
@@ -490,7 +481,7 @@ def convert_to_vlm_format(
             _notify(msg)
             raise ValueError(msg)
 
-        # Estimate total time for remaining samples
+        # Estimate time for remaining samples
         remaining = total - PROBE_SIZE
         estimated_seconds = remaining / throughput if throughput > 0 else 0
         eta_str = _format_eta(estimated_seconds)
@@ -546,7 +537,7 @@ def convert_to_vlm_format(
 
             converted_list.extend(r for r in batch_results if r is not None)
 
-            # Progress update every batch
+            # Per-batch progress update
             elapsed = time.time() - start_time
             done = batch_end
             rate = done / elapsed if elapsed > 0 else 0
@@ -558,7 +549,7 @@ def convert_to_vlm_format(
             )
             _notify(progress_msg)
     else:
-        # Sequential conversion for local/embedded images (fast, no I/O bottleneck)
+        # Sequential conversion for local/embedded images (no I/O bottleneck)
         pbar = tqdm(dataset, total = total, desc = "Converting VLM samples", unit = "sample")
         for sample in pbar:
             try:
@@ -576,7 +567,7 @@ def convert_to_vlm_format(
         logger.info(
             f"⚠️ Skipped {failed_count}/{total} ({fail_rate:.0%}) samples with broken/unreachable images"
         )
-        # For datasets that skipped the probe (small URL datasets), check fail rate now
+        # Small URL datasets skip the probe; check fail rate here
         if has_urls and fail_rate >= MAX_FAIL_RATE:
             issues = [
                 f"{fail_rate:.0%} of images failed to download ({failed_count}/{total})",
@@ -629,7 +620,7 @@ def convert_to_vlm_format(
     logger.info(f"✅ Converted {len(converted_list)}/{total} samples")
     _notify(f"Converted {len(converted_list):,}/{total:,} images successfully")
 
-    # Return list, NOT Dataset
+    # Return list, NOT a Dataset
     return converted_list
 
 
@@ -641,8 +632,8 @@ def convert_sharegpt_with_images_to_vlm_format(
     progress_callback = None,
 ):
     """
-    Converts ShareGPT/ChatML datasets that have a separate image column and
-    ```` placeholders inside the conversation text.
+    Convert ShareGPT/ChatML datasets with a separate image column and
+    ```` placeholders in the conversation text.
 
     Example input::
 
@@ -672,7 +663,7 @@ def convert_sharegpt_with_images_to_vlm_format(
         if progress_callback:
             progress_callback(status_message = msg)
 
-    # ── Resolve image loading strategy (same 3-tier as convert_to_vlm_format) ──
+    # ── Resolve image loading (same 3-tier as convert_to_vlm_format) ──
     total = len(dataset)
     first_image = next(iter(dataset))[image_column]
 
@@ -696,7 +687,7 @@ def convert_sharegpt_with_images_to_vlm_format(
                 for f in repo_files
                 if any(f.lower().endswith(ext) for ext in _IMAGE_EXTS)
             }
-            # Also add the full relative paths as keys (for paths like "sam/images/sa_545504.jpg")
+            # Also key by full relative path (e.g. "sam/images/sa_545504.jpg")
             for f in repo_files:
                 if any(f.lower().endswith(ext) for ext in _IMAGE_EXTS):
                     _image_lookup[f] = f
@@ -714,7 +705,7 @@ def convert_sharegpt_with_images_to_vlm_format(
             _image_lookup = None
 
     def _resolve_image(image_data):
-        """Resolve image data to a PIL Image object."""
+        """Resolve image data to a PIL Image."""
         if hasattr(image_data, "size") and hasattr(image_data, "mode"):
             return image_data  # Already PIL
         if isinstance(image_data, str):
@@ -742,7 +733,7 @@ def convert_sharegpt_with_images_to_vlm_format(
         raise ValueError(f"Cannot resolve image: {type(image_data)}")
 
     def _convert_single_sample(sample):
-        """Convert a single ShareGPT+image sample to standard VLM format."""
+        """Convert one ShareGPT+image sample to standard VLM format."""
         pil_image = _resolve_image(sample[image_column])
         conversation = sample[messages_column]
 
@@ -752,7 +743,7 @@ def convert_sharegpt_with_images_to_vlm_format(
             role = _ROLE_MAP.get(role_raw.lower(), role_raw.lower())
             text = msg.get("value") or msg.get("content") or ""
 
-            # Split on  to interleave text and image content blocks
+            # Interleave text and image blocks around 
             if "" in text:
                 parts = text.split("")
                 content = []
@@ -762,7 +753,7 @@ def convert_sharegpt_with_images_to_vlm_format(
                         content.append({"type": "text", "text": part})
                     if i < len(parts) - 1:
                         content.append({"type": "image", "image": pil_image})
-                # If  was the entire text, content might just be the image
+                # If text was only , content is just the image
                 if not content:
                     content.append({"type": "image", "image": pil_image})
             else:
@@ -804,7 +795,7 @@ def convert_sharegpt_with_images_to_vlm_format(
 
 def convert_llava_to_vlm_format(dataset):
     """
-    Converts Llava format to standard VLM format.
+    Convert Llava format to standard VLM format.
 
     Llava format:
     - messages: [{'content': [{'type': 'image', 'index': 0}, {'type': 'text', 'text': '...'}]}]
@@ -818,23 +809,22 @@ def convert_llava_to_vlm_format(dataset):
     logger.info(f"🔄 Converting {len(dataset)} samples from Llava format to standard VLM format...")
 
     def _convert_single_sample(sample):
-        """Convert a single llava sample to standard VLM format."""
+        """Convert one llava sample to standard VLM format."""
         messages = sample["messages"]
         images = sample.get("images", [])
 
-        # Process each message
         new_messages = []
         for msg in messages:
             new_content = []
 
             for item in msg["content"]:
                 if item["type"] == "image":
-                    # Replace index with actual PIL image
+                    # Replace index with the actual PIL image
                     if "index" in item and item["index"] is not None:
                         img_idx = item["index"]
                         if img_idx < len(images):
                             pil_image = images[img_idx]
-                            # Ensure it's PIL
+                            # Ensure PIL
                             if isinstance(pil_image, str):
                                 pil_image = Image.open(pil_image).convert("RGB")
 
@@ -845,7 +835,7 @@ def convert_llava_to_vlm_format(dataset):
                                 }
                             )
                     else:
-                        # No index, try to use first image
+                        # No index: use the first image
                         if len(images) > 0:
                             pil_image = images[0]
                             if isinstance(pil_image, str):
@@ -854,14 +844,12 @@ def convert_llava_to_vlm_format(dataset):
                             new_content.append({"type": "image", "image": pil_image})
 
                 elif item["type"] == "text":
-                    # Keep text as-is (only type + text)
                     new_content.append({"type": "text", "text": item.get("text", "")})
 
             new_messages.append({"role": msg["role"], "content": new_content})
 
         return {"messages": new_messages}
 
-    # Convert using list comprehension
     converted_list = [_convert_single_sample(sample) for sample in dataset]
 
     logger.info(f"✅ Converted {len(converted_list)} samples")
diff --git a/studio/backend/utils/datasets/format_detection.py b/studio/backend/utils/datasets/format_detection.py
index 829838064a..72f8f48cf7 100644
--- a/studio/backend/utils/datasets/format_detection.py
+++ b/studio/backend/utils/datasets/format_detection.py
@@ -1,11 +1,10 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Format detection utilities for dataset processing.
+"""Format detection utilities for dataset processing.
 
-This module contains functions for detecting dataset formats (Alpaca, ShareGPT, ChatML),
-detecting multimodal/VLM dataset structures, and heuristic-based column mapping.
+Detects dataset formats (Alpaca, ShareGPT, ChatML), multimodal/VLM
+structures, and heuristic column mapping.
 """
 
 import re
@@ -17,8 +16,7 @@ def _keyword_in_column(keyword: str, col_name: str) -> bool:
 
 
 def detect_dataset_format(dataset):
-    """
-    Detects dataset format by inspecting structure.
+    """Detect dataset format by inspecting structure.
 
     Returns:
         dict: {
@@ -30,7 +28,7 @@ def detect_dataset_format(dataset):
     """
     column_names = set(next(iter(dataset)).keys())
 
-    # Check for Alpaca
+    # Alpaca
     alpaca_columns = {"instruction", "output"}
     if alpaca_columns.issubset(column_names):
         return {
@@ -40,7 +38,7 @@ def detect_dataset_format(dataset):
             "sample_keys": [],
         }
 
-    # Check for chat-based formats (messages or conversations)
+    # Chat-based formats (messages or conversations)
     chat_column = None
     if "messages" in column_names:
         chat_column = "messages"
@@ -50,7 +48,7 @@ def detect_dataset_format(dataset):
         chat_column = "texts"
 
     if chat_column:
-        # Inspect the structure to determine if ShareGPT or ChatML
+        # Inspect structure: ShareGPT or ChatML?
         try:
             sample = next(iter(dataset))
             chat_data = sample[chat_column]
@@ -77,7 +75,7 @@ def detect_dataset_format(dataset):
                         "sample_keys": list(msg_keys),
                     }
 
-                # Unknown structure but has chat column
+                # Has chat column but unknown structure
                 else:
                     return {
                         "format": "unknown",
@@ -104,8 +102,7 @@ def detect_dataset_format(dataset):
 
 
 def detect_custom_format_heuristic(dataset):
-    """
-    Smart detection with priority scoring.
+    """Detection with priority scoring.
 
     Strategy for ambiguous keywords like 'task':
     1. Detect assistant first (unambiguous)
@@ -159,7 +156,7 @@ def detect_custom_format_heuristic(dataset):
         "persona",
         "role",
         "template",
-        "task",  # Also in system
+        "task",  # also a system keyword
     ]
 
     # Metadata columns to ignore
@@ -197,7 +194,7 @@ def detect_custom_format_heuristic(dataset):
     }
 
     def has_keyword(col_name, keywords):
-        """Check if any keyword appears in column name."""
+        """True if any keyword appears in the column name."""
         col_lower = col_name.lower()
         col_normalized = col_lower.replace("_", "").replace("-", "").replace(" ", "")
 
@@ -207,7 +204,7 @@ def detect_custom_format_heuristic(dataset):
         return False
 
     def is_metadata(col_name):
-        """Check if column is likely metadata."""
+        """True if the column is likely metadata."""
         col_lower = col_name.lower()
 
         if col_lower in metadata_exact_match:
@@ -229,7 +226,7 @@ def detect_custom_format_heuristic(dataset):
         return False
 
     def get_priority_score(col_name):
-        """Calculate priority score based on column name patterns."""
+        """Priority score from column-name patterns."""
         col_lower = col_name.lower()
         score = 0
 
@@ -240,7 +237,7 @@ def detect_custom_format_heuristic(dataset):
         return score
 
     def get_content_length(col_name):
-        """Get average content length for this column."""
+        """Average content length for this column."""
         try:
             if col_name in sample and sample[col_name]:
                 content = str(sample[col_name])
@@ -250,7 +247,7 @@ def detect_custom_format_heuristic(dataset):
             return 0
 
     def score_column(col_name, keywords, role_type, num_candidates):
-        """Score a column for how likely it is to be a particular role."""
+        """Score how likely a column is to be a given role."""
         if not has_keyword(col_name, keywords):
             return 0
 
@@ -260,7 +257,7 @@ def detect_custom_format_heuristic(dataset):
         # Penalize ambiguous keywords when scoring for user
         if role_type == "user":
             col_lower = col_name.lower()
-            # If column is ONLY "task" (or task_xxx), give it lower priority for user role
+            # ONLY "task" (or task_xxx): lower priority for user role
             if "task" in col_lower and not any(kw in col_lower for kw in user_words_high_priority):
                 score -= 15  # Significant penalty so other user columns win
 
@@ -289,10 +286,10 @@ def detect_custom_format_heuristic(dataset):
 
         return score
 
-    # Filter out metadata columns
+    # Drop metadata columns
     content_columns = [col for col in all_columns if not is_metadata(col)]
 
-    # Count candidates first
+    # Count candidates
     assistant_potential = [col for col in content_columns if has_keyword(col, assistant_words)]
     user_potential = [col for col in content_columns if has_keyword(col, user_words)]
 
@@ -332,7 +329,7 @@ def detect_custom_format_heuristic(dataset):
     system_col = None
     for col in remaining_columns:
         if has_keyword(col, system_words):
-            # Found a system match in remaining columns
+            # System match found
             mapping[col] = "system"
             system_col = col
             break
@@ -344,17 +341,17 @@ def detect_custom_format_heuristic(dataset):
     if len(remaining_columns) >= 1:
         remaining_col = remaining_columns[0]
 
-        # If no strong keyword match, decide based on what's missing
+        # No strong keyword match: decide by what's missing
         if not has_keyword(remaining_col, user_words + assistant_words):
             mapping[remaining_col] = "system"
         elif user_col is None:
-            # No user column yet, assign this as user
+            # No user column yet: assign this as user
             mapping[remaining_col] = "user"
         else:
-            # Already have user + assistant, treat as system context
+            # Already have user + assistant: treat as system context
             mapping[remaining_col] = "system"
 
-    # VALIDATION: Ensure we have at least user + assistant
+    # Ensure we have at least user + assistant
     has_user = any(role == "user" for role in mapping.values())
     has_assistant = any(role == "assistant" for role in mapping.values())
 
@@ -372,12 +369,11 @@ def detect_custom_format_heuristic(dataset):
 
 
 def detect_multimodal_dataset(dataset):
-    """
-    Detects if dataset contains multimodal data (images and/or audio).
+    """Detect multimodal data (images and/or audio) in a dataset.
 
-    Two-pass approach for each modality:
-      1. Column-name heuristic (fast): checks for keywords.
-      2. Value-type inspection (reliable): checks actual sample values.
+    Two passes per modality:
+      1. Column-name heuristic (fast): keyword match.
+      2. Value-type inspection (reliable): check actual sample values.
 
     Returns:
         dict: {
@@ -393,7 +389,7 @@ def detect_multimodal_dataset(dataset):
     sample = next(iter(dataset))
     column_names = list(sample.keys())
 
-    # Keywords that indicate image data
+    # Image keywords
     image_keywords = [
         "image",
         "img",
@@ -414,7 +410,7 @@ def detect_multimodal_dataset(dataset):
         "filename",
     ]
 
-    # Keywords that indicate audio data
+    # Audio keywords
     audio_keywords = ["audio", "speech", "wav", "waveform", "sound"]
 
     multimodal_columns = []
@@ -422,8 +418,8 @@ def detect_multimodal_dataset(dataset):
     modality_types = set()
 
     # ── Image detection ─────────────────────────────────────
-    # Pass 1: column-name heuristic (word-boundary match to avoid
-    #          false positives like 'pic' in 'topic')
+    # Pass 1: column-name heuristic (word-boundary match avoids false
+    #          positives like 'pic' in 'topic')
     for col_name in column_names:
         for keyword in image_keywords:
             if _keyword_in_column(keyword, col_name):
@@ -460,13 +456,13 @@ def detect_multimodal_dataset(dataset):
             audio_columns.append(col_name)
             modality_types.add("audio")
 
-    # Filter out columns that are actually audio from the image list
-    # (e.g. a column named "audio" with {"bytes", "path"} could match _is_image_value)
+    # Drop audio columns from the image list (e.g. a column named "audio"
+    # with {"bytes", "path"} could match _is_image_value)
     if audio_columns:
         audio_set = set(audio_columns)
         multimodal_columns = [c for c in multimodal_columns if c not in audio_set]
 
-    # Detect text column for audio datasets
+    # Text column for audio datasets
     detected_text_col = None
     if audio_columns:
         text_keywords = ["text", "sentence", "transcript", "transcription", "label"]
@@ -477,7 +473,7 @@ def detect_multimodal_dataset(dataset):
 
     is_audio = len(audio_columns) > 0
 
-    # Detect speaker_id column for TTS datasets (CSM, Orpheus, Spark)
+    # speaker_id column for TTS datasets (CSM, Orpheus, Spark)
     detected_speaker_col = None
     if audio_columns:
         speaker_keywords = ["source", "speaker", "speaker_id"]
@@ -511,14 +507,13 @@ def _is_image_value(value) -> bool:
     except ImportError:
         pass
 
-    # HF datasets Image feature stores decoded images as PIL or dicts with
-    # {"bytes": b"...", "path": "..."} when not yet decoded.
+    # HF Image feature: decoded as PIL, or {"bytes", "path"} when undecoded.
     # Exclude audio dicts (decoded audio has "array" + "sampling_rate").
     if isinstance(value, dict):
         if "array" in value and "sampling_rate" in value:
-            return False  # This is audio, not image
+            return False  # audio, not image
         if "bytes" in value and "path" in value:
-            # Check path extension to exclude audio files
+            # Use path extension to exclude audio files
             path = value.get("path") or ""
             if isinstance(path, str) and any(
                 path.lower().endswith(ext) for ext in _AUDIO_EXTENSIONS
@@ -539,7 +534,7 @@ def _is_image_value(value) -> bool:
             lower.split("?")[0].endswith(ext) for ext in _IMAGE_EXTS
         ):
             return True
-        # Image file path (relative or absolute path ending in image extension)
+        # Image file path (relative or absolute)
         if any(lower.endswith(ext) for ext in _IMAGE_EXTS):
             return True
 
@@ -564,11 +559,11 @@ def _is_audio_value(value) -> bool:
     if value is None:
         return False
 
-    # HF datasets Audio feature: decoded → {"array": np.ndarray, "sampling_rate": int}
+    # HF Audio feature: decoded → {"array": np.ndarray, "sampling_rate": int}
     if isinstance(value, dict):
         if "array" in value and "sampling_rate" in value:
             return True
-        # Undecoded/streaming → {"bytes": b"...", "path": "some.wav"}
+        # Undecoded/streaming → {"bytes", "path": "some.wav"}
         if "bytes" in value or "path" in value:
             path = value.get("path") or ""
             if isinstance(path, str) and any(
@@ -602,9 +597,8 @@ def _has_image_header(data: bytes) -> bool:
 
 
 def detect_vlm_dataset_structure(dataset):
-    """
-    Detects if VLM dataset is:
-    - Standard VLM messages format (image objects in content)
+    """Detect which VLM dataset shape this is:
+    - Standard VLM messages (image objects in content)
     - Llava format (image indices + separate images column)
     - Simple format needing conversion (image + text columns)
     """
@@ -621,7 +615,7 @@ def detect_vlm_dataset_structure(dataset):
 
     column_names = set(sample.keys())
 
-    # Check if has messages column
+    # Has messages column?
     if "messages" in column_names:
         messages = sample["messages"]
 
@@ -632,7 +626,7 @@ def detect_vlm_dataset_structure(dataset):
 
                 if isinstance(content, list) and len(content) > 0:
                     if isinstance(content[0], dict) and "type" in content[0]:
-                        # Check for llava format
+                        # Llava format?
                         has_index = any(
                             "index" in item for item in content if isinstance(item, dict)
                         )
@@ -660,8 +654,8 @@ def detect_vlm_dataset_structure(dataset):
                                 "text_column": None,
                             }
 
-    # Check for ShareGPT/ChatML conversations with  placeholder + companion image column
-    # (e.g. Lin-Chen/ShareGPT4V, LLaVA-style datasets)
+    # ShareGPT/ChatML conversations with  placeholder + companion
+    # image column (e.g. Lin-Chen/ShareGPT4V, LLaVA-style datasets)
     for chat_col in ("conversations", "messages"):
         if chat_col not in column_names:
             continue
@@ -671,11 +665,11 @@ def detect_vlm_dataset_structure(dataset):
         first_msg = chat_data[0]
         if not isinstance(first_msg, dict):
             continue
-        # Detect ShareGPT (from/value) or ChatML (role/content) keys
+        # ShareGPT (from/value) or ChatML (role/content) keys
         msg_text = first_msg.get("value") or first_msg.get("content")
         if not isinstance(msg_text, str):
             continue
-        # Check for  placeholder anywhere in the conversation
+        #  placeholder anywhere in the conversation?
         has_image_placeholder = any(
             "" in str(m.get("value", "") or m.get("content", ""))
             for m in chat_data
@@ -700,9 +694,7 @@ def detect_vlm_dataset_structure(dataset):
                 "messages_column": chat_col,
             }
 
-    # Find image and text columns using metadata filtering
-
-    # Define metadata patterns to EXCLUDE
+    # Find image and text columns, filtering out metadata patterns
     metadata_patterns = {
         "suffixes": [
             "_id",
@@ -726,7 +718,7 @@ def detect_vlm_dataset_structure(dataset):
         ],
     }
 
-    # Image-related keywords
+    # Image keywords
     image_keywords = [
         "image",
         "img",
@@ -739,7 +731,7 @@ def detect_vlm_dataset_structure(dataset):
         "filename",
     ]
 
-    # Text-related keywords
+    # Text keywords
     text_keywords = [
         "text",
         "caption",
@@ -752,14 +744,14 @@ def detect_vlm_dataset_structure(dataset):
     ]
 
     def is_metadata_column(col_name):
-        """Check if column name looks like metadata."""
+        """True if the column name looks like metadata."""
         col_lower = col_name.lower()
 
-        # Check suffixes
+        # Suffixes
         if any(col_lower.endswith(suffix) for suffix in metadata_patterns["suffixes"]):
             return True
 
-        # Check prefixes
+        # Prefixes
         if any(col_lower.startswith(prefix) for prefix in metadata_patterns["prefixes"]):
             return True
 
@@ -767,16 +759,16 @@ def detect_vlm_dataset_structure(dataset):
 
     def _score_image_candidate(col, sample_value):
         """Score a candidate image column by how resolvable its value is."""
-        # PIL Image object (highest priority - already loaded)
+        # PIL Image object (already loaded -> highest)
         if hasattr(sample_value, "size") and hasattr(sample_value, "mode"):
             return 100
 
-        # Dict with image data (bytes/path from HF Image feature)
+        # Dict with bytes/path from HF Image feature
         if isinstance(sample_value, dict) and ("bytes" in sample_value or "path" in sample_value):
             return 75
 
         if isinstance(sample_value, str):
-            # URL strings
+            # URL
             if sample_value.startswith(("http://", "https://")):
                 return 70 if not is_metadata_column(col) else 55
             # Bare file path
@@ -787,8 +779,8 @@ def detect_vlm_dataset_structure(dataset):
         return 0
 
     def _probe_image_candidate(col, sample_value):
-        """Quick probe to check if an image candidate is actually reachable.
-        Returns True if likely valid, False if definitely broken."""
+        """Probe whether an image candidate is reachable.
+        True if likely valid, False if definitely broken."""
         import os
 
         # PIL / dict — already loaded, always valid
@@ -799,7 +791,7 @@ def detect_vlm_dataset_structure(dataset):
         if not sample_value.startswith(("http://", "https://")):
             return os.path.exists(sample_value)  # bare filenames return False here, that's OK
 
-        # URL — quick HEAD request with short timeout
+        # URL — quick HEAD with short timeout
         try:
             import urllib.request
 
@@ -810,8 +802,8 @@ def detect_vlm_dataset_structure(dataset):
             return False
 
     def find_image_column():
-        """Find image column by keyword match + value-based fallback.
-        When multiple candidates exist, probes them to find one that works."""
+        """Find image column by keyword match + value-based fallback,
+        probing candidates to find one that works."""
         candidates = []
 
         # Pass 1: keyword-matched columns
@@ -822,8 +814,8 @@ def detect_vlm_dataset_structure(dataset):
                 if score > 0:
                     candidates.append((col, score))
 
-        # Pass 2: value-based fallback — find columns with image URLs/paths
-        # even if the column name doesn't match image keywords
+        # Pass 2: value-based fallback — columns with image URLs/paths
+        # even if the name doesn't match image keywords
         already = {c[0] for c in candidates}
         for col in column_names:
             if col in already:
@@ -831,7 +823,7 @@ def detect_vlm_dataset_structure(dataset):
             sample_value = sample[col]
             if _is_image_value(sample_value):
                 score = _score_image_candidate(col, sample_value)
-                # Slightly penalise non-keyword columns so keyword matches win on ties
+                # Penalise non-keyword columns so keyword matches win on ties
                 candidates.append((col, max(score - 5, 1)))
 
         if not candidates:
@@ -839,48 +831,47 @@ def detect_vlm_dataset_structure(dataset):
 
         candidates.sort(key = lambda x: x[1], reverse = True)
 
-        # Single candidate or top candidate is PIL/dict — no probing needed
+        # Single candidate or top is PIL/dict — no probing needed
         if len(candidates) == 1 or candidates[0][1] >= 75:
             return candidates[0][0]
 
-        # Multiple string-based candidates — probe to find one that actually works
+        # Multiple string candidates — probe for one that works
         for col, score in candidates:
             sample_value = sample[col]
             if _probe_image_candidate(col, sample_value):
                 return col
 
-        # Nothing probed successfully — return highest-scored anyway and let
-        # conversion handle the error (it may still resolve via hf_hub_download)
+        # None probed OK — return highest-scored and let conversion handle
+        # the error (it may still resolve via hf_hub_download)
         return candidates[0][0]
 
     def find_text_column():
-        """Find text column by filtering out metadata and checking keywords."""
+        """Find text column: skip metadata, match keywords."""
         candidates = []
 
         for col in column_names:
-            # Skip metadata columns
             if is_metadata_column(col):
                 continue
 
-            # Check if contains text keywords (word-boundary match)
+            # Text keyword (word-boundary match)
             if any(_keyword_in_column(keyword, col) for keyword in text_keywords):
                 # Verify it's actually text
                 sample_value = sample[col]
 
                 if isinstance(sample_value, str) and len(sample_value) > 0:
-                    # Longer text = higher priority (likely content, not just a label)
-                    priority = min(len(sample_value), 1000)  # Cap at 1000
+                    # Longer text = higher priority (content, not a label)
+                    priority = min(len(sample_value), 1000)  # cap at 1000
                     candidates.append((col, priority))
                 elif (
                     isinstance(sample_value, list)
                     and len(sample_value) > 0
                     and isinstance(sample_value[0], str)
                 ):
-                    # List of strings (e.g. captions list) — lower priority than plain strings
+                    # List of strings (e.g. captions) — lower priority than plain str
                     priority = min(len(sample_value[0]), 1000) // 2
                     candidates.append((col, priority))
 
-        # Return highest priority candidate
+        # Highest-priority candidate
         if candidates:
             candidates.sort(key = lambda x: x[1], reverse = True)
             return candidates[0][0]
diff --git a/studio/backend/utils/datasets/llm_assist.py b/studio/backend/utils/datasets/llm_assist.py
index 10004ce3db..d6bb0dc91d 100644
--- a/studio/backend/utils/datasets/llm_assist.py
+++ b/studio/backend/utils/datasets/llm_assist.py
@@ -4,13 +4,13 @@
 """
 LLM-assisted dataset analysis using an ephemeral GGUF helper model.
 
-Complements heuristic-based detection in format_detection.py and
-vlm_processing.py.  Only invoked when heuristics are uncertain.
+Complements heuristic detection in format_detection.py and vlm_processing.py.
+Only invoked when heuristics are uncertain.
 
 Architecture:
   - Instantiates LlamaCppBackend, loads model, runs completion(s), unloads.
   - Not kept warm — VRAM is freed immediately after use.
-  - Gracefully degrades: returns None when unavailable (no binary, OOM, disabled).
+  - Degrades gracefully: returns None when unavailable (no binary, OOM, disabled).
 """
 
 import json
@@ -35,20 +35,19 @@ README_MAX_CHARS = 1500
 def _strip_think_tags(text: str) -> str:
     """Strip ... reasoning blocks emitted by some models.
 
-    If the model places its actual answer OUTSIDE the think block, we
-    discard the think block and keep the rest.  If the entire response
-    is INSIDE a think block (nothing useful outside), we extract and
-    return the inner content instead of discarding everything.
+    If the answer is OUTSIDE the think block, discard the block and keep the
+    rest. If the entire response is INSIDE a think block (nothing useful
+    outside), return the inner content instead of discarding everything.
     """
     if "" not in text:
         return text
 
-    # Try stripping think blocks — keep content outside them
+    # Strip think blocks — keep content outside them
     stripped = re.sub(r".*?\s*", "", text, flags = re.DOTALL).strip()
     if stripped:
         return stripped
 
-    # Everything was inside  tags — extract the inner content of the last block
+    # Everything was inside  tags — return the last block's inner content
     matches = re.findall(r"(.*?)", text, flags = re.DOTALL)
     if matches:
         return matches[-1].strip()
@@ -60,9 +59,9 @@ def precache_helper_gguf():
     """
     Pre-download the helper GGUF to HF cache.
 
-    Called on FastAPI startup in a background thread so subsequent
+    Called on FastAPI startup in a background thread so later
     ``_run_with_helper()`` calls skip the download and only pay for
-    llama-server startup.  No-op if already cached or disabled.
+    llama-server startup. No-op if already cached or disabled.
     """
     if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):
         return
@@ -82,7 +81,7 @@ def precache_helper_gguf():
         files = api.list_repo_files(repo, repo_type = "model")
         gguf_files = [f for f in files if f.endswith(".gguf")]
 
-        # Find all GGUF files matching the variant (may be split into shards)
+        # All GGUF files matching the variant (may be split into shards)
         variant_lower = variant.lower().replace("-", "_")
         matching = sorted(f for f in gguf_files if variant_lower in f.lower().replace("-", "_"))
 
@@ -150,7 +149,7 @@ def _run_with_helper(prompt: str, max_tokens: int = 256) -> Optional[str]:
         ):
             if isinstance(chunk, dict):
                 continue  # skip metadata events
-            cumulative = chunk  # cumulative — last value is full text
+            cumulative = chunk  # cumulative; last value is full text
 
         result = cumulative.strip()
         result = _strip_think_tags(result)
@@ -181,8 +180,8 @@ def llm_generate_vlm_instruction(
     """
     Ask a helper LLM to generate a task-specific VLM instruction.
 
-    Called when heuristic instruction generation returns low confidence
-    or falls back to generic.
+    Called when heuristic instruction generation returns low confidence or
+    falls back to generic.
 
     Args:
         column_names: Column names in the dataset.
@@ -218,9 +217,9 @@ def llm_generate_vlm_instruction(
     if not result:
         return None
 
-    # Clean up: strip quotes, ensure it's a single sentence
+    # Strip quotes; ensure a single sentence
     instruction = result.strip().strip('"').strip("'").strip()
-    # Reject obviously bad outputs (too short, too long, or multi-line)
+    # Reject bad outputs (too short, too long, or multi-line)
     if len(instruction) < 10 or len(instruction) > 200 or "\n" in instruction:
         logger.warning(f"Helper model returned unusable instruction: {instruction!r}")
         return None
@@ -243,8 +242,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Option
         samples: 3-5 sample rows with values truncated to 200 chars.
 
     Returns:
-        Dict mapping column_name → role ("user"|"assistant"|"system"|"metadata"),
-        or None on failure.
+        Dict mapping column_name → role ("user"|"assistant"|"system"|"metadata"), or None.
     """
     formatted = ""
     for i, row in enumerate(samples[:5], 1):
@@ -281,7 +279,7 @@ def llm_classify_columns(column_names: list[str], samples: list[dict]) -> Option
     try:
         mapping = json.loads(text)
     except json.JSONDecodeError:
-        # Try to find JSON object in the response
+        # Find a JSON object in the response
         import re
         match = re.search(r"\{[^}]+\}", text)
         if match:
@@ -324,7 +322,7 @@ def llm_generate_dataset_warning(
     column_names: Optional[list[str]] = None,
 ) -> Optional[str]:
     """
-    Ask the helper LLM to turn technical dataset issues into a user-friendly warning.
+    Ask the helper LLM to turn technical dataset issues into a friendly warning.
 
     Works for all modalities (text, vision, audio).
 
@@ -359,7 +357,7 @@ def llm_generate_dataset_warning(
         return None
 
     warning = result.strip()
-    # Reject obviously bad outputs
+    # Reject bad outputs
     if len(warning) < 10 or len(warning) > 500:
         return None
 
@@ -489,7 +487,7 @@ def _run_multi_pass_advisor(
     """
     Multi-pass LLM analysis: classify → convert → validate.
 
-    Keeps model loaded across all passes. Returns combined result dict or None.
+    Keeps the model loaded across passes. Returns combined result dict or None.
     """
     if os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip() in ("1", "true"):
         return None
@@ -619,7 +617,7 @@ def _run_multi_pass_advisor(
             logger.warning(f"Advisor Pass 1 failed to produce JSON: {raw1[:200]}")
             return None
 
-        # If dataset is already conversational, skip passes 2-3
+        # Already conversational: skip passes 2-3
         if pass1.get("is_conversational") and not pass1.get("needs_conversion"):
             return {
                 "success": True,
@@ -724,7 +722,7 @@ def _run_multi_pass_advisor(
         column_roles = pass2.get("column_roles", {})
         label_map = pass2.get("label_mapping") or {}  # may be null
 
-        # Validate: must have at least one user AND one assistant
+        # Must have at least one user AND one assistant
         roles_present = set(column_roles.values())
         if "user" not in roles_present or "assistant" not in roles_present:
             logger.warning(f"Pass 2 sanity fail: missing user or assistant role: {column_roles}")
@@ -739,7 +737,7 @@ def _run_multi_pass_advisor(
             logger.info("Pass 3: Generating system prompt...")
             t3 = time.monotonic()
 
-            # Format label mapping info for the prompt
+            # Format label mapping for the prompt
             label_info = ""
             if label_map:
                 for col, mapping in label_map.items():
@@ -782,12 +780,12 @@ def _run_multi_pass_advisor(
             )
 
             if raw3:
-                # Pass 3 returns raw text, not JSON — clean it up
+                # Pass 3 returns raw text, not JSON — clean it
                 cleaned = raw3.strip().strip('"').strip("'").strip()
                 if len(cleaned) >= 20 and cleaned.lower() not in ("null", "none", ""):
                     sys_prompt = cleaned
 
-        # Build suggested_mapping (column → role, for the frontend dropdowns)
+        # Build suggested_mapping (column → role) for the frontend dropdowns
         suggested_mapping = {}
         for col, role in column_roles.items():
             if col in columns and role in ("user", "assistant", "system"):
@@ -855,7 +853,7 @@ def llm_conversion_advisor(
     if dataset_name and "/" in dataset_name:
         dataset_card, dataset_metadata = fetch_hf_dataset_card(dataset_name, hf_token)
 
-    # Try multi-pass advisor
+    # Try the multi-pass advisor
     result = _run_multi_pass_advisor(
         columns = column_names,
         samples = samples,
diff --git a/studio/backend/utils/datasets/model_mappings.py b/studio/backend/utils/datasets/model_mappings.py
index eb2e5482c9..b550dc81bd 100644
--- a/studio/backend/utils/datasets/model_mappings.py
+++ b/studio/backend/utils/datasets/model_mappings.py
@@ -1,11 +1,9 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Model and template mappings for dataset processing.
+"""Model and template mappings for dataset processing.
 
-This module contains the mapping dictionaries that associate model names
-with their corresponding chat templates and response markers.
+Maps model names to their chat templates and response markers.
 """
 
 TEMPLATE_TO_MODEL_MAPPER = {
@@ -445,8 +443,8 @@ for key, values in TEMPLATE_TO_MODEL_MAPPER.items():
 def is_gpt_oss_model_name(name: str) -> bool:
     """Name-based check for gpt-oss / harmony models.
 
-    Used by both the in-process backend and the parent-process
-    orchestrator to detect harmony models without an IPC round-trip.
+    Used by the in-process backend and the parent orchestrator to detect
+    harmony models without an IPC round-trip.
     """
     name = (name or "").lower()
     if not name:
diff --git a/studio/backend/utils/datasets/vlm_processing.py b/studio/backend/utils/datasets/vlm_processing.py
index a0f1fd9f99..4919b8884d 100644
--- a/studio/backend/utils/datasets/vlm_processing.py
+++ b/studio/backend/utils/datasets/vlm_processing.py
@@ -4,8 +4,8 @@
 """
 VLM (Vision-Language Model) processing utilities.
 
-This module contains functions for generating smart instructions
-for VLM datasets based on content analysis and heuristics.
+Generates smart instructions for VLM datasets via content analysis and
+heuristics.
 """
 
 import re
@@ -19,19 +19,19 @@ def generate_smart_vlm_instruction(
     dataset_name = None,
 ):
     """
-    Generate smart, context-aware instruction for VLM datasets using heuristics.
+    Generate a smart, context-aware instruction for VLM datasets via heuristics.
 
     Strategy:
-    1. Check for explicit question/instruction columns → use that
+    1. Explicit question/instruction column → use that
     2. Infer from text column name + sample content
     3. Analyze dataset name for task hints
-    4. Fall back to generic instruction
+    4. Generic fallback
 
     Returns:
         dict: {
             "instruction": str or None,  # None means use column content
             "instruction_type": "explicit" | "inferred" | "generic",
-            "uses_dynamic_instruction": bool,  # True if instruction varies per sample
+            "uses_dynamic_instruction": bool,  # True if it varies per sample
             "confidence": float,  # 0.0 to 1.0
         }
     """
@@ -39,16 +39,16 @@ def generate_smart_vlm_instruction(
     sample = next(iter(dataset))
 
     # ===== LEVEL 1: Explicit Instruction Columns =====
-    # Check for columns that contain per-sample instructions
+    # Columns that hold per-sample instructions
     question_columns = ["question", "query", "prompt", "instruction", "user_prompt"]
 
     for col in question_columns:
         if col in column_names:
-            # Check if this column has varied content (not just empty/same)
+            # Use it only if it has non-empty content
             sample_content = sample[col]
             if sample_content and str(sample_content).strip():
                 return {
-                    "instruction": None,  # Signal to use column content
+                    "instruction": None,  # use column content
                     "instruction_column": col,
                     "instruction_type": "explicit",
                     "uses_dynamic_instruction": True,
@@ -58,7 +58,7 @@ def generate_smart_vlm_instruction(
     # ===== LEVEL 2: Infer from Column Names + Content =====
     text_col_lower = text_column.lower()
 
-    # Sample the text content to detect patterns
+    # Sample text content for pattern detection
     text_sample = str(sample.get(text_column, ""))[:500]  # First 500 chars
 
     # Task-specific keywords and their instructions
@@ -122,24 +122,24 @@ def generate_smart_vlm_instruction(
         },
     }
 
-    # Check column name matches
+    # Score each task by column/dataset name and content matches
     best_match = None
     best_score = 0.0
 
     for task_name, task_info in task_patterns.items():
         score = 0.0
 
-        # Check column name
+        # Column name
         if any(keyword in text_col_lower for keyword in task_info["keywords"]):
             score += 0.5
 
-        # Check dataset name if provided
+        # Dataset name if provided
         if dataset_name and any(
             keyword in dataset_name.lower() for keyword in task_info["keywords"]
         ):
             score += 0.3
 
-        # Check content patterns
+        # Content patterns
         for pattern in task_info["content_hints"]:
             if re.search(pattern, text_sample, re.IGNORECASE):
                 score += 0.4
@@ -162,7 +162,6 @@ def generate_smart_vlm_instruction(
     if dataset_name:
         name_lower = dataset_name.lower()
 
-        # Common dataset name patterns
         if "vqa" in name_lower or "question" in name_lower:
             return {
                 "instruction": "Answer the question about this image.",
diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.py
index 400b5dd066..7ccba6315e 100644
--- a/studio/backend/utils/hardware/__init__.py
+++ b/studio/backend/utils/hardware/__init__.py
@@ -1,9 +1,7 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Hardware detection and GPU utilities
-"""
+"""Hardware detection and GPU utilities."""
 
 from . import hardware as _hardware
 from .hardware import (
@@ -86,8 +84,8 @@ __all__ = [
 
 
 def __getattr__(name: str):
-    """Resolve IS_ROCM at access time so callers always see the live value
-    after detect_hardware() runs (it flips the flag in hardware.py)."""
+    """Resolve IS_ROCM at access time so callers see the live value after
+    detect_hardware() runs (it flips the flag in hardware.py)."""
     if name == "IS_ROCM":
         return getattr(_hardware, "IS_ROCM")
     raise AttributeError(name)
diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.py
index 04b9494a29..41ee9f3fbe 100644
--- a/studio/backend/utils/hardware/amd.py
+++ b/studio/backend/utils/hardware/amd.py
@@ -3,9 +3,8 @@
 
 """AMD GPU monitoring via amd-smi.
 
-Mirrors the nvidia.py module structure so hardware.py can swap backends
-based on IS_ROCM. All functions return the same dict shapes as their
-nvidia.py counterparts.
+Mirrors nvidia.py so hardware.py can swap backends based on IS_ROCM.
+All functions return the same dict shapes as their nvidia.py counterparts.
 """
 
 import json
@@ -23,20 +22,20 @@ from utils.subprocess_compat import windows_hidden_subprocess_kwargs
 
 logger = get_logger(__name__)
 
-# amd-smi on Windows must initialise the full ROCm runtime on first call, which
-# can take 15-25 s on cold hardware.  Linux is consistently < 2 s.
+# amd-smi on Windows initialises the full ROCm runtime on first call, which
+# can take 15-25 s on cold hardware. Linux is consistently < 2 s.
 _AMD_SMI_DEFAULT_TIMEOUT = 30 if platform.system() == "Windows" else 10
 
 # Circuit breaker: stop calling amd-smi after this many consecutive failures.
 # On Windows, each failed call spawns a process that may show a UAC/DiskPart
-# elevation prompt.  Once we know amd-smi doesn't work we stop polling it.
+# elevation prompt. Once we know amd-smi doesn't work, stop polling it.
 _AMD_SMI_FAILURE_LIMIT = 3
 _amd_smi_consecutive_failures = 0
 _amd_smi_disabled = False
 
 
 def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optional[Any]:
-    """Run amd-smi with the given arguments and return parsed JSON, or None."""
+    """Run amd-smi with the given args and return parsed JSON, or None."""
     global _amd_smi_consecutive_failures, _amd_smi_disabled
     if _amd_smi_disabled:
         return None
@@ -52,7 +51,7 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
     except (OSError, subprocess.TimeoutExpired) as e:
         if isinstance(e, FileNotFoundError):
             # amd-smi ships with Adrenalin, not the HIP SDK -- absence is
-            # expected on HIP SDK-only Windows setups.  Log at debug only.
+            # expected on HIP SDK-only Windows setups. Log at debug only.
             logger.debug("amd-smi not found (not in PATH): %s", e)
         else:
             logger.warning("amd-smi query failed: %s", e)
@@ -75,9 +74,9 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
             _amd_smi_disabled = True
         return None
     if not result.stdout.strip():
-        # amd-smi exited successfully but produced no output (e.g. no GPUs
-        # visible on this query, or a version that emits nothing for --json).
-        # This is not a tool failure, so don't count against the circuit breaker.
+        # amd-smi exited 0 but produced no output (e.g. no GPUs visible on
+        # this query, or a version that emits nothing for --json). Not a tool
+        # failure, so don't count against the circuit breaker.
         logger.debug("amd-smi exited 0 but returned no output")
         return None
     _amd_smi_consecutive_failures = 0  # reset on success
@@ -89,7 +88,7 @@ def _run_amd_smi(*args: str, timeout: int = _AMD_SMI_DEFAULT_TIMEOUT) -> Optiona
 
 
 def _parse_numeric(value: Any) -> Optional[float]:
-    """Extract a numeric value from amd-smi output (may be str, int, float, or dict)."""
+    """Extract a numeric value from amd-smi output (str, int, float, or dict)."""
     if value is None:
         return None
     # Newer amd-smi versions emit {"value": 10, "unit": "W"}
@@ -114,9 +113,8 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
     """Parse a memory value from amd-smi output and return MB.
 
     Handles bare numbers (assumed MB -- the amd-smi convention on every
-    version we have seen), dict-shaped values with explicit units
-    (``{"value": 192, "unit": "GiB"}`` on newer releases), and plain
-    strings like ``"8192 MiB"``.
+    version seen), dict values with explicit units (``{"value": 192,
+    "unit": "GiB"}`` on newer releases), and strings like ``"8192 MiB"``.
     """
     unit = ""
     raw_value = value
@@ -134,8 +132,8 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
     if num is None:
         return None
 
-    # Unit conversion -- GPU tools (including amd-smi) use binary units even
-    # when labeling them "GB" or "MB", so treat GB/GiB and MB/MiB the same.
+    # Unit conversion -- GPU tools (incl. amd-smi) use binary units even when
+    # labeled "GB" or "MB", so treat GB/GiB and MB/MiB the same.
     if "gib" in unit or "gb" in unit:
         return num * 1024
     if "mib" in unit or "mb" in unit:
@@ -146,27 +144,27 @@ def _parse_memory_mb(value: Any) -> Optional[float]:
         # Plain bytes
         return num / (1024 * 1024)
 
-    # No explicit unit -- default to MB, which is the amd-smi convention
-    # for bare numeric values. A previous heuristic assumed values above
-    # ~10M were bytes, but that misclassifies small VRAM allocations
-    # (e.g. 5 MB = 5,242,880 reported without a unit) as ~5 TB. Modern
-    # amd-smi always ships explicit units, so the heuristic branch only
-    # fired for legacy output where MB was already the convention.
+    # No explicit unit -- default to MB, the amd-smi convention for bare
+    # numeric values. A previous heuristic assumed values above ~10M were
+    # bytes, but that misclassifies small VRAM allocations (e.g. 5 MB =
+    # 5,242,880 reported without a unit) as ~5 TB. Modern amd-smi always
+    # ships explicit units, so the heuristic only fired for legacy output
+    # where MB was already the convention.
     return num
 
 
 def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
     """Extract standardized metrics from a single GPU's amd-smi data."""
-    # amd-smi metric output structure varies by version; try common paths
+    # Output structure varies by version; try common paths
     usage = gpu_data.get("usage", gpu_data.get("gpu_activity", {}))
     if isinstance(usage, dict):
         gpu_util = _parse_numeric(usage.get("gfx_activity", usage.get("gpu_use_percent")))
     else:
         gpu_util = _parse_numeric(usage)
 
-    # Temperature -- try multiple keys in priority order.
-    # dict.get() returns "N/A" strings rather than falling through,
-    # so we must try each key and check if it parses to a real number.
+    # Temperature -- try keys in priority order. dict.get() returns "N/A"
+    # strings rather than falling through, so try each key and check it
+    # parses to a real number.
     temp_data = gpu_data.get("temperature", {})
     temp = None
     if isinstance(temp_data, dict):
@@ -191,10 +189,10 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
         power_draw = None
         power_limit = None
 
-    # VRAM -- unit-aware parsing to handle varying amd-smi output formats.
-    # Newer amd-smi versions may return {"value": 192, "unit": "GiB"}.
-    # Newer amd-smi uses "mem_usage" with "total_vram" / "used_vram" keys;
-    # older versions use "vram" or "fb_memory_usage" with "used" / "total".
+    # VRAM -- unit-aware parsing for varying amd-smi output formats.
+    # Newer versions may return {"value": 192, "unit": "GiB"} and use
+    # "mem_usage" with "total_vram" / "used_vram" keys; older versions use
+    # "vram" or "fb_memory_usage" with "used" / "total".
     vram_data = gpu_data.get(
         "mem_usage",
         gpu_data.get("vram", gpu_data.get("fb_memory_usage", {})),
@@ -239,11 +237,10 @@ def _extract_gpu_metrics(gpu_data: dict) -> dict[str, Any]:
 def _has_real_metrics(metrics: dict[str, Any]) -> bool:
     """Return True when ``metrics`` contains at least one non-None value.
 
-    ``amd-smi`` can return a zero-exit JSON envelope that is missing every
-    expected field (error response, unsupported card, hipless container).
-    In that case ``_extract_gpu_metrics`` produces a dict where every value
-    is ``None`` -- callers must surface this as ``available: False`` rather
-    than ``available: True`` with empty data.
+    ``amd-smi`` can return a zero-exit JSON envelope missing every expected
+    field (error response, unsupported card, hipless container). Then
+    ``_extract_gpu_metrics`` produces an all-``None`` dict -- callers must
+    surface this as ``available: False``, not ``available: True`` with empty data.
     """
     return any(value is not None for value in metrics.values())
 
@@ -255,9 +252,9 @@ def get_physical_gpu_count() -> Optional[int]:
         return None
     if isinstance(data, list):
         return len(data)
-    # Some versions return a dict with a "gpu" / "gpus" key. Guard the
-    # .get() access with an isinstance check so a malformed scalar /
-    # string response from amd-smi cannot raise AttributeError.
+    # Some versions return a dict with a "gpu" / "gpus" key. Guard .get()
+    # with isinstance so a malformed scalar/string response cannot raise
+    # AttributeError.
     if not isinstance(data, dict):
         return None
     gpus = data.get("gpu", data.get("gpus", []))
@@ -267,12 +264,12 @@ def get_physical_gpu_count() -> Optional[int]:
 
 
 def _first_visible_amd_gpu_id() -> Optional[str]:
-    """Return the physical AMD GPU id that should be treated as 'primary'.
+    """Return the physical AMD GPU id treated as 'primary'.
 
     Honours HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES
-    in that order (HIP respects all three). Returns ``"0"`` when none are
-    set, and ``None`` when the env var explicitly narrows to zero GPUs
-    ("" or "-1"), so callers can short-circuit to "available: False".
+    in that order (HIP respects all three). Returns ``"0"`` when none are set,
+    and ``None`` when the env var narrows to zero GPUs ("" or "-1"), so callers
+    can short-circuit to "available: False".
     """
     for env_name in (
         "HIP_VISIBLE_DEVICES",
@@ -285,11 +282,10 @@ def _first_visible_amd_gpu_id() -> Optional[str]:
         raw = raw.strip()
         if raw == "" or raw == "-1":
             return None
-        # Filter out empty tokens after splitting. This tolerates minor
-        # typos like ``HIP_VISIBLE_DEVICES=",1"`` (leading comma, user
-        # clearly meant to narrow to device 1) while still falling
-        # through to the next env var when every token is empty
-        # (e.g. ``,,,``).
+        # Drop empty tokens after splitting. Tolerates minor typos like
+        # ``HIP_VISIBLE_DEVICES=",1"`` (leading comma, clearly meant device 1)
+        # while still falling through to the next env var when every token is
+        # empty (e.g. ``,,,``).
         tokens = [t.strip() for t in raw.split(",") if t.strip()]
         if tokens:
             return tokens[0]
@@ -320,10 +316,9 @@ def get_primary_gpu_utilization() -> dict[str, Any]:
 
     metrics = _extract_gpu_metrics(gpu_data)
     if not _has_real_metrics(metrics):
-        # amd-smi returned a JSON envelope with no usable fields (error
-        # response or unsupported card). Surface as unavailable rather
-        # than available-with-empty-data so the UI does not render a
-        # ghost device.
+        # JSON envelope with no usable fields (error response or unsupported
+        # card). Surface as unavailable rather than available-with-empty-data
+        # so the UI does not render a ghost device.
         return {"available": False}
     metrics["available"] = True
     return metrics
@@ -352,11 +347,10 @@ def get_visible_gpu_utilization(
             "index_kind": "physical",
         }
 
-    # Extract a device list from amd-smi's envelope. Newer versions return
-    # a JSON array directly, older versions return a dict with a "gpus" /
-    # "gpu" key wrapping the list. Guard non-dict / non-list envelopes
-    # (scalar / string fallbacks from malformed output) so the .get()
-    # access cannot raise AttributeError on an unexpected shape.
+    # Extract a device list from amd-smi's envelope. Newer versions return a
+    # JSON array directly; older versions wrap the list in a dict under
+    # "gpus" / "gpu". Guard non-dict / non-list envelopes (scalar/string
+    # fallbacks from malformed output) so .get() cannot raise AttributeError.
     if isinstance(data, list):
         gpu_list = data
     elif isinstance(data, dict):
@@ -369,17 +363,15 @@ def get_visible_gpu_utilization(
 
     devices = []
     for fallback_idx, gpu_data in enumerate(gpu_list):
-        # Skip non-dict entries defensively: if amd-smi ever ships a
-        # scalar inside its "gpus" array (observed on some malformed
-        # output), _extract_gpu_metrics would raise AttributeError on
-        # the first .get() call.
+        # Skip non-dict entries: a scalar inside the "gpus" array (seen on
+        # some malformed output) would make _extract_gpu_metrics raise
+        # AttributeError on the first .get() call.
         if not isinstance(gpu_data, dict):
             continue
-        # Use AMD-reported GPU ID when available, fall back to enumeration
-        # index. Newer amd-smi versions wrap scalars as ``{"value": 0,
-        # "unit": "none"}``, so route raw_id through ``_parse_numeric``
-        # which already handles bare ints, floats, strings, and that
-        # dict shape uniformly.
+        # Use AMD-reported GPU ID when available, else the enumeration index.
+        # Newer amd-smi wraps scalars as ``{"value": 0, "unit": "none"}``, so
+        # route raw_id through ``_parse_numeric`` which handles bare ints,
+        # floats, strings, and that dict shape uniformly.
         raw_id = gpu_data.get("gpu", gpu_data.get("gpu_id", gpu_data.get("id", fallback_idx)))
         parsed_id = _parse_numeric(raw_id)
         if parsed_id is None:
@@ -403,10 +395,9 @@ def get_visible_gpu_utilization(
             continue
         metrics = _extract_gpu_metrics(gpu_data)
         if not _has_real_metrics(metrics):
-            # Skip ghost entries: an amd-smi response that decodes to a
-            # dict but contains no usable fields (error envelope, etc.)
-            # would otherwise show up as a device row with all-None
-            # numbers in the UI.
+            # Skip ghost entries: a dict response with no usable fields
+            # (error envelope, etc.) would otherwise show up as a device row
+            # with all-None numbers in the UI.
             continue
         metrics["index"] = idx
         metrics["index_kind"] = "physical"
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 3f2823302a..df3fbac47a 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -39,7 +39,7 @@ logger = get_logger(__name__)
 
 
 class DeviceType(str, Enum):
-    """Supported compute backends. Inherits from str so it serializes cleanly in JSON."""
+    """Supported compute backends. str subclass for clean JSON serialization."""
 
     CUDA = "cuda"
     XPU = "xpu"
@@ -57,14 +57,11 @@ IS_ROCM: bool = False  # True when running on AMD ROCm (HIP) -- routes GPU monit
 def _backend_label(device: DeviceType) -> str:
     """Return the user-facing backend name for API responses.
 
-    Internally we still represent ROCm hosts as ``DeviceType.CUDA`` because
-    ROCm torch sets ``torch.cuda.is_available() = True`` and reuses the whole
-    ``torch.cuda.*`` API surface, so branching on ``DeviceType`` stays
-    consistent with the rest of the codebase. For the JSON responses served
-    to the Studio frontend and other clients, however, "cuda" is misleading
-    on an AMD machine. This helper swaps the label to ``"rocm"`` when the
-    module-level ``IS_ROCM`` flag is set so the UI can render the correct
-    backend name without every caller having to duplicate the check.
+    ROCm hosts stay ``DeviceType.CUDA`` internally (ROCm torch sets
+    ``torch.cuda.is_available() = True`` and reuses ``torch.cuda.*``), so
+    branching on ``DeviceType`` stays consistent. But "cuda" is misleading
+    in JSON responses on an AMD machine, so this swaps the label to
+    ``"rocm"`` when ``IS_ROCM`` is set, sparing callers the check.
     """
     if IS_ROCM and device == DeviceType.CUDA:
         return "rocm"
@@ -75,12 +72,12 @@ def _backend_label(device: DeviceType) -> str:
 
 
 def is_apple_silicon() -> bool:
-    """Check if running on Apple Silicon hardware (pure platform check, no ML imports)."""
+    """True on Apple Silicon (pure platform check, no ML imports)."""
     return platform.system() == "Darwin" and platform.machine() == "arm64"
 
 
 def _has_torch() -> bool:
-    """Check if PyTorch is importable."""
+    """True if PyTorch is importable."""
     try:
         import torch
         return True
@@ -89,7 +86,7 @@ def _has_torch() -> bool:
 
 
 def _has_mlx() -> bool:
-    """Check if MLX is importable."""
+    """True if MLX is importable."""
     try:
         import mlx.core
         return True
@@ -99,10 +96,9 @@ def _has_mlx() -> bool:
 
 def detect_hardware() -> DeviceType:
     """
-    Detect the best available compute device and set the module-level DEVICE global.
+    Detect the best compute device and set the module-level DEVICE global.
 
-    Should be called exactly once during FastAPI lifespan startup.
-    Safe to call multiple times (idempotent).
+    Call once at FastAPI lifespan startup; idempotent.
 
     Detection order:
       1. CUDA  (NVIDIA GPU, requires torch)
@@ -121,10 +117,10 @@ def detect_hardware() -> DeviceType:
             CHAT_ONLY = False
             device_name = torch.cuda.get_device_properties(0).name
 
-            # Distinguish AMD ROCm (HIP) from NVIDIA CUDA for display purposes.
+            # Distinguish AMD ROCm (HIP) from NVIDIA CUDA for display only;
             # DeviceType stays CUDA since torch.cuda.* works on ROCm via HIP.
-            # AMD's repo.radeon.com SDK wheels (e.g. 2.9.0+rocmsdk20251116) do
-            # not set torch.version.hip, so fall back to checking __version__.
+            # AMD's repo.radeon.com SDK wheels (e.g. 2.9.0+rocmsdk20251116)
+            # don't set torch.version.hip, so fall back to __version__.
             _hip_ver = getattr(torch.version, "hip", None)
             if _hip_ver is not None or "rocm" in torch.__version__.lower():
                 IS_ROCM = True
@@ -148,9 +144,9 @@ def detect_hardware() -> DeviceType:
     if is_apple_silicon() and _has_mlx():
         DEVICE = DeviceType.MLX
         CHAT_ONLY = False
-        # platform.processor() runs `uname -p` which returns "i386" on most
-        # universal2 / Rosetta-shaped Python builds even on native arm64.
-        # platform.machine() is "arm64" once is_apple_silicon() has gated us.
+        # platform.processor() (`uname -p`) returns "i386" on most
+        # universal2 / Rosetta Python builds even on native arm64.
+        # platform.machine() is "arm64" once is_apple_silicon() gated us.
         chip = platform.machine() or "arm64"
         print(f"Hardware detected: MLX — Apple Silicon ({chip})")
         return DEVICE
@@ -166,8 +162,8 @@ def detect_hardware() -> DeviceType:
 
 def get_device() -> DeviceType:
     """
-    Return the detected device. Auto-detects if detect_hardware() hasn't been called yet.
-    Prefer calling detect_hardware() explicitly at startup instead.
+    Return the detected device, auto-detecting if detect_hardware() hasn't run.
+    Prefer calling detect_hardware() explicitly at startup.
     """
     global DEVICE
     if DEVICE is None:
@@ -178,7 +174,7 @@ def get_device() -> DeviceType:
 def clear_gpu_cache():
     """
     Clear GPU memory cache for the current device.
-    Safe to call on any platform — no-ops gracefully.
+    Safe on any platform — no-ops gracefully.
     """
     gc.collect()
 
@@ -195,15 +191,15 @@ def clear_gpu_cache():
         torch.xpu.synchronize()
         torch.xpu.empty_cache()
     elif device == DeviceType.MLX:
-        # MLX manages memory automatically; no explicit cache clear needed.
-        # mlx.core has no empty_cache equivalent — gc.collect() above is enough.
+        # MLX manages memory automatically; no empty_cache equivalent,
+        # so the gc.collect() above is enough.
         pass
 
 
 def get_gpu_memory_info() -> Dict[str, Any]:
     """
-    Get GPU memory information.
-    Supports CUDA (NVIDIA), MLX (Apple Silicon), and CPU-only environments.
+    Get GPU memory info.
+    Supports CUDA (NVIDIA), MLX (Apple Silicon), and CPU-only.
     """
     device = get_device()
 
@@ -275,8 +271,8 @@ def get_gpu_memory_info() -> Dict[str, Any]:
             import mlx.core as mx
             import psutil
 
-            # MLX uses unified memory. Total = system RAM. GPU memory used
-            # comes from IORegistry's AGXAccelerator (system-wide, no sudo).
+            # MLX uses unified memory: total = system RAM, GPU used comes
+            # from IORegistry's AGXAccelerator (system-wide, no sudo).
             total = psutil.virtual_memory().total
             agx = _read_apple_gpu_stats()
             allocated = agx.get("vram_used_bytes", 0) if agx else 0
@@ -284,7 +280,7 @@ def get_gpu_memory_info() -> Dict[str, Any]:
             try:
                 info = mx.device_info()
                 # See detect_hardware(): platform.processor() can return "i386"
-                # on native arm64 Python builds, so prefer machine() as fallback.
+                # on native arm64 builds, so prefer machine() as fallback.
                 gpu_name = info.get("device_name") or platform.machine() or "arm64"
             except Exception:
                 gpu_name = platform.machine() or "arm64"
@@ -352,13 +348,11 @@ def get_gpu_summary() -> Dict[str, Any]:
 
 def get_package_versions() -> Dict[str, Optional[str]]:
     """
-    Return the installed versions of key ML packages.
+    Return installed versions of key ML packages.
 
-    Uses importlib.metadata (stdlib) so no subprocess is needed.
-    CUDA version comes from torch.version.cuda.
-
-    Returns dict with keys: unsloth, torch, transformers, cuda.
-    Missing packages yield None.
+    Uses importlib.metadata (stdlib), no subprocess. CUDA version from
+    torch.version.cuda. Returns dict keyed unsloth/torch/transformers/cuda;
+    missing packages yield None.
     """
     packages = ("unsloth", "torch", "transformers")
     versions: Dict[str, Optional[str]] = {}
@@ -418,8 +412,8 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]
             # torch uses 0-based ordinals relative to CUDA_VISIBLE_DEVICES
             props = mod.get_device_properties(ordinal)
             total_bytes = props.total_memory
-            # Prefer mem_get_info (reports system-wide usage, not just this
-            # process) so auto-selection accounts for other GPU consumers.
+            # Prefer mem_get_info (system-wide usage, not just this process)
+            # so auto-selection accounts for other GPU consumers.
             if hasattr(mod, "mem_get_info"):
                 free_bytes, total_bytes = mod.mem_get_info(ordinal)
                 used_bytes = total_bytes - free_bytes
@@ -443,9 +437,9 @@ def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]
 
 
 def _smi_query(func_name: str, *args, **kwargs) -> Optional[Dict[str, Any]]:
-    """Run a query against the appropriate SMI backend (amd-smi or nvidia-smi).
+    """Query the appropriate SMI backend (amd-smi or nvidia-smi).
 
-    Returns the result dict if available, or None on failure/unavailability.
+    Returns the result dict if available, else None.
     """
     if IS_ROCM:
         backend_name = "amd-smi"
@@ -474,8 +468,8 @@ def _smi_query(func_name: str, *args, **kwargs) -> Optional[Dict[str, Any]]:
 def _read_apple_gpu_stats() -> Dict[str, Any]:
     """Query macOS IORegistry for AGX (Apple GPU) live stats. No sudo needed.
 
-    Returns dict with utilization_pct, vram_used_bytes (system-wide GPU memory).
-    Returns empty dict on failure.
+    Returns dict with utilization_pct, vram_used_bytes (system-wide GPU
+    memory), or empty dict on failure.
     """
     try:
         result = subprocess.run(
@@ -574,7 +568,7 @@ def _rocm_windows_perf_counter_gpu_util_pct() -> Optional[float]:
 def _rocm_linux_sysfs_vram_gb() -> tuple[Optional[float], Optional[float]]:
     """Query system-wide AMD GPU VRAM via Linux DRM sysfs.
 
-    Reads /sys/class/drm/card*/device/mem_info_vram_* which the kernel
+    Reads /sys/class/drm/card*/device/mem_info_vram_*, which the kernel
     updates in real-time across all processes. No tools required.
     Returns (used_gb, total_gb) or (None, None) on failure.
     """
@@ -597,8 +591,8 @@ def _rocm_linux_sysfs_vram_gb() -> tuple[Optional[float], Optional[float]]:
 def _rocm_windows_perf_counter_vram_gb() -> tuple[Optional[float], Optional[float]]:
     """Query system-wide dedicated GPU VRAM via Windows Performance Counters.
 
-    Uses the same data source as Task Manager so it reflects cross-process
-    usage accurately. Works for any GPU vendor without amd-smi or nvidia-smi.
+    Same data source as Task Manager, so cross-process usage is accurate.
+    Works for any GPU vendor without amd-smi or nvidia-smi.
     Returns (used_gb, total_gb) or (None, None) on failure.
     """
     if platform.system() != "Windows":
@@ -640,10 +634,10 @@ def get_gpu_utilization() -> Dict[str, Any]:
                 # Fix unified-memory VRAM on AMD iGPUs (Strix Halo etc.)
                 _reconcile_primary_rocm_unified_memory(result, _get_parent_visible_gpu_spec())
             return result
-        # SMI tool unavailable or returned no usable data. On Windows, query
+        # SMI tool unavailable or returned nothing usable. On Windows, query
         # the Performance Counter API (same source as Task Manager) for
         # system-wide dedicated VRAM — covers cross-process usage that
-        # torch.cuda.mem_get_info cannot see from the Studio server process.
+        # torch.cuda.mem_get_info can't see from the Studio server process.
         if IS_ROCM and platform.system() == "Windows":
             _win_used, _win_total = _rocm_windows_perf_counter_vram_gb()
             if _win_used is not None and _win_total is not None:
@@ -705,8 +699,8 @@ def get_gpu_utilization() -> Dict[str, Any]:
                 "power_utilization_pct": None,
             }
 
-    # MLX path: single _read_apple_gpu_stats() call carries both VRAM-used
-    # bytes and GPU utilization %. psutil for unified-memory total is cheap.
+    # MLX path: one _read_apple_gpu_stats() call carries both VRAM-used bytes
+    # and GPU utilization %. psutil for unified-memory total is cheap.
     if device == DeviceType.MLX:
         try:
             import psutil
@@ -772,8 +766,8 @@ def _apply_unified_memory_correction(
     """Per-device reconciliation: when torch reports a larger memory total
     than amd-smi, overwrite the smi VRAM fields in place.
 
-    Used by both the multi-device and primary-device reconciliation helpers
-    so the two endpoints stay in sync on AMD iGPUs with unified memory.
+    Used by both the multi-device and primary-device reconcilers so the two
+    endpoints stay in sync on AMD iGPUs with unified memory.
     """
     torch_total_gb = torch_info["total_gb"]
     smi_total_gb = device_metrics.get("vram_total_gb") or 0.0
@@ -798,7 +792,7 @@ def _reconcile_rocm_unified_memory(utilization: Dict[str, Any], device_indices:
 
     amd-smi reports only the dedicated slice (~512 MB); torch sees the full
     GTT pool (~128 GB). When torch total > smi total, overwrite per-device
-    VRAM fields so GPU selection uses the real available memory.
+    VRAM fields so GPU selection uses real available memory.
     """
     torch_devices = _torch_get_per_device_info(device_indices)
     if not torch_devices:
@@ -820,10 +814,9 @@ def _reconcile_primary_rocm_unified_memory(
         # No visibility env var set: torch ordinal 0 is the primary device.
         primary_idx = [0]
     elif len(numeric_ids) == 0:
-        # Empty mask (HIP_VISIBLE_DEVICES="" or "-1"): no GPU is visible to
-        # this process. Querying torch device 0 would raise a RuntimeError or
-        # return stale/wrong data, so bail out rather than writing bad values
-        # into the utilization dict.
+        # Empty mask (HIP_VISIBLE_DEVICES="" or "-1"): no GPU visible to this
+        # process. Querying torch device 0 would raise or return stale data,
+        # so bail rather than write bad values into the utilization dict.
         return
     else:
         primary_idx = [int(numeric_ids[0])]
@@ -942,14 +935,14 @@ _visible_gpu_count: Optional[int] = None
 
 
 def _get_parent_visible_gpu_spec() -> Dict[str, Any]:
-    # ROCm uses HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES in addition to
-    # CUDA_VISIBLE_DEVICES (which HIP also respects).  Check ROCm-specific
-    # env vars first so multi-GPU AMD setups are handled correctly.
-    # Use explicit None checks (not `or`) so empty string "" is honoured
-    # as "no visible GPUs" rather than falling through to CUDA_VISIBLE_DEVICES.
+    # ROCm uses HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES on top of
+    # CUDA_VISIBLE_DEVICES (which HIP also respects). Check ROCm env vars
+    # first for multi-GPU AMD setups. Use explicit None checks (not `or`)
+    # so empty string "" is honoured as "no visible GPUs" rather than
+    # falling through to CUDA_VISIBLE_DEVICES.
     cuda_visible = None
     # Prefer ROCm masks only on a ROCm host, or when no CUDA mask is set, so a
-    # stale HIP_VISIBLE_DEVICES on an NVIDIA host can't override CUDA_VISIBLE_DEVICES.
+    # stale HIP_VISIBLE_DEVICES on NVIDIA can't override CUDA_VISIBLE_DEVICES.
     _is_rocm_spec = IS_ROCM or (
         "CUDA_VISIBLE_DEVICES" not in os.environ
         and ("HIP_VISIBLE_DEVICES" in os.environ or "ROCR_VISIBLE_DEVICES" in os.environ)
@@ -1027,7 +1020,7 @@ def resolve_requested_gpu_ids(gpu_ids: Optional[list[int]]) -> list[int]:
             f"Parent-visible GPUs: {parent_visible_ids}"
         )
 
-    # Reject negative IDs unconditionally.
+    # Reject negative IDs.
     negative_ids = [gpu_id for gpu_id in requested_ids if gpu_id < 0]
     if negative_ids:
         raise ValueError(
@@ -1035,12 +1028,11 @@ def resolve_requested_gpu_ids(gpu_ids: Optional[list[int]]) -> list[int]:
             f"Rejected IDs: {negative_ids}. Parent-visible GPUs: {parent_visible_ids}"
         )
 
-    # Only enforce the physical upper bound when we have a reliable count
-    # from nvidia-smi. When the count comes from torch, it reflects visible
-    # devices (filtered by CUDA_VISIBLE_DEVICES), not the physical total,
-    # so high physical indices like 3 would be falsely rejected on a
-    # CUDA_VISIBLE_DEVICES="2,3" machine that reports device_count()=2.
-    # The parent-visible check below is authoritative in all cases.
+    # Only enforce the physical upper bound when the count is reliable
+    # (from nvidia-smi). A torch count reflects visible devices (filtered by
+    # CUDA_VISIBLE_DEVICES), not the physical total, so e.g. index 3 would be
+    # falsely rejected on a CUDA_VISIBLE_DEVICES="2,3" host reporting
+    # device_count()=2. The parent-visible check below is always authoritative.
     if physical_gpu_count > 0 and parent_visible_ids:
         max_parent_id = max(parent_visible_ids)
         if physical_gpu_count > max_parent_id:
@@ -1123,13 +1115,13 @@ def _load_config_for_gpu_estimate(model_name: str, hf_token: Optional[str] = Non
 
 
 def _determine_attention_impl_for_gpu_estimate(config) -> str:
-    # torch.distributed is incomplete on Windows ROCm — torch._C is a C
-    # extension (not a package), so Python cannot import the submodule
-    # torch._C._distributed_c10d that torch.distributed depends on.
-    # Inject an empty stub into sys.modules BEFORE importing torch.distributed
-    # so the import succeeds, then patch the missing process-group helpers.
+    # torch.distributed is incomplete on Windows ROCm: torch._C is a C
+    # extension (not a package), so the submodule torch._C._distributed_c10d
+    # that torch.distributed depends on can't be imported. Inject an empty
+    # stub into sys.modules BEFORE importing torch.distributed so the import
+    # succeeds, then patch the missing process-group helpers.
     if sys.platform == "win32" and IS_ROCM:
-        # Dummy class for any name torch.distributed tries to import from these stubs
+        # Dummy for any name torch.distributed imports from these stubs
         class _Dummy:
             pass
 
@@ -1177,11 +1169,11 @@ def _determine_attention_impl_for_gpu_estimate(config) -> str:
     from unsloth.models._utils import resolve_attention_implementation
     from transformers import AutoModel, AutoModelForCausalLM
 
-    # why: resolve_attention_implementation calls _set_attn_impl which writes
+    # why: resolve_attention_implementation calls _set_attn_impl, which writes
     # _attn_implementation onto the config; PreTrainedConfig's setter walks
     # `sub_configs` and propagates to nested text_config / sub-configs, so a
-    # shallow copy still mutates those shared inner objects on the cached
-    # config returned by _load_config_for_gpu_estimate. Deepcopy isolates them.
+    # shallow copy would still mutate those shared inner objects on the cached
+    # config from _load_config_for_gpu_estimate. Deepcopy isolates them.
     config_copy = copy.deepcopy(config)
 
     model_class = None
@@ -1357,15 +1349,15 @@ def estimate_required_model_memory_gb(
                 config
             )
         except Exception as e:
-            # Log at debug: on Windows ROCm the torch.distributed stub does
-            # not implement Store, so this fires on every estimate call.
-            # It is expected and non-actionable -- eager is the safe fallback.
+            # Debug-level: on Windows ROCm the torch.distributed stub lacks
+            # Store, so this fires every estimate call. Expected and
+            # non-actionable -- eager is the safe fallback.
             logger.debug(
                 "Could not resolve attention implementation for '%s': %s",
                 estimate_model,
                 e,
             )
-            # why: if we cannot prove flash attention is usable, charge the
+            # why: if flash attention can't be proven usable, charge the
             # quadratic non-flash activation path so GPU selection stays
             # conservative.
             vram_config.attention_implementation = "eager"
@@ -1374,14 +1366,14 @@ def estimate_required_model_memory_gb(
     if arch is not None:
         breakdown = estimate_training_vram(arch, vram_config)
         # why: extract_arch_config only sees text_config; safetensors include
-        # vision/audio tower bytes that the text-arch fp16 total misses.
+        # vision/audio tower bytes the text-arch fp16 total misses.
         arch_fp16_bytes = compute_total_params(arch) * 2
         extra_bytes = max(0, int(model_size_bytes) - arch_fp16_bytes)
         if extra_bytes > 0:
             breakdown.model_weights += extra_bytes
             if training_method == "full":
                 # why: full fine-tuning makes the extra (vision/audio) params
-                # trainable; optimizer + gradient bytes scale with them too.
+                # trainable; optimizer + gradient bytes scale with them.
                 extra_params = extra_bytes // 2
                 breakdown.optimizer_states += compute_optimizer_bytes(
                     extra_params,
@@ -1460,9 +1452,8 @@ def auto_select_gpu_ids(
         return None, metadata
 
     if required_gb is None:
-        # Cannot estimate model size -- fall back to all visible GPUs
-        # rather than risk loading on a single GPU that may not have
-        # enough memory.
+        # Cannot estimate model size -- fall back to all visible GPUs rather
+        # than risk loading on a single GPU that may lack memory.
         parent_ids = get_parent_visible_gpu_ids()
         metadata["selection_mode"] = "fallback_all"
         metadata["selected_gpu_ids"] = parent_ids
@@ -1500,17 +1491,16 @@ def auto_select_gpu_ids(
     free_by_index = {item["index"]: item["free_gb"] for item in ranked}
     selected: list[int] = []
     usable_gb = 0.0
-    # Multi-GPU sharding has overhead from inter-GPU communication (NCCL
-    # all-reduce, PCIe/NVLink transfers, synchronization barriers), so each
-    # additional GPU contributes less than its raw free memory. The first GPU
-    # keeps its full capacity (no cross-device overhead). 0.85 was calibrated
-    # empirically on 2-8 GPU setups with NVLink and PCIe topologies -- the
-    # 15% discount accounts for NCCL buffers (~2-5% of VRAM), pipeline bubble
-    # overhead, and memory fragmentation from non-uniform shard sizes.
+    # Multi-GPU sharding has inter-GPU communication overhead (NCCL
+    # all-reduce, PCIe/NVLink transfers, sync barriers), so each extra GPU
+    # contributes less than its raw free memory; the first GPU keeps full
+    # capacity. 0.85 was calibrated empirically on 2-8 GPU NVLink/PCIe
+    # setups -- the 15% discount covers NCCL buffers (~2-5% of VRAM),
+    # pipeline bubble overhead, and fragmentation from non-uniform shards.
     multi_gpu_overhead = 0.85
 
     # Per-GPU check: activations don't shard, so each GPU needs its weight
-    # shard + full activation cost. Use precomputed min_per_gpu_N values.
+    # shard + full activation cost. Uses precomputed min_per_gpu_N values.
     vram_breakdown = estimate_metadata.get("vram_breakdown", {})
 
     for candidate in ranked:
@@ -1547,7 +1537,7 @@ def auto_select_gpu_ids(
             )
             return selected, metadata
 
-    # Use only GPUs with verified VRAM data (from gpu_candidates, not raw devices)
+    # Use only GPUs with verified VRAM data (gpu_candidates, not raw devices)
     fallback_all = [c["index"] for c in gpu_candidates] if gpu_candidates else parent_ids
     metadata["selection_mode"] = "fallback_all"
     if ranked:
@@ -1586,18 +1576,17 @@ def prepare_gpu_selection(
     """Resolve which physical GPUs to use for a model load.
 
     GPU selection modes:
-      - **Explicit** (``gpu_ids=[5, 6, 7]``): the caller chooses exact GPUs.
-        All listed GPUs are used and the model is sharded across them via
-        ``device_map="balanced"``, regardless of whether the model would fit
-        on fewer GPUs.  IDs are validated against the parent-visible set.
-      - **Auto** (``gpu_ids=None`` or ``[]``): ``auto_select_gpu_ids`` estimates
-        VRAM requirements and picks the *minimum* number of GPUs needed,
-        preferring GPUs with the most free memory.
+      - **Explicit** (``gpu_ids=[5, 6, 7]``): caller chooses exact GPUs.
+        All listed GPUs are used and the model is sharded via
+        ``device_map="balanced"``, even if it would fit on fewer. IDs are
+        validated against the parent-visible set.
+      - **Auto** (``gpu_ids=None`` or ``[]``): ``auto_select_gpu_ids``
+        estimates VRAM needs and picks the *minimum* GPUs needed,
+        preferring those with the most free memory.
 
-    The returned ``gpu_ids`` list is later passed to ``get_device_map()`` which
-    maps it to a Hugging Face ``device_map`` string, and to ``apply_gpu_ids()``
-    in the worker subprocess which narrows ``CUDA_VISIBLE_DEVICES`` before any
-    torch/CUDA initialisation.
+    The returned ``gpu_ids`` is later passed to ``get_device_map()`` (maps it
+    to a Hugging Face ``device_map`` string) and to ``apply_gpu_ids()`` in the
+    worker subprocess (narrows ``CUDA_VISIBLE_DEVICES`` before torch/CUDA init).
     """
     if gpu_ids and get_device() != DeviceType.CUDA:
         raise ValueError(
@@ -1633,8 +1622,7 @@ def get_physical_gpu_count() -> int:
     Return the number of physical GPUs on the machine.
 
     Uses ``nvidia-smi -L`` on NVIDIA (unaffected by CUDA_VISIBLE_DEVICES),
-    with a torch-based fallback for AMD ROCm and Intel XPU.
-    Result is cached after the first call.
+    with a torch fallback for AMD ROCm and Intel XPU. Cached after first call.
     """
     global _physical_gpu_count
     if _physical_gpu_count is not None:
@@ -1676,10 +1664,10 @@ def get_physical_gpu_count() -> int:
 def _backend_visible_devices_env() -> Optional[str]:
     """Return the raw visibility env string that applies to this backend.
 
-    On ROCm, HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES take precedence
-    over CUDA_VISIBLE_DEVICES; the helper mirrors the resolution logic in
-    ``_get_parent_visible_gpu_spec`` so ``backend_cuda_visible_devices``
-    reports the value that is actually narrowing the visible device set.
+    On ROCm, HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES take precedence over
+    CUDA_VISIBLE_DEVICES; this mirrors ``_get_parent_visible_gpu_spec`` so
+    ``backend_cuda_visible_devices`` reports the value actually narrowing the
+    visible device set.
     """
     if IS_ROCM:
         return _get_parent_visible_gpu_spec().get("raw")
@@ -1706,7 +1694,7 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
             except Exception as e:
                 logger.warning("Backend GPU visibility query failed: %s", e)
 
-        # Torch fallback (AMD ROCm, Intel XPU, nvidia-smi missing/failed)
+        # Torch fallback (AMD ROCm, Intel XPU, nvidia-smi missing/failed).
         # When parent_visible_ids is empty (UUID/MIG mask), enumerate by
         # torch ordinal so the UI still shows devices.
         if parent_visible_ids:
@@ -1789,15 +1777,15 @@ def get_visible_gpu_count() -> int:
     Return the number of GPUs visible to this process.
 
     Respects ``CUDA_VISIBLE_DEVICES`` -- if set, only those GPUs count.
-    Falls back to physical count if the env var is unset or torch is
-    unavailable.  Result is cached after the first call.
+    Falls back to physical count if unset or torch is unavailable.
+    Cached after the first call.
     """
     global _visible_gpu_count
     if _visible_gpu_count is not None:
         return _visible_gpu_count
 
-    # Use _get_parent_visible_gpu_spec() which already handles
-    # HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES on ROCm.
+    # _get_parent_visible_gpu_spec() already handles HIP_VISIBLE_DEVICES /
+    # ROCR_VISIBLE_DEVICES on ROCm.
     visible_spec = _get_parent_visible_gpu_spec()
     if visible_spec["raw"] is not None:
         raw = visible_spec["raw"].strip()
@@ -1809,7 +1797,7 @@ def get_visible_gpu_count() -> int:
             _visible_gpu_count = len([x for x in raw.split(",") if x.strip()])
         return _visible_gpu_count
 
-    # No visibility env var set -- try torch, fall back to physical count
+    # No visibility env var set -- try torch, else physical count
     try:
         import torch
         if get_device() == DeviceType.XPU and hasattr(torch, "xpu"):
@@ -1826,9 +1814,9 @@ def apply_gpu_ids(gpu_ids) -> None:
     if gpu_ids is None:
         return
 
-    # Empty list means "no GPUs visible" -- treat the same as None
-    # (inherit parent) to avoid setting CUDA_VISIBLE_DEVICES="" which
-    # disables CUDA entirely and crashes downstream torch calls.
+    # Empty list means "no GPUs visible" -- treat like None (inherit parent)
+    # to avoid setting CUDA_VISIBLE_DEVICES="", which disables CUDA entirely
+    # and crashes downstream torch calls.
     if isinstance(gpu_ids, (list, tuple)) and len(gpu_ids) == 0:
         return
 
@@ -1841,22 +1829,21 @@ def apply_gpu_ids(gpu_ids) -> None:
 
     os.environ["CUDA_VISIBLE_DEVICES"] = value
     # Keep ROCm visibility env vars in sync so _get_parent_visible_gpu_spec()
-    # picks up the narrowed set on AMD systems. Workers can call
-    # apply_gpu_ids() before detect_hardware() runs (so IS_ROCM is still
-    # its default False), so also mirror the selection whenever the
-    # parent process already set a ROCm visibility variable -- that
-    # way a downstream ROCm process inherits the narrowed mask even
-    # before Studio's hardware detection has classified the host.
-    # Final fallback: probe torch.version.hip so AMD workers without
-    # HIP_VISIBLE_DEVICES still get the correct ROCm visibility mask.
+    # picks up the narrowed set on AMD. Workers may call apply_gpu_ids()
+    # before detect_hardware() runs (IS_ROCM still default False), so also
+    # mirror the selection whenever the parent already set a ROCm visibility
+    # var -- a downstream ROCm process then inherits the narrowed mask before
+    # hardware detection classifies the host. Final fallback: probe
+    # torch.version.hip so AMD workers without HIP_VISIBLE_DEVICES still get
+    # the correct ROCm visibility mask.
     _inherits_rocm_visibility = (
         "HIP_VISIBLE_DEVICES" in os.environ or "ROCR_VISIBLE_DEVICES" in os.environ
     )
     _is_rocm = IS_ROCM or _inherits_rocm_visibility
     if not _is_rocm:
         # torch.version.hip is a non-empty string on ROCm, None on CUDA.
-        # AMD SDK / Radeon ROCm wheels can leave torch.version.hip unset but
-        # still encode "rocm" in torch.__version__, matching detect_hardware().
+        # AMD SDK / Radeon ROCm wheels may leave it unset but still encode
+        # "rocm" in torch.__version__ (matching detect_hardware()).
         # Broad except: a probe failure must never crash a training worker.
         try:
             import torch as _torch
@@ -1886,22 +1873,21 @@ def get_device_map(gpu_ids: Optional[list[int]] = None) -> str:
     Returns ``"balanced"`` (shard evenly across GPUs) when:
       - ``gpu_ids`` explicitly lists >1 GPU, **or**
       - ``CUDA_VISIBLE_DEVICES`` uses UUID/MIG identifiers (non-numeric) and
-        more than one GPU is visible (fallback: we cannot resolve numeric IDs,
-        so we assume the caller intends multi-GPU).
+        >1 GPU is visible (fallback: numeric IDs unresolvable, so assume
+        multi-GPU is intended).
 
-    Returns ``"sequential"`` (single device) in all other cases, including
-    non-CUDA backends (CPU, MLX).
+    Returns ``"sequential"`` (single device) otherwise, including non-CUDA
+    backends (CPU, MLX).
 
-    Callers should use ``prepare_gpu_selection()`` upstream to determine the
-    ``gpu_ids`` list -- that function handles the smart auto-selection of the
-    minimum number of GPUs needed for a given model.
+    Use ``prepare_gpu_selection()`` upstream to determine ``gpu_ids`` -- it
+    handles auto-selecting the minimum GPUs needed for a model.
     """
     device = get_device()
     if device == DeviceType.CUDA:
         multi_gpu = gpu_ids is not None and len(gpu_ids) > 1
 
         if not multi_gpu:
-            # UUID/MIG masks cannot be split into numeric IDs, so if multiple
+            # UUID/MIG masks can't be split into numeric IDs, so if multiple
             # GPUs are visible we assume multi-GPU sharding is intended.
             parent_visible_spec = _get_parent_visible_gpu_spec()
             if parent_visible_spec["numeric_ids"] is None and get_visible_gpu_count() > 1:
@@ -1944,18 +1930,14 @@ def safe_num_proc(desired: Optional[int] = None) -> int:
     """
     Return a safe ``num_proc`` for ``dataset.map()`` calls.
 
-    On Windows, always returns 1 because Python uses ``spawn`` instead of
-    ``fork`` for multiprocessing -- the overhead of re-importing torch,
-    transformers, unsloth etc. per worker is typically slower than
-    single-process for normal dataset sizes.
+    On Windows always returns 1: Python uses ``spawn`` not ``fork``, so
+    re-importing torch/transformers/unsloth per worker is typically slower
+    than single-process for normal dataset sizes.
 
-    On multi-GPU machines (where multiple GPUs are *visible* to this
-    process) the NVIDIA driver spawns extra background threads, making
-    ``os.fork()`` prone to deadlocks when many workers are created.
-    This helper caps ``num_proc`` to 4 on such machines.
-
-    When ``CUDA_VISIBLE_DEVICES`` restricts to a single GPU, the cap
-    does not apply.
+    On multi-GPU machines (multiple GPUs *visible* to this process) the
+    NVIDIA driver spawns extra background threads, making ``os.fork()``
+    deadlock-prone with many workers, so this caps ``num_proc`` to 4.
+    The cap does not apply when ``CUDA_VISIBLE_DEVICES`` restricts to one GPU.
 
     Args:
         desired: The num_proc you *want*. If None, auto-computes from
@@ -1964,9 +1946,8 @@ def safe_num_proc(desired: Optional[int] = None) -> int:
     Returns:
         A safe integer ≥ 1.
     """
-    # Windows and macOS use 'spawn' for multiprocessing -- the overhead of
-    # re-importing torch/transformers/unsloth per worker is typically slower
-    # than single-process.
+    # Windows/macOS use 'spawn'; re-importing torch/transformers/unsloth per
+    # worker is typically slower than single-process.
     if sys.platform in ("win32", "darwin"):
         return 1
 
@@ -1989,9 +1970,8 @@ def safe_thread_num_proc(desired: Optional[int] = None) -> int:
     """
     Return a safe worker count for ``ThreadPoolExecutor`` calls.
 
-    Unlike ``safe_num_proc()``, this does NOT cap to 1 on macOS/Windows.
-    Threads share the parent process address space and are unaffected by
-    the ``spawn`` vs ``fork`` distinction.
+    Unlike ``safe_num_proc()``, does NOT cap to 1 on macOS/Windows: threads
+    share the parent address space, unaffected by ``spawn`` vs ``fork``.
 
     Args:
         desired: The thread count you *want*. If None, auto-computes
@@ -2010,9 +1990,9 @@ def dataset_map_num_proc(desired: Optional[int] = None) -> Optional[int]:
     """
     Return a safe ``num_proc`` for ``Dataset.map()`` and ``Dataset.filter()``.
 
-    Returns ``None`` on spawn-based platforms (Windows, macOS) because
-    ``datasets`` treats ``num_proc=1`` as multiprocessing (creates ``Pool(1)``).
-    Only ``num_proc=None`` guarantees in-process execution.
+    Returns ``None`` on spawn platforms (Windows, macOS) because ``datasets``
+    treats ``num_proc=1`` as multiprocessing (creates ``Pool(1)``); only
+    ``num_proc=None`` guarantees in-process execution.
     """
     if sys.platform in ("win32", "darwin"):
         return None
diff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.py
index 6cead61f08..b8f307df9e 100644
--- a/studio/backend/utils/hardware/nvidia.py
+++ b/studio/backend/utils/hardware/nvidia.py
@@ -110,9 +110,9 @@ def get_primary_gpu_utilization() -> dict[str, Any]:
 def get_visible_gpu_utilization(
     parent_visible_ids: Optional[list[int]], parent_cuda_visible_devices: Optional[str] = None
 ) -> dict[str, Any]:
-    # When parent_visible_ids is None (UUID/MIG mask), we cannot safely
-    # map nvidia-smi rows to the process's visible devices. Return empty
-    # instead of exposing all physical GPUs.
+    # parent_visible_ids None (UUID/MIG mask): can't safely map
+    # nvidia-smi rows to visible devices. Return empty rather than
+    # exposing all physical GPUs.
     if parent_visible_ids is None:
         return {
             "available": False,
@@ -196,8 +196,8 @@ def get_visible_gpu_utilization(
 def get_backend_visible_gpu_info(
     parent_visible_ids: Optional[list[int]], backend_cuda_visible_devices: Optional[str]
 ) -> dict[str, Any]:
-    # When parent_visible_ids is None (UUID/MIG mask), we cannot safely
-    # map nvidia-smi rows to the process's visible devices.
+    # parent_visible_ids None (UUID/MIG mask): can't safely map
+    # nvidia-smi rows to visible devices.
     if parent_visible_ids is None:
         return {
             "available": False,
@@ -249,7 +249,7 @@ def get_backend_visible_gpu_info(
             continue
         if visible_ordinals is not None and idx not in visible_ordinals:
             continue
-        # Use split with limit to handle GPU names containing commas
+        # Rejoin in case the GPU name contains commas
         name = parts[1] if len(parts) == 3 else ", ".join(parts[1:-1])
         try:
             mem_total_mb = int(parts[-1])
diff --git a/studio/backend/utils/hardware/vram_estimation.py b/studio/backend/utils/hardware/vram_estimation.py
index ddc39733e3..51903e0c97 100644
--- a/studio/backend/utils/hardware/vram_estimation.py
+++ b/studio/backend/utils/hardware/vram_estimation.py
@@ -59,8 +59,8 @@ OPTIMIZER_BYTES_PER_PARAM: Dict[str, int] = {
 }
 
 # (full_ft_multiplier, lora_multiplier) — fraction of num_layers.
-# LoRA: frozen base layers skip activation storage, but you always need
-# at least ~1 layer in flight during backprop recomputation.
+# LoRA: frozen base layers skip activation storage, but ~1 layer is always
+# in flight during backprop recomputation.
 GC_LAYER_MULTIPLIERS = {
     "none": (None, None),
     "true": (2.0, 1.0),
@@ -125,8 +125,7 @@ class VramBreakdown:
     gradients: int
     activations: int
     cuda_overhead: int
-    # Equals `activations`; retained for backward compatibility with
-    # consumers that read this field.
+    # Equals `activations`; kept for backward compat with field consumers.
     activations_computed: int = 0
 
     @property
@@ -141,10 +140,10 @@ class VramBreakdown:
         )
 
     def min_gpu_vram(self, n_gpus: int) -> int:
-        """Minimum VRAM a single GPU needs: its shard + non-shardable costs.
+        """Min VRAM one GPU needs: its shard + non-shardable costs.
 
-        Weights/LoRA/optimizer/gradients shard across GPUs.
-        Activations do NOT shard (the GPU running a layer holds them).
+        Weights/LoRA/optimizer/gradients shard across GPUs; activations do
+        NOT (the GPU running a layer holds them).
         """
         shardable = self.model_weights + self.lora_adapters + self.optimizer_states + self.gradients
         per_gpu_fixed = self.activations + self.cuda_overhead
@@ -163,7 +162,7 @@ class VramBreakdown:
 
 
 def _first_scalar(value):
-    # why: ERNIE MoE configs ship moe_intermediate_size / moe_num_experts as
+    # ERNIE MoE ships moe_intermediate_size / moe_num_experts as
     # [routed, shared] lists; downstream arithmetic needs the routed scalar.
     if isinstance(value, (list, tuple)):
         return value[0] if value else None
@@ -171,8 +170,8 @@ def _first_scalar(value):
 
 
 def _max_scalar(value):
-    # why: Hunyuan-V1-MoE moe_topk can be a per-layer list; activation
-    # accounting uses the max top-k as a conservative upper bound.
+    # Hunyuan-V1-MoE moe_topk can be a per-layer list; activation accounting
+    # uses max top-k as a conservative upper bound.
     if isinstance(value, (list, tuple)):
         items = [v for v in value if v is not None]
         return max(items) if items else None
@@ -181,8 +180,8 @@ def _max_scalar(value):
 
 def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
     """Layer indices that use dense MLP instead of MoE. Position matters."""
-    # why: transformers Exaone-MoE / Laguna / Hy_v3 / GLM-MoE-DSA / GLM4-MoE-Lite /
-    # Ernie4_5_VL_MoE prefer per-position `mlp_layer_types` over the prefix-style
+    # Exaone-MoE / Laguna / Hy_v3 / GLM-MoE-DSA / GLM4-MoE-Lite / Ernie4_5_VL_MoE
+    # prefer per-position `mlp_layer_types` over prefix-style
     # `first_k_dense_replace` and may omit `decoder_sparse_step` entirely.
     layer_types = getattr(text_config, "mlp_layer_types", None)
     if layer_types:
@@ -190,7 +189,7 @@ def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
             i for i, t in enumerate(layer_types[:total_layers]) if str(t).lower() == "dense"
         )
 
-    # why: Llama4TextConfig.__init__ auto-populates self.moe_layers from
+    # Llama4TextConfig.__init__ auto-populates self.moe_layers from
     # interleave_moe_layer_step; Llama4TextDecoderLayer dispatches via
     # `layer_idx in config.moe_layers` (modeling_llama4.py).
     llama4_moe_layers = getattr(text_config, "moe_layers", None)
@@ -198,9 +197,9 @@ def _compute_dense_layer_indices(text_config, total_layers: int) -> tuple:
         moe_indices = {int(i) for i in llama4_moe_layers}
         return tuple(i for i in range(total_layers) if i not in moe_indices)
 
-    # why: transformers ERNIE 4.5 MoE / ERNIE 4.5 VL MoE declare MoE layers
-    # via moe_layer_start_index / moe_layer_end_index / moe_layer_interval;
-    # the model's per-layer guard is `(layer_idx + 1) % interval == 0` with
+    # ERNIE 4.5 MoE / ERNIE 4.5 VL MoE declare MoE layers via
+    # moe_layer_start_index / moe_layer_end_index / moe_layer_interval; the
+    # per-layer guard is `(layer_idx + 1) % interval == 0` with
     # start <= layer_idx <= end (modeling_ernie4_5_moe.py).
     moe_start = getattr(text_config, "moe_layer_start_index", None)
     moe_interval = getattr(text_config, "moe_layer_interval", None)
@@ -261,8 +260,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
 
     num_kv_heads = getattr(text_config, "num_key_value_heads", num_heads)
 
-    # why: DBRX places its MoE attrs on the DbrxFFNConfig sub-config; probe
-    # ffn_config as a secondary source so DBRX is not misclassified as dense.
+    # DBRX places its MoE attrs on the DbrxFFNConfig sub-config; probe
+    # ffn_config as a secondary source so DBRX isn't misclassified as dense.
     ffn_config = getattr(text_config, "ffn_config", None)
 
     def _moe_attr(name):
@@ -286,8 +285,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
     if moe_intermediate_raw is None:
         moe_intermediate_raw = _moe_attr("ffn_hidden_size")
     moe_intermediate = _first_scalar(moe_intermediate_raw)
-    # why: Exaone-MoE / ERNIE families alias num_shared_experts /
-    # moe_num_shared_experts to the canonical n_shared_experts.
+    # Exaone-MoE / ERNIE alias num_shared_experts / moe_num_shared_experts
+    # to the canonical n_shared_experts.
     n_shared_experts = (
         _first_scalar(_moe_attr("n_shared_experts"))
         or _first_scalar(_moe_attr("num_shared_experts"))
@@ -297,9 +296,9 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
     shared_expert_intermediate_size = _moe_attr("shared_expert_intermediate_size")
     if shared_expert_intermediate_size and n_shared_experts == 0:
         n_shared_experts = 1
-    # why: DBRX exposes moe_top_k, Hunyuan-V1-MoE exposes moe_topk (which can
-    # be a per-layer list); _max_scalar normalizes list values to the worst
-    # case so int(...) below cannot crash on the canonical attribute_map path.
+    # DBRX exposes moe_top_k; Hunyuan-V1-MoE exposes moe_topk (can be a
+    # per-layer list). _max_scalar normalizes lists to the worst case so
+    # int(...) below cannot crash on the canonical attribute_map path.
     num_experts_per_tok = (
         _max_scalar(_moe_attr("num_experts_per_tok"))
         or _max_scalar(_moe_attr("top_k_experts"))
@@ -313,9 +312,9 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
         dense_layer_indices = _compute_dense_layer_indices(text_config, num_layers)
     num_dense_layers = len(dense_layer_indices)
 
-    # why: Llama4 dense layers use intermediate_size_mlp; routed and shared
-    # experts use intermediate_size. Llama4TextMoe builds one shared_expert
-    # per MoE layer (modeling_llama4.py).
+    # Llama4 dense layers use intermediate_size_mlp; routed/shared experts use
+    # intermediate_size. Llama4TextMoe builds one shared_expert per MoE layer
+    # (modeling_llama4.py).
     intermediate_size_mlp_raw = _first_scalar(_moe_attr("intermediate_size_mlp"))
     dense_intermediate_size = (
         int(intermediate_size_mlp_raw) if intermediate_size_mlp_raw is not None else None
@@ -386,8 +385,8 @@ def extract_arch_config(hf_config) -> Optional[ModelArchConfig]:
 
 
 def _targets_all_linear(target_modules) -> bool:
-    # why: peft LoraConfig accepts target_modules="all-linear" as a bare
-    # string; iterating a string yields chars and never matches the set.
+    # peft LoraConfig accepts target_modules="all-linear" as a bare string;
+    # iterating a string yields chars and never matches the set.
     if isinstance(target_modules, str):
         target_modules = [target_modules]
     normalized = {str(module).lower().replace("_", "-") for module in target_modules}
@@ -425,10 +424,9 @@ def _is_kv_shared_layer(arch: ModelArchConfig, layer_idx: int) -> bool:
     if arch.num_kv_shared_layers <= 0:
         return False
     first_shared = arch.num_hidden_layers - arch.num_kv_shared_layers
-    # why: transformers Gemma4 (modeling_gemma4.py:1031, modular_gemma4.py:863)
-    # uses the same `> 0` guard so a fully-shared config raises during model
-    # construction; matching upstream avoids producing a detailed estimate
-    # for a shape the actual model code rejects.
+    # Gemma4 (modeling_gemma4.py:1031, modular_gemma4.py:863) uses the same
+    # `> 0` guard so a fully-shared config raises at model construction;
+    # matching upstream avoids estimating a shape the model code rejects.
     return layer_idx >= first_shared > 0
 
 
@@ -439,9 +437,9 @@ def _is_dense_mlp_layer(arch: ModelArchConfig, layer_idx: int) -> bool:
 
 
 def _per_layer_input_quantizable(arch: ModelArchConfig) -> int:
-    # why: Gemma4 PLE block adds per_layer_model_projection (single Linear),
+    # Gemma4 PLE block adds per_layer_model_projection (single Linear),
     # per_layer_input_gate (per layer), and per_layer_projection (per layer);
-    # see transformers gemma4/modular_gemma4.py:1077-1083 and :1247-1253.
+    # see gemma4/modular_gemma4.py:1077-1083 and :1247-1253.
     pli = arch.hidden_size_per_layer_input
     if pli <= 0:
         return 0
@@ -460,10 +458,10 @@ def _per_layer_input_norm_elements(arch: ModelArchConfig) -> int:
 
 
 def _per_layer_input_lora_params(arch: ModelArchConfig, r: int, target_modules) -> int:
-    # why: Unsloth's get_peft_regex (unsloth_zoo/peft_utils.py) requires module
-    # names to contain a component tag (mlp/attn/...); PLE module names lack
-    # any tag, so all-linear training does NOT attach LoRA to them. Only count
-    # PLE LoRA when the user explicitly names PLE modules.
+    # Unsloth's get_peft_regex (unsloth_zoo/peft_utils.py) requires module
+    # names to contain a component tag (mlp/attn/...); PLE names lack any tag,
+    # so all-linear does NOT attach LoRA to them. Only count PLE LoRA when the
+    # user explicitly names PLE modules.
     pli = arch.hidden_size_per_layer_input
     if pli <= 0:
         return 0
@@ -543,17 +541,17 @@ def _module_path_matches(skip_module: str, alias: str) -> bool:
     if alias_parts[0] == "layers":
         return skip_parts == alias_parts
     if len(skip_parts) <= len(alias_parts):
-        # why: transformers BNB quantizer suffix-matches short skip entries
-        # like ["q_proj"] / ["lm_head"] against full module paths, so a skip
-        # shorter than the alias is a tail match.
+        # BNB quantizer suffix-matches short skip entries like ["q_proj"] /
+        # ["lm_head"] against full paths, so a skip shorter than the alias is
+        # a tail match.
         return alias_parts[-len(skip_parts) :] == skip_parts
     if skip_parts[-len(alias_parts) :] != alias_parts:
         return False
     prefix_parts = skip_parts[: len(skip_parts) - len(alias_parts)]
     if not prefix_parts:
         return True
-    # why: bound the prefix to known text-tower roots so VLM skip names like
-    # vision_tower.model.layers..self_attn.q_proj do not shadow the text
+    # Bound the prefix to known text-tower roots so VLM skip names like
+    # vision_tower.model.layers..self_attn.q_proj don't shadow the text
     # alias model.layers..self_attn.q_proj.
     return ".".join(prefix_parts) in _SKIP_MODULE_TEXT_PREFIXES
 
@@ -587,9 +585,9 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
         mlp_dims = {name: dim for name, dim in dims.items() if name in MLP_TARGET_MODULES}
 
         if is_mla:
-            # why: _text_linear_dims uses (hd, hd) for q/o; MLA actually splits
-            # into q_a/q_b/kv_a/kv_b, so emit a single self_attn aggregate at
-            # the authoritative MLA per-layer total.
+            # _text_linear_dims uses (hd, hd) for q/o; MLA splits into
+            # q_a/q_b/kv_a/kv_b, so emit a single self_attn aggregate at the
+            # authoritative MLA per-layer total.
             layer_modules["self_attn"] = _compute_attn_elements(arch)
         else:
             for name, (in_dim, out_dim) in attn_dims.items():
@@ -607,17 +605,17 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
                 layer_modules["mlp.experts"] = _compute_routed_moe_elements(arch)
                 shared_moe = _compute_shared_moe_elements(arch)
                 if shared_moe:
-                    # why: Qwen3.5-MoE exposes shared expert as
-                    # mlp.shared_expert; Exaone-MoE/Laguna/GLM-style configs use
-                    # mlp.shared_experts. Register both names so child-path
-                    # llm_int8_skip_modules entries match the right shared block.
+                    # Qwen3.5-MoE exposes shared expert as mlp.shared_expert;
+                    # Exaone-MoE/Laguna/GLM-style use mlp.shared_experts.
+                    # Register both names so child-path llm_int8_skip_modules
+                    # entries match the right shared block.
                     layer_modules["mlp.shared_expert"] = shared_moe
                 if arch.moe_has_dense_mlp:
-                    # why: enable_moe_block runs the dense MLP and the MoE
-                    # experts in parallel; register both for skip matching.
-                    # Non-structured _text_linear_dims returns mlp_size from
-                    # _get_mlp_size which prefers moe_intermediate_size, so
-                    # rebuild dense dims from arch.intermediate_size directly.
+                    # enable_moe_block runs the dense MLP and MoE experts in
+                    # parallel; register both for skip matching. Non-structured
+                    # _text_linear_dims returns mlp_size from _get_mlp_size
+                    # (prefers moe_intermediate_size), so rebuild dense dims
+                    # from arch.intermediate_size directly.
                     if _uses_structured_layer_shapes(arch):
                         dense_dims = mlp_dims
                     else:
@@ -640,8 +638,8 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
             )
 
         if pli > 0:
-            # why: register PLE per-layer linears so llm_int8_skip_modules
-            # entries like model.layers.0.per_layer_input_gate match.
+            # Register PLE per-layer linears so llm_int8_skip_modules entries
+            # like model.layers.0.per_layer_input_gate match.
             layer_modules["per_layer_input_gate"] = hd_global * pli
             layer_modules["per_layer_projection"] = pli * hd_global
 
@@ -650,10 +648,10 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
             for name, value in layer_modules.items()
             if name == "self_attn" or name.startswith("self_attn.")
         )
-        # why: gemma4 enable_moe_block puts routed experts at the sibling
+        # gemma4 enable_moe_block puts routed experts at the sibling
         # layers..experts attribute, not under self.mlp; the layer's "mlp"
         # aggregate must reflect only the dense MLP path so a skip module
-        # `model.layers.0.mlp` does not over-skip into the experts block.
+        # `model.layers.0.mlp` doesn't over-skip into the experts block.
         is_sibling_experts = bool(arch.moe_has_dense_mlp)
         mlp_total = sum(
             value
@@ -683,11 +681,11 @@ def _build_text_module_elements(arch: ModelArchConfig) -> tuple[Dict[str, int],
             elements[canonical] = value
             _add_module_aliases(aliases, canonical, canonical.removeprefix("text."))
             if name == "mlp.experts" and arch.moe_has_dense_mlp:
-                # why: gemma4 enable_moe_block exposes routed experts at
+                # gemma4 enable_moe_block exposes routed experts at
                 # layers..experts (sibling of self.mlp), not under mlp.
                 _add_module_aliases(aliases, canonical, f"layers.{layer_idx}.experts")
             elif name == "mlp.shared_expert":
-                # why: Exaone-MoE / Laguna / GLM-style configs use the plural
+                # Exaone-MoE / Laguna / GLM-style use the plural
                 # `shared_experts` attribute name; register both spellings.
                 _add_module_aliases(
                     aliases,
@@ -733,8 +731,8 @@ def _get_mlp_size(arch: ModelArchConfig) -> int:
 
 
 def _dense_mlp_size(arch: ModelArchConfig) -> int:
-    # why: Llama4 dense layers use intermediate_size_mlp; routed/shared
-    # experts use intermediate_size. Other configs leave the field None.
+    # Llama4 dense layers use intermediate_size_mlp; routed/shared experts use
+    # intermediate_size. Other configs leave the field None.
     return arch.dense_intermediate_size or arch.intermediate_size
 
 
@@ -764,7 +762,7 @@ def _compute_dense_mlp_elements(arch: ModelArchConfig) -> int:
 
 
 def _shared_expert_size(arch: ModelArchConfig) -> int:
-    # why: Qwen3.5-MoE shared expert has its own intermediate_size (default 512)
+    # Qwen3.5-MoE shared expert has its own intermediate_size (default 512)
     # distinct from moe_intermediate_size; fall back to routed mlp_size for
     # families that share it (deepseek-style configs).
     return arch.shared_expert_intermediate_size or _get_mlp_size(arch)
@@ -782,10 +780,10 @@ def _compute_shared_moe_elements(arch: ModelArchConfig) -> int:
     hd = arch.hidden_size
     shared_size = _shared_expert_size(arch)
     total = hd * shared_size * 3 * arch.n_shared_experts
-    # why: only Qwen2-MoE / Qwen3.5-MoE define a shared_expert_gate Linear
-    # (hidden_size→1); other families (Exaone-MoE, HY-V3, GLM4-MoE-Lite, Laguna)
-    # have shared_experts without a gate. shared_expert_intermediate_size is the
-    # Qwen-style discriminator.
+    # Only Qwen2-MoE / Qwen3.5-MoE define a shared_expert_gate Linear
+    # (hidden_size->1); other families (Exaone-MoE, HY-V3, GLM4-MoE-Lite,
+    # Laguna) have shared_experts without a gate.
+    # shared_expert_intermediate_size is the Qwen-style discriminator.
     if arch.shared_expert_intermediate_size:
         total += arch.n_shared_experts * hd
     return total
@@ -824,8 +822,8 @@ def _compute_layer_elements(arch: ModelArchConfig):
             n_moe = n_layers - n_dense
             moe_mlp_total = _compute_moe_mlp_elements(arch) * n_moe
             if arch.moe_has_dense_mlp:
-                # why: enable_moe_block runs dense MLP and MoE experts in
-                # parallel; count dense for every layer alongside MoE.
+                # enable_moe_block runs dense MLP and MoE experts in parallel;
+                # count dense for every layer alongside MoE.
                 mlp_total = sum(per_layer_dense_mlp) + moe_mlp_total
             else:
                 dense_only_total = sum(
@@ -958,11 +956,10 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
         if n_experts > 1:
             n_dense = arch.num_dense_layers
             n_moe = n_layers - n_dense
-            # why: peft "all-linear" attaches LoRA to nn.Linear only;
-            # routed experts are nn.Parameter and need explicit
-            # gate_proj/up_proj/down_proj naming via Unsloth's
-            # get_moe_target_parameters. Shared experts are nn.Linear and
-            # are picked up by get_peft_regex.
+            # peft "all-linear" attaches LoRA to nn.Linear only; routed experts
+            # are nn.Parameter and need explicit gate_proj/up_proj/down_proj
+            # naming via Unsloth's get_moe_target_parameters. Shared experts are
+            # nn.Linear, picked up by get_peft_regex.
             routed_moe = (
                 0
                 if all_linear
@@ -983,7 +980,7 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
             )
             moe_mlp = routed_moe + shared_moe
             if arch.moe_has_dense_mlp:
-                # why: parallel dense MLP coexists with MoE on every layer.
+                # Parallel dense MLP coexists with MoE on every layer.
                 mlp_total = structured_dense_mlp + moe_mlp * n_moe
             else:
                 dense_only = sum(
@@ -999,7 +996,7 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l
         attn_total = _lora_attn_elements(arch, r, selected_modules) * n_layers
         n_dense = arch.num_dense_layers
         n_moe = n_layers - n_dense
-        # why: routed and shared experts may use different intermediate sizes
+        # Routed and shared experts may use different intermediate sizes
         # (Qwen3.5-MoE: routed mlp_size != shared_expert_intermediate_size).
         # See structured branch for the all-linear exclusion rationale; only
         # routed (nn.Parameter) experts are excluded under all-linear.
@@ -1064,7 +1061,7 @@ def compute_gradient_bytes(trainable_params: int) -> int:
 
 
 def _is_linear_attention(attention_implementation: Optional[str]) -> bool:
-    # why: PyTorch SDPA dispatches to flash/memory-efficient O(n) backends; only
+    # PyTorch SDPA dispatches to flash/memory-efficient O(n) backends; only
     # eager (and other non-flash impls) need the quadratic correction.
     return attention_implementation in LINEAR_ATTENTION_IMPLS
 
@@ -1081,16 +1078,16 @@ def _layer_qkv_mlp_sizes(arch: ModelArchConfig, layer_idx: int) -> tuple:
     is_moe_layer = n_experts > 1 and not _is_dense_mlp_layer(arch, layer_idx)
     if _uses_structured_layer_shapes(arch):
         q_size, kv_size, _has_k, _has_v = _layer_attention_dims(arch, layer_idx)
-        # why: KV-shared layers (Gemma4/Gemma3n) drop k_proj/v_proj WEIGHTS but
-        # the donor layer's K/V tensors stay alive across the shared range, so
-        # activation memory still pays for kv_size; only the weight path uses
+        # KV-shared layers (Gemma4/Gemma3n) drop k_proj/v_proj WEIGHTS but the
+        # donor layer's K/V tensors stay alive across the shared range, so
+        # activation memory still pays kv_size; only the weight path uses
         # has_k/has_v.
         layer_type = _layer_types(arch)[layer_idx]
         use_alt_attention = arch.attention_k_eq_v and layer_type != "sliding_attention"
         kv_count = 1 if use_alt_attention else 2
         qkv_size = q_size + kv_size * kv_count
         if is_moe_layer:
-            # why: each token routes through `num_experts_per_tok` experts; their
+            # Each token routes through `num_experts_per_tok` experts; their
             # gate/up/down intermediates are all live during MLP forward.
             mlp_size = _get_mlp_size(arch) * arch.num_experts_per_tok
             if arch.n_shared_experts:
@@ -1119,9 +1116,9 @@ def _per_layer_activation_bytes(
     activation_qkv = seq_len * batch_size * qkv_size
     residual_memory = (seq_len * batch_size) * 2
     activation_mlp = seq_len * batch_size * (mlp_size + mlp_size)
-    # why: per_layer_input_gate (hd-sized) and per_layer_projection (pli-sized)
-    # outputs materialize once per decoder layer when hidden_size_per_layer_input
-    # is set; see gemma4/modular_gemma4.py:1141-1145.
+    # per_layer_input_gate (hd-sized) and per_layer_projection (pli-sized)
+    # outputs materialize once per decoder layer when
+    # hidden_size_per_layer_input is set; see gemma4/modular_gemma4.py:1141-1145.
     pli = arch.hidden_size_per_layer_input
     activation_ple = seq_len * batch_size * (arch.hidden_size + pli) if pli > 0 else 0
     return int((activation_qkv + residual_memory + activation_mlp + activation_ple) * 2 * 1.25)
@@ -1154,8 +1151,8 @@ def compute_activation_bytes(
         )
         linear_bytes = int(max_layer_bytes * effective_layers)
 
-    # why: gemma4 per_layer_model_projection runs once outside the per-decoder
-    # loop and materializes a [B, S, L, PLI] tensor; see modular_gemma4.py:1247.
+    # gemma4 per_layer_model_projection runs once outside the per-decoder loop
+    # and materializes a [B, S, L, PLI] tensor; see modular_gemma4.py:1247.
     pli = arch.hidden_size_per_layer_input
     if pli > 0:
         linear_bytes += int(seq_len * batch_size * n_layers * pli * 2 * 1.25)
diff --git a/studio/backend/utils/inference/inference_config.py b/studio/backend/utils/inference/inference_config.py
index e07bc62cfd..87e2aac833 100644
--- a/studio/backend/utils/inference/inference_config.py
+++ b/studio/backend/utils/inference/inference_config.py
@@ -4,9 +4,9 @@
 """
 Inference configuration loading utilities.
 
-This module provides functions to load inference parameters (temperature, top_p, top_k, min_p)
-from model YAML configuration files, with fallback to default.yaml.
-Includes family-based lookup from inference_defaults.json for GGUF models.
+Loads inference parameters (temperature, top_p, top_k, min_p) from model YAML
+configs, falling back to default.yaml. Includes family-based lookup from
+inference_defaults.json for GGUF models.
 """
 
 from pathlib import Path
@@ -51,8 +51,8 @@ def get_family_inference_params(model_id: str) -> Dict[str, Any]:
     """
     Look up recommended inference parameters by model family.
 
-    Extracts the model family from the identifier (e.g. "unsloth/Qwen3.5-9B-GGUF" -> "qwen3.5")
-    and returns the matching parameters from inference_defaults.json.
+    Extracts the family from the identifier (e.g. "unsloth/Qwen3.5-9B-GGUF" ->
+    "qwen3.5") and returns the matching params from inference_defaults.json.
 
     Args:
         model_id: Model identifier (e.g. "unsloth/Qwen3.5-9B-GGUF")
@@ -65,12 +65,12 @@ def get_family_inference_params(model_id: str) -> Dict[str, Any]:
     if not _FAMILY_PATTERNS or not _FAMILY_DEFAULTS:
         return {}
 
-    # Normalize: lowercase, strip org prefix
+    # Normalize: lowercase, strip org prefix.
     normalized = model_id.lower()
     if "/" in normalized:
         normalized = normalized.split("/", 1)[1]
 
-    # Match against patterns (ordered longest-match-first in the JSON)
+    # Match patterns (ordered longest-match-first in the JSON).
     for pattern in _FAMILY_PATTERNS:
         if pattern in normalized:
             params = _FAMILY_DEFAULTS.get(pattern, {})
@@ -87,14 +87,13 @@ def _has_specific_yaml(model_identifier: str) -> bool:
     script_dir = Path(__file__).parent.parent.parent
     defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
 
-    # Check the mapping
+    # Check the mapping.
     if model_identifier.lower() in _REVERSE_MODEL_MAPPING:
         return True
 
-    # For local filesystem paths (e.g. C:\Users\...\model on Windows),
-    # normalize backslashes so Path().parts splits correctly on POSIX/WSL,
-    # then try matching the last 1-2 path components against the registry
-    # (mirrors the logic in load_model_defaults).
+    # For local paths (e.g. C:\Users\...\model on Windows), normalize backslashes
+    # so Path().parts splits correctly on POSIX/WSL, then match the last 1-2 path
+    # components against the registry (mirrors load_model_defaults).
     _is_local = is_local_path(model_identifier)
     _normalized = normalize_path(model_identifier) if _is_local else model_identifier
 
@@ -109,9 +108,8 @@ def _has_specific_yaml(model_identifier: str) -> bool:
     else:
         _lookup = model_identifier
 
-    # Check for exact filename match (basename for local paths to avoid
-    # passing absolute paths into rglob which raises
-    # "Non-relative patterns are unsupported" on Windows).
+    # Exact filename match (basename for local paths; passing absolute paths to
+    # rglob raises "Non-relative patterns are unsupported" on Windows).
     model_filename = _lookup.replace("/", "_") + ".yaml"
     for config_path in defaults_dir.rglob(model_filename):
         if config_path.is_file():
@@ -125,15 +123,15 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
     Load inference configuration parameters for a model.
 
     Priority chain:
-    1. Model-specific YAML (if it exists and has inference params)
-    2. Family-based defaults from inference_defaults.json
-    3. default.yaml fallback
+    1. Model-specific YAML (if it exists and has inference params).
+    2. Family-based defaults from inference_defaults.json.
+    3. default.yaml fallback.
 
     Args:
         model_identifier: Model identifier (e.g., "unsloth/llama-3-8b-bnb-4bit")
 
     Returns:
-        Dictionary containing inference parameters:
+        Dict of inference parameters:
         {
             "temperature": float,
             "top_p": float,
@@ -141,10 +139,10 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
             "min_p": float
         }
     """
-    # Load model defaults to get inference parameters
+    # Model defaults for inference parameters.
     model_defaults = load_model_defaults(model_identifier)
 
-    # Load default.yaml for fallback values
+    # default.yaml for fallback values.
     script_dir = Path(__file__).parent.parent.parent
     defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
     default_config_path = defaults_dir / "default.yaml"
@@ -158,18 +156,18 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
         except Exception as e:
             logger.warning(f"Failed to load default.yaml: {e}")
 
-    # Family-based defaults from inference_defaults.json
+    # Family-based defaults from inference_defaults.json.
     family_params = get_family_inference_params(model_identifier)
 
     model_inference = model_defaults.get("inference", {})
 
-    # If the model has its own YAML config, those values take priority over family defaults.
-    # If it only fell back to default.yaml, family defaults take priority.
+    # Model's own YAML beats family defaults; if it only fell back to
+    # default.yaml, family defaults win.
     has_own_yaml = _has_specific_yaml(model_identifier)
 
     def _get_param(key, hardcoded_default):
         if has_own_yaml:
-            # Model-specific YAML wins, then family fills gaps, then default.yaml
+            # Model-specific YAML wins, then family fills gaps, then default.yaml.
             val = model_inference.get(key)
             if val is not None and isinstance(val, (int, float)):
                 return val
@@ -177,7 +175,7 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
                 return family_params[key]
             return default_inference.get(key, hardcoded_default)
         else:
-            # No model-specific YAML: family wins, then default.yaml
+            # No model-specific YAML: family wins, then default.yaml.
             if key in family_params:
                 return family_params[key]
             return default_inference.get(key, hardcoded_default)
diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.py
index f0e642a38e..3635969c73 100644
--- a/studio/backend/utils/llama_cpp_freshness.py
+++ b/studio/backend/utils/llama_cpp_freshness.py
@@ -45,7 +45,7 @@ def _cache_dir() -> Path:
 
 def read_install_marker(binary_path: Optional[str]) -> Optional[dict]:
     """Walk up from binary_path to find UNSLOTH_PREBUILT_INFO.json.
-    None means no marker (source build / custom path) or invalid JSON."""
+    None = no marker (source build / custom path) or invalid JSON."""
     if not binary_path:
         return None
     cached = _marker_cache.get(binary_path)
diff --git a/studio/backend/utils/models/checkpoints.py b/studio/backend/utils/models/checkpoints.py
index 99770ce7a6..80312af0f7 100644
--- a/studio/backend/utils/models/checkpoints.py
+++ b/studio/backend/utils/models/checkpoints.py
@@ -1,9 +1,7 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Checkpoint scanning utilities for discovering training runs and their checkpoints.
-"""
+"""Checkpoint scanning utilities for discovering training runs and checkpoints."""
 
 import json
 import structlog
@@ -17,7 +15,7 @@ logger = get_logger(__name__)
 
 def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:
     """
-    Read the training loss from a checkpoint's trainer_state.json.
+    Read training loss from a checkpoint's trainer_state.json.
 
     Returns the loss from the last log_history entry, or None if unavailable.
     """
@@ -91,8 +89,8 @@ def scan_checkpoints(
             except Exception:
                 pass
 
-            # Fallback: extract base model name from folder name
-            # e.g. "unsloth_Llama-3.2-3B-Instruct_1771227800" → "unsloth/Llama-3.2-3B-Instruct"
+            # Fallback: extract base model name from the folder name, e.g.
+            # "unsloth_Llama-3.2-3B-Instruct_1771227800" → "unsloth/Llama-3.2-3B-Instruct"
             if not metadata.get("base_model"):
                 parts = item.name.rsplit("_", 1)
                 if len(parts) == 2 and parts[1].isdigit():
@@ -103,13 +101,13 @@ def scan_checkpoints(
                     else:
                         metadata["base_model"] = name_part
 
-            # This is a valid training run
+            # Valid training run.
             checkpoints = []
 
-            # Placeholder for the main adapter — loss filled from last checkpoint below
+            # Main adapter placeholder — loss filled from the last checkpoint below.
             checkpoints.append((item.name, str(item), None))
 
-            # Scan for intermediate checkpoints (checkpoint-N subdirs)
+            # Scan for intermediate checkpoints (checkpoint-N subdirs).
             for sub in sorted(item.iterdir()):
                 if not sub.is_dir() or not sub.name.startswith("checkpoint-"):
                     continue
@@ -119,7 +117,7 @@ def scan_checkpoints(
                     loss = _read_checkpoint_loss(sub)
                     checkpoints.append((sub.name, str(sub), loss))
 
-            # Assign the last checkpoint's loss to the main adapter entry
+            # Assign the last checkpoint's loss to the main adapter entry.
             if len(checkpoints) > 1:
                 last_checkpoint_loss = checkpoints[-1][2]
                 checkpoints[0] = (
diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.py
index 32618773b7..a2912cc843 100644
--- a/studio/backend/utils/models/gguf_metadata.py
+++ b/studio/backend/utils/models/gguf_metadata.py
@@ -1,10 +1,9 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""Free-function ``general.*`` reader for GGUF headers, used by
-``detect_mmproj_file`` to pair weights and projectors via
-``general.base_model.0.repo_url``. ~30 ms per file, cached by
-(path, mtime, size)."""
+"""``general.*`` reader for GGUF headers, used by ``detect_mmproj_file`` to
+pair weights and projectors via ``general.base_model.0.repo_url``. ~30 ms
+per file, cached by (path, mtime, size)."""
 
 from __future__ import annotations
 
@@ -65,9 +64,9 @@ def _cache_key(path: str) -> Optional[_CacheKey]:
 
 
 def read_gguf_general_metadata(path: str) -> Optional[Dict[str, str]]:
-    """Return ``general.*`` strings from a GGUF header, or ``None`` if
-    the file is missing, unreadable, or not a GGUF. ``{}`` means the
-    file is valid but carries none of the wanted keys."""
+    """Return ``general.*`` strings from a GGUF header, or ``None`` if the
+    file is missing, unreadable, or not a GGUF. ``{}`` means valid but
+    carrying none of the wanted keys."""
     key = _cache_key(path)
     if key is None:
         return None
@@ -156,9 +155,9 @@ _FIXED_VTYPE_SIZES: Dict[int, int] = {
 
 
 def _skip_gguf_value(f, vtype: int) -> bool:
-    """Advance past one GGUF value. ``f.seek(.., 1)`` past EOF is legal
-    on a regular file so truncation is detected on the next read; we
-    only return False for unknown types or sanity-bound overflow."""
+    """Advance past one GGUF value. ``f.seek(.., 1)`` past EOF is legal on a
+    regular file, so truncation is caught on the next read; return False only
+    for unknown types or sanity-bound overflow."""
     if vtype == 8:  # STRING
         slen_bytes = f.read(8)
         if len(slen_bytes) < 8:
@@ -265,9 +264,9 @@ def _read_gguf_bool(path: str, wanted_key: str) -> Optional[bool]:
 
 
 def read_mmproj_audio_capability(path: str) -> Optional[bool]:
-    """``clip.has_audio_encoder`` from an mmproj GGUF (e.g. Gemma 4's gemma4ua):
-    ``True``/``False`` if present, ``None`` if absent / unreadable. Flags
-    audio-input models independently of tokenizer token names."""
+    """``clip.has_audio_encoder`` from an mmproj GGUF (e.g. Gemma 4's
+    gemma4ua): ``True``/``False`` if present, ``None`` if absent/unreadable.
+    Flags audio-input models independently of tokenizer token names."""
     return _read_gguf_bool(path, "clip.has_audio_encoder")
 
 
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 2947bab3d3..abddd07367 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1,9 +1,7 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Model and LoRA configuration handling
-"""
+"""Model and LoRA configuration handling."""
 
 from dataclasses import dataclass
 from typing import Optional, Dict, Any
@@ -58,7 +56,7 @@ def _env_offline() -> bool:
 import re as _re
 
 _MODEL_SIZE_RE = _re.compile(r"(?:^|[-_/])(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)
-# MoE active-parameter pattern: matches "A3B", "A3.5B", etc.
+# MoE active-parameter pattern: "A3B", "A3.5B", etc.
 _ACTIVE_SIZE_RE = _re.compile(r"(?:^|[-_/])a(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)
 
 
@@ -66,8 +64,8 @@ def extract_model_size_b(model_id: str) -> float | None:
     """Extract model size in billions from a model identifier.
 
     Prefers MoE active-parameter notation (e.g. ``A3B`` in
-    ``Qwen3.5-35B-A3B``) over the total parameter count.
-    Handles both ``B`` (billions) and ``M`` (millions) suffixes.
+    ``Qwen3.5-35B-A3B``) over total params. Handles ``B`` (billions)
+    and ``M`` (millions) suffixes.
     """
     mid = (model_id or "").lower()
     active = _ACTIVE_SIZE_RE.search(mid)
@@ -81,9 +79,9 @@ def extract_model_size_b(model_id: str) -> float | None:
     return val / 1000.0 if size.group(2).lower() == "m" else val
 
 
-# Model name mapping: maps all equivalent model names to their canonical YAML config file
-# Format: "canonical_model_name.yaml": [list of all equivalent model names]
-# Based on the model mapper provided - canonical filename is based on the first model name in the mapper
+# Maps equivalent model names to their canonical YAML config file.
+# Format: "canonical_model_name.yaml": [equivalent model names].
+# Canonical filename derives from the first model name in each list.
 MODEL_NAME_MAPPING = {
     # ── Embedding models ──
     "unsloth_all-MiniLM-L6-v2.yaml": [
@@ -457,7 +455,7 @@ MODEL_NAME_MAPPING = {
     ],
 }
 
-# Reverse mapping for quick lookup: model_name -> canonical_filename
+# Reverse lookup: model_name -> canonical_filename
 _REVERSE_MODEL_MAPPING = {}
 for canonical_file, model_names in MODEL_NAME_MAPPING.items():
     for model_name in model_names:
@@ -470,19 +468,17 @@ def load_model_config(
     token: Optional[str] = None,
     trust_remote_code: bool = True,
 ):
-    """
-    Load model config with optional authentication control.
-    """
+    """Load model config with optional authentication control."""
     from transformers import AutoConfig
 
     if token:
-        # Explicit token provided - use it
+        # Explicit token provided
         return AutoConfig.from_pretrained(
             model_name, trust_remote_code = trust_remote_code, token = token
         )
 
     if not use_auth:
-        # Load without any authentication (for public model checks)
+        # No authentication (for public model checks)
         with without_hf_auth():
             return AutoConfig.from_pretrained(
                 model_name,
@@ -490,7 +486,7 @@ def load_model_config(
                 token = None,
             )
 
-    # Use default authentication (cached tokens)
+    # Default authentication (cached tokens)
     return AutoConfig.from_pretrained(
         model_name,
         trust_remote_code = trust_remote_code,
@@ -588,8 +584,8 @@ _VISION_CHECK_INLINE_HELPERS = (
     "    )\n"
 )
 
-# Inline script executed in a subprocess with transformers 5.x activated.
-# Receives model_name and token via argv, prints JSON result to stdout.
+# Subprocess script run with transformers 5.x active. Takes model_name and
+# token via argv, prints JSON result to stdout.
 _VISION_CHECK_SCRIPT = (
     r"""
 import sys, os, json
@@ -636,10 +632,10 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)
     with .venv_t5/ prepended to sys.path so AutoConfig recognizes newer
     architectures (glm4_moe_lite, etc.).
 
-    Returns True/False for definitive results, or None for transient failures
-    (timeouts, subprocess errors) so callers can decide whether to cache
-    the result. Subprocess failures are treated as transient because they
-    can be caused by temporary HF/auth/network issues.
+    Returns True/False for definitive results, or None for transient
+    failures (timeouts, subprocess errors) so callers can decide whether
+    to cache. Subprocess failures are treated as transient since they may
+    stem from temporary HF/auth/network issues.
     """
     token_arg = hf_token or ""
 
@@ -699,7 +695,7 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)
 
 
 def _token_fingerprint(token: Optional[str]) -> Optional[str]:
-    """Return a SHA256 digest of the token for use as a cache key.
+    """SHA256 digest of the token for use as a cache key.
 
     Avoids storing the raw bearer token in process memory as a dict key.
     """
@@ -708,26 +704,26 @@ def _token_fingerprint(token: Optional[str]) -> Optional[str]:
     return hashlib.sha256(token.encode("utf-8")).hexdigest()
 
 
-# Cache vision detection results per session to avoid repeated subprocess spawns.
-# Keyed by (normalized_model_name, token_fingerprint) to handle gated models correctly.
-# Only definitive results (True/False from successful detection) are cached;
-# transient failures (network errors, timeouts) are NOT cached so they can be retried.
+# Cache vision detection per session to avoid repeated subprocess spawns.
+# Keyed by (normalized_model_name, token_fingerprint) to handle gated models.
+# Only definitive results are cached; transient failures (network, timeouts)
+# are NOT cached so they can be retried.
 _vision_detection_cache: Dict[Tuple[str, Optional[str]], bool] = {}
 _vision_cache_lock = threading.Lock()
 
 
 def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
     """
-    Detect vision-language models (VLMs) by checking architecture in config.
+    Detect vision-language models (VLMs) via architecture in config.
     Works for fine-tuned models since they inherit the base architecture.
 
     For models that require transformers 5.x (e.g. GLM-4.7-Flash), the check
     runs in a subprocess with .venv_t5/ activated -- same pattern as the
     training and inference workers.
 
-    Results are cached per (model_name, token_fingerprint) for the lifetime of
-    the process to avoid repeated subprocess spawns and HuggingFace API calls.
-    Transient failures are not cached so they can be retried on the next call.
+    Results are cached per (model_name, token_fingerprint) for the process
+    lifetime to avoid repeated subprocess spawns and HuggingFace API calls.
+    Transient failures are not cached so they can be retried.
 
     Args:
         model_name: Model identifier (HF repo or local path)
@@ -749,21 +745,21 @@ def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
         resolved_name = model_name
     cache_key = (resolved_name, _token_fingerprint(hf_token))
 
-    # Lock-free fast path for cache hits. Uses a sentinel to distinguish
-    # "key not found" from "value is False" in a single atomic dict.get() call.
+    # Lock-free fast path for cache hits. Sentinel distinguishes "key not
+    # found" from "value is False" in a single atomic dict.get() call.
     _MISS = object()
     cached = _vision_detection_cache.get(cache_key, _MISS)
     if cached is not _MISS:
         return cached
 
     # Compute outside the lock to avoid serializing long-running detection
-    # (subprocess spawns with 60s timeout, HF API calls) across all models.
-    # The tradeoff: two concurrent calls for the same uncached model may
-    # both run detection, but they produce the same result and the second
-    # write is a benign no-op.
+    # (60s-timeout subprocess spawns, HF API calls) across all models.
+    # Tradeoff: two concurrent calls for the same uncached model may both
+    # run detection, but produce the same result and the second write is a
+    # benign no-op.
     result = _is_vision_model_uncached(resolved_name, hf_token)
-    # Only cache definitive results; None means a transient failure occurred
-    # and we should retry on the next call instead of locking in a wrong answer.
+    # Only cache definitive results; None means a transient failure, so
+    # retry on the next call instead of locking in a wrong answer.
     if result is not None:
         with _vision_cache_lock:
             _vision_detection_cache[cache_key] = result
@@ -774,13 +770,12 @@ def is_vision_model(model_name: str, hf_token: Optional[str] = None) -> bool:
 def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -> Optional[bool]:
     """Uncached vision model detection -- called by is_vision_model().
 
-    Returns True/False for definitive results, or None when detection failed
-    due to a transient error (network, timeout, subprocess failure) so the
-    caller knows not to cache the result.
+    Returns True/False for definitive results, or None on transient errors
+    (network, timeout, subprocess failure) so the caller knows not to cache.
 
     Do not call directly; use is_vision_model() instead.
     """
-    # Models that need transformers 5.x must be checked in a subprocess
+    # Models needing transformers 5.x must be checked in a subprocess
     # because AutoConfig in the main process (transformers 4.57.x) doesn't
     # recognize their architectures.
     from utils.transformers_version import needs_transformers_5
@@ -798,7 +793,7 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
     try:
         config = load_model_config(model_name, use_auth = True, token = hf_token)
 
-        # Exclude audio-only models that share ForConditionalGeneration suffix
+        # Exclude audio-only models sharing the ForConditionalGeneration suffix
         # (e.g. CsmForConditionalGeneration, WhisperForConditionalGeneration)
         model_type = getattr(config, "model_type", None)
         if model_type in _AUDIO_ONLY_MODEL_TYPES:
@@ -818,8 +813,8 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
 
     except Exception as e:
         logger.warning(f"Could not determine if {model_name} is vision model: {e}")
-        # Permanent failures (model not found, gated, bad config) should be
-        # cached as False. Transient failures (network, timeout) should not.
+        # Permanent failures (not found, gated, bad config) cache as False;
+        # transient failures (network, timeout) should not.
         try:
             from huggingface_hub.errors import RepositoryNotFoundError, GatedRepoError
         except ImportError:
@@ -841,10 +836,10 @@ def _is_vision_model_uncached(model_name: str, hf_token: Optional[str] = None) -
 
 VALID_AUDIO_TYPES = ("snac", "csm", "bicodec", "dac", "whisper", "audio_vlm")
 
-# Cache detection results per session to avoid repeated API calls
+# Cache detection per session to avoid repeated API calls
 _audio_detection_cache: Dict[str, Optional[str]] = {}
 
-# Tokenizer token patterns → audio_type (all 6 types detected from tokenizer_config.json)
+# Tokenizer token patterns → audio_type (all 6 types from tokenizer_config.json)
 _AUDIO_TOKEN_PATTERNS = {
     "csm": lambda tokens: "<|AUDIO|>" in tokens and "<|audio_eos|>" in tokens,
     "whisper": lambda tokens: "<|startoftranscript|>" in tokens,
@@ -863,10 +858,10 @@ _AUDIO_TOKEN_PATTERNS = {
 
 def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:
     """
-    Dynamically detect if a model is an audio model and return its type.
+    Detect if a model is an audio model and return its type.
 
-    Fully dynamic — works for any model, not just known ones.
-    Uses tokenizer_config.json special tokens to detect all 6 audio types.
+    Works for any model, not just known ones. Uses tokenizer_config.json
+    special tokens to detect all 6 audio types.
 
     Returns: audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper', 'audio_vlm') or None.
     """
@@ -882,10 +877,10 @@ def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Option
 
 
 def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:
-    """Detect audio type from tokenizer special tokens (for LLM-based audio models).
+    """Detect audio type from tokenizer special tokens (LLM-based audio models).
 
-    First checks local HF cache, then fetches tokenizer_config.json from HuggingFace.
-    Checks added_tokens_decoder for distinctive patterns.
+    Checks local HF cache first, then fetches tokenizer_config.json from
+    HuggingFace. Examines added_tokens_decoder for distinctive patterns.
     """
 
     def _check_token_patterns(tok_config: dict) -> Optional[str]:
@@ -898,7 +893,7 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None
                 return audio_type
         return None
 
-    # 1) Check local HF cache first (works for gated/offline models)
+    # 1) Local HF cache first (works for gated/offline models)
     try:
         repo_dir = get_cache_path(model_name)
         if repo_dir is not None and repo_dir.exists():
@@ -924,7 +919,7 @@ def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None
         import os
 
         paths_to_try = ["tokenizer_config.json", "LLM/tokenizer_config.json"]
-        # Use provided token, or fall back to env
+        # Use provided token, else env
         token = hf_token or os.environ.get("HF_TOKEN")
         headers = {}
         if token:
@@ -994,7 +989,7 @@ _MODEL_FAMILY_TOKENS: tuple[str, ...] = (
 )
 
 
-# Word-bounded match: any letter on either side disqualifies. Stops
+# Word-bounded match: a letter on either side disqualifies. Stops
 # ``phi`` matching ``sapphire``, ``yi`` matching ``tiny``, etc.
 _FAMILY_TOKEN_RE_CACHE: Dict[str, "_re.Pattern[str]"] = {}
 
@@ -1022,8 +1017,8 @@ def _detect_family_token(filename: str) -> Optional[str]:
 
 
 def mmproj_matches_model_family(model_path: str, mmproj_path: str) -> bool:
-    """Defense-in-depth guard for the launcher: True unless both filenames
-    carry recognised family tokens that disagree."""
+    """Launcher guard: True unless both filenames carry recognised family
+    tokens that disagree."""
     model_fam = _detect_family_token(Path(model_path).name)
     mmproj_fam = _detect_family_token(Path(mmproj_path).name)
     if model_fam is None or mmproj_fam is None:
@@ -1116,7 +1111,7 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optional
                 continue
             if resolved in seen_resolved:
                 continue
-            # Prefer ``general.type=='mmproj'``; fall back to filename.
+            # Prefer ``general.type=='mmproj'``, else filename.
             meta = read_gguf_general_metadata(str(resolved))
             by_meta = is_mmproj_by_metadata(meta)
             if by_meta is True or (by_meta is None and _is_mmproj(f.name)):
@@ -1211,12 +1206,10 @@ def detect_gguf_model(path: str) -> Optional[str]:
     return None
 
 
-# Preferred GGUF quantization levels, in descending priority.
-# Q4_K_M is a good default: small, fast, acceptable quality.
-# UD (Unsloth Dynamic) variants are always preferred over standard quants
-# because they provide better quality per bit. If the repo has no UD variants
-# (e.g., bartowski repos), the standard quants are used as fallback.
-# Ordered by best size/quality tradeoff, not raw quality.
+# Preferred GGUF quant levels, descending priority. Q4_K_M is a good default
+# (small, fast, acceptable quality). UD (Unsloth Dynamic) variants beat
+# standard quants on quality per bit; repos without UD (e.g. bartowski) fall
+# back to standard quants. Ordered by size/quality tradeoff, not raw quality.
 _GGUF_QUANT_PREFERENCE = [
     # UD variants (best quality per bit) -- Q4 is the sweet spot
     "UD-Q4_K_XL",
@@ -1263,8 +1256,7 @@ def _pick_best_gguf(filenames: list[str]) -> Optional[str]:
     """
     Pick the best GGUF file from a list of filenames.
 
-    Prefers quantization levels in _GGUF_QUANT_PREFERENCE order.
-    Falls back to the first .gguf file found.
+    Prefers quant levels in _GGUF_QUANT_PREFERENCE order; else the first .gguf.
     """
     gguf_files = [f for f in filenames if f.lower().endswith(".gguf")]
     if not gguf_files:
@@ -1291,7 +1283,7 @@ class GgufVariantInfo:
 
 def _extract_quant_label(filename: str) -> str:
     """
-    Extract quantization label like Q4_K_M, IQ4_XS, BF16 from a GGUF filename.
+    Extract quant label like Q4_K_M, IQ4_XS, BF16 from a GGUF filename.
 
     Examples:
         "gemma-3-4b-it-Q4_K_M.gguf"          → "Q4_K_M"
@@ -1318,8 +1310,8 @@ def _extract_quant_label(filename: str) -> str:
     )
     match = re.search(quant_re, stem, re.IGNORECASE)
     # Subdir layouts like ``BF16/foo.gguf`` keep the quant in the directory,
-    # not the basename. Look at the parent dirs too so the variant label
-    # matches the snapshot-relative path produced elsewhere.
+    # not the basename. Check parent dirs too so the label matches the
+    # snapshot-relative path produced elsewhere.
     if not match and "/" in filename:
         parents = filename.rsplit("/", 1)[0]
         for segment in reversed(parents.split("/")):
@@ -1330,16 +1322,16 @@ def _extract_quant_label(filename: str) -> str:
     if match:
         prefix = match.group(1) or ""
         return f"{prefix}{match.group(2)}"
-    # Fallback: last segment after hyphen
+    # Fallback: last hyphen-separated segment
     return stem.split("-")[-1]
 
 
 def _iter_hf_cache_snapshots(repo_id: str):
     """Yield HF cache snapshot dirs for *repo_id*, newest first.
 
-    Empty generator if HF_HUB_CACHE is missing, the repo isn't cached,
-    or has no snapshots. Repo name match is case-insensitive to handle
-    casing drift between download time and lookup.
+    Empty if HF_HUB_CACHE is missing, the repo isn't cached, or has no
+    snapshots. Repo name match is case-insensitive to handle casing drift
+    between download time and lookup.
     """
     try:
         from huggingface_hub import constants as hf_constants
@@ -1389,8 +1381,8 @@ def list_gguf_variants(
     """
     List all GGUF quantization variants in a HuggingFace repo.
 
-    Separates main model files from mmproj (vision projection) files.
-    The presence of mmproj files indicates a vision-capable model.
+    Separates main model files from mmproj (vision projection) files;
+    mmproj presence indicates a vision-capable model.
 
     Returns:
         (variants, has_vision): list of non-mmproj GGUF variants + vision flag.
@@ -1406,9 +1398,9 @@ def list_gguf_variants(
     try:
         info = hf_model_info(repo_id, token = hf_token, files_metadata = True)
     except Exception as e:
-        # Permanent errors (deleted/gated/bad revision) must surface to
-        # the caller; serving stale cache here would mask the real cause.
-        # Matches the early-return in ``detect_gguf_model_remote``.
+        # Permanent errors (deleted/gated/bad revision) must surface to the
+        # caller; serving stale cache would mask the real cause. Matches the
+        # early-return in ``detect_gguf_model_remote``.
         if type(e).__name__ in (
             "RepositoryNotFoundError",
             "GatedRepoError",
@@ -1438,7 +1430,7 @@ def list_gguf_variants(
             continue
         size = sibling.size or 0
 
-        # mmproj files are vision projection models, not main model files
+        # mmproj files are vision projections, not main model files
         if "mmproj" in fname.lower():
             has_vision = True
             continue
@@ -1457,9 +1449,8 @@ def list_gguf_variants(
             )
         )
 
-    # Sort by size descending (largest = best quality first).
-    # Recommended pinning and OOM demotion are handled client-side
-    # where GPU VRAM info is available.
+    # Sort by size descending (largest = best quality first). Recommended
+    # pinning and OOM demotion happen client-side where GPU VRAM info exists.
     variants.sort(key = lambda v: -v.size_bytes)
 
     return variants, has_vision
@@ -1468,11 +1459,10 @@ def list_gguf_variants(
 def _resolve_gguf_dir(p: Path) -> Optional[Path]:
     """Resolve a path to the directory containing GGUF variants.
 
-    If *p* is already a directory, returns it directly.  If *p* is a ``.gguf``
-    file whose parent directory has model metadata (``config.json`` or
-    ``adapter_config.json``), returns the parent -- all GGUFs in that
-    directory belong to the same model.  Returns ``None`` for loose standalone
-    GGUFs (no config) to avoid cross-wiring unrelated models.
+    Directory *p* returns directly. A ``.gguf`` file whose parent dir has
+    model metadata (``config.json`` or ``adapter_config.json``) returns the
+    parent -- all GGUFs there belong to the same model. Returns ``None`` for
+    loose standalone GGUFs (no config) to avoid cross-wiring unrelated models.
     """
     if p.is_dir():
         return p
@@ -1490,9 +1480,9 @@ def _resolve_gguf_dir(p: Path) -> Optional[Path]:
 def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], bool]:
     """List GGUF quantization variants in a local directory.
 
-    Mirrors :func:`list_gguf_variants` but reads from the filesystem
-    instead of the HuggingFace API.  Aggregates shard sizes by quant
-    label so that split GGUFs appear as a single variant.
+    Mirrors :func:`list_gguf_variants` but reads the filesystem instead of
+    the HuggingFace API. Aggregates shard sizes by quant label so split
+    GGUFs appear as a single variant.
 
     Returns:
         (variants, has_vision): list of non-mmproj GGUF variants + vision flag.
@@ -1505,10 +1495,10 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
     quant_first_file: dict[str, str] = {}
     has_vision = False
 
-    # Recurse so variant-specific subdirectories (e.g. ``BF16/...gguf``
-    # used by some HF GGUF repos for the largest quants) are picked up.
-    # Filenames in the result preserve the relative subpath so that
-    # ``_find_local_gguf_by_variant`` can locate the file again.
+    # Recurse so variant-specific subdirs (e.g. ``BF16/...gguf`` used by
+    # some HF GGUF repos for the largest quants) are picked up. Result
+    # filenames keep the relative subpath so ``_find_local_gguf_by_variant``
+    # can locate the file again.
     for f in sorted(_iter_gguf_files(p, recursive = True)):
         if _is_mmproj(f.name):
             has_vision = True
@@ -1517,8 +1507,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
             size = f.stat().st_size
         except OSError:
             size = 0
-        # Pass the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``
-        # produce distinct quant labels instead of collapsing on basename.
+        # Use the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``
+        # get distinct quant labels instead of collapsing on basename.
         rel = f.relative_to(p).as_posix()
         quant = _extract_quant_label(rel)
         quant_totals[quant] = quant_totals.get(quant, 0) + size
@@ -1540,8 +1530,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo
 def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
     """Find the GGUF file in *directory* matching a quantization *variant*.
 
-    For sharded GGUFs (multiple files with the same quant label), returns
-    the first shard (sorted by name) which is what ``llama-server -m`` expects.
+    For sharded GGUFs (multiple files sharing a quant label), returns the
+    first shard (sorted by name), which is what ``llama-server -m`` expects.
 
     Returns the resolved absolute path, or ``None`` if no match.
     """
@@ -1549,10 +1539,10 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
     if p is None:
         return None
 
-    # Recurse into subdirectories so variants stored under a quant-named
-    # subdir (e.g. ``BF16/foo-BF16-00001-of-00002.gguf``) are found.
-    # Match against the relative path so the quant label can come from
-    # the directory name when the basename omits it.
+    # Recurse so variants under a quant-named subdir (e.g.
+    # ``BF16/foo-BF16-00001-of-00002.gguf``) are found. Match the relative
+    # path so the quant label can come from the dir name when the basename
+    # omits it.
     matches = sorted(
         f
         for f in _iter_gguf_files(p, recursive = True)
@@ -1566,8 +1556,8 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:
 def _detect_gguf_from_hf_cache(repo_id: str) -> Optional[str]:
     """Best GGUF filename for *repo_id* from the local HF cache, or None.
 
-    Excludes mmproj (vision projector) files so a partial cache that
-    only has the projector cannot route the projector as the main model.
+    Excludes mmproj (vision projector) files so a partial cache holding only
+    the projector cannot route it as the main model.
     """
     for snap in _iter_hf_cache_snapshots(repo_id):
         rel_files = [
@@ -1586,16 +1576,15 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Op
 
     Returns the filename of the best GGUF file in the repo, or None.
 
-    Retries on transient HF Hub failures (network hiccups, 5xx, slow
-    cold-start of the API). Without retry, a single transient failure
-    here returns None silently and the caller treats the repo as
-    non-GGUF -- which on Apple Silicon (Mac UI route) means falling
-    through to the MLX backend, which then fails opening a non-existent
-    config.json on the GGUF-only repo. Three attempts with 1s/2s/4s
-    backoff covers the typical free-runner HF Hub flakiness.
+    Retries on transient HF Hub failures (network hiccups, 5xx, slow API
+    cold-start). Without retry, a single transient failure returns None
+    silently and the caller treats the repo as non-GGUF -- which on Apple
+    Silicon (Mac UI route) falls through to the MLX backend, which then
+    fails opening a non-existent config.json on the GGUF-only repo. Three
+    attempts with 1s/2s/4s backoff covers typical free-runner HF Hub flakiness.
 
-    When offline, falls back to the local HF cache so a downloaded
-    repo is still routed to llama-server (not MLX/Unsloth).
+    When offline, falls back to the local HF cache so a downloaded repo is
+    still routed to llama-server (not MLX/Unsloth).
     """
     import time
     from huggingface_hub import model_info as hf_model_info
@@ -1613,7 +1602,7 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Op
             return _pick_best_gguf(repo_files)
         except Exception as e:
             last_err = e
-            # 404 / RepoNotFound is permanent -- don't waste attempts.
+            # 404 / RepoNotFound is permanent -- don't retry.
             err_name = type(e).__name__
             if err_name in (
                 "RepositoryNotFoundError",
@@ -1660,20 +1649,20 @@ def download_gguf_file(
     return local_path
 
 
-# Cache embedding detection results per session to avoid repeated HF API calls
+# Cache embedding detection per session to avoid repeated HF API calls
 _embedding_detection_cache: Dict[tuple, bool] = {}
 
 
 def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
     """
-    Detect embedding/sentence-transformer models using HuggingFace model metadata.
+    Detect embedding/sentence-transformer models via HuggingFace metadata.
 
-    Uses a belt-and-suspenders approach combining three signals:
+    Combines three signals:
       1. "sentence-transformers" in model tags
       2. "feature-extraction" in model tags
       3. pipeline_tag is "sentence-similarity" or "feature-extraction"
 
-    This catches all known embedding models including those like gte-modernbert
+    Catches all known embedding models, including ones like gte-modernbert
     whose library_name is "transformers" rather than "sentence-transformers".
 
     Args:
@@ -1681,8 +1670,8 @@ def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
         hf_token: Optional HF token for accessing gated/private models
 
     Returns:
-        True if the model is an embedding model, False otherwise.
-        Defaults to False for local paths or on errors.
+        True if embedding model, else False. Defaults to False for local
+        paths or on errors.
     """
     cache_key = (model_name, hf_token)
     if cache_key in _embedding_detection_cache:
@@ -1774,8 +1763,8 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[st
     Scan outputs folder for trained Studio models.
 
     Returns:
-        List of tuples: [(display_name, model_path, model_type), ...]
-        model_type is "lora" for adapter runs and "merged" for full finetunes.
+        List of [(display_name, model_path, model_type), ...].
+        model_type is "lora" for adapter runs, "merged" for full finetunes.
     """
     trained_models = []
     outputs_path = resolve_output_dir(outputs_dir)
@@ -1796,7 +1785,7 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[st
                 trained_models.append((display_name, model_path, model_type))
                 logger.debug("Found trained model: %s (%s)", display_name, model_type)
 
-        # Sort by modification time (newest first)
+        # Sort by mtime, newest first
         trained_models.sort(key = lambda x: Path(x[1]).stat().st_mtime, reverse = True)
 
         logger.info(
@@ -1822,7 +1811,7 @@ def scan_exported_models(
       - Flat:      {name}-finetune-gguf/  (GGUF exports)
 
     Returns:
-        List of tuples: [(display_name, model_path, export_type, base_model), ...]
+        List of [(display_name, model_path, export_type, base_model), ...].
         export_type: "lora" | "merged" | "gguf"
     """
     results = []
@@ -1836,8 +1825,8 @@ def scan_exported_models(
             if not run_dir.is_dir():
                 continue
 
-            # Check for flat GGUF export (e.g. exports/gemma-3-4b-it-finetune-gguf/)
-            # Filter out mmproj (vision projection) files — they aren't loadable as main models
+            # Flat GGUF export (e.g. exports/gemma-3-4b-it-finetune-gguf/).
+            # Skip mmproj (vision projection) files — not loadable as main models.
             gguf_files = [f for f in _iter_gguf_files(run_dir) if not _is_mmproj(f.name)]
             if gguf_files:
                 base_model = None
@@ -1850,7 +1839,7 @@ def scan_exported_models(
                     pass
 
                 display_name = run_dir.name
-                model_path = str(gguf_files[0])  # path to the .gguf file
+                model_path = str(gguf_files[0])  # the .gguf file
                 results.append((display_name, model_path, "gguf", base_model))
                 logger.debug(f"Found GGUF export: {display_name}")
                 continue
@@ -1889,8 +1878,8 @@ def scan_exported_models(
                 elif has_gguf:
                     export_type = "gguf"
                     gguf_list = list(_iter_gguf_files(checkpoint_dir))
-                    # Check checkpoint_dir first, then fall back to parent run_dir
-                    # (export.py writes metadata to the top-level export directory)
+                    # Check checkpoint_dir first, then parent run_dir
+                    # (export.py writes metadata to the top-level export dir)
                     for meta_dir in (checkpoint_dir, run_dir):
                         export_meta = meta_dir / "export_metadata.json"
                         try:
@@ -1910,7 +1899,7 @@ def scan_exported_models(
                 else:
                     continue
 
-                # Fallback: read base model from the original training run's
+                # Fallback: read base model from the training run's
                 # adapter_config.json in ./outputs/{run_name}/
                 if not base_model:
                     outputs_adapter_cfg = resolve_output_dir(run_dir.name) / "adapter_config.json"
@@ -2012,7 +2001,7 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:
         if not _looks_like_lora_adapter(lora_path_obj):
             return None
 
-        # Try adapter_config.json first
+        # adapter_config.json first
         adapter_config_path = lora_path_obj / "adapter_config.json"
         if adapter_config_path.exists():
             with open(adapter_config_path, "r") as f:
@@ -2043,7 +2032,7 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:
         # Format: unsloth_Meta-Llama-3.1-8B-Instruct-bnb-4bit_timestamp
         dir_name = lora_path_obj.name
         if dir_name.startswith("unsloth_"):
-            # Remove timestamp suffix (usually _1234567890)
+            # Drop timestamp suffix (usually _1234567890)
             parts = dir_name.split("_")
             # Reconstruct model name
             if len(parts) >= 2:
@@ -2072,21 +2061,21 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
         model_name: Model identifier (e.g., "unsloth/Meta-Llama-3.1-8B-bnb-4bit")
 
     Returns:
-        Dictionary with default parameters from YAML file, or empty dict if not found
+        Dict of default parameters from the YAML file, or empty dict if none.
 
-    The function looks for a YAML file in configs/model_defaults/ (including subfolders)
-    based on the model name or its aliases from MODEL_NAME_MAPPING.
-    If no specific file exists, it falls back to default.yaml.
+    Looks for a YAML in configs/model_defaults/ (including subfolders) by the
+    model name or its aliases from MODEL_NAME_MAPPING, else falls back to
+    default.yaml.
     """
     try:
-        # Get the script directory to locate configs
+        # Locate configs relative to the script dir
         script_dir = Path(__file__).parent.parent.parent
         defaults_dir = script_dir / "assets" / "configs" / "model_defaults"
 
-        # First, check if model is in the mapping
+        # Check the mapping first
         if model_name.lower() in _REVERSE_MODEL_MAPPING:
             canonical_file = _REVERSE_MODEL_MAPPING[model_name.lower()]
-            # Search in subfolders and root
+            # Search subfolders and root
             for config_path in defaults_dir.rglob(canonical_file):
                 if config_path.is_file():
                     with open(config_path, "r", encoding = "utf-8") as f:
@@ -2094,10 +2083,9 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
                         logger.info(f"Loaded model defaults from {config_path} (via mapping)")
                         return config
 
-        # If model_name is a local path (e.g. /home/.../Spark-TTS-0.5B/LLM from
-        # adapter_config.json, or C:\Users\...\model on Windows), try matching
-        # the last 1-2 path components against the registry
-        # (e.g. "Spark-TTS-0.5B/LLM").
+        # For local paths (e.g. /home/.../Spark-TTS-0.5B/LLM from
+        # adapter_config.json, or C:\Users\...\model on Windows), match the
+        # last 1-2 path components against the registry (e.g. "Spark-TTS-0.5B/LLM").
         _is_local_path = is_local_path(model_name)
         # Normalize Windows backslash paths so Path().parts splits correctly
         # on POSIX/WSL hosts (pathlib treats backslashes as literals on Linux).
@@ -2118,13 +2106,13 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
                                     )
                                     return config
 
-        # Try exact model name match (for backward compatibility).
-        # For local filesystem paths, use only the directory basename to
-        # avoid passing absolute paths (e.g. C:\...) into rglob which
-        # raises "Non-relative patterns are unsupported" on Windows.
+        # Exact model name match (backward compatibility). For local paths,
+        # use only the dir basename to avoid passing absolute paths (e.g.
+        # C:\...) into rglob, which raises "Non-relative patterns are
+        # unsupported" on Windows.
         _lookup_name = Path(_normalized).name if _is_local_path else model_name
         model_filename = _lookup_name.replace("/", "_") + ".yaml"
-        # Search in subfolders and root
+        # Search subfolders and root
         for config_path in defaults_dir.rglob(model_filename):
             if config_path.is_file():
                 with open(config_path, "r", encoding = "utf-8") as f:
@@ -2150,17 +2138,17 @@ def load_model_defaults(model_name: str) -> Dict[str, Any]:
 
 @dataclass
 class ModelConfig:
-    """Configuration for a model to load"""
+    """Configuration for a model to load."""
 
     identifier: str  # Clean model identifier (org/name or path)
     display_name: str  # Original UI display name
     path: str  # Normalized filesystem path
-    is_local: bool  # Is this a local file vs HF model?
-    is_cached: bool  # Is this already in HF cache?
-    is_vision: bool  # Is this a vision model?
-    is_lora: bool  # Is this a lora adapter?
-    is_gguf: bool = False  # Is this a GGUF model?
-    is_audio: bool = False  # Is this a TTS audio model?
+    is_local: bool  # Local file vs HF model?
+    is_cached: bool  # Already in HF cache?
+    is_vision: bool  # Vision model?
+    is_lora: bool  # LoRA adapter?
+    is_gguf: bool = False  # GGUF model?
+    is_audio: bool = False  # TTS audio model?
     audio_type: Optional[str] = None  # Audio codec type: 'snac', 'csm', 'bicodec', 'dac'
     has_audio_input: bool = False  # Accepts audio input (ASR/speech understanding)
     gguf_file: Optional[str] = None  # Full path to the .gguf file (local mode)
@@ -2180,7 +2168,7 @@ class ModelConfig:
         """
         Create ModelConfig from a local LoRA adapter path.
 
-        Automatically detects the base model from adapter config.
+        Auto-detects the base model from adapter config.
 
         Args:
             lora_path: Path to LoRA adapter (e.g., "./outputs/unsloth_Meta-Llama-3.1_.../")
@@ -2196,27 +2184,23 @@ class ModelConfig:
                 logger.error(f"LoRA path does not exist: {lora_path}")
                 return None
 
-            # Get base model
             base_model = get_base_model_from_lora(lora_path)
             if not base_model:
                 logger.error(f"Could not determine base model for LoRA: {lora_path}")
                 return None
 
-            # Check if base model is vision
             is_vision = is_vision_model(base_model, hf_token = hf_token)
-
-            # Check if base model is audio
             audio_type = detect_audio_type(base_model, hf_token = hf_token)
 
             display_name = lora_path_obj.name
-            identifier = lora_path  # Use path as identifier for local LoRAs
+            identifier = lora_path  # path as identifier for local LoRAs
 
             return cls(
                 identifier = identifier,
                 display_name = display_name,
                 path = lora_path,
                 is_local = True,
-                is_cached = True,  # Local LoRAs are always "cached"
+                is_cached = True,  # local LoRAs are always "cached"
                 is_vision = is_vision,
                 is_lora = True,
                 is_audio = audio_type is not None and audio_type != "audio_vlm",
@@ -2241,7 +2225,7 @@ class ModelConfig:
         Create ModelConfig from a clean model identifier.
 
         For FastAPI routes where the frontend sends sanitized model paths.
-        No Gradio dropdown parsing - expects clean identifiers like:
+        No Gradio dropdown parsing; expects clean identifiers like:
         - "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit"
         - "./outputs/my_lora_adapter"
         - "/absolute/path/to/model"
@@ -2250,9 +2234,9 @@ class ModelConfig:
             model_id: Clean model identifier (HF repo name or local path)
             hf_token: Optional HF token for vision detection on gated models
             is_lora: Whether this is a LoRA adapter
-            gguf_variant: Optional GGUF quantization variant (e.g. "Q4_K_M").
-                For remote GGUF repos, specifies which quant to load via -hf.
-                If None, auto-selects using _pick_best_gguf().
+            gguf_variant: Optional GGUF quant variant (e.g. "Q4_K_M"). For
+                remote GGUF repos, sets which quant to load via -hf. If None,
+                auto-selects via _pick_best_gguf().
 
         Returns:
             ModelConfig or None if configuration cannot be created
@@ -2269,8 +2253,9 @@ class ModelConfig:
             identifier = f"unsloth/{identifier}"
             path = identifier
 
-        # Preserve requested casing, but if a case-variant already exists in local HF cache,
-        # reuse that exact repo_id spelling to avoid one-time re-downloads after #2592.
+        # Preserve requested casing, but if a case-variant already exists in
+        # local HF cache, reuse that exact repo_id spelling to avoid one-time
+        # re-downloads after #2592.
         if not is_local:
             resolved_identifier = resolve_cached_repo_id_case(identifier)
             if resolved_identifier != identifier:
@@ -2292,12 +2277,12 @@ class ModelConfig:
                 display_name = Path(gguf_file).stem
                 logger.info(f"Detected local GGUF model: {gguf_file}")
 
-                # Detect vision: check if base model is vision, then look for mmproj
+                # Vision: check base model, then look for mmproj
                 mmproj_file = None
                 gguf_is_vision = False
                 gguf_dir = Path(gguf_file).parent
 
-                # Determine if this is a vision model from export metadata
+                # Is this a vision model, per export metadata?
                 base_is_vision = False
                 meta_path = gguf_dir / "export_metadata.json"
                 if meta_path.exists():
@@ -2310,15 +2295,12 @@ class ModelConfig:
                     except Exception as e:
                         logger.debug(f"Could not read export metadata: {e}")
 
-                # If vision (or mmproj happens to exist), find the mmproj
-                # file. The recursive variant scan in
-                # ``_find_local_gguf_by_variant`` may have returned a
-                # weight file inside a quant-named subdir (e.g.
-                # ``.../BF16/foo.gguf``) while ``mmproj-*.gguf`` lives
-                # at the snapshot root. Pass ``search_root=path`` so
-                # ``detect_mmproj_file`` walks up to the snapshot root
-                # instead of seeing only the weight file's immediate
-                # parent.
+                # Find the mmproj file. The recursive variant scan in
+                # ``_find_local_gguf_by_variant`` may have returned a weight
+                # file inside a quant-named subdir (e.g. ``.../BF16/foo.gguf``)
+                # while ``mmproj-*.gguf`` lives at the snapshot root. Pass
+                # ``search_root=path`` so ``detect_mmproj_file`` walks up to
+                # the snapshot root instead of only the weight's parent.
                 mmproj_file = detect_mmproj_file(gguf_file, search_root = path)
                 if mmproj_file:
                     gguf_is_vision = True
@@ -2339,11 +2321,11 @@ class ModelConfig:
                     gguf_mmproj_file = mmproj_file,
                 )
         else:
-            # Check if the HF repo contains GGUF files
+            # Does the HF repo contain GGUF files?
             gguf_filename = detect_gguf_model_remote(identifier, hf_token = hf_token)
             if gguf_filename:
-                # Preflight: verify llama-server binary exists BEFORE user waits
-                # for a multi-GB download that llama-server handles natively
+                # Preflight: verify llama-server binary exists BEFORE the user
+                # waits for a multi-GB download llama-server handles natively
                 from core.inference.llama_cpp import LlamaCppBackend
 
                 if not LlamaCppBackend._find_llama_server_binary():
@@ -2352,7 +2334,7 @@ class ModelConfig:
                         "Run setup.sh to build it, or set LLAMA_SERVER_PATH."
                     )
 
-                # Use list_gguf_variants() to detect vision & resolve variant
+                # list_gguf_variants() detects vision & resolves the variant
                 variants, has_vision = list_gguf_variants(identifier, hf_token = hf_token)
                 variant = gguf_variant
                 if not variant:
@@ -2383,7 +2365,7 @@ class ModelConfig:
                     gguf_variant = variant,
                 )
 
-        # Auto-detect LoRA for local paths (check adapter_config.json on disk)
+        # Auto-detect LoRA for local paths (adapter_config.json on disk)
         if not is_lora and is_local:
             detected_base = (
                 get_base_model_from_lora(path) if _looks_like_lora_adapter(Path(path)) else None
@@ -2406,7 +2388,7 @@ class ModelConfig:
             except Exception as e:
                 logger.debug(f"Could not check remote LoRA status for '{identifier}': {e}")
 
-            # API may have failed; adapter_config.json may still be cached.
+            # API may have failed; adapter_config.json could still be cached.
             if not is_lora:
                 for snap in _iter_hf_cache_snapshots(identifier):
                     if (snap / "adapter_config.json").is_file():
@@ -2421,7 +2403,7 @@ class ModelConfig:
                 # Local LoRA: read adapter_config.json from disk
                 base_model = get_base_model_from_lora(path)
             else:
-                # Remote LoRA: download adapter_config.json from HF
+                # Remote LoRA: fetch adapter_config.json from HF
                 try:
                     from huggingface_hub import hf_hub_download
 
@@ -2473,7 +2455,7 @@ class ModelConfig:
         is_lora: bool = False,
     ) -> Optional["ModelConfig"]:
         """
-        Create a universal ModelConfig from UI dropdown/search selections.
+        Create a ModelConfig from UI dropdown/search selections.
         Handles base models and LoRA adapters.
         """
         selected = None
@@ -2487,7 +2469,7 @@ class ModelConfig:
 
         display_name = selected
 
-        #  Use the correct 'local_models' parameter to resolve display names
+        # Resolve display names via the 'local_models' parameter
         if " (Active)" in selected or " (Ready)" in selected:
             clean_display_name = selected.replace(" (Active)", "").replace(" (Ready)", "")
             if local_models:
@@ -2496,7 +2478,7 @@ class ModelConfig:
                         selected = local_path
                         break
 
-        # Clean all UI status indicators to get the final identifier
+        # Strip all UI status indicators to get the final identifier
         identifier = selected
         for status in UI_STATUS_INDICATORS:
             identifier = identifier.replace(status, "")
@@ -2516,23 +2498,23 @@ class ModelConfig:
                 identifier = resolved_identifier
                 path = resolved_identifier
 
-        # --- Logic for Base Model and Vision Detection ---
+        # --- Base Model and Vision Detection ---
         base_model = None
         is_vision = False
 
         if is_lora:
-            # For a LoRA, we MUST find its base model.
+            # A LoRA MUST have a base model.
             base_model = get_base_model_from_lora(path)
             if not base_model:
                 logger.warning(
                     f"Could not determine base model for LoRA '{path}'. Cannot create config."
                 )
-                return None  # Cannot proceed without a base model
+                return None  # cannot proceed without a base model
 
-            # A LoRA's vision capability is determined by its base model.
+            # A LoRA's vision capability comes from its base model.
             is_vision = is_vision_model(base_model, hf_token = hf_token)
         else:
-            # For a base model, just check its own vision status.
+            # Base model: check its own vision status.
             is_vision = is_vision_model(identifier, hf_token = hf_token)
 
         from utils.paths import is_model_cached
@@ -2547,5 +2529,5 @@ class ModelConfig:
             is_cached = is_cached,
             is_vision = is_vision,
             is_lora = is_lora,
-            base_model = base_model,  # This will be None for base models, and populated for LoRAs
+            base_model = base_model,  # None for base models, set for LoRAs
         )
diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.py
index eba7a9de6c..8805308829 100644
--- a/studio/backend/utils/paths/__init__.py
+++ b/studio/backend/utils/paths/__init__.py
@@ -1,9 +1,7 @@
 # SPDX-License-Identifier: AGPL-3.0-only
 # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
 
-"""
-Path utilities for model and dataset handling
-"""
+"""Path utilities for model and dataset handling."""
 
 from .path_utils import (
     normalize_path,
@@ -46,8 +44,8 @@ from .storage_roots import (
     resolve_dataset_path,
 )
 
-# Re-export shim: name-load the project-path helpers so the import-hoist
-# safety net sees them used here, not just listed in __all__ as strings.
+# Re-export shim: reference the project-path helpers by name so the
+# import-hoist safety net sees them used, not just named in __all__.
 _REEXPORTED = (documents_root, project_workspaces_root)
 
 __all__ = [
diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.py
index 22c6c46ee1..a065250154 100644
--- a/studio/backend/utils/paths/path_utils.py
+++ b/studio/backend/utils/paths/path_utils.py
@@ -17,7 +17,7 @@ logger = get_logger(__name__)
 # Per-process cache to avoid repeated cache-dir scans for the same identifier.
 _CACHE_CASE_RESOLUTION_MEMO: dict[str, str] = {}
 
-# Lightweight instrumentation counters for operational visibility.
+# Instrumentation counters for operational visibility.
 _CACHE_CASE_RESOLUTION_STATS: dict[str, int] = {
     "calls": 0,
     "memo_hits": 0,
@@ -63,8 +63,7 @@ def normalize_path(path: str) -> str:
 
     # Handle Windows drive letters (C:\\ or c:\\)
     if len(path) >= 3 and path[1] == ":" and path[2] in ("\\", "/"):
-        # Only map to /mnt// when running under WSL;
-        # on native Windows the drive letter must be preserved.
+        # Map to /mnt// only under WSL; native Windows keeps the drive letter.
         if _IS_WSL:
             drive = path[0].lower()
             rest = path[3:].replace("\\", "/")
@@ -86,7 +85,7 @@ def is_local_path(path: str) -> bool:
     if not path:
         return False
 
-    # If it exists on disk, treat as local (covers relative paths like "outputs/foo").
+    # Exists on disk → local (covers relative paths like "outputs/foo").
     try:
         if Path(normalize_path(path)).expanduser().exists():
             return True
@@ -122,7 +121,7 @@ def is_model_cached(model_name: str) -> bool:
     if not cache_path:
         return False
 
-    # Check for actual model files
+    # Check for model files
     for suffix in [".safetensors", ".bin", ".json"]:
         if list(cache_path.rglob(f"*{suffix}")):
             return True
@@ -146,9 +145,9 @@ def _hf_hub_cache_dir() -> Path:
 def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
     """Resolve repo_id to the exact casing already present in local HF cache.
 
-    Policy: prefer the requested/canonical repo_id, but if a case-variant already
-    exists in local HF cache, reuse that exact cached spelling. This avoids
-    duplicate downloads while preserving user intent whenever possible.
+    Policy: prefer the requested/canonical repo_id, but reuse a case-variant's
+    exact cached spelling if one already exists in local HF cache. Avoids
+    duplicate downloads while preserving user intent where possible.
     """
     _CACHE_CASE_RESOLUTION_STATS["calls"] += 1
 
@@ -163,8 +162,8 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
 
     expected_dir = f"models--{model_name.replace('/', '--')}"
 
-    # Always check the exact-case path first so a newly-appeared exact match
-    # wins over any previously memoized variant.
+    # Check the exact-case path first so a newly-appeared exact match wins over
+    # any previously memoized variant.
     exact_path = cache_dir / expected_dir
     if exact_path.is_dir():
         if use_memo:
@@ -172,8 +171,8 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
         _CACHE_CASE_RESOLUTION_STATS["exact_hits"] += 1
         return model_name
 
-    # Validate memoized entries still exist on disk before returning them.
-    # This prevents stale results when cache dirs are deleted/recreated.
+    # Validate memoized entries still exist on disk before returning them,
+    # preventing stale results when cache dirs are deleted/recreated.
     if use_memo:
         cached = _CACHE_CASE_RESOLUTION_MEMO.get(model_name)
         if cached is not None:
@@ -181,7 +180,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
             if cached_path.is_dir():
                 _CACHE_CASE_RESOLUTION_STATS["memo_hits"] += 1
                 return cached
-            # Stale entry -- drop it and re-scan below.
+            # Stale entry -- drop it and re-scan below
             _CACHE_CASE_RESOLUTION_MEMO.pop(model_name, None)
 
     expected_lower = expected_dir.lower()
@@ -200,7 +199,7 @@ def resolve_cached_repo_id_case(model_name: str, use_memo: bool = True) -> str:
             candidates.append(repo_part.replace("--", "/"))
 
         if candidates:
-            # Deterministic tie-break if multiple case variants coexist.
+            # Deterministic tie-break if multiple case variants coexist
             resolved = sorted(candidates)[0]
             if len(candidates) > 1:
                 _CACHE_CASE_RESOLUTION_STATS["tie_breaks"] += 1
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index b254c20f97..de88a0bf31 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -11,9 +11,9 @@ import tempfile
 
 
 def _infer_studio_home_from_venv() -> Path | None:
-    """Return parent dir of sys.prefix as STUDIO_HOME if running from an
+    """Return parent of sys.prefix as STUDIO_HOME when running from an
     installer-managed unsloth_studio venv. Sentinel-gated (share/studio.conf
-    or bin shim) so a developer venv named unsloth_studio is not misidentified.
+    or bin shim) so a dev venv named unsloth_studio isn't misidentified.
     """
     try:
         prefix = Path(sys.prefix).resolve()
@@ -38,8 +38,8 @@ def studio_root() -> Path:
     """Studio install root.
 
     Priority: UNSLOTH_STUDIO_HOME, then STUDIO_HOME alias, then sys.prefix
-    inference, then legacy ~/.unsloth/studio. UNSLOTH_STUDIO_HOME wins when
-    both are set (the more specific signal beats the generic alias).
+    inference, then legacy ~/.unsloth/studio. UNSLOTH_STUDIO_HOME wins if
+    both are set (specific signal beats generic alias).
     """
     override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()
     if not override:
@@ -56,7 +56,7 @@ def studio_root() -> Path:
 
 
 def cache_root() -> Path:
-    """Central cache directory for all studio downloads (models, datasets, etc.)."""
+    """Central cache dir for all studio downloads (models, datasets, etc.)."""
     return studio_root() / "cache"
 
 
@@ -158,16 +158,15 @@ def ensure_dir(path: Path) -> Path:
 
 
 def legacy_hf_cache_dir() -> Path:
-    """Old Unsloth-specific HF hub cache, kept for backward-compat scanning."""
+    """Old Unsloth-specific HF hub cache, kept for backward-compat scans."""
     return cache_root() / "huggingface" / "hub"
 
 
 def hf_default_cache_dir() -> Path:
-    """Return the platform default HuggingFace hub cache (ignoring env overrides).
+    """Platform default HuggingFace hub cache (ignoring env overrides).
 
-    This is the location HF uses when no ``HF_HUB_CACHE`` / ``HF_HOME``
-    env var is set.  We scan it so that models a user downloaded *before*
-    installing Unsloth Studio are still discovered.
+    Where HF caches when no ``HF_HUB_CACHE`` / ``HF_HOME`` is set. Scanned
+    so models downloaded *before* installing Unsloth Studio are discovered.
     """
     return Path.home() / ".cache" / "huggingface" / "hub"
 
@@ -183,7 +182,7 @@ def lmstudio_model_dirs() -> list[Path]:
             seen.add(resolved)
             dirs.append(p)
 
-    # 1. Check LM Studio settings.json for custom downloads folder
+    # 1. LM Studio settings.json custom downloads folder
     settings_path = Path.home() / ".lmstudio" / "settings.json"
     if settings_path.is_file():
         try:
@@ -207,17 +206,17 @@ def lmstudio_model_dirs() -> list[Path]:
 def well_known_model_dirs() -> list[Path]:
     """Return directories commonly used by other local LLM tools.
 
-    Used by the folder browser to offer quick-pick chips. Returns only
-    paths that exist on disk, so the UI never shows dead chips. Order
-    reflects a rough "likelihood the user has models here" -- LM Studio
-    and Ollama first, then the generic fallbacks.
+    Backs the folder browser's quick-pick chips. Returns only paths that
+    exist on disk, so the UI never shows dead chips. Order reflects rough
+    likelihood of models being there -- LM Studio and Ollama first, then
+    generic fallbacks.
     """
     candidates: list[Path] = []
 
     # LM Studio (reuses the logic above, including settings.json override)
     candidates.extend(lmstudio_model_dirs())
 
-    # Ollama -- both the user-level and common system-wide install paths
+    # Ollama -- user-level and common system-wide install paths
     # (https://github.com/ollama/ollama/issues/733).
     ollama_env = os.environ.get("OLLAMA_MODELS")
     if ollama_env:
@@ -229,7 +228,7 @@ def well_known_model_dirs() -> list[Path]:
     # HF hub cache root (separate from the explicit HF cache chip)
     candidates.append(Path.home() / ".cache" / "huggingface" / "hub")
 
-    # Generic "my models" spots users tend to drop things into
+    # Generic "my models" spots users drop things into
     for name in ("models", "Models"):
         candidates.append(Path.home() / name)
 
@@ -253,14 +252,12 @@ def _setup_cache_env() -> None:
     """Set cache environment variables for HuggingFace, uv, and vLLM.
 
     Respects the standard HF cache resolution chain: explicit ``HF_HOME``
-    / ``HF_HUB_CACHE`` env vars take priority, then ``XDG_CACHE_HOME``,
-    then the platform default (``~/.cache/huggingface``).  The legacy
-    Unsloth cache is still *scanned* for models but is never set as the
-    active download target.
+    / ``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 that are not already set by the user, so
-    explicit overrides (e.g. HF_HOME=/data/hf) are respected.
-    Works on Linux, macOS, and Windows.
+    Only sets variables not already set by the user, so explicit overrides
+    (e.g. HF_HOME=/data/hf) are respected. Works on Linux, macOS, Windows.
     """
     root = cache_root()
     xdg_cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")).expanduser()
@@ -327,8 +324,8 @@ def resolve_under_root(
 ) -> Path:
     """Resolve ``path_value`` and assert the result is under ``root``.
 
-    Absolutes are accepted only if already contained (so internal pre-resolved
-    paths re-enter idempotently); user-facing schemas reject absolutes upstream.
+    Absolutes are accepted only if already contained (so pre-resolved
+    internal paths re-enter idempotently); schemas reject absolutes upstream.
     """
     if not path_value or not str(path_value).strip():
         return root
diff --git a/studio/backend/utils/studio_version.py b/studio/backend/utils/studio_version.py
index e59439a2cc..98c48fe45c 100644
--- a/studio/backend/utils/studio_version.py
+++ b/studio/backend/utils/studio_version.py
@@ -74,8 +74,8 @@ def _exact_git_studio_tag(repo_root: Path) -> str | None:
 def get_studio_version(repo_root: Path | None = None) -> str:
     """Return the installed Studio release tag for display, or ``dev``.
 
-    This value is intentionally separate from the PyPI ``unsloth`` package
-    version used by update checks. It never performs network requests.
+    Intentionally separate from the PyPI ``unsloth`` package version used by
+    update checks. Never performs network requests.
     """
     resolved_repo_root = repo_root or _repo_root()
 
diff --git a/studio/backend/utils/subprocess_compat.py b/studio/backend/utils/subprocess_compat.py
index bedf8cf2e6..b7fe906e91 100644
--- a/studio/backend/utils/subprocess_compat.py
+++ b/studio/backend/utils/subprocess_compat.py
@@ -10,8 +10,8 @@ import sys
 def windows_hidden_subprocess_kwargs() -> dict[str, object]:
     """Return Windows-only subprocess kwargs that suppress console windows.
 
-    On non-Windows platforms returns an empty dict so callers can always
-    unpack the result into ``subprocess.run`` / ``subprocess.Popen`` via
+    Returns an empty dict off Windows so callers can always unpack it into
+    ``subprocess.run`` / ``subprocess.Popen`` via
     ``**windows_hidden_subprocess_kwargs()``.
     """
     if sys.platform != "win32":
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 16f964d628..7c1bc361b6 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -4,26 +4,24 @@
 """
 Automatic transformers version switching.
 
-Some newer model architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,
-tiny_qwen3_moe) require transformers>=5.3.0, while Gemma 4 models require
-transformers>=5.5.0.  Everything else needs the default 4.57.x that ships
-with Unsloth.
+Some newer architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,
+tiny_qwen3_moe) need transformers>=5.3.0; Gemma 4 needs >=5.5.0. Everything
+else uses the default 4.57.x that ships with Unsloth.
 
-Two separate target directories are maintained:
+Two target directories:
   - .venv_t5_530/  — transformers 5.3.0 (Ministral-3, GLM, Qwen3 MoE, etc.)
   - .venv_t5_550/  — transformers 5.5.0 (Gemma 4)
 
-When loading a LoRA adapter with a custom name, we resolve the base model from
-``adapter_config.json`` and check *that* against the model list.
+For a custom-named LoRA adapter, the base model is resolved from
+``adapter_config.json`` and checked against the model list.
 
 Strategy:
-  Training and inference run in subprocesses that activate the correct version
-  via sys.path (prepending the appropriate .venv_t5_*/ directory). See:
-    - core/training/worker.py
-    - core/inference/worker.py
+  Training and inference run in subprocesses that activate the right version
+  via sys.path (prepending the appropriate .venv_t5_*/ dir). See
+  core/training/worker.py and core/inference/worker.py.
 
-  For export (still in-process), ensure_transformers_version() does a lightweight
-  sys.path swap using the same directories pre-installed by setup.sh.
+  For export (in-process), ensure_transformers_version() does a lightweight
+  sys.path swap using the same setup.sh-installed directories.
 """
 
 import importlib
@@ -57,8 +55,7 @@ def _env_offline() -> bool:
 # Detection
 # ---------------------------------------------------------------------------
 
-# Lowercase substrings — if ANY appears anywhere in the lowered model name,
-# we need transformers 5.3.0.
+# Lowercase substrings — any match in the lowered model name needs transformers 5.3.0.
 TRANSFORMERS_5_MODEL_SUBSTRINGS: tuple[str, ...] = (
     "ministral-3-",  # Ministral-3-{3,8,14}B-{Instruct,Reasoning,Base}-2512
     "glm-4.7-flash",  # GLM-4.7-Flash
@@ -85,15 +82,15 @@ _TRANSFORMERS_550_MODEL_TYPES: set[str] = {
     "gemma4",
 }
 
-# Tokenizer classes that only exist in transformers>=5.x
+# Tokenizer classes that only exist in transformers>=5.x.
 _TRANSFORMERS_5_TOKENIZER_CLASSES: set[str] = {
     "TokenizersBackend",
 }
 
-# Cache for dynamic tokenizer_config.json lookups to avoid repeated fetches
+# Cache for dynamic tokenizer_config.json lookups (avoids repeated fetches).
 _tokenizer_class_cache: dict[str, bool] = {}
 
-# Cache for dynamic config.json lookups (architecture/model_type checks)
+# Cache for dynamic config.json lookups (architecture/model_type checks).
 _config_needs_550_cache: dict[str, bool] = {}
 
 # Versions
@@ -116,12 +113,10 @@ _VENV_T5_DIR = _VENV_T5_550_DIR
 def activate_transformers_for_subprocess(model_name: str) -> None:
     """Activate the correct transformers version in a subprocess worker.
 
-    Call this BEFORE any ML imports. Resolves LoRA adapters to their base
-    model, determines the required tier, and prepends the appropriate
-    ``.venv_t5_*`` directory to ``sys.path``.  Also propagates the path
-    via ``PYTHONPATH`` for child processes (e.g. GGUF converter).
-
-    Used by training, inference, and export workers.
+    Call BEFORE any ML imports. Resolves LoRA adapters to their base model,
+    determines the required tier, prepends the appropriate ``.venv_t5_*`` dir to
+    ``sys.path``, and propagates it via ``PYTHONPATH`` for child processes
+    (e.g. GGUF converter). Used by training, inference, and export workers.
     """
     resolved = _resolve_base_model(model_name)
     tier = get_transformers_tier(resolved)
@@ -155,11 +150,10 @@ def activate_transformers_for_subprocess(model_name: str) -> None:
 def _resolve_base_model(model_name: str) -> str:
     """If *model_name* points to a LoRA adapter, return its base model.
 
-    Checks for ``adapter_config.json`` locally first.  Only calls the heavier
-    ``get_base_model_from_lora`` for paths that are actual local directories
-    (avoids noisy warnings for plain HF model IDs).
-
-    Returns the original *model_name* unchanged if it is not a LoRA adapter.
+    Checks ``adapter_config.json`` locally first. Only calls the heavier
+    ``get_base_model_from_lora`` for real local directories (avoids noisy
+    warnings for plain HF model IDs). Returns *model_name* unchanged if not a
+    LoRA adapter.
     """
     # --- Fast local check ---------------------------------------------------
     local_path = Path(model_name)
@@ -221,11 +215,11 @@ def _resolve_base_model(model_name: str) -> str:
 
 
 def _check_tokenizer_config_needs_v5(model_name: str) -> bool:
-    """Fetch tokenizer_config.json from HuggingFace and check if the
-    tokenizer_class requires transformers 5.x.
+    """True if the model's tokenizer_class requires transformers 5.x.
 
-    Results are cached in ``_tokenizer_class_cache`` to avoid repeated fetches.
-    Returns False on any network/parse error (fail-open to default version).
+    Checks local tokenizer_config.json, else fetches from HuggingFace. Cached in
+    ``_tokenizer_class_cache``. Returns False on any network/parse error
+    (fail-open to default version).
     """
     if model_name in _tokenizer_class_cache:
         return _tokenizer_class_cache[model_name]
@@ -280,12 +274,11 @@ def _check_tokenizer_config_needs_v5(model_name: str) -> bool:
 
 
 def _check_config_needs_550(model_name: str) -> bool:
-    """Check ``config.json`` for architectures or model_type that require
-    transformers 5.5.0 (e.g. Gemma 4).
+    """True if ``config.json`` has architectures/model_type needing transformers
+    5.5.0 (e.g. Gemma 4).
 
-    Checks locally first, then falls back to fetching from HuggingFace.
-    Results are cached in ``_config_needs_550_cache``.
-    Returns False on any error (fail-open to lower tier).
+    Checks locally first, else fetches from HuggingFace. Cached in
+    ``_config_needs_550_cache``. Returns False on any error (fail-open to lower tier).
     """
     if model_name in _config_needs_550_cache:
         return _config_needs_550_cache[model_name]
@@ -352,10 +345,8 @@ def _check_config_needs_550(model_name: str) -> bool:
 def get_transformers_tier(model_name: str) -> str:
     """Return the transformers tier required for *model_name*.
 
-    Returns ``"550"`` for models needing transformers 5.5.0 (e.g. Gemma 4),
-    ``"530"`` for models needing transformers 5.3.0 (e.g. Ministral-3, Qwen3 MoE),
-    or ``"default"`` for everything else (4.57.x).
-
+    ``"550"`` for transformers 5.5.0 (e.g. Gemma 4), ``"530"`` for 5.3.0
+    (e.g. Ministral-3, Qwen3 MoE), or ``"default"`` for everything else (4.57.x).
     The 5.5.0 check runs first, then 5.3.0.
     """
     lowered = model_name.lower()
@@ -407,9 +398,9 @@ _PURGE_PREFIXES = (
     "accelerate",
     "auto_gptq",
     # NOTE: bitsandbytes is intentionally EXCLUDED — it registers torch custom
-    # operators at import time via torch.library.define(). Those registrations
-    # live in torch's global operator registry which survives module purge.
-    # Re-importing bitsandbytes after purge → duplicate registration → crash.
+    # operators at import via torch.library.define() into torch's global
+    # registry, which survives module purge. Re-importing it after purge →
+    # duplicate registration → crash.
     # Our own modules that import from transformers at module level
     # (e.g. model_config.py: `from transformers import AutoConfig`)
     "utils.models",
@@ -462,15 +453,15 @@ def _venv_dir_is_valid(venv_dir: str, packages: tuple[str, ...]) -> bool:
         pkg_name = parts[0]
         pkg_version = parts[1] if len(parts) > 1 else None
         pkg_name_norm = pkg_name.replace("-", "_")
-        # Check directory exists
+        # Directory must exist.
         if not any(
             (Path(venv_dir) / d).is_dir() for d in (pkg_name_norm, pkg_name_norm.replace("_", "-"))
         ):
             return False
-        # For unpinned packages, existence is enough
+        # Unpinned packages: existence is enough.
         if pkg_version is None:
             continue
-        # Check version via .dist-info metadata
+        # Check version via .dist-info metadata.
         dist_info_found = False
         for di in Path(venv_dir).glob(f"{pkg_name_norm}-*.dist-info"):
             metadata = di / "METADATA"
@@ -504,7 +495,7 @@ def _venv_t5_is_valid() -> bool:
 
 def _install_to_dir(pkg: str, target_dir: str) -> bool:
     """Install a single package into *target_dir*, preferring uv then pip."""
-    # Try uv first (faster) if already on PATH -- do NOT install uv at runtime
+    # Try uv first (faster) if on PATH -- do NOT install uv at runtime.
     if shutil.which("uv"):
         result = subprocess.run(
             [
@@ -529,7 +520,7 @@ def _install_to_dir(pkg: str, target_dir: str) -> bool:
             return True
         logger.warning("uv install of %s failed, falling back to pip", pkg)
 
-    # Fallback to pip
+    # Fallback to pip.
     result = subprocess.run(
         [
             sys.executable,
@@ -621,13 +612,13 @@ def ensure_transformers_version(model_name: str) -> None:
       • Need 5.3.0 → prepend .venv_t5_530/ to sys.path, purge modules.
       • Need 4.x  → remove all .venv_t5_*/ from sys.path, purge modules.
 
-    For LoRA adapters with custom names, the base model is resolved from
+    For custom-named LoRA adapters, the base model is resolved from
     ``adapter_config.json`` before checking.
 
-    NOTE: Training and inference use subprocess isolation instead of this
-    function. This is only used by the export path (routes/export.py).
+    NOTE: Training and inference use subprocess isolation instead. Used only by
+    the export path (routes/export.py).
     """
-    # Resolve LoRA adapters to their base model for accurate detection
+    # Resolve LoRA adapters to their base model for accurate detection.
     resolved = _resolve_base_model(model_name)
     tier = get_transformers_tier(resolved)
 
@@ -666,10 +657,10 @@ def ensure_transformers_version(model_name: str) -> None:
                 model_name,
             )
             return
-        # Different 5.x → need to switch (e.g. 5.3.0 loaded but need 5.5.0)
+        # Different 5.x → must switch (e.g. 5.3.0 loaded but need 5.5.0).
         in_memory_major = int(in_memory.split(".")[0])
         if in_memory_major == target_major and venv_dir is None:
-            # Both are default (4.x) — close enough
+            # Both are default (4.x) — close enough.
             logger.info(
                 "transformers %s already loaded — correct for '%s'",
                 in_memory,
@@ -679,7 +670,7 @@ def ensure_transformers_version(model_name: str) -> None:
 
     # --- Switch version -----------------------------------------------------
     if venv_dir is not None:
-        # First remove any other 5.x venv from sys.path
+        # First remove any other 5.x venv from sys.path.
         _deactivate_5x()
         if not ensure_fn():
             raise RuntimeError(
diff --git a/studio/backend/utils/update_status.py b/studio/backend/utils/update_status.py
index 9b71ff31a0..ad9dabcf36 100644
--- a/studio/backend/utils/update_status.py
+++ b/studio/backend/utils/update_status.py
@@ -3,9 +3,8 @@
 
 """Web update status helpers for browser-served Unsloth Studio.
 
-This module is intentionally side-effect light: no network work happens at
-import time or from /api/health. The PyPI check is lazy, cached, and only used
-for normal PyPI-managed installs.
+Side-effect light: no network work at import time or from /api/health.
+The PyPI check is lazy, cached, and only for PyPI-managed installs.
 """
 
 from __future__ import annotations
@@ -66,9 +65,9 @@ def reset_update_status_cache() -> None:
 def detect_install_source() -> str:
     """Return a coarse install source without exposing local paths.
 
-    Sources are intentionally conservative. PEP 610 local/vcs metadata wins.
-    Legacy source installs are treated as local only when package files resolve
-    outside site-packages/dist-packages and under a Git checkout.
+    Conservative: PEP 610 local/vcs metadata wins. Legacy source
+    installs count as local only when package files resolve outside
+    site-packages/dist-packages and under a Git checkout.
     """
     try:
         dist = distribution(PACKAGE_NAME)
diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.py
index 7a7774be40..c51fc267f2 100644
--- a/studio/backend/utils/utils.py
+++ b/studio/backend/utils/utils.py
@@ -77,14 +77,14 @@ def log_and_http_error(
 @contextmanager
 def without_hf_auth():
     """
-    Context manager to temporarily disable HuggingFace authentication.
+    Temporarily disable HuggingFace authentication.
 
     Usage:
         with without_hf_auth():
             # Code that should run without cached tokens
             model_info(model_name, token=None)
     """
-    # Save environment variables
+    # Save and clear env vars
     saved_env = {}
     env_vars = ["HF_TOKEN", "HUGGINGFACE_HUB_TOKEN", "HF_HOME"]
     for var in env_vars:
@@ -92,11 +92,10 @@ def without_hf_auth():
             saved_env[var] = os.environ[var]
             del os.environ[var]
 
-    # Save disable flag
     saved_disable = os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN")
     os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
 
-    # Move token files temporarily
+    # Move token files aside temporarily
     token_files = []
     token_locations = [
         Path.home() / ".cache" / "huggingface" / "token",
@@ -121,7 +120,7 @@ def without_hf_auth():
             except Exception as e:
                 logger.error(f"Failed to restore token {original}: {e}")
 
-        # Restore environment
+        # Restore env
         for var, value in saved_env.items():
             os.environ[var] = value
 
@@ -133,14 +132,11 @@ def without_hf_auth():
 
 def format_error_message(error: Exception, model_name: str) -> str:
     """
-    Format user-friendly error messages for common issues.
+    Format a user-friendly error message for common load issues.
 
     Args:
         error: The exception that occurred
         model_name: Name of the model being loaded
-
-    Returns:
-        User-friendly error string
     """
     error_str = str(error).lower()
     model_short = model_name.split("/")[-1] if "/" in model_name else model_name
@@ -171,5 +167,4 @@ def format_error_message(error: Exception, model_name: str) -> str:
         )
         return f"Not enough {device_label} memory to load '{model_short}'. Try a smaller model or free memory."
 
-    # Generic fallback
     return str(error)
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index cca30bfd44..59632963b7 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -27,12 +27,12 @@ def has_blackwell_gpu() -> bool:
     """Return True if any visible NVIDIA GPU has compute capability >= 10.0
     (Blackwell: sm_100, sm_120, sm_121, ...).
 
-    Dao-AILab does not publish prebuilt flash-attention wheels for these
-    architectures, and the older-arch wheels fail to load on Blackwell, so
-    callers use this gate to skip the flash-attn install/upgrade path.
+    Dao-AILab publishes no prebuilt flash-attention wheels for these archs,
+    and older-arch wheels fail to load on Blackwell, so callers use this gate
+    to skip the flash-attn install/upgrade path.
 
-    Result is cached for the process lifetime since GPU hardware does not
-    change. Tests that mock subprocess/nvidia-smi must call
+    Cached for the process lifetime since GPU hardware doesn't change. Tests
+    that mock subprocess/nvidia-smi must call
     ``has_blackwell_gpu.cache_clear()`` before each invocation.
     """
     exe = shutil.which("nvidia-smi")
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index 09953843f0..80e5257c8d 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -89,9 +89,9 @@ def env_int(
     return value
 
 
-# Prefer "latest" over "master" -- "master" bypasses the prebuilt resolver
+# Prefer "latest" over "master": "master" bypasses the prebuilt resolver
 # (no matching GitHub release), forces a source build, and causes HTTP 422
-# errors. Only use "master" temporarily when the latest release is missing
+# errors. Use "master" only temporarily when the latest release lacks
 # support for a new model architecture.
 DEFAULT_LLAMA_TAG = os.environ.get("UNSLOTH_LLAMA_TAG", "latest")
 # Default published repo for prebuilt release resolution. Linux uses
@@ -113,21 +113,19 @@ LEMONADE_ROCM_RELEASES_API = f"https://api.github.com/repos/{LEMONADE_ROCM_REPO}
 
 
 def _lemonade_release_api_for(llama_tag: str) -> str:
-    """Return the GitHub API URL for the lemonade release that matches a
-    requested llama.cpp tag.
+    """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 the
-    caller has pinned a specific tag (e.g. "b1260"), point at the same tag in
-    lemonade. Lemonade tracks `ggml-org/llama.cpp` build tags (e.g. "b1260")
-    but is NOT guaranteed to publish every upstream build -- lemonade may be
-    several builds behind ggml-org. Pinning to a specific tag that lemonade
-    skipped will produce a 404 and the caller falls through to the upstream
-    tarball; that is intentional so pinned installs stay reproducible.
-    Do NOT pass a `unslothai/llama.cpp` fork tag -- the fork uses its own
-    namespace and will always 404 against lemonade.
+    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 an unexpected slash / hash / query
-    character cannot reshape the URL.
+    The tag is URL-encoded with `safe=""` so a stray slash / hash / query
+    char cannot reshape the URL.
     """
     normalized = (llama_tag or "").strip()
     if not normalized or normalized.lower() == "latest":
@@ -162,25 +160,25 @@ DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS = env_int(
     2,
     minimum = 1,
 )
-# Deeper macOS-only walk-back: upstream can ship a run of prebuilts built for a
-# newer macOS than the host, only caught at validate time, so an older host must
-# skip the whole run. Free on new hosts (first plan validates, extras unused).
+# Deeper macOS-only walk-back: upstream can ship a run of prebuilts built for
+# a newer macOS than the host, caught only at validate time, so an older host
+# must skip the whole run. Free on new hosts (first plan validates).
 DEFAULT_MAX_MACOS_RELEASE_FALLBACKS = env_int(
     "UNSLOTH_LLAMA_MAX_MACOS_RELEASE_FALLBACKS",
     16,
     minimum = 1,
 )
 # Deterministic macOS pin. At b9428 ggml-org's macOS runner moved to macOS 26
-# (Tahoe), so b9428+ prebuilts only load on macOS 26+. b9415 is the last build
-# stamped below 26 (arm64 minos 14, x64 minos 13.3); loads on macOS 13.3/14/15/26.
+# (Tahoe), so b9428+ prebuilts load only on macOS 26+. b9415 is the last build
+# stamped below 26 (arm64 minos 14, x64 minos 13.3); loads on 13.3/14/15/26.
 _PINNED_MACOS_FALLBACK_TAG = "b9415"
 _PINNED_MACOS_LATEST_FLOOR = (26, 0)
 FORCE_COMPILE_DEFAULT_REF = os.environ.get("UNSLOTH_LLAMA_FORCE_COMPILE_REF", "master")
 
 # sm_103 (B300 / GB300 Blackwell Ultra) is not built natively but runs on the
 # bundled base compute_100 PTX, which the driver JIT-compiles forward to sm_103.
-# It is listed in every bundle that ships the sm_100 build (the "newer" and
-# "portable" classes) so those hosts get a prebuilt instead of a source compile.
+# Listed in every bundle that ships the sm_100 build (the "newer" and
+# "portable" classes) so those hosts get a prebuilt, not a source compile.
 DIRECT_LINUX_BUNDLE_PROFILES: dict[str, dict[str, Any]] = {
     "cuda12-older": {
         "runtime_line": "cuda12",
@@ -234,18 +232,18 @@ DIRECT_LINUX_BUNDLE_PROFILES: dict[str, dict[str, Any]] = {
 
 # Lowest CUDA major we ship prebuilts for, and the highest major we probe for
 # installed runtime libraries. Detection and runtime-line derivation are
-# generated per major so a new toolkit (cuda14, ...) needs no code change while
-# llama.cpp keeps the cudart64_.dll / libcudart.so. naming.
+# generated per major so a new toolkit (cuda14, ...) needs no code change as
+# long as llama.cpp keeps the cudart64_.dll / libcudart.so. naming.
 _MIN_CUDA_MAJOR = 12
 _MAX_PROBE_CUDA_MAJOR = 19
 
 # Last ggml-org release whose Windows win-cuda-13 build is still sub-13.3
 # (cuda-13.1, b9360, 2026-05-27). Upstream bumped win-cuda-13 to 13.3 at b9365
 # and now ships only cuda-12.4 + cuda-13.3. cuda-12.4 predates Blackwell (ggml
-# compiles sm_120 only at toolkit >= 12.8), so a Blackwell host on a 13.0/13.1/13.2
-# driver is gated off 13.3 and would drop to a CPU-only 12.4 build. b9360 is
-# immutable, so we pin its cuda-13.1 build (plus paired cudart) as a GPU
-# fallback for exactly those hosts. See unslothai/unsloth#5887.
+# compiles sm_120 only at toolkit >= 12.8), so a Blackwell host on a
+# 13.0/13.1/13.2 driver is gated off 13.3 and would drop to CPU-only 12.4.
+# b9360 is immutable, so we pin its cuda-13.1 build (plus paired cudart) as a
+# GPU fallback for exactly those hosts. See unslothai/unsloth#5887.
 _PINNED_BLACKWELL_FALLBACK_TAG = "b9360"
 _PINNED_BLACKWELL_FALLBACK_RUNTIME = "13.1"
 # Floor at 13.0: b9360 ships native sm_120a SASS (no PTX/JIT) and a bundled
@@ -255,15 +253,15 @@ _PINNED_BLACKWELL_DRIVER_FLOOR = (13, 0)
 _BLACKWELL_MIN_SM = 120
 # ggml compiles Blackwell sm_120 only at toolkit >= 12.8, so an in-release
 # windows-cuda build at or above this already covers Blackwell and makes the
-# older pinned 13.1 fallback unnecessary (cuda-12.4 is below it).
+# pinned 13.1 fallback unnecessary (cuda-12.4 is below it).
 _BLACKWELL_MIN_TOOLKIT = (12, 8)
 _PINNED_BLACKWELL_LLAMA_SHA256 = "31ddb8b42d7ab4a47cab8c48c397519f580ca502df7e73f3ab396eacc16c8e8d"
 _PINNED_BLACKWELL_CUDART_SHA256 = "f96935e7e385e3b2d0189239077c10fe8fd7e95690fea4afec455b1b6c7e3f18"
 
 
 def _cuda_runtime_lines_for_major(major: int) -> list[str]:
-    """Runtime lines a driver of this CUDA major can use, newest major first
-    down to the minimum we ship. A driver runs its own major and any older one
+    """Runtime lines a driver of this CUDA major can use, newest first down to
+    the minimum we ship. A driver runs its own major and any older one
     (backward compatibility)."""
     return [f"cuda{m}" for m in range(major, _MIN_CUDA_MAJOR - 1, -1)]
 
@@ -272,7 +270,7 @@ def _resolve_linux_bundle_profile(bundle_profile: str) -> "dict[str, Any] | None
     """Profile (runtime line + sm coverage) for a linux-x64-cuda-
     bundle. Known majors use their published coverage; an unknown future major
     reuses the newest known major's coverage for the same class as a forward
-    default, with the post-build GPU smoke test as the backstop."""
+    default, with the post-build GPU smoke test as backstop."""
     known = DIRECT_LINUX_BUNDLE_PROFILES.get(bundle_profile)
     if known is not None:
         return known
@@ -325,8 +323,8 @@ class AssetChoice:
     url: str
     source_label: str
     # Paired runtime archive (Windows CUDA cudart bundle). When set,
-    # install_from_archives also downloads it and overlays its DLLs on
-    # top of the main install. See unslothai/unsloth#5106.
+    # install_from_archives also downloads it and overlays its DLLs on top
+    # of the main install. See unslothai/unsloth#5106.
     runtime_name: str | None = None
     runtime_url: str | None = None
     runtime_sha256: str | None = None
@@ -553,14 +551,13 @@ def is_github_api_url(url: str | None) -> bool:
 
 def is_retryable_url_error(exc: Exception) -> bool:
     if isinstance(exc, urllib.error.HTTPError):
-        # GitHub returns 403 (not the standard 429) when the API rate
-        # limit is hit. Anonymous calls share a 60-req/hour bucket per
-        # runner IP, which CI fleets can exhaust trivially. Treat 403
-        # against api.github.com as retryable so we get one or two
-        # backoff cycles before the source-build fallback fires; honour
-        # Retry-After / X-RateLimit-Reset in sleep_backoff for accurate
-        # waits. Real 403s on other hosts (private artefact downloads,
-        # auth failures) stay non-retryable.
+        # GitHub returns 403 (not 429) when the API rate limit is hit.
+        # Anonymous calls share a 60-req/hour bucket per runner IP, which
+        # CI fleets exhaust trivially. Treat 403 against api.github.com as
+        # retryable so we get a backoff cycle or two before the source-build
+        # fallback fires; sleep_backoff honours Retry-After /
+        # X-RateLimit-Reset for accurate waits. Real 403s on other hosts
+        # (private artefact downloads, auth failures) stay non-retryable.
         if exc.code == 403:
             return is_github_api_url(getattr(exc, "url", None))
         return exc.code in RETRYABLE_HTTP_STATUS
@@ -579,9 +576,9 @@ _RATE_LIMIT_WAIT_CAP_SECONDS = 60.0
 def _http_error_retry_delay(exc: Exception) -> float | None:
     """Extract a recommended wait from rate-limit headers on a 403/429.
 
-    Returns None when no header is present or the indicated wait is
-    longer than _RATE_LIMIT_WAIT_CAP_SECONDS (in which case the caller
-    should not block on it -- the source-build fallback is faster).
+    Returns None when no header is present or the wait exceeds
+    _RATE_LIMIT_WAIT_CAP_SECONDS (the caller should not block then -- the
+    source-build fallback is faster).
     """
     if not isinstance(exc, urllib.error.HTTPError):
         return None
@@ -790,12 +787,12 @@ def refs_match(candidate_ref: str | None, requested_ref: str | None) -> bool:
 
 
 def checkout_friendly_ref(ref_kind: str | None, ref: str | None) -> str | None:
-    """Normalize a source ref to a form that ``git clone --branch`` accepts.
+    """Normalize a source ref to a form ``git clone --branch`` accepts.
 
-    Fully qualified branch refs like ``refs/heads/main`` are stripped to
-    ``main``; tag refs like ``refs/tags/b8508`` are stripped to ``b8508``.
-    Pull refs like ``refs/pull/123/head`` are left as-is since they are
-    always fetched explicitly rather than cloned with ``--branch``.
+    Fully qualified branch refs (``refs/heads/main``) are stripped to
+    ``main``; tag refs (``refs/tags/b8508``) to ``b8508``. Pull refs
+    (``refs/pull/123/head``) are left as-is since they are fetched
+    explicitly rather than cloned with ``--branch``.
     """
     if not isinstance(ref, str) or not ref:
         return ref
@@ -845,8 +842,8 @@ def _published_windows_cuda_runtime(
     """Highest cuda-. published upstream that `driver` can run by
     default CUDA compatibility, i.e. (major, minor) <= driver. None if nothing
     qualifies. Gating on the driver (not just the major) keeps a 13.3 build off
-    a driver that only advertises 13.1, where it would otherwise rely on the
-    unguaranteed minor-version-compatibility path."""
+    a 13.1-only driver, where it would rely on the unguaranteed
+    minor-version-compatibility path."""
     if driver is None:
         return None
     best: int | None = None
@@ -1361,8 +1358,8 @@ def direct_linux_release_plan(
     attempts: list[AssetChoice] = []
     if host.has_usable_nvidia:
         # Prefer the cudart major Studio loads at runtime (torch's bundled
-        # libcudart), not the newest detected on disk. Without this a stray
-        # cuda13 runtime outranks the torch cuda12 the binary links against.
+        # libcudart), not the newest on disk. Otherwise a stray cuda13
+        # runtime outranks the torch cuda12 the binary links against.
         torch_preference = detect_torch_cuda_runtime_preference(host)
         selection = linux_cuda_choice_from_release(
             host,
@@ -1375,14 +1372,13 @@ def direct_linux_release_plan(
     if host.has_rocm and not host.has_usable_nvidia:
         # Per-GPU lemonade prebuilts ship the ROCm runtime libs alongside
         # llama.cpp, so they install cleanly even on hosts (e.g. gfx1151
-        # Strix Halo) that the upstream combined-ROCm tarball doesn't cover.
-        # The "ubuntu" label is lemonade's asset naming convention only --
-        # the binary is a manylinux-style glibc build that runs on Arch,
-        # Fedora, openSUSE, etc. as long as the host glibc is recent enough.
-        # Do NOT append the CPU asset for ROCm-only hosts: if lemonade fails
-        # validation we want validate_prebuilt_attempts to raise PrebuiltFallback
-        # so the caller triggers the HIP source build, not silently install a
-        # CPU-only binary.
+        # Strix Halo) the upstream combined-ROCm tarball doesn't cover.
+        # "ubuntu" is lemonade's asset naming convention only -- the binary
+        # is a manylinux-style glibc build that runs on Arch, Fedora,
+        # openSUSE, etc. with a recent-enough glibc. Do NOT append the CPU
+        # asset for ROCm-only hosts: if lemonade fails validation we want
+        # validate_prebuilt_attempts to raise PrebuiltFallback so the caller
+        # triggers the HIP source build, not silently install a CPU binary.
         lemonade_choice = resolve_lemonade_rocm_choice(
             host, "ubuntu", "linux-rocm", llama_tag = requested_tag
         )
@@ -1405,9 +1401,9 @@ def direct_linux_release_plan(
     ):
         approved_checksums = load_approved_release_checksums(repo, bundle.release_tag)
         # Require exact source provenance for branch/pull/commit releases.
-        # Mirrors validated_checksums_for_bundle so incomplete metadata
-        # fails closed instead of degrading to the legacy branch-as-tag
-        # source hydration path that this PR is meant to eliminate.
+        # Mirrors validated_checksums_for_bundle so incomplete metadata fails
+        # closed instead of degrading to the legacy branch-as-tag source
+        # hydration path this PR eliminates.
         if (
             not approved_checksums.source_commit
             or exact_source_archive_hash(approved_checksums) is None
@@ -1455,7 +1451,7 @@ def direct_upstream_release_plan(
                 )
             )
             # Blackwell on a 13.1/13.2 driver: prefer the pinned cuda-13.1 GPU
-            # build over the CPU-only cuda-12.4 the in-release gating leaves.
+            # build over the CPU-only cuda-12.4 left by in-release gating.
             pinned = _pinned_windows_cuda_fallback(host, attempts)
             if pinned is not None:
                 attempts.insert(0, pinned)
@@ -1493,9 +1489,9 @@ def direct_upstream_release_plan(
             )
     elif host.is_windows and host.is_arm64:
         # Upstream ggml-org/llama.cpp ships llama-bNNNN-bin-win-cpu-arm64.zip
-        # (visible in the b9334 release manifest). Without this branch the
-        # selector returned 0 attempts and the installer fell back to a
-        # source build on every Windows ARM64 host.
+        # (in the b9334 release manifest). Without this branch the selector
+        # returned 0 attempts and fell back to a source build on every
+        # Windows ARM64 host.
         cpu_asset = f"llama-{release_tag}-bin-win-cpu-arm64.zip"
         cpu_url = assets.get(cpu_asset)
         if cpu_url:
@@ -1553,10 +1549,10 @@ def direct_upstream_release_plan(
             )
     elif host.is_linux and host.is_arm64 and not host.has_usable_nvidia:
         # Upstream ggml-org/llama.cpp ships llama-bNNNN-bin-ubuntu-arm64.tar.gz
-        # (visible in the b9334 release manifest). Without this branch the
-        # selector returned 0 attempts and the installer fell back to a
-        # source build on every Linux ARM64 host (DGX Spark, Ampere
-        # Altra, GitHub-hosted ubuntu-24.04-arm runners, etc.).
+        # (in the b9334 release manifest). Without this branch the selector
+        # returned 0 attempts and fell back to a source build on every Linux
+        # ARM64 host (DGX Spark, Ampere Altra, GitHub ubuntu-24.04-arm
+        # runners, etc.).
         asset_name = f"llama-{release_tag}-bin-ubuntu-arm64.tar.gz"
         asset_url = assets.get(asset_name)
         if asset_url:
@@ -1586,9 +1582,9 @@ def direct_upstream_release_plan(
 
 
 def pinned_macos_release_tag(host: HostInfo, repo: str) -> str | None:
-    """Pin b9415 (the last upstream macOS build that loads below macOS 26) for a
-    known pre-26 host on ggml-org upstream; return None to keep latest selection.
-    The unslothai/llama.cpp fork ships its own prebuilts (arm64 minos 14, x64
+    """Pin b9415 (last upstream macOS build that loads below macOS 26) for a
+    known pre-26 host on ggml-org upstream; None keeps latest selection. The
+    unslothai/llama.cpp fork ships its own prebuilts (arm64 minos 14, x64
     minos 13.3) and needs no pin, so this is a no-op there and for macOS 26+,
     unknown version, non-macOS."""
     if repo != UPSTREAM_REPO:
@@ -1614,9 +1610,9 @@ def resolve_simple_install_release_plans(
     repo = published_repo or DEFAULT_PUBLISHED_REPO
     requested_tag = normalized_requested_llama_tag(llama_tag)
     # The unslothai/llama.cpp fork ships only linux-x64 bundles. An arm64 Linux
-    # host with a GPU (GH200/GB200/DGX Spark) routes here; it must not install an
-    # x64 binary, so fall back to a source build that targets the GPU rather than
-    # selecting the wrong arch (or silently dropping to a CPU arm64 build).
+    # host with a GPU (GH200/GB200/DGX Spark) routes here; it must not install
+    # an x64 binary, so fall back to a GPU-targeting source build rather than
+    # the wrong arch (or silently dropping to a CPU arm64 build).
     if host.is_linux and not host.is_x86_64 and repo == DEFAULT_PUBLISHED_REPO:
         raise PrebuiltFallback(
             f"{repo} ships only linux-x64 prebuilts; "
@@ -1625,7 +1621,7 @@ def resolve_simple_install_release_plans(
     allow_older_release_fallback = requested_tag == "latest" and not published_release_tag
     # macOS: pin the last upstream build that loads on a pre-26 host instead of
     # fetching the latest (macOS 26 only) build and walking back release by
-    # release. No-op on macOS 26+, unknown version, non-macOS, and the fork.
+    # release. No-op on macOS 26+, unknown version, non-macOS, the fork.
     if allow_older_release_fallback:
         pinned_macos = pinned_macos_release_tag(host, repo)
         if pinned_macos is not None:
@@ -1940,8 +1936,8 @@ def parse_published_release_bundle(
     if not manifest_url:
         return None
 
-    # Mixed repos are filtered by an explicit release-side manifest rather than
-    # by release tag or asset filename conventions.
+    # Mixed repos are filtered by an explicit release-side manifest, not by
+    # release tag or asset filename conventions.
     manifest_bytes = download_bytes(
         manifest_url,
         timeout = 30,
@@ -2393,9 +2389,9 @@ def validated_checksums_for_bundle(
             raise PrebuiltFallback(
                 "published manifest checksum did not match the approved checksum asset"
             )
-    # Accept bundles that carry only an exact-commit source archive
-    # (e.g. llama.cpp-source-commit-.tar.gz) without requiring the
-    # legacy llama.cpp-source-.tar.gz entry.
+    # Accept bundles carrying only an exact-commit source archive
+    # (llama.cpp-source-commit-.tar.gz) without requiring the legacy
+    # llama.cpp-source-.tar.gz entry.
     if exact_source_archive_hash(checksums) is None:
         require_approved_source_hash(checksums, bundle.upstream_tag)
     return checksums
@@ -2531,23 +2527,22 @@ def resolve_requested_llama_tag(
 
     Resolution order:
       1. Concrete tag (e.g. "b8508") -- returned as-is.
-      2. "latest" with published_repo -- resolve the latest usable Unsloth
-         published release bundle and return its upstream_tag. This is the
-         preferred version that matches the published prebuilt metadata.
-      3. "latest" without published_repo or if (2) fails -- query the upstream
-         ggml-org/llama.cpp repo. This may return a newer, untested tag.
+      2. "latest" with published_repo -- the latest usable Unsloth published
+         bundle's upstream_tag (matches the published prebuilt metadata).
+      3. "latest" without published_repo, or if (2) fails -- query upstream
+         ggml-org/llama.cpp. May return a newer, untested tag.
 
-    The Unsloth repo is preferred because its releases are pinned to specific
-    upstream tags that have been validated with Unsloth Studio. Using the
-    upstream bleeding-edge tag risks API/ABI incompatibilities.
+    The Unsloth repo is preferred because its releases are pinned to upstream
+    tags validated with Unsloth Studio; the upstream bleeding-edge tag risks
+    API/ABI incompatibilities.
     """
     normalized_requested = normalized_requested_llama_tag(requested_tag)
     if normalized_requested != "latest":
         return normalized_requested
     # Prefer the Unsloth release repo tag (tested/approved) over bleeding-edge
-    # upstream. For example, unslothai/llama.cpp may publish b8508 while
-    # ggml-org/llama.cpp latest is b8514. The source-build fallback should
-    # compile the same version the prebuilt path would have installed.
+    # upstream. E.g. unslothai/llama.cpp may publish b8508 while ggml-org
+    # latest is b8514. The source-build fallback should compile the same
+    # version the prebuilt path would have installed.
     if published_repo:
         try:
             return resolve_published_release(
@@ -2557,7 +2552,7 @@ def resolve_requested_llama_tag(
             ).bundle.upstream_tag
         except Exception:
             pass
-    # Fall back to upstream ggml-org latest release tag
+    # Fall back to the upstream ggml-org latest release tag
     return latest_upstream_release_tag()
 
 
@@ -2704,38 +2699,38 @@ def _pick_rocm_gfx_target(out: str) -> str | None:
     A bare first-match picked the wrong device on mixed APU + dGPU hosts
     (e.g. Strix Halo gfx1151 + discrete RX 7900 gfx1100). Respect
     HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES so the
-    asset matches what HIP actually runs on. Falls back to the first GPU when
-    no env var is set.
+    asset matches what HIP runs on; falls back to the first GPU with no env
+    var set.
 
     rocminfo / hipinfo print the same gfx token multiple times per GPU (Name,
-    ISA, marketing-name). We first try to split the output on per-GPU section
-    headers (rocminfo: "Agent N" blocks, hipinfo: "device#N" entries) and take
-    exactly one gfx token per section. This gives the correct per-GPU list even
-    on same-arch multi-GPU hosts (e.g. two RX 7900 XTX cards) where global
-    dict.fromkeys dedup would collapse both cards to a single entry and make
-    HIP_VISIBLE_DEVICES=1 point out of range.
+    ISA, marketing-name). We first split the output on per-GPU section headers
+    (rocminfo: "Agent N" blocks, hipinfo: "device#N" entries) and take exactly
+    one gfx token per section -- this gives the correct per-GPU list even on
+    same-arch multi-GPU hosts (e.g. two RX 7900 XTX) where global dict.fromkeys
+    dedup would collapse both to one entry and make HIP_VISIBLE_DEVICES=1 point
+    out of range.
 
     Falls back to insertion-order dedup when the output has no recognisable
     section markers (flat gfx-string inputs, unit-test stubs, etc.).
 
     Empty / "-1" env values mean no AMD GPU is visible to HIP: return None.
     """
-    # Try to build a per-GPU token list by splitting on section boundaries.
-    # rocminfo sections are introduced by "Agent N" lines (optionally between
-    # rows of asterisks). hipinfo sections start with "device#N".
+    # Build a per-GPU token list by splitting on section boundaries. rocminfo
+    # sections start with "Agent N" lines (optionally between rows of
+    # asterisks); hipinfo sections with "device#N".
     _sections = re.split(
         r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bdevice\s*#\s*\d+\b",
         out,
     )
     if len(_sections) > 1:
-        # Section-based: one gfx token per GPU section preserves physical order.
+        # One gfx token per GPU section preserves physical order.
         _tokens: list[str] = []
         for _sec in _sections[1:]:
             _m = re.search(r"gfx[1-9][0-9a-z]{2,3}", _sec.lower())
             if _m:
                 _tokens.append(_m.group(0))
     else:
-        # Fallback: insertion-order dedup (handles flat strings / unknown formats).
+        # Fallback: insertion-order dedup (flat strings / unknown formats).
         _raw = re.findall(r"gfx[1-9][0-9a-z]{2,3}", out.lower())
         _tokens = list(dict.fromkeys(_raw))
 
@@ -2751,7 +2746,7 @@ def _pick_rocm_gfx_target(out: str) -> str | None:
             break
     if _vis_raw is not None:
         _vis = _vis_raw.strip()
-        # Empty or "-1" means "no AMD GPU visible" (matches the rest of Studio).
+        # Empty or "-1" means "no AMD GPU visible" (matches the rest of Studio)
         if _vis == "" or _vis == "-1":
             return None
         _first = _vis.split(",")[0].strip()
@@ -2783,11 +2778,10 @@ def detect_host() -> HostInfo:
     has_physical_nvidia = False
     has_usable_nvidia = False
     if nvidia_smi:
-        # Require `nvidia-smi -L` to actually list a GPU before treating the
-        # host as NVIDIA. The banner text "NVIDIA-SMI ..." is printed even
-        # when the command fails to communicate with the driver (e.g. stale
-        # container leftovers), which would otherwise misclassify an AMD
-        # ROCm host as NVIDIA and short-circuit the ROCm path.
+        # Require `nvidia-smi -L` to list a GPU before treating the host as
+        # NVIDIA. The "NVIDIA-SMI ..." banner prints even when the command
+        # can't reach the driver (e.g. stale container leftovers), which
+        # would misclassify an AMD ROCm host as NVIDIA and skip the ROCm path.
         try:
             listing = run_capture([nvidia_smi, "-L"], timeout = 20)
             gpu_lines = [line for line in listing.stdout.splitlines() if line.startswith("GPU ")]
@@ -2800,9 +2794,9 @@ def detect_host() -> HostInfo:
         try:
             result = run_capture([nvidia_smi], timeout = 20)
             merged = "\n".join(part for part in (result.stdout, result.stderr) if part)
-            # Newer NVIDIA drivers (e.g. 610.x on Windows) print
-            # "CUDA UMD Version: X.Y" instead of the legacy
-            # "CUDA Version: X.Y"; accept both spellings.
+            # Newer NVIDIA drivers (e.g. 610.x on Windows) print "CUDA UMD
+            # Version: X.Y" instead of the legacy "CUDA Version: X.Y"; accept
+            # both spellings.
             cuda_match = re.search(
                 r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)",
                 merged,
@@ -2845,10 +2839,10 @@ def detect_host() -> HostInfo:
 
             if visible_gpu_rows:
                 has_usable_nvidia = True
-                # Older nvidia-smi versions (pre -L support) hit the
-                # except in the first try block but still succeed here,
-                # leaving has_physical_nvidia unset. Mirror the -L path
-                # so downstream diagnostics on line ~4390 still run.
+                # Older nvidia-smi (pre -L support) hits the except in the
+                # first try block but still succeeds here, leaving
+                # has_physical_nvidia unset. Mirror the -L path so downstream
+                # diagnostics on line ~4390 still run.
                 if not has_physical_nvidia:
                     has_physical_nvidia = True
             elif visible_device_tokens == []:
@@ -2870,10 +2864,10 @@ def detect_host() -> HostInfo:
     rocm_gfx_target: str | None = None
     if is_linux:
         for _cmd, _check in (
-            # rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
-            # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
-            # "gfx11-generic" or "gfx9-4-generic" which only have 1-2 digits before
-            # the dash and must not be treated as a real GPU.
+            # rocminfo: a real gfx GPU id (3-4 chars, nonzero first digit).
+            # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines
+            # ("gfx11-generic", "gfx9-4-generic") with only 1-2 digits before
+            # the dash, which must not be treated as a real GPU.
             (
                 ["rocminfo"],
                 lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
@@ -2893,14 +2887,13 @@ def detect_host() -> HostInfo:
                     rocm_gfx_target = _pick_rocm_gfx_target(_result.stdout)
                     break
     elif is_windows:
-        # Windows: prefer active probes that validate GPU presence.
-        # hipinfo / amd-smi are often NOT on PATH -- the HIP SDK installer
-        # sets HIP_PATH / ROCM_PATH but does not always add the bin dir to
-        # the system PATH.  Mirror setup.ps1's fallback: check the env-var
-        # bin dirs before giving up so that `has_rocm` is not silently False
-        # on machines where the PATH is not yet updated.
+        # Windows: prefer active probes that validate GPU presence. hipinfo /
+        # amd-smi are often NOT on PATH -- the HIP SDK installer sets HIP_PATH
+        # / ROCM_PATH but doesn't always add the bin dir to PATH. Mirror
+        # setup.ps1's fallback: check the env-var bin dirs before giving up so
+        # `has_rocm` isn't silently False when PATH isn't updated yet.
         def _resolve_exe(name: str) -> str | None:
-            """Return full path to `name`, checking PATH then HIP_PATH/ROCM_PATH bin."""
+            """Full path to `name`, checking PATH then HIP_PATH/ROCM_PATH bin."""
             found = shutil.which(name)
             if found:
                 return found
@@ -2929,8 +2922,8 @@ def detect_host() -> HostInfo:
                     # hipinfo reports "gcnArchName: gfx1100" -- extract if present
                     rocm_gfx_target = _pick_rocm_gfx_target(_result.stdout)
                     break
-        # Note: amdhip64.dll presence alone is NOT treated as GPU evidence
-        # since the HIP SDK can be installed without an AMD GPU.
+        # Note: amdhip64.dll presence alone is NOT GPU evidence -- the HIP SDK
+        # can be installed without an AMD GPU.
 
     return HostInfo(
         system = system,
@@ -2955,7 +2948,7 @@ def detect_host() -> HostInfo:
 def _normalize_forwarded_gfx(value: str | None) -> str | None:
     """Extract a single gfx token from a forwarded --rocm-gfx / env value.
     setup.sh/setup.ps1 already picked the active GPU, so take the token as-is
-    without re-applying visible-device selection. Ignore anything malformed."""
+    without re-applying visible-device selection. Ignore malformed input."""
     if not value:
         return None
     m = re.search(r"gfx[1-9][0-9a-z]{2,3}", value.lower())
@@ -2971,8 +2964,8 @@ def _apply_host_overrides(
 ) -> HostInfo:
     """Fold setup.sh/setup.ps1's forwarded detection into the host profile.
     A forwarded gfx (--rocm-gfx or UNSLOTH_ROCM_GFX_ARCH) is authoritative and
-    implies ROCm: the installer's own hipinfo/amd-smi probe can miss the arch on
-    amd-smi-only hosts or when setup inferred it from the GPU name, leaving
+    implies ROCm: the installer's own hipinfo/amd-smi probe can miss the arch
+    on amd-smi-only hosts or when setup inferred it from the GPU name, leaving
     rocm_gfx_target None and no lemonade prebuilt selected. force_cpu is the
     opposite explicit signal (arm64 Linux GPU host whose source build failed):
     drop GPU attributes so the CPU prebuilt for this OS/arch is selected."""
@@ -3014,7 +3007,7 @@ def compatible_linux_runtime_lines(host: HostInfo) -> list[str]:
 
 def windows_runtime_line_info() -> dict[str, tuple[str, ...]]:
     # Generated per CUDA major (newest first) so a new toolkit is detected
-    # without a code change while the cudart64_.dll naming holds.
+    # without code changes while the cudart64_.dll naming holds.
     return {
         f"cuda{m}": (
             f"cudart64_{m}*.dll",
@@ -3041,7 +3034,7 @@ def compatible_windows_runtime_lines(host: HostInfo) -> list[str]:
     if not host.driver_cuda_version:
         return []
     major, minor = host.driver_cuda_version
-    # cuda12 prebuilts need a 12.4+ driver; cuda13+ any minor of the major.
+    # cuda12 prebuilts need a 12.4+ driver; cuda13+ any minor.
     if major < _MIN_CUDA_MAJOR or (major == _MIN_CUDA_MAJOR and minor < 4):
         return []
     return _cuda_runtime_lines_for_major(major)
@@ -3181,8 +3174,8 @@ def windows_cuda_attempts(
     runtime_order.extend(
         runtime_line for runtime_line in normal_runtime_lines if runtime_line not in runtime_order
     )
-    # Keep every driver-compatible line reachable as a fallback, so a line gated
-    # out by the driver version still drops to an older major (cuda13 -> cuda12).
+    # Keep every driver-compatible line reachable as a fallback, so a line
+    # gated out by driver version still drops to an older major (cuda13->cuda12).
     runtime_order.extend(
         runtime_line
         for runtime_line in compatible_runtime_lines
@@ -3201,7 +3194,7 @@ def windows_cuda_attempts(
     for runtime_line in runtime_order:
         major = int(runtime_line.removeprefix("cuda"))
         # Track whatever minor llama.cpp actually ships for this major
-        # (cuda13 -> 13.1, 13.3, ...). Skip the line when the release has no
+        # (cuda13 -> 13.1, 13.3, ...). Skip the line when the release lacks a
         # matching asset instead of guessing a now-missing name.
         runtime = _published_windows_cuda_runtime(upstream_assets, major, host.driver_cuda_version)
         if runtime is None:
@@ -3222,10 +3215,10 @@ def windows_cuda_attempts(
                 + ",".join(windows_cuda_upstream_asset_names(llama_tag, runtime))
             )
             continue
-        # Pair the cudart bundle when upstream ships it. Without this
-        # the binary needs a system CUDA toolkit on PATH at runtime
-        # (#5106). Only pair when the selected main archive is the
-        # binary archive, not the cudart archive itself.
+        # Pair the cudart bundle when upstream ships it; otherwise the binary
+        # needs a system CUDA toolkit on PATH at runtime (#5106). Only pair
+        # when the selected main archive is the binary archive, not the cudart
+        # archive itself.
         runtime_archive_name: str | None = None
         runtime_archive_url: str | None = None
         if selected_name.startswith("llama-"):
@@ -3264,8 +3257,8 @@ def windows_cuda_attempts(
 
 
 def _windows_cuda_attempt_covers_blackwell(attempt: AssetChoice) -> bool:
-    """True if an in-release windows-cuda attempt is built with a toolkit that
-    covers Blackwell sm_120 (>= 12.8), read from its asset name's CUDA minor."""
+    """True if an in-release windows-cuda attempt's toolkit covers Blackwell
+    sm_120 (>= 12.8), read from its asset name's CUDA minor."""
     if attempt.install_kind != "windows-cuda":
         return False
     m = re.search(r"-bin-win-cuda-(\d+)\.(\d+)-x64\.zip$", attempt.name)
@@ -3276,16 +3269,16 @@ def _pinned_windows_cuda_fallback(
     host: HostInfo, existing_cuda_attempts: list[AssetChoice]
 ) -> AssetChoice | None:
     """Pinned GPU fallback for a Blackwell host the in-release build gates off.
-    Upstream stopped publishing a sub-13.3 Windows cuda13 build after b9360, and
-    cuda-12.4 cannot offload sm_120, so a 13.1/13.2 driver would land on CPU.
-    b9360's cuda-13.1 build is immutable and runs on those drivers. Returns None
-    (dormant) whenever the in-release selection already offers a Blackwell-capable
-    build (toolkit >= 12.8, e.g. a runnable cuda13/cuda14), so it self-disables
-    once upstream ships a driver-runnable build again.
+    Upstream stopped publishing a sub-13.3 Windows cuda13 build after b9360,
+    and cuda-12.4 cannot offload sm_120, so a 13.1/13.2 driver would land on
+    CPU. b9360's cuda-13.1 build is immutable and runs on those drivers.
+    Returns None (dormant) whenever the in-release selection already offers a
+    Blackwell-capable build (toolkit >= 12.8, e.g. a runnable cuda13/cuda14),
+    so it self-disables once upstream ships a driver-runnable build again.
 
-    The b9360 binary reuses the current release's source tree and convert scripts
-    and is recorded via binary_release_tag, the same binary/source split used for
-    the lemonade prebuilt."""
+    The b9360 binary reuses the current release's source tree and convert
+    scripts and is recorded via binary_release_tag, the same binary/source
+    split used for the lemonade prebuilt."""
     if not (host.is_windows and host.is_x86_64 and host.has_usable_nvidia):
         return None
     driver = host.driver_cuda_version
@@ -3327,8 +3320,8 @@ def _pinned_windows_cuda_fallback(
 def _augment_checksums_with_pin(
     checksums: ApprovedReleaseChecksums, pin: AssetChoice
 ) -> ApprovedReleaseChecksums:
-    """Add the pin's own verified hashes to a copy of the approved checksums so
-    apply_approved_hashes keeps it on the published path (b9360 is not in the
+    """Add the pin's verified hashes to a copy of the approved checksums so
+    apply_approved_hashes keeps it on the published path (b9360 isn't in the
     release manifest)."""
     artifacts = dict(checksums.artifacts)
     if pin.expected_sha256:
@@ -3352,7 +3345,7 @@ def _with_pinned_windows_cuda_fallback(
     host: HostInfo, attempts: list[AssetChoice], checksums: ApprovedReleaseChecksums
 ) -> tuple[list[AssetChoice], ApprovedReleaseChecksums]:
     """Insert the Blackwell pin ahead of the Windows CUDA attempts and keep it
-    through apply_approved_hashes, or return the inputs unchanged when dormant.
+    through apply_approved_hashes, or return inputs unchanged when dormant.
     Gives the published install path the same GPU fallback as the simple path."""
     pin = _pinned_windows_cuda_fallback(host, attempts)
     if pin is None:
@@ -3369,7 +3362,7 @@ def published_windows_cuda_attempts(
     selection_log = list(release.selection_log) + list(selection_preamble)
     # Seed the runtime-line ordering from the real published windows-cuda minors
     # (their names encode the minor), so a future CUDA major published here is
-    # ordered too instead of a hardcoded cuda12/cuda13 pair. Keys mirror the
+    # ordered too rather than a hardcoded cuda12/cuda13 pair. Keys mirror the
     # upstream naming so windows_cuda_attempts can match them; fall back to the
     # long-standing default when the release lists no windows-cuda asset.
     published_minors: list[str] = []
@@ -3414,8 +3407,8 @@ def published_windows_cuda_attempts(
             if not asset_url:
                 continue
             am = re.search(r"-bin-win-cuda-(\d+)\.(\d+)-x64\.zip$", artifact.asset_name)
-            # Gate the real published minor against the driver, so a published
-            # windows-cuda artifact can never bypass the driver-version gate.
+            # Gate the published minor against the driver so it can never
+            # bypass the driver-version gate.
             if (
                 am is not None
                 and host.driver_cuda_version is not None
@@ -3516,9 +3509,9 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
     """Return (major, minor) of the installed ROCm runtime, or None.
 
     Best-effort read from /opt/rocm/.info/version, amd-smi version, and
-    hipconfig --version. Used to pick a compatible upstream llama.cpp
-    ROCm prebuilt rather than always taking the numerically newest one
-    (which can be newer than the host runtime).
+    hipconfig --version. Used to pick a compatible upstream llama.cpp ROCm
+    prebuilt rather than the numerically newest one (which can be newer than
+    the host runtime).
     """
     rocm_root = os.environ.get("ROCM_PATH") or "/opt/rocm"
     for path in (
@@ -3528,9 +3521,9 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
         try:
             with open(path) as fh:
                 parts = fh.read().strip().split("-")[0].split(".")
-            # Explicit length guard avoids relying on the broad except
-            # below to swallow IndexError when the version file contains
-            # a single component (e.g. "6\n" on a partial install).
+            # Explicit length guard so we don't rely on the broad except
+            # below to swallow IndexError when the version file has a single
+            # component (e.g. "6\n" on a partial install).
             if len(parts) >= 2:
                 return int(parts[0]), int(parts[1])
         except Exception:
@@ -3571,8 +3564,8 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
 
     # Distro package-manager fallbacks. Mirrors install.sh::get_torch_index_url
     # and _detect_rocm_version() in install_python_stack.py so package-managed
-    # ROCm hosts without /opt/rocm/.info/version still report a usable version
-    # and the <= host version filter in resolve_upstream_asset_choice picks
+    # ROCm hosts without /opt/rocm/.info/version still report a usable version,
+    # letting the <= host version filter in resolve_upstream_asset_choice pick
     # the correct upstream prebuilt instead of the newest-regardless fallback.
     for _cmd in (
         ["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
@@ -3594,7 +3587,7 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
         if _result.returncode != 0 or not _result.stdout.strip():
             continue
         _raw = _result.stdout.strip()
-        # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
+        # dpkg can prepend an epoch ("1:6.3.0-1"); strip it first.
         _raw = re.sub(r"^\d+:", "", _raw)
         _m = re.match(r"(\d+)[.-](\d+)", _raw)
         if _m:
@@ -3603,7 +3596,7 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
 
 
 # Map detected gfx IDs to lemonade-sdk asset family suffixes.
-# More-specific prefixes must come before shorter ones (e.g. gfx1151 before gfx110).
+# More-specific prefixes must precede shorter ones (e.g. gfx1151 before gfx110).
 _LEMONADE_GFX_FAMILIES: list[tuple[str, str]] = [
     ("gfx1151", "gfx1151"),
     ("gfx1150", "gfx1150"),
@@ -3627,9 +3620,8 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
     Accepts:
       https://github.com/{expected_repo}/releases/download/...
       https://objects.githubusercontent.com/...   (GitHub's release CDN)
-    Anything else (including http://, raw.githubusercontent.com, gist, etc.)
-    is rejected so a malicious API response cannot redirect downloads to an
-    attacker-chosen host.
+    Anything else (http://, raw.githubusercontent.com, gist, etc.) is rejected
+    so a malicious API response can't redirect downloads to an attacker host.
     """
     if not isinstance(url, str) or not url:
         return False
@@ -3642,8 +3634,8 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
     host = (parsed.netloc or "").lower()
     if host == "objects.githubusercontent.com":
         # GitHub's release CDN. Restrict to release-asset paths so a tampered
-        # API response pointing at an arbitrary CDN object is still rejected.
-        # Real release asset URLs carry the "/github-production-release-asset-"
+        # API response pointing at an arbitrary CDN object is rejected. Real
+        # release asset URLs carry the "/github-production-release-asset-"
         # prefix; gist / raw / avatar CDN paths do not.
         return parsed.path.startswith("/github-production-release-asset-")
     if host == "github.com":
@@ -3655,12 +3647,12 @@ def _is_trusted_github_release_url(url: str, expected_repo: str) -> bool:
 def _fetch_lemonade_release_cached(api_url: str, llama_tag: str) -> "dict | None":
     """Cached wrapper around fetch_json for lemonade release lookups.
 
-    resolve_lemonade_rocm_choice() is called twice per install (once from the
-    direct planner, once from resolve_upstream_asset_choice) with identical
-    arguments. Without memoisation, each install hits api.github.com twice,
-    doubling the rate-limit failure surface on busy CI runners. Cache is
-    process-scoped; tests that need to vary fetch_json's return value across
-    invocations should call cache_clear().
+    resolve_lemonade_rocm_choice() is called twice per install (direct planner
+    + resolve_upstream_asset_choice) with identical arguments. Without
+    memoisation each install hits api.github.com twice, doubling the
+    rate-limit failure surface on busy CI runners. Cache is process-scoped;
+    tests that vary fetch_json's return value across calls should call
+    cache_clear().
     """
     try:
         return fetch_json(api_url)
@@ -3686,23 +3678,21 @@ def resolve_lemonade_rocm_choice(
 
     os_prefix:   lemonade's asset filename label, NOT a host-distro filter.
                  Pass "ubuntu" for any Linux host (Arch, Fedora, openSUSE,
-                 Debian, ...) -- lemonade only publishes one Linux variant
-                 and it is a manylinux-style glibc build that runs on any
-                 distro with a recent-enough glibc. Pass "windows" for
-                 Windows hosts.
+                 Debian, ...) -- lemonade publishes one Linux variant, a
+                 manylinux-style glibc build that runs on any distro with a
+                 recent-enough glibc. Pass "windows" for Windows hosts.
     install_kind: "linux-rocm" or "windows-hip"
     llama_tag:   the requested upstream llama.cpp tag ("latest" or a pinned
-                 release like "b1260"). When pinned, the resolver fetches
-                 the matching lemonade release. When the pinned tag is not
-                 published by lemonade we skip silently (and the caller
-                 falls through to upstream) rather than drift to whatever
-                 lemonade ships as latest.
+                 release like "b1260"). When pinned, fetch the matching
+                 lemonade release; if lemonade hasn't published that tag, skip
+                 silently (caller falls through to upstream) rather than drift
+                 to whatever lemonade ships as latest.
     """
     if not host.rocm_gfx_target:
         return None
     # Opt-out for users who want the upstream HIP build path only -- lemonade
-    # binaries are downloaded without entries in the approved-hash manifest, so
-    # the integrity gate is functional validation only.
+    # binaries lack approved-hash manifest entries, so their integrity gate is
+    # functional validation only.
     if os.environ.get("UNSLOTH_DISABLE_LEMONADE_ROCM", "").strip().lower() in (
         "1",
         "true",
@@ -3735,7 +3725,7 @@ def resolve_lemonade_rocm_choice(
         return None
     asset_url = assets[asset_name]
     if not asset_url:
-        # release_asset_map defaults to "" when an asset row is missing
+        # release_asset_map defaults to "" when an asset row lacks
         # browser_download_url; skip cleanly instead of letting
         # download_file("") raise a less obvious error downstream.
         log(
@@ -3744,9 +3734,9 @@ def resolve_lemonade_rocm_choice(
         )
         return None
     # Defence in depth: lemonade browser_download_url should be on github.com
-    # or githubusercontent.com. A compromised GitHub API response that
-    # redirects to an attacker-chosen host would otherwise be honoured
-    # silently (lemonade assets are not in the approved-hash manifest).
+    # or githubusercontent.com. A compromised GitHub API response redirecting
+    # to an attacker host would otherwise be honoured silently (lemonade
+    # assets are not in the approved-hash manifest).
     if not _is_trusted_github_release_url(asset_url, LEMONADE_ROCM_REPO):
         log(
             f"{LEMONADE_ROCM_REPO}@{release_tag} asset {asset_name!r} points "
@@ -3754,9 +3744,9 @@ def resolve_lemonade_rocm_choice(
             "lemonade prebuilt"
         )
         return None
-    # Note: lemonade tags Linux assets with "ubuntu" but the binary is a
-    # generic glibc build that runs on any distro (Arch, Fedora, ...), so
-    # this attempt is selected for all Linux ROCm hosts, not just Ubuntu.
+    # Note: lemonade tags Linux assets "ubuntu" but the binary is a generic
+    # glibc build that runs on any distro (Arch, Fedora, ...), so this attempt
+    # is selected for all Linux ROCm hosts, not just Ubuntu.
     log(
         f"AMD GPU {host.rocm_gfx_target!r} ({gfx_family}) -- "
         f"trying lemonade-sdk ROCm prebuilt {asset_name} "
@@ -3782,28 +3772,27 @@ def resolve_lemonade_rocm_choice(
 def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice:
     upstream_assets = github_release_assets(UPSTREAM_REPO, llama_tag)
     if host.is_linux and host.is_x86_64:
-        # AMD ROCm: try upstream ROCm prebuilt first, then fall back to source build.
-        # Source build (via setup.sh) compiles with -DGGML_HIP=ON and auto-detects
-        # the exact GPU target via rocminfo, which is more reliable for consumer
-        # GPUs (e.g. gfx1151) that may not be in the prebuilt.
+        # AMD ROCm: try upstream ROCm prebuilt first, then a source build. The
+        # source build (via setup.sh) compiles with -DGGML_HIP=ON and
+        # auto-detects the exact GPU target via rocminfo, more reliable for
+        # consumer GPUs (e.g. gfx1151) that may not be in the prebuilt.
         if host.has_rocm and not host.has_usable_nvidia:
-            # Try lemonade-sdk per-GPU prebuilt first: these are built against
-            # specific gfx targets and bundle all required ROCm runtime libs.
+            # Try lemonade-sdk per-GPU prebuilt first: built against specific
+            # gfx targets and bundle all required ROCm runtime libs.
             lemonade_choice = resolve_lemonade_rocm_choice(
                 host, "ubuntu", "linux-rocm", llama_tag = llama_tag
             )
             if lemonade_choice is not None:
                 return lemonade_choice
 
-            # Fall back to upstream combined ROCm tarball.
-            # Scan upstream assets for any rocm- prebuilt. When the
-            # host ROCm runtime version is known, pick the newest candidate
-            # whose major.minor is <= host version -- otherwise a ROCm 6.4
-            # host would download the rocm-7.2 tarball, fail preflight, and
-            # fall back to a source build even though a compatible 6.4
-            # prebuilt exists. If no compatible candidate matches (e.g. host
-            # runtime is older than every published prebuilt), fall back to
-            # the numerically newest so we at least try something.
+            # Fall back to the upstream combined ROCm tarball. Scan for any
+            # rocm- prebuilt; when the host ROCm version is known,
+            # pick the newest candidate whose major.minor is <= host version
+            # -- otherwise a ROCm 6.4 host downloads the rocm-7.2 tarball,
+            # fails preflight, and source-builds even though a 6.4 prebuilt
+            # exists. If none is compatible (host older than every published
+            # prebuilt), fall back to the numerically newest so we try
+            # something.
             _rocm_pattern = re.compile(
                 rf"llama-{re.escape(llama_tag)}-bin-ubuntu-rocm-([0-9]+(?:\.[0-9]+)*)-x64\.tar\.gz"
             )
@@ -3822,10 +3811,10 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
                     item for item in rocm_candidates if item[0][:2] <= _host_rocm_version
                 ]
             if rocm_candidates and not _compatible:
-                # Fall back to the newest candidate so a source build is
-                # not forced when the host runtime is older than every
-                # published prebuilt: preflight will still catch a true
-                # incompatibility and trigger a fallback.
+                # Fall back to the newest candidate so we don't force a source
+                # build when the host runtime is older than every published
+                # prebuilt: preflight still catches a true incompatibility and
+                # triggers a fallback.
                 _compatible = rocm_candidates[:1]
             if _compatible:
                 rocm_name = _compatible[0][1]
@@ -3848,7 +3837,7 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice
                     source_label = "upstream",
                     install_kind = "linux-rocm",
                 )
-            # No ROCm prebuilt available -- fall back to source build
+            # No ROCm prebuilt available -- fall back to a source build
             raise PrebuiltFallback(
                 "AMD ROCm detected but no upstream ROCm prebuilt found; "
                 "falling back to source build with HIP support"
@@ -3978,12 +3967,11 @@ def resolve_release_asset_choice(
 
     published_choice: AssetChoice | None = None
     if host.is_windows and host.is_x86_64:
-        # AMD Windows hosts should prefer a hash-approved published
-        # Windows HIP bundle when one exists, but otherwise fall through
-        # to resolve_asset_choice() so the upstream HIP prebuilt is
-        # tried before the CPU fallback. Hard-pinning the published
-        # windows-cpu bundle here would make the new HIP path
-        # unreachable.
+        # AMD Windows hosts prefer a hash-approved published Windows HIP
+        # bundle when one exists, otherwise fall through to
+        # resolve_asset_choice() so the upstream HIP prebuilt is tried before
+        # the CPU fallback. Hard-pinning the published windows-cpu bundle here
+        # would make the HIP path unreachable.
         if host.has_rocm:
             published_choice = published_asset_choice_for_kind(release, "windows-hip")
         else:
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 5ff8e8572b..0cff45daef 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -5,9 +5,8 @@
 
 """Cross-platform Python dependency installer for Unsloth Studio.
 
-Called by both setup.sh (Linux / WSL) and setup.ps1 (Windows) after the
-virtual environment is already activated.  Expects `pip` and `python` on
-PATH to point at the venv.
+Called by setup.sh (Linux/WSL) and setup.ps1 (Windows) after the venv is
+activated. Expects `pip` and `python` on PATH to point at the venv.
 """
 
 from __future__ import annotations
@@ -42,11 +41,10 @@ IS_MAC_INTEL = IS_MACOS and platform.machine() == "x86_64"
 IS_MAC_ARM = IS_MACOS and platform.machine() == "arm64"
 IS_LINUX = sys.platform.startswith("linux")
 # torchcodec ships wheels only for manylinux_2_28_x86_64,
-# macosx_12_0_arm64, and win_amd64 (visible in the 0.10.0 PyPI page).
-# Trying to install it on any other host fails the whole
-# extras-no-deps step. `unsloth studio update` does not have a
-# --no-torch flag, so on these hosts the audio extras must be
-# filtered out independent of the NO_TORCH env var.
+# macosx_12_0_arm64, and win_amd64 (per the 0.10.0 PyPI page). Installing
+# on any other host fails the whole extras-no-deps step. `unsloth studio
+# update` has no --no-torch flag, so on these hosts the audio extras must
+# be filtered out regardless of the NO_TORCH env var.
 PLATFORM_LACKS_TORCHCODEC_WHEEL = (
     (IS_LINUX and platform.machine() in {"aarch64", "arm64"})
     or (IS_WINDOWS and platform.machine().lower() in {"arm64", "aarch64"})
@@ -54,8 +52,8 @@ PLATFORM_LACKS_TORCHCODEC_WHEEL = (
 )
 
 # ── ROCm / AMD GPU support ─────────────────────────────────────────────────────
-# Mapping from detected ROCm (major, minor) to the best PyTorch wheel tag on
-# download.pytorch.org.  Entries are checked newest-first (>=).
+# Detected ROCm (major, minor) -> best PyTorch wheel tag on
+# download.pytorch.org. Checked newest-first (>=).
 _ROCM_TORCH_INDEX: dict[tuple[int, int], str] = {
     (7, 2): "rocm7.2",  # torch 2.11.0
     (7, 1): "rocm7.1",  # torch 2.10.0
@@ -85,15 +83,15 @@ _PYTORCH_WHL_BASE = (
     os.environ.get("UNSLOTH_PYTORCH_MIRROR") or "https://download.pytorch.org/whl"
 ).rstrip("/")
 
-# AMD Windows ROCm wheels — repo.amd.com (arch-specific pip index)
+# AMD Windows ROCm wheels — repo.amd.com (arch-specific pip index).
 # Format: https://repo.amd.com/rocm/whl/{arch_family}/
-# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped / mirror installs.
+# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped/mirror installs.
 _ROCM_WINDOWS_INDEX_BASE = (
     os.environ.get("UNSLOTH_ROCM_WINDOWS_MIRROR") or "https://repo.amd.com/rocm/whl"
 ).rstrip("/")
 
-# Maps gfx arch → AMD index arch-family suffix.
-# Each family is a separate pip index on repo.amd.com.
+# gfx arch → AMD index arch-family suffix; each family is a separate
+# pip index on repo.amd.com.
 _GFX_TO_AMD_INDEX_ARCH: dict[str, str] = {
     "gfx1201": "gfx120X-all",
     "gfx1200": "gfx120X-all",  # RDNA 4
@@ -122,9 +120,9 @@ _BNB_ROCM_PRERELEASE_URLS: dict[str, str] = {
         "bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_aarch64.whl"
     ),
     # Windows ROCm wheel — ships libbitsandbytes_rocm{VER}.dll.
-    # BNB auto-detects HIP version from torch.version.hip, which does not always
-    # match the DLL suffix in this prerelease wheel (e.g. torch 7.13 with a rocm72
-    # DLL).  We scan the installed wheel for the actual DLL name and set
+    # BNB auto-detects HIP version from torch.version.hip, which may not match
+    # the DLL suffix in this prerelease wheel (e.g. torch 7.13 with a rocm72
+    # DLL). We scan the installed wheel for the real DLL name and set
     # BNB_ROCM_VERSION accordingly in _install_bnb_windows_rocm() and worker.py.
     "win_amd64": (
         "https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
@@ -136,8 +134,8 @@ _BNB_ROCM_PYPI_FALLBACK = "bitsandbytes>=0.49.1"
 
 
 def _bnb_rocm_prerelease_url() -> str | None:
-    """Return the continuous-release_main bnb wheel URL for the current
-    architecture, or None when no pre-release wheel is available.
+    """Return the continuous-release_main bnb wheel URL for the current arch,
+    or None when no pre-release wheel is available.
     """
     arch = platform.machine().lower()
     arch = {"amd64": "x86_64", "arm64": "aarch64"}.get(arch, arch)
@@ -155,9 +153,9 @@ def _detect_rocm_version() -> tuple[int, int] | None:
         try:
             with open(path) as fh:
                 parts = fh.read().strip().split("-")[0].split(".")
-            # Explicit length guard avoids relying on the broad except
-            # below to swallow IndexError when the version file contains
-            # a single component (e.g. "6\n" on a partial install).
+            # Explicit length guard so we don't rely on the broad except
+            # below to swallow IndexError when the version file has a
+            # single component (e.g. "6\n" on a partial install).
             if len(parts) >= 2:
                 return int(parts[0]), int(parts[1])
         except Exception:
@@ -201,11 +199,10 @@ def _detect_rocm_version() -> tuple[int, int] | None:
             pass
 
     # Distro package-manager fallbacks. Package-managed ROCm installs can
-    # expose GPUs via rocminfo / amd-smi but still lack /opt/rocm/.info/version
-    # and hipconfig, so probe dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE)
-    # for the rocm-core package version. Matches the chain in
-    # install.sh::get_torch_index_url so `unsloth studio update` behaves
-    # the same as a fresh `curl | sh` install.
+    # expose GPUs via rocminfo/amd-smi but lack /opt/rocm/.info/version and
+    # hipconfig, so probe dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE)
+    # for the rocm-core version. Matches install.sh::get_torch_index_url so
+    # `unsloth studio update` behaves like a fresh `curl | sh` install.
     for cmd in (
         ["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
         ["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
@@ -236,9 +233,9 @@ def _detect_rocm_version() -> tuple[int, int] | None:
 
 
 def _pick_visible_index(num_tokens: int) -> int:
-    """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an integer
-    index into a list of length num_tokens. Returns 0 (first GPU) for
-    unset, empty, '-1', UUID-style, or out-of-range values."""
+    """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an index into a
+    list of length num_tokens. Returns 0 (first GPU) for unset, empty, '-1',
+    UUID-style, or out-of-range values."""
     for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
         _val = os.environ.get(_env)
         if _val is None:
@@ -260,14 +257,14 @@ def _pick_visible_index(num_tokens: int) -> int:
 def _detect_windows_gfx_arch() -> str | None:
     """Return the gcnArchName on Windows (e.g. 'gfx1200'), or None.
 
-    Probe order matches the PowerShell installer: env-var override first,
-    then hipinfo (PATH or HIP_PATH / ROCM_PATH bin), then amd-smi. Without
-    the amd-smi fallback, runtime-only AMD installs without hipinfo on PATH
+    Probe order matches the PowerShell installer: env-var override, then
+    hipinfo (PATH or HIP_PATH/ROCM_PATH bin), then amd-smi. Without the
+    amd-smi fallback, runtime-only AMD installs lacking hipinfo on PATH
     return early and `studio update` cannot repair a CPU-only venv.
 
-    On multi-GPU hosts, all detected gfx tokens are deduplicated (preserving
-    enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES selects
-    which one to install for. The first GPU is used when no env var is set.
+    On multi-GPU hosts, detected gfx tokens are deduplicated (preserving
+    enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES picks
+    which to install for. The first GPU is used when no env var is set.
     """
     # 1. Explicit override (matches PowerShell installer's env-var path).
     _override = os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
@@ -277,8 +274,8 @@ def _detect_windows_gfx_arch() -> str | None:
     def _dedup_pick(tokens: list[str]) -> "str | None":
         if not tokens:
             return None
-        # Index into the full (ordered) list first so HIP_VISIBLE_DEVICES
-        # correctly addresses GPU N on mixed-arch hosts, then return that arch.
+        # Index into the full ordered list so HIP_VISIBLE_DEVICES addresses
+        # GPU N on mixed-arch hosts, then return that arch.
         return tokens[_pick_visible_index(len(tokens))]
 
     # 2. hipinfo via PATH, then HIP_PATH\bin / ROCM_PATH\bin.
@@ -301,8 +298,8 @@ def _detect_windows_gfx_arch() -> str | None:
             )
             if result.returncode == 0:
                 text = result.stdout.decode(errors = "replace")
-                # findall picks every gcnArchName line so multi-GPU hosts
-                # are enumerable and HIP_VISIBLE_DEVICES selects correctly.
+                # findall gets every gcnArchName line so multi-GPU hosts are
+                # enumerable and HIP_VISIBLE_DEVICES selects correctly.
                 _tokens = [
                     t.strip().lower() for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
                 ]
@@ -353,10 +350,10 @@ def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:
 def _detect_bnb_rocm_dll_ver() -> str | None:
     """Scan the installed bitsandbytes package for libbitsandbytes_rocm{VER}.dll.
 
-    Returns the version suffix string (e.g. ``"72"``, ``"713"``) or ``None``
-    if bitsandbytes is not installed or no ROCm DLL is found.  Does NOT import
-    bitsandbytes — uses importlib.util.find_spec so it is safe to call before
-    BNB is imported.
+    Returns the version suffix (e.g. ``"72"``, ``"713"``) or ``None`` if
+    bitsandbytes is not installed or no ROCm DLL is found. Does NOT import
+    bitsandbytes — uses importlib.util.find_spec, so it is safe to call
+    before BNB is imported.
     """
     import importlib.util
 
@@ -369,9 +366,9 @@ def _detect_bnb_rocm_dll_ver() -> str | None:
             m = re.search(r"libbitsandbytes_rocm(\d+)\.dll", os.path.basename(dll))
             if m:
                 all_vers.append(m.group(1))
-    # Pick the highest numeric suffix so that e.g. "713" wins over "72" when
-    # both variants are present in the wheel.  Filesystem glob order is not
-    # guaranteed, so always sort rather than stopping at the first match.
+    # Pick the highest numeric suffix so e.g. "713" wins over "72" when both
+    # variants are present. Glob order is not guaranteed, so always sort
+    # rather than stopping at the first match.
     return max(all_vers, key = lambda v: int(v)) if all_vers else None
 
 
@@ -380,8 +377,8 @@ def _has_rocm_gpu() -> bool:
     for cmd, check_fn in (
         # rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
         # gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
-        # "gfx11-generic" or "gfx9-4-generic" which only have 1-2 digits before
-        # the dash and must not be treated as a real GPU.
+        # "gfx11-generic"/"gfx9-4-generic" with only 1-2 digits before the dash,
+        # which must not be treated as a real GPU.
         (
             ["rocminfo"],
             lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
@@ -410,9 +407,8 @@ def _has_rocm_gpu() -> bool:
                 return True
     # sysfs KFD topology fallback (Linux only) -- matches install.sh's
     # runtime-only detection. On minimal package-managed installs (no
-    # rocminfo / no amd-smi GUI tools), the kernel exposes AMD GPUs via
-    # /sys/class/kfd so `studio update` can still detect the GPU and
-    # repair the venv.
+    # rocminfo / no amd-smi tools), the kernel exposes AMD GPUs via
+    # /sys/class/kfd so `studio update` can still detect and repair.
     if sys.platform != "win32":
         try:
             kfd_nodes = "/sys/class/kfd/kfd/topology/nodes"
@@ -450,12 +446,11 @@ def _has_usable_nvidia_gpu() -> bool:
 
 
 def _detect_amd_gfx_codes() -> list[str]:
-    """Return the list of AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
+    """Return the AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
 
-    Probes rocminfo first, then falls back to ``amd-smi list`` and
-    ``amd-smi static --asic`` for runtime-only Radeon hosts that ship
-    amd-smi but no rocminfo. Returns an empty list when no probe yields
-    a gfx target.
+    Probes rocminfo, then falls back to ``amd-smi list`` and ``amd-smi
+    static --asic`` for runtime-only Radeon hosts that ship amd-smi but no
+    rocminfo. Returns an empty list when no probe yields a gfx target.
     """
 
     def _extract(text: str) -> list[str]:
@@ -495,13 +490,13 @@ def _install_bnb_windows_rocm() -> bool:
     """Install the AMD Windows BNB prerelease wheel. Returns True on success.
 
     The continuous-release wheel is intentionally mismatched: the filename
-    encodes version 1.33.7.preview (parsed as 1.33.7rc0 by PEP 440) while the
-    wheel metadata reports 0.50.0.dev0.  uv rejects this filename/metadata
-    mismatch -- and bypassing it with UV_SKIP_WHEEL_FILENAME_CHECK still leaves
-    uv mangling the bitsandbytes install. Per the AMD install guide
+    encodes 1.33.7.preview (parsed as 1.33.7rc0 by PEP 440) while the wheel
+    metadata reports 0.50.0.dev0. uv rejects this filename/metadata mismatch,
+    and bypassing it with UV_SKIP_WHEEL_FILENAME_CHECK still leaves uv mangling
+    the bitsandbytes install. Per the AMD install guide
     (https://unsloth.ai/docs/get-started/install/amd/amd-hackathon) the wheel
-    must be installed with plain pip, not uv, so we force pip here
-    (force_pip=True). plain pip performs no wheel filename/metadata check.
+    must be installed with plain pip, not uv, so we force pip (force_pip=True);
+    plain pip performs no wheel filename/metadata check.
     """
     _bnb_win_url = _BNB_ROCM_PRERELEASE_URLS.get("win_amd64")
     if _bnb_win_url is None:
@@ -517,13 +512,12 @@ def _install_bnb_windows_rocm() -> bool:
     )
     if not _ok:
         return False
-    # After install: detect the actual ROCm DLL suffix shipped in the wheel and
-    # set BNB_ROCM_VERSION so bitsandbytes loads the correct DLL regardless of
-    # what torch.version.hip reports.  The wheel may ship an older suffix (e.g.
-    # "72") while torch reports a newer HIP version (e.g. 7.13); the env var
-    # override ensures bitsandbytes does not fail looking for a non-existent DLL.
-    # The worker subprocess inherits this env var automatically.
-    # Fall back to "72" if detection fails (e.g. install was a no-op / dry-run).
+    # After install: detect the actual ROCm DLL suffix in the wheel and set
+    # BNB_ROCM_VERSION so bitsandbytes loads the correct DLL regardless of what
+    # torch.version.hip reports. The wheel may ship an older suffix (e.g. "72")
+    # while torch reports a newer HIP version (e.g. 7.13); the override stops
+    # bitsandbytes from failing on a non-existent DLL. The worker subprocess
+    # inherits this env var. Fall back to "72" if detection fails (no-op/dry-run).
     if "BNB_ROCM_VERSION" not in os.environ:
         _ver = _detect_bnb_rocm_dll_ver() or "72"
         os.environ["BNB_ROCM_VERSION"] = _ver
@@ -540,9 +534,9 @@ def _ensure_rocm_torch() -> None:
     Uses pip_install() to respect uv, constraints, and --python targeting.
     """
     global _rocm_windows_torch_installed
-    # setup.ps1 sets this when it already installed AMD wheels; skip the probe
-    # only when torch is actually importable as ROCm. If the venv was wiped
-    # between runs, the stale env-var would suppress a needed reinstall.
+    # setup.ps1 sets this after installing AMD wheels; skip the probe only when
+    # torch is actually importable as ROCm. If the venv was wiped between runs,
+    # the stale env-var would suppress a needed reinstall.
     if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
         _torch_ok = False
         try:
@@ -566,9 +560,9 @@ def _ensure_rocm_torch() -> None:
             pass
         if _torch_ok:
             _rocm_windows_torch_installed = True
-            # setup.ps1 already installed ROCm torch, but we still need to install
-            # the AMD Windows BNB wheel here -- the PyPI bitsandbytes wheel ships
-            # only CUDA DLLs and will fail to load on ROCm.
+            # setup.ps1 already installed ROCm torch, but we still need the AMD
+            # Windows BNB wheel here -- the PyPI bitsandbytes wheel ships only
+            # CUDA DLLs and fails to load on ROCm.
             _install_bnb_windows_rocm()
             return
         # torch was wiped between runs; fall through to the full install path
@@ -619,14 +613,14 @@ def _ensure_rocm_torch() -> None:
                 "torchaudio",
                 constrain = False,
             )
-        # ROCm torch is installed (or already was); flag it so later install
-        # phases do not overwrite it with the generic CPU torch wheel. BNB is
-        # a separate dependency -- a BNB install failure must NOT roll the
-        # torch ROCm install back.
+        # ROCm torch is installed (or already was); flag it so later phases
+        # do not overwrite it with the generic CPU torch wheel. BNB is a
+        # separate dependency -- a BNB install failure must NOT roll back the
+        # torch ROCm install.
         _rocm_windows_torch_installed = True
         # Always install AMD Windows bitsandbytes -- the PyPI wheel ships only
-        # CUDA DLLs and will fail to load on ROCm.  Install even when torch was
-        # already a ROCm build so that `studio update` repairs a broken bnb.
+        # CUDA DLLs and fails on ROCm. Install even when torch was already a
+        # ROCm build so `studio update` repairs a broken bnb.
         if not _install_bnb_windows_rocm():
             print(
                 "   Warning: AMD Windows bitsandbytes install failed; "
@@ -637,16 +631,15 @@ def _ensure_rocm_torch() -> None:
     # ── Linux x86_64 only: PyTorch ROCm wheels are not published for aarch64 ──
     if platform.machine().lower() not in {"x86_64", "amd64"}:
         return
-    # NVIDIA takes precedence on mixed hosts -- but only if an actual GPU is usable
+    # NVIDIA takes precedence on mixed hosts -- but only if a GPU is usable
     if _has_usable_nvidia_gpu():
         return
-    # Rely on _has_rocm_gpu() (rocminfo / amd-smi GPU data rows) as the
-    # authoritative "is this actually an AMD ROCm host?" signal. The old
-    # gate required /opt/rocm or hipcc to exist, which breaks on
-    # runtime-only ROCm installs (package-managed minimal installs,
-    # Radeon software) that ship amd-smi/rocminfo without /opt/rocm or
-    # hipcc, and leaves `unsloth studio update` unable to repair a
-    # CPU-only venv on those systems.
+    # Use _has_rocm_gpu() (rocminfo / amd-smi GPU data rows) as the
+    # authoritative "is this an AMD ROCm host?" signal. The old gate required
+    # /opt/rocm or hipcc to exist, which breaks runtime-only ROCm installs
+    # (minimal package-managed installs, Radeon software) that ship
+    # amd-smi/rocminfo without /opt/rocm or hipcc, leaving `unsloth studio
+    # update` unable to repair a CPU-only venv on those systems.
     if not _has_rocm_gpu():
         return  # no AMD GPU visible
 
@@ -655,9 +648,9 @@ def _ensure_rocm_torch() -> None:
         print("   ROCm detected but version unreadable -- skipping torch reinstall")
         return
 
-    # Probe whether torch already links against HIP (ROCm is already working).
-    # Do NOT skip for CUDA-only builds since they are unusable on AMD-only
-    # hosts (the NVIDIA check above already handled mixed AMD+NVIDIA setups).
+    # Probe whether torch already links against HIP (ROCm already working).
+    # Do NOT skip for CUDA-only builds: they are unusable on AMD-only hosts
+    # (the NVIDIA check above already handled mixed AMD+NVIDIA setups).
     try:
         probe = subprocess.run(
             [
@@ -667,7 +660,7 @@ def _ensure_rocm_torch() -> None:
                     "import torch; "
                     "hip=getattr(torch.version,'hip','') or ''; "
                     "ver=getattr(torch,'__version__','').lower(); "
-                    # Print the HIP version when present (back-compat), else
+                    # Print the HIP version when present (back-compat), else a
                     # "rocm" sentinel when only torch.__version__ flags ROCm
                     # (AMD SDK / Radeon wheels). Empty string = CPU/CUDA.
                     "print(hip if hip else ('rocm' if 'rocm' in ver else ''))"
@@ -689,10 +682,9 @@ def _ensure_rocm_torch() -> None:
     # in torch._grouped_mm. AMD's per-gfx repo ships torch 2.11.0+rocm7.13.0
     # with the real fix, so route those hosts there instead of the generic
     # pytorch.org rocm7.1 wheel. Mirrors install.sh's Strix override.
-    # On mixed hosts (Strix iGPU + non-Strix dGPU), only route to the AMD
-    # per-gfx index when the GPU HIP will actually run on is the Strix one --
-    # otherwise the dGPU would get an incompatible wheel. Use HIP_VISIBLE_DEVICES
-    # to determine the runtime target.
+    # On mixed hosts (Strix iGPU + non-Strix dGPU), route to the AMD per-gfx
+    # index only when HIP's runtime GPU is the Strix one -- else the dGPU gets
+    # an incompatible wheel. Use HIP_VISIBLE_DEVICES for the runtime target.
     _strix_override_url: "str | None" = None
     _strix_override_pkgs: "tuple[str, str, str] | None" = None
     if ver < (7, 2):
@@ -700,10 +692,9 @@ def _ensure_rocm_torch() -> None:
         _strix_gfx = {"gfx1151", "gfx1150"}
         _detected_strix = _strix_gfx.intersection(gfx_codes)
         if _detected_strix:
-            # Pick the runtime-visible GPU. If HIP_VISIBLE_DEVICES selects a
-            # specific index into gfx_codes, use that gfx; else default to the
-            # first listed GPU. Skip the override unless the resolved GPU is
-            # Strix.
+            # Pick the runtime-visible GPU: use the HIP_VISIBLE_DEVICES index
+            # into gfx_codes, else default to the first GPU. Skip the override
+            # unless the resolved GPU is Strix.
             _runtime_gfx = gfx_codes[_pick_visible_index(len(gfx_codes))] if gfx_codes else None
             if _runtime_gfx in _strix_gfx:
                 _selected_gfx = _runtime_gfx
@@ -715,10 +706,10 @@ def _ensure_rocm_torch() -> None:
                     "torch>=2.11.0,<2.12.0",
                     # Pin torchvision/torchaudio to the 2.11.x-compatible range.
                     # The install uses --index-url (exclusive, no PyPI fallback),
-                    # so bare unversioned names risk resolving a build from AMD's
-                    # index that targets a different torch major (e.g. 0.27 built
-                    # against torch 2.12), which would fail at runtime with an
-                    # ABI/version mismatch. Matches _ROCM_TORCH_CONSTRAINT["rocm7.2"].
+                    # so bare unversioned names risk resolving an AMD-index build
+                    # targeting a different torch major (e.g. 0.27 built against
+                    # torch 2.12), which fails at runtime with an ABI/version
+                    # mismatch. Matches _ROCM_TORCH_CONSTRAINT["rocm7.2"].
                     "torchvision>=0.26.0,<0.27.0",
                     "torchaudio>=2.11.0,<2.12.0",
                 )
@@ -740,8 +731,8 @@ def _ensure_rocm_torch() -> None:
 
     # Strix override on ROCm 7.1 must fire even when has_hip_torch is True --
     # an existing torch with `torch.version.hip == "7.1"` is exactly the broken
-    # combo the override is meant to repair, so skipping it leaves users on
-    # the known _grouped_mm segfault.
+    # combo the override repairs, so skipping it leaves users on the known
+    # _grouped_mm segfault.
     if _strix_override_url is not None and _strix_override_pkgs is not None:
         index_url = _strix_override_url
         _torch_pkg, _vision_pkg, _audio_pkg = _strix_override_pkgs
@@ -790,10 +781,9 @@ def _ensure_rocm_torch() -> None:
             rocm_torch_ready = True
 
     # Install bitsandbytes only when torch links against ROCm. Prefers the
-    # continuous-release_main wheel (bnb PR #1887 4-bit GEMV fix) and falls
-    # back to PyPI when the pre-release wheel cannot be installed. Use pip for
-    # the pre-release wheel because uv rejects the wheel's filename/metadata
-    # version mismatch.
+    # continuous-release_main wheel (bnb PR #1887 4-bit GEMV fix), falling back
+    # to PyPI when the pre-release wheel won't install. Use pip for the
+    # pre-release wheel because uv rejects its filename/metadata version mismatch.
     if rocm_torch_ready:
         _bnb_url = _bnb_rocm_prerelease_url()
         _bnb_installed = False
@@ -871,10 +861,9 @@ def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
 def _infer_no_torch() -> bool:
     """Determine whether to run in no-torch (GGUF-only) mode.
 
-    Checks UNSLOTH_NO_TORCH env var first.  When unset, falls back to
-    platform detection so that Intel Macs automatically use GGUF-only
-    mode even when invoked from ``unsloth studio update`` (which does
-    not inject the env var).
+    Checks UNSLOTH_NO_TORCH first. When unset, falls back to platform
+    detection so Intel Macs use GGUF-only mode even when invoked from
+    ``unsloth studio update`` (which does not inject the env var).
     """
     env = os.environ.get("UNSLOTH_NO_TORCH")
     if env is not None:
@@ -886,15 +875,15 @@ NO_TORCH = _infer_no_torch()
 
 
 # -- Verbosity control ----------------------------------------------------------
-# By default the installer shows a minimal progress bar (one line, in-place).
-# Set UNSLOTH_VERBOSE=1 in the environment to restore full per-step output:
+# By default the installer shows a minimal in-place one-line progress bar.
+# Set UNSLOTH_VERBOSE=1 to restore full per-step output:
 #   CLI:        unsloth studio setup --verbose
 #   Linux/Mac:  UNSLOTH_VERBOSE=1 ./studio/setup.sh
 #   Windows:    $env:UNSLOTH_VERBOSE="1" ; .\studio\setup.ps1
 VERBOSE: bool = os.environ.get("UNSLOTH_VERBOSE", "0") == "1"
 
-# Progress bar state -- updated by _progress() as each install step runs.
-# Update _TOTAL here if you add or remove install steps in install_python_stack().
+# Progress bar state -- updated by _progress() per install step.
+# Update _TOTAL if you add/remove steps in install_python_stack().
 _STEP: int = 0
 _TOTAL: int = 0  # set at runtime in install_python_stack() based on platform
 
@@ -908,16 +897,15 @@ LOCAL_DD_UNSTRUCTURED_PLUGIN = (
 )
 LOCAL_DD_GITHUB_PLUGIN = SCRIPT_DIR / "backend" / "plugins" / "data-designer-github-repo-seed"
 
-# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides file).
+# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides).
 _MLX_OVERRIDES = SINGLE_ENV / "overrides-darwin-arm64.txt"
 if IS_MAC_ARM and _MLX_OVERRIDES.is_file():
     os.environ.setdefault("UV_OVERRIDE", str(_MLX_OVERRIDES))
 
 # -- Unicode-safe printing ---------------------------------------------
-# On Windows the default console encoding can be a legacy code page
-# (e.g. CP1252) that cannot represent Unicode glyphs such as ✅ or ❌.
-# _safe_print() gracefully degrades to ASCII equivalents so the
-# installer never crashes just because of a status glyph.
+# On Windows the console encoding may be a legacy code page (e.g. CP1252)
+# that cannot represent glyphs like ✅ or ❌. _safe_print() degrades to ASCII
+# equivalents so the installer never crashes over a status glyph.
 
 _UNICODE_TO_ASCII: dict[str, str] = {
     "\u2705": "[OK]",  # ✅
@@ -934,11 +922,11 @@ def _safe_print(*args: object, **kwargs: object) -> None:
     except OSError:
         return
     except UnicodeEncodeError:
-        # Stringify, then swap emoji for ASCII equivalents
+        # Stringify, then swap emoji for ASCII equivalents.
         text = " ".join(str(a) for a in args)
         for uni, ascii_alt in _UNICODE_TO_ASCII.items():
             text = text.replace(uni, ascii_alt)
-        # Final fallback: replace any remaining unencodable chars
+        # Final fallback: replace any remaining unencodable chars.
         print(
             text.encode(sys.stdout.encoding or "ascii", errors = "replace").decode(
                 sys.stdout.encoding or "ascii", errors = "replace"
@@ -1065,16 +1053,14 @@ def run(
 WINDOWS_SKIP_PACKAGES = {"open_spiel", "triton_kernels"}
 
 # Packages to skip when torch is unavailable (Intel Mac GGUF-only mode).
-# These packages either *are* torch extensions or have unconditional
-# ``Requires-Dist: torch`` in their published metadata, so installing
-# them would pull torch back into the environment. ``librosa`` also
-# lives in this set even though it does not itself require torch:
-# upstream ``llvmlite`` dropped its macOS x86_64 wheel between 0.42.0
-# and 0.46.0+ (see https://pypi.org/project/llvmlite/0.47.0/#files --
-# only macosx_arm64 / manylinux / win_amd64 remain), so on Intel Mac
-# the librosa -> numba -> llvmlite chain triggers a from-source build
-# that fails inside CI and on the host without LLVM 14/15 headers.
-# Tracked separately in unslothai/unsloth#5046.
+# These either *are* torch extensions or have unconditional
+# ``Requires-Dist: torch``, so installing them would pull torch back in.
+# ``librosa`` is here too despite not requiring torch: upstream ``llvmlite``
+# dropped its macOS x86_64 wheel between 0.42.0 and 0.46.0+ (see
+# https://pypi.org/project/llvmlite/0.47.0/#files -- only
+# macosx_arm64 / manylinux / win_amd64 remain), so on Intel Mac the
+# librosa -> numba -> llvmlite chain triggers a from-source build that fails
+# in CI and on hosts without LLVM 14/15 headers. Tracked in unslothai/unsloth#5046.
 NO_TORCH_SKIP_PACKAGES = {
     "torch-stoi",
     "timm",
@@ -1238,14 +1224,14 @@ def _build_uv_cmd(args: tuple[str, ...]) -> list[str]:
     cmd = ["uv", "pip", "install"]
     if UV_NEEDS_SYSTEM:
         cmd.append("--system")
-    # Always pass --python so uv targets the correct environment.
-    # Without this, uv can ignore an activated venv and install into
-    # the system Python (observed on Colab and similar environments).
+    # Always pass --python so uv targets the right environment. Without it, uv
+    # can ignore an activated venv and install into the system Python (seen on
+    # Colab and similar).
     cmd.extend(["--python", sys.executable])
     cmd.extend(_translate_pip_args_for_uv(args))
-    # Torch is pre-installed by install.sh/setup.ps1.  Do not add
-    # --torch-backend by default -- it can cause solver dead-ends on
-    # CPU-only machines.  Callers that need it can set UV_TORCH_BACKEND.
+    # Torch is pre-installed by install.sh/setup.ps1. Do not add
+    # --torch-backend by default -- it can cause solver dead-ends on CPU-only
+    # machines. Callers that need it can set UV_TORCH_BACKEND.
     _tb = os.environ.get("UV_TORCH_BACKEND", "")
     if _tb:
         cmd.append(f"--torch-backend={_tb}")
@@ -1259,7 +1245,7 @@ def pip_install_try(
     force_pip: bool = False,
 ) -> bool:
     """Like pip_install but returns False on failure instead of exiting.
-    For optional installs with a follow-up fallback.
+    For optional installs that have a follow-up fallback.
     """
     constraint_args_pip: list[str] = []
     constraint_args_uv: list[str] = []
@@ -1384,14 +1370,14 @@ def install_python_stack() -> int:
     global USE_UV, _STEP, _TOTAL
     _STEP = 0
 
-    # When called from install.sh (which already installed unsloth into the venv),
-    # SKIP_STUDIO_BASE=1 is set to avoid redundant reinstallation of base packages.
-    # When called from "unsloth studio update", it is NOT set so base packages
-    # (unsloth + unsloth-zoo) are always reinstalled to pick up new versions.
+    # install.sh (which already installed unsloth) sets SKIP_STUDIO_BASE=1 to
+    # avoid reinstalling base packages. "unsloth studio update" does NOT set it,
+    # so base packages (unsloth + unsloth-zoo) are reinstalled to pick up new
+    # versions.
     skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"
-    # When --package is used, install a different package name (for testing)
+    # --package installs a different package name (for testing).
     package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")
-    # When --local is used, overlay a local repo checkout after updating deps
+    # --local overlays a local repo checkout after updating deps.
     local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")
     base_total = 10 if IS_WINDOWS else 11
     if IS_MACOS:
@@ -1402,11 +1388,11 @@ def install_python_stack() -> int:
             base_total += 2  # flash-attn (line 1620) + ROCm torch final (line 1705) -- Linux only
     _TOTAL = (base_total - 1) if skip_base else base_total
 
-    # 1. Try to use uv for faster installs (must happen before pip upgrade
-    #    because uv venvs don't include pip by default)
+    # 1. Try uv for faster installs (before pip upgrade -- uv venvs don't
+    #    include pip by default).
     USE_UV = _bootstrap_uv()
 
-    # 2. Ensure pip is available (uv venvs created by install.sh don't include pip)
+    # 2. Ensure pip is available (uv venvs from install.sh omit pip).
     _progress("pip bootstrap")
     if USE_UV:
         run(
@@ -1421,9 +1407,8 @@ def install_python_stack() -> int:
             ],
         )
     else:
-        # pip may not exist yet (uv-created venvs omit it). Try ensurepip
-        # first, then upgrade. Only fall back to a direct upgrade when pip
-        # is already present.
+        # pip may not exist yet (uv-created venvs omit it). Try ensurepip,
+        # then upgrade. Direct upgrade only when pip is already present.
         _has_pip = (
             subprocess.run(
                 [sys.executable, "-m", "pip", "--version"],
@@ -1464,8 +1449,8 @@ def install_python_stack() -> int:
         pass
     elif NO_TORCH:
         # No-torch update path: install unsloth + unsloth-zoo with --no-deps
-        # (current PyPI metadata still declares torch as a hard dep), then
-        # runtime deps with --no-deps (avoids transitive torch).
+        # (PyPI metadata still declares torch as a hard dep), then runtime deps
+        # with --no-deps (avoids transitive torch).
         _progress("base packages (no torch)")
         pip_install(
             f"Updating {package_name} + unsloth-zoo (no-torch mode)",
@@ -1478,11 +1463,10 @@ def install_python_stack() -> int:
             package_name,
             "unsloth-zoo",
         )
-        # Resolve pydantic WITH deps so pip pins pydantic-core to the
-        # exact version pydantic's metadata declares. Under --no-deps
-        # alone pip picks the latest of each and trips pydantic's
-        # _ensure_pydantic_core_version check. Transitive deps are
-        # torch-free.
+        # Resolve pydantic WITH deps so pip pins pydantic-core to the exact
+        # version pydantic's metadata declares. Under --no-deps pip picks the
+        # latest of each and trips pydantic's _ensure_pydantic_core_version
+        # check. Transitive deps are torch-free.
         pip_install(
             "Installing pydantic (with deps for compatible core)",
             "--no-cache-dir",
@@ -1514,9 +1498,8 @@ def install_python_stack() -> int:
                 constrain = False,
             )
     elif local_repo:
-        # Local dev install: update deps from base.txt, then overlay the
-        # local checkout as an editable install (--no-deps so torch is
-        # never re-resolved).
+        # Local dev install: update deps from base.txt, then overlay the local
+        # checkout as an editable install (--no-deps so torch is not re-resolved).
         _progress("base packages")
         pip_install(
             "Updating base packages",
@@ -1546,7 +1529,7 @@ def install_python_stack() -> int:
             constrain = False,
         )
     elif package_name != "unsloth":
-        # Custom package name (for testing), install directly
+        # Custom package name (for testing): install directly.
         _progress("base packages")
         pip_install(
             f"Installing {package_name}",
@@ -1554,9 +1537,9 @@ def install_python_stack() -> int:
             package_name,
         )
     else:
-        # Update path: upgrade only unsloth + unsloth-zoo while preserving
-        # existing torch/CUDA installations.  Torch is pre-installed by
-        # install.sh / setup.ps1; --upgrade-package targets only base pkgs.
+        # Update path: upgrade only unsloth + unsloth-zoo, preserving existing
+        # torch/CUDA installs. Torch is pre-installed by install.sh/setup.ps1;
+        # --upgrade-package targets only base pkgs.
         _progress("base packages")
         pip_install(
             "Updating base packages",
@@ -1569,16 +1552,16 @@ def install_python_stack() -> int:
         )
 
     # 2b. AMD ROCm: reinstall torch with HIP wheels if the host has ROCm but the
-    #     venv received CPU-only torch (common when pip resolves torch from PyPI).
-    #     Must come immediately after base packages so torch is present for inspection.
+    #     venv got CPU-only torch (common when pip resolves torch from PyPI).
+    #     Must follow base packages so torch is present for inspection.
     if not IS_MACOS and not NO_TORCH:
         _progress("ROCm torch check")
         _ensure_rocm_torch()
 
-    # Windows + AMD GPU: if ROCm torch was not installed (wrong Python version
-    # or unknown ROCm version), warn the user.
+    # Windows + AMD GPU: warn if ROCm torch was not installed (wrong Python
+    # version or unknown ROCm version).
     if IS_WINDOWS and not NO_TORCH and not _has_usable_nvidia_gpu():
-        # Validate actual AMD GPU presence (not just tool existence)
+        # Validate actual AMD GPU presence (not just tool existence).
         import re as _re_win
 
         def _win_amd_smi_has_gpu(stdout: str) -> bool:
@@ -1632,9 +1615,9 @@ def install_python_stack() -> int:
         req = REQ_ROOT / "extras-no-deps.txt",
     )
 
-    # 4. Overrides (torchao, transformers) -- force-reinstall
-    #    Skip entirely when torch is unavailable (e.g. Intel Mac GGUF-only mode)
-    #    because overrides.txt contains torchao which requires torch.
+    # 4. Overrides (torchao, transformers) -- force-reinstall.
+    #    Skip when torch is unavailable (e.g. Intel Mac GGUF-only mode):
+    #    overrides.txt contains torchao, which requires torch.
     if NO_TORCH:
         _progress("dependency overrides (skipped, no torch)")
     else:
@@ -1642,8 +1625,8 @@ def install_python_stack() -> int:
         _override_extra_args: tuple[str, ...] = ()
         if _rocm_windows_torch_installed:
             # torchao in overrides.txt declares torch as a dependency; without
-            # --no-deps uv would resolve and install CPU torch from PyPI,
-            # overwriting the AMD ROCm wheels we just installed.
+            # --no-deps uv would install CPU torch from PyPI, overwriting the
+            # AMD ROCm wheels we just installed.
             _override_extra_args = ("--no-deps",)
         pip_install(
             "Installing dependency overrides",
@@ -1653,8 +1636,8 @@ def install_python_stack() -> int:
             req = REQ_ROOT / "overrides.txt",
         )
 
-    # 5. Triton kernels (no-deps, from source)
-    #    Skip on Windows (no support) and macOS (no support).
+    # 5. Triton kernels (no-deps, from source). Skip on Windows and macOS
+    #    (no support).
     if not IS_WINDOWS and not IS_MACOS:
         _progress("triton kernels")
         pip_install(
@@ -1745,11 +1728,10 @@ def install_python_stack() -> int:
         [sys.executable, str(SINGLE_ENV / "patch_metadata.py")],
     )
 
-    # 13. AMD ROCm: final torch repair.  Multiple install steps above can
-    #     pull in CUDA torch from PyPI (base packages, extras, overrides,
-    #     studio deps, etc.).  Running the repair as the very last step
-    #     ensures ROCm torch is in place at runtime, regardless of which
-    #     intermediate step clobbered it.
+    # 13. AMD ROCm: final torch repair. Several steps above can pull in CUDA
+    #     torch from PyPI (base packages, extras, overrides, studio deps, etc.).
+    #     Running the repair last ensures ROCm torch is in place at runtime,
+    #     whichever intermediate step clobbered it.
     if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:
         _progress("ROCm torch (final)")
         _ensure_rocm_torch()