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: split model-load progress label across two rows (#5020)
Daniel Han5861a7ce1527
diff --git a/studio/backend/tests/test_llama_cpp_load_progress_live.py b/studio/backend/tests/test_llama_cpp_load_progress_live.pynew file mode 100644index 00000000000..beed8713c18--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_load_progress_live.py@@ -0,0 +1,202 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Live, no-mock integration test for ``LlamaCppBackend.load_progress()``.++The companion files (``test_llama_cpp_load_progress.py`` and+``test_llama_cpp_load_progress_matrix.py``) patch ``builtins.open`` to+feed synthetic VmRSS values. This file is the opposite: it uses **real**+subprocesses, **real** file sizes, and the **real** ``/proc``+interface. It is the sanity check that the contract we keep in the+mocked tests still maps to what the kernel actually returns on a live+Linux system.++Why both: the mocked tests can be fooled by a buggy implementation that+parses ``/proc`` output in a format the kernel no longer uses, or that+makes assumptions about ``Path.stat()`` vs ``os.path.getsize``. This+file hits the real APIs so any format drift gets caught.++Skipped cleanly on non-Linux (no ``/proc``).+"""++from __future__ import annotations++import os+import subprocess+import sys+import time+import types as _types+from pathlib import Path++import pytest++# ---------------------------------------------------------------------------+# Same stubs as the matrix file (keep self-contained so the file can be+# run standalone as well as via the full suite).+# ---------------------------------------------------------------------------++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)+_structlog_stub = _types.ModuleType("structlog")+sys.modules.setdefault("structlog", _structlog_stub)+_httpx_stub = _types.ModuleType("httpx")+for _exc in (+ "ConnectError",+ "TimeoutException",+ "ReadTimeout",+ "ReadError",+ "RemoteProtocolError",+ "CloseError",+):+ setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))+_httpx_stub.Timeout = type("Timeout", (), {"__init__": lambda self, *a, **k: None})+_httpx_stub.Client = type(+ "Client",+ (),+ {+ "__init__": lambda self, **kw: None,+ "__enter__": lambda self: self,+ "__exit__": lambda self, *a: None,+ },+)+sys.modules.setdefault("httpx", _httpx_stub)++from core.inference.llama_cpp import LlamaCppBackend+++pytestmark = pytest.mark.skipif(+ not Path("/proc").exists(),+ reason = "live /proc test is Linux-only",+)+++def _make_backend(pid: int, gguf_path: str, healthy: bool = False):+ inst = LlamaCppBackend.__new__(LlamaCppBackend)+ inst._process = type("P", (), {"pid": pid})()+ inst._gguf_path = gguf_path+ inst._healthy = healthy+ return inst+++def test_live_rss_matches_kernel_vmrss(tmp_path):+ """Spawn a real child, let it allocate real bytes, confirm+ ``bytes_loaded`` tracks the kernel's VmRSS within a sane tolerance."""+ # Child that allocates ~100 MB of zero'd bytes and then idles.+ script = tmp_path / "burn.py"+ script.write_text(+ "import time, sys\n"+ "buf = bytearray(100 * 1024 * 1024)\n" # 100 MB+ "# touch every page so RSS actually grows\n"+ "for i in range(0, len(buf), 4096):\n"+ " buf[i] = 1\n"+ "sys.stdout.write('ready\\n')\n"+ "sys.stdout.flush()\n"+ "time.sleep(10)\n"+ )+ proc = subprocess.Popen(+ [sys.executable, str(script)],+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ )+ try:+ # Wait for the child to finish touching pages.+ ready = proc.stdout.readline()+ assert ready.strip() == b"ready"++ # Create a fake 200 MB sparse gguf so bytes_total is concrete.+ gguf = tmp_path / "model.gguf"+ with open(gguf, "wb") as f:+ f.truncate(200 * 1024 * 1024)++ inst = _make_backend(proc.pid, str(gguf), healthy = False)+ out = inst.load_progress()++ assert out is not None, "load_progress returned None for live pid"+ assert out["phase"] == "mmap"+ assert out["bytes_total"] == 200 * 1024 * 1024+ # VmRSS for the Python child includes the interpreter + the 100MB+ # buffer, so a realistic floor is 50 MB and ceiling is 200 MB.+ assert (+ out["bytes_loaded"] >= 50 * 1024 * 1024+ ), f"bytes_loaded unexpectedly low: {out['bytes_loaded']}"+ assert out["bytes_loaded"] <= 200 * 1024 * 1024+ assert 0.0 < out["fraction"] <= 1.0+ finally:+ proc.terminate()+ try:+ proc.wait(timeout = 5)+ except subprocess.TimeoutExpired:+ proc.kill()+++def test_live_ready_phase_when_healthy(tmp_path):+ gguf = tmp_path / "m.gguf"+ with open(gguf, "wb") as f:+ f.truncate(1 * 1024 * 1024)++ inst = _make_backend(os.getpid(), str(gguf), healthy = True)+ out = inst.load_progress()+ assert out is not None+ assert out["phase"] == "ready"+ assert out["bytes_total"] == 1 * 1024 * 1024+ # Self-pid RSS is well above 1 MiB for CPython; fraction caps at 1.+ assert out["fraction"] == 1.0+++def test_live_dead_pid_returns_none(tmp_path):+ """A recently-dead pid may linger in /proc for ms; use a clearly+ invalid id so the read reliably fails."""+ gguf = tmp_path / "m.gguf"+ gguf.touch()++ inst = _make_backend(9_999_999_999, str(gguf), healthy = False)+ out = inst.load_progress()+ assert out is None+++def test_live_shard_aggregation_counts_real_files(tmp_path):+ """With 4 real sibling shards on disk, ``bytes_total`` equals their+ summed size to the byte."""+ shard_size = 7 * 1024 * 1024 # 7 MB each+ for i in range(1, 5):+ f = tmp_path / f"model-{i:05d}-of-00004.gguf"+ with open(f, "wb") as fh:+ fh.truncate(shard_size)+ # Unrelated file in same dir -- must not be counted.+ with open(tmp_path / "config.json", "wb") as fh:+ fh.truncate(123)++ inst = _make_backend(+ os.getpid(),+ str(tmp_path / "model-00001-of-00004.gguf"),+ healthy = False,+ )+ out = inst.load_progress()+ assert out is not None+ assert out["bytes_total"] == 4 * shard_size+++def test_live_repeated_polling_stays_sane(tmp_path):+ """Sampling the same backend 20 times should not raise or produce+ non-numeric output, even under normal kernel RSS jitter."""+ gguf = tmp_path / "m.gguf"+ with open(gguf, "wb") as f:+ f.truncate(500 * 1024 * 1024)++ inst = _make_backend(os.getpid(), str(gguf), healthy = False)+ seen = []+ for _ in range(20):+ out = inst.load_progress()+ assert out is not None+ assert isinstance(out["bytes_loaded"], int)+ assert isinstance(out["bytes_total"], int)+ assert 0.0 <= out["fraction"] <= 1.0+ seen.append(out["bytes_loaded"])+ time.sleep(0.01)+ # RSS of a healthy Python process doesn't go below ~5 MB.+ assert min(seen) > 1 * 1024 * 1024diff --git a/studio/backend/tests/test_llama_cpp_load_progress_matrix.py b/studio/backend/tests/test_llama_cpp_load_progress_matrix.pynew file mode 100644index 00000000000..a88450ec0b5--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_load_progress_matrix.py@@ -0,0 +1,473 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Extended test matrix for ``LlamaCppBackend.load_progress()``.++Companion to ``test_llama_cpp_load_progress.py`` (which pins the basic+contract). This file widens coverage to the edge cases that bit users+or were hypothesized to bite them on cross-platform installs:++ * Platform matrix — macOS/Windows simulation via ``/proc`` absence.+ * ``VmRSS`` parsing — tab vs space delimiter, missing line, malformed+ integer.+ * Filesystem edges — HF-cache symlinks, broken symlinks, nonexistent+ paths, relative paths.+ * Shard aggregation — partial multi-shard downloads where some shards+ are still ``.incomplete``, two shard series in the same dir,+ ``mmproj-*.gguf`` sibling exclusion for non-sharded primaries,+ single-file models.+ * Lifecycle races — process set before ``_gguf_path`` is assigned,+ process dead mid-sample, ``_healthy`` flipped to True.+ * Concurrent sampling — 10 threads × 50 iterations against a single+ backend, hitting real ``/proc`` (no mocks — see the note in+ ``TestConcurrentSampling`` for why).+ * Fraction bounds — capped at 1.0 when RSS exceeds total; 0.0 when+ total is zero.++All tests are Linux-only in practice (we stub ``/proc`` where needed).+The stable subset runs in well under a second.+"""++from __future__ import annotations++import io+import os+import sys+import threading+import types as _types+from pathlib import Path+from unittest.mock import patch++import pytest++# ---------------------------------------------------------------------------+# Stub heavy / unavailable external dependencies before importing the+# module under test. Same pattern as test_llama_cpp_load_progress.py.+# ---------------------------------------------------------------------------++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++_structlog_stub = _types.ModuleType("structlog")+sys.modules.setdefault("structlog", _structlog_stub)++_httpx_stub = _types.ModuleType("httpx")+for _exc_name in (+ "ConnectError",+ "TimeoutException",+ "ReadTimeout",+ "ReadError",+ "RemoteProtocolError",+ "CloseError",+):+ setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))+++class _FakeTimeout:+ def __init__(self, *a, **kw):+ pass+++_httpx_stub.Timeout = _FakeTimeout+_httpx_stub.Client = type(+ "Client",+ (),+ {+ "__init__": lambda self, **kw: None,+ "__enter__": lambda self: self,+ "__exit__": lambda self, *a: None,+ },+)+sys.modules.setdefault("httpx", _httpx_stub)++from core.inference.llama_cpp import LlamaCppBackend+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make():+ inst = LlamaCppBackend.__new__(LlamaCppBackend)+ inst._process = None+ inst._gguf_path = None+ inst._healthy = False+ return inst+++class _Proc:+ def __init__(self, pid):+ self.pid = pid+++def _sparse(path, size):+ with open(path, "wb") as f:+ if size > 0:+ f.truncate(size)+++def _fake_proc_reader(rss_kb):+ """Return an ``open()`` replacement that fakes /proc reads with a VmRSS line."""++ def fake_open(path, *args, **kwargs):+ if str(path).startswith("/proc/"):+ return io.StringIO(f"VmRSS:\t{rss_kb}\tkB\n")+ return open(path, *args, **kwargs)++ return fake_open+++# ---------------------------------------------------------------------------+# A. Platform matrix+# ---------------------------------------------------------------------------+++class TestPlatformMatrix:+ """The method is Linux-first via /proc. On macOS/Windows it must+ degrade to None rather than crash."""++ def test_linux_live_proc_is_self_pid(self, tmp_path):+ """Self-pid /proc read uses the real kernel interface."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(gguf)+ inst._healthy = False+ out = inst.load_progress()+ assert out is not None+ assert out["phase"] == "mmap"+ assert out["bytes_total"] == 1 * 1024**3+ # Our Python process has some RSS -- just sanity-check positive.+ assert out["bytes_loaded"] > 0++ def test_macos_no_proc_returns_none(self, tmp_path):+ """Simulate macOS: /proc open fails with FileNotFoundError."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(pid = 12345)+ inst._gguf_path = str(gguf)++ def fake_open(path, *args, **kwargs):+ if str(path).startswith("/proc/"):+ raise FileNotFoundError(f"No such file: {path}")+ return open(path, *args, **kwargs)++ with patch("builtins.open", side_effect = fake_open):+ out = inst.load_progress()+ assert out is None++ def test_windows_no_proc_returns_none(self, tmp_path):+ """Simulate Windows: opening /proc raises PermissionError or OSError."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(pid = 4567)+ inst._gguf_path = str(gguf)++ def fake_open(path, *args, **kwargs):+ if str(path).startswith("/proc/"):+ raise PermissionError("access denied")+ return open(path, *args, **kwargs)++ with patch("builtins.open", side_effect = fake_open):+ out = inst.load_progress()+ assert out is None+++# ---------------------------------------------------------------------------+# B. VmRSS parsing edge cases+# ---------------------------------------------------------------------------+++class TestVmRSSParsing:+ def test_standard_tab_delimited(self, tmp_path):+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 4 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(gguf)+ with patch("builtins.open", side_effect = _fake_proc_reader(2 * 1024**2)):+ out = inst.load_progress()+ assert out["bytes_loaded"] == 2 * 1024**3++ def test_space_separated_fallback(self, tmp_path):+ """Some kernels emit single-space rather than tab."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 4 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(gguf)++ def fake_open(path, *a, **kw):+ if str(path).startswith("/proc/"):+ return io.StringIO("VmRSS: 4194304 kB\n")+ return open(path, *a, **kw)++ with patch("builtins.open", side_effect = fake_open):+ out = inst.load_progress()+ assert out["bytes_loaded"] == 4 * 1024**3++ def test_missing_vmrss_line(self, tmp_path):+ """Kernel with VmRSS stripped (zombie / kthread) -> 0."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(gguf)++ def fake_open(path, *a, **kw):+ if str(path).startswith("/proc/"):+ return io.StringIO("Name:\ttest\nState:\tZ (zombie)\n")+ return open(path, *a, **kw)++ with patch("builtins.open", side_effect = fake_open):+ out = inst.load_progress()+ assert out is not None+ assert out["bytes_loaded"] == 0+ assert out["fraction"] == 0.0++ def test_malformed_vmrss_value(self, tmp_path):+ """Non-integer VmRSS value should be treated as if the line were+ absent (early ValueError caught)."""+ gguf = tmp_path / "m.gguf"+ _sparse(gguf, 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(gguf)++ def fake_open(path, *a, **kw):+ if str(path).startswith("/proc/"):+ return io.StringIO("VmRSS:\tXXXX\tkB\n")+ return open(path, *a, **kw)++ with patch("builtins.open", side_effect = fake_open):+ out = inst.load_progress()+ # The implementation catches ValueError on int() and returns None.+ assert out is None+++# ---------------------------------------------------------------------------+# C. Filesystem edge cases+# ---------------------------------------------------------------------------+++class TestFilesystemEdges:+ def test_symlink_primary_follows_to_blob(self, tmp_path):+ """HF cache stores blobs under blobs/ and symlinks them from+ snapshots/. The method must follow the symlink."""+ blob = tmp_path / "blob"+ _sparse(blob, 12 * 1024**3)+ snap = tmp_path / "snap"+ snap.mkdir()+ link = snap / "m.gguf"+ link.symlink_to(blob)++ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(link)+ with patch("builtins.open", side_effect = _fake_proc_reader(6 * 1024**2)):+ out = inst.load_progress()+ assert out["bytes_total"] == 12 * 1024**3++ def test_broken_symlink_skipped(self, tmp_path):+ snap = tmp_path / "snap"+ snap.mkdir()+ link = snap / "m.gguf"+ link.symlink_to(tmp_path / "missing-blob")+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(link)+ with patch("builtins.open", side_effect = _fake_proc_reader(1024)):+ out = inst.load_progress()+ assert out["bytes_total"] == 0+ assert out["bytes_loaded"] == 1024 * 1024++ def test_nonexistent_path_skipped(self, tmp_path):+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "ghost.gguf")+ with patch("builtins.open", side_effect = _fake_proc_reader(1024)):+ out = inst.load_progress()+ assert out["bytes_total"] == 0++ def test_relative_gguf_path(self, tmp_path):+ """Relative paths shouldn't crash; behaviour depends on CWD but+ the method must not raise."""+ cwd = os.getcwd()+ try:+ os.chdir(tmp_path)+ _sparse(Path("rel.gguf"), 8 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = "rel.gguf"+ with patch("builtins.open", side_effect = _fake_proc_reader(0)):+ out = inst.load_progress()+ assert out is not None+ assert out["bytes_total"] == 8 * 1024**3+ finally:+ os.chdir(cwd)+++# ---------------------------------------------------------------------------+# D. Shard aggregation+# ---------------------------------------------------------------------------+++class TestShardAggregation:+ def test_partial_multi_shard_download(self, tmp_path):+ """Primary present but shards 2..N still downloading as+ ``.incomplete``. Sums only the fully-arrived ``.gguf`` files."""+ _sparse(tmp_path / "m-00001-of-00004.gguf", 30 * 1024**3)+ _sparse(tmp_path / "m-00002-of-00004.gguf", 30 * 1024**3)+ # 3 and 4 still downloading as .incomplete+ _sparse(tmp_path / "m-00003-of-00004.gguf.incomplete", 5 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m-00001-of-00004.gguf")+ with patch("builtins.open", side_effect = _fake_proc_reader(0)):+ out = inst.load_progress()+ assert out["bytes_total"] == 60 * 1024**3 # only the .gguf siblings++ def test_two_shard_series_in_same_dir(self, tmp_path):+ """Defensive: if two quant series share a dir, prefix filter+ only sums siblings of the chosen primary."""+ for i in range(1, 3):+ _sparse(tmp_path / f"m_q4-{i:05d}-of-00002.gguf", 10 * 1024**3)+ _sparse(tmp_path / f"m_q8-{i:05d}-of-00002.gguf", 20 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m_q8-00001-of-00002.gguf")+ with patch("builtins.open", side_effect = _fake_proc_reader(0)):+ out = inst.load_progress()+ assert out["bytes_total"] == 40 * 1024**3 # just q8 series++ def test_mmproj_sibling_not_counted(self, tmp_path):+ """Vision models drop an ``mmproj-*.gguf`` alongside. For a+ single-file (non-sharded) primary we only count the primary."""+ _sparse(tmp_path / "m.gguf", 8 * 1024**3)+ _sparse(tmp_path / "mmproj-BF16.gguf", 2 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m.gguf")+ with patch("builtins.open", side_effect = _fake_proc_reader(0)):+ out = inst.load_progress()+ # Non-sharded primary: only the primary is counted.+ assert out["bytes_total"] == 8 * 1024**3++ def test_single_file_model(self, tmp_path):+ """Non-sharded model: primary only."""+ _sparse(tmp_path / "small.gguf", 4 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "small.gguf")+ with patch("builtins.open", side_effect = _fake_proc_reader(2 * 1024**2)):+ out = inst.load_progress()+ assert out["bytes_total"] == 4 * 1024**3+ assert out["bytes_loaded"] == 2 * 1024**3+++# ---------------------------------------------------------------------------+# E. Lifecycle races+# ---------------------------------------------------------------------------+++class TestLifecycleRaces:+ def test_process_set_but_gguf_path_not_yet(self, tmp_path):+ """Moment between Popen and self._gguf_path=model_path."""+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = None+ with patch("builtins.open", side_effect = _fake_proc_reader(1024)):+ out = inst.load_progress()+ assert out is not None+ assert out["phase"] == "mmap"+ assert out["bytes_total"] == 0+ assert out["bytes_loaded"] == 1024 * 1024++ def test_process_died_mid_sample(self, tmp_path):+ """/proc/<pid> disappears -> None."""+ _sparse(tmp_path / "m.gguf", 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(pid = 999_999_999)+ inst._gguf_path = str(tmp_path / "m.gguf")+ assert inst.load_progress() is None++ def test_healthy_true_ready_phase(self, tmp_path):+ _sparse(tmp_path / "m.gguf", 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m.gguf")+ inst._healthy = True+ with patch("builtins.open", side_effect = _fake_proc_reader(1024)):+ out = inst.load_progress()+ assert out["phase"] == "ready"+++# ---------------------------------------------------------------------------+# F. Concurrent sampling (simulates multiple browser tabs polling)+# ---------------------------------------------------------------------------+++class TestConcurrentSampling:+ def test_parallel_invocations_never_raise(self, tmp_path):+ """Many concurrent samplers hitting the same backend must not raise.++ We intentionally do NOT patch ``builtins.open`` here because+ ``unittest.mock.patch`` is not thread-safe: interleaved+ enter/exit across threads can leak a Mock into ``builtins.open``+ and poison every subsequent test in the session. Instead, we+ let each thread hit the real ``/proc/self/status`` of the test+ process, which is exactly the code path that matters in prod.+ """+ _sparse(tmp_path / "m.gguf", 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m.gguf")+ errors = []++ def run():+ try:+ for _ in range(50):+ inst.load_progress()+ except Exception as e: # pragma: no cover+ errors.append(e)++ threads = [threading.Thread(target = run) for _ in range(10)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert not errors, errors+++# ---------------------------------------------------------------------------+# G. Fraction bounds+# ---------------------------------------------------------------------------+++class TestFractionBounds:+ def test_fraction_capped_at_one(self, tmp_path):+ _sparse(tmp_path / "m.gguf", 1 * 1024**3)+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = str(tmp_path / "m.gguf")+ # RSS > total (post-paged-in + extra structures)+ with patch("builtins.open", side_effect = _fake_proc_reader(2 * 1024**2)):+ out = inst.load_progress()+ assert 0.0 <= out["fraction"] <= 1.0++ def test_fraction_zero_when_total_zero(self):+ inst = _make()+ inst._process = _Proc(os.getpid())+ inst._gguf_path = None+ with patch("builtins.open", side_effect = _fake_proc_reader(1024**2)):+ out = inst.load_progress()+ assert out["fraction"] == 0.0diff --git a/studio/frontend/src/features/chat/components/model-load-status.tsx b/studio/frontend/src/features/chat/components/model-load-status.tsxindex afec327a0f6..16583519e46 100644--- a/studio/frontend/src/features/chat/components/model-load-status.tsx+++ b/studio/frontend/src/features/chat/components/model-load-status.tsx@@ -17,6 +17,29 @@ function clampProgress(value: number): number {return Math.max(0, Math.min(100, value));}+/**+ * Split a composed progress label like+ * "22.8 of 122.3 GB • 330.1 MB/s • 5m 9s left"+ * into a primary chunk ("22.8 of 122.3 GB") that can sit next to the+ * percent, and a secondary chunk ("330.1 MB/s • 5m 9s left") that can+ * live on its own row. This keeps either line from overflowing into a+ * ragged wrap when the rate/ETA part shows up mid-download.+ *+ * Labels without " • " (e.g. "22.8 GB downloaded") are returned+ * primary-only, so the secondary row simply doesn't render.+ */+function splitProgressLabel(+ label: string | null | undefined,+): { primary: string; secondary: string } {+ if (!label) return { primary: "", secondary: "" };+ const idx = label.indexOf(" \u2022 ");+ if (idx < 0) return { primary: label, secondary: "" };+ return {+ primary: label.slice(0, idx),+ secondary: label.slice(idx + 3),+ };+}+export function ModelLoadDescription({title,message,@@ -25,6 +48,10 @@ export function ModelLoadDescription({onStop,}: ModelLoadDescriptionProps) {const hasProgress = typeof progressPercent === "number";+ // Split once at the top of the render so the JSX below stays flat --+ // no IIFE required. splitProgressLabel is a trivial string op.+ const { primary: labelPrimary, secondary: labelSecondary } =+ splitProgressLabel(progressLabel);return (<div className="relative flex min-h-12 w-full items-stretch gap-2">@@ -35,11 +62,21 @@ export function ModelLoadDescription({{title ? <p className="text-foreground leading-5 font-semibold">{title}</p> : null}{hasProgress ? (<div className="w-full pt-1">- <div className="flex items-center justify-between text-[10px] font-medium tracking-[0.08em] text-muted-foreground/80">- <span>{progressLabel}</span>- <span>{Math.round(clampProgress(progressPercent))}%</span>+ <div className="flex items-center justify-between gap-2 text-[10px] font-medium tracking-[0.08em] text-muted-foreground/80">+ <span className="min-w-0 truncate">{labelPrimary}</span>+ <span className="shrink-0 tabular-nums">+ {Math.round(clampProgress(progressPercent))}%+ </span></div>- <Progress value={clampProgress(progressPercent)} className="h-1 bg-foreground/[0.08]" />+ {labelSecondary ? (+ <div className="truncate pt-0.5 text-[10px] font-medium tracking-[0.08em] text-muted-foreground/60">+ {labelSecondary}+ </div>+ ) : null}+ <Progress+ value={clampProgress(progressPercent)}+ className="mt-1 h-1 bg-foreground/[0.08]"+ /></div>) : message ? (<p className="pt-1 text-xs leading-relaxed text-muted-foreground">{message}</p>@@ -89,9 +126,17 @@ export function ModelLoadInlineStatus({<div className="min-w-[7rem] flex-1"><Progress value={clampProgress(progressPercent)} className="h-1 bg-foreground/[0.08]" /></div>- <div className="flex shrink-0 items-center gap-1 text-[10px] font-medium tracking-[0.08em] text-muted-foreground/80">- <span>{progressLabel}</span>- <span>{Math.round(clampProgress(progressPercent))}%</span>+ <div+ className="flex shrink-0 items-center gap-1 text-[10px] font-medium tracking-[0.08em] text-muted-foreground/80"+ title={progressLabel ?? undefined}+ >+ {/* Inline layout is horizontal and tight -- show only the+ primary (bytes) chunk; the full label (with rate/ETA)+ stays available via the tooltip. */}+ <span>{splitProgressLabel(progressLabel).primary}</span>+ <span className="tabular-nums">+ {Math.round(clampProgress(progressPercent))}%+ </span></div></div>) : null}diff --git a/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts b/studio/frontend/src/features/chat/hooks/use-transfer-stats.tsindex 9ea7d1e625c..56816808422 100644--- a/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts+++ b/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts@@ -19,26 +19,20 @@import { useEffect, useRef, useState } from "react";-export type TransferStats = {- rateBytesPerSecond: number;- etaSeconds: number;- /**- * False for the first few ticks (window not filled, or no forward- * progress yet). Consumers should hide rate/ETA while unstable so the- * UI doesn't flicker "123 GB/s" during the first tick.- */- stable: boolean;-};+import {+ appendSample,+ computeTransferStats,+ type TransferSample,+ type TransferStats,+} from "../utils/transfer-stats";-const MIN_SAMPLES = 3;-const MIN_WINDOW_SECONDS = 3;-const MAX_WINDOW_SECONDS = 15;+export type { TransferStats } from "../utils/transfer-stats";export function useTransferStats(bytes: number | null | undefined,totalBytes: number | null | undefined,): TransferStats {- const samplesRef = useRef<{ t: number; b: number }[]>([]);+ const samplesRef = useRef<TransferSample[]>([]);const [state, setState] = useState<TransferStats>({rateBytesPerSecond: 0,etaSeconds: 0,@@ -53,45 +47,8 @@ export function useTransferStats(? totalBytes: 0;- // If the counter resets (e.g. user unloaded and started a new- // download), drop the stale window.- const samples = samplesRef.current;- if (samples.length > 0 && cur < samples[samples.length - 1].b) {- samples.length = 0;- }-- samples.push({ t: now, b: cur });-- // Drop samples older than MAX_WINDOW_SECONDS; keep at least 2 so we- // can still compute a rate when the counter hasn't moved in a while.- const cutoff = now - MAX_WINDOW_SECONDS;- while (samples.length > 2 && samples[0].t < cutoff) {- samples.shift();- }-- if (samples.length < MIN_SAMPLES) {- setState({ rateBytesPerSecond: 0, etaSeconds: 0, stable: false });- return;- }-- const first = samples[0];- const last = samples[samples.length - 1];- const dt = last.t - first.t;- const db = last.b - first.b;- if (dt < MIN_WINDOW_SECONDS || db <= 0) {- setState({ rateBytesPerSecond: 0, etaSeconds: 0, stable: false });- return;- }-- const rate = db / dt;- const eta =- total > 0 && cur < total && rate > 0 ? (total - cur) / rate : 0;-- setState({- rateBytesPerSecond: rate,- etaSeconds: eta,- stable: true,- });+ appendSample(samplesRef.current, now, cur);+ setState(computeTransferStats(samplesRef.current, total));}, [bytes, totalBytes]);return state;diff --git a/studio/frontend/src/features/chat/utils/transfer-stats.ts b/studio/frontend/src/features/chat/utils/transfer-stats.tsnew file mode 100644index 00000000000..7aecf29eb0f--- /dev/null+++ b/studio/frontend/src/features/chat/utils/transfer-stats.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Pure, framework-free math behind {@link useTransferStats}.+ *+ * Split out so it can be unit-tested without a DOM/React renderer, and+ * so the training-start overlay, the chat download toast, and the+ * model-load phase UI all share the exact same rate/ETA semantics.+ *+ * No React, no `useRef`/`useState`, no timers -- the caller owns the+ * sample buffer and clock. This is the "what is the rate right now+ * given these samples" question, nothing more.+ */++export type TransferSample = { t: number; b: number };++export type TransferStats = {+ rateBytesPerSecond: number;+ etaSeconds: number;+ /**+ * False until the window has at least {@link MIN_SAMPLES} samples+ * spanning ≥ {@link MIN_WINDOW_SECONDS} with strictly forward progress.+ * Consumers should hide rate/ETA while this is false so the UI doesn't+ * flicker "123 GB/s" during the first tick.+ */+ stable: boolean;+};++export const MIN_SAMPLES = 3;+export const MIN_WINDOW_SECONDS = 3;+export const MAX_WINDOW_SECONDS = 15;++/**+ * Mutate ``samples`` in place: append the new sample, drop any that+ * fell out of the rolling window, and clear the buffer if the counter+ * went backwards (user cancelled + restarted a download, etc.).+ *+ * Returns the same array for chain-ability.+ */+export function appendSample(+ samples: TransferSample[],+ t: number,+ b: number,+ maxWindowSeconds: number = MAX_WINDOW_SECONDS,+): TransferSample[] {+ if (samples.length > 0 && b < samples[samples.length - 1].b) {+ samples.length = 0;+ }+ samples.push({ t, b });+ const cutoff = t - maxWindowSeconds;+ while (samples.length > 2 && samples[0].t < cutoff) {+ samples.shift();+ }+ return samples;+}++/**+ * Derive {@link TransferStats} from a window of cumulative-byte samples+ * plus the known total.+ *+ * * Needs ≥ {@link MIN_SAMPLES} samples spanning ≥ {@link MIN_WINDOW_SECONDS}+ * seconds before it will report ``stable: true``.+ * * ETA is clamped to 0 when: no progress, no total known, or the+ * counter already hit the total.+ */+export function computeTransferStats(+ samples: readonly TransferSample[],+ total: number,+): TransferStats {+ if (samples.length < MIN_SAMPLES) {+ return { rateBytesPerSecond: 0, etaSeconds: 0, stable: false };+ }+ const first = samples[0];+ const last = samples[samples.length - 1];+ const dt = last.t - first.t;+ const db = last.b - first.b;+ if (dt < MIN_WINDOW_SECONDS || db <= 0) {+ return { rateBytesPerSecond: 0, etaSeconds: 0, stable: false };+ }+ const rate = db / dt;+ const safeTotal = Number.isFinite(total) && total > 0 ? total : 0;+ const eta =+ safeTotal > 0 && last.b < safeTotal && rate > 0+ ? (safeTotal - last.b) / rate+ : 0;+ return { rateBytesPerSecond: rate, etaSeconds: eta, stable: true };+}