Skip to content

Windows: read safetensors shards with pread on transformers 5.0 - 5.16 - #14856

Merged
danielhanchen merged 6 commits into
mainfrom
windows-safetensors-pread
Oct 23, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
windows-safetensors-pread

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Problem

On Windows, loading a safetensors model through transformers 5.0 to 5.16 can exhaust the commit limit (RAM plus pagefile) and end in "The paging file is too small for this operation to complete" (os error 1455) or an access violation inside torch.

  • transformers 5.x opens every shard of a checkpoint before materialising any weight.
  • safetensors maps each shard copy-on-write, and Windows charges the whole view to commit for as long as the shard is open ("When copy-on-write access is specified, the system and process commit charge taken is for the entire view", MapViewOfFile docs).
  • So a load converting a bf16 checkpoint to fp16 (T4, V100, RTX 20 series, any fp16-only GPU) needs about twice the model in commit, and a 4-bit load still pays the full bf16 size on top of what it keeps.

This hits training, Unsloth inference and embedding models alike, since they all load through from_pretrained. Studio pins transformers 5.5, and Unsloth allows up to 5.17.

Fix

transformers 5.17 already switched Windows to safetensors' pread backend (huggingface/transformers#48341), which reads each tensor into its own buffer instead of mapping the file. This backports that behaviour:

  • unsloth/models/_windows_safetensors.py wraps transformers.modeling_utils.safe_open so CPU shard opens default to backend="pread", the same rewrite 5.17 does (it also replaces the explicit backend="mmap" that 5.13 to 5.16 pass).
  • Active only on Windows, transformers >= 5.0 and < 5.17, and safetensors >= 0.8 (the backend keyword). Linux and macOS are untouched, as are transformers 4.x (loads one shard at a time) and 5.17+ (already does this).
  • UNSLOTH_SAFETENSORS_PREAD=0 opts out, =1 forces it on any OS.
  • A caller can keep one shard on mmap with _unsloth_keep_mmap=True. Studio's small-host route needs that, since it keeps a text encoder memory-mapped on purpose.
  • Installed next to the UMA safetensors patch in unsloth/models/_utils.py, before it, so the UMA wrapper sits on top and both compose.

llama.cpp and ComfyUI avoid the same charge by mapping files read-only (PAGE_READONLY). GGUF loads in Unsloth and Studio go through llama.cpp and are unaffected.

Merge order

Merge after (or together with) #14514. Inside a Studio media load, Studio's own scope decides each shard's backend and passes _unsloth_keep_mmap for the shards it keeps mapped; that wiring lives in #14514.

Tests

tests/test_windows_safetensors_pread.py:

  • gating per platform, transformers version and env;
  • idempotent install, also when another wrapper sits on top;
  • the backend each open gets (cpu, explicit mmap, keep-mmap, CUDA target);
  • a real from_pretrained at bf16 and fp16 reads every shard with pread and gives bit-identical weights;
  • on Windows with transformers < 5.17, the real process commit of a ~1.5 GB bf16 checkpoint loaded at fp16, mmap vs pread.

Measured on windows-latest (transformers 5.5.0, safetensors 0.8.0, torch 2.14.1), a 1426 MiB bf16 checkpoint loaded at fp16, peak process commit in a fresh process per arm:

Backend Peak commit x checkpoint
mmap (before) 3477 MiB 2.44
pread (after) 2101 MiB 1.47

pread drops the 1.4 GB copy-on-write charge for the stored bytes. Both arms carry about 0.6 GB of other load-time allocations besides the fp16 copy. Staging: 18 passed on Windows, 17 passed + 1 Windows-only skip on Ubuntu and macOS.

Regression switchboard, base 3af683547 vs head 9e623b831 on Linux (where the patch is inert): NO_REGRESSION. regression_smoke, the sft and inference_smoke job A/Bs and the Studio auth / settings / crawl journeys all match base (two 0-pixel DOM-only crawl diffs, one visual diff that did not reproduce on confirm).

Not covered

  • .bin checkpoints still load with torch.load(mmap=True), which Windows charges the same way. They are rare for current models and left as they are.
  • Saving / merging reads one shard at a time and is unchanged.

transformers 5.x opens every shard before materialising weights and safetensors
maps each one copy-on-write, which Windows charges in full to the commit limit
for the whole load. A bf16 checkpoint converted to fp16 (T4 / V100 / RTX 20)
then needs about twice the model in commit, and a 4-bit load the full bf16
size, ending in os error 1455 or an access violation inside torch.

transformers 5.17 switched Windows to the pread backend
(huggingface/transformers#48341); backport that for 5.0 - 5.16 by defaulting
CPU shard opens to backend="pread". Windows only, safetensors >= 0.8,
UNSLOTH_SAFETENSORS_PREAD=0 opts out, and a caller can keep one shard on mmap
with _unsloth_keep_mmap=True.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 23, 2026
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T02:56:36.824552Z 9e623b8 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7574f49c5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +84 to +85
if not keep and str(device) == "cpu" and kwargs.get("backend") in (None, "mmap"):
kwargs["backend"] = "pread"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve mmap for Studio's same-dtype shards

When Windows Studio loads video under transformers 5.0–5.16 after Unsloth has been imported, studio/backend/core/inference/safetensors_pread.py::_with_pread intentionally leaves bf16/fp16 shards at None or "mmap"; test_windows_bf16_shards_keep_mmap enforces this because the small-host encoder path relies on file-backed weights. This wrapper then unconditionally converts both values to pread, and a repo-wide search finds no Studio caller supplying _unsloth_keep_mmap, so those large encoders are instead materialized in RAM and can exhaust small hosts. Wire the escape keyword into the existing Studio wrapper before overriding explicit mmap choices globally.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed on the Studio side in #14514 (82d5cbf): inside a Studio media load the scope passes _unsloth_keep_mmap for every shard it leaves on mmap (same-dtype shards and the small-host route's encoder), so this patch never overrides those choices; it also reads safetensors' backend support from the innermost safe_open, since a wrapper drops text_signature. #14514 should merge before or together with this PR.

Comment thread unsloth/models/_windows_safetensors.py Outdated
return real_safe_open(*args, **kwargs)

_pread_safe_open._unsloth_windows_pread = True
_mu.safe_open = _pread_safe_open

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Patch the MTP loader's independent safe_open reference

On transformers versions that provide MtpModel, its loader imports safe_open into transformers.modeling_layers and opens every MTP weight file through that separate reference, so assigning only _mu.safe_open leaves those files on the Windows mmap backend. Large MTP checkpoints can therefore still incur the same all-shards commit charge and fail even though the main checkpoint used pread; the upstream fix being backported explicitly changed both modeling_utils.py and modeling_layers.py. Apply the wrapper to the MTP module's reference as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9e623b8: transformers 5.16 imports its own safe_open into modeling_layers for the MTP loader, so that reference is wrapped too (test_the_mtp_loaders_own_reference_is_wrapped).

danielhanchen added a commit to VTplus/unsloth that referenced this pull request Oct 23, 2026
…load commits one copy

Windows charges a copy-on-write safetensors view to commit in full while
transformers holds every shard open, so a bf16 encoder loaded at fp16 commits
the stored bytes next to the fp16 copy (unslothai#14513). Extend the video pread scope
to image pipeline loads and to every bf16 / fp16 shard converted to another
dtype; shards loaded at their stored dtype (the small-host route's encoder)
keep mmap. The commit guard then counts no source view for components read
through pread, so the reporter's load stays dense instead of rerouting.

Also: read safetensors' backend support from the innermost safe_open (a
wrapper drops __text_signature__ and silently disabled the scope), and pass
_unsloth_keep_mmap for shards this scope leaves on mmap when unsloth's
Windows pread patch (unslothai#14856) sits underneath.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 9e623b8318

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

danielhanchen added a commit that referenced this pull request Oct 23, 2026
…ds (#14514)

## Summary

GGUF image loads can exhaust Windows system commit while the small-host
guard considers dense loading safe. The guard now also checks the
Windows commit headroom, so affected loads take the existing low-memory
route; the existing RAM refusal is unchanged.

Fixes #14513

## Changes

- On Windows, read the commit headroom (`CommitLimit - CommitTotal`)
with `K32GetPerformanceInfo`. A converting load keeps each copy-on-write
safetensors view charged to commit next to the converted copy, so its
commit need is the stored bytes plus the dense estimate (2x dense for an
fp16 load; measured 2.06x on the Qwen-Image encoder). If that plus the
reserve does not fit the headroom, the low-memory route engages even
when physical RAM says the dense load fits.
- The physical check is the same as before (dense estimate vs available
RAM, no extra margin). Linux and macOS have no commit reading, so their
decisions do not change.
- On Windows, image pipeline loads now read every bf16 / fp16
safetensors shard that converts to another dtype with safetensors'
`pread` backend (the scope #13432 added for fp32 video encoders,
generalized). `pread` reads each tensor into its own buffer, so the
stored bytes are never charged to commit; this is what transformers 5.17
does on Windows (huggingface/transformers#48341), and what ComfyUI and
llama.cpp get by mapping read-only. Shards loaded at their stored dtype
keep mmap, since that mapping is the weight and the low-memory route
relies on it. The commit check then counts one copy for components read
this way, so the reporter's load can stay dense instead of rerouting.
- If unsloth's own Windows pread patch (#14856) is loaded in the same
process, this scope still decides each shard inside a media load and
tells it which shards to keep on mmap.
- The pre-built GGUF transformer is not added to the estimate: diffusers
copies every GGUF tensor into private memory when it builds the
transformer, so both readings already exclude it.
- The commit check only routes. The refusal still uses physical RAM,
since a system-managed pagefile can grow past the current commit limit.
- Log measured dense decisions as well, with the commit headroom when it
is read, so a crash after a dense decision shows what the guard saw.
- Add `UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIB` to cap the total, available
and commit values the guard sees, for testing. It does not enforce a
process memory limit.

## Known limitations

- A system-managed pagefile can grow, so the current commit limit can
understate what Windows would eventually allow. Those hosts may take the
low-memory route when a dense load would have just fit.
- The commit estimate assumes Studio's pinned transformers 5.5, which
reads shards through copy-on-write mmap on Windows. transformers 5.17
and later read them with `pread` on Windows
(huggingface/transformers#48341), so there the source views cost no
commit and the estimate is conservative: such installs may take the
low-memory route sooner than needed.
- The replacement/reload crash described in the issue is outside this
change. Loading peaks and the timing of host-memory release need
separate investigation.
- The video loading path is unchanged.

## Testing

`studio/backend/tests/test_diffusion_small_host.py` covers the #14513
case (a 16.7 GB bf16 encoder with the GGUF DiT already built: dense on
physical RAM alone, routed with 30 GB of commit headroom, dense again
with 50 GB), commit never refusing, LoRA keeping the dense denoiser,
unreadable commit giving the same decisions as the physical check, the
env cap, the Windows API reader (runs on Windows), and the pipeline call
site passing the commit reading and logging dense decisions.

Decision grid against `main` (3 families x fp16/fp32/bf16 x 5 host sizes
x 22 free-RAM levels x LoRA on/off): with no commit reading, 864 of 864
cells give the same decision. With commit headroom from 0 to 192 GB,
every cell that moves goes from dense to the low-memory route because
the commit need does not fit; no new refusals and no LoRA cell moves.

Windows commit, measured on `windows-latest` (transformers 5.5.0,
safetensors 0.8.0) through this scope: a 1426 MiB bf16 checkpoint loaded
at fp16 peaks at 3478 MiB of process commit with mmap and 2085 MiB with
`pread`; the 1.4 GB difference is the copy-on-write charge for the
stored bytes. Staging: 51 passed on Windows, 50 passed + 1 Windows-only
skip on Ubuntu and macOS.

GPU check on a Colab Tesla T4 (fp16 compute, like the reporter's V100),
through Studio's real load and generate, with a Qwen-Image 2.1 pipe
whose text encoder is 667 MiB bf16. With the commit reading faked to 1
GB, the guard logs `engaged=True (... 1024 MiB commit headroom (dense
needs ~1536 MiB))`, the encoder loads memory-mapped with layerwise
casting, and peak RSS drops from 2.92 to 2.31 GiB. With no commit
reading (Linux) or a large one, the load stays dense. The image is
bit-identical to `main` in all four arms.

The same check with `UNSLOTH_SAFETENSORS_PREAD=1` forced on: the dense
load reads the converted encoder through `pread`, and with the commit
reading faked tight the route engages and keeps the encoder
memory-mapped. Every arm's image is bit-identical to `main`.

On the original 48 GB Windows host, the earlier version of this PR sent
the previously failing Turbo load through the low-memory route, and it
completed and generated images. With this version the same load needs
about 43.4 GB of commit headroom to stay dense (38.4 GB for the source
views and the fp16 copy, plus the 4.9 GB reserve). The failing run
committed 44.7 GB before it ran out, so its headroom was below that and
it routes. This version has not been rerun on that host yet.

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@danielhanchen
danielhanchen merged commit 6108ff5 into main Oct 23, 2026
3 of 33 checks passed
@danielhanchen
danielhanchen deleted the windows-safetensors-pread branch October 23, 2026 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant