Skip to content

Studio: fix host memory checks and improve logging for GGUF image loads - #14514

Merged
danielhanchen merged 23 commits into
unslothai:mainfrom
VTplus:studio-host-ram-guard
Oct 23, 2026
Merged

danielhanchen merged 23 commits into
unslothai:mainfrom
VTplus:studio-host-ram-guard

Conversation

@VTplus

@VTplus VTplus commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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 Studio: stop LTX-2 loads crashing Windows with an access violation on 32 GB machines #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 (Fix safe_open mmap memory exhaustion on Windows by using pread backend 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 (Windows: read safetensors shards with pread on transformers 5.0 - 5.16 #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 (Fix safe_open mmap memory exhaustion on Windows by using pread backend 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.

…Windows commit headroom in the small-host guard
…ync branch with upstream

67 upstream commit(s) since the branch base; see git log for the range.
…ync branch with upstream

5 upstream commit(s) since the branch base; see git log for the range.
…ync branch with upstream

493 upstream commit(s) since the branch base; see git log for the range.
…ync branch with upstream

42 upstream commit(s) since the branch base; see git log for the range.
@VTplus
VTplus requested a review from danielhanchen as a code owner October 21, 2026 13:15
@LeoBorcherding

LeoBorcherding commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for the very detailed issue. Having the Event 2004 commit figure and the small_host log lines made this much easier to check.

Linux, full load: Colab T4 high-RAM (Tesla T4 15 GB, ~50 GB RAM, no bf16, so it does the same fp16 conversion as your V100). unsloth/Qwen-Image-2.1-Turbo-GGUF Q4_K_M on Qwen/Qwen-Image-2.1-Turbo, diffusers engine. Head 4377e46 against merge base af28041 on the same VM, with host memory sampled every 0.2 s.

run route result peak anon RSS
base dense, no log line loaded, image generated 22.8 GB
head dense, logs fits 45458 MiB loaded, image generated 23.0 GB
head, UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIB=36000 low-memory route loaded, image generated 8.7 GB
head, limit 4500 refusal "Not enough system RAM… about 7.5 GB… 4.4 GB is available", server stays healthy n/a

Windows, the commit side: Windows 11, 62 GB RAM, 46 GB pagefile (110 GB commit limit), Python from an isolated install of this branch. The GPU there computes in bf16, so this is not a full load: these are the pieces the guard depends on, run directly on CPU.

  • _windows_commit_headroom_mib() returned 90037 MiB. GlobalMemoryStatusEx gives the same figure to the MiB, and the Committed Bytes / Commit Limit counters agree within noise.
  • The new tests fail 7/7 on the merge base (the reader test runs here) and pass on head. With test_diffusion_memory.py the total is 179 passed, 1 skipped (the glibc-only test). Linux gives the same totals.

The route, the refusal, the env hook, the reader and the new log lines all work as described. Two things in the estimate, now measured on both OSes:

  1. The GGUF transformer is counted twice. _small_host_decision reads host_ram_mib() after the transformer is built (diffusion.py:10940-10941). diffusers copies every GGUF tensor into private memory when it loads the file (tensor.data.copy() in load_gguf_checkpoint), so both readings already exclude it. On Colab, available host memory went from 49613 MiB before the load to 45458 MiB at the decision. On Windows, loading the same Q4_K_M file took 4072 MiB of commit headroom and 3863 MiB of physical, for a 4005 MiB file. diffusion_small_host.py:244-245 then adds prebuilt=4005 again.

  2. The margin is in the right place for commit and the wrong place for physical memory, and on Windows it's too small. On Windows, loading the bf16 text encoder at fp16 peaked at 39561 MiB of commit, 2.06× the guard's dense of 19230 MiB, where the PR budgets 1.5× (28845 MiB). On Linux, physical memory matched the old estimate (anon RSS rose ~18 GB after the decision), while commit (Committed_AS) doubled the same way, rising 37.8 GB. Linux doesn't enforce commit, so loads that fit there now take the slower route. Using the real decide_small_host with the FLUX.1 fixture, a 64 GB host with 58 GB free now routes FLUX.1 fp16 to the int8 denoiser, where base loaded it dense. That's a quality change, not just speed.

A shape that covers both: compare dense (no margin, no prebuilt) against physical available, and compare ~2× dense against _windows_commit_headroom_mib() only when it's readable. Engage the route if either check fails. Right now the double-counted GGUF plus the reserve is what makes up most of the Windows commit shortfall. Fixing (1) alone would reopen your crash on hosts whose commit headroom lands in the gap, so I'd change both together.

Not tested: your crash itself on a host where commit is the binding side (the Windows box here has more commit headroom than physical). A full Unsloth Studio load on Windows with fp16 compute. The pipeline call site with a real FLUX.1 load (decision function only). Q8_0 and other quants.

…cal estimate

The GGUF DiT is already in both host readings when the guard runs (diffusers
copies every GGUF tensor into private memory), so adding its file size counted
it twice. The 1.5x margin on the physical check routed loads that fit on Linux
(FLUX.1 fp16 with 58 GB free went int8) while still under-budgeting Windows
commit, where the copy-on-write source views stay charged next to the
converted copy (measured 2.06x dense).

Compare the dense estimate against physical available as before, and on
Windows also compare dense + stored source bytes against the commit headroom;
either failing engages the low-memory route. The refusal stays on physical
RAM. Linux and macOS decisions are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks @LeoBorcherding, both points held up, so I changed the PR to the shape you suggested (6843699):

  • The GGUF file size is no longer added. I checked diffusers 0.41: load_gguf_checkpoint does torch.from_numpy(tensor.data.copy()), so the DiT is private memory before the guard reads host RAM.
  • The 1.5x margin is gone from the physical check, so Linux and macOS decisions are back to main exactly (864 of 864 cells in a decision grid; FLUX.1 fp16 with 58 GB free on a 64 GB host is dense again).
  • On Windows the guard also compares the dense load's commit need, the stored bytes plus the converted copy (2x dense at fp16, matching your 2.06x), against CommitLimit - CommitTotal. If that fails, the low-memory route engages. The refusal still uses physical RAM, because a system-managed pagefile can grow past the current limit.

@VTplus if you can, please rerun the Turbo Q4 / Q8 load on the 48 GB host with this head. The diffusion.small_host line now shows the commit headroom and the commit need.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-23T10:34:32.197210Z cdaf6f6 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.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 979d545a5f

ℹ️ 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".

@VTplus

VTplus commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @danielhanchen for the quick update, and thanks @LeoBorcherding for the detailed analysis.

I'll rerun Turbo Q4 and Q8 on the 48 GB host with this PR head, and report back with the diffusion.small_host logs, and load results.

Btw: I've saved my local rework on a separate branch, which also included commit estimates based on checkpoint mapping sizes and additional regression tests. Windows load testing of that rework was still pending.

@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@VTplus

VTplus commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

@danielhanchen here are the reruns on the 48 GB host against this head.

Host: 48 GB RAM with a fixed 16 GB pagefile (commit limit a hard 65 447 MiB), Tesla V100 32 GB fp16, Windows.

For testing: commit and physical memory sampled every 500 ms through every load.

Q8 decides dense with room on both budgets and loads fine:

diffusion.small_host: engaged=False (dense float16 load (19972 MiB) fits 39588 MiB available host RAM, 54260 MiB commit headroom (dense needs ~39944 MiB))

Q4 passes too — 33 135 MiB physical available, 47 038 MiB commit headroom against the modeled 39 944 MiB need:

diffusion.small_host: engaged=False (dense float16 load (19972 MiB) fits 33135 MiB available host RAM, 47038 MiB commit headroom (dense needs ~39944 MiB))

The measured commit climb confirms the stored-plus-converted model almost exactly: from 18 409 MiB at the decision point, the load reached a peak of 58 379 MiB — 39 970 MiB actual against 39 944 modeled, within 0.1%. At that peak python had filled physical RAM machine-wide (~1 GiB left), and that is the one state in which this host becomes unstable. (no crashes without these loads, and none with the model resident on the GPU)

The previous version of the guard (my original head 4377e46) keeps both quants on the low-memory route on the same host:

diffusion.small_host: engaged=True (dense float16 load needs ~33963 MiB + 4906 MiB reserve of host RAM, 34971 MiB available)

That path loads and generates fine and never enters the filled-physical-RAM state: commit peaks ~25 GiB above idle with ~15 GiB physical still free, nearly quant-independent.

That's why I'm currently working on an optional noswap mode (regarding image and video loads) on top of your pushed branch.

One more measured effect: eject seems to not return all commit:

On the 48 GB host, on the route path, unload gives back ~16.9 GiB but leaves ~5.3 GiB bound above the idle baseline (5.2 and 5.4 GiB on consecutive quants, barely cumulative); the same effect, larger, showed on a dense load in the 64 GB configuration, where ~11 GiB stayed bound between two consecutive loads (commit headroom 54 260 MiB before the first load, 43 194 MiB at the next decision). A following image load therefore starts with a tighter budget than a fresh one.

@VTplus

VTplus commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

As proposed: on top of the converged head I put an opt-in flag, UNSLOTH_DIFFUSION_HOST_RAM_NO_SWAP=1, in

https://github.com/VTplus/unsloth/tree/studio-host-ram-noswap

It caps the Windows commit budget at the physical RAM available, so a dense image or video diffusion load that would only fit by dipping into the pagefile takes the low-memory route instead (llama models unaffected as the llama.cpp loader keeps its own mmap options). Without the flag, or where no commit headroom is reported (Linux, macOS), nothing changes.

All numbers below come from a host-memory sampler (500 ms) next to the loads — host: 48 GB RAM, fixed 16 GB pagefile (hard 64 GB commit limit), V100 fp16. The flag-on runs never overloaded RAM; they stayed far from the limit:

load (fresh boot) decision commit peak outcome
Turbo Q4, flag on route (budget 27 749 MiB) 44 050 MiB (67 %) loaded + generated, clean unload
Turbo Q8, flag on route (budget 32 628 MiB) 38 418 MiB (59 %) loaded + generated, clean unload
Turbo Q4, flag off — same dense admission as the converged head dense 58 379 / 65 447 MiB (89 %) memory-manager bugcheck during teardown

Two measurements behind the flag, also taken without overloading anything:

  • Dense model check: the Turbo Q8 load logs a dense commit need of 39 944 MiB against 49 891 MiB headroom and stays dense; the sampler measured the real cost from the decision point at 39 970 MiB — 0.07 % off the model. The 2x dense estimate is the load.
  • Route check: once the route engages, materialisation adds 19 947 MiB of commit on top of the pre-load state (the mapped bf16 sources are copy-on-write views) — that path has no budget of its own yet.

The flag also names the budget kind and the stored source size in the decision log, keeps the dense LoRA exception, and carries unit tests for the cap, its boundary, the no-commit path and single-sample logging.
The route-side budget is deliberately not in it , since that might need its own discussion (meaning consecutive loads can still overload memory on the route).

@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

…th upstream

# Conflicts:
#	tests/test_fp8_block_small_m.py
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… shards

A scope with a target dtype now reads a shard through pread only when its
stored dtype differs from the target, so an fp32 encoder loaded at fp32 stays
memory-mapped; the video scope keeps its fp32-only rule. A shard the
small-host route keeps is forced to mmap even when transformers >= 5.17
passes backend=pread itself.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A concurrent image and video load (multi-model policy) shared one rule list,
so the image's keep entry for text_encoder kept the video's fp32 encoder on
mmap. Rules now live in thread-local storage; the safe_open patch stays
process-wide.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 21edd4113d

ℹ️ 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".



def _active_rules() -> tuple[tuple[Optional[str], frozenset[str]], ...]:
return getattr(_local, "rules", ())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve pread rules across parallel shard workers

When HF_ENABLE_PARALLEL_LOADING=true and a checkpoint has multiple shards, Transformers executes safe_open in executor threads, but the rules set by pread_safetensors() live only on the caller's threading.local, so those workers get (). This regresses the existing video scope (the old filename-only rule worked in workers) and makes dense image loads on pinned Transformers 5.5 stay mmap even though _small_host_decision() subtracts Transformers source views via pread_available(); on Windows, large converted encoders can therefore again exhaust commit. Associate rules with the load/snapshot or propagate them into shard workers without leaking them to concurrent media loads.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not reachable here: transformers 5.x (Studio pins 5.5; 5.16 the same) has no HF_ENABLE_PARALLEL_LOADING path. modeling_utils opens every shard with safe_open in a plain loop in the loading thread (5.5 line 4240) and its ThreadPoolExecutor in core_model_loading only materialises tensors from those already-open handles, so the thread-local rules are seen by every safe_open. Parallel shard workers exist in transformers 4.x and in diffusers' own load_file, neither of which this scope wraps.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…a through it

A thread with no active rule is outside every media scope, so the wrapper no
longer sends the keep flag there and unsloth's Windows pread default stands.
HiDream's 16 GB bf16 Llama text_encoder_4 loads before the pipeline scope, so
it now gets its own scope with the pipeline dtype.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4cd4d3f32c

ℹ️ 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".

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Measured the pread path on Windows at cdaf6f6: Windows 11, 62 GB RAM, Python from an isolated install of this branch. I loaded the Qwen/Qwen-Image-2.1-Turbo text encoder (16.7 GB bf16) at fp16 through transformers.from_pretrained, with and without pread_safetensors(convert_to=torch.float16), twice each:

peak private commit used settled private
mmap 39659 / 39705 MiB 39575 MiB ~22.9 GB
pread 22940 / 22959 MiB 20749 MiB ~22.9 GB

pread brings the peak down to the converted copy itself, so it removes the ~2× transient measured earlier. The resident result is identical, and the load is a few seconds slower. Commit is from the first pair only: another process on the box grew during the second pair and expanded the pagefile, which distorts those headroom readings. This is the component load on its own, not a full Unsloth Studio load (the GPU there computes in bf16).

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: cdaf6f6298

ℹ️ 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".

@VTplus

VTplus commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Just ran the Turbo Q4 load live on the Windows host again, now on the pread head: the guard keeps the load dense with a modelled commit need of ~20713 MiB (the converting encoder no longer adds its stored bytes on top of the converted copy), and measured host commit peaked at 69 percent of the 64 GB limit — load, generation and unload all clean, versus the same load on the pre-pread head which climbed to 89 percent and bugchecked.

One leftover observation for completeness: after unloading, commit stays around 41 GB until the allocator returns it, so consecutive loads start from a higher baseline.

@VTplus

VTplus commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Now the Turbo Q8 load to complete the originally requested tests, on the same host and head; both live runs together:

Turbo Q4 Turbo Q8
Decision dense (fits) dense (fits)
Modelled commit need ~20713 MiB ~20713 MiB
Host RAM available at the decision 29230 MiB 25277 MiB
Commit headroom at the decision 43886 MiB 39729 MiB
Measured host commit peak 45293 MiB (69 %) 49407 MiB (75 %)
Load / test generation / unload clean, no errors clean, no errors

Post-unload: VRAM back at the warmup residual (~0.5 GB of 32 GB), host commit again ~41 GB until the server releases it.

@danielhanchen
danielhanchen merged commit 03639b7 into unslothai:main Oct 23, 2026
4 of 38 checks passed
danielhanchen added a commit that referenced this pull request Oct 23, 2026
#14856)

## 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.
@VTplus
VTplus deleted the studio-host-ram-guard branch October 26, 2026 07:01
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 10, 2026
…unslothai#17378)

Fixes unslothai#17137

## Problem

On Windows, loading Qwen-Image-2.1-Turbo or FLUX.3 Klein (GGUF denoiser + base repo) onto an Intel Arc 140V (Lunar Lake iGPU, 32 GB shared RAM) fails with

```
OSError: The paging file is too small for this operation to complete. (os error 1455)
  transformers/modeling_utils.py, in _load_pretrained_model: safe_open(file, framework="pt", device="cpu")
```

and the retry kills the backend with `0xc0000005`, the native form of the same commit exhaustion (unslothai#13432, unslothai#14513).

Why:
- On Windows, safetensors' default mmap backend maps a shard copy-on-write, and Windows charges the whole view to the commit limit while any tensor from that shard is alive.
- Studio's media-load scope (unslothai#14514) moves only *converting* loads to `pread`; a same-dtype bf16 load keeps the mapping, which is fine on a discrete card.
- On an iGPU the device copy is host commit too. Qwen-Image-2.1's text encoder is one 16.3 GB bf16 file: its mapped view stays charged until the last tensor has moved to the XPU, so the load needs about twice the encoder in commit.

## Change

- `pread_safetensors(..., every_shard=True)` reads same-dtype shards through `pread` as well (component dirs the small-host route keeps mapped still stay mapped).
- The image-load scope sets it only on Windows when the current XPU is a Core Ultra Arc iGPU (`xpu_is_integrated()`, by PCI id: the iGPU subset of the existing XPU allowlist, split into `_INTEL_XPU_IGPU_PCI_IDS` with no change to `_INTEL_XPU_PCI_IDS`).

Every other platform and device keeps the byte-identical path: off Windows the scope installs nothing, and on Windows a CUDA, ROCm, discrete Arc or unclassifiable XPU load passes `every_shard=False`.

## Tests

`studio/backend/tests/test_safetensors_pread_igpu.py`: the iGPU classifier over Lunar Lake / Meteor Lake / Panther Lake vs discrete Arc / Data Center ids, the backend choice with and without `every_shard`, the image-load scope engaging only on Windows + iGPU, and a Windows-only commit measurement (bf16 load at bf16, then each weight copied the way `.to("xpu")` does on shared memory, mmap vs pread arms).
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.

Studio: GGUF loads can crash the server on Windows instead of taking the low-memory route

3 participants