Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(ideogram4): keep the transformer pair from filling the card

Alexander Eichhorna96ca5c48f2d
diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py
index ce090072b6..d6e9e6f790 100644
--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py
+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py
@@ -20,6 +20,7 @@ from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Transformer
from invokeai.backend.ideogram4.sampler_configs import PRESETS
from invokeai.backend.ideogram4.sampling_utils import PIXELS_PER_IMAGE_TOKEN, unpatchify_and_denormalize
from invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPair
+from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Ideogram4ConditioningInfo
@@ -30,6 +31,18 @@ from invokeai.backend.util.fp8 import get_model_compute_dtype
# logit-normal schedule mean/std. V4_QUALITY_48 is the reference default.
IDEOGRAM4_SAMPLER_PRESETS = Literal["V4_QUALITY_48", "V4_DEFAULT_20", "V4_TURBO_12"]
+# The floor the derived residency target is clamped to, so a device short by more than a whole
+# branch still keeps a working set instead of streaming every layer of every step. The same 2 GiB
+# Wan holds its transformer to, and for the same reason.
+IDEOGRAM4_MIN_RESIDENT_SECOND_BRANCH_BYTES = 2 * 2**30
+
+# What the pair is asked to leave unclaimed for everything that is not this generation. On a
+# workstation the generation GPU usually also drives the display: measured 1.2-1.8 GiB held by the
+# desktop while idle here, and it spikes above that when a browser or the app's own UI repaints.
+# It is a term in the target, not a guarantee -- see `_second_branch_residency_target` for what the
+# reservation's own error does to it.
+IDEOGRAM4_LEAVE_FREE_FOR_THE_SYSTEM_BYTES = 3 * 2**30
+
def _effective_guidance_schedule(
base_schedule: tuple[float, ...], preset_num_steps: int, num_steps: int, guidance_scale: Optional[float]
@@ -249,12 +262,13 @@ class Ideogram4DenoiseInvocation(BaseInvocation):
files are two models and are locked simultaneously, because every step runs both and
releasing one between steps would make the cache stream it back for the next.
- Both locks get the *same* reservation even though the dequantization transient is per branch
- and the two branches can be different builds. The cache computes free VRAM as
- `capacity - working_mem - in_use` at each lock, and the second lock cannot claw space back
- from the first, which is already locked: a first branch that reserved less has taken
- headroom the second one still needs, and with the second branch already resident from an
- earlier run there is nothing left to evict.
+ Both locks reserve the same *activation* headroom, even though the dequantization transient
+ is per branch and the two branches can be different builds. The cache recomputes what is
+ free at each lock and the second cannot claw space back from the first, which is already
+ locked: a first branch that reserved less has taken headroom the second one still needs,
+ and with the second branch already resident from an earlier run there is nothing left to
+ evict. The second lock is then given *more* than that, when the pair would otherwise fill
+ the device -- see `_second_branch_residency_target` for what is added and why.
Taking the maximum up front costs reading `LoadedModel.model` -- documented as returning the
model unlocked, and it is already constructed by then -- and loading the second branch into
@@ -295,13 +309,125 @@ class Ideogram4DenoiseInvocation(BaseInvocation):
# locking it does not change what it is. The user-facing refusals are the two checks
# further up, which is why they are `raise` and this is not.
assert isinstance(primary, Ideogram4TransformerPair)
+ # A pipeline's pair is ONE cache record holding both branches, so the residency cap
+ # below does not apply to it: it has no second record to hold back, and bounding the
+ # single record would stream both branches instead of one. Such a build is also the
+ # smaller problem — `transformer_pair.py` notes its co-residency is what makes the nf4
+ # build fit in 24 GB in the first place.
return primary.conditional, primary.unconditional
- unconditional = stack.enter_context(unconditional_info.model_on_device(working_mem_bytes=reservation))[1]
+ # Told to the cache *before* the lock, so the branch settles near its target instead of
+ # loading whole and being pushed back. It lands near rather than on it: the cache budgets
+ # from `free + reclaimable-allocator-bytes - working_mem` and spends that on the weights the
+ # model is still *missing*, neither of which this arithmetic models. Measured on the
+ # reference card the lock overshoots by a steady 0.23 GiB, cold and warm alike, which the
+ # correction after the validation below takes off again.
+ target = self._second_branch_residency_target(context, conditional_info, unconditional_info, reservation)
+ second_reservation = reservation
+ if target is not None:
+ free_bytes, _total = torch.cuda.mem_get_info(unconditional_info.compute_device)
+ second_reservation = max(reservation, free_bytes - target)
+
+ unconditional = stack.enter_context(unconditional_info.model_on_device(working_mem_bytes=second_reservation))[1]
for role, branch in (("Transformer", primary), ("Transformer (Unconditional)", unconditional)):
if not isinstance(branch, Ideogram4Transformer):
raise ValueError(
f"'{role}' is a {type(branch).__name__}, not an Ideogram 4 transformer. Both inputs "
"must come from the Ideogram 4 model loader."
)
+ # After the cheap validation, so a mis-wired graph errors out instead of first paying an
+ # unload it will never use.
+ if target is not None:
+ self._hold_the_second_branch_to(context, unconditional_info, target)
return primary, unconditional
+
+ @staticmethod
+ def _second_branch_residency_target(
+ context: InvocationContext,
+ first_branch: LoadedModel,
+ second_branch: LoadedModel,
+ reservation: int,
+ ) -> Optional[int]:
+ """How many of the unconditional branch's weight bytes may stay on the device, or None.
+
+ Ideogram 4 is the only node here that keeps two transformers resident, and the fp8 pair is
+ 17.4 GiB. On a 24 GB card that plus the loop's reservation is the whole device: measured at
+ 1024x1024, the two branches settled at 100% and 96.8% residency and the card peaked at 23288
+ of 24564 MiB, leaving nothing for whatever else owns the display. Nothing is wrong with the
+ cache's arithmetic -- `capacity - working_mem - in_use` is exactly what it promised -- the
+ pair simply does not leave room to be a good neighbour, so the node has to decide not to take
+ it all. Same purpose as Wan's expert swapper, which bounds its transformer's residency
+ through the reservation for the same reason.
+
+ The target is derived, not chosen: whatever is left once the system's share, the reservation
+ the cache will really apply, and the *other* branch are subtracted from the device. That
+ keeps the cost proportional to how badly the pair overflows, and it makes
+ `device_working_mem_gb` the knob for it -- raising the reserve lowers the target one for one,
+ with no second setting to discover. Measured on the reference card at 1024x1024, 8 steps:
+
+ uncapped 38.2s, peak 23288 MiB, 1.2 GiB free
+ derived, reserve 5 GiB 35.8s, peak 22117 MiB, 2.4 GiB free (branch B at 84%)
+ derived, reserve 8 GiB 40.2s, peak 19009 MiB, 5.4 GiB free (branch B at 50%)
+
+ Stated plainly: at the default reserve this does *not* deliver the whole share the constant
+ below names. The reservation is an estimate of the loop's activations and measurably a low
+ one -- at 1024x1024 the non-weight bytes at peak were ~8 GiB against an estimate near 5 --
+ so the target it yields is correspondingly generous. The arithmetic is still the right shape
+ (more reserve, less residency, continuously), and the honest remedy for a machine that needs
+ more is the reserve, not a fudge factor hidden in this method.
+
+ Returns None when no cap is wanted or possible: a device that fits the pair with the
+ system's share to spare, a branch the cache holds whole (partial loading off, where a
+ partial unload would drop every weight instead), or a non-CUDA device.
+
+ Both branch sizes are read rather than doubling one of them. The loader lets an int8 branch
+ guide against an fp8 one, and `_estimate_working_memory` records the spread those builds
+ have -- 8.7, 8.9, or 17.3 GiB when an fp8 file is expanded -- so a pair can be lopsided
+ enough that doubling either side answers the wrong question.
+ """
+ device = second_branch.compute_device
+ if not second_branch.supports_partial_loading or device.type != "cuda":
+ return None
+ # An explicit `max_cache_vram_gb` makes the cache budget from that cap rather than from the
+ # device, so a target derived from physical memory describes a machine the cache is not
+ # using: the inflated reservation would be subtracted from the cap a second time and push
+ # the branch below the floor this method exists to hold. Such an install has already chosen
+ # how much VRAM the cache may take, which is this policy by another route.
+ if context.config.get().max_cache_vram_gb is not None:
+ return None
+ _free, total = torch.cuda.mem_get_info(device)
+ # The cache raises any reservation below its configured floor (`_get_vram_available`), so
+ # the node's own estimate is not what will be held free. Asking with the smaller number
+ # would clear the gate at low resolutions while the cache reserved more and the pair still
+ # took everything.
+ effective_reservation = max(reservation, int(context.config.get().device_working_mem_gb * 2**30))
+ room = total - IDEOGRAM4_LEAVE_FREE_FOR_THE_SYSTEM_BYTES - effective_reservation - first_branch.weight_bytes
+ if room >= second_branch.weight_bytes:
+ return None
+ return max(room, IDEOGRAM4_MIN_RESIDENT_SECOND_BRANCH_BYTES)
+
+ @staticmethod
+ def _hold_the_second_branch_to(context: InvocationContext, second_branch: LoadedModel, target: int) -> None:
+ """Correct the second branch down to `target` if its lock still settled above it.
+
+ The reservation handed to that lock is the primary lever and usually lands it there, but it
+ is computed from `mem_get_info` while the cache decides from its own accounting, and another
+ load can slip into a paced lock's gap. Without this the guarantee would be approximate; with
+ it the reservation saves the transfer and this only ever trims what is left over.
+
+ `keep_required_weights_in_vram` leaves behind the tensors a streamed forward cannot fetch
+ per layer, such as quantization scales.
+ """
+ excess = second_branch.resident_weight_bytes - target
+ if excess <= 0:
+ return
+ freed = second_branch.unload_from_vram(excess, keep_required_weights_in_vram=True)
+ # The cache moves the weights to RAM but does not return the blocks to the driver, so
+ # without this the bytes stay in torch's reserve -- invisible to the display, which is who
+ # the room was made for.
+ TorchDevice.empty_cache()
+ context.logger.info(
+ f"Ideogram 4: streamed {freed / 2**30:.2f} GiB of the unconditional branch to leave room "
+ f"for the rest of the system on {second_branch.compute_device}; this trades generation "
+ f"time for VRAM and does not happen on a card that fits both branches."
+ )
diff --git a/tests/app/invocations/test_ideogram4_denoise_branches.py b/tests/app/invocations/test_ideogram4_denoise_branches.py
index 6e29345f90..7dee0603f7 100644
--- a/tests/app/invocations/test_ideogram4_denoise_branches.py
+++ b/tests/app/invocations/test_ideogram4_denoise_branches.py
@@ -7,6 +7,7 @@ The mismatches are rejected rather than tolerated: either one would otherwise su
loop, as a missing attribute or as a branch guiding against itself.
"""
+import logging
from contextlib import ExitStack, contextmanager
from types import SimpleNamespace
@@ -24,6 +25,7 @@ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
Ideogram4ConditioningInfo,
)
+from invokeai.backend.util.devices import TorchDevice
TINY = Ideogram4Config(
emb_dim=64,
@@ -46,6 +48,23 @@ def _field(key: str) -> TransformerField:
)
+class _Residency:
+ """What the cap reads off a branch: where it lives, how big it is, how much of it is resident."""
+
+ def __init__(
+ self,
+ device: str = "cpu",
+ weight_bytes: int = 0,
+ resident_weight_bytes: int = 0,
+ supports_partial_loading: bool = True,
+ ) -> None:
+ self.device = device
+ self.weight_bytes = weight_bytes
+ self.resident_weight_bytes = resident_weight_bytes
+ self.supports_partial_loading = supports_partial_loading
+ self.unloaded: list[tuple[int, bool]] = []
+
+
class _LoadedModel:
"""The slice of `LoadedModel` this method uses, plus a record of how it was entered and left.
@@ -53,12 +72,27 @@ class _LoadedModel:
is an int8 build whose per-forward dequantization needs headroom of its own.
"""
- def __init__(self, model: torch.nn.Module, calls: list[tuple[str, int]], released: list[str], key: str) -> None:
+ def __init__(
+ self,
+ model: torch.nn.Module,
+ calls: list[tuple[str, int]],
+ released: list[str],
+ key: str,
+ residency: "_Residency | None" = None,
+ ) -> None:
self.model = model
self._model = model
self._calls = calls
self._released = released
self._key = key
+ # Default to a CPU branch, which is the shape every reservation test wants: the cap has
+ # nothing to stream there and returns before touching any of the fields below.
+ residency = residency or _Residency(device="cpu")
+ self.compute_device = torch.device(residency.device)
+ self.supports_partial_loading = residency.supports_partial_loading
+ self.weight_bytes = residency.weight_bytes
+ self.resident_weight_bytes = residency.resident_weight_bytes
+ self.unloaded: list[tuple[int, bool]] = residency.unloaded
@contextmanager
def model_on_device(self, working_mem_bytes: int = 0):
@@ -68,12 +102,19 @@ class _LoadedModel:
finally:
self._released.append(self._key)
+ def unload_from_vram(self, vram_bytes_to_free: int, keep_required_weights_in_vram: bool = False) -> int:
+ self.unloaded.append((vram_bytes_to_free, keep_required_weights_in_vram))
+ return vram_bytes_to_free
+
def _context(
models: dict[str, torch.nn.Module],
released: list[str],
calls: list[tuple[str, int]] | None = None,
loaded: list[str] | None = None,
+ residency: "dict[str, _Residency] | None" = None,
+ working_mem_gb: float = 3.0,
+ max_cache_vram_gb: float | None = None,
) -> SimpleNamespace:
"""`calls` records the *locks* and their reservations; `loaded` records the RAM-level loads.
@@ -85,9 +126,23 @@ def _context(
def load(identifier: ModelIdentifierField) -> _LoadedModel:
reads.append(identifier.key)
- return _LoadedModel(models[identifier.key], recorded, released, identifier.key)
+ return _LoadedModel(
+ models[identifier.key],
+ recorded,
+ released,
+ identifier.key,
+ (residency or {}).get(identifier.key),
+ )
- return SimpleNamespace(models=SimpleNamespace(load=load))
+ return SimpleNamespace(
+ models=SimpleNamespace(load=load),
+ logger=logging.getLogger("test"),
+ # The node reads `device_working_mem_gb` because the cache raises any smaller reservation to
+ # it; the default here is the repository default.
+ config=SimpleNamespace(
+ get=lambda: SimpleNamespace(device_working_mem_gb=working_mem_gb, max_cache_vram_gb=max_cache_vram_gb)
+ ),
+ )
def _invocation(**fields) -> Ideogram4DenoiseInvocation:
@@ -291,3 +346,249 @@ def test_invoke_passes_its_own_estimate_into_the_load(monkeypatch) -> None:
invocation.invoke(context)
assert reserved == [invocation._estimate_working_memory(TEXT_TOKENS)]
+
+
+GIB = 1024**3
+# The shipped fp8 branch is 8891.78 MB. The reservation at 1024x1024 is about 5 GiB, which is also
+# the cache's configured floor on the machine these numbers come from.
+BRANCH_BYTES = 8891 * 1024**2
+RESERVATION = 5 * GIB
+WORKING_MEM_GB = 5.0
+
+
+def _drive(
+ monkeypatch,
+ total_vram: int,
+ *,
+ cond: "_Residency | None" = None,
+ uncond: "_Residency | None" = None,
+ working_mem_gb: float = WORKING_MEM_GB,
+ reservation: int = RESERVATION,
+ free_vram: int | None = None,
+ max_cache_vram_gb: float | None = None,
+) -> tuple["_Residency", "_Residency", list[tuple[str, int]], list[str]]:
+ """Run `_load_branches` with both branches on a fake CUDA device of `total_vram` bytes.
+
+ `mem_get_info` is stubbed rather than skipped off CUDA hardware: what is under test is the
+ node's arithmetic against a device's capacity, which is worth pinning wherever the suite runs.
+ `empty_cache` is stubbed too -- the real one is a process-global free, which a unit test has no
+ business issuing -- and its calls are recorded, because without it the freed blocks stay in
+ torch's reserve and the room the node just made is invisible to anything outside the process.
+ """
+ # Free defaults to the device minus a desktop's worth and the first branch, which is the state
+ # the second lock actually meets.
+ free = total_vram - (3 * GIB) // 2 - BRANCH_BYTES if free_vram is None else free_vram
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda _device: (free, total_vram))
+ emptied: list[str] = []
+ monkeypatch.setattr(TorchDevice, "empty_cache", staticmethod(lambda: emptied.append("empty_cache")))
+
+ cond = cond or _Residency(device="cuda", weight_bytes=BRANCH_BYTES, resident_weight_bytes=BRANCH_BYTES)
+ uncond = uncond or _Residency(device="cuda", weight_bytes=BRANCH_BYTES, resident_weight_bytes=BRANCH_BYTES)
+ models = {"cond": Ideogram4Transformer(TINY), "uncond": Ideogram4Transformer(TINY)}
+ invocation = _invocation(transformer=_field("cond"))
+ invocation.unconditional_transformer = _field("uncond")
+ calls: list[tuple[str, int]] = []
+
+ with ExitStack() as stack:
+ invocation._load_branches(
+ _context(
+ models,
+ [],
+ calls,
+ residency={"cond": cond, "uncond": uncond},
+ working_mem_gb=working_mem_gb,
+ max_cache_vram_gb=max_cache_vram_gb,
+ ),
+ stack,
+ reservation,
+ )
+ return cond, uncond, calls, emptied
+
+
+def _target_for(total_vram: int, other_branch: int = BRANCH_BYTES, reservation: int = RESERVATION) -> int:
+ """What is left for the second branch once the system, the reservation and the other branch are
+ subtracted. Written out here rather than imported so a change of policy fails these cells."""
+ return total_vram - 3 * GIB - reservation - other_branch
+
+
+def test_the_second_branch_is_held_to_what_the_card_has_left(monkeypatch) -> None:
+ """The target is the deficit, not a fixed number.
+
+ Measured on the real models before this existed: both branches settled at 100% and 96.8%
+ residency and the card peaked at 23288 of 24564 MiB -- the whole device, on a machine whose GPU
+ also drives the display. With the target derived, the same generation settled branch B at 84%
+ and peaked at 22117 MiB; raising `device_working_mem_gb` to 8 moved it to 50% and 19009 MiB.
+ """
+ _cond, uncond, _calls, emptied = _drive(monkeypatch, total_vram=24 * GIB)
+
+ target = _target_for(24 * GIB)
+ assert 2 * GIB < target < BRANCH_BYTES, "the fixture must exercise a derived target, not the floor"
+ # The tensors a streamed forward cannot fetch per layer stay behind.
+ assert uncond.unloaded == [(BRANCH_BYTES - target, True)]
+ # Without returning the blocks to the driver the room exists only inside this process.
+ assert emptied == ["empty_cache"]
+
+
+def test_the_lock_is_told_the_target_so_the_weights_are_never_loaded_twice(monkeypatch) -> None:
+ """The reservation is the lever; the unload is only a correction.
+
+ Letting the cache fill the branch and pushing it back afterwards moves ~6 GiB onto the device
+ and straight off again on every invocation. The second lock therefore gets a reservation that
+ leaves exactly the target free, which is what Wan's expert swapper does.
+ """
+ _cond, _uncond, calls, _emptied = _drive(monkeypatch, total_vram=24 * GIB)
+
+ (first_key, first_reservation), (second_key, second_reservation) = calls
+ assert (first_key, second_key) == ("cond", "uncond")
+ # The conditional branch is not capped: it is locked first and every step runs it.
+ assert first_reservation == RESERVATION
+ # `_get_vram_available` is `free - working_mem`, so this leaves the target and nothing more.
+ free = 24 * GIB - (3 * GIB) // 2 - BRANCH_BYTES
+ assert second_reservation == free - _target_for(24 * GIB)
+ # And it is genuinely an inflation, not the node's own number arriving unchanged.
+ assert second_reservation > RESERVATION
+
+
+def test_a_lopsided_pair_is_measured_rather_than_doubled(monkeypatch) -> None:
+ """The two branches can be different builds, so neither one's size stands in for the pair.
+
+ The loader accepts an int8 branch guiding against an fp8 one, and an fp8 file that is expanded
+ rather than kept quantized is about twice the size of either. Doubling the second branch here
+ would compute 17.4 GiB for a pair that is really 25.7 GiB, clear the gate on a 32 GiB card and
+ leave the display with nothing.
+ """
+ expanded = 17 * GIB
+ cond = _Residency(device="cuda", weight_bytes=expanded, resident_weight_bytes=expanded)
+ _cond, uncond, _calls, _emptied = _drive(monkeypatch, total_vram=32 * GIB, cond=cond)
+
+ assert uncond.unloaded, "a 17 GiB + 8.7 GiB pair does not fit a 32 GiB card"
+ assert uncond.unloaded == [(BRANCH_BYTES - _target_for(32 * GIB, other_branch=expanded), True)]
+
+
+def test_the_gate_uses_the_reservation_the_cache_will_actually_apply(monkeypatch) -> None:
+ """`_get_vram_available` raises any reservation below `device_working_mem_gb`.
+
+ At 512px the node's own estimate is far under that floor, so asking the gate with it would
+ clear a card the cache then fills anyway -- both branches resident and under 2 GiB left for the
+ display, which is the condition this whole path exists to detect.
+ """
+ # 24 - 3 - 2 - 8.68 leaves room for the second branch; 24 - 3 - 5 - 8.68 does not.
+ _cond, uncond, _calls, _emptied = _drive(monkeypatch, total_vram=24 * GIB, reservation=2 * GIB, working_mem_gb=5.0)
+
+ assert uncond.unloaded, "the gate must use the 5 GiB floor, not the 2 GiB estimate"
+
+
+def test_a_card_with_room_for_the_pair_keeps_both_resident(monkeypatch) -> None:
+ """The cap answers a device that is too small, not a policy about Ideogram: without this, a
+ 48 GB card would pay the streaming cost for headroom it already has."""
+ _cond, uncond, calls, emptied = _drive(monkeypatch, total_vram=48 * GIB)
+
+ assert uncond.unloaded == []
+ assert emptied == []
+ # And both locks are given the node's own reservation, unmodified.
+ assert calls == [("cond", RESERVATION), ("uncond", RESERVATION)]
+
+
+def test_a_card_just_above_the_threshold_is_left_alone(monkeypatch) -> None:
+ """Brackets the system's share from the other side.
+
+ The 48 GiB cell alone would stay green if the reserve were raised to any value below ~26 GiB,
+ which would start capping 32 and 40 GB cards that have room to spare.
+ """
+ # 2 x 8.68 + 5 + 3 = 25.4 GiB, so 26 GiB clears it with little to spare.
+ _cond, uncond, _calls, _emptied = _drive(monkeypatch, total_vram=26 * GIB)
+
+ assert uncond.unloaded == []
+
+
+def test_a_branch_already_below_the_target_is_not_touched(monkeypatch) -> None:
+ """A second invocation finds the branch as the first one left it. Trimming again would ask the
+ cache to free bytes that are not there, and an unconditional call would log a 0 GiB stream."""
+ low = _Residency(device="cuda", weight_bytes=BRANCH_BYTES, resident_weight_bytes=1 * GIB)
+ _cond, uncond, _calls, emptied = _drive(monkeypatch, total_vram=24 * GIB, uncond=low)
+
+ assert uncond.unloaded == []
+ assert emptied == []
+
+
+def test_the_size_and_the_residency_are_not_interchangeable(monkeypatch) -> None:
+ """The gate asks how big the pair is; the trim asks how much of it is on the device.
+
+ A second generation in a session finds the branch as the first one left it -- partly resident.
+ Reading residency where size belongs would then under-read the pair, decide the card has room
+ and hand the second lock an uninflated reservation, so the branch would fill up again and the
+ feature would silently stop working exactly when it matters. Pinned on the reservation rather
+ than on the unload, because a branch already under the target has nothing to trim.
+ """
+ half = _Residency(device="cuda", weight_bytes=BRANCH_BYTES, resident_weight_bytes=2 * GIB)
+ _cond, uncond, calls, _emptied = _drive(monkeypatch, total_vram=24 * GIB, uncond=half)
+
+ free = 24 * GIB - (3 * GIB) // 2 - BRANCH_BYTES
+ assert calls[1] == ("uncond", free - _target_for(24 * GIB))
+ # Nothing to trim: the cache already holds less than the branch is allowed to keep.
+ assert uncond.unloaded == []
+
+
+def test_a_branch_that_cannot_stream_is_left_alone(monkeypatch) -> None:
+ """With partial loading off the cache holds the model whole, so a partial unload cannot help:
+ asking for one drops every weight and makes the loop rebuild it from RAM each step."""
+ whole = _Residency(
+ device="cuda",
+ weight_bytes=BRANCH_BYTES,
+ resident_weight_bytes=BRANCH_BYTES,
+ supports_partial_loading=False,
+ )
+ _cond, uncond, calls, _emptied = _drive(monkeypatch, total_vram=24 * GIB, uncond=whole)
+
+ assert uncond.unloaded == []
+ # And no inflated reservation either -- it would only starve the branch the cache must load whole.
+ assert calls == [("cond", RESERVATION), ("uncond", RESERVATION)]
+
+
+def test_the_bundled_pair_is_never_capped(monkeypatch) -> None:
+ """A diffusers pipeline is one cache record holding *both* branches, and the node returns before
+ the cap. Generalizing the cap onto that record would read one branch's size as the pair's, fire
+ on almost any card, and then stream both branches -- worse than the problem being fixed."""
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda _device: (12 * GIB, 24 * GIB))
+ pair_record = _Residency(device="cuda", weight_bytes=2 * BRANCH_BYTES, resident_weight_bytes=2 * BRANCH_BYTES)
+ pair = Ideogram4TransformerPair(conditional=Ideogram4Transformer(TINY), unconditional=Ideogram4Transformer(TINY))
+ invocation = _invocation(transformer=_field("pipeline"))
+
+ with ExitStack() as stack:
+ invocation._load_branches(
+ _context({"pipeline": pair}, [], residency={"pipeline": pair_record}), stack, RESERVATION
+ )
+
+ assert pair_record.unloaded == []
+
+
+def test_a_card_short_by_more_than_a_branch_keeps_a_working_set(monkeypatch) -> None:
+ """Below roughly 19 GiB the derived target goes negative and the floor becomes the policy.
+
+ Without the clamp both consumers run on a negative number: the second lock is handed a
+ reservation larger than the whole free pool, so the cache loads almost none of the branch, and
+ the correction then asks it to free more than is resident. A 12-16 GB card would stream every
+ layer of every step instead of keeping a working set -- slow turns into unusable, which is
+ exactly what the floor exists to prevent.
+ """
+ assert _target_for(16 * GIB) < 0, "the fixture must reach the floor, not a derived target"
+ _cond, uncond, calls, _emptied = _drive(monkeypatch, total_vram=16 * GIB)
+
+ assert uncond.unloaded == [(BRANCH_BYTES - 2 * GIB, True)]
+ free = 16 * GIB - (3 * GIB) // 2 - BRANCH_BYTES
+ assert calls[1] == ("uncond", max(RESERVATION, free - 2 * GIB))
+
+
+def test_an_explicitly_capped_cache_is_left_to_its_own_budget(monkeypatch) -> None:
+ """With `max_cache_vram_gb` set the cache budgets from that cap, not from the device.
+
+ A target derived from physical memory then describes a machine the cache is not using, and the
+ inflated reservation would come off the cap a second time -- on a 24 GiB card capped at 16 that
+ pushes the branch under the 2 GiB floor, in the name of freeing VRAM the cache was already
+ forbidden to take. Such an install has already chosen its residency by another route.
+ """
+ _cond, uncond, calls, emptied = _drive(monkeypatch, total_vram=24 * GIB, max_cache_vram_gb=16.0)
+
+ assert uncond.unloaded == []
+ assert emptied == []
+ assert calls == [("cond", RESERVATION), ("uncond", RESERVATION)]