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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: run MiniMax-H3's INT8 denoiser from the ConvRot checkpoint (#8293)
Daniel Han7ef075b9bd32
diff --git a/scripts/build_prequant_checkpoint.py b/scripts/build_prequant_checkpoint.pyindex a3d03aa1b7f..2e0f13f4028 100644--- a/scripts/build_prequant_checkpoint.py+++ b/scripts/build_prequant_checkpoint.py@@ -24,10 +24,62 @@ import argparseimport sysimport timefrom pathlib import Path+from typing import Any, Optional, SequenceBACKEND = Path(__file__).resolve().parent.parent / "studio" / "backend"+def convrot_refusal(+ group: int, rotatable: Sequence[str], not_divisible: Sequence[str]+) -> Optional[str]:+ """Why a ConvRot build must not be quantised and saved, or None when it is fine.++ An empty rotatable set means the group divides no quantized input axis (a group larger than+ every Linear, say). The build would still stamp the v2 tag and an empty fqn list, which+ ``rotation_metadata_error`` refuses at load time, so the only thing it produces is a+ multi-gigabyte artifact nothing can ever open. Refuse before the hours, not after."""+ if rotatable:+ return None+ return (+ f"ConvRot group {group} divides the in_features of none of the {len(not_divisible)} "+ "quantized linears, so the checkpoint would record an empty rotation and be refused at "+ "load time. Pick a smaller power-of-4 group, or drop --convrot-groupsize."+ )+++def upload_destination(+ fam: Any,+ scheme: str,+ *,+ rotated: bool,+ override: Optional[str] = None,+) -> str:+ """The repo-root filename this build should publish under.++ The loader asks for the family's declared ``prequant_filenames`` name first and the derived+ ``<Model>-<SCHEME>.pt`` second, so a ROTATED artifact published under the legacy+ ``transformer_<scheme>.pt`` is either never resolved at all, or resolved as the fallback by a+ build too old to honour the rotation, which then refuses the v2 tag and drops to the dense+ download. A rotated build therefore goes to the declared name or nowhere. Plain builds keep+ the legacy name they have always used."""+ if override:+ return override+ from core.inference.diffusion_prequant import prequant_filename++ if not rotated:+ return prequant_filename(scheme)+ from core.inference.diffusion_families import family_prequant_filename++ preferred = family_prequant_filename(fam, scheme)+ if not preferred:+ raise ValueError(+ f"family {getattr(fam, 'name', fam)!r} declares no prequant_filenames entry for "+ f"{scheme!r}, so a rotated checkpoint has no name the loader would ask for. Add the "+ "entry to the family table, or pass --upload-filename."+ )+ return preferred++def main(argv = None) -> int:p = argparse.ArgumentParser()p.add_argument(@@ -39,10 +91,27 @@ def main(argv = None) -> int:p.add_argument("--min-features", type = int, default = 512)p.add_argument("--dtype", default = "bfloat16", choices = ["bfloat16"])p.add_argument("--hf-token", default = None)+ p.add_argument(+ "--convrot-groupsize",+ type = int,+ default = 0,+ help = "bake a ConvRot block-Hadamard activation rotation at this group size (a power of "+ "4; 0 = off). Every quantized Linear whose in_features the group divides has its "+ "weight rotated before quantize_ so the quantizer sees a flatter distribution; the "+ "exact fqn list is recorded in the checkpoint and the loader rotates the "+ "activations of that list and nothing else. Writes the v2 format tag.",+ )p.add_argument("--upload-repo", default = None, help = "optional HF repo id to upload the checkpoint to")p.add_argument("--upload-revision", default = None)+ p.add_argument(+ "--upload-filename",+ default = None,+ help = "repo-root filename to publish under; defaults to the family's declared "+ "prequant_filenames entry for a rotated build and the legacy transformer_<scheme>.pt "+ "otherwise",+ )args = p.parse_args(argv)sys.path.insert(0, str(BACKEND))@@ -51,7 +120,7 @@ def main(argv = None) -> int:import diffusersfrom core.inference.diffusion_families import detect_family- from core.inference.diffusion_prequant import PREQUANT_FORMAT, prequant_filename+ from core.inference.diffusion_prequant import prequant_format_for# Reuse the runtime quant factory + filter so offline == runtime (the LPIPS-0 invariant).from core.inference.diffusion_transformer_quant import (@@ -75,6 +144,20 @@ def main(argv = None) -> int:print(f"error: unknown family '{args.family}'", flush = True)return 2transformer_cls = getattr(diffusers, fam.transformer_class)+ # Resolved BEFORE the load, so a rotated build with nowhere resolvable to publish fails in a+ # second rather than after the quantise and the multi-gigabyte save.+ upload_dest = None+ if args.upload_repo:+ try:+ upload_dest = upload_destination(+ fam,+ scheme,+ rotated = bool(args.convrot_groupsize),+ override = args.upload_filename,+ )+ except ValueError as exc:+ print(f"error: {exc}", flush = True)+ return 2print(f"== build prequant ({fam.name}/{scheme}, min_feat={args.min_features}) ==", flush = True)print(f" loading dense transformer from {args.base} (subfolder=transformer) ...", flush = True)@@ -89,16 +172,39 @@ def main(argv = None) -> int:require_bf16 = scheme in _REQUIRE_BF16_SCHEMES# fp8 bakes the accumulate mode in; record it so the loader can reject a contradicting request.fast_accum = _resolve_fast_accum(None) if scheme == TQ_FP8 else None- quantize_(- transformer,- _make_quant_config(scheme),- filter_fn = make_filter_fn(- args.min_features,- exclude_name_tokens = exclude_name_tokens,- require_bf16 = require_bf16,- ),+ filter_fn = make_filter_fn(+ args.min_features,+ exclude_name_tokens = exclude_name_tokens,+ require_bf16 = require_bf16,)+ # ConvRot, BEFORE quantize_: rotating the weights is only worth anything if the quantizer then+ # sees the rotated distribution. The fqn list is recorded, never re-derived at load time.+ rotation: dict = {}+ if args.convrot_groupsize:+ from core.inference.diffusion_convrot import (+ rotatable_fqns,+ rotate_linears_,+ rotation_metadata,+ )++ group = int(args.convrot_groupsize)+ rotatable, not_divisible = rotatable_fqns(transformer, filter_fn, group)+ refusal = convrot_refusal(group, rotatable, not_divisible)+ if refusal:+ print(f"error: {refusal}", flush = True)+ return 2+ rotate_linears_(transformer, rotatable, group)+ rotation = rotation_metadata(group, rotatable)+ print(+ f" rotated {len(rotatable)} linears at ConvRot group {group}; "+ f"{len(not_divisible)} quantized linears left plain (in_features not divisible)"+ + (f", e.g. {not_divisible[0]}" if not_divisible else ""),+ flush = True,+ )++ quantize_(transformer, _make_quant_config(scheme), filter_fn = filter_fn)+# CPU state dict for a portable, GPU-free artifact.state_dict = {k: (v.detach().to("cpu") if hasattr(v, "detach") else v)@@ -123,8 +229,11 @@ def main(argv = None) -> int:# fp8 granularity: lets the loader reject a stale per-tensor checkpoint (runtime needs per-row).if scheme == TQ_FP8:metadata["fp8_granularity"] = FP8_GRANULARITY+ metadata.update(rotation)ckpt = {- "format": PREQUANT_FORMAT,+ # v2 when a rotation is baked in, so a Studio predating the online half refuses the file+ # rather than running the rotated weights against unrotated activations.+ "format": prequant_format_for(metadata),"metadata": metadata,"state_dict": state_dict,}@@ -139,7 +248,7 @@ def main(argv = None) -> int:if args.upload_repo:from huggingface_hub import HfApi- dest = prequant_filename(scheme)+ dest = upload_destprint(f" uploading -> {args.upload_repo}:{dest} ...", flush = True)api = HfApi(token = args.hf_token)api.create_repo(args.upload_repo, exist_ok = True)diff --git a/studio/backend/core/inference/diffusion_convrot.py b/studio/backend/core/inference/diffusion_convrot.pynew file mode 100644index 00000000000..e09466ddce1--- /dev/null+++ b/studio/backend/core/inference/diffusion_convrot.py@@ -0,0 +1,378 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""ConvRot: block-Hadamard activation rotation for a pre-quantized DiT transformer.++A dynamic-activation INT8 Linear quantizes BOTH sides of its GEMM to 8 bits, so its error is set+by whichever side has the heaviest outliers. A DiT's activations are outlier-heavy by+construction: a handful of channels carry most of the magnitude, the per-row amax is pinned by+them, and every other channel spends its 8 bits on a fraction of the range it could have used.++Rotating the input axis by an orthogonal matrix spreads that magnitude across the group. With a+normalized regular Hadamard ``H`` of size ``g``, applied blockwise along the input axis:++ offline: W[o, k, :] <- W[o, k, :] @ H.T (baked into the checkpoint)+ online: x[..., k, :] <- x[..., k, :] @ H (this module, at every forward)++``H`` is symmetric and orthogonal, so ``(x @ H) @ (W @ H.T).T == x @ W.T``: in float the pair is+an exact identity and the model is unchanged. What changes is only that the INT8 quantizer sees a+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+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+rotation, the ``nn.Linear`` subclass that applies the online half, and the metadata contract that+keeps the two in step.++Why the fqn list is RECORDED rather than recomputed+---------------------------------------------------+The two halves of the identity live in different places: one in the checkpoint's weights, one in+this process. If they ever disagree about WHICH Linears are rotated, the mismatched ones compute+``x @ H @ W.T`` or ``x @ (W @ H.T).T`` -- finite, plausible-looking, and completely wrong. There+is no exception to catch and no NaN to notice; the render is just quietly worse. So the+checkpoint carries the exact list of rotated fqns and the loader rotates that list, rather than+whatever a re-evaluated filter rule selects today. A rule can drift with a code change (the set+is "quantized Linears whose in_features the group divides", and both halves of that have moved+before); a list cannot.++Everything here fails CLOSED for the same reason. ``apply_activation_rotation`` RAISES on an fqn+it cannot find, on a module that is not a Linear, on an ``in_features`` the group does not+divide, and on a rotation kind it does not implement. Its caller (the prequant loader) turns that+into a refused checkpoint and a dense fallback, which is slow but correct. Rotated artifacts also+carry their own format tag, so a Studio old enough to predate this module rejects them outright+instead of running them unrotated.++torch is imported inside the functions, matching the other lazily-loaded inference helpers, so+reading the metadata contract costs no import.+"""++from __future__ import annotations++from typing import Any, Iterable, Optional++# ── the metadata contract, carried in the prequant checkpoint's own ``metadata`` dict ──────────+# The rotation KIND. A value this module does not implement is refused, so a future scheme can be+# added without a released Studio silently treating it as this one.+CONVROT_KIND = "convrot_hadamard_v1"+# Key naming mirrors the adaLN curve contract next door (``adaln_form`` / ``curve_dim`` /+# ``curve_grid``): a form tag plus the parameters needed to reproduce the form.+ROTATION_KEY = "activation_rotation"+ROTATION_GROUP_KEY = "activation_rotation_group"+ROTATION_FQNS_KEY = "activation_rotation_fqns"++# The group size the denoiser artifact ships at, and the one the hosted conditioner already uses.+# 256 beat 64 in weight space on MiniMax-H3 (mean relative quantization error -19.9% vs -17.3%+# over 200 layers) and is the largest power of 4 that divides every quantized H3 input axis.+DEFAULT_CONVROT_GROUPSIZE = 256++# Marker set on a transformer whose rotation is installed, so a caller can tell a rotated module+# from an unrotated one without re-deriving anything. Diagnostic only.+CONVROT_ATTR = "_unsloth_activation_rotation"+++def is_power_of_four(size: Any) -> bool:+ """True for 4, 16, 64, 256, ... -- the sizes a kron power of ``H4`` can produce.++ A genuine ``int`` only. ``"256"`` is not accepted even though it would coerce: this also gates+ the group recorded in a checkpoint, and a value whose TYPE is already wrong says the artifact+ was not written by the builder in this tree, which is not something to guess about."""+ if not isinstance(size, int) or isinstance(size, bool):+ return False+ n = size+ if n < 4 or n & (n - 1):+ return False+ # A power of two is a power of four exactly when its single set bit sits at an even index.+ 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 Studio does not ship.++_HADAMARD_CACHE: dict = {}+++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."""+ import torch++ if dtype is None:+ dtype = torch.float32+ key = (size, str(device), dtype)+ cached = _HADAMARD_CACHE.get(key)+ if cached is not None:+ 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)+ _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]+ 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)+++def rotate_convrot_weight_(module: Any, group_size: int) -> None:+ """``W <- W @ blockdiag(H).T`` in place, accumulated in float32 and cast back.++ float32 regardless of the stored dtype: each output element becomes a ``group_size``-term dot+ product, and accumulating that in bfloat16 would spend a visible part of the error budget the+ rotation exists to save. The offline half only runs once, so the upcast is free."""+ import torch++ weight = module.weight.data+ out_features, in_features = weight.shape+ if in_features % group_size:+ raise ValueError(+ 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)+++def convrot_linear_class() -> Any:+ """The ``nn.Linear`` subclass that rotates its input, built lazily so importing this module+ never imports torch.++ A CLASS SWAP rather than a wrapper module, and that is load-bearing twice over: the module+ stays an ``nn.Linear``, so torchao's filter and ``quantize_`` treat it exactly as they treat+ an unrotated one, and the state dict keys are unchanged, so the hosted checkpoint still loads+ under ``strict = True`` with no rename. The rotation carries no parameters of its own, so+ there is nothing to serialize."""+ import torch+ import torch.nn.functional as F+ from torch import nn++ class ConvRotLinear(nn.Linear):+ """``nn.Linear`` whose input is block-Hadamard rotated before the matmul."""++ # Set per instance by ``_install_rotation``; the class default exists only so a+ # half-constructed instance cannot silently rotate at some other group.+ convrot_groupsize: int = DEFAULT_CONVROT_GROUPSIZE++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ group = self.convrot_groupsize+ h = build_convrot_hadamard(group, device = x.device, dtype = x.dtype)+ return F.linear(rotate_convrot_activation(x, h, group), self.weight, self.bias)++ def extra_repr(self) -> str: # pragma: no cover - debug aid+ return f"{super().extra_repr()}, convrot(group={self.convrot_groupsize})"++ return ConvRotLinear+++def is_rotated_linear(module: Any) -> bool:+ """True when ``module`` already applies the online rotation to its own input."""+ return type(module).__name__ == "ConvRotLinear" and hasattr(module, "convrot_groupsize")+++def _install_rotation(module: Any, group_size: int) -> None:+ """Swap ``module`` onto the rotating subclass, in place."""+ module.convrot_groupsize = int(group_size)+ module.__class__ = convrot_linear_class()+++# ── the metadata contract ─────────────────────────────────────────────────────────────────────+++def declares_rotation(metadata: Any) -> bool:+ """True when ``metadata`` claims its weights were rotated offline.++ Deliberately keyed on the KEY being populated, not on the value being one this module+ understands: an unknown kind has to read as "a rotation is declared" so the validator can+ refuse it, rather than as "no rotation" so the loader runs rotated weights unrotated."""+ return isinstance(metadata, dict) and metadata.get(ROTATION_KEY) not in (None, "")+++def rotation_metadata_error(metadata: Any) -> Optional[str]:+ """Why ``metadata``'s declared rotation is unusable, or None when it is well formed.++ Pure and torch-free, so the prequant validator can call it before anything is built. Checks+ the CONTRACT only (kind, group, fqn list shape); whether those fqns exist on this particular+ model is ``apply_activation_rotation``'s question, since answering it needs the model."""+ if not declares_rotation(metadata):+ return None+ kind = metadata.get(ROTATION_KEY)+ if kind != CONVROT_KIND:+ return f"unsupported activation rotation {kind!r} (this build implements {CONVROT_KIND!r})"+ group = metadata.get(ROTATION_GROUP_KEY)+ if not is_power_of_four(group):+ return (+ f"activation rotation group {group!r} is not a power of 4; the Hadamard is built as a "+ "kron power of H4"+ )+ fqns = metadata.get(ROTATION_FQNS_KEY)+ if not isinstance(fqns, (list, tuple)) or not fqns:+ # An empty list is refused rather than read as "rotate nothing": a builder that failed to+ # record its set would otherwise emit an artifact that loads clean and renders garbage.+ return f"activation rotation records no fqns ({ROTATION_FQNS_KEY} is {fqns!r})"+ if not all(isinstance(fqn, str) and fqn for fqn in fqns):+ return f"activation rotation {ROTATION_FQNS_KEY} has non-string entries"+ if len(set(fqns)) != len(fqns):+ return f"activation rotation {ROTATION_FQNS_KEY} has duplicates"+ return None+++def rotation_metadata(group_size: int, fqns: Iterable[str]) -> dict:+ """The metadata fragment an offline builder merges in after rotating ``fqns``.++ Sorted, so two builds of the same model produce identical metadata and a rebuilt artifact can+ be diffed against the shipped one."""+ return {+ ROTATION_KEY: CONVROT_KIND,+ ROTATION_GROUP_KEY: int(group_size),+ ROTATION_FQNS_KEY: sorted(fqns),+ }+++# ── the two halves ────────────────────────────────────────────────────────────────────────────+++def rotatable_fqns(+ transformer: Any,+ filter_fn: Any,+ group_size: int = DEFAULT_CONVROT_GROUPSIZE,+) -> tuple[tuple[str, ...], tuple[str, ...]]:+ """``(rotatable, not_divisible)`` among the Linears ``filter_fn`` selects for quantization.++ The second tuple is why the shipped set is recorded rather than derived: the Hadamard only+ tiles an input axis the group divides, so some quantized Linears are always left plain, and+ which ones is a property of the architecture rather than of a rule worth re-evaluating at+ load time."""+ from torch import nn++ rotatable: list[str] = []+ not_divisible: list[str] = []+ for fqn, module in transformer.named_modules():+ if not isinstance(module, nn.Linear) or not filter_fn(module, fqn):+ continue+ (rotatable if module.in_features % group_size == 0 else not_divisible).append(fqn)+ return tuple(rotatable), tuple(not_divisible)+++def rotate_linears_(+ transformer: Any,+ fqns: Iterable[str],+ group_size: int = DEFAULT_CONVROT_GROUPSIZE,+) -> tuple[str, ...]:+ """OFFLINE half: rotate the weights of ``fqns`` and install the online rotation on each.++ Call BEFORE ``quantize_``, on a dense model: the whole point is that the quantizer sees the+ flatter distribution. Returns the fqns rotated, in the order given. Raises on anything it+ cannot rotate, so a builder can never record a set larger than the one it actually applied."""+ from torch import nn++ if not is_power_of_four(group_size):+ raise ValueError(f"ConvRot group size must be a power of 4, got {group_size!r}")+ modules = dict(transformer.named_modules())+ rotated: list[str] = []+ for fqn in fqns:+ module = modules.get(fqn)+ if not isinstance(module, nn.Linear):+ raise ValueError(f"cannot rotate {fqn!r}: not an nn.Linear on this model")+ rotate_convrot_weight_(module, group_size)+ _install_rotation(module, group_size)+ rotated.append(fqn)+ return tuple(rotated)+++def apply_activation_rotation(+ transformer: Any,+ metadata: Any,+ *,+ logger: Any = None,+) -> tuple[str, ...]:+ """ONLINE half: install the input rotation on exactly the fqns ``metadata`` records.++ Returns the fqns rotated, or ``()`` when ``metadata`` declares no rotation -- the plain+ artifacts, which have to be left exactly as they are. RAISES on any other outcome: an+ unusable contract, an fqn this model does not have, a target that is not a Linear, an+ ``in_features`` the recorded group does not divide, or a Linear already rotated. The prequant+ loader turns a raise into a refused checkpoint and a dense fallback.++ Call AFTER ``load_state_dict`` and BEFORE ``apply_small_m_padding``: after, because the meta+ retry path rebuilds the module from the config and would discard an earlier swap; before,+ because padding reparents the Linears under a wrapper while the recorded fqns name the+ unwrapped tree."""+ if not declares_rotation(metadata):+ return ()+ problem = rotation_metadata_error(metadata)+ if problem:+ raise ValueError(problem)++ from torch import nn++ group_size = int(metadata[ROTATION_GROUP_KEY])+ fqns = list(metadata[ROTATION_FQNS_KEY])+ modules = dict(transformer.named_modules())+ missing = [fqn for fqn in fqns if fqn not in modules]+ if missing:+ raise ValueError(+ f"activation rotation names {len(missing)} fqn(s) this model does not have "+ f"(e.g. {missing[0]!r}); the checkpoint and this build disagree about the model"+ )+ for fqn in fqns:+ module = modules[fqn]+ if not isinstance(module, nn.Linear):+ raise ValueError(f"activation rotation target {fqn!r} is not an nn.Linear")+ if is_rotated_linear(module):+ raise ValueError(f"activation rotation target {fqn!r} is already rotated")+ if module.in_features % group_size:+ raise ValueError(+ f"activation rotation target {fqn!r} has in_features {module.in_features}, "+ f"which the recorded group {group_size} does not divide"+ )+ # Every target is validated before ANY is swapped. A partial install is the one outcome worse+ # than either end state: the rotated half still renders, just wrongly, so there is nothing to+ # notice and nothing to fall back from.+ for fqn in fqns:+ _install_rotation(modules[fqn], group_size)+ try:+ setattr(+ transformer,+ CONVROT_ATTR,+ {"kind": CONVROT_KIND, "group": group_size, "linears": len(fqns)},+ )+ except Exception: # noqa: BLE001 -- the marker is a diagnostic, never the mechanism+ pass+ if logger is not None:+ logger.info(+ "diffusion.convrot: installed %s on %d linears at group %d",+ CONVROT_KIND,+ len(fqns),+ group_size,+ )+ return tuple(fqns)diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 52797a7d604..efcf694977d 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -65,6 +65,13 @@ class DiffusionFamily:# Hosted checkpoints for NON-DEFAULT bases as (base_repo, scheme, repo_id), base_repo lowercased: one family entry covers# variants whose weights differ. Resolution prefers an exact variant match, then falls back to ``prequant_repos``.prequant_variant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)+ # Preferred checkpoint FILENAME for a scheme, as (scheme, filename), overriding the+ # ``<Model>-<SCHEME>.pt`` name ``prequant_repo_filename`` derives. The derived name stays on as+ # the fallback, so a repo hosting BOTH an old and a new artifact serves the new one to a build+ # that asks for it by name and the old one to every build that does not. That is what lets a+ # rotated (v2) checkpoint ship without regressing an already-installed Studio, which would+ # otherwise refuse the v2 tag and fall all the way back to the dense download.+ prequant_filenames: tuple[tuple[str, str], ...] = field(default_factory = tuple)# Hosted PRE-CAST text-encoder checkpoints as (scheme, component, repo_id). Layerwise-fp8 only: the cast is deterministic, so the artifact is bit-identical while skipping the dense TE download.te_prequant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)# Native (sd.cpp) single-file assets, used only on the no-GPU sd.cpp engine. The transformer GGUF is shared with@@ -787,6 +794,18 @@ def family_prequant_repo(return None+def family_prequant_filename(fam: DiffusionFamily, scheme: str) -> Optional[str]:+ """The preferred checkpoint filename this family declares for ``scheme``, or None.++ ``None`` means "use the derived ``<Model>-<SCHEME>.pt`` name", which is every family but the+ ones shipping a second artifact under the same repo and scheme. Not variant-keyed: the+ filename says WHICH artifact, the repo says which base."""+ for entry_scheme, filename in getattr(fam, "prequant_filenames", ()) or ():+ if entry_scheme == scheme:+ return filename+ return None++# The release where diffusers' own requires-python went ">= 3.10.0", which makes 0.36.0 the newest# a supported Python 3.9 host can resolve._DIFFUSERS_DROPPED_PY39 = "0.37.0"diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex fd35d732176..891cc0f4cbc 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -27,6 +27,24 @@ from typing import Any, Optional# torch.save dict layout tag; bump on an on-disk change so old/foreign artifacts are rejected.PREQUANT_FORMAT = "unsloth_prequant_transformer_state_dict_v1"+# v2 is v1 plus an ACTIVATION ROTATION (see ``diffusion_convrot``): the weights are stored in a+# rotated basis and are wrong unless the loader rotates the activations to match. That is the one+# on-disk change a released Studio cannot ignore safely -- an old build reading a rotated artifact+# as v1 would load it clean, raise nothing and render quietly wrong pixels forever -- so it gets a+# tag old builds refuse outright, and the load drops to dense instead. Strictly a biconditional:+# a v2 artifact MUST declare a rotation and a v1 artifact must NOT, both checked below, so neither+# a hand-edited tag nor a builder that forgot one half can produce something that loads.+PREQUANT_FORMAT_ROTATED = "unsloth_prequant_transformer_state_dict_v2"++PREQUANT_FORMATS = (PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED)+++def prequant_format_for(metadata: Any) -> str:+ """The on-disk format tag an offline builder should stamp for ``metadata``."""+ from .diffusion_convrot import declares_rotation+ return PREQUANT_FORMAT_ROTATED if declares_rotation(metadata) else PREQUANT_FORMAT++# Loading ends in ``torch.load(weights_only=False)``, which executes pickle code. A hosted repo checkpoint is first-party;# a ``kind == "path"`` can come from a request, so it is unpickled ONLY inside an operator-configured directory ALLOWLIST.ALLOW_LOCAL_PREQUANT_PATH_ENV = "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH"@@ -133,17 +151,25 @@ def resolve_prequant_source(override = (path_override or "").strip()if override:return PrequantSource(kind = "path", location = override, filename = None)+ preferred = Nonetry:- from .diffusion_families import family_prequant_repo+ from .diffusion_families import family_prequant_filename, family_prequant_reporepo_id = family_prequant_repo(fam, scheme, base_repo = base_repo)+ preferred = family_prequant_filename(fam, scheme)except Exception: # noqa: BLE001 — a bad family object must not break the loadrepo_id = Noneif repo_id:+ derived = prequant_repo_filename(repo_id, scheme)+ # A family may name a SECOND artifact for the same repo and scheme (today: MiniMax-H3's+ # rotated INT8 denoiser). It becomes the primary and the derived name becomes the+ # fallback, so a build that knows the new name gets it and every older build keeps+ # resolving the artifact it already understands. Without an override nothing changes: the+ # derived name is primary and the legacy transformer_<scheme>.pt is the fallback.return PrequantSource(kind = "repo",location = repo_id,- filename = prequant_repo_filename(repo_id, scheme),- fallback_filename = prequant_filename(scheme),+ filename = preferred or derived,+ fallback_filename = derived if preferred else prequant_filename(scheme),)return None@@ -183,7 +209,7 @@ def local_prequant_scheme(path: str) -> Optional[str]:try:import torchobj = torch.load(real, map_location = "meta", weights_only = False, mmap = True)- if isinstance(obj, dict) and obj.get("format") == PREQUANT_FORMAT:+ if isinstance(obj, dict) and obj.get("format") in PREQUANT_FORMATS:recorded = (obj.get("metadata") or {}).get("scheme")scheme = str(recorded) if recorded else Noneexcept Exception: # noqa: BLE001 -- a checkpoint we cannot parse is "unknown", never a match@@ -329,9 +355,16 @@ def load_prequantized_transformer(can key on what was baked rather than on today's defaults. A raising callback falls out to theouter handler below, i.e. a warning and a dense fallback, never a failed load.+ A checkpoint that declares an ACTIVATION ROTATION (``diffusion_convrot``) has the matching+ online half installed here, on exactly the fqns it records. That is unconditional and central+ rather than a family opt-in, because the one failure mode worth designing against is the+ silent one: rotated weights met by unrotated activations render wrong pixels and raise+ nothing.+Returns the placed transformer, or None on any problem (missing / mismatched /- unreadable checkpoint, or unsupported meta-init) so the caller falls back to- dense-quantise. Best-effort: never raises for an unavailable artifact.+ unreadable checkpoint, unsupported meta-init, or a rotation this build cannot apply exactly)+ so the caller falls back to dense-quantise. Best-effort: never raises for an unavailable+ artifact."""try:# weights_only=False executes pickle code, so a local path is unpickled ONLY when allowlisted; the hosted family repo is first-party.@@ -386,6 +419,18 @@ def load_prequantized_transformer(prepare_model(transformer, metadata)transformer.load_state_dict(state_dict, strict = True, assign = True)+ # The ONLINE half of an activation rotation, applied here rather than in a family's+ # ``prepare_model`` hook so that no route can load a rotated checkpoint without it: the+ # offline half is already baked into the weights that were just assigned, and a rotated+ # weight met by an unrotated activation renders plausible garbage with nothing to catch.+ # A no-op for every artifact that declares no rotation, and a RAISE (caught below into the+ # dense fallback) for one this build cannot honour exactly. After load_state_dict because+ # the meta retry above rebuilds the module; before apply_small_m_padding because padding+ # reparents the Linears and the recorded fqns name the unwrapped tree.+ from .diffusion_convrot import apply_activation_rotation++ apply_activation_rotation(transformer, metadata, logger = logger)+transformer = transformer.to(device)# Same small-M row padding the runtime quantise path applies, and for the same reason: a# checkpoint built under the current exclusion set QUANTISES the family's small-M linears,@@ -598,6 +643,46 @@ def _fp8_activation_floor_present(state_dict: Any, logger: Any) -> bool:return True+def _validate_activation_rotation(ckpt_format: Any, meta: Any, scheme: str, logger: Any) -> bool:+ """Reject a checkpoint whose activation rotation this build cannot honour EXACTLY.++ Three ways an artifact and a loader can disagree about the rotation, and all three end in the+ same place -- weights in a rotated basis multiplied by unrotated activations, which is finite,+ raises nothing, and renders quietly wrong -- so all three are refused here rather than+ discovered later:++ * the artifact declares a rotation and is tagged v1. Only v2 makes a Studio too old for this+ code refuse it, so a v1 tag on rotated weights is a hazard to every OTHER build, and the+ builder that produced it is not one to trust about anything else in the file;+ * the artifact is tagged v2 and declares none. Nothing here would rotate, and the tag says+ something was meant to;+ * the rotation is declared but its contract does not parse (an unknown kind, a group that is+ not a power of 4, an absent or malformed fqn list).++ Refusing costs a dense fallback: slower and bigger, never wrong."""+ from .diffusion_convrot import declares_rotation, rotation_metadata_error++ rotated = declares_rotation(meta)+ tagged = ckpt_format == PREQUANT_FORMAT_ROTATED+ if rotated != tagged:+ _warn(+ logger,+ scheme,+ ValueError(+ f"checkpoint format {ckpt_format!r} and its activation rotation disagree "+ f"(declares a rotation: {rotated}); a rotated checkpoint must be tagged "+ f"{PREQUANT_FORMAT_ROTATED!r} so older builds refuse it instead of running it "+ "unrotated"+ ),+ )+ return False+ problem = rotation_metadata_error(meta)+ if problem:+ _warn(logger, scheme, ValueError(problem))+ return False+ return True++def _validate_checkpoint(ckpt: Any,scheme: str,@@ -615,13 +700,15 @@ def _validate_checkpoint(``fast_accum`` (fp8 only): when the caller forces it and the checkpoint baked a differentvalue, the loaded kernels would ignore the request, so reject and let the dense pathhonor it. A checkpoint predating a metadata field (absent) is accepted for back-compat."""- if not isinstance(ckpt, dict) or ckpt.get("format") != PREQUANT_FORMAT:+ if not isinstance(ckpt, dict) or ckpt.get("format") not in PREQUANT_FORMATS:_warn(logger, scheme, ValueError("unrecognised pre-quant checkpoint format"))return Falseif "state_dict" not in ckpt:_warn(logger, scheme, ValueError("pre-quant checkpoint has no state_dict"))return Falsemeta = ckpt.get("metadata") or {}+ if not _validate_activation_rotation(ckpt.get("format"), meta, scheme, logger):+ return Falseif meta.get("scheme") != scheme:_warn(logger, scheme, ValueError(f"checkpoint scheme {meta.get('scheme')!r} != {scheme!r}"))return Falsediff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex 85eb8459482..7bd730be772 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -98,6 +98,13 @@ class VideoFamily:# without one falls through to prequant_repos and, if that checkpoint was baked elsewhere, the# loader's base_model_id check sends the load back to the dense path.prequant_variant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)+ # Preferred checkpoint FILENAME for a scheme, as (scheme, filename), overriding the+ # ``<Model>-<SCHEME>.pt`` name ``prequant_repo_filename`` derives. The derived name stays on as+ # the fallback, so a repo hosting BOTH an old and a new artifact serves the new one to a build+ # that asks for it by name and the old one to every build that does not. That is what lets a+ # rotated (v2) checkpoint ship without regressing an already-installed Studio, which would+ # otherwise refuse the v2 tag and fall all the way back to the dense download.+ prequant_filenames: tuple[tuple[str, str], ...] = field(default_factory = tuple)# Modular Diffusers workflow to load instead of a conventional DiffusionPipeline. Its# components are loaded without pruning the workflow's routing blocks.modular_workflow: Optional[str] = None@@ -155,6 +162,13 @@ _FAMILIES: tuple[VideoFamily, ...] = (# the layout every image-side prequant repo already uses and the one prequant_repo_filename# builds without help.prequant_repos = (("int8", "unsloth/MiniMax-H3-FP8"), ("fp8", "unsloth/MiniMax-H3-FP8")),+ # The INT8 denoiser is ConvRot-rotated (see diffusion_convrot): its weights live in a+ # Hadamard-rotated basis and are wrong unless the loader rotates the activations to match,+ # so it carries the v2 format tag a Studio predating that code refuses. Shipping it under+ # its own name rather than over MiniMax-H3-INT8.pt keeps both true at once: this build+ # gets the rotated artifact, and an older install still resolves the plain one instead of+ # refusing the v2 tag and falling back to the 66.3 GB dense download.+ prequant_filenames = (("int8", "MiniMax-H3-INT8-ConvRot.pt"),),# Both schemes are ~20.3 GB resident against the 66.3 GB dense denoiser; see the field.prequant_resident_gb = 20.3,modular_workflow = "fl2va",diff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.pyindex 325b385c813..39b31a18544 100644--- a/studio/backend/core/inference/video_minimax_h3_te.py+++ b/studio/backend/core/inference/video_minimax_h3_te.py@@ -49,6 +49,13 @@ from __future__ import annotationsfrom typing import Any, Optional+# The ConvRot primitives, shared with the denoiser's hosted INT8 checkpoint. Re-exported below+# under the names this module has always used.+from .diffusion_convrot import ( # noqa: F401 (re-export: callers and tests name them here)+ build_convrot_hadamard,+ rotate_convrot_activation,+)+# The repo the Diffusers H3 path already pulls its VAEs from, so this adds no new dependency.from .video_minimax_h3 import H3_COMPONENT_REPO@@ -129,52 +136,13 @@ def h3_te_resident_gb(scheme: Optional[str], *, bf16_gb: float) -> float:# rotation, 137% without).## This mirrors comfy-kitchen's ``_build_hadamard`` / ``_rotate_activation`` / ``_rotate_weight``-# exactly, in ~30 lines of torch, rather than taking a dependency on a wheel Studio does not ship.--_HADAMARD_CACHE: dict[tuple[int, str, Any], Any] = {}---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)."""- import math-- import torch-- if dtype is None:- dtype = torch.float32- key = (size, str(device), dtype)- cached = _HADAMARD_CACHE.get(key)- if cached is not None:- return cached- if size < 4 or (size & (size - 1)) != 0 or math.log(size, 4) % 1 != 0:- 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)- _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]- 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)+# exactly, in a few lines of torch, rather than taking a dependency on a wheel Studio does not ship.+#+# ``build_convrot_hadamard`` and ``rotate_convrot_activation`` are imported at the top of this+# module from ``diffusion_convrot``, where they now live. The DENOISER runs the same ConvRot on its+# own hosted INT8 checkpoint, and the two rotations have to agree with the same comfy-kitchen+# definition down to the normalizer -- two copies of a matrix nobody re-derives at review time is+# exactly how they would stop agreeing. Both stay importable from here.def _int8_convrot_linear_class() -> Any:diff --git a/studio/backend/tests/test_build_prequant_checkpoint.py b/studio/backend/tests/test_build_prequant_checkpoint.pynew file mode 100644index 00000000000..c422db32fa7--- /dev/null+++ b/studio/backend/tests/test_build_prequant_checkpoint.py@@ -0,0 +1,72 @@+# 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 two decisions ``scripts/build_prequant_checkpoint.py`` makes that a bad answer to is+silent: whether a ConvRot build is buildable at all, and what filename it publishes under.++Both end in an artifact that costs GPU-hours and tens of gigabytes and then cannot be resolved+or cannot be loaded, with nothing at build time saying so, which is why they are pulled out as+pure functions and asserted here rather than left inline in ``main``."""++import importlib.util+import sys+from pathlib import Path++import pytest++from core.inference.diffusion_convrot import rotation_metadata, rotation_metadata_error+from core.inference.diffusion_families import detect_family+from core.inference.video_families import detect_video_family++_SCRIPT = Path(__file__).resolve().parents[3] / "scripts" / "build_prequant_checkpoint.py"+++def _script():+ """The build script as a module. Imported by path: ``scripts/`` is not a package."""+ spec = importlib.util.spec_from_file_location("build_prequant_checkpoint", _SCRIPT)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def test_a_convrot_group_that_rotates_nothing_is_refused_before_anything_is_built():+ build = _script()+ # The group divides no quantized input axis, so the rotation would be empty.+ refusal = build.convrot_refusal(4096, (), ("blocks.0.ff.net.0", "blocks.0.attn.to_q"))+ assert refusal is not None+ assert "4096" in refusal and "2" in refusal+ # And the reason it has to be refused: the artifact it would have written is unloadable.+ assert rotation_metadata_error(rotation_metadata(4096, ())) is not None+ # A non-empty set is built normally.+ assert build.convrot_refusal(256, ("blocks.0.attn.to_q",), ()) is None+++def test_a_rotated_upload_goes_to_the_name_the_loader_asks_for_not_the_legacy_fallback():+ build = _script()+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")+ assert h3 is not None+ # The rotated INT8 denoiser is published under the family's declared name, which is the one+ # resolve_prequant_source asks for first. transformer_int8.pt is never asked for on this+ # family, so an upload landing there would be invisible.+ assert build.upload_destination(h3, "int8", rotated = True) == "MiniMax-H3-INT8-ConvRot.pt"+ # A plain build keeps the legacy name it has always used, so nothing else moves.+ assert build.upload_destination(h3, "int8", rotated = False) == "transformer_int8.pt"+++def test_a_rotated_upload_with_no_declared_name_is_refused_rather_than_published_over_the_fallback():+ build = _script()+ zimage = detect_family("Tongyi-MAI/Z-Image-Turbo", override = "z-image")+ assert zimage is not None+ # Publishing a v2 artifact under transformer_<scheme>.pt hands it to every OLDER build as the+ # fallback, which refuses the tag and drops to the dense download. Refuse instead.+ with pytest.raises(ValueError, match = "prequant_filenames"):+ build.upload_destination(zimage, "int8", rotated = True)+ # An explicit name is the operator's escape hatch, rotated or not.+ assert (+ build.upload_destination(+ zimage, "int8", rotated = True, override = "Z-Image-Turbo-INT8-ConvRot.pt"+ )+ == "Z-Image-Turbo-INT8-ConvRot.pt"+ )+ assert build.upload_destination(zimage, "fp8", rotated = False) == "transformer_fp8.pt"diff --git a/studio/backend/tests/test_diffusion_convrot.py b/studio/backend/tests/test_diffusion_convrot.pynew file mode 100644index 00000000000..71c7935e944--- /dev/null+++ b/studio/backend/tests/test_diffusion_convrot.py@@ -0,0 +1,400 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the ConvRot activation rotation (``diffusion_convrot.py``).++Real torch, CPU only, small dense Linears: the rotation is an orthogonal change of basis, so a+float32 Linear proves every property that matters here -- that the offline and online halves+cancel exactly, that the loader rotates the RECORDED set and nothing else, and that every way the+two halves could disagree is refused rather than run.++That last group is the point of the file. A rotated weight met by an unrotated activation is+finite, raises nothing, and renders quietly wrong, so there is no failure to observe downstream:+the only place it can be caught is here, at the contract.+"""++from __future__ import annotations++import contextlib+import sys+import types++import pytest++torch = pytest.importorskip("torch")+nn = torch.nn++import core.inference.diffusion_prequant as pq # noqa: E402+from core.inference.diffusion_convrot import ( # noqa: E402+ CONVROT_ATTR,+ CONVROT_KIND,+ DEFAULT_CONVROT_GROUPSIZE,+ ROTATION_FQNS_KEY,+ ROTATION_GROUP_KEY,+ ROTATION_KEY,+ apply_activation_rotation,+ build_convrot_hadamard,+ declares_rotation,+ is_power_of_four,+ is_rotated_linear,+ rotatable_fqns,+ rotate_convrot_weight_,+ rotate_linears_,+ rotation_metadata,+ rotation_metadata_error,+)++GROUP = 16 # a power of 4, small enough to keep the test model tiny+++class _Model(nn.Module):+ """Three Linears: two the group divides, one it does not."""++ def __init__(self, group: int = GROUP) -> None:+ super().__init__()+ self.a = nn.Linear(4 * group, 8)+ self.b = nn.Linear(2 * group, 8)+ self.odd = nn.Linear(group + 1, 8)+++def _meta(+ fqns,+ group = GROUP,+ kind = CONVROT_KIND,+):+ return {+ ROTATION_KEY: kind,+ ROTATION_GROUP_KEY: group,+ ROTATION_FQNS_KEY: list(fqns),+ }+++# ── the Hadamard itself ───────────────────────────────────────────────────────────+++def test_power_of_four_gate():+ assert [n for n in (1, 2, 4, 8, 16, 32, 64, 256, 1024) if is_power_of_four(n)] == [+ 4,+ 16,+ 64,+ 256,+ 1024,+ ]+ assert not is_power_of_four(0)+ assert not is_power_of_four(-4)+ assert not is_power_of_four("256")+ assert not is_power_of_four(None)+++def test_hadamard_is_symmetric_and_orthogonal():+ # Both properties are what make the offline/online pair an identity: symmetric so H.T is H,+ # orthogonal so the two applications cancel.+ for size in (4, 16, 64, 256):+ h = build_convrot_hadamard(size, device = "cpu", dtype = torch.float32)+ assert h.shape == (size, size)+ assert torch.equal(h, h.T)+ assert torch.allclose(h @ h, torch.eye(size), atol = 1e-5)+++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.+ from core.inference import video_minimax_h3_te as te++ from core.inference import diffusion_convrot as cr++ assert te.build_convrot_hadamard is cr.build_convrot_hadamard+ assert te.rotate_convrot_activation is cr.rotate_convrot_activation+++# ── the identity ──────────────────────────────────────────────────────────────────+++def test_rotate_then_unrotate_is_the_identity():+ # The core invariant: rotating the weight offline and the activation online leaves the float+ # result unchanged. Everything the rotation buys happens inside the quantizer, not here.+ torch.manual_seed(0)+ linear = nn.Linear(1024, 512, dtype = torch.float32)+ x = torch.randn(37, 1024)+ reference = linear(x)++ rotate_convrot_weight_(linear, DEFAULT_CONVROT_GROUPSIZE)+ assert not torch.allclose(linear(x), reference) # weight side alone is NOT a no-op+ linear.convrot_groupsize = DEFAULT_CONVROT_GROUPSIZE+ from core.inference.diffusion_convrot import convrot_linear_class++ linear.__class__ = convrot_linear_class()++ got = linear(x)+ assert ((got - reference).norm() / reference.norm()).item() < 1e-5+++def test_rotation_survives_extra_leading_dims():+ torch.manual_seed(1)+ model = _Model()+ x = torch.randn(2, 5, 4 * GROUP)+ reference = model.a(x)+ rotate_linears_(model, ["a"], GROUP)+ assert torch.allclose(model.a(x), reference, atol = 1e-5)+++def test_rotate_weight_refuses_an_indivisible_input_axis():+ with pytest.raises(ValueError):+ rotate_convrot_weight_(nn.Linear(GROUP + 1, 8), GROUP)+++def test_rotatable_fqns_splits_on_divisibility():+ model = _Model()+ rotatable, not_divisible = rotatable_fqns(model, lambda m, fqn: True, GROUP)+ assert rotatable == ("a", "b")+ assert not_divisible == ("odd",)+ # A filter that rejects a Linear keeps it out of BOTH lists: it is never quantized, so there+ # is nothing for the rotation to help.+ rotatable, not_divisible = rotatable_fqns(model, lambda m, fqn: fqn != "b", GROUP)+ assert rotatable == ("a",) and not_divisible == ("odd",)+++def test_offline_rotation_records_only_what_it_applied():+ model = _Model()+ rotated = rotate_linears_(model, ["a", "b"], GROUP)+ meta = rotation_metadata(GROUP, rotated)+ assert meta[ROTATION_KEY] == CONVROT_KIND+ assert meta[ROTATION_GROUP_KEY] == GROUP+ assert meta[ROTATION_FQNS_KEY] == ["a", "b"] # sorted, so two builds agree byte for byte+ assert rotation_metadata_error(meta) is None+++def test_offline_rotation_raises_rather_than_over_recording():+ model = _Model()+ with pytest.raises(ValueError):+ rotate_linears_(model, ["a", "nope"], GROUP)+ with pytest.raises(ValueError):+ rotate_linears_(model, ["a"], 32)+++# ── the loader rotates exactly the recorded set ───────────────────────────────────+++def test_apply_rotates_exactly_the_recorded_fqns():+ model = _Model()+ assert apply_activation_rotation(model, _meta(["a"])) == ("a",)+ assert is_rotated_linear(model.a)+ # ... and nothing else, including the other Linear the group WOULD divide. The recorded list+ # is the contract; "everything divisible" is a rule, and a rule can drift away from the+ # weights that were actually baked.+ assert not is_rotated_linear(model.b)+ assert not is_rotated_linear(model.odd)+ assert getattr(model, CONVROT_ATTR)["linears"] == 1+ assert getattr(model, CONVROT_ATTR)["group"] == GROUP+++def test_apply_is_inert_without_a_declared_rotation():+ model = _Model()+ for metadata in ({}, None, {"scheme": "int8"}, {ROTATION_KEY: None}, {ROTATION_KEY: ""}):+ assert apply_activation_rotation(model, metadata) == ()+ assert not any(is_rotated_linear(m) for m in (model.a, model.b, model.odd))+++def test_rotated_linear_keeps_the_state_dict_unchanged():+ # The swap must not add, rename or drop a key: the hosted checkpoint loads under strict=True.+ before = sorted(_Model().state_dict())+ model = _Model()+ apply_activation_rotation(model, _meta(["a", "b"]))+ assert sorted(model.state_dict()) == before+ assert isinstance(model.a, nn.Linear) # still an nn.Linear, so torchao treats it as one+++ "metadata",+ [+ _meta(["a"], kind = "convrot_hadamard_v2"), # a kind this build does not implement+ _meta(["a"], kind = True),+ _meta(["a"], group = 32), # not a power of 4+ _meta(["a"], group = "256"),+ _meta([]), # declared but records nothing+ {ROTATION_KEY: CONVROT_KIND, ROTATION_GROUP_KEY: GROUP}, # no fqn key at all+ _meta(["a", "a"]), # duplicates+ _meta(["a", 7]), # not strings+ ],+)+def test_apply_refuses_an_unusable_contract(metadata):+ assert declares_rotation(metadata)+ assert rotation_metadata_error(metadata)+ model = _Model()+ with pytest.raises(ValueError):+ apply_activation_rotation(model, metadata)+ assert not any(is_rotated_linear(m) for m in (model.a, model.b, model.odd))+++def test_apply_refuses_an_fqn_this_model_does_not_have():+ model = _Model()+ with pytest.raises(ValueError, match = "does not have"):+ apply_activation_rotation(model, _meta(["a", "missing.linear"]))+++def test_apply_refuses_a_target_that_is_not_a_linear():+ model = _Model()+ model.not_a_linear = nn.LayerNorm(GROUP)+ with pytest.raises(ValueError, match = "not an nn.Linear"):+ apply_activation_rotation(model, _meta(["not_a_linear"]))+++def test_apply_refuses_an_indivisible_target():+ model = _Model()+ with pytest.raises(ValueError, match = "does not divide"):+ apply_activation_rotation(model, _meta(["odd"]))+++def test_apply_refuses_to_rotate_twice():+ model = _Model()+ apply_activation_rotation(model, _meta(["a"]))+ with pytest.raises(ValueError, match = "already rotated"):+ apply_activation_rotation(model, _meta(["a"]))+++def test_a_refused_apply_rotates_nothing_at_all():+ # A PARTIAL install is worse than either end state: the rotated half still renders, just+ # wrongly, so nothing downstream fails. Validate every target before swapping any.+ model = _Model()+ with pytest.raises(ValueError):+ apply_activation_rotation(model, _meta(["a", "b", "odd"]))+ assert not any(is_rotated_linear(m) for m in (model.a, model.b, model.odd))+++# ── the prequant checkpoint contract ──────────────────────────────────────────────+++def test_format_tag_follows_the_rotation():+ assert pq.prequant_format_for({"scheme": "int8"}) == pq.PREQUANT_FORMAT+ assert pq.prequant_format_for(_meta(["a"])) == pq.PREQUANT_FORMAT_ROTATED+ assert pq.PREQUANT_FORMAT_ROTATED != pq.PREQUANT_FORMAT+ assert set(pq.PREQUANT_FORMATS) == {pq.PREQUANT_FORMAT, pq.PREQUANT_FORMAT_ROTATED}+++ ("fmt", "metadata", "ok"),+ [+ (pq.PREQUANT_FORMAT, {}, True),+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["a"]), True),+ # A rotated artifact tagged v1 loads clean on a Studio predating the online half and+ # renders wrong pixels. Refuse it here too: whoever wrote the tag is not to be trusted+ # about the rest of the file either.+ (pq.PREQUANT_FORMAT, _meta(["a"]), False),+ # A v2 tag with nothing to rotate: something was meant to happen and did not.+ (pq.PREQUANT_FORMAT_ROTATED, {}, False),+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["a"], kind = "something_else"), False),+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["a"], group = 32), False),+ (pq.PREQUANT_FORMAT_ROTATED, _meta([]), False),+ ],+)+def test_validator_enforces_the_format_rotation_biconditional(fmt, metadata, ok):+ assert pq._validate_activation_rotation(fmt, metadata, "int8", None) is ok+++def test_h3_int8_resolves_to_the_rotated_artifact_with_the_plain_one_behind_it():+ # The wiring the shipped denoiser depends on: this build asks for the ConvRot artifact by+ # name, and the derived name stays as the fallback so an install predating the online half+ # still resolves the plain checkpoint instead of refusing the v2 tag and downloading 66.3 GB+ # of dense weights.+ from core.inference.video_families import detect_video_family++ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ src = pq.resolve_prequant_source(fam, "int8")+ assert src.location == "unsloth/MiniMax-H3-FP8"+ assert src.filename == "MiniMax-H3-INT8-ConvRot.pt"+ assert src.fallback_filename == "MiniMax-H3-INT8.pt"+ # fp8 is untouched: one artifact, the derived name.+ assert pq.resolve_prequant_source(fam, "fp8").filename == "MiniMax-H3-FP8.pt"+++# ── end to end through the prequant loader ────────────────────────────────────────+++class _FakeTransformer(nn.Module):+ """Just enough of a diffusers transformer for ``load_prequantized_transformer``."""++ calls: dict = {}++ def __init__(self) -> None:+ super().__init__()+ self.a = nn.Linear(4 * GROUP, 8)+ self.b = nn.Linear(2 * GROUP, 8)++ @classmethod+ def load_config(cls, base, **kw):+ return {"cfg": True}++ @classmethod+ def from_config(cls, config):+ return cls()++ def load_state_dict(+ self,+ sd,+ strict = True,+ assign = False,+ ):+ _FakeTransformer.calls["load_state_dict"] = {"strict": strict, "assign": assign}+++def _load_rotated(monkeypatch, tmp_path, ckpt):+ """Drive ``load_prequantized_transformer`` over ``ckpt`` with real torch."""+ _FakeTransformer.calls = {}+ monkeypatch.setattr(torch, "load", lambda *a, **k: ckpt)+ accelerate = types.ModuleType("accelerate")+ accelerate.init_empty_weights = lambda: contextlib.nullcontext()+ monkeypatch.setitem(sys.modules, "accelerate", accelerate)+ monkeypatch.setenv(pq.ALLOW_LOCAL_PREQUANT_PATH_ENV, str(tmp_path))+ path = tmp_path / "ckpt.pt"+ path.write_bytes(b"x")+ return pq.load_prequantized_transformer(+ _FakeTransformer,+ "Tongyi-MAI/Z-Image-Turbo",+ pq.PrequantSource(kind = "path", location = str(path), filename = None),+ device = "cpu",+ dtype = "bfloat16",+ hf_token = None,+ scheme = "int8",+ logger = None,+ )+++def _ckpt(fmt, metadata):+ meta = {"scheme": "int8", "base_model_id": "Tongyi-MAI/Z-Image-Turbo"}+ meta.update(metadata)+ return {"format": fmt, "metadata": meta, "state_dict": {}}+++def test_loader_installs_the_rotation_the_checkpoint_records(monkeypatch, tmp_path):+ loaded = _load_rotated(monkeypatch, tmp_path, _ckpt(pq.PREQUANT_FORMAT_ROTATED, _meta(["a"])))+ assert loaded is not None+ assert is_rotated_linear(loaded.a) and not is_rotated_linear(loaded.b)+++def test_loader_leaves_a_plain_checkpoint_alone(monkeypatch, tmp_path):+ loaded = _load_rotated(monkeypatch, tmp_path, _ckpt(pq.PREQUANT_FORMAT, {}))+ assert loaded is not None+ assert not is_rotated_linear(loaded.a) and not is_rotated_linear(loaded.b)+++ ("fmt", "metadata"),+ [+ # Declared but unusable, in each of the ways the loader can tell.+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["a"], kind = "convrot_hadamard_v99")),+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["a"], group = 32)),+ (pq.PREQUANT_FORMAT_ROTATED, _meta(["not_on_this_model"])),+ (pq.PREQUANT_FORMAT_ROTATED, _meta([])),+ (pq.PREQUANT_FORMAT, _meta(["a"])),+ ],+)+def test_loader_refuses_a_rotation_it_cannot_apply(monkeypatch, tmp_path, fmt, metadata):+ # None means "fall back to the dense download": slower and bigger, but never wrong. The+ # alternative -- loading it anyway -- has no symptom at all.+ assert _load_rotated(monkeypatch, tmp_path, _ckpt(fmt, metadata)) is Nonediff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex 64beebbaa9a..35095b3e92f 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -12,6 +12,7 @@ are all exercised without CUDA, torchao, or a real diffusers model.from __future__ import annotationsimport contextlib+import dataclassesimport sysimport types@@ -108,6 +109,23 @@ def test_flux1_variant_prequant_wiring():)+def test_resolve_prefers_a_family_declared_filename():+ # A family may host a SECOND artifact for the same repo and scheme. Naming it makes it the+ # primary and demotes the derived name to the fallback, so a build that knows the new name+ # gets it while an older one still resolves the artifact it already understands.+ fam = _fam(prequant_repos = (("int8", "unsloth/Model-FP8"),))+ fam = dataclasses.replace(fam, prequant_filenames = (("int8", "Model-INT8-ConvRot.pt"),))+ src = resolve_prequant_source(fam, "int8")+ assert src.filename == "Model-INT8-ConvRot.pt"+ assert src.fallback_filename == "Model-INT8.pt"+ # Only for the scheme that declares one; everything else keeps today's derived/legacy pair.+ other = resolve_prequant_source(+ dataclasses.replace(fam, prequant_repos = (("fp8", "unsloth/Model-FP8"),)), "fp8"+ )+ assert other.filename == "Model-FP8.pt"+ assert other.fallback_filename == "transformer_fp8.pt"++def test_resolve_wrong_scheme_is_none():fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))assert resolve_prequant_source(fam, "int8") is Nonediff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pyindex 9865fb30a2b..8ee9439f2c8 100644--- a/studio/backend/tests/test_video_prequant.py+++ b/studio/backend/tests/test_video_prequant.py@@ -100,7 +100,9 @@ def test_both_h3_schemes_resolve_to_one_repo():# ── repo-root naming ─────────────────────────────────────────────────────────────@pytest.mark.parametrize("scheme, expected",- [("int8", "MiniMax-H3-INT8.pt"), ("fp8", "MiniMax-H3-FP8.pt")],+ # int8 is the ConvRot-rotated denoiser, which the family names explicitly; fp8 keeps the+ # derived <Model>-<SCHEME>.pt.+ [("int8", "MiniMax-H3-INT8-ConvRot.pt"), ("fp8", "MiniMax-H3-FP8.pt")],)def test_h3_resolves_the_primary_name_at_the_repo_root(scheme, expected):# The name the hosted repo actually publishes. It has to be the PRIMARY, not the fallback:@@ -113,6 +115,17 @@ def test_h3_resolves_the_primary_name_at_the_repo_root(scheme, expected):assert "/" not in src.filename and "\\" not in src.filename+def test_h3_int8_keeps_the_plain_denoiser_as_its_fallback():+ # The rotated artifact carries the v2 format tag, which a Studio predating the online rotation+ # refuses. Naming it explicitly and demoting the derived name to the fallback is what stops+ # that refusal from reaching anyone: an older install still resolves MiniMax-H3-INT8.pt, and+ # this one takes the rotated file when the repo has it.+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")+ src = resolve_prequant_source(fam, "int8")+ assert src.fallback_filename == "MiniMax-H3-INT8.pt"+ assert "/" not in src.fallback_filename and "\\" not in src.fallback_filename++def test_the_h3_primary_name_is_what_memory_planning_credits():# The under-crediting bug in full: seed the cache under the primary name and# cached_checkpoint_path must find it. A nested (or otherwise non-primary) name would not.@@ -126,7 +139,7 @@ def test_the_h3_primary_name_is_what_memory_planning_credits():cache_dir = None,):seen["filename"] = filename- return "/cache/blobs/h3" if filename == "MiniMax-H3-INT8.pt" else None+ return "/cache/blobs/h3" if filename == "MiniMax-H3-INT8-ConvRot.pt" else Noneimport huggingface_hubimport os@@ -140,7 +153,7 @@ def test_the_h3_primary_name_is_what_memory_planning_credits():finally:huggingface_hub.try_to_load_from_cache = real_hubos.path.isfile = real_isfile- assert seen["filename"] == "MiniMax-H3-INT8.pt"+ assert seen["filename"] == "MiniMax-H3-INT8-ConvRot.pt"def test_the_names_are_built_from_the_repo_and_the_scheme():