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 sd.cpp installer: retry a transient download failure before stepping down to the CPU build (#16788)
Daniel Han9d40777eb19d
diff --git a/studio/backend/tests/test_sd_cpp_download_retry.py b/studio/backend/tests/test_sd_cpp_download_retry.pynew file mode 100644index 00000000000..b22afbe3ead--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_download_retry.py@@ -0,0 +1,97 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The prebuilt download retries a transient failure (HTTP 5xx / 429, socket errors) and raises a permanent one at once.++A single gateway 504 from the GitHub asset CDN used to fail the CUDA bundle, after which the MiniMax-H3 native load+installed the CPU build on a CUDA host and rendered on the CPU."""++from __future__ import annotations++import io+import sys+import urllib.error+from pathlib import Path++import pytest++_STUDIO = Path(__file__).resolve().parents[2]+if str(_STUDIO) not in sys.path:+ sys.path.insert(0, str(_STUDIO))++import install_sd_cpp_prebuilt as sdmod # noqa: E402+++class _Resp(io.BytesIO):+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False+++def _fake(monkeypatch, outcomes):+ calls = []++ def urlopen(req, timeout = 300.0):+ url = getattr(req, "full_url", req)+ calls.append(url)+ out = outcomes[min(len(calls) - 1, len(outcomes) - 1)]+ if isinstance(out, BaseException):+ raise out+ return _Resp(out)++ monkeypatch.setattr(sdmod.urllib.request, "urlopen", urlopen)+ monkeypatch.setattr("time.sleep", lambda s: None)+ return calls+++def _http(code):+ return urllib.error.HTTPError("https://example.invalid/a.zip", code, "x", None, None)+++def test_transient_504_is_retried_then_succeeds(tmp_path, monkeypatch):+ calls = _fake(monkeypatch, [_http(504), _http(502), b"payload"])+ dest = tmp_path / "a.zip"+ sdmod._download("https://example.invalid/a.zip", dest)+ assert dest.read_bytes() == b"payload"+ assert len(calls) == 3+++def test_socket_error_and_429_are_retried(tmp_path, monkeypatch):+ calls = _fake(monkeypatch, [urllib.error.URLError("reset"), _http(429), b"ok"])+ dest = tmp_path / "a.zip"+ sdmod._download("https://example.invalid/a.zip", dest)+ assert dest.read_bytes() == b"ok" and len(calls) == 3++[email protected]("code", [403, 404])+def test_permanent_4xx_is_raised_without_retry(tmp_path, monkeypatch, code):+ calls = _fake(monkeypatch, [_http(code), b"never"])+ with pytest.raises(urllib.error.HTTPError) as err:+ sdmod._download("https://example.invalid/a.zip", tmp_path / "a.zip")+ assert err.value.code == code and len(calls) == 1+++def test_persistent_5xx_raises_after_all_attempts(tmp_path, monkeypatch):+ calls = _fake(monkeypatch, [_http(504)])+ with pytest.raises(urllib.error.HTTPError) as err:+ sdmod._download("https://example.invalid/a.zip", tmp_path / "a.zip")+ assert err.value.code == 504 and len(calls) == sdmod._DOWNLOAD_ATTEMPTS+++def test_a_stall_that_used_the_whole_timeout_is_not_retried(tmp_path, monkeypatch):+ clock = [0.0]+ monkeypatch.setattr("time.monotonic", lambda: clock[0])+ calls = []++ def urlopen(req, timeout = 300.0):+ calls.append(req)+ clock[0] += timeout+ raise urllib.error.URLError(TimeoutError("timed out"))++ monkeypatch.setattr(sdmod.urllib.request, "urlopen", urlopen)+ monkeypatch.setattr("time.sleep", lambda s: None)+ with pytest.raises(urllib.error.URLError):+ sdmod._download("https://example.invalid/a.zip", tmp_path / "a.zip", timeout = 30.0)+ assert len(calls) == 1diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex 65146b1c736..b71dc50f24e 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -462,12 +462,45 @@ def _download(*,timeout: float = 300.0,) -> None:- """Stream ``url`` to ``dest`` with an explicit timeout: ``urlretrieve`` takes no timeout and can hang forever on a stalled socket. A User-Agent is set because the GitHub asset CDN can reject header-less requests; the API fetch carries any token."""+ """Stream ``url`` to ``dest`` with an explicit timeout: ``urlretrieve`` takes no timeout and can hang forever on a stalled socket. A User-Agent is set because the GitHub asset CDN can reject header-less requests; the API fetch carries any token.++ A transient failure (HTTP 5xx / 429, a reset or timed-out socket) is retried with backoff before it is raised: one+ gateway 504 from the asset CDN otherwise fails the GPU bundle and the caller steps down the accelerator ladder, so+ a CUDA host ends up rendering on the CPU build. A 4xx other than 429 is permanent and raised at once. Once the+ attempts so far have used ``timeout`` in all (a stalled route), the failure is raised without another attempt, so a+ dead route fails in about the time it did before the retries."""import shutil+ import time++ last: Optional[BaseException] = None+ start = time.monotonic()+ for attempt in range(_DOWNLOAD_ATTEMPTS):+ if attempt:+ if time.monotonic() - start >= timeout:+ break+ time.sleep(_DOWNLOAD_BACKOFF_S * (2 ** (attempt - 1)))+ req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-sd-cpp-installer"})+ try:+ with urllib.request.urlopen(req, timeout = timeout) as resp, open(dest, "wb") as f: # noqa: S310+ shutil.copyfileobj(resp, f)+ return+ except urllib.error.HTTPError as exc:+ if exc.code != 429 and exc.code < 500:+ raise+ last = exc+ except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:+ last = exc+ print(+ f"download of {url} failed ({last}); attempt {attempt + 1} of {_DOWNLOAD_ATTEMPTS}",+ flush = True,+ )+ assert last is not None+ raise last+- req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-sd-cpp-installer"})- with urllib.request.urlopen(req, timeout = timeout) as resp, open(dest, "wb") as f: # noqa: S310- shutil.copyfileobj(resp, f)+# Transient download failures (5xx / 429 / socket) retried this many times in all, backoff 2, 4, 8 s.+_DOWNLOAD_ATTEMPTS = 4+_DOWNLOAD_BACKOFF_S = 2.0# PATH_MAX: a larger link payload is a decompression bomb.