Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep unsloth start alive while a LoRA adapter's base model downloads (#10550)
Nilayfd1ddeb4a42d
diff --git a/studio/backend/core/inference/audio_codecs.py b/studio/backend/core/inference/audio_codecs.pyindex b6dc11bcc4a..876eaf45f87 100644--- a/studio/backend/core/inference/audio_codecs.py+++ b/studio/backend/core/inference/audio_codecs.py@@ -22,6 +22,8 @@ import numpy as npimport torchfrom utils.third_party_source import (+ SNAC_REPOSITORY,+ SPARK_TTS_REPOSITORY,deactivate_pinned_package,ensure_dac_speech_weights,ensure_outetts_source,@@ -31,7 +33,7 @@ from utils.third_party_source import ()logger = get_logger(__name__)-_SPARK_TTS_REPO = "unsloth/Spark-TTS-0.5B"+_SPARK_TTS_REPO = SPARK_TTS_REPOSITORY_MAX_SPARK_EXPORT_METADATA_BYTES = 1_000_000@@ -175,7 +177,7 @@ class AudioCodecManager:# Route weights to the selected cache; this can run in the main process.self._snac_model = (SNAC.from_pretrained(- model_repo_path or "hubertsiuzdak/snac_24khz",+ model_repo_path or SNAC_REPOSITORY,cache_dir = active_hf_hub_cache(),).to(device)diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex ac1c715f2ba..65399c1b681 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -388,6 +388,9 @@ class InferenceOrchestrator:routes/inference.py needs minimal changes); all heavy ML work happens in a persistentsubprocess."""+ # Registry keys of the downloads the in-flight load announced; released when the load ends.+ _load_download_keys: Sequence[str] = ()+def __init__(self):self._proc: Optional[mp.Process] = None# Retired when the next worker is spawned; read long after _proc has been cleared.@@ -1223,6 +1226,11 @@ class InferenceOrchestrator:deadline = time.monotonic() + timeoutcontinue+ if rtype == "downloads":+ self._claim_load_downloads(resp)+ deadline = time.monotonic() + timeout+ continue+if rtype == "stall":msg = resp.get("message", "Download stalled")logger.warning("Subprocess reported stall: %s", msg)@@ -2260,6 +2268,31 @@ class InferenceOrchestrator:except Exception as teardown_exc:logger.warning("Could not shut the failed load's worker down: %s", teardown_exc)raise+ finally:+ self._release_load_downloads()++ def _claim_load_downloads(self, resp: dict) -> None:+ from hub.services.load_downloads import claim_load_downloads+ self._release_load_downloads()+ try:+ self._load_download_keys = claim_load_downloads(+ resp.get("repo_ids") or [],+ xet_disabled = bool(resp.get("xet_disabled")),+ hub_cache = resp.get("hub_cache"),+ )+ except Exception as exc:+ logger.warning("Could not register the load's downloads: %s", exc)++ def _release_load_downloads(self) -> None:+ keys, self._load_download_keys = self._load_download_keys, []+ if not keys:+ return+ from hub.services.load_downloads import release_load_downloads++ try:+ release_load_downloads(keys)+ except Exception as exc:+ logger.warning("Could not release the load's downloads: %s", exc)def cancel_load(self, model_name: str) -> bool:"""Abort an in-flight load by terminating its subprocess. Returns True if a load fordiff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 2e58d7e5f1c..70c44c563fe 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -510,6 +510,60 @@ def _worker_reclaimable_gpu_gb(config: dict) -> dict[str, float] | None:return None+def _load_download_repos(+ mc,+ load_in_4bit: bool,+ backend,+ companions = (),+) -> list[str]:+ from hub.utils.paths import is_valid_repo_id+ from utils.paths import is_local_path+ from utils.security.file_security import load_scan_target+ from utils.third_party_source import SPEECH_CODEC_REPOSITORIES++ audio_type = getattr(mc, "audio_type", None)+ repos = [str(mc.identifier), *(str(repo) for repo in companions)]+ base = getattr(mc, "base_model", None)+ if base:+ repos.append(str(base))+ mapped = None+ if getattr(backend, "device", None) == "mlx":+ from core.inference.model_ids import mlx_bnb_base_repo+ mapped = mlx_bnb_base_repo(str(base))+ else:+ try:+ from unsloth.models import loader+ from unsloth.models.loader_utils import get_model_name++ quantized = (+ load_in_4bit+ and not getattr(mc, "is_audio", False)+ and getattr(loader, "ALLOW_BITSANDBYTES", True)+ )+ mapped = get_model_name(str(base), load_in_4bit = quantized)+ if mapped and not getattr(loader, "ALLOW_PREQUANTIZED_MODELS", True):+ mapped = loader._strip_unsloth_bnb_4bit_suffix(mapped)+ except Exception:+ mapped = None+ if mapped:+ repos.append(str(mapped))+ repos.extend(SPEECH_CODEC_REPOSITORIES.get(audio_type, ()))+ hub_ids: list[str] = []+ for repo in repos:+ repo, _subdirs = load_scan_target(repo, ())+ if is_valid_repo_id(repo) and not is_local_path(repo) and repo not in hub_ids:+ hub_ids.append(repo)+ return hub_ids+++def _hub_cache_dir() -> Optional[str]:+ try:+ from utils.hf_cache_settings import get_hf_cache_paths+ return str(get_hf_cache_paths().hub_cache)+ except Exception:+ return None++# The token env before a load scrubbed it; the next load restores it._TOKEN_ENV_BEFORE_ANONYMOUS_LOAD: Optional[dict] = None@@ -649,6 +703,15 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:},)+ _send_response(+ resp_queue,+ {+ "type": "downloads",+ "repo_ids": _load_download_repos(mc, load_in_4bit, backend, targets),+ "xet_disabled": os.environ.get("HF_HUB_DISABLE_XET") == "1",+ "hub_cache": _hub_cache_dir(),+ },+ )heartbeat_stop = start_watchdog(repo_ids = watch_repos,on_stall = lambda msg: _send_response(resp_queue, {"type": "stall", "message": msg}),diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.pyindex 88360cf6e5c..bf73ed444d1 100644--- a/studio/backend/hub/schemas/downloads.py+++ b/studio/backend/hub/schemas/downloads.py@@ -105,6 +105,8 @@ class ActiveDownload(BaseModel):variant: Optional[str] = Nonetransport: Optional[str] = Nonecancel_transport: Optional[str] = None+ owner: Optional[str] = None+ load_attached: Optional[bool] = Nonestate: strfiles: Optional[List[str]] = Field(None,diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex 9649702a9e0..3577b95ec5e 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -1641,6 +1641,8 @@ def active_download_refs(cancel_transport = (metadata.cancel_marker_transport if metadata is not None else None),+ owner = metadata.owner if metadata is not None else None,+ load_attached = metadata.load_attached if metadata is not None else None,state = ref.state,generation = ref.generation,files = scoped_files or None,diff --git a/studio/backend/hub/services/load_downloads.py b/studio/backend/hub/services/load_downloads.pynew file mode 100644index 00000000000..cceac2864e9--- /dev/null+++ b/studio/backend/hub/services/load_downloads.py@@ -0,0 +1,60 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from typing import Optional, Sequence++from hub.services import download_lifecycle+from hub.utils import download_registry+from hub.utils.hf_cache_state import TRANSPORT_HTTP, TRANSPORT_XET++LOAD_OWNER = "load"+_ACTIVE = ("running", "cancelling")+++def _job_key(repo_id: str) -> str:+ return download_registry.normalize_job_key(f"{download_registry.normalize_repo_key(repo_id)}::")+++def is_load_owned(registry: download_registry.DownloadRegistry, key: str) -> bool:+ metadata = registry.get_job_metadata(key)+ if metadata is None or metadata.owner != LOAD_OWNER:+ return False+ return registry.get_job(key).state in _ACTIVE+++def claim_load_downloads(+ repo_ids: Sequence[str],+ *,+ xet_disabled: bool = False,+ hub_cache: Optional[str] = None,+) -> list[str]:+ registry = download_registry.get_models_registry()+ transport = TRANSPORT_HTTP if xet_disabled else TRANSPORT_XET+ keys: list[str] = []+ for repo_id in repo_ids:+ key = _job_key(repo_id)+ accepted, _state = registry.claim(+ key,+ transport,+ repo_type = "model",+ repo_id = repo_id,+ hub_cache = hub_cache,+ owner = LOAD_OWNER,+ )+ if accepted:+ # The load runs as its caller, so a managed account sees its own load's downloads.+ download_lifecycle.record_download_account(registry, key)+ keys.append(key)+ continue+ for ref in registry.active_job_refs(repo_id):+ registry.mark_load_attached(ref.key, True)+ if ref.key not in keys:+ keys.append(ref.key)+ return keys+++def release_load_downloads(keys: Sequence[str]) -> None:+ registry = download_registry.get_models_registry()+ for key in keys:+ if not registry.release_owned(key, LOAD_OWNER):+ registry.mark_load_attached(key, False)diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 5fe319ce0e2..08d24cc21e4 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -31,6 +31,7 @@ from hub.utils.paths import ()from hub.services import snapshot_progressfrom hub.services import download_lifecycle+from hub.services import load_downloadsfrom hub.services.models import account_access, cache_inventory, gguf_variantslogger = get_logger(__name__)@@ -150,6 +151,17 @@ def _reject_if_load_in_flight(repo_id: str) -> None:raise _load_in_flight_error(repo_id)+def _reject_if_load_owned(key: str) -> None:+ if load_downloads.is_load_owned(_registry, key):+ raise HTTPException(+ status_code = 409,+ detail = (+ "A model load is fetching this repo. Wait for the load to finish "+ "(or cancel it), then start the download."+ ),+ )++def _spawn_download_worker(repo_id: str,variant: Optional[str],@@ -226,6 +238,7 @@ async def download_model_response(raise HTTPException(status_code = 400, detail = f"Invalid scope_id: {body.scope_id!r}")variant = scope_variantkey = _download_job_key(repo_id, variant)+ _reject_if_load_owned(key)# Size and Auto resolution may perform network probes, so keep both off the event loop.largest_file_bytes = await asyncio.to_thread(download_lifecycle.largest_download_file_bytes,@@ -328,6 +341,7 @@ async def download_model_response(),)# claim_state is the blocking job's state. Attaching and accepting are one verdict: only this key's own in-flight job can be joined, and a cross-variant conflict or in-progress delete joined nothing.+ _reject_if_load_owned(key)adoptable = _registry.adoptable(key)return {"job_key": key,@@ -429,6 +443,11 @@ async def cancel_download_model_response(body: CancelDownloadRequest):detail = f"Invalid gguf_variant: {variant!r}",)key = _download_job_key(repo_id, variant)+ if load_downloads.is_load_owned(_registry, key):+ raise HTTPException(+ status_code = 409,+ detail = "This repo is being fetched by a model load; cancel the load instead.",+ )state = download_lifecycle.cancel_worker(_registry,diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 35f48f990e1..9704d0246de 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -5336,6 +5336,9 @@ def test_model_download_records_completed_baseline_for_new_gguf_variant(monkeypa)class _Registry:+ def get_job_metadata(self, _key):+ return None+claim_kwargs = Nonedef claim(self, _key, _transport, **kwargs):@@ -5418,6 +5421,9 @@ def test_gguf_model_download_skips_completed_baseline_for_variant_resume_state()class _Registry:+ def get_job_metadata(self, _key):+ return None+claim_kwargs = Nonedef claim(self, _key, _transport, **kwargs):@@ -5610,6 +5616,9 @@ def test_model_claim_register_cancel_uses_registry_marker_owner(monkeypatch):killed = []class _Registry:+ def get_job_metadata(self, _key):+ return None+def claim(self, *_args, **_kwargs):return True, "running"@@ -5655,6 +5664,9 @@ def test_model_cancel_registered_worker_requests_and_kills(monkeypatch):events.append(("kill",))class _Registry:+ def get_job_metadata(self, _key):+ return None+def get_process(self, _key):return _Proc()@@ -5693,6 +5705,9 @@ def test_model_download_watcher_invalidates_hf_cache_scan(monkeypatch):invalidated = []class _Registry:+ def get_job_metadata(self, _key):+ return None+def claim(self, *_args, **_kwargs):return True, "running"diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex 9bc2d418a5d..6c4289e2634 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -1140,6 +1140,8 @@ class DownloadMetadata:xet_cache: Optional[str] = None# Scoped jobs only: the exact files to fetch, kept so the XET -> HTTP retry respawns the same scoped download.scoped_files: tuple[str, ...] = ()+ owner: Optional[str] = None+ load_attached: bool = False@dataclass(frozen = True)@@ -1328,6 +1330,34 @@ class DownloadRegistry:returnself._metadata[key] = replace(metadata, transport = transport)+ def release_owned(self, key: str, owner: str) -> bool:+ key = normalize_job_key(key)+ with self._lock:+ metadata = self._metadata.get(key)+ if metadata is None or metadata.owner != owner:+ return False+ if self._jobs.get(key, DownloadState("idle")).state not in _ACTIVE_STATES:+ return False+ self._jobs[key] = DownloadState("idle")+ self._discard_active_locked(key)+ return True++ def _discard_active_locked(self, key: str) -> None:+ repo = _repo_of_key(key)+ active = self._repo_active.get(repo)+ if active is not None:+ active.discard(key)+ if not active:+ self._repo_active.pop(repo, None)++ def mark_load_attached(self, key: str, attached: bool) -> None:+ key = normalize_job_key(key)+ with self._lock:+ metadata = self._metadata.get(key)+ if metadata is None or metadata.load_attached == attached:+ return+ self._metadata[key] = replace(metadata, load_attached = attached)+def release_active_slot(self, key: str) -> None:key = normalize_job_key(key)repo = _repo_of_key(key)@@ -1469,6 +1499,7 @@ class DownloadRegistry:hub_cache: Optional[str] = None,xet_cache: Optional[str] = None,scoped_files: Optional[Sequence[str]] = None,+ owner: Optional[str] = None,) -> tuple[bool, str]:key = normalize_job_key(key)repo = _repo_of_key(key)@@ -1533,6 +1564,7 @@ class DownloadRegistry:else:self._generations[key] = generationself._attempts[key] = self._attempts.get(key, 1) + 1+ previous = self._metadata.get(key) if current in _ACTIVE_STATES else Noneself._jobs[key] = DownloadState("running")self._repo_active.setdefault(repo, active).add(key)if repo_type and repo_id:@@ -1551,6 +1583,8 @@ class DownloadRegistry:hub_cache = hub_cache,xet_cache = xet_cache,scoped_files = tuple(scoped_files or ()),+ owner = owner,+ load_attached = previous.load_attached if previous is not None else False,)if cancel_marker_transport is not None:self._cancel_marker_transports[key] = cancel_marker_transport@@ -1590,6 +1624,9 @@ class DownloadRegistry:"""True when *key* itself has a live job a client can attach to. Lets a rejected claim distinguish a collision with this key's own in-flight job (pollable) from one blocked by a different repo job or an in-progress delete, where no job exists for this key."""key = normalize_job_key(key)with self._lock:+ metadata = self._metadata.get(key)+ if metadata is not None and metadata.owner is not None:+ return Falsereturn self._jobs.get(key, DownloadState("idle")).state in _ACTIVE_STATESdef _active_job_variant_locked(self, key: str) -> Optional[str]:@@ -1811,6 +1848,11 @@ class DownloadRegistry:for key, job in list(self._jobs.items()):if job.state not in _ACTIVE_STATES or key in live_keys:continue+ placeholder = self._metadata.get(key)+ if placeholder is not None and placeholder.owner is not None:+ self._jobs[key] = DownloadState("idle")+ self._discard_active_locked(key)+ continueproc = self._processes.get(key)if proc is not None:if proc.poll() == 0:diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex f6359e0181d..7406c8de75a 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -1151,6 +1151,9 @@ class TestLoadHubDownloadExclusion:return frozenset()class _Registry:+ def get_job_metadata(self, _key):+ return None+def claim(self, *_args, admission_check, **_kwargs):assert admission_check() is Falsereturn False, "admission_blocked"diff --git a/studio/backend/tests/test_load_downloads.py b/studio/backend/tests/test_load_downloads.pynew file mode 100644index 00000000000..f131a2318b7--- /dev/null+++ b/studio/backend/tests/test_load_downloads.py@@ -0,0 +1,257 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from fastapi import HTTPException++from hub.schemas.downloads import CancelDownloadRequest+from hub.services import download_lifecycle, load_downloads+from hub.utils import download_registry+from hub.utils.download_registry import DownloadRegistry+++def registry(monkeypatch):+ fresh = DownloadRegistry()+ monkeypatch.setattr(download_registry, "get_models_registry", lambda: fresh)+ return fresh+++def _active(registry):+ return [+ (ref.repo_id, ref.owner, ref.state)+ for ref in download_lifecycle.active_download_refs(registry, None, with_variant = False)+ ]+++def test_a_load_claims_running_jobs_the_active_list_reports(registry):+ keys = load_downloads.claim_load_downloads(+ ["owner/adapter", "Owner/Base"],+ xet_disabled = True,+ hub_cache = "/cache/hub",+ )++ assert len(keys) == 2+ assert sorted(_active(registry)) == [+ ("Owner/Base", "load", "running"),+ ("owner/adapter", "load", "running"),+ ]+ metadata = registry.get_job_metadata(keys[1])+ assert metadata.hub_cache == "/cache/hub"+ assert metadata.transport == "http"++ load_downloads.release_load_downloads(keys)++ assert _active(registry) == []+ assert registry.get_job(keys[0]).state == "idle"+ assert registry._repo_active == {}+ assert registry.claim(keys[0], "http", repo_type = "model", repo_id = "owner/adapter")[0]+++def test_release_leaves_a_job_another_owner_took_over(registry):+ keys = load_downloads.claim_load_downloads(["owner/base"])+ assert registry.release_owned(keys[0], load_downloads.LOAD_OWNER)+ assert registry.claim("owner/base::", "http", repo_type = "model", repo_id = "owner/base")[0]++ load_downloads.release_load_downloads(keys)++ assert registry.get_job("owner/base::").state == "running"+ assert registry._repo_active == {"owner/base": {"owner/base::"}}+++def test_a_load_attaches_to_a_hub_download_of_the_same_repo(registry):+ assert registry.claim("owner/base::", "xet", repo_type = "model", repo_id = "owner/base")[0]++ keys = load_downloads.claim_load_downloads(["owner/base"])++ assert keys == ["owner/base::"]+ ref = download_lifecycle.active_download_refs(registry, None, with_variant = False)[0]+ assert (ref.owner, ref.load_attached) == (None, True)+ assert not load_downloads.is_load_owned(registry, "owner/base::")+ # A Xet -> HTTP retry keeps the attachment.+ assert registry.claim(+ "owner/base::", "http", repo_type = "model", repo_id = "owner/base", replace_active = True+ )[0]+ assert registry.get_job_metadata("owner/base::").load_attached is True++ load_downloads.release_load_downloads(keys)++ ref = download_lifecycle.active_download_refs(registry, None, with_variant = False)[0]+ assert (ref.load_attached, ref.state) == (False, "running")+++def test_a_load_placeholder_cannot_be_adopted_started_or_cancelled(registry, monkeypatch):+ from hub.services.models import downloads++ monkeypatch.setattr(downloads, "_registry", registry)+ load_downloads.claim_load_downloads(["owner/base"])++ assert registry.adoptable("owner/base::") is False+ with pytest.raises(HTTPException) as started:+ downloads._reject_if_load_owned("owner/base::")+ with pytest.raises(HTTPException) as cancelled:+ asyncio.run(+ downloads.cancel_download_model_response(CancelDownloadRequest(repo_id = "owner/base"))+ )+ assert (started.value.status_code, cancelled.value.status_code) == (409, 409)+ assert registry.get_job("owner/base::").state == "running"++ load_downloads.release_load_downloads(["owner/base::"])+ downloads._reject_if_load_owned("owner/base::")+++def test_shutdown_leaves_no_cancel_marker_for_a_load_placeholder(registry, monkeypatch):+ markers = []+ monkeypatch.setattr(+ download_registry, "persist_cancel_marker", lambda *args, **kwargs: markers.append(args[1])+ )+ load_downloads.claim_load_downloads(["owner/adapter", "owner/base"])+ assert registry.claim("owner/other::", "http", repo_type = "model", repo_id = "owner/other")[0]++ registry.terminate_all()++ assert markers == ["owner/other"]+ assert registry.get_job("owner/adapter::").state == "idle"+ assert registry.get_job("owner/base::").state == "idle"+ assert _active(registry) == [("owner/other", None, "cancelling")]+++def test_the_orchestrator_registers_the_downloads_a_load_reports(registry, monkeypatch):+ class DummyThread:+ def __init__(self, *args, **kwargs):+ pass++ def start(self):+ return None++ with patch("core.inference.orchestrator.threading.Thread", DummyThread):+ from core.inference.orchestrator import InferenceOrchestrator+ orchestrator = InferenceOrchestrator()++ responses = iter(+ [+ {+ "type": "downloads",+ "repo_ids": ["owner/adapter", "owner/base"],+ "xet_disabled": True,+ },+ {"type": "loaded", "success": True},+ ]+ )+ monkeypatch.setattr(orchestrator, "_read_resp", lambda timeout = 1.0: next(responses))++ assert orchestrator._wait_response("loaded", timeout = 5)["success"]+ assert _active(registry) == [+ ("owner/adapter", "load", "running"),+ ("owner/base", "load", "running"),+ ]++ orchestrator._release_load_downloads()++ assert _active(registry) == []+ orchestrator._release_load_downloads()+++def test_the_worker_reports_the_repos_a_lora_load_fetches(monkeypatch):+ import sys+ import types++ from core.inference import worker++ package = types.ModuleType("unsloth")+ models = types.ModuleType("unsloth.models")+ loader_utils = types.ModuleType("unsloth.models.loader_utils")+ loader_utils.get_model_name = (+ lambda name, load_in_4bit = True: "unsloth/base-bnb-4bit" if load_in_4bit else name+ )+ loader = types.ModuleType("unsloth.models.loader")+ loader.ALLOW_PREQUANTIZED_MODELS = True+ loader.ALLOW_BITSANDBYTES = True+ loader._strip_unsloth_bnb_4bit_suffix = lambda name: name.removesuffix("-bnb-4bit")+ for name, module in (+ ("unsloth", package),+ ("unsloth.models", models),+ ("unsloth.models.loader", loader),+ ("unsloth.models.loader_utils", loader_utils),+ ):+ monkeypatch.setitem(sys.modules, name, module)++ adapter = SimpleNamespace(identifier = "owner/adapter", base_model = "owner/base")+ cuda = SimpleNamespace(device = "cuda")++ assert worker._load_download_repos(adapter, True, cuda) == [+ "owner/adapter",+ "owner/base",+ "unsloth/base-bnb-4bit",+ ]+ assert worker._load_download_repos(adapter, False, cuda) == ["owner/adapter", "owner/base"]+ assert worker._load_download_repos(adapter, True, SimpleNamespace(device = "mlx")) == [+ "owner/adapter",+ "owner/base",+ ]+ bnb = SimpleNamespace(identifier = "owner/adapter", base_model = "unsloth/base-unsloth-bnb-4bit")+ assert worker._load_download_repos(bnb, True, SimpleNamespace(device = "mlx")) == [+ "owner/adapter",+ "unsloth/base-unsloth-bnb-4bit",+ "unsloth/base",+ ]+ local = SimpleNamespace(identifier = "/models/adapter", base_model = "owner/base")+ assert worker._load_download_repos(local, True, SimpleNamespace(device = "mlx")) == ["owner/base"]+ plain = SimpleNamespace(identifier = "owner/model", base_model = None)+ assert worker._load_download_repos(plain, True, cuda) == ["owner/model"]+ legacy = SimpleNamespace(identifier = "owner/gpt2-lora", base_model = "gpt2")+ assert worker._load_download_repos(legacy, False, cuda) == ["owner/gpt2-lora", "gpt2"]++ loader.ALLOW_PREQUANTIZED_MODELS = False+ assert worker._load_download_repos(adapter, True, cuda) == [+ "owner/adapter",+ "owner/base",+ "unsloth/base",+ ]+ loader.ALLOW_PREQUANTIZED_MODELS = True++ loader.ALLOW_BITSANDBYTES = False+ assert worker._load_download_repos(adapter, True, cuda) == ["owner/adapter", "owner/base"]+ loader.ALLOW_BITSANDBYTES = True++ audio = SimpleNamespace(+ identifier = "owner/tts-lora", base_model = "owner/base", audio_type = "snac", is_audio = True+ )+ assert worker._load_download_repos(audio, True, cuda, ["owner/tts-lora", "owner/codec"]) == [+ "owner/tts-lora",+ "owner/codec",+ "owner/base",+ "hubertsiuzdak/snac_24khz",+ ]+ audio_vlm = SimpleNamespace(+ identifier = "owner/avlm-lora",+ base_model = "owner/base",+ audio_type = "audio_vlm",+ is_audio = False,+ )+ assert worker._load_download_repos(audio_vlm, True, cuda) == [+ "owner/avlm-lora",+ "owner/base",+ "unsloth/base-bnb-4bit",+ ]+ spark = SimpleNamespace(+ identifier = "owner/spark-lora", base_model = "unsloth/Spark-TTS-0.5B/LLM", audio_type = "bicodec"+ )+ monkeypatch.setattr(worker, "_load_download_repos", worker._load_download_repos)+ import utils.security.file_security as file_security++ monkeypatch.setattr(+ file_security,+ "load_scan_target",+ lambda name, subdirs: ("unsloth/Spark-TTS-0.5B", ("LLM",))+ if name.endswith("/LLM")+ else (name, subdirs),+ )+ assert worker._load_download_repos(spark, True, SimpleNamespace(device = "mlx")) == [+ "owner/spark-lora",+ "unsloth/Spark-TTS-0.5B",+ ]diff --git a/studio/backend/utils/third_party_source.py b/studio/backend/utils/third_party_source.pyindex dd033d2022b..6661a2e9cc1 100644--- a/studio/backend/utils/third_party_source.py+++ b/studio/backend/utils/third_party_source.py@@ -96,6 +96,13 @@ _SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")_IMPORT_LOCK = threading.RLock()_DAC_REPOSITORY = "ibm-research/DAC.speech.v1.0"+SNAC_REPOSITORY = "hubertsiuzdak/snac_24khz"+SPARK_TTS_REPOSITORY = "unsloth/Spark-TTS-0.5B"+SPEECH_CODEC_REPOSITORIES = {+ "snac": (SNAC_REPOSITORY,),+ "bicodec": (SPARK_TTS_REPOSITORY,),+ "dac": (_DAC_REPOSITORY,),+}_DAC_REVISION = "1ea7f64cd0678415e2d8c32d67b190722cb9b149"_DAC_FILENAME = "weights_24khz_1.5kbps_v1.0.pth"_DAC_SIZE = 295731578diff --git a/tests/studio/test_cli_start_download_liveness.py b/tests/studio/test_cli_start_download_liveness.pyindex c1a9bd4862f..4df5897d813 100644--- a/tests/studio/test_cli_start_download_liveness.py+++ b/tests/studio/test_cli_start_download_liveness.py@@ -5,6 +5,8 @@from __future__ import annotations+from urllib.parse import urlencode+import pytestimport typer@@ -13,6 +15,9 @@ import unsloth_cli.commands.start as start_cliBASE = "http://127.0.0.1:8888"MODEL = "unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF"+ADAPTER = "owner/coder-lora"+ADAPTER_BASE = "owner/coder-base"+ADAPTER_BYTES = 20 * 1024**2KEY_LINE = f"{start_cli._START_API_KEY_PREFIX}sk-unsloth-test\n"EXPECTED_BYTES = 500 * 1024**3STEP_S = 120.0@@ -89,6 +94,7 @@ class Harness:rebound = False,ready_at = None,tail = KEY_LINE,+ model = MODEL,):self.clock = FakeClock(STEP_S)self.log_path = None@@ -106,6 +112,8 @@ class Harness:self.chunk_bytes = chunk_bytesself.ready_at = ready_atself.tail = tail+ self.model = model+ self.base_polls = 0self.server = FakePopen()self.iterations = 0self.polls = 0@@ -128,6 +136,20 @@ class Harness:timeout = 30,error = None,):+ if url.endswith("/active-downloads"):+ if self.model != ADAPTER:+ return {"downloads": []}+ return {"downloads": [{"repo_id": ADAPTER_BASE, "owner": "load", "state": "running"}]}+ if "download-progress" in url and urlencode({"repo_id": ADAPTER}) in url:+ return {+ "downloaded_bytes": ADAPTER_BYTES,+ "completed_bytes": ADAPTER_BYTES,+ "expected_bytes": ADAPTER_BYTES,+ "progress": 1.0,+ "cache_measured": True,+ }+ if urlencode({"repo_id": ADAPTER_BASE}) in url:+ self.base_polls += 1if "gguf-variants" in url:return {"default_variant": "Q4_K_M",@@ -212,12 +234,12 @@ class Harness:with open(self.log_path, "ab") as handle:handle.write(self.chatter(self.iterations).encode())if self.ready_at is not None and self.iterations >= self.ready_at:- self.tail = f"{KEY_LINE}Model loaded: {MODEL}\n"+ self.tail = f"{KEY_LINE}Model loaded: {self.model}\n"return Truereturn Falsedef start(self):- return start_cli._start_studio_server(BASE, MODEL, start_cli.LoadOptions())[1]+ return start_cli._start_studio_server(BASE, self.model, start_cli.LoadOptions())[1]def test_a_live_download_survives_past_the_idle_cap(monkeypatch):@@ -402,3 +424,31 @@ def test_a_vanished_cache_mount_is_not_progress(monkeypatch, capsys):assert harness.shutdowns == [harness.server]assert f"made no progress for {start_cli._SERVER_START_TIMEOUT_S}s" in capsys.readouterr().errassert harness.clock.elapsed < 2 * start_cli._SERVER_START_TIMEOUT_S+++def test_a_lora_base_model_download_counts_as_progress(monkeypatch):+ harness = Harness(monkeypatch, model = ADAPTER, chunk_bytes = 1024**3, ready_at = 40)++ server = harness.start()++ assert server is harness.server+ assert harness.shutdowns == []+ assert harness.base_polls >= 40+ assert harness.clock.elapsed > start_cli._SERVER_START_TIMEOUT_S+++def test_a_stalled_lora_base_model_still_times_out(monkeypatch, capsys):+ harness = Harness(+ monkeypatch,+ model = ADAPTER,+ downloaded_bytes = 12 * 1024**3,+ chunk_bytes = 0,+ )++ with pytest.raises(typer.Exit):+ harness.start()++ assert harness.base_polls > 0+ assert harness.shutdowns == [harness.server]+ assert f"made no progress for {start_cli._SERVER_START_TIMEOUT_S}s" in capsys.readouterr().err+ assert harness.clock.elapsed < 2 * start_cli._SERVER_START_TIMEOUT_Sdiff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex dcdb1b174f4..e38d4ad4ad9 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -825,6 +825,8 @@ _SERVER_START_TIMEOUT_S = 900_DOWNLOAD_POLL_INTERVAL_S = 1.0# Ceiling on the doubling back-off the progress reader uses after a polling error._DOWNLOAD_POLL_MAX_BACKOFF_S = 60.0+# How often the progress reader re-lists the repos a load announced; each listed repo costs a cache scan per poll.+_LOAD_DOWNLOAD_LIST_INTERVAL_S = 5.0_START_API_KEY_PREFIX = "UNSLOTH_START_API_KEY: "_START_PORT_PREFIX = "UNSLOTH_START_PORT: "_START_API_KEY_MARKER_ENV = "_UNSLOTH_START_API_KEY_MARKER"@@ -860,9 +862,21 @@ class _DownloadProgressDisplay:self._last_bucket = -1self._last_line_length = 0self._last_expected = 0+ self._source: Optional[str] = Noneself._interactive = bool(getattr(sys.stdout, "isatty", lambda: False)())- def update(self, progress: dict) -> None:+ def update(+ self,+ progress: dict,+ source: Optional[str] = None,+ ) -> None:+ if source != self._source:+ # A new repo is a new transfer; else redirected output (prints only on a rising bucket) stays silent for a base that starts after the adapter finished.+ self._source = source+ self._samples.clear()+ self._last_expected = 0+ # Keep `_shown`: `complete()` and `close()` gate on it.+ self._last_bucket = -1downloaded = max(0, int(progress.get("downloaded_bytes") or 0))completed = max(0, int(progress.get("completed_bytes") or 0))expected = max(0, int(progress.get("expected_bytes") or 0))@@ -958,15 +972,27 @@ class _ModelDownloadProgress:self._retry_at = 0.0self._display = _DownloadProgressDisplay()self._configured = False+ # A local model has no Hub reading of its own, but a remote base it names is still listed.self._disabled = not _is_hub_model_id(model)self._progress_prefix = "/api/hub"+ # Repos the load announced (its base, the base the loader substitutes): bytes summed for liveness.+ self._repo_bytes: dict[str, int] = {}+ self._companions: list[str] = []+ self._finished: dict[+ str, dict+ ] = {} # Complete companions: final reading kept, never re-read.+ self._listed_at: Optional[float] = None+ self._active_repo = model++ def _is_gguf(self) -> bool:+ return bool(self._variant) or "gguf" in self._model.lower()def _configure(self) -> None:self._configured = Trueif self._disabled:return# GGUF repos need the selected quant's size; the repo endpoint totals every quant. Resolve the variant first, otherwise show bytes only.- if self._variant or "gguf" in self._model.lower():+ if self._is_gguf():try:params = urlencode({"repo_id": self._model})try:@@ -1000,51 +1026,87 @@ class _ModelDownloadProgress:# Older servers lack this endpoint; byte progress is still useful.pass+ def _companion_repos(self) -> list[str]:+ now = time.monotonic()+ if self._listed_at is not None and now - self._listed_at < _LOAD_DOWNLOAD_LIST_INTERVAL_S:+ return self._companions+ self._listed_at = now+ try:+ url = f"{self._base}{self._progress_prefix}/active-downloads"+ listing = _http_json("GET", url, self._key, timeout = 10)+ except urllib.error.HTTPError as exc:+ if exc.code == 404:+ self._listed_at = float("inf") # Older server: no load-owned jobs to find.+ return self._companions+ except Exception:+ return self._companions+ for item in listing.get("downloads") or []:+ repo = str(item.get("repo_id") or "")+ if not (item.get("owner") == "load" or item.get("load_attached")):+ continue+ if repo and repo.lower() != self._model.lower() and repo not in self._companions:+ self._companions.append(repo)+ return self._companions++ def _read(+ self,+ repo: str,+ gguf: bool = False,+ ) -> dict:+ if gguf:+ params = urlencode(+ {"repo_id": repo, "variant": self._variant, "expected_bytes": self._expected_bytes}+ )+ url = f"{self._base}{self._progress_prefix}/gguf-download-progress?{params}"+ else:+ params = urlencode({"repo_id": repo})+ url = f"{self._base}{self._progress_prefix}/download-progress?{params}"+ return _http_json("GET", url, self._key, timeout = 10)+def poll(self) -> None:if not self._configured:self._configure()- if self._disabled:- returnif time.monotonic() < self._retry_at:returntry:- if self._variant or "gguf" in self._model.lower():- params = urlencode(- {- "repo_id": self._model,- "variant": self._variant,- "expected_bytes": self._expected_bytes,- }- )- url = f"{self._base}{self._progress_prefix}/gguf-download-progress?{params}"- else:- url = (- f"{self._base}{self._progress_prefix}/download-progress?"- f"{urlencode({'repo_id': self._model})}"- )+ readings = {}try:- reading = _http_json("GET", url, self._key, timeout = 10)+ if not self._disabled:+ readings[self._model] = self._read(self._model, gguf = self._is_gguf())except urllib.error.HTTPError as exc:if exc.code != 404 or self._progress_prefix == "/api/models":raiseself._progress_prefix = "/api/models"self.poll()return- # The liveness baseline only ever rises. A reading falls for reasons that are- # not "bytes left the disk": an incomplete scan reporting a lower bound, a- # cache mount vanishing cleanly (`hf_cache_state._safe_is_dir` calls that a- # measured absence, not an error), an XET run purging its partial. Following a- # reading down would make the recovery back to the same figure look like fresh- # growth and renew the deadline for a server that is downloading nothing, and a- # flapping mount could do that forever. The cost is that a transfer which truly- # restarts is not counted again until it passes its own high mark; that failure- # is bounded and says so, where a false renewal is an unbounded wait.- self._downloaded_bytes = max(- self._downloaded_bytes, max(0, int(reading.get("downloaded_bytes") or 0))- )+ for repo in self._companion_repos():+ if repo in self._finished:+ readings[repo] = self._finished[repo]+ continue+ try:+ readings[repo] = item = self._read(repo)+ except Exception:+ continue+ if (+ 0+ < int(item.get("expected_bytes") or 0)+ <= int(item.get("completed_bytes") or 0)+ ):+ self._finished[repo] = item+ # The line follows whichever repo grew most; a repo first seen already large (a cached base) has not grown.+ growth = 0+ for repo, item in readings.items():+ current = max(0, int(item.get("downloaded_bytes") or 0))+ if current - self._repo_bytes.get(repo, current) > growth:+ growth, self._active_repo = current - self._repo_bytes[repo], repo+ # Only ever rises, so a dip and recovery never counts as fresh growth.+ self._repo_bytes[repo] = max(self._repo_bytes.get(repo, 0), current)+ self._downloaded_bytes = max(self._downloaded_bytes, sum(self._repo_bytes.values()))self._failures = 0self._retry_at = 0.0- self._display.update(reading)+ active = self._active_repo if self._active_repo in readings else self._model+ if active in readings:+ self._display.update(readings[active], active)except Exception:# Progress is best-effort and never fails the load, but `_start_studio_server`# reads `downloaded_bytes` to tell a live transfer from a wedged one. Backingdiff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex bf75ac561f6..6155c190ffa 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -18,6 +18,7 @@ import sysimport threadingimport timeimport urllib.error+import urllib.parsefrom pathlib import Pathfrom types import ModuleType, SimpleNamespace@@ -9809,3 +9810,152 @@ def test_direct_gguf_labels_keep_packed_and_grouped_quants():("Ternary-Bonsai-2-27B-PTQ1_0.gguf", "PTQ1_0"),):assert start._direct_gguf_variant_labels(name)[1] == label+++GiB = 1024**3+++class _LoadServer:+ """Fake Studio: `listing` answers active-downloads, `repos` maps repo -> iterator of progress readings."""++ def __init__(self, listing, repos):+ self.listing = listing+ self.repos = {repo: iter(readings) for repo, readings in repos.items()}+ self.urls = []++ def __call__(+ self,+ method,+ url,+ token,+ payload = None,+ timeout = 30,+ error = None,+ ):+ self.urls.append(url)+ if url.endswith("/active-downloads"):+ if isinstance(self.listing, Exception):+ raise self.listing+ return {"downloads": self.listing}+ repo = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["repo_id"][0]+ reading = next(self.repos[repo])+ if isinstance(reading, Exception):+ raise reading+ return reading++ def count(self, fragment):+ return sum(fragment in url for url in self.urls)+++def _reading(+ downloaded,+ expected = 4 * GiB,+ completed = 0,+):+ return {+ "downloaded_bytes": downloaded,+ "completed_bytes": completed,+ "expected_bytes": expected,+ }+++def _load_job(repo, **extra):+ return {"repo_id": repo, "owner": "load", "state": "running", **extra}+++def _progress(monkeypatch, server, clock):+ monkeypatch.setattr(start, "_http_json", server)+ monkeypatch.setattr(start.time, "monotonic", lambda: clock[0])+ return start._ModelDownloadProgress(BASE, "sk-test", "owner/adapter", None)+++def test_model_download_progress_counts_the_base_a_load_reports(monkeypatch, capsys):+ adapter_done = _reading(8 * 1024**2, 8 * 1024**2, 8 * 1024**2)+ server = _LoadServer(+ [+ _load_job("owner/base"),+ {"repo_id": "someone/else", "state": "running"},+ {"repo_id": "owner/attached", "state": "running", "load_attached": True},+ ],+ {+ "owner/adapter": [adapter_done] * 3,+ "owner/base": [_reading(0), _reading(1 * GiB), _reading(2 * GiB)],+ "owner/attached": [_reading(3 * GiB)] + [TimeoutError("slow")] * 2,+ },+ )+ clock = [0.0]+ progress = _progress(monkeypatch, server, clock)++ for _ in range(3):+ progress.poll()+ clock[0] += 1.0++ assert progress.downloaded_bytes == 8 * 1024**2 + 2 * GiB + 3 * GiB+ assert server.count("someone%2Felse") == 0+ # The line follows the base as it grows, not the attached job first seen at 3 GiB.+ out = capsys.readouterr().out+ assert "1.0 GiB / 4.0 GiB" in out and "3.0 GiB" not in out+++def test_model_download_progress_lists_load_jobs_at_most_every_interval(monkeypatch):+ done = _reading(4 * GiB, completed = 4 * GiB)+ server = _LoadServer(+ [_load_job("owner/base")],+ {+ "owner/adapter": [_reading(1024)] * 20,+ "owner/base": [_reading(GiB), done] + [AssertionError] * 20,+ },+ )+ clock = [0.0]+ progress = _progress(monkeypatch, server, clock)++ for _ in range(12):+ progress.poll()+ clock[0] += 1.0++ assert server.count("/active-downloads") == 3+ # A finished base is not scanned again, but its bytes still count.+ assert server.count("owner%2Fbase") == 2+ assert progress.downloaded_bytes == 1024 + 4 * GiB+++def test_model_download_progress_stops_listing_on_a_server_without_the_route(monkeypatch):+ missing = urllib.error.HTTPError(BASE, 404, "Not Found", None, None)+ server = _LoadServer(missing, {"owner/adapter": [_reading(1024)] * 20})+ clock = [0.0]+ progress = _progress(monkeypatch, server, clock)++ for _ in range(12):+ progress.poll()+ clock[0] += 1.0++ assert server.count("/active-downloads") == 1+ assert progress.downloaded_bytes == 1024+++def test_download_progress_display_restarts_when_the_repo_changes(monkeypatch, capsys):+ monkeypatch.setattr(start.sys.stdout, "isatty", lambda: False, raising = False)+ display = start._DownloadProgressDisplay()++ display.update(_reading(19 * 1024**2, 20 * 1024**2), "owner/adapter")+ display.update(_reading(GiB), "owner/base")++ out = capsys.readouterr().out+ assert "19.0 MiB / 20.0 MiB" in out+ assert "1.0 GiB / 4.0 GiB" in out+++def test_model_download_progress_counts_the_remote_base_of_a_local_adapter(monkeypatch):+ server = _LoadServer(+ [_load_job("owner/base")], {"owner/base": [_reading(GiB), _reading(2 * GiB)]}+ )+ clock = [0.0]+ monkeypatch.setattr(start, "_http_json", server)+ monkeypatch.setattr(start.time, "monotonic", lambda: clock[0])+ progress = start._ModelDownloadProgress(BASE, "sk-test", "/models/my-lora", None)++ progress.poll()+ progress.poll()++ assert progress.downloaded_bytes == 2 * GiB+ assert server.count("my-lora") == 0