Skip to content

fix(memory): size integrated CUDA cache from shared pool - #10342

Open
JPPhoto wants to merge 120 commits into
invoke-ai:mainfrom
JPPhoto:nvidia-spark-unified-memory-support
Open

JPPhoto wants to merge 120 commits into
invoke-ai:mainfrom
JPPhoto:nvidia-spark-unified-memory-support

Conversation

@JPPhoto

@JPPhoto JPPhoto commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Integrated CUDA (Spark): shared-memory budget counts resident weights once; impossible host-admission requests refuse before evicting (the admin clear-cache route forces explicitly); the eviction sweep releases the allocator after dropping a device-resident entry so its host sample reflects its own progress; path-load admission sizes host headroom only, leaving cache-cap eviction to 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).
  • Integrated CUDA with 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.
  • Shared-memory refusals (integrated CUDA and integrated XPU): a full-load refusal leaves the model cached for a retry, where main deleted the entry on integrated XPU, and reports as OutOfMemoryError. The text states free host memory, the working memory and reserve_vram_gb held back, and max_cache_vram_gb when it is the limit, which on integrated XPU is whenever it is set.
  • Dedicated CUDA / ROCm / MPS / CPU / XPU: no device-allocation admission lock is taken and no per-device lock dict exists, and patch restore takes no lock (all as on main). make_room eviction sizes changed where the disk-size estimate changed: get_size_fs now 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_weights is unset by default and reports null in the config and API schema; unset means on, except on integrated CUDA where it means off.
  • context.models.make_room_in_vram_with_write_lock is a new public node API. It raises RuntimeError unless the calling thread holds the model-load write lock.
  • On devices with no separate VRAM pool there is nothing to offload to: offload_model_from_vram, offload_models_from_vram_except and offload_unlocked_models_from_vram return 0 without touching the cache for integrated XPU, for integrated CUDA without a kept RAM copy, and for CPU execution.
  • Safetensors identification strictness is exactly main's on every platform: payload-offset bounds moved to safetensors_payload_bytes(), used by the three sizing paths in this PR that consume data_offsets. get_size_fs can 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 and int8_convrot's marker reads predate this PR and keep main's behavior. read_safetensors_header refuses any header longer than 100,000,000 bytes before allocating it.
  • Ideogram4 single-file FP8 checkpoints are built on the meta device (init_empty_weights) and aliased from the checkpoint, so no dense float32 copy is allocated first on any platform.
  • Windows ARM64 installs a matching dependency pair (PyTorch 2.14 wheel plus triton-windows>=3.8,<3.9); other Windows installs keep the existing triton-windows>=3.7,<3.8.

QA Instructions

  • Local full Python suite at 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.
  • Windows Spark RTX (integrated CUDA live), affected-path chunks run serially: 5,921 passed at 52b3723ce7 (model cache, model load, patches, RAM, working memory, Qwen encoder), and 3,447 passed at 06d0e90eff (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.
  • Linux Spark DGX, the author's latest affected-path sweep (before 1e13392b7e): 8,021 passed. Its NVIDIA driver is down, so the integrated-CUDA-only test groups skip there.
  • 1e13392b7e and 2a23b4e82b (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 at 06d0e90eff too. Neither commit has run on a Spark.
  • Pinned Ruff 0.11.2 check and format, and git diff --check, pass. Generated API artifacts are byte-identical to a fresh regeneration. Windows Spark image generation and model_cache_keep_alive_min were verified by hand earlier in the PR. No family E2E manifest is configured in this checkout.

Review

Material findings resolved:

  • Integrated-CUDA budgets count resident weights once.
  • Host-memory admission and the device-allocation lock apply only on integrated CUDA; other devices behave as on main.
  • A lock is charged the model's full bytes left to move, with no credit for weights that may be file-mapped.
  • The eviction estimate keeps no evicted model alive, so the sweep sees the memory it freed.
  • Moving a model onto the GPU unloads an idle model with a RAM copy before it can drop it, and a load that must fit whole does not empty the idle RAM copies only to be refused.
  • A shared-memory refusal keeps the cache entry and reports as OutOfMemoryError.

Remaining limits:

  • 1e13392b7e and 2a23b4e82b have not run on a Spark.
  • Live two-model-resident generation on the Linux DGX Spark is unverified (its NVIDIA driver is down, root needed); live memory-pressure scenarios ran on the Windows Spark instead.
  • 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).
  • Dropping an idle model whose RAM copy is a view of the model file's mapping returns no memory, and the cache cannot tell such a copy from an owned one.

Compatibility / Rollout

Existing explicit keep_ram_copy_of_weights values remain honored. No persisted-data migration is required.

Checklist

  • The PR has a short but descriptive title, suitable for a changelog
  • Meaningful regression coverage added / updated where needed; obsolete tests/code removed
  • Persisted-state and API changes include required migrations / compatibility validation
  • Relevant performance/efficiency opportunities considered; material claims have evidence
  • Material review findings resolved and relevant checks rerun
  • Documentation added / updated (if applicable)
  • Updated What's New copy (if doing a release after this PR)

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.
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.
@github-actions github-actions Bot added python PRs that change python files Root invocations PRs that change invocations backend PRs that change backend files services PRs that change app services python-tests PRs that change python tests documentation PRs that change docs python-deps PRs that change python dependencies labels Nov 20, 2026
@JPPhoto JPPhoto changed the title Fix unified-memory budgeting on Spark fix(memory): size integrated CUDA cache from shared pool Nov 20, 2026

@joshistoast joshistoast left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread invokeai/backend/util/devices.py Resolved
Comment thread invokeai/backend/util/devices.py Resolved
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.

JPPhoto commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

@joshistoast, I addressed all ten inline findings:

  • Windows integrated CUDA now uses the CUDA allocation budget for GPU residency, with host RAM and Windows commit checked separately.
  • Cold model loads check fresh host and cgroup headroom before construction and evict cached models first.
  • Unowned weights are dropped without a CPU copy. Detached handles clean up on a deferred worker; queue accounting updates after release.
  • Preview and model-load paths use a consistent lock order.
  • Cgroup admission credits reclaimable file pages.
  • The Spark comparison benchmark reacquires models after eviction.
  • Ideogram FP8 swaps build replacement buffers on meta. Quantized-load admission accounts for real cast/dequant/fold lifetimes and only incremental FP8 preparation allocations.
  • The automatic YAML behavior now says to omit the setting or use null; the platform-specific test pins the NVIDIA path.
  • Added regression coverage for these paths.

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.
@JPPhoto

JPPhoto commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Round-4 fixes are pushed (6b52ef95c3..40181bb33a), on top of a fresh origin/main merge (5ae8c35dfb), so all lanes are running.

P1s

  • Credit on file-mapped weights: took your first option — the self-funded move credit is removed entirely (6b52ef95c3). The integrated lock is charged the full bytes-left-to-move at all three sites, and the admission-site comment records why (mapped views return nothing to the pool; the storage class is indistinguishable in torch) so the credit can't be re-added from this thread's history. The pass-based re-sampling design that would restore the owned-weights benefit safely is filed as Integrated CUDA: fund self-funding model locks by moving in passes sized by a fresh host sample #10436 with the two ceiling/empty_cache corners, for its own review with real integrated-CUDA runs.
  • Ceiling loop locals: confirmed and fixed (8cb35108ca) — the evictable-bytes sum moved into a helper so no entry reference outlives the estimate, plus a weakref-driven host sampler test that reproduces your exact "cleared 1, then refused" at the previous head and ends satisfied now.
  • CI on this head: main merged as asked; lanes are live on the pushed head.

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 CUDA_VISIBLE_DEVICES="" — runs on the CPU lanes, zero skips); the keep-copy cell now ends admitted; refusals name the component (2338ae4619); history references are gone from the whole added diff, including one of my own comments that predated this round (59c2733893).

Two extra fixes fell out of re-gating on the Windows Spark: on the real integrated-CUDA box, test_cached_model_only_full_load.py's and test_model_cache_paced_lock.py's lock tests inherited ambient host RAM — a pressured machine refused their 60KB/10KB models (the shared-memory guard working as designed on genuinely starved hardware). Same hermeticity fix as the earlier end-to-end load case: pin the host sampler (e6723382ff, cc7ca4dbaf), each refusal reproduced under a scripted starved-host harness before the fix and green under the same harness after.

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 (ed418f3d2a, merge 5ae8c35dfb): the one semantic overlap is main's capture/rebind sidecar restoration replacing the PR's leaf.to() restore loop; the PR's admission/lock gating now wraps main's mechanism unchanged, and the two lock-guarantee tests were re-seamed to the new restoration function (verified non-vacuous on the integrated box). A follow-up pins the classification detectors in those tests (40181bb33a). PR description updated per your list.

@JPPhoto
JPPhoto requested a review from joshistoast December 1, 2026 03:12

@joshistoast joshistoast left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 dbb2d03b1e apart 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_path now calls make_room(0, …) before the loader runs, keep_ram_copy_of_weights now reports null when unset in the config and API schema, and context.models has 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.

Comment on lines +750 to +777
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +3234 to +3262
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +2367 to +2375
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`."
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

Comment on lines +2677 to +2681
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
):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +764 to +770
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +1 to +10
"""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.
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +28 to +43
@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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +825 to +829

@pytest.mark.parametrize(
("integrated_cuda", "hip"),
[(False, None), (True, None), (False, "6.2")],
ids=["dedicated", "integrated", "rocm"],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +162 to +166
- **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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

Comment thread scripts/report_spark_memory.py Outdated
from invokeai.backend.util.devices import _host_memory_available


class _PerformanceInformation(ctypes.Structure):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@joshistoast
joshistoast self-requested a review December 1, 2026 04:33
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).
@JPPhoto

JPPhoto commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Round-5 fixes are pushed (40181bb33a..06d0e90eff) — all 14 findings addressed, each with per-fix red-green evidence in its thread.

P2s

  • Mistral triple parse: Tekken size memoised on (path, size, mtime) — one metadata parse per cold load for sizing + admission — and _get_host_bytes_needed is now only asked where the figure is consumed: a new ModelCache.host_admission_applies() mirrors the internal integrated gate, so dedicated/CPU/MPS loads skip host-only estimation entirely (6685f9edbc).
  • Idle entry with a RAM copy: your fix shape taken — the offload loop moves any entry with a cache-owned shadow, live handles or not, and drops only shadow-less entries (753b40f22e).

P3s

  • Refusal messages now name the free host figure and the working-memory holdback, and the full-load guard keeps its cache entry via a refusal subclass that still surfaces as torch.OutOfMemoryError (982cebe6d0).
  • The public make_room_in_vram_with_write_lock now raises RuntimeError unless the calling thread holds MODEL_LOAD_LOCK's write lock — the lock tracks its writer thread; generated invocation-context doc refreshed (0524a87cf5, 028a988cd8).
  • Path-load admission: gated to integrated CUDA (no walk, no make_room(0, …) elsewhere), recursion skips directories without weight files, and the refusal names the file (da8412a13a).
  • Ideogram 4 nf4 branches pass host_bytes_needed=0 — the mapped state dict is resident and aliased, nothing new is allocated (7a1119a5d7).
  • Both stale history comments restated in present tense (329946bedf); the self-funding test file renamed with the fictional mapped/owned pair merged and the args-spy test reworked to outcome assertions, regression-proven against the pre-removal credit code (650449341c); the host-sampler pin consolidated into one conftest fixture opted into by four files (c0a7180765); the vacuous device parametrization in the sidecar-restoration lock test dropped with mutation proofs, one deviation documented in its thread (52b3723ce7); the docs regain the 32GB/4GB automatic-cap facts (1aef0f5512); and the three Spark scripts get a development-guide page plus the PERFORMANCE_INFORMATION struct deduped to devices.py — all three kept, since the probe imports the reporter's helpers (350454b41b).

Also this round (06d0e90eff, found reviewing my own round-5 code): the new refusal diagnostic re-sampled host memory while raising — a sampler failing at that instant escaped the refusal handler into the generic one and deleted a cache entry nothing had touched; it also ignored an explicit max_vram_cache_size_gb (often the real limiter on an integrated device, so the advice sent users to free RAM they had free) and priced the full-load holdback from the configured default instead of the lock's requested working memory. All three fixed, each with a test (RED: sampler error escaped and entry deleted / cap absent from the message / 1024.00MB reported where the lock asked 4096.00MB).

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 52b3723ce7 26,096 passed / 4 failed — the pre-existing #10416 CUDA-only set, unchanged; Windows Spark (integrated CUDA live) four serial chunks 875 / 1,457 / 1,112 / 2,477 = 5,921 passed, 0 failed; Linux Spark DGX 8,018 passed, exit 0; CI green on all 12 lanes at 1b92a208c7 (an earlier linux-cpu failure was my walk-filter test materializing a 10 GiB fixture and OOM-killing a worker — fixed in that commit, sparse truncate).

joshistoast and others added 9 commits December 1, 2026 12:03
…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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

7.0.0 api backend PRs that change backend files CI-CD Continuous integration / Continuous delivery docs documentation PRs that change docs invocations PRs that change invocations python PRs that change python files python-deps PRs that change python dependencies python-tests PRs that change python tests Root services PRs that change app services

Projects

Status: 7.0.0: UX overhaul

Development

Successfully merging this pull request may close these issues.

3 participants