Repository navigation
Studio: fix host memory checks and improve logging for GGUF image loads - #14514
Conversation
…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.
|
Thanks for the very detailed issue. Having the Event 2004 commit figure and the 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).
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.
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:
A shape that covers both: compare 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.
…th upstream [skip ci]
|
Thanks @LeoBorcherding, both points held up, so I changed the PR to the shape you suggested (6843699):
@VTplus if you can, please rerun the Turbo Q4 / Q8 load on the 48 GB host with this head. The |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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. |
|
pre-commit.ci run |
|
@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: Q4 passes too — 33 135 MiB physical available, 47 038 MiB commit headroom against the modeled 39 944 MiB need: 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: 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. |
|
As proposed: on top of the converged head I put an opt-in flag, 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:
Two measurements behind the flag, also taken without overloading anything:
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. |
|
pre-commit.ci run |
…th upstream # Conflicts: # tests/test_fp8_block_small_m.py
… 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]
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]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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", ()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Measured the pread path on Windows at
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). |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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. |
|
Now the Turbo Q8 load to complete the originally requested tests, on the same host and head; both live runs together:
Post-unload: VRAM back at the warmup residual (~0.5 GB of 32 GB), host commit again ~41 GB until the server releases it. |
#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.
…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).
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
CommitLimit - CommitTotal) withK32GetPerformanceInfo. 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.preadbackend (the scope Studio: stop LTX-2 loads crashing Windows with an access violation on 32 GB machines #13432 added for fp32 video encoders, generalized).preadreads each tensor into its own buffer, so the stored bytes are never charged to commit; this is what transformers 5.17 does on Windows (Fixsafe_openmmap memory exhaustion on Windows by usingpreadbackend 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.UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIBto cap the total, available and commit values the guard sees, for testing. It does not enforce a process memory limit.Known limitations
preadon Windows (Fixsafe_openmmap memory exhaustion on Windows by usingpreadbackend 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.Testing
studio/backend/tests/test_diffusion_small_host.pycovers 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 withpread; 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 tomainin all four arms.The same check with
UNSLOTH_SAFETENSORS_PREAD=1forced on: the dense load reads the converted encoder throughpread, and with the commit reading faked tight the route engages and keeps the encoder memory-mapped. Every arm's image is bit-identical tomain.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.