Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: drop the unfused QKV copies after the SDXL fuse, and decline the speed profile when kept copies would not fit (#16621)

Daniel Han914f10beaf43
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 40caed79a4a..67e662188f6 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -292,7 +292,9 @@ from .diffusion_speed import (
family_compiles_regionally,
fp16_compile_explicit_only,
fp16_unet_offloaded,
+ fused_qkv_added_bytes,
fresh_compile_count,
+ restore_unfused_projections,
int8_gemm_live,
arm_graphs_after_placement,
normalize_speed_mode,
@@ -3053,6 +3055,101 @@ def _learned_peak_for_keys(
return None
+DEFERRED_HEADROOM_ENV = "UNSLOTH_DIFFUSION_DEFERRED_HEADROOM"
+# Room kept free above the eager peak plus the profile's added weights: allocator fragmentation, the stable range's
+# granularity and the compiled render's cuBLAS / cuDNN workspaces (SDXL 2048^2 at 8 GiB: 346 MiB short of this OOMs).
+_DEFERRED_HEADROOM_MIN_BYTES = 512 << 20
+_DEFERRED_HEADROOM_FRACTION = 0.10
+
+
+_DEFERRED_EAGER_PEAK_ATTR = "_unsloth_deferred_eager_peak"
+
+
+def _deferred_peak_now(dev: Any) -> int:
+ from .diffusion_stable_arena import peak_mapped_bytes
+ import torch
+ return int(torch.cuda.max_memory_allocated(dev)) + int(peak_mapped_bytes(dev.index))
+
+
+def _cuda_device_of(state: Any) -> Any:
+ import torch
+
+ dev = torch.device(str(getattr(state, "device", "")))
+ if dev.type != "cuda" or not torch.cuda.is_available():
+ return None
+ return dev if dev.index is not None else torch.device("cuda", torch.cuda.current_device())
+
+
+def _note_deferred_eager_peak(state: Any) -> None:
+ """Keep the highest device peak of this load's eager renders, read as each one ends (a caller may reset the peak
+ counters before the next generate, which would hide them from a read at engagement)."""
+ try:
+ dev = _cuda_device_of(state)
+ if dev is None:
+ return
+ pipe = state.pipe
+ peak = max(_deferred_peak_now(dev), int(getattr(pipe, _DEFERRED_EAGER_PEAK_ATTR, 0) or 0))
+ setattr(pipe, _DEFERRED_EAGER_PEAK_ATTR, peak)
+ except Exception: # noqa: BLE001 - measurement only
+ pass
+
+
+def _open_deferred_peak_window(state: Any) -> None:
+ """Reset the device peak counters at the start of a deferred load's eager render when no learned-peak probe did
+ (``UNSLOTH_DIFFUSION_LEARNED_PEAKS=0`` or an unkeyed render): otherwise the reading at its end could be an earlier
+ model's peak and decline the profile for good."""
+ try:
+ dev = _cuda_device_of(state)
+ if dev is None:
+ return
+ import torch
+ from .diffusion_stable_arena import reset_peak_mapped
+
+ torch.cuda.reset_peak_memory_stats(dev)
+ reset_peak_mapped(dev.index)
+ except Exception: # noqa: BLE001 - measurement only
+ pass
+
+
+def _deferred_profile_headroom_short(state: Any) -> Optional[str]:
+ """Why the deferred profile would not fit on the card, else None. The eager renders' measured peak plus the bytes
+ the profile adds to the denoiser (the U-Net QKV fuse keeps the unfused projections) must leave a margin inside
+ what this process can hold: free device memory plus its own allocator cache and stable ranges."""
+ if (os.environ.get(DEFERRED_HEADROOM_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return None
+ if getattr(state, "offload_policy", OFFLOAD_NONE) not in (OFFLOAD_NONE, OFFLOAD_MODEL):
+ return None # streamed / grouped denoisers never hold the whole module on the card
+ added = fused_qkv_added_bytes(getattr(state, "pipe", None))
+ if added <= 0:
+ return None
+ try:
+ import torch
+
+ dev = _cuda_device_of(state)
+ if dev is None:
+ return None
+ from .diffusion_stable_arena import mapped_bytes
+
+ # the eager renders this load ran, as each one ended (plus anything since)
+ peak = max(
+ _deferred_peak_now(dev),
+ int(getattr(state.pipe, _DEFERRED_EAGER_PEAK_ATTR, 0) or 0),
+ )
+ free, _total = torch.cuda.mem_get_info(dev)
+ capacity = int(free) + int(torch.cuda.memory_reserved(dev)) + int(mapped_bytes(dev.index))
+ except Exception: # noqa: BLE001 - unreadable: engage as before
+ return None
+ need = peak + added
+ need += max(_DEFERRED_HEADROOM_MIN_BYTES, int(need * _DEFERRED_HEADROOM_FRACTION))
+ if need <= capacity:
+ return None
+ mib = 1 << 20
+ return (
+ f"eager peak {peak // mib} MiB + {added // mib} MiB of fused QKV weights + margin = {need // mib} MiB, "
+ f"this process can hold {capacity // mib} MiB"
+ )
+
+
def _follow_live_graph_mode(state: Any) -> None:
"""Keep a deferred profile's identity on the CUDA graph mode actually running (armed, then possibly dropped)."""
pipe = getattr(state, "pipe", None)
@@ -13131,6 +13228,8 @@ class DiffusionBackend:
cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)
return
+ # PEFT targets to_q / to_k / to_v: a fused U-Net that dropped them gets them back first (bit-exact).
+ restore_unfused_projections(getattr(pipe, "unet", None))
# Read before loading, so a file rewritten during the load reads as changed next time.
file_sigs = _lora_file_sigs(desired)
try:
@@ -13250,6 +13349,22 @@ class DiffusionBackend:
"under the offload hooks)"
)
return
+ short = _deferred_profile_headroom_short(state)
+ if short is not None:
+ # declined before anything is patched: this load keeps rendering exactly as speed_mode=off
+ object.__setattr__(state, "deferred_static_plan", None)
+ logger.info(
+ "diffusion.speed: deferred profile declined, staying eager for this load (%s; %s=0 engages it "
+ "anyway)",
+ short,
+ DEFERRED_HEADROOM_ENV,
+ )
+ entry = (state.resolved or {}).get("speed_mode")
+ if isinstance(entry, dict):
+ entry["reason"] = (
+ f"auto: compiled profile declined, it does not fit on the card ({short})"
+ )
+ return
plan = state.deferred_static_plan
object.__setattr__(state, "deferred_static_plan", None)
tc = (state.resolved or {}).get("transformer_cache")
@@ -14458,6 +14573,8 @@ class DiffusionBackend:
# a whole-denoiser call's peak is not the streamed placement's
peak_probe = None if whole_tier is not None else _start_peak_probe(state)
+ if peak_probe is None and state.speed_deferred:
+ _open_deferred_peak_window(state)
decode_restores: list = []
try:
previewer = _start_previewer()
@@ -14757,6 +14874,9 @@ class DiffusionBackend:
# Count the finished generation (drives deferred speed); a batch is one generation.
if (_hires_pass is None or not _hires_pass.refine) and not aux_pass:
object.__setattr__(state, "generation_count", state.generation_count + 1)
+ if state.speed_deferred:
+ # every eager pass, hires refinements included: the next pass resets the counters
+ _note_deferred_eager_peak(state)
result = {
"images": list(images),
"seed": int(seed),
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 1b1fbb31cf3..d5d7d7b6d69 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -995,6 +995,44 @@ def _denoiser_unet(pipe: Any) -> Any:
return None
+def fused_qkv_added_bytes(pipe: Any) -> int:
+ """Device bytes the default tier's U-Net QKV fuse adds. diffusers' ``fuse_projections`` builds ``to_qkv`` /
+ ``to_kv`` beside the ``to_q`` / ``to_k`` / ``to_v`` it keeps, so a U-Net that moves whole (model offload) or stays
+ resident carries both (SDXL: 4897 MiB grows to 6132 MiB). 0 when the tier would not fuse."""
+ unet = _denoiser_unet(pipe)
+ if unet is None:
+ return 0
+ try:
+ import torch
+ from .diffusion_native_quant import is_native_quantised
+
+ if any(is_native_quantised(dit) for dit in _denoiser_dits(pipe)):
+ return 0
+ if unfused_projections_will_drop(unet):
+ return 0 # the fused weights replace the projections they were built from
+ total = 0
+ for module in unet.modules():
+ if not callable(getattr(module, "fuse_projections", None)) or getattr(
+ module, "fused_projections", False
+ ):
+ continue
+ names = (
+ ("to_k", "to_v")
+ if getattr(module, "is_cross_attention", False)
+ else ("to_q", "to_k", "to_v")
+ )
+ if getattr(module, "add_q_proj", None) is not None:
+ names += ("add_q_proj", "add_k_proj", "add_v_proj")
+ for name in names:
+ linear = getattr(module, name, None)
+ for t in (getattr(linear, "weight", None), getattr(linear, "bias", None)):
+ if isinstance(t, torch.Tensor):
+ total += t.numel() * t.element_size()
+ return total
+ except Exception: # noqa: BLE001 - unreadable: no extra bytes claimed
+ return 0
+
+
def compiled_shapes_are_static(pipe: Any, speed_mode: Optional[str]) -> bool:
"""Whether this load's compiled artifacts are per-(width, height, batch); the compile cache keys on it."""
mode = normalize_speed_mode(speed_mode)
@@ -2028,6 +2066,7 @@ def _fuse_qkv(pipe: Any, logger: Any) -> bool:
): # the pipe-level fuse resets every VAE processor to FusedAttnProcessor2_0
from . import diffusion_vae_fused # noqa: PLC0415
diffusion_vae_fused.install_attention_processors(vae)
+ drop_unfused_projections(_denoiser_unet(pipe), logger)
return True
except Exception as exc: # noqa: BLE001 - optimisation only
_warn(logger, "fuse_qkv_projections", exc)
@@ -2044,6 +2083,151 @@ def _fuse_qkv(pipe: Any, logger: Any) -> bool:
return engaged
+DROP_UNFUSED_QKV_ENV = "UNSLOTH_DIFFUSION_DROP_UNFUSED_QKV"
+_DROPPED_ATTR = "_unsloth_dropped_projections"
+
+
+def _fused_attention_drops(module: Any) -> tuple:
+ """The projections diffusers' fused processor no longer calls: self attention runs ``to_qkv`` (q, k, v unused),
+ cross attention ``to_q`` + ``to_kv`` (k, v unused)."""
+ if not getattr(module, "fused_projections", False):
+ return ()
+ if getattr(module, "is_cross_attention", False):
+ return ("to_k", "to_v") if getattr(module, "to_kv", None) is not None else ()
+ return ("to_q", "to_k", "to_v") if getattr(module, "to_qkv", None) is not None else ()
+
+
+def _drop_unfused_enabled() -> bool:
+ return (os.environ.get(DROP_UNFUSED_QKV_ENV) or "").strip().lower() not in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def _droppable_projection(module: Any, name: str) -> bool:
+ """A projection the drop may delete: a plain Linear without hooks (quantised / wrapped ones are left alone)."""
+ from torch import nn
+
+ p = getattr(module, name, None)
+ return type(p) is nn.Linear and not (
+ p._forward_pre_hooks or p._forward_hooks or hasattr(p, "_hf_hook")
+ )
+
+
+def _drop_plan(unet: Any) -> list:
+ """``(module, names)`` the drop would delete on a fused ``unet``; empty when it is off, a PEFT adapter is attached
+ (it targets to_q / to_k / to_v) or any projection is not a plain hook-free Linear (all or nothing)."""
+ if unet is None or not _drop_unfused_enabled():
+ return []
+ if any(hasattr(m, "lora_A") for m in unet.modules()):
+ return []
+ plan = []
+ for module in unet.modules():
+ names = _fused_attention_drops(module)
+ if not names:
+ continue
+ if not all(_droppable_projection(module, n) for n in names):
+ return []
+ plan.append((module, names))
+ return plan
+
+
+def unfused_projections_will_drop(unet: Any) -> bool:
+ """Whether the fuse's unfused copies will be dropped on this (not yet fused) U-Net: drop on, no PEFT adapter, and
+ every projection the fused processor stops calling is a plain hook-free Linear."""
+ if unet is None or not _drop_unfused_enabled():
+ return False
+ try:
+ if any(hasattr(m, "lora_A") for m in unet.modules()):
+ return False
+ seen = False
+ for module in unet.modules():
+ if not callable(getattr(module, "fuse_projections", None)) or getattr(
+ module, "fused_projections", False
+ ):
+ continue
+ if getattr(module, "add_q_proj", None) is not None:
+ return False # the added projections are fused too and never dropped
+ names = (
+ ("to_k", "to_v")
+ if getattr(module, "is_cross_attention", False)
+ else ("to_q", "to_k", "to_v")
+ )
+ if not all(_droppable_projection(module, n) for n in names):
+ return False
+ seen = True
+ return seen
+ except Exception: # noqa: BLE001 - unreadable: count the copies
+ return False
+
+
+def drop_unfused_projections(unet: Any, logger: Any = None) -> int:
+ """Delete the unfused projections a U-Net QKV fuse left beside ``to_qkv`` / ``to_kv`` (SDXL: 1235 MiB). Kept when
+ a PEFT adapter is attached (it targets them) or the modules carry hooks; ``restore_unfused_projections`` rebuilds
+ them bit-exactly from the fused weights. UNSLOTH_DIFFUSION_DROP_UNFUSED_QKV=0 keeps them."""
+ try:
+ import torch
+
+ plan = _drop_plan(unet)
+ freed = 0
+ for module, names in plan:
+ shapes = []
+ for n in names:
+ p = getattr(module, n)
+ freed += sum(t.numel() * t.element_size() for t in p.parameters())
+ shapes.append((n, p.in_features, p.out_features, p.bias is not None))
+ delattr(module, n)
+ setattr(module, _DROPPED_ATTR, tuple(shapes))
+ if plan and torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ if plan and logger is not None:
+ logger.info(
+ "diffusion.speed: dropped the unfused projections beside the fused QKV on %d attention modules "
+ "(%d MiB)",
+ len(plan),
+ freed >> 20,
+ )
+ return freed
+ except Exception as exc: # noqa: BLE001 - memory only: a failed drop keeps what is left
+ _warn(logger, "dropping the unfused projections", exc)
+ return 0
+
+
+def restore_unfused_projections(unet: Any) -> int:
+ """Rebuild the projections ``drop_unfused_projections`` deleted, row slices of the fused weights (bit-exact: the
+ fuse concatenated them unchanged). Returns the modules restored."""
+ if unet is None:
+ return 0
+ import torch
+ from torch import nn
+
+ restored = 0
+ for module in unet.modules():
+ shapes = getattr(module, _DROPPED_ATTR, None)
+ if not shapes:
+ continue
+ fused = module.to_kv if getattr(module, "is_cross_attention", False) else module.to_qkv
+ rows = 0
+ for name, fin, fout, has_bias in shapes:
+ lin = nn.Linear(fin, fout, bias = has_bias, device = "meta")
+ with torch.no_grad():
+ grad = bool(fused.weight.requires_grad)
+ lin.weight = nn.Parameter(
+ fused.weight[rows : rows + fout].clone(), requires_grad = grad
+ )
+ if has_bias:
+ lin.bias = nn.Parameter(
+ fused.bias[rows : rows + fout].clone(), requires_grad = grad
+ )
+ setattr(module, name, lin)
+ rows += fout
+ delattr(module, _DROPPED_ATTR)
+ restored += 1
+ return restored
+
+
def _warn(logger: Any, what: str, exc: Exception) -> None:
if logger is not None:
logger.warning("diffusion.speed: %s failed: %s", what, exc)
diff --git a/studio/backend/tests/test_diffusion_deferred_headroom.py b/studio/backend/tests/test_diffusion_deferred_headroom.py
new file mode 100644
index 00000000000..a77c3ff2bb2
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_deferred_headroom.py
@@ -0,0 +1,228 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The deferred speed profile declines when the eager peak plus the fused QKV copies would not fit on the card."""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+diffusers = pytest.importorskip("diffusers")
+
+from core.inference import diffusion as dmod # noqa: E402
+from core.inference import diffusion_speed as dspeed # noqa: E402
+
+MIB = 1 << 20
+HEADROOM_ENV = "UNSLOTH_DIFFUSION_DEFERRED_HEADROOM"
+
+
+def _tiny_unet():
+ from diffusers import UNet2DConditionModel
+ torch.manual_seed(0)
+ return UNet2DConditionModel(
+ sample_size = 8,
+ in_channels = 4,
+ out_channels = 4,
+ layers_per_block = 1,
+ block_out_channels = (32, 64),
+ down_block_types = ("DownBlock2D", "CrossAttnDownBlock2D"),
+ up_block_types = ("CrossAttnUpBlock2D", "UpBlock2D"),
+ cross_attention_dim = 24,
+ attention_head_dim = 8,
+ norm_num_groups = 8,
+ )
+
+
+def _bytes(module) -> int:
+ return sum(p.numel() * p.element_size() for p in module.parameters())
+
+
+def _keep_copies(monkeypatch):
+ monkeypatch.setenv(dspeed.DROP_UNFUSED_QKV_ENV, "0")
+
+
+def test_added_bytes_equal_what_diffusers_fuse_adds(monkeypatch):
+ _keep_copies(monkeypatch)
+ unet = _tiny_unet()
+ pipe = types.SimpleNamespace(unet = unet)
+ added = dspeed.fused_qkv_added_bytes(pipe)
+ before = _bytes(unet)
+ unet.fuse_qkv_projections()
+ assert added > 0
+ assert _bytes(unet) - before == added
+ # already fused: nothing more to add
+ assert dspeed.fused_qkv_added_bytes(pipe) == 0
+
+
+def test_no_unet_adds_nothing():
+ assert dspeed.fused_qkv_added_bytes(types.SimpleNamespace(transformer = object())) == 0
+
+
+def card(monkeypatch):
+ """A fake CUDA card: ``peak`` / ``free`` / ``reserved`` in MiB."""
+ reading = {"peak": 0, "free": 0, "reserved": 0}
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda dev = None: reading["peak"] * MIB)
+ monkeypatch.setattr(
+ torch.cuda, "mem_get_info", lambda dev = None: (reading["free"] * MIB, 24576 * MIB)
+ )
+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda dev = None: reading["reserved"] * MIB)
+ monkeypatch.delenv(HEADROOM_ENV, raising = False)
+ # the fused copies stay beside the originals (the case the gate guards); test_drop_* cover the dropped case
+ monkeypatch.setenv(dspeed.DROP_UNFUSED_QKV_ENV, "0")
+ return reading
+
+
+def engage(monkeypatch):
+ ran = []
+ monkeypatch.setattr(
+ dmod.DiffusionBackend, "_engage_deferred_profile", lambda self, state: ran.append(state)
+ )
+ monkeypatch.setattr(dmod, "invalidate_cfg_replica", lambda *a, **k: None)
+ monkeypatch.setattr(dmod, "drop_displaced_cfg_router", lambda *a, **k: None)
+ backend = object.__new__(dmod.DiffusionBackend)
+
+ def make(offload_policy = dmod.OFFLOAD_MODEL):
+ return types.SimpleNamespace(
+ pipe = types.SimpleNamespace(unet = _tiny_unet()),
+ speed_deferred = True,
+ deferred_static_plan = {"every": 3, "min_steps": 20},
+ resolved = {"speed_mode": {"value": "deferred", "reason": "auto"}},
+ transformer_cache = None,
+ offload_policy = offload_policy,
+ device = "cuda:0",
+ )
+
+ def run(offload_policy = dmod.OFFLOAD_MODEL, state = None):
+ state = state if state is not None else make(offload_policy)
+ dmod.DiffusionBackend._engage_deferred_speed(backend, state)
+ return state, bool(ran and ran[-1] is state)
+
+ run.make = make
+ return run
+
+
+def test_profile_declined_when_the_render_would_not_fit(card, engage):
+ # SDXL 2048^2 at 8 GiB on an L4: eager peak 6197 MiB, 544 MiB free beside a 7234 MiB cache
+ # (the tiny U-Net's fused copies are KiB: the peak sits 300 MiB inside capacity, short of the margin)
+ card.update(peak = 7778 - 300, free = 544, reserved = 7234)
+ state, engaged = engage()
+ assert not engaged
+ assert state.speed_deferred is False # never retried on this load
+ assert (
+ state.deferred_static_plan is None
+ ) # no static skip either: renders stay as speed_mode=off
+ assert "declined" in state.resolved["speed_mode"]["reason"]
+
+
+def test_profile_engages_when_the_render_fits(card, engage):
+ # SDXL 1024^2 at 8 GiB: eager peak 5232 MiB leaves room for the fused copies
+ card.update(peak = 5232, free = 1322, reserved = 6456)
+ _state, engaged = engage()
+ assert engaged
+
+
+def test_header_names_the_kill_switch():
+ assert dmod.DEFERRED_HEADROOM_ENV == HEADROOM_ENV
+
+
+def test_kill_switch_engages_regardless(card, engage, monkeypatch):
+ card.update(peak = 7700, free = 50, reserved = 7728)
+ monkeypatch.setenv(HEADROOM_ENV, "0")
+ _state, engaged = engage()
+ assert engaged
+
+
+def test_grouped_offload_is_not_gated(card, engage):
+ card.update(peak = 7700, free = 50, reserved = 7728)
+ _state, engaged = engage(offload_policy = dmod.OFFLOAD_GROUP)
+ assert engaged
+
+
+def test_unreadable_card_engages(card, engage, monkeypatch):
+ def boom(dev = None):
+ raise RuntimeError("no reading")
+
+ monkeypatch.setattr(torch.cuda, "mem_get_info", boom)
+ card.update(peak = 7700)
+ _state, engaged = engage()
+ assert engaged
+
+
+def test_eager_peak_read_at_render_end_survives_a_counter_reset(card, engage):
+ # a caller resets the peak counters before the 3rd generate: the eager peak noted as render 2 ended still counts
+ state = engage.make()
+ card.update(peak = 7778 - 300, free = 544, reserved = 7234)
+ dmod._note_deferred_eager_peak(state)
+ card["peak"] = 10
+ _state, engaged = engage(state = state)
+ assert not engaged
+
+
+def test_render_start_opens_a_fresh_peak_window_without_the_learned_probe(
+ card, engage, monkeypatch
+):
+ # a previous model left a 23 GiB peak in the counters and no learned-peak probe reset them (LEARNED_PEAKS=0)
+ from core.inference import diffusion_stable_arena as arena
+
+ resets = []
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda dev = None: card.update(peak = 0))
+ monkeypatch.setattr(arena, "reset_peak_mapped", lambda index: resets.append(index))
+ state = engage.make()
+ card.update(peak = 23 * 1024, free = 16384, reserved = 1024)
+ dmod._open_deferred_peak_window(state)
+ assert card["peak"] == 0 and resets == [0]
+ card["peak"] = 5232 # this load's own eager render
+ dmod._note_deferred_eager_peak(state)
+ _state, engaged = engage(state = state)
+ assert engaged
+
+
+def test_hires_refinement_peaks_are_noted_too():
+ # The refinement pass does not count as a generation, but its (larger) peak must still be noted before the next
+ # pass resets the counters, so the note may not sit under the generation-count branch.
+ import ast
+ import inspect
+
+ tree = ast.parse(inspect.getsource(dmod))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.If) and "generation_count" in ast.unparse(node.body[0]):
+ assert "_note_deferred_eager_peak" not in ast.unparse(node), ast.unparse(node)[:200]
+ break
+ else:
+ pytest.fail("generation_count branch not found")
+ assert "_note_deferred_eager_peak(state)" in inspect.getsource(dmod)
+
+
+def test_drop_makes_the_fuse_add_nothing(monkeypatch):
+ # with the unfused copies dropped after the fuse, the fused weights replace the originals
+ monkeypatch.delenv(dspeed.DROP_UNFUSED_QKV_ENV, raising = False)
+ pipe = types.SimpleNamespace(unet = _tiny_unet())
+ assert dspeed.unfused_projections_will_drop(pipe.unet)
+ assert dspeed.fused_qkv_added_bytes(pipe) == 0
+
+
+def test_a_lora_keeps_the_copies_so_they_count(monkeypatch):
+ monkeypatch.delenv(dspeed.DROP_UNFUSED_QKV_ENV, raising = False)
+ unet = _tiny_unet()
+ attn = next(m for m in unet.modules() if callable(getattr(m, "fuse_projections", None)))
+ attn.to_q.lora_A = (
+ torch.nn.ModuleDict()
+ ) # a PEFT adapter on the projections: the drop is skipped
+ pipe = types.SimpleNamespace(unet = unet)
+ assert not dspeed.unfused_projections_will_drop(unet)
+ assert dspeed.fused_qkv_added_bytes(pipe) > 0
+
+
+def test_drop_lets_the_profile_engage_where_the_copies_would_not_fit(card, engage, monkeypatch):
+ # the reading test_profile_declined_when_the_render_would_not_fit declines with the copies kept engages once
+ # they are dropped: the fuse then adds nothing to the card
+ monkeypatch.delenv(dspeed.DROP_UNFUSED_QKV_ENV, raising = False)
+ card.update(peak = 7778 - 300, free = 544, reserved = 7234)
+ _state, engaged = engage()
+ assert engaged
diff --git a/studio/backend/tests/test_diffusion_drop_unfused_qkv.py b/studio/backend/tests/test_diffusion_drop_unfused_qkv.py
new file mode 100644
index 00000000000..d3e56e5e5ae
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_drop_unfused_qkv.py
@@ -0,0 +1,123 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The U-Net QKV fuse drops the projections its fused processor no longer calls, bit-identically, and can rebuild them."""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("diffusers")
+
+from core.inference import diffusion_speed as dspeed # noqa: E402
+
+ENV = "UNSLOTH_DIFFUSION_DROP_UNFUSED_QKV"
+
+
+def _unet():
+ from diffusers import UNet2DConditionModel
+ torch.manual_seed(0)
+ return UNet2DConditionModel(
+ sample_size = 8,
+ in_channels = 4,
+ out_channels = 4,
+ layers_per_block = 1,
+ block_out_channels = (32, 64),
+ down_block_types = ("DownBlock2D", "CrossAttnDownBlock2D"),
+ up_block_types = ("CrossAttnUpBlock2D", "UpBlock2D"),
+ cross_attention_dim = 24,
+ attention_head_dim = 8,
+ norm_num_groups = 8,
+ ).eval()
+
+
+def _inputs():
+ g = torch.Generator().manual_seed(1)
+ return (
+ torch.randn(1, 4, 8, 8, generator = g),
+ torch.tensor([10]),
+ torch.randn(1, 3, 24, generator = g),
+ )
+
+
+def _bytes(m) -> int:
+ return sum(p.numel() * p.element_size() for p in m.parameters())
+
+
+def _pipe(unet):
+ return types.SimpleNamespace(
+ unet = unet, vae = None, fuse_qkv_projections = unet.fuse_qkv_projections
+ )
+
+
+def _attn(unet):
+ from diffusers.models.attention_processor import Attention
+ return [m for m in unet.modules() if isinstance(m, Attention)]
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ monkeypatch.delenv(ENV, raising = False)
+
+
+def test_fuse_drops_the_unused_projections_and_output_is_bit_identical(monkeypatch):
+ # the claim is about the drop, not the fuse: a fused U-Net that keeps its unfused copies (main) against one that
+ # dropped them (the fused GEMM itself may differ from three GEMMs in the last bit on some BLAS builds)
+ kept = _unet()
+ monkeypatch.setenv(ENV, "0")
+ dspeed._fuse_qkv(_pipe(kept), None)
+ monkeypatch.delenv(ENV)
+ with torch.no_grad():
+ before = kept(*_inputs()).sample
+ unet = _unet()
+ unfused_bytes = _bytes(unet)
+ assert dspeed._fuse_qkv(_pipe(unet), None) is True
+ with torch.no_grad():
+ after = unet(*_inputs()).sample
+ assert torch.equal(before, after)
+ # the fused weights replace the dropped ones byte for byte: nothing is held twice
+ assert _bytes(unet) == unfused_bytes
+ for m in _attn(unet):
+ if m.is_cross_attention:
+ assert hasattr(m, "to_q") and not hasattr(m, "to_k") and not hasattr(m, "to_v")
+ else:
+ assert not any(hasattr(m, n) for n in ("to_q", "to_k", "to_v"))
+
+
+def test_restore_rebuilds_the_projections_bit_exactly():
+ unet = _unet()
+ originals = {
+ (i, n): getattr(m, n).weight.detach().clone()
+ for i, m in enumerate(_attn(unet))
+ for n in ("to_q", "to_k", "to_v")
+ }
+ dspeed._fuse_qkv(_pipe(unet), None)
+ assert dspeed.restore_unfused_projections(unet) == len(_attn(unet))
+ for (i, n), w in originals.items():
+ assert torch.equal(getattr(_attn(unet)[i], n).weight, w)
+ assert dspeed.restore_unfused_projections(unet) == 0 # nothing left to rebuild
+
+
+def test_kill_switch_keeps_them(monkeypatch):
+ monkeypatch.setenv(ENV, "0")
+ unet = _unet()
+ unfused_bytes = _bytes(unet)
+ dspeed._fuse_qkv(_pipe(unet), None)
+ assert all(hasattr(m, "to_k") for m in _attn(unet))
+ assert _bytes(unet) > unfused_bytes
+
+
+def test_a_peft_adapter_keeps_them():
+ pytest.importorskip("peft")
+ from peft import LoraConfig
+
+ unet = _unet()
+ unet.add_adapter(
+ LoraConfig(r = 2, lora_alpha = 2, target_modules = ["to_q", "to_k", "to_v"]), adapter_name = "a"
+ )
+ unet.fuse_qkv_projections()
+ assert dspeed.drop_unfused_projections(unet) == 0
+ assert all(hasattr(m, "to_k") for m in _attn(unet))