Repository navigation
Conversation
Use host headroom and cgroup v2 limits for integrated CUDA admission, cache sizing, and calibration. Preserve RAM-copy settings; offload duplicate CUDA weights when a retained copy exists. Spark pressure validation remains pending.
Use host headroom for UMA workload sizing and serialize local admissions. Refuse minimum-weight loads over budget; guard the Qwen quantized allocation.
Use marker-gated direct wheel URLs for the self-built Windows ARM64 wheels, leaving PyPI as the Windows x64 source. Verify both Windows routes in the lock checker and keep direct URLs out of published project metadata.
This reverts commit ea97e8f.
Resolve unset retained-copy config per device topology while preserving explicit values. Update config docs and API artifacts, and cover defaults and YAML overrides.
Use the Triton 3.8 wheel with ARM64 PyTorch 2.14. Update install and feature docs.
Keep integrated-CUDA models warm until shared-memory headroom requires space, then drop unlocked cache entries instead of moving them to CPU RAM. Reuse allocator-held blocks under capped and uncapped budgets. Document cache capacity and idle release behavior.
Add a read-only cross-platform host and CUDA memory inventory. Include Linux cgroup and Windows WDDM counters when available.
Use Spark's CUDA-reported shared pool as the cache ceiling and evict idle entries under live pressure. Keep RAM weight copies off by default on integrated CUDA, and retain accounting while live handles reference evicted models. Extend the bounded allocation probe beyond 64 GiB and document Spark limits.
joshistoast
left a comment
There was a problem hiding this comment.
Avoiding duplicate CPU weight copies on Spark is worthwhile. I’m requesting changes because Windows GPU budgeting can reject models that fit, Linux cold loading and eviction can exhaust RAM, and two lock paths can hang generation. The inline comments give the affected lines and a way to address each issue.
732 focused tests passed locally, with one deselected. The preview lock cycle was reproduced in isolation, and the stale Queue usage was reproduced with mocked Spark detection. This review did not exercise generation under memory pressure on Spark hardware.
Use shared-pool budgets and live host headroom for model loading.\nAccount for quantized preparation peaks and deferred release lifetimes.\nDocument Spark memory behavior and add regression coverage.
|
@joshistoast, I addressed all ten inline findings:
I ran the changed Python tests: 762 passed, 4 deselected. Ruff, formatting, and diff checks passed. The docs tests and build passed earlier. Windows image generation and the allocation probe were exercised; Linux pressure behavior and Windows allocation beyond the configured commit floor remain unverified. CI for this commit has not reported yet. Please re-review the updated branch. |
…lock tests The restore gate reads layer_patcher's own device_is_integrated_cuda import, which the tests left real: on an integrated machine the 'dedicated' parametrization silently took the gated path. Patch both modules' detectors so the cells mean what they name, and correct the seam comment: under force_sidecar_patching the direct-patch restoration never runs, so the seam's emptiness guard is deliberate insurance, not the dispatch.
|
Round-4 fixes are pushed ( P1s
P2s / P3s: cap item dissolves with the credit removal; the self-funding test file's skip is gone (cache built inside the integrated patch, ~5MB tensors, verified with Two extra fixes fell out of re-gating on the Windows Spark: on the real integrated-CUDA box, Verification for this round: RED captured per fix (pool oversold by 530,432 bytes; ask 4,198,400 vs 5,249,024; cleared-1/refused; component assertion; starved-host refusal). Local affected sweeps 5,746 and 4,417 passed / 0 failed. Linux Spark DGX: 6,038 passed pre-merge, 5,600 after the second merge, exit 0. Windows Spark (integrated CUDA live): four serial chunks at the merge head - model_cache 871, load-minus-cache 1,451, model_load+ram+patches 1,112, working memory 2,429 - 5,863 passed / 0 failed. Main merged once more ( |
joshistoast
left a comment
There was a problem hiding this comment.
Reviewed 40181bb33a. This is very close and I have no P1s left. All eight findings from the last round are fixed, and each fix fails a test when I revert it, with CUDA visible and hidden (13 of 13 reverts caught).
What I checked on this head:
- Lock credit: gone at all three sites. The lock path matches
dbb2d03b1eapart from the new comment. - Ceiling helper: dropped models now really die. Real CLIP, T5, VAE, UNet and FLUX instances were freed without a garbage-collection pass.
- The main merge in
layer_patcher.py: head is main's file plus the gating. On dedicated devices restore takes no lock, as on main, and I found no lock-order inversion. reserve_for_load: 3,000 random state dicts gave main's cache figure every time.- CI: all green, and the workflow diff against main is empty. windows-cpu ran 381 s against 266–337 s on main's last three runs, and windows-arm64 1/4 ran 881 s against 747–783 s. That is one sample each, so I am only noting it.
I would like two things before merging, both inline and both older than this round, so I should have caught them sooner: the Mistral GGUF tokenizer estimate parses the file two extra times on every device, and on integrated CUDA an idle model with a RAM copy is evicted where it could be moved to RAM. The P3 comments are fine as follow-ups.
For the description:
- "Patch restore no longer takes the global load lock" is not a change. Main takes no lock there.
- Unlisted, on every device:
load_model_from_pathnow callsmake_room(0, …)before the loader runs,keep_ram_copy_of_weightsnow reportsnullwhen unset in the config and API schema, andcontext.modelshas a new public method. - Unlisted cost of removing the credit: an integrated lock can evict a neighbour it did not need, or refuse a minimum-weight load that would fit. A line pointing at #10436 would cover it.
- The "Review rounds" bullet and the "All inline findings… are replied to" paragraph are process narration, and "Local full Python suite at
dbb2d03b1e" refers to an old head.
Not verified on my side: real Spark, Mac, ROCm or Windows hardware (the integrated results are simulations on an RTX 5090 with the device classification and host sampler patched), the GGUF timing on a real Mistral file, live generation, and family E2E. The PR's changed test files under the cache, patches, model-load and util test directories passed locally: 822 passed, 45 skipped.
| def _embedded_tekken_size(model_path: Path) -> int: | ||
| """Return the decoded Tekken byte count from container metadata without reading tensor payloads.""" | ||
| suffix = model_path.suffix.lower() | ||
| try: | ||
| if suffix == ".safetensors": | ||
| from safetensors import safe_open | ||
|
|
||
| with safe_open(str(model_path), framework="pt") as f: | ||
| if "tekken_model" not in f.keys(): | ||
| return 0 | ||
| tensor = f.get_slice("tekken_model") | ||
| if tensor.get_dtype() != "U8": | ||
| return 0 | ||
| size = 1 | ||
| for dimension in tensor.get_shape(): | ||
| size *= dimension | ||
| return size | ||
| if suffix == ".gguf": | ||
| import gguf | ||
|
|
||
| for tensor in gguf.GGUFReader(str(model_path)).tensors: | ||
| if tensor.name == "tekken_model": | ||
| # Embedded GGUF variants store one value per original tokenizer byte; the loader | ||
| # converts the payload to one byte per element regardless of its source dtype. | ||
| return int(tensor.n_elements) | ||
| except Exception: | ||
| return 0 | ||
| return 0 |
There was a problem hiding this comment.
[P2] Mistral GGUF tokenizer loads parse the file three times, on every device
_mistral_tokenizer_size and _mistral_tokenizer_host_bytes_needed each call this, and for a GGUF it builds a full GGUFReader, which parses every metadata field. load_default.py:573-574 calls both on every device, although the host figure is only used on integrated CUDA. The loader's own _extract_tekken_bytes then parses the file a third time. Main parses it once. All of this runs under the model-load write lock.
On a synthetic file shaped like a llama.cpp conversion (131,072 tokens and 269,443 merges in the metadata, no tekken_model tensor):
| Step | Time |
|---|---|
one plain GGUFReader |
5.5 s |
| the two estimate calls together | 12.4 s |
| the loader's own parse (main does this too) | 6.0 s |
I had no real Mistral GGUF to time, so the real cost may differ. The three parses against one are from the code.
Please compute the Tekken size once per load, for example memoised on path, size and mtime, and only ask for the host estimate when the cache's device is integrated CUDA.
There was a problem hiding this comment.
Fixed in 6685f9edbc. The Tekken figure is now memoised on (path, size, mtime_ns) with a bounded lru_cache, so the full GGUFReader metadata parse runs once per cold load for the sizing + admission pair; the loader's own _extract_tekken_bytes payload read stays a separate real read (it needs the bytes, not the count). And the second half: ModelCache.host_admission_applies() mirrors the internal integrated gate in _make_room_internal, and load_default.py only calls _get_host_bytes_needed where that is true — on dedicated/CPU/MPS caches the figure is discarded inside make_room, so the estimation is skipped outright. RED: a GGUFReader construction counter showed 2 parses per estimate pair at head (both with and without a tekken_model tensor), 1 now; a spy showed _get_host_bytes_needed called on a dedicated device at head, not called now.
| if integrated_cuda: | ||
| has_live_handles = bool(cache_entry.live_handles) | ||
| if has_live_handles and cache_entry.cached_model.get_cpu_state_dict() is not None: | ||
| # A live handle keeps the record usable after eviction. When the cache already owns a | ||
| # complete CPU shadow, unload the device weights in place instead of detaching the record: | ||
| # materializing another shadow would be wasteful, and detaching would leave the handle's | ||
| # device weights resident while reporting zero bytes freed. | ||
| epoch = TorchDevice.release_epoch() | ||
| cache_entry_bytes_freed = self._move_model_to_ram(cache_entry, vram_bytes_shortfall) | ||
| if cache_entry_bytes_freed > 0: | ||
| self._logger.debug( | ||
| f"Unloaded {cache_entry.key} from VRAM to free {(cache_entry_bytes_freed / MB):.0f} MB." | ||
| ) | ||
| if empty_cache_per_offload: | ||
| # An integrated device's budget is the shared host pool, not the cap: a deferred or | ||
| # refused trim is still credited, unlike the dedicated-device capped-budget path. | ||
| outcome = TorchDevice.empty_cache() | ||
| if outcome is EmptyCacheOutcome.RAN: | ||
| released() | ||
| elif outcome is EmptyCacheOutcome.DEFERRED: | ||
| ledger.defer(cache_entry_bytes_freed, epoch) | ||
| else: | ||
| vram_bytes_refused += cache_entry_bytes_freed | ||
| vram_bytes_freed += cache_entry_bytes_freed | ||
| continue | ||
| # Drop unowned UMA entries directly: moving them to CPU would materialize a second copy first. | ||
| epoch = TorchDevice.release_epoch() | ||
| cache_entry_bytes_freed = 0 if has_live_handles else cache_entry.cached_model.cur_vram_bytes() | ||
| self._delete_cache_entry(cache_entry) |
There was a problem hiding this comment.
[P2] An idle model with a RAM copy is evicted where it could be moved to RAM
The branch above moves a model to RAM only when it has a RAM copy and live handles. An idle entry with a RAM copy and no handles falls through to this drop, and its RAM copy goes with it. The comment here ("moving them to CPU would materialize a second copy first") is only true for entries without a RAM copy.
This affects integrated CUDA with keep_ram_copy_of_weights: true. The docs say that setting "speeds switching", and the description says explicit values remain honored. Main moves the model to RAM and keeps it cached, so its next use is a copy from RAM, not a load from disk. Dropping also frees both copies when only the device copy needed to go.
Simulated with two 8 MB models, keep-copy on, and the pool short by half a model: locking B deleted A from the cache.
Please send any entry whose get_cpu_state_dict() is not None through _move_model_to_ram, with or without live handles, and drop only entries without a RAM copy. If dropping is deliberate, the docs for keep_ram_copy_of_weights on integrated CUDA need to say so.
There was a problem hiding this comment.
Fixed in 753b40f22e — your reading was right. The move branch now fires on get_cpu_state_dict() is not None alone; only RAM-copy-less entries drop, and the drop comment states the reason that is actually true (a move would materialize a second copy). Checked _move_model_to_ram first: it keys on is_locked (locked entries are skipped earlier in the loop) and skips host admission when a CPU shadow exists, so the handle-free move is sound. RED: an idle no-handle entry with a shadow was deleted from the cache entirely (assert 'idle' in {}); it now ends cached at 0 bytes resident, shadow intact, full size reported freed.
| if required_bytes > max(vram_available, 0): | ||
| raise torch.OutOfMemoryError( | ||
| f"Cannot load the minimum required weights for model '{cache_entry.key}' onto " | ||
| f"{cache_entry.cached_model.compute_device}: they need {required_bytes / MB:.2f}MB but only " | ||
| f"{max(vram_available, 0) / MB:.2f}MB is available. The device shares memory with the CPU, " | ||
| "so proceeding would exhaust system memory. Free up RAM, use a smaller or more heavily " | ||
| "quantized model, or lower `device_working_mem_gb`." | ||
| ) | ||
|
|
There was a problem hiding this comment.
[P3] "only 0.00MB is available" when gigabytes are free
vram_available already has the working-memory reserve taken off (device_working_mem_gb, 3 GB by default). With 2.9 GB of host memory free, a 10 KB model is refused with "they need 0.01MB but only 0.00MB is available". At 3.1 GB it locks.
This is what your two hermeticity fixes ran into, and I agree the refusal itself is the guard working as designed. The message is the problem: it tells the user nothing is free when the reserve is what blocked the load. Please report the free figure and the working memory held back, so "lower device_working_mem_gb" makes sense.
There was a problem hiding this comment.
Fixed in 982cebe6d0. Both refusal messages now say, e.g. "they need 0.01MB but only 0.00MB is usable: 3072.00MB of host memory is free, of which 3072.00MB is being held back for working memory (device_working_mem_gb)". The figures come from a _shared_memory_diagnostic helper (working-mem reserve + reserve_vram_gb + the streaming reserve), reached only when raising. RED test patches the host sampler to exactly the reserve so the shortfall is purely the holdback and asserts the new wording. My own follow-up review of that helper found three more accuracy gaps, fixed in 06d0e90eff: it re-sampled host memory while raising, so a sampler failing at that instant escaped the refusal handler into the generic one and deleted an untouched cache entry (now raise-proof, entry survives); it ignored an explicit max_vram_cache_size_gb, which on an integrated device is often the real limiter, so the advice sent users to free RAM they had free (the cap is now named in the message); and the full-load guard priced the holdback from the configured default rather than the lock's requested working memory (now threaded through). Each has its own test (RED: sampler error escaped + entry deleted / no cap clause / 1024.00MB held back where 4096.00MB was asked).
| if ( | ||
| hasattr(cache_entry.cached_model.model, "to") | ||
| and (_is_integrated_xpu(device) or device_is_integrated_cuda(device)) | ||
| and model_bytes_needed > vram_available | ||
| ): |
There was a problem hiding this comment.
[P3] A full-load refusal also deletes the model from the cache
This refusal is raised inside the try, so the handler below deletes the entry although nothing moved. The partial-load refusal keeps its entry, and a test asserts that. Integrated XPU already behaved this way; this line extends it to integrated CUDA. I read this from the code and did not run it.
Raising before the try, or letting this error past the delete the way HostMemoryAdmissionError is handled, would make the two paths agree. Fine as a follow-up.
There was a problem hiding this comment.
Fixed in 982cebe6d0 (your first option, taken as part of the same raise): the guard raises _SharedMemoryLoadRefusal(torch.OutOfMemoryError) and an except _SharedMemoryLoadRefusal: raise clause sits before the delete handler, so the entry survives — same outcome the partial-load refusal's keeps-entry test already pins. Callers still see torch.OutOfMemoryError (lock()/continue_lock() classify on it and only unpin). RED: entry existed, lock raised, entry gone at head; GREEN: entry survives, unpinned, not detached.
| def make_room_in_vram_with_write_lock(self, vram_bytes_needed: int) -> int: | ||
| """Make room while the caller holds `MODEL_LOAD_LOCK`'s write lock. | ||
| This is for an out-of-cache load that has already serialized construction and must recheck shared memory | ||
| without dropping the writer lock. The cache call still acquires its own admission and cache locks. | ||
| """ | ||
| return self._services.model_manager.load.ram_cache.make_room_in_vram(vram_bytes_needed) |
There was a problem hiding this comment.
[P3] A public node API that is only safe while holding an internal lock
This is on context.models and is listed in docs/src/generated/invocation-context.json, so custom nodes can call it. It is correct only when the caller already holds MODEL_LOAD_LOCK's write lock, and nothing checks that. A node that calls it without the lock skips the load lock entirely.
The only caller is the Qwen image text encoder. Please keep this internal to that caller, or assert that the write lock is held.
There was a problem hiding this comment.
Fixed in 0524a87cf5 with the assert option. _ModelLoadReadWriteLock now records the writer's thread id at acquisition (cleared at release, same fields, same critical section — no new locking), and write_lock_held_by_current_thread() answers it. make_room_in_vram_with_write_lock raises RuntimeError naming the contract when the caller isn't that writer; docstring Raises: added and docs/src/generated/invocation-context.json regenerated (028a988cd8). RED: unguarded call raised nothing at head. The only caller (Qwen image encoder) already takes MODEL_LOAD_LOCK.write_lock() around the call — verified by reading; a happy-path test calls the real method inside the write lock against a real ModelCache without deadlock.
| """Integrated-CUDA lock admission charges an entry's full bytes-left-to-move, even without a RAM copy. | ||
|
|
||
| A no-RAM-copy entry may own its CPU tensors or merely view them: many loads leave parameters as | ||
| views of the safetensors file mapping (single-file loads with `assign=True`, `from_pretrained` at | ||
| the stored dtype). Dropping a mapped view returns nothing to the pool - untouched pages were never | ||
| resident and touched ones are clean page cache the host sample already counts as available - so | ||
| the host figure falls by the device bytes as they land, and the demand is the whole move. Torch | ||
| cannot tell a mapped storage from an owned one, so the cache charges every no-RAM-copy entry the | ||
| full amount rather than crediting a class it cannot identify. | ||
| """ |
There was a problem hiding this comment.
[P3] The file is named after the feature it no longer has
With the credit removed, test_model_cache_integrated_lock_admission.py or similar would describe it.
Two things inside it:
- The "mapped" and "owned" tests build the same freshly allocated
nn.Linear. The only mapped part is the mocked move lowering the free figure, so the two names promise a contrast the tests do not make. - The owned-weights test asserts on the arguments passed to two private methods. It is the only test that catches a revert of the eviction ask, so it cannot just go. Asserting on the outcome (an idle neighbour stays or is evicted) would test the same thing through behaviour.
There was a problem hiding this comment.
Fixed in 650449341c — all three points. The file is now test_model_cache_integrated_lock_admission.py. The fictional mapped/owned pair merged into one pool-oversell invariant test (one test per real behavior; the "mapped" contrast was indeed just the mocked move). The args-spy test asserts the outcome now: with an idle unowned resident neighbour and free covering the largest module but not the full move, the neighbour is evicted and the lock settles. Regression strength proven by scratch-reverting model_cache.py to the pre-removal credit version: the reworked tests fail three ways (pool oversold by 530,432 bytes; neighbour stayed; refusal not raised); all pass at head.
| @pytest.fixture(autouse=True) | ||
| def _stable_host_headroom(monkeypatch: pytest.MonkeyPatch): | ||
| """These locks stream real micro-models through the real cache, and on an | ||
| integrated-CUDA machine admission reads live host RAM: a box that happens to be | ||
| out of RAM refuses a 10KB model here while the same tests pass everywhere else | ||
| (right in production, ambient in a test). The budget arithmetic has its own unit | ||
| tests; pin the OS sampler to a healthy figure so the guard stays reachable but | ||
| deterministic.""" | ||
| from invokeai.backend.model_manager.load.model_cache import model_cache as mc | ||
| from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import ( | ||
| weight_streaming as weight_streaming_module, | ||
| ) | ||
|
|
||
| healthy = 64 * 1024**3 | ||
| monkeypatch.setattr(mc, "_host_memory_available", lambda: healthy) | ||
| monkeypatch.setattr(weight_streaming_module, "_host_memory_available", lambda: healthy) |
There was a problem hiding this comment.
[P3] The same host-sampler pin now lives in three files
This autouse fixture has the same body in cached_model/test_cached_model_only_full_load.py:25 and model_loading/test_model_load.py:13. The scope is fine: none of the tests in these files is meant to exercise host admission. One shared fixture in a conftest that the three files opt into would keep them from drifting.
test_async_weight_streaming.py also drives the real cache on CUDA without a pin. With the device patched to integrated it only starts failing at about 1 MiB of host memory, so the risk is low.
There was a problem hiding this comment.
Fixed in c0a7180765: one non-autouse stable_host_headroom fixture in tests/backend/model_manager/conftest.py, opted into per file via module-level usefixtures — the three originals plus test_async_weight_streaming.py (confirmed it drives real ModelCache.lock on CUDA before opting it in). Verified live with --setup-show.
|
|
||
| @pytest.mark.parametrize( | ||
| ("integrated_cuda", "hip"), | ||
| [(False, None), (True, None), (False, "6.2")], | ||
| ids=["dedicated", "integrated", "rocm"], |
There was a problem hiding this comment.
[P3] The device cells here do not test the device gate
The integrated cell passes exclusive_model_load_lock=True, so the blocked move proves the exclusive write lock. Removing the integrated gate from layer_patcher.py does not fail this test, and forcing the gate on every device does not fail its dedicated cell. Only test_restoration_waits_on_model_construction_only_on_integrated_cuda catches the gate, and it does so in both directions.
The rocm cell at line 886 repeats the dedicated one, because both classifiers are patched to False and hip has no effect.
I would drop the device parametrization from this test, and drop the rocm cell or make hip matter.
There was a problem hiding this comment.
Fixed in 52b3723ce7: parametrization and the inert torch.version.hip patch dropped. One deviation from your example: I pinned the classification True rather than False — with classifiers False, cuda_device_allocation_lock is a no-op on both sides and the "device allocation lock" half of the test's own name would assert nothing; the integrated cell was the only one exercising anything, and it's preserved as the single configuration. The docstring points at test_restoration_waits_on_model_construction_only_on_integrated_cuda as the gate's owner (untouched). Mutation-checked: removing the restore holds fails this test and the gate test; removing only the integrated clause fails just the gate test.
| - **RAM**: unless you set `max_cache_ram_gb`, the cache gets half your system RAM minus 2GB. On a GPU with dedicated | ||
| memory that is capped at its VRAM minus `device_working_mem_gb` (or at `max_cache_vram_gb` if you set it). The log | ||
| shows this calculation at startup: `Calculated model RAM cache size: … MB`. Native | ||
| integrated CUDA skips the half-RAM heuristic: its automatic RAM-cache limit is the CUDA-reported allocation pool | ||
| minus `device_working_mem_gb`, with a 4GB minimum. If you set `max_cache_vram_gb`, the pool is capped at that value |
There was a problem hiding this comment.
[P3] Two facts about the automatic RAM cache were dropped
Main's text said the automatic figure is capped at 32GB where there is no dedicated GPU, and is never below 4GB. Both are still true in _calc_ram_available_to_model_cache (32 * GB and MIN_RAM_CACHE_BYTES), but the rewrite lost them. The integrated-CUDA sentences that follow do match the code.
There was a problem hiding this comment.
Fixed in 1aef0f5512: the 32GB cap where there is no dedicated GPU and the never-below-4GB floor are back, re-verified against _calc_ram_available_to_model_cache (max_ram_cache_size_bytes = 32 * GB default, MIN_RAM_CACHE_BYTES floor).
| from invokeai.backend.util.devices import _host_memory_available | ||
|
|
||
|
|
||
| class _PerformanceInformation(ctypes.Structure): |
There was a problem hiding this comment.
[P3] This script has no test and no doc link
This struct also duplicates _WindowsPerformanceInformation in devices.py. None of the three Spark scripts is referenced from a doc page, so nobody will find them. Please link them from a development doc, or drop the ones that were only needed while building this.
There was a problem hiding this comment.
Fixed in 350454b41b. I kept all three scripts — the probe imports the reporter's counter helpers (_cgroup_memory, _windows_memory, build_report), and all three answer distinct diagnostic questions (counters, allocation pool, keep-copy switching), two with test coverage. The duplicated struct is gone: report_spark_memory.py now ctypes-imports the same PERFORMANCE_INFORMATION structure from devices.py. And they have a doc home: development/Guides/spark-memory-diagnostics.mdx (sidebar autogenerates it), stating what each measures and when to reach for it.
The rewrite dropped two facts that still hold in _calc_ram_available_to_model_cache: the 32GB cap where the execution device reports no dedicated memory, and the 4GB floor.
… dropping them With keep_ram_copy_of_weights on, an idle integrated-CUDA entry whose device copy is redundant fell through to the drop branch and was evicted entirely; the cache already owned the CPU shadow, so the device copy could simply be unloaded in place and the entry kept for the next use (a RAM copy from RAM, not a rebuild from disk). Dropping remains right only for entries without a RAM copy, where a move would first materialize a second copy.
… memory The min-weights and full-load shared-memory guards reported "only 0.00MB is available" while gigabytes were free: the figure is post-reserve. Both messages now report the free host figure and how much of it is held back by device_working_mem_gb (plus the streaming reserve), so the advice to lower it is actionable. The full-load guard now raises a marked refusal subclass so the entry survives the refusal (nothing was moved), matching the partial-load guard; the error still surfaces as torch.OutOfMemoryError for callers that classify on it.
… Windows struct The three Spark diagnostics scripts were unreferenced, so nobody would find them; a development guide now explains what each measures and when to reach for it. report_spark_memory.py re-declared the Windows PERFORMANCE_INFORMATION struct ctypes-imported already in devices.py; it now imports it. Verified: all three scripts run --help, and the probe/benchmark test files pass unchanged (16).
…ytes only where used Sizing and host admission each built a full GGUFReader over the tokenizer metadata (hundreds of thousands of tokens/merges dominate), and load_default asked both on every device although the host figure is consumed only under integrated-CUDA host admission. The Tekken size is now memoised on (path, size, mtime) for one parse per cold load, and ModelCache.host_admission_applies() - mirroring the internal integrated gate - lets the loader skip host-only estimation elsewhere. A GGUFReader construction counter shows one parse where there were two.
…ame the file, skip unread dirs Every uncached path load walked the model tree and asked make_room for host admission on every device: on dedicated/CPU/MPS caches the figure is discarded and make_room(0) can still evict an over-cap cache. The block now runs only where host admission applies. The walk no longer charges directories the path loader never opens (onnx/, scheduler/, feature_extractor/): it descends only into subtrees holding weight files. The refusal now names the file it refused.
…ost memory The nf4 transformer and text-encoder branches sized host admission by the full state dict, so on integrated CUDA the ceiling demanded that much free RAM - although the state dict is already resident (safetensors mmap) and the meta-built model aliases it via assign=True, allocating nothing new. host_bytes_needed=0 keeps the cap-side eviction ask unchanged. Two real-nf4-fixture tests against a real ModelCache with 4 KiB host-free (RED: MemoryError; GREEN: admitted, InvokeLinearNF4 with live quant_state).
The fp8-branch comment pointed at a since-removed dense FP8 path; it now states what the cast itself does (non-persistent RoPE buffers take the compute dtype from it, not the checkpoint). The preview-lock test's comment described the old admission-then-read order; it now describes today's single lock order and why the choreographed crossing must bound out.
…ock room API context.models.make_room_in_vram_with_write_lock is node-facing but deliberately takes no MODEL_LOAD_LOCK itself - correct only for a caller already holding the write lock; an unprotected caller would race the model-construction monkey-patches. The read-write lock now tracks the writer's thread id, and the method raises RuntimeError naming the contract when the calling thread is not that writer. The only internal caller (Qwen image encoder) already takes the write lock around the call.
…eed it Four suites drive the real model cache with real CUDA on hosts where integrated admission reads live RAM; the same autouse pin had been copy-pasted into three files. One named fixture in a shared conftest, opted in per file, with async weight streaming opted in too - the reviewer noted it unpinned.
…prove the charge by outcome The file kept the name of the self-funding credit round 4 removed. Its fictional "mapped vs owned" pair (both built freshly allocated modules) merged into one honest pool-oversell invariant, and the private-method args spy became an outcome test: an idle unowned neighbour IS evicted when the lock is charged the full move. Against the pre-credit code the reworked tests fail three ways (pool oversold, neighbour stayed, refusal not raised); at head all pass.
…ock test The [dedicated, integrated, rocm] parametrization proved nothing about the device gate: exclusive_model_load_lock alone holds the restore block on every device, and the rocm cell was the dedicated cell with an inert hip patch. One configuration (integrated classification pinned so the device-allocation half of the name means what it says); per-device gating stays owned by test_restoration_waits_on_model_construction_only_on_integrated_cuda. Mutation-checked both ways.
The walk-filter test materialized a 10GiB bytes object, which OOM-killed an xdist worker on the linux-cpu CI lane. The walk only reads st_size through the estimator, so truncate() gives the same figure without the allocation (verified: calc_model_size_by_fs reports 10737418240 for the sparse file, identical to the materialized one).
…of and complete Three message-accuracy defects in the guard added this round: the diagnostic re-sampled host memory while raising, so a sampler failing at that instant escaped the refusal handler into the generic one and deleted a cache entry nothing had touched, replacing an actionable refusal with the sampler error (it is now raise-proof and the entry survives); the holdback ignored an explicit max_vram_cache_size_gb, which on an integrated device may be the real limiter, so the advice sent users to free RAM they had free (the cap is now named); and the full-load guard priced the holdback from the configured default instead of the lock's requested working memory (now threaded through).
|
Round-5 fixes are pushed ( P2s
P3s
Also this round ( Verification for this round: local affected sweep 5,923 passed / 0 failed, post-follow-up sweep 7,969 passed / 0 failed (plus the new-test RED/GREEN runs); local full suite at |
…rated CUDA Under pressure an idle model with a RAM copy is unloaded from the device, then any device weights it still holds, and is dropped only when the request is still short; under max_cache_vram_gb drops stop once the cap is the limit. The full-load shared-memory refusal is a plain torch.OutOfMemoryError raised before anything moves, and refusal messages name max_cache_vram_gb only when it binds and price reserve_vram_gb separately. The 10 GiB test fixture is 4 KiB, since truncate() zero-fills on Windows; the Spark diagnostics page gains run commands.
…the load On integrated CUDA a model that loads in full, or an out-of-cache load, drops idle models with a RAM copy only if doing so meets the request; a refused load no longer empties the cache first. A refusal under a binding max_cache_vram_gb names the bytes already in use on the device, and a failed host sample no longer hides the cap. The low-VRAM docs scope the unload-before-drop behaviour to moving a model onto the GPU.
Budget GPU moves against CUDA capacity and system commit on Windows, and preserve idle weights when eviction cannot relieve the shortage. Size Wan expert residency and Wan, Gemma and FLUX.3 loader allocations from the work each performs. Include cache-miss reconstruction in the Spark switch benchmark.
Size the selected checkpoint files, tokenizer construction and FP8 scale conversions before loading. Account for mandatory buffers, warm branch weights and native allocator splits during cache admission. Check host, shared and device headroom before constructing benchmark models.
… room stub Single-file loaders now pass host_bytes_needed to make_room, so the calibration script's stub must accept it like the cache does.
… reads On Windows the integrated offload measures _integrated_cuda_budget_limits directly, so a stubbed _get_vram_available left the eviction test reading the runner's real headroom. Stub the shared budget limits and run the case on both platforms.
Keep shared backing charged until its final view is released during model loads. Credit inactive cgroup file pages conservatively using dirty and writeback counters.
Use one headroom sample for the four callers and remove two redundant CUDA checks.
Summary
Integrated CUDA devices now use a shared-memory budget for model-cache sizing and pressure decisions. Spark defaults avoid duplicate CPU weight copies, retain the configured idle timeout, and account for conversion buffers, tokenizer construction, and asynchronous pinned weights during admission. Windows Spark documentation includes NVIDIA's page-file guidance. Three diagnostic scripts (
scripts/report_spark_memory.py,scripts/probe_spark_gpu_allocation.py,scripts/benchmark_spark_model_cache_copy.py) and a Spark Memory Diagnostics development guide are added.Cross-hardware behavior changes
put(); weight-streaming host-headroom checks run only for integrated holders. A lock is charged the model's full bytes left to move, because weights mapped from the model file return nothing to the pool when they move; the cost is that a lock can evict an idle neighbour it did not need, or refuse a minimum-weight load that would fit (Integrated CUDA: fund self-funding model locks by moving in passes sized by a fresh host sample #10436 tracks a pass-by-pass design that avoids this).keep_ram_copy_of_weights: true: when moving a model onto the GPU runs short, an idle model is unloaded from the device first and kept in RAM, and is dropped only when that is not enough. A model that loads in full, or an out-of-cache load, drops idle models only if doing so lets it fit. Loading a new model from disk under host-memory pressure drops idle models directly.OutOfMemoryError. The text states free host memory, the working memory andreserve_vram_gbheld back, andmax_cache_vram_gbwhen it is the limit, which on integrated XPU is whenever it is set.make_roomeviction sizes changed where the disk-size estimate changed:get_size_fsnow returns the transformer-payload bytes for FLUX.1 bundles (main charged the whole file), the connector's payload subset for LTX-2 connector requests, and the actual tokenizer footprint for tokenizer submodel requests instead of up to the whole file - the sizing overrides cover Qwen-VL single-file, Qwen3.5, Krea-2, Mistral, Z-Image, TextLLM and the T5/Gemma loaders, matching what the loaders actually allocate. The Mistral GGUF tokenizer size is memoised per process on path, size and mtime.keep_ram_copy_of_weightsis unset by default and reportsnullin the config and API schema; unset means on, except on integrated CUDA where it means off.context.models.make_room_in_vram_with_write_lockis a new public node API. It raisesRuntimeErrorunless the calling thread holds the model-load write lock.offload_model_from_vram,offload_models_from_vram_exceptandoffload_unlocked_models_from_vramreturn 0 without touching the cache for integrated XPU, for integrated CUDA without a kept RAM copy, and for CPU execution.safetensors_payload_bytes(), used by the three sizing paths in this PR that consumedata_offsets.get_size_fscan now raise on FLUX bundles with out-of-range offsets where main returned an fs size (broken-file loads only);qwen3_vl's offset sum andint8_convrot's marker reads predate this PR and keep main's behavior.read_safetensors_headerrefuses any header longer than 100,000,000 bytes before allocating it.init_empty_weights) and aliased from the checkpoint, so no dense float32 copy is allocated first on any platform.triton-windows>=3.8,<3.9); other Windows installs keep the existingtriton-windows>=3.7,<3.8.QA Instructions
06d0e90eff: 26,099 passed, 4 failed. The four are CUDA-only failures that reproduce on plain main and never run on CI's CPU runners, tracked in CUDA-only bnb-quantized Qwen2.5-VL sidecar LoRA tests fail on forward: encoder loaded without LM head #10416.52b3723ce7(model cache, model load, patches, RAM, working memory, Qwen encoder), and 3,447 passed at06d0e90eff(model cache, model load, patches, RAM). The quantization chunk's 4 failures are the CUDA-only bnb-quantized Qwen2.5-VL sidecar LoRA tests fail on forward: encoder loaded without LM head #10416 set.1e13392b7e): 8,021 passed. Its NVIDIA driver is down, so the integrated-CUDA-only test groups skip there.1e13392b7eand2a23b4e82b(the staged offload, the refusal type and text, test and docs fixes) were verified on an Apple-silicon Mac with integrated CUDA simulated: 4,610 passed across the model-cache, model-load, patches, preview and script tests; one VAE loader test fails there at06d0e90efftoo. Neither commit has run on a Spark.git diff --check, pass. Generated API artifacts are byte-identical to a fresh regeneration. Windows Spark image generation andmodel_cache_keep_alive_minwere verified by hand earlier in the PR. No family E2E manifest is configured in this checkout.Review
Material findings resolved:
OutOfMemoryError.Remaining limits:
1e13392b7eand2a23b4e82bhave not run on a Spark.Compatibility / Rollout
Existing explicit
keep_ram_copy_of_weightsvalues remain honored. No persisted-data migration is required.Checklist
What's Newcopy (if doing a release after this PR)