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: build the ConvRot rotation from its definition (#11807)

Daniel Han3ed8f685996b
diff --git a/studio/backend/core/inference/diffusion_convrot.py b/studio/backend/core/inference/diffusion_convrot.py
index 65b34e528bd..e6a5af8d8fc 100644
--- a/studio/backend/core/inference/diffusion_convrot.py
+++ b/studio/backend/core/inference/diffusion_convrot.py
@@ -21,7 +21,7 @@ flatter distribution on both sides.
The arithmetic is the SAME ConvRot the hosted Qwen3-VL conditioner already runs, so
``build_convrot_hadamard`` / ``rotate_convrot_activation`` live here and
``video_minimax_h3_te`` imports them. One Hadamard in the tree, not two: the conditioner's and
-the denoiser's rotations have to agree with the same comfy-kitchen definition, and two copies of
+the denoiser's rotations have to agree on the same ConvRot definition, and two copies of
a matrix nobody re-derives at review time is how they stop agreeing.
What this module adds on top of those primitives is the DENOISER half: the offline weight
@@ -90,22 +90,32 @@ def is_power_of_four(size: Any) -> bool:
return (n.bit_length() - 1) % 2 == 0
-# The rotation itself. Mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight``, in a
-# few lines of torch rather than a dependency on a wheel Unsloth does not ship.
+# H = kron(H4, ...) / sqrt(size), H4[a, b] = -1 iff a ^ b == 3: sign(i, j) = parity of base-4 digits of i ^ j equal to 3.
+# Must stay bit-identical to the kron construction the hosted checkpoints were rotated with.
_HADAMARD_CACHE: dict = {}
+def _convrot_sign_bits(size: int) -> Any:
+ """Bool ``[size, size]`` tensor, True where the unnormalized kron power of H4 is -1."""
+ import torch
+
+ idx = torch.arange(size, dtype = torch.int64)
+ both = idx[:, None] ^ idx[None, :]
+ threes = both & (both >> 1) & 0x5555555555555555
+ parity = torch.zeros_like(threes)
+ # fixed Python loop count keeps this traceable under fullgraph
+ for _ in range((size.bit_length() - 1) // 2):
+ parity ^= threes & 1
+ threes = threes >> 2
+ return parity.bool()
+
+
def build_convrot_hadamard(
size: int,
device: Any = "cpu",
dtype: Any = None,
) -> Any:
- """The normalized regular Hadamard matrix ConvRot rotates by. Cached per (size, device, dtype).
-
- Built as ``kron(H4, H4, ...) / sqrt(size)``, which is both symmetric and orthogonal -- the
- property the offline/online pair relies on, since it means the same matrix undoes itself and
- the weight side can use ``H.T`` interchangeably with ``H``. Building directly in ``dtype`` is
- exact for every float type: the entries are +-1 and the normalizer is a power of two."""
+ """Normalized ConvRot Hadamard, cached per (size, device, dtype). Symmetric, so ``H.T == H``."""
import torch
if dtype is None:
@@ -116,29 +126,21 @@ def build_convrot_hadamard(
return cached
if not is_power_of_four(size):
raise ValueError(f"ConvRot group size must be a power of 4, got {size}")
- h4 = torch.tensor(
- [[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]],
- dtype = dtype,
- device = device,
- )
- h = h4
- current = 4
- while current < size:
- h = torch.kron(h, h4)
- current *= 4
- h = h / (size**0.5)
+ scale = 2.0 ** -((size.bit_length() - 1) // 2)
+ negative = _convrot_sign_bits(size).to(device)
+ h = torch.full((size, size), scale, dtype = dtype, device = device)
+ h = h.masked_fill(negative, -scale)
_HADAMARD_CACHE[key] = h
return h
def rotate_convrot_activation(x: Any, h: Any, group_size: int) -> Any:
- """``x @ H`` blockwise over the last dimension."""
- shape = x.shape
- features = shape[-1]
+ """``x @ blockdiag(H)`` over the last dimension."""
+ features = x.shape[-1]
if features % group_size != 0:
raise ValueError(f"features {features} not divisible by ConvRot group {group_size}")
- grouped = x.reshape(-1, features // group_size, group_size)
- return grouped.matmul(h.to(dtype = x.dtype, device = x.device)).reshape(shape)
+ blocks = x.reshape(-1, features // group_size, group_size)
+ return (blocks @ h.to(device = x.device, dtype = x.dtype)).reshape(x.shape)
def rotate_convrot_weight_(module: Any, group_size: int) -> None:
@@ -156,10 +158,8 @@ def rotate_convrot_weight_(module: Any, group_size: int) -> None:
f"in_features {in_features} is not divisible by the ConvRot group {group_size}"
)
h = build_convrot_hadamard(group_size, device = weight.device, dtype = torch.float32)
- rotated = torch.matmul(
- weight.float().reshape(out_features, in_features // group_size, group_size), h.T
- ).reshape(out_features, in_features)
- module.weight.data = rotated.to(weight.dtype)
+ blocks = weight.float().reshape(out_features, in_features // group_size, group_size)
+ module.weight.data = (blocks @ h.T).reshape(out_features, in_features).to(weight.dtype)
@lru_cache(maxsize = None)
diff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.py
index f5d9ced1268..386579f02b9 100644
--- a/studio/backend/core/inference/video_minimax_h3_te.py
+++ b/studio/backend/core/inference/video_minimax_h3_te.py
@@ -163,11 +163,7 @@ def h3_te_resident_gb(scheme: Optional[str], *, bf16_gb: float) -> float:
# which is symmetric and orthogonal, so H @ H == I exactly and x_rot @ W_rot^T == x @ W^T. The rotation is what lets
# INT8 survive Qwen3-VL's per-channel activation outliers; dequantizing WITHOUT it is not an approximation, it is
# noise (measured against the hosted bfloat16 file for one projection: 0.9% relative error with the rotation, 137%
-# without). This mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight`` exactly
-# rather than taking a dependency on a wheel Unsloth does not ship. ``build_convrot_hadamard`` and
-# ``rotate_convrot_activation`` live in ``diffusion_convrot`` and are imported at the top of this module: the DENOISER
-# runs the same ConvRot on its own hosted INT8 checkpoint, and two copies of a matrix nobody re-derives at review time
-# is exactly how they would stop agreeing. Both stay importable from here.
+# without). The Hadamard lives in ``diffusion_convrot`` so the denoiser and conditioner share one copy.
@lru_cache(maxsize = None)
def _int8_convrot_linear_class() -> Any:
"""The ConvRot INT8 ``nn.Linear`` stand-in, built lazily so importing this module never imports
@@ -195,9 +191,7 @@ def _int8_convrot_linear_class() -> Any:
tiny tensor instead of approximate in bfloat16 over a huge one. INT8 values are integers
below 256, so the ``.to(compute dtype)`` is exact in bfloat16.
- Weight-only, unlike comfy-kitchen's W8A8 kernel, which also quantizes the activation
- per row. Same weights and the same rotation, strictly less error, and the conditioner runs
- once per generation so the dequantize is not on any hot path.
+ Weight-only (not W8A8): less error, and the conditioner runs once per generation.
"""
def __init__(
diff --git a/studio/backend/tests/test_diffusion_convrot.py b/studio/backend/tests/test_diffusion_convrot.py
index 2990b1cc24d..fa09bb0f5a5 100644
--- a/studio/backend/tests/test_diffusion_convrot.py
+++ b/studio/backend/tests/test_diffusion_convrot.py
@@ -103,15 +103,70 @@ def test_hadamard_is_symmetric_and_orthogonal():
assert torch.allclose(h @ h, torch.eye(size), atol = 1e-5)
+_H4 = ((1, 1, 1, -1), (1, 1, -1, 1), (1, -1, 1, 1), (-1, 1, 1, 1))
+_SIZES = (4, 16, 64, 256, 1024)
+_DTYPES = (torch.float32, torch.float16, torch.bfloat16)
+_DEVICES = ("cpu",) + (("cuda",) if torch.cuda.is_available() else ())
+
+
+def _reference_hadamard(size, dtype):
+ # the kron definition the hosted checkpoints were rotated with; exact in float64
+ h4 = torch.tensor(_H4, dtype = torch.float64)
+ h = h4
+ while h.shape[0] < size:
+ h = torch.kron(h, h4)
+ return (h / size**0.5).to(dtype)
+
+
+def _bits(t):
+ return t.view(torch.int32 if t.dtype == torch.float32 else torch.int16)
+
+
[email protected]("device", _DEVICES)
[email protected]("dtype", _DTYPES)
[email protected]("size", _SIZES)
+def test_hadamard_is_bit_identical_to_the_kron_definition(size, dtype, device):
+ h = build_convrot_hadamard(size, device = device, dtype = dtype)
+ ref = _reference_hadamard(size, dtype).to(device)
+ assert h.dtype == dtype and h.device.type == torch.device(device).type
+ assert h.shape == (size, size)
+ assert torch.equal(_bits(h), _bits(ref))
+
+
[email protected]("size", _SIZES)
+def test_hadamard_is_orthogonal_in_float64_exactly(size):
+ h = build_convrot_hadamard(size, dtype = torch.float64)
+ assert torch.equal(h, h.T)
+ assert torch.equal(h @ h.T, torch.eye(size, dtype = torch.float64))
+
+
[email protected]("device", _DEVICES)
[email protected]("size", (4, 16, 256))
+def test_rotations_match_an_explicit_block_diagonal(size, device):
+ from core.inference.diffusion_convrot import rotate_convrot_activation
+
+ torch.manual_seed(0)
+ groups = 3
+ ref = _reference_hadamard(size, torch.float64).to(device)
+ block = torch.block_diag(*([ref] * groups))
+ x = torch.randn(2, 5, groups * size, dtype = torch.float64, device = device)
+ h = build_convrot_hadamard(size, device = device, dtype = torch.float64)
+ assert torch.allclose(rotate_convrot_activation(x, h, size), x @ block, atol = 1e-12)
+
+ linear = nn.Linear(groups * size, 6, dtype = torch.float32, device = device)
+ dense = linear.weight.detach().double().clone()
+ rotate_convrot_weight_(linear, size)
+ expected = (dense @ block.T).float()
+ assert torch.allclose(linear.weight, expected, atol = 1e-6)
+
+
def test_hadamard_rejects_a_non_power_of_four():
with pytest.raises(ValueError):
build_convrot_hadamard(32)
def test_denoiser_and_conditioner_share_one_hadamard():
- # The hosted conditioner (PR 8283) and the denoiser have to agree with the same comfy-kitchen
- # definition down to the normalizer. Sharing the function is how that is guaranteed rather
- # than periodically re-checked; this pins the sharing so a future copy-paste fails here.
+ # conditioner (PR 8283) and denoiser must share one Hadamard; fails on a future copy-paste
from core.inference import video_minimax_h3_te as te
from core.inference import diffusion_convrot as cr
@@ -434,3 +489,22 @@ def test_every_rotated_projection_shares_one_class():
_install_rotation(third, 128)
assert (first.convrot_groupsize, third.convrot_groupsize) == (256, 128)
assert torch.is_tensor(first.weight)
+
+
+def test_rotated_forward_traces_fullgraph_on_a_cold_cache(monkeypatch):
+ """Denoiser blocks compile with fullgraph=True; a cold Hadamard build must not graph-break."""
+ import torch
+ from torch import nn
+
+ import core.inference.diffusion_convrot as dc
+
+ torch._dynamo.reset()
+ monkeypatch.setattr(dc, "_HADAMARD_CACHE", {})
+ linear = nn.Linear(256, 8, bias = False)
+ dc._install_rotation(linear, 64)
+ x = torch.randn(3, 256)
+ expected = linear(x)
+ dc._HADAMARD_CACHE.clear()
+ compiled = torch.compile(linear, fullgraph = True, backend = "eager")
+ assert torch.equal(compiled(x), expected)
+ torch._dynamo.reset()