Skip to content

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

Restore the comment tails the trim cut off (#10205)

Daniel Han28a6c36a2280
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index cb04cf78c3a..579c560776b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -232,7 +232,7 @@ def _gated_in_chain(exc: BaseException) -> Optional[BaseException]:
seen.add(id(exc))
if any(cls.__name__ == "GatedRepoError" for cls in type(exc).__mro__):
return exc
- # `raise ... from None` means the raiser already wrote a better message (the base-repo preflight does)
+ # `raise ... from None` means the raiser already wrote a better message (the base-repo preflight does), so stop.
exc = exc.__cause__ or (None if exc.__suppress_context__ else exc.__context__)
return None
@@ -789,7 +789,7 @@ def _assert_base_repo_accessible(
except Exception: # noqa: BLE001 - offline / transient: the download surfaces any real error
return None
# Nothing to carry: model_info answered, so the size estimate lists the base files and the prefetch resolves each
- # through whichever root holds it
+ # through whichever root holds it.
if not gated or _already_downloaded():
return None
try:
@@ -1893,7 +1893,7 @@ class DiffusionBackend:
if kind in ("gguf", "single_file"):
if not gguf_filename:
raise ValueError(f"a single-file checkpoint name is required for a '{kind}' load.")
- # Fail a kind/extension mismatch before the handoff: gguf needs .gguf, single_file must not
+ # Fail a kind/extension mismatch before the handoff: gguf needs .gguf, single_file must not.
is_gguf_name = gguf_filename.lower().endswith(".gguf")
if kind == "gguf" and not is_gguf_name:
raise ValueError("a 'gguf' load requires a .gguf checkpoint name.")
@@ -3732,7 +3732,8 @@ class DiffusionBackend:
replanned = _replan_candidate()
if (
replanned.offload_policy != OFFLOAD_NONE
- # Explicit balanced/low_vram picks offload BY MODE, so a fresh snapshot cannot change it
+ # Explicit balanced/low_vram picks offload BY MODE, so a fresh snapshot cannot change
+ # it.
and normalize_memory_mode(memory_mode)
not in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM)
and plan_fits_total_capacity(replanned)
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index b169041a742..bdb0846095f 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -1080,7 +1080,7 @@ def _validate_checkpoint(
),
)
return False
- # fp8 fast-accum is baked into the saved kernels; only enforce when the caller forces it
+ # fp8 fast-accum is baked into the saved kernels; only enforce when the caller forces it.
if fast_accum is not None:
ckpt_fa = meta.get("fast_accum")
if ckpt_fa is not None and bool(ckpt_fa) != bool(fast_accum):
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 5ab0fa753ad..75cd063ed4c 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -908,7 +908,7 @@ def _run_smoke_probe(scheme: str, device: str) -> Optional[bool]:
lin = torch.nn.Linear(512, 512, bias = False).to(device = device, dtype = torch.bfloat16)
quantize_(lin, _make_quant_config(scheme), filter_fn = make_filter_fn(0))
- # M stays 32 (scaled_mm wants 16-aligned dims); the zero rows go inside it, not after it
+ # M stays 32 (scaled_mm wants 16-aligned dims); the zero rows go inside it, not after it.
x = torch.randn(32, 512, device = device, dtype = torch.bfloat16)
x[16:] = 0
with torch.no_grad():
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index f4272b64b32..f15855abea1 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -95,7 +95,7 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (
# --agent is --tools by another name: upstream documents it as "enable CORS proxy and ALL built-in tools", and that
# set includes exec_shell_command. Denying --tools while allowing this left the same capability one alias away.
frozenset({"-ag", "--agent", "-no-ag", "--no-agent"}),
- # Where those tools run: docker:/podman: spins up a container, ssh:<target> runs them on another host
+ # Where those tools run: docker:/podman: spins up a container, ssh:<target> runs them on another host entirely.
frozenset({"--tools-runtime"}),
# MCP servers are tools from a config file or an inline JSON blob; upstream says "do not enable in untrusted
# environments" for both.
@@ -1869,7 +1869,7 @@ def memory_state_satisfies_settings(
return True
mlock, reserves_ram = state
if get_no_ram_reserve():
- # mlock_applicable only excuses a MISSING lock; a live reservation still has to go, wherever the weights are
+ # mlock_applicable only excuses a MISSING lock; a live reservation still has to go, wherever the weights are.
return not (mlock or reserves_ram)
if get_keep_resident():
return mlock or not mlock_applicable
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.py
index f6c35c319d6..6d6b2a8b47b 100644
--- a/studio/backend/core/inference/local_model_resolver.py
+++ b/studio/backend/core/inference/local_model_resolver.py
@@ -292,7 +292,7 @@ def _config_is_servable_here(load_dir, config: dict) -> bool:
"""
from utils.security.remote_code_scan import REMOTE_CODE_CONFIG_FILES
- # trust_remote_code needs an approval fingerprint a switch has not got; read as data only
+ # trust_remote_code needs an approval fingerprint a switch has not got; read as data only.
for name in REMOTE_CODE_CONFIG_FILES:
candidate = config if name == "config.json" else _read_json(load_dir / name)
# truthiness like the consent gate's _config_has_auto_map: an empty map runs nothing.
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 1dba00face5..5874b320f6e 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1227,7 +1227,7 @@ class SdCppDiffusionBackend:
attention_backend: Optional[str] = None,
transformer_cache: Optional[str] = None,
transformer_cache_threshold: Optional[float] = None,
- # Accepted for interface parity; native is text-to-image only, so image-conditioned requests are rejected below.
+ # Accepted for interface parity; native is GGUF-only (router forces diffusers otherwise).
model_kind: Optional[str] = None,
# Parity with the diffusers load-time LoRA bake; native applies LoRA per generation, so a load-time selection is
# ignored.
@@ -1349,7 +1349,7 @@ class SdCppDiffusionBackend:
_load_token: int,
_cancel_event: Optional[threading.Event] = None,
) -> None:
- # This load's own event: a later load replaces self._cancel_event rather than clearing it
+ # This load's own event: a later load replaces self._cancel_event rather than clearing it.
cancel_event = _cancel_event if _cancel_event is not None else self._cancel_event
# The server this load publishes to _pending_server, out here so the backstop below can always unpublish it. A
# leaked _pending_server reads as "the managed tree is busy" for the rest of the process and blocks every later
@@ -1714,7 +1714,7 @@ class SdCppDiffusionBackend:
if self._load_token != _load_token:
return
logger.error("sd_cpp.load_failed: %s", exc)
- # Redact filesystem paths before this reaches /images/load-progress (as diffusers does)
+ # Redact filesystem paths before this reaches /images/load-progress (as diffusers does).
from utils.native_path_leases import redact_native_paths
with self._lock:
@@ -2140,7 +2140,7 @@ class SdCppDiffusionBackend:
# would render them serially.
prompts: Optional[list[str]] = None,
seeds: Optional[list[int]] = None,
- # Accepted for interface parity; native is text-to-image only
+ # Accepted for interface parity; native is text-to-image only, so image-conditioned requests are rejected below.
init_image: Optional[str] = None,
mask_image: Optional[str] = None,
strength: Optional[float] = None,
@@ -2350,7 +2350,7 @@ class SdCppDiffusionBackend:
images: list = []
seeds: list[int] = []
# Stage LoRAs into a per-request subdir of the server lora-model-dir (so a prior request's adapters cannot leak
- # in)
+ # in); removed after.
lora_payload: Optional[list[dict]] = None
lora_stage: Optional[Path] = None
if lora_resolved:
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index baf670dce30..91b8e9822a4 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -932,7 +932,7 @@ class _Turn:
# calls. A lone announcement the provider opened is kept (a zero-parameter tool looks like that). Its metadata
# goes to the call it was mistaken for: Gemini stows a thought signature there and rejects a replay without one.
for key, waiting in self.pending_extra.items():
- # No object ever came, so the repeated name was that call's after all and so is the metadata that rode it
+ # No object ever came, so the repeated name was that call's after all and so is the metadata that rode it.
held = self.by_index.get(key)
if held is not None and waiting:
held["extra_content"] = {**held.get("extra_content", {}), **waiting}
@@ -1705,7 +1705,7 @@ async def stream_with_studio_tools(
asyncio.to_thread(_advance_tool_stream, tool_stream, outcome)
)
# wait, not await: cancelling this coroutine must leave the worker pending so the drain below can
- # still join it
+ # still join it.
await asyncio.wait({step_task})
event = step_task.result()
step_task = None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 84aaf2ffd9c..e5abcd78901 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1422,7 +1422,7 @@ class VideoBackend:
def _run_load(self, **kwargs: Any) -> None:
token = kwargs.get("_load_token")
- # This load's own event: a later load replaces self._cancel_event rather than clearing it
+ # This load's own event: a later load replaces self._cancel_event rather than clearing it.
cancel_event = kwargs.pop("_cancel_event", None) or self._cancel_event
# An API-initiated load promises to download NOTHING: it may only open what is already cached. Read once here
# and threaded into every helper below -- the metadata probes as much as the fetches, since a model_info call
@@ -2039,7 +2039,7 @@ class VideoBackend:
base or str(getattr(fam, "base_repo", "") or ""),
te_quant_mode = text_encoder_quant,
# The selected card: an fp8 encoder the default card cannot take is still hosted pre-cast for the one this
- # load lands on
+ # load lands on, and vice versa.
target = (
resolve_diffusion_device_target()
if gpu_ordinal is None
@@ -3463,8 +3463,7 @@ class VideoBackend:
# Same fence unload() takes, raised BEFORE the barrier: a queued generation holds no cancel event, so the
# signal above cannot reach it and it would slip through the moment the barrier released _generate_lock.
self._teardown_waiters += 1
- # Barrier: wait for the signalled generation to exit before freeing the pipeline, else we report the VRAM free
- # while the clip still holds it. Teardown runs INSIDE the barrier: releasing first would hand out one last clip.
+ # Barrier: wait for the signalled generation to exit before teardown, or two models coexist in VRAM.
with self._generate_lock:
with self._lock:
try:
diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.py
index 5326b743a47..146a41b0011 100644
--- a/studio/backend/core/training/diffusion_checkpoint.py
+++ b/studio/backend/core/training/diffusion_checkpoint.py
@@ -1054,7 +1054,8 @@ def _prune_staging(root: Path) -> None:
except OSError:
return
- # Newest first, so a stacked slot gets its immediate predecessor back rather than whichever
+ # Newest first, so a stacked slot gets its immediate predecessor back rather than whichever entry the filesystem
+ # happened to list first.
def _written_at(path: Path) -> float:
try:
return path.stat().st_mtime
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 4a1c91f4848..7f95bd26848 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -1289,7 +1289,8 @@ def _ltx2_collate(
):
import torch
- # encode_prompt pads to max_sequence_length, so every connector embed is [1, 1024, 3840]
+ # encode_prompt pads to max_sequence_length, so every connector embed is [1, 1024, 3840] and a plain concat batches
+ # them; ``pad_to`` is moot.
video = torch.cat([e[0] for e in entries]).to(device = device, dtype = weight_dtype)
audio = torch.cat([e[1] for e in entries]).to(device = device, dtype = weight_dtype)
mask = torch.cat([e[2] for e in entries]).to(device)
@@ -2396,7 +2397,7 @@ def _train_dit(
steps_run = done if cfg.train_steps else 0,
wall_seconds = round(time.time() - t_start, 1),
resumed_from_step = resumed or None,
- # "Stop without saving" discards the run, so its own periodic checkpoints must not keep
+ # "Stop without saving" discards the run, so its own periodic checkpoints must not keep offering to continue it.
discarded = bool(stopped and not _save_on_stop()),
)
return str(out_dir)
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index aa4f81b08bb..8bc24dc9e29 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -954,6 +954,8 @@ class DiffusionLoraConfig:
# TF32 matmuls + cudnn autotuning for the run. Near-lossless; disable for strict bit-reproducibility A/Bs.
enable_tf32: bool = True
# DiT base transformer precision: "nf4" (bitsandbytes QLoRA, the memory floor and default), "bf16" (dense, fastest
+ # eager), "int8" (torchao weight-only), "fp8" (Ada/Hopper/Blackwell + compile) or "auto". Non-nf4 needs a dense
+ # base.
base_precision: str = "nf4"
# None resolves per family in normalized(); a number applies s*u/(1+(s-1)*u), and "auto" without
# dynamic shifting falls back to identity.
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index fec2390b36c..601f03b82eb 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -1597,7 +1597,7 @@ class TrainingBackend:
logger.warning("Training subprocess already running")
return False
- # Wait for pump thread to finish DB finalization (8s covers SQLite's 5s lock timeout).
+ # Join prior pump thread, refuse to start if it won't die
if self._pump_thread is not None and self._pump_thread.is_alive():
self._pump_thread.join(timeout = 5.0)
if self._pump_thread.is_alive():
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 3b7f9bc9d87..fcd73fa3a94 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -428,7 +428,8 @@ def _base_transformers_can_chat(
)
except Exception:
continue
- # A non-str is _CACHED_NO_EXIST ("we know it is absent here") or None ("unknown"),
+ # A non-str is _CACHED_NO_EXIST ("we know it is absent here") or None ("unknown"), and neither rules the base
+ # out of a different root.
if isinstance(found, str):
config_path = found
break
diff --git a/studio/backend/hub/services/models/companion_cleanup.py b/studio/backend/hub/services/models/companion_cleanup.py
index 856d5bac61f..22540e2358f 100644
--- a/studio/backend/hub/services/models/companion_cleanup.py
+++ b/studio/backend/hub/services/models/companion_cleanup.py
@@ -156,7 +156,8 @@ def _delete_impact_blocking(repo_id: str, variant: Optional[str]) -> dict:
for repo_info in repos:
reclaimed += _variant_bytes(repo_info, variant) if variant else _repo_blob_bytes(repo_info)
- # Would this delete leave the repo with no runnable checkpoint? Only then can its companions
+ # Would this delete leave the repo with no runnable checkpoint? Only then can its companions become reclaimable;
+ # while a sibling quant survives they stay in use.
removes_last_checkpoint = True
if variant:
for repo_info in repos:
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index d5731ac38e6..16624318f3d 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -75,9 +75,10 @@ _VARIANT_HASH_MAX = 512
# Blob hashes are derived from the same mutable remote revision metadata as variant requirements, so
# they must not outlive that freshness window.
_VARIANT_HASH_POS_TTL = 60.0
-# Refresh resolved variant requirements so a moved repo revision is picked up
+# Refresh resolved variant requirements so a moved repo revision is picked up within the session instead of being pinned
+# for the backend's lifetime.
_VARIANT_REQUIREMENT_POS_TTL = 60.0
-# Suppress retries on a metadata-fetch failure so a slow/flaky link doesn't
+# Suppress retries on a metadata-fetch failure so a slow/flaky link doesn't re-hammer the API on every page refresh.
_VARIANT_REQUIREMENT_NEG_TTL = 60.0
# Fail fast on a slow link so the variant render isn't blocked for seconds.
_GGUF_METADATA_TIMEOUT_SECONDS = 5.0
@@ -792,7 +793,8 @@ def _direct_gguf_split_is_whole(path: Path) -> bool:
try:
found = _indexes_beside(path, sibling)
if not found >= set(range(1, total + 1)) and path.is_symlink():
- # _local_gguf_load_path resolves siblings from the TARGET, so a renamed alias
+ # _local_gguf_load_path resolves siblings from the TARGET, so a renamed alias still loads the target's real
+ # set -- and a torn target stays torn.
return _target_set_is_whole(path.resolve())
except OSError:
return True
@@ -1588,7 +1590,8 @@ async def get_gguf_variants_answer(
requirement = requirements_by_quant.get(variant.quant.lower())
if requirement is None or not _repo_signals_apply_to(variant.quant):
continue
- # companion_hashes adds the MTP drafter (mmproj_hashes covers
+ # companion_hashes adds the MTP drafter (mmproj_hashes covers every mmproj precision in the repo, not
+ # just the planned one).
if (
(requirement.mmproj_hashes | requirement.companion_hashes) & incomplete_hashes
) and _filenames_cached(
diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.py
index 3f42de8bc92..4fa51ebdbb3 100644
--- a/studio/backend/hub/services/snapshot_progress.py
+++ b/studio/backend/hub/services/snapshot_progress.py
@@ -45,7 +45,7 @@ SnapshotExpectedFilesResolver = Callable[
# Supplied per repo kind, so this module keeps knowing nothing about quant labels.
VariantFileMatcher = Callable[[str], bool]
-# One progress log per 10% step per job, so an active download reports progress
+# One progress log per 10% step per job, so an active download reports progress without emitting a line on every poll.
_progress_step_lock = threading.Lock()
_last_progress_step: dict[str, int] = {}
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index 1c9f3843954..c1bcd39faad 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -1239,7 +1239,7 @@ class DownloadMetadata:
blob_hashes: frozenset[str] = field(default_factory = frozenset)
# Includes the shared mmproj companion for vision GGUF repos.
progress_blob_hashes: frozenset[str] = field(default_factory = frozenset)
- # Bytes already complete before this job started; not counted as this run's
+ # Bytes already complete before this job started; not counted as this run's progress.
completed_baseline_bytes: int = 0
hub_cache: Optional[str] = None
xet_cache: Optional[str] = None
@@ -1934,7 +1934,8 @@ class DownloadRegistry:
if proc.poll() is None
]
live_keys = {key for key, _proc, _metadata in live}
- # Flag as an intentional stop so the watcher's exit classification
+ # Flag as an intentional stop so the watcher's exit classification reports them cancelled rather than an
+ # OOM/crash once SIGKILL lands.
for key, _proc, _metadata in live:
if self._jobs.get(key, DownloadState("idle")).state == "running":
self._jobs[key] = DownloadState("cancelling")
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.py
index f57f012f39c..488f1e774b7 100644
--- a/studio/backend/loggers/handlers.py
+++ b/studio/backend/loggers/handlers.py
@@ -38,7 +38,8 @@ def _env_int(name: str, default: int) -> int:
# Collapse identical GET/2xx logs within the window, since the SPA fans one invalidation into many
# list fetches; mutations and errors always log.
_ACCESS_LOG_DEDUP_MS = _env_int("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", 300)
-# Liveness/UI polls whose line means only "still polling"; collapse to a longer
+# Liveness/UI polls whose line means only "still polling"; collapse to a longer heartbeat. First hit and errors still
+# log. 0 = off.
_QUIET_POLL_DEDUP_MS = _env_int("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", 10000)
# The desktop watchdog probe rounds are ~19s apart, so a 10s window that stamps only on emit would
# collapse nothing; it gets its own, wider window.
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index e7708841685..9fc92348e3d 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -436,7 +436,8 @@ async def test_mcp_server(
current_subject: str = Depends(get_current_subject),
via_api_key: ViaApiKey = False,
):
- # URL/header validation must surface as 400 like create/update
+ # URL/header validation must surface as 400 like create/update so the frontend's create-form pre-flight gets the
+ # same error semantics as the save call. Only catch transport/timeout errors below.
url = _validate_url(payload.url)
# Caller-supplied and unstored, so the gate has to land before
# list_tools_async -- after it the process has already started.
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 157ae0ca3a7..bcf52bc947e 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1589,7 +1589,13 @@ def _fill_target_id(target_id: str) -> str:
return target_id
-# One override write at a time. A save stores its target key and then reads the map back
+# One override write at a time. A save stores its target key and then reads the map back to retire the other spelling of
+# the same cached repo, and a remove clears up to four keys, each its own transaction: atomic on their own, but not as a
+# sequence. This route is a plain `def`, so FastAPI runs it in a threadpool, and two clients saving one quant under both
+# spellings (the repo id the picker sends and the snapshot path an upgraded install still holds) could each write before
+# either cleanup ran and then retire the other's row, leaving no override at all from two saves that both returned 200.
+# Serialize the whole handler instead: overrides are written by a settings edit, never on a hot path, and the server
+# runs one process.
_override_write_lock = threading.Lock()
@@ -1735,7 +1741,11 @@ def update_openai_auto_switch_override(
llama_extra_args = [],
max_seq_length = None,
)
- # The mirror image of the carry-over above: a save under repo:QUANT copies
+ # The mirror image of the carry-over above: a save under repo:QUANT copies the flags off a legacy bare
+ # `repo` entry and leaves it in place, and the loader falls back to it when the qualified key misses, so
+ # clearing only the qualified key hands the same flags straight back and the forget does nothing. Nothing in
+ # the UI can reach that bare entry. Only once it is nobody else's fallback, though: it backs every quant
+ # with no entry of its own, so forgetting Q4 must not strip Q8.
bare_id = _bare_model_id(payload.model_id)
if (
bare_id
@@ -2651,7 +2661,8 @@ def update_embedding_model(
# Fall back to the loader's own token so a gated/private repo is actually scanned
# (a token-less scan fails open for exactly the repo that would still load).
scan_token = hf_token or _ambient_hf_token()
- # Offline: subdir probes would hit the network and hang; the offline gate walks
+ # Offline: subdir probes would hit the network and hang; the offline gate walks the whole cached snapshot, so no
+ # load-subdir hints are needed.
if local_only_load:
load_subdirs = ()
else:
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index eb0cc6f0fab..a2c90a3f846 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -1499,7 +1499,8 @@ async def start_training(
"s3_config": request.s3_config.model_dump() if request.s3_config else None,
}
- # Latest-sidecar models size and train 16-bit (same flip as chat load): 4-bit is disabled
+ # Latest-sidecar models size and train 16-bit (same flip as chat load): 4-bit is disabled for brand-new
+ # architectures, so VRAM checks must not underestimate a load the worker refuses.
from core.training.provenance import (
ExactResumeResourcesUnavailable,
effective_training_load_in_4bit,
@@ -2847,7 +2848,9 @@ async def start_diffusion_training(
config["resume_from_checkpoint"] = str(
resolve_resume_dir(normalized_cfg.resume_from_checkpoint)
)
- # In epochs mode the real target is only known once the dataset size is; skip
+ # In epochs mode the real target is only known once the dataset size is; skip the "already finished" check
+ # here and make it below, with the resolved step count. Offloaded like the other preflights: validating a
+ # bundle parses a safetensors header and walks two torch-zip pickles, which must not block the event loop.
await asyncio.to_thread(
_preflight_diffusion_resume,
config,
@@ -3001,7 +3004,8 @@ async def list_diffusion_training_runs(
per-run records. Summaries only; fetch one run for its config + metric logs."""
from core.training.diffusion_training_service import list_diffusion_runs
- # Offloaded: each record's can_resume is re-derived by validating the checkpoint bundles
+ # Offloaded: each record's can_resume is re-derived by validating the checkpoint bundles on disk (safetensors header
+ # + torch-zip pickle walk per file), which must not block the loop.
records = await asyncio.to_thread(list_diffusion_runs, limit = limit)
summaries: list[DiffusionTrainingRunSummary] = []
for r in records:
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index cd11b3a5440..8d72628ef57 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -331,6 +331,8 @@ async def load_video_model_gated(
if device != "cpu":
# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts VIDEO
+ # before the load is marked, finds nothing to cancel, and both allocate at once. The training admission
+ # wraps the same span.
from routes.inference import _diffusion_training_admission
def _acquire_and_begin():
with _diffusion_training_admission():
diff --git a/studio/backend/storage/api_usage_db.py b/studio/backend/storage/api_usage_db.py
index ba36fd759e9..5f8f7cbac2e 100644
--- a/studio/backend/storage/api_usage_db.py
+++ b/studio/backend/storage/api_usage_db.py
@@ -211,7 +211,8 @@ class ApiUsageWriter:
if not self._stopped:
self._stopped = True
self._queue.put_nowait(_STOP)
- # Production calls this through asyncio.to_thread so even the bounded
+ # Production calls this through asyncio.to_thread so even the bounded wait cannot pause inference or the event
+ # loop.
self._thread.join(timeout = max(0.0, timeout))
drained = not self._thread.is_alive()
if not drained:
diff --git a/studio/backend/storage/profile_stats_db.py b/studio/backend/storage/profile_stats_db.py
index ba109cac443..bed1101034f 100644
--- a/studio/backend/storage/profile_stats_db.py
+++ b/studio/backend/storage/profile_stats_db.py
@@ -226,7 +226,7 @@ def _fold_api_usage(conn, zone, subject: str) -> _ApiUsageFold:
total_tokens = _as_int(row["total_tokens"])
fold.prompt_tokens += prompt_tokens
fold.completion_tokens += completion_tokens
- # Preserve the provider's authoritative total even when it differs
+ # Preserve the provider's authoritative total even when it differs from the input/output sum.
fold.total_tokens += total_tokens
fold.requests += 1
@@ -364,7 +364,8 @@ def _fold_messages(conn, zone) -> _MessageFold:
# single conversation, so counting them twice inflates the chat total.
conversation_id = row["pair_id"] or thread_id
- # A fork is its own visible conversation, so it counts towards the chat
+ # A fork is its own visible conversation, so it counts towards the chat total from the moment it exists, before
+ # any new turn is added.
fold.threads.add(conversation_id)
# Forking clones the whole ancestry keeping each copy's timestamp, so skip a clone while the row
@@ -588,7 +589,8 @@ def _training_stats(conn) -> dict[str, Any]:
"recent": [
{
"id": item["id"],
- # A renamed run keeps the name the user gave it; otherwise fall
+ # A renamed run keeps the name the user gave it; otherwise fall back to the short model label rather
+ # than the full repo id.
"name": _clean_str(item["display_name"]) or _model_label(item["model_name"] or ""),
"modelLabel": _model_label(item["model_name"] or ""),
"datasetLabel": _model_label(item["dataset_name"] or ""),
diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.py
index 7384a3424a2..7d2bc882de1 100644
--- a/studio/backend/utils/hardware/amd.py
+++ b/studio/backend/utils/hardware/amd.py
@@ -42,7 +42,8 @@ def _path_inside_venv(path: str) -> bool:
try:
# realpath (not abspath): resolve symlinks/8.3 names so an aliased venv matches.
root = os.path.normcase(os.path.realpath(sys.prefix))
- # Guard a root-dir prefix (C:\ or /): commonpath would match every path
+ # Guard a root-dir prefix (C:\ or /): commonpath would match every path on it. A venv is never at root, so treat
+ # that as outside.
if os.path.dirname(root) == root:
return False
return os.path.normcase(os.path.commonpath([os.path.realpath(path), root])) == root
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index c3cebd022b7..52d4f211406 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -503,7 +503,7 @@ def maybe_auto_start_lan_access(app) -> bool:
try:
start_lan_access(app)
except Exception as exc:
- # an optional preference must never take the whole server down
+ # an optional preference must never take the whole server down with it
logger.info("LAN access auto-start skipped: %s", exc)
return False
return True
diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.py
index f07e7f7fc7d..56559e8e1c2 100644
--- a/studio/backend/utils/llama_cpp_freshness.py
+++ b/studio/backend/utils/llama_cpp_freshness.py
@@ -121,7 +121,8 @@ def update_download_size_bytes(
installed_asset = marker.get("asset")
if not isinstance(installed_asset, str):
return None
- # Tag-independent platform suffix: accept the fork's "app-*" bundles
+ # Tag-independent platform suffix: accept the fork's "app-*" bundles and the upstream ggml-org "ubuntu-*"/"win-*"
+ # prebuilts ("windows" before "win").
m = re.search(r"-((?:linux|ubuntu|windows|win|macos|darwin)-.*)$", installed_asset)
if not m:
return None
diff --git a/studio/backend/utils/model_memory_settings.py b/studio/backend/utils/model_memory_settings.py
index b1d037ea978..2706c08508b 100644
--- a/studio/backend/utils/model_memory_settings.py
+++ b/studio/backend/utils/model_memory_settings.py
@@ -30,7 +30,8 @@ DEFAULT_NO_RAM_RESERVE = False
_CACHE_TTL_S = 2.0
_cache_lock = threading.Lock()
_cache: dict[str, tuple[float, Any]] = {}
-# Bumped on every write. A read that began before a write must not fill
+# Bumped on every write. A read that began before a write must not fill the cache with the value it already fetched, or
+# the new setting would appear to revert for the rest of the TTL and a load could launch contradicting it.
_generation: dict[str, int] = {}
diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.py
index bc66e21870b..5d133cbeb30 100644
--- a/studio/backend/utils/models/gguf_metadata.py
+++ b/studio/backend/utils/models/gguf_metadata.py
@@ -314,7 +314,7 @@ def _parse_gguf_staged_dims(path: str) -> Optional[Dict[str, Optional[int]]]:
return None
ctx = vals.get("context_length")
block = vals.get("block_count")
- # A real context/layer count is positive; treat 0/garbage as absent
+ # A real context/layer count is positive; treat 0/garbage as absent so the UI never builds a slider with max < min.
context_length = ctx if ctx and ctx > 0 else None
layer_count = block if block and block > 0 else None
# MoE layer count = block_count - leading dense layers, only when experts
diff --git a/studio/backend/utils/node_runtime.py b/studio/backend/utils/node_runtime.py
index 0d587abdf61..a2546e4883e 100644
--- a/studio/backend/utils/node_runtime.py
+++ b/studio/backend/utils/node_runtime.py
@@ -94,7 +94,8 @@ def managed_node_bin_dir() -> Path | None:
return None
-# Success-only memoization, like _resolved_node: the installer may finish
+# Success-only memoization, like _resolved_node: the installer may finish after the first probe, so a negative verdict
+# must not stick until restart.
_managed_node_ok: bool = False
_usable_node_cache: dict[tuple[str, str | None], bool] = {}
diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.py
index b504e32ffe5..cab1110bf37 100644
--- a/studio/backend/utils/prebuilt/freshness_flow.py
+++ b/studio/backend/utils/prebuilt/freshness_flow.py
@@ -24,7 +24,7 @@ logger = structlog.get_logger(__name__)
# 24h TTL keeps the GitHub call off the hot path and within rate limits.
RELEASE_CACHE_TTL_SECONDS = 24 * 60 * 60
-# Briefly memoize failed lookups so recurring status reads do not retry
+# Briefly memoize failed lookups so recurring status reads do not retry an unreachable GitHub endpoint on every request.
RELEASE_FAILURE_CACHE_TTL_SECONDS = 60
diff --git a/studio/backend/utils/prebuilt/update_flow.py b/studio/backend/utils/prebuilt/update_flow.py
index be2b255a226..cad61f09350 100644
--- a/studio/backend/utils/prebuilt/update_flow.py
+++ b/studio/backend/utils/prebuilt/update_flow.py
@@ -528,7 +528,8 @@ def stream_installer(
hint_lines.append(line)
child = child_line
if child is not None:
- # Recorded while it runs and dropped when the installer says
+ # Recorded while it runs and dropped when the installer says it stopped; one it never got to report
+ # stays for the sweep.
started, child_pid = child.group(1) == "started", int(child.group(2))
if started:
adopt_pid(child_pid)
diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py
index 608dddec960..330736781a4 100644
--- a/studio/backend/utils/process_lifetime.py
+++ b/studio/backend/utils/process_lifetime.py
@@ -498,7 +498,8 @@ def _pid_identity(pid: int) -> Optional[str]:
except Exception:
return None
if _is_windows():
- # Creation time, so a recycled pid is never mistaken for the child
+ # Creation time, so a recycled pid is never mistaken for the child that was recorded. Same purpose as starttime
+ # on Linux.
try:
import ctypes
from ctypes import wintypes
diff --git a/studio/backend/utils/torch_device_probe.py b/studio/backend/utils/torch_device_probe.py
index 80050ed1508..9b486cc5540 100644
--- a/studio/backend/utils/torch_device_probe.py
+++ b/studio/backend/utils/torch_device_probe.py
@@ -247,7 +247,8 @@ def _device_can_allocate_cached(device: str, _identity: tuple[str | None, ...])
encoding = "utf-8",
errors = "replace",
env = utf8_child_env(env),
- # No child_popen_kwargs() here. Its Linux preexec_fn can deadlock
+ # No child_popen_kwargs() here. Its Linux preexec_fn can deadlock when this multithreaded backend forks and
+ # executes Python before exec.
**windows_hidden_subprocess_kwargs(),
)
except Exception: # noqa: BLE001 - no child ran, so nothing was proven
diff --git a/studio/backend/utils/whisper_cpp_update.py b/studio/backend/utils/whisper_cpp_update.py
index 11ebd76db8a..33b657cfe27 100644
--- a/studio/backend/utils/whisper_cpp_update.py
+++ b/studio/backend/utils/whisper_cpp_update.py
@@ -232,7 +232,8 @@ def get_update_status(*, force_refresh: bool = False) -> dict:
force_refresh bypasses the 24h release cache for an explicit "check now".
"""
binary = _find_binary()
- # A locally-linked whisper.cpp dir is the user's own tree; never offer
+ # A locally-linked whisper.cpp dir is the user's own tree; never offer to replace it. Bail before any
+ # network/freshness work.
if _active_install_is_local_link(binary):
return _local_link_status()
marker = read_install_marker(binary)
diff --git a/studio/install_manifest.py b/studio/install_manifest.py
index 7614ac51db1..7b773ef7550 100644
--- a/studio/install_manifest.py
+++ b/studio/install_manifest.py
@@ -297,7 +297,8 @@ def write_manifest(
# `unsloth studio update` would otherwise reinstall torch into a GGUF-only venv.
if no_torch is not None:
payload["no_torch"] = bool(no_torch)
- # The FLAVOR, never the index URL it came from: a pinned index can carry a token
+ # The FLAVOR, never the index URL it came from: a pinned index can carry a token in its userinfo, query or fragment,
+ # and this file lives in the venv and is read back by verify-install, desktop-capabilities and the setup fast path.
if expected_torch_tag:
payload["expected_torch_tag"] = str(expected_torch_tag).strip().lower()
# Whether that flavor was NAMED by whoever ran the install, or merely what the selection
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index 5cabd37950d..42c3a03aaff 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -170,7 +170,8 @@ def _write_install_record(
rec["ships_server"] = ships_server
_INSTALLED_SHIPS_SERVER_MEMO[str(root)] = ships_server
else:
- # An install that did not report the capability must not leave an older memo standing
+ # An install that did not report the capability must not leave an older memo standing in for this one -- the
+ # tree is now whatever this bundle put there.
_INSTALLED_SHIPS_SERVER_MEMO.pop(str(root), None)
try:
with open(root / INSTALL_RECORD, "w", encoding = "utf-8") as f:
@@ -530,7 +531,9 @@ _MAX_LINK_TARGET_BYTES = 4096
_MAX_LINK_DEPTH = 40
-# Creators whose ``external_attr`` high bits are a Unix ``st_mode``: 3 (Info-ZIP, CPython)
+# Creators whose ``external_attr`` high bits are a Unix ``st_mode``: 3 (Info-ZIP, CPython) and 19 (Apple's ditto, same
+# layout). FAT and NTFS keep DOS attribute flags there, so reading a mode out of one would invent symlinks the archive
+# never described.
_UNIX_CREATORS = (3, 19)
@@ -622,7 +625,8 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
plain: list[zipfile.ZipInfo] = []
written: list[tuple[Path, str]] = []
for member in zf.infolist():
- # extractall DROPS ".." instead of cancelling the component before it, so "a/.." is "a"
+ # extractall DROPS ".." instead of cancelling the component before it, so "a/.." is "a" to it and normalising
+ # here would check a path it never writes. No release ships one.
if ".." in PurePosixPath(member.filename).parts:
raise RuntimeError(f"unsafe path in archive: {member.filename!r}")
# Lexical, never resolve()d: extraction MERGES.
@@ -668,7 +672,9 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
raise RuntimeError(f"symlink onto a reserved installer path: {member.filename!r}")
if key.is_dir() and not key.is_symlink():
raise RuntimeError(f"symlink member collides with a directory: {member.filename!r}")
- # Chains are normal (libwebp.so -> .so.7 -> .so.7.2.0) but must terminate: a cycle installs
+ # Chains are normal (libwebp.so -> .so.7 -> .so.7.2.0) but must terminate: a cycle installs a library nothing can
+ # read, so every load reinstalls it. Walk the graph the tree WILL have, keyed by landing point so alias/a and real/b
+ # count as one cycle.
by_dest = {str(keys[str(d)]): t for d, t, _ in links}
for dest, _, member in links:
seen, cur, hops = set(), str(keys[str(dest)]), 0
@@ -687,7 +693,8 @@ def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
if hops > _MAX_LINK_DEPTH:
raise RuntimeError(f"symlink chain too deep in archive: {member.filename!r}")
nxt = Path(os.path.normpath(os.path.join(os.path.dirname(cur), nxt)))
- # a -> a/x never reaches a second node, so repetition never fires, yet resolving
+ # a -> a/x never reaches a second node, so repetition never fires, yet resolving a walks a again. Anything
+ # under the link is a loop.
if Path(cur) in nxt.parents:
raise RuntimeError(f"symlink cycle in archive: {member.filename!r}")
cur = str(_plan_key(nxt, base, replaced, archive))
diff --git a/studio/scripts/unsloth_freeze_report.py b/studio/scripts/unsloth_freeze_report.py
index 9d2dd0187b4..52fd9ac3586 100644
--- a/studio/scripts/unsloth_freeze_report.py
+++ b/studio/scripts/unsloth_freeze_report.py
@@ -75,7 +75,8 @@ LIVENESS = re.compile(r"/api/liveness")
SESSION = re.compile(r"/api/auth/(?:status|login|logout|refresh)\b")
# Printed by the desktop shell (main.rs) before anything else, through a stderr logger
SHELL_STARTED = re.compile(r"Unsloth desktop app starting")
-# `{reason}; set VAR=1 VAR2=1 for WebKitGTK compatibility`, the app's own record
+# `{reason}; set VAR=1 VAR2=1 for WebKitGTK compatibility`, the app's own record of the renderer workaround it chose for
+# itself.
RENDERER_APPLIED = re.compile(r"set ((?:[A-Za-z_][A-Za-z_0-9]*=1\s*)+)for WebKitGTK compatibility")
# Overridable so CI can exercise this script end to end in a couple of minutes.
@@ -491,7 +492,8 @@ def classify(
return f"CRASHED: the app exited on its own (code {exited})"
if n_mon == 0 and n_live == 0:
- # Do not guess the cause: the preflight line the app already printed says
+ # Do not guess the cause: the preflight line the app already printed says which of the two it is, and naming the
+ # wrong one sends the user off fixing nothing.
if not preflight and not shell_started:
reason = (
"the desktop shell never started. If you launched `unsloth studio`, that "
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index f8b6b1ffa6f..6e10f24f27f 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -3724,10 +3724,8 @@ def patch_peft_fast_inference(model):
model.load_lora = functools.partial(load_lora, model)
- # Without an engine there was no `save_lora` at all, and `save_lora` needs none: it is `save_pretrained`
- # over the adapter. Gating it on the engine gave `fast_inference = False` GRPO runs `AttributeError:
- # 'Lfm2ForCausalLM' object has no attribute 'save_lora'`. Set only when absent, so a model carrying its
- # own keeps it.
+ # An engine keeps the Zoo helper it has always had: vLLM reads the saved adapter back through its own LoRA
+ # loader, so what that file may carry is its call, not one to change here.
if not hasattr(model, "save_lora"):
try:
from unsloth_zoo.vllm_utils import save_lora
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 64fba41b818..f339146a129 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -2740,8 +2740,7 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
)
extra_args += max_length_check
- # Sync chat_template from processing_class to vLLM's tokenizer This fixes base models that have custom chat
- # templates applied after loading
+ # Enable for training and move padding side of tokenizer to right
if "model" in call_args:
training_check = (
"if model is not None and hasattr(model, 'for_training'):\n"
diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.py
index d073bf54bcb..31749818f31 100644
--- a/unsloth/tokenizer_utils.py
+++ b/unsloth/tokenizer_utils.py
@@ -1665,7 +1665,7 @@ def patch_sft_trainer_tokenizer():
"fix_zero_training_loss(self.model, tokenizer, self.train_dataset)\n\n"
)
- # Also DPO weirdly tokenizes non numeric columns? Delete them!
+ # Warn on gradient accumulation steps if it's used
check_text += (
"\n"
"try:\n"