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: stop LTX-2 loads crashing Windows with an access violation on 32 GB machines (#13432)

Daniel Han65e03e777f69
diff --git a/pyproject.toml b/pyproject.toml
index cd4f37e7b8c..69c426d7bc8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -184,6 +184,7 @@ studio = [
"fastmcp>=3.0.2",
"gguf==0.19.0 ; python_version >= '3.10'",
"gguf==0.18.0 ; python_version < '3.10'",
+ "safetensors>=0.8.0 ; sys_platform == 'win32' and python_version >= '3.10'",
"av>=12.3.0",
# No win_arm64 wheel and no sdist either, so it cannot be floored or built. Dropped rather
# than pinned: the RAG store already treats a missing sqlite_vec as "RAG unavailable".
diff --git a/studio/backend/core/inference/safetensors_pread.py b/studio/backend/core/inference/safetensors_pread.py
new file mode 100644
index 00000000000..1dfdfe98dce
--- /dev/null
+++ b/studio/backend/core/inference/safetensors_pread.py
@@ -0,0 +1,93 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Windows video loads read fp32 safetensors shards with safetensors' ``pread`` backend instead of mmap (#9977).
+
+torch maps a shard copy-on-write and Windows charges the whole view to commit while transformers holds every shard
+open: LTX-2's 48.7 GB fp32 Gemma3 loaded at bf16 needs ~73 GB, and torch's unchecked ``MapViewOfFile`` NULL is an
+access violation on a 32 GB host. bf16 / fp16 shards keep mmap: their mapping is the loaded weight.
+``UNSLOTH_SAFETENSORS_PREAD=0|1`` disables / forces it on any OS.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import os
+import sys
+import threading
+from typing import Any, Iterator
+
+PREAD_ENV = "UNSLOTH_SAFETENSORS_PREAD"
+
+_lock = threading.Lock()
+_depth = 0
+_original: Any = None
+
+
+def pread_wanted() -> bool:
+ value = (os.environ.get(PREAD_ENV) or "").strip().lower()
+ if value in ("0", "off", "false", "no"):
+ return False
+ if value in ("1", "on", "true", "yes"):
+ return True
+ return sys.platform == "win32"
+
+
+def _supports_backend(safe_open: Any) -> bool:
+ # safetensors < 0.8 has no backend keyword, and an unknown keyword is a TypeError on every load.
+ return "backend" in (getattr(safe_open, "__text_signature__", None) or "")
+
+
+def _stored_mostly_fp32(filename: Any) -> bool:
+ from pathlib import Path
+
+ from .diffusion_small_host import _safetensors_bytes_by_dtype
+
+ stored = _safetensors_bytes_by_dtype(Path(filename))
+ return stored.get("float32", 0) * 2 > sum(stored.values())
+
+
+def _with_pread(safe_open: Any) -> Any:
+ @functools.wraps(safe_open)
+ def pread_safe_open(filename: Any, *args: Any, **kwargs: Any) -> Any:
+ # transformers 5.13 - 5.16 pass backend="mmap" explicitly; 5.17 already picks pread on Windows (#48341).
+ if kwargs.get("backend") in (None, "mmap") and _stored_mostly_fp32(filename):
+ kwargs["backend"] = "pread"
+ return safe_open(filename, *args, **kwargs)
+
+ return pread_safe_open
+
+
+def pread_safetensors() -> Iterator[bool]:
+ """Route ``transformers.modeling_utils.safe_open`` of fp32 shards through ``pread``; yields whether it did. Nests; a
+ concurrent load in another thread only gets the same bytes through another backend."""
+ global _depth, _original
+ installed = False
+ if pread_wanted():
+ try:
+ import transformers.modeling_utils as modeling_utils
+ with _lock:
+ current = getattr(modeling_utils, "safe_open", None)
+ if _depth:
+ installed = True
+ elif current is not None and _supports_backend(current):
+ _original = current
+ modeling_utils.safe_open = _with_pread(current)
+ installed = True
+ if installed:
+ _depth += 1
+ except Exception: # noqa: BLE001 - the mmap backend still loads wherever commit allows
+ installed = False
+ try:
+ yield installed
+ finally:
+ if installed:
+ with _lock:
+ _depth -= 1
+ if not _depth:
+ import transformers.modeling_utils as modeling_utils
+ if getattr(modeling_utils.safe_open, "__wrapped__", None) is _original:
+ modeling_utils.safe_open = _original
+ _original = None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 01bb603b871..c9514955cc6 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3608,7 +3608,10 @@ class VideoBackend:
# The 2.3 assembly pulls per component from the hub id (its snapshot lacks the base VAEs), so it only gets
# the warmed cache.
kwargs["_base_local_dir"] = None if ltx23 else base_local
- self.load_pipeline(**kwargs)
+ from .safetensors_pread import pread_safetensors
+
+ with pread_safetensors():
+ self.load_pipeline(**kwargs)
with self._lock:
if self._load_token == token:
self._loading = None
diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txt
index 8ce1687b6af..c0024de8ca9 100644
--- a/studio/backend/requirements/studio.txt
+++ b/studio/backend/requirements/studio.txt
@@ -54,6 +54,8 @@ fastmcp>=3.0.2
# gguf is torch-free so it lives here, where it's installed in every mode.
gguf==0.19.0; python_version >= "3.10"
gguf==0.18.0; python_version < "3.10"
+# Windows video loads read fp32 shards with the pread backend (core/inference/safetensors_pread.py, #9977).
+safetensors>=0.8.0; sys_platform == "win32" and python_version >= "3.10"
# Local video generation (Video page): MP4 encode (H.264 + AAC mux for LTX-2's
# synchronized audio) runs through PyAV, which bundles its own ffmpeg libs. The
# video load path fails fast with a clear error when this is missing, so keep it
diff --git a/studio/backend/tests/test_safetensors_pread.py b/studio/backend/tests/test_safetensors_pread.py
new file mode 100644
index 00000000000..7e37c3ebc2c
--- /dev/null
+++ b/studio/backend/tests/test_safetensors_pread.py
@@ -0,0 +1,204 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``safetensors_pread.py``: on Windows a media load reads transformers' safetensors shards with the ``pread`` backend
+instead of torch's copy-on-write file mapping (#9977), and every other platform keeps the byte-identical mmap path.
+CPU only."""
+
+from __future__ import annotations
+
+import inspect
+import sys
+import threading
+
+import pytest
+import torch
+
+import core.inference.safetensors_pread as sp
+
+transformers = pytest.importorskip("transformers")
+import transformers.modeling_utils as modeling_utils # noqa: E402
+
+# transformers < 5.6 passes no backend (None), later releases pass "mmap" off Windows.
+MMAP = {None, "mmap"}
+
+requires_backend = pytest.mark.skipif(
+ not sp._supports_backend(modeling_utils.safe_open),
+ reason = "installed safetensors has no backend keyword",
+)
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ monkeypatch.delenv(sp.PREAD_ENV, raising = False)
+ yield
+ assert sp._depth == 0 and sp._original is None
+
+
+def _record_backends(monkeypatch):
+ """Spy under the patch: the backend keyword each transformers safe_open call carried (None = default mmap)."""
+ seen = []
+ real = modeling_utils.safe_open
+
+ def spy(*args, **kwargs):
+ seen.append(kwargs.get("backend"))
+ return real(*args, **kwargs)
+
+ spy.__text_signature__ = real.__text_signature__
+ monkeypatch.setattr(modeling_utils, "safe_open", spy)
+ return seen
+
+
+ "platform, env, wanted",
+ [
+ ("win32", None, True),
+ ("linux", None, False),
+ ("darwin", None, False),
+ ("win32", "0", False),
+ ("linux", "1", True),
+ ],
+)
+def test_pread_wanted(monkeypatch, platform, env, wanted):
+ monkeypatch.setattr(sys, "platform", platform)
+ if env is not None:
+ monkeypatch.setenv(sp.PREAD_ENV, env)
+ assert sp.pread_wanted() is wanted
+
+
+def test_off_windows_nothing_is_patched(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ before = modeling_utils.safe_open
+ with sp.pread_safetensors() as engaged:
+ assert engaged is False
+ assert modeling_utils.safe_open is before
+
+
+def test_old_safetensors_without_backend_is_left_alone(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+
+ def old_safe_open(
+ filename,
+ framework,
+ device = "cpu",
+ ):
+ raise AssertionError("not called")
+
+ monkeypatch.setattr(modeling_utils, "safe_open", old_safe_open)
+ with sp.pread_safetensors() as engaged:
+ assert engaged is False
+ assert modeling_utils.safe_open is old_safe_open
+
+
+def _save_llama(path, dtype):
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ config = LlamaConfig(
+ vocab_size = 64,
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 4,
+ )
+ torch.manual_seed(0)
+ LlamaForCausalLM(config).to(dtype).save_pretrained(path, max_shard_size = "20KB")
+ assert len(list(path.glob("*.safetensors"))) > 1
+ return LlamaForCausalLM
+
+
+@requires_backend
+def test_windows_fp32_load_reads_with_pread_and_matches_mmap(monkeypatch, tmp_path):
+ """The reported path: an fp32 checkpoint loaded at bf16 through transformers' from_pretrained."""
+ model_cls = _save_llama(tmp_path, torch.float32)
+ seen = _record_backends(monkeypatch)
+ dense = model_cls.from_pretrained(tmp_path, dtype = torch.bfloat16)
+ assert seen and set(seen) <= MMAP
+
+ monkeypatch.setenv(sp.PREAD_ENV, "1")
+ seen.clear()
+ spy = modeling_utils.safe_open
+ with sp.pread_safetensors() as engaged:
+ assert engaged is True
+ assert modeling_utils.safe_open.__wrapped__ is spy
+ loaded = model_cls.from_pretrained(tmp_path, dtype = torch.bfloat16)
+ assert seen and set(seen) == {"pread"}
+ assert modeling_utils.safe_open is spy
+
+ expected = dense.state_dict()
+ for name, tensor in loaded.state_dict().items():
+ assert tensor.dtype == torch.bfloat16
+ assert torch.equal(tensor, expected[name]), name
+
+
+@requires_backend
+def test_windows_bf16_shards_keep_mmap(monkeypatch, tmp_path):
+ """A bf16 shard's mapping is the loaded weight, so it stays on the default backend."""
+ model_cls = _save_llama(tmp_path, torch.bfloat16)
+ monkeypatch.setenv(sp.PREAD_ENV, "1")
+ seen = _record_backends(monkeypatch)
+ with sp.pread_safetensors() as engaged:
+ assert engaged is True
+ model_cls.from_pretrained(tmp_path, dtype = torch.bfloat16)
+ assert seen and set(seen) <= MMAP
+
+
+@requires_backend
+ "dtype, passed, expected",
+ [
+ (torch.float32, None, "pread"),
+ (torch.float32, "mmap", "pread"),
+ (torch.float32, "pread", "pread"),
+ (torch.bfloat16, None, None),
+ (torch.bfloat16, "mmap", "mmap"),
+ ],
+)
+def test_backend_choice(monkeypatch, tmp_path, dtype, passed, expected):
+ from safetensors.torch import save_file
+
+ path = tmp_path / "shard.safetensors"
+ save_file({"w": torch.zeros(64, 64, dtype = dtype)}, str(path))
+ monkeypatch.setattr(sys, "platform", "win32")
+ seen = _record_backends(monkeypatch)
+ kwargs = {} if passed is None else {"backend": passed}
+ with sp.pread_safetensors():
+ with modeling_utils.safe_open(str(path), framework = "pt", device = "cpu", **kwargs) as handle:
+ assert torch.equal(handle.get_slice("w")[...], torch.zeros(64, 64, dtype = dtype))
+ assert seen == [expected]
+
+
+@requires_backend
+def test_nested_and_concurrent_loads_restore_once(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ original = modeling_utils.safe_open
+ inside = threading.Event()
+ release = threading.Event()
+
+ def other_load():
+ with sp.pread_safetensors() as engaged:
+ assert engaged
+ inside.set()
+ release.wait(5)
+
+ worker = threading.Thread(target = other_load)
+ with sp.pread_safetensors() as outer:
+ assert outer
+ patched = modeling_utils.safe_open
+ worker.start()
+ assert inside.wait(5)
+ with sp.pread_safetensors() as inner:
+ assert inner and modeling_utils.safe_open is patched
+ assert modeling_utils.safe_open is patched
+ assert modeling_utils.safe_open is patched
+ release.set()
+ worker.join(5)
+ assert modeling_utils.safe_open is original
+
+
+def test_video_load_runs_inside_the_scope():
+ from core.inference.video import VideoBackend
+
+ source = inspect.getsource(VideoBackend._run_load)
+ scope = source.index("with pread_safetensors():")
+ assert scope < source.index("self.load_pipeline(**kwargs)", scope)