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.

Studio: the load prefetch skips chunks already in the page cache and budgets its read buffers (#17112)

Daniel Hande1568a6ccc9
diff --git a/studio/backend/core/inference/diffusion_fast_load.py b/studio/backend/core/inference/diffusion_fast_load.py
index 78f4c60331c..1dfff7a1921 100644
--- a/studio/backend/core/inference/diffusion_fast_load.py
+++ b/studio/backend/core/inference/diffusion_fast_load.py
@@ -13,6 +13,8 @@ import threading
from typing import Any, Iterable, Iterator, Optional, Sequence
PREFETCH_ENV = "UNSLOTH_DIFFUSION_PREFETCH"
+# "0": every slice is read whole, its page-cache-resident chunks included.
+PREFETCH_SKIP_CACHED_ENV = "UNSLOTH_DIFFUSION_PREFETCH_SKIP_CACHED"
FAST_UPLOAD_ENV = "UNSLOTH_DIFFUSION_FAST_UPLOAD"
_SWITCH_OFF = ("0", "off", "false", "no")
@@ -72,6 +74,57 @@ def _uncached_bytes(path: str) -> int:
return uncached(path)
+_LSB = bytes(b & 1 for b in range(256)) # mincore defines only bit 0 of each byte
+_LIBC: list = []
+
+
+def _mincore() -> Any:
+ if not _LIBC:
+ import ctypes
+
+ libc = ctypes.CDLL(None, use_errno = True)
+ libc.mincore.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p]
+ _LIBC.append(libc.mincore)
+ return _LIBC[0]
+
+
+def _chunk_resident(mapped: Any, start: int, length: int) -> bool:
+ """True when every page of the chunk is in the page cache; False when it cannot tell."""
+ import ctypes
+ import mmap
+
+ try:
+ page = mmap.PAGESIZE
+ first = start - start % page
+ span = start + length - first
+ pages = (span + page - 1) // page
+ mincore = _mincore()
+ anchor = ctypes.c_char.from_buffer(mapped, first)
+ try:
+ vector = (ctypes.c_ubyte * pages)()
+ if mincore(ctypes.addressof(anchor), ctypes.c_size_t(span), vector) != 0:
+ return False
+ return b"\x00" not in bytes(vector).translate(_LSB)
+ finally:
+ del anchor
+ except Exception: # noqa: BLE001 - unknown residency: read it
+ return False
+
+
+def _residency_map(path: str) -> Any:
+ """A mapping for ``mincore``, or None (non-Linux, switch off, unmappable)."""
+ import sys
+
+ if not sys.platform.startswith("linux") or not _switch_on(PREFETCH_SKIP_CACHED_ENV):
+ return None
+ try:
+ import mmap
+ with open(path, "rb") as handle:
+ return mmap.mmap(handle.fileno(), 0, access = mmap.ACCESS_COPY)
+ except Exception: # noqa: BLE001
+ return None
+
+
def _available_host_mib() -> Optional[int]:
try:
from .diffusion_memory import _available_system_memory_mib
@@ -138,7 +191,14 @@ def start_prefetch(
logger.info("diffusion.prefetch: skipped, the weights are on a rotational disk")
return None
available = _available_host_mib()
- if available is None or need > (int(available) << 20) // 2:
+ threads = max(1, int(threads))
+ largest = max(os.path.getsize(path) for path in pending)
+ buffer_bytes = max(1 << 20, min(_PREFETCH_READ_BYTES, -(-largest // threads)))
+ if available is not None:
+ # each worker's read buffer counts too: fewer workers before none
+ room = (int(available) << 20) // 2 - need
+ threads = max(1, min(threads, room // buffer_bytes))
+ if available is None or need + threads * buffer_bytes > (int(available) << 20) // 2:
if logger is not None:
logger.info(
"diffusion.prefetch: skipped, %.1f GiB uncached against %s MiB available host RAM",
@@ -146,7 +206,6 @@ def start_prefetch(
available,
)
return None
- threads = max(1, int(threads))
# Thread i reads slice i of every file, files in load order, so the first file is warm first.
plan: list[list[tuple[str, int, int]]] = [[] for _ in range(threads)]
for path in pending:
@@ -160,20 +219,29 @@ def start_prefetch(
stop = threading.Event()
def _worker(jobs: list[tuple[str, int, int]]) -> None:
- buffer = bytearray(_PREFETCH_READ_BYTES)
+ buffer = bytearray(buffer_bytes)
view = memoryview(buffer)
try:
for path, start, end in jobs:
if stop.is_set():
return
- with open(path, "rb", buffering = 0) as handle:
- handle.seek(start)
- at = start
- while at < end and not stop.is_set():
- got = handle.readinto(view[: min(_PREFETCH_READ_BYTES, end - at)])
- if not got:
- break
- at += got
+ mapped = _residency_map(path)
+ try:
+ with open(path, "rb", buffering = 0) as handle:
+ at = start
+ while at < end and not stop.is_set():
+ want = min(buffer_bytes, end - at)
+ if mapped is not None and _chunk_resident(mapped, at, want):
+ at += want
+ continue
+ handle.seek(at)
+ got = handle.readinto(view[:want])
+ if not got:
+ break
+ at += got
+ finally:
+ if mapped is not None:
+ mapped.close()
except Exception: # noqa: BLE001 - a prefetch is only a hint
pass
diff --git a/studio/backend/tests/test_diffusion_fast_load.py b/studio/backend/tests/test_diffusion_fast_load.py
index 27dbcf755dd..7c1ca3e17ec 100644
--- a/studio/backend/tests/test_diffusion_fast_load.py
+++ b/studio/backend/tests/test_diffusion_fast_load.py
@@ -76,6 +76,7 @@ def test_prefetch_reads_every_uncached_byte_in_order(tmp_path, monkeypatch):
monkeypatch.setattr(fl, "_uncached_bytes", lambda path: __import__("os").path.getsize(path))
monkeypatch.setattr(fl, "_available_host_mib", lambda: 1 << 20)
+ monkeypatch.setattr(fl, "_residency_map", lambda path: None, raising = False) # nothing cached
monkeypatch.setattr("builtins.open", _Spy)
handle = fl.start_prefetch(
files + [files[0], str(tmp_path / "missing")], min_bytes = 0, threads = 4
@@ -409,3 +410,95 @@ def test_rotational_lookup_never_raises(tmp_path):
path.write_bytes(b"z")
assert fl._on_rotational_disk(str(path)) in (True, False)
assert fl._on_rotational_disk(str(tmp_path / "missing")) is False
+
+
+SKIP_CACHED_ENV = "UNSLOTH_DIFFUSION_PREFETCH_SKIP_CACHED"
+
+
+def _spy_reads(monkeypatch):
+ read: list = []
+ real_open = open
+
+ class _Counted:
+ def __init__(self, path, *args, **kwargs):
+ self._path = str(path)
+ self._handle = real_open(path, *args, **kwargs)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self._handle.close()
+
+ def readinto(self, view):
+ got = self._handle.readinto(view)
+ read.append((self._path, got))
+ return got
+
+ def __getattr__(self, name):
+ return getattr(self._handle, name)
+
+ monkeypatch.setattr(fl, "open", _Counted, raising = False)
+ return read
+
+
+def test_a_mostly_cached_file_reads_only_its_uncached_chunks(tmp_path, monkeypatch):
+ monkeypatch.delenv(SKIP_CACHED_ENV, raising = False)
+ path = tmp_path / "dit.safetensors"
+ size = 8 << 20
+ path.write_bytes(b"q" * size)
+ monkeypatch.setattr(fl, "_uncached_bytes", lambda p: 1 << 20)
+ monkeypatch.setattr(fl, "_available_host_mib", lambda: 1 << 20)
+ # the first 7 MiB sit in the page cache, the last MiB does not
+ monkeypatch.setattr(
+ fl,
+ "_chunk_resident",
+ lambda mapped, start, length: start + length <= 7 << 20,
+ raising = False,
+ )
+ read = _spy_reads(monkeypatch)
+ _join_prefetch(fl.start_prefetch([str(path)], min_bytes = 0, threads = 8))
+ assert sum(got for name, got in read if name == str(path)) == 1 << 20
+
+
+def test_the_skip_cached_switch_reads_whole_slices(tmp_path, monkeypatch):
+ monkeypatch.setenv(SKIP_CACHED_ENV, "0")
+ path = tmp_path / "dit.safetensors"
+ path.write_bytes(b"q" * (8 << 20))
+ monkeypatch.setattr(fl, "_uncached_bytes", lambda p: 1 << 20)
+ monkeypatch.setattr(fl, "_available_host_mib", lambda: 1 << 20)
+ monkeypatch.setattr(fl, "_chunk_resident", lambda mapped, start, length: True, raising = False)
+ read = _spy_reads(monkeypatch)
+ _join_prefetch(fl.start_prefetch([str(path)], min_bytes = 0, threads = 8))
+ assert sum(got for name, got in read if name == str(path)) == 8 << 20
+
+
+ not __import__("sys").platform.startswith("linux"), reason = "mincore is Linux only"
+)
+def test_the_residency_check_sees_a_file_just_written(tmp_path, monkeypatch):
+ monkeypatch.delenv(SKIP_CACHED_ENV, raising = False)
+ path = tmp_path / "w.bin"
+ path.write_bytes(b"r" * (3 << 20))
+ path.read_bytes()
+ assert fl.PREFETCH_SKIP_CACHED_ENV == SKIP_CACHED_ENV
+ mapped = fl._residency_map(str(path))
+ assert mapped is not None
+ try:
+ assert fl._chunk_resident(mapped, 1 << 20, 1 << 20)
+ finally:
+ mapped.close()
+
+
+def test_the_read_buffers_count_against_the_ram_check(tmp_path, monkeypatch):
+ path = tmp_path / "big.safetensors"
+ path.write_bytes(b"s" * (16 << 20))
+ monkeypatch.setattr(fl, "_uncached_bytes", lambda p: 16 << 20)
+ monkeypatch.setattr(fl, "_residency_map", lambda path: None, raising = False)
+ # half of 40 MiB = 20 MiB: the 16 MiB warmed + two 2 MiB buffers fit, eight do not
+ monkeypatch.setattr(fl, "_available_host_mib", lambda: 40)
+ handle = fl.start_prefetch([str(path)], min_bytes = 0, threads = 8)
+ assert handle is not None and len(handle.threads) == 2
+ _join_prefetch(handle)
+ monkeypatch.setattr(fl, "_available_host_mib", lambda: 34) # 17 MiB: not even one buffer
+ assert fl.start_prefetch([str(path)], min_bytes = 0, threads = 8) is None