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 Qwen-Image-2.1: one GEMM for the dense gate + value and Q / K / V projections (#17214)

Daniel Han8504a4fc1b39
diff --git a/studio/backend/core/inference/diffusion_autoopt/patches.py b/studio/backend/core/inference/diffusion_autoopt/patches.py
index ec70d2bbdab..26d424b0c5b 100644
--- a/studio/backend/core/inference/diffusion_autoopt/patches.py
+++ b/studio/backend/core/inference/diffusion_autoopt/patches.py
@@ -484,6 +484,16 @@ def _builtin_specs() -> list[PatchSpec]:
from ..diffusion_qwenimage21_fused import uninstall
uninstall()
+ def q21_dense_fused(ctx: PatchContext) -> Any:
+ from ..diffusion_qwenimage21_dense_fused import install
+ return install(
+ ctx.transformer,
+ ctx.logger,
+ offload_active = ctx.offload_active
+ if ctx.denoiser_offloaded is None
+ else bool(ctx.denoiser_offloaded),
+ )
+
def moss_fused(ctx: PatchContext) -> Any:
from ..diffusion_moss_fused import install
return install(
@@ -611,6 +621,16 @@ def _builtin_specs() -> list[PatchSpec]:
warn = "qwen-image-2.1 convrot sharing",
env = "UNSLOTH_DIFFUSION_Q21_CONVROT_FUSED",
),
+ PatchSpec(
+ "qwenimage21_dense_fused",
+ STAGE_PRE_COMPILE,
+ q21_dense_fused,
+ None,
+ group = GROUP_FUSED_DIT,
+ classes = ("QwenImage21Transformer2DModel",),
+ warn = "qwen-image-2.1 dense gate/value GEMM",
+ env = "UNSLOTH_DIFFUSION_Q21_DENSE_FUSED",
+ ),
PatchSpec(
"moss_fused",
STAGE_PRE_COMPILE,
diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.py
index 62b2c44acdd..0e4f9321714 100644
--- a/studio/backend/core/inference/diffusion_multigpu.py
+++ b/studio/backend/core/inference/diffusion_multigpu.py
@@ -1989,6 +1989,8 @@ def _copy_module(module: Any, device: Any) -> Any:
continue
memo[id(buffer)] = buffer.detach().to(device)
keep.append(buffer)
+ from .diffusion_qwenimage21_dense_fused import is_replica_record, rebuild_replica
+
for sub in module.modules():
offload_keys = set(_offload_attr_keys(sub))
for key, value in sub.__dict__.items():
@@ -1996,6 +1998,7 @@ def _copy_module(module: Any, device: Any) -> Any:
isinstance(value, CfgParallelRouter)
or key in offload_keys
or key in _SOURCE_ONLY_ATTRS
+ or is_replica_record(key, value)
):
# never traversed: offload state holds pinned host copies a deepcopy would duplicate, and a
# source-only cache holds source-card tensors
@@ -2034,6 +2037,16 @@ def _copy_module(module: Any, device: Any) -> Any:
del hooks[hook_id]
for other in _ROOT_HOOK_DICTS:
sub.__dict__.get(other, {}).pop(hook_id, None)
+ # Release the copies before re-fusing on the replica's card, else each replaced allocation stays alive.
+ memo.clear()
+ del keep
+ param = copied = new = buffer = (
+ None # the copy loop's last parameter, still referenced by these names
+ )
+ try:
+ rebuild_replica(module, replica)
+ except Exception: # noqa: BLE001 - the replica keeps the stock projections
+ pass
if isinstance(router, CfgParallelRouter) and router.had_override:
_rebind_root_forward(router.orig_forward, module, replica)
# The source's own __call__ runs its root hooks around every branch; the copy must not run them a second time.
diff --git a/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py b/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py
new file mode 100644
index 00000000000..16f5e971f18
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_qwenimage21_dense_fused.py
@@ -0,0 +1,206 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Qwen-Image-2.1 dense projections that read one input run as one GEMM over the row-concatenated weight:
+the SwiGLU ``gate_layer`` + ``proj`` (the single-file layout's ``gate_up``; the halves feed ``silu(gate) * value``)
+and, under compile, attention ``to_q`` + ``to_k`` + ``to_v`` (through the shared Q / K / V helper of
+``diffusion_qwenimage21_fused``). The parts become row views of the fused weight, so it costs no memory and in-place
+weight writes (LoRA fold / restore) reach both. Plain bf16 / fp16 / fp32 Linears on one resident GPU only
+(quantised, GGUF, LoRA-wrapped, hooked or offloaded layers keep the stock modules); compiled loads only.
+UNSLOTH_DIFFUSION_Q21_DENSE_FUSED=0 keeps the stock projections."""
+
+from __future__ import annotations
+
+import os
+import threading
+import types
+from typing import Any
+
+Q21_DENSE_FUSED_ENV = "UNSLOTH_DIFFUSION_Q21_DENSE_FUSED"
+_FF_ATTR = "_unsloth_q21_dense_gate_up"
+_FF_CLASS = "QwenImage21SwiGLUFeedForward"
+_ATTN_CLASS = "QwenImage21Attention"
+_FIRST_CALL_KEY = "q21_dense_fused"
+_DEVICE_TYPES = ("cuda",) # CUDA and ROCm torch both report "cuda"
+
+_LOCK = threading.Lock()
+
+
+def disabled() -> bool:
+ return (os.environ.get(Q21_DENSE_FUSED_ENV) or "").strip().lower() in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def _plain_dense(lin: Any) -> bool:
+ import torch
+ from torch import nn
+
+ if type(lin) is not nn.Linear or lin.bias is not None:
+ return False
+ if "forward" in lin.__dict__ or lin._forward_hooks or lin._forward_pre_hooks:
+ return False
+ w = lin.weight
+ return (
+ type(w) is nn.Parameter
+ and type(w.data) is torch.Tensor
+ and w.dtype in (torch.bfloat16, torch.float16, torch.float32)
+ and w.device.type in _DEVICE_TYPES
+ )
+
+
+def _resident_device(module: Any) -> Any:
+ try:
+ devices = {p.device for p in module.parameters()}
+ except Exception: # noqa: BLE001
+ return None
+ if len(devices) != 1:
+ return None
+ dev = next(iter(devices))
+ return dev if dev.type in _DEVICE_TYPES else None
+
+
+def _intact(ff: Any) -> Any:
+ rec = ff.__dict__.get(_FF_ATTR)
+ if rec is None:
+ return None
+ weight, gate, proj, gate_w, proj_w = rec
+ if ff.gate_layer is not gate or ff.proj is not proj:
+ return None
+ if gate.weight is not gate_w or proj.weight is not proj_w:
+ return None
+ if weight.device != gate_w.device:
+ return None
+ return weight
+
+
+def _forward(self: Any, hidden_states: Any) -> Any:
+ import torch.nn.functional as F
+
+ weight = _intact(self)
+ if weight is None:
+ return type(self).forward(self, hidden_states)
+ gate, value = F.linear(hidden_states, weight).chunk(2, dim = -1)
+ return self.out(self.activation_fn(gate) * value)
+
+
+def _fuse(ff: Any) -> bool:
+ import torch
+ from torch import nn
+
+ gate, proj = ff.gate_layer, ff.proj
+ if not (_plain_dense(gate) and _plain_dense(proj)) or not _plain_dense(ff.out):
+ return False
+ gw, pw = gate.weight, proj.weight
+ if gw.shape != pw.shape or gw.dtype != pw.dtype or gw.device != pw.device:
+ return False
+ with torch.no_grad():
+ fused = torch.cat([gw.detach(), pw.detach()], dim = 0)
+ n = gw.shape[0]
+ gate.weight = nn.Parameter(fused[:n], requires_grad = False)
+ proj.weight = nn.Parameter(fused[n:], requires_grad = False)
+ ff.__dict__[_FF_ATTR] = (fused, gate, proj, gate.weight, proj.weight)
+ ff.forward = types.MethodType(_forward, ff)
+ return True
+
+
+def _fuse_qkv(attn: Any, qkv_attr: str) -> bool:
+ from .diffusion_zimage_fused import _fuse_linears, _share_storage
+
+ parts = [getattr(attn, n, None) for n in ("to_q", "to_k", "to_v")]
+ if any(p is None or not _plain_dense(p) for p in parts):
+ return False
+ if len({(p.weight.dtype, p.weight.device, p.weight.shape[1]) for p in parts}) != 1:
+ return False
+ fused = _fuse_linears(parts)
+ if fused is None or not _share_storage(fused, parts):
+ return False
+ attn.__dict__[qkv_attr] = (fused, *parts)
+ return True
+
+
+def install_modules(root: Any, logger: Any = None) -> dict:
+ result = {"gate_up": 0, "qkv": 0}
+ if disabled() or _resident_device(root) is None:
+ return result
+ from . import diffusion_qwenimage21_fused as q21f
+
+ qkv_ok = not q21f.q21_convrot_fused_disabled() and q21f._patch_prepare(logger)
+ with _LOCK:
+ for module in root.modules():
+ name = type(module).__name__
+ if name == _FF_CLASS:
+ if _intact(module) is not None or _fuse(module):
+ result["gate_up"] += 1
+ elif name == _ATTN_CLASS and qkv_ok:
+ if q21f._qkv_intact(module) is not None or _fuse_qkv(module, q21f._QKV_ATTR):
+ result["qkv"] += 1
+ if logger is not None and (result["gate_up"] or result["qkv"]):
+ logger.info(
+ "diffusion.q21_dense_fused: one GEMM for gate + value in %d MLP(s), for Q / K / V in %d attention(s)",
+ result["gate_up"],
+ result["qkv"],
+ )
+ return result
+
+
+def install(
+ transformer: Any,
+ logger: Any = None,
+ offload_active: bool = False,
+) -> Any:
+ """Offloaded loads stay stock: an offload hook moving the row views would copy each part beside the fused weight."""
+ if disabled():
+ uninstall(transformer)
+ return {"gate_up": 0, "qkv": 0}
+ if type(transformer).__name__ != "QwenImage21Transformer2DModel" or offload_active:
+ return {"gate_up": 0, "qkv": 0}
+ if _resident_device(transformer) is not None:
+ return install_modules(transformer, logger)
+ from .diffusion_int8_fused import run_on_first_call
+
+ run_on_first_call(transformer, _FIRST_CALL_KEY, lambda t: install_modules(t, logger))
+ return None
+
+
+def uninstall(transformer: Any = None) -> None:
+ if transformer is None:
+ return
+ from .diffusion_int8_fused import cancel_first_call
+ from .diffusion_qwenimage21_fused import _QKV_ATTR
+
+ cancel_first_call(transformer, _FIRST_CALL_KEY)
+ with _LOCK:
+ for module in transformer.modules():
+ rec = module.__dict__.get(_QKV_ATTR)
+ if rec is not None and _plain_dense(rec[0]):
+ module.__dict__.pop(_QKV_ATTR, None)
+ if module.__dict__.pop(_FF_ATTR, None) is not None:
+ fwd = module.__dict__.get("forward")
+ if getattr(fwd, "__func__", None) is _forward:
+ module.__dict__.pop("forward", None)
+
+
+def is_replica_record(key: str, value: Any) -> bool:
+ """Fused weights live outside the module tree: a deep copy (CFG replica) would duplicate them on the source card."""
+ if key == _FF_ATTR:
+ return True
+ from .diffusion_qwenimage21_fused import _QKV_ATTR
+
+ try:
+ return key == _QKV_ATTR and isinstance(value, tuple) and _plain_dense(value[0])
+ except Exception: # noqa: BLE001
+ return False
+
+
+def rebuild_replica(source: Any, replica: Any) -> dict:
+ if not any(is_replica_record(k, v) for m in source.modules() for k, v in m.__dict__.items()):
+ return {"gate_up": 0, "qkv": 0}
+ return install_modules(replica)
+
+
+def is_installed(module: Any) -> bool:
+ return _FF_ATTR in getattr(module, "__dict__", {})
diff --git a/studio/backend/tests/test_diffusion_autoopt_core.py b/studio/backend/tests/test_diffusion_autoopt_core.py
index c4139057d85..469bdb214ba 100644
--- a/studio/backend/tests/test_diffusion_autoopt_core.py
+++ b/studio/backend/tests/test_diffusion_autoopt_core.py
@@ -205,6 +205,7 @@ def test_builtin_specs_cover_every_former_install_site():
"qwenimage_real_rope",
"zimage_fused",
"qwenimage21_fused",
+ "qwenimage21_dense_fused",
"moss_fused",
}
# the former hand-kept teardown list is now a registry group
@@ -215,6 +216,7 @@ def test_builtin_specs_cover_every_former_install_site():
"qwenimage_real_rope",
"zimage_fused",
"qwenimage21_fused",
+ "qwenimage21_dense_fused",
"moss_fused",
}
# every spec answers its module's existing kill switch name
@@ -228,6 +230,7 @@ def test_builtin_specs_cover_every_former_install_site():
"qwenimage_real_rope",
"zimage_fused",
"qwenimage21_fused",
+ "qwenimage21_dense_fused",
"moss_fused",
]
diff --git a/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py b/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py
new file mode 100644
index 00000000000..06c27f10bdd
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_qwenimage21_dense_fused.py
@@ -0,0 +1,347 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Qwen-Image-2.1 dense SwiGLU gate / value GEMM fusion (CPU stand-ins with the diffusers class names)."""
+
+from __future__ import annotations
+
+import pytest
+
+torch = pytest.importorskip("torch")
+from torch import nn # noqa: E402
+
+from core.inference import diffusion_qwenimage21_dense_fused as dfu # noqa: E402
+
+
+class QwenImage21SwiGLUFeedForward(nn.Module):
+ """diffusers' module, same attributes and forward."""
+
+ def __init__(self, hidden_size: int, mlp_hidden_size: int):
+ super().__init__()
+ self.proj = nn.Linear(hidden_size, mlp_hidden_size, bias = False)
+ self.out = nn.Linear(mlp_hidden_size, hidden_size, bias = False)
+ self.gate_layer = nn.Linear(hidden_size, mlp_hidden_size, bias = False)
+ self.activation_fn = nn.SiLU()
+
+ def forward(self, hidden_states):
+ return self.out(
+ self.activation_fn(self.gate_layer(hidden_states)) * self.proj(hidden_states)
+ )
+
+
+class QwenImage21Transformer2DModel(nn.Module):
+ def __init__(
+ self,
+ n: int = 2,
+ dim: int = 32,
+ ):
+ super().__init__()
+ self.blocks = nn.ModuleList(QwenImage21SwiGLUFeedForward(dim, 3 * dim) for _ in range(n))
+
+ def forward(self, x):
+ for b in self.blocks:
+ x = x + b(x)
+ return x
+
+
[email protected](autouse = True)
+def _cpu(monkeypatch):
+ monkeypatch.setattr(dfu, "_DEVICE_TYPES", ("cpu",))
+ monkeypatch.delenv(dfu.Q21_DENSE_FUSED_ENV, raising = False)
+ torch.manual_seed(0)
+
+
+def _model(dtype = torch.float32):
+ return QwenImage21Transformer2DModel().to(dtype).eval()
+
+
+def test_fused_matches_stock_and_shares_storage():
+ m = _model()
+ x = torch.randn(3, 7, 32)
+ with torch.no_grad():
+ ref = m(x)
+ assert dfu.install(m)["gate_up"] == 2
+ for b in m.blocks:
+ fused = b.__dict__[dfu._FF_ATTR][0]
+ assert (
+ b.gate_layer.weight.untyped_storage().data_ptr() == fused.untyped_storage().data_ptr()
+ )
+ assert b.proj.weight.untyped_storage().data_ptr() == fused.untyped_storage().data_ptr()
+ assert fused.shape == (2 * 96, 32)
+ with torch.no_grad():
+ out = m(x)
+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-5)
+ # no second parameter set: the model's parameter bytes are unchanged
+ assert sum(p.numel() for p in m.parameters()) == 2 * (3 * 96 * 32)
+
+
+def test_bf16_matches_stock_within_one_rounding():
+ m = _model(torch.bfloat16)
+ x = torch.randn(2, 5, 32, dtype = torch.bfloat16)
+ with torch.no_grad():
+ ref = m(x).float()
+ dfu.install(m)
+ with torch.no_grad():
+ out = m(x).float()
+ torch.testing.assert_close(out, ref, rtol = 2e-2, atol = 2e-2)
+
+
+def test_in_place_weight_write_reaches_the_fused_gemm():
+ m = _model()
+ x = torch.randn(2, 4, 32)
+ dfu.install(m)
+ with torch.no_grad():
+ m.blocks[0].gate_layer.weight.add_(0.5) # a LoRA fold / restore writes in place
+ out = m(x)
+ dfu.uninstall(m)
+ ref = m(x)
+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-5)
+
+
+def test_swapped_parts_fall_back_to_the_stock_forward():
+ m = _model()
+ x = torch.randn(2, 4, 32)
+ dfu.install(m)
+ b = m.blocks[0]
+ b.gate_layer = nn.Linear(32, 96, bias = False) # e.g. an adapter wrapper replacing the module
+ assert dfu._intact(b) is None
+ with torch.no_grad():
+ got = b(x)
+ want = b.out(b.activation_fn(b.gate_layer(x)) * b.proj(x))
+ torch.testing.assert_close(got, want)
+ b2 = m.blocks[1]
+ b2.proj.weight = nn.Parameter(
+ b2.proj.weight.detach().clone(), requires_grad = False
+ ) # a new parameter
+ assert dfu._intact(b2) is None
+
+
[email protected]("why", ["kill", "offload", "bias", "hook", "subclass", "other_model"])
+def test_declines(monkeypatch, why):
+ m = _model()
+ b = m.blocks[0]
+ kw = {}
+ if why == "kill":
+ monkeypatch.setenv(dfu.Q21_DENSE_FUSED_ENV, "0")
+ elif why == "offload":
+ kw["offload_active"] = True
+ elif why == "bias":
+ b.gate_layer.bias = nn.Parameter(torch.zeros(96))
+ elif why == "hook":
+ b.proj.register_forward_pre_hook(lambda mod, args: None)
+ elif why == "subclass":
+
+ class QuantWeight(torch.Tensor):
+ pass
+
+ b.proj.weight = nn.Parameter(
+ b.proj.weight.detach().as_subclass(QuantWeight), requires_grad = False
+ )
+ elif why == "other_model":
+ m.__class__ = type(
+ "FluxTransformer2DModel",
+ (nn.Module,),
+ {"forward": QwenImage21Transformer2DModel.forward},
+ )
+ n = dfu.install(m, **kw)
+ if why in ("kill", "offload", "other_model"):
+ assert not any(n.values())
+ assert not any(dfu.is_installed(x) for x in m.modules())
+ else:
+ assert n["gate_up"] == 1 # the other block still fuses
+ assert not dfu.is_installed(b)
+
+
+def test_weights_off_the_gpu_defer_to_the_first_call(monkeypatch):
+ m = _model()
+ monkeypatch.setattr(dfu, "_DEVICE_TYPES", ("cuda",))
+ assert dfu.install(m) is None
+ assert not any(dfu.is_installed(x) for x in m.modules())
+ monkeypatch.setattr(dfu, "_DEVICE_TYPES", ("cpu",)) # "placed" before the first forward
+ with torch.no_grad():
+ m(torch.randn(1, 2, 32))
+ assert all(dfu.is_installed(b) for b in m.blocks)
+
+
+def test_uninstall_restores_the_stock_forward():
+ m = _model()
+ dfu.install(m)
+ dfu.uninstall(m)
+ for b in m.blocks:
+ assert not dfu.is_installed(b)
+ assert "forward" not in b.__dict__
+
+
+def test_compiles_without_graph_breaks():
+ m = _model()
+ dfu.install(m)
+ torch._dynamo.reset()
+ try:
+ explain = torch._dynamo.explain(m.blocks[0])(torch.randn(2, 4, 32))
+ finally:
+ torch._dynamo.reset()
+ assert explain.graph_break_count == 0
+ assert explain.graph_count == 1
+
+
+def test_qkv_records_go_through_the_shared_helper(monkeypatch):
+ from core.inference import diffusion_qwenimage21_fused as q21f
+
+ class QwenImage21Attention(nn.Module):
+ def __init__(self, dim = 32):
+ super().__init__()
+ self.to_q = nn.Linear(dim, dim, bias = False)
+ self.to_k = nn.Linear(dim, dim, bias = False)
+ self.to_v = nn.Linear(dim, dim, bias = False)
+
+ m = _model()
+ m.attn = QwenImage21Attention()
+ monkeypatch.setattr(q21f, "_patch_prepare", lambda logger = None: True)
+ out = dfu.install(m)
+ assert out == {"gate_up": 2, "qkv": 1}
+ fused = q21f._qkv_intact(m.attn)
+ assert fused is not None and fused.weight.shape == (96, 32)
+ x = torch.randn(2, 3, 32)
+ with torch.no_grad():
+ q, k, v = fused(x).chunk(3, dim = -1)
+ torch.testing.assert_close(q, m.attn.to_q(x))
+ torch.testing.assert_close(v, m.attn.to_v(x))
+ dfu.uninstall(m)
+ assert q21f._qkv_intact(m.attn) is None
+ # the int8 path's kill switch also keeps Q / K / V stock
+ monkeypatch.setenv(q21f.Q21_CONVROT_FUSED_ENV, "0")
+ m2 = _model()
+ m2.attn = QwenImage21Attention()
+ assert dfu.install(m2) == {"gate_up": 2, "qkv": 0}
+
+
+def test_real_tiny_qwen21_stock_vs_fused_eager_and_compiled():
+ qmod = pytest.importorskip("diffusers.models.transformers.transformer_qwenimage21")
+ from core.inference import diffusion_qwenimage21_fused as q21f
+
+ torch.manual_seed(0)
+ m = qmod.QwenImage21Transformer2DModel(
+ num_layers = 2,
+ attention_head_dim = 16,
+ num_attention_heads = 2,
+ context_in_dim = 24,
+ in_channels = 8,
+ out_channels = 8,
+ axes_dims_rope = (4, 6, 6),
+ ).eval()
+ with torch.no_grad():
+ for p in m.parameters():
+ p.normal_(0, 0.2)
+ g = torch.Generator().manual_seed(7)
+ text, (th, tw) = 9, (4, 6)
+ img_mask = torch.cat(
+ [torch.zeros(text, dtype = torch.bool), torch.ones(th * tw // 4, dtype = torch.bool)]
+ )[None]
+ ehs = torch.randn(1, text, 24, generator = g)
+ lat0 = torch.randn(1, th * tw, 8, generator = g)
+
+ def _render(steps = 3):
+ outs, lat = [], lat0
+ kv = qmod.QwenImage21KVCache(len(m.transformer_blocks))
+ with torch.inference_mode():
+ for i in range(steps):
+ out = m(
+ hidden_states = lat,
+ timestep = torch.full((1,), 1.0 - i / steps),
+ encoder_hidden_states = ehs,
+ encoder_hidden_states_mask = None,
+ img_shapes = [[(1, th, tw)]],
+ img_mask = img_mask,
+ kv_cache = kv,
+ kv_cache_mode = "extract" if i == 0 else "cached",
+ return_dict = False,
+ )[0]
+ outs.append(out.clone())
+ lat = lat - 0.1 * out[:, -lat.shape[1] :]
+ return outs
+
+ ref = _render()
+ try:
+ out = dfu.install(m)
+ assert out["gate_up"] == len(m.transformer_blocks)
+ assert out["qkv"] == len(m.transformer_blocks)
+ eager = _render()
+ for a, b in zip(ref, eager):
+ torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-5)
+ hits = []
+ for mod in m.modules():
+ fused = q21f._qkv_intact(mod) if type(mod).__name__ == "QwenImage21Attention" else None
+ if fused is not None:
+ fused.register_forward_pre_hook(lambda *_a: hits.append(1))
+ torch._dynamo.reset()
+ m.compile_repeated_blocks(backend = "eager", fullgraph = True, dynamic = False)
+ compiled = _render()
+ assert hits, "the compiled blocks never ran the fused Q / K / V projection"
+ for a, b in zip(ref, compiled):
+ torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-5)
+ finally:
+ torch._dynamo.reset()
+ dfu.uninstall(m)
+ q21f.uninstall()
+ assert qmod._qwenimage21_prepare_qkv.__name__ == "_qwenimage21_prepare_qkv"
+
+
+def test_cfg_replica_drops_source_records_and_fuses_its_own(monkeypatch):
+ from core.inference import diffusion_multigpu as mg
+ from core.inference import diffusion_qwenimage21_fused as q21f
+
+ class QwenImage21Attention(nn.Module):
+ def __init__(self, dim = 32):
+ super().__init__()
+ self.to_q = nn.Linear(dim, dim, bias = False)
+ self.to_k = nn.Linear(dim, dim, bias = False)
+ self.to_v = nn.Linear(dim, dim, bias = False)
+
+ monkeypatch.setattr(q21f, "_patch_prepare", lambda logger = None: True)
+ m = _model()
+ m.attn = QwenImage21Attention()
+ assert dfu.install(m) == {"gate_up": 2, "qkv": 1}
+ src_ptrs = {b.__dict__[dfu._FF_ATTR][0].untyped_storage().data_ptr() for b in m.blocks}
+ replica = mg._copy_module(m, torch.device("cpu"))
+ for b in replica.blocks:
+ rec = b.__dict__[dfu._FF_ATTR]
+ ptr = rec[0].untyped_storage().data_ptr()
+ assert ptr not in src_ptrs # not the source's fused copy
+ assert b.gate_layer.weight.untyped_storage().data_ptr() == ptr # the replica's own views
+ assert dfu._intact(b) is not None
+ fused = q21f._qkv_intact(replica.attn)
+ assert fused is not None
+ assert (
+ replica.attn.to_q.weight.untyped_storage().data_ptr()
+ == fused.weight.untyped_storage().data_ptr()
+ )
+ x = torch.randn(2, 3, 32)
+ with torch.no_grad():
+ torch.testing.assert_close(replica(x), m(x), rtol = 1e-5, atol = 1e-5)
+
+
+def test_cfg_replica_rebuild_frees_the_copied_parts(monkeypatch):
+ import gc
+ import weakref
+
+ from core.inference import diffusion_multigpu as mg
+
+ m = _model()
+ dfu.install(m)
+ alive_after_rebuild = []
+ orig = dfu.rebuild_replica
+
+ def spy(source, replica):
+ refs = [
+ weakref.ref(b.gate_layer.weight) for b in replica.blocks
+ ] # the copies the deepcopy made
+ out = orig(source, replica)
+ gc.collect()
+ # still inside _copy_module: nothing but its memo could keep the replaced copies alive here
+ alive_after_rebuild.extend(r() is not None for r in refs)
+ return out
+
+ monkeypatch.setattr(dfu, "rebuild_replica", spy)
+ replica = mg._copy_module(m, torch.device("cpu"))
+ assert alive_after_rebuild == [False] * len(replica.blocks)
+ assert all(dfu._intact(b) is not None for b in replica.blocks)